PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
logging.h
Go to the documentation of this file.
1/**
2 * @file logging.h
3 * @brief Logging utilities and macros for PETSc-based applications.
4 *
5 * This header defines logging levels, scopes, and macros for consistent logging throughout the application.
6 * It provides functions to retrieve the current logging level and macros to simplify logging with scope control.
7 */
8
9#ifndef LOGGING_H
10#define LOGGING_H
11
12// Include necessary headers
13#include <petsc.h> // PETSc library header
14#include <stdlib.h>
15#include <string.h>
16#include <petscsys.h>
17#include <ctype.h>
18#include "variables.h"
19#include "statistics_window.h"
20#include "Boundaries.h"
21// --------------------- Logging Levels Definition ---------------------
22
23/**
24 * @brief Enumeration of logging levels.
25 *
26 * Defines various severity levels for logging messages.
27 */
28typedef enum {
29 LOG_ERROR = 0, /**< Critical errors that may halt the program */
30 LOG_WARNING, /**< Non-critical issues that warrant attention */
31 LOG_INFO, /**< Informational messages about program execution */
32 LOG_DEBUG, /**< Detailed debugging information */
33 LOG_TRACE, /**< Very fine-grained tracing information for in-depth debugging */
34 LOG_VERBOSE /**< Extremely detailed logs, typically for development use only */
36
37// -------------------- Logging Scope Definitions ------------------
38
39/**
40 * @brief Logging scope definitions for controlling message output.
41 *
42 * - LOCAL: Logs on the current process using MPI_COMM_SELF.
43 * - GLOBAL: Logs across all processes using MPI_COMM_WORLD.
44 */
45#define LOCAL 0 ///< Scope for local logging on the current process.
46#define GLOBAL 1 ///< Scope for global logging across all processes.
47
48//----------------------- Custom KSP Monitor Struct ------------
49
50/**
51 * @brief Context for a dual-purpose KSP monitor.
52 *
53 * Holds the rank-0 history file the monitor writes one CSV row per iteration to, whether the
54 * true residual is computed and echoed to the console, and the workspaces that computation keeps.
55 */
56typedef struct {
57 FILE *file_handle; // C file handling for logging.
58 PetscBool log_to_console; // Flag to enable console output.
59 PetscBool true_residual; // Compute the true residual each iteration (solver_monitoring.poisson.pic_true_residual).
60 PetscReal bnorm; // Stores the norm of the initial RHS vector.
61 PetscInt step; // Timestep
62 PetscInt block_id; // the ID of the block this monitor is for.
63 Vec residual_work[2]; // KSPBuildResidual() workspaces, created on first use and kept with the KSP.
65
66// --------------------- Logging Macros ---------------------
67
68/**
69 * @brief Logging macro for PETSc-based applications with scope control.
70 *
71 * This macro provides a convenient way to log messages with different scopes
72 * (LOCAL or GLOBAL) and severity levels. It utilizes PETSc's `PetscPrintf`
73 * function for message output.
74 *
75 * @param scope Specifies the logging scope:
76 * - LOCAL: Logs on the current process using MPI_COMM_SELF.
77 * - GLOBAL: Logs on all processes using MPI_COMM_WORLD.
78 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
79 * @param fmt The format string for the message (similar to printf).
80 * @param ... Additional arguments for the format string (optional).
81 *
82 * Example usage:
83 * LOG(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx);
84 * LOG(GLOBAL, LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);
85 */
86#define LOG(scope, level, fmt, ...) \
87 do { \
88 /* Determine the MPI communicator based on the scope */ \
89 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
90 /* Check if the log level is within the allowed range */ \
91 if ((int)(level) <= (int)get_log_level()) { \
92 /* Print the message to the specified communicator */ \
93 PetscPrintf(comm, fmt, ##__VA_ARGS__); \
94 } \
95 } while (0)
96
97/**
98 * @brief Default logging macro for PETSc-based applications.
99 *
100 * This macro simplifies logging by defaulting the scope to GLOBAL
101 * (i.e., `MPI_COMM_WORLD`) and providing a convenient interface for
102 * common logging needs.
103 *
104 * @param level The severity level of the message (e.g., LOG_ERROR, LOG_INFO).
105 * @param fmt The format string for the log message (similar to printf).
106 * @param ... Additional arguments for the format string (optional).
107 *
108 * Example usage:
109 * LOG_DEFAULT(LOG_ERROR, "Error occurred at index %ld.\n", idx);
110 * LOG_DEFAULT(LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);
111 *
112 * @note
113 * - By default, this macro logs across all MPI processes using `MPI_COMM_WORLD`.
114 * - If finer control (e.g., local logging) is required, use the more general `LOG` macro.
115 * - The log level is filtered based on the value returned by `get_log_level()`.
116 */
117#define LOG_DEFAULT(level, fmt, ...) \
118 do { \
119 /* Set the communicator to global (MPI_COMM_WORLD) by default */ \
120 MPI_Comm comm = MPI_COMM_WORLD; \
121 /* Check if the log level is within the allowed range */ \
122 if ((int)(level) <= (int)get_log_level()) { \
123 /* Print the message using PetscPrintf with the global communicator */ \
124 PetscPrintf(comm, fmt, ##__VA_ARGS__); \
125 } \
126 } while (0)
127
128/**
129 * @brief Logging macro for PETSc-based applications with scope control,
130 * using synchronized output across processes.
131 *
132 * This macro uses `PetscSynchronizedPrintf` and `PetscSynchronizedFlush` to
133 * ensure messages from different ranks are printed in a synchronized (rank-by-rank)
134 * manner, preventing interleaved outputs.
135 *
136 * @param scope Specifies the logging scope:
137 * - LOCAL: Logs on the current process using MPI_COMM_SELF.
138 * - GLOBAL: Logs on all processes using MPI_COMM_WORLD.
139 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
140 * @param fmt The format string for the message (similar to printf).
141 * @param ... Additional arguments for the format string (optional).
142 *
143 * Example usage:
144 * LOG_SYNC(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx);
145 * LOG_SYNC(GLOBAL, LOG_INFO, "Synchronized info: rank = %ld.\n", rank);
146 */
147#define LOG_SYNC(scope, level, fmt, ...) \
148 do { \
149 /* Determine the MPI communicator based on the scope */ \
150 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
151 /* Check if the log level is within the allowed range */ \
152 if ((int)(level) <= (int)get_log_level()) { \
153 /* Synchronized print (collective) on the specified communicator */ \
154 PetscSynchronizedPrintf(comm, fmt, ##__VA_ARGS__); \
155 /* Ensure all ranks have finished printing before continuing */ \
156 PetscSynchronizedFlush(comm, PETSC_STDOUT); \
157 } \
158 } while (0)
159
160/**
161 * @brief Default synchronized logging macro for PETSc-based applications.
162 *
163 * This macro simplifies logging by defaulting the scope to GLOBAL
164 * (i.e., `MPI_COMM_WORLD`) and provides synchronized output across
165 * all processes.
166 *
167 * @param level The severity level of the message (e.g., LOG_ERROR, LOG_INFO).
168 * @param fmt The format string for the log message (similar to printf).
169 * @param ... Additional arguments for the format string (optional).
170 *
171 * Example usage:
172 * LOG_SYNC_DEFAULT(LOG_ERROR, "Error at index %ld.\n", idx);
173 * LOG_SYNC_DEFAULT(LOG_INFO, "Process rank: %ld.\n", rank);
174 *
175 * @note
176 * - By default, this macro logs across all MPI processes using `MPI_COMM_WORLD`.
177 * - If local (per-process) logging is required, use the more general `LOG_SYNC` macro.
178 * - The log level is filtered based on the value returned by `get_log_level()`.
179 */
180#define LOG_SYNC_DEFAULT(level, fmt, ...) \
181 do { \
182 if ((int)(level) <= (int)get_log_level()) { \
183 PetscSynchronizedPrintf(MPI_COMM_WORLD, fmt, ##__VA_ARGS__); \
184 PetscSynchronizedFlush(MPI_COMM_WORLD, PETSC_STDOUT); \
185 } \
186 } while (0)
187
188
189
190/**
191 * @brief True when a code-level diagnostic at `level` prints from the calling function.
192 *
193 * The level must be admitted by the run's verbosity. A warning or an error then prints from
194 * any function, since an operator running at WARNING must see it; INFO and below print only
195 * from allow-listed functions, so instrumenting one function does not drag in the others.
196 * The value is the same on every rank.
197 */
198#define LOG_LEVEL_ADMITS(level) \
199 ((int)(level) <= (int)get_log_level() && ((int)(level) <= (int)LOG_WARNING || is_function_allowed(__func__)))
200
201/**
202 * @brief Logging macro that checks both the log level and whether the calling function
203 * is in the allowed-function list before printing. Useful for selective, per-function logging.
204 * Warnings and errors ignore the allow-list (see LOG_LEVEL_ADMITS()).
205 *
206 * @param scope Specifies the logging scope (LOCAL or GLOBAL).
207 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
208 * @param fmt The format string for the message (similar to printf).
209 * @param ... Additional arguments for the format string (optional).
210 *
211 * Example usage:
212 * LOG_ALLOW(LOCAL, LOG_DEBUG, "Debugging info in function: %s\n", __func__);
213 */
214#define LOG_ALLOW(scope, level, fmt, ...) \
215 do { \
216 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
217 if (LOG_LEVEL_ADMITS(level)) { \
218 PetscPrintf(comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
219 } \
220 } while (0)
221
222
223/* ------- DEBUG ------------------------------------------
224#define LOG_ALLOW(scope, level, fmt, ...) \
225 do { \
226 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
227 PetscInt __current_level_val = get_log_level(); \
228 PetscBool __allowed_func_val = is_function_allowed(__func__); \
229 // Print BEFORE the check \
230 if (strcmp(__func__, "LocateAllParticlesInGrid") == 0) { \
231 printf("[DEBUG LOG_ALLOW in %s] Checking: level=%d, get_log_level() returned %d, func_allowed=%d\n", \
232 __func__, (int)level, (int)__current_level_val, (int)__allowed_func_val); \
233 } \
234 if ((int)(level) <= (int)__current_level_val && __allowed_func_val) { \
235 // Print AFTER passing the check // \
236 if (strcmp(__func__, "LocateAllParticlesInGrid") == 0) { \
237 printf("[DEBUG LOG_ALLOW in %s] Check PASSED. Printing log.\n", __func__); \
238 } \
239 PetscPrintf(comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
240 } \
241 } while (0)
242-------------------------------------------------------------------------------
243*/
244
245/**
246 * @brief Synchronized logging macro that checks both the log level
247 * and whether the calling function is in the allow-list.
248 *
249 * This macro uses `PetscSynchronizedPrintf` and `PetscSynchronizedFlush` to
250 * ensure messages from different ranks are printed in a rank-ordered fashion
251 * (i.e., to avoid interleaving). It also filters out messages if the current
252 * function is not in the allow-list (`is_function_allowed(__func__)`) or the
253 * requested log level is higher than `get_log_level()`.
254 *
255 * With GLOBAL scope every rank prints its own line, in rank order, so the message should
256 * carry per-rank data; a value every rank shares belongs in `LOG_ALLOW(GLOBAL, ...)`, which
257 * prints it once. The flush is collective over the scope's communicator and runs only when
258 * the message is enabled. The level and the allow-list are the same on every rank, so either
259 * every rank of the communicator flushes or none does: a disabled message costs no
260 * communication. Every rank of that communicator must still reach the call.
261 *
262 * @param scope Either LOCAL (MPI_COMM_SELF) or GLOBAL (MPI_COMM_WORLD).
263 * @param level One of LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG, LOG_TRACE, LOG_VERBOSE.
264 * @param fmt A `printf`-style format string (e.g., "Message: %ld\n").
265 * @param ... Variadic arguments to fill in `fmt`.
266 *
267 * Example usage:
268 *
269 * \code{.c}
270 * LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "[Rank %d] owns %d cells\n", rank, ncells);
271 * \endcode
272 */
273#define LOG_ALLOW_SYNC(scope, level, fmt, ...) \
274do { \
275 /* ------------------------------------------------------------------ */ \
276 /* Validate scope and pick communicator *before* any early exits. */ \
277 /* ------------------------------------------------------------------ */ \
278 MPI_Comm _comm; \
279 if ((scope) == LOCAL) _comm = MPI_COMM_SELF; \
280 else if ((scope) == GLOBAL) _comm = MPI_COMM_WORLD; \
281 else { \
282 fprintf(stderr, "LOG_ALLOW_SYNC ERROR: invalid scope (%d) at %s:%d\n", \
283 (scope), __FILE__, __LINE__); \
284 MPI_Abort(MPI_COMM_WORLD, 1); \
285 } \
286 \
287 /* ------------------------------------------------------------------ */ \
288 /* Decide whether *this* rank should actually print. */ \
289 /* ------------------------------------------------------------------ */ \
290 PetscBool _doPrint = \
291 LOG_LEVEL_ADMITS(level); \
292 \
293 if (_doPrint) { \
294 PetscSynchronizedPrintf(_comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
295 /* Collective; _doPrint has the same value on every rank. */ \
296 PetscSynchronizedFlush(_comm, PETSC_STDOUT); \
297 } \
298} while (0)
299
300/**
301 * @brief True when `pid` is one of the run's traced particles (`simCtx->tracePIDs`, sorted).
302 * @param[in] simCtx The simulation context holding the traced IDs.
303 * @param[in] pid The particle ID to test.
304 * @return PETSC_TRUE when the particle is traced.
305 */
306static inline PetscBool ParticleIsTraced(const SimCtx *simCtx, PetscInt64 pid)
307{
308 PetscInt lo = 0, hi = simCtx->nTracePIDs - 1;
309 while (lo <= hi) {
310 const PetscInt mid = lo + (hi - lo) / 2;
311 if (simCtx->tracePIDs[mid] == pid) return PETSC_TRUE;
312 if (simCtx->tracePIDs[mid] < pid) lo = mid + 1;
313 else hi = mid - 1;
314 }
315 return PETSC_FALSE;
316}
317
318/** @brief True when the calling function's per-particle lines print for every particle (VERBOSE and allow-listed). */
319#define PARTICLE_LOG_VERBOSE_ENABLED() \
320 (PetscUnlikely((int)get_log_level() >= (int)LOG_VERBOSE) && is_function_allowed(__func__))
321
322/**
323 * @brief True when `pid` is traced (`monitor.yml -> logging.trace_particles`).
324 * @details A run that traces no particle pays one load and one compare; only a run that traces
325 * some searches the sorted list.
326 */
327#define PARTICLE_IS_TRACED(simCtx, pid) \
328 ((PetscBool)(PetscUnlikely((simCtx)->nTracePIDs > 0) && ParticleIsTraced((simCtx), (pid))))
329
330/**
331 * @brief True when LOG_PARTICLE() would print for this particle in the calling function.
332 * @details For a stage whose line is costly to assemble (several fields): test this, build the
333 * text, then emit it with LOG_PARTICLE().
334 */
335#define PARTICLE_LOG_ACTIVE(simCtx, pid) \
336 ((PetscBool)(PARTICLE_IS_TRACED((simCtx), (pid)) || PARTICLE_LOG_VERBOSE_ENABLED()))
337
338/**
339 * @brief Reports one particle at one stage of a step: the consolidated per-particle line.
340 *
341 * Each stage that processes particles (position update, location, interpolation, model
342 * update, removal) emits at most one such line per particle, carrying every value the stage
343 * computed for it. The line prints, on the rank holding the particle, when either
344 * - the particle is traced (`monitor.yml -> logging.trace_particles`), whatever the log level
345 * and allow-list, prefixed `[trace pid=<id> step=<n> <stage>]`; or
346 * - the log level is VERBOSE and the calling function is allow-listed, prefixed with the
347 * function name.
348 * With neither, it costs two loads and two compares.
349 *
350 * @param simCtx The simulation context (`const SimCtx *`).
351 * @param pid The particle ID (`PetscInt64`).
352 * @param stage A short stage label, such as "locate".
353 * @param fmt A `printf`-style format string ending in a newline.
354 */
355#define LOG_PARTICLE(simCtx, pid, stage, fmt, ...) \
356 do { \
357 const PetscBool _picurv_traced = PARTICLE_IS_TRACED((simCtx), (pid)); \
358 if (_picurv_traced || PARTICLE_LOG_VERBOSE_ENABLED()) { \
359 PetscPrintf(PETSC_COMM_SELF, "[%s pid=%lld step=%" PetscInt_FMT " %s] " fmt, \
360 _picurv_traced ? "trace" : __func__, (long long)(pid), (simCtx)->step, \
361 (stage), ##__VA_ARGS__); \
362 } \
363 } while (0)
364
365/**
366 * @brief Logs a message inside a loop, but only every `interval` iterations.
367 *
368 * @param scope LOCAL or GLOBAL.
369 * @param level LOG_* level.
370 * @param iterVar The loop variable (e.g., i).
371 * @param interval Only log when (iterVar % interval == 0).
372 * @param fmt printf-style format string.
373 * @param ... Variadic arguments to include in the formatted message.
374 *
375 * Example:
376 * for (int i = 0; i < 100; i++) {
377 * LOG_LOOP_ALLOW(LOCAL, LOG_DEBUG, i, 10, "Value of i=%d\n", i);
378 * }
379 */
380#define LOG_LOOP_ALLOW(scope, level, iterVar, interval, fmt, ...) \
381 do { \
382 if (LOG_LEVEL_ADMITS(level)) { \
383 if ((iterVar) % (interval) == 0) { \
384 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
385 PetscPrintf(comm, "[%s] [%s=%" PetscInt_FMT "] " fmt, \
386 __func__, #iterVar, (iterVar), ##__VA_ARGS__); \
387 } \
388 } \
389 } while (0)
390
391/**
392 * @brief Logs a custom message if a variable equals a specific value.
393 *
394 * This is a variadic macro for logging a single event when a condition is met.
395 * It is extremely useful for printing debug information at a specific iteration
396 * of a loop or when a state variable reaches a certain value.
397 *
398 * @param scope Either LOCAL or GLOBAL.
399 * @param level The logging level.
400 * @param var The variable to check (e.g., a loop counter 'k').
401 * @param val The value that triggers the log (e.g., 6). The log prints if var == val.
402 * @param fmt A printf-style format string.
403 * @param ... A printf-style format string and its corresponding arguments.
404 */
405#define LOG_LOOP_ALLOW_EXACT(scope, level, var, val, fmt, ...) \
406 do { \
407 /* First, perform the cheap, standard gatekeeper checks. */ \
408 if (LOG_LEVEL_ADMITS(level)) { \
409 /* Only if those pass, check the user's specific condition. */ \
410 if ((var) == (val)) { \
411 MPI_Comm comm = ((scope) == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
412 /* Print the standard prefix, then the user's custom message. */ \
413 PetscPrintf(comm, "[%s] [%s=%" PetscInt_FMT "] " fmt, \
414 __func__, #var, (var), ##__VA_ARGS__); \
415 } \
416 } \
417 } while (0)
418
419/**
420 * @brief Logs a single element of an array, given an index.
421 *
422 * @param scope Either LOCAL or GLOBAL.
423 * @param level LOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
424 * @param arr Pointer to the array to log from.
425 * @param length The length of the array (to prevent out-of-bounds).
426 * @param idx The index of the element to print.
427 * @param fmt The printf-style format specifier (e.g. "%g", "%f", etc.).
428 *
429 * This macro only logs if:
430 * 1) The current function is in the allow-list (`is_function_allowed(__func__)`).
431 * 2) The requested logging `level` <= the current global `get_log_level()`.
432 * 3) The index `idx` is valid (0 <= idx < length).
433 */
434#define LOG_ARRAY_ELEMENT_ALLOW(scope,level, arr, length, idx, fmt) \
435 do { \
436 if (LOG_LEVEL_ADMITS(level)) { \
437 if ((idx) >= 0 && (idx) < (length)) { \
438 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
439 PetscPrintf(comm, "[%s] arr[%" PetscInt_FMT "] = " fmt "\n", \
440 __func__, (PetscInt)(idx), (arr)[idx]); \
441 } \
442 } \
443 } while (0)
444
445/**
446 * @brief Logs a consecutive subrange of an array.
447 *
448 * @param scope Either LOCAL or GLOBAL.
449 * @param level LOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
450 * @param arr Pointer to the array to log from.
451 * @param length Total length of the array.
452 * @param start Starting index of the subrange.
453 * @param end Ending index of the subrange (inclusive).
454 * @param fmt The printf-style format specifier (e.g., "%g", "%f").
455 *
456 * This macro prints each element arr[i] for i in [start, end], bounded by [0, length-1].
457 */
458#define LOG_ARRAY_SUBRANGE_ALLOW(scope,level, arr, length, start, end, fmt) \
459 do { \
460 if (LOG_LEVEL_ADMITS(level)) { \
461 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
462 PetscInt _start = (start) < 0 ? 0 : (start); \
463 PetscInt _end = (end) >= (length) ? (length) - 1 : (end); \
464 for (PetscInt i = _start; i <= _end; i++) { \
465 PetscPrintf(comm, "[%s] arr[%" PetscInt_FMT "] = " fmt "\n", __func__, i, (arr)[i]); \
466 } \
467 } \
468 } while (0)
469
470// --------------------- Function Declarations ---------------------
471
472/**
473 * @brief Read-only view of the cached logging level; -1 until the first get_log_level() call.
474 * @details Only logging.c writes the level. The view lets get_log_level() be inlined into every
475 * logging macro, so a disabled message in a per-particle loop costs a load and a
476 * compare rather than a function call.
477 */
478extern const LogLevel *const _picurv_log_level;
479
480/**
481 * @brief Internal hook: read `LOG_LEVEL` from the environment and cache it, once.
482 * @details Supported levels are "ERROR", "WARNING", "INFO", "DEBUG", "TRACE", and "VERBOSE".
483 * Unset or unrecognized values default to "ERROR". Call get_log_level() instead.
484 * @return LogLevel The cached logging level.
485 */
487
488/**
489 * @brief Retrieves the current logging level from the environment variable `LOG_LEVEL`.
490 *
491 * The first call reads `LOG_LEVEL` (see _ResolveLogLevel()); every later call returns the
492 * cached value.
493 *
494 * @return LogLevel The current logging level.
495 */
496static inline LogLevel get_log_level(void)
497{
498 const LogLevel level = *_picurv_log_level;
499 return PetscLikely((int)level != -1) ? level : _ResolveLogLevel();
500}
501
502/**
503 * @brief Prints the current logging level to the console.
504 *
505 * This function retrieves the log level using `get_log_level()` and prints
506 * the corresponding log level name. It helps verify the logging configuration
507 * at runtime.
508 * The log levels supported are:
509 * - `LOG_ERROR` (0) : Logs only critical errors.
510 * - `LOG_WARNING` (1) : Logs warnings and errors.
511 * - `LOG_INFO` (2) : Logs general information, warnings, and errors.
512 * - `LOG_DEBUG` (3) : Logs debugging information, info, warnings, and errors.
513 * - `LOG_TRACE` (4) : Logs fine-grained trace information.
514 * - `LOG_VERBOSE` (5) : Logs very detailed developer output.
515 * If `LOG_LEVEL` is not set, it defaults to `LOG_ERROR`.
516 * @return PetscErrorCode 0 on success.
517 */
518PetscErrorCode print_log_level(void);
519
520/**
521 * @brief Sets the global list of function names that are allowed to log.
522 *
523 * You can replace the entire list of allowed function names at runtime.
524 *
525 * @param functionList Replacement array of permitted function names.
526 * @param count Number of entries in `functionList`.
527 */
528void set_allowed_functions(const char** functionList, int count);
529
530/**
531 * @brief Checks if a given function is in the allow-list.
532 *
533 * This helper is used internally by the LOG_ALLOW macro.
534 *
535 * @param functionName Function name to query.
536 * @return PETSC_TRUE when the name is enabled by the allow-list.
537 */
538PetscBool is_function_allowed(const char* functionName);
539
540/**
541 * @brief Prints the coordinates of a cell's vertices.
542 *
543 * This function iterates through the eight vertices of a given cell and prints their
544 * coordinates. It is primarily used for debugging purposes to verify the correctness
545 * of cell vertex assignments.
546 *
547 * @param[in] cell Pointer to a `Cell` structure representing the cell, containing its vertices.
548 * @param[in] rank MPI rank for identification (useful in parallel environments).
549 * @return PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
550 *
551 * @note
552 * - Ensure that the `cell` pointer is not `NULL` before calling this function..
553 */
554PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank);
555
556/**
557 * @brief Prints the signed distances to each face of the cell.
558 *
559 * This function iterates through the six signed distances from a point to each face of a given cell
560 * and prints their values. It is primarily used for debugging purposes to verify the correctness
561 * of distance calculations.
562 *
563 * @param[in] d An array of six `PetscReal` values representing the signed distances.
564 * The indices correspond to:
565 * - d[LEFT]: Left Face
566 * - d[RIGHT]: Right Face
567 * - d[BOTTOM]: Bottom Face
568 * - d[TOP]: Top Face
569 * - d[FRONT]: Front Face
570 * - d[BACK]: Back Face
571 *
572 * @return PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
573 *
574 * @note
575 * - Ensure that the `d` array is correctly populated with signed distances before calling this function.
576 */
577PetscErrorCode LOG_FACE_DISTANCES(PetscReal* d);
578
579/**
580 * @brief Prints particle fields in a table that automatically adjusts its column widths.
581 *
582 * Collective. A row is printed for each particle whose ID is a multiple of `printInterval`,
583 * at most PICURV_SNAPSHOT_ROWS_PER_RANK per rank, so successive snapshots show the same
584 * particles and the table's size does not grow with the swarm. Column widths are agreed
585 * across ranks; one header precedes every rank's rows, and a closing line states how many
586 * rows of how many particles were shown.
587 *
588 * @param[in] user Pointer to the UserCtx structure.
589 * @param[in] printInterval Sampling interval on particle IDs (values below 1 mean every particle).
590 *
591 * @return PetscErrorCode Returns 0 on success.
592 */
593PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx* user, PetscInt printInterval);
594
595/**
596 * @brief Returns whether periodic particle console snapshots are enabled.
597 *
598 * This checks only the reporting contract (particles exist, cadence is enabled,
599 * and the global log level is at least INFO).
600 *
601 * @param simCtx Simulation context controlling the operation (NULL means disabled).
602 * @return PETSC_TRUE when snapshots are enabled.
603 */
604PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx);
605
606/**
607 * @brief Returns whether a particle console snapshot should be emitted for the completed timestep.
608 *
609 * True when snapshots are enabled (IsParticleConsoleSnapshotEnabled()) and the positive
610 * `completed_step` is a multiple of the snapshot cadence.
611 *
612 * @param simCtx Simulation context controlling the operation.
613 * @param completed_step Completed step index used by the decision helper.
614 * @return PETSC_TRUE when a snapshot is due.
615 */
616PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step);
617
618/**
619 * @brief Emits one particle console snapshot into the main solver log.
620 *
621 * @param user Primary `UserCtx` input for the operation.
622 * @param simCtx Simulation context controlling the operation.
623 * @param step Step index associated with the operation.
624 * @return PetscErrorCode 0 on success.
625 */
626PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step);
627
628/**
629 * @brief Reports whether the periodic statistics console snapshot is enabled.
630 *
631 * Mirrors the particle console gate: the subsystem must be active, the configured
632 * cadence positive, and the effective log level at least `LOG_INFO`.
633 *
634 * @param[in] simCtx Simulation context to inspect.
635 * @return `PETSC_TRUE` when snapshots should be emitted.
636 */
637PetscBool IsStatisticsConsoleSnapshotEnabled(const struct SimCtx *simCtx);
638
639/**
640 * @brief Reports whether a completed step falls on the console snapshot cadence.
641 * @param[in] simCtx Simulation context to inspect.
642 * @param[in] completed_step Step that has just completed.
643 * @return `PETSC_TRUE` when a snapshot is due for this step.
644 */
645PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step);
646
647/**
648 * @brief Emits one console snapshot of window progress.
649 *
650 * Reports window-level scalars only; it never dumps field data.
651 *
652 * @param[in] user Finest-level block array supplying accumulator state.
653 * @param[in] simCtx Simulation context carrying the window array.
654 * @param[in] step Step the snapshot describes.
655 * @return Zero on success.
656 */
657PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step);
658
659/* ------------------------------------------------------------------------- */
660/**
661 * @brief Free an array previously returned by LoadAllowedFunctionsFromFile().
662 *
663 * @param[in,out] funcs Array of strings to release (may be @c NULL).
664 * @param[in] n Number of entries in @p funcs. Ignored if @p funcs is
665 * @c NULL.
666 *
667 * @return 0 on success or a PETSc error code.
668 */
669PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n);
670
671/**
672 * @brief Load function names from a text file.
673 *
674 * The file is expected to contain **one identifier per line**. Blank lines and
675 * lines whose first non‑blank character is a <tt>#</tt> are silently skipped so
676 * the file can include comments. Example:
677 *
678 * @code{.txt}
679 * # Allowed function list
680 * main
681 * InitializeSimulation
682 * InterpolateAllFieldsToSwarm # inline comments are OK, too
683 * @endcode
684 *
685 * The routine allocates memory as needed (growing an internal buffer with
686 * @c PetscRealloc()) and returns the resulting array and its length to the
687 * caller. Use FreeAllowedFunctions() to clean up when done.
688 *
689 * @param[in] filename Path of the configuration file to read.
690 * @param[out] funcsOut On success, points to a freshly‑allocated array of
691 * <tt>char*</tt> (size @p nOut).
692 * @param[out] nOut Number of valid entries in @p funcsOut.
693 *
694 * @return 0 on success, or a PETSc error code on failure (e.g. I/O error, OOM).
695 */
696PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[],
697 char ***funcsOut,
698 PetscInt *nOut);
699
700
701/**
702 * @brief Returns the canonical log token for a boundary-face enum value.
703 * @param[in] face The BCFace enum value.
704 * @return Pointer to a constant string representing the face.
705 */
706const char* BCFaceToString(BCFace face);
707
708/**
709 * @brief Returns the canonical log token for a particle-initialization mode.
710 * @param[in] ParticleInitialization The ParticleInitialization enum value.
711 * @return Pointer to a constant string representing the particle initialization type.
712 */
713const char* ParticleInitializationToString(ParticleInitializationType ParticleInitialization);
714
715/**
716 * @brief Returns the canonical log token for an LES model selector.
717 * @param[in] LESFlag The LES flag value.
718 * @return Pointer to a constant string representing the LES Flag.
719 */
720const char* LESModelToString(LESModelType LESFlag);
721
722/**
723 * @brief Returns the user-facing name of an LES grid-filter-width model.
724 * @param[in] model The filter-width model selector.
725 * @return Pointer to a constant string naming the model.
726 */
728
729/**
730 * @brief Returns the user-facing name of an LES test-filter kernel.
731 * @param[in] kernel The test-filter kernel selector.
732 * @return Pointer to a constant string naming the kernel.
733 */
735
736/**
737 * @brief Returns the user-facing name of an LES coefficient-averaging mode.
738 * @param[in] mode The averaging mode selector.
739 * @return Pointer to a constant string naming the mode.
740 */
742
743/**
744 * @brief Returns the user-facing name of an LES coefficient-limiting mode.
745 * @param[in] mode The limiting mode selector.
746 * @return Pointer to a constant string naming the mode.
747 */
748const char* LESClipModeToString(LESClipMode mode);
749
750/**
751 * @brief Returns the user-facing name of a wall-function model.
752 * @param[in] model The wall-model selector.
753 * @return Pointer to a constant string naming the model, or "none" when disabled.
754 */
756
757/**
758 * @brief Returns the canonical log token for a momentum-solver selector.
759 * @param[in] SolverFlag The Momentum Solver flag value.
760 * @return Pointer to a constant string representing the MomentumSolverType.
761 */
762const char* MomentumSolverTypeToString(MomentumSolverType SolverFlag);
763
764/**
765 * @brief Returns the canonical log token for a boundary mathematical type.
766 * @param[in] type The BCType enum value.
767 * @return Pointer to a constant string representing the BC type.
768 */
769const char* BCTypeToString(BCType type);
770
771/**
772 * @brief Returns the configuration token for a particle boundary policy.
773 * @param[in] policy The ParticleBoundaryPolicy enum value.
774 * @return Pointer to a constant string: "remove", "reflect" or "wrap".
775 */
777
778/**
779 * @brief Returns the display name of a grid-to-particle interpolation method.
780 * @param[in] method The InterpolationMethod enum value.
781 * @return Pointer to a constant string naming the method, as the banner and logs print it.
782 */
784
785/**
786 * @brief Converts a BCHandlerType enum to its string representation.
787 *
788 * Provides a descriptive string for a specific boundary condition implementation strategy.
789 * This is crucial for logging the exact behavior configured for a face.
790 *
791 * @param handler_type The BCHandlerType enum value (e.g., BC_HANDLER_WALL_NOSLIP).
792 * @return A constant character string corresponding to the enum. Returns
793 * "UNKNOWN_HANDLER" if the enum value is not recognized.
794 */
795const char* BCHandlerTypeToString(BCHandlerType handler_type);
796
797/**
798 * @brief A custom KSP monitor that logs to a file and optionally to the console.
799 *
800 * On rank 0 it writes one CSV row per iteration to the context's history file, when one is
801 * open, and prints the same values when `log_to_console` is set. When the context asks for the
802 * true residual it also computes the true and relative residual norms (collective).
803 *
804 * @param ksp The Krylov subspace context.
805 * @param it The current iteration number.
806 * @param rnorm The preconditioned residual norm.
807 * @param ctx A pointer to the DualMonitorCtx structure.
808 * @return PetscErrorCode 0 on success.
809 */
810PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx);
811
812/**
813 * @brief Destroys the DualMonitorCtx.
814 *
815 * This function is passed to KSPMonitorSet so that, when the KSP is destroyed, rank 0 closes
816 * any open history file and the residual workspaces and the context are freed.
817 * @param ctx a pointer to the context pointer to be destroyed
818 * @return PetscErrorCode
819 */
820PetscErrorCode DualMonitorDestroy(void **ctx);
821
822/**
823 * @brief Logs continuity metrics for a single block to a file.
824 *
825 * This function should be called for each block, once per timestep. Rank 0 appends one row
826 * per block to `<log_dir>/Continuity_Metrics.csv` (see PicurvOpenDiagnosticsCsv()); only
827 * block 0 may write a continued run's continuation marker, so the marker appears once.
828 *
829 * @param user A pointer to the UserCtx for the specific block whose metrics
830 * are to be logged. The function accesses both global (SimCtx)
831 * and local (user->...) data.
832 * @return PetscErrorCode 0 on success.
833 */
834PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user);
835
836/**
837 * @brief Logs physical solution-convergence metrics once per completed timestep.
838 *
839 * This logger is intentionally separate from the detailed inner solver-health
840 * logs. Depending on the configured mode, it records deterministic step drift,
841 * periodic phase-aligned drift, or statistical window drift into
842 * `<log_dir>/solution_convergence.csv`.
843 *
844 * The logger is solver-mode only and is intended to run after a completed
845 * flow-solve / projection step but before history vectors are shifted forward.
846 * Warmup rows are handled internally:
847 * - steady/transient mode: the first logged step has `has_reference = 0`
848 * - periodic mode: the first cycle fills the phase reference ring
849 * - statistical mode: window-drift fields remain zero until enough samples
850 * exist to form the requested windows
851 *
852 * Existing detailed inner logs remain the authoritative source for momentum,
853 * Poisson, and continuity health. This logger only summarizes physical
854 * solution-drift metrics.
855 *
856 * @param[in,out] simCtx Master simulation context controlling the logging mode
857 * and owning any supporting runtime buffers.
858 * @return PetscErrorCode 0 on success.
859 */
860PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx);
861
862/**
863 * @brief A function that outputs the name of the current level in the ParticleLocation enum.
864 * @param level The ParticleLocation enum value.
865 * @return A constant character string corresponding to the enum. Returns
866 * "UNKNOWN_LEVEL" if the enum value is not recognized.
867 */
869
870/*================================================================================*
871 * PROGRESS BAR UTILITY *
872 *================================================================================*/
873
874/**
875 * @brief Prints a progress bar to the console.
876 *
877 * This function should only be called by the root process (rank 0). It uses
878 * a carriage return `\r` to overwrite the same line in the terminal, creating
879 * a dynamic progress bar.
880 *
881 * @param step The current step index from the loop (e.g., from 0 to N-1).
882 * @param startStep The global starting step number of the simulation.
883 * @param totalSteps The total number of steps to be run in this simulation instance.
884 * @param currentTime The current simulation time to display.
885 * @param seconds_per_step Mean wall seconds per completed step, with the time left at that rate;
886 * omitted when not positive.
887 * @param lost_cumulative Particles lost so far in the run; omitted when negative.
888 */
889void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime,
890 PetscReal seconds_per_step, PetscInt64 lost_cumulative);
891
892/**
893 * @brief Applies the profiling configuration from SimCtx to PICurv's PETSc log events.
894 *
895 * Records the per-step `selected` function list and the enabled helper timers
896 * (`profiling.helpers`), and switches each helper event registered so far on or off to
897 * match. Starts PETSc's default log handler if nothing has yet. Called once from
898 * CreateSimulationContext(), before the main time loop.
899 *
900 * @param simCtx The master simulation context holding the profiling configuration; its
901 * name lists must outlive profiling.
902 * @return PetscErrorCode
903 */
904PetscErrorCode ProfilingInitialize(SimCtx *simCtx);
905
906/**
907 * @brief Starts a new per-step profiling interval.
908 *
909 * Records every PETSc event's running totals; the next ProfilingLogTimestepSummary()
910 * reports the difference. Cumulative totals are untouched.
911 *
912 * @return PetscErrorCode 0 on success.
913 */
914PetscErrorCode ProfilingResetTimestepCounters(void);
915
916/**
917 * @brief Logs the performance summary for the current timestep and resets timers.
918 *
919 * Depending on the configured profiling timestep mode, rank 0 writes per-step profiling rows to
920 * `<log_dir>/Profiling_Timestep_Summary.csv`, opened at its first row (see PicurvOpenRunCsv()):
921 * - `off`: writes nothing
922 * - `selected`: writes only functions marked for per-step reporting
923 * - `all`: writes every instrumented function that ran in the timestep
924 *
925 * It must be called once per timestep, typically at the end of the main loop. A step's
926 * values are the change in each PICurv event's PETSc running totals since the previous
927 * call (or ProfilingResetTimestepCounters()); an event still open, such as the enclosing
928 * time loop, adds its time only when it ends. Only rank 0 writes.
929 *
930 * @param simCtx The simulation context holding profiling output settings.
931 * @param step The current simulation step number, for logging context.
932 * @return PetscErrorCode
933 */
934PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step);
935
936/**
937 * @brief Append a reduced runtime memory sample to the configured memory log.
938 *
939 * The log is intentionally compact: every rank samples process/PETSc allocator
940 * memory, one max reduction summarizes the job, and rank 0 appends one CSV row to
941 * `<log_dir>/Runtime_Memory.csv`, which is appended to and never truncated.
942 *
943 * @param simCtx The simulation context holding log directory and memory log settings.
944 * @param step The solver/post step associated with the sample.
945 * @param event Human-readable event label such as "Step", "Post", "Shutdown", or "Final".
946 * @param reason Human-readable reason, or NULL/"-" when not applicable.
947 * @return PetscErrorCode
948 */
949PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason);
950
951
952/**
953 * @brief Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.
954 *
955 * Two sections: PICurv's events (aggregates, and helpers that were enabled), then PETSc's own
956 * events, whose inclusive times nest inside PICurv's. In each, the names any rank recorded are
957 * united by name, each name's total time is reduced to its maximum and minimum (with the ranks
958 * holding them) and its mean over ranks, and its calls are summed and reduced to their minimum
959 * and maximum per rank (with ranks), so a time spread can be told apart from a call-count spread.
960 * Rank 0 writes `ProfilingSummary_<mode>.csv` (`<mode>` is `Solver` or `PostProcessor`), slowest
961 * rank first; a continued run appends its totals after a continuation marker. This is the profiler's only
962 * communication; the timed path stays local to each rank.
963 *
964 * @param simCtx The Simulation Context Structure that can contains all the data regarding the simulation.
965 *
966 * @return PetscErrorCode 0 on success.
967 */
968PetscErrorCode ProfilingFinalize(SimCtx *simCtx);
969
970// --- Internal functions, do not call directly ---
971// Called by the macros below.
972/**
973 * @brief Internal profiling hook: register a call site's function as a PETSc log event.
974 * @details Called once per call site, on its first execution. Registers the PICurv event
975 * classes and starts PETSc's default log handler on the first call anywhere. A helper
976 * event is switched off as it registers unless its name is enabled
977 * (`profiling.helpers`). Before PetscInitialize, after PetscFinalize, or on failure, it
978 * registers nothing and the call site stays untimed, trying again on its next call.
979 * @param func_name Function name (`__func__`), the event's name.
980 * @param helper PETSC_TRUE for a per-particle or per-cell helper, PETSC_FALSE for an aggregate.
981 * @param event Call site's cached event; set when registration succeeds, else left at -1.
982 */
983void _ProfilingRegister(const char *func_name, PetscBool helper, PetscLogEvent *event);
984
985/**
986 * @brief Read-only view: whether `profiling.helpers` enables any helper timer.
987 * @details False until ProfilingInitialize() applies a non-empty list. While it is false every
988 * helper event is switched off, so PROFILE_HELPER_BEGIN skips PETSc's per-event check.
989 */
990extern const PetscBool *const _picurv_profile_helpers_on;
991
992/**
993 * @brief Marks the beginning of a profiled function: an always-on aggregate timer.
994 *
995 * Place this macro at the very beginning of a function called once or a few times per step
996 * or solver pass. The function is a PETSc log event of class `PICurv`, named by `__func__`,
997 * registered on its first call and cached in a function-local static; it appears in the
998 * final profiling summary, the per-step output and `log_view`.
999 */
1000#define PROFILE_FUNCTION_BEGIN \
1001 static PetscLogEvent _picurv_profile_event = -1; \
1002 if (PetscUnlikely(_picurv_profile_event < 0)) _ProfilingRegister(__func__, PETSC_FALSE, &_picurv_profile_event); \
1003 const PetscBool _picurv_profile_timed = (PetscBool)(_picurv_profile_event >= 0); \
1004 if (_picurv_profile_timed) (void)PetscLogEventBegin(_picurv_profile_event, 0, 0, 0, 0)
1005
1006/**
1007 * @brief Marks the beginning of a profiled helper: timed only when enabled by name.
1008 *
1009 * For functions called per particle or per cell. The event (class `PICurvHelper`) is off
1010 * unless `profiling.helpers` names it (or is `all`). With no helper enabled, a call costs one
1011 * flag test; with some enabled, PETSc's per-event check decides.
1012 * End it with PROFILE_FUNCTION_END (or its alias PROFILE_HELPER_END).
1013 */
1014#define PROFILE_HELPER_BEGIN \
1015 static PetscLogEvent _picurv_profile_event = -1; \
1016 if (PetscUnlikely(_picurv_profile_event < 0)) _ProfilingRegister(__func__, PETSC_TRUE, &_picurv_profile_event); \
1017 const PetscBool _picurv_profile_timed = (PetscBool)(*_picurv_profile_helpers_on && _picurv_profile_event >= 0); \
1018 if (_picurv_profile_timed) (void)PetscLogEventBegin(_picurv_profile_event, 0, 0, 0, 0)
1019
1020/**
1021 * @brief Marks the end of a profiled code block.
1022 *
1023 * Place this macro just before every return point in a function that starts with
1024 * PROFILE_FUNCTION_BEGIN or PROFILE_HELPER_BEGIN. A missed one leaves the PETSc event open,
1025 * and the function's later calls are then not recorded. It ends the event only if the BEGIN
1026 * macro began it, and reads the state that macro declares, so it must sit in that macro's
1027 * scope; a function that ends a timer it never began does not compile.
1028 */
1029#define PROFILE_FUNCTION_END \
1030 do { if (_picurv_profile_timed) (void)PetscLogEventEnd(_picurv_profile_event, 0, 0, 0, 0); } while (0)
1031
1032/** @brief Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN. */
1033#define PROFILE_HELPER_END PROFILE_FUNCTION_END
1034
1035
1036/**
1037 * @brief Computes and logs the local and global min/max values of a 3-component vector field.
1038 *
1039 * This utility function inspects a PETSc Vec associated with a DMDA and calculates the
1040 * minimum and maximum values for each of its three components (e.g., x, y, z) both for the
1041 * local data on the current MPI rank and for the entire global domain.
1042 *
1043 * It uses the same "smart" logic as the flow solver, ignoring the padding nodes at the
1044 * IM, JM, and KM boundaries of the grid. The results are printed to the standard output
1045 * in a formatted, easy-to-read table.
1046 *
1047 * @param[in] user Pointer to the user-defined context. Used for grid information (IM, JM, KM)
1048 * and MPI rank.
1049 * @param[in] field_id Typed identity of the field being analyzed.
1050 *
1051 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
1052 */
1053PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id);
1054
1055/**
1056 * @brief Logs the anatomy of a specified field at key boundary locations,
1057 * respecting the solver's specific grid and variable architecture.
1058 *
1059 * This intelligent diagnostic function inspects a PETSc Vec and prints its values
1060 * at critical boundary locations (-Xi/+Xi, -Eta/+Eta, -Zeta/+Zeta). It is "architecture-aware":
1061 *
1062 * - **Cell-Centered Fields ("Ucat", "P"):** It correctly applies the "Shifted Index Architecture,"
1063 * where the value for geometric `Cell i` is stored at array index `i+1`. It labels
1064 * the output to clearly distinguish between true physical values and ghost values.
1065 * - **Single-Face-Family Fields:** `Csi/ICsi/IEta/IZet/Centx` belong to the
1066 * I-face family, with corresponding J- and K-face families.
1067 * - **Component-Staggered Fields ("Ucont" and histories):** x/y/z components
1068 * live on I/J/K faces respectively.
1069 * - **Node-Centered Fields ("Coordinates"):** It uses a direct index mapping, where the value for
1070 * `Node i` is stored at index `i`.
1071 *
1072 * The output is synchronized across MPI ranks to ensure readability and focuses on a
1073 * slice through the center of the domain to be concise.
1074 *
1075 * @param user A pointer to the UserCtx structure containing the DMs and Vecs.
1076 * @param field_id Typed identity of the persistent Eulerian field to log.
1077 * @param stage_name A string identifier for the current simulation stage (e.g., "After Advection").
1078 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
1079 */
1080PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name);
1081
1082/**
1083 * @brief Logs the node-layout anatomy of the transient center-to-corner interpolation field.
1084 * @param user Context owning the corner-staging workspace.
1085 * @param corner_field_id Which corner workspace the caller populated.
1086 * @param stage_name Printable simulation stage.
1087 * @return Zero on success.
1088 */
1089PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name);
1090
1091/**
1092 * @brief Logs the interpolation error between the analytical and computed solutions.
1093 *
1094 * @param user Primary `UserCtx` input for the operation.
1095 * @return PetscErrorCode 0 on success.
1096 */
1097PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user);
1098
1099/**
1100 * @brief Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
1101 *
1102 * @param user Primary `UserCtx` input for the operation.
1103 * @return PetscErrorCode 0 on success.
1104 */
1105PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user);
1106
1107/**
1108 * @brief Resets the aggregate per-timestep search instrumentation counters.
1109 *
1110 * @param simCtx Simulation context whose search metrics should be zeroed.
1111 * @return PetscErrorCode 0 on success.
1112 */
1113PetscErrorCode ResetSearchMetrics(SimCtx *simCtx);
1114
1115/**
1116 * @brief Computes advanced particle statistics and stores them in SimCtx.
1117 *
1118 * This function calculates:
1119 * - Particle load imbalance across MPI ranks.
1120 * - The total number of grid cells occupied by at least one particle.
1121 * - The fewest, mean, and most particles per cell over the physical cells.
1122 *
1123 * It requires that CalculateParticleCountPerCell() has been called prior to its
1124 * execution. It uses collective MPI operations and must be called by all ranks.
1125 *
1126 * @param user Pointer to the UserCtx.
1127 * @return PetscErrorCode 0 on success.
1128 */
1129PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user);
1130
1131/**
1132 * @brief Writes compact runtime search metrics to CSV and optionally to console.
1133 *
1134 * The CSV artifact is always written for particle-enabled runs. Console output
1135 * remains gated by normal logging level and function allow-listing.
1136 *
1137 * @param user Pointer to the UserCtx.
1138 * @return PetscErrorCode 0 on success.
1139 */
1140PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user);
1141
1142
1143/** @brief What a run's first write does to an existing CSV record (see PicurvOpenRunCsv()). */
1144typedef enum {
1145 PICURV_CSV_APPEND = 0, /**< Every run appends: earlier runs' rows are kept. */
1146 PICURV_CSV_TRUNCATE_ON_FRESH /**< A fresh run's first write empties the file; a continued run appends. */
1148
1149/**
1150 * @brief Opens one of the run's CSV records (diagnostics, solver history, profiling) for writing.
1151 *
1152 * The record lives in `dir`: the run's analysis directory (`simCtx->analysis_dir`) or log
1153 * directory (`simCtx->log_dir`). This owns the file's lifecycle; the caller owns the columns:
1154 * - `header` (starting `step,` or `section,`) is written whenever the file is empty, so it
1155 * appears once, at the top;
1156 * - on the run's first open of the file, whenever it falls, a `PICURV_CSV_TRUNCATE_ON_FRESH`
1157 * record is emptied first unless the run is a continuation (`simCtx->continueMode`), and a
1158 * continuation writes `# Continuation from step <StartStep>`, so a reader can tell a resumed
1159 * run from a discontinuity in the data. Every other call appends.
1160 *
1161 * The run's first open is tracked here, by path, in `simCtx->runCsvWritten`, so a record
1162 * written at the output cadence, from step 0, or by several calls in one step needs no flag
1163 * of its own.
1164 *
1165 * Call on rank 0 only - the file is a serial artifact, and a collective write to it would
1166 * interleave. The caller closes the handle.
1167 *
1168 * @param[in,out] simCtx Simulation context supplying the continuation state and `StartStep`, and
1169 * recording the files the run has opened.
1170 * @param[in] dir Directory of the file.
1171 * @param[in] filename Basename of the CSV, including the extension.
1172 * @param[in] header Column header written to an empty file, without a trailing newline.
1173 * @param[in] lifecycle Whether a fresh run's first write empties the file.
1174 * @param[in] required PETSC_TRUE: a file that cannot be opened is an error. PETSC_FALSE: it
1175 * is a warning and `*file` is NULL, for a diagnostic whose loss must not
1176 * stop or change the run.
1177 * @param[out] file Open handle positioned at the end of the file; NULL only when
1178 * `required` is false and the file could not be opened.
1179 * @return PetscErrorCode 0 on success; `PETSC_ERR_FILE_OPEN` if a required file cannot be opened.
1180 */
1181PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header,
1182 PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file);
1183
1184/**
1185 * @brief Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
1186 *
1187 * For a record written every step and kept across runs: `PICURV_CSV_APPEND`, and a file that
1188 * cannot be opened is an error.
1189 *
1190 * @param[in,out] simCtx Simulation context, as PicurvOpenRunCsv() takes it.
1191 * @param[in] dir Directory of the file (`simCtx->analysis_dir` or `simCtx->log_dir`).
1192 * @param[in] filename Basename of the CSV, including the extension.
1193 * @param[in] header Column header written to an empty file, without a trailing newline.
1194 * @param[out] file Open append handle, never NULL on success.
1195 * @return PetscErrorCode 0 on success; `PETSC_ERR_FILE_OPEN` if the file cannot be opened.
1196 */
1197static inline PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename,
1198 const char *header, FILE **file)
1199{
1200 return PicurvOpenRunCsv(simCtx, dir, filename, header, PICURV_CSV_APPEND, PETSC_TRUE, file);
1201}
1202#endif // LOGGING_H
FieldId
Compile-time identity for a catalogued Eulerian field.
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Computes and logs the local and global min/max values of a 3-component vector field.
Definition logging.c:2501
const char * LESTestFilterKernelToString(LESTestFilterKernel kernel)
Returns the user-facing name of an LES test-filter kernel.
Definition logging.c:727
void set_allowed_functions(const char **functionList, int count)
Sets the global list of function names that are allowed to log.
Definition logging.c:176
PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
Opens one of the run's CSV records (diagnostics, solver history, profiling) for writing.
Definition logging.c:3552
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step)
Reports whether a completed step falls on the console snapshot cadence.
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
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:888
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
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)
Destroys the DualMonitorCtx.
Definition logging.c:927
PetscBool IsStatisticsConsoleSnapshotEnabled(const struct SimCtx *simCtx)
Reports whether the periodic statistics console snapshot is enabled.
void _ProfilingRegister(const char *func_name, PetscBool helper, PetscLogEvent *event)
Internal profiling hook: register a call site's function as a PETSc log event.
Definition logging.c:1984
PetscBool log_to_console
Definition logging.h:58
PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user)
Logs the interpolation error between the analytical and computed solutions.
Definition logging.c:3024
const char * ParticleBoundaryPolicyToString(ParticleBoundaryPolicy policy)
Returns the configuration token for a particle boundary policy.
Definition logging.c:850
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Returns whether a particle console snapshot should be emitted for the completed timestep.
Definition logging.c:501
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
static PetscErrorCode PicurvOpenDiagnosticsCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, FILE **file)
Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.
Definition logging.h:1197
PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n)
Free an array previously returned by LoadAllowedFunctionsFromFile().
Definition logging.c:619
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
Definition logging.c:484
PetscErrorCode print_log_level(void)
Prints the current logging level to the console.
Definition logging.c:138
static PetscBool ParticleIsTraced(const SimCtx *simCtx, PetscInt64 pid)
True when pid is one of the run's traced particles (simCtx->tracePIDs, sorted).
Definition logging.h:306
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
Definition logging.c:518
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
Prints a progress bar to the console.
Definition logging.c:2446
PetscReal bnorm
Definition logging.h:60
PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.
Definition logging.c:2380
PetscInt step
Definition logging.h:61
PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[], char ***funcsOut, PetscInt *nOut)
Load function names from a text file.
Definition logging.c:561
PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step)
Emits one console snapshot of window progress.
const char * WallFunctionModelToString(WallFunctionModel model)
Returns the user-facing name of a wall-function model.
Definition logging.c:786
PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
Append a reduced runtime memory sample to the configured memory log.
Definition logging.c:2170
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Logs the performance summary for the current timestep and resets timers.
Definition logging.c:2100
const char * LESFilterWidthModelToString(LESFilterWidthModel model)
Returns the user-facing name of an LES grid-filter-width model.
Definition logging.c:704
PetscErrorCode LOG_FACE_DISTANCES(PetscReal *d)
Prints the signed distances to each face of the cell.
Definition logging.c:256
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
Definition logging.c:399
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Computes advanced particle statistics and stores them in SimCtx.
Definition logging.c:3484
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
Definition logging.c:1905
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
Definition logging.c:3101
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Logs physical solution-convergence metrics once per completed timestep.
Definition logging.c:1714
PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx)
A custom KSP monitor that logs to a file and optionally to the console.
Definition logging.c:955
PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user)
Logs continuity metrics for a single block to a file.
Definition logging.c:1866
PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name)
Logs the node-layout anatomy of the transient center-to-corner interpolation field.
Definition logging.c:2997
const char * LESAveragingModeToString(LESAveragingMode mode)
Returns the user-facing name of an LES coefficient-averaging mode.
Definition logging.c:746
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific gri...
Definition logging.c:2903
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Writes compact runtime search metrics to CSV and optionally to console.
Definition logging.c:3288
const char * InterpolationMethodToString(InterpolationMethod method)
Returns the display name of a grid-to-particle interpolation method.
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)
Applies the profiling configuration from SimCtx to PICurv's PETSc log events.
Definition logging.c:2015
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
const char * LESModelToString(LESModelType LESFlag)
Returns the canonical log token for an LES model selector.
Definition logging.c:682
PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank)
Prints the coordinates of a cell's vertices.
Definition logging.c:229
LogLevel _ResolveLogLevel(void)
Internal hook: read LOG_LEVEL from the environment and cache it, once.
Definition logging.c:101
PetscErrorCode ProfilingResetTimestepCounters(void)
Starts a new per-step profiling interval.
Definition logging.c:2087
PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
Resets the aggregate per-timestep search instrumentation counters.
Definition logging.c:3252
const char * LESClipModeToString(LESClipMode mode)
Returns the user-facing name of an LES coefficient-limiting mode.
Definition logging.c:766
const char * MomentumSolverTypeToString(MomentumSolverType SolverFlag)
Returns the canonical log token for a momentum-solver selector.
Definition logging.c:808
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:62
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Context for a dual-purpose KSP monitor.
Definition logging.h:56
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
Main header file for a complex fluid dynamics solver.
LESModelType
Identifies the subgrid-scale closure evaluated during a timestep.
Definition variables.h:583
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
ParticleInitializationType
Enumerator to identify the particle initialization strategy.
Definition variables.h:746
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:186
PetscInt nTracePIDs
Number of entries in tracePIDs (at most PICURV_MAX_TRACED_PARTICLES).
Definition variables.h:1089
ParticleBoundaryPolicy
What happens to a particle that crosses a domain-boundary face.
Definition variables.h:336
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
LESClipMode
Selects the admissible range imposed on the dynamic model coefficient.
Definition variables.h:652
LESTestFilterKernel
Selects the discrete test-filter kernel used by the dynamic procedure.
Definition variables.h:626
WallFunctionModel
Selects the wall model applied on WALL faces.
Definition variables.h:600
MomentumSolverType
Enumerator to identify the implemented momentum solver strategies.
Definition variables.h:729
InterpolationMethod
Selects the grid-to-particle interpolation method.
Definition variables.h:760
LESAveragingMode
Selects the set over which the Germano contractions are averaged.
Definition variables.h:639
PetscInt64 * tracePIDs
Sorted, distinct IDs of the particles whose every stage is reported (-picurv_trace_particles); NULL w...
Definition variables.h:1088
LESFilterWidthModel
Selects how a cell's grid filter width is derived from its metrics.
Definition variables.h:614
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
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