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 * This struct holds a file viewer for unconditional logging and a boolean
54 * flag to enable/disable optional logging to the console.
55 */
56typedef struct {
57 FILE *file_handle; // C file handling for logging.
58 PetscBool log_to_console; // Flag to enable console output.
59 PetscReal bnorm; // Stores the norm of the initial RHS vector.
60 PetscInt step; // Timestep
61 PetscInt block_id; // the ID of the block this monitor is for.
63
64// --------------------- Logging Macros ---------------------
65
66/**
67 * @brief Logging macro for PETSc-based applications with scope control.
68 *
69 * This macro provides a convenient way to log messages with different scopes
70 * (LOCAL or GLOBAL) and severity levels. It utilizes PETSc's `PetscPrintf`
71 * function for message output.
72 *
73 * @param scope Specifies the logging scope:
74 * - LOCAL: Logs on the current process using MPI_COMM_SELF.
75 * - GLOBAL: Logs on all processes using MPI_COMM_WORLD.
76 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
77 * @param fmt The format string for the message (similar to printf).
78 * @param ... Additional arguments for the format string (optional).
79 *
80 * Example usage:
81 * LOG(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx);
82 * LOG(GLOBAL, LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);
83 */
84#define LOG(scope, level, fmt, ...) \
85 do { \
86 /* Determine the MPI communicator based on the scope */ \
87 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
88 /* Check if the log level is within the allowed range */ \
89 if ((int)(level) <= (int)get_log_level()) { \
90 /* Print the message to the specified communicator */ \
91 PetscPrintf(comm, fmt, ##__VA_ARGS__); \
92 } \
93 } while (0)
94
95/**
96 * @brief Default logging macro for PETSc-based applications.
97 *
98 * This macro simplifies logging by defaulting the scope to GLOBAL
99 * (i.e., `MPI_COMM_WORLD`) and providing a convenient interface for
100 * common logging needs.
101 *
102 * @param level The severity level of the message (e.g., LOG_ERROR, LOG_INFO).
103 * @param fmt The format string for the log message (similar to printf).
104 * @param ... Additional arguments for the format string (optional).
105 *
106 * Example usage:
107 * LOG_DEFAULT(LOG_ERROR, "Error occurred at index %ld.\n", idx);
108 * LOG_DEFAULT(LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);
109 *
110 * @note
111 * - By default, this macro logs across all MPI processes using `MPI_COMM_WORLD`.
112 * - If finer control (e.g., local logging) is required, use the more general `LOG` macro.
113 * - The log level is filtered based on the value returned by `get_log_level()`.
114 */
115#define LOG_DEFAULT(level, fmt, ...) \
116 do { \
117 /* Set the communicator to global (MPI_COMM_WORLD) by default */ \
118 MPI_Comm comm = MPI_COMM_WORLD; \
119 /* Check if the log level is within the allowed range */ \
120 if ((int)(level) <= (int)get_log_level()) { \
121 /* Print the message using PetscPrintf with the global communicator */ \
122 PetscPrintf(comm, fmt, ##__VA_ARGS__); \
123 } \
124 } while (0)
125
126/**
127 * @brief Logging macro for PETSc-based applications with scope control,
128 * using synchronized output across processes.
129 *
130 * This macro uses `PetscSynchronizedPrintf` and `PetscSynchronizedFlush` to
131 * ensure messages from different ranks are printed in a synchronized (rank-by-rank)
132 * manner, preventing interleaved outputs.
133 *
134 * @param scope Specifies the logging scope:
135 * - LOCAL: Logs on the current process using MPI_COMM_SELF.
136 * - GLOBAL: Logs on all processes using MPI_COMM_WORLD.
137 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
138 * @param fmt The format string for the message (similar to printf).
139 * @param ... Additional arguments for the format string (optional).
140 *
141 * Example usage:
142 * LOG_SYNC(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx);
143 * LOG_SYNC(GLOBAL, LOG_INFO, "Synchronized info: rank = %ld.\n", rank);
144 */
145#define LOG_SYNC(scope, level, fmt, ...) \
146 do { \
147 /* Determine the MPI communicator based on the scope */ \
148 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
149 /* Check if the log level is within the allowed range */ \
150 if ((int)(level) <= (int)get_log_level()) { \
151 /* Synchronized print (collective) on the specified communicator */ \
152 PetscSynchronizedPrintf(comm, fmt, ##__VA_ARGS__); \
153 /* Ensure all ranks have finished printing before continuing */ \
154 PetscSynchronizedFlush(comm, PETSC_STDOUT); \
155 } \
156 } while (0)
157
158/**
159 * @brief Default synchronized logging macro for PETSc-based applications.
160 *
161 * This macro simplifies logging by defaulting the scope to GLOBAL
162 * (i.e., `MPI_COMM_WORLD`) and provides synchronized output across
163 * all processes.
164 *
165 * @param level The severity level of the message (e.g., LOG_ERROR, LOG_INFO).
166 * @param fmt The format string for the log message (similar to printf).
167 * @param ... Additional arguments for the format string (optional).
168 *
169 * Example usage:
170 * LOG_SYNC_DEFAULT(LOG_ERROR, "Error at index %ld.\n", idx);
171 * LOG_SYNC_DEFAULT(LOG_INFO, "Process rank: %ld.\n", rank);
172 *
173 * @note
174 * - By default, this macro logs across all MPI processes using `MPI_COMM_WORLD`.
175 * - If local (per-process) logging is required, use the more general `LOG_SYNC` macro.
176 * - The log level is filtered based on the value returned by `get_log_level()`.
177 */
178#define LOG_SYNC_DEFAULT(level, fmt, ...) \
179 do { \
180 if ((int)(level) <= (int)get_log_level()) { \
181 PetscSynchronizedPrintf(MPI_COMM_WORLD, fmt, ##__VA_ARGS__); \
182 PetscSynchronizedFlush(MPI_COMM_WORLD, PETSC_STDOUT); \
183 } \
184 } while (0)
185
186
187
188/**
189 * @brief Logging macro that checks both the log level and whether the calling function
190 * is in the allowed-function list before printing. Useful for selective, per-function logging.
191 *
192 * @param scope Specifies the logging scope (LOCAL or GLOBAL).
193 * @param level The severity level of the message (e.g., LOG_INFO, LOG_ERROR).
194 * @param fmt The format string for the message (similar to printf).
195 * @param ... Additional arguments for the format string (optional).
196 *
197 * Example usage:
198 * LOG_ALLOW(LOCAL, LOG_DEBUG, "Debugging info in function: %s\n", __func__);
199 */
200#define LOG_ALLOW(scope, level, fmt, ...) \
201 do { \
202 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
203 if ((int)(level) <= (int)get_log_level() && is_function_allowed(__func__)) { \
204 PetscPrintf(comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
205 } \
206 } while (0)
207
208
209/* ------- DEBUG ------------------------------------------
210#define LOG_ALLOW(scope, level, fmt, ...) \
211 do { \
212 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
213 PetscInt __current_level_val = get_log_level(); \
214 PetscBool __allowed_func_val = is_function_allowed(__func__); \
215 // Print BEFORE the check \
216 if (strcmp(__func__, "LocateAllParticlesInGrid") == 0) { \
217 printf("[DEBUG LOG_ALLOW in %s] Checking: level=%d, get_log_level() returned %d, func_allowed=%d\n", \
218 __func__, (int)level, (int)__current_level_val, (int)__allowed_func_val); \
219 } \
220 if ((int)(level) <= (int)__current_level_val && __allowed_func_val) { \
221 // Print AFTER passing the check // \
222 if (strcmp(__func__, "LocateAllParticlesInGrid") == 0) { \
223 printf("[DEBUG LOG_ALLOW in %s] Check PASSED. Printing log.\n", __func__); \
224 } \
225 PetscPrintf(comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
226 } \
227 } while (0)
228-------------------------------------------------------------------------------
229*/
230
231/**
232 * @brief Synchronized logging macro that checks both the log level
233 * and whether the calling function is in the allow-list.
234 *
235 * This macro uses `PetscSynchronizedPrintf` and `PetscSynchronizedFlush` to
236 * ensure messages from different ranks are printed in a rank-ordered fashion
237 * (i.e., to avoid interleaving). It also filters out messages if the current
238 * function is not in the allow-list (`is_function_allowed(__func__)`) or the
239 * requested log level is higher than `get_log_level()`.
240 *
241 * @param scope Either LOCAL (MPI_COMM_SELF) or GLOBAL (MPI_COMM_WORLD).
242 * @param level One of LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG.
243 * @param fmt A `printf`-style format string (e.g., "Message: %ld\n").
244 * @param ... Variadic arguments to fill in `fmt`.
245 *
246 * Example usage:
247 *
248 * \code{.c}
249 * LOG_ALLOW_SYNC(LOCAL, LOG_DEBUG, "Debug info: rank = %ld\n", rank);
250 * LOG_ALLOW_SYNC(GLOBAL, LOG_INFO, "Synchronized info in %s\n", __func__);
251 * \endcode
252 */
253#define LOG_ALLOW_SYNC(scope, level, fmt, ...) \
254do { \
255 /* ------------------------------------------------------------------ */ \
256 /* Validate scope and pick communicator *before* any early exits. */ \
257 /* ------------------------------------------------------------------ */ \
258 MPI_Comm _comm; \
259 if ((scope) == LOCAL) _comm = MPI_COMM_SELF; \
260 else if ((scope) == GLOBAL) _comm = MPI_COMM_WORLD; \
261 else { \
262 fprintf(stderr, "LOG_ALLOW_SYNC ERROR: invalid scope (%d) at %s:%d\n", \
263 (scope), __FILE__, __LINE__); \
264 MPI_Abort(MPI_COMM_WORLD, 1); \
265 } \
266 \
267 /* ------------------------------------------------------------------ */ \
268 /* Decide whether *this* rank should actually print. */ \
269 /* ------------------------------------------------------------------ */ \
270 PetscBool _doPrint = \
271 is_function_allowed(__func__) && ((int)(level) <= (int)get_log_level()); \
272 \
273 if (_doPrint) { \
274 PetscSynchronizedPrintf(_comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
275 } \
276 \
277 /* ------------------------------------------------------------------ */ \
278 /* ALL ranks call the flush, even if they printed nothing. */ \
279 /* ------------------------------------------------------------------ */ \
280 PetscSynchronizedFlush(_comm, PETSC_STDOUT); \
281} while (0)
282
283/**
284 * @brief Logs a message inside a loop, but only every `interval` iterations.
285 *
286 * @param scope LOCAL or GLOBAL.
287 * @param level LOG_* level.
288 * @param iterVar The loop variable (e.g., i).
289 * @param interval Only log when (iterVar % interval == 0).
290 * @param fmt printf-style format string.
291 * @param ... Variadic arguments to include in the formatted message.
292 *
293 * Example:
294 * for (int i = 0; i < 100; i++) {
295 * LOG_LOOP_ALLOW(LOCAL, LOG_DEBUG, i, 10, "Value of i=%d\n", i);
296 * }
297 */
298#define LOG_LOOP_ALLOW(scope, level, iterVar, interval, fmt, ...) \
299 do { \
300 if (is_function_allowed(__func__) && (int)(level) <= (int)get_log_level()) { \
301 if ((iterVar) % (interval) == 0) { \
302 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
303 PetscPrintf(comm, "[%s] [%s=%d] " fmt, \
304 __func__, #iterVar, (iterVar), ##__VA_ARGS__); \
305 } \
306 } \
307 } while (0)
308/*
309#define LOG_LOOP_ALLOW(scope,level, iterVar, interval, fmt, ...) \
310 do { \
311 if (is_function_allowed(__func__) && (int)(level) <= (int)get_log_level()) { \
312 if ((iterVar) % (interval) == 0) { \
313 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
314 PetscPrintf(comm, "[%s] [Iter=%d] " fmt, \
315 __func__, (iterVar), ##__VA_ARGS__); \
316 } \
317 } \
318 } while (0)
319*/
320
321/**
322 * @brief Logs a custom message if a variable equals a specific value.
323 *
324 * This is a variadic macro for logging a single event when a condition is met.
325 * It is extremely useful for printing debug information at a specific iteration
326 * of a loop or when a state variable reaches a certain value.
327 *
328 * @param scope Either LOCAL or GLOBAL.
329 * @param level The logging level.
330 * @param var The variable to check (e.g., a loop counter 'k').
331 * @param val The value that triggers the log (e.g., 6). The log prints if var == val.
332 * @param fmt A printf-style format string.
333 * @param ... A printf-style format string and its corresponding arguments.
334 */
335#define LOG_LOOP_ALLOW_EXACT(scope, level, var, val, fmt, ...) \
336 do { \
337 /* First, perform the cheap, standard gatekeeper checks. */ \
338 if (is_function_allowed(__func__) && (int)(level) <= (int)get_log_level()) { \
339 /* Only if those pass, check the user's specific condition. */ \
340 if ((var) == (val)) { \
341 MPI_Comm comm = ((scope) == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
342 /* Print the standard prefix, then the user's custom message. */ \
343 PetscPrintf(comm, "[%s] [%s=%d] " fmt, \
344 __func__, #var, (var), ##__VA_ARGS__); \
345 } \
346 } \
347 } while (0)
348
349/**
350 * @brief Logs a single element of an array, given an index.
351 *
352 * @param scope Either LOCAL or GLOBAL.
353 * @param level LOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
354 * @param arr Pointer to the array to log from.
355 * @param length The length of the array (to prevent out-of-bounds).
356 * @param idx The index of the element to print.
357 * @param fmt The printf-style format specifier (e.g. "%g", "%f", etc.).
358 *
359 * This macro only logs if:
360 * 1) The current function is in the allow-list (`is_function_allowed(__func__)`).
361 * 2) The requested logging `level` <= the current global `get_log_level()`.
362 * 3) The index `idx` is valid (0 <= idx < length).
363 */
364#define LOG_ARRAY_ELEMENT_ALLOW(scope,level, arr, length, idx, fmt) \
365 do { \
366 if (is_function_allowed(__func__) && (int)(level) <= (int)get_log_level()) { \
367 if ((idx) >= 0 && (idx) < (length)) { \
368 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
369 PetscPrintf(comm, "[%s] arr[%d] = " fmt "\n", \
370 __func__, (idx), (arr)[idx]); \
371 } \
372 } \
373 } while (0)
374
375/**
376 * @brief Logs a consecutive subrange of an array.
377 *
378 * @param scope Either LOCAL or GLOBAL.
379 * @param level LOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
380 * @param arr Pointer to the array to log from.
381 * @param length Total length of the array.
382 * @param start Starting index of the subrange.
383 * @param end Ending index of the subrange (inclusive).
384 * @param fmt The printf-style format specifier (e.g., "%g", "%f").
385 *
386 * This macro prints each element arr[i] for i in [start, end], bounded by [0, length-1].
387 */
388#define LOG_ARRAY_SUBRANGE_ALLOW(scope,level, arr, length, start, end, fmt) \
389 do { \
390 if (is_function_allowed(__func__) && (int)(level) <= (int)get_log_level()) { \
391 MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
392 PetscInt _start = (start) < 0 ? 0 : (start); \
393 PetscInt _end = (end) >= (length) ? (length) - 1 : (end); \
394 for (PetscInt i = _start; i <= _end; i++) { \
395 PetscPrintf(comm, "[%s] arr[%d] = " fmt "\n", __func__, i, (arr)[i]); \
396 } \
397 } \
398 } while (0)
399
400// --------------------- Function Declarations ---------------------
401
402/**
403 * @brief Retrieves the current logging level from the environment variable `LOG_LEVEL`.
404 *
405 * The function checks the `LOG_LEVEL` environment variable and sets the logging level accordingly.
406 * Supported levels are "ERROR", "WARNING", "INFO", "DEBUG", "TRACE", and "VERBOSE".
407 * Unset or unrecognized values default to "ERROR".
408 *
409 * @return LogLevel The current logging level.
410 */
412
413/**
414 * @brief Prints the current logging level to the console.
415 *
416 * This function retrieves the log level using `get_log_level()` and prints
417 * the corresponding log level name. It helps verify the logging configuration
418 * at runtime.
419 * The log levels supported are:
420 * - `LOG_ERROR` (0) : Logs only critical errors.
421 * - `LOG_WARNING` (1) : Logs warnings and errors.
422 * - `LOG_INFO` (2) : Logs general information, warnings, and errors.
423 * - `LOG_DEBUG` (3) : Logs debugging information, info, warnings, and errors.
424 * - `LOG_TRACE` (4) : Logs fine-grained trace information.
425 * - `LOG_VERBOSE` (5) : Logs very detailed developer output.
426 * If `LOG_LEVEL` is not set, it defaults to `LOG_ERROR`.
427 * @return PetscErrorCode 0 on success.
428 */
429PetscErrorCode print_log_level(void);
430
431/**
432 * @brief Sets the global list of function names that are allowed to log.
433 *
434 * You can replace the entire list of allowed function names at runtime.
435 *
436 * @param functionList Replacement array of permitted function names.
437 * @param count Number of entries in `functionList`.
438 */
439void set_allowed_functions(const char** functionList, int count);
440
441/**
442 * @brief Checks if a given function is in the allow-list.
443 *
444 * This helper is used internally by the LOG_ALLOW macro.
445 *
446 * @param functionName Function name to query.
447 * @return PETSC_TRUE when the name is enabled by the allow-list.
448 */
449PetscBool is_function_allowed(const char* functionName);
450
451/**
452 * @brief Prints the coordinates of a cell's vertices.
453 *
454 * This function iterates through the eight vertices of a given cell and prints their
455 * coordinates. It is primarily used for debugging purposes to verify the correctness
456 * of cell vertex assignments.
457 *
458 * @param[in] cell Pointer to a `Cell` structure representing the cell, containing its vertices.
459 * @param[in] rank MPI rank for identification (useful in parallel environments).
460 * @return PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
461 *
462 * @note
463 * - Ensure that the `cell` pointer is not `NULL` before calling this function..
464 */
465PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank);
466
467/**
468 * @brief Prints the signed distances to each face of the cell.
469 *
470 * This function iterates through the six signed distances from a point to each face of a given cell
471 * and prints their values. It is primarily used for debugging purposes to verify the correctness
472 * of distance calculations.
473 *
474 * @param[in] d An array of six `PetscReal` values representing the signed distances.
475 * The indices correspond to:
476 * - d[LEFT]: Left Face
477 * - d[RIGHT]: Right Face
478 * - d[BOTTOM]: Bottom Face
479 * - d[TOP]: Top Face
480 * - d[FRONT]: Front Face
481 * - d[BACK]: Back Face
482 *
483 * @return PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
484 *
485 * @note
486 * - Ensure that the `d` array is correctly populated with signed distances before calling this function.
487 */
488PetscErrorCode LOG_FACE_DISTANCES(PetscReal* d);
489
490/**
491 * @brief Prints particle fields in a table that automatically adjusts its column widths.
492 *
493 * This function retrieves data from the particle swarm and prints a table where the
494 * width of each column is determined by the maximum width needed to display the data.
495 * Only every 'printInterval'-th particle is printed.
496 *
497 * @param[in] user Pointer to the UserCtx structure.
498 * @param[in] printInterval Only every printInterval‑th particle is printed.
499 *
500 * @return PetscErrorCode Returns 0 on success.
501 */
502PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx* user, PetscInt printInterval);
503
504/**
505 * @brief Returns whether periodic particle console snapshots are enabled.
506 *
507 * This checks only the reporting contract (particles exist, cadence is enabled,
508 * and the global log level is at least INFO).
509 *
510 * @param simCtx Simulation context controlling the operation.
511 * @return PetscBool indicating the result of `IsParticleConsoleSnapshotEnabled()`.
512 */
513PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx);
514
515/**
516 * @brief Returns whether a particle console snapshot should be emitted for the
517 *
518 * completed timestep.
519 *
520 * @param simCtx Simulation context controlling the operation.
521 * @param completed_step Completed step index used by the decision helper.
522 * @return PetscBool indicating the result of `ShouldEmitPeriodicParticleConsoleSnapshot()`.
523 */
524PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step);
525
526/**
527 * @brief Emits one particle console snapshot into the main solver log.
528 *
529 * @param user Primary `UserCtx` input for the operation.
530 * @param simCtx Simulation context controlling the operation.
531 * @param step Step index associated with the operation.
532 * @return PetscErrorCode 0 on success.
533 */
534PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step);
535
536/**
537 * @brief Reports whether the periodic statistics console snapshot is enabled.
538 *
539 * Mirrors the particle console gate: the subsystem must be active, the configured
540 * cadence positive, and the effective log level at least `LOG_INFO`.
541 *
542 * @param[in] simCtx Simulation context to inspect.
543 * @return `PETSC_TRUE` when snapshots should be emitted.
544 */
545PetscBool IsStatisticsConsoleSnapshotEnabled(const struct SimCtx *simCtx);
546
547/**
548 * @brief Reports whether a completed step falls on the console snapshot cadence.
549 * @param[in] simCtx Simulation context to inspect.
550 * @param[in] completed_step Step that has just completed.
551 * @return `PETSC_TRUE` when a snapshot is due for this step.
552 */
553PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step);
554
555/**
556 * @brief Emits one console snapshot of window progress.
557 *
558 * Reports window-level scalars only; it never dumps field data.
559 *
560 * @param[in] user Finest-level block array supplying accumulator state.
561 * @param[in] simCtx Simulation context carrying the window array.
562 * @param[in] step Step the snapshot describes.
563 * @return Zero on success.
564 */
565PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step);
566
567/* ------------------------------------------------------------------------- */
568/**
569 * @brief Free an array previously returned by LoadAllowedFunctionsFromFile().
570 *
571 * @param[in,out] funcs Array of strings to release (may be @c NULL).
572 * @param[in] n Number of entries in @p funcs. Ignored if @p funcs is
573 * @c NULL.
574 *
575 * @return 0 on success or a PETSc error code.
576 */
577PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n);
578
579/**
580 * @brief Load function names from a text file.
581 *
582 * The file is expected to contain **one identifier per line**. Blank lines and
583 * lines whose first non‑blank character is a <tt>#</tt> are silently skipped so
584 * the file can include comments. Example:
585 *
586 * @code{.txt}
587 * # Allowed function list
588 * main
589 * InitializeSimulation
590 * InterpolateAllFieldsToSwarm # inline comments are OK, too
591 * @endcode
592 *
593 * The routine allocates memory as needed (growing an internal buffer with
594 * @c PetscRealloc()) and returns the resulting array and its length to the
595 * caller. Use FreeAllowedFunctions() to clean up when done.
596 *
597 * @param[in] filename Path of the configuration file to read.
598 * @param[out] funcsOut On success, points to a freshly‑allocated array of
599 * <tt>char*</tt> (size @p nOut).
600 * @param[out] nOut Number of valid entries in @p funcsOut.
601 *
602 * @return 0 on success, or a PETSc error code on failure (e.g. I/O error, OOM).
603 */
604PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[],
605 char ***funcsOut,
606 PetscInt *nOut);
607
608
609/**
610 * @brief Returns the canonical log token for a boundary-face enum value.
611 * @param[in] face The BCFace enum value.
612 * @return Pointer to a constant string representing the face.
613 */
614const char* BCFaceToString(BCFace face);
615
616/**
617 * @brief Convert an initial-condition mode to a string representation.
618 * @param[in] mode Initial-condition mode value.
619 * @return Pointer to a constant string representing the initial-condition mode.
620 */
622
623/**
624 * @brief Convert a FlowDirection enum value to its YAML token string.
625 * @param[in] fd FlowDirection value.
626 * @return Token string such as "+Zeta", or "from INLET" when FLOW_DIR_UNSET.
627 */
629
630/**
631 * @brief Returns the canonical log token for a particle-initialization mode.
632 * @param[in] ParticleInitialization The ParticleInitialization enum value.
633 * @return Pointer to a constant string representing the particle initialization type.
634 */
635const char* ParticleInitializationToString(ParticleInitializationType ParticleInitialization);
636
637/**
638 * @brief Returns the canonical log token for an LES model selector.
639 * @param[in] LESFlag The LES flag value.
640 * @return Pointer to a constant string representing the LES Flag.
641 */
642const char* LESModelToString(LESModelType LESFlag);
643
644/**
645 * @brief Returns the canonical log token for a momentum-solver selector.
646 * @param[in] SolverFlag The Momentum Solver flag value.
647 * @return Pointer to a constant string representing the MomentumSolverType.
648 */
649const char* MomentumSolverTypeToString(MomentumSolverType SolverFlag);
650
651/**
652 * @brief Returns the canonical log token for a boundary mathematical type.
653 * @param[in] type The BCType enum value.
654 * @return Pointer to a constant string representing the BC type.
655 */
656const char* BCTypeToString(BCType type);
657
658/**
659 * @brief Converts a BCHandlerType enum to its string representation.
660 *
661 * Provides a descriptive string for a specific boundary condition implementation strategy.
662 * This is crucial for logging the exact behavior configured for a face.
663 *
664 * @param handler_type The BCHandlerType enum value (e.g., BC_HANDLER_WALL_NOSLIP).
665 * @return A constant character string corresponding to the enum. Returns
666 * "UNKNOWN_HANDLER" if the enum value is not recognized.
667 */
668const char* BCHandlerTypeToString(BCHandlerType handler_type);
669
670/**
671 * @brief A custom KSP monitor that logs to a file and optionally to the console.
672 *
673 * This function unconditionally calls the standard true residual monitor to log to a
674 * file viewer provided in the context. It also checks a flag in the context
675* and, if true, calls the monitor again to log to standard output.
676 *
677 * @param ksp The Krylov subspace context.
678 * @param it The current iteration number.
679 * @param rnorm The preconditioned residual norm.
680 * @param ctx A pointer to the DualMonitorCtx structure.
681 * @return PetscErrorCode 0 on success.
682 */
683PetscErrorCode DualKSPMonitor(KSP ksp, PetscInt it, PetscReal rnorm, void *ctx);
684
685/**
686 * @brief Destroys the DualMonitorCtx.
687 *
688 * This function is passed to KSPMonitorSet to ensure the viewer is
689 * properly destroyed and the context memory is freed when the KSP is destroyed.
690 * @param ctx a pointer to the context pointer to be destroyed
691 * @return PetscErrorCode
692 */
693PetscErrorCode DualMonitorDestroy(void **ctx);
694
695/**
696 * @brief Logs continuity metrics for a single block to a file.
697 *
698 * This function should be called for each block, once per timestep. It opens a
699 * central log file in append mode. To ensure the header is written only once,
700 * it checks if it is processing block 0 on the simulation's start step.
701 *
702 * @param user A pointer to the UserCtx for the specific block whose metrics
703 * are to be logged. The function accesses both global (SimCtx)
704 * and local (user->...) data.
705 * @return PetscErrorCode 0 on success.
706 */
707PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user);
708
709/**
710 * @brief Logs physical solution-convergence metrics once per completed timestep.
711 *
712 * This logger is intentionally separate from the detailed inner solver-health
713 * logs. Depending on the configured mode, it records deterministic step drift,
714 * periodic phase-aligned drift, or statistical window drift into
715 * `logs/solution_convergence.log`.
716 *
717 * The logger is solver-mode only and is intended to run after a completed
718 * flow-solve / projection step but before history vectors are shifted forward.
719 * Warmup rows are handled internally:
720 * - steady/transient mode: the first logged step has `has_reference = 0`
721 * - periodic mode: the first cycle fills the phase reference ring
722 * - statistical mode: window-drift fields remain zero until enough samples
723 * exist to form the requested windows
724 *
725 * Existing detailed inner logs remain the authoritative source for momentum,
726 * Poisson, and continuity health. This logger only summarizes physical
727 * solution-drift metrics.
728 *
729 * @param[in,out] simCtx Master simulation context controlling the logging mode
730 * and owning any supporting runtime buffers.
731 * @return PetscErrorCode 0 on success.
732 */
733PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx);
734
735/**
736 * @brief A function that outputs the name of the current level in the ParticleLocation enum.
737 * @param level The ParticleLocation enum value.
738 * @return A constant character string corresponding to the enum. Returns
739 * "UNKNOWN_LEVEL" if the enum value is not recognized.
740 */
742
743/*================================================================================*
744 * PROGRESS BAR UTILITY *
745 *================================================================================*/
746
747/**
748 * @brief Prints a progress bar to the console.
749 *
750 * This function should only be called by the root process (rank 0). It uses
751 * a carriage return `\r` to overwrite the same line in the terminal, creating
752 * a dynamic progress bar.
753 *
754 * @param step The current step index from the loop (e.g., from 0 to N-1).
755 * @param startStep The global starting step number of the simulation.
756 * @param totalSteps The total number of steps to be run in this simulation instance.
757 * @param currentTime The current simulation time to display.
758 */
759void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime);
760
761/**
762 * @brief Initializes the custom profiling system using configuration from SimCtx.
763 *
764 * This function sets up the internal data structures for tracking function
765 * performance. It reads the list of "critical functions" from the provided
766 * SimCtx and marks them for per-step logging at LOG_INFO level.
767 *
768 * It should be called once at the beginning of the application, after
769 * CreateSimulationContext() but before the main time loop.
770 *
771 * @param simCtx The master simulation context, which contains the list of
772 * critical function names to always log.
773 * @return PetscErrorCode
774 */
775PetscErrorCode ProfilingInitialize(SimCtx *simCtx);
776
777/**
778 * @brief Resets per-timestep profiling counters for the next solver step.
779 *
780 * This clears transient counters without discarding cumulative totals used by
781 * final profiling summaries.
782 *
783 * @return PetscErrorCode 0 on success.
784 */
785PetscErrorCode ProfilingResetTimestepCounters(void);
786
787/**
788 * @brief Logs the performance summary for the current timestep and resets timers.
789 *
790 * Depending on the configured profiling timestep mode, this function writes
791 * per-step profiling rows to the configured profiling log file:
792 * - `off`: writes nothing
793 * - `selected`: writes only functions marked for per-step reporting
794 * - `all`: writes every instrumented function that ran in the timestep
795 *
796 * It must be called once per timestep, typically at the end of the main loop.
797 * After logging, it resets the per-step counters and timers.
798 *
799 * @param simCtx The simulation context holding profiling output settings.
800 * @param step The current simulation step number, for logging context.
801 * @return PetscErrorCode
802 */
803PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step);
804
805/**
806 * @brief Append a reduced runtime memory sample to the configured memory log.
807 *
808 * The log is intentionally compact: every rank samples process/PETSc allocator
809 * memory, one max reduction summarizes the job, and rank 0 appends one
810 * terminal-readable row.
811 *
812 * @param simCtx The simulation context holding log directory and memory log settings.
813 * @param step The solver/post step associated with the sample.
814 * @param event Human-readable event label such as "Step", "Post", "Shutdown", or "Final".
815 * @param reason Human-readable reason, or NULL/"-" when not applicable.
816 * @return PetscErrorCode
817 */
818PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason);
819
820
821/**
822 * @brief the profiling excercise and build a profiling summary which is then printed to a log file.
823 *
824 * @param simCtx The Simulation Context Structure that can contains all the data regarding the simulation.
825 *
826 * @return PetscErrorCode 0 on success.
827 */
828PetscErrorCode ProfilingFinalize(SimCtx *simCtx);
829
830// --- Internal functions, do not call directly ---
831// These are called by the macros below.
832/**
833 * @brief Internal profiling hook invoked by `PROFILE_FUNCTION_BEGIN`.
834 * @param func_name Function name used by the profiling helper.
835 */
836void _ProfilingStart(const char *func_name);
837/**
838 * @brief Internal profiling hook invoked by `PROFILE_FUNCTION_END`.
839 * @param func_name Function name used by the profiling helper.
840 */
841void _ProfilingEnd(const char *func_name);
842
843
844/**
845 * @brief Marks the beginning of a profiled code block (typically a function).
846 *
847 * Place this macro at the very beginning of a function you wish to profile.
848 * It automatically captures the function's name and starts a wall-clock timer.
849 */
850#define PROFILE_FUNCTION_BEGIN \
851 _ProfilingStart(__FUNCT__)
852
853/**
854 * @brief Marks the end of a profiled code block.
855 *
856 * Place this macro just before every return point in a function that starts
857 * with PROFILE_FUNCTION_BEGIN. It stops the timer and accumulates the results.
858 */
859#define PROFILE_FUNCTION_END \
860 _ProfilingEnd(__FUNCT__)
861
862
863/**
864 * @brief Computes and logs the local and global min/max values of a 3-component vector field.
865 *
866 * This utility function inspects a PETSc Vec associated with a DMDA and calculates the
867 * minimum and maximum values for each of its three components (e.g., x, y, z) both for the
868 * local data on the current MPI rank and for the entire global domain.
869 *
870 * It uses the same "smart" logic as the flow solver, ignoring the padding nodes at the
871 * IM, JM, and KM boundaries of the grid. The results are printed to the standard output
872 * in a formatted, easy-to-read table.
873 *
874 * @param[in] user Pointer to the user-defined context. Used for grid information (IM, JM, KM)
875 * and MPI rank.
876 * @param[in] field_id Typed identity of the field being analyzed.
877 *
878 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
879 */
880PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id);
881
882/**
883 * @brief Logs the anatomy of a specified field at key boundary locations,
884 * respecting the solver's specific grid and variable architecture.
885 *
886 * This intelligent diagnostic function inspects a PETSc Vec and prints its values
887 * at critical boundary locations (-Xi/+Xi, -Eta/+Eta, -Zeta/+Zeta). It is "architecture-aware":
888 *
889 * - **Cell-Centered Fields ("Ucat", "P"):** It correctly applies the "Shifted Index Architecture,"
890 * where the value for geometric `Cell i` is stored at array index `i+1`. It labels
891 * the output to clearly distinguish between true physical values and ghost values.
892 * - **Single-Face-Family Fields:** `Csi/ICsi/IEta/IZet/Centx` belong to the
893 * I-face family, with corresponding J- and K-face families.
894 * - **Component-Staggered Fields ("Ucont" and histories):** x/y/z components
895 * live on I/J/K faces respectively.
896 * - **Node-Centered Fields ("Coordinates"):** It uses a direct index mapping, where the value for
897 * `Node i` is stored at index `i`.
898 *
899 * The output is synchronized across MPI ranks to ensure readability and focuses on a
900 * slice through the center of the domain to be concise.
901 *
902 * @param user A pointer to the UserCtx structure containing the DMs and Vecs.
903 * @param field_id Typed identity of the persistent Eulerian field to log.
904 * @param stage_name A string identifier for the current simulation stage (e.g., "After Advection").
905 * @return PetscErrorCode Returns 0 on success, non-zero on failure.
906 */
907PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name);
908
909/**
910 * @brief Logs the node-layout anatomy of the transient center-to-corner interpolation field.
911 * @param user Context owning the corner-staging workspace.
912 * @param corner_field_id Which corner workspace the caller populated.
913 * @param stage_name Printable simulation stage.
914 * @return Zero on success.
915 */
916PetscErrorCode LOG_CORNER_FIELD_ANATOMY(UserCtx *user, FieldId corner_field_id, const char *stage_name);
917
918/**
919 * @brief Logs the interpolation error between the analytical and computed solutions.
920 *
921 * @param user Primary `UserCtx` input for the operation.
922 * @return PetscErrorCode 0 on success.
923 */
924PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user);
925
926/**
927 * @brief Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
928 *
929 * @param user Primary `UserCtx` input for the operation.
930 * @return PetscErrorCode 0 on success.
931 */
932PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user);
933
934/**
935 * @brief Resets the aggregate per-timestep search instrumentation counters.
936 *
937 * @param simCtx Simulation context whose search metrics should be zeroed.
938 * @return PetscErrorCode 0 on success.
939 */
940PetscErrorCode ResetSearchMetrics(SimCtx *simCtx);
941
942/**
943 * @brief Computes advanced particle statistics and stores them in SimCtx.
944 *
945 * This function calculates:
946 * - Particle load imbalance across MPI ranks.
947 * - The total number of grid cells occupied by at least one particle.
948 *
949 * It requires that CalculateParticleCountPerCell() has been called prior to its
950 * execution. It uses collective MPI operations and must be called by all ranks.
951 *
952 * @param user Pointer to the UserCtx.
953 * @return PetscErrorCode 0 on success.
954 */
955PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user);
956
957/**
958 * @brief Writes compact runtime search metrics to CSV and optionally to console.
959 *
960 * The CSV artifact is always written for particle-enabled runs. Console output
961 * remains gated by normal logging level and function allow-listing.
962 *
963 * @param user Pointer to the UserCtx.
964 * @return PetscErrorCode 0 on success.
965 */
966PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user);
967
968/**
969 * @brief Logs particle swarm metrics, adapting its behavior based on a boolean flag in SimCtx.
970 *
971 * This function serves a dual purpose:
972 * 1. If simCtx->isInitializationPhase is PETSC_TRUE, it logs settlement
973 * diagnostics to "Initialization_Metrics.log", using the provided stageName.
974 * 2. If simCtx->isInitializationPhase is PETSC_FALSE, it logs regular
975 * timestep metrics to "Particle_Metrics.log".
976 *
977 * @param user A pointer to the UserCtx.
978 * @param stageName A descriptive label recorded in the metrics log (for example,
979 * initialization stage name or "Timestep Metrics").
980 * @return PetscErrorCode 0 on success.
981 */
982PetscErrorCode LOG_PARTICLE_METRICS(UserCtx *user, const char *stageName);
983#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:2349
void set_allowed_functions(const char **functionList, int count)
Sets the global list of function names that are allowed to log.
Definition logging.c:155
PetscErrorCode LOG_PARTICLE_METRICS(UserCtx *user, const char *stageName)
Logs particle swarm metrics, adapting its behavior based on a boolean flag in SimCtx.
Definition logging.c:3337
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step)
Reports whether a completed step falls on the console snapshot cadence.
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:793
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:186
PetscErrorCode DualMonitorDestroy(void **ctx)
Destroys the DualMonitorCtx.
Definition logging.c:831
PetscBool IsStatisticsConsoleSnapshotEnabled(const struct SimCtx *simCtx)
Reports whether the periodic statistics console snapshot is enabled.
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:2865
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Returns whether a particle console snapshot should be emitted for the.
Definition logging.c:545
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:671
PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n)
Free an array previously returned by LoadAllowedFunctionsFromFile().
Definition logging.c:652
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
Definition logging.c:528
PetscErrorCode print_log_level(void)
Prints the current logging level to the console.
Definition logging.c:119
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
Definition logging.c:559
PetscReal bnorm
Definition logging.h:59
PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
the profiling excercise and build a profiling summary which is then printed to a log file.
Definition logging.c:2196
PetscInt step
Definition logging.h:60
PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[], char ***funcsOut, PetscInt *nOut)
Load function names from a text file.
Definition logging.c:598
PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step)
Emits one console snapshot of window progress.
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime)
Prints a progress bar to the console.
Definition logging.c:2302
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:2086
LogLevel get_log_level()
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.c:87
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Logs the performance summary for the current timestep and resets timers.
Definition logging.c:2005
PetscErrorCode LOG_FACE_DISTANCES(PetscReal *d)
Prints the signed distances to each face of the cell.
Definition logging.c:233
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
Definition logging.c:400
void _ProfilingEnd(const char *func_name)
Internal profiling hook invoked by PROFILE_FUNCTION_END.
Definition logging.c:1966
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:773
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Computes advanced particle statistics and stores them in SimCtx.
Definition logging.c:3283
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
Definition logging.c:1858
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
Definition logging.c:2944
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Logs physical solution-convergence metrics once per completed timestep.
Definition logging.c:1600
const char * FlowDirectionToString(FlowDirection fd)
Convert a FlowDirection enum value to its YAML token string.
Definition logging.c:705
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:870
PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user)
Logs continuity metrics for a single block to a file.
Definition logging.c:1796
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:2838
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:2752
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Writes compact runtime search metrics to CSV and optionally to console.
Definition logging.c:3129
const char * InitialConditionModeToString(InitialConditionMode mode)
Convert an initial-condition mode to a string representation.
Definition logging.c:689
PetscErrorCode ProfilingInitialize(SimCtx *simCtx)
Initializes the custom profiling system using configuration from SimCtx.
Definition logging.c:1928
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:741
PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank)
Prints the coordinates of a cell's vertices.
Definition logging.c:208
PetscErrorCode ProfilingResetTimestepCounters(void)
Resets per-timestep profiling counters for the next solver step.
Definition logging.c:1988
PetscErrorCode ResetSearchMetrics(SimCtx *simCtx)
Resets the aggregate per-timestep search instrumentation counters.
Definition logging.c:3098
const char * MomentumSolverTypeToString(MomentumSolverType SolverFlag)
Returns the canonical log token for a momentum-solver selector.
Definition logging.c:757
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:61
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:724
void _ProfilingStart(const char *func_name)
Internal profiling hook invoked by PROFILE_FUNCTION_BEGIN.
Definition logging.c:1952
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 six logical faces of a structured computational block.
Definition variables.h:520
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:283
ParticleInitializationType
Enumerator to identify the particle initialization strategy.
Definition variables.h:551
ParticleLocationStatus
Defines the state of a particle with respect to its location and migration status during the iterativ...
Definition variables.h:137
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:303
MomentumSolverType
Enumerator to identify the implemented momentum solver strategies.
Definition variables.h:534
FlowDirection
Primary flow direction for streamwise IC and Poiseuille modes.
Definition variables.h:272
InitialConditionMode
Selects the algorithm used to populate a fresh Eulerian velocity field.
Definition variables.h:151
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:261
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:177
The master context for the entire simulation.
Definition variables.h:695
User-defined context containing data specific to a single computational grid level.
Definition variables.h:906