PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
interpolation.c
Go to the documentation of this file.
1/**
2 * @file interpolation.c
3 * @brief Main program for DMSwarm interpolation using the fdf-curvIB method.
4 *
5 * Provides routines for interpolation between corner-based and center-based
6 * fields in the cell-centered DM (fda), plus partial usage examples for
7 * DMSwarm-based field sampling.
8 */
9
10#include "interpolation.h"
11
12// Number of weights used in certain trilinear interpolation examples
13#define NUM_WEIGHTS 8
14// Define a buffer size for error messages if not already available
15#ifndef ERROR_MSG_BUFFER_SIZE
16#define ERROR_MSG_BUFFER_SIZE 256 // Or use PETSC_MAX_PATH_LEN if appropriate
17#endif
18
19/**
20 * @brief Implementation of \ref InterpolateFieldFromCornerToCenter_Vector().
21 * @see InterpolateFieldFromCornerToCenter_Vector()
22 */
24 Cmpnts ***field_arr, /* Input: Ghosted local array view from user->fda (global node indices) */
25 Cmpnts ***centfield_arr, /* Output: Array view for cell-centered data (global indices) */
26 UserCtx *user)
27{
28 DMDALocalInfo info;
29
30 PetscFunctionBeginUser;
32
33 info = user->info;
34
35 // Interior cells only: the dummy layers at index 0 and m-1 are excluded.
36 PetscInt lo[3], hi[3];
37 GetOwnedInteriorCellBounds(&info, lo, hi);
38 PetscInt is = lo[0], js = lo[1], ks = lo[2], ie = hi[0], je = hi[1], ke = hi[2];
39
40 // Loop over the locally owned INTERIOR cells.
41 for (PetscInt k = ks; k < ke; k++) {
42 for (PetscInt j = js; j < je; j++) {
43 for (PetscInt i = is; i < ie; i++) {
44 // Calculate cell center value as the average of its 8 corner nodes
45 centfield_arr[k][j][i].x = 0.125 * (field_arr[k][j][i].x + field_arr[k][j-1][i].x +
46 field_arr[k-1][j][i].x + field_arr[k-1][j-1][i].x +
47 field_arr[k][j][i-1].x + field_arr[k][j-1][i-1].x +
48 field_arr[k-1][j][i-1].x + field_arr[k-1][j-1][i-1].x);
49
50 centfield_arr[k][j][i].y = 0.125 * (field_arr[k][j][i].y + field_arr[k][j-1][i].y +
51 field_arr[k-1][j][i].y + field_arr[k-1][j-1][i].y +
52 field_arr[k][j][i-1].y + field_arr[k][j-1][i-1].y +
53 field_arr[k-1][j][i-1].y + field_arr[k-1][j-1][i-1].y);
54
55 centfield_arr[k][j][i].z = 0.125 * (field_arr[k][j][i].z + field_arr[k][j-1][i].z +
56 field_arr[k-1][j][i].z + field_arr[k-1][j-1][i].z +
57 field_arr[k][j][i-1].z + field_arr[k][j-1][i-1].z +
58 field_arr[k-1][j][i-1].z + field_arr[k-1][j-1][i-1].z);
59 }
60 }
61 }
62
64 PetscFunctionReturn(0);
65}
66
67/**
68 * @brief Implementation of \ref InterpolateFieldFromCornerToCenter_Scalar().
69 * @see InterpolateFieldFromCornerToCenter_Scalar()
70 */
72 PetscReal ***field_arr, /* Input: Ghosted local array view from user->fda (global node indices) */
73 PetscReal ***centfield_arr, /* Output: Array view for cell-centered data (global indices) */
74 UserCtx *user)
75{
76 DMDALocalInfo info;
77
78 PetscFunctionBeginUser;
80
81 info = user->info;
82
83 // Interior cells only: the dummy layers at index 0 and m-1 are excluded.
84 PetscInt lo[3], hi[3];
85 GetOwnedInteriorCellBounds(&info, lo, hi);
86 PetscInt is = lo[0], js = lo[1], ks = lo[2], ie = hi[0], je = hi[1], ke = hi[2];
87
88 // Loop over the locally owned INTERIOR cells.
89 for (PetscInt k = ks; k < ke; k++) {
90 for (PetscInt j = js; j < je; j++) {
91 for (PetscInt i = is; i < ie; i++) {
92 // Calculate cell center value as the average of its 8 corner nodes
93 centfield_arr[k][j][i] = 0.125 * (field_arr[k][j][i] + field_arr[k][j-1][i] +
94 field_arr[k-1][j][i] + field_arr[k-1][j-1][i] +
95 field_arr[k][j][i-1] + field_arr[k][j-1][i-1] +
96 field_arr[k-1][j][i-1] + field_arr[k-1][j-1][i-1]);
97 }
98 }
99 }
100
102 PetscFunctionReturn(0);
103}
104
105/**
106 * @brief Implementation of \ref TestCornerToCenterInterpolation().
107 * @see TestCornerToCenterInterpolation()
108 */
110{
111 PetscErrorCode ierr;
112 Vec lCoords, TestCent;
113 Cmpnts ***coor_arr, ***test_cent_arr;
114 PetscReal diff_norm;
115
116 PetscFunctionBeginUser;
118
119 // 1. Create a temporary vector to hold the result of our interpolation.
120 // It must have the same layout and size as the ground-truth user->Cent vector.
121 ierr = VecDuplicate(user->Cent, &TestCent); CHKERRQ(ierr);
122
123 // 2. Get the input (corner coordinates) and output (our test vector) arrays.
124 lCoords = user->lCoor;
125 ierr = DMDAVecGetArrayRead(user->fda, lCoords, &coor_arr); CHKERRQ(ierr);
126 ierr = DMDAVecGetArray(user->fda, TestCent, &test_cent_arr); CHKERRQ(ierr);
127
128 // 3. Call the generic interpolation macro.
129 // The macro will see that `coor_arr` is of type `Cmpnts***` and correctly
130 // call the `InterpolateFieldFromCornerToCenter_Vector` function.
131 ierr = InterpolateFieldFromCornerToCenter(coor_arr, test_cent_arr, user); CHKERRQ(ierr);
132
133 // 4. Restore the arrays.
134 ierr = DMDAVecRestoreArrayRead(user->fda, lCoords, &coor_arr); CHKERRQ(ierr);
135 ierr = DMDAVecRestoreArray(user->fda, TestCent, &test_cent_arr); CHKERRQ(ierr);
136
137 // 5. IMPORTANT: Assemble the vector so its values are communicated across processors
138 // and it's ready for global operations like VecNorm.
139 ierr = VecAssemblyBegin(TestCent); CHKERRQ(ierr);
140 ierr = VecAssemblyEnd(TestCent); CHKERRQ(ierr);
141
142 // 6. Compare the result with the ground truth.
143 // We compute TestCent = -1.0 * user->Cent + 1.0 * TestCent.
144 // This calculates the difference vector: TestCent - user->Cent.
145 ierr = VecAXPY(TestCent, -1.0, user->Cent); CHKERRQ(ierr);
146
147 // Now, compute the L2 norm of the difference vector. If the functions are
148 // identical, the norm should be zero (or very close due to floating point).
149 ierr = VecNorm(TestCent, NORM_2, &diff_norm); CHKERRQ(ierr);
150
151 // 7. Report the result and clean up.
152 if (diff_norm < 1.0e-12) {
153 LOG_ALLOW(GLOBAL,LOG_DEBUG,"[SUCCESS] Test passed. Norm of difference is %g.\n", (double)diff_norm);
154 } else {
155 LOG_ALLOW(GLOBAL,LOG_DEBUG, "[FAILURE] Test failed. Norm of difference is %g.\n", (double)diff_norm);
156 }
157
158 ierr = VecDestroy(&TestCent); CHKERRQ(ierr);
159
161 PetscFunctionReturn(0);
162}
163
164/**
165 * @brief Implementation of \ref InterpolateFieldFromCenterToCorner_Vector().
166 * @see InterpolateFieldFromCenterToCorner_Vector()
167 */
169 Cmpnts ***centfield_arr, /* Input: Ghosted local array from Vec (read) */
170 Cmpnts ***corner_arr, /* Output: global array from Vec (write) */
171 UserCtx *user)
172{
173 DMDALocalInfo info;
174 PetscMPIInt rank;
176 rank = user->simCtx->rank;
177 info = user->info;
178
179 // Node ownership range (GLOBAL indices)
180 PetscInt xs_node = info.xs, xm_node = info.xm, xe_node = xs_node + xm_node;
181 PetscInt ys_node = info.ys, ym_node = info.ym, ye_node = ys_node + ym_node;
182 PetscInt zs_node = info.zs, zm_node = info.zm, ze_node = zs_node + zm_node;
183
184 PetscInt nCellsX = info.mx - 2; // Number of cells in x-direction
185 PetscInt nCellsY = info.my - 2; // Number of cells in y-direction
186 PetscInt nCellsZ = info.mz - 2; // Number of cells in z-direction
187
188
189 // Global grid dimensions (used for valid cell check)
190 PetscInt IM = info.mx - 1; // Total nodes in i-direction
191 PetscInt JM = info.my - 1; // Total nodes in j-direction
192 PetscInt KM = info.mz - 1; // Total nodes in k-direction
193
195 "[Rank %d] Starting -- Node ownership k=%" PetscInt_FMT "..%" PetscInt_FMT ", j=%" PetscInt_FMT "..%" PetscInt_FMT ", i=%" PetscInt_FMT "..%" PetscInt_FMT "\n",
196 rank, zs_node, ze_node-1, ys_node, ye_node-1, xs_node, xe_node-1);
197
198 // Loop over the GLOBAL indices of the NODES owned by this processor
199 for (PetscInt k = zs_node; k < ze_node; k++) {
200 for (PetscInt j = ys_node; j < ye_node; j++) {
201 for (PetscInt i = xs_node; i < xe_node; i++) {
202 Cmpnts sum = {0.0, 0.0, 0.0};
203 PetscInt count = 0;
204
205 // DEBUG 1 TEST
206 /*
207 if(rank == 1 && i == 24 && j == 12 && k == 49){
208 PetscInt i_cell_A = i - 1;
209 PetscInt i_cell_B = i;
210
211 Cmpnts ucat_A = centfield_arr[k][j][i_cell_A]; // 23
212 Cmpnts ucat_B = centfield_arr[k][j][i_cell_B]; // 24 (out-of-bounds if IM=25)
213
214 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Read { Valid Cell }Ucat[%d][%d][%d]=(%.2f,%.2f,%.2f) and {Out-of-Bounds Cell}Ucat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
215 rank, k, j, i,
216 k, j, i_cell_A, ucat_A.x, ucat_A.y, ucat_A.z,
217 k, j, i_cell_B, ucat_B.x, ucat_B.y, ucat_B.z);
218
219 }
220 */
221
222 // Skip processing the unused last node in each dimension.
223 if(i >= IM || j >= JM || k >= KM){
224 continue;
225 }
226 // Loop over the 8 potential cells surrounding node N(k,j,i) and accumulate values.
227 // The index offsets correspond to the relative position of the indices(shifted) that represent cell-centered field values of cells that share the node N(k,j,i) as a corner
228 for (PetscInt dk_offset = -1; dk_offset <= 0; dk_offset++) {
229 for (PetscInt dj_offset = -1; dj_offset <= 0; dj_offset++) {
230 for (PetscInt di_offset = -1; di_offset <= 0; di_offset++) {
231
232 // These are still GLOBAL cell indices
233 PetscInt global_cell_k = k + dk_offset;
234 PetscInt global_cell_j = j + dj_offset;
235 PetscInt global_cell_i = i + di_offset;
236
237 // Check if this corresponds to a valid GLOBAL cell index
238 if (global_cell_i >= 0 && global_cell_i < nCellsX &&
239 global_cell_j >= 0 && global_cell_j < nCellsY &&
240 global_cell_k >= 0 && global_cell_k < nCellsZ)
241 {
242 Cmpnts cell_val = centfield_arr[global_cell_k + 1][global_cell_j + 1][global_cell_i + 1];
243
244 LOG_LOOP_ALLOW_EXACT(LOCAL, LOG_VERBOSE,k,49,"[Rank %d] successful read from [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "] -> (%.2f, %.2f, %.2f)\n",
245 rank,global_cell_k,global_cell_j,global_cell_i,cell_val.x, cell_val.y, cell_val.z);
246
247 sum.x += cell_val.x;
248 sum.y += cell_val.y;
249 sum.z += cell_val.z;
250 count++;
251 }
252 }
253 }
254 }
255
256 PetscInt i_global_write = i; // Global index in GLOBAL array.
257 PetscInt j_global_write = j;
258 PetscInt k_global_write = k;
259
260 // We write directly into the array using the global loop indices.
261 if (count > 0) {
262 corner_arr[k_global_write][j_global_write][i_global_write].x = sum.x / (PetscReal)count;
263 corner_arr[k_global_write][j_global_write][i_global_write].y = sum.y / (PetscReal)count;
264 corner_arr[k_global_write][j_global_write][i_global_write].z = sum.z / (PetscReal)count;
265 } else {
266 // This case should ideally not happen for a valid owned node, but as a failsafe:
267 corner_arr[k_global_write][j_global_write][i_global_write] = (Cmpnts){0.0, 0.0, 0.0};
268 }
269
270 // DEBUG 2
271 /*
272 if(rank == 1){
273 if(i == 11 && j == 11 && k == 49){
274 Cmpnts ucat_node = corner_arr[k][j][i];
275 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Wrote CornerUcat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
276 rank, k, j, i,
277 k, j, i, ucat_node.x, ucat_node.y, ucat_node.z);
278 }
279 }
280
281 if(rank == 0 && i == 24 && j == 12 && k == 0){
282 Cmpnts ucat_node = corner_arr[k][j][i];
283 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Wrote CornerUcat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
284 rank, k, j, i,
285 k, j, i, ucat_node.x, ucat_node.y, ucat_node.z);
286 }
287 */
288 // LOG_LOOP_ALLOW_EXACT(LOCAL, LOG_VERBOSE,k,48,"[Rank %d] Node(k,j,i)=%d,%d,%d finished loops and write.\n", rank, k, j, i);
289 }
290 }
291 }
293 return 0;
294}
295
296/**
297 * @brief Implementation of \ref InterpolateFieldFromCenterToCorner_Scalar().
298 * @see InterpolateFieldFromCenterToCorner_Scalar()
299 */
301 PetscReal ***centfield_arr, /* Input: Ghosted local array from Vec (read) */
302 PetscReal ***corner_arr, /* Output: global array from Vec (write) */
303 UserCtx *user)
304{
305 DMDALocalInfo info;
306 PetscMPIInt rank;
308 rank = user->simCtx->rank;
309 info = user->info;
310
311 // Node ownership range (GLOBAL indices)
312 PetscInt xs_node = info.xs, xm_node = info.xm, xe_node = xs_node + xm_node;
313 PetscInt ys_node = info.ys, ym_node = info.ym, ye_node = ys_node + ym_node;
314 PetscInt zs_node = info.zs, zm_node = info.zm, ze_node = zs_node + zm_node;
315
316 PetscInt nCellsX = info.mx - 2; // Number of cells in x-direction
317 PetscInt nCellsY = info.my - 2; // Number of cells in y-direction
318 PetscInt nCellsZ = info.mz - 2; // Number of cells in z-direction
319
320
321 // Global grid dimensions (used for valid cell check)
322 PetscInt IM = info.mx - 1; // Total nodes in i-direction
323 PetscInt JM = info.my - 1; // Total nodes in j-direction
324 PetscInt KM = info.mz - 1; // Total nodes in k-direction
325
327 "[Rank %d] Starting -- Node ownership k=%" PetscInt_FMT "..%" PetscInt_FMT ", j=%" PetscInt_FMT "..%" PetscInt_FMT ", i=%" PetscInt_FMT "..%" PetscInt_FMT "\n",
328 rank, zs_node, ze_node-1, ys_node, ye_node-1, xs_node, xe_node-1);
329
330 // Loop over the GLOBAL indices of the NODES owned by this processor
331 for (PetscInt k = zs_node; k < ze_node; k++) {
332 for (PetscInt j = ys_node; j < ye_node; j++) {
333 for (PetscInt i = xs_node; i < xe_node; i++) {
334 PetscReal sum = 0.0;
335 PetscInt count = 0;
336
337 // DEBUG 1 TEST
338 /*
339 if(rank == 1 && i == 24 && j == 12 && k == 49){
340 PetscInt i_cell_A = i - 1;
341 PetscInt i_cell_B = i;
342
343 Cmpnts ucat_A = centfield_arr[k][j][i_cell_A]; // 23
344 Cmpnts ucat_B = centfield_arr[k][j][i_cell_B]; // 24 (out-of-bounds if IM=25)
345
346 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Read { Valid Cell }Ucat[%d][%d][%d]=(%.2f,%.2f,%.2f) and {Out-of-Bounds Cell}Ucat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
347 rank, k, j, i,
348 k, j, i_cell_A, ucat_A.x, ucat_A.y, ucat_A.z,
349 k, j, i_cell_B, ucat_B.x, ucat_B.y, ucat_B.z);
350
351 }
352 */
353
354 // Skip processing the unused last node in each dimension.
355 if(i >= IM || j >= JM || k >= KM){
356 continue;
357 }
358 // Loop over the 8 potential cells surrounding node N(k,j,i) and accumulate values.
359 // The index offsets correspond to the relative position of the indices(shifted) that represent cell-centered field values of cells that share the node N(k,j,i) as a corner
360 for (PetscInt dk_offset = -1; dk_offset <= 0; dk_offset++) {
361 for (PetscInt dj_offset = -1; dj_offset <= 0; dj_offset++) {
362 for (PetscInt di_offset = -1; di_offset <= 0; di_offset++) {
363
364 // These are still GLOBAL cell indices
365 PetscInt global_cell_k = k + dk_offset;
366 PetscInt global_cell_j = j + dj_offset;
367 PetscInt global_cell_i = i + di_offset;
368
369 // Check if this corresponds to a valid GLOBAL cell index
370 if (global_cell_i >= 0 && global_cell_i < nCellsX &&
371 global_cell_j >= 0 && global_cell_j < nCellsY &&
372 global_cell_k >= 0 && global_cell_k < nCellsZ)
373 {
374 PetscReal cell_val = centfield_arr[global_cell_k + 1][global_cell_j + 1][global_cell_i + 1];
375
376 LOG_LOOP_ALLOW_EXACT(LOCAL, LOG_VERBOSE,k,49,"[Rank %d] successful read from [%" PetscInt_FMT "][%" PetscInt_FMT "][%" PetscInt_FMT "] -> (%.2f)\n",
377 rank,global_cell_k,global_cell_j,global_cell_i,cell_val);
378
379 sum += cell_val;
380 count++;
381 }
382 }
383 }
384 }
385
386 PetscInt i_global_write = i; // Global index in GLOBAL array.
387 PetscInt j_global_write = j;
388 PetscInt k_global_write = k;
389
390 // We write directly into the array using the global loop indices.
391 if (count > 0) {
392 corner_arr[k_global_write][j_global_write][i_global_write] = sum / (PetscReal)count;
393 } else {
394 // This case should ideally not happen for a valid owned node, but as a failsafe:
395 corner_arr[k_global_write][j_global_write][i_global_write] = 0.0;
396 }
397
398 // DEBUG 2
399 /*
400 if(rank == 1){
401 if(i == 11 && j == 11 && k == 49){
402 Cmpnts ucat_node = corner_arr[k][j][i];
403 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Wrote CornerUcat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
404 rank, k, j, i,
405 k, j, i, ucat_node.x, ucat_node.y, ucat_node.z);
406 }
407 }
408
409 if(rank == 0 && i == 24 && j == 12 && k == 0){
410 Cmpnts ucat_node = corner_arr[k][j][i];
411 PetscPrintf(PETSC_COMM_WORLD,"[Rank %d] DEBUG TEST at Node(k,j,i)=%d,%d,%d: Wrote CornerUcat[%d][%d][%d]=(%.2f,%.2f,%.2f)\n",
412 rank, k, j, i,
413 k, j, i, ucat_node.x, ucat_node.y, ucat_node.z);
414 }
415 */
416 // LOG_LOOP_ALLOW_EXACT(LOCAL, LOG_VERBOSE,k,48,"[Rank %d] Node(k,j,i)=%d,%d,%d finished loops and write.\n", rank, k, j, i);
417 }
418 }
419 }
421 return 0;
422}
423
424/**
425 * @brief Compute the eight trilinear interpolation weights for a particle's local coordinates.
426 */
427static inline void ComputeTrilinearWeights(PetscReal a1, PetscReal a2, PetscReal a3, PetscReal *w) {
428 // Ensure a1, a2, a3 are within [0,1]
429 a1 = PetscMax(0.0, PetscMin(1.0, a1));
430 a2 = PetscMax(0.0, PetscMin(1.0, a2));
431 a3 = PetscMax(0.0, PetscMin(1.0, a3));
432
433 const PetscReal oa1 = 1.0 - a1;
434 const PetscReal oa2 = 1.0 - a2;
435 const PetscReal oa3 = 1.0 - a3;
436
437 w[0] = oa1 * oa2 * oa3; /* cornerOffsets[0] => (0,0,0) */
438 w[1] = a1 * oa2 * oa3; /* cornerOffsets[1] => (1,0,0) */
439 w[2] = oa1 * a2 * oa3; /* cornerOffsets[2] => (0,1,0) */
440 w[3] = a1 * a2 * oa3; /* cornerOffsets[3] => (1,1,0) */
441 w[4] = oa1 * oa2 * a3; /* cornerOffsets[4] => (0,0,1) */
442 w[5] = a1 * oa2 * a3; /* cornerOffsets[5] => (1,0,1) */
443 w[6] = oa1 * a2 * a3; /* cornerOffsets[6] => (0,1,1) */
444 w[7] = a1 * a2 * a3; /* cornerOffsets[7] => (1,1,1) */
445}
446
447/**
448 * @brief Unclamped trilinear weights for boundary extrapolation.
449 * @details Identical to ComputeTrilinearWeights() but without clamping
450 * a1, a2, a3 to [0,1]. Allows weights outside [0,1] for linear
451 * extrapolation at non-periodic boundaries. Weights still sum to 1.0.
452 */
453static inline void ComputeTrilinearWeightsUnclamped(PetscReal a1, PetscReal a2, PetscReal a3, PetscReal *w) {
454 const PetscReal oa1 = 1.0 - a1;
455 const PetscReal oa2 = 1.0 - a2;
456 const PetscReal oa3 = 1.0 - a3;
457
458 w[0] = oa1 * oa2 * oa3;
459 w[1] = a1 * oa2 * oa3;
460 w[2] = oa1 * a2 * oa3;
461 w[3] = a1 * a2 * oa3;
462 w[4] = oa1 * oa2 * a3;
463 w[5] = a1 * oa2 * a3;
464 w[6] = oa1 * a2 * a3;
465 w[7] = a1 * a2 * a3;
466}
467
468
469/**
470 * @brief Implementation of \ref TrilinearInterpolation_Scalar().
471 * @see TrilinearInterpolation_Scalar()
472 */
474 PetscReal ***fieldScal,
475 PetscInt i,
476 PetscInt j,
477 PetscInt k,
478 PetscReal a1,
479 PetscReal a2,
480 PetscReal a3,
481 PetscReal *val)
482{
483 PetscFunctionBegin; // PETSc macro for error/stack tracing
484
485 // Compute the 8 corner weights
486 PetscReal wcorner[8];
487 ComputeTrilinearWeights(a1, a2, a3, wcorner);
488
489 // Offsets for cell corners
490 PetscInt i1 = i + 1;
491 PetscInt j1 = j + 1;
492 PetscInt k1 = k + 1;
493
494 // Initialize the output scalar
495 PetscReal sum = 0.0;
496
497 // Corner 0 => (i, j, k)
498 sum += wcorner[0] * fieldScal[k ][j ][i ];
499 // Corner 1 => (i+1, j, k)
500 sum += wcorner[1] * fieldScal[k ][j ][i1];
501 // Corner 2 => (i, j+1, k)
502 sum += wcorner[2] * fieldScal[k ][j1][i ];
503 // Corner 3 => (i+1, j+1, k)
504 sum += wcorner[3] * fieldScal[k ][j1][i1];
505 // Corner 4 => (i, j, k+1)
506 sum += wcorner[4] * fieldScal[k1][j ][i ];
507 // Corner 5 => (i+1, j, k+1)
508 sum += wcorner[5] * fieldScal[k1][j ][i1];
509 // Corner 6 => (i, j+1, k+1)
510 sum += wcorner[6] * fieldScal[k1][j1][i ];
511 // Corner 7 => (i+1, j+1, k+1)
512 sum += wcorner[7] * fieldScal[k1][j1][i1];
513
514 *val = sum;
515
516 PetscFunctionReturn(0);
517}
518
519
520/**
521 * @brief Implementation of \ref TrilinearInterpolation_Vector().
522 * @see TrilinearInterpolation_Vector()
523 */
525 Cmpnts ***fieldVec, /* 3D array [k][j][i], dimension [mz][my][mx] */
526 PetscInt i, // local cell index i
527 PetscInt j, // local cell index j
528 PetscInt k, // local cell index k
529 PetscReal a1,
530 PetscReal a2,
531 PetscReal a3,
532 Cmpnts *vec)
533{
534 PetscFunctionBegin; // PETSc macro for error/stack tracing
535
536 // Compute the 8 corner weights
537 PetscReal wcorner[8];
538
539 ComputeTrilinearWeights(a1, a2, a3, wcorner);
540
541 // For partial interpolation, we'll keep track of how many corners are valid
542 // and how much sum of weights is used. Then we do a final normalization.
543 PetscReal sumW = 0.0;
544 Cmpnts accum = {0.0, 0.0, 0.0};
545
546 // The eight corner indices, with their weights:
547 // corners: (i,j,k), (i+1,j,k), (i,j+1,k), (i+1,j+1,k), etc.
548 // We store them in an array to iterate cleanly.
549 const PetscInt cornerOffsets[8][3] = {
550 {0, 0, 0},
551 {1, 0, 0},
552 {0, 1, 0},
553 {1, 1, 0},
554 {0, 0, 1},
555 {1, 0, 1},
556 {0, 1, 1},
557 {1, 1, 1}
558 };
559
560 // Weighted partial sum
561 for (PetscInt c = 0; c < 8; c++) {
562 const PetscInt di = cornerOffsets[c][0];
563 const PetscInt dj = cornerOffsets[c][1];
564 const PetscInt dk = cornerOffsets[c][2];
565 PetscInt iC = i + di;
566 PetscInt jC = j + dj;
567 PetscInt kC = k + dk;
568
569 /*
570 // skip if out of domain
571 // (Assuming you know global domain is [0..mx), [0..my), [0..mz).)
572 if (iC < 0 || iC >= (PetscInt)userGlobalMx ||
573 jC < 0 || jC >= (PetscInt)userGlobalMy ||
574 kC < 0 || kC >= (PetscInt)userGlobalMz)
575 {
576 // skip this corner
577 continue;
578 }
579
580 */
581
582 // Otherwise, accumulate
583 accum.x += wcorner[c] * fieldVec[kC][jC][iC].x;
584 accum.y += wcorner[c] * fieldVec[kC][jC][iC].y;
585 accum.z += wcorner[c] * fieldVec[kC][jC][iC].z;
586 sumW += wcorner[c];
587 }
588
589 // If sumW=0 => out-of-range or zero weighting => set (0,0,0)
590 if (sumW > 1.0e-14) {
591 vec->x = accum.x / sumW;
592 vec->y = accum.y / sumW;
593 vec->z = accum.z / sumW;
594 } else {
595 vec->x = 0.0; vec->y = 0.0; vec->z = 0.0;
596 }
597
598 PetscFunctionReturn(0);
599}
600
601
602/**
603 * @brief Interpolate one Eulerian field to a single located swarm particle.
604 */
605static inline PetscErrorCode InterpolateEulerFieldToSwarmForParticle(
606 void *fieldPtr, /* typed Pointer => either (PetscReal***) or (Cmpnts***) */
607 Particle *particle, /* particle struct containing Cell ID and weight information. */
608 void *swarmOut, /* typed Pointer => (PetscReal*) or (Cmpnts*) or dof=3 array */
609 PetscInt p, /* particle index */
610 PetscInt blockSize) /* dof=1 => scalar, dof=3 => vector */
611{
612 PetscErrorCode ierr;
613 PetscFunctionBegin;
614
615 PetscInt iCell = particle->cell[0];
616 PetscInt jCell = particle->cell[1];
617 PetscInt kCell = particle->cell[2];
618 PetscReal a1 = particle->weights.x;
619 PetscReal a2 = particle->weights.y;
620 PetscReal a3 = particle->weights.z;
621
622 /* Called once per particle: a helper event, timed only when enabled by name. The caller
623 * reports the particle's result in its interpolate line. */
625
626 /*
627 If blockSize=1, we PetscInterpret the fieldPtr as a 3D array of PetscReal (scalar).
628 If blockSize=3, we PetscInterpret the fieldPtr as a 3D array of Cmpnts (vector).
629 */
630 if (blockSize == 1) {
631 /* Scalar field: Cast fieldPtr to (PetscReal ***). */
632 PetscReal ***fieldScal = (PetscReal ***) fieldPtr;
633 PetscReal val;
634
635 ierr = TrilinearInterpolation(fieldScal,
636 iCell, jCell, kCell,
637 a1, a2, a3,
638 &val);
639 CHKERRQ(ierr);
640
641 // Write the scalar result to the swarm output at index [p].
642 ((PetscReal*)swarmOut)[p] = val;
643 }
644 else if (blockSize == 3) {
645 /* Vector field: Cast fieldPtr to (Cmpnts ***). */
646 Cmpnts ***fieldVec = (Cmpnts ***) fieldPtr;
647 Cmpnts vec;
648
649 ierr = TrilinearInterpolation(fieldVec,
650 iCell, jCell, kCell,
651 a1, a2, a3,
652 &vec);
653 CHKERRQ(ierr);
654
655 // If swarmOut is an array of 3 reals per particle:
656 ((PetscReal*)swarmOut)[3*p + 0] = vec.x;
657 ((PetscReal*)swarmOut)[3*p + 1] = vec.y;
658 ((PetscReal*)swarmOut)[3*p + 2] = vec.z;
659
660 /*
661 If you store the vector result as a Cmpnts in the swarm, do instead:
662 ((Cmpnts*)swarmOut)[p] = vec;
663 but ensure your DMSwarm field is sized for a Cmpnts struct.
664 */
665 }
666 else {
667 /* If blockSize isn't 1 or 3, we raise an error. */
668 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP,
669 "InterpolateEulerFieldToSwarmForParticle: only blockSize=1 or 3 supported, got %" PetscInt_FMT ".",
670 (PetscInt)blockSize);
671 }
672
674 PetscFunctionReturn(0);
675}
676
677/** @brief One cell-centred field interpolated to a particle field in a shared pass. */
679 Vec local_vec; ///< Ghosted cell-centred source.
680 const char *field_name; ///< Source name, for logging.
681 const char *swarm_name; ///< Destination swarm field.
682 PetscInt bs; ///< 1 or 3 components.
683 void *field_ptr; ///< Source array while the pass runs.
684 PetscReal *swarm_out; ///< Destination array while the pass runs.
686
687/**
688 * @brief Appends one target's interpolated value and its eight dual-cell corner values to a
689 * particle's interpolate line; the text is truncated rather than overrun.
690 * @details Corners are listed i fastest, then j, then k, from dual base `(bi, bj, bk)`.
691 * Local to this translation unit.
692 */
693static void AppendInterpolationTargetText(char *text, size_t size, size_t *used,
694 const CenterInterpolationTarget *tg, PetscInt p,
695 PetscInt bi, PetscInt bj, PetscInt bk)
696{
698#define PICURV_APPEND(...) do { if (*used < size) { int _n = snprintf(text + *used, size - *used, __VA_ARGS__); \
699 if (_n > 0) *used = PetscMin(size - 1, *used + (size_t)_n); } } while (0)
700 PICURV_APPEND(" | %s =", tg->field_name);
701 for (PetscInt c = 0; c < tg->bs; ++c) PICURV_APPEND(" %.6e", (double)tg->swarm_out[tg->bs * p + c]);
702 PICURV_APPEND(" from corners");
703 for (PetscInt dk = 1; dk <= 2; ++dk) for (PetscInt dj = 1; dj <= 2; ++dj) for (PetscInt di = 1; di <= 2; ++di) {
704 if (tg->bs == 1) {
705 const PetscReal ***f = (const PetscReal ***)tg->field_ptr;
706 PICURV_APPEND(" %.6e", (double)f[bk + dk][bj + dj][bi + di]);
707 } else {
708 const Cmpnts ***f = (const Cmpnts ***)tg->field_ptr;
709 const Cmpnts v = f[bk + dk][bj + dj][bi + di];
710 PICURV_APPEND(" (%.6e,%.6e,%.6e)", (double)v.x, (double)v.y, (double)v.z);
711 }
712 }
713#undef PICURV_APPEND
715}
716
717
718/**
719 * @brief The dual cell of cell centres a point interpolates from, and its trilinear weights.
720 * @details The octant of the point in its host cell picks the dual cell. At a non-periodic
721 * boundary the dual cell is clamped to the physical cells, and the weights then
722 * extrapolate. The weights come from the point's distances to the dual cell's face
723 * planes. Local to this translation unit.
724 * @param[in] info Grid layout.
725 * @param[in] dual Dual face-plane arrays (MetricGetFacePlaneArrays() with `dual` set).
726 * @param[in] periodic Whether each axis is periodic.
727 * @param[in] cell Host cell, geometric indices.
728 * @param[in] weights The point's logical coordinates in the host cell.
729 * @param[in] loc The point.
730 * @param[out] base Dual cell origin, geometric indices.
731 * @param[out] a Trilinear coordinates in the dual cell.
732 * @param[out] w Corner weights, set only when `unclamped` is true.
733 * @param[out] unclamped PETSC_TRUE when the dual cell was clamped.
734 * @param[out] outside PETSC_TRUE when the dual cell lies outside the ghosted region; then
735 * nothing else is set.
736 */
737static inline PetscErrorCode CenterDualCellWeights(const DMDALocalInfo *info, const FacePlaneArrays *dual,
738 const PetscBool periodic[3], const PetscInt cell[3],
739 const PetscReal weights[3], Cmpnts loc, PetscInt base[3],
740 PetscReal a[3], PetscReal w[8], PetscBool *unclamped,
741 PetscBool *outside)
742{
743 const PetscInt n_cells[3] = {info->mx - 2, info->my - 2, info->mz - 2};
744 PetscReal d[NUM_FACES];
745 CellFacePlanes dual_planes;
746 PetscErrorCode ierr;
747
748 /* Called per particle and kept off the PETSc call stack, like the weight helpers. */
749 *unclamped = PETSC_FALSE;
750 for (PetscInt c = 0; c < 3; ++c) {
751 /* Determine octant, then clamp it at non-periodic boundaries */
752 base[c] = cell[c] + ((weights[c] < 0.5) ? -1 : 0);
753 if (!periodic[c]) {
754 if (base[c] < 0) { base[c] = 0; *unclamped = PETSC_TRUE; }
755 if (base[c] + 1 >= n_cells[c]) { base[c] = n_cells[c] - 2; *unclamped = PETSC_TRUE; }
756 }
757 }
758 /* Bounds check — dual cell stencil must fit in ghosted region */
759 *outside = (PetscBool)(base[0] + 1 < info->gxs || base[0] + 1 >= info->gxs + info->gxm - 1 ||
760 base[1] + 1 < info->gys || base[1] + 1 >= info->gys + info->gym - 1 ||
761 base[2] + 1 < info->gzs || base[2] + 1 >= info->gzs + info->gzm - 1);
762 if (*outside) return PETSC_SUCCESS;
763
764 /* Face distances from the point to the dual cell whose vertex 0 is
765 * lCent[bk+1][bj+1][bi+1] (shifted index: cent[k+1][j+1][i+1] for cell (i,j,k)). */
766 MetricGatherCellFacePlanes(dual, info, base[0] + 1, base[1] + 1, base[2] + 1, &dual_planes);
767 ierr = CalculateDistancesToCellFacePlanes(loc, &dual_planes, d, 1e-11, NULL);
768 if (ierr) return ierr;
769
770 /* Trilinear parametric coordinates from face distances */
771 a[0] = d[LEFT] / (d[LEFT] + d[RIGHT]);
772 a[1] = d[BOTTOM] / (d[BOTTOM] + d[TOP]);
773 a[2] = d[BACK] / (d[FRONT] + d[BACK]);
774 if (*unclamped) ComputeTrilinearWeightsUnclamped(a[0], a[1], a[2], w);
775 return PETSC_SUCCESS;
776}
777
778/**
779 * @brief A cell-centred vector at a point, from the dual cell CenterDualCellWeights() found.
780 * @details Trilinear inside the domain, the unclamped corner weights where the dual cell was
781 * clamped. Local to this translation unit.
782 */
783static inline PetscErrorCode CenterInterpolateVector(Cmpnts ***fieldVec, const PetscInt base[3],
784 const PetscReal a[3], const PetscReal w[8], PetscBool unclamped,
785 Cmpnts *vec)
786{
787 const PetscInt bi = base[0], bj = base[1], bk = base[2];
788
789 /* Called per particle and kept off the PETSc call stack, like the weight helpers. */
790 if (unclamped) {
791 vec->x = w[0]*fieldVec[bk+1][bj+1][bi+1].x + w[1]*fieldVec[bk+1][bj+1][bi+2].x
792 + w[2]*fieldVec[bk+1][bj+2][bi+1].x + w[3]*fieldVec[bk+1][bj+2][bi+2].x
793 + w[4]*fieldVec[bk+2][bj+1][bi+1].x + w[5]*fieldVec[bk+2][bj+1][bi+2].x
794 + w[6]*fieldVec[bk+2][bj+2][bi+1].x + w[7]*fieldVec[bk+2][bj+2][bi+2].x;
795 vec->y = w[0]*fieldVec[bk+1][bj+1][bi+1].y + w[1]*fieldVec[bk+1][bj+1][bi+2].y
796 + w[2]*fieldVec[bk+1][bj+2][bi+1].y + w[3]*fieldVec[bk+1][bj+2][bi+2].y
797 + w[4]*fieldVec[bk+2][bj+1][bi+1].y + w[5]*fieldVec[bk+2][bj+1][bi+2].y
798 + w[6]*fieldVec[bk+2][bj+2][bi+1].y + w[7]*fieldVec[bk+2][bj+2][bi+2].y;
799 vec->z = w[0]*fieldVec[bk+1][bj+1][bi+1].z + w[1]*fieldVec[bk+1][bj+1][bi+2].z
800 + w[2]*fieldVec[bk+1][bj+2][bi+1].z + w[3]*fieldVec[bk+1][bj+2][bi+2].z
801 + w[4]*fieldVec[bk+2][bj+1][bi+1].z + w[5]*fieldVec[bk+2][bj+1][bi+2].z
802 + w[6]*fieldVec[bk+2][bj+2][bi+1].z + w[7]*fieldVec[bk+2][bj+2][bi+2].z;
803 } else {
804 /* Shifted index: pass (bi+1, bj+1, bk+1) so the kernel accesses
805 * field[bk+1..bk+2][bj+1..bj+2][bi+1..bi+2] = cells (bi..bi+1, bj..bj+1, bk..bk+1). */
806 return TrilinearInterpolation_Vector(fieldVec, bi + 1, bj + 1, bk + 1, a[0], a[1], a[2], vec);
807 }
808 return PETSC_SUCCESS;
809}
810
811/**
812 * @brief A cell-centred scalar at a point, from the dual cell CenterDualCellWeights() found.
813 * @details The scalar counterpart of CenterInterpolateVector(). Local to this translation unit.
814 */
815static inline PetscErrorCode CenterInterpolateScalar(PetscReal ***fieldScal, const PetscInt base[3], const PetscReal a[3],
816 const PetscReal w[8], PetscBool unclamped, PetscReal *val)
817{
818 const PetscInt bi = base[0], bj = base[1], bk = base[2];
819
820 /* Called per particle and kept off the PETSc call stack, like the weight helpers. */
821 if (unclamped) {
822 *val = w[0] * fieldScal[bk+1][bj+1][bi+1] + w[1] * fieldScal[bk+1][bj+1][bi+2]
823 + w[2] * fieldScal[bk+1][bj+2][bi+1] + w[3] * fieldScal[bk+1][bj+2][bi+2]
824 + w[4] * fieldScal[bk+2][bj+1][bi+1] + w[5] * fieldScal[bk+2][bj+1][bi+2]
825 + w[6] * fieldScal[bk+2][bj+2][bi+1] + w[7] * fieldScal[bk+2][bj+2][bi+2];
826 return PETSC_SUCCESS;
827 }
828 /* Shifted index, as in CenterInterpolateVector(). */
829 return TrilinearInterpolation_Scalar(fieldScal, bi + 1, bj + 1, bk + 1, a[0], a[1], a[2], val);
830}
831
832/**
833 * @brief Whether the face fluxes of a host cell lie in the ghosted region: in cell-centred
834 * numbering (i,j,k) = cell + 1, its faces are i-1 and i along each axis.
835 */
836static inline PetscBool FaceFluxStencilIsLocal(const DMDALocalInfo *info, const PetscInt cell[3])
837{
838 const PetscInt i = cell[0] + 1, j = cell[1] + 1, k = cell[2] + 1;
839 return (PetscBool)!(i - 1 < info->gxs || i >= info->gxs + info->gxm ||
840 j - 1 < info->gys || j >= info->gys + info->gym ||
841 k - 1 < info->gzs || k >= info->gzs + info->gzm);
842}
843
844/** @brief Whether the eight corners of a host cell (nodes cell to cell + 1) lie in the ghosted region. */
845static inline PetscBool CornerStencilIsLocal(const DMDALocalInfo *info, const PetscInt cell[3])
846{
847 return (PetscBool)!(cell[0] < info->gxs || cell[0] >= info->gxs + info->gxm - 1 ||
848 cell[1] < info->gys || cell[1] >= info->gys + info->gym - 1 ||
849 cell[2] < info->gzs || cell[2] >= info->gzs + info->gzm - 1);
850}
851
852/**
853 * @brief Direct cell-center trilinear interpolation (second-order on curvilinear grids).
854 * @details For each particle, determines the 8 nearest cell centers via octant
855 * detection, takes the dual cell they form, computes face-distance-based
856 * trilinear weights, and interpolates directly from cell-centered data.
857 * At non-periodic boundaries where the dual cell cannot be fully formed,
858 * octant clamping with unclamped trilinear extrapolation preserves
859 * second-order accuracy. Periodic boundaries use ghost cell data directly.
860 * No intermediate corner staging or extra ghost exchange is needed.
861 * The dual cell's face planes are precomputed (MetricComputeFacePlanes()),
862 * and the octant, dual cell and weights depend only on the particle, so they
863 * are computed once per particle for all `ntargets` fields; each field's value
864 * is the one a separate pass would give.
865 */
867 UserCtx *user,
868 PetscInt ntargets,
870{
871 PetscErrorCode ierr;
872 DM swarm = user->swarm;
873 DMDALocalInfo info;
874 PetscMPIInt rank;
875
876 PetscInt *cellIDs = NULL;
877 PetscReal *weights = NULL;
878 PetscInt64 *pids = NULL;
879 PetscReal *pos = NULL;
880 PetscInt *status = NULL;
881 PetscInt nLocal;
882
883 PetscFunctionBegin;
885 rank = user->simCtx->rank;
886 info = user->info;
887 FacePlaneArrays dual_arrays;
888 ierr = MetricGetFacePlaneArrays(user, PETSC_TRUE, &dual_arrays); CHKERRQ(ierr);
889
890 PetscBool periodic[3];
891 GetPeriodicAxes(user->simCtx, periodic);
892
893 /* Get read-only arrays for each cell-centered field and its swarm destination */
894 for (PetscInt t = 0; t < ntargets; ++t) {
895 CenterInterpolationTarget *tg = &targets[t];
896 ierr = VecGetBlockSize(tg->local_vec, &tg->bs); CHKERRQ(ierr);
897 if (tg->bs != 1 && tg->bs != 3) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "BlockSize must be 1 or 3.");
898 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Starting direct cell-center interpolation for field '%s'...\n", tg->field_name);
899 ierr = DMDAVecGetArrayRead((tg->bs == 3) ? user->fda : user->da, tg->local_vec, &tg->field_ptr); CHKERRQ(ierr);
900 ierr = DMSwarmGetField(swarm, tg->swarm_name, NULL, NULL, (void **)&tg->swarm_out); CHKERRQ(ierr);
901 }
902
903 /* Retrieve swarm fields */
904 ierr = DMSwarmGetLocalSize(swarm, &nLocal); CHKERRQ(ierr);
905 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
906 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
907 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
908 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
909 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
910
911 /* Loop over each local particle */
912 PetscInt n_outside = 0; /* Particles whose dual cell lies outside the ghosted region */
913 for (PetscInt p = 0; p < nLocal; p++) {
914
915 Particle particle;
916 ierr = UnpackSwarmFields(p, pids, weights, pos, cellIDs, NULL, status, NULL, NULL, NULL, &particle); CHKERRQ(ierr);
917
918 /* The dual cell from the host cell and the particle's weights, and the trilinear
919 * coordinates in it */
920 const PetscReal host_weights[3] = {particle.weights.x, particle.weights.y, particle.weights.z};
921 PetscInt base[3];
922 PetscReal a_new[3], w[8] = {0}; /* w is read only when needs_unclamped, which also fills it */
923 PetscBool needs_unclamped, outside;
924 ierr = CenterDualCellWeights(&info, &dual_arrays, periodic, particle.cell, host_weights, particle.loc,
925 base, a_new, w, &needs_unclamped, &outside); CHKERRQ(ierr);
926 const PetscInt bi = base[0], bj = base[1], bk = base[2];
927 const PetscReal a1_new = a_new[0], a2_new = a_new[1], a3_new = a_new[2];
928 if (outside)
929 {
930 n_outside++;
931 LOG_PARTICLE(user->simCtx, particle.PID, "interpolate",
932 "dual cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") outside the ghosted region: %" PetscInt_FMT " field(s) zeroed\n",
933 bi, bj, bk, ntargets);
934 for (PetscInt t = 0; t < ntargets; ++t) {
935 for (PetscInt c = 0; c < targets[t].bs; ++c) targets[t].swarm_out[targets[t].bs * p + c] = 0.0;
936 }
937 continue;
938 }
939
940 /* Each field from the same dual cell and weights. */
941 for (PetscInt t = 0; t < ntargets; ++t) {
942 PetscReal *swarmOut = targets[t].swarm_out;
943 if (targets[t].bs == 1) {
944 PetscReal val;
945 ierr = CenterInterpolateScalar((PetscReal ***)targets[t].field_ptr, base, a_new, w, needs_unclamped,
946 &val); CHKERRQ(ierr);
947 swarmOut[p] = val;
948 } else {
949 Cmpnts vec;
950 ierr = CenterInterpolateVector((Cmpnts ***)targets[t].field_ptr, base, a_new, w,
951 needs_unclamped, &vec); CHKERRQ(ierr);
952 swarmOut[3*p + 0] = vec.x;
953 swarmOut[3*p + 1] = vec.y;
954 swarmOut[3*p + 2] = vec.z;
955 }
956 }
957 if (PARTICLE_LOG_ACTIVE(user->simCtx, particle.PID)) {
958 char text[4096];
959 size_t used = 0;
960 text[0] = '\0';
961 for (PetscInt t = 0; t < ntargets; ++t) AppendInterpolationTargetText(text, sizeof(text), &used, &targets[t], p, bi, bj, bk);
962 LOG_PARTICLE(user->simCtx, particle.PID, "interpolate",
963 "host cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") dual base (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") weights (%.6f, %.6f, %.6f)%s%s\n",
964 particle.cell[0], particle.cell[1], particle.cell[2], bi, bj, bk, a1_new, a2_new, a3_new,
965 needs_unclamped ? " unclamped extrapolation" : "", text);
966 }
967 }
968 if (n_outside > 0) {
970 "[Rank %d] %" PetscInt_FMT " particle(s) had their dual cell outside the ghosted region; their interpolated fields were zeroed.\n",
971 rank, n_outside);
972 }
973
974 /* Restore arrays and swarm fields */
975 for (PetscInt t = 0; t < ntargets; ++t) {
976 CenterInterpolationTarget *tg = &targets[t];
977 ierr = DMDAVecRestoreArrayRead((tg->bs == 3) ? user->fda : user->da, tg->local_vec, &tg->field_ptr); CHKERRQ(ierr);
978 ierr = DMSwarmRestoreField(swarm, tg->swarm_name, NULL, NULL, (void **)&tg->swarm_out); CHKERRQ(ierr);
979 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Finished direct cell-center interpolation for field '%s'.\n", tg->field_name);
980 }
981 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
982 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
983 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
984 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
985 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
986 ierr = MetricRestoreFacePlaneArrays(user, &dual_arrays); CHKERRQ(ierr);
987
989 PetscFunctionReturn(0);
990}
991
992
993/**
994 * @brief Particle velocity from the host cell's face fluxes (the FaceFlux method).
995 * @details Each contravariant flux varies linearly between the cell's two faces of its
996 * family, at the particle's in-cell weights, and is mapped to Cartesian velocity by
997 * ContravariantToCartesianInCell(), the cell-centre solve of Contra2Cart(). The
998 * field is divergence-free wherever the fluxes are (exactly on rectilinear cells),
999 * its wall-normal component vanishes on a wall face, and its components are linear
1000 * only along their own axis, so it is first-order accurate. Local to this
1001 * translation unit.
1002 */
1003static PetscErrorCode InterpolateEulerVelocityFromFacesToSwarm(UserCtx *user, const char *swarmOutFieldName)
1004{
1005 PetscErrorCode ierr;
1006 DM swarm = user->swarm;
1007 DMDALocalInfo info;
1008 PetscMPIInt rank;
1009 Cmpnts ***lucont = NULL, ***lcsi = NULL, ***leta = NULL, ***lzet = NULL;
1010 PetscInt *cellIDs = NULL;
1011 PetscReal *weights = NULL, *velocity = NULL;
1012 PetscInt64 *pids = NULL;
1013 PetscInt nLocal;
1014
1015 PetscFunctionBegin;
1017 rank = user->simCtx->rank;
1018 info = user->info;
1019 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting face-flux velocity interpolation into '%s'...\n", swarmOutFieldName);
1020
1021 ierr = DMDAVecGetArrayRead(user->fda, user->lUcont, (void *)&lucont); CHKERRQ(ierr);
1022 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&lcsi); CHKERRQ(ierr);
1023 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&leta); CHKERRQ(ierr);
1024 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&lzet); CHKERRQ(ierr);
1025 ierr = DMSwarmGetLocalSize(swarm, &nLocal); CHKERRQ(ierr);
1026 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
1027 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
1028 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
1029 ierr = DMSwarmGetField(swarm, swarmOutFieldName, NULL, NULL, (void**)&velocity); CHKERRQ(ierr);
1030
1031 PetscInt n_outside = 0; /* Particles whose host-cell faces lie outside the ghosted region */
1032 for (PetscInt p = 0; p < nLocal; p++) {
1033 /* Host cell in cell-centred array numbering; its minimum faces are one index below. */
1034 const PetscInt i = cellIDs[3*p + 0] + 1, j = cellIDs[3*p + 1] + 1, k = cellIDs[3*p + 2] + 1;
1035 const Cmpnts w = {weights[3*p + 0], weights[3*p + 1], weights[3*p + 2]};
1036 Cmpnts u = {0.0, 0.0, 0.0}; /* set by the solve; initialised for compilers that cannot see it */
1037
1038 if (!FaceFluxStencilIsLocal(&info, &cellIDs[3*p])) {
1039 n_outside++;
1040 LOG_PARTICLE(user->simCtx, pids[p], "interpolate",
1041 "host cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") faces outside the ghosted region: '%s' zeroed\n",
1042 i - 1, j - 1, k - 1, swarmOutFieldName);
1043 velocity[3*p + 0] = velocity[3*p + 1] = velocity[3*p + 2] = 0.0;
1044 continue;
1045 }
1046 ierr = ContravariantToCartesianInCell(lucont, lcsi, leta, lzet, i, j, k, w, &u); CHKERRQ(ierr);
1047 velocity[3*p + 0] = u.x;
1048 velocity[3*p + 1] = u.y;
1049 velocity[3*p + 2] = u.z;
1050 LOG_PARTICLE(user->simCtx, pids[p], "interpolate",
1051 "face-flux '%s' in host cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") weights (%.6f, %.6f, %.6f) from fluxes x %.6e %.6e y %.6e %.6e z %.6e %.6e = (%.6e, %.6e, %.6e)\n",
1052 swarmOutFieldName, i - 1, j - 1, k - 1, w.x, w.y, w.z,
1053 lucont[k][j][i-1].x, lucont[k][j][i].x, lucont[k][j-1][i].y, lucont[k][j][i].y,
1054 lucont[k-1][j][i].z, lucont[k][j][i].z, u.x, u.y, u.z);
1055 }
1056 if (n_outside > 0) {
1058 "[Rank %d] %" PetscInt_FMT " particle(s) had their host-cell faces outside the ghosted region; '%s' was zeroed for them.\n",
1059 rank, n_outside, swarmOutFieldName);
1060 }
1061
1062 ierr = DMSwarmRestoreField(swarm, swarmOutFieldName, NULL, NULL, (void**)&velocity); CHKERRQ(ierr);
1063 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
1064 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
1065 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
1066 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&lzet); CHKERRQ(ierr);
1067 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&leta); CHKERRQ(ierr);
1068 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&lcsi); CHKERRQ(ierr);
1069 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcont, (void *)&lucont); CHKERRQ(ierr);
1070
1071 LOG_ALLOW(GLOBAL, LOG_INFO, "Finished face-flux velocity interpolation into '%s'.\n", swarmOutFieldName);
1073 PetscFunctionReturn(0);
1074}
1075
1076
1077/**
1078 * @brief Stage a ghosted cell-centred field at the grid corners, in the corner workspace for its
1079 * block size: zeroed, filled with the unweighted average of the surrounding cell centres
1080 * (InterpolateFieldFromCenterToCorner()), then its ghosts refreshed. Collective.
1081 * @param[in] user Grid context.
1082 * @param[in] cell_local Ghosted cell-centred field, its ghosts current.
1083 * @param[in] bs Its block size, 1 or 3.
1084 * @param[out] corner_view The corner workspace; its local vector holds the result.
1085 */
1086static PetscErrorCode StageCellFieldAtCorners(UserCtx *user, Vec cell_local, PetscInt bs, FieldView *corner_view)
1087{
1088 const FieldId corner_field_id = (bs == 3) ? FIELD_ID_CELL_VECTOR_AT_CORNER : FIELD_ID_CELL_SCALAR_AT_CORNER;
1089 DM dm = (bs == 3) ? user->fda : user->da;
1090 void *cell = NULL, *corner = NULL;
1091
1092 PetscFunctionBegin;
1094 // Both workspaces are allocated once by CreateAndInitializeAllVectors.
1095 PetscCall(FieldGetView(user, corner_field_id, corner_view));
1096 PetscCall(VecSet(corner_view->global_vec, 0.0));
1097 PetscCall(VecSet(corner_view->local_vec, 0.0));
1098 PetscCall(DMDAVecGetArrayRead(dm, cell_local, &cell));
1099 PetscCall(DMDAVecGetArray(dm, corner_view->global_vec, &corner));
1100 PetscCall(InterpolateFieldFromCenterToCorner(bs, cell, corner, user));
1101 PetscCall(DMDAVecRestoreArray(dm, corner_view->global_vec, &corner));
1102 PetscCall(DMDAVecRestoreArrayRead(dm, cell_local, &cell));
1103 PetscCall(UpdateLocalGhosts(user, corner_field_id));
1105 PetscFunctionReturn(0);
1106}
1107
1108/**
1109 * @brief Corner-averaged interpolation path (legacy).
1110 * @details Stages cell-centered data to corners via unweighted averaging,
1111 * then trilinear interpolation from corners to particles.
1112 * Local to this translation unit.
1113 */
1115 UserCtx *user,
1116 Vec fieldLocal_cellCentered,
1117 const char *fieldName,
1118 const char *swarmOutFieldName)
1119{
1120 PetscErrorCode ierr;
1121 DM swarm = user->swarm;
1122 PetscInt bs;
1123 DMDALocalInfo info;
1124 PetscMPIInt rank;
1125
1126 void *cornerPtr_read_with_ghosts;
1127
1128 // Swarm-related pointers
1129 PetscInt *cellIDs = NULL;
1130 PetscReal *weights = NULL;
1131 PetscInt64 *pids = NULL; // For logging particle IDs in warnings
1132 void *swarmOut = NULL;
1133 PetscReal *pos = NULL;
1134 PetscInt *status = NULL;
1135 PetscInt nLocal;
1136
1137 PetscFunctionBegin;
1139 rank = user->simCtx->rank;
1140 info = user->info;
1141 ierr = VecGetBlockSize(fieldLocal_cellCentered, &bs); CHKERRQ(ierr);
1142 if (bs != 1 && bs != 3) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "BlockSize must be 1 or 3.");
1143
1144 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting for field '%s'... \n", fieldName);
1145 // Select the appropriate DM for intermediate corner data based on block size
1146 DM dm_corner = (bs == 3) ? user->fda : user->da;
1147
1148 /* STAGE 1: Center-to-Corner Calculation with Communication */
1149 FieldView corner_view;
1150 ierr = StageCellFieldAtCorners(user, fieldLocal_cellCentered, bs, &corner_view); CHKERRQ(ierr);
1151 const FieldId corner_field_id = (bs == 3) ? FIELD_ID_CELL_VECTOR_AT_CORNER : FIELD_ID_CELL_SCALAR_AT_CORNER;
1152 Vec cornerLocal = corner_view.local_vec;
1153
1154 if (is_function_allowed(__func__) && (int)(LOG_VERBOSE) <= (int)get_log_level()) {
1155 ierr = LOG_CORNER_FIELD_ANATOMY(user, corner_field_id, "After Corner Velocity Interpolated"); CHKERRQ(ierr);
1156 }
1157
1158 // STAGE 2: Particle Interpolation using Ghosted Corner Data */
1159
1160 // (E) Get the local, GHOSTED array of corner data for the final interpolation step
1161 ierr = DMDAVecGetArrayRead(dm_corner, cornerLocal, &cornerPtr_read_with_ghosts); CHKERRQ(ierr);
1162
1163 // (F) Retrieve swarm fields for the particle loop
1164 ierr = DMSwarmGetLocalSize(swarm, &nLocal); CHKERRQ(ierr);
1165 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
1166 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
1167 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
1168 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
1169 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
1170 ierr = DMSwarmGetField(swarm, swarmOutFieldName, NULL, NULL, &swarmOut); CHKERRQ(ierr);
1171
1172 LOG_ALLOW(LOCAL,LOG_TRACE," Rank %d holds data upto & including %" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ".\n",rank,info.gxs + info.gxm,info.gys+info.gym,info.gzs+info.gzm);
1173
1174 // (G) Loop over each local particle
1175 PetscInt n_outside = 0; /* Particles whose corner stencil lies outside the ghosted region */
1176 for (PetscInt p = 0; p < nLocal; p++) {
1177
1178 Particle particle;
1179
1180 ierr = UnpackSwarmFields(p,pids,weights,pos,cellIDs,NULL,status,NULL,NULL,NULL,&particle); CHKERRQ(ierr);
1181
1182 // Safety check: Ensure the entire 8-node stencil is within the valid memory
1183 // region (owned + ghosts) of the local array.
1184
1185 if (!CornerStencilIsLocal(&info, particle.cell))
1186 {
1187 n_outside++;
1188 LOG_PARTICLE(user->simCtx, particle.PID, "interpolate",
1189 "cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") corner stencil outside the ghosted region: '%s' zeroed\n",
1190 particle.cell[0], particle.cell[1], particle.cell[2], fieldName);
1191 if (bs == 3) {
1192 ((PetscReal*)swarmOut)[3*p + 0] = 0.0;
1193 ((PetscReal*)swarmOut)[3*p + 1] = 0.0;
1194 ((PetscReal*)swarmOut)[3*p + 2] = 0.0;
1195 } else {
1196 ((PetscReal*)swarmOut)[p] = 0.0;
1197 }
1198 continue;
1199 }
1200
1202 cornerPtr_read_with_ghosts,
1203 &particle,
1204 swarmOut, p, bs);
1205 CHKERRQ(ierr);
1206 {
1207 const PetscReal *out = (const PetscReal *)swarmOut + bs * p;
1208 LOG_PARTICLE(user->simCtx, particle.PID, "interpolate",
1209 "corner-averaged '%s' in cell (%" PetscInt_FMT ",%" PetscInt_FMT ",%" PetscInt_FMT ") weights (%.6f, %.6f, %.6f) = %.6e %.6e %.6e\n",
1210 fieldName, particle.cell[0], particle.cell[1], particle.cell[2],
1211 particle.weights.x, particle.weights.y, particle.weights.z,
1212 (double)out[0], (double)(bs == 3 ? out[1] : 0.0), (double)(bs == 3 ? out[2] : 0.0));
1213 }
1214 }
1215 if (n_outside > 0) {
1217 "[Rank %d] %" PetscInt_FMT " particle(s) had their corner stencil outside the ghosted region; '%s' was zeroed for them.\n",
1218 rank, n_outside, fieldName);
1219 }
1220
1221 // (H) Restore all retrieved arrays and vectors */
1222 ierr = DMDAVecRestoreArrayRead(dm_corner, cornerLocal, &cornerPtr_read_with_ghosts); CHKERRQ(ierr);
1223
1224 // (I) Restore swarm fields
1225 ierr = DMSwarmRestoreField(swarm, swarmOutFieldName, NULL, NULL, &swarmOut); CHKERRQ(ierr);
1226 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
1227 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&pids); CHKERRQ(ierr);
1228 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
1229 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos); CHKERRQ(ierr);
1230 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_LOCATION_STATUS), NULL, NULL, (void**)&status); CHKERRQ(ierr);
1231 LOG_ALLOW(GLOBAL, LOG_INFO, "Finished for field '%s'.\n", fieldName);
1233 PetscFunctionReturn(0);
1234}
1235
1236/** @brief The arrays one method's point evaluation reads. */
1240 PetscBool periodic[3];
1241 Cmpnts ***field; /* Ucat, Ucat at the corners, or Ucont */
1242 Cmpnts ***csi, ***eta, ***zet; /* FaceFlux */
1243 FacePlaneArrays dual; /* Trilinear */
1244};
1245
1246/**
1247 * @brief Implementation of \ref InterpolateVelocityAtPointBegin().
1248 * @see InterpolateVelocityAtPointBegin()
1249 */
1251{
1252 VelocityPointInterpolator *v = NULL;
1253
1254 PetscFunctionBegin;
1256 PetscCall(PetscNew(&v));
1257 v->user = user;
1258 v->method = user->simCtx->interpolationMethod;
1259 GetPeriodicAxes(user->simCtx, v->periodic);
1260 if (v->method == INTERP_FACE_FLUX) {
1261 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcont, (void *)&v->field));
1262 PetscCall(DMDAVecGetArrayRead(user->fda, user->lCsi, (void *)&v->csi));
1263 PetscCall(DMDAVecGetArrayRead(user->fda, user->lEta, (void *)&v->eta));
1264 PetscCall(DMDAVecGetArrayRead(user->fda, user->lZet, (void *)&v->zet));
1265 } else if (v->method == INTERP_CORNER_AVERAGED) {
1266 FieldView corner;
1267
1268 // The same staging as the corner-averaged swarm pass.
1269 PetscCall(StageCellFieldAtCorners(user, user->lUcat, 3, &corner));
1270 PetscCall(DMDAVecGetArrayRead(user->fda, corner.local_vec, (void *)&v->field));
1271 } else {
1272 PetscCall(DMDAVecGetArrayRead(user->fda, user->lUcat, (void *)&v->field));
1273 PetscCall(MetricGetFacePlaneArrays(user, PETSC_TRUE, &v->dual));
1274 }
1275 *interp = v;
1277 PetscFunctionReturn(0);
1278}
1279
1280/**
1281 * @brief Implementation of \ref InterpolateVelocityAtPoint().
1282 * @see InterpolateVelocityAtPoint()
1283 */
1284PetscErrorCode InterpolateVelocityAtPoint(const VelocityPointInterpolator *interp, const PetscInt cell[3],
1285 const PetscReal weights[3], Cmpnts point, Cmpnts *u)
1286{
1287 const DMDALocalInfo *info = &interp->user->info;
1288
1289 PetscFunctionBegin;
1290 /* Called once per draw: a helper event, timed only when enabled by name. */
1292 u->x = u->y = u->z = 0.0;
1293 if (interp->method == INTERP_FACE_FLUX) {
1294 /* Host cell in cell-centred array numbering; its minimum faces are one index below. */
1295 const Cmpnts w = {weights[0], weights[1], weights[2]};
1296 if (FaceFluxStencilIsLocal(info, cell))
1297 PetscCall(ContravariantToCartesianInCell(interp->field, interp->csi, interp->eta, interp->zet,
1298 cell[0] + 1, cell[1] + 1, cell[2] + 1, w, u));
1299 } else if (interp->method == INTERP_CORNER_AVERAGED) {
1300 if (CornerStencilIsLocal(info, cell))
1301 PetscCall(TrilinearInterpolation_Vector(interp->field, cell[0], cell[1], cell[2],
1302 weights[0], weights[1], weights[2], u));
1303 } else {
1304 PetscInt base[3];
1305 PetscReal a[3], w[8] = {0};
1306 PetscBool unclamped, outside;
1307 PetscCall(CenterDualCellWeights(info, &interp->dual, interp->periodic, cell, weights, point, base, a, w,
1308 &unclamped, &outside));
1309 if (!outside) PetscCall(CenterInterpolateVector(interp->field, base, a, w, unclamped, u));
1310 }
1312 PetscFunctionReturn(0);
1313}
1314
1315/**
1316 * @brief Implementation of \ref InterpolateVelocityAtPointEnd().
1317 * @see InterpolateVelocityAtPointEnd()
1318 */
1320{
1321 VelocityPointInterpolator *v = *interp;
1322 UserCtx *user = v->user;
1323
1324 PetscFunctionBegin;
1326 if (v->method == INTERP_FACE_FLUX) {
1327 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lZet, (void *)&v->zet));
1328 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lEta, (void *)&v->eta));
1329 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void *)&v->csi));
1330 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcont, (void *)&v->field));
1331 } else if (v->method == INTERP_CORNER_AVERAGED) {
1332 FieldView corner;
1333 PetscCall(FieldGetView(user, FIELD_ID_CELL_VECTOR_AT_CORNER, &corner));
1334 PetscCall(DMDAVecRestoreArrayRead(user->fda, corner.local_vec, (void *)&v->field));
1335 } else {
1336 PetscCall(MetricRestoreFacePlaneArrays(user, &v->dual));
1337 PetscCall(DMDAVecRestoreArrayRead(user->fda, user->lUcat, (void *)&v->field));
1338 }
1339 PetscCall(PetscFree(*interp));
1341 PetscFunctionReturn(0);
1342}
1343
1344/**
1345 * @brief Check that an Eulerian source can be interpolated to a particle destination.
1346 * @details The source must be cell-centred, the destination real-valued, and their component
1347 * counts equal. Local to this translation unit.
1348 */
1349static PetscErrorCode ResolveInterpolationPair(UserCtx *user, FieldId source_field_id, ParticleFieldId target_field_id,
1350 FieldView *source_view, const ParticleFieldDescriptor **target_descriptor)
1351{
1352 PetscFunctionBegin;
1354 PetscCall(FieldGetView(user, source_field_id, source_view));
1355 PetscCall(ParticleFieldGetDescriptor(target_field_id, target_descriptor));
1356 PetscCheck(source_view->descriptor->layout == FIELD_LAYOUT_CELL_CENTERED,
1357 PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1358 "Eulerian-to-particle interpolation requires a cell-centered source; '%s' uses layout %s.",
1359 source_view->descriptor->canonical_name,
1360 FieldLayoutName(source_view->descriptor->layout));
1361 PetscCheck((*target_descriptor)->data_type == PETSC_REAL,
1362 PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1363 "Eulerian interpolation destination '%s' must use PETSC_REAL storage.",
1364 (*target_descriptor)->canonical_name);
1365 PetscCheck(source_view->descriptor->dof == (*target_descriptor)->components,
1366 PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1367 "Eulerian source '%s' has %" PetscInt_FMT " components but particle destination '%s' has %" PetscInt_FMT ".",
1368 source_view->descriptor->canonical_name, source_view->descriptor->dof,
1369 (*target_descriptor)->canonical_name, (*target_descriptor)->components);
1371 PetscFunctionReturn(0);
1372}
1373
1374/**
1375 * @brief Interpolates several Eulerian fields to their particle fields with the configured method.
1376 * @details FaceFlux takes Ucat from the face fluxes; the corner-averaged method runs one pass per
1377 * field; the cell-centre method interpolates every remaining field in one pass, sharing
1378 * each particle's dual cell and weights. Each field's values match a pass of its own.
1379 * Local to this translation unit.
1380 */
1381static PetscErrorCode InterpolateEulerFieldsToSwarm(UserCtx *user, PetscInt n, const FieldId source_field_ids[],
1382 const ParticleFieldId target_field_ids[])
1383{
1384 CenterInterpolationTarget targets[8];
1385 PetscInt ncenter = 0;
1386
1387 PetscFunctionBegin;
1389 PetscCheck(n <= (PetscInt)(sizeof(targets) / sizeof(targets[0])), PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1390 "At most %d fields interpolate in one pass; %d requested.", (int)(sizeof(targets) / sizeof(targets[0])), (int)n);
1391 for (PetscInt f = 0; f < n; ++f) {
1392 FieldView source_view;
1393 const ParticleFieldDescriptor *target_descriptor = NULL;
1394
1395 PetscCall(ResolveInterpolationPair(user, source_field_ids[f], target_field_ids[f], &source_view, &target_descriptor));
1396 if (user->simCtx->interpolationMethod == INTERP_FACE_FLUX && source_field_ids[f] == FIELD_ID_UCAT) {
1397 // Velocity comes from the face fluxes Ucat was built from; other fields have none.
1398 PetscCall(InterpolateEulerVelocityFromFacesToSwarm(user, target_descriptor->canonical_name));
1399 } else if (user->simCtx->interpolationMethod != INTERP_CORNER_AVERAGED) {
1400 targets[ncenter].local_vec = source_view.local_vec;
1401 targets[ncenter].field_name = source_view.descriptor->canonical_name;
1402 targets[ncenter].swarm_name = target_descriptor->canonical_name;
1403 ncenter++;
1404 } else {
1405 PetscCall(InterpolateEulerFieldFromCornerToSwarm(user, source_view.local_vec,
1406 source_view.descriptor->canonical_name,
1407 target_descriptor->canonical_name));
1408 }
1409 }
1410 if (ncenter > 0) PetscCall(InterpolateEulerFieldFromCenterToSwarm(user, ncenter, targets));
1412 PetscFunctionReturn(0);
1413}
1414
1415
1416/**
1417 * @brief Implementation of \ref InterpolateAllFieldsToSwarm().
1418 * @see InterpolateAllFieldsToSwarm()
1419 */
1421{
1422 PetscErrorCode ierr;
1423 PetscMPIInt rank;
1427 PetscFunctionBegin;
1428
1430
1431 rank = user->simCtx->rank;
1432
1434 " Interpolation of ucat to velocity begins on rank %d.\n",rank);
1435 /* Add fields as necessary to sources/targets; one pass shares each particle's dual cell. */
1436 ierr = InterpolateEulerFieldsToSwarm(user, (PetscInt)(sizeof(sources) / sizeof(sources[0])), sources, targets); CHKERRQ(ierr);
1437
1438 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRQ(ierr);
1440 "[rank %d]Completed Interpolateting all fields to the swarm.\n",rank);
1441
1443
1444 PetscFunctionReturn(0);
1445}
1446
1447/////////////////////// Scatter from particles to euler fields
1448
1449/**
1450 * @brief Functions for scattering particle data (scalar or vector) onto
1451 * Eulerian grid fields by averaging contributions within each cell.
1452 *
1453 * This file provides a modular set of functions to perform particle-to-grid
1454 * projection, specifically calculating cell-averaged quantities from particle properties.
1455 * It assumes a PETSc environment using DMDA for the grids and DMSwarm for particles.
1456 *
1457 * Key Features:
1458 * - Handles both scalar (DOF=1) and vector (DOF=3) particle fields.
1459 * - Uses a pre-calculated particle count vector (`ParticleCount`) for normalization.
1460 * - Uses particle-catalog metadata to resolve each supported Eulerian target.
1461 * - Modifies an existing, explicitly provided Eulerian field vector in place.
1462 * - Provides a high-level wrapper function (`ScatterAllParticleFieldsToEulerFields`)
1463 * to easily scatter a standard set of fields.
1464 * - Uses only the base `SETERRQ` macro for error reporting to maximize compiler compatibility.
1465 *
1466 * Dependencies:
1467 * - PETSc library (DMDA, DMSwarm, Vec, IS, PetscLog, etc.)
1468 * - A `UserCtx` struct (defined elsewhere, e.g., "userctx.h") containing pointers
1469 * to relevant DMs (`da`, `fda`), Vecs (`ParticleCount`, `P`, `Nvert`, `Ucat`, etc.),
1470 * and the `DMSwarm` object (`swarm`).
1471 * - A custom DMSwarm field named `"DMSwarm_CellID"` (blockSize=3, type=PETSC_INT)
1472 * must be registered and populated with the local cell indices for each particle.
1473 * - Logging infrastructure (`LOG_ALLOW`, etc.) assumed to be defined elsewhere.
1474 *
1475 * @defgroup scatter_module Particle-to-Grid Scattering
1476 * @{
1477 */
1478
1479//-----------------------------------------------------------------------------
1480// Internal Helper Modules (Lower-level building blocks)
1481//-----------------------------------------------------------------------------
1482/**
1483 * @defgroup scatter_module_internal Internal Scattering Helpers
1484 * @ingroup scatter_module
1485 * @brief Lower-level functions used by the main scattering routines.
1486 * @{
1487 */
1488
1489/*
1490 * Internal implementation detail for public API `AccumulateParticleField`.
1491 * Documentation is maintained in include/interpolation.h to keep a single source
1492 * of truth for Doxygen output.
1493 */
1494PetscErrorCode AccumulateParticleField(DM swarm, ParticleFieldId particle_field_id,
1495 DM gridSumDM, Vec localAccumulatorVec)
1496{
1497 PetscErrorCode ierr;
1498 PetscInt dof;
1499 PetscInt nlocal, p;
1500 const PetscReal *particle_arr = NULL;
1501 const PetscInt *cell_id_arr = NULL;
1502
1503 // DMDA Accessors
1504 PetscScalar ***arr_1d = NULL; // For scalar fields
1505 PetscScalar ****arr_3d = NULL; // For vector fields
1506
1507 // Ghosted dimension variables
1508 PetscInt gxs, gys, gzs, gxm, gym, gzm;
1509 char msg[ERROR_MSG_BUFFER_SIZE];
1510 const ParticleFieldDescriptor *descriptor = NULL;
1511 const char *particleFieldName = NULL;
1512
1513 PetscFunctionBeginUser;
1515
1516 ierr = ParticleFieldGetDescriptor(particle_field_id, &descriptor); CHKERRQ(ierr);
1517 PetscCheck(descriptor->data_type == PETSC_REAL, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1518 "Particle-to-grid accumulation requires PETSC_REAL data; field '%s' uses %s.",
1519 descriptor->canonical_name, PetscDataTypes[descriptor->data_type]);
1520 particleFieldName = descriptor->canonical_name;
1521
1522 // --- 1. Validation & Setup ---
1523 if (!swarm || !gridSumDM || !localAccumulatorVec)
1524 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Null input in AccumulateParticleField.");
1525
1526 // Get DMDA information
1527 ierr = DMDAGetInfo(gridSumDM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &dof, NULL, NULL, NULL, NULL, NULL); CHKERRQ(ierr);
1528 // Get Ghosted Corners (Global indices of the ghosted patch start, and its dimensions)
1529 ierr = DMDAGetGhostCorners(gridSumDM, &gxs, &gys, &gzs, &gxm, &gym, &gzm); CHKERRQ(ierr);
1530
1531 // --- 2. Verify Vector Type (Global vs Local) ---
1532 {
1533 PetscInt vecSize;
1534 PetscInt expectedLocalSize = gxm * gym * gzm * dof;
1535 ierr = VecGetSize(localAccumulatorVec, &vecSize); CHKERRQ(ierr);
1536
1537 if (vecSize != expectedLocalSize) {
1538 PetscSNPrintf(msg, sizeof(msg),
1539 "Vector dimension mismatch! Expected Ghosted Local Vector size %" PetscInt_FMT " (gxm*gym*gzm*dof), got %" PetscInt_FMT ". "
1540 "Did you pass a Global Vector instead of a Local Vector?",
1541 expectedLocalSize, vecSize);
1542 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", msg);
1543 }
1544 }
1545
1546 // --- 3. Acquire Particle Data ---
1547 ierr = DMSwarmGetLocalSize(swarm, &nlocal); CHKERRQ(ierr);
1548 // These calls will fail nicely if the field doesn't exist
1549 ierr = DMSwarmGetField(swarm, particleFieldName, NULL, NULL, (void **)&particle_arr); CHKERRQ(ierr);
1550 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cell_id_arr); CHKERRQ(ierr);
1551
1552 // --- 4. Acquire Grid Accessors ---
1553 // DMDAVecGetArray* handles the mapping from Global (i,j,k) to the underlying Local Array index
1554 if (dof == 1) {
1555 ierr = DMDAVecGetArray(gridSumDM, localAccumulatorVec, &arr_1d); CHKERRQ(ierr);
1556 } else if (dof == 3) {
1557 ierr = DMDAVecGetArrayDOF(gridSumDM, localAccumulatorVec, &arr_3d); CHKERRQ(ierr);
1558 } else {
1559 PetscSNPrintf(msg, sizeof(msg), "Unsupported DOF=%" PetscInt_FMT ". AccumulateParticleField supports DOF 1 or 3.", dof);
1560 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "%s", msg);
1561 }
1562
1563 // --- 5. Accumulate Loop ---
1564 // Iterate through all local particles
1565 for (p = 0; p < nlocal; ++p) {
1566 // Retrieve Geometric Grid Index (0-based)
1567 PetscInt i_geom = cell_id_arr[p * 3 + 0];
1568 PetscInt j_geom = cell_id_arr[p * 3 + 1];
1569 PetscInt k_geom = cell_id_arr[p * 3 + 2];
1570
1571 // Apply Shift (+1) to match Memory Layout (Index 0 is boundary/ghost)
1572 PetscInt i = i_geom + 1;
1573 PetscInt j = j_geom + 1;
1574 PetscInt k = k_geom + 1;
1575
1576 // Bounds Check: Ensure (i,j,k) falls within the Local Ghosted Patch.
1577 // This allows writing to ghost slots which will later be reduced to the owner rank.
1578 if (i >= gxs && i < gxs + gxm &&
1579 j >= gys && j < gys + gym &&
1580 k >= gzs && k < gzs + gzm)
1581 {
1582 if (dof == 1) {
1583 arr_1d[k][j][i] += particle_arr[p];
1584 } else {
1585 // For DOF=3, unroll the loop for slight optimization
1586 arr_3d[k][j][i][0] += particle_arr[p * 3 + 0];
1587 arr_3d[k][j][i][1] += particle_arr[p * 3 + 1];
1588 arr_3d[k][j][i][2] += particle_arr[p * 3 + 2];
1589 }
1590 }
1591 // Note: Particles outside the ghost layer are skipped. This is expected behavior
1592 // if particles have not yet been migrated or localized correctly.
1593 }
1594
1595 // --- 6. Restore Arrays and Fields ---
1596 if (dof == 1) {
1597 ierr = DMDAVecRestoreArray(gridSumDM, localAccumulatorVec, &arr_1d); CHKERRQ(ierr);
1598 } else {
1599 ierr = DMDAVecRestoreArrayDOF(gridSumDM, localAccumulatorVec, &arr_3d); CHKERRQ(ierr);
1600 }
1601
1602 ierr = DMSwarmRestoreField(swarm, particleFieldName, NULL, NULL, (void **)&particle_arr); CHKERRQ(ierr);
1603 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void **)&cell_id_arr); CHKERRQ(ierr);
1604
1606 PetscFunctionReturn(0);
1607}
1608
1609
1610/* Implementation for NormalizeGridVectorByCount declared in include/interpolation.h. */
1611PetscErrorCode NormalizeGridVectorByCount(DM countDM, Vec countVec,
1612 DM dataDM, Vec sumVec, Vec avgVec)
1613{
1614 PetscErrorCode ierr;
1615 PetscInt data_dof;
1616 PetscInt count_dof;
1617 PetscMPIInt rank;
1618 char msg[ERROR_MSG_BUFFER_SIZE];
1619
1620 // Pointers for DMDA array accessors - declare specific types
1621 PetscScalar ***count_arr_3d = NULL; // For DOF=1 count vector (3D DMDA)
1622 PetscScalar ***sum_arr_scalar = NULL; // For DOF=1 sum vector (3D DMDA)
1623 PetscScalar ***avg_arr_scalar = NULL; // For DOF=1 avg vector (3D DMDA)
1624 PetscScalar ****sum_arr_vector = NULL; // For DOF=3 sum vector (3D DMDA + DOF)
1625 PetscScalar ****avg_arr_vector = NULL; // For DOF=3 avg vector (3D DMDA + DOF)
1626
1627
1628 PetscFunctionBeginUser;
1629
1631
1632 rank = PetscGlobalRank;
1633
1634 // --- Validation ---
1635 ierr = DMDAGetInfo(countDM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &count_dof, NULL, NULL, NULL, NULL, NULL); CHKERRQ(ierr);
1636 ierr = DMDAGetInfo(dataDM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &data_dof, NULL, NULL, NULL, NULL, NULL); CHKERRQ(ierr);
1637 if (count_dof != 1) { PetscSNPrintf(msg, sizeof(msg), "countDM must have DOF=1, got %" PetscInt_FMT ".", count_dof); SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", msg); }
1638 if (data_dof != 1 && data_dof != 3) { PetscSNPrintf(msg, sizeof(msg), "dataDM DOF must be 1 or 3, got %" PetscInt_FMT ".", data_dof); SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "%s", msg); }
1639
1640 // --- Get Array Access using appropriate DMDA accessors ---
1641 ierr = DMDAVecGetArrayRead(countDM, countVec, &count_arr_3d); CHKERRQ(ierr);
1642
1643 if (data_dof == 1) {
1644 ierr = DMDAVecGetArrayRead(dataDM, sumVec, &sum_arr_scalar); CHKERRQ(ierr);
1645 ierr = DMDAVecGetArray(dataDM, avgVec, &avg_arr_scalar); CHKERRQ(ierr);
1646 } else { // data_dof == 3
1647 ierr = DMDAVecGetArrayDOFRead(dataDM, sumVec, &sum_arr_vector); CHKERRQ(ierr);
1648 ierr = DMDAVecGetArrayDOF(dataDM, avgVec, &avg_arr_vector); CHKERRQ(ierr);
1649 }
1650
1651 // Get the corners (global start indices) and dimensions of the *local owned* region
1652 PetscInt xs, ys, zs, xm, ym, zm;
1653 ierr = DMDAGetCorners(countDM, &xs, &ys, &zs, &xm, &ym, &zm); CHKERRQ(ierr);
1654
1655 // --- Normalize Over Owned Cells ---
1656 LOG_ALLOW(LOCAL, LOG_DEBUG, "(Rank %d): Normalizing DOF=%" PetscInt_FMT " data over owned range [%" PetscInt_FMT ":%" PetscInt_FMT ", %" PetscInt_FMT ":%" PetscInt_FMT ", %" PetscInt_FMT ":%" PetscInt_FMT "].\n",
1657 rank, data_dof, xs, xs+xm, ys, ys+ym, zs, zs+zm);
1658
1659 // Loop using GLOBAL indices (i, j, k) over the range owned by this process
1660 for (PetscInt k = zs; k < zs + zm; ++k) {
1661 for (PetscInt j = ys; j < ys + ym; ++j) {
1662 for (PetscInt i = xs; i < xs + xm; ++i) {
1663
1664 // Access the count using standard 3D indexing
1665 PetscScalar count = count_arr_3d[k][j][i];
1666
1667 if (PetscRealPart(count) > 0.5) { // Use tolerance for float comparison
1668 if (data_dof == 1) {
1669 // Access scalar sum/avg using standard 3D indexing
1670 avg_arr_scalar[k][j][i] = sum_arr_scalar[k][j][i] / count;
1671 } else { // data_dof == 3
1672 // Access vector components using DOF indexing on the last dimension
1673 for (PetscInt c = 0; c < data_dof; ++c) {
1674 avg_arr_vector[k][j][i][c] = sum_arr_vector[k][j][i][c] / count;
1675 }
1676 }
1677 } else { // count is zero or negative
1678 // Set average to zero
1679 if (data_dof == 1) {
1680 avg_arr_scalar[k][j][i] = 0.0;
1681 } else { // data_dof == 3
1682 for (PetscInt c = 0; c < data_dof; ++c) {
1683 avg_arr_vector[k][j][i][c] = 0.0;
1684 }
1685 }
1686 } // end if count > 0.5
1687 } // end i loop
1688 } // end j loop
1689 } // end k loop
1690
1691 // --- Restore Arrays using appropriate functions ---
1692 ierr = DMDAVecRestoreArrayRead(countDM, countVec, &count_arr_3d); CHKERRQ(ierr);
1693 if (data_dof == 1) {
1694 ierr = DMDAVecRestoreArrayRead(dataDM, sumVec, &sum_arr_scalar); CHKERRQ(ierr);
1695 ierr = DMDAVecRestoreArray(dataDM, avgVec, &avg_arr_scalar); CHKERRQ(ierr);
1696 } else { // data_dof == 3
1697 ierr = DMDAVecRestoreArrayDOFRead(dataDM, sumVec, &sum_arr_vector); CHKERRQ(ierr);
1698 ierr = DMDAVecRestoreArrayDOF(dataDM, avgVec, &avg_arr_vector); CHKERRQ(ierr);
1699 }
1700
1701 // --- Assemble Final Average Vector ---
1702 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Assembling final average vector (DOF=%" PetscInt_FMT ").\n", data_dof);
1703 ierr = VecAssemblyBegin(avgVec); CHKERRQ(ierr);
1704 ierr = VecAssemblyEnd(avgVec); CHKERRQ(ierr);
1705
1706
1708
1709 PetscFunctionReturn(0);
1710}
1711
1712/** @} */ // End of scatter_module_internal group
1713
1714//-----------------------------------------------------------------------------
1715// User-Facing API
1716//-----------------------------------------------------------------------------
1717//-----------------------------------------------------------------------------
1718// MODULE 4: Internal Scatter Orchestration Helper - No PetscErrorClear
1719//-----------------------------------------------------------------------------
1720
1721/**
1722 * @brief Implementation of \ref ScatterParticleFieldCellMean().
1723 * @see ScatterParticleFieldCellMean()
1724 */
1725PetscErrorCode ScatterParticleFieldCellMean(UserCtx *user, ParticleFieldId particle_field_id, DM dataDM,
1726 Vec countVec, PetscBool recount, Vec meanVec)
1727{
1728 PetscInt data_dof = 0;
1729 Vec local_sum = NULL, sum = NULL;
1730 const ParticleFieldDescriptor *descriptor = NULL;
1731
1732 PetscFunctionBeginUser;
1734 PetscCheck(user && user->swarm && dataDM && countVec && meanVec, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
1735 "Context, swarm, data DM, count and mean vectors are required.");
1736 PetscCall(ParticleFieldGetDescriptor(particle_field_id, &descriptor));
1737 PetscCall(DMDAGetInfo(dataDM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &data_dof, NULL, NULL, NULL, NULL, NULL));
1738 PetscCheck(data_dof == descriptor->components, PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP,
1739 "Field '%s' has %" PetscInt_FMT " components but the data DM has DOF %" PetscInt_FMT ".",
1740 descriptor->canonical_name, descriptor->components, data_dof);
1741
1742 // Each rank's particles add into its ghosted copy; the owners sum the copies.
1743 PetscCall(DMGetLocalVector(dataDM, &local_sum));
1744 PetscCall(VecSet(local_sum, 0.0));
1745 PetscCall(AccumulateParticleField(user->swarm, particle_field_id, dataDM, local_sum));
1746 PetscCall(DMGetGlobalVector(dataDM, &sum));
1747 PetscCall(VecSet(sum, 0.0));
1748 PetscCall(DMLocalToGlobalBegin(dataDM, local_sum, ADD_VALUES, sum));
1749 PetscCall(DMLocalToGlobalEnd(dataDM, local_sum, ADD_VALUES, sum));
1750 PetscCall(DMRestoreLocalVector(dataDM, &local_sum));
1751
1752 if (recount) PetscCall(CalculateParticleCountPerCell(user));
1753 PetscCall(NormalizeGridVectorByCount(user->da, countVec, dataDM, sum, meanVec));
1754 PetscCall(DMRestoreGlobalVector(dataDM, &sum));
1756 PetscFunctionReturn(0);
1757}
1758
1759
1760/* Implementation for ScatterParticleFieldToEulerField declared in include/interpolation.h. */
1762 ParticleFieldId particle_field_id,
1763 Vec eulerFieldAverageVec)
1764{
1765 PetscErrorCode ierr;
1766 DM targetDM = NULL; // Will point to user->da or user->fda
1767 PetscInt expected_dof = 0; // Will be 1 or 3
1768 char msg[ERROR_MSG_BUFFER_SIZE]; // Buffer for formatted error messages
1769 const ParticleFieldDescriptor *particle_descriptor = NULL;
1770 const FieldDescriptor *eulerian_descriptor = NULL;
1771 FieldView target_view;
1772 const char *particleFieldName = NULL;
1773
1774 PetscFunctionBeginUser;
1775
1777
1778 // --- Essential Input Validation ---
1779 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx pointer is NULL.");
1780 if (!user->swarm) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->swarm is NULL.");
1781 if (!user->ParticleCount) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx->ParticleCount is NULL.");
1782 if (!eulerFieldAverageVec) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Output eulerFieldAverageVec is NULL.");
1783 ierr = ParticleFieldGetDescriptor(particle_field_id, &particle_descriptor); CHKERRQ(ierr);
1784 PetscCheck((particle_descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_EULERIAN_SCATTER) != 0,
1785 PETSC_COMM_SELF, PETSC_ERR_SUP,
1786 "Particle field '%s' has no registered Eulerian scatter target.",
1787 particle_descriptor->canonical_name);
1788 PetscCheck(particle_descriptor->eulerian_scatter_target != FIELD_ID_INVALID,
1789 PETSC_COMM_SELF, PETSC_ERR_PLIB,
1790 "Particle field '%s' advertises scatter support without an Eulerian target.",
1791 particle_descriptor->canonical_name);
1792 particleFieldName = particle_descriptor->canonical_name;
1793 expected_dof = particle_descriptor->components;
1794 ierr = FieldGetDescriptor(particle_descriptor->eulerian_scatter_target, &eulerian_descriptor); CHKERRQ(ierr);
1795 PetscCheck(eulerian_descriptor->dof == expected_dof, PETSC_COMM_SELF, PETSC_ERR_PLIB,
1796 "Particle field '%s' has %" PetscInt_FMT " components but Eulerian target '%s' has %" PetscInt_FMT ".",
1797 particleFieldName, expected_dof, eulerian_descriptor->canonical_name, eulerian_descriptor->dof);
1798 ierr = FieldGetView(user, particle_descriptor->eulerian_scatter_target, &target_view); CHKERRQ(ierr);
1799 targetDM = target_view.dm;
1800
1801 // --- Validate the provided Target Vec's Compatibility ---
1802 DM vec_dm;
1803 PetscInt vec_dof;
1804 // Check that the provided average vector has a DM associated with it
1805 ierr = VecGetDM(eulerFieldAverageVec, &vec_dm); CHKERRQ(ierr);
1806 if (!vec_dm) {
1807 PetscSNPrintf(msg, sizeof(msg), "Provided eulerFieldAverageVec for field '%s' does not have an associated DM.", particleFieldName);
1808 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "%s", msg);
1809 }
1810 // Get the block size (DOF) of the provided vector
1811 ierr = VecGetBlockSize(eulerFieldAverageVec, &vec_dof); CHKERRQ(ierr);
1812 // Compare the vector's associated DM with the one determined by the field name
1813 if (vec_dm != targetDM) {
1814 const char *target_dm_name = "targetDM", *vec_dm_name = "vec_dm";
1815 // Get actual names if possible for a more informative error message
1816 PetscObjectGetName((PetscObject)targetDM, &target_dm_name);
1817 PetscObjectGetName((PetscObject)vec_dm, &vec_dm_name);
1818 PetscSNPrintf(msg, sizeof(msg), "Provided eulerFieldAverageVec associated with DM '%s', but field '%s' requires scatter to DM '%s'.", vec_dm_name, particleFieldName, target_dm_name);
1819 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "%s", msg);
1820 }
1821 // Compare the vector's DOF with the one expected for the field name
1822 if (vec_dof != expected_dof) {
1823 PetscSNPrintf(msg, sizeof(msg), "Field '%s' requires DOF %" PetscInt_FMT ", but provided eulerFieldAverageVec has DOF %" PetscInt_FMT ".", particleFieldName, expected_dof, vec_dof);
1824 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_INCOMP, "%s", msg);
1825 }
1826
1827 // --- Perform Scatter using Internal Helper ---
1828 // Log intent before calling the core logic
1829 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Scattering field '%s' (DOF=%" PetscInt_FMT ").\n", particleFieldName, expected_dof);
1830 ierr = ScatterParticleFieldCellMean(user, particle_field_id, targetDM, user->ParticleCount, PETSC_TRUE,
1831 eulerFieldAverageVec); CHKERRQ(ierr);
1832
1833 LOG_ALLOW(GLOBAL, LOG_INFO, "Successfully scattered field '%s'.\n", particleFieldName);
1834
1836
1837 PetscFunctionReturn(0);
1838}
1839
1840/* Implementation for ScatterAllParticleFieldsToEulerFields declared in include/interpolation.h. */
1842{
1843 PetscErrorCode ierr;
1844 PetscFunctionBeginUser;
1846
1847 LOG_ALLOW(GLOBAL, LOG_INFO, "Starting scattering of specified particle fields to Eulerian grids.\n");
1848
1849 // --- Pre-computation Check: Ensure Particle Counts are Ready ---
1850 if (!user->ParticleCount) {
1851 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "UserCtx->ParticleCount is NULL. Compute counts before calling ScatterAllParticleFieldsToEulerFields.");
1852 }
1853
1854 // --- Scatter Particle Field "Psi" -> Eulerian Field user->Psi (on da) ---
1855 // Check if the target Eulerian vector 'user->Psi' exists.
1856 if (user->Psi) {
1857
1858 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Scattering particle field 'Psi' to user->Psi.\n");
1859 // Zero the target vector before accumulating the new average for this step/call.
1860
1861 // Debug verification: global means are collectives, so they run only when they are logged.
1862 const PetscBool log_means = (PetscBool)((int)get_log_level() >= (int)LOG_DEBUG);
1863 PetscReal Avg_Psi = 0.0, Avg_swarm_Psi = 0.0;
1864 if (log_means) {
1865 Vec swarm_Psi;
1866 ierr = VecMean(user->Psi,&Avg_Psi); CHKERRQ(ierr);
1867 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Scalar(Psi) before scatter: %.4f.\n",Avg_Psi);
1868 ierr = DMSwarmCreateGlobalVectorFromField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), &swarm_Psi); CHKERRQ(ierr);
1869 ierr = VecMean(swarm_Psi,&Avg_swarm_Psi); CHKERRQ(ierr);
1870 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Particle Scalar(Psi): %.4f.\n",Avg_swarm_Psi);
1871 ierr = DMSwarmDestroyGlobalVectorFromField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), &swarm_Psi); CHKERRQ(ierr);
1872 }
1873
1874 //ierr = VecSet(user->P, 0.0); CHKERRQ(ierr);
1875 // Call the unified scatter function. It will handle DM determination and validation.
1876 // It will also error out if the *particle* field "Psi" doesn't exist in the swarm.
1877 ierr = ScatterParticleFieldToEulerField(user, PARTICLE_FIELD_ID_PSI, user->Psi); CHKERRQ(ierr);
1878 // The average leaves the empty dummy cells at zero; give them the adjacent cell's
1879 // value (no scalar flux through the boundary) so node averages near a boundary read
1880 // cell means, not a mix with zeros.
1881 ierr = UpdateDummyCells(user, FIELD_ID_PSI); CHKERRQ(ierr);
1882 ierr = UpdateCornerNodes(user, FIELD_ID_PSI); CHKERRQ(ierr);
1883 // IEM reads the cell mean through the ghosted lPsi; refresh it from the new average.
1884 ierr = UpdateLocalGhosts(user, FIELD_ID_PSI); CHKERRQ(ierr);
1885 if (log_means) {
1886 ierr = VecMean(user->Psi,&Avg_Psi); CHKERRQ(ierr);
1887 LOG_ALLOW(GLOBAL,LOG_DEBUG," Average of Scalar(Psi) after scatter: %.4f.\n",Avg_Psi);
1888 }
1889 } else {
1890 // Only log a warning if the target Eulerian field is missing in the context.
1891 LOG_ALLOW(GLOBAL, LOG_WARNING, "Skipping scatter for 'Psi': UserCtx->Psi is NULL.\n");
1892 }
1893
1894 // Additional scatterable particle fields require an explicit catalog entry
1895 // with a compatible persistent Eulerian target.
1896
1897 LOG_ALLOW(GLOBAL, LOG_INFO, "Finished scattering specified particle fields.\n");
1899 PetscFunctionReturn(0);
1900}
1901
1902/** @} */ // End of scatter_module group
1903
1904
1905
1906/**
1907 * @brief Implementation of \ref InterpolateCornerToFaceCenter_Scalar().
1908 * @see InterpolateCornerToFaceCenter_Scalar()
1909 */
1911 PetscReal ***corner_arr,
1912 PetscReal ***faceX_arr,
1913 PetscReal ***faceY_arr,
1914 PetscReal ***faceZ_arr,
1915 UserCtx *user)
1916{
1917 PetscErrorCode ierr;
1918 DMDALocalInfo info;
1919
1920 PetscFunctionBeginUser;
1921
1923
1924 info = user->info;
1925
1926 // Determine owned-cell ranges based on corner-node ownership
1927 PetscInt xs, xm, ys, ym, zs, zm;
1928 ierr = GetOwnedCellRange(&info, 0, &xs, &xm); CHKERRQ(ierr);
1929 ierr = GetOwnedCellRange(&info, 1, &ys, &ym); CHKERRQ(ierr);
1930 ierr = GetOwnedCellRange(&info, 2, &zs, &zm); CHKERRQ(ierr);
1931
1932 // Global exclusive end indices for cells
1933 PetscInt xe = xs + xm;
1934 PetscInt ye = ys + ym;
1935 PetscInt ze = zs + zm;
1936
1937 // --- X‐faces: loops k=zs..ze-1, j=ys..ye-1, i=xs..xe (xm+1 faces per row) ---
1938 for (PetscInt k = zs; k < ze; ++k) {
1939 PetscInt k_loc = k - zs;
1940 for (PetscInt j = ys; j < ye; ++j) {
1941 PetscInt j_loc = j - ys;
1942 for (PetscInt i = xs; i <= xe; ++i) {
1943 PetscInt i_loc = i - xs; // 0..xm
1944 // Average the four corners of the Y-Z face at X = i
1945 PetscReal sum = corner_arr[k ][j ][i]
1946 + corner_arr[k+1][j ][i]
1947 + corner_arr[k ][j+1][i]
1948 + corner_arr[k+1][j+1][i];
1949 faceX_arr[k_loc][j_loc][i_loc] = sum * 0.25;
1950 }
1951 }
1952 }
1953
1954 // --- Y‐faces: loops k=zs..ze-1, j=ys..ye (ym+1 faces), i=xs..xe-1 ---
1955 for (PetscInt k = zs; k < ze; ++k) {
1956 PetscInt k_loc = k - zs;
1957 for (PetscInt j = ys; j <= ye; ++j) {
1958 PetscInt j_loc = j - ys; // 0..ym
1959 for (PetscInt i = xs; i < xe; ++i) {
1960 PetscInt i_loc = i - xs;
1961 // Average the four corners of the X-Z face at Y = j
1962 PetscReal sum = corner_arr[k ][j][i ]
1963 + corner_arr[k+1][j][i ]
1964 + corner_arr[k ][j][i+1]
1965 + corner_arr[k+1][j][i+1];
1966 faceY_arr[k_loc][j_loc][i_loc] = sum * 0.25;
1967 }
1968 }
1969 }
1970
1971 // --- Z‐faces: loops k=zs..ze (zm+1), j=ys..ye-1, i=xs..xe-1 ---
1972 for (PetscInt k = zs; k <= ze; ++k) {
1973 PetscInt k_loc = k - zs;
1974 for (PetscInt j = ys; j < ye; ++j) {
1975 PetscInt j_loc = j - ys;
1976 for (PetscInt i = xs; i < xe; ++i) {
1977 PetscInt i_loc = i - xs;
1978 // Average the four corners of the X-Y face at Z = k
1979 PetscReal sum = corner_arr[k][j ][i ]
1980 + corner_arr[k][j ][i+1]
1981 + corner_arr[k][j+1][i ]
1982 + corner_arr[k][j+1][i+1];
1983 faceZ_arr[k_loc][j_loc][i_loc] = sum * 0.25;
1984 }
1985 }
1986 }
1987
1989
1990 PetscFunctionReturn(0);
1991}
1992
1993
1994/**
1995 * @brief Implementation of \ref InterpolateCornerToFaceCenter_Vector().
1996 * @see InterpolateCornerToFaceCenter_Vector()
1997 */
1999 Cmpnts ***corner_arr,
2000 Cmpnts ***faceX_arr,
2001 Cmpnts ***faceY_arr,
2002 Cmpnts ***faceZ_arr,
2003 UserCtx *user)
2004{
2005 PetscErrorCode ierr;
2006 DMDALocalInfo info;
2007 PetscMPIInt rank;
2008
2009 PetscFunctionBeginUser;
2010
2012
2013 rank = user->simCtx->rank;
2015 "Rank %d starting InterpolateFieldFromCornerToFaceCenter_Vector.\n", rank);
2016
2017 info = user->info;
2018
2019 PetscInt xs, xm, ys, ym, zs, zm;
2020 ierr = GetOwnedCellRange(&info, 0, &xs, &xm); CHKERRQ(ierr);
2021 ierr = GetOwnedCellRange(&info, 1, &ys, &ym); CHKERRQ(ierr);
2022 ierr = GetOwnedCellRange(&info, 2, &zs, &zm); CHKERRQ(ierr);
2023
2024 PetscInt xe = xs + xm;
2025 PetscInt ye = ys + ym;
2026 PetscInt ze = zs + zm;
2027
2028 // X-faces
2029 for (PetscInt k = zs; k < ze; ++k) {
2030 PetscInt k_loc = k - zs;
2031 for (PetscInt j = ys; j < ye; ++j) {
2032 PetscInt j_loc = j - ys;
2033 for (PetscInt i = xs; i <= xe; ++i) {
2034 PetscInt i_loc = i - xs;
2035 Cmpnts sum = {0,0,0};
2036 sum.x = corner_arr[k ][j ][i].x + corner_arr[k+1][j ][i].x
2037 + corner_arr[k ][j+1][i].x + corner_arr[k+1][j+1][i].x;
2038 sum.y = corner_arr[k ][j ][i].y + corner_arr[k+1][j ][i].y
2039 + corner_arr[k ][j+1][i].y + corner_arr[k+1][j+1][i].y;
2040 sum.z = corner_arr[k ][j ][i].z + corner_arr[k+1][j ][i].z
2041 + corner_arr[k ][j+1][i].z + corner_arr[k+1][j+1][i].z;
2042 faceX_arr[k_loc][j_loc][i_loc].x = sum.x * 0.25;
2043 faceX_arr[k_loc][j_loc][i_loc].y = sum.y * 0.25;
2044 faceX_arr[k_loc][j_loc][i_loc].z = sum.z * 0.25;
2045 }
2046 }
2047 }
2048
2050 "Rank %d x-face Interpolation complete.\n", rank);
2051
2052 // Y-faces
2053 for (PetscInt k = zs; k < ze; ++k) {
2054 PetscInt k_loc = k - zs;
2055 for (PetscInt j = ys; j <= ye; ++j) {
2056 PetscInt j_loc = j - ys;
2057 for (PetscInt i = xs; i < xe; ++i) {
2058 PetscInt i_loc = i - xs;
2059 Cmpnts sum = {0,0,0};
2060 sum.x = corner_arr[k ][j][i ].x + corner_arr[k+1][j][i ].x
2061 + corner_arr[k ][j][i+1].x + corner_arr[k+1][j][i+1].x;
2062 sum.y = corner_arr[k ][j][i ].y + corner_arr[k+1][j][i ].y
2063 + corner_arr[k ][j][i+1].y + corner_arr[k+1][j][i+1].y;
2064 sum.z = corner_arr[k ][j][i ].z + corner_arr[k+1][j][i ].z
2065 + corner_arr[k ][j][i+1].z + corner_arr[k+1][j][i+1].z;
2066 faceY_arr[k_loc][j_loc][i_loc].x = sum.x * 0.25;
2067 faceY_arr[k_loc][j_loc][i_loc].y = sum.y * 0.25;
2068 faceY_arr[k_loc][j_loc][i_loc].z = sum.z * 0.25;
2069 }
2070 }
2071 }
2072
2074 "Rank %d y-face Interpolation complete.\n", rank);
2075
2076 // Z-faces
2077 for (PetscInt k = zs; k <= ze; ++k) {
2078 PetscInt k_loc = k - zs;
2079 for (PetscInt j = ys; j < ye; ++j) {
2080 PetscInt j_loc = j - ys;
2081 for (PetscInt i = xs; i < xe; ++i) {
2082 PetscInt i_loc = i - xs;
2083 Cmpnts sum = {0,0,0};
2084 sum.x = corner_arr[k][j ][i ].x + corner_arr[k][j ][i+1].x
2085 + corner_arr[k][j+1][i ].x + corner_arr[k][j+1][i+1].x;
2086 sum.y = corner_arr[k][j ][i ].y + corner_arr[k][j ][i+1].y
2087 + corner_arr[k][j+1][i ].y + corner_arr[k][j+1][i+1].y;
2088 sum.z = corner_arr[k][j ][i ].z + corner_arr[k][j ][i+1].z
2089 + corner_arr[k][j+1][i ].z + corner_arr[k][j+1][i+1].z;
2090 faceZ_arr[k_loc][j_loc][i_loc].x = sum.x * 0.25;
2091 faceZ_arr[k_loc][j_loc][i_loc].y = sum.y * 0.25;
2092 faceZ_arr[k_loc][j_loc][i_loc].z = sum.z * 0.25;
2093 }
2094 }
2095 }
2096
2098 "Rank %d z-face Interpolation complete.\n", rank);
2099
2101 PetscFunctionReturn(0);
2102}
PetscErrorCode UpdateDummyCells(UserCtx *user, FieldId field_id)
Fills the dummy cells on the non-periodic faces of one cell-centred field.
PetscErrorCode UpdateCornerNodes(UserCtx *user, FieldId field_id)
Fills the edge and corner dummy cells of one cell-centred field.
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
Read-only flat arrays of one family of face planes (grid cells or dual cells).
Definition Metric.h:528
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
PetscErrorCode UnpackSwarmFields(PetscInt i, const PetscInt64 *PIDs, const PetscReal *weights, const PetscReal *positions, const PetscInt *cellIndices, PetscReal *velocities, PetscInt *LocStatus, PetscReal *diffusivity, Cmpnts *diffusivitygradient, PetscReal *psi, Particle *particle)
Initializes a Particle struct with data from DMSwarm fields.
FieldLayout layout
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
@ FIELD_LAYOUT_CELL_CENTERED
const char * canonical_name
const char * FieldLayoutName(FieldLayout layout)
Return a stable printable label for a field layout.
PetscErrorCode FieldGetDescriptor(FieldId field_id, const FieldDescriptor **descriptor)
Return immutable metadata for a valid field identifier.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_PSI
@ FIELD_ID_CELL_SCALAR_AT_CORNER
@ FIELD_ID_UCAT
@ FIELD_ID_CELL_VECTOR_AT_CORNER
@ FIELD_ID_DIFFUSIVITY_GRADIENT
@ FIELD_ID_INVALID
@ FIELD_ID_DIFFUSIVITY
Immutable metadata for one field identity.
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode AccumulateParticleField(DM swarm, ParticleFieldId particle_field_id, DM gridSumDM, Vec gridSumVec)
Accumulates a particle field (scalar or vector) into a target grid sum vector.
PetscErrorCode NormalizeGridVectorByCount(DM countDM, Vec countVec, DM dataDM, Vec sumVec, Vec avgVec)
Normalizes a grid vector of sums by a grid vector of counts to produce an average.
PetscErrorCode ScatterParticleFieldToEulerField(UserCtx *user, ParticleFieldId particle_field_id, Vec eulerFieldAverageVec)
Scatters a particle field (scalar or vector) to the corresponding Eulerian field average.
PetscErrorCode ScatterAllParticleFieldsToEulerFields(UserCtx *user)
Scatters a predefined set of particle fields to their corresponding Eulerian fields.
PetscErrorCode ScatterParticleFieldCellMean(UserCtx *user, ParticleFieldId particle_field_id, DM dataDM, Vec countVec, PetscBool recount, Vec meanVec)
Cell mean of a particle field: the field summed over each cell's particles, divided by the cell's cou...
static PetscBool FaceFluxStencilIsLocal(const DMDALocalInfo *info, const PetscInt cell[3])
Whether the face fluxes of a host cell lie in the ghosted region: in cell-centred numbering (i,...
PetscErrorCode TrilinearInterpolation_Vector(Cmpnts ***fieldVec, PetscInt i, PetscInt j, PetscInt k, PetscReal a1, PetscReal a2, PetscReal a3, Cmpnts *vec)
Implementation of TrilinearInterpolation_Vector().
static PetscErrorCode InterpolateEulerFieldFromCenterToSwarm(UserCtx *user, PetscInt ntargets, CenterInterpolationTarget *targets)
Direct cell-center trilinear interpolation (second-order on curvilinear grids).
PetscErrorCode InterpolateFieldFromCornerToCenter_Vector(Cmpnts ***field_arr, Cmpnts ***centfield_arr, UserCtx *user)
Implementation of InterpolateFieldFromCornerToCenter_Vector().
PetscErrorCode InterpolateCornerToFaceCenter_Vector(Cmpnts ***corner_arr, Cmpnts ***faceX_arr, Cmpnts ***faceY_arr, Cmpnts ***faceZ_arr, UserCtx *user)
Implementation of InterpolateCornerToFaceCenter_Vector().
PetscErrorCode InterpolateFieldFromCornerToCenter_Scalar(PetscReal ***field_arr, PetscReal ***centfield_arr, UserCtx *user)
Implementation of InterpolateFieldFromCornerToCenter_Scalar().
void * field_ptr
Source array while the pass runs.
static PetscErrorCode CenterInterpolateScalar(PetscReal ***fieldScal, const PetscInt base[3], const PetscReal a[3], const PetscReal w[8], PetscBool unclamped, PetscReal *val)
A cell-centred scalar at a point, from the dual cell CenterDualCellWeights() found.
PetscErrorCode InterpolateAllFieldsToSwarm(UserCtx *user)
Implementation of InterpolateAllFieldsToSwarm().
Vec local_vec
Ghosted cell-centred source.
static PetscErrorCode ResolveInterpolationPair(UserCtx *user, FieldId source_field_id, ParticleFieldId target_field_id, FieldView *source_view, const ParticleFieldDescriptor **target_descriptor)
Check that an Eulerian source can be interpolated to a particle destination.
static PetscErrorCode CenterInterpolateVector(Cmpnts ***fieldVec, const PetscInt base[3], const PetscReal a[3], const PetscReal w[8], PetscBool unclamped, Cmpnts *vec)
A cell-centred vector at a point, from the dual cell CenterDualCellWeights() found.
static PetscBool CornerStencilIsLocal(const DMDALocalInfo *info, const PetscInt cell[3])
Whether the eight corners of a host cell (nodes cell to cell + 1) lie in the ghosted region.
const char * swarm_name
Destination swarm field.
PetscReal * swarm_out
Destination array while the pass runs.
#define PICURV_APPEND(...)
PetscErrorCode InterpolateVelocityAtPoint(const VelocityPointInterpolator *interp, const PetscInt cell[3], const PetscReal weights[3], Cmpnts point, Cmpnts *u)
Implementation of InterpolateVelocityAtPoint().
PetscErrorCode InterpolateVelocityAtPointEnd(VelocityPointInterpolator **interp)
Implementation of InterpolateVelocityAtPointEnd().
static PetscErrorCode InterpolateEulerVelocityFromFacesToSwarm(UserCtx *user, const char *swarmOutFieldName)
Particle velocity from the host cell's face fluxes (the FaceFlux method).
static void ComputeTrilinearWeightsUnclamped(PetscReal a1, PetscReal a2, PetscReal a3, PetscReal *w)
Unclamped trilinear weights for boundary extrapolation.
PetscInt bs
1 or 3 components.
#define ERROR_MSG_BUFFER_SIZE
PetscErrorCode TestCornerToCenterInterpolation(UserCtx *user)
Implementation of TestCornerToCenterInterpolation().
static PetscErrorCode InterpolateEulerFieldFromCornerToSwarm(UserCtx *user, Vec fieldLocal_cellCentered, const char *fieldName, const char *swarmOutFieldName)
Corner-averaged interpolation path (legacy).
static PetscErrorCode CenterDualCellWeights(const DMDALocalInfo *info, const FacePlaneArrays *dual, const PetscBool periodic[3], const PetscInt cell[3], const PetscReal weights[3], Cmpnts loc, PetscInt base[3], PetscReal a[3], PetscReal w[8], PetscBool *unclamped, PetscBool *outside)
The dual cell of cell centres a point interpolates from, and its trilinear weights.
PetscErrorCode TrilinearInterpolation_Scalar(PetscReal ***fieldScal, PetscInt i, PetscInt j, PetscInt k, PetscReal a1, PetscReal a2, PetscReal a3, PetscReal *val)
Implementation of TrilinearInterpolation_Scalar().
PetscErrorCode InterpolateFieldFromCenterToCorner_Vector(Cmpnts ***centfield_arr, Cmpnts ***corner_arr, UserCtx *user)
Implementation of InterpolateFieldFromCenterToCorner_Vector().
static PetscErrorCode InterpolateEulerFieldsToSwarm(UserCtx *user, PetscInt n, const FieldId source_field_ids[], const ParticleFieldId target_field_ids[])
Interpolates several Eulerian fields to their particle fields with the configured method.
static void ComputeTrilinearWeights(PetscReal a1, PetscReal a2, PetscReal a3, PetscReal *w)
Compute the eight trilinear interpolation weights for a particle's local coordinates.
PetscErrorCode InterpolateVelocityAtPointBegin(UserCtx *user, VelocityPointInterpolator **interp)
Implementation of InterpolateVelocityAtPointBegin().
const char * field_name
Source name, for logging.
PetscErrorCode InterpolateCornerToFaceCenter_Scalar(PetscReal ***corner_arr, PetscReal ***faceX_arr, PetscReal ***faceY_arr, PetscReal ***faceZ_arr, UserCtx *user)
Implementation of InterpolateCornerToFaceCenter_Scalar().
static PetscErrorCode InterpolateEulerFieldToSwarmForParticle(void *fieldPtr, Particle *particle, void *swarmOut, PetscInt p, PetscInt blockSize)
Interpolate one Eulerian field to a single located swarm particle.
InterpolationMethod method
static void AppendInterpolationTargetText(char *text, size_t size, size_t *used, const CenterInterpolationTarget *tg, PetscInt p, PetscInt bi, PetscInt bj, PetscInt bk)
Appends one target's interpolated value and its eight dual-cell corner values to a particle's interpo...
static PetscErrorCode StageCellFieldAtCorners(UserCtx *user, Vec cell_local, PetscInt bs, FieldView *corner_view)
Stage a ghosted cell-centred field at the grid corners, in the corner workspace for its block size: z...
PetscErrorCode InterpolateFieldFromCenterToCorner_Scalar(PetscReal ***centfield_arr, PetscReal ***corner_arr, UserCtx *user)
Implementation of InterpolateFieldFromCenterToCorner_Scalar().
One cell-centred field interpolated to a particle field in a shared pass.
The arrays one method's point evaluation reads.
#define InterpolateFieldFromCenterToCorner(blockSize, centfield_ptr, corner_ptr, user_ctx)
Macro to dispatch to the correct scalar or vector center-to-corner function based on a runtime block ...
#define InterpolateFieldFromCornerToCenter(field, centfield, user)
Generic macro to call the appropriate interpolation function based on the field type.
#define TrilinearInterpolation(fieldPtr, i, j, k, a1, a2, a3, outPtr)
Macro that calls either the scalar or vector trilinear interpolation function based on the type of th...
#define LOG_PARTICLE(simCtx, pid, stage, fmt,...)
Reports one particle at one stage of a step: the consolidated per-particle line.
Definition logging.h:355
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PARTICLE_LOG_ACTIVE(simCtx, pid)
True when LOG_PARTICLE() would print for this particle in the calling function.
Definition logging.h:335
#define LOG_LOOP_ALLOW_EXACT(scope, level, var, val, fmt,...)
Logs a custom message if a variable equals a specific value.
Definition logging.h:405
PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name)
Logs the node-layout anatomy of the transient center-to-corner interpolation field.
Definition logging.c:2997
@ LOG_TRACE
Very fine-grained tracing information for in-depth debugging.
Definition logging.h:33
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_LOCATION_STATUS
@ PARTICLE_FIELD_ID_WEIGHT
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_PID
@ PARTICLE_FIELD_ID_CELL_ID
@ PARTICLE_FIELD_ID_PSI
@ PARTICLE_FIELD_ID_DIFFUSIVITY_GRADIENT
@ PARTICLE_FIELD_ID_DIFFUSIVITY
@ PARTICLE_FIELD_ID_VELOCITY
@ PARTICLE_FIELD_CAPABILITY_EULERIAN_SCATTER
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
PetscErrorCode GetOwnedCellRange(const DMDALocalInfo *info_nodes, PetscInt dim, PetscInt *xs_cell_global_out, PetscInt *xm_cell_local_out)
Determines the global starting index and number of CELLS owned by the current processor in a specifie...
Definition setup.c:3021
static void GetOwnedInteriorCellBounds(const DMDALocalInfo *info, PetscInt lo[3], PetscInt hi[3])
Index bounds of the interior cells this rank owns in the solver's cell-centred layout: the owned rang...
Definition setup.h:378
static PetscErrorCode ContravariantToCartesianInCell(Cmpnts ***lucont, Cmpnts ***lcsi, Cmpnts ***leta, Cmpnts ***lzet, PetscInt i, PetscInt j, PetscInt k, Cmpnts w, Cmpnts *ucat)
Cartesian velocity at a point of one cell from the cell's face fluxes.
Definition setup.h:503
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
static void GetPeriodicAxes(const SimCtx *simCtx, PetscBool periodic[3])
Which grid axes are periodic.
Definition setup.h:361
PetscMPIInt rank
Definition variables.h:919
PetscInt cell[3]
Definition variables.h:238
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscScalar x
Definition variables.h:145
Cmpnts loc
Definition variables.h:239
InterpolationMethod interpolationMethod
Definition variables.h:1055
PetscScalar z
Definition variables.h:145
InterpolationMethod
Selects the grid-to-particle interpolation method.
Definition variables.h:760
@ INTERP_CORNER_AVERAGED
Definition variables.h:762
@ INTERP_FACE_FLUX
Definition variables.h:763
Vec ParticleCount
Definition variables.h:1276
Vec lCoor
Definition variables.h:1243
Vec lUcont
Definition variables.h:1197
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
Cmpnts weights
Definition variables.h:241
@ TOP
Definition variables.h:197
@ FRONT
Definition variables.h:197
@ BOTTOM
Definition variables.h:197
@ BACK
Definition variables.h:197
@ LEFT
Definition variables.h:197
@ NUM_FACES
Definition variables.h:197
@ RIGHT
Definition variables.h:197
PetscInt64 PID
Definition variables.h:237
The six face planes of one hexahedron, indexed by Face, and its characteristic size.
Definition variables.h:229
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Defines a particle's core properties for Lagrangian tracking.
Definition variables.h:236
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscErrorCode CalculateDistancesToCellFacePlanes(const Cmpnts p, const CellFacePlanes *planes, PetscReal *d, const PetscReal threshold, Cmpnts *normals)
Signed distances from a point to precomputed cell face planes.