PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
logging.c
Go to the documentation of this file.
1// logging.c
2#include "logging.h"
3#include "statistics_window.h"
8
9/* Maximum temporary buffer size for converting numbers to strings */
10#define TMP_BUF_SIZE 128
11
12// --------------------- Static Variable for Log Level ---------------------
13
14/**
15 * @brief Static variable to cache the current logging level.
16 *
17 * Initialized to -1 to indicate that the log level has not been set yet.
18 */
20
22
23// --------------------- Static Variables for Allow-List -------------------
24
25/**
26 * @brief Global/static array of function names allowed to log.
27 */
28static char** gAllowedFunctions = NULL;
29
30/**
31 * @brief Number of entries in the gAllowedFunctions array.
32 */
33static int gNumAllowed = 0;
34
35enum {
55};
56
57/**
58 * @brief Internal reduction callback for packed search metrics.
59 * @details Local to this translation unit.
60 */
61static void SearchMetricsReduceOp(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype)
62{
64 PetscReal *in = (PetscReal *)invec;
65 PetscReal *inout = (PetscReal *)inoutvec;
66 (void)datatype;
67
68 for (int idx = 0; idx < *len; idx += SEARCH_METRIC_REDUCTION_LEN) {
84 inout[idx + SEARCH_METRIC_SUM_WRAPS] += in[idx + SEARCH_METRIC_SUM_WRAPS];
87 inout[idx + SEARCH_METRIC_MAX_PASS_DEPTH] = PetscMax(inout[idx + SEARCH_METRIC_MAX_PASS_DEPTH],
89 }
91}
92
93// --------------------- Function Implementations ---------------------
94
95/**
96 * @brief Implementation of \ref _ResolveLogLevel().
97 * @details Full API contract (arguments, ownership, side effects) is documented with
98 * the header declaration in `include/logging.h`.
99 * @see _ResolveLogLevel()
100 */
102 if (current_log_level == -1) { // Log level not set yet
103 const char *env = getenv("LOG_LEVEL");
104 if (!env) {
105 current_log_level = LOG_ERROR; // Default level
106 }
107 else if (strcmp(env, "DEBUG") == 0) {
109 }
110 else if (strcmp(env, "INFO") == 0) {
112 }
113 else if (strcmp(env, "WARNING") == 0) {
115 }
116 else if (strcmp(env, "VERBOSE") == 0) {
118 }
119 else if (strcmp(env, "TRACE") == 0) {
121 }
122 else {
123 current_log_level = LOG_ERROR; // Default if unrecognized
124 if (PetscGlobalRank == 0) {
125 fprintf(stderr, "[WARNING] Unrecognized LOG_LEVEL '%s'; using ERROR. Valid levels: ERROR, WARNING, INFO, DEBUG, TRACE, VERBOSE.\n", env);
126 }
127 }
128 }
129 return current_log_level;
130}
131
132/**
133 * @brief Implementation of \ref print_log_level().
134 * @details Full API contract (arguments, ownership, side effects) is documented with
135 * the header declaration in `include/logging.h`.
136 * @see print_log_level()
137 */
138PetscErrorCode print_log_level(void)
139{
140 PetscMPIInt rank;
141 PetscErrorCode ierr;
142 int level;
143 const char *level_name;
144
145 PetscFunctionBeginUser;
147 /* get MPI rank */
148 rank = PetscGlobalRank;
149
150 /* decide level name */
151 level = get_log_level();
152 level_name = (level == LOG_ERROR) ? "ERROR" :
153 (level == LOG_WARNING) ? "WARNING" :
154 (level == LOG_INFO) ? "INFO" :
155 (level == LOG_DEBUG) ? "DEBUG" :
156 (level == LOG_VERBOSE) ? "VERBOSE" :
157 (level == LOG_TRACE) ? "TRACE" :
158 "UNKNOWN";
159
160 /* print it out */
161 ierr = PetscPrintf(PETSC_COMM_SELF,
162 "Current log level: %s (%d) | rank: %d\n",
163 level_name, level, (int)rank);
164 CHKERRQ(ierr);
165
167 PetscFunctionReturn(PETSC_SUCCESS);
168}
169
170/**
171 * @brief Implementation of \ref set_allowed_functions().
172 * @details Full API contract (arguments, ownership, side effects) is documented with
173 * the header declaration in `include/logging.h`.
174 * @see set_allowed_functions()
175 */
176void set_allowed_functions(const char** functionList, int count)
177{
178 // 1. Free any existing entries
179 if (gAllowedFunctions) {
180 for (int i = 0; i < gNumAllowed; ++i) {
181 free(gAllowedFunctions[i]); // each was strdup'ed
182 }
183 free(gAllowedFunctions);
184 gAllowedFunctions = NULL;
185 gNumAllowed = 0;
186 }
187
188 // 2. Allocate new array
189 if (count > 0) {
190 gAllowedFunctions = (char**)malloc(sizeof(char*) * count);
191 }
192
193 // 3. Copy the new entries
194 for (int i = 0; i < count; ++i) {
195 // strdup is a POSIX function. If not available, implement your own string copy.
196 gAllowedFunctions[i] = strdup(functionList[i]);
197 }
198 gNumAllowed = count;
199}
200
201/**
202 * @brief Implementation of \ref is_function_allowed().
203 * @details Full API contract (arguments, ownership, side effects) is documented with
204 * the header declaration in `include/logging.h`.
205 * @see is_function_allowed()
206 */
207PetscBool is_function_allowed(const char* functionName)
208{
209 /* no list ⇒ allow all */
210 if (gNumAllowed == 0) {
211 return PETSC_TRUE;
212 }
213
214 /* otherwise only the listed functions are allowed */
215 for (int i = 0; i < gNumAllowed; ++i) {
216 if (strcmp(gAllowedFunctions[i], functionName) == 0) {
217 return PETSC_TRUE;
218 }
219 }
220 return PETSC_FALSE;
221}
222
223/**
224 * @brief Implementation of \ref LOG_CELL_VERTICES().
225 * @details Full API contract (arguments, ownership, side effects) is documented with
226 * the header declaration in `include/logging.h`.
227 * @see LOG_CELL_VERTICES()
228 */
229PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank)
230{
232
233 // Validate input pointers
234 if (cell == NULL) {
235 LOG_ALLOW(LOCAL,LOG_ERROR, "'cell' is NULL.\n");
236 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "LOG_CELL_VERTICES - Input parameter 'cell' is NULL.");
237 }
238
239 LOG_ALLOW(LOCAL,LOG_VERBOSE, "Rank %d, Cell Vertices:\n", rank);
240 for(int i = 0; i < 8; i++){
241 LOG_ALLOW(LOCAL,LOG_VERBOSE, " Vertex[%d]: (%.2f, %.2f, %.2f)\n",
242 i, cell->vertices[i].x, cell->vertices[i].y, cell->vertices[i].z);
243 }
244
246 return 0; // Indicate successful execution
247}
248
249
250/**
251 * @brief Implementation of \ref LOG_FACE_DISTANCES().
252 * @details Full API contract (arguments, ownership, side effects) is documented with
253 * the header declaration in `include/logging.h`.
254 * @see LOG_FACE_DISTANCES()
255 */
256PetscErrorCode LOG_FACE_DISTANCES(PetscReal* d)
257{
259
260 // Validate input array
261 if (d == NULL) {
262 LOG_ALLOW(LOCAL,LOG_ERROR, " 'd' is NULL.\n");
263 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, " Input array 'd' is NULL.");
264 }
265
266 PetscPrintf(PETSC_COMM_SELF, " Face Distances:\n");
267 PetscPrintf(PETSC_COMM_SELF, " LEFT(%d): %.15f\n", LEFT, d[LEFT]);
268 PetscPrintf(PETSC_COMM_SELF, " RIGHT(%d): %.15f\n", RIGHT, d[RIGHT]);
269 PetscPrintf(PETSC_COMM_SELF, " BOTTOM(%d): %.15f\n", BOTTOM, d[BOTTOM]);
270 PetscPrintf(PETSC_COMM_SELF, " TOP(%d): %.15f\n", TOP, d[TOP]);
271 PetscPrintf(PETSC_COMM_SELF, " FRONT(%d): %.15f\n", FRONT, d[FRONT]);
272 PetscPrintf(PETSC_COMM_SELF, " BACK(%d): %.15f\n", BACK, d[BACK]);
273
275 return 0; // Indicate successful execution
276}
277
278/*
279 * Helper function: Converts an integer (of type int) to a string.
280 */
281static void IntToStr(int value, char *buf, size_t bufsize)
282{
284 snprintf(buf, bufsize, "%d", value);
286}
287
288/*
289 * Helper function: Converts a 64‐bit integer to a string.
290 */
291static void Int64ToStr(PetscInt64 value, char *buf, size_t bufsize)
292{
294 snprintf(buf, bufsize, "%" PetscInt64_FMT, value);
296}
297
298/*
299 * Helper function: Converts three integers into a formatted string "(i, j, k)".
300 */
301static void CellToStr(const PetscInt *cell, char *buf, size_t bufsize)
302{
304 snprintf(buf, bufsize, "(%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ")", cell[0], cell[1], cell[2]);
306}
307
308/*
309 * Helper function: Converts three PetscReal values into a formatted string "(x, y, z)".
310 */
311static void TripleRealToStr(const PetscReal *arr, char *buf, size_t bufsize)
312{
314 snprintf(buf, bufsize, "(%.4f, %.4f, %.4f)", arr[0], arr[1], arr[2]);
316}
317
318/*
319 * Helper function: Computes the maximum string length for each column over the sampled rows.
320 *
321 * Only the `nRows` particles listed in `rows` are formatted, so the cost follows the table, not
322 * the swarm. The widths start at the header label lengths.
323 */
324static PetscErrorCode ComputeMaxColumnWidths(PetscInt nRows, const PetscInt *rows,
325 const PetscMPIInt *ranks,
326 const PetscInt64 *pids,
327 const PetscInt *cellIDs,
328 const PetscReal *positions,
329 const PetscReal *velocities,
330 const PetscReal *weights,
331 int widths[6])
332{
334 char tmp[TMP_BUF_SIZE];
335
336 widths[0] = (int)strlen("Rank"); /* Start with the header label lengths */
337 widths[1] = (int)strlen("PID");
338 widths[2] = (int)strlen("Cell (i,j,k)");
339 widths[3] = (int)strlen("Position (x,y,z)");
340 widths[4] = (int)strlen("Velocity (x,y,z)");
341 widths[5] = (int)strlen("Weights (a1,a2,a3)");
342
343 for (PetscInt r = 0; r < nRows; r++) {
344 const PetscInt i = rows[r];
345 IntToStr(ranks[i], tmp, TMP_BUF_SIZE); widths[0] = PetscMax(widths[0], (int)strlen(tmp));
346 Int64ToStr(pids[i], tmp, TMP_BUF_SIZE); widths[1] = PetscMax(widths[1], (int)strlen(tmp));
347 CellToStr(&cellIDs[3 * i], tmp, TMP_BUF_SIZE); widths[2] = PetscMax(widths[2], (int)strlen(tmp));
348 TripleRealToStr(&positions[3 * i], tmp, TMP_BUF_SIZE); widths[3] = PetscMax(widths[3], (int)strlen(tmp));
349 TripleRealToStr(&velocities[3 * i], tmp, TMP_BUF_SIZE); widths[4] = PetscMax(widths[4], (int)strlen(tmp));
350 TripleRealToStr(&weights[3 * i], tmp, TMP_BUF_SIZE); widths[5] = PetscMax(widths[5], (int)strlen(tmp));
351 }
353 return 0;
354}
355
356/*
357 * Helper function: Builds the printf format of one table row from the column widths.
358 *
359 * The rank is a PetscMPIInt (`d`), the PID a PetscInt64 (`PetscInt64_FMT`), and the cell,
360 * position, velocity and weight columns strings formatted beforehand, for example
361 * "| %-4d | %-8ld | %-12s | %-25s | %-25s | %-25s |\n".
362 *
363 * @param widths Column widths: rank, PID, cell, position, velocity, weights.
364 * @param fmtStr Buffer in which to build the format string.
365 * @param bufSize Size of fmtStr.
366 */
367static void BuildRowFormatString(const int widths[6], char *fmtStr, size_t bufSize)
368{
370 snprintf(fmtStr, bufSize,
371 "| %%-%dd | %%-%d" PetscInt64_FMT " | %%-%ds | %%-%ds | %%-%ds | %%-%ds |\n",
372 widths[0], widths[1], widths[2], widths[3], widths[4], widths[5]);
374}
375
376/*
377 * Helper function: Builds the table's header line from the column widths (as BuildRowFormatString()).
378 */
379static void BuildHeaderString(char *headerStr, size_t bufSize, const int widths[6])
380{
382 snprintf(headerStr, bufSize,
383 "| %-*s | %-*s | %-*s | %-*s | %-*s | %-*s |\n",
384 widths[0], "Rank",
385 widths[1], "PID",
386 widths[2], "Cell (i,j,k)",
387 widths[3], "Position (x,y,z)",
388 widths[4], "Velocity (x,y,z)",
389 widths[5], "Weights (a1,a2,a3)");
391}
392
393/**
394 * @brief Implementation of \ref LOG_PARTICLE_FIELDS().
395 * @details Full API contract (arguments, ownership, side effects) is documented with
396 * the header declaration in `include/logging.h`.
397 * @see LOG_PARTICLE_FIELDS()
398 */
399PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx* user, PetscInt printInterval)
400{
402 DM swarm = user->swarm;
403 PetscErrorCode ierr;
404 PetscInt localNumParticles;
405 PetscReal *positions = NULL;
406 PetscInt64 *particleIDs = NULL;
407 PetscMPIInt *particleRanks = NULL;
408 PetscInt *cellIDs = NULL;
409 PetscReal *weights = NULL;
410 PetscReal *velocities = NULL;
411 PetscInt rows[PICURV_SNAPSHOT_ROWS_PER_RANK];
412 PetscInt nRows = 0;
413 const PetscInt interval = (printInterval > 0) ? printInterval : 1;
414
415 ierr = DMSwarmGetLocalSize(swarm, &localNumParticles); CHKERRQ(ierr);
416 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions); CHKERRQ(ierr);
417 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
418 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void**)&particleRanks); CHKERRQ(ierr);
419 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
420 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
421 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&velocities); CHKERRQ(ierr);
422
423 /* Rows: the particles whose ID is a multiple of the interval, so a later snapshot shows the
424 * same particles wherever they moved, and at most PICURV_SNAPSHOT_ROWS_PER_RANK per rank. */
425 for (PetscInt i = 0; i < localNumParticles && nRows < PICURV_SNAPSHOT_ROWS_PER_RANK; i++) {
426 if (particleIDs[i] % interval == 0) rows[nRows++] = i;
427 }
428
429 /* Column widths agreed across ranks, so every rank's rows align under one header. */
430 int widths[6];
431 ierr = ComputeMaxColumnWidths(nRows, rows, particleRanks, particleIDs, cellIDs,
432 positions, velocities, weights, widths); CHKERRQ(ierr);
433 ierr = MPI_Allreduce(MPI_IN_PLACE, widths, 6, MPI_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
434
435 char headerFmt[256];
436 char rowFmt[256];
437 BuildHeaderString(headerFmt, sizeof(headerFmt), widths);
438 BuildRowFormatString(widths, rowFmt, sizeof(rowFmt));
439
440 /* The header once (rank 0 prints first), then every rank's rows in rank order. */
441 if (user->simCtx->rank == 0) {
442 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
443 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "%s", headerFmt); CHKERRQ(ierr);
444 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
445 }
446 char rowStr[256];
447 for (PetscInt r = 0; r < nRows; r++) {
448 const PetscInt i = rows[r];
449 char cellStr[TMP_BUF_SIZE], posStr[TMP_BUF_SIZE], velStr[TMP_BUF_SIZE], wtStr[TMP_BUF_SIZE];
450 CellToStr(&cellIDs[3*i], cellStr, TMP_BUF_SIZE);
451 TripleRealToStr(&positions[3*i], posStr, TMP_BUF_SIZE);
452 TripleRealToStr(&velocities[3*i], velStr, TMP_BUF_SIZE);
453 TripleRealToStr(&weights[3*i], wtStr, TMP_BUF_SIZE);
454 snprintf(rowStr, sizeof(rowStr), rowFmt, particleRanks[i], particleIDs[i], cellStr, posStr, velStr, wtStr);
455 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "%s", rowStr); CHKERRQ(ierr);
456 }
457 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
458
459 {
460 PetscInt64 counts[2] = {(PetscInt64)localNumParticles, (PetscInt64)nRows};
461 ierr = MPI_Allreduce(MPI_IN_PLACE, counts, 2, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
462 ierr = PetscPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
463 ierr = PetscPrintf(PETSC_COMM_WORLD, "%lld row(s) of %lld particle(s): IDs that are multiples of %" PetscInt_FMT ", at most %d per rank.\n\n",
464 (long long)counts[1], (long long)counts[0], interval, PICURV_SNAPSHOT_ROWS_PER_RANK); CHKERRQ(ierr);
465 }
466
467 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions); CHKERRQ(ierr);
468 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
469 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void**)&particleRanks); CHKERRQ(ierr);
470 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
471 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
472 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&velocities); CHKERRQ(ierr);
474 return 0;
475}
476
477/**
478 * @brief Implementation of \ref IsParticleConsoleSnapshotEnabled().
479 * @details Full API contract (arguments, ownership, side effects) is documented with
480 * the header declaration in `include/logging.h`.
481 * @see IsParticleConsoleSnapshotEnabled()
482 */
483
485{
487 const PetscBool enabled = (PetscBool)(simCtx && ParticlesEnabled(simCtx) &&
488 simCtx->particleConsoleOutputFreq > 0 &&
491 return enabled;
492}
493
494/**
495 * @brief Implementation of \ref ShouldEmitPeriodicParticleConsoleSnapshot().
496 * @details Full API contract (arguments, ownership, side effects) is documented with
497 * the header declaration in `include/logging.h`.
498 * @see ShouldEmitPeriodicParticleConsoleSnapshot()
499 */
500
501PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
502{
504 const PetscBool due = (PetscBool)(IsParticleConsoleSnapshotEnabled(simCtx) &&
505 completed_step > 0 &&
506 completed_step % simCtx->particleConsoleOutputFreq == 0);
508 return due;
509}
510
511/**
512 * @brief Implementation of \ref EmitParticleConsoleSnapshot().
513 * @details Full API contract (arguments, ownership, side effects) is documented with
514 * the header declaration in `include/logging.h`.
515 * @see EmitParticleConsoleSnapshot()
516 */
517
518PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
519{
520 PetscErrorCode ierr;
521
522 PetscFunctionBeginUser;
524 LOG(GLOBAL, LOG_INFO, "Particle states at step %" PetscInt_FMT ":\n", step);
525 ierr = LOG_PARTICLE_FIELDS(user, simCtx->LoggingFrequency); CHKERRQ(ierr);
527 PetscFunctionReturn(0);
528}
529
530
531/**
532 * @brief Remove leading and trailing whitespace from a mutable configuration string.
533 */
534static void trim(char *s)
535{
537 if (!s) { PROFILE_HELPER_END; return; }
538
539 /* ---- 1. strip leading blanks ----------------------------------- */
540 char *p = s;
541 while (*p && isspace((unsigned char)*p))
542 ++p;
543
544 if (p != s) /* move the trimmed text forward */
545 memmove(s, p, strlen(p) + 1); /* +1 to copy the final NUL */
546
547 /* ---- 2. strip trailing blanks ---------------------------------- */
548 size_t len = strlen(s);
549 while (len > 0 && isspace((unsigned char)s[len - 1]))
550 s[--len] = '\0';
552}
553
554/* ------------------------------------------------------------------------- */
555/**
556 * @brief Implementation of \ref LoadAllowedFunctionsFromFile().
557 * @details Full API contract (arguments, ownership, side effects) is documented with
558 * the header declaration in `include/logging.h`.
559 * @see LoadAllowedFunctionsFromFile()
560 */
561PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[],
562 char ***funcsOut,
563 PetscInt *nOut)
564{
565 FILE *fp = NULL;
566 char **funcs = NULL;
567 size_t cap = 16; /* initial capacity */
568 size_t n = 0; /* number of names */
569 char line[PETSC_MAX_PATH_LEN];
570 PetscErrorCode ierr;
571
572 PetscFunctionBegin;
574
575 /* ---------------------------------------------------------------------- */
576 /* 1. Open file */
577 fp = fopen(filename, "r");
578 if (!fp) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
579 "Cannot open %s", filename);
580
581 /* 2. Allocate initial pointer array */
582 ierr = PetscMalloc1(cap, &funcs); CHKERRQ(ierr);
583
584 /* 3. Read file line by line */
585 while (fgets(line, sizeof line, fp)) {
586 /* Strip everything after a comment character '#'. */
587 char *hash = strchr(line, '#');
588 if (hash) *hash = '\0';
589
590 trim(line); /* remove leading/trailing blanks */
591 if (!*line) continue; /* skip if empty */
592
593 /* Grow the array if necessary */
594 if (n == cap) {
595 cap *= 2;
596 ierr = PetscRealloc(cap * sizeof(*funcs), (void **)&funcs); CHKERRQ(ierr);
597 }
598
599 /* Deep‑copy the cleaned identifier */
600 ierr = PetscStrallocpy(line, &funcs[n++]); CHKERRQ(ierr);
601 }
602 fclose(fp);
603
604 /* 4. Return results to caller */
605 *funcsOut = funcs;
606 *nOut = (PetscInt)n;
607
609 PetscFunctionReturn(0);
610}
611
612/* ------------------------------------------------------------------------- */
613/**
614 * @brief Implementation of \ref FreeAllowedFunctions().
615 * @details Full API contract (arguments, ownership, side effects) is documented with
616 * the header declaration in `include/logging.h`.
617 * @see FreeAllowedFunctions()
618 */
619PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n)
620{
621 PetscErrorCode ierr;
622 PetscFunctionBegin;
624 if (funcs) {
625 for (PetscInt i = 0; i < n; ++i) {
626 ierr = PetscFree(funcs[i]); CHKERRQ(ierr);
627 }
628 ierr = PetscFree(funcs); CHKERRQ(ierr);
629 }
631 PetscFunctionReturn(0);
632}
633
634/**
635 * @brief Implementation of \ref BCFaceToString().
636 * @details Full API contract (arguments, ownership, side effects) is documented with
637 * the header declaration in `include/logging.h`.
638 * @see BCFaceToString()
639 */
640const char* BCFaceToString(BCFace face) {
642 const char *name;
643 switch (face) {
644 case BC_FACE_NEG_X: name = "-Xi (I-Min)"; break;
645 case BC_FACE_POS_X: name = "+Xi (I-Max)"; break;
646 case BC_FACE_NEG_Y: name = "-Eta (J-Min)"; break;
647 case BC_FACE_POS_Y: name = "+Eta (J-Max)"; break;
648 case BC_FACE_NEG_Z: name = "-Zeta (K-Min)"; break;
649 case BC_FACE_POS_Z: name = "+Zeta (K-Max)"; break;
650 default: name = "Unknown Face"; break;
651 }
653 return name;
654}
655
656/**
657 * @brief Implementation of \ref ParticleInitializationToString().
658 * @details Full API contract (arguments, ownership, side effects) is documented with
659 * the header declaration in `include/logging.h`.
660 * @see ParticleInitializationToString()
661 */
663{
665 const char *name;
666 switch(ParticleInitialization){
667 case PARTICLE_INIT_SURFACE_RANDOM: name = "Surface: Random"; break;
668 case PARTICLE_INIT_VOLUME: name = "Volume"; break;
669 case PARTICLE_INIT_POINT_SOURCE: name = "Point Source"; break;
670 default: name = "Unknown Particle Initialization"; break;
671 }
673 return name;
674}
675
676/**
677 * @brief Implementation of \ref LESModelToString().
678 * @details Full API contract (arguments, ownership, side effects) is documented with
679 * the header declaration in `include/logging.h`.
680 * @see LESModelToString()
681 */
682const char* LESModelToString(LESModelType LESFlag)
683{
685 const char *name;
686 switch(LESFlag){
687 case NO_LES_MODEL: name = "No LES"; break;
688 case CONSTANT_SMAGORINSKY: name = "Constant Smagorinsky"; break;
689 case DYNAMIC_SMAGORINSKY: name = "Dynamic Smagorinsky"; break;
690 case VREMAN: name = "Vreman"; break;
691 case WALE: name = "WALE"; break;
692 default: name = "Unknown LES Flag"; break;
693 }
695 return name;
696}
697
698/**
699 * @brief Implementation of \ref LESFilterWidthModelToString().
700 * @details Full API contract is documented with the header declaration in
701 * `include/logging.h`.
702 * @see LESFilterWidthModelToString()
703 */
705{
707 const char *name;
708 /* These spellings are the user-facing YAML values, so a banner line can be pasted
709 back into a case file without translation. */
710 switch(model){
711 case LES_FILTER_WIDTH_CUBE_ROOT_VOLUME: name = "cube_root_volume"; break;
712 case LES_FILTER_WIDTH_GEOMETRIC_MEAN: name = "geometric_mean"; break;
713 case LES_FILTER_WIDTH_MAX_EDGE: name = "max_edge"; break;
714 case LES_FILTER_WIDTH_SCOTTI: name = "scotti"; break;
715 default: name = "unknown"; break;
716 }
718 return name;
719}
720
721/**
722 * @brief Implementation of \ref LESTestFilterKernelToString().
723 * @details Full API contract is documented with the header declaration in
724 * `include/logging.h`.
725 * @see LESTestFilterKernelToString()
726 */
728{
730 const char *name;
731 switch(kernel){
732 case LES_TEST_FILTER_VOLUME_WEIGHTED_BOX: name = "volume_weighted_box"; break;
733 case LES_TEST_FILTER_SIMPSON_IK: name = "simpson_ik"; break;
734 default: name = "unknown"; break;
735 }
737 return name;
738}
739
740/**
741 * @brief Implementation of \ref LESAveragingModeToString().
742 * @details Full API contract is documented with the header declaration in
743 * `include/logging.h`.
744 * @see LESAveragingModeToString()
745 */
747{
749 const char *name;
750 switch(mode){
751 case LES_AVERAGING_LOCAL: name = "local"; break;
752 case LES_AVERAGING_HOMOGENEOUS: name = "homogeneous"; break;
753 case LES_AVERAGING_GLOBAL: name = "global"; break;
754 default: name = "unknown"; break;
755 }
757 return name;
758}
759
760/**
761 * @brief Implementation of \ref LESClipModeToString().
762 * @details Full API contract is documented with the header declaration in
763 * `include/logging.h`.
764 * @see LESClipModeToString()
765 */
767{
769 const char *name;
770 switch(mode){
771 case LES_CLIP_CLAMP: name = "clamp"; break;
772 case LES_CLIP_CLIP_NEGATIVE: name = "clip_negative"; break;
773 case LES_CLIP_NONE: name = "none"; break;
774 default: name = "unknown"; break;
775 }
777 return name;
778}
779
780/**
781 * @brief Implementation of \ref WallFunctionModelToString().
782 * @details Full API contract is documented with the header declaration in
783 * `include/logging.h`.
784 * @see WallFunctionModelToString()
785 */
787{
789 const char *name;
790 /* User-facing YAML spellings, so a banner line can be pasted back into a case. */
791 switch(model){
792 case WALL_FUNCTION_NONE: name = "none"; break;
793 case WALL_FUNCTION_LOG_LAW: name = "log_law"; break;
794 case WALL_FUNCTION_WERNER: name = "werner"; break;
795 case WALL_FUNCTION_CABOT: name = "cabot"; break;
796 default: name = "unknown"; break;
797 }
799 return name;
800}
801
802/**
803 * @brief Implementation of \ref MomentumSolverTypeToString().
804 * @details Full API contract (arguments, ownership, side effects) is documented with
805 * the header declaration in `include/logging.h`.
806 * @see MomentumSolverTypeToString()
807 */
809{
811 const char *name;
812 switch(SolverFlag){
813 case MOMENTUM_SOLVER_EXPLICIT_RK: name = "Explicit 4 stage Runge-Kutta "; break;
814 case MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK: name = "Dual Time Picard with 4-stage Jameson RK Smoothing"; break;
815 case MOMENTUM_SOLVER_NEWTON_KRYLOV: name = "Newton Krylov"; break;
816 default: name = "Unknown Momentum Solver Type"; break;
817 }
819 return name;
820}
821
822/**
823 * @brief Implementation of \ref BCTypeToString().
824 * @details Full API contract (arguments, ownership, side effects) is documented with
825 * the header declaration in `include/logging.h`.
826 * @see BCTypeToString()
827 */
828const char* BCTypeToString(BCType type) {
830 const char *name;
831 switch (type) {
832 case WALL: name = "WALL"; break;
833 case INLET: name = "INLET"; break;
834 case OUTLET: name = "OUTLET"; break;
835 case FARFIELD: name = "FARFIELD"; break;
836 case PERIODIC: name = "PERIODIC"; break;
837 case INTERFACE: name = "INTERFACE"; break;
838 default: name = "Unknown BC Type"; break;
839 }
841 return name;
842}
843
844/**
845 * @brief Implementation of \ref ParticleBoundaryPolicyToString().
846 * @details Full API contract (arguments, ownership, side effects) is documented with
847 * the header declaration in `include/logging.h`.
848 * @see ParticleBoundaryPolicyToString()
849 */
852 const char *name;
853 switch (policy) {
854 case PARTICLE_BOUNDARY_REMOVE: name = "remove"; break;
855 case PARTICLE_BOUNDARY_REFLECT: name = "reflect"; break;
856 case PARTICLE_BOUNDARY_WRAP: name = "wrap"; break;
857 default: name = "Unknown particle boundary policy"; break;
858 }
860 return name;
861}
862
863/**
864 * @brief Implementation of \ref InterpolationMethodToString().
865 * @details Full API contract (arguments, ownership, side effects) is documented with
866 * the header declaration in `include/logging.h`.
867 * @see InterpolationMethodToString()
868 */
871 const char *name;
872 switch (method) {
873 case INTERP_TRILINEAR: name = "Trilinear (direct cell-center)"; break;
874 case INTERP_CORNER_AVERAGED: name = "CornerAveraged (legacy)"; break;
875 case INTERP_FACE_FLUX: name = "FaceFlux (divergence-free velocity from face fluxes)"; break;
876 default: name = "Unknown interpolation method"; break;
877 }
879 return name;
880}
881
882/**
883 * @brief Implementation of \ref BCHandlerTypeToString().
884 * @details Full API contract (arguments, ownership, side effects) is documented with
885 * the header declaration in `include/logging.h`.
886 * @see BCHandlerTypeToString()
887 */
888const char* BCHandlerTypeToString(BCHandlerType handler_type) {
890 const char *name;
891 switch (handler_type) {
892 // Wall Handlers
893 case BC_HANDLER_WALL_NOSLIP: name = "noslip"; break;
894 case BC_HANDLER_WALL_MOVING: name = "moving"; break;
895 case BC_HANDLER_WALL_FREE_SLIP: name = "free_slip"; break;
896
897 // Inlet Handlers
898 case BC_HANDLER_INLET_PRESCRIBED_VELOCITY: name = "prescribed_velocity"; break;
899
900 // Outlet Handlers
901 case BC_HANDLER_OUTLET_CONSERVATION: name = "conservation"; break;
902 case BC_HANDLER_OUTLET_PRESSURE: name = "pressure"; break;
903
904 // Other Physical Handlers
905 case BC_HANDLER_FARFIELD_NONREFLECTING: name = "nonreflecting"; break;
906
907 // Multi-Block / Interface Handlers
908 case BC_HANDLER_PERIODIC_GEOMETRIC: name = "geometric"; break;
909 case BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX: name = "constant flux"; break;
910 case BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX: name = "initial flux"; break;
911 case BC_HANDLER_INTERFACE_OVERSET: name = "overset"; break;
912
913 // Default case
915 default: name = "UNKNOWN_HANDLER"; break;
916 }
918 return name;
919}
920
921/**
922 * @brief Implementation of \ref DualMonitorDestroy().
923 * @details Full API contract (arguments, ownership, side effects) is documented with
924 * the header declaration in `include/logging.h`.
925 * @see DualMonitorDestroy()
926 */
927PetscErrorCode DualMonitorDestroy(void **ctx)
928{
929 DualMonitorCtx *monctx = (DualMonitorCtx*)*ctx;
930 PetscErrorCode ierr;
931 PetscMPIInt rank;
932
933 PetscFunctionBeginUser;
935 rank = PetscGlobalRank;
936 if(!rank && monctx->file_handle){
937 fclose(monctx->file_handle);
938 }
939 ierr = VecDestroy(&monctx->residual_work[0]); CHKERRQ(ierr);
940 ierr = VecDestroy(&monctx->residual_work[1]); CHKERRQ(ierr);
941
942 ierr = PetscFree(monctx); CHKERRQ(ierr);
943 *ctx = NULL;
945 PetscFunctionReturn(0);
946}
947
948/**
949 * @brief Implementation of \ref DualKSPMonitor().
950 * @details Full API contract (arguments, ownership, side effects) is documented with
951 * the header declaration in `include/logging.h`.
952 * @see DualKSPMonitor()
953 */
954
955PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx)
956{
957 DualMonitorCtx *monctx = (DualMonitorCtx*)ctx;
958 PetscErrorCode ierr;
959 PetscReal trnorm = 0.0, relnorm;
960 Vec r;
961 char norm_buf[256];
962 PetscMPIInt rank;
963
964 PetscFunctionBeginUser;
966 rank = PetscGlobalRank;
967
968 // 1. The true residual, when asked for: it costs a residual build and a norm per iteration.
969 // Both workspaces are fully overwritten on each call, so they are kept rather than
970 // created and destroyed every iteration.
971 if (monctx->true_residual) {
972 Vec b;
973 ierr = KSPGetRhs(ksp, &b); CHKERRQ(ierr);
974 if (!monctx->residual_work[0]) {
975 Vec x;
976 ierr = KSPGetSolution(ksp, &x); CHKERRQ(ierr);
977 ierr = VecDuplicate(x, &monctx->residual_work[0]); CHKERRQ(ierr);
978 ierr = VecDuplicate(b, &monctx->residual_work[1]); CHKERRQ(ierr);
979 }
980 ierr = KSPBuildResidual(ksp, monctx->residual_work[0], monctx->residual_work[1], &r); CHKERRQ(ierr);
981 ierr = VecNorm(r, NORM_2, &trnorm); CHKERRQ(ierr);
982
983 // 2. On the first iteration, compute and store the norm of the RHS vector `b`.
984 if (it == 0) {
985 ierr = VecNorm(b, NORM_2, &monctx->bnorm); CHKERRQ(ierr);
986 }
987 }
988
989 if(!rank){
990 const PetscBool have_rel = (PetscBool)(monctx->true_residual && monctx->bnorm > 1.e-15);
991 relnorm = have_rel ? trnorm / monctx->bnorm : 0.0;
992
993 // 3. The history file: one CSV row per iteration.
994 if (monctx->file_handle) {
995 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%d,%d,%d,%.5e,", (int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm); CHKERRQ(ierr);
996 if (monctx->true_residual) { ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%.5e", (double)trnorm); CHKERRQ(ierr); }
997 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, ","); CHKERRQ(ierr);
998 if (have_rel) { ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%.5e", (double)relnorm); CHKERRQ(ierr); }
999 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "\n"); CHKERRQ(ierr);
1000 }
1001 // 4. The console, when asked for: the same values, readable.
1002 if (monctx->log_to_console) {
1003 if (have_rel) sprintf(norm_buf, "ts: %-5d | block: %-2d | iter: %-3d | Unprecond Norm: %12.5e | True Norm: %12.5e | Rel Norm: %12.5e",(int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm, (double)trnorm, (double)relnorm);
1004 else sprintf(norm_buf, "ts: %-5d | block: %-2d | iter: %-3d | Unprecond Norm: %12.5e | True Norm: %12.5e",(int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm, (double)trnorm);
1005 ierr = PetscFPrintf(PETSC_COMM_SELF, stdout, "%s\n", norm_buf); CHKERRQ(ierr);
1006 }
1007 } //rank
1008
1010 PetscFunctionReturn(0);
1011}
1012
1013#define SOLUTION_CONVERGENCE_FLUID_THRESHOLD 0.1
1014#define SOLUTION_CONVERGENCE_REL_EPS 1.0e-30
1015
1027
1032
1033/**
1034 * @brief Forms a guarded relative metric for solution-convergence logging.
1035 *
1036 * This helper centralizes the divide-by-nearly-zero protection used by the
1037 * solution-convergence logger when turning an absolute drift into a relative
1038 * one. The denominator is clamped away from zero so warmup rows, quiescent
1039 * fields, and statistically small observables do not generate infinities.
1040 *
1041 * @param[in] numerator Absolute quantity or drift magnitude.
1042 * @param[in] denominator Reference magnitude used for normalization.
1043 * @return Guarded relative value `numerator / max(|denominator|, eps)`.
1044 */
1045static PetscReal SolutionConvergenceSafeRelative(PetscReal numerator, PetscReal denominator)
1046{
1048 const PetscReal relative = numerator / PetscMax(PetscAbsReal(denominator), SOLUTION_CONVERGENCE_REL_EPS);
1050 return relative;
1051}
1052
1053/**
1054 * @brief Computes instantaneous global flow observables for statistical mode.
1055 *
1056 * The statistical solution-convergence path does not compare full Eulerian
1057 * fields. Instead, it tracks a compact history of global observables derived
1058 * from the completed Eulerian state. This helper computes the current
1059 * volume-weighted fluid-domain mean speed and mean kinetic energy from `Ucat`.
1060 *
1061 * Only physical fluid cells contribute:
1062 * - solid/immersed cells are excluded using `Nvert`
1063 * - cells with near-zero metric Jacobian are ignored to avoid invalid volume
1064 * weights
1065 *
1066 * Each MPI rank accumulates local partial sums and the routine reduces them to
1067 * one global pair of observables.
1068 *
1069 * @param[in] simCtx Simulation context owning the finest-level flow
1070 * fields.
1071 * @param[out] mean_speed_out Volume-weighted domain mean of `|u|`.
1072 * @param[out] mean_ke_out Volume-weighted domain mean of `0.5 |u|^2`.
1073 * @return PetscErrorCode 0 on success.
1074 */
1075static PetscErrorCode ComputeCurrentFlowObservables(SimCtx *simCtx, PetscReal *mean_speed_out, PetscReal *mean_ke_out)
1076{
1077 PetscReal local[3] = {0.0, 0.0, 0.0};
1078 PetscReal global[3] = {0.0, 0.0, 0.0};
1079 UserCtx *user = NULL;
1080
1081 PetscFunctionBeginUser;
1083 if (!simCtx || !mean_speed_out || !mean_ke_out) {
1084 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "ComputeCurrentFlowObservables received a NULL argument.");
1085 }
1086
1087 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1088
1089 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
1090 const DMDALocalInfo info = user[bi].info;
1091 /* Physical cells only. Index 0 and mx-1 are ghost layers on every axis - a
1092 boundary-condition image on a wall, a copy of the opposite cell on a
1093 periodic axis - and counting them biased every mean and norm here. */
1094 const PetscInt i_start = PetscMax(info.xs, 1), i_end = PetscMin(info.xs + info.xm, info.mx - 1);
1095 const PetscInt j_start = PetscMax(info.ys, 1), j_end = PetscMin(info.ys + info.ym, info.my - 1);
1096 const PetscInt k_start = PetscMax(info.zs, 1), k_end = PetscMin(info.zs + info.zm, info.mz - 1);
1097 Cmpnts ***ucat = NULL;
1098 PetscReal ***aj = NULL;
1099 PetscReal ***nvert = NULL;
1100
1101 PetscCall(DMDAVecGetArrayRead(user[bi].fda, user[bi].Ucat, &ucat));
1102 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Aj, &aj));
1103 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1104
1105 for (PetscInt k = k_start; k < k_end; ++k) {
1106 for (PetscInt j = j_start; j < j_end; ++j) {
1107 for (PetscInt i = i_start; i < i_end; ++i) {
1108 PetscReal jac = aj[k][j][i];
1109 PetscReal cell_volume = 0.0;
1110 PetscReal speed = 0.0;
1111 PetscReal ke = 0.0;
1112
1113 if (nvert[k][j][i] > SOLUTION_CONVERGENCE_FLUID_THRESHOLD) continue;
1114 if (PetscAbsReal(jac) <= 1.0e-14) continue;
1115
1116 cell_volume = 1.0 / jac;
1117 speed = PetscSqrtReal(ucat[k][j][i].x * ucat[k][j][i].x +
1118 ucat[k][j][i].y * ucat[k][j][i].y +
1119 ucat[k][j][i].z * ucat[k][j][i].z);
1120 ke = 0.5 * speed * speed;
1121
1122 local[0] += cell_volume;
1123 local[1] += speed * cell_volume;
1124 local[2] += ke * cell_volume;
1125 }
1126 }
1127 }
1128
1129 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1130 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Aj, &aj));
1131 PetscCall(DMDAVecRestoreArrayRead(user[bi].fda, user[bi].Ucat, &ucat));
1132 }
1133
1134 PetscCallMPI(MPI_Allreduce(local, global, 3, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1135
1136 if (global[0] <= 0.0) {
1137 *mean_speed_out = 0.0;
1138 *mean_ke_out = 0.0;
1139 } else {
1140 *mean_speed_out = global[1] / global[0];
1141 *mean_ke_out = global[2] / global[0];
1142 }
1143
1145 PetscFunctionReturn(0);
1146}
1147
1148/**
1149 * @brief Computes deterministic solution-drift metrics for the current step.
1150 *
1151 * This helper powers both `steady_deterministic` and
1152 * `periodic_deterministic` solution-convergence modes. It compares the
1153 * completed Eulerian state against either:
1154 * - the previous physical timestep (`Ucat_o`, `P_o`) for steady/transient use
1155 * - the stored phase-aligned snapshot ring for periodic use
1156 *
1157 * The routine performs two passes over the fluid cells:
1158 * 1. velocity/observable pass
1159 * - computes current and reference mean speed / mean KE
1160 * - computes absolute/relative velocity L2 drift
1161 * - accumulates pressure means needed for gauge removal
1162 * 2. pressure-only pass
1163 * - subtracts the volume-weighted mean pressure from both states
1164 * - computes gauge-invariant pressure L2 drift
1165 *
1166 * Warmup behavior is handled here. If no valid reference exists yet, all drift
1167 * outputs are left at zero and `has_reference_out` is set to `PETSC_FALSE`,
1168 * while current observables are still reported.
1169 *
1170 * @param[in] simCtx Simulation context owning the current state.
1171 * @param[in] periodic_mode `PETSC_TRUE` when comparing against
1172 * phase-aligned periodic storage.
1173 * @param[in] phase_step Active phase slot for periodic mode, or `-1`
1174 * when unused.
1175 * @param[in] samples_before Number of solution-convergence samples
1176 * already recorded before this timestep.
1177 * @param[out] has_reference_out Whether a valid comparison state existed.
1178 * @param[out] u_abs_l2_out Absolute L2 drift of Cartesian velocity.
1179 * @param[out] u_rel_l2_out Relative L2 drift of Cartesian velocity.
1180 * @param[out] p_abs_l2_out Gauge-invariant absolute L2 pressure drift.
1181 * @param[out] p_rel_l2_out Gauge-invariant relative L2 pressure drift.
1182 * @param[out] mean_speed_out Current volume-weighted mean speed.
1183 * @param[out] mean_speed_ref_out Reference volume-weighted mean speed.
1184 * @param[out] mean_speed_abs_out Absolute drift of mean speed.
1185 * @param[out] mean_speed_rel_out Relative drift of mean speed.
1186 * @param[out] mean_ke_out Current volume-weighted mean kinetic energy.
1187 * @param[out] mean_ke_ref_out Reference volume-weighted mean kinetic
1188 * energy.
1189 * @param[out] mean_ke_abs_out Absolute drift of mean kinetic energy.
1190 * @param[out] mean_ke_rel_out Relative drift of mean kinetic energy.
1191 * @return PetscErrorCode 0 on success.
1192 */
1193static PetscErrorCode ComputeDeterministicSolutionMetrics(SimCtx *simCtx,
1194 PetscBool periodic_mode,
1195 PetscInt phase_step,
1196 PetscInt samples_before,
1197 PetscBool *has_reference_out,
1198 PetscReal *u_abs_l2_out,
1199 PetscReal *u_rel_l2_out,
1200 PetscReal *p_abs_l2_out,
1201 PetscReal *p_rel_l2_out,
1202 PetscReal *mean_speed_out,
1203 PetscReal *mean_speed_ref_out,
1204 PetscReal *mean_speed_abs_out,
1205 PetscReal *mean_speed_rel_out,
1206 PetscReal *mean_ke_out,
1207 PetscReal *mean_ke_ref_out,
1208 PetscReal *mean_ke_abs_out,
1209 PetscReal *mean_ke_rel_out)
1210{
1211 SolutionConvergenceDeterministicPass1 local_pass1 = {0};
1212 SolutionConvergenceDeterministicPass1 global_pass1 = {0};
1213 SolutionConvergenceDeterministicPass2 local_pass2 = {0};
1214 SolutionConvergenceDeterministicPass2 global_pass2 = {0};
1215 PetscReal current_pressure_mean = 0.0;
1216 PetscReal reference_pressure_mean = 0.0;
1217 UserCtx *user = NULL;
1218
1219 PetscFunctionBeginUser;
1221 if (!simCtx || !has_reference_out || !u_abs_l2_out || !u_rel_l2_out || !p_abs_l2_out || !p_rel_l2_out ||
1222 !mean_speed_out || !mean_speed_ref_out || !mean_speed_abs_out || !mean_speed_rel_out ||
1223 !mean_ke_out || !mean_ke_ref_out || !mean_ke_abs_out || !mean_ke_rel_out) {
1224 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "ComputeDeterministicSolutionMetrics received a NULL output pointer.");
1225 }
1226
1227 *has_reference_out = periodic_mode
1228 ? (PetscBool)(simCtx->solutionConvergencePeriodSteps > 0 &&
1229 phase_step >= 0 &&
1230 phase_step < simCtx->solutionConvergencePeriodSteps &&
1231 samples_before >= simCtx->solutionConvergencePeriodSteps)
1232 : (PetscBool)(samples_before > 0);
1233
1234 *u_abs_l2_out = 0.0;
1235 *u_rel_l2_out = 0.0;
1236 *p_abs_l2_out = 0.0;
1237 *p_rel_l2_out = 0.0;
1238 *mean_speed_out = 0.0;
1239 *mean_speed_ref_out = 0.0;
1240 *mean_speed_abs_out = 0.0;
1241 *mean_speed_rel_out = 0.0;
1242 *mean_ke_out = 0.0;
1243 *mean_ke_ref_out = 0.0;
1244 *mean_ke_abs_out = 0.0;
1245 *mean_ke_rel_out = 0.0;
1246
1247 user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1248
1249 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
1250 const DMDALocalInfo info = user[bi].info;
1251 /* Physical cells only. Index 0 and mx-1 are ghost layers on every axis - a
1252 boundary-condition image on a wall, a copy of the opposite cell on a
1253 periodic axis - and counting them biased every mean and norm here. */
1254 const PetscInt i_start = PetscMax(info.xs, 1), i_end = PetscMin(info.xs + info.xm, info.mx - 1);
1255 const PetscInt j_start = PetscMax(info.ys, 1), j_end = PetscMin(info.ys + info.ym, info.my - 1);
1256 const PetscInt k_start = PetscMax(info.zs, 1), k_end = PetscMin(info.zs + info.zm, info.mz - 1);
1257 Cmpnts ***ucat = NULL;
1258 Cmpnts ***ucat_ref = NULL;
1259 PetscReal ***pressure = NULL;
1260 PetscReal ***pressure_ref = NULL;
1261 PetscReal ***aj = NULL;
1262 PetscReal ***nvert = NULL;
1263 Vec ucat_reference_vec = NULL;
1264 Vec pressure_reference_vec = NULL;
1265
1266 if (*has_reference_out) {
1267 if (periodic_mode) {
1268 ucat_reference_vec = user[bi].solutionConvergencePeriodicUcatRef[phase_step];
1269 pressure_reference_vec = user[bi].solutionConvergencePeriodicPRef[phase_step];
1270 } else {
1271 ucat_reference_vec = user[bi].Ucat_o;
1272 pressure_reference_vec = user[bi].P_o;
1273 }
1274 }
1275
1276 PetscCall(DMDAVecGetArrayRead(user[bi].fda, user[bi].Ucat, &ucat));
1277 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].P, &pressure));
1278 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Aj, &aj));
1279 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1280 if (*has_reference_out) {
1281 PetscCall(DMDAVecGetArrayRead(user[bi].fda, ucat_reference_vec, &ucat_ref));
1282 PetscCall(DMDAVecGetArrayRead(user[bi].da, pressure_reference_vec, &pressure_ref));
1283 }
1284
1285 for (PetscInt k = k_start; k < k_end; ++k) {
1286 for (PetscInt j = j_start; j < j_end; ++j) {
1287 for (PetscInt i = i_start; i < i_end; ++i) {
1288 PetscReal jac = aj[k][j][i];
1289 PetscReal cell_volume = 0.0;
1290 PetscReal speed = 0.0;
1291 PetscReal ke = 0.0;
1292
1293 if (nvert[k][j][i] > SOLUTION_CONVERGENCE_FLUID_THRESHOLD) continue;
1294 if (PetscAbsReal(jac) <= 1.0e-14) continue;
1295
1296 cell_volume = 1.0 / jac;
1297 speed = PetscSqrtReal(ucat[k][j][i].x * ucat[k][j][i].x +
1298 ucat[k][j][i].y * ucat[k][j][i].y +
1299 ucat[k][j][i].z * ucat[k][j][i].z);
1300 ke = 0.5 * speed * speed;
1301
1302 local_pass1.fluid_volume += cell_volume;
1303 local_pass1.current_speed_sum += speed * cell_volume;
1304 local_pass1.current_ke_sum += ke * cell_volume;
1305 local_pass1.current_u_norm_sq += (ucat[k][j][i].x * ucat[k][j][i].x +
1306 ucat[k][j][i].y * ucat[k][j][i].y +
1307 ucat[k][j][i].z * ucat[k][j][i].z) * cell_volume;
1308
1309 if (*has_reference_out) {
1310 PetscReal ref_speed = PetscSqrtReal(ucat_ref[k][j][i].x * ucat_ref[k][j][i].x +
1311 ucat_ref[k][j][i].y * ucat_ref[k][j][i].y +
1312 ucat_ref[k][j][i].z * ucat_ref[k][j][i].z);
1313 PetscReal ref_ke = 0.5 * ref_speed * ref_speed;
1314 PetscReal dux = ucat[k][j][i].x - ucat_ref[k][j][i].x;
1315 PetscReal duy = ucat[k][j][i].y - ucat_ref[k][j][i].y;
1316 PetscReal duz = ucat[k][j][i].z - ucat_ref[k][j][i].z;
1317
1318 local_pass1.reference_speed_sum += ref_speed * cell_volume;
1319 local_pass1.reference_ke_sum += ref_ke * cell_volume;
1320 local_pass1.delta_u_norm_sq += (dux * dux + duy * duy + duz * duz) * cell_volume;
1321 local_pass1.current_pressure_sum += pressure[k][j][i] * cell_volume;
1322 local_pass1.reference_pressure_sum += pressure_ref[k][j][i] * cell_volume;
1323 }
1324 }
1325 }
1326 }
1327
1328 if (*has_reference_out) {
1329 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, pressure_reference_vec, &pressure_ref));
1330 PetscCall(DMDAVecRestoreArrayRead(user[bi].fda, ucat_reference_vec, &ucat_ref));
1331 }
1332 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1333 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Aj, &aj));
1334 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].P, &pressure));
1335 PetscCall(DMDAVecRestoreArrayRead(user[bi].fda, user[bi].Ucat, &ucat));
1336 }
1337
1338 PetscCallMPI(MPI_Allreduce(&local_pass1, &global_pass1,
1339 sizeof(SolutionConvergenceDeterministicPass1) / sizeof(PetscReal),
1340 MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1341
1342 if (global_pass1.fluid_volume <= 0.0) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1343
1344 *mean_speed_out = global_pass1.current_speed_sum / global_pass1.fluid_volume;
1345 *mean_ke_out = global_pass1.current_ke_sum / global_pass1.fluid_volume;
1346
1347 if (!*has_reference_out) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1348
1349 *mean_speed_ref_out = global_pass1.reference_speed_sum / global_pass1.fluid_volume;
1350 *mean_speed_abs_out = PetscAbsReal(*mean_speed_out - *mean_speed_ref_out);
1351 *mean_speed_rel_out = SolutionConvergenceSafeRelative(*mean_speed_abs_out, *mean_speed_out);
1352 *mean_ke_ref_out = global_pass1.reference_ke_sum / global_pass1.fluid_volume;
1353 *mean_ke_abs_out = PetscAbsReal(*mean_ke_out - *mean_ke_ref_out);
1354 *mean_ke_rel_out = SolutionConvergenceSafeRelative(*mean_ke_abs_out, *mean_ke_out);
1355
1356 current_pressure_mean = global_pass1.current_pressure_sum / global_pass1.fluid_volume;
1357 reference_pressure_mean = global_pass1.reference_pressure_sum / global_pass1.fluid_volume;
1358
1359 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
1360 const DMDALocalInfo info = user[bi].info;
1361 /* Physical cells only. Index 0 and mx-1 are ghost layers on every axis - a
1362 boundary-condition image on a wall, a copy of the opposite cell on a
1363 periodic axis - and counting them biased every mean and norm here. */
1364 const PetscInt i_start = PetscMax(info.xs, 1), i_end = PetscMin(info.xs + info.xm, info.mx - 1);
1365 const PetscInt j_start = PetscMax(info.ys, 1), j_end = PetscMin(info.ys + info.ym, info.my - 1);
1366 const PetscInt k_start = PetscMax(info.zs, 1), k_end = PetscMin(info.zs + info.zm, info.mz - 1);
1367 PetscReal ***pressure = NULL;
1368 PetscReal ***pressure_ref = NULL;
1369 PetscReal ***aj = NULL;
1370 PetscReal ***nvert = NULL;
1371 Vec pressure_reference_vec = periodic_mode ? user[bi].solutionConvergencePeriodicPRef[phase_step] : user[bi].P_o;
1372
1373 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].P, &pressure));
1374 PetscCall(DMDAVecGetArrayRead(user[bi].da, pressure_reference_vec, &pressure_ref));
1375 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Aj, &aj));
1376 PetscCall(DMDAVecGetArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1377
1378 for (PetscInt k = k_start; k < k_end; ++k) {
1379 for (PetscInt j = j_start; j < j_end; ++j) {
1380 for (PetscInt i = i_start; i < i_end; ++i) {
1381 PetscReal jac = aj[k][j][i];
1382 PetscReal cell_volume = 0.0;
1383 PetscReal current_pressure = 0.0;
1384 PetscReal reference_pressure = 0.0;
1385 PetscReal delta_pressure = 0.0;
1386
1387 if (nvert[k][j][i] > SOLUTION_CONVERGENCE_FLUID_THRESHOLD) continue;
1388 if (PetscAbsReal(jac) <= 1.0e-14) continue;
1389
1390 cell_volume = 1.0 / jac;
1391 current_pressure = pressure[k][j][i] - current_pressure_mean;
1392 reference_pressure = pressure_ref[k][j][i] - reference_pressure_mean;
1393 delta_pressure = current_pressure - reference_pressure;
1394
1395 local_pass2.current_pressure_norm_sq += current_pressure * current_pressure * cell_volume;
1396 local_pass2.delta_pressure_norm_sq += delta_pressure * delta_pressure * cell_volume;
1397 }
1398 }
1399 }
1400
1401 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Nvert, &nvert));
1402 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].Aj, &aj));
1403 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, pressure_reference_vec, &pressure_ref));
1404 PetscCall(DMDAVecRestoreArrayRead(user[bi].da, user[bi].P, &pressure));
1405 }
1406
1407 PetscCallMPI(MPI_Allreduce(&local_pass2, &global_pass2,
1408 sizeof(SolutionConvergenceDeterministicPass2) / sizeof(PetscReal),
1409 MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD));
1410
1411 *u_abs_l2_out = PetscSqrtReal(global_pass1.delta_u_norm_sq);
1412 *u_rel_l2_out = SolutionConvergenceSafeRelative(*u_abs_l2_out, PetscSqrtReal(global_pass1.current_u_norm_sq));
1413 *p_abs_l2_out = PetscSqrtReal(global_pass2.delta_pressure_norm_sq);
1414 *p_rel_l2_out = SolutionConvergenceSafeRelative(*p_abs_l2_out, PetscSqrtReal(global_pass2.current_pressure_norm_sq));
1415
1417 PetscFunctionReturn(0);
1418}
1419
1420/**
1421 * @brief Reads one sample from the statistical ring buffer by age.
1422 *
1423 * The statistical logger stores scalar observables in a compact circular
1424 * buffer. This helper interprets the buffer using `samples_available` as the
1425 * logical end of the history and returns the entry `offset_from_latest` steps
1426 * back from the newest stored sample.
1427 *
1428 * Out-of-range requests return zero so warmup handling can remain simple and
1429 * deterministic.
1430 *
1431 * @param[in] history Ring-buffer storage array.
1432 * @param[in] capacity Total ring-buffer capacity.
1433 * @param[in] samples_available Number of logical samples available to read.
1434 * @param[in] offset_from_latest `0` means newest sample, `1` previous sample,
1435 * and so on.
1436 * @return Requested historical sample, or `0.0` if unavailable.
1437 */
1438static PetscReal SolutionConvergenceHistoryGet(const PetscReal *history,
1439 PetscInt capacity,
1440 PetscInt samples_available,
1441 PetscInt offset_from_latest)
1442{
1444 PetscInt count = 0;
1445 PetscInt index = 0;
1446
1447 if (!history || capacity <= 0 || samples_available <= 0 || offset_from_latest < 0) {
1449 return 0.0;
1450 }
1451
1452 count = PetscMin(samples_available, capacity);
1453 if (offset_from_latest >= count) { PROFILE_HELPER_END; return 0.0; }
1454
1455 index = (samples_available - 1 - offset_from_latest) % capacity;
1456 if (index < 0) index += capacity;
1458 return history[index];
1459}
1460
1461/**
1462 * @brief Appends one timestep's scalar observables to the statistical history.
1463 *
1464 * Statistical solution-convergence compares adjacent windows of scalar
1465 * observables rather than full fields. This helper writes the current
1466 * `mean_speed` and `mean_ke` into the rolling history arrays using the current
1467 * sample count to choose the circular-buffer slot.
1468 *
1469 * @param[in,out] simCtx Simulation context owning the history arrays.
1470 * @param[in] samples_before Number of samples present before appending the
1471 * current timestep.
1472 * @param[in] mean_speed Current timestep mean-speed observable.
1473 * @param[in] mean_ke Current timestep mean-KE observable.
1474 * @return PetscErrorCode 0 on success.
1475 */
1476static PetscErrorCode AppendStatisticalObservableSample(SimCtx *simCtx,
1477 PetscInt samples_before,
1478 PetscReal mean_speed,
1479 PetscReal mean_ke)
1480{
1481 PetscInt history_capacity = 0;
1482 PetscInt slot = 0;
1483
1484 PetscFunctionBeginUser;
1486 if (!simCtx || !simCtx->solutionConvergenceMeanSpeedHistory || !simCtx->solutionConvergenceMeanKEHistory) {
1487 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Statistical solution-convergence history is not allocated.");
1488 }
1489
1490 history_capacity = 2 * simCtx->solutionConvergenceWindowSteps;
1491 if (history_capacity <= 0) {
1492 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Statistical solution-convergence history capacity must be positive.");
1493 }
1494
1495 slot = samples_before % history_capacity;
1496 simCtx->solutionConvergenceMeanSpeedHistory[slot] = mean_speed;
1497 simCtx->solutionConvergenceMeanKEHistory[slot] = mean_ke;
1498
1500 PetscFunctionReturn(0);
1501}
1502
1503/**
1504 * @brief Computes adjacent-window drift metrics for statistical steady mode.
1505 *
1506 * Once enough samples have been accumulated, this helper forms:
1507 * - the current window over the most recent `window_steps` samples
1508 * - the previous adjacent window over the preceding `window_steps` samples
1509 *
1510 * From those windows it computes means, RMS values, and absolute/relative
1511 * drift for both tracked observables (`mean_speed` and `mean_ke`). When the
1512 * history is still warming up:
1513 * - fewer than `window_steps` samples: no window metrics are available
1514 * - between `window_steps` and `2*window_steps - 1` samples: current-window
1515 * metrics are available, but no reference window exists yet
1516 *
1517 * @param[in] simCtx Simulation context owning the
1518 * statistical history.
1519 * @param[in] samples_available Number of samples available after
1520 * appending the current timestep.
1521 * @param[out] has_reference_out Whether both adjacent windows
1522 * exist and drift metrics are
1523 * meaningful.
1524 * @param[out] mean_speed_window_out Mean speed over the current
1525 * window.
1526 * @param[out] mean_speed_window_prev_out Mean speed over the previous
1527 * window.
1528 * @param[out] mean_speed_window_abs_out Absolute drift between current
1529 * and previous window means.
1530 * @param[out] mean_speed_window_rel_out Relative drift between current
1531 * and previous window means.
1532 * @param[out] mean_speed_rms_window_out RMS of mean-speed samples in the
1533 * current window.
1534 * @param[out] mean_speed_rms_window_prev_out RMS of mean-speed samples in the
1535 * previous window.
1536 * @param[out] mean_speed_rms_window_abs_out Absolute drift between window RMS
1537 * values.
1538 * @param[out] mean_speed_rms_window_rel_out Relative drift between window RMS
1539 * values.
1540 * @param[out] mean_ke_window_out Mean kinetic energy over the
1541 * current window.
1542 * @param[out] mean_ke_window_prev_out Mean kinetic energy over the
1543 * previous window.
1544 * @param[out] mean_ke_window_abs_out Absolute drift between current
1545 * and previous KE-window means.
1546 * @param[out] mean_ke_window_rel_out Relative drift between current
1547 * and previous KE-window means.
1548 * @param[out] mean_ke_rms_window_out RMS of mean-KE samples in the
1549 * current window.
1550 * @param[out] mean_ke_rms_window_prev_out RMS of mean-KE samples in the
1551 * previous window.
1552 * @param[out] mean_ke_rms_window_abs_out Absolute drift between KE-window
1553 * RMS values.
1554 * @param[out] mean_ke_rms_window_rel_out Relative drift between KE-window
1555 * RMS values.
1556 * @return PetscErrorCode 0 on success.
1557 */
1558static PetscErrorCode ComputeStatisticalWindowMetrics(const SimCtx *simCtx,
1559 PetscInt samples_available,
1560 PetscBool *has_reference_out,
1561 PetscReal *mean_speed_window_out,
1562 PetscReal *mean_speed_window_prev_out,
1563 PetscReal *mean_speed_window_abs_out,
1564 PetscReal *mean_speed_window_rel_out,
1565 PetscReal *mean_speed_rms_window_out,
1566 PetscReal *mean_speed_rms_window_prev_out,
1567 PetscReal *mean_speed_rms_window_abs_out,
1568 PetscReal *mean_speed_rms_window_rel_out,
1569 PetscReal *mean_ke_window_out,
1570 PetscReal *mean_ke_window_prev_out,
1571 PetscReal *mean_ke_window_abs_out,
1572 PetscReal *mean_ke_window_rel_out,
1573 PetscReal *mean_ke_rms_window_out,
1574 PetscReal *mean_ke_rms_window_prev_out,
1575 PetscReal *mean_ke_rms_window_abs_out,
1576 PetscReal *mean_ke_rms_window_rel_out)
1577{
1578 PetscInt w = 0;
1579 PetscInt history_capacity = 0;
1580 PetscReal speed_sum = 0.0;
1581 PetscReal speed_sum_sq = 0.0;
1582 PetscReal speed_prev_sum = 0.0;
1583 PetscReal speed_prev_sum_sq = 0.0;
1584 PetscReal ke_sum = 0.0;
1585 PetscReal ke_sum_sq = 0.0;
1586 PetscReal ke_prev_sum = 0.0;
1587 PetscReal ke_prev_sum_sq = 0.0;
1588
1589 PetscFunctionBeginUser;
1591 if (!simCtx || !has_reference_out || !mean_speed_window_out || !mean_speed_window_prev_out ||
1592 !mean_speed_window_abs_out || !mean_speed_window_rel_out || !mean_speed_rms_window_out ||
1593 !mean_speed_rms_window_prev_out || !mean_speed_rms_window_abs_out || !mean_speed_rms_window_rel_out ||
1594 !mean_ke_window_out || !mean_ke_window_prev_out || !mean_ke_window_abs_out || !mean_ke_window_rel_out ||
1595 !mean_ke_rms_window_out || !mean_ke_rms_window_prev_out || !mean_ke_rms_window_abs_out ||
1596 !mean_ke_rms_window_rel_out) {
1597 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "ComputeStatisticalWindowMetrics received a NULL output pointer.");
1598 }
1599
1600 *has_reference_out = PETSC_FALSE;
1601 *mean_speed_window_out = 0.0;
1602 *mean_speed_window_prev_out = 0.0;
1603 *mean_speed_window_abs_out = 0.0;
1604 *mean_speed_window_rel_out = 0.0;
1605 *mean_speed_rms_window_out = 0.0;
1606 *mean_speed_rms_window_prev_out = 0.0;
1607 *mean_speed_rms_window_abs_out = 0.0;
1608 *mean_speed_rms_window_rel_out = 0.0;
1609 *mean_ke_window_out = 0.0;
1610 *mean_ke_window_prev_out = 0.0;
1611 *mean_ke_window_abs_out = 0.0;
1612 *mean_ke_window_rel_out = 0.0;
1613 *mean_ke_rms_window_out = 0.0;
1614 *mean_ke_rms_window_prev_out = 0.0;
1615 *mean_ke_rms_window_abs_out = 0.0;
1616 *mean_ke_rms_window_rel_out = 0.0;
1617
1619 history_capacity = 2 * w;
1620 if (w <= 0 || samples_available < w) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1621
1622 for (PetscInt idx = 0; idx < w; ++idx) {
1624 history_capacity,
1625 samples_available,
1626 idx);
1628 history_capacity,
1629 samples_available,
1630 idx);
1631 speed_sum += speed_value;
1632 speed_sum_sq += speed_value * speed_value;
1633 ke_sum += ke_value;
1634 ke_sum_sq += ke_value * ke_value;
1635 }
1636
1637 *mean_speed_window_out = speed_sum / (PetscReal)w;
1638 *mean_speed_rms_window_out = PetscSqrtReal(PetscMax(0.0, speed_sum_sq / (PetscReal)w -
1639 (*mean_speed_window_out) * (*mean_speed_window_out)));
1640 *mean_ke_window_out = ke_sum / (PetscReal)w;
1641 *mean_ke_rms_window_out = PetscSqrtReal(PetscMax(0.0, ke_sum_sq / (PetscReal)w -
1642 (*mean_ke_window_out) * (*mean_ke_window_out)));
1643
1644 if (samples_available < 2 * w) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
1645
1646 for (PetscInt idx = w; idx < 2 * w; ++idx) {
1648 history_capacity,
1649 samples_available,
1650 idx);
1652 history_capacity,
1653 samples_available,
1654 idx);
1655 speed_prev_sum += speed_value;
1656 speed_prev_sum_sq += speed_value * speed_value;
1657 ke_prev_sum += ke_value;
1658 ke_prev_sum_sq += ke_value * ke_value;
1659 }
1660
1661 *has_reference_out = PETSC_TRUE;
1662 *mean_speed_window_prev_out = speed_prev_sum / (PetscReal)w;
1663 *mean_speed_window_abs_out = PetscAbsReal(*mean_speed_window_out - *mean_speed_window_prev_out);
1664 *mean_speed_window_rel_out = SolutionConvergenceSafeRelative(*mean_speed_window_abs_out, *mean_speed_window_out);
1665 *mean_speed_rms_window_prev_out = PetscSqrtReal(PetscMax(0.0, speed_prev_sum_sq / (PetscReal)w -
1666 (*mean_speed_window_prev_out) * (*mean_speed_window_prev_out)));
1667 *mean_speed_rms_window_abs_out = PetscAbsReal(*mean_speed_rms_window_out - *mean_speed_rms_window_prev_out);
1668 *mean_speed_rms_window_rel_out = SolutionConvergenceSafeRelative(*mean_speed_rms_window_abs_out, *mean_speed_rms_window_out);
1669
1670 *mean_ke_window_prev_out = ke_prev_sum / (PetscReal)w;
1671 *mean_ke_window_abs_out = PetscAbsReal(*mean_ke_window_out - *mean_ke_window_prev_out);
1672 *mean_ke_window_rel_out = SolutionConvergenceSafeRelative(*mean_ke_window_abs_out, *mean_ke_window_out);
1673 *mean_ke_rms_window_prev_out = PetscSqrtReal(PetscMax(0.0, ke_prev_sum_sq / (PetscReal)w -
1674 (*mean_ke_window_prev_out) * (*mean_ke_window_prev_out)));
1675 *mean_ke_rms_window_abs_out = PetscAbsReal(*mean_ke_rms_window_out - *mean_ke_rms_window_prev_out);
1676 *mean_ke_rms_window_rel_out = SolutionConvergenceSafeRelative(*mean_ke_rms_window_abs_out, *mean_ke_rms_window_out);
1677
1679 PetscFunctionReturn(0);
1680}
1681
1682/**
1683 * @brief Maps the internal solution-convergence mode enum to its log label.
1684 *
1685 * The logger writes a human-readable mode string into the
1686 * `solution_convergence.log` banner and `mode` column. This helper keeps the
1687 * formatting centralized so the file output stays consistent with the accepted
1688 * configuration names.
1689 *
1690 * @param[in] mode Internal solution-convergence mode selector.
1691 * @return Lowercase string label written to the log output.
1692 */
1694{
1696 const char *name;
1697 switch (mode) {
1698 case SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC: name = "steady_deterministic"; break;
1699 case SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC: name = "periodic_deterministic"; break;
1700 case SOLUTION_CONVERGENCE_STATISTICAL_STEADY: name = "statistical_steady"; break;
1701 case SOLUTION_CONVERGENCE_TRANSIENT: name = "transient"; break;
1702 default: name = "unknown"; break;
1703 }
1705 return name;
1706}
1707
1708/**
1709 * @brief Implementation of \ref LOG_SOLUTION_CONVERGENCE().
1710 * @details Full API contract (arguments, ownership, side effects) is documented with
1711 * the header declaration in `include/logging.h`.
1712 * @see LOG_SOLUTION_CONVERGENCE()
1713 */
1714PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
1715{
1716 PetscMPIInt rank = 0;
1717 PetscBool has_reference = PETSC_FALSE;
1718 PetscInt phase_step = -1;
1719 PetscInt samples_before = 0;
1720 PetscReal u_abs_l2 = 0.0, u_rel_l2 = 0.0, p_abs_l2 = 0.0, p_rel_l2 = 0.0;
1721 PetscReal mean_speed = 0.0, mean_speed_reference = 0.0, mean_speed_abs_drift = 0.0, mean_speed_rel_drift = 0.0;
1722 PetscReal mean_ke = 0.0, mean_ke_reference = 0.0, mean_ke_abs_drift = 0.0, mean_ke_rel_drift = 0.0;
1723 PetscReal mean_speed_window = 0.0, mean_speed_window_prev = 0.0, mean_speed_window_abs_drift = 0.0, mean_speed_window_rel_drift = 0.0;
1724 PetscReal mean_speed_rms_window = 0.0, mean_speed_rms_window_prev = 0.0, mean_speed_rms_window_abs_drift = 0.0, mean_speed_rms_window_rel_drift = 0.0;
1725 PetscReal mean_ke_window = 0.0, mean_ke_window_prev = 0.0, mean_ke_window_abs_drift = 0.0, mean_ke_window_rel_drift = 0.0;
1726 PetscReal mean_ke_rms_window = 0.0, mean_ke_rms_window_prev = 0.0, mean_ke_rms_window_abs_drift = 0.0, mean_ke_rms_window_rel_drift = 0.0;
1727
1728 PetscFunctionBeginUser;
1730 if (!simCtx) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1731 if (simCtx->exec_mode != EXEC_MODE_SOLVER) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1732 if (!simCtx->solutionConvergenceEnabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1733
1734 samples_before = simCtx->solutionConvergenceSamplesRecorded;
1735
1736 switch (simCtx->solutionConvergenceMode) {
1739 PetscCall(ComputeDeterministicSolutionMetrics(simCtx, PETSC_FALSE, -1, samples_before,
1740 &has_reference,
1741 &u_abs_l2, &u_rel_l2,
1742 &p_abs_l2, &p_rel_l2,
1743 &mean_speed, &mean_speed_reference,
1744 &mean_speed_abs_drift, &mean_speed_rel_drift,
1745 &mean_ke, &mean_ke_reference,
1746 &mean_ke_abs_drift, &mean_ke_rel_drift));
1747 break;
1749 phase_step = simCtx->solutionConvergencePeriodSteps > 0 ? (simCtx->step % simCtx->solutionConvergencePeriodSteps) : -1;
1750 PetscCall(ComputeDeterministicSolutionMetrics(simCtx, PETSC_TRUE, phase_step, samples_before,
1751 &has_reference,
1752 &u_abs_l2, &u_rel_l2,
1753 &p_abs_l2, &p_rel_l2,
1754 &mean_speed, &mean_speed_reference,
1755 &mean_speed_abs_drift, &mean_speed_rel_drift,
1756 &mean_ke, &mean_ke_reference,
1757 &mean_ke_abs_drift, &mean_ke_rel_drift));
1758 break;
1760 PetscCall(ComputeCurrentFlowObservables(simCtx, &mean_speed, &mean_ke));
1761 PetscCall(AppendStatisticalObservableSample(simCtx, samples_before, mean_speed, mean_ke));
1762 PetscCall(ComputeStatisticalWindowMetrics(simCtx, samples_before + 1,
1763 &has_reference,
1764 &mean_speed_window, &mean_speed_window_prev,
1765 &mean_speed_window_abs_drift, &mean_speed_window_rel_drift,
1766 &mean_speed_rms_window, &mean_speed_rms_window_prev,
1767 &mean_speed_rms_window_abs_drift, &mean_speed_rms_window_rel_drift,
1768 &mean_ke_window, &mean_ke_window_prev,
1769 &mean_ke_window_abs_drift, &mean_ke_window_rel_drift,
1770 &mean_ke_rms_window, &mean_ke_rms_window_prev,
1771 &mean_ke_rms_window_abs_drift, &mean_ke_rms_window_rel_drift));
1772 break;
1773 default:
1774 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown solution convergence mode %d.", (int)simCtx->solutionConvergenceMode);
1775 }
1776
1777 rank = simCtx->rank;
1778 if (rank == 0) {
1779 FILE *f = NULL;
1780 const char *mode_str = SolutionConvergenceModeToString(simCtx->solutionConvergenceMode);
1781 const char *header = NULL;
1782
1783 /* One mode per run, so one header; every row also names its mode. */
1784 switch (simCtx->solutionConvergenceMode) {
1786 header = "step,time,mode,ref,ph,per,u_abs_l2,u_rel_l2,p_abs_l2,p_rel_l2,"
1787 "mean_speed,spd_ref,spd_abs,spd_rel,mean_ke,ke_ref,ke_abs,ke_rel";
1788 break;
1790 header = "step,time,mode,ref,win,mean_speed,mean_ke,spd_win,spd_win_prev,spd_win_abs,spd_win_rel,"
1791 "spd_rms_win,spd_rms_abs,spd_rms_rel,ke_win,ke_win_prev,ke_win_abs,ke_win_rel,"
1792 "ke_rms_win,ke_rms_abs,ke_rms_rel";
1793 break;
1794 default:
1795 header = "step,time,mode,ref,u_abs_l2,u_rel_l2,p_abs_l2,p_rel_l2,"
1796 "mean_speed,spd_ref,spd_abs,spd_rel,mean_ke,ke_ref,ke_abs,ke_rel";
1797 break;
1798 }
1799 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->log_dir, "solution_convergence.csv", header, &f));
1800
1801 switch (simCtx->solutionConvergenceMode) {
1804 fprintf(f,
1805 "%d,%.10e,%s,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1806 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1807 (double)u_abs_l2, (double)u_rel_l2, (double)p_abs_l2, (double)p_rel_l2,
1808 (double)mean_speed, (double)mean_speed_reference,
1809 (double)mean_speed_abs_drift, (double)mean_speed_rel_drift,
1810 (double)mean_ke, (double)mean_ke_reference,
1811 (double)mean_ke_abs_drift, (double)mean_ke_rel_drift);
1812 break;
1814 fprintf(f,
1815 "%d,%.10e,%s,%d,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1816 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1817 (int)phase_step, (int)simCtx->solutionConvergencePeriodSteps,
1818 (double)u_abs_l2, (double)u_rel_l2, (double)p_abs_l2, (double)p_rel_l2,
1819 (double)mean_speed, (double)mean_speed_reference,
1820 (double)mean_speed_abs_drift, (double)mean_speed_rel_drift,
1821 (double)mean_ke, (double)mean_ke_reference,
1822 (double)mean_ke_abs_drift, (double)mean_ke_rel_drift);
1823 break;
1825 fprintf(f,
1826 "%d,%.10e,%s,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1827 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1828 (int)simCtx->solutionConvergenceWindowSteps,
1829 (double)mean_speed, (double)mean_ke,
1830 (double)mean_speed_window, (double)mean_speed_window_prev,
1831 (double)mean_speed_window_abs_drift, (double)mean_speed_window_rel_drift,
1832 (double)mean_speed_rms_window,
1833 (double)mean_speed_rms_window_abs_drift, (double)mean_speed_rms_window_rel_drift,
1834 (double)mean_ke_window, (double)mean_ke_window_prev,
1835 (double)mean_ke_window_abs_drift, (double)mean_ke_window_rel_drift,
1836 (double)mean_ke_rms_window,
1837 (double)mean_ke_rms_window_abs_drift, (double)mean_ke_rms_window_rel_drift);
1838 break;
1839 default: break;
1840 }
1841 fclose(f);
1842 }
1843
1845 phase_step >= 0 && phase_step < simCtx->solutionConvergencePeriodSteps) {
1846 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1847 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
1848 PetscCall(VecCopy(user[bi].Ucat, user[bi].solutionConvergencePeriodicUcatRef[phase_step]));
1849 PetscCall(VecCopy(user[bi].P, user[bi].solutionConvergencePeriodicPRef[phase_step]));
1850 }
1851 }
1852
1853 simCtx->solutionConvergenceSamplesRecorded = samples_before + 1;
1854
1856 PetscFunctionReturn(0);
1857}
1858
1859/**
1860 * @brief Implementation of \ref LOG_CONTINUITY_METRICS().
1861 * @details Full API contract (arguments, ownership, side effects) is documented with
1862 * the header declaration in `include/logging.h`.
1863 * @see LOG_CONTINUITY_METRICS()
1864 */
1865
1866PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user)
1867{
1868 PetscErrorCode ierr;
1869 PetscMPIInt rank;
1870 SimCtx *simCtx = user->simCtx; // Get the shared SimCtx
1871 const PetscInt bi = user->_this; // Get this block's specific ID
1872 const PetscInt ti = simCtx->step; // Get the current timestep
1873
1874 PetscFunctionBeginUser;
1876 rank = simCtx->rank;
1877
1878 // Only rank 0 performs file I/O. One row per block per step; only block 0 marks a continuation.
1879 if (!rank) {
1880 FILE *f = NULL;
1881 PetscReal physical_time = 0.0;
1882 ierr = PicurvOpenDiagnosticsCsv(simCtx, simCtx->log_dir, "Continuity_Metrics.csv",
1883 "step,block,max_divergence,max_divergence_k,max_divergence_j,max_divergence_i,"
1884 "max_divergence_index,poisson_source_imbalance,flux_in,flux_out,net_flux,time,physical_time",
1885 &f); CHKERRQ(ierr);
1886 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time); CHKERRQ(ierr);
1887 fprintf(f, "%d,%d,%.10e,%d,%d,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1888 (int)ti, (int)bi, (double)simCtx->MaxDiv,
1889 (int)simCtx->MaxDivz, (int)simCtx->MaxDivy, (int)simCtx->MaxDivx, (int)simCtx->MaxDivFlatArg,
1890 (double)simCtx->poissonSourceImbalance, (double)simCtx->FluxInSum, (double)simCtx->FluxOutSum,
1891 (double)(simCtx->FluxInSum - simCtx->FluxOutSum), (double)simCtx->ti, (double)physical_time);
1892 fclose(f);
1893 }
1894
1896 PetscFunctionReturn(0);
1897}
1898
1899/**
1900 * @brief Implementation of \ref ParticleLocationStatusToString().
1901 * @details Full API contract (arguments, ownership, side effects) is documented with
1902 * the header declaration in `include/logging.h`.
1903 * @see ParticleLocationStatusToString()
1904 */
1906{
1908 const char *name;
1909 switch (level) {
1910 case NEEDS_LOCATION: name = "NEEDS_LOCATION"; break;
1911 case ACTIVE_AND_LOCATED: name = "ACTIVE_AND_LOCATED"; break;
1912 case MIGRATING_OUT: name = "MIGRATING_OUT"; break;
1913 case LOST: name = "LOST"; break;
1914 case UNINITIALIZED: name = "UNINITIALIZED"; break;
1915 case EXITED: name = "EXITED"; break;
1916 default: name = "UNKNOWN_LEVEL"; break;
1917 }
1919 return name;
1920}
1921
1922///////// Profiling System /////////
1923// Timers are PETSc log events, so PETSc's own events, log_view and the PICurv reports below
1924// read one record. PICurv functions register under two classes: aggregates (always on) and
1925// helpers (per-particle or per-cell functions, off unless enabled by name). This file keeps
1926// only reporting state: the enabled and selected names and the per-step snapshot.
1927
1928static PetscClassId g_profile_class_function = 0; // "PICurv"; 0 until first profiled call
1929static PetscClassId g_profile_class_helper = 0; // "PICurvHelper"
1930static char **g_profile_helpers = NULL; // Helpers enabled by name (owned by SimCtx)
1931static PetscInt g_profile_nhelpers = 0;
1932static PetscBool g_profile_all_helpers = PETSC_FALSE;
1933static PetscBool g_profile_any_helpers = PETSC_FALSE;
1935static char **g_profile_selected = NULL; // timestep_output 'selected' names (owned by SimCtx)
1936static PetscInt g_profile_nselected = 0;
1937static PetscLogDouble *g_profile_step_time = NULL; // Running totals at the last step boundary,
1938static int *g_profile_step_count = NULL; // indexed by PETSc event
1939static PetscInt g_profile_step_capacity = 0;
1940
1941/**
1942 * @brief Whether a name appears in a list of names.
1943 */
1944static PetscBool _ProfilingNameListed(const char *name, char **names, PetscInt n)
1945{
1946 for (PetscInt i = 0; i < n; ++i) if (names[i] && strcmp(names[i], name) == 0) return PETSC_TRUE;
1947 return PETSC_FALSE;
1948}
1949
1950/**
1951 * @brief Whether a helper function's timer is enabled.
1952 */
1953static PetscBool _ProfilingHelperEnabled(const char *name)
1954{
1956}
1957
1958/**
1959 * @brief Register the two PICurv event classes and start PETSc's default log handler, once.
1960 * @details The handler must run before the first event begins: an event that begins before it
1961 * and ends after it is not one the handler can close.
1962 */
1963static PetscErrorCode _ProfilingEnsureStarted(void)
1964{
1965 PetscLogHandler handler = NULL;
1966
1967 PetscFunctionBeginUser;
1969 PetscCall(PetscClassIdRegister("PICurv", &g_profile_class_function));
1970 PetscCall(PetscClassIdRegister("PICurvHelper", &g_profile_class_helper));
1971 }
1972 // The reports read the default handler, which -log_trace or another handler does not start.
1973 PetscCall(PetscLogGetDefaultHandler(&handler));
1974 if (!handler) PetscCall(PetscLogDefaultBegin());
1975 PetscFunctionReturn(0);
1976}
1977
1978/**
1979 * @brief Implementation of \ref _ProfilingRegister().
1980 * @details Full API contract (arguments, ownership, side effects) is documented with
1981 * the header declaration in `include/logging.h`.
1982 * @see _ProfilingRegister()
1983 */
1984void _ProfilingRegister(const char *func_name, PetscBool helper, PetscLogEvent *event)
1985{
1986 PetscLogEvent registered = -1;
1987
1988 // Before PetscInitialize (argument handling in main) or after PetscFinalize there is no log
1989 // to register with; the call site stays untimed and tries again on its next call.
1990 if (!PetscInitializeCalled || PetscFinalizeCalled) return;
1991 if (_ProfilingEnsureStarted() != 0) return; // Fail silently: the call site stays untimed
1992 if (PetscLogEventRegister(func_name, helper ? g_profile_class_helper : g_profile_class_function, &registered) != 0) return;
1993 // New events start active, and excluding a class reaches only events that already exist,
1994 // so a helper is switched off as it registers unless it is enabled.
1995 if (helper && !_ProfilingHelperEnabled(func_name)) {
1996 if (PetscLogEventSetActiveAll(registered, PETSC_FALSE) != 0) return;
1997 }
1998 *event = registered;
1999}
2000
2001/**
2002 * @brief Whether a PETSc event belongs to one of PICurv's classes.
2003 */
2004static PetscBool _ProfilingIsPicurvClass(PetscClassId classid)
2005{
2006 return (PetscBool)(classid && (classid == g_profile_class_function || classid == g_profile_class_helper));
2007}
2008
2009/**
2010 * @brief Implementation of \ref ProfilingInitialize().
2011 * @details Full API contract (arguments, ownership, side effects) is documented with
2012 * the header declaration in `include/logging.h`.
2013 * @see ProfilingInitialize()
2014 */
2015PetscErrorCode ProfilingInitialize(SimCtx *simCtx)
2016{
2017 PetscLogState state = NULL;
2018 PetscInt nevents = 0;
2019
2020 PetscFunctionBeginUser;
2021 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for ProfilingInitialize");
2022 PetscCall(_ProfilingEnsureStarted());
2029 // Helpers that ran before this (during setup) registered switched off; apply the list to them.
2030 PetscCall(PetscLogGetState(&state));
2031 PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2032 for (PetscLogEvent e = 0; e < nevents; ++e) {
2033 PetscLogEventInfo info;
2034 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2035 if (info.classid == g_profile_class_helper) PetscCall(PetscLogEventSetActiveAll(e, _ProfilingHelperEnabled(info.name)));
2036 }
2037 for (PetscInt i = 0; i < g_profile_nselected; ++i) {
2038 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Marked '%s' for per-step profiling output.\n", g_profile_selected[i]);
2039 }
2040 for (PetscInt i = 0; i < g_profile_nhelpers; ++i) {
2041 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Enabled helper timer '%s'.\n", g_profile_helpers[i]);
2042 }
2043 PetscFunctionReturn(0);
2044}
2045
2046/**
2047 * @brief Read an event's running total time and call count on this rank (main stage).
2048 */
2049static PetscErrorCode _ProfilingEventTotals(PetscLogEvent event, PetscLogDouble *time, int *count)
2050{
2051 PetscEventPerfInfo info;
2052
2053 PetscFunctionBeginUser;
2054 PetscCall(PetscLogEventGetPerfInfo(PETSC_DETERMINE, event, &info));
2055 *time = info.time;
2056 *count = info.count;
2057 PetscFunctionReturn(0);
2058}
2059
2060/**
2061 * @brief Record every event's running totals as the start of the next step.
2062 */
2063static PetscErrorCode _ProfilingSnapshotStep(void)
2064{
2065 PetscLogState state = NULL;
2066 PetscInt nevents = 0;
2067
2068 PetscFunctionBeginUser;
2069 PetscCall(PetscLogGetState(&state));
2070 if (!state) PetscFunctionReturn(0);
2071 PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2072 if (nevents > g_profile_step_capacity) {
2073 PetscCall(PetscFree2(g_profile_step_time, g_profile_step_count));
2074 g_profile_step_capacity = PetscMax(2 * g_profile_step_capacity, nevents);
2076 }
2077 for (PetscLogEvent e = 0; e < nevents; ++e) PetscCall(_ProfilingEventTotals(e, &g_profile_step_time[e], &g_profile_step_count[e]));
2078 PetscFunctionReturn(0);
2079}
2080
2081/**
2082 * @brief Implementation of \ref ProfilingResetTimestepCounters().
2083 * @details Full API contract (arguments, ownership, side effects) is documented with
2084 * the header declaration in `include/logging.h`.
2085 * @see ProfilingResetTimestepCounters()
2086 */
2088{
2089 PetscFunctionBeginUser;
2090 PetscCall(_ProfilingSnapshotStep());
2091 PetscFunctionReturn(0);
2092}
2093
2094/**
2095 * @brief Implementation of \ref ProfilingLogTimestepSummary().
2096 * @details Full API contract (arguments, ownership, side effects) is documented with
2097 * the header declaration in `include/logging.h`.
2098 * @see ProfilingLogTimestepSummary()
2099 */
2100PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
2101{
2102 const PetscBool all = (PetscBool)(simCtx && strcmp(simCtx->profilingTimestepMode, "all") == 0);
2103 PetscLogState state = NULL;
2104 PetscInt nevents = 0;
2105 FILE *f = NULL;
2106
2107 PetscFunctionBeginUser;
2108 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for ProfilingLogTimestepSummary");
2109 if (strcmp(simCtx->profilingTimestepMode, "off") == 0) PetscFunctionReturn(0);
2110
2111 PetscCall(PetscLogGetState(&state));
2112 PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2113
2114 /* A selected name that matches no instrumented function records nothing, and a
2115 list made only of such names writes no file at all. Say so once, on the first
2116 step, rather than leave an absent file to be discovered after the run. */
2117 if (step == simCtx->StartStep + 1 && !all) {
2118 for (PetscInt i = 0; i < g_profile_nselected; ++i) {
2119 PetscBool ran = PETSC_FALSE;
2120 for (PetscLogEvent e = 0; e < nevents && !ran; ++e) {
2121 PetscLogEventInfo info;
2122 PetscLogDouble time = 0.0;
2123 int count = 0;
2124 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2125 if (!_ProfilingIsPicurvClass(info.classid) || strcmp(info.name, g_profile_selected[i]) != 0) continue;
2126 PetscCall(_ProfilingEventTotals(e, &time, &count));
2127 ran = (PetscBool)(count > 0);
2128 }
2129 if (!ran) {
2131 "profiling.timestep_output.functions lists '%s', which recorded no call in the first "
2132 "step. It is not an instrumented function; the final summary lists the names that are.\n",
2134 }
2135 }
2136 }
2137
2138 for (PetscLogEvent e = 0; e < nevents; ++e) {
2139 PetscLogEventInfo info;
2140 PetscLogDouble time = 0.0, since_time;
2141 int count = 0, since_count;
2142 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2143 if (!_ProfilingIsPicurvClass(info.classid)) continue;
2144 if (!all && !_ProfilingNameListed(info.name, g_profile_selected, g_profile_nselected)) continue;
2145 PetscCall(_ProfilingEventTotals(e, &time, &count));
2146 // An event registered after the last snapshot started from zero.
2147 since_time = time - (e < g_profile_step_capacity ? g_profile_step_time[e] : 0.0);
2148 since_count = count - (e < g_profile_step_capacity ? g_profile_step_count[e] : 0);
2149 if (since_count <= 0 || simCtx->rank != 0) continue;
2150 /* The file is opened at its first row, which need not be in the run's first step: a
2151 selected function may first run later. */
2152 if (!f) {
2153 PetscCall(PicurvOpenRunCsv(simCtx, simCtx->log_dir, "Profiling_Timestep_Summary.csv",
2154 "step,function,calls,step_time_s", PICURV_CSV_TRUNCATE_ON_FRESH,
2155 PETSC_TRUE, &f));
2156 }
2157 PetscFPrintf(PETSC_COMM_SELF, f, "%d,%s,%d,%.6f\n", (int)step, info.name, since_count, (double)since_time);
2158 }
2159 if (f) fclose(f);
2160 PetscCall(_ProfilingSnapshotStep());
2161 PetscFunctionReturn(0);
2162}
2163
2164/**
2165 * @brief Implementation of \ref RuntimeMemoryLogSample().
2166 * @details Full API contract (arguments, ownership, side effects) is documented with
2167 * the header declaration in `include/logging.h`.
2168 * @see RuntimeMemoryLogSample()
2169 */
2170PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
2171{
2172 PetscErrorCode ierr;
2173 PetscLogDouble process_current_bytes = 0.0;
2174 PetscLogDouble process_peak_bytes = 0.0;
2175 PetscLogDouble petsc_current_bytes = 0.0;
2176 PetscLogDouble petsc_peak_bytes = 0.0;
2177 PetscReal local_values[5];
2178 PetscReal global_values[5];
2179 PetscReal process_current_mb = 0.0;
2180 PetscReal process_peak_mb = 0.0;
2181 PetscReal petsc_current_mb = 0.0;
2182 PetscReal petsc_peak_mb = 0.0;
2183 PetscReal process_change_mb = 0.0;
2184 FILE *f = NULL;
2185
2186 PetscFunctionBeginUser;
2188 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for RuntimeMemoryLogSample");
2189 if (!simCtx->runtimeMemoryLogEnabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2190
2191 ierr = PetscMemoryGetCurrentUsage(&process_current_bytes); CHKERRQ(ierr);
2192 ierr = PetscMemoryGetMaximumUsage(&process_peak_bytes); CHKERRQ(ierr);
2193 ierr = PetscMallocGetCurrentUsage(&petsc_current_bytes); CHKERRQ(ierr);
2194 ierr = PetscMallocGetMaximumUsage(&petsc_peak_bytes); CHKERRQ(ierr);
2195
2196 process_current_mb = (PetscReal)(process_current_bytes / (1024.0 * 1024.0));
2197 process_peak_mb = (PetscReal)(process_peak_bytes / (1024.0 * 1024.0));
2198 petsc_current_mb = (PetscReal)(petsc_current_bytes / (1024.0 * 1024.0));
2199 petsc_peak_mb = (PetscReal)(petsc_peak_bytes / (1024.0 * 1024.0));
2200 if (simCtx->runtimeMemoryLogHasPrevious) {
2201 process_change_mb = process_current_mb - simCtx->runtimeMemoryLogPreviousProcessMB;
2202 }
2203
2204 local_values[0] = process_current_mb;
2205 local_values[1] = process_peak_mb;
2206 local_values[2] = petsc_current_mb;
2207 local_values[3] = petsc_peak_mb;
2208 local_values[4] = process_change_mb;
2209 ierr = MPI_Allreduce(local_values, global_values, 5, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
2210
2211 simCtx->runtimeMemoryLogPreviousProcessMB = process_current_mb;
2212 simCtx->runtimeMemoryLogHasPrevious = PETSC_TRUE;
2213
2214 if (simCtx->rank == 0) {
2215 /* Never truncated: every run appends its samples, a continuation's after its marker. */
2216 ierr = PicurvOpenRunCsv(simCtx, simCtx->log_dir, "Runtime_Memory.csv",
2217 "step,event,process_current_mb_max,process_peak_mb_max,petsc_allocated_mb_max,"
2218 "petsc_peak_allocated_mb_max,process_change_mb_max,reason,step_wall_s",
2219 PICURV_CSV_APPEND, PETSC_TRUE, &f); CHKERRQ(ierr);
2220
2221 fprintf(f, "%" PetscInt_FMT ",%s,%.3f,%.3f,%.3f,%.3f,%.3f,%s,",
2222 step, event ? event : "-",
2223 (double)global_values[0], (double)global_values[1], (double)global_values[2],
2224 (double)global_values[3], (double)global_values[4],
2225 (reason && reason[0]) ? reason : "-");
2226 /* The step's slowest-rank wall time, on the per-step sample only. */
2227 if (event && strcmp(event, "Step") == 0) fprintf(f, "%.6f", (double)simCtx->lastStepWallSeconds);
2228 fprintf(f, "\n");
2229 if ((event && (strcmp(event, "Shutdown") == 0 || strcmp(event, "Final") == 0))) {
2230 fflush(f);
2231 }
2232 fclose(f);
2233 }
2234
2236 PetscFunctionReturn(0);
2237}
2238
2239// One row of the final summary: a function's total time across ranks
2240typedef struct {
2241 const char *name;
2242 double mean_time, min_time, max_time;
2243 int min_rank, max_rank;
2244 long long call_count; // Summed over ranks
2245 double min_calls, max_calls; // Calls on the ranks with the fewest and the most
2246 int min_calls_rank, max_calls_rank;
2248
2249/**
2250 * @brief Order C strings, for qsort over `const char *` arrays.
2251 */
2252static int _CompareNames(const void *a, const void *b)
2253{
2254 return strcmp(*(const char *const *)a, *(const char *const *)b);
2255}
2256
2257/**
2258 * @brief Order final-summary rows by their slowest rank's total time, descending.
2259 */
2260static int _CompareProfiledFunctionRanks(const void *a, const void *b)
2261{
2262 const ProfiledFunctionRanks *func_a = (const ProfiledFunctionRanks *)a;
2263 const ProfiledFunctionRanks *func_b = (const ProfiledFunctionRanks *)b;
2264
2265 if (func_a->max_time < func_b->max_time) return 1;
2266 if (func_a->max_time > func_b->max_time) return -1;
2267 return 0;
2268}
2269
2270/**
2271 * @brief Reduce one section of the final summary across ranks and print it on rank 0.
2272 * @details Collective. Every rank contributes the events it recorded (`names`, with their totals);
2273 * the union of names over ranks is formed by name, so ranks may have recorded different
2274 * sets. Each name's time is reduced to its max and min with their ranks and its mean, and
2275 * its calls are summed and reduced to their min and max per rank with ranks. Rows with
2276 * calls on some rank are printed, slowest rank first.
2277 */
2278static PetscErrorCode _ProfilingReduceSection(FILE *f, const char *section, PetscInt nlocal, const char **names,
2279 const PetscLogDouble *times, const long long *counts)
2280{
2281 PetscMPIInt rank, size, local_len = 0, total_len = 0, *lens = NULL, *displs = NULL;
2282 char *local_names = NULL, *all_names = NULL;
2283 const char **unique = NULL;
2284 PetscInt nall = 0, nunique = 0;
2285 struct { double value; int rank; } *local_time = NULL, *min_time = NULL, *max_time = NULL;
2286 struct { double value; int rank; } *local_count = NULL, *min_count = NULL, *max_count = NULL;
2287 double *local_seconds = NULL, *sum_time = NULL;
2288 long long *local_calls = NULL, *sum_calls = NULL;
2289
2290 PetscFunctionBeginUser;
2291 rank = PetscGlobalRank;
2292 size = PetscGlobalSize;
2293
2294 // --- Union of the recorded names over ranks, in name order ---
2295 for (PetscInt i = 0; i < nlocal; ++i) local_len += (PetscMPIInt)strlen(names[i]) + 1;
2296 PetscCall(PetscMalloc1(local_len + 1, &local_names));
2297 for (PetscInt i = 0, off = 0; i < nlocal; ++i) { strcpy(local_names + off, names[i]); off += (PetscInt)strlen(names[i]) + 1; }
2298 PetscCall(PetscMalloc2(size, &lens, size, &displs));
2299 PetscCallMPI(MPI_Allgather(&local_len, 1, MPI_INT, lens, 1, MPI_INT, PETSC_COMM_WORLD));
2300 for (PetscMPIInt r = 0; r < size; ++r) { displs[r] = total_len; total_len += lens[r]; }
2301 PetscCall(PetscMalloc1(total_len + 1, &all_names));
2302 PetscCallMPI(MPI_Allgatherv(local_names, local_len, MPI_CHAR, all_names, lens, displs, MPI_CHAR, PETSC_COMM_WORLD));
2303 for (PetscMPIInt off = 0; off < total_len; off += (PetscMPIInt)strlen(all_names + off) + 1) nall++;
2304 PetscCall(PetscMalloc1(nall + 1, &unique));
2305 for (PetscMPIInt off = 0; off < total_len; off += (PetscMPIInt)strlen(all_names + off) + 1) unique[nunique++] = all_names + off;
2306 qsort(unique, nunique, sizeof(*unique), _CompareNames);
2307 {
2308 PetscInt kept = 0;
2309 for (PetscInt i = 0; i < nunique; ++i) if (kept == 0 || strcmp(unique[kept - 1], unique[i]) != 0) unique[kept++] = unique[i];
2310 nunique = kept;
2311 }
2312
2313 // --- This rank's totals in union order (zero for a name it did not record) ---
2314 PetscCall(PetscMalloc4(nunique + 1, &local_time, nunique + 1, &min_time, nunique + 1, &max_time, nunique + 1, &sum_time));
2315 PetscCall(PetscMalloc3(nunique + 1, &local_seconds, nunique + 1, &local_calls, nunique + 1, &sum_calls));
2316 PetscCall(PetscMalloc3(nunique + 1, &local_count, nunique + 1, &min_count, nunique + 1, &max_count));
2317 for (PetscInt u = 0; u < nunique; ++u) {
2318 double t = 0.0;
2319 long long c = 0;
2320 for (PetscInt i = 0; i < nlocal; ++i) if (strcmp(names[i], unique[u]) == 0) { t += times[i]; c += counts[i]; }
2321 local_seconds[u] = t; local_time[u].value = t; local_time[u].rank = (int)rank;
2322 local_calls[u] = c; local_count[u].value = (double)c; local_count[u].rank = (int)rank; // Exact below 2^53 calls
2323 }
2324 PetscCallMPI(MPI_Reduce(local_time, min_time, (int)nunique, MPI_DOUBLE_INT, MPI_MINLOC, 0, PETSC_COMM_WORLD));
2325 PetscCallMPI(MPI_Reduce(local_time, max_time, (int)nunique, MPI_DOUBLE_INT, MPI_MAXLOC, 0, PETSC_COMM_WORLD));
2326 PetscCallMPI(MPI_Reduce(local_seconds, sum_time, (int)nunique, MPI_DOUBLE, MPI_SUM, 0, PETSC_COMM_WORLD));
2327 PetscCallMPI(MPI_Reduce(local_calls, sum_calls, (int)nunique, MPI_LONG_LONG, MPI_SUM, 0, PETSC_COMM_WORLD));
2328 PetscCallMPI(MPI_Reduce(local_count, min_count, (int)nunique, MPI_DOUBLE_INT, MPI_MINLOC, 0, PETSC_COMM_WORLD));
2329 PetscCallMPI(MPI_Reduce(local_count, max_count, (int)nunique, MPI_DOUBLE_INT, MPI_MAXLOC, 0, PETSC_COMM_WORLD));
2330
2331 if (!rank) {
2332 ProfiledFunctionRanks *rows = NULL;
2333 PetscInt nrows = 0;
2334 PetscCall(PetscMalloc1(nunique + 1, &rows));
2335 for (PetscInt u = 0; u < nunique; ++u) {
2336 if (sum_calls[u] == 0) continue;
2337 rows[nrows].name = unique[u];
2338 rows[nrows].mean_time = sum_time[u] / size;
2339 rows[nrows].min_time = min_time[u].value;
2340 rows[nrows].min_rank = min_time[u].rank;
2341 rows[nrows].max_time = max_time[u].value;
2342 rows[nrows].max_rank = max_time[u].rank;
2343 rows[nrows].call_count = sum_calls[u];
2344 rows[nrows].min_calls = min_count[u].value;
2345 rows[nrows].min_calls_rank = min_count[u].rank;
2346 rows[nrows].max_calls = max_count[u].value;
2347 rows[nrows].max_calls_rank = max_count[u].rank;
2348 nrows++;
2349 }
2350 qsort(rows, nrows, sizeof(ProfiledFunctionRanks), _CompareProfiledFunctionRanks);
2351 /* One CSV row per function, slowest rank first; `section` keeps PICurv's functions and
2352 * PETSc's own (inclusive, so not additive with them) apart. */
2353 for (PetscInt i = 0; i < nrows; ++i) {
2354 double avg_time_ms = (rows[i].mean_time * size / rows[i].call_count) * 1000.0;
2355 PetscFPrintf(PETSC_COMM_SELF, f, "%s,%s,%.6f,%d,%.6f,%.6f,%d,%lld,%.6f,%.0f,%d,%.0f,%d\n",
2356 section, rows[i].name,
2357 rows[i].max_time, rows[i].max_rank, rows[i].mean_time,
2358 rows[i].min_time, rows[i].min_rank, rows[i].call_count, avg_time_ms,
2359 rows[i].min_calls, rows[i].min_calls_rank, rows[i].max_calls, rows[i].max_calls_rank);
2360 }
2361 PetscCall(PetscFree(rows));
2362 }
2363
2364 PetscCall(PetscFree4(local_time, min_time, max_time, sum_time));
2365 PetscCall(PetscFree3(local_seconds, local_calls, sum_calls));
2366 PetscCall(PetscFree3(local_count, min_count, max_count));
2367 PetscCall(PetscFree(unique));
2368 PetscCall(PetscFree(all_names));
2369 PetscCall(PetscFree2(lens, displs));
2370 PetscCall(PetscFree(local_names));
2371 PetscFunctionReturn(0);
2372}
2373
2374/**
2375 * @brief Implementation of \ref ProfilingFinalize().
2376 * @details Full API contract (arguments, ownership, side effects) is documented with
2377 * the header declaration in `include/logging.h`.
2378 * @see ProfilingFinalize()
2379 */
2380PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
2381{
2382 PetscLogState state = NULL;
2383 PetscInt nevents = 0, npicurv = 0, npetsc = 0;
2384 const char **picurv_names = NULL, **petsc_names = NULL;
2385 PetscLogDouble *picurv_times = NULL, *petsc_times = NULL;
2386 long long *picurv_counts = NULL, *petsc_counts = NULL;
2387 FILE *f = NULL;
2388
2389 PetscFunctionBeginUser;
2390 if (!simCtx->profilingFinalSummary) PetscFunctionReturn(0);
2391
2392 // --- This rank's recorded events, split into PICurv's and PETSc's own ---
2393 PetscCall(PetscLogGetState(&state));
2394 if (state) PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2395 PetscCall(PetscMalloc3(nevents + 1, &picurv_names, nevents + 1, &picurv_times, nevents + 1, &picurv_counts));
2396 PetscCall(PetscMalloc3(nevents + 1, &petsc_names, nevents + 1, &petsc_times, nevents + 1, &petsc_counts));
2397 for (PetscLogEvent e = 0; e < nevents; ++e) {
2398 PetscLogEventInfo info;
2399 PetscLogDouble time = 0.0;
2400 int count = 0;
2401 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2402 PetscCall(_ProfilingEventTotals(e, &time, &count));
2403 if (count <= 0) continue;
2404 if (_ProfilingIsPicurvClass(info.classid)) {
2405 picurv_names[npicurv] = info.name; picurv_times[npicurv] = time; picurv_counts[npicurv++] = count;
2406 } else {
2407 petsc_names[npetsc] = info.name; petsc_times[npetsc] = time; petsc_counts[npetsc++] = count;
2408 }
2409 }
2410
2411 if (!simCtx->rank) {
2412 char exec_mode_modifier[32] = "Unknown";
2413 char filen[64];
2414 if (simCtx->exec_mode == EXEC_MODE_SOLVER) PetscCall(PetscStrncpy(exec_mode_modifier, "Solver", sizeof(exec_mode_modifier)));
2415 else if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) PetscCall(PetscStrncpy(exec_mode_modifier, "PostProcessor", sizeof(exec_mode_modifier)));
2416 PetscCall(PetscSNPrintf(filen, sizeof(filen), "ProfilingSummary_%s.csv", exec_mode_modifier));
2417 // Written once, at the end: a fresh run replaces the file, a continuation appends its totals after its marker.
2418 PetscCall(PicurvOpenRunCsv(simCtx, simCtx->log_dir, filen,
2419 "section,function,max_time_s,max_rank,mean_time_s,min_time_s,min_rank,calls,avg_time_per_call_ms,"
2420 "min_calls_per_rank,min_calls_rank,max_calls_per_rank,max_calls_rank",
2421 PICURV_CSV_TRUNCATE_ON_FRESH, PETSC_TRUE, &f));
2422 fprintf(f, "# Total time per rank over %d rank(s). Section 'petsc' times are inclusive and run inside the "
2423 "'picurv' functions, so the two sections must not be added together.\n", (int)simCtx->size);
2424 }
2425 PetscCall(_ProfilingReduceSection(f, "picurv", npicurv, picurv_names, picurv_times, picurv_counts));
2426 PetscCall(_ProfilingReduceSection(f, "petsc", npetsc, petsc_names, petsc_times, petsc_counts));
2427 if (f) fclose(f);
2428
2429 PetscCall(PetscFree3(picurv_names, picurv_times, picurv_counts));
2430 PetscCall(PetscFree3(petsc_names, petsc_times, petsc_counts));
2431 PetscCall(PetscFree2(g_profile_step_time, g_profile_step_count));
2433 PetscFunctionReturn(0);
2434}
2435
2436/*================================================================================*
2437 * PROGRESS BAR UTILITY *
2438 *================================================================================*/
2439
2440/**
2441 * @brief Implementation of \ref PrintProgressBar().
2442 * @details Full API contract (arguments, ownership, side effects) is documented with
2443 * the header declaration in `include/logging.h`.
2444 * @see PrintProgressBar()
2445 */
2446void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime,
2447 PetscReal seconds_per_step, PetscInt64 lost_cumulative)
2448{
2450 if (totalSteps <= 0) { PROFILE_FUNCTION_END; return; }
2451
2452 // --- Configuration ---
2453 const int barWidth = 50;
2454
2455 // --- Calculation ---
2456 // Calculate progress as a fraction from 0.0 to 1.0
2457 PetscReal progress = (PetscReal)(step - startStep + 1) / totalSteps;
2458 // Ensure progress doesn't exceed 1.0 due to floating point inaccuracies
2459 if (progress > 1.0) progress = 1.0;
2460
2461 int pos = (int)(barWidth * progress);
2462
2463 // --- Printing ---
2464 // Carriage return moves cursor to the beginning of the line
2465 PetscPrintf(PETSC_COMM_SELF, "\rProgress: [");
2466
2467 for (int i = 0; i < barWidth; ++i) {
2468 if (i < pos) {
2469 PetscPrintf(PETSC_COMM_SELF, "=");
2470 } else if (i == pos) {
2471 PetscPrintf(PETSC_COMM_SELF, ">");
2472 } else {
2473 PetscPrintf(PETSC_COMM_SELF, " ");
2474 }
2475 }
2476
2477 // Print percentage, step count, and current time
2478 PetscPrintf(PETSC_COMM_SELF, "] %3d%% (Step %" PetscInt_FMT "/%" PetscInt_FMT ", t=%.4f)",
2479 (int)(progress * 100.0),
2480 step + 1,
2481 startStep + totalSteps,
2482 currentTime);
2483 if (seconds_per_step > 0.0) {
2484 const PetscInt remaining = PetscMax(0, startStep + totalSteps - (step + 1));
2485 const long long eta = (long long)(seconds_per_step * (PetscReal)remaining + 0.5);
2486 PetscPrintf(PETSC_COMM_SELF, " | %.3g s/step | ETA %lld:%02lld:%02lld",
2487 (double)seconds_per_step, eta / 3600, (eta / 60) % 60, eta % 60);
2488 }
2489 if (lost_cumulative >= 0) PetscPrintf(PETSC_COMM_SELF, " | lost %lld", (long long)lost_cumulative);
2490
2491 // Flush the output buffer to ensure the bar is displayed immediately
2492 fflush(stdout);
2494}
2495
2496/**
2497 * @brief Implementation of \ref LOG_FIELD_MIN_MAX().
2498 * @details Full API contract is documented with the header declaration in `include/logging.h`.
2499 * @see LOG_FIELD_MIN_MAX()
2500 */
2501PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
2502{
2503 PetscErrorCode ierr;
2504 PetscInt i, j, k;
2505 DMDALocalInfo info;
2506
2507 FieldView view;
2508 Vec fieldVec = NULL;
2509 DM dm = NULL;
2510 PetscInt dof;
2511 FieldLayout layout;
2512 const char *fieldName = NULL;
2513 const char *data_layout = NULL;
2514
2515 PetscFunctionBeginUser;
2517
2518 ierr = FieldGetView(user, field_id, &view); CHKERRQ(ierr);
2519 fieldName = view.descriptor->canonical_name;
2520 dm = view.dm;
2521 dof = view.descriptor->dof;
2522 layout = view.descriptor->layout;
2523 data_layout = FieldLayoutName(layout);
2524 fieldVec = (layout == FIELD_LAYOUT_COMPONENT_STAGGERED) ? view.local_vec : view.global_vec;
2525
2526 info = user->info; // dm is user->da or user->fda, which share one decomposition
2527
2528 // --- 2. Define Architecture-Aware Loop Bounds ---
2529 PetscInt i_start, i_end, j_start, j_end, k_start, k_end;
2530
2531 if (layout == FIELD_LAYOUT_CELL_CENTERED) {
2532 // For cell-centered data, the physical values are stored from index 1 to N-1.
2533 // We find the intersection of the rank's owned range [xs, xe) with the
2534 // physical data range [1, IM-1).
2535 i_start = PetscMax(info.xs, 1); i_end = PetscMin(info.xs + info.xm, user->IM);
2536 j_start = PetscMax(info.ys, 1); j_end = PetscMin(info.ys + info.ym, user->JM);
2537 k_start = PetscMax(info.zs, 1); k_end = PetscMin(info.zs + info.zm, user->KM);
2538 } else { // For Node- or Face-Centered data
2539 // The physical values are stored from index 0 to N-1.
2540 // We find the intersection of the rank's owned range [xs, xe) with the
2541 // physical data range [0, IM-1].
2542 i_start = PetscMax(info.xs, 0); i_end = PetscMin(info.xs + info.xm, user->IM);
2543 j_start = PetscMax(info.ys, 0); j_end = PetscMin(info.ys + info.ym, user->JM);
2544 k_start = PetscMax(info.zs, 0); k_end = PetscMin(info.zs + info.zm, user->KM);
2545 }
2546
2547 // --- 3. Barrier for clean, grouped output ---
2548 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRQ(ierr);
2549 if (user->simCtx->rank == 0) {
2550 PetscPrintf(PETSC_COMM_SELF, "\n--- Field Ranges: [%s] (Layout: %s) ---\n", fieldName, data_layout);
2551 }
2552
2553 // --- 4. Branch on DoF and perform calculation with correct bounds ---
2554 if (dof == 1) {
2555 PetscReal localMin = PETSC_MAX_REAL, localMax = PETSC_MIN_REAL;
2556 PetscReal globalMin, globalMax;
2557 const PetscScalar ***array;
2558
2559 ierr = DMDAVecGetArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2560 for (k = k_start; k < k_end; k++) {
2561 for (j = j_start; j < j_end; j++) {
2562 for (i = i_start; i < i_end; i++) {
2563 localMin = PetscMin(localMin, array[k][j][i]);
2564 localMax = PetscMax(localMax, array[k][j][i]);
2565 }
2566 }
2567 }
2568 ierr = DMDAVecRestoreArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2569
2570 ierr = MPI_Allreduce(&localMin, &globalMin, 1, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD); CHKERRQ(ierr);
2571 ierr = MPI_Allreduce(&localMax, &globalMax, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
2572
2573 PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin, localMax);
2574 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
2575 if (user->simCtx->rank == 0) {
2576 PetscPrintf(PETSC_COMM_SELF, " Global Range: [ %11.4e , %11.4e ]\n", globalMin, globalMax);
2577 }
2578
2579 } else if (dof == 3) {
2580 Cmpnts localMin = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MAX_REAL};
2581 Cmpnts localMax = {PETSC_MIN_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
2582 Cmpnts globalMin, globalMax;
2583 const Cmpnts ***array;
2584
2585 ierr = DMDAVecGetArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2586 for (k = k_start; k < k_end; k++) {
2587 for (j = j_start; j < j_end; j++) {
2588 for (i = i_start; i < i_end; i++) {
2589 localMin.x = PetscMin(localMin.x, array[k][j][i].x);
2590 localMin.y = PetscMin(localMin.y, array[k][j][i].y);
2591 localMin.z = PetscMin(localMin.z, array[k][j][i].z);
2592 localMax.x = PetscMax(localMax.x, array[k][j][i].x);
2593 localMax.y = PetscMax(localMax.y, array[k][j][i].y);
2594 localMax.z = PetscMax(localMax.z, array[k][j][i].z);
2595 }
2596 }
2597 }
2598 ierr = DMDAVecRestoreArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2599
2600 ierr = MPI_Allreduce(&localMin, &globalMin, 3, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD); CHKERRQ(ierr);
2601 ierr = MPI_Allreduce(&localMax, &globalMax, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
2602
2603 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local X-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.x, localMax.x);
2604 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Y-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.y, localMax.y);
2605 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Z-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.z, localMax.z);
2606 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
2607
2608 if (user->simCtx->rank == 0) {
2609 PetscPrintf(PETSC_COMM_SELF, " [Global] X-Range: [ %11.4e , %11.4e ]\n", globalMin.x, globalMax.x);
2610 PetscPrintf(PETSC_COMM_SELF, " [Global] Y-Range: [ %11.4e , %11.4e ]\n", globalMin.y, globalMax.y);
2611 PetscPrintf(PETSC_COMM_SELF, " [Global] Z-Range: [ %11.4e , %11.4e ]\n", globalMin.z, globalMax.z);
2612 }
2613
2614 } else {
2615 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "LogFieldStatistics only supports fields with 1 or 3 components, but field '%s' has %" PetscInt_FMT ".", fieldName, dof);
2616 }
2617
2618 // --- 5. Final barrier for clean output ordering ---
2619 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRQ(ierr);
2620 if (user->simCtx->rank == 0) {
2621 PetscPrintf(PETSC_COMM_SELF, "--------------------------------------------\n\n");
2622 }
2623
2625 PetscFunctionReturn(0);
2626}
2627
2628/**
2629 * @brief Shared architecture-aware anatomy logger for catalog and transient fields.
2630 */
2631static PetscErrorCode LogFieldAnatomyView(UserCtx *user, const char *field_name,
2632 const char *stage_name, DM dm,
2633 Vec vec_local, PetscInt dof,
2634 FieldLayout layout)
2635{
2636 PetscErrorCode ierr;
2637 DMDALocalInfo info;
2638 PetscMPIInt rank;
2639 const char *data_layout = FieldLayoutName(layout);
2640 char dominant_dir = '\0'; // 'x', 'y', 'z' for face-centered, 'm' for mixed (Ucont)
2641
2642 PetscFunctionBeginUser;
2644 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
2645 PetscCheck(field_name != NULL && stage_name != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
2646 "Field and stage labels cannot be NULL.");
2647 PetscCheck(dm != NULL && vec_local != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
2648 "Field '%s' has no available DM/local vector for anatomy logging.", field_name);
2649 PetscCheck(dof == 1 || dof == 3, PETSC_COMM_SELF, PETSC_ERR_SUP,
2650 "Field anatomy logging supports one- or three-component fields; '%s' has %" PetscInt_FMT ".",
2651 field_name, dof);
2652 rank = user->simCtx->rank;
2653
2654 if (layout == FIELD_LAYOUT_I_FACE) dominant_dir = 'x';
2655 else if (layout == FIELD_LAYOUT_J_FACE) dominant_dir = 'y';
2656 else if (layout == FIELD_LAYOUT_K_FACE) dominant_dir = 'z';
2657 else if (layout == FIELD_LAYOUT_COMPONENT_STAGGERED) dominant_dir = 'm';
2658
2659 // --- 2. Get Grid Info and Array Pointers ---
2660 info = user->info; // dm is user->da or user->fda, which share one decomposition
2661
2662 ierr = PetscBarrier(NULL);
2663 PetscPrintf(PETSC_COMM_WORLD, "\n--- Field Anatomy Log: [%s] | Stage: [%s] | Layout: [%s] ---\n", field_name, stage_name, data_layout);
2664
2665 // Global physical dimensions (number of cells)
2666 PetscInt im_phys = user->IM;
2667 PetscInt jm_phys = user->JM;
2668 PetscInt km_phys = user->KM;
2669
2670 // Slice through the center of the local domain
2671 PetscInt i_mid = (PetscInt)(info.xs + 0.5 * info.xm) - 1;
2672 PetscInt j_mid = (PetscInt)(info.ys + 0.5 * info.ym) - 1;
2673 PetscInt k_mid = (PetscInt)(info.zs + 0.5 * info.zm) - 1;
2674
2675 // --- 3. Print Boundary Information based on Data Layout ---
2676
2677 // ======================================================================
2678 // === CASE 1: Cell-Centered Fields (Ucat, P) - USES SHIFTED INDEX ===
2679 // ======================================================================
2680 if (layout == FIELD_LAYOUT_CELL_CENTERED) {
2681 const void *l_arr;
2682 ierr = DMDAVecGetArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2683
2684
2685 // --- I-Direction Boundaries ---
2686 if (info.xs == 0) { // Rank on -Xi boundary
2687 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (Ghost for Cell[k][j][0]) = ", rank, 0);
2688 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][j_mid][0]);
2689 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][j_mid][0].x, ((const Cmpnts***)l_arr)[k_mid][j_mid][0].y, ((const Cmpnts***)l_arr)[k_mid][j_mid][0].z);
2690
2691 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (Value for Cell[k][j][0]) = ", rank, 1);
2692 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][j_mid][1]);
2693 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][j_mid][1].x, ((const Cmpnts***)l_arr)[k_mid][j_mid][1].y, ((const Cmpnts***)l_arr)[k_mid][j_mid][1].z);
2694 }
2695 if (info.xs + info.xm == info.mx) { // Rank on +Xi boundary
2696 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Value for Cell[k][j][%" PetscInt_FMT "]) = ", rank, im_phys - 1, im_phys - 2);
2697 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][j_mid][im_phys - 1]);
2698 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys - 1].x, ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys - 1].y, ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys - 1].z);
2699
2700 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Ghost for Cell[k][j][%" PetscInt_FMT "]) = ", rank, im_phys, im_phys - 2);
2701 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][j_mid][im_phys]);
2702 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys].x, ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys].y, ((const Cmpnts***)l_arr)[k_mid][j_mid][im_phys].z);
2703 }
2704
2705 // --- J-Direction Boundaries ---
2706 if (info.ys == 0) { // Rank on -Eta boundary
2707 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (Ghost for Cell[k][0][i]) = ", rank, 0);
2708 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][0][i_mid]);
2709 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][0][i_mid].x, ((const Cmpnts***)l_arr)[k_mid][0][i_mid].y, ((const Cmpnts***)l_arr)[k_mid][0][i_mid].z);
2710
2711 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (Value for Cell[k][0][i]) = ", rank, 1);
2712 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][1][i_mid]);
2713 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][1][i_mid].x, ((const Cmpnts***)l_arr)[k_mid][1][i_mid].y, ((const Cmpnts***)l_arr)[k_mid][1][i_mid].z);
2714 }
2715
2716 if (info.ys + info.ym == info.my) { // Rank on +Eta boundary
2717 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Value for Cell[k][%" PetscInt_FMT "][i]) = ", rank, jm_phys - 1, jm_phys - 2);
2718 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][jm_phys - 1][i_mid]);
2719 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][jm_phys - 1][i_mid].x, ((const Cmpnts***)l_arr)[k_mid][jm_phys - 1][i_mid].y, ((const Cmpnts***)l_arr)[k_mid][jm_phys - 1][i_mid].z);
2720
2721 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Ghost for Cell[k][%" PetscInt_FMT "][i]) = ", rank, jm_phys, jm_phys - 2);
2722 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[k_mid][jm_phys][i_mid]);
2723 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[k_mid][jm_phys][i_mid].x, ((const Cmpnts***)l_arr)[k_mid][jm_phys][i_mid].y, ((const Cmpnts***)l_arr)[k_mid][jm_phys][i_mid].z);
2724 }
2725
2726 // --- K-Direction Boundaries ---
2727 if (info.zs == 0) { // Rank on -Zeta boundary
2728 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (Ghost for Cell[0][j][i]) = ", rank, 0);
2729 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[0][j_mid][i_mid]);
2730 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[0][j_mid][i_mid].x, ((const Cmpnts***)l_arr)[0][j_mid][i_mid].y, ((const Cmpnts***)l_arr)[0][j_mid][i_mid].z);
2731 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (Value for Cell[0][j][i]) = ", rank, 1);
2732 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[1][j_mid][i_mid]);
2733 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[1][j_mid][i_mid].x, ((const Cmpnts***)l_arr)[1][j_mid][i_mid].y, ((const Cmpnts***)l_arr)[1][j_mid][i_mid].z);
2734 }
2735 if (info.zs + info.zm == info.mz) { // Rank on +Zeta boundary
2736 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Value for Cell[%" PetscInt_FMT "][j][i]) = ", rank, km_phys - 1, km_phys - 2);
2737 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[km_phys - 1][j_mid][i_mid]);
2738 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[km_phys - 1][j_mid][i_mid].x, ((const Cmpnts***)l_arr)[km_phys - 1][j_mid][i_mid].y, ((const Cmpnts***)l_arr)[km_phys - 1][j_mid][i_mid].z);
2739 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Ghost for Cell[%" PetscInt_FMT "][j][i]) = ", rank, km_phys, km_phys - 2);
2740 if(dof==1) PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f)\n", ((const PetscReal***)l_arr)[km_phys][j_mid][i_mid]);
2741 else PetscSynchronizedPrintf(PETSC_COMM_WORLD, "(%.5f, %.5f, %.5f)\n", ((const Cmpnts***)l_arr)[km_phys][j_mid][i_mid].x, ((const Cmpnts***)l_arr)[km_phys][j_mid][i_mid].y, ((const Cmpnts***)l_arr)[km_phys][j_mid][i_mid].z);
2742 }
2743 ierr = DMDAVecRestoreArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2744 }
2745 // ======================================================================
2746 // === CASE 2: Face-Centered Fields - NUANCED DIRECTIONAL LOGIC ===
2747 // ======================================================================
2748 else if (layout == FIELD_LAYOUT_I_FACE ||
2749 layout == FIELD_LAYOUT_J_FACE ||
2750 layout == FIELD_LAYOUT_K_FACE ||
2752 const Cmpnts ***l_arr;
2753 ierr = DMDAVecGetArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2754
2755 // --- I-Direction Boundaries ---
2756 if (info.xs == 0) { // Rank on -Xi boundary
2757 if (dominant_dir == 'x') { // Node-like in I-dir
2758 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (First Phys. X-Face) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][j_mid][0].x, l_arr[k_mid][j_mid][0].y, l_arr[k_mid][j_mid][0].z);
2759 } else if (dominant_dir == 'y' || dominant_dir == 'z') { // Cell-like in I-dir
2760 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (Ghost for Cell[k][j][0]) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][j_mid][0].x, l_arr[k_mid][j_mid][0].y, l_arr[k_mid][j_mid][0].z);
2761 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (Value for Cell[k][j][0]) = (%.5f, %.5f, %.5f)\n", rank, 1, l_arr[k_mid][j_mid][1].x, l_arr[k_mid][j_mid][1].y, l_arr[k_mid][j_mid][1].z);
2762 } else if (dominant_dir == 'm') { // Ucont: Mixed
2763 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: u-comp @ Idx %2d (1st X-Face) = %.5f\n", rank, 0, l_arr[k_mid][j_mid][0].x);
2764 }
2765 }
2766 if (info.xs + info.xm == info.mx) { // Rank on +Xi boundary
2767 if (dominant_dir == 'x') { // Node-like in I-dir
2768 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Last Phys. X-Face) = (%.5f, %.5f, %.5f)\n", rank, im_phys - 1, l_arr[k_mid][j_mid][im_phys - 1].x, l_arr[k_mid][j_mid][im_phys-1].y, l_arr[k_mid][j_mid][im_phys - 1].z);
2769 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Ghost Location) = (%.5f, %.5f, %.5f)\n", rank, im_phys, l_arr[k_mid][j_mid][im_phys].x, l_arr[k_mid][j_mid][im_phys].y, l_arr[k_mid][j_mid][im_phys].z);
2770 } else if (dominant_dir == 'y' || dominant_dir == 'z') { // Cell-like in I-dir
2771 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Value for Cell[k][j][%" PetscInt_FMT "]) = (%.5f, %.5f, %.5f)\n", rank, im_phys - 1, im_phys - 2, l_arr[k_mid][j_mid][im_phys - 1].x, l_arr[k_mid][j_mid][im_phys - 1].y, l_arr[k_mid][j_mid][im_phys-1].z);
2772 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Ghost for Cell[k][j][%" PetscInt_FMT "]) = (%.5f, %.5f, %.5f)\n", rank, im_phys, im_phys - 2, l_arr[k_mid][j_mid][im_phys].x, l_arr[k_mid][j_mid][im_phys].y, l_arr[k_mid][j_mid][im_phys].z);
2773 } else if (dominant_dir == 'm') { // Ucont: Mixed
2774 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: u-comp @ Idx %2" PetscInt_FMT " (Last X-Face) = %.5f\n", rank, im_phys - 1, l_arr[k_mid][j_mid][im_phys - 1].x);
2775 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: u-comp @ Idx %2" PetscInt_FMT " (Ghost Location) = %.5f\n", rank, im_phys, l_arr[k_mid][j_mid][im_phys].x);
2776 }
2777 }
2778
2779 // --- J-Direction Boundaries ---
2780 if (info.ys == 0) { // Rank on -Eta boundary
2781 if (dominant_dir == 'y') { // Node-like in J-dir
2782 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (First Phys. Y-Face) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][0][i_mid].x, l_arr[k_mid][0][i_mid].y, l_arr[k_mid][0][i_mid].z);
2783 } else if (dominant_dir == 'x' || dominant_dir == 'z') { // Cell-like in J-dir
2784 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (Ghost for Cell[k][0][i]) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][0][i_mid].x, l_arr[k_mid][0][i_mid].y, l_arr[k_mid][0][i_mid].z);
2785 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (Value for Cell[k][0][i]) = (%.5f, %.5f, %.5f)\n", rank, 1, l_arr[k_mid][1][i_mid].x, l_arr[k_mid][1][i_mid].y, l_arr[k_mid][1][i_mid].z);
2786 } else if (dominant_dir == 'm') { // Ucont: Mixed
2787 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: v-comp @ Jdx %2d (1st Y-Face) = %.5f\n", rank, 0, l_arr[k_mid][0][i_mid].y);
2788 }
2789 }
2790 if (info.ys + info.ym == info.my) { // Rank on +Eta boundary
2791 if (dominant_dir == 'y') { // Node-like in J-dir
2792 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Last Phys. Y-Face) = (%.5f, %.5f, %.5f)\n", rank, jm_phys - 1, l_arr[k_mid][jm_phys - 1][i_mid].x, l_arr[k_mid][jm_phys - 1][i_mid].y, l_arr[k_mid][jm_phys - 1][i_mid].z);
2793 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Ghost Location) = (%.5f, %.5f, %.5f)\n", rank, jm_phys, l_arr[k_mid][jm_phys][i_mid].x, l_arr[k_mid][jm_phys][i_mid].y, l_arr[k_mid][jm_phys][i_mid].z);
2794 } else if (dominant_dir == 'x' || dominant_dir == 'z') { // Cell-like in J-dir
2795 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Value for Cell[k][%" PetscInt_FMT "][i]) = (%.5f, %.5f, %.5f)\n", rank, jm_phys-1, jm_phys-2, l_arr[k_mid][jm_phys - 1][i_mid].x, l_arr[k_mid][jm_phys - 1][i_mid].y, l_arr[k_mid][jm_phys - 1][i_mid].z);
2796 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Ghost for Cell[k][%" PetscInt_FMT "][i]) = (%.5f, %.5f, %.5f)\n", rank, jm_phys, jm_phys-2, l_arr[k_mid][jm_phys][i_mid].x, l_arr[k_mid][jm_phys][i_mid].y, l_arr[k_mid][jm_phys][i_mid].z);
2797 } else if (dominant_dir == 'm') { // Ucont: Mixed
2798 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: v-comp @ Jdx %2" PetscInt_FMT " (Last Y-Face) = %.5f\n", rank, jm_phys - 1, l_arr[k_mid][jm_phys - 1][i_mid].y);
2799 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: v-comp @ Jdx %2" PetscInt_FMT " (Ghost Location) = %.5f\n", rank, jm_phys, l_arr[k_mid][jm_phys][i_mid].y);
2800 }
2801 }
2802
2803 // --- K-Direction Boundaries ---
2804 if (info.zs == 0) { // Rank on -Zeta boundary
2805 if (dominant_dir == 'z') { // Node-like in K-dir
2806 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (First Phys. Z-Face) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[0][j_mid][i_mid].x, l_arr[0][j_mid][i_mid].y, l_arr[0][j_mid][i_mid].z);
2807 } else if (dominant_dir == 'x' || dominant_dir == 'y') { // Cell-like in K-dir
2808 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (Ghost for Cell[0][j][i]) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[0][j_mid][i_mid].x, l_arr[0][j_mid][i_mid].y, l_arr[0][j_mid][i_mid].z);
2809 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (Value for Cell[0][j][i]) = (%.5f, %.5f, %.5f)\n", rank, 1, l_arr[1][j_mid][i_mid].x, l_arr[1][j_mid][i_mid].y, l_arr[1][j_mid][i_mid].z);
2810 } else if (dominant_dir == 'm') { // Ucont: Mixed
2811 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: w-comp @ Idx %2d (1st Z-Face) = %.5f\n", rank, 0, l_arr[0][j_mid][i_mid].z);
2812 }
2813 }
2814 if (info.zs + info.zm == info.mz) { // Rank on +Zeta boundary
2815 if (dominant_dir == 'z') { // Node-like in K-dir
2816 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Idx %2" PetscInt_FMT " (Last Phys. Z-Face) = (%.5f, %.5f, %.5f)\n", rank, km_phys - 1, l_arr[km_phys - 1][j_mid][i_mid].x, l_arr[km_phys - 1][j_mid][i_mid].y, l_arr[km_phys - 1][j_mid][i_mid].z);
2817 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Idx %2" PetscInt_FMT " (Ghost Location) = (%.5f, %.5f, %.5f)\n", rank, km_phys, l_arr[km_phys][j_mid][i_mid].x, l_arr[km_phys][j_mid][i_mid].y, l_arr[km_phys][j_mid][i_mid].z);
2818 } else if (dominant_dir == 'x' || dominant_dir == 'y') { // Cell-like in K-dir
2819 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Idx %2" PetscInt_FMT " (Value for Cell[%" PetscInt_FMT "][j][i]) = (%.5f, %.5f, %.5f)\n", rank, km_phys-1, km_phys-2, l_arr[km_phys-1][j_mid][i_mid].x, l_arr[km_phys-1][j_mid][i_mid].y, l_arr[km_phys - 1][j_mid][i_mid].z);
2820 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Idx %2" PetscInt_FMT " (Ghost for Cell[%" PetscInt_FMT "][j][i]) = (%.5f, %.5f, %.5f)\n", rank, km_phys, km_phys-2, l_arr[km_phys][j_mid][i_mid].x, l_arr[km_phys][j_mid][i_mid].y, l_arr[km_phys][j_mid][i_mid].z);
2821 } else if (dominant_dir == 'm') { // Ucont: Mixed
2822 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: w-comp @ Idx %2" PetscInt_FMT " (Last Z-Face) = %.5f\n", rank, km_phys - 1, l_arr[km_phys - 1][j_mid][i_mid].z);
2823 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: w-comp @ Idx %2" PetscInt_FMT " (Ghost Loc.) = %.5f\n", rank, km_phys, l_arr[km_phys][j_mid][i_mid].z);
2824
2825 }
2826 }
2827 ierr = DMDAVecRestoreArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2828 }
2829 // ======================================================================
2830 // === CASE 3: Node-Centered Fields - USES DIRECT INDEX ===
2831 // ======================================================================
2832 else if (layout == FIELD_LAYOUT_NODE_CENTERED) {
2833 if (dof == 1) {
2834 const PetscReal ***l_arr;
2835 ierr = DMDAVecGetArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2836
2837 if (info.xs == 0)
2838 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (First Phys. Node) = %.5f\n", rank, 0, l_arr[k_mid][j_mid][0]);
2839 if (info.xs + info.xm == info.mx) {
2840 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Last Phys. Node) = %.5f\n", rank, im_phys - 1, l_arr[k_mid][j_mid][im_phys - 1]);
2841 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Unused/Ghost Loc) = %.5f\n", rank, im_phys, l_arr[k_mid][j_mid][im_phys]);
2842 }
2843 if (info.ys == 0)
2844 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (First Phys. Node) = %.5f\n", rank, 0, l_arr[k_mid][0][i_mid]);
2845 if (info.ys + info.ym == info.my) {
2846 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Last Phys. Node) = %.5f\n", rank, jm_phys - 1, l_arr[k_mid][jm_phys - 1][i_mid]);
2847 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Unused/Ghost Loc) = %.5f\n", rank, jm_phys, l_arr[k_mid][jm_phys][i_mid]);
2848 }
2849 if (info.zs == 0)
2850 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (First Phys. Node) = %.5f\n", rank, 0, l_arr[0][j_mid][i_mid]);
2851 if (info.zs + info.zm == info.mz) {
2852 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Last Phys. Node) = %.5f\n", rank, km_phys - 1, l_arr[km_phys - 1][j_mid][i_mid]);
2853 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Unused/Ghost Loc) = %.5f\n", rank, km_phys, l_arr[km_phys][j_mid][i_mid]);
2854 }
2855 ierr = DMDAVecRestoreArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2856 } else {
2857 const Cmpnts ***l_arr;
2858 ierr = DMDAVecGetArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2859
2860 // --- I-Direction Boundaries ---
2861 if (info.xs == 0) {
2862 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2d (First Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][j_mid][0].x, l_arr[k_mid][j_mid][0].y, l_arr[k_mid][j_mid][0].z);
2863 }
2864 if (info.xs + info.xm == info.mx) {
2865 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Last Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, im_phys - 1, l_arr[k_mid][j_mid][im_phys - 1].x, l_arr[k_mid][j_mid][im_phys - 1].y, l_arr[k_mid][j_mid][im_phys - 1].z);
2866 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, I-DIR]: Idx %2" PetscInt_FMT " (Unused/Ghost Loc) = (%.5f, %.5f, %.5f)\n", rank, im_phys, l_arr[k_mid][j_mid][im_phys].x, l_arr[k_mid][j_mid][im_phys].y, l_arr[k_mid][j_mid][im_phys].z);
2867 }
2868 // --- J-Direction Boundaries ---
2869 if (info.ys == 0) {
2870 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2d (First Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[k_mid][0][i_mid].x, l_arr[k_mid][0][i_mid].y, l_arr[k_mid][0][i_mid].z);
2871 }
2872 if (info.ys + info.ym == info.my) {
2873 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Last Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, jm_phys - 1, l_arr[k_mid][jm_phys - 1][i_mid].x, l_arr[k_mid][jm_phys - 1][i_mid].y, l_arr[k_mid][jm_phys - 1][i_mid].z);
2874 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, J-DIR]: Jdx %2" PetscInt_FMT " (Unused/Ghost Loc) = (%.5f, %.5f, %.5f)\n", rank, jm_phys, l_arr[k_mid][jm_phys][i_mid].x, l_arr[k_mid][jm_phys][i_mid].y, l_arr[k_mid][jm_phys][i_mid].z);
2875 }
2876 // --- K-Direction Boundaries ---
2877 if (info.zs == 0) {
2878 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2d (First Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, 0, l_arr[0][j_mid][i_mid].x, l_arr[0][j_mid][i_mid].y, l_arr[0][j_mid][i_mid].z);
2879 }
2880 if(info.zs + info.zm == info.mz) {
2881 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Last Phys. Node) = (%.5f, %.5f, %.5f)\n", rank, km_phys - 1, l_arr[km_phys - 1][j_mid][i_mid].x, l_arr[km_phys - 1][j_mid][i_mid].y, l_arr[km_phys - 1][j_mid][i_mid].z);
2882 PetscSynchronizedPrintf(PETSC_COMM_WORLD, "[Rank %d, K-DIR]: Kdx %2" PetscInt_FMT " (Unused/Ghost Loc) = (%.5f, %.5f, %.5f)\n", rank, km_phys, l_arr[km_phys][j_mid][i_mid].x, l_arr[km_phys][j_mid][i_mid].y, l_arr[km_phys][j_mid][i_mid].z);
2883 }
2884 ierr = DMDAVecRestoreArrayRead(dm, vec_local, (void*)&l_arr); CHKERRQ(ierr);
2885 }
2886 }
2887 else {
2888 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
2889 "LOG_FIELD_ANATOMY encountered unsupported layout %d for field '%s'.",
2890 (int)layout, field_name);
2891 }
2892
2893 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
2894 ierr = PetscBarrier(NULL);
2896 PetscFunctionReturn(0);
2897}
2898
2899/**
2900 * @brief Resolves a persistent field view and emits its layout-aware boundary anatomy.
2901 * @see LOG_FIELD_ANATOMY()
2902 */
2903PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
2904{
2905 FieldView view;
2906
2907 PetscFunctionBeginUser;
2909 PetscCall(FieldGetView(user, field_id, &view));
2910 PetscCall(LogFieldAnatomyView(user, view.descriptor->canonical_name, stage_name,
2911 view.dm, view.local_vec, view.descriptor->dof,
2912 view.descriptor->layout));
2914 PetscFunctionReturn(0);
2915}
2916
2917/**
2918 * @brief Implementation of \ref IsStatisticsConsoleSnapshotEnabled().
2919 * @see IsStatisticsConsoleSnapshotEnabled()
2920 */
2922{
2924 const PetscBool enabled = (PetscBool)(FieldStatisticsIsActive(simCtx) &&
2925 simCtx->statisticsConsoleOutputFreq > 0 &&
2926 get_log_level() >= LOG_INFO);
2928 return enabled;
2929}
2930
2931/**
2932 * @brief Implementation of \ref ShouldEmitPeriodicStatisticsConsoleSnapshot().
2933 * @see ShouldEmitPeriodicStatisticsConsoleSnapshot()
2934 */
2935PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
2936{
2938 const PetscBool due = (PetscBool)(IsStatisticsConsoleSnapshotEnabled(simCtx) && completed_step >= 0 &&
2939 completed_step % simCtx->statisticsConsoleOutputFreq == 0);
2941 return due;
2942}
2943
2944/**
2945 * @brief Implementation of \ref EmitStatisticsConsoleSnapshot().
2946 * @see EmitStatisticsConsoleSnapshot()
2947 */
2948PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const SimCtx *simCtx, PetscInt step)
2949{
2950 PetscFunctionBeginUser;
2952 PetscCheck(simCtx != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL.");
2953 if (!IsStatisticsConsoleSnapshotEnabled(simCtx)) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
2954
2955 LOG(GLOBAL, LOG_INFO, "Statistics windows at step %" PetscInt_FMT " (%" PetscInt_FMT " window(s)):\n",
2956 step, simCtx->fieldStatisticsWindowCount);
2957 for (PetscInt w = 0; w < simCtx->fieldStatisticsWindowCount; ++w) {
2958 const PicurvWindow *window = &simCtx->fieldStatisticsWindows[w];
2959 char progress[16];
2960 char coverage[32] = "";
2961
2962 if (window->definition.bounded) {
2963 PetscCall(PetscSNPrintf(progress, sizeof(progress), "%5.1f%%",
2964 100.0 * (double)PicurvWindowProgress(window)));
2965 } else {
2966 PetscCall(PetscSNPrintf(progress, sizeof(progress), " open"));
2967 }
2968
2969 /* Mask health: with a moving body different points see different numbers of
2970 * states, and the spread of per-point valid fraction is what tells an
2971 * operator whether the window covers the domain evenly. Reported only on the
2972 * first block, since the reduction it performs is already collective. */
2973 if (user && user->fieldStatisticsStorage && window->sample_count > 0) {
2974 PetscReal lowest = 1.0, highest = 0.0;
2975
2976 PetscCall(PicurvWindowValidFractionRange(user, &window->definition,
2977 &user->fieldStatisticsStorage[w],
2978 window->sample_count, &lowest, &highest));
2979 PetscCall(PetscSNPrintf(coverage, sizeof(coverage), " valid=[%.2f,%.2f]",
2980 (double)lowest, (double)highest));
2981 }
2982
2984 " %-24s %-8s samples=%-8" PetscInt_FMT " weight=%-12.6g represented=%-12.6g progress=%s%s\n",
2985 window->definition.name, PicurvWindowStateName(window->state),
2986 window->sample_count, (double)window->total_weight,
2987 (double)window->represented_time, progress, coverage);
2988 }
2990 PetscFunctionReturn(0);
2991}
2992
2993/**
2994 * @brief Emits anatomy for the transient scalar or vector corner-staging field.
2995 * @see LOG_CORNER_FIELD_ANATOMY()
2996 */
2997PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name)
2998{
2999 FieldView view;
3000
3001 PetscFunctionBeginUser;
3003 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
3004 PetscCheck(corner_field_id == FIELD_ID_CELL_SCALAR_AT_CORNER ||
3005 corner_field_id == FIELD_ID_CELL_VECTOR_AT_CORNER,
3006 PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
3007 "Corner anatomy logging expects a corner-staging field identity.");
3008 /* The caller states which workspace it used, so the degree of freedom and DM
3009 * come from the catalog instead of being inferred from a cached vector. */
3010 PetscCall(FieldGetView(user, corner_field_id, &view));
3011 PetscCall(LogFieldAnatomyView(user, view.descriptor->canonical_name, stage_name, view.dm,
3012 view.local_vec, view.descriptor->dof,
3013 view.descriptor->layout));
3015 PetscFunctionReturn(0);
3016}
3017
3018/**
3019 * @brief Implementation of \ref LOG_INTERPOLATION_ERROR().
3020 * @details Full API contract (arguments, ownership, side effects) is documented with
3021 * the header declaration in `include/logging.h`.
3022 * @see LOG_INTERPOLATION_ERROR()
3023 */
3025{
3027 SimCtx *simCtx = user->simCtx;
3028 PetscErrorCode ierr;
3029 DM swarm = user->swarm;
3030 Vec positionVec, analyticalvelocityVec, velocityVec, errorVec;
3031 PetscReal Interpolation_error = 0.0;
3032 PetscReal Maximum_Interpolation_error = 0.0;
3033 PetscReal AnalyticalSolution_magnitude = 0.0;
3034 PetscReal ErrorPercentage = 0.0;
3035
3036 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Creating global vectors.\n");
3037 ierr = DMSwarmCreateGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), &positionVec); CHKERRQ(ierr);
3038 ierr = DMSwarmCreateGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), &velocityVec); CHKERRQ(ierr);
3039
3040 ierr = VecDuplicate(positionVec, &analyticalvelocityVec); CHKERRQ(ierr);
3041 ierr = VecCopy(positionVec, analyticalvelocityVec); CHKERRQ(ierr);
3042
3043 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Computing analytical solution.\n");
3044 ierr = SetAnalyticalSolutionForParticles(analyticalvelocityVec, simCtx); CHKERRQ(ierr);
3045
3046 ierr = VecDuplicate(analyticalvelocityVec, &errorVec); CHKERRQ(ierr);
3047 ierr = VecCopy(analyticalvelocityVec, errorVec); CHKERRQ(ierr);
3048
3049 ierr = VecNorm(analyticalvelocityVec, NORM_2, &AnalyticalSolution_magnitude); CHKERRQ(ierr);
3050
3051 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Computing error.\n");
3052 ierr = VecAXPY(errorVec, -1.0, velocityVec); CHKERRQ(ierr);
3053 ierr = VecNorm(errorVec, NORM_2, &Interpolation_error); CHKERRQ(ierr);
3054 ierr = VecNorm(errorVec,NORM_INFINITY,&Maximum_Interpolation_error); CHKERRQ(ierr);
3055
3056 ErrorPercentage = (AnalyticalSolution_magnitude > 0) ?
3057 (Interpolation_error / AnalyticalSolution_magnitude * 100.0) : 0.0;
3058
3059 /* --- CSV output (always, rank 0 only) --- */
3060 if (simCtx->rank == 0) {
3061 FILE *f = NULL;
3062 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "interpolation_error.csv",
3063 "step,time,L2_error,Linf_error,L2_analytical,error_pct,physical_time", PICURV_CSV_APPEND,
3064 PETSC_FALSE, &f); CHKERRQ(ierr);
3065 if (f) {
3066 /* ti is solver time, not a step count; physical_time is it in seconds. */
3067 PetscReal t = simCtx->ti;
3068 PetscReal physical_time = 0.0;
3069 ierr = PicurvPhysicalTime(simCtx, t, &physical_time); CHKERRQ(ierr);
3070 fprintf(f, "%d,%.6e,%.6e,%.6e,%.6e,%.4f,%.6e\n",
3071 (int)simCtx->step, t,
3072 Interpolation_error, Maximum_Interpolation_error,
3073 AnalyticalSolution_magnitude, ErrorPercentage, physical_time);
3074 fclose(f);
3075 }
3076 }
3077
3078 /* --- Console output (only at INFO level or above) --- */
3079 if (get_log_level() >= LOG_INFO) {
3080 LOG_ALLOW(GLOBAL, LOG_INFO, "Interpolation error (%%): %g\n", ErrorPercentage);
3081 PetscPrintf(PETSC_COMM_WORLD, "Interpolation error (%%): %g\n", ErrorPercentage);
3082 LOG_ALLOW(GLOBAL, LOG_INFO, "Maximum Interpolation error: %g\n", Maximum_Interpolation_error);
3083 PetscPrintf(PETSC_COMM_WORLD, "Maximum Interpolation error: %g\n", Maximum_Interpolation_error);
3084 }
3085
3086 ierr = VecDestroy(&analyticalvelocityVec); CHKERRQ(ierr);
3087 ierr = VecDestroy(&errorVec); CHKERRQ(ierr);
3088 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), &positionVec); CHKERRQ(ierr);
3089 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), &velocityVec); CHKERRQ(ierr);
3090
3092 return 0;
3093}
3094
3095/**
3096 * @brief Implementation of \ref LOG_SCATTER_METRICS().
3097 * @details Full API contract (arguments, ownership, side effects) is documented with
3098 * the header declaration in `include/logging.h`.
3099 * @see LOG_SCATTER_METRICS()
3100 */
3101PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
3102{
3103 PetscErrorCode ierr;
3104 SimCtx *simCtx = NULL;
3105 DMDALocalInfo info;
3106 PetscInt xs, xe, ys, ye, zs, ze, mx, my, mz;
3107 PetscInt lxs, lxe, lys, lye, lzs, lze;
3108 Vec reference_vec = NULL;
3109 PetscReal ***psi = NULL;
3110 PetscReal ***psi_ref = NULL;
3111 PetscReal ***aj = NULL;
3112 PetscReal ***count = NULL;
3113 PetscReal *particle_psi = NULL;
3114 PetscInt nlocal = 0;
3115 PetscReal local_l1 = 0.0, global_l1 = 0.0;
3116 PetscReal local_l2_sq = 0.0, global_l2_sq = 0.0;
3117 PetscReal local_linf = 0.0, global_linf = 0.0;
3118 PetscReal local_ref_l2_sq = 0.0, global_ref_l2_sq = 0.0;
3119 PetscReal local_grid_integral = 0.0, global_grid_integral = 0.0;
3120 PetscReal local_domain_volume = 0.0, global_domain_volume = 0.0;
3121 PetscReal local_particle_sum = 0.0, global_particle_sum = 0.0;
3122 PetscInt64 local_particle_count = 0, global_particle_count = 0;
3123 PetscInt64 local_cell_count = 0, global_cell_count = 0;
3124 PetscInt64 local_occupied_count = 0, global_occupied_count = 0;
3125 PetscReal particle_integral = 0.0;
3126 PetscReal occupancy_fraction = 0.0;
3127 PetscReal mean_particles_per_occupied_cell = 0.0;
3128 PetscReal l2_error = 0.0;
3129 PetscReal relative_l2_error = 0.0;
3130
3131 PetscFunctionBeginUser;
3133 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
3134 simCtx = user->simCtx;
3135 if (!VerificationScalarOverrideActive(simCtx) || !user->swarm || !user->Psi || !user->ParticleCount) {
3137 PetscFunctionReturn(0);
3138 }
3139
3140 info = user->info;
3141 xs = info.xs; xe = info.xs + info.xm;
3142 ys = info.ys; ye = info.ys + info.ym;
3143 zs = info.zs; ze = info.zs + info.zm;
3144 mx = info.mx; my = info.my; mz = info.mz;
3145 lxs = (xs == 0) ? xs + 1 : xs; lxe = (xe == mx) ? xe - 1 : xe;
3146 lys = (ys == 0) ? ys + 1 : ys; lye = (ye == my) ? ye - 1 : ye;
3147 lzs = (zs == 0) ? zs + 1 : zs; lze = (ze == mz) ? ze - 1 : ze;
3148
3149 ierr = VecDuplicate(user->Psi, &reference_vec); CHKERRQ(ierr);
3150 ierr = SetVerificationScalarAtCellCenters(user, reference_vec); CHKERRQ(ierr);
3151
3152 ierr = DMDAVecGetArrayRead(user->da, user->Psi, &psi); CHKERRQ(ierr);
3153 ierr = DMDAVecGetArrayRead(user->da, reference_vec, &psi_ref); CHKERRQ(ierr);
3154 ierr = DMDAVecGetArrayRead(user->da, user->Aj, &aj); CHKERRQ(ierr);
3155 ierr = DMDAVecGetArrayRead(user->da, user->ParticleCount, &count); CHKERRQ(ierr);
3156
3157 for (PetscInt k = lzs; k < lze; ++k) {
3158 for (PetscInt j = lys; j < lye; ++j) {
3159 for (PetscInt i = lxs; i < lxe; ++i) {
3160 const PetscReal cell_volume = (PetscAbsReal(aj[k][j][i]) > 1.0e-14) ? (1.0 / aj[k][j][i]) : 0.0;
3161 const PetscReal err = psi[k][j][i] - psi_ref[k][j][i];
3162 local_cell_count += 1;
3163 local_domain_volume += cell_volume;
3164 local_grid_integral += psi[k][j][i] * cell_volume;
3165 local_l1 += PetscAbsReal(err) * cell_volume;
3166 local_l2_sq += err * err * cell_volume;
3167 local_ref_l2_sq += psi_ref[k][j][i] * psi_ref[k][j][i] * cell_volume;
3168 local_linf = PetscMax(local_linf, PetscAbsReal(err));
3169 if (count[k][j][i] > 0.0) local_occupied_count += 1;
3170 }
3171 }
3172 }
3173
3174 ierr = DMDAVecRestoreArrayRead(user->da, user->ParticleCount, &count); CHKERRQ(ierr);
3175 ierr = DMDAVecRestoreArrayRead(user->da, user->Aj, &aj); CHKERRQ(ierr);
3176 ierr = DMDAVecRestoreArrayRead(user->da, reference_vec, &psi_ref); CHKERRQ(ierr);
3177 ierr = DMDAVecRestoreArrayRead(user->da, user->Psi, &psi); CHKERRQ(ierr);
3178 ierr = VecDestroy(&reference_vec); CHKERRQ(ierr);
3179
3180 ierr = DMSwarmGetLocalSize(user->swarm, &nlocal); CHKERRQ(ierr);
3181 local_particle_count = (PetscInt64)nlocal;
3182 if (nlocal > 0) {
3183 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&particle_psi); CHKERRQ(ierr);
3184 for (PetscInt p = 0; p < nlocal; ++p) local_particle_sum += particle_psi[p];
3185 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&particle_psi); CHKERRQ(ierr);
3186 }
3187
3188 ierr = MPI_Allreduce(&local_l1, &global_l1, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3189 ierr = MPI_Allreduce(&local_l2_sq, &global_l2_sq, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3190 ierr = MPI_Allreduce(&local_linf, &global_linf, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3191 ierr = MPI_Allreduce(&local_ref_l2_sq, &global_ref_l2_sq, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3192 ierr = MPI_Allreduce(&local_grid_integral, &global_grid_integral, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3193 ierr = MPI_Allreduce(&local_domain_volume, &global_domain_volume, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3194 ierr = MPI_Allreduce(&local_particle_sum, &global_particle_sum, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3195 ierr = MPI_Allreduce(&local_particle_count, &global_particle_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3196 ierr = MPI_Allreduce(&local_cell_count, &global_cell_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3197 ierr = MPI_Allreduce(&local_occupied_count, &global_occupied_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3198
3199 l2_error = PetscSqrtReal(global_l2_sq);
3200 relative_l2_error = (global_ref_l2_sq > 0.0) ? (l2_error / PetscSqrtReal(global_ref_l2_sq)) : 0.0;
3201 occupancy_fraction = (global_cell_count > 0) ? ((PetscReal)global_occupied_count / (PetscReal)global_cell_count) : 0.0;
3202 mean_particles_per_occupied_cell =
3203 (global_occupied_count > 0) ? ((PetscReal)global_particle_count / (PetscReal)global_occupied_count) : 0.0;
3204 particle_integral =
3205 (global_particle_count > 0) ? (global_domain_volume * global_particle_sum / (PetscReal)global_particle_count) : 0.0;
3206
3207 if (simCtx->rank == 0) {
3208 FILE *f = NULL;
3209 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "scatter_metrics.csv",
3210 "step,time,total_particles,total_cells,occupied_cells,occupancy_fraction,"
3211 "mean_particles_per_occupied_cell,particle_integral,grid_integral,"
3212 "conservation_error_abs,L1_error,L2_error,Linf_error,relative_L2_error,"
3213 "physical_time", PICURV_CSV_APPEND, PETSC_FALSE, &f); CHKERRQ(ierr);
3214 if (f) {
3215 PetscReal physical_time = 0.0;
3216 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time); CHKERRQ(ierr);
3217 fprintf(f, "%d,%.6e,%lld,%lld,%lld,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e\n",
3218 (int)simCtx->step,
3219 (double)simCtx->ti,
3220 (long long)global_particle_count,
3221 (long long)global_cell_count,
3222 (long long)global_occupied_count,
3223 (double)occupancy_fraction,
3224 (double)mean_particles_per_occupied_cell,
3225 (double)particle_integral,
3226 (double)global_grid_integral,
3227 (double)PetscAbsReal(global_grid_integral - particle_integral),
3228 (double)global_l1,
3229 (double)l2_error,
3230 (double)global_linf,
3231 (double)relative_l2_error,
3232 (double)physical_time);
3233 fclose(f);
3234 }
3235 }
3236
3237 if (get_log_level() >= LOG_INFO) {
3238 LOG_ALLOW(GLOBAL, LOG_INFO, "Scatter relative L2 error: %.6e\n", (double)relative_l2_error);
3239 LOG_ALLOW(GLOBAL, LOG_INFO, "Scatter occupancy fraction: %.6e\n", (double)occupancy_fraction);
3240 }
3241
3243 PetscFunctionReturn(0);
3244}
3245
3246/**
3247 * @brief Implementation of \ref ResetSearchMetrics().
3248 * @details Full API contract (arguments, ownership, side effects) is documented with
3249 * the header declaration in `include/logging.h`.
3250 * @see ResetSearchMetrics()
3251 */
3252PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
3253{
3254 PetscFunctionBeginUser;
3256 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL for ResetSearchMetrics.");
3257
3258 simCtx->searchMetrics.searchAttempts = 0;
3259 simCtx->searchMetrics.searchPopulation = 0;
3261 simCtx->searchMetrics.searchLostCount = 0;
3262 simCtx->searchMetrics.traversalStepsSum = 0;
3263 simCtx->searchMetrics.reSearchCount = 0;
3264 simCtx->searchMetrics.maxTraversalSteps = 0;
3266 simCtx->searchMetrics.tieBreakCount = 0;
3271 simCtx->searchMetrics.searchExitedCount = 0;
3273 simCtx->searchMetrics.reflectionCount = 0;
3275 simCtx->searchMetrics.wrapCount = 0;
3277
3279 PetscFunctionReturn(0);
3280}
3281
3282/**
3283 * @brief Implementation of \ref LOG_SEARCH_METRICS().
3284 * @details Full API contract (arguments, ownership, side effects) is documented with
3285 * the header declaration in `include/logging.h`.
3286 * @see LOG_SEARCH_METRICS()
3287 */
3288PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
3289{
3290 PetscErrorCode ierr;
3291 SimCtx *simCtx = NULL;
3292 PetscInt totalParticles = 0;
3293 PetscReal local_metrics[SEARCH_METRIC_REDUCTION_LEN] = {0.0};
3294 PetscReal global_metrics[SEARCH_METRIC_REDUCTION_LEN] = {0.0};
3295 PetscReal meanTraversalSteps = 0.0;
3296 PetscReal searchFailureFraction = 0.0;
3297 PetscReal searchWorkIndex = 0.0;
3298 PetscReal reSearchFraction = 0.0;
3299 long long searchAttempts = 0;
3300 long long searchPopulation = 0;
3301 long long searchLocatedCount = 0;
3302 long long searchLostCount = 0;
3303 long long traversalStepsSum = 0;
3304 long long reSearchCount = 0;
3305 long long tieBreakCount = 0;
3306 long long boundaryClampCount = 0;
3307 long long bboxGuessSuccessCount = 0;
3308 long long bboxGuessFallbackCount = 0;
3309 long long maxTraversalFailCount = 0;
3310 long long maxTraversalSteps = 0;
3311 long long maxPassDepth = 0;
3312 long long searchExitedCount = 0;
3313 long long blockedWalkRetryCount = 0;
3314 long long reflectionCount = 0;
3315 long long reflectionFallbackCount = 0;
3316 long long wrapCount = 0;
3317 MPI_Op reduction_op = MPI_OP_NULL;
3318
3319 PetscFunctionBeginUser;
3321 if (!user || !user->simCtx) {
3322 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx and SimCtx are required for LOG_SEARCH_METRICS.");
3323 }
3324 simCtx = user->simCtx;
3325
3326 if (!ParticlesEnabled(simCtx)) {
3328 PetscFunctionReturn(0);
3329 }
3330
3331 ierr = DMSwarmGetSize(user->swarm, &totalParticles); CHKERRQ(ierr);
3332
3333 local_metrics[SEARCH_METRIC_SUM_SEARCH_ATTEMPTS] = (PetscReal)simCtx->searchMetrics.searchAttempts;
3334 local_metrics[SEARCH_METRIC_SUM_SEARCH_POPULATION] = (PetscReal)simCtx->searchMetrics.searchPopulation;
3335 local_metrics[SEARCH_METRIC_SUM_SEARCH_LOCATED] = (PetscReal)simCtx->searchMetrics.searchLocatedCount;
3336 local_metrics[SEARCH_METRIC_SUM_SEARCH_LOST] = (PetscReal)simCtx->searchMetrics.searchLostCount;
3337 local_metrics[SEARCH_METRIC_SUM_TRAVERSAL_STEPS] = (PetscReal)simCtx->searchMetrics.traversalStepsSum;
3338 local_metrics[SEARCH_METRIC_SUM_RESEARCH] = (PetscReal)simCtx->searchMetrics.reSearchCount;
3339 local_metrics[SEARCH_METRIC_SUM_TIE_BREAKS] = (PetscReal)simCtx->searchMetrics.tieBreakCount;
3340 local_metrics[SEARCH_METRIC_SUM_BOUNDARY_CLAMPS] = (PetscReal)simCtx->searchMetrics.boundaryClampCount;
3344 local_metrics[SEARCH_METRIC_SUM_SEARCH_EXITED] = (PetscReal)simCtx->searchMetrics.searchExitedCount;
3345 local_metrics[SEARCH_METRIC_SUM_BLOCKED_RETRY] = (PetscReal)simCtx->searchMetrics.blockedWalkRetryCount;
3346 local_metrics[SEARCH_METRIC_SUM_REFLECTIONS] = (PetscReal)simCtx->searchMetrics.reflectionCount;
3348 local_metrics[SEARCH_METRIC_SUM_WRAPS] = (PetscReal)simCtx->searchMetrics.wrapCount;
3349 local_metrics[SEARCH_METRIC_MAX_TRAVERSAL_STEPS] = (PetscReal)simCtx->searchMetrics.maxTraversalSteps;
3350 local_metrics[SEARCH_METRIC_MAX_PASS_DEPTH] = (PetscReal)simCtx->searchMetrics.maxParticlePassDepth;
3351
3352 ierr = MPI_Op_create(SearchMetricsReduceOp, PETSC_TRUE, &reduction_op); CHKERRMPI(ierr);
3353 ierr = MPI_Allreduce(local_metrics, global_metrics, SEARCH_METRIC_REDUCTION_LEN, MPIU_REAL, reduction_op, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3354 ierr = MPI_Op_free(&reduction_op); CHKERRMPI(ierr);
3355 reduction_op = MPI_OP_NULL;
3356
3357 searchAttempts = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_ATTEMPTS] + 0.5);
3358 searchPopulation = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_POPULATION] + 0.5);
3359 searchLocatedCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_LOCATED] + 0.5);
3360 searchLostCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_LOST] + 0.5);
3361 traversalStepsSum = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_TRAVERSAL_STEPS] + 0.5);
3362 reSearchCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_RESEARCH] + 0.5);
3363 tieBreakCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_TIE_BREAKS] + 0.5);
3364 boundaryClampCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BOUNDARY_CLAMPS] + 0.5);
3365 bboxGuessSuccessCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_SUCCESS] + 0.5);
3366 bboxGuessFallbackCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_FALLBACK] + 0.5);
3367 maxTraversalFailCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_MAX_TRAVERSAL_FAILS] + 0.5);
3368 maxTraversalSteps = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_MAX_TRAVERSAL_STEPS] + 0.5);
3369 maxPassDepth = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_MAX_PASS_DEPTH] + 0.5);
3370 searchExitedCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_EXITED] + 0.5);
3371 blockedWalkRetryCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BLOCKED_RETRY] + 0.5);
3372 reflectionCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_REFLECTIONS] + 0.5);
3373 reflectionFallbackCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_REFLECTION_FALLBACKS] + 0.5);
3374 wrapCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_WRAPS] + 0.5);
3375
3376 if (searchAttempts > 0) {
3377 meanTraversalSteps = (PetscReal)traversalStepsSum / (PetscReal)searchAttempts;
3378 }
3379 if (searchPopulation > 0) {
3380 searchFailureFraction = (PetscReal)searchLostCount / (PetscReal)searchPopulation;
3381 searchWorkIndex = (PetscReal)traversalStepsSum / (PetscReal)searchPopulation;
3382 reSearchFraction = (PetscReal)reSearchCount / (PetscReal)searchPopulation;
3383 }
3384
3385 if (simCtx->rank == 0) {
3386 FILE *f = NULL;
3387 PetscReal searchPhysicalTime = 0.0;
3388
3389 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &searchPhysicalTime); CHKERRQ(ierr);
3390 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "search_metrics.csv",
3391 "step,time,total_particles,lost,lost_cumulative,migrated,migration_passes,search_attempts,"
3392 "mean_traversal_steps,max_traversal_steps,tie_break_count,boundary_clamp_count,"
3393 "bbox_guess_success_count,bbox_guess_fallback_count,max_particle_pass_depth,load_imbalance,"
3394 "search_population,search_located_count,search_lost_count,traversal_steps_sum,re_search_count,"
3395 "max_traversal_fail_count,search_failure_fraction,search_work_index,re_search_fraction,"
3396 "physical_time,lost_psi_sum,exited,exited_cumulative,exited_psi_sum,search_exited_count,"
3397 "blocked_walk_retry_count,reflections,reflection_fallbacks,wraps,occupied_cells,"
3398 "particles_per_cell_min,particles_per_cell_mean,particles_per_cell_max",
3399 PICURV_CSV_APPEND, PETSC_FALSE, &f); CHKERRQ(ierr);
3400 if (f) {
3401 fprintf(f,
3402 "%d,%.6e,%d,%d,%lld,%d,%d,%lld,%.6e,%lld,%lld,%lld,%lld,%lld,%lld,%.6e,%lld,%lld,%lld,%lld,%lld,%lld,%.6e,%.6e,%.6e,%.6e,%.10e,"
3403 "%d,%lld,%.10e,%lld,%lld,%lld,%lld,%lld,%d,%d,%.6e,%d\n",
3404 (int)simCtx->step,
3405 (double)simCtx->ti,
3406 (int)totalParticles,
3407 (int)simCtx->particlesLostLastStep,
3408 (long long)simCtx->particlesLostCumulative,
3409 (int)simCtx->particlesMigratedLastStep,
3410 (int)simCtx->migrationPassesLastStep,
3411 searchAttempts,
3412 (double)meanTraversalSteps,
3413 maxTraversalSteps,
3414 tieBreakCount,
3415 boundaryClampCount,
3416 bboxGuessSuccessCount,
3417 bboxGuessFallbackCount,
3418 maxPassDepth,
3419 (double)simCtx->particleLoadImbalance,
3420 searchPopulation,
3421 searchLocatedCount,
3422 searchLostCount,
3423 traversalStepsSum,
3424 reSearchCount,
3425 maxTraversalFailCount,
3426 (double)searchFailureFraction,
3427 (double)searchWorkIndex,
3428 (double)reSearchFraction,
3429 (double)searchPhysicalTime,
3430 (double)simCtx->particlesLostScalarLastStep,
3431 (int)simCtx->particlesExitedLastStep,
3432 (long long)simCtx->particlesExitedCumulative,
3433 (double)simCtx->particlesExitedScalarLastStep,
3434 searchExitedCount,
3435 blockedWalkRetryCount,
3436 reflectionCount,
3437 reflectionFallbackCount,
3438 wrapCount,
3439 (int)simCtx->occupiedCellCount,
3440 (int)simCtx->particlesPerCellMin,
3441 (double)simCtx->particlesPerCellMean,
3442 (int)simCtx->particlesPerCellMax);
3443 fclose(f);
3444 }
3445 }
3446
3447 // Boundary events, one line per step after the reduction rather than one message per particle.
3448 if (reflectionCount > 0 || blockedWalkRetryCount > 0 || wrapCount > 0) {
3449 LOG_ALLOW(GLOBAL, LOG_INFO, "Step %d boundary events: %lld wall reflections, %lld periodic wraps, %lld blocked walks searched again.\n",
3450 (int)simCtx->step, reflectionCount, wrapCount, blockedWalkRetryCount);
3451 }
3452 if (reflectionFallbackCount > 0) {
3453 LOG_ALLOW(GLOBAL, LOG_WARNING, "Step %d: %lld particles reached the reflection cap and were placed just inside their boundary cell.\n",
3454 (int)simCtx->step, reflectionFallbackCount);
3455 }
3456
3458 "Search metrics: sff=%.3e swi=%.3e re_search=%.3e lost(step/total)=%d/%lld exited(step/total)=%d/%lld blocked_retries=%lld migrated=%d passes=%d traversal(mean/max)=%.2f/%lld tie_breaks=%lld max_pass_depth=%lld\n",
3459 (double)searchFailureFraction,
3460 (double)searchWorkIndex,
3461 (double)reSearchFraction,
3462 (int)simCtx->particlesLostLastStep,
3463 (long long)simCtx->particlesLostCumulative,
3464 (int)simCtx->particlesExitedLastStep,
3465 (long long)simCtx->particlesExitedCumulative,
3466 blockedWalkRetryCount,
3467 (int)simCtx->particlesMigratedLastStep,
3468 (int)simCtx->migrationPassesLastStep,
3469 (double)meanTraversalSteps,
3470 maxTraversalSteps,
3471 tieBreakCount,
3472 maxPassDepth);
3473
3475 PetscFunctionReturn(0);
3476}
3477
3478/**
3479 * @brief Implementation of \ref CalculateAdvancedParticleMetrics().
3480 * @details Full API contract (arguments, ownership, side effects) is documented with
3481 * the header declaration in `include/logging.h`.
3482 * @see CalculateAdvancedParticleMetrics()
3483 */
3485{
3486 PetscErrorCode ierr;
3487 SimCtx *simCtx = user->simCtx;
3488 PetscMPIInt size;
3489
3490 PetscFunctionBeginUser;
3492 size = simCtx->size;
3493
3494 // --- 1. Particle Load Imbalance ---
3495 PetscInt nLocal, nGlobal, nLocalMax;
3496 ierr = DMSwarmGetLocalSize(user->swarm, &nLocal); CHKERRQ(ierr);
3497 ierr = DMSwarmGetSize(user->swarm, &nGlobal); CHKERRQ(ierr);
3498 ierr = MPI_Allreduce(&nLocal, &nLocalMax, 1, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
3499
3500 PetscReal avg_per_rank = (size > 0) ? ((PetscReal)nGlobal / size) : 0.0;
3501 // Handle division by zero if there are no particles
3502 simCtx->particleLoadImbalance = (avg_per_rank > 1e-9) ? (nLocalMax / avg_per_rank) : 1.0;
3503
3504
3505 // --- 2. Particles per Cell: Occupied Cells, Fewest, Mean, Most ---
3506 // ParticleCount stores cell c at index c + 1, so the physical cells are indices 1..m-2 on
3507 // each axis; a rank visits the ones in its owned index range, so each cell counts once.
3508 const DMDALocalInfo *info = &user->info;
3509 const PetscScalar ***count_array;
3510 PetscInt64 sums[3] = {0, 0, 0}; // occupied cells, particles, cells
3511 PetscInt64 extremes[2] = {PETSC_INT64_MAX, PETSC_INT64_MAX}; // fewest, -most
3512 const PetscInt i_lo = PetscMax(info->xs, 1), i_hi = PetscMin(info->xs + info->xm, info->mx - 1);
3513 const PetscInt j_lo = PetscMax(info->ys, 1), j_hi = PetscMin(info->ys + info->ym, info->my - 1);
3514 const PetscInt k_lo = PetscMax(info->zs, 1), k_hi = PetscMin(info->zs + info->zm, info->mz - 1);
3515
3516 ierr = DMDAVecGetArrayRead(user->da, user->ParticleCount, (void *)&count_array); CHKERRQ(ierr);
3517 for (PetscInt k = k_lo; k < k_hi; ++k) {
3518 for (PetscInt j = j_lo; j < j_hi; ++j) {
3519 for (PetscInt i = i_lo; i < i_hi; ++i) {
3520 const PetscInt64 n = (PetscInt64)(PetscRealPart(count_array[k][j][i]) + 0.5); // counts are whole numbers
3521 sums[0] += (n > 0);
3522 sums[1] += n;
3523 sums[2] += 1;
3524 extremes[0] = PetscMin(extremes[0], n);
3525 extremes[1] = PetscMin(extremes[1], -n);
3526 }
3527 }
3528 }
3529 ierr = DMDAVecRestoreArrayRead(user->da, user->ParticleCount, (void *)&count_array); CHKERRQ(ierr);
3530
3531 ierr = MPI_Allreduce(MPI_IN_PLACE, sums, 3, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3532 ierr = MPI_Allreduce(MPI_IN_PLACE, extremes, 2, MPIU_INT64, MPI_MIN, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3533 simCtx->occupiedCellCount = (PetscInt)sums[0];
3534 simCtx->particlesPerCellMin = (sums[2] > 0) ? (PetscInt)extremes[0] : 0;
3535 simCtx->particlesPerCellMax = (sums[2] > 0) ? (PetscInt)(-extremes[1]) : 0;
3536 simCtx->particlesPerCellMean = (sums[2] > 0) ? (PetscReal)sums[1] / (PetscReal)sums[2] : 0.0;
3537
3538 LOG_ALLOW(GLOBAL, LOG_INFO, "Advanced Metrics: Imbalance=%.2f, OccupiedCells=%" PetscInt_FMT ", ParticlesPerCell min/mean/max=%" PetscInt_FMT "/%.3f/%" PetscInt_FMT "\n",
3540 simCtx->particlesPerCellMin, (double)simCtx->particlesPerCellMean, simCtx->particlesPerCellMax);
3541
3543 PetscFunctionReturn(0);
3544}
3545
3546/**
3547 * @brief Implementation of \ref PicurvOpenRunCsv().
3548 * @details Full API contract is documented with the header declaration in
3549 * `include/logging.h`.
3550 * @see PicurvOpenRunCsv()
3551 */
3552PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header,
3553 PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
3554{
3555 char path[PETSC_MAX_PATH_LEN + 128];
3556 FILE *handle = NULL;
3557 uint64_t key = 0xCBF29CE484222325ULL; /* FNV-1a of the path */
3558 PetscBool first_write = PETSC_TRUE;
3559
3560 PetscFunctionBeginUser;
3562 PetscCheck(simCtx && dir && filename && header && file, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
3563 "A diagnostics CSV needs a context, a directory, a name, a header, and somewhere to "
3564 "return the handle.");
3565 *file = NULL;
3566
3567 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/%s", dir, filename));
3568 for (const char *c = path; *c; ++c) key = (key ^ (uint64_t)(unsigned char)*c) * 0x100000001B3ULL;
3569 for (PetscInt n = 0; n < simCtx->runCsvWrittenCount && first_write; ++n) {
3570 if (simCtx->runCsvWritten[n] == key) first_write = PETSC_FALSE;
3571 }
3572 PetscCheck(!first_write || simCtx->runCsvWrittenCount < PICURV_RUN_CSV_CAPACITY, PETSC_COMM_SELF, PETSC_ERR_PLIB,
3573 "A run writes more than %d CSV records; raise PICURV_RUN_CSV_CAPACITY.", PICURV_RUN_CSV_CAPACITY);
3574 handle = fopen(path, (lifecycle == PICURV_CSV_TRUNCATE_ON_FRESH && first_write && !simCtx->continueMode) ? "w" : "a");
3575 if (!handle) {
3576 PetscCheck(!required, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to open diagnostics file '%s'.", path);
3577 LOG_ALLOW(LOCAL, LOG_WARNING, "Could not open diagnostics file '%s'; its rows are not recorded.\n", path);
3579 PetscFunctionReturn(0);
3580 }
3581 if (first_write) simCtx->runCsvWritten[simCtx->runCsvWrittenCount++] = key;
3582
3583 if (ftell(handle) == 0) fprintf(handle, "%s\n", header);
3584 /* Written once per continuation, so that a reader can tell a resumed run from a jump in
3585 the data itself. */
3586 if (first_write && simCtx->continueMode) {
3587 fprintf(handle, "# Continuation from step %" PetscInt_FMT "\n", simCtx->StartStep);
3588 }
3589
3590 *file = handle;
3592 PetscFunctionReturn(0);
3593}
PetscErrorCode SetAnalyticalSolutionForParticles(Vec tempVec, SimCtx *simCtx)
Evaluates the analytical velocity at particle positions.
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.
FieldLayout
Logical storage topology of a field.
@ FIELD_LAYOUT_K_FACE
@ FIELD_LAYOUT_I_FACE
@ FIELD_LAYOUT_CELL_CENTERED
@ FIELD_LAYOUT_COMPONENT_STAGGERED
@ FIELD_LAYOUT_NODE_CENTERED
@ FIELD_LAYOUT_J_FACE
const char * canonical_name
const char * FieldLayoutName(FieldLayout layout)
Return a stable printable label for a field layout.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_CELL_SCALAR_AT_CORNER
@ FIELD_ID_CELL_VECTOR_AT_CORNER
Non-owning runtime objects resolved for one field and UserCtx.
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
static PetscErrorCode _ProfilingEventTotals(PetscLogEvent event, PetscLogDouble *time, int *count)
Read an event's running total time and call count on this rank (main stage).
Definition logging.c:2049
static void BuildHeaderString(char *headerStr, size_t bufSize, const int widths[6])
Definition logging.c:379
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Implementation of LOG_FIELD_MIN_MAX().
Definition logging.c:2501
const char * LESTestFilterKernelToString(LESTestFilterKernel kernel)
Implementation of LESTestFilterKernelToString().
Definition logging.c:727
PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const SimCtx *simCtx, PetscInt step)
Implementation of EmitStatisticsConsoleSnapshot().
Definition logging.c:2948
void set_allowed_functions(const char **functionList, int count)
Implementation of set_allowed_functions().
Definition logging.c:176
static PetscErrorCode AppendStatisticalObservableSample(SimCtx *simCtx, PetscInt samples_before, PetscReal mean_speed, PetscReal mean_ke)
Appends one timestep's scalar observables to the statistical history.
Definition logging.c:1476
static PetscErrorCode LogFieldAnatomyView(UserCtx *user, const char *field_name, const char *stage_name, DM dm, Vec vec_local, PetscInt dof, FieldLayout layout)
Shared architecture-aware anatomy logger for catalog and transient fields.
Definition logging.c:2631
PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
Implementation of PicurvOpenRunCsv().
Definition logging.c:3552
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Implementation of ShouldEmitPeriodicStatisticsConsoleSnapshot().
Definition logging.c:2935
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Implementation of BCHandlerTypeToString().
Definition logging.c:888
PetscBool is_function_allowed(const char *functionName)
Implementation of is_function_allowed().
Definition logging.c:207
const LogLevel *const _picurv_log_level
Read-only view of the cached logging level; -1 until the first get_log_level() call.
Definition logging.c:21
PetscErrorCode DualMonitorDestroy(void **ctx)
Implementation of DualMonitorDestroy().
Definition logging.c:927
static PetscErrorCode ComputeMaxColumnWidths(PetscInt nRows, const PetscInt *rows, const PetscMPIInt *ranks, const PetscInt64 *pids, const PetscInt *cellIDs, const PetscReal *positions, const PetscReal *velocities, const PetscReal *weights, int widths[6])
Definition logging.c:324
#define TMP_BUF_SIZE
Definition logging.c:10
static int _CompareProfiledFunctionRanks(const void *a, const void *b)
Order final-summary rows by their slowest rank's total time, descending.
Definition logging.c:2260
static char ** gAllowedFunctions
Global/static array of function names allowed to log.
Definition logging.c:28
void _ProfilingRegister(const char *func_name, PetscBool helper, PetscLogEvent *event)
Implementation of _ProfilingRegister().
Definition logging.c:1984
static LogLevel current_log_level
Static variable to cache the current logging level.
Definition logging.c:19
PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user)
Implementation of LOG_INTERPOLATION_ERROR().
Definition logging.c:3024
static PetscReal SolutionConvergenceHistoryGet(const PetscReal *history, PetscInt capacity, PetscInt samples_available, PetscInt offset_from_latest)
Reads one sample from the statistical ring buffer by age.
Definition logging.c:1438
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Implementation of ParticleBoundaryPolicyToString().
Definition logging.c:850
static PetscLogDouble * g_profile_step_time
Definition logging.c:1937
static PetscInt g_profile_nselected
Definition logging.c:1936
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Implementation of ShouldEmitPeriodicParticleConsoleSnapshot().
Definition logging.c:501
static char ** g_profile_selected
Definition logging.c:1935
const char * BCFaceToString(BCFace face)
Implementation of BCFaceToString().
Definition logging.c:640
static int * g_profile_step_count
Definition logging.c:1938
PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n)
Implementation of FreeAllowedFunctions().
Definition logging.c:619
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Implementation of IsParticleConsoleSnapshotEnabled().
Definition logging.c:484
PetscErrorCode print_log_level(void)
Implementation of print_log_level().
Definition logging.c:138
static PetscReal SolutionConvergenceSafeRelative(PetscReal numerator, PetscReal denominator)
Forms a guarded relative metric for solution-convergence logging.
Definition logging.c:1045
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Implementation of EmitParticleConsoleSnapshot().
Definition logging.c:518
static PetscInt g_profile_step_capacity
Definition logging.c:1939
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
Implementation of PrintProgressBar().
Definition logging.c:2446
PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
Implementation of ProfilingFinalize().
Definition logging.c:2380
static void trim(char *s)
Remove leading and trailing whitespace from a mutable configuration string.
Definition logging.c:534
PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[], char ***funcsOut, PetscInt *nOut)
Implementation of LoadAllowedFunctionsFromFile().
Definition logging.c:561
#define SOLUTION_CONVERGENCE_REL_EPS
Definition logging.c:1014
static PetscClassId g_profile_class_helper
Definition logging.c:1929
static int gNumAllowed
Number of entries in the gAllowedFunctions array.
Definition logging.c:33
static const char * SolutionConvergenceModeToString(SolutionConvergenceMode mode)
Maps the internal solution-convergence mode enum to its log label.
Definition logging.c:1693
static void BuildRowFormatString(const int widths[6], char *fmtStr, size_t bufSize)
Definition logging.c:367
static PetscBool g_profile_all_helpers
Definition logging.c:1932
const char * WallFunctionModelToString(WallFunctionModel model)
Implementation of WallFunctionModelToString().
Definition logging.c:786
static void CellToStr(const PetscInt *cell, char *buf, size_t bufsize)
Definition logging.c:301
PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
Implementation of RuntimeMemoryLogSample().
Definition logging.c:2170
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Implementation of ProfilingLogTimestepSummary().
Definition logging.c:2100
const char * LESFilterWidthModelToString(LESFilterWidthModel model)
Implementation of LESFilterWidthModelToString().
Definition logging.c:704
PetscErrorCode LOG_FACE_DISTANCES(PetscReal *d)
Implementation of LOG_FACE_DISTANCES().
Definition logging.c:256
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Implementation of LOG_PARTICLE_FIELDS().
Definition logging.c:399
static void TripleRealToStr(const PetscReal *arr, char *buf, size_t bufsize)
Definition logging.c:311
static PetscErrorCode _ProfilingSnapshotStep(void)
Record every event's running totals as the start of the next step.
Definition logging.c:2063
static void Int64ToStr(PetscInt64 value, char *buf, size_t bufsize)
Definition logging.c:291
const char * BCTypeToString(BCType type)
Implementation of BCTypeToString().
Definition logging.c:828
static PetscBool _ProfilingHelperEnabled(const char *name)
Whether a helper function's timer is enabled.
Definition logging.c:1953
static PetscBool _ProfilingNameListed(const char *name, char **names, PetscInt n)
Whether a name appears in a list of names.
Definition logging.c:1944
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Implementation of CalculateAdvancedParticleMetrics().
Definition logging.c:3484
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
Implementation of ParticleLocationStatusToString().
Definition logging.c:1905
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Implementation of LOG_SCATTER_METRICS().
Definition logging.c:3101
static PetscErrorCode _ProfilingEnsureStarted(void)
Register the two PICurv event classes and start PETSc's default log handler, once.
Definition logging.c:1963
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Implementation of LOG_SOLUTION_CONVERGENCE().
Definition logging.c:1714
PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx)
Implementation of DualKSPMonitor().
Definition logging.c:955
static PetscErrorCode _ProfilingReduceSection(FILE *f, const char *section, PetscInt nlocal, const char **names, const PetscLogDouble *times, const long long *counts)
Reduce one section of the final summary across ranks and print it on rank 0.
Definition logging.c:2278
PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user)
Implementation of LOG_CONTINUITY_METRICS().
Definition logging.c:1866
PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name)
Emits anatomy for the transient scalar or vector corner-staging field.
Definition logging.c:2997
const char * LESAveragingModeToString(LESAveragingMode mode)
Implementation of LESAveragingModeToString().
Definition logging.c:746
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
Resolves a persistent field view and emits its layout-aware boundary anatomy.
Definition logging.c:2903
static PetscErrorCode ComputeStatisticalWindowMetrics(const SimCtx *simCtx, PetscInt samples_available, PetscBool *has_reference_out, PetscReal *mean_speed_window_out, PetscReal *mean_speed_window_prev_out, PetscReal *mean_speed_window_abs_out, PetscReal *mean_speed_window_rel_out, PetscReal *mean_speed_rms_window_out, PetscReal *mean_speed_rms_window_prev_out, PetscReal *mean_speed_rms_window_abs_out, PetscReal *mean_speed_rms_window_rel_out, PetscReal *mean_ke_window_out, PetscReal *mean_ke_window_prev_out, PetscReal *mean_ke_window_abs_out, PetscReal *mean_ke_window_rel_out, PetscReal *mean_ke_rms_window_out, PetscReal *mean_ke_rms_window_prev_out, PetscReal *mean_ke_rms_window_abs_out, PetscReal *mean_ke_rms_window_rel_out)
Computes adjacent-window drift metrics for statistical steady mode.
Definition logging.c:1558
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Implementation of LOG_SEARCH_METRICS().
Definition logging.c:3288
const char * InterpolationMethodToString(InterpolationMethod method)
Implementation of InterpolationMethodToString().
Definition logging.c:869
const PetscBool *const _picurv_profile_helpers_on
Read-only view: whether profiling.helpers enables any helper timer.
Definition logging.c:1934
PetscErrorCode ProfilingInitialize(SimCtx *simCtx)
Implementation of ProfilingInitialize().
Definition logging.c:2015
static PetscClassId g_profile_class_function
Definition logging.c:1928
const char * LESModelToString(LESModelType LESFlag)
Implementation of LESModelToString().
Definition logging.c:682
PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank)
Implementation of LOG_CELL_VERTICES().
Definition logging.c:229
static void IntToStr(int value, char *buf, size_t bufsize)
Definition logging.c:281
LogLevel _ResolveLogLevel(void)
Implementation of _ResolveLogLevel().
Definition logging.c:101
static PetscErrorCode ComputeDeterministicSolutionMetrics(SimCtx *simCtx, PetscBool periodic_mode, PetscInt phase_step, PetscInt samples_before, PetscBool *has_reference_out, PetscReal *u_abs_l2_out, PetscReal *u_rel_l2_out, PetscReal *p_abs_l2_out, PetscReal *p_rel_l2_out, PetscReal *mean_speed_out, PetscReal *mean_speed_ref_out, PetscReal *mean_speed_abs_out, PetscReal *mean_speed_rel_out, PetscReal *mean_ke_out, PetscReal *mean_ke_ref_out, PetscReal *mean_ke_abs_out, PetscReal *mean_ke_rel_out)
Computes deterministic solution-drift metrics for the current step.
Definition logging.c:1193
PetscErrorCode ProfilingResetTimestepCounters(void)
Implementation of ProfilingResetTimestepCounters().
Definition logging.c:2087
PetscBool IsStatisticsConsoleSnapshotEnabled(const SimCtx *simCtx)
Implementation of IsStatisticsConsoleSnapshotEnabled().
Definition logging.c:2921
PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
Implementation of ResetSearchMetrics().
Definition logging.c:3252
const char * LESClipModeToString(LESClipMode mode)
Implementation of LESClipModeToString().
Definition logging.c:766
const char * MomentumSolverTypeToString(MomentumSolverType SolverFlag)
Implementation of MomentumSolverTypeToString().
Definition logging.c:808
static PetscBool _ProfilingIsPicurvClass(PetscClassId classid)
Whether a PETSc event belongs to one of PICurv's classes.
Definition logging.c:2004
@ SEARCH_METRIC_SUM_SEARCH_LOCATED
Definition logging.c:38
@ SEARCH_METRIC_SUM_WRAPS
Definition logging.c:51
@ SEARCH_METRIC_SUM_MAX_TRAVERSAL_FAILS
Definition logging.c:46
@ SEARCH_METRIC_REDUCTION_LEN
Definition logging.c:54
@ SEARCH_METRIC_SUM_BBOX_GUESS_FALLBACK
Definition logging.c:45
@ SEARCH_METRIC_SUM_RESEARCH
Definition logging.c:41
@ SEARCH_METRIC_SUM_SEARCH_EXITED
Definition logging.c:47
@ SEARCH_METRIC_SUM_REFLECTIONS
Definition logging.c:49
@ SEARCH_METRIC_SUM_TRAVERSAL_STEPS
Definition logging.c:40
@ SEARCH_METRIC_SUM_BLOCKED_RETRY
Definition logging.c:48
@ SEARCH_METRIC_MAX_TRAVERSAL_STEPS
Definition logging.c:52
@ SEARCH_METRIC_SUM_BOUNDARY_CLAMPS
Definition logging.c:43
@ SEARCH_METRIC_SUM_SEARCH_POPULATION
Definition logging.c:37
@ SEARCH_METRIC_MAX_PASS_DEPTH
Definition logging.c:53
@ SEARCH_METRIC_SUM_TIE_BREAKS
Definition logging.c:42
@ SEARCH_METRIC_SUM_SEARCH_LOST
Definition logging.c:39
@ SEARCH_METRIC_SUM_REFLECTION_FALLBACKS
Definition logging.c:50
@ SEARCH_METRIC_SUM_BBOX_GUESS_SUCCESS
Definition logging.c:44
@ SEARCH_METRIC_SUM_SEARCH_ATTEMPTS
Definition logging.c:36
static PetscErrorCode ComputeCurrentFlowObservables(SimCtx *simCtx, PetscReal *mean_speed_out, PetscReal *mean_ke_out)
Computes instantaneous global flow observables for statistical mode.
Definition logging.c:1075
#define SOLUTION_CONVERGENCE_FLUID_THRESHOLD
Definition logging.c:1013
static char ** g_profile_helpers
Definition logging.c:1930
static PetscBool g_profile_any_helpers
Definition logging.c:1933
const char * name
Definition logging.c:2241
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Implementation of ParticleInitializationToString().
Definition logging.c:662
static int _CompareNames(const void *a, const void *b)
Order C strings, for qsort over const char * arrays.
Definition logging.c:2252
static void SearchMetricsReduceOp(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype)
Internal reduction callback for packed search metrics.
Definition logging.c:61
static PetscInt g_profile_nhelpers
Definition logging.c:1931
Logging utilities and macros for PETSc-based applications.
Vec residual_work[2]
Definition logging.h:63
PicurvCsvLifecycle
What a run's first write does to an existing CSV record (see PicurvOpenRunCsv()).
Definition logging.h:1144
@ PICURV_CSV_TRUNCATE_ON_FRESH
A fresh run's first write empties the file; a continued run appends.
Definition logging.h:1146
@ PICURV_CSV_APPEND
Every run appends: earlier runs' rows are kept.
Definition logging.h:1145
PetscBool true_residual
Definition logging.h:59
PetscBool log_to_console
Definition logging.h:58
#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
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
PetscReal bnorm
Definition logging.h:60
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
PetscInt step
Definition logging.h:61
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
LogLevel
Enumeration of logging levels.
Definition logging.h:28
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ 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
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:62
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Context for a dual-purpose KSP monitor.
Definition logging.h:56
Typed identities and metadata for persistent solver-particle fields.
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_WEIGHT
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_PID
@ PARTICLE_FIELD_ID_CELL_ID
@ PARTICLE_FIELD_ID_PSI
@ PARTICLE_FIELD_ID_RANK
@ PARTICLE_FIELD_ID_VELOCITY
Per-window PETSc accumulator storage and pointwise application.
PetscErrorCode PicurvWindowValidFractionRange(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt sample_count, PetscReal *minimum, PetscReal *maximum)
Reports the range of per-point valid fraction across a window's domain.
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
PetscInt sample_count
PicurvWindowState state
PetscReal total_weight
const char * PicurvWindowStateName(PicurvWindowState state)
Returns a stable human-readable name for a window state.
PetscBool bounded
False for an open-ended window.
PicurvWindowDefinition definition
PetscBool FieldStatisticsIsActive(const struct SimCtx *simCtx)
Reports whether this run has live field-statistics state.
PetscReal PicurvWindowProgress(const PicurvWindow *window)
Reports the fraction of a bounded window's span that has been represented.
PetscReal represented_time
Physical time the window covers.
Runtime state of one window.
PetscInt particlesPerCellMin
Fewest particles in any cell after the step.
Definition variables.h:1069
LESModelType
Identifies the subgrid-scale closure evaluated during a timestep.
Definition variables.h:583
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
@ VREMAN
Definition variables.h:587
@ NO_LES_MODEL
Definition variables.h:584
@ WALE
Definition variables.h:588
@ CONSTANT_SMAGORINSKY
Definition variables.h:585
PetscInt particlesPerCellMax
Most particles in any cell after the step.
Definition variables.h:1070
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ INLET
Definition variables.h:323
@ INTERFACE
Definition variables.h:318
@ FARFIELD
Definition variables.h:324
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
PetscBool continueMode
Definition variables.h:935
UserCtx * user
Definition variables.h:768
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscMPIInt rank
Definition variables.h:919
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt64 reflectionCount
Definition variables.h:296
PetscInt statisticsConsoleOutputFreq
Definition variables.h:991
PetscInt block_number
Definition variables.h:1009
PetscInt64 searchLostCount
Definition variables.h:284
Vec * solutionConvergencePeriodicPRef
Definition variables.h:1209
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
ParticleInitializationType
Enumerator to identify the particle initialization strategy.
Definition variables.h:746
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
@ PARTICLE_INIT_POINT_SOURCE
All particles at a fixed (psrc_x,psrc_y,psrc_z) — for validation.
Definition variables.h:749
@ PARTICLE_INIT_VOLUME
Random volumetric distribution across the domain.
Definition variables.h:748
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
@ LOST
The search failed for a particle believed to be inside the domain.
Definition variables.h:190
@ NEEDS_LOCATION
Definition variables.h:187
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
@ UNINITIALIZED
Definition variables.h:191
@ MIGRATING_OUT
Definition variables.h:189
PetscReal * solutionConvergenceMeanSpeedHistory
Definition variables.h:985
PetscReal FluxOutSum
Definition variables.h:1016
PetscBool runtimeMemoryLogEnabled
Enable the rank-reduced runtime memory log (log_dir/Runtime_Memory.csv).
Definition variables.h:1123
PetscInt64 wrapCount
Definition variables.h:298
PetscInt64 boundaryClampCount
Definition variables.h:290
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
Definition variables.h:1057
PetscInt KM
Definition variables.h:1171
UserMG usermg
Definition variables.h:1082
Vec * solutionConvergencePeriodicUcatRef
Definition variables.h:1208
ParticleBoundaryPolicy
What happens to a particle that crosses a domain-boundary face.
Definition variables.h:336
@ PARTICLE_BOUNDARY_REMOVE
The particle leaves the domain (EXITED) and is removed.
Definition variables.h:337
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
@ PARTICLE_BOUNDARY_WRAP
Periodic faces: the particle re-enters through the paired face.
Definition variables.h:339
PetscInt64 traversalStepsSum
Definition variables.h:285
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_INTERFACE_OVERSET
Definition variables.h:353
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
@ BC_HANDLER_OUTLET_CONSERVATION
Definition variables.h:350
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
@ BC_HANDLER_FARFIELD_NONREFLECTING
Definition variables.h:349
@ BC_HANDLER_OUTLET_PRESSURE
Definition variables.h:351
@ BC_HANDLER_UNDEFINED
Definition variables.h:344
PetscInt solutionConvergenceSamplesRecorded
Definition variables.h:984
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscInt _this
Definition variables.h:1175
PetscInt64 searchPopulation
Definition variables.h:282
PetscBool solutionConvergenceEnabled
Definition variables.h:980
PetscReal * solutionConvergenceMeanKEHistory
Definition variables.h:986
PetscInt occupiedCellCount
Definition variables.h:1068
LESClipMode
Selects the admissible range imposed on the dynamic model coefficient.
Definition variables.h:652
@ LES_CLIP_CLIP_NEGATIVE
Definition variables.h:654
@ LES_CLIP_CLAMP
Definition variables.h:653
@ LES_CLIP_NONE
Definition variables.h:655
char profilingTimestepMode[32]
Definition variables.h:1106
LESTestFilterKernel
Selects the discrete test-filter kernel used by the dynamic procedure.
Definition variables.h:626
@ LES_TEST_FILTER_SIMPSON_IK
Definition variables.h:628
@ LES_TEST_FILTER_VOLUME_WEIGHTED_BOX
Definition variables.h:627
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
Definition variables.h:1143
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
@ WALL_FUNCTION_CABOT
Definition variables.h:604
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
@ WALL_FUNCTION_WERNER
Definition variables.h:603
@ WALL_FUNCTION_NONE
Definition variables.h:601
PetscInt currentSettlementPass
Definition variables.h:299
PetscInt64 searchExitedCount
Definition variables.h:294
PetscInt StartStep
Definition variables.h:926
MomentumSolverType
Enumerator to identify the implemented momentum solver strategies.
Definition variables.h:729
@ MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK
Definition variables.h:731
@ MOMENTUM_SOLVER_EXPLICIT_RK
Definition variables.h:730
@ MOMENTUM_SOLVER_NEWTON_KRYLOV
Definition variables.h:732
PetscInt solutionConvergencePeriodSteps
Definition variables.h:982
PetscScalar x
Definition variables.h:145
PetscInt64 reSearchCount
Definition variables.h:286
PetscReal MaxDiv
Definition variables.h:1096
PetscReal particlesExitedScalarLastStep
Sum of Psi over the particles that left the domain this step.
Definition variables.h:1062
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
Vec Ucat_o
Definition variables.h:1204
PetscInt MaxDivx
Definition variables.h:1097
PetscInt MaxDivy
Definition variables.h:1097
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
uint64_t runCsvWritten[256]
Rank 0 only: path hashes of the CSV records this run has opened (see PicurvOpenRunCsv()).
Definition variables.h:1124
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
PetscInt MaxDivz
Definition variables.h:1097
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt MaxDivFlatArg
Definition variables.h:1097
PetscReal FluxInSum
Definition variables.h:1016
PetscInt64 maxParticlePassDepth
Definition variables.h:293
PetscInt64 maxTraversalSteps
Definition variables.h:287
PetscInt64 particlesLostCumulative
Definition variables.h:1058
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
@ INTERP_TRILINEAR
Definition variables.h:761
Vec ParticleCount
Definition variables.h:1276
#define PICURV_RUN_CSV_CAPACITY
Most distinct CSV records one run opens through PicurvOpenRunCsv(): about twenty, plus a few per bloc...
Definition variables.h:75
PetscReal particlesPerCellMean
Particles counted in cells divided by the cell count.
Definition variables.h:1071
PetscInt JM
Definition variables.h:1171
LESAveragingMode
Selects the set over which the Germano contractions are averaged.
Definition variables.h:639
@ LES_AVERAGING_LOCAL
Definition variables.h:640
@ LES_AVERAGING_GLOBAL
Definition variables.h:642
@ LES_AVERAGING_HOMOGENEOUS
Definition variables.h:641
PetscBool runtimeMemoryLogHasPrevious
True after the first process-memory sample.
Definition variables.h:1126
PetscInt mglevels
Definition variables.h:775
char ** profilingSelectedFuncs
Definition variables.h:1101
PetscInt64 particlesExitedCumulative
Definition variables.h:1061
PetscInt solutionConvergenceWindowSteps
Definition variables.h:983
PetscInt particlesExitedLastStep
Particles removed this step because they left the domain.
Definition variables.h:1060
PetscInt nProfilingSelectedFuncs
Definition variables.h:1102
PetscInt particlesMigratedLastStep
Definition variables.h:1067
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
PetscInt particleConsoleOutputFreq
Definition variables.h:931
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscReal runtimeMemoryLogPreviousProcessMB
Previous local process memory sample in MB.
Definition variables.h:1127
PetscInt step
Definition variables.h:924
DMDALocalInfo info
Definition variables.h:1169
PetscInt migrationPassesLastStep
Definition variables.h:1066
PetscScalar y
Definition variables.h:145
PetscMPIInt size
Definition variables.h:920
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
PetscInt IM
Definition variables.h:1171
@ 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
@ RIGHT
Definition variables.h:197
PetscBool profilingAllHelpers
-profiling_helpers all: every helper timer is enabled.
Definition variables.h:1105
MGCtx * mgctx
Definition variables.h:778
SolutionConvergenceMode
Selects the runtime solution-convergence diagnostics mode.
Definition variables.h:738
@ SOLUTION_CONVERGENCE_TRANSIENT
Definition variables.h:742
@ SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC
Definition variables.h:740
@ SOLUTION_CONVERGENCE_STATISTICAL_STEADY
Definition variables.h:741
@ SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC
Definition variables.h:739
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
char ** profilingHelpers
Helper functions whose timers are enabled (-profiling_helpers).
Definition variables.h:1103
PetscReal particlesLostScalarLastStep
Sum of Psi over the particles removed this step as LOST.
Definition variables.h:1059
PetscInt64 searchAttempts
Definition variables.h:281
ExecutionMode exec_mode
Definition variables.h:937
PetscInt64 reflectionFallbackCount
Definition variables.h:297
PetscInt64 tieBreakCount
Definition variables.h:289
PetscReal ti
Definition variables.h:925
PetscInt64 blockedWalkRetryCount
Definition variables.h:295
PetscInt64 maxTraversalFailCount
Definition variables.h:288
PetscInt nProfilingHelpers
Definition variables.h:1104
LESFilterWidthModel
Selects how a cell's grid filter width is derived from its metrics.
Definition variables.h:614
@ LES_FILTER_WIDTH_SCOTTI
Definition variables.h:618
@ LES_FILTER_WIDTH_GEOMETRIC_MEAN
Definition variables.h:616
@ LES_FILTER_WIDTH_CUBE_ROOT_VOLUME
Definition variables.h:615
@ LES_FILTER_WIDTH_MAX_EDGE
Definition variables.h:617
PetscInt LoggingFrequency
Definition variables.h:1087
Cmpnts vertices[8]
Coordinates of the eight vertices of the cell.
Definition variables.h:219
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
Definition variables.h:1128
PetscReal particleLoadImbalance
Definition variables.h:1072
PetscInt runCsvWrittenCount
Entries of runCsvWritten in use.
Definition variables.h:1125
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
#define PICURV_SNAPSHOT_ROWS_PER_RANK
Most rows one rank contributes to a particle console snapshot (io.particle_log_interval samples IDs).
Definition variables.h:72
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
A 3D point or vector with PetscScalar components.
Definition variables.h:144
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.
PetscErrorCode SetVerificationScalarAtCellCenters(UserCtx *user, Vec targetVec)
Writes the configured verification scalar profile at physical cell centers into a scalar Vec.