PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Data Structures | Macros | Enumerations | Functions | Variables
logging.h File Reference

Logging utilities and macros for PETSc-based applications. More...

#include <petsc.h>
#include <stdlib.h>
#include <string.h>
#include <petscsys.h>
#include <ctype.h>
#include "variables.h"
#include "statistics_window.h"
#include "Boundaries.h"
Include dependency graph for logging.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  DualMonitorCtx
 Context for a dual-purpose KSP monitor. More...
 

Macros

#define LOCAL   0
 Logging scope definitions for controlling message output.
 
#define GLOBAL   1
 Scope for global logging across all processes.
 
#define LOG(scope, level, fmt, ...)
 Logging macro for PETSc-based applications with scope control.
 
#define LOG_DEFAULT(level, fmt, ...)
 Default logging macro for PETSc-based applications.
 
#define LOG_SYNC(scope, level, fmt, ...)
 Logging macro for PETSc-based applications with scope control, using synchronized output across processes.
 
#define LOG_SYNC_DEFAULT(level, fmt, ...)
 Default synchronized logging macro for PETSc-based applications.
 
#define LOG_LEVEL_ADMITS(level)    ((int)(level) <= (int)get_log_level() && ((int)(level) <= (int)LOG_WARNING || is_function_allowed(__func__)))
 True when a code-level diagnostic at level prints from the calling function.
 
#define LOG_ALLOW(scope, level, fmt, ...)
 Logging macro that checks both the log level and whether the calling function is in the allowed-function list before printing.
 
#define LOG_ALLOW_SYNC(scope, level, fmt, ...)
 Synchronized logging macro that checks both the log level and whether the calling function is in the allow-list.
 
#define PARTICLE_LOG_VERBOSE_ENABLED()    (PetscUnlikely((int)get_log_level() >= (int)LOG_VERBOSE) && is_function_allowed(__func__))
 True when the calling function's per-particle lines print for every particle (VERBOSE and allow-listed).
 
#define PARTICLE_IS_TRACED(simCtx, pid)    ((PetscBool)(PetscUnlikely((simCtx)->nTracePIDs > 0) && ParticleIsTraced((simCtx), (pid))))
 True when pid is traced (monitor.yml -> logging.trace_particles).
 
#define PARTICLE_LOG_ACTIVE(simCtx, pid)    ((PetscBool)(PARTICLE_IS_TRACED((simCtx), (pid)) || PARTICLE_LOG_VERBOSE_ENABLED()))
 True when LOG_PARTICLE() would print for this particle in the calling function.
 
#define LOG_PARTICLE(simCtx, pid, stage, fmt, ...)
 Reports one particle at one stage of a step: the consolidated per-particle line.
 
#define LOG_LOOP_ALLOW(scope, level, iterVar, interval, fmt, ...)
 Logs a message inside a loop, but only every interval iterations.
 
#define LOG_LOOP_ALLOW_EXACT(scope, level, var, val, fmt, ...)
 Logs a custom message if a variable equals a specific value.
 
#define LOG_ARRAY_ELEMENT_ALLOW(scope, level, arr, length, idx, fmt)
 Logs a single element of an array, given an index.
 
#define LOG_ARRAY_SUBRANGE_ALLOW(scope, level, arr, length, start, end, fmt)
 Logs a consecutive subrange of an array.
 
#define PROFILE_FUNCTION_BEGIN
 Marks the beginning of a profiled function: an always-on aggregate timer.
 
#define PROFILE_HELPER_BEGIN
 Marks the beginning of a profiled helper: timed only when enabled by name.
 
#define PROFILE_FUNCTION_END    do { if (_picurv_profile_timed) (void)PetscLogEventEnd(_picurv_profile_event, 0, 0, 0, 0); } while (0)
 Marks the end of a profiled code block.
 
#define PROFILE_HELPER_END   PROFILE_FUNCTION_END
 Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
 

Enumerations

enum  LogLevel {
  LOG_ERROR = 0 , LOG_WARNING , LOG_INFO , LOG_DEBUG ,
  LOG_TRACE , LOG_VERBOSE
}
 Enumeration of logging levels. More...
 
enum  PicurvCsvLifecycle { PICURV_CSV_APPEND = 0 , PICURV_CSV_TRUNCATE_ON_FRESH }
 What a run's first write does to an existing CSV record (see PicurvOpenRunCsv()). More...
 

Functions

static PetscBool ParticleIsTraced (const SimCtx *simCtx, PetscInt64 pid)
 True when pid is one of the run's traced particles (simCtx->tracePIDs, sorted).
 
LogLevel _ResolveLogLevel (void)
 Internal hook: read LOG_LEVEL from the environment and cache it, once.
 
static LogLevel get_log_level (void)
 Retrieves the current logging level from the environment variable LOG_LEVEL.
 
PetscErrorCode print_log_level (void)
 Prints the current logging level to the console.
 
void set_allowed_functions (const char **functionList, int count)
 Sets the global list of function names that are allowed to log.
 
PetscBool is_function_allowed (const char *functionName)
 Checks if a given function is in the allow-list.
 
PetscErrorCode LOG_CELL_VERTICES (const Cell *cell, PetscMPIInt rank)
 Prints the coordinates of a cell's vertices.
 
PetscErrorCode LOG_FACE_DISTANCES (PetscReal *d)
 Prints the signed distances to each face of the cell.
 
PetscErrorCode LOG_PARTICLE_FIELDS (UserCtx *user, PetscInt printInterval)
 Prints particle fields in a table that automatically adjusts its column widths.
 
PetscBool IsParticleConsoleSnapshotEnabled (const SimCtx *simCtx)
 Returns whether periodic particle console snapshots are enabled.
 
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot (const SimCtx *simCtx, PetscInt completed_step)
 Returns whether a particle console snapshot should be emitted for the completed timestep.
 
PetscErrorCode EmitParticleConsoleSnapshot (UserCtx *user, SimCtx *simCtx, PetscInt step)
 Emits one particle console snapshot into the main solver log.
 
PetscBool IsStatisticsConsoleSnapshotEnabled (const struct SimCtx *simCtx)
 Reports whether the periodic statistics console snapshot is enabled.
 
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot (const struct SimCtx *simCtx, PetscInt completed_step)
 Reports whether a completed step falls on the console snapshot cadence.
 
PetscErrorCode EmitStatisticsConsoleSnapshot (UserCtx *user, const struct SimCtx *simCtx, PetscInt step)
 Emits one console snapshot of window progress.
 
PetscErrorCode FreeAllowedFunctions (char **funcs, PetscInt n)
 Free an array previously returned by LoadAllowedFunctionsFromFile().
 
PetscErrorCode LoadAllowedFunctionsFromFile (const char filename[], char ***funcsOut, PetscInt *nOut)
 Load function names from a text file.
 
const char * BCFaceToString (BCFace face)
 Returns the canonical log token for a boundary-face enum value.
 
const char * ParticleInitializationToString (ParticleInitializationType ParticleInitialization)
 Returns the canonical log token for a particle-initialization mode.
 
const char * LESModelToString (LESModelType LESFlag)
 Returns the canonical log token for an LES model selector.
 
const char * LESFilterWidthModelToString (LESFilterWidthModel model)
 Returns the user-facing name of an LES grid-filter-width model.
 
const char * LESTestFilterKernelToString (LESTestFilterKernel kernel)
 Returns the user-facing name of an LES test-filter kernel.
 
const char * LESAveragingModeToString (LESAveragingMode mode)
 Returns the user-facing name of an LES coefficient-averaging mode.
 
const char * LESClipModeToString (LESClipMode mode)
 Returns the user-facing name of an LES coefficient-limiting mode.
 
const char * WallFunctionModelToString (WallFunctionModel model)
 Returns the user-facing name of a wall-function model.
 
const char * MomentumSolverTypeToString (MomentumSolverType SolverFlag)
 Returns the canonical log token for a momentum-solver selector.
 
const char * BCTypeToString (BCType type)
 Returns the canonical log token for a boundary mathematical type.
 
const char * ParticleBoundaryPolicyToString (ParticleBoundaryPolicy policy)
 Returns the configuration token for a particle boundary policy.
 
const char * InterpolationMethodToString (InterpolationMethod method)
 Returns the display name of a grid-to-particle interpolation method.
 
const char * BCHandlerTypeToString (BCHandlerType handler_type)
 Converts a BCHandlerType enum to its string representation.
 
PetscErrorCode DualKSPMonitor (KSP ksp, PetscInt it, PetscReal rnorm, void *ctx)
 A custom KSP monitor that logs to a file and optionally to the console.
 
PetscErrorCode DualMonitorDestroy (void **ctx)
 Destroys the DualMonitorCtx.
 
PetscErrorCode LOG_CONTINUITY_METRICS (UserCtx *user)
 Logs continuity metrics for a single block to a file.
 
PetscErrorCode LOG_SOLUTION_CONVERGENCE (SimCtx *simCtx)
 Logs physical solution-convergence metrics once per completed timestep.
 
const char * ParticleLocationStatusToString (ParticleLocationStatus level)
 A function that outputs the name of the current level in the ParticleLocation enum.
 
void PrintProgressBar (PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
 Prints a progress bar to the console.
 
PetscErrorCode ProfilingInitialize (SimCtx *simCtx)
 Applies the profiling configuration from SimCtx to PICurv's PETSc log events.
 
PetscErrorCode ProfilingResetTimestepCounters (void)
 Starts a new per-step profiling interval.
 
PetscErrorCode ProfilingLogTimestepSummary (SimCtx *simCtx, PetscInt step)
 Logs the performance summary for the current timestep and resets timers.
 
PetscErrorCode RuntimeMemoryLogSample (SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
 Append a reduced runtime memory sample to the configured memory log.
 
PetscErrorCode ProfilingFinalize (SimCtx *simCtx)
 Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.
 
void _ProfilingRegister (const char *func_name, PetscBool helper, PetscLogEvent *event)
 Internal profiling hook: register a call site's function as a PETSc log event.
 
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.
 
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 grid and variable architecture.
 
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.
 
PetscErrorCode LOG_INTERPOLATION_ERROR (UserCtx *user)
 Logs the interpolation error between the analytical and computed solutions.
 
PetscErrorCode LOG_SCATTER_METRICS (UserCtx *user)
 Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
 
PetscErrorCode ResetSearchMetrics (SimCtx *simCtx)
 Resets the aggregate per-timestep search instrumentation counters.
 
PetscErrorCode CalculateAdvancedParticleMetrics (UserCtx *user)
 Computes advanced particle statistics and stores them in SimCtx.
 
PetscErrorCode LOG_SEARCH_METRICS (UserCtx *user)
 Writes compact runtime search metrics to CSV and optionally to console.
 
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.
 
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.
 

Variables

const LogLevel *const _picurv_log_level
 Read-only view of the cached logging level; -1 until the first get_log_level() call.
 
const PetscBool *const _picurv_profile_helpers_on
 Read-only view: whether profiling.helpers enables any helper timer.
 

Detailed Description

Logging utilities and macros for PETSc-based applications.

This header defines logging levels, scopes, and macros for consistent logging throughout the application. It provides functions to retrieve the current logging level and macros to simplify logging with scope control.

Definition in file logging.h.


Data Structure Documentation

◆ DualMonitorCtx

struct DualMonitorCtx

Context for a dual-purpose KSP monitor.

Holds the rank-0 history file the monitor writes one CSV row per iteration to, whether the true residual is computed and echoed to the console, and the workspaces that computation keeps.

Definition at line 56 of file logging.h.

Data Fields
FILE * file_handle
PetscBool log_to_console
PetscBool true_residual
PetscReal bnorm
PetscInt step
PetscInt block_id
Vec residual_work[2]

Macro Definition Documentation

◆ LOCAL

#define LOCAL   0

Logging scope definitions for controlling message output.

  • LOCAL: Logs on the current process using MPI_COMM_SELF.
  • GLOBAL: Logs across all processes using MPI_COMM_WORLD. Scope for local logging on the current process.

Definition at line 45 of file logging.h.

◆ GLOBAL

#define GLOBAL   1

Scope for global logging across all processes.

Definition at line 46 of file logging.h.

◆ LOG

#define LOG (   scope,
  level,
  fmt,
  ... 
)
Value:
do { \
/* Determine the MPI communicator based on the scope */ \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
/* Check if the log level is within the allowed range */ \
if ((int)(level) <= (int)get_log_level()) { \
/* Print the message to the specified communicator */ \
PetscPrintf(comm, fmt, ##__VA_ARGS__); \
} \
} while (0)
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496

Logging macro for PETSc-based applications with scope control.

This macro provides a convenient way to log messages with different scopes (LOCAL or GLOBAL) and severity levels. It utilizes PETSc's PetscPrintf function for message output.

Parameters
scopeSpecifies the logging scope:
  • LOCAL: Logs on the current process using MPI_COMM_SELF.
  • GLOBAL: Logs on all processes using MPI_COMM_WORLD.
levelThe severity level of the message (e.g., LOG_INFO, LOG_ERROR).
fmtThe format string for the message (similar to printf).
...Additional arguments for the format string (optional).

Example usage: LOG(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx); LOG(GLOBAL, LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);

Definition at line 86 of file logging.h.

87 { \
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)

◆ LOG_DEFAULT

#define LOG_DEFAULT (   level,
  fmt,
  ... 
)
Value:
do { \
/* Set the communicator to global (MPI_COMM_WORLD) by default */ \
MPI_Comm comm = MPI_COMM_WORLD; \
/* Check if the log level is within the allowed range */ \
if ((int)(level) <= (int)get_log_level()) { \
/* Print the message using PetscPrintf with the global communicator */ \
PetscPrintf(comm, fmt, ##__VA_ARGS__); \
} \
} while (0)

Default logging macro for PETSc-based applications.

This macro simplifies logging by defaulting the scope to GLOBAL (i.e., MPI_COMM_WORLD) and providing a convenient interface for common logging needs.

Parameters
levelThe severity level of the message (e.g., LOG_ERROR, LOG_INFO).
fmtThe format string for the log message (similar to printf).
...Additional arguments for the format string (optional).

Example usage: LOG_DEFAULT(LOG_ERROR, "Error occurred at index %ld.\n", idx); LOG_DEFAULT(LOG_INFO, "Grid size: %ld x %ld x %ld.\n", nx, ny, nz);

Note
  • By default, this macro logs across all MPI processes using MPI_COMM_WORLD.
  • If finer control (e.g., local logging) is required, use the more general LOG macro.
  • The log level is filtered based on the value returned by get_log_level().

Definition at line 117 of file logging.h.

118 { \
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)

◆ LOG_SYNC

#define LOG_SYNC (   scope,
  level,
  fmt,
  ... 
)
Value:
do { \
/* Determine the MPI communicator based on the scope */ \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
/* Check if the log level is within the allowed range */ \
if ((int)(level) <= (int)get_log_level()) { \
/* Synchronized print (collective) on the specified communicator */ \
PetscSynchronizedPrintf(comm, fmt, ##__VA_ARGS__); \
/* Ensure all ranks have finished printing before continuing */ \
PetscSynchronizedFlush(comm, PETSC_STDOUT); \
} \
} while (0)

Logging macro for PETSc-based applications with scope control, using synchronized output across processes.

This macro uses PetscSynchronizedPrintf and PetscSynchronizedFlush to ensure messages from different ranks are printed in a synchronized (rank-by-rank) manner, preventing interleaved outputs.

Parameters
scopeSpecifies the logging scope:
  • LOCAL: Logs on the current process using MPI_COMM_SELF.
  • GLOBAL: Logs on all processes using MPI_COMM_WORLD.
levelThe severity level of the message (e.g., LOG_INFO, LOG_ERROR).
fmtThe format string for the message (similar to printf).
...Additional arguments for the format string (optional).

Example usage: LOG_SYNC(LOCAL, LOG_ERROR, "An error occurred at index %ld.\n", idx); LOG_SYNC(GLOBAL, LOG_INFO, "Synchronized info: rank = %ld.\n", rank);

Definition at line 147 of file logging.h.

148 { \
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)

◆ LOG_SYNC_DEFAULT

#define LOG_SYNC_DEFAULT (   level,
  fmt,
  ... 
)
Value:
do { \
if ((int)(level) <= (int)get_log_level()) { \
PetscSynchronizedPrintf(MPI_COMM_WORLD, fmt, ##__VA_ARGS__); \
PetscSynchronizedFlush(MPI_COMM_WORLD, PETSC_STDOUT); \
} \
} while (0)

Default synchronized logging macro for PETSc-based applications.

This macro simplifies logging by defaulting the scope to GLOBAL (i.e., MPI_COMM_WORLD) and provides synchronized output across all processes.

Parameters
levelThe severity level of the message (e.g., LOG_ERROR, LOG_INFO).
fmtThe format string for the log message (similar to printf).
...Additional arguments for the format string (optional).

Example usage: LOG_SYNC_DEFAULT(LOG_ERROR, "Error at index %ld.\n", idx); LOG_SYNC_DEFAULT(LOG_INFO, "Process rank: %ld.\n", rank);

Note
  • By default, this macro logs across all MPI processes using MPI_COMM_WORLD.
  • If local (per-process) logging is required, use the more general LOG_SYNC macro.
  • The log level is filtered based on the value returned by get_log_level().

Definition at line 180 of file logging.h.

181 { \
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)

◆ LOG_LEVEL_ADMITS

#define LOG_LEVEL_ADMITS (   level)     ((int)(level) <= (int)get_log_level() && ((int)(level) <= (int)LOG_WARNING || is_function_allowed(__func__)))

True when a code-level diagnostic at level prints from the calling function.

The level must be admitted by the run's verbosity. A warning or an error then prints from any function, since an operator running at WARNING must see it; INFO and below print only from allow-listed functions, so instrumenting one function does not drag in the others. The value is the same on every rank.

Definition at line 198 of file logging.h.

◆ LOG_ALLOW

#define LOG_ALLOW (   scope,
  level,
  fmt,
  ... 
)
Value:
do { \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
if (LOG_LEVEL_ADMITS(level)) { \
PetscPrintf(comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
} \
} while (0)
#define LOG_LEVEL_ADMITS(level)
True when a code-level diagnostic at level prints from the calling function.
Definition logging.h:198

Logging macro that checks both the log level and whether the calling function is in the allowed-function list before printing.

Useful for selective, per-function logging. Warnings and errors ignore the allow-list (see LOG_LEVEL_ADMITS()).

Parameters
scopeSpecifies the logging scope (LOCAL or GLOBAL).
levelThe severity level of the message (e.g., LOG_INFO, LOG_ERROR).
fmtThe format string for the message (similar to printf).
...Additional arguments for the format string (optional).

Example usage: LOG_ALLOW(LOCAL, LOG_DEBUG, "Debugging info in function: %s\n", func);

Definition at line 214 of file logging.h.

215 { \
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)

◆ LOG_ALLOW_SYNC

#define LOG_ALLOW_SYNC (   scope,
  level,
  fmt,
  ... 
)
Value:
do { \
/* ------------------------------------------------------------------ */ \
/* Validate scope and pick communicator *before* any early exits. */ \
/* ------------------------------------------------------------------ */ \
MPI_Comm _comm; \
if ((scope) == LOCAL) _comm = MPI_COMM_SELF; \
else if ((scope) == GLOBAL) _comm = MPI_COMM_WORLD; \
else { \
fprintf(stderr, "LOG_ALLOW_SYNC ERROR: invalid scope (%d) at %s:%d\n", \
(scope), __FILE__, __LINE__); \
MPI_Abort(MPI_COMM_WORLD, 1); \
} \
\
/* ------------------------------------------------------------------ */ \
/* Decide whether *this* rank should actually print. */ \
/* ------------------------------------------------------------------ */ \
PetscBool _doPrint = \
LOG_LEVEL_ADMITS(level); \
\
if (_doPrint) { \
PetscSynchronizedPrintf(_comm, "[%s] " fmt, __func__, ##__VA_ARGS__); \
/* Collective; _doPrint has the same value on every rank. */ \
PetscSynchronizedFlush(_comm, PETSC_STDOUT); \
} \
} while (0)
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46

Synchronized logging macro that checks both the log level and whether the calling function is in the allow-list.

This macro uses PetscSynchronizedPrintf and PetscSynchronizedFlush to ensure messages from different ranks are printed in a rank-ordered fashion (i.e., to avoid interleaving). It also filters out messages if the current function is not in the allow-list (is_function_allowed(__func__)) or the requested log level is higher than get_log_level().

With GLOBAL scope every rank prints its own line, in rank order, so the message should carry per-rank data; a value every rank shares belongs in LOG_ALLOW(GLOBAL, ...), which prints it once. The flush is collective over the scope's communicator and runs only when the message is enabled. The level and the allow-list are the same on every rank, so either every rank of the communicator flushes or none does: a disabled message costs no communication. Every rank of that communicator must still reach the call.

Parameters
scopeEither LOCAL (MPI_COMM_SELF) or GLOBAL (MPI_COMM_WORLD).
levelOne of LOG_ERROR, LOG_WARNING, LOG_INFO, LOG_DEBUG, LOG_TRACE, LOG_VERBOSE.
fmtA printf-style format string (e.g., "Message: %ld\n").
...Variadic arguments to fill in fmt.

Example usage:

LOG_ALLOW_SYNC(GLOBAL, LOG_DEBUG, "[Rank %d] owns %d cells\n", rank, ncells);
#define LOG_ALLOW_SYNC(scope, level, fmt,...)
Synchronized logging macro that checks both the log level and whether the calling function is in the ...
Definition logging.h:273
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32

Definition at line 273 of file logging.h.

274 { \
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)

◆ PARTICLE_LOG_VERBOSE_ENABLED

#define PARTICLE_LOG_VERBOSE_ENABLED ( )     (PetscUnlikely((int)get_log_level() >= (int)LOG_VERBOSE) && is_function_allowed(__func__))

True when the calling function's per-particle lines print for every particle (VERBOSE and allow-listed).

Definition at line 319 of file logging.h.

◆ PARTICLE_IS_TRACED

#define PARTICLE_IS_TRACED (   simCtx,
  pid 
)     ((PetscBool)(PetscUnlikely((simCtx)->nTracePIDs > 0) && ParticleIsTraced((simCtx), (pid))))

True when pid is traced (monitor.yml -> logging.trace_particles).

A run that traces no particle pays one load and one compare; only a run that traces some searches the sorted list.

Definition at line 327 of file logging.h.

◆ PARTICLE_LOG_ACTIVE

#define PARTICLE_LOG_ACTIVE (   simCtx,
  pid 
)     ((PetscBool)(PARTICLE_IS_TRACED((simCtx), (pid)) || PARTICLE_LOG_VERBOSE_ENABLED()))

True when LOG_PARTICLE() would print for this particle in the calling function.

For a stage whose line is costly to assemble (several fields): test this, build the text, then emit it with LOG_PARTICLE().

Definition at line 335 of file logging.h.

◆ LOG_PARTICLE

#define LOG_PARTICLE (   simCtx,
  pid,
  stage,
  fmt,
  ... 
)
Value:
do { \
const PetscBool _picurv_traced = PARTICLE_IS_TRACED((simCtx), (pid)); \
if (_picurv_traced || PARTICLE_LOG_VERBOSE_ENABLED()) { \
PetscPrintf(PETSC_COMM_SELF, "[%s pid=%lld step=%" PetscInt_FMT " %s] " fmt, \
_picurv_traced ? "trace" : __func__, (long long)(pid), (simCtx)->step, \
(stage), ##__VA_ARGS__); \
} \
} while (0)
#define PARTICLE_LOG_VERBOSE_ENABLED()
True when the calling function's per-particle lines print for every particle (VERBOSE and allow-liste...
Definition logging.h:319
#define PARTICLE_IS_TRACED(simCtx, pid)
True when pid is traced (monitor.yml -> logging.trace_particles).
Definition logging.h:327

Reports one particle at one stage of a step: the consolidated per-particle line.

Each stage that processes particles (position update, location, interpolation, model update, removal) emits at most one such line per particle, carrying every value the stage computed for it. The line prints, on the rank holding the particle, when either

  • the particle is traced (monitor.yml -> logging.trace_particles), whatever the log level and allow-list, prefixed [trace pid=<id> step=<n> <stage>]; or
  • the log level is VERBOSE and the calling function is allow-listed, prefixed with the function name. With neither, it costs two loads and two compares.
Parameters
simCtxThe simulation context (const SimCtx *).
pidThe particle ID (PetscInt64).
stageA short stage label, such as "locate".
fmtA printf-style format string ending in a newline.

Definition at line 355 of file logging.h.

356 { \
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)

◆ LOG_LOOP_ALLOW

#define LOG_LOOP_ALLOW (   scope,
  level,
  iterVar,
  interval,
  fmt,
  ... 
)
Value:
do { \
if (LOG_LEVEL_ADMITS(level)) { \
if ((iterVar) % (interval) == 0) { \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
PetscPrintf(comm, "[%s] [%s=%" PetscInt_FMT "] " fmt, \
__func__, #iterVar, (iterVar), ##__VA_ARGS__); \
} \
} \
} while (0)

Logs a message inside a loop, but only every interval iterations.

Parameters
scopeLOCAL or GLOBAL.
levelLOG_* level.
iterVarThe loop variable (e.g., i).
intervalOnly log when (iterVar % interval == 0).
fmtprintf-style format string.
...Variadic arguments to include in the formatted message.

Example: for (int i = 0; i < 100; i++) { LOG_LOOP_ALLOW(LOCAL, LOG_DEBUG, i, 10, "Value of i=%d\n", i); }

Definition at line 380 of file logging.h.

381 { \
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)

◆ LOG_LOOP_ALLOW_EXACT

#define LOG_LOOP_ALLOW_EXACT (   scope,
  level,
  var,
  val,
  fmt,
  ... 
)
Value:
do { \
/* First, perform the cheap, standard gatekeeper checks. */ \
if (LOG_LEVEL_ADMITS(level)) { \
/* Only if those pass, check the user's specific condition. */ \
if ((var) == (val)) { \
MPI_Comm comm = ((scope) == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
/* Print the standard prefix, then the user's custom message. */ \
PetscPrintf(comm, "[%s] [%s=%" PetscInt_FMT "] " fmt, \
__func__, #var, (var), ##__VA_ARGS__); \
} \
} \
} while (0)

Logs a custom message if a variable equals a specific value.

This is a variadic macro for logging a single event when a condition is met. It is extremely useful for printing debug information at a specific iteration of a loop or when a state variable reaches a certain value.

Parameters
scopeEither LOCAL or GLOBAL.
levelThe logging level.
varThe variable to check (e.g., a loop counter 'k').
valThe value that triggers the log (e.g., 6). The log prints if var == val.
fmtA printf-style format string.
...A printf-style format string and its corresponding arguments.

Definition at line 405 of file logging.h.

406 { \
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)

◆ LOG_ARRAY_ELEMENT_ALLOW

#define LOG_ARRAY_ELEMENT_ALLOW (   scope,
  level,
  arr,
  length,
  idx,
  fmt 
)
Value:
do { \
if (LOG_LEVEL_ADMITS(level)) { \
if ((idx) >= 0 && (idx) < (length)) { \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
PetscPrintf(comm, "[%s] arr[%" PetscInt_FMT "] = " fmt "\n", \
__func__, (PetscInt)(idx), (arr)[idx]); \
} \
} \
} while (0)

Logs a single element of an array, given an index.

Parameters
scopeEither LOCAL or GLOBAL.
levelLOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
arrPointer to the array to log from.
lengthThe length of the array (to prevent out-of-bounds).
idxThe index of the element to print.
fmtThe printf-style format specifier (e.g. "%g", "%f", etc.).

This macro only logs if: 1) The current function is in the allow-list (is_function_allowed(__func__)). 2) The requested logging level <= the current global get_log_level(). 3) The index idx is valid (0 <= idx < length).

Definition at line 434 of file logging.h.

435 { \
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)

◆ LOG_ARRAY_SUBRANGE_ALLOW

#define LOG_ARRAY_SUBRANGE_ALLOW (   scope,
  level,
  arr,
  length,
  start,
  end,
  fmt 
)
Value:
do { \
if (LOG_LEVEL_ADMITS(level)) { \
MPI_Comm comm = (scope == LOCAL) ? MPI_COMM_SELF : MPI_COMM_WORLD; \
PetscInt _start = (start) < 0 ? 0 : (start); \
PetscInt _end = (end) >= (length) ? (length) - 1 : (end); \
for (PetscInt i = _start; i <= _end; i++) { \
PetscPrintf(comm, "[%s] arr[%" PetscInt_FMT "] = " fmt "\n", __func__, i, (arr)[i]); \
} \
} \
} while (0)

Logs a consecutive subrange of an array.

Parameters
scopeEither LOCAL or GLOBAL.
levelLOG_ERROR, LOG_WARNING, LOG_INFO, or LOG_DEBUG.
arrPointer to the array to log from.
lengthTotal length of the array.
startStarting index of the subrange.
endEnding index of the subrange (inclusive).
fmtThe printf-style format specifier (e.g., "%g", "%f").

This macro prints each element arr[i] for i in [start, end], bounded by [0, length-1].

Definition at line 458 of file logging.h.

459 { \
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)

◆ PROFILE_FUNCTION_BEGIN

#define PROFILE_FUNCTION_BEGIN
Value:
static PetscLogEvent _picurv_profile_event = -1; \
if (PetscUnlikely(_picurv_profile_event < 0)) _ProfilingRegister(__func__, PETSC_FALSE, &_picurv_profile_event); \
const PetscBool _picurv_profile_timed = (PetscBool)(_picurv_profile_event >= 0); \
if (_picurv_profile_timed) (void)PetscLogEventBegin(_picurv_profile_event, 0, 0, 0, 0)
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

Marks the beginning of a profiled function: an always-on aggregate timer.

Place this macro at the very beginning of a function called once or a few times per step or solver pass. The function is a PETSc log event of class PICurv, named by __func__, registered on its first call and cached in a function-local static; it appears in the final profiling summary, the per-step output and log_view.

Definition at line 1000 of file logging.h.

◆ PROFILE_HELPER_BEGIN

#define PROFILE_HELPER_BEGIN
Value:
static PetscLogEvent _picurv_profile_event = -1; \
if (PetscUnlikely(_picurv_profile_event < 0)) _ProfilingRegister(__func__, PETSC_TRUE, &_picurv_profile_event); \
const PetscBool _picurv_profile_timed = (PetscBool)(*_picurv_profile_helpers_on && _picurv_profile_event >= 0); \
if (_picurv_profile_timed) (void)PetscLogEventBegin(_picurv_profile_event, 0, 0, 0, 0)
const PetscBool *const _picurv_profile_helpers_on
Read-only view: whether profiling.helpers enables any helper timer.
Definition logging.c:1934

Marks the beginning of a profiled helper: timed only when enabled by name.

For functions called per particle or per cell. The event (class PICurvHelper) is off unless profiling.helpers names it (or is all). With no helper enabled, a call costs one flag test; with some enabled, PETSc's per-event check decides. End it with PROFILE_FUNCTION_END (or its alias PROFILE_HELPER_END).

Definition at line 1014 of file logging.h.

◆ PROFILE_FUNCTION_END

#define PROFILE_FUNCTION_END    do { if (_picurv_profile_timed) (void)PetscLogEventEnd(_picurv_profile_event, 0, 0, 0, 0); } while (0)

Marks the end of a profiled code block.

Place this macro just before every return point in a function that starts with PROFILE_FUNCTION_BEGIN or PROFILE_HELPER_BEGIN. A missed one leaves the PETSc event open, and the function's later calls are then not recorded. It ends the event only if the BEGIN macro began it, and reads the state that macro declares, so it must sit in that macro's scope; a function that ends a timer it never began does not compile.

Definition at line 1029 of file logging.h.

1030 { if (_picurv_profile_timed) (void)PetscLogEventEnd(_picurv_profile_event, 0, 0, 0, 0); } while (0)

◆ PROFILE_HELPER_END

#define PROFILE_HELPER_END   PROFILE_FUNCTION_END

Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.

Definition at line 1033 of file logging.h.

Enumeration Type Documentation

◆ LogLevel

enum LogLevel

Enumeration of logging levels.

Defines various severity levels for logging messages.

Enumerator
LOG_ERROR 

Critical errors that may halt the program.

LOG_WARNING 

Non-critical issues that warrant attention.

LOG_INFO 

Informational messages about program execution.

LOG_DEBUG 

Detailed debugging information.

LOG_TRACE 

Very fine-grained tracing information for in-depth debugging.

LOG_VERBOSE 

Extremely detailed logs, typically for development use only.

Definition at line 28 of file logging.h.

28 {
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 */
35} LogLevel;
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_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34

◆ PicurvCsvLifecycle

What a run's first write does to an existing CSV record (see PicurvOpenRunCsv()).

Enumerator
PICURV_CSV_APPEND 

Every run appends: earlier runs' rows are kept.

PICURV_CSV_TRUNCATE_ON_FRESH 

A fresh run's first write empties the file; a continued run appends.

Definition at line 1144 of file logging.h.

1144 {
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. */
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

Function Documentation

◆ ParticleIsTraced()

static PetscBool ParticleIsTraced ( const SimCtx *  simCtx,
PetscInt64  pid 
)
inlinestatic

True when pid is one of the run's traced particles (simCtx->tracePIDs, sorted).

Parameters
[in]simCtxThe simulation context holding the traced IDs.
[in]pidThe particle ID to test.
Returns
PETSC_TRUE when the particle is traced.

Definition at line 306 of file logging.h.

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}
PetscInt nTracePIDs
Number of entries in tracePIDs (at most PICURV_MAX_TRACED_PARTICLES).
Definition variables.h:1089
PetscInt64 * tracePIDs
Sorted, distinct IDs of the particles whose every stage is reported (-picurv_trace_particles); NULL w...
Definition variables.h:1088

◆ _ResolveLogLevel()

LogLevel _ResolveLogLevel ( void  )

Internal hook: read LOG_LEVEL from the environment and cache it, once.

Supported levels are "ERROR", "WARNING", "INFO", "DEBUG", "TRACE", and "VERBOSE". Unset or unrecognized values default to "ERROR". Call get_log_level() instead.

Returns
LogLevel The cached logging level.

Internal hook: read LOG_LEVEL from the environment and cache it, once.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
_ResolveLogLevel()

Definition at line 101 of file logging.c.

101 {
102 if (current_log_level == -1) { // Log level not set yet
103 const char *env = getenv("LOG_LEVEL");
104 if (!env) {
105 current_log_level = LOG_ERROR; // Default level
106 }
107 else if (strcmp(env, "DEBUG") == 0) {
109 }
110 else if (strcmp(env, "INFO") == 0) {
112 }
113 else if (strcmp(env, "WARNING") == 0) {
115 }
116 else if (strcmp(env, "VERBOSE") == 0) {
118 }
119 else if (strcmp(env, "TRACE") == 0) {
121 }
122 else {
123 current_log_level = LOG_ERROR; // Default if unrecognized
124 if (PetscGlobalRank == 0) {
125 fprintf(stderr, "[WARNING] Unrecognized LOG_LEVEL '%s'; using ERROR. Valid levels: ERROR, WARNING, INFO, DEBUG, TRACE, VERBOSE.\n", env);
126 }
127 }
128 }
129 return current_log_level;
130}
static LogLevel current_log_level
Static variable to cache the current logging level.
Definition logging.c:19
Here is the caller graph for this function:

◆ get_log_level()

static LogLevel get_log_level ( void  )
inlinestatic

Retrieves the current logging level from the environment variable LOG_LEVEL.

The first call reads LOG_LEVEL (see _ResolveLogLevel()); every later call returns the cached value.

Returns
LogLevel The current logging level.

Definition at line 496 of file logging.h.

497{
498 const LogLevel level = *_picurv_log_level;
499 return PetscLikely((int)level != -1) ? level : _ResolveLogLevel();
500}
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
LogLevel _ResolveLogLevel(void)
Internal hook: read LOG_LEVEL from the environment and cache it, once.
Definition logging.c:101
Here is the call graph for this function:
Here is the caller graph for this function:

◆ print_log_level()

PetscErrorCode print_log_level ( void  )

Prints the current logging level to the console.

This function retrieves the log level using get_log_level() and prints the corresponding log level name. It helps verify the logging configuration at runtime. The log levels supported are:

  • LOG_ERROR (0) : Logs only critical errors.
  • LOG_WARNING (1) : Logs warnings and errors.
  • LOG_INFO (2) : Logs general information, warnings, and errors.
  • LOG_DEBUG (3) : Logs debugging information, info, warnings, and errors.
  • LOG_TRACE (4) : Logs fine-grained trace information.
  • LOG_VERBOSE (5) : Logs very detailed developer output. If LOG_LEVEL is not set, it defaults to LOG_ERROR.

    Returns
    PetscErrorCode 0 on success.

    Prints the current logging level to the console.

    Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

    See also
    print_log_level()

Definition at line 138 of file logging.c.

139{
140 PetscMPIInt rank;
141 PetscErrorCode ierr;
142 int level;
143 const char *level_name;
144
145 PetscFunctionBeginUser;
147 /* get MPI rank */
148 rank = PetscGlobalRank;
149
150 /* decide level name */
151 level = get_log_level();
152 level_name = (level == LOG_ERROR) ? "ERROR" :
153 (level == LOG_WARNING) ? "WARNING" :
154 (level == LOG_INFO) ? "INFO" :
155 (level == LOG_DEBUG) ? "DEBUG" :
156 (level == LOG_VERBOSE) ? "VERBOSE" :
157 (level == LOG_TRACE) ? "TRACE" :
158 "UNKNOWN";
159
160 /* print it out */
161 ierr = PetscPrintf(PETSC_COMM_SELF,
162 "Current log level: %s (%d) | rank: %d\n",
163 level_name, level, (int)rank);
164 CHKERRQ(ierr);
165
167 PetscFunctionReturn(PETSC_SUCCESS);
168}
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
Here is the call graph for this function:
Here is the caller graph for this function:

◆ set_allowed_functions()

void set_allowed_functions ( const char **  functionList,
int  count 
)

Sets the global list of function names that are allowed to log.

You can replace the entire list of allowed function names at runtime.

Parameters
functionListReplacement array of permitted function names.
countNumber of entries in functionList.

Sets the global list of function names that are allowed to log.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
set_allowed_functions()

Definition at line 176 of file logging.c.

177{
178 // 1. Free any existing entries
179 if (gAllowedFunctions) {
180 for (int i = 0; i < gNumAllowed; ++i) {
181 free(gAllowedFunctions[i]); // each was strdup'ed
182 }
183 free(gAllowedFunctions);
184 gAllowedFunctions = NULL;
185 gNumAllowed = 0;
186 }
187
188 // 2. Allocate new array
189 if (count > 0) {
190 gAllowedFunctions = (char**)malloc(sizeof(char*) * count);
191 }
192
193 // 3. Copy the new entries
194 for (int i = 0; i < count; ++i) {
195 // strdup is a POSIX function. If not available, implement your own string copy.
196 gAllowedFunctions[i] = strdup(functionList[i]);
197 }
198 gNumAllowed = count;
199}
static char ** gAllowedFunctions
Global/static array of function names allowed to log.
Definition logging.c:28
static int gNumAllowed
Number of entries in the gAllowedFunctions array.
Definition logging.c:33
Here is the caller graph for this function:

◆ is_function_allowed()

PetscBool is_function_allowed ( const char *  functionName)

Checks if a given function is in the allow-list.

This helper is used internally by the LOG_ALLOW macro.

Parameters
functionNameFunction name to query.
Returns
PETSC_TRUE when the name is enabled by the allow-list.

Checks if a given function is in the allow-list.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
is_function_allowed()

Definition at line 207 of file logging.c.

208{
209 /* no list ⇒ allow all */
210 if (gNumAllowed == 0) {
211 return PETSC_TRUE;
212 }
213
214 /* otherwise only the listed functions are allowed */
215 for (int i = 0; i < gNumAllowed; ++i) {
216 if (strcmp(gAllowedFunctions[i], functionName) == 0) {
217 return PETSC_TRUE;
218 }
219 }
220 return PETSC_FALSE;
221}
Here is the caller graph for this function:

◆ LOG_CELL_VERTICES()

PetscErrorCode LOG_CELL_VERTICES ( const Cell *  cell,
PetscMPIInt  rank 
)

Prints the coordinates of a cell's vertices.

This function iterates through the eight vertices of a given cell and prints their coordinates. It is primarily used for debugging purposes to verify the correctness of cell vertex assignments.

Parameters
[in]cellPointer to a Cell structure representing the cell, containing its vertices.
[in]rankMPI rank for identification (useful in parallel environments).
Returns
PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
Note
  • Ensure that the cell pointer is not NULL before calling this function..

Prints the coordinates of a cell's vertices.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_CELL_VERTICES()

Definition at line 229 of file logging.c.

230{
232
233 // Validate input pointers
234 if (cell == NULL) {
235 LOG_ALLOW(LOCAL,LOG_ERROR, "'cell' is NULL.\n");
236 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "LOG_CELL_VERTICES - Input parameter 'cell' is NULL.");
237 }
238
239 LOG_ALLOW(LOCAL,LOG_VERBOSE, "Rank %d, Cell Vertices:\n", rank);
240 for(int i = 0; i < 8; i++){
241 LOG_ALLOW(LOCAL,LOG_VERBOSE, " Vertex[%d]: (%.2f, %.2f, %.2f)\n",
242 i, cell->vertices[i].x, cell->vertices[i].y, cell->vertices[i].z);
243 }
244
246 return 0; // Indicate successful execution
247}
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
PetscScalar y
Definition variables.h:145
Cmpnts vertices[8]
Coordinates of the eight vertices of the cell.
Definition variables.h:219
Here is the caller graph for this function:

◆ LOG_FACE_DISTANCES()

PetscErrorCode LOG_FACE_DISTANCES ( PetscReal *  d)

Prints the signed distances to each face of the cell.

This function iterates through the six signed distances from a point to each face of a given cell and prints their values. It is primarily used for debugging purposes to verify the correctness of distance calculations.

Parameters
[in]dAn array of six PetscReal values representing the signed distances. The indices correspond to:
  • d[LEFT]: Left Face
  • d[RIGHT]: Right Face
  • d[BOTTOM]: Bottom Face
  • d[TOP]: Top Face
  • d[FRONT]: Front Face
  • d[BACK]: Back Face
Returns
PetscErrorCode Returns 0 to indicate successful execution. Non-zero on failure.
Note
  • Ensure that the d array is correctly populated with signed distances before calling this function.

Prints the signed distances to each face of the cell.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_FACE_DISTANCES()

Definition at line 256 of file logging.c.

257{
259
260 // Validate input array
261 if (d == NULL) {
262 LOG_ALLOW(LOCAL,LOG_ERROR, " 'd' is NULL.\n");
263 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, " Input array 'd' is NULL.");
264 }
265
266 PetscPrintf(PETSC_COMM_SELF, " Face Distances:\n");
267 PetscPrintf(PETSC_COMM_SELF, " LEFT(%d): %.15f\n", LEFT, d[LEFT]);
268 PetscPrintf(PETSC_COMM_SELF, " RIGHT(%d): %.15f\n", RIGHT, d[RIGHT]);
269 PetscPrintf(PETSC_COMM_SELF, " BOTTOM(%d): %.15f\n", BOTTOM, d[BOTTOM]);
270 PetscPrintf(PETSC_COMM_SELF, " TOP(%d): %.15f\n", TOP, d[TOP]);
271 PetscPrintf(PETSC_COMM_SELF, " FRONT(%d): %.15f\n", FRONT, d[FRONT]);
272 PetscPrintf(PETSC_COMM_SELF, " BACK(%d): %.15f\n", BACK, d[BACK]);
273
275 return 0; // Indicate successful execution
276}
@ TOP
Definition variables.h:197
@ FRONT
Definition variables.h:197
@ BOTTOM
Definition variables.h:197
@ BACK
Definition variables.h:197
@ LEFT
Definition variables.h:197
@ RIGHT
Definition variables.h:197
Here is the caller graph for this function:

◆ LOG_PARTICLE_FIELDS()

PetscErrorCode LOG_PARTICLE_FIELDS ( UserCtx *  user,
PetscInt  printInterval 
)

Prints particle fields in a table that automatically adjusts its column widths.

Collective. A row is printed for each particle whose ID is a multiple of printInterval, at most PICURV_SNAPSHOT_ROWS_PER_RANK per rank, so successive snapshots show the same particles and the table's size does not grow with the swarm. Column widths are agreed across ranks; one header precedes every rank's rows, and a closing line states how many rows of how many particles were shown.

Parameters
[in]userPointer to the UserCtx structure.
[in]printIntervalSampling interval on particle IDs (values below 1 mean every particle).
Returns
PetscErrorCode Returns 0 on success.

Prints particle fields in a table that automatically adjusts its column widths.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_PARTICLE_FIELDS()

Definition at line 399 of file logging.c.

400{
402 DM swarm = user->swarm;
403 PetscErrorCode ierr;
404 PetscInt localNumParticles;
405 PetscReal *positions = NULL;
406 PetscInt64 *particleIDs = NULL;
407 PetscMPIInt *particleRanks = NULL;
408 PetscInt *cellIDs = NULL;
409 PetscReal *weights = NULL;
410 PetscReal *velocities = NULL;
411 PetscInt rows[PICURV_SNAPSHOT_ROWS_PER_RANK];
412 PetscInt nRows = 0;
413 const PetscInt interval = (printInterval > 0) ? printInterval : 1;
414
415 ierr = DMSwarmGetLocalSize(swarm, &localNumParticles); CHKERRQ(ierr);
416 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions); CHKERRQ(ierr);
417 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
418 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void**)&particleRanks); CHKERRQ(ierr);
419 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
420 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
421 ierr = DMSwarmGetField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&velocities); CHKERRQ(ierr);
422
423 /* Rows: the particles whose ID is a multiple of the interval, so a later snapshot shows the
424 * same particles wherever they moved, and at most PICURV_SNAPSHOT_ROWS_PER_RANK per rank. */
425 for (PetscInt i = 0; i < localNumParticles && nRows < PICURV_SNAPSHOT_ROWS_PER_RANK; i++) {
426 if (particleIDs[i] % interval == 0) rows[nRows++] = i;
427 }
428
429 /* Column widths agreed across ranks, so every rank's rows align under one header. */
430 int widths[6];
431 ierr = ComputeMaxColumnWidths(nRows, rows, particleRanks, particleIDs, cellIDs,
432 positions, velocities, weights, widths); CHKERRQ(ierr);
433 ierr = MPI_Allreduce(MPI_IN_PLACE, widths, 6, MPI_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
434
435 char headerFmt[256];
436 char rowFmt[256];
437 BuildHeaderString(headerFmt, sizeof(headerFmt), widths);
438 BuildRowFormatString(widths, rowFmt, sizeof(rowFmt));
439
440 /* The header once (rank 0 prints first), then every rank's rows in rank order. */
441 if (user->simCtx->rank == 0) {
442 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
443 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "%s", headerFmt); CHKERRQ(ierr);
444 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
445 }
446 char rowStr[256];
447 for (PetscInt r = 0; r < nRows; r++) {
448 const PetscInt i = rows[r];
449 char cellStr[TMP_BUF_SIZE], posStr[TMP_BUF_SIZE], velStr[TMP_BUF_SIZE], wtStr[TMP_BUF_SIZE];
450 CellToStr(&cellIDs[3*i], cellStr, TMP_BUF_SIZE);
451 TripleRealToStr(&positions[3*i], posStr, TMP_BUF_SIZE);
452 TripleRealToStr(&velocities[3*i], velStr, TMP_BUF_SIZE);
453 TripleRealToStr(&weights[3*i], wtStr, TMP_BUF_SIZE);
454 snprintf(rowStr, sizeof(rowStr), rowFmt, particleRanks[i], particleIDs[i], cellStr, posStr, velStr, wtStr);
455 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, "%s", rowStr); CHKERRQ(ierr);
456 }
457 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
458
459 {
460 PetscInt64 counts[2] = {(PetscInt64)localNumParticles, (PetscInt64)nRows};
461 ierr = MPI_Allreduce(MPI_IN_PLACE, counts, 2, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
462 ierr = PetscPrintf(PETSC_COMM_WORLD, "--------------------------------------------------------------------------------------------------------------\n"); CHKERRQ(ierr);
463 ierr = PetscPrintf(PETSC_COMM_WORLD, "%lld row(s) of %lld particle(s): IDs that are multiples of %" PetscInt_FMT ", at most %d per rank.\n\n",
464 (long long)counts[1], (long long)counts[0], interval, PICURV_SNAPSHOT_ROWS_PER_RANK); CHKERRQ(ierr);
465 }
466
467 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&positions); CHKERRQ(ierr);
468 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_PID), NULL, NULL, (void**)&particleIDs); CHKERRQ(ierr);
469 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_RANK), NULL, NULL, (void**)&particleRanks); CHKERRQ(ierr);
470 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_CELL_ID), NULL, NULL, (void**)&cellIDs); CHKERRQ(ierr);
471 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_WEIGHT), NULL, NULL, (void**)&weights); CHKERRQ(ierr);
472 ierr = DMSwarmRestoreField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), NULL, NULL, (void**)&velocities); CHKERRQ(ierr);
474 return 0;
475}
static void BuildHeaderString(char *headerStr, size_t bufSize, const int widths[6])
Definition logging.c:379
static PetscErrorCode ComputeMaxColumnWidths(PetscInt nRows, const PetscInt *rows, const PetscMPIInt *ranks, const PetscInt64 *pids, const PetscInt *cellIDs, const PetscReal *positions, const PetscReal *velocities, const PetscReal *weights, int widths[6])
Definition logging.c:324
#define TMP_BUF_SIZE
Definition logging.c:10
static void BuildRowFormatString(const int widths[6], char *fmtStr, size_t bufSize)
Definition logging.c:367
static void CellToStr(const PetscInt *cell, char *buf, size_t bufsize)
Definition logging.c:301
static void TripleRealToStr(const PetscReal *arr, char *buf, size_t bufsize)
Definition logging.c:311
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_WEIGHT
@ PARTICLE_FIELD_ID_POSITION
@ PARTICLE_FIELD_ID_PID
@ PARTICLE_FIELD_ID_CELL_ID
@ PARTICLE_FIELD_ID_RANK
@ PARTICLE_FIELD_ID_VELOCITY
PetscMPIInt rank
Definition variables.h:919
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
#define PICURV_SNAPSHOT_ROWS_PER_RANK
Most rows one rank contributes to a particle console snapshot (io.particle_log_interval samples IDs).
Definition variables.h:72
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsParticleConsoleSnapshotEnabled()

PetscBool IsParticleConsoleSnapshotEnabled ( const SimCtx *  simCtx)

Returns whether periodic particle console snapshots are enabled.

This checks only the reporting contract (particles exist, cadence is enabled, and the global log level is at least INFO).

Parameters
simCtxSimulation context controlling the operation (NULL means disabled).
Returns
PETSC_TRUE when snapshots are enabled.

Returns whether periodic particle console snapshots are enabled.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
IsParticleConsoleSnapshotEnabled()

Definition at line 484 of file logging.c.

485{
487 const PetscBool enabled = (PetscBool)(simCtx && ParticlesEnabled(simCtx) &&
488 simCtx->particleConsoleOutputFreq > 0 &&
491 return enabled;
492}
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
Definition variables.h:1143
PetscInt particleConsoleOutputFreq
Definition variables.h:931
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ShouldEmitPeriodicParticleConsoleSnapshot()

PetscBool ShouldEmitPeriodicParticleConsoleSnapshot ( const SimCtx *  simCtx,
PetscInt  completed_step 
)

Returns whether a particle console snapshot should be emitted for the completed timestep.

True when snapshots are enabled (IsParticleConsoleSnapshotEnabled()) and the positive completed_step is a multiple of the snapshot cadence.

Parameters
simCtxSimulation context controlling the operation.
completed_stepCompleted step index used by the decision helper.
Returns
PETSC_TRUE when a snapshot is due.

Returns whether a particle console snapshot should be emitted for the completed timestep.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ShouldEmitPeriodicParticleConsoleSnapshot()

Definition at line 501 of file logging.c.

502{
504 const PetscBool due = (PetscBool)(IsParticleConsoleSnapshotEnabled(simCtx) &&
505 completed_step > 0 &&
506 completed_step % simCtx->particleConsoleOutputFreq == 0);
508 return due;
509}
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Implementation of IsParticleConsoleSnapshotEnabled().
Definition logging.c:484
Here is the call graph for this function:
Here is the caller graph for this function:

◆ EmitParticleConsoleSnapshot()

PetscErrorCode EmitParticleConsoleSnapshot ( UserCtx *  user,
SimCtx *  simCtx,
PetscInt  step 
)

Emits one particle console snapshot into the main solver log.

Parameters
userPrimary UserCtx input for the operation.
simCtxSimulation context controlling the operation.
stepStep index associated with the operation.
Returns
PetscErrorCode 0 on success.

Emits one particle console snapshot into the main solver log.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
EmitParticleConsoleSnapshot()

Definition at line 518 of file logging.c.

519{
520 PetscErrorCode ierr;
521
522 PetscFunctionBeginUser;
524 LOG(GLOBAL, LOG_INFO, "Particle states at step %" PetscInt_FMT ":\n", step);
525 ierr = LOG_PARTICLE_FIELDS(user, simCtx->LoggingFrequency); CHKERRQ(ierr);
527 PetscFunctionReturn(0);
528}
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Implementation of LOG_PARTICLE_FIELDS().
Definition logging.c:399
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
PetscInt LoggingFrequency
Definition variables.h:1087
Here is the call graph for this function:
Here is the caller graph for this function:

◆ IsStatisticsConsoleSnapshotEnabled()

PetscBool IsStatisticsConsoleSnapshotEnabled ( const struct SimCtx *  simCtx)

Reports whether the periodic statistics console snapshot is enabled.

Mirrors the particle console gate: the subsystem must be active, the configured cadence positive, and the effective log level at least LOG_INFO.

Parameters
[in]simCtxSimulation context to inspect.
Returns
PETSC_TRUE when snapshots should be emitted.
Here is the caller graph for this function:

◆ ShouldEmitPeriodicStatisticsConsoleSnapshot()

PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot ( const struct SimCtx *  simCtx,
PetscInt  completed_step 
)

Reports whether a completed step falls on the console snapshot cadence.

Parameters
[in]simCtxSimulation context to inspect.
[in]completed_stepStep that has just completed.
Returns
PETSC_TRUE when a snapshot is due for this step.
Here is the caller graph for this function:

◆ EmitStatisticsConsoleSnapshot()

PetscErrorCode EmitStatisticsConsoleSnapshot ( UserCtx *  user,
const struct SimCtx *  simCtx,
PetscInt  step 
)

Emits one console snapshot of window progress.

Reports window-level scalars only; it never dumps field data.

Parameters
[in]userFinest-level block array supplying accumulator state.
[in]simCtxSimulation context carrying the window array.
[in]stepStep the snapshot describes.
Returns
Zero on success.
Here is the caller graph for this function:

◆ FreeAllowedFunctions()

PetscErrorCode FreeAllowedFunctions ( char **  funcs,
PetscInt  n 
)

Free an array previously returned by LoadAllowedFunctionsFromFile().

Parameters
[in,out]funcsArray of strings to release (may be NULL).
[in]nNumber of entries in funcs. Ignored if funcs is NULL.
Returns
0 on success or a PETSc error code.

Free an array previously returned by LoadAllowedFunctionsFromFile().

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
FreeAllowedFunctions()

Definition at line 619 of file logging.c.

620{
621 PetscErrorCode ierr;
622 PetscFunctionBegin;
624 if (funcs) {
625 for (PetscInt i = 0; i < n; ++i) {
626 ierr = PetscFree(funcs[i]); CHKERRQ(ierr);
627 }
628 ierr = PetscFree(funcs); CHKERRQ(ierr);
629 }
631 PetscFunctionReturn(0);
632}
Here is the caller graph for this function:

◆ LoadAllowedFunctionsFromFile()

PetscErrorCode LoadAllowedFunctionsFromFile ( const char  filename[],
char ***  funcsOut,
PetscInt *  nOut 
)

Load function names from a text file.

The file is expected to contain one identifier per line. Blank lines and lines whose first non‑blank character is a # are silently skipped so the file can include comments. Example:

# Allowed function list
InitializeSimulation
InterpolateAllFieldsToSwarm # inline comments are OK, too
PetscErrorCode InterpolateAllFieldsToSwarm(UserCtx *user)
Interpolates the Eulerian fields the particles carry to every local particle.
int main(int argc, char **argv)
Entry point for the postprocessor executable.

The routine allocates memory as needed (growing an internal buffer with PetscRealloc()) and returns the resulting array and its length to the caller. Use FreeAllowedFunctions() to clean up when done.

Parameters
[in]filenamePath of the configuration file to read.
[out]funcsOutOn success, points to a freshly‑allocated array of char* (size nOut).
[out]nOutNumber of valid entries in funcsOut.
Returns
0 on success, or a PETSc error code on failure (e.g. I/O error, OOM).

Load function names from a text file.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LoadAllowedFunctionsFromFile()

Definition at line 561 of file logging.c.

564{
565 FILE *fp = NULL;
566 char **funcs = NULL;
567 size_t cap = 16; /* initial capacity */
568 size_t n = 0; /* number of names */
569 char line[PETSC_MAX_PATH_LEN];
570 PetscErrorCode ierr;
571
572 PetscFunctionBegin;
574
575 /* ---------------------------------------------------------------------- */
576 /* 1. Open file */
577 fp = fopen(filename, "r");
578 if (!fp) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
579 "Cannot open %s", filename);
580
581 /* 2. Allocate initial pointer array */
582 ierr = PetscMalloc1(cap, &funcs); CHKERRQ(ierr);
583
584 /* 3. Read file line by line */
585 while (fgets(line, sizeof line, fp)) {
586 /* Strip everything after a comment character '#'. */
587 char *hash = strchr(line, '#');
588 if (hash) *hash = '\0';
589
590 trim(line); /* remove leading/trailing blanks */
591 if (!*line) continue; /* skip if empty */
592
593 /* Grow the array if necessary */
594 if (n == cap) {
595 cap *= 2;
596 ierr = PetscRealloc(cap * sizeof(*funcs), (void **)&funcs); CHKERRQ(ierr);
597 }
598
599 /* Deep‑copy the cleaned identifier */
600 ierr = PetscStrallocpy(line, &funcs[n++]); CHKERRQ(ierr);
601 }
602 fclose(fp);
603
604 /* 4. Return results to caller */
605 *funcsOut = funcs;
606 *nOut = (PetscInt)n;
607
609 PetscFunctionReturn(0);
610}
static void trim(char *s)
Remove leading and trailing whitespace from a mutable configuration string.
Definition logging.c:534
Here is the call graph for this function:
Here is the caller graph for this function:

◆ BCFaceToString()

const char * BCFaceToString ( BCFace  face)

Returns the canonical log token for a boundary-face enum value.

Parameters
[in]faceThe BCFace enum value.
Returns
Pointer to a constant string representing the face.

Returns the canonical log token for a boundary-face enum value.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
BCFaceToString()

Definition at line 640 of file logging.c.

640 {
642 const char *name;
643 switch (face) {
644 case BC_FACE_NEG_X: name = "-Xi (I-Min)"; break;
645 case BC_FACE_POS_X: name = "+Xi (I-Max)"; break;
646 case BC_FACE_NEG_Y: name = "-Eta (J-Min)"; break;
647 case BC_FACE_POS_Y: name = "+Eta (J-Max)"; break;
648 case BC_FACE_NEG_Z: name = "-Zeta (K-Min)"; break;
649 case BC_FACE_POS_Z: name = "+Zeta (K-Max)"; break;
650 default: name = "Unknown Face"; break;
651 }
653 return name;
654}
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
@ BC_FACE_POS_Y
Definition variables.h:310
@ BC_FACE_NEG_Z
Definition variables.h:311
@ BC_FACE_POS_X
Definition variables.h:309
@ BC_FACE_NEG_Y
Definition variables.h:310
Here is the caller graph for this function:

◆ ParticleInitializationToString()

const char * ParticleInitializationToString ( ParticleInitializationType  ParticleInitialization)

Returns the canonical log token for a particle-initialization mode.

Parameters
[in]ParticleInitializationThe ParticleInitialization enum value.
Returns
Pointer to a constant string representing the particle initialization type.

Returns the canonical log token for a particle-initialization mode.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ParticleInitializationToString()

Definition at line 662 of file logging.c.

663{
665 const char *name;
666 switch(ParticleInitialization){
667 case PARTICLE_INIT_SURFACE_RANDOM: name = "Surface: Random"; break;
668 case PARTICLE_INIT_VOLUME: name = "Volume"; break;
669 case PARTICLE_INIT_POINT_SOURCE: name = "Point Source"; break;
670 default: name = "Unknown Particle Initialization"; break;
671 }
673 return name;
674}
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
@ PARTICLE_INIT_POINT_SOURCE
All particles at a fixed (psrc_x,psrc_y,psrc_z) — for validation.
Definition variables.h:749
@ PARTICLE_INIT_VOLUME
Random volumetric distribution across the domain.
Definition variables.h:748
Here is the caller graph for this function:

◆ LESModelToString()

const char * LESModelToString ( LESModelType  LESFlag)

Returns the canonical log token for an LES model selector.

Parameters
[in]LESFlagThe LES flag value.
Returns
Pointer to a constant string representing the LES Flag.

Returns the canonical log token for an LES model selector.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LESModelToString()

Definition at line 682 of file logging.c.

683{
685 const char *name;
686 switch(LESFlag){
687 case NO_LES_MODEL: name = "No LES"; break;
688 case CONSTANT_SMAGORINSKY: name = "Constant Smagorinsky"; break;
689 case DYNAMIC_SMAGORINSKY: name = "Dynamic Smagorinsky"; break;
690 case VREMAN: name = "Vreman"; break;
691 case WALE: name = "WALE"; break;
692 default: name = "Unknown LES Flag"; break;
693 }
695 return name;
696}
@ DYNAMIC_SMAGORINSKY
Definition variables.h:586
@ VREMAN
Definition variables.h:587
@ NO_LES_MODEL
Definition variables.h:584
@ WALE
Definition variables.h:588
@ CONSTANT_SMAGORINSKY
Definition variables.h:585
Here is the caller graph for this function:

◆ LESFilterWidthModelToString()

const char * LESFilterWidthModelToString ( LESFilterWidthModel  model)

Returns the user-facing name of an LES grid-filter-width model.

Parameters
[in]modelThe filter-width model selector.
Returns
Pointer to a constant string naming the model.

Returns the user-facing name of an LES grid-filter-width model.

Full API contract is documented with the header declaration in include/logging.h.

See also
LESFilterWidthModelToString()

Definition at line 704 of file logging.c.

705{
707 const char *name;
708 /* These spellings are the user-facing YAML values, so a banner line can be pasted
709 back into a case file without translation. */
710 switch(model){
711 case LES_FILTER_WIDTH_CUBE_ROOT_VOLUME: name = "cube_root_volume"; break;
712 case LES_FILTER_WIDTH_GEOMETRIC_MEAN: name = "geometric_mean"; break;
713 case LES_FILTER_WIDTH_MAX_EDGE: name = "max_edge"; break;
714 case LES_FILTER_WIDTH_SCOTTI: name = "scotti"; break;
715 default: name = "unknown"; break;
716 }
718 return name;
719}
@ LES_FILTER_WIDTH_SCOTTI
Definition variables.h:618
@ LES_FILTER_WIDTH_GEOMETRIC_MEAN
Definition variables.h:616
@ LES_FILTER_WIDTH_CUBE_ROOT_VOLUME
Definition variables.h:615
@ LES_FILTER_WIDTH_MAX_EDGE
Definition variables.h:617
Here is the caller graph for this function:

◆ LESTestFilterKernelToString()

const char * LESTestFilterKernelToString ( LESTestFilterKernel  kernel)

Returns the user-facing name of an LES test-filter kernel.

Parameters
[in]kernelThe test-filter kernel selector.
Returns
Pointer to a constant string naming the kernel.

Returns the user-facing name of an LES test-filter kernel.

Full API contract is documented with the header declaration in include/logging.h.

See also
LESTestFilterKernelToString()

Definition at line 727 of file logging.c.

728{
730 const char *name;
731 switch(kernel){
732 case LES_TEST_FILTER_VOLUME_WEIGHTED_BOX: name = "volume_weighted_box"; break;
733 case LES_TEST_FILTER_SIMPSON_IK: name = "simpson_ik"; break;
734 default: name = "unknown"; break;
735 }
737 return name;
738}
@ LES_TEST_FILTER_SIMPSON_IK
Definition variables.h:628
@ LES_TEST_FILTER_VOLUME_WEIGHTED_BOX
Definition variables.h:627
Here is the caller graph for this function:

◆ LESAveragingModeToString()

const char * LESAveragingModeToString ( LESAveragingMode  mode)

Returns the user-facing name of an LES coefficient-averaging mode.

Parameters
[in]modeThe averaging mode selector.
Returns
Pointer to a constant string naming the mode.

Returns the user-facing name of an LES coefficient-averaging mode.

Full API contract is documented with the header declaration in include/logging.h.

See also
LESAveragingModeToString()

Definition at line 746 of file logging.c.

747{
749 const char *name;
750 switch(mode){
751 case LES_AVERAGING_LOCAL: name = "local"; break;
752 case LES_AVERAGING_HOMOGENEOUS: name = "homogeneous"; break;
753 case LES_AVERAGING_GLOBAL: name = "global"; break;
754 default: name = "unknown"; break;
755 }
757 return name;
758}
@ LES_AVERAGING_LOCAL
Definition variables.h:640
@ LES_AVERAGING_GLOBAL
Definition variables.h:642
@ LES_AVERAGING_HOMOGENEOUS
Definition variables.h:641
Here is the caller graph for this function:

◆ LESClipModeToString()

const char * LESClipModeToString ( LESClipMode  mode)

Returns the user-facing name of an LES coefficient-limiting mode.

Parameters
[in]modeThe limiting mode selector.
Returns
Pointer to a constant string naming the mode.

Returns the user-facing name of an LES coefficient-limiting mode.

Full API contract is documented with the header declaration in include/logging.h.

See also
LESClipModeToString()

Definition at line 766 of file logging.c.

767{
769 const char *name;
770 switch(mode){
771 case LES_CLIP_CLAMP: name = "clamp"; break;
772 case LES_CLIP_CLIP_NEGATIVE: name = "clip_negative"; break;
773 case LES_CLIP_NONE: name = "none"; break;
774 default: name = "unknown"; break;
775 }
777 return name;
778}
@ LES_CLIP_CLIP_NEGATIVE
Definition variables.h:654
@ LES_CLIP_CLAMP
Definition variables.h:653
@ LES_CLIP_NONE
Definition variables.h:655
Here is the caller graph for this function:

◆ WallFunctionModelToString()

const char * WallFunctionModelToString ( WallFunctionModel  model)

Returns the user-facing name of a wall-function model.

Parameters
[in]modelThe wall-model selector.
Returns
Pointer to a constant string naming the model, or "none" when disabled.

Returns the user-facing name of a wall-function model.

Full API contract is documented with the header declaration in include/logging.h.

See also
WallFunctionModelToString()

Definition at line 786 of file logging.c.

787{
789 const char *name;
790 /* User-facing YAML spellings, so a banner line can be pasted back into a case. */
791 switch(model){
792 case WALL_FUNCTION_NONE: name = "none"; break;
793 case WALL_FUNCTION_LOG_LAW: name = "log_law"; break;
794 case WALL_FUNCTION_WERNER: name = "werner"; break;
795 case WALL_FUNCTION_CABOT: name = "cabot"; break;
796 default: name = "unknown"; break;
797 }
799 return name;
800}
@ WALL_FUNCTION_CABOT
Definition variables.h:604
@ WALL_FUNCTION_LOG_LAW
Definition variables.h:602
@ WALL_FUNCTION_WERNER
Definition variables.h:603
@ WALL_FUNCTION_NONE
Definition variables.h:601
Here is the caller graph for this function:

◆ MomentumSolverTypeToString()

const char * MomentumSolverTypeToString ( MomentumSolverType  SolverFlag)

Returns the canonical log token for a momentum-solver selector.

Parameters
[in]SolverFlagThe Momentum Solver flag value.
Returns
Pointer to a constant string representing the MomentumSolverType.

Returns the canonical log token for a momentum-solver selector.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
MomentumSolverTypeToString()

Definition at line 808 of file logging.c.

809{
811 const char *name;
812 switch(SolverFlag){
813 case MOMENTUM_SOLVER_EXPLICIT_RK: name = "Explicit 4 stage Runge-Kutta "; break;
814 case MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK: name = "Dual Time Picard with 4-stage Jameson RK Smoothing"; break;
815 case MOMENTUM_SOLVER_NEWTON_KRYLOV: name = "Newton Krylov"; break;
816 default: name = "Unknown Momentum Solver Type"; break;
817 }
819 return name;
820}
@ MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK
Definition variables.h:731
@ MOMENTUM_SOLVER_EXPLICIT_RK
Definition variables.h:730
@ MOMENTUM_SOLVER_NEWTON_KRYLOV
Definition variables.h:732
Here is the caller graph for this function:

◆ BCTypeToString()

const char * BCTypeToString ( BCType  type)

Returns the canonical log token for a boundary mathematical type.

Parameters
[in]typeThe BCType enum value.
Returns
Pointer to a constant string representing the BC type.

Returns the canonical log token for a boundary mathematical type.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
BCTypeToString()

Definition at line 828 of file logging.c.

828 {
830 const char *name;
831 switch (type) {
832 case WALL: name = "WALL"; break;
833 case INLET: name = "INLET"; break;
834 case OUTLET: name = "OUTLET"; break;
835 case FARFIELD: name = "FARFIELD"; break;
836 case PERIODIC: name = "PERIODIC"; break;
837 case INTERFACE: name = "INTERFACE"; break;
838 default: name = "Unknown BC Type"; break;
839 }
841 return name;
842}
@ INLET
Definition variables.h:323
@ INTERFACE
Definition variables.h:318
@ FARFIELD
Definition variables.h:324
@ OUTLET
Definition variables.h:322
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
Here is the caller graph for this function:

◆ ParticleBoundaryPolicyToString()

const char * ParticleBoundaryPolicyToString ( ParticleBoundaryPolicy  policy)

Returns the configuration token for a particle boundary policy.

Parameters
[in]policyThe ParticleBoundaryPolicy enum value.
Returns
Pointer to a constant string: "remove", "reflect" or "wrap".

Returns the configuration token for a particle boundary policy.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ParticleBoundaryPolicyToString()

Definition at line 850 of file logging.c.

850 {
852 const char *name;
853 switch (policy) {
854 case PARTICLE_BOUNDARY_REMOVE: name = "remove"; break;
855 case PARTICLE_BOUNDARY_REFLECT: name = "reflect"; break;
856 case PARTICLE_BOUNDARY_WRAP: name = "wrap"; break;
857 default: name = "Unknown particle boundary policy"; break;
858 }
860 return name;
861}
@ PARTICLE_BOUNDARY_REMOVE
The particle leaves the domain (EXITED) and is removed.
Definition variables.h:337
@ PARTICLE_BOUNDARY_REFLECT
The particle is mirrored about the face plane and stays.
Definition variables.h:338
@ PARTICLE_BOUNDARY_WRAP
Periodic faces: the particle re-enters through the paired face.
Definition variables.h:339
Here is the caller graph for this function:

◆ InterpolationMethodToString()

const char * InterpolationMethodToString ( InterpolationMethod  method)

Returns the display name of a grid-to-particle interpolation method.

Parameters
[in]methodThe InterpolationMethod enum value.
Returns
Pointer to a constant string naming the method, as the banner and logs print it.

Returns the display name of a grid-to-particle interpolation method.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
InterpolationMethodToString()

Definition at line 869 of file logging.c.

869 {
871 const char *name;
872 switch (method) {
873 case INTERP_TRILINEAR: name = "Trilinear (direct cell-center)"; break;
874 case INTERP_CORNER_AVERAGED: name = "CornerAveraged (legacy)"; break;
875 case INTERP_FACE_FLUX: name = "FaceFlux (divergence-free velocity from face fluxes)"; break;
876 default: name = "Unknown interpolation method"; break;
877 }
879 return name;
880}
@ INTERP_CORNER_AVERAGED
Definition variables.h:762
@ INTERP_FACE_FLUX
Definition variables.h:763
@ INTERP_TRILINEAR
Definition variables.h:761
Here is the caller graph for this function:

◆ BCHandlerTypeToString()

const char * BCHandlerTypeToString ( BCHandlerType  handler_type)

Converts a BCHandlerType enum to its string representation.

Provides a descriptive string for a specific boundary condition implementation strategy. This is crucial for logging the exact behavior configured for a face.

Parameters
handler_typeThe BCHandlerType enum value (e.g., BC_HANDLER_WALL_NOSLIP).
Returns
A constant character string corresponding to the enum. Returns "UNKNOWN_HANDLER" if the enum value is not recognized.

Converts a BCHandlerType enum to its string representation.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
BCHandlerTypeToString()

Definition at line 888 of file logging.c.

888 {
890 const char *name;
891 switch (handler_type) {
892 // Wall Handlers
893 case BC_HANDLER_WALL_NOSLIP: name = "noslip"; break;
894 case BC_HANDLER_WALL_MOVING: name = "moving"; break;
895 case BC_HANDLER_WALL_FREE_SLIP: name = "free_slip"; break;
896
897 // Inlet Handlers
898 case BC_HANDLER_INLET_PRESCRIBED_VELOCITY: name = "prescribed_velocity"; break;
899
900 // Outlet Handlers
901 case BC_HANDLER_OUTLET_CONSERVATION: name = "conservation"; break;
902 case BC_HANDLER_OUTLET_PRESSURE: name = "pressure"; break;
903
904 // Other Physical Handlers
905 case BC_HANDLER_FARFIELD_NONREFLECTING: name = "nonreflecting"; break;
906
907 // Multi-Block / Interface Handlers
908 case BC_HANDLER_PERIODIC_GEOMETRIC: name = "geometric"; break;
909 case BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX: name = "constant flux"; break;
910 case BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX: name = "initial flux"; break;
911 case BC_HANDLER_INTERFACE_OVERSET: name = "overset"; break;
912
913 // Default case
915 default: name = "UNKNOWN_HANDLER"; break;
916 }
918 return name;
919}
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
@ BC_HANDLER_PERIODIC_DRIVEN_INITIAL_FLUX
Definition variables.h:355
@ BC_HANDLER_INTERFACE_OVERSET
Definition variables.h:353
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_WALL_MOVING
Definition variables.h:346
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
@ BC_HANDLER_OUTLET_CONSERVATION
Definition variables.h:350
@ BC_HANDLER_WALL_FREE_SLIP
Definition variables.h:347
@ BC_HANDLER_FARFIELD_NONREFLECTING
Definition variables.h:349
@ BC_HANDLER_OUTLET_PRESSURE
Definition variables.h:351
@ BC_HANDLER_UNDEFINED
Definition variables.h:344
Here is the caller graph for this function:

◆ DualKSPMonitor()

PetscErrorCode DualKSPMonitor ( KSP  ksp,
PetscInt  it,
PetscReal  rnorm,
void *  ctx 
)

A custom KSP monitor that logs to a file and optionally to the console.

On rank 0 it writes one CSV row per iteration to the context's history file, when one is open, and prints the same values when log_to_console is set. When the context asks for the true residual it also computes the true and relative residual norms (collective).

Parameters
kspThe Krylov subspace context.
itThe current iteration number.
rnormThe preconditioned residual norm.
ctxA pointer to the DualMonitorCtx structure.
Returns
PetscErrorCode 0 on success.

A custom KSP monitor that logs to a file and optionally to the console.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
DualKSPMonitor()

Definition at line 955 of file logging.c.

956{
957 DualMonitorCtx *monctx = (DualMonitorCtx*)ctx;
958 PetscErrorCode ierr;
959 PetscReal trnorm = 0.0, relnorm;
960 Vec r;
961 char norm_buf[256];
962 PetscMPIInt rank;
963
964 PetscFunctionBeginUser;
966 rank = PetscGlobalRank;
967
968 // 1. The true residual, when asked for: it costs a residual build and a norm per iteration.
969 // Both workspaces are fully overwritten on each call, so they are kept rather than
970 // created and destroyed every iteration.
971 if (monctx->true_residual) {
972 Vec b;
973 ierr = KSPGetRhs(ksp, &b); CHKERRQ(ierr);
974 if (!monctx->residual_work[0]) {
975 Vec x;
976 ierr = KSPGetSolution(ksp, &x); CHKERRQ(ierr);
977 ierr = VecDuplicate(x, &monctx->residual_work[0]); CHKERRQ(ierr);
978 ierr = VecDuplicate(b, &monctx->residual_work[1]); CHKERRQ(ierr);
979 }
980 ierr = KSPBuildResidual(ksp, monctx->residual_work[0], monctx->residual_work[1], &r); CHKERRQ(ierr);
981 ierr = VecNorm(r, NORM_2, &trnorm); CHKERRQ(ierr);
982
983 // 2. On the first iteration, compute and store the norm of the RHS vector `b`.
984 if (it == 0) {
985 ierr = VecNorm(b, NORM_2, &monctx->bnorm); CHKERRQ(ierr);
986 }
987 }
988
989 if(!rank){
990 const PetscBool have_rel = (PetscBool)(monctx->true_residual && monctx->bnorm > 1.e-15);
991 relnorm = have_rel ? trnorm / monctx->bnorm : 0.0;
992
993 // 3. The history file: one CSV row per iteration.
994 if (monctx->file_handle) {
995 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%d,%d,%d,%.5e,", (int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm); CHKERRQ(ierr);
996 if (monctx->true_residual) { ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%.5e", (double)trnorm); CHKERRQ(ierr); }
997 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, ","); CHKERRQ(ierr);
998 if (have_rel) { ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "%.5e", (double)relnorm); CHKERRQ(ierr); }
999 ierr = PetscFPrintf(PETSC_COMM_SELF, monctx->file_handle, "\n"); CHKERRQ(ierr);
1000 }
1001 // 4. The console, when asked for: the same values, readable.
1002 if (monctx->log_to_console) {
1003 if (have_rel) sprintf(norm_buf, "ts: %-5d | block: %-2d | iter: %-3d | Unprecond Norm: %12.5e | True Norm: %12.5e | Rel Norm: %12.5e",(int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm, (double)trnorm, (double)relnorm);
1004 else sprintf(norm_buf, "ts: %-5d | block: %-2d | iter: %-3d | Unprecond Norm: %12.5e | True Norm: %12.5e",(int)monctx->step, (int)monctx->block_id, (int)it, (double)rnorm, (double)trnorm);
1005 ierr = PetscFPrintf(PETSC_COMM_SELF, stdout, "%s\n", norm_buf); CHKERRQ(ierr);
1006 }
1007 } //rank
1008
1010 PetscFunctionReturn(0);
1011}
Vec residual_work[2]
Definition logging.h:63
PetscBool true_residual
Definition logging.h:59
PetscBool log_to_console
Definition logging.h:58
PetscReal bnorm
Definition logging.h:60
PetscInt step
Definition logging.h:61
FILE * file_handle
Definition logging.h:57
PetscInt block_id
Definition logging.h:62
Context for a dual-purpose KSP monitor.
Definition logging.h:56
Here is the caller graph for this function:

◆ DualMonitorDestroy()

PetscErrorCode DualMonitorDestroy ( void **  ctx)

Destroys the DualMonitorCtx.

This function is passed to KSPMonitorSet so that, when the KSP is destroyed, rank 0 closes any open history file and the residual workspaces and the context are freed.

Parameters
ctxa pointer to the context pointer to be destroyed
Returns
PetscErrorCode

Destroys the DualMonitorCtx.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
DualMonitorDestroy()

Definition at line 927 of file logging.c.

928{
929 DualMonitorCtx *monctx = (DualMonitorCtx*)*ctx;
930 PetscErrorCode ierr;
931 PetscMPIInt rank;
932
933 PetscFunctionBeginUser;
935 rank = PetscGlobalRank;
936 if(!rank && monctx->file_handle){
937 fclose(monctx->file_handle);
938 }
939 ierr = VecDestroy(&monctx->residual_work[0]); CHKERRQ(ierr);
940 ierr = VecDestroy(&monctx->residual_work[1]); CHKERRQ(ierr);
941
942 ierr = PetscFree(monctx); CHKERRQ(ierr);
943 *ctx = NULL;
945 PetscFunctionReturn(0);
946}
Here is the caller graph for this function:

◆ LOG_CONTINUITY_METRICS()

PetscErrorCode LOG_CONTINUITY_METRICS ( UserCtx *  user)

Logs continuity metrics for a single block to a file.

This function should be called for each block, once per timestep. Rank 0 appends one row per block to <log_dir>/Continuity_Metrics.csv (see PicurvOpenDiagnosticsCsv()); only block 0 may write a continued run's continuation marker, so the marker appears once.

Parameters
userA pointer to the UserCtx for the specific block whose metrics are to be logged. The function accesses both global (SimCtx) and local (user->...) data.
Returns
PetscErrorCode 0 on success.

Logs continuity metrics for a single block to a file.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_CONTINUITY_METRICS()

Definition at line 1866 of file logging.c.

1867{
1868 PetscErrorCode ierr;
1869 PetscMPIInt rank;
1870 SimCtx *simCtx = user->simCtx; // Get the shared SimCtx
1871 const PetscInt bi = user->_this; // Get this block's specific ID
1872 const PetscInt ti = simCtx->step; // Get the current timestep
1873
1874 PetscFunctionBeginUser;
1876 rank = simCtx->rank;
1877
1878 // Only rank 0 performs file I/O. One row per block per step; only block 0 marks a continuation.
1879 if (!rank) {
1880 FILE *f = NULL;
1881 PetscReal physical_time = 0.0;
1882 ierr = PicurvOpenDiagnosticsCsv(simCtx, simCtx->log_dir, "Continuity_Metrics.csv",
1883 "step,block,max_divergence,max_divergence_k,max_divergence_j,max_divergence_i,"
1884 "max_divergence_index,poisson_source_imbalance,flux_in,flux_out,net_flux,time,physical_time",
1885 &f); CHKERRQ(ierr);
1886 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time); CHKERRQ(ierr);
1887 fprintf(f, "%d,%d,%.10e,%d,%d,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1888 (int)ti, (int)bi, (double)simCtx->MaxDiv,
1889 (int)simCtx->MaxDivz, (int)simCtx->MaxDivy, (int)simCtx->MaxDivx, (int)simCtx->MaxDivFlatArg,
1890 (double)simCtx->poissonSourceImbalance, (double)simCtx->FluxInSum, (double)simCtx->FluxOutSum,
1891 (double)(simCtx->FluxInSum - simCtx->FluxOutSum), (double)simCtx->ti, (double)physical_time);
1892 fclose(f);
1893 }
1894
1896 PetscFunctionReturn(0);
1897}
PetscErrorCode PicurvPhysicalTime(const SimCtx *simCtx, PetscReal solver_time, PetscReal *physical)
Convert a solver time to physical seconds, t * L_ref / U_ref.
Definition io.c:2986
static PetscErrorCode 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
PetscReal FluxOutSum
Definition variables.h:1016
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscInt _this
Definition variables.h:1175
PetscReal MaxDiv
Definition variables.h:1096
PetscInt MaxDivx
Definition variables.h:1097
PetscInt MaxDivy
Definition variables.h:1097
PetscInt MaxDivz
Definition variables.h:1097
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt MaxDivFlatArg
Definition variables.h:1097
PetscReal FluxInSum
Definition variables.h:1016
PetscInt step
Definition variables.h:924
PetscReal ti
Definition variables.h:925
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LOG_SOLUTION_CONVERGENCE()

PetscErrorCode LOG_SOLUTION_CONVERGENCE ( SimCtx *  simCtx)

Logs physical solution-convergence metrics once per completed timestep.

This logger is intentionally separate from the detailed inner solver-health logs. Depending on the configured mode, it records deterministic step drift, periodic phase-aligned drift, or statistical window drift into <log_dir>/solution_convergence.csv.

The logger is solver-mode only and is intended to run after a completed flow-solve / projection step but before history vectors are shifted forward. Warmup rows are handled internally:

  • steady/transient mode: the first logged step has has_reference = 0
  • periodic mode: the first cycle fills the phase reference ring
  • statistical mode: window-drift fields remain zero until enough samples exist to form the requested windows

Existing detailed inner logs remain the authoritative source for momentum, Poisson, and continuity health. This logger only summarizes physical solution-drift metrics.

Parameters
[in,out]simCtxMaster simulation context controlling the logging mode and owning any supporting runtime buffers.
Returns
PetscErrorCode 0 on success.

Logs physical solution-convergence metrics once per completed timestep.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_SOLUTION_CONVERGENCE()

Definition at line 1714 of file logging.c.

1715{
1716 PetscMPIInt rank = 0;
1717 PetscBool has_reference = PETSC_FALSE;
1718 PetscInt phase_step = -1;
1719 PetscInt samples_before = 0;
1720 PetscReal u_abs_l2 = 0.0, u_rel_l2 = 0.0, p_abs_l2 = 0.0, p_rel_l2 = 0.0;
1721 PetscReal mean_speed = 0.0, mean_speed_reference = 0.0, mean_speed_abs_drift = 0.0, mean_speed_rel_drift = 0.0;
1722 PetscReal mean_ke = 0.0, mean_ke_reference = 0.0, mean_ke_abs_drift = 0.0, mean_ke_rel_drift = 0.0;
1723 PetscReal mean_speed_window = 0.0, mean_speed_window_prev = 0.0, mean_speed_window_abs_drift = 0.0, mean_speed_window_rel_drift = 0.0;
1724 PetscReal mean_speed_rms_window = 0.0, mean_speed_rms_window_prev = 0.0, mean_speed_rms_window_abs_drift = 0.0, mean_speed_rms_window_rel_drift = 0.0;
1725 PetscReal mean_ke_window = 0.0, mean_ke_window_prev = 0.0, mean_ke_window_abs_drift = 0.0, mean_ke_window_rel_drift = 0.0;
1726 PetscReal mean_ke_rms_window = 0.0, mean_ke_rms_window_prev = 0.0, mean_ke_rms_window_abs_drift = 0.0, mean_ke_rms_window_rel_drift = 0.0;
1727
1728 PetscFunctionBeginUser;
1730 if (!simCtx) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1731 if (simCtx->exec_mode != EXEC_MODE_SOLVER) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1732 if (!simCtx->solutionConvergenceEnabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1733
1734 samples_before = simCtx->solutionConvergenceSamplesRecorded;
1735
1736 switch (simCtx->solutionConvergenceMode) {
1739 PetscCall(ComputeDeterministicSolutionMetrics(simCtx, PETSC_FALSE, -1, samples_before,
1740 &has_reference,
1741 &u_abs_l2, &u_rel_l2,
1742 &p_abs_l2, &p_rel_l2,
1743 &mean_speed, &mean_speed_reference,
1744 &mean_speed_abs_drift, &mean_speed_rel_drift,
1745 &mean_ke, &mean_ke_reference,
1746 &mean_ke_abs_drift, &mean_ke_rel_drift));
1747 break;
1749 phase_step = simCtx->solutionConvergencePeriodSteps > 0 ? (simCtx->step % simCtx->solutionConvergencePeriodSteps) : -1;
1750 PetscCall(ComputeDeterministicSolutionMetrics(simCtx, PETSC_TRUE, phase_step, samples_before,
1751 &has_reference,
1752 &u_abs_l2, &u_rel_l2,
1753 &p_abs_l2, &p_rel_l2,
1754 &mean_speed, &mean_speed_reference,
1755 &mean_speed_abs_drift, &mean_speed_rel_drift,
1756 &mean_ke, &mean_ke_reference,
1757 &mean_ke_abs_drift, &mean_ke_rel_drift));
1758 break;
1760 PetscCall(ComputeCurrentFlowObservables(simCtx, &mean_speed, &mean_ke));
1761 PetscCall(AppendStatisticalObservableSample(simCtx, samples_before, mean_speed, mean_ke));
1762 PetscCall(ComputeStatisticalWindowMetrics(simCtx, samples_before + 1,
1763 &has_reference,
1764 &mean_speed_window, &mean_speed_window_prev,
1765 &mean_speed_window_abs_drift, &mean_speed_window_rel_drift,
1766 &mean_speed_rms_window, &mean_speed_rms_window_prev,
1767 &mean_speed_rms_window_abs_drift, &mean_speed_rms_window_rel_drift,
1768 &mean_ke_window, &mean_ke_window_prev,
1769 &mean_ke_window_abs_drift, &mean_ke_window_rel_drift,
1770 &mean_ke_rms_window, &mean_ke_rms_window_prev,
1771 &mean_ke_rms_window_abs_drift, &mean_ke_rms_window_rel_drift));
1772 break;
1773 default:
1774 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Unknown solution convergence mode %d.", (int)simCtx->solutionConvergenceMode);
1775 }
1776
1777 rank = simCtx->rank;
1778 if (rank == 0) {
1779 FILE *f = NULL;
1780 const char *mode_str = SolutionConvergenceModeToString(simCtx->solutionConvergenceMode);
1781 const char *header = NULL;
1782
1783 /* One mode per run, so one header; every row also names its mode. */
1784 switch (simCtx->solutionConvergenceMode) {
1786 header = "step,time,mode,ref,ph,per,u_abs_l2,u_rel_l2,p_abs_l2,p_rel_l2,"
1787 "mean_speed,spd_ref,spd_abs,spd_rel,mean_ke,ke_ref,ke_abs,ke_rel";
1788 break;
1790 header = "step,time,mode,ref,win,mean_speed,mean_ke,spd_win,spd_win_prev,spd_win_abs,spd_win_rel,"
1791 "spd_rms_win,spd_rms_abs,spd_rms_rel,ke_win,ke_win_prev,ke_win_abs,ke_win_rel,"
1792 "ke_rms_win,ke_rms_abs,ke_rms_rel";
1793 break;
1794 default:
1795 header = "step,time,mode,ref,u_abs_l2,u_rel_l2,p_abs_l2,p_rel_l2,"
1796 "mean_speed,spd_ref,spd_abs,spd_rel,mean_ke,ke_ref,ke_abs,ke_rel";
1797 break;
1798 }
1799 PetscCall(PicurvOpenDiagnosticsCsv(simCtx, simCtx->log_dir, "solution_convergence.csv", header, &f));
1800
1801 switch (simCtx->solutionConvergenceMode) {
1804 fprintf(f,
1805 "%d,%.10e,%s,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1806 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1807 (double)u_abs_l2, (double)u_rel_l2, (double)p_abs_l2, (double)p_rel_l2,
1808 (double)mean_speed, (double)mean_speed_reference,
1809 (double)mean_speed_abs_drift, (double)mean_speed_rel_drift,
1810 (double)mean_ke, (double)mean_ke_reference,
1811 (double)mean_ke_abs_drift, (double)mean_ke_rel_drift);
1812 break;
1814 fprintf(f,
1815 "%d,%.10e,%s,%d,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1816 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1817 (int)phase_step, (int)simCtx->solutionConvergencePeriodSteps,
1818 (double)u_abs_l2, (double)u_rel_l2, (double)p_abs_l2, (double)p_rel_l2,
1819 (double)mean_speed, (double)mean_speed_reference,
1820 (double)mean_speed_abs_drift, (double)mean_speed_rel_drift,
1821 (double)mean_ke, (double)mean_ke_reference,
1822 (double)mean_ke_abs_drift, (double)mean_ke_rel_drift);
1823 break;
1825 fprintf(f,
1826 "%d,%.10e,%s,%d,%d,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e,%.10e\n",
1827 (int)simCtx->step, (double)simCtx->ti, mode_str, has_reference ? 1 : 0,
1828 (int)simCtx->solutionConvergenceWindowSteps,
1829 (double)mean_speed, (double)mean_ke,
1830 (double)mean_speed_window, (double)mean_speed_window_prev,
1831 (double)mean_speed_window_abs_drift, (double)mean_speed_window_rel_drift,
1832 (double)mean_speed_rms_window,
1833 (double)mean_speed_rms_window_abs_drift, (double)mean_speed_rms_window_rel_drift,
1834 (double)mean_ke_window, (double)mean_ke_window_prev,
1835 (double)mean_ke_window_abs_drift, (double)mean_ke_window_rel_drift,
1836 (double)mean_ke_rms_window,
1837 (double)mean_ke_rms_window_abs_drift, (double)mean_ke_rms_window_rel_drift);
1838 break;
1839 default: break;
1840 }
1841 fclose(f);
1842 }
1843
1845 phase_step >= 0 && phase_step < simCtx->solutionConvergencePeriodSteps) {
1846 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels - 1].user;
1847 for (PetscInt bi = 0; bi < simCtx->block_number; ++bi) {
1848 PetscCall(VecCopy(user[bi].Ucat, user[bi].solutionConvergencePeriodicUcatRef[phase_step]));
1849 PetscCall(VecCopy(user[bi].P, user[bi].solutionConvergencePeriodicPRef[phase_step]));
1850 }
1851 }
1852
1853 simCtx->solutionConvergenceSamplesRecorded = samples_before + 1;
1854
1856 PetscFunctionReturn(0);
1857}
static PetscErrorCode AppendStatisticalObservableSample(SimCtx *simCtx, PetscInt samples_before, PetscReal mean_speed, PetscReal mean_ke)
Appends one timestep's scalar observables to the statistical history.
Definition logging.c:1476
static const char * SolutionConvergenceModeToString(SolutionConvergenceMode mode)
Maps the internal solution-convergence mode enum to its log label.
Definition logging.c:1693
static PetscErrorCode ComputeStatisticalWindowMetrics(const SimCtx *simCtx, PetscInt samples_available, PetscBool *has_reference_out, PetscReal *mean_speed_window_out, PetscReal *mean_speed_window_prev_out, PetscReal *mean_speed_window_abs_out, PetscReal *mean_speed_window_rel_out, PetscReal *mean_speed_rms_window_out, PetscReal *mean_speed_rms_window_prev_out, PetscReal *mean_speed_rms_window_abs_out, PetscReal *mean_speed_rms_window_rel_out, PetscReal *mean_ke_window_out, PetscReal *mean_ke_window_prev_out, PetscReal *mean_ke_window_abs_out, PetscReal *mean_ke_window_rel_out, PetscReal *mean_ke_rms_window_out, PetscReal *mean_ke_rms_window_prev_out, PetscReal *mean_ke_rms_window_abs_out, PetscReal *mean_ke_rms_window_rel_out)
Computes adjacent-window drift metrics for statistical steady mode.
Definition logging.c:1558
static PetscErrorCode ComputeDeterministicSolutionMetrics(SimCtx *simCtx, PetscBool periodic_mode, PetscInt phase_step, PetscInt samples_before, PetscBool *has_reference_out, PetscReal *u_abs_l2_out, PetscReal *u_rel_l2_out, PetscReal *p_abs_l2_out, PetscReal *p_rel_l2_out, PetscReal *mean_speed_out, PetscReal *mean_speed_ref_out, PetscReal *mean_speed_abs_out, PetscReal *mean_speed_rel_out, PetscReal *mean_ke_out, PetscReal *mean_ke_ref_out, PetscReal *mean_ke_abs_out, PetscReal *mean_ke_rel_out)
Computes deterministic solution-drift metrics for the current step.
Definition logging.c:1193
static PetscErrorCode ComputeCurrentFlowObservables(SimCtx *simCtx, PetscReal *mean_speed_out, PetscReal *mean_ke_out)
Computes instantaneous global flow observables for statistical mode.
Definition logging.c:1075
UserCtx * user
Definition variables.h:768
PetscInt block_number
Definition variables.h:1009
UserMG usermg
Definition variables.h:1082
PetscInt solutionConvergenceSamplesRecorded
Definition variables.h:984
PetscBool solutionConvergenceEnabled
Definition variables.h:980
PetscInt solutionConvergencePeriodSteps
Definition variables.h:982
PetscInt mglevels
Definition variables.h:775
@ EXEC_MODE_SOLVER
Definition variables.h:888
MGCtx * mgctx
Definition variables.h:778
@ SOLUTION_CONVERGENCE_TRANSIENT
Definition variables.h:742
@ SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC
Definition variables.h:740
@ SOLUTION_CONVERGENCE_STATISTICAL_STEADY
Definition variables.h:741
@ SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC
Definition variables.h:739
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
ExecutionMode exec_mode
Definition variables.h:937
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParticleLocationStatusToString()

const char * ParticleLocationStatusToString ( ParticleLocationStatus  level)

A function that outputs the name of the current level in the ParticleLocation enum.

Parameters
levelThe ParticleLocation enum value.
Returns
A constant character string corresponding to the enum. Returns "UNKNOWN_LEVEL" if the enum value is not recognized.

A function that outputs the name of the current level in the ParticleLocation enum.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ParticleLocationStatusToString()

Definition at line 1905 of file logging.c.

1906{
1908 const char *name;
1909 switch (level) {
1910 case NEEDS_LOCATION: name = "NEEDS_LOCATION"; break;
1911 case ACTIVE_AND_LOCATED: name = "ACTIVE_AND_LOCATED"; break;
1912 case MIGRATING_OUT: name = "MIGRATING_OUT"; break;
1913 case LOST: name = "LOST"; break;
1914 case UNINITIALIZED: name = "UNINITIALIZED"; break;
1915 case EXITED: name = "EXITED"; break;
1916 default: name = "UNKNOWN_LEVEL"; break;
1917 }
1919 return name;
1920}
@ LOST
The search failed for a particle believed to be inside the domain.
Definition variables.h:190
@ NEEDS_LOCATION
Definition variables.h:187
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
@ UNINITIALIZED
Definition variables.h:191
@ MIGRATING_OUT
Definition variables.h:189
Here is the caller graph for this function:

◆ PrintProgressBar()

void PrintProgressBar ( PetscInt  step,
PetscInt  startStep,
PetscInt  totalSteps,
PetscReal  currentTime,
PetscReal  seconds_per_step,
PetscInt64  lost_cumulative 
)

Prints a progress bar to the console.

This function should only be called by the root process (rank 0). It uses a carriage return \r to overwrite the same line in the terminal, creating a dynamic progress bar.

Parameters
stepThe current step index from the loop (e.g., from 0 to N-1).
startStepThe global starting step number of the simulation.
totalStepsThe total number of steps to be run in this simulation instance.
currentTimeThe current simulation time to display.
seconds_per_stepMean wall seconds per completed step, with the time left at that rate; omitted when not positive.
lost_cumulativeParticles lost so far in the run; omitted when negative.

Prints a progress bar to the console.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
PrintProgressBar()

Definition at line 2446 of file logging.c.

2448{
2450 if (totalSteps <= 0) { PROFILE_FUNCTION_END; return; }
2451
2452 // --- Configuration ---
2453 const int barWidth = 50;
2454
2455 // --- Calculation ---
2456 // Calculate progress as a fraction from 0.0 to 1.0
2457 PetscReal progress = (PetscReal)(step - startStep + 1) / totalSteps;
2458 // Ensure progress doesn't exceed 1.0 due to floating point inaccuracies
2459 if (progress > 1.0) progress = 1.0;
2460
2461 int pos = (int)(barWidth * progress);
2462
2463 // --- Printing ---
2464 // Carriage return moves cursor to the beginning of the line
2465 PetscPrintf(PETSC_COMM_SELF, "\rProgress: [");
2466
2467 for (int i = 0; i < barWidth; ++i) {
2468 if (i < pos) {
2469 PetscPrintf(PETSC_COMM_SELF, "=");
2470 } else if (i == pos) {
2471 PetscPrintf(PETSC_COMM_SELF, ">");
2472 } else {
2473 PetscPrintf(PETSC_COMM_SELF, " ");
2474 }
2475 }
2476
2477 // Print percentage, step count, and current time
2478 PetscPrintf(PETSC_COMM_SELF, "] %3d%% (Step %" PetscInt_FMT "/%" PetscInt_FMT ", t=%.4f)",
2479 (int)(progress * 100.0),
2480 step + 1,
2481 startStep + totalSteps,
2482 currentTime);
2483 if (seconds_per_step > 0.0) {
2484 const PetscInt remaining = PetscMax(0, startStep + totalSteps - (step + 1));
2485 const long long eta = (long long)(seconds_per_step * (PetscReal)remaining + 0.5);
2486 PetscPrintf(PETSC_COMM_SELF, " | %.3g s/step | ETA %lld:%02lld:%02lld",
2487 (double)seconds_per_step, eta / 3600, (eta / 60) % 60, eta % 60);
2488 }
2489 if (lost_cumulative >= 0) PetscPrintf(PETSC_COMM_SELF, " | lost %lld", (long long)lost_cumulative);
2490
2491 // Flush the output buffer to ensure the bar is displayed immediately
2492 fflush(stdout);
2494}
Here is the caller graph for this function:

◆ ProfilingInitialize()

PetscErrorCode ProfilingInitialize ( SimCtx *  simCtx)

Applies the profiling configuration from SimCtx to PICurv's PETSc log events.

Records the per-step selected function list and the enabled helper timers (profiling.helpers), and switches each helper event registered so far on or off to match. Starts PETSc's default log handler if nothing has yet. Called once from CreateSimulationContext(), before the main time loop.

Parameters
simCtxThe master simulation context holding the profiling configuration; its name lists must outlive profiling.
Returns
PetscErrorCode

Applies the profiling configuration from SimCtx to PICurv's PETSc log events.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ProfilingInitialize()

Definition at line 2015 of file logging.c.

2016{
2017 PetscLogState state = NULL;
2018 PetscInt nevents = 0;
2019
2020 PetscFunctionBeginUser;
2021 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for ProfilingInitialize");
2022 PetscCall(_ProfilingEnsureStarted());
2029 // Helpers that ran before this (during setup) registered switched off; apply the list to them.
2030 PetscCall(PetscLogGetState(&state));
2031 PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2032 for (PetscLogEvent e = 0; e < nevents; ++e) {
2033 PetscLogEventInfo info;
2034 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2035 if (info.classid == g_profile_class_helper) PetscCall(PetscLogEventSetActiveAll(e, _ProfilingHelperEnabled(info.name)));
2036 }
2037 for (PetscInt i = 0; i < g_profile_nselected; ++i) {
2038 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Marked '%s' for per-step profiling output.\n", g_profile_selected[i]);
2039 }
2040 for (PetscInt i = 0; i < g_profile_nhelpers; ++i) {
2041 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Enabled helper timer '%s'.\n", g_profile_helpers[i]);
2042 }
2043 PetscFunctionReturn(0);
2044}
static PetscInt g_profile_nselected
Definition logging.c:1936
static char ** g_profile_selected
Definition logging.c:1935
static PetscClassId g_profile_class_helper
Definition logging.c:1929
static PetscBool g_profile_all_helpers
Definition logging.c:1932
static PetscBool _ProfilingHelperEnabled(const char *name)
Whether a helper function's timer is enabled.
Definition logging.c:1953
static PetscErrorCode _ProfilingEnsureStarted(void)
Register the two PICurv event classes and start PETSc's default log handler, once.
Definition logging.c:1963
static char ** g_profile_helpers
Definition logging.c:1930
static PetscBool g_profile_any_helpers
Definition logging.c:1933
static PetscInt g_profile_nhelpers
Definition logging.c:1931
char ** profilingSelectedFuncs
Definition variables.h:1101
PetscInt nProfilingSelectedFuncs
Definition variables.h:1102
PetscBool profilingAllHelpers
-profiling_helpers all: every helper timer is enabled.
Definition variables.h:1105
char ** profilingHelpers
Helper functions whose timers are enabled (-profiling_helpers).
Definition variables.h:1103
PetscInt nProfilingHelpers
Definition variables.h:1104
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProfilingResetTimestepCounters()

PetscErrorCode ProfilingResetTimestepCounters ( void  )

Starts a new per-step profiling interval.

Records every PETSc event's running totals; the next ProfilingLogTimestepSummary() reports the difference. Cumulative totals are untouched.

Returns
PetscErrorCode 0 on success.

Starts a new per-step profiling interval.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ProfilingResetTimestepCounters()

Definition at line 2087 of file logging.c.

2088{
2089 PetscFunctionBeginUser;
2090 PetscCall(_ProfilingSnapshotStep());
2091 PetscFunctionReturn(0);
2092}
static PetscErrorCode _ProfilingSnapshotStep(void)
Record every event's running totals as the start of the next step.
Definition logging.c:2063
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProfilingLogTimestepSummary()

PetscErrorCode ProfilingLogTimestepSummary ( SimCtx *  simCtx,
PetscInt  step 
)

Logs the performance summary for the current timestep and resets timers.

Depending on the configured profiling timestep mode, rank 0 writes per-step profiling rows to <log_dir>/Profiling_Timestep_Summary.csv, opened at its first row (see PicurvOpenRunCsv()):

  • off: writes nothing
  • selected: writes only functions marked for per-step reporting
  • all: writes every instrumented function that ran in the timestep

It must be called once per timestep, typically at the end of the main loop. A step's values are the change in each PICurv event's PETSc running totals since the previous call (or ProfilingResetTimestepCounters()); an event still open, such as the enclosing time loop, adds its time only when it ends. Only rank 0 writes.

Parameters
simCtxThe simulation context holding profiling output settings.
stepThe current simulation step number, for logging context.
Returns
PetscErrorCode

Logs the performance summary for the current timestep and resets timers.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ProfilingLogTimestepSummary()

Definition at line 2100 of file logging.c.

2101{
2102 const PetscBool all = (PetscBool)(simCtx && strcmp(simCtx->profilingTimestepMode, "all") == 0);
2103 PetscLogState state = NULL;
2104 PetscInt nevents = 0;
2105 FILE *f = NULL;
2106
2107 PetscFunctionBeginUser;
2108 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for ProfilingLogTimestepSummary");
2109 if (strcmp(simCtx->profilingTimestepMode, "off") == 0) PetscFunctionReturn(0);
2110
2111 PetscCall(PetscLogGetState(&state));
2112 PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2113
2114 /* A selected name that matches no instrumented function records nothing, and a
2115 list made only of such names writes no file at all. Say so once, on the first
2116 step, rather than leave an absent file to be discovered after the run. */
2117 if (step == simCtx->StartStep + 1 && !all) {
2118 for (PetscInt i = 0; i < g_profile_nselected; ++i) {
2119 PetscBool ran = PETSC_FALSE;
2120 for (PetscLogEvent e = 0; e < nevents && !ran; ++e) {
2121 PetscLogEventInfo info;
2122 PetscLogDouble time = 0.0;
2123 int count = 0;
2124 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2125 if (!_ProfilingIsPicurvClass(info.classid) || strcmp(info.name, g_profile_selected[i]) != 0) continue;
2126 PetscCall(_ProfilingEventTotals(e, &time, &count));
2127 ran = (PetscBool)(count > 0);
2128 }
2129 if (!ran) {
2131 "profiling.timestep_output.functions lists '%s', which recorded no call in the first "
2132 "step. It is not an instrumented function; the final summary lists the names that are.\n",
2134 }
2135 }
2136 }
2137
2138 for (PetscLogEvent e = 0; e < nevents; ++e) {
2139 PetscLogEventInfo info;
2140 PetscLogDouble time = 0.0, since_time;
2141 int count = 0, since_count;
2142 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2143 if (!_ProfilingIsPicurvClass(info.classid)) continue;
2144 if (!all && !_ProfilingNameListed(info.name, g_profile_selected, g_profile_nselected)) continue;
2145 PetscCall(_ProfilingEventTotals(e, &time, &count));
2146 // An event registered after the last snapshot started from zero.
2147 since_time = time - (e < g_profile_step_capacity ? g_profile_step_time[e] : 0.0);
2148 since_count = count - (e < g_profile_step_capacity ? g_profile_step_count[e] : 0);
2149 if (since_count <= 0 || simCtx->rank != 0) continue;
2150 /* The file is opened at its first row, which need not be in the run's first step: a
2151 selected function may first run later. */
2152 if (!f) {
2153 PetscCall(PicurvOpenRunCsv(simCtx, simCtx->log_dir, "Profiling_Timestep_Summary.csv",
2154 "step,function,calls,step_time_s", PICURV_CSV_TRUNCATE_ON_FRESH,
2155 PETSC_TRUE, &f));
2156 }
2157 PetscFPrintf(PETSC_COMM_SELF, f, "%d,%s,%d,%.6f\n", (int)step, info.name, since_count, (double)since_time);
2158 }
2159 if (f) fclose(f);
2160 PetscCall(_ProfilingSnapshotStep());
2161 PetscFunctionReturn(0);
2162}
static PetscErrorCode _ProfilingEventTotals(PetscLogEvent event, PetscLogDouble *time, int *count)
Read an event's running total time and call count on this rank (main stage).
Definition logging.c:2049
PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
Implementation of PicurvOpenRunCsv().
Definition logging.c:3552
static PetscLogDouble * g_profile_step_time
Definition logging.c:1937
static int * g_profile_step_count
Definition logging.c:1938
static PetscInt g_profile_step_capacity
Definition logging.c:1939
static PetscBool _ProfilingNameListed(const char *name, char **names, PetscInt n)
Whether a name appears in a list of names.
Definition logging.c:1944
static PetscBool _ProfilingIsPicurvClass(PetscClassId classid)
Whether a PETSc event belongs to one of PICurv's classes.
Definition logging.c:2004
char profilingTimestepMode[32]
Definition variables.h:1106
PetscInt StartStep
Definition variables.h:926
Here is the call graph for this function:
Here is the caller graph for this function:

◆ RuntimeMemoryLogSample()

PetscErrorCode RuntimeMemoryLogSample ( SimCtx *  simCtx,
PetscInt  step,
const char *  event,
const char *  reason 
)

Append a reduced runtime memory sample to the configured memory log.

The log is intentionally compact: every rank samples process/PETSc allocator memory, one max reduction summarizes the job, and rank 0 appends one CSV row to <log_dir>/Runtime_Memory.csv, which is appended to and never truncated.

Parameters
simCtxThe simulation context holding log directory and memory log settings.
stepThe solver/post step associated with the sample.
eventHuman-readable event label such as "Step", "Post", "Shutdown", or "Final".
reasonHuman-readable reason, or NULL/"-" when not applicable.
Returns
PetscErrorCode

Append a reduced runtime memory sample to the configured memory log.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
RuntimeMemoryLogSample()

Definition at line 2170 of file logging.c.

2171{
2172 PetscErrorCode ierr;
2173 PetscLogDouble process_current_bytes = 0.0;
2174 PetscLogDouble process_peak_bytes = 0.0;
2175 PetscLogDouble petsc_current_bytes = 0.0;
2176 PetscLogDouble petsc_peak_bytes = 0.0;
2177 PetscReal local_values[5];
2178 PetscReal global_values[5];
2179 PetscReal process_current_mb = 0.0;
2180 PetscReal process_peak_mb = 0.0;
2181 PetscReal petsc_current_mb = 0.0;
2182 PetscReal petsc_peak_mb = 0.0;
2183 PetscReal process_change_mb = 0.0;
2184 FILE *f = NULL;
2185
2186 PetscFunctionBeginUser;
2188 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be null for RuntimeMemoryLogSample");
2189 if (!simCtx->runtimeMemoryLogEnabled) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
2190
2191 ierr = PetscMemoryGetCurrentUsage(&process_current_bytes); CHKERRQ(ierr);
2192 ierr = PetscMemoryGetMaximumUsage(&process_peak_bytes); CHKERRQ(ierr);
2193 ierr = PetscMallocGetCurrentUsage(&petsc_current_bytes); CHKERRQ(ierr);
2194 ierr = PetscMallocGetMaximumUsage(&petsc_peak_bytes); CHKERRQ(ierr);
2195
2196 process_current_mb = (PetscReal)(process_current_bytes / (1024.0 * 1024.0));
2197 process_peak_mb = (PetscReal)(process_peak_bytes / (1024.0 * 1024.0));
2198 petsc_current_mb = (PetscReal)(petsc_current_bytes / (1024.0 * 1024.0));
2199 petsc_peak_mb = (PetscReal)(petsc_peak_bytes / (1024.0 * 1024.0));
2200 if (simCtx->runtimeMemoryLogHasPrevious) {
2201 process_change_mb = process_current_mb - simCtx->runtimeMemoryLogPreviousProcessMB;
2202 }
2203
2204 local_values[0] = process_current_mb;
2205 local_values[1] = process_peak_mb;
2206 local_values[2] = petsc_current_mb;
2207 local_values[3] = petsc_peak_mb;
2208 local_values[4] = process_change_mb;
2209 ierr = MPI_Allreduce(local_values, global_values, 5, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
2210
2211 simCtx->runtimeMemoryLogPreviousProcessMB = process_current_mb;
2212 simCtx->runtimeMemoryLogHasPrevious = PETSC_TRUE;
2213
2214 if (simCtx->rank == 0) {
2215 /* Never truncated: every run appends its samples, a continuation's after its marker. */
2216 ierr = PicurvOpenRunCsv(simCtx, simCtx->log_dir, "Runtime_Memory.csv",
2217 "step,event,process_current_mb_max,process_peak_mb_max,petsc_allocated_mb_max,"
2218 "petsc_peak_allocated_mb_max,process_change_mb_max,reason,step_wall_s",
2219 PICURV_CSV_APPEND, PETSC_TRUE, &f); CHKERRQ(ierr);
2220
2221 fprintf(f, "%" PetscInt_FMT ",%s,%.3f,%.3f,%.3f,%.3f,%.3f,%s,",
2222 step, event ? event : "-",
2223 (double)global_values[0], (double)global_values[1], (double)global_values[2],
2224 (double)global_values[3], (double)global_values[4],
2225 (reason && reason[0]) ? reason : "-");
2226 /* The step's slowest-rank wall time, on the per-step sample only. */
2227 if (event && strcmp(event, "Step") == 0) fprintf(f, "%.6f", (double)simCtx->lastStepWallSeconds);
2228 fprintf(f, "\n");
2229 if ((event && (strcmp(event, "Shutdown") == 0 || strcmp(event, "Final") == 0))) {
2230 fflush(f);
2231 }
2232 fclose(f);
2233 }
2234
2236 PetscFunctionReturn(0);
2237}
PetscBool runtimeMemoryLogEnabled
Enable the rank-reduced runtime memory log (log_dir/Runtime_Memory.csv).
Definition variables.h:1123
PetscBool runtimeMemoryLogHasPrevious
True after the first process-memory sample.
Definition variables.h:1126
PetscReal runtimeMemoryLogPreviousProcessMB
Previous local process memory sample in MB.
Definition variables.h:1127
PetscReal lastStepWallSeconds
Slowest rank's wall time of the last completed step (0 before one).
Definition variables.h:1128
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ProfilingFinalize()

PetscErrorCode ProfilingFinalize ( SimCtx *  simCtx)

Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.

Two sections: PICurv's events (aggregates, and helpers that were enabled), then PETSc's own events, whose inclusive times nest inside PICurv's. In each, the names any rank recorded are united by name, each name's total time is reduced to its maximum and minimum (with the ranks holding them) and its mean over ranks, and its calls are summed and reduced to their minimum and maximum per rank (with ranks), so a time spread can be told apart from a call-count spread. Rank 0 writes ProfilingSummary_<mode>.csv (<mode> is Solver or PostProcessor), slowest rank first; a continued run appends its totals after a continuation marker. This is the profiler's only communication; the timed path stays local to each rank.

Parameters
simCtxThe Simulation Context Structure that can contains all the data regarding the simulation.
Returns
PetscErrorCode 0 on success.

Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ProfilingFinalize()

Definition at line 2380 of file logging.c.

2381{
2382 PetscLogState state = NULL;
2383 PetscInt nevents = 0, npicurv = 0, npetsc = 0;
2384 const char **picurv_names = NULL, **petsc_names = NULL;
2385 PetscLogDouble *picurv_times = NULL, *petsc_times = NULL;
2386 long long *picurv_counts = NULL, *petsc_counts = NULL;
2387 FILE *f = NULL;
2388
2389 PetscFunctionBeginUser;
2390 if (!simCtx->profilingFinalSummary) PetscFunctionReturn(0);
2391
2392 // --- This rank's recorded events, split into PICurv's and PETSc's own ---
2393 PetscCall(PetscLogGetState(&state));
2394 if (state) PetscCall(PetscLogStateGetNumEvents(state, &nevents));
2395 PetscCall(PetscMalloc3(nevents + 1, &picurv_names, nevents + 1, &picurv_times, nevents + 1, &picurv_counts));
2396 PetscCall(PetscMalloc3(nevents + 1, &petsc_names, nevents + 1, &petsc_times, nevents + 1, &petsc_counts));
2397 for (PetscLogEvent e = 0; e < nevents; ++e) {
2398 PetscLogEventInfo info;
2399 PetscLogDouble time = 0.0;
2400 int count = 0;
2401 PetscCall(PetscLogStateEventGetInfo(state, e, &info));
2402 PetscCall(_ProfilingEventTotals(e, &time, &count));
2403 if (count <= 0) continue;
2404 if (_ProfilingIsPicurvClass(info.classid)) {
2405 picurv_names[npicurv] = info.name; picurv_times[npicurv] = time; picurv_counts[npicurv++] = count;
2406 } else {
2407 petsc_names[npetsc] = info.name; petsc_times[npetsc] = time; petsc_counts[npetsc++] = count;
2408 }
2409 }
2410
2411 if (!simCtx->rank) {
2412 char exec_mode_modifier[32] = "Unknown";
2413 char filen[64];
2414 if (simCtx->exec_mode == EXEC_MODE_SOLVER) PetscCall(PetscStrncpy(exec_mode_modifier, "Solver", sizeof(exec_mode_modifier)));
2415 else if (simCtx->exec_mode == EXEC_MODE_POSTPROCESSOR) PetscCall(PetscStrncpy(exec_mode_modifier, "PostProcessor", sizeof(exec_mode_modifier)));
2416 PetscCall(PetscSNPrintf(filen, sizeof(filen), "ProfilingSummary_%s.csv", exec_mode_modifier));
2417 // Written once, at the end: a fresh run replaces the file, a continuation appends its totals after its marker.
2418 PetscCall(PicurvOpenRunCsv(simCtx, simCtx->log_dir, filen,
2419 "section,function,max_time_s,max_rank,mean_time_s,min_time_s,min_rank,calls,avg_time_per_call_ms,"
2420 "min_calls_per_rank,min_calls_rank,max_calls_per_rank,max_calls_rank",
2421 PICURV_CSV_TRUNCATE_ON_FRESH, PETSC_TRUE, &f));
2422 fprintf(f, "# Total time per rank over %d rank(s). Section 'petsc' times are inclusive and run inside the "
2423 "'picurv' functions, so the two sections must not be added together.\n", (int)simCtx->size);
2424 }
2425 PetscCall(_ProfilingReduceSection(f, "picurv", npicurv, picurv_names, picurv_times, picurv_counts));
2426 PetscCall(_ProfilingReduceSection(f, "petsc", npetsc, petsc_names, petsc_times, petsc_counts));
2427 if (f) fclose(f);
2428
2429 PetscCall(PetscFree3(picurv_names, picurv_times, picurv_counts));
2430 PetscCall(PetscFree3(petsc_names, petsc_times, petsc_counts));
2431 PetscCall(PetscFree2(g_profile_step_time, g_profile_step_count));
2433 PetscFunctionReturn(0);
2434}
static PetscErrorCode _ProfilingReduceSection(FILE *f, const char *section, PetscInt nlocal, const char **names, const PetscLogDouble *times, const long long *counts)
Reduce one section of the final summary across ranks and print it on rank 0.
Definition logging.c:2278
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscMPIInt size
Definition variables.h:920
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
Here is the call graph for this function:
Here is the caller graph for this function:

◆ _ProfilingRegister()

void _ProfilingRegister ( const char *  func_name,
PetscBool  helper,
PetscLogEvent *  event 
)

Internal profiling hook: register a call site's function as a PETSc log event.

Called once per call site, on its first execution. Registers the PICurv event classes and starts PETSc's default log handler on the first call anywhere. A helper event is switched off as it registers unless its name is enabled (profiling.helpers). Before PetscInitialize, after PetscFinalize, or on failure, it registers nothing and the call site stays untimed, trying again on its next call.

Parameters
func_nameFunction name (__func__), the event's name.
helperPETSC_TRUE for a per-particle or per-cell helper, PETSC_FALSE for an aggregate.
eventCall site's cached event; set when registration succeeds, else left at -1.

Internal profiling hook: register a call site's function as a PETSc log event.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
_ProfilingRegister()

Definition at line 1984 of file logging.c.

1985{
1986 PetscLogEvent registered = -1;
1987
1988 // Before PetscInitialize (argument handling in main) or after PetscFinalize there is no log
1989 // to register with; the call site stays untimed and tries again on its next call.
1990 if (!PetscInitializeCalled || PetscFinalizeCalled) return;
1991 if (_ProfilingEnsureStarted() != 0) return; // Fail silently: the call site stays untimed
1992 if (PetscLogEventRegister(func_name, helper ? g_profile_class_helper : g_profile_class_function, &registered) != 0) return;
1993 // New events start active, and excluding a class reaches only events that already exist,
1994 // so a helper is switched off as it registers unless it is enabled.
1995 if (helper && !_ProfilingHelperEnabled(func_name)) {
1996 if (PetscLogEventSetActiveAll(registered, PETSC_FALSE) != 0) return;
1997 }
1998 *event = registered;
1999}
static PetscClassId g_profile_class_function
Definition logging.c:1928
Here is the call graph for this function:

◆ LOG_FIELD_MIN_MAX()

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.

This utility function inspects a PETSc Vec associated with a DMDA and calculates the minimum and maximum values for each of its three components (e.g., x, y, z) both for the local data on the current MPI rank and for the entire global domain.

It uses the same "smart" logic as the flow solver, ignoring the padding nodes at the IM, JM, and KM boundaries of the grid. The results are printed to the standard output in a formatted, easy-to-read table.

Parameters
[in]userPointer to the user-defined context. Used for grid information (IM, JM, KM) and MPI rank.
[in]field_idTyped identity of the field being analyzed.
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Computes and logs the local and global min/max values of a 3-component vector field.

Full API contract is documented with the header declaration in include/logging.h.

See also
LOG_FIELD_MIN_MAX()

Definition at line 2501 of file logging.c.

2502{
2503 PetscErrorCode ierr;
2504 PetscInt i, j, k;
2505 DMDALocalInfo info;
2506
2507 FieldView view;
2508 Vec fieldVec = NULL;
2509 DM dm = NULL;
2510 PetscInt dof;
2511 FieldLayout layout;
2512 const char *fieldName = NULL;
2513 const char *data_layout = NULL;
2514
2515 PetscFunctionBeginUser;
2517
2518 ierr = FieldGetView(user, field_id, &view); CHKERRQ(ierr);
2519 fieldName = view.descriptor->canonical_name;
2520 dm = view.dm;
2521 dof = view.descriptor->dof;
2522 layout = view.descriptor->layout;
2523 data_layout = FieldLayoutName(layout);
2524 fieldVec = (layout == FIELD_LAYOUT_COMPONENT_STAGGERED) ? view.local_vec : view.global_vec;
2525
2526 info = user->info; // dm is user->da or user->fda, which share one decomposition
2527
2528 // --- 2. Define Architecture-Aware Loop Bounds ---
2529 PetscInt i_start, i_end, j_start, j_end, k_start, k_end;
2530
2531 if (layout == FIELD_LAYOUT_CELL_CENTERED) {
2532 // For cell-centered data, the physical values are stored from index 1 to N-1.
2533 // We find the intersection of the rank's owned range [xs, xe) with the
2534 // physical data range [1, IM-1).
2535 i_start = PetscMax(info.xs, 1); i_end = PetscMin(info.xs + info.xm, user->IM);
2536 j_start = PetscMax(info.ys, 1); j_end = PetscMin(info.ys + info.ym, user->JM);
2537 k_start = PetscMax(info.zs, 1); k_end = PetscMin(info.zs + info.zm, user->KM);
2538 } else { // For Node- or Face-Centered data
2539 // The physical values are stored from index 0 to N-1.
2540 // We find the intersection of the rank's owned range [xs, xe) with the
2541 // physical data range [0, IM-1].
2542 i_start = PetscMax(info.xs, 0); i_end = PetscMin(info.xs + info.xm, user->IM);
2543 j_start = PetscMax(info.ys, 0); j_end = PetscMin(info.ys + info.ym, user->JM);
2544 k_start = PetscMax(info.zs, 0); k_end = PetscMin(info.zs + info.zm, user->KM);
2545 }
2546
2547 // --- 3. Barrier for clean, grouped output ---
2548 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRQ(ierr);
2549 if (user->simCtx->rank == 0) {
2550 PetscPrintf(PETSC_COMM_SELF, "\n--- Field Ranges: [%s] (Layout: %s) ---\n", fieldName, data_layout);
2551 }
2552
2553 // --- 4. Branch on DoF and perform calculation with correct bounds ---
2554 if (dof == 1) {
2555 PetscReal localMin = PETSC_MAX_REAL, localMax = PETSC_MIN_REAL;
2556 PetscReal globalMin, globalMax;
2557 const PetscScalar ***array;
2558
2559 ierr = DMDAVecGetArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2560 for (k = k_start; k < k_end; k++) {
2561 for (j = j_start; j < j_end; j++) {
2562 for (i = i_start; i < i_end; i++) {
2563 localMin = PetscMin(localMin, array[k][j][i]);
2564 localMax = PetscMax(localMax, array[k][j][i]);
2565 }
2566 }
2567 }
2568 ierr = DMDAVecRestoreArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2569
2570 ierr = MPI_Allreduce(&localMin, &globalMin, 1, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD); CHKERRQ(ierr);
2571 ierr = MPI_Allreduce(&localMax, &globalMax, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
2572
2573 PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin, localMax);
2574 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
2575 if (user->simCtx->rank == 0) {
2576 PetscPrintf(PETSC_COMM_SELF, " Global Range: [ %11.4e , %11.4e ]\n", globalMin, globalMax);
2577 }
2578
2579 } else if (dof == 3) {
2580 Cmpnts localMin = {PETSC_MAX_REAL, PETSC_MAX_REAL, PETSC_MAX_REAL};
2581 Cmpnts localMax = {PETSC_MIN_REAL, PETSC_MIN_REAL, PETSC_MIN_REAL};
2582 Cmpnts globalMin, globalMax;
2583 const Cmpnts ***array;
2584
2585 ierr = DMDAVecGetArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2586 for (k = k_start; k < k_end; k++) {
2587 for (j = j_start; j < j_end; j++) {
2588 for (i = i_start; i < i_end; i++) {
2589 localMin.x = PetscMin(localMin.x, array[k][j][i].x);
2590 localMin.y = PetscMin(localMin.y, array[k][j][i].y);
2591 localMin.z = PetscMin(localMin.z, array[k][j][i].z);
2592 localMax.x = PetscMax(localMax.x, array[k][j][i].x);
2593 localMax.y = PetscMax(localMax.y, array[k][j][i].y);
2594 localMax.z = PetscMax(localMax.z, array[k][j][i].z);
2595 }
2596 }
2597 }
2598 ierr = DMDAVecRestoreArrayRead(dm, fieldVec, &array); CHKERRQ(ierr);
2599
2600 ierr = MPI_Allreduce(&localMin, &globalMin, 3, MPIU_REAL, MPI_MIN, PETSC_COMM_WORLD); CHKERRQ(ierr);
2601 ierr = MPI_Allreduce(&localMax, &globalMax, 3, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
2602
2603 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local X-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.x, localMax.x);
2604 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Y-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.y, localMax.y);
2605 ierr = PetscSynchronizedPrintf(PETSC_COMM_WORLD, " [Rank %d] Local Z-Range: [ %11.4e , %11.4e ]\n", user->simCtx->rank, localMin.z, localMax.z);
2606 ierr = PetscSynchronizedFlush(PETSC_COMM_WORLD, PETSC_STDOUT); CHKERRQ(ierr);
2607
2608 if (user->simCtx->rank == 0) {
2609 PetscPrintf(PETSC_COMM_SELF, " [Global] X-Range: [ %11.4e , %11.4e ]\n", globalMin.x, globalMax.x);
2610 PetscPrintf(PETSC_COMM_SELF, " [Global] Y-Range: [ %11.4e , %11.4e ]\n", globalMin.y, globalMax.y);
2611 PetscPrintf(PETSC_COMM_SELF, " [Global] Z-Range: [ %11.4e , %11.4e ]\n", globalMin.z, globalMax.z);
2612 }
2613
2614 } else {
2615 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "LogFieldStatistics only supports fields with 1 or 3 components, but field '%s' has %" PetscInt_FMT ".", fieldName, dof);
2616 }
2617
2618 // --- 5. Final barrier for clean output ordering ---
2619 ierr = MPI_Barrier(PETSC_COMM_WORLD); CHKERRQ(ierr);
2620 if (user->simCtx->rank == 0) {
2621 PetscPrintf(PETSC_COMM_SELF, "--------------------------------------------\n\n");
2622 }
2623
2625 PetscFunctionReturn(0);
2626}
FieldLayout layout
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
FieldLayout
Logical storage topology of a field.
@ FIELD_LAYOUT_CELL_CENTERED
@ FIELD_LAYOUT_COMPONENT_STAGGERED
const char * canonical_name
const char * FieldLayoutName(FieldLayout layout)
Return a stable printable label for a field layout.
Non-owning runtime objects resolved for one field and UserCtx.
PetscInt KM
Definition variables.h:1171
PetscInt JM
Definition variables.h:1171
DMDALocalInfo info
Definition variables.h:1169
PetscInt IM
Definition variables.h:1171
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LOG_FIELD_ANATOMY()

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 grid and variable architecture.

This intelligent diagnostic function inspects a PETSc Vec and prints its values at critical boundary locations (-Xi/+Xi, -Eta/+Eta, -Zeta/+Zeta). It is "architecture-aware":

  • Cell-Centered Fields ("Ucat", "P"): It correctly applies the "Shifted Index Architecture," where the value for geometric Cell i is stored at array index i+1. It labels the output to clearly distinguish between true physical values and ghost values.
  • Single-Face-Family Fields: Csi/ICsi/IEta/IZet/Centx belong to the I-face family, with corresponding J- and K-face families.
  • Component-Staggered Fields ("Ucont" and histories): x/y/z components live on I/J/K faces respectively.
  • Node-Centered Fields ("Coordinates"): It uses a direct index mapping, where the value for Node i is stored at index i.

The output is synchronized across MPI ranks to ensure readability and focuses on a slice through the center of the domain to be concise.

Parameters
userA pointer to the UserCtx structure containing the DMs and Vecs.
field_idTyped identity of the persistent Eulerian field to log.
stage_nameA string identifier for the current simulation stage (e.g., "After Advection").
Returns
PetscErrorCode Returns 0 on success, non-zero on failure.

Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific grid and variable architecture.

See also
LOG_FIELD_ANATOMY()

Definition at line 2903 of file logging.c.

2904{
2905 FieldView view;
2906
2907 PetscFunctionBeginUser;
2909 PetscCall(FieldGetView(user, field_id, &view));
2910 PetscCall(LogFieldAnatomyView(user, view.descriptor->canonical_name, stage_name,
2911 view.dm, view.local_vec, view.descriptor->dof,
2912 view.descriptor->layout));
2914 PetscFunctionReturn(0);
2915}
static PetscErrorCode LogFieldAnatomyView(UserCtx *user, const char *field_name, const char *stage_name, DM dm, Vec vec_local, PetscInt dof, FieldLayout layout)
Shared architecture-aware anatomy logger for catalog and transient fields.
Definition logging.c:2631
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LOG_CORNER_FIELD_ANATOMY()

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.

Parameters
userContext owning the corner-staging workspace.
corner_field_idWhich corner workspace the caller populated.
stage_namePrintable simulation stage.
Returns
Zero on success.

Logs the node-layout anatomy of the transient center-to-corner interpolation field.

See also
LOG_CORNER_FIELD_ANATOMY()

Definition at line 2997 of file logging.c.

2998{
2999 FieldView view;
3000
3001 PetscFunctionBeginUser;
3003 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
3004 PetscCheck(corner_field_id == FIELD_ID_CELL_SCALAR_AT_CORNER ||
3005 corner_field_id == FIELD_ID_CELL_VECTOR_AT_CORNER,
3006 PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
3007 "Corner anatomy logging expects a corner-staging field identity.");
3008 /* The caller states which workspace it used, so the degree of freedom and DM
3009 * come from the catalog instead of being inferred from a cached vector. */
3010 PetscCall(FieldGetView(user, corner_field_id, &view));
3011 PetscCall(LogFieldAnatomyView(user, view.descriptor->canonical_name, stage_name, view.dm,
3012 view.local_vec, view.descriptor->dof,
3013 view.descriptor->layout));
3015 PetscFunctionReturn(0);
3016}
@ FIELD_ID_CELL_SCALAR_AT_CORNER
@ FIELD_ID_CELL_VECTOR_AT_CORNER
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LOG_INTERPOLATION_ERROR()

PetscErrorCode LOG_INTERPOLATION_ERROR ( UserCtx *  user)

Logs the interpolation error between the analytical and computed solutions.

Parameters
userPrimary UserCtx input for the operation.
Returns
PetscErrorCode 0 on success.

Logs the interpolation error between the analytical and computed solutions.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_INTERPOLATION_ERROR()

Definition at line 3024 of file logging.c.

3025{
3027 SimCtx *simCtx = user->simCtx;
3028 PetscErrorCode ierr;
3029 DM swarm = user->swarm;
3030 Vec positionVec, analyticalvelocityVec, velocityVec, errorVec;
3031 PetscReal Interpolation_error = 0.0;
3032 PetscReal Maximum_Interpolation_error = 0.0;
3033 PetscReal AnalyticalSolution_magnitude = 0.0;
3034 PetscReal ErrorPercentage = 0.0;
3035
3036 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Creating global vectors.\n");
3037 ierr = DMSwarmCreateGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), &positionVec); CHKERRQ(ierr);
3038 ierr = DMSwarmCreateGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), &velocityVec); CHKERRQ(ierr);
3039
3040 ierr = VecDuplicate(positionVec, &analyticalvelocityVec); CHKERRQ(ierr);
3041 ierr = VecCopy(positionVec, analyticalvelocityVec); CHKERRQ(ierr);
3042
3043 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Computing analytical solution.\n");
3044 ierr = SetAnalyticalSolutionForParticles(analyticalvelocityVec, simCtx); CHKERRQ(ierr);
3045
3046 ierr = VecDuplicate(analyticalvelocityVec, &errorVec); CHKERRQ(ierr);
3047 ierr = VecCopy(analyticalvelocityVec, errorVec); CHKERRQ(ierr);
3048
3049 ierr = VecNorm(analyticalvelocityVec, NORM_2, &AnalyticalSolution_magnitude); CHKERRQ(ierr);
3050
3051 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Computing error.\n");
3052 ierr = VecAXPY(errorVec, -1.0, velocityVec); CHKERRQ(ierr);
3053 ierr = VecNorm(errorVec, NORM_2, &Interpolation_error); CHKERRQ(ierr);
3054 ierr = VecNorm(errorVec,NORM_INFINITY,&Maximum_Interpolation_error); CHKERRQ(ierr);
3055
3056 ErrorPercentage = (AnalyticalSolution_magnitude > 0) ?
3057 (Interpolation_error / AnalyticalSolution_magnitude * 100.0) : 0.0;
3058
3059 /* --- CSV output (always, rank 0 only) --- */
3060 if (simCtx->rank == 0) {
3061 FILE *f = NULL;
3062 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "interpolation_error.csv",
3063 "step,time,L2_error,Linf_error,L2_analytical,error_pct,physical_time", PICURV_CSV_APPEND,
3064 PETSC_FALSE, &f); CHKERRQ(ierr);
3065 if (f) {
3066 /* ti is solver time, not a step count; physical_time is it in seconds. */
3067 PetscReal t = simCtx->ti;
3068 PetscReal physical_time = 0.0;
3069 ierr = PicurvPhysicalTime(simCtx, t, &physical_time); CHKERRQ(ierr);
3070 fprintf(f, "%d,%.6e,%.6e,%.6e,%.6e,%.4f,%.6e\n",
3071 (int)simCtx->step, t,
3072 Interpolation_error, Maximum_Interpolation_error,
3073 AnalyticalSolution_magnitude, ErrorPercentage, physical_time);
3074 fclose(f);
3075 }
3076 }
3077
3078 /* --- Console output (only at INFO level or above) --- */
3079 if (get_log_level() >= LOG_INFO) {
3080 LOG_ALLOW(GLOBAL, LOG_INFO, "Interpolation error (%%): %g\n", ErrorPercentage);
3081 PetscPrintf(PETSC_COMM_WORLD, "Interpolation error (%%): %g\n", ErrorPercentage);
3082 LOG_ALLOW(GLOBAL, LOG_INFO, "Maximum Interpolation error: %g\n", Maximum_Interpolation_error);
3083 PetscPrintf(PETSC_COMM_WORLD, "Maximum Interpolation error: %g\n", Maximum_Interpolation_error);
3084 }
3085
3086 ierr = VecDestroy(&analyticalvelocityVec); CHKERRQ(ierr);
3087 ierr = VecDestroy(&errorVec); CHKERRQ(ierr);
3088 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), &positionVec); CHKERRQ(ierr);
3089 ierr = DMSwarmDestroyGlobalVectorFromField(swarm, ParticleFieldName(PARTICLE_FIELD_ID_VELOCITY), &velocityVec); CHKERRQ(ierr);
3090
3092 return 0;
3093}
PetscErrorCode SetAnalyticalSolutionForParticles(Vec tempVec, SimCtx *simCtx)
Evaluates the analytical velocity at particle positions.
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
Here is the call graph for this function:
Here is the caller graph for this function:

◆ LOG_SCATTER_METRICS()

PetscErrorCode LOG_SCATTER_METRICS ( UserCtx *  user)

Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.

Parameters
userPrimary UserCtx input for the operation.
Returns
PetscErrorCode 0 on success.

Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_SCATTER_METRICS()

Definition at line 3101 of file logging.c.

3102{
3103 PetscErrorCode ierr;
3104 SimCtx *simCtx = NULL;
3105 DMDALocalInfo info;
3106 PetscInt xs, xe, ys, ye, zs, ze, mx, my, mz;
3107 PetscInt lxs, lxe, lys, lye, lzs, lze;
3108 Vec reference_vec = NULL;
3109 PetscReal ***psi = NULL;
3110 PetscReal ***psi_ref = NULL;
3111 PetscReal ***aj = NULL;
3112 PetscReal ***count = NULL;
3113 PetscReal *particle_psi = NULL;
3114 PetscInt nlocal = 0;
3115 PetscReal local_l1 = 0.0, global_l1 = 0.0;
3116 PetscReal local_l2_sq = 0.0, global_l2_sq = 0.0;
3117 PetscReal local_linf = 0.0, global_linf = 0.0;
3118 PetscReal local_ref_l2_sq = 0.0, global_ref_l2_sq = 0.0;
3119 PetscReal local_grid_integral = 0.0, global_grid_integral = 0.0;
3120 PetscReal local_domain_volume = 0.0, global_domain_volume = 0.0;
3121 PetscReal local_particle_sum = 0.0, global_particle_sum = 0.0;
3122 PetscInt64 local_particle_count = 0, global_particle_count = 0;
3123 PetscInt64 local_cell_count = 0, global_cell_count = 0;
3124 PetscInt64 local_occupied_count = 0, global_occupied_count = 0;
3125 PetscReal particle_integral = 0.0;
3126 PetscReal occupancy_fraction = 0.0;
3127 PetscReal mean_particles_per_occupied_cell = 0.0;
3128 PetscReal l2_error = 0.0;
3129 PetscReal relative_l2_error = 0.0;
3130
3131 PetscFunctionBeginUser;
3133 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
3134 simCtx = user->simCtx;
3135 if (!VerificationScalarOverrideActive(simCtx) || !user->swarm || !user->Psi || !user->ParticleCount) {
3137 PetscFunctionReturn(0);
3138 }
3139
3140 info = user->info;
3141 xs = info.xs; xe = info.xs + info.xm;
3142 ys = info.ys; ye = info.ys + info.ym;
3143 zs = info.zs; ze = info.zs + info.zm;
3144 mx = info.mx; my = info.my; mz = info.mz;
3145 lxs = (xs == 0) ? xs + 1 : xs; lxe = (xe == mx) ? xe - 1 : xe;
3146 lys = (ys == 0) ? ys + 1 : ys; lye = (ye == my) ? ye - 1 : ye;
3147 lzs = (zs == 0) ? zs + 1 : zs; lze = (ze == mz) ? ze - 1 : ze;
3148
3149 ierr = VecDuplicate(user->Psi, &reference_vec); CHKERRQ(ierr);
3150 ierr = SetVerificationScalarAtCellCenters(user, reference_vec); CHKERRQ(ierr);
3151
3152 ierr = DMDAVecGetArrayRead(user->da, user->Psi, &psi); CHKERRQ(ierr);
3153 ierr = DMDAVecGetArrayRead(user->da, reference_vec, &psi_ref); CHKERRQ(ierr);
3154 ierr = DMDAVecGetArrayRead(user->da, user->Aj, &aj); CHKERRQ(ierr);
3155 ierr = DMDAVecGetArrayRead(user->da, user->ParticleCount, &count); CHKERRQ(ierr);
3156
3157 for (PetscInt k = lzs; k < lze; ++k) {
3158 for (PetscInt j = lys; j < lye; ++j) {
3159 for (PetscInt i = lxs; i < lxe; ++i) {
3160 const PetscReal cell_volume = (PetscAbsReal(aj[k][j][i]) > 1.0e-14) ? (1.0 / aj[k][j][i]) : 0.0;
3161 const PetscReal err = psi[k][j][i] - psi_ref[k][j][i];
3162 local_cell_count += 1;
3163 local_domain_volume += cell_volume;
3164 local_grid_integral += psi[k][j][i] * cell_volume;
3165 local_l1 += PetscAbsReal(err) * cell_volume;
3166 local_l2_sq += err * err * cell_volume;
3167 local_ref_l2_sq += psi_ref[k][j][i] * psi_ref[k][j][i] * cell_volume;
3168 local_linf = PetscMax(local_linf, PetscAbsReal(err));
3169 if (count[k][j][i] > 0.0) local_occupied_count += 1;
3170 }
3171 }
3172 }
3173
3174 ierr = DMDAVecRestoreArrayRead(user->da, user->ParticleCount, &count); CHKERRQ(ierr);
3175 ierr = DMDAVecRestoreArrayRead(user->da, user->Aj, &aj); CHKERRQ(ierr);
3176 ierr = DMDAVecRestoreArrayRead(user->da, reference_vec, &psi_ref); CHKERRQ(ierr);
3177 ierr = DMDAVecRestoreArrayRead(user->da, user->Psi, &psi); CHKERRQ(ierr);
3178 ierr = VecDestroy(&reference_vec); CHKERRQ(ierr);
3179
3180 ierr = DMSwarmGetLocalSize(user->swarm, &nlocal); CHKERRQ(ierr);
3181 local_particle_count = (PetscInt64)nlocal;
3182 if (nlocal > 0) {
3183 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&particle_psi); CHKERRQ(ierr);
3184 for (PetscInt p = 0; p < nlocal; ++p) local_particle_sum += particle_psi[p];
3185 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_PSI), NULL, NULL, (void **)&particle_psi); CHKERRQ(ierr);
3186 }
3187
3188 ierr = MPI_Allreduce(&local_l1, &global_l1, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3189 ierr = MPI_Allreduce(&local_l2_sq, &global_l2_sq, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3190 ierr = MPI_Allreduce(&local_linf, &global_linf, 1, MPIU_REAL, MPI_MAX, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3191 ierr = MPI_Allreduce(&local_ref_l2_sq, &global_ref_l2_sq, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3192 ierr = MPI_Allreduce(&local_grid_integral, &global_grid_integral, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3193 ierr = MPI_Allreduce(&local_domain_volume, &global_domain_volume, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3194 ierr = MPI_Allreduce(&local_particle_sum, &global_particle_sum, 1, MPIU_REAL, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3195 ierr = MPI_Allreduce(&local_particle_count, &global_particle_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3196 ierr = MPI_Allreduce(&local_cell_count, &global_cell_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3197 ierr = MPI_Allreduce(&local_occupied_count, &global_occupied_count, 1, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3198
3199 l2_error = PetscSqrtReal(global_l2_sq);
3200 relative_l2_error = (global_ref_l2_sq > 0.0) ? (l2_error / PetscSqrtReal(global_ref_l2_sq)) : 0.0;
3201 occupancy_fraction = (global_cell_count > 0) ? ((PetscReal)global_occupied_count / (PetscReal)global_cell_count) : 0.0;
3202 mean_particles_per_occupied_cell =
3203 (global_occupied_count > 0) ? ((PetscReal)global_particle_count / (PetscReal)global_occupied_count) : 0.0;
3204 particle_integral =
3205 (global_particle_count > 0) ? (global_domain_volume * global_particle_sum / (PetscReal)global_particle_count) : 0.0;
3206
3207 if (simCtx->rank == 0) {
3208 FILE *f = NULL;
3209 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "scatter_metrics.csv",
3210 "step,time,total_particles,total_cells,occupied_cells,occupancy_fraction,"
3211 "mean_particles_per_occupied_cell,particle_integral,grid_integral,"
3212 "conservation_error_abs,L1_error,L2_error,Linf_error,relative_L2_error,"
3213 "physical_time", PICURV_CSV_APPEND, PETSC_FALSE, &f); CHKERRQ(ierr);
3214 if (f) {
3215 PetscReal physical_time = 0.0;
3216 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &physical_time); CHKERRQ(ierr);
3217 fprintf(f, "%d,%.6e,%lld,%lld,%lld,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e\n",
3218 (int)simCtx->step,
3219 (double)simCtx->ti,
3220 (long long)global_particle_count,
3221 (long long)global_cell_count,
3222 (long long)global_occupied_count,
3223 (double)occupancy_fraction,
3224 (double)mean_particles_per_occupied_cell,
3225 (double)particle_integral,
3226 (double)global_grid_integral,
3227 (double)PetscAbsReal(global_grid_integral - particle_integral),
3228 (double)global_l1,
3229 (double)l2_error,
3230 (double)global_linf,
3231 (double)relative_l2_error,
3232 (double)physical_time);
3233 fclose(f);
3234 }
3235 }
3236
3237 if (get_log_level() >= LOG_INFO) {
3238 LOG_ALLOW(GLOBAL, LOG_INFO, "Scatter relative L2 error: %.6e\n", (double)relative_l2_error);
3239 LOG_ALLOW(GLOBAL, LOG_INFO, "Scatter occupancy fraction: %.6e\n", (double)occupancy_fraction);
3240 }
3241
3243 PetscFunctionReturn(0);
3244}
@ PARTICLE_FIELD_ID_PSI
Vec ParticleCount
Definition variables.h:1276
PetscBool VerificationScalarOverrideActive(const SimCtx *simCtx)
Reports whether a verification-only scalar override is active.
PetscErrorCode SetVerificationScalarAtCellCenters(UserCtx *user, Vec targetVec)
Writes the configured verification scalar profile at physical cell centers into a scalar Vec.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResetSearchMetrics()

PetscErrorCode ResetSearchMetrics ( SimCtx *  simCtx)

Resets the aggregate per-timestep search instrumentation counters.

Parameters
simCtxSimulation context whose search metrics should be zeroed.
Returns
PetscErrorCode 0 on success.

Resets the aggregate per-timestep search instrumentation counters.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
ResetSearchMetrics()

Definition at line 3252 of file logging.c.

3253{
3254 PetscFunctionBeginUser;
3256 if (!simCtx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL for ResetSearchMetrics.");
3257
3258 simCtx->searchMetrics.searchAttempts = 0;
3259 simCtx->searchMetrics.searchPopulation = 0;
3261 simCtx->searchMetrics.searchLostCount = 0;
3262 simCtx->searchMetrics.traversalStepsSum = 0;
3263 simCtx->searchMetrics.reSearchCount = 0;
3264 simCtx->searchMetrics.maxTraversalSteps = 0;
3266 simCtx->searchMetrics.tieBreakCount = 0;
3271 simCtx->searchMetrics.searchExitedCount = 0;
3273 simCtx->searchMetrics.reflectionCount = 0;
3275 simCtx->searchMetrics.wrapCount = 0;
3277
3279 PetscFunctionReturn(0);
3280}
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt64 reflectionCount
Definition variables.h:296
PetscInt64 searchLostCount
Definition variables.h:284
PetscInt64 wrapCount
Definition variables.h:298
PetscInt64 boundaryClampCount
Definition variables.h:290
PetscInt64 traversalStepsSum
Definition variables.h:285
PetscInt64 searchPopulation
Definition variables.h:282
PetscInt currentSettlementPass
Definition variables.h:299
PetscInt64 searchExitedCount
Definition variables.h:294
PetscInt64 reSearchCount
Definition variables.h:286
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
PetscInt64 maxParticlePassDepth
Definition variables.h:293
PetscInt64 maxTraversalSteps
Definition variables.h:287
SearchMetricsState searchMetrics
Definition variables.h:1073
PetscInt64 searchAttempts
Definition variables.h:281
PetscInt64 reflectionFallbackCount
Definition variables.h:297
PetscInt64 tieBreakCount
Definition variables.h:289
PetscInt64 blockedWalkRetryCount
Definition variables.h:295
PetscInt64 maxTraversalFailCount
Definition variables.h:288
Here is the caller graph for this function:

◆ CalculateAdvancedParticleMetrics()

PetscErrorCode CalculateAdvancedParticleMetrics ( UserCtx *  user)

Computes advanced particle statistics and stores them in SimCtx.

This function calculates:

  • Particle load imbalance across MPI ranks.
  • The total number of grid cells occupied by at least one particle.
  • The fewest, mean, and most particles per cell over the physical cells.

It requires that CalculateParticleCountPerCell() has been called prior to its execution. It uses collective MPI operations and must be called by all ranks.

Parameters
userPointer to the UserCtx.
Returns
PetscErrorCode 0 on success.

Computes advanced particle statistics and stores them in SimCtx.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
CalculateAdvancedParticleMetrics()

Definition at line 3484 of file logging.c.

3485{
3486 PetscErrorCode ierr;
3487 SimCtx *simCtx = user->simCtx;
3488 PetscMPIInt size;
3489
3490 PetscFunctionBeginUser;
3492 size = simCtx->size;
3493
3494 // --- 1. Particle Load Imbalance ---
3495 PetscInt nLocal, nGlobal, nLocalMax;
3496 ierr = DMSwarmGetLocalSize(user->swarm, &nLocal); CHKERRQ(ierr);
3497 ierr = DMSwarmGetSize(user->swarm, &nGlobal); CHKERRQ(ierr);
3498 ierr = MPI_Allreduce(&nLocal, &nLocalMax, 1, MPIU_INT, MPI_MAX, PETSC_COMM_WORLD); CHKERRQ(ierr);
3499
3500 PetscReal avg_per_rank = (size > 0) ? ((PetscReal)nGlobal / size) : 0.0;
3501 // Handle division by zero if there are no particles
3502 simCtx->particleLoadImbalance = (avg_per_rank > 1e-9) ? (nLocalMax / avg_per_rank) : 1.0;
3503
3504
3505 // --- 2. Particles per Cell: Occupied Cells, Fewest, Mean, Most ---
3506 // ParticleCount stores cell c at index c + 1, so the physical cells are indices 1..m-2 on
3507 // each axis; a rank visits the ones in its owned index range, so each cell counts once.
3508 const DMDALocalInfo *info = &user->info;
3509 const PetscScalar ***count_array;
3510 PetscInt64 sums[3] = {0, 0, 0}; // occupied cells, particles, cells
3511 PetscInt64 extremes[2] = {PETSC_INT64_MAX, PETSC_INT64_MAX}; // fewest, -most
3512 const PetscInt i_lo = PetscMax(info->xs, 1), i_hi = PetscMin(info->xs + info->xm, info->mx - 1);
3513 const PetscInt j_lo = PetscMax(info->ys, 1), j_hi = PetscMin(info->ys + info->ym, info->my - 1);
3514 const PetscInt k_lo = PetscMax(info->zs, 1), k_hi = PetscMin(info->zs + info->zm, info->mz - 1);
3515
3516 ierr = DMDAVecGetArrayRead(user->da, user->ParticleCount, (void *)&count_array); CHKERRQ(ierr);
3517 for (PetscInt k = k_lo; k < k_hi; ++k) {
3518 for (PetscInt j = j_lo; j < j_hi; ++j) {
3519 for (PetscInt i = i_lo; i < i_hi; ++i) {
3520 const PetscInt64 n = (PetscInt64)(PetscRealPart(count_array[k][j][i]) + 0.5); // counts are whole numbers
3521 sums[0] += (n > 0);
3522 sums[1] += n;
3523 sums[2] += 1;
3524 extremes[0] = PetscMin(extremes[0], n);
3525 extremes[1] = PetscMin(extremes[1], -n);
3526 }
3527 }
3528 }
3529 ierr = DMDAVecRestoreArrayRead(user->da, user->ParticleCount, (void *)&count_array); CHKERRQ(ierr);
3530
3531 ierr = MPI_Allreduce(MPI_IN_PLACE, sums, 3, MPIU_INT64, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3532 ierr = MPI_Allreduce(MPI_IN_PLACE, extremes, 2, MPIU_INT64, MPI_MIN, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3533 simCtx->occupiedCellCount = (PetscInt)sums[0];
3534 simCtx->particlesPerCellMin = (sums[2] > 0) ? (PetscInt)extremes[0] : 0;
3535 simCtx->particlesPerCellMax = (sums[2] > 0) ? (PetscInt)(-extremes[1]) : 0;
3536 simCtx->particlesPerCellMean = (sums[2] > 0) ? (PetscReal)sums[1] / (PetscReal)sums[2] : 0.0;
3537
3538 LOG_ALLOW(GLOBAL, LOG_INFO, "Advanced Metrics: Imbalance=%.2f, OccupiedCells=%" PetscInt_FMT ", ParticlesPerCell min/mean/max=%" PetscInt_FMT "/%.3f/%" PetscInt_FMT "\n",
3540 simCtx->particlesPerCellMin, (double)simCtx->particlesPerCellMean, simCtx->particlesPerCellMax);
3541
3543 PetscFunctionReturn(0);
3544}
PetscInt particlesPerCellMin
Fewest particles in any cell after the step.
Definition variables.h:1069
PetscInt particlesPerCellMax
Most particles in any cell after the step.
Definition variables.h:1070
PetscInt occupiedCellCount
Definition variables.h:1068
PetscReal particlesPerCellMean
Particles counted in cells divided by the cell count.
Definition variables.h:1071
PetscReal particleLoadImbalance
Definition variables.h:1072
Here is the caller graph for this function:

◆ LOG_SEARCH_METRICS()

PetscErrorCode LOG_SEARCH_METRICS ( UserCtx *  user)

Writes compact runtime search metrics to CSV and optionally to console.

The CSV artifact is always written for particle-enabled runs. Console output remains gated by normal logging level and function allow-listing.

Parameters
userPointer to the UserCtx.
Returns
PetscErrorCode 0 on success.

Writes compact runtime search metrics to CSV and optionally to console.

Full API contract (arguments, ownership, side effects) is documented with the header declaration in include/logging.h.

See also
LOG_SEARCH_METRICS()

Definition at line 3288 of file logging.c.

3289{
3290 PetscErrorCode ierr;
3291 SimCtx *simCtx = NULL;
3292 PetscInt totalParticles = 0;
3293 PetscReal local_metrics[SEARCH_METRIC_REDUCTION_LEN] = {0.0};
3294 PetscReal global_metrics[SEARCH_METRIC_REDUCTION_LEN] = {0.0};
3295 PetscReal meanTraversalSteps = 0.0;
3296 PetscReal searchFailureFraction = 0.0;
3297 PetscReal searchWorkIndex = 0.0;
3298 PetscReal reSearchFraction = 0.0;
3299 long long searchAttempts = 0;
3300 long long searchPopulation = 0;
3301 long long searchLocatedCount = 0;
3302 long long searchLostCount = 0;
3303 long long traversalStepsSum = 0;
3304 long long reSearchCount = 0;
3305 long long tieBreakCount = 0;
3306 long long boundaryClampCount = 0;
3307 long long bboxGuessSuccessCount = 0;
3308 long long bboxGuessFallbackCount = 0;
3309 long long maxTraversalFailCount = 0;
3310 long long maxTraversalSteps = 0;
3311 long long maxPassDepth = 0;
3312 long long searchExitedCount = 0;
3313 long long blockedWalkRetryCount = 0;
3314 long long reflectionCount = 0;
3315 long long reflectionFallbackCount = 0;
3316 long long wrapCount = 0;
3317 MPI_Op reduction_op = MPI_OP_NULL;
3318
3319 PetscFunctionBeginUser;
3321 if (!user || !user->simCtx) {
3322 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx and SimCtx are required for LOG_SEARCH_METRICS.");
3323 }
3324 simCtx = user->simCtx;
3325
3326 if (!ParticlesEnabled(simCtx)) {
3328 PetscFunctionReturn(0);
3329 }
3330
3331 ierr = DMSwarmGetSize(user->swarm, &totalParticles); CHKERRQ(ierr);
3332
3333 local_metrics[SEARCH_METRIC_SUM_SEARCH_ATTEMPTS] = (PetscReal)simCtx->searchMetrics.searchAttempts;
3334 local_metrics[SEARCH_METRIC_SUM_SEARCH_POPULATION] = (PetscReal)simCtx->searchMetrics.searchPopulation;
3335 local_metrics[SEARCH_METRIC_SUM_SEARCH_LOCATED] = (PetscReal)simCtx->searchMetrics.searchLocatedCount;
3336 local_metrics[SEARCH_METRIC_SUM_SEARCH_LOST] = (PetscReal)simCtx->searchMetrics.searchLostCount;
3337 local_metrics[SEARCH_METRIC_SUM_TRAVERSAL_STEPS] = (PetscReal)simCtx->searchMetrics.traversalStepsSum;
3338 local_metrics[SEARCH_METRIC_SUM_RESEARCH] = (PetscReal)simCtx->searchMetrics.reSearchCount;
3339 local_metrics[SEARCH_METRIC_SUM_TIE_BREAKS] = (PetscReal)simCtx->searchMetrics.tieBreakCount;
3340 local_metrics[SEARCH_METRIC_SUM_BOUNDARY_CLAMPS] = (PetscReal)simCtx->searchMetrics.boundaryClampCount;
3341 local_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_SUCCESS] = (PetscReal)simCtx->searchMetrics.bboxGuessSuccessCount;
3342 local_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_FALLBACK] = (PetscReal)simCtx->searchMetrics.bboxGuessFallbackCount;
3343 local_metrics[SEARCH_METRIC_SUM_MAX_TRAVERSAL_FAILS] = (PetscReal)simCtx->searchMetrics.maxTraversalFailCount;
3344 local_metrics[SEARCH_METRIC_SUM_SEARCH_EXITED] = (PetscReal)simCtx->searchMetrics.searchExitedCount;
3345 local_metrics[SEARCH_METRIC_SUM_BLOCKED_RETRY] = (PetscReal)simCtx->searchMetrics.blockedWalkRetryCount;
3346 local_metrics[SEARCH_METRIC_SUM_REFLECTIONS] = (PetscReal)simCtx->searchMetrics.reflectionCount;
3347 local_metrics[SEARCH_METRIC_SUM_REFLECTION_FALLBACKS] = (PetscReal)simCtx->searchMetrics.reflectionFallbackCount;
3348 local_metrics[SEARCH_METRIC_SUM_WRAPS] = (PetscReal)simCtx->searchMetrics.wrapCount;
3349 local_metrics[SEARCH_METRIC_MAX_TRAVERSAL_STEPS] = (PetscReal)simCtx->searchMetrics.maxTraversalSteps;
3350 local_metrics[SEARCH_METRIC_MAX_PASS_DEPTH] = (PetscReal)simCtx->searchMetrics.maxParticlePassDepth;
3351
3352 ierr = MPI_Op_create(SearchMetricsReduceOp, PETSC_TRUE, &reduction_op); CHKERRMPI(ierr);
3353 ierr = MPI_Allreduce(local_metrics, global_metrics, SEARCH_METRIC_REDUCTION_LEN, MPIU_REAL, reduction_op, PETSC_COMM_WORLD); CHKERRMPI(ierr);
3354 ierr = MPI_Op_free(&reduction_op); CHKERRMPI(ierr);
3355 reduction_op = MPI_OP_NULL;
3356
3357 searchAttempts = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_ATTEMPTS] + 0.5);
3358 searchPopulation = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_POPULATION] + 0.5);
3359 searchLocatedCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_LOCATED] + 0.5);
3360 searchLostCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_LOST] + 0.5);
3361 traversalStepsSum = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_TRAVERSAL_STEPS] + 0.5);
3362 reSearchCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_RESEARCH] + 0.5);
3363 tieBreakCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_TIE_BREAKS] + 0.5);
3364 boundaryClampCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BOUNDARY_CLAMPS] + 0.5);
3365 bboxGuessSuccessCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_SUCCESS] + 0.5);
3366 bboxGuessFallbackCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BBOX_GUESS_FALLBACK] + 0.5);
3367 maxTraversalFailCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_MAX_TRAVERSAL_FAILS] + 0.5);
3368 maxTraversalSteps = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_MAX_TRAVERSAL_STEPS] + 0.5);
3369 maxPassDepth = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_MAX_PASS_DEPTH] + 0.5);
3370 searchExitedCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_SEARCH_EXITED] + 0.5);
3371 blockedWalkRetryCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_BLOCKED_RETRY] + 0.5);
3372 reflectionCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_REFLECTIONS] + 0.5);
3373 reflectionFallbackCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_REFLECTION_FALLBACKS] + 0.5);
3374 wrapCount = (long long)PetscFloorReal(global_metrics[SEARCH_METRIC_SUM_WRAPS] + 0.5);
3375
3376 if (searchAttempts > 0) {
3377 meanTraversalSteps = (PetscReal)traversalStepsSum / (PetscReal)searchAttempts;
3378 }
3379 if (searchPopulation > 0) {
3380 searchFailureFraction = (PetscReal)searchLostCount / (PetscReal)searchPopulation;
3381 searchWorkIndex = (PetscReal)traversalStepsSum / (PetscReal)searchPopulation;
3382 reSearchFraction = (PetscReal)reSearchCount / (PetscReal)searchPopulation;
3383 }
3384
3385 if (simCtx->rank == 0) {
3386 FILE *f = NULL;
3387 PetscReal searchPhysicalTime = 0.0;
3388
3389 ierr = PicurvPhysicalTime(simCtx, simCtx->ti, &searchPhysicalTime); CHKERRQ(ierr);
3390 ierr = PicurvOpenRunCsv(simCtx, simCtx->analysis_dir, "search_metrics.csv",
3391 "step,time,total_particles,lost,lost_cumulative,migrated,migration_passes,search_attempts,"
3392 "mean_traversal_steps,max_traversal_steps,tie_break_count,boundary_clamp_count,"
3393 "bbox_guess_success_count,bbox_guess_fallback_count,max_particle_pass_depth,load_imbalance,"
3394 "search_population,search_located_count,search_lost_count,traversal_steps_sum,re_search_count,"
3395 "max_traversal_fail_count,search_failure_fraction,search_work_index,re_search_fraction,"
3396 "physical_time,lost_psi_sum,exited,exited_cumulative,exited_psi_sum,search_exited_count,"
3397 "blocked_walk_retry_count,reflections,reflection_fallbacks,wraps,occupied_cells,"
3398 "particles_per_cell_min,particles_per_cell_mean,particles_per_cell_max",
3399 PICURV_CSV_APPEND, PETSC_FALSE, &f); CHKERRQ(ierr);
3400 if (f) {
3401 fprintf(f,
3402 "%d,%.6e,%d,%d,%lld,%d,%d,%lld,%.6e,%lld,%lld,%lld,%lld,%lld,%lld,%.6e,%lld,%lld,%lld,%lld,%lld,%lld,%.6e,%.6e,%.6e,%.6e,%.10e,"
3403 "%d,%lld,%.10e,%lld,%lld,%lld,%lld,%lld,%d,%d,%.6e,%d\n",
3404 (int)simCtx->step,
3405 (double)simCtx->ti,
3406 (int)totalParticles,
3407 (int)simCtx->particlesLostLastStep,
3408 (long long)simCtx->particlesLostCumulative,
3409 (int)simCtx->particlesMigratedLastStep,
3410 (int)simCtx->migrationPassesLastStep,
3411 searchAttempts,
3412 (double)meanTraversalSteps,
3413 maxTraversalSteps,
3414 tieBreakCount,
3415 boundaryClampCount,
3416 bboxGuessSuccessCount,
3417 bboxGuessFallbackCount,
3418 maxPassDepth,
3419 (double)simCtx->particleLoadImbalance,
3420 searchPopulation,
3421 searchLocatedCount,
3422 searchLostCount,
3423 traversalStepsSum,
3424 reSearchCount,
3425 maxTraversalFailCount,
3426 (double)searchFailureFraction,
3427 (double)searchWorkIndex,
3428 (double)reSearchFraction,
3429 (double)searchPhysicalTime,
3430 (double)simCtx->particlesLostScalarLastStep,
3431 (int)simCtx->particlesExitedLastStep,
3432 (long long)simCtx->particlesExitedCumulative,
3433 (double)simCtx->particlesExitedScalarLastStep,
3434 searchExitedCount,
3435 blockedWalkRetryCount,
3436 reflectionCount,
3437 reflectionFallbackCount,
3438 wrapCount,
3439 (int)simCtx->occupiedCellCount,
3440 (int)simCtx->particlesPerCellMin,
3441 (double)simCtx->particlesPerCellMean,
3442 (int)simCtx->particlesPerCellMax);
3443 fclose(f);
3444 }
3445 }
3446
3447 // Boundary events, one line per step after the reduction rather than one message per particle.
3448 if (reflectionCount > 0 || blockedWalkRetryCount > 0 || wrapCount > 0) {
3449 LOG_ALLOW(GLOBAL, LOG_INFO, "Step %d boundary events: %lld wall reflections, %lld periodic wraps, %lld blocked walks searched again.\n",
3450 (int)simCtx->step, reflectionCount, wrapCount, blockedWalkRetryCount);
3451 }
3452 if (reflectionFallbackCount > 0) {
3453 LOG_ALLOW(GLOBAL, LOG_WARNING, "Step %d: %lld particles reached the reflection cap and were placed just inside their boundary cell.\n",
3454 (int)simCtx->step, reflectionFallbackCount);
3455 }
3456
3458 "Search metrics: sff=%.3e swi=%.3e re_search=%.3e lost(step/total)=%d/%lld exited(step/total)=%d/%lld blocked_retries=%lld migrated=%d passes=%d traversal(mean/max)=%.2f/%lld tie_breaks=%lld max_pass_depth=%lld\n",
3459 (double)searchFailureFraction,
3460 (double)searchWorkIndex,
3461 (double)reSearchFraction,
3462 (int)simCtx->particlesLostLastStep,
3463 (long long)simCtx->particlesLostCumulative,
3464 (int)simCtx->particlesExitedLastStep,
3465 (long long)simCtx->particlesExitedCumulative,
3466 blockedWalkRetryCount,
3467 (int)simCtx->particlesMigratedLastStep,
3468 (int)simCtx->migrationPassesLastStep,
3469 (double)meanTraversalSteps,
3470 maxTraversalSteps,
3471 tieBreakCount,
3472 maxPassDepth);
3473
3475 PetscFunctionReturn(0);
3476}
@ SEARCH_METRIC_SUM_SEARCH_LOCATED
Definition logging.c:38
@ SEARCH_METRIC_SUM_WRAPS
Definition logging.c:51
@ SEARCH_METRIC_SUM_MAX_TRAVERSAL_FAILS
Definition logging.c:46
@ SEARCH_METRIC_REDUCTION_LEN
Definition logging.c:54
@ SEARCH_METRIC_SUM_BBOX_GUESS_FALLBACK
Definition logging.c:45
@ SEARCH_METRIC_SUM_RESEARCH
Definition logging.c:41
@ SEARCH_METRIC_SUM_SEARCH_EXITED
Definition logging.c:47
@ SEARCH_METRIC_SUM_REFLECTIONS
Definition logging.c:49
@ SEARCH_METRIC_SUM_TRAVERSAL_STEPS
Definition logging.c:40
@ SEARCH_METRIC_SUM_BLOCKED_RETRY
Definition logging.c:48
@ SEARCH_METRIC_MAX_TRAVERSAL_STEPS
Definition logging.c:52
@ SEARCH_METRIC_SUM_BOUNDARY_CLAMPS
Definition logging.c:43
@ SEARCH_METRIC_SUM_SEARCH_POPULATION
Definition logging.c:37
@ SEARCH_METRIC_MAX_PASS_DEPTH
Definition logging.c:53
@ SEARCH_METRIC_SUM_TIE_BREAKS
Definition logging.c:42
@ SEARCH_METRIC_SUM_SEARCH_LOST
Definition logging.c:39
@ SEARCH_METRIC_SUM_REFLECTION_FALLBACKS
Definition logging.c:50
@ SEARCH_METRIC_SUM_BBOX_GUESS_SUCCESS
Definition logging.c:44
@ SEARCH_METRIC_SUM_SEARCH_ATTEMPTS
Definition logging.c:36
static void SearchMetricsReduceOp(void *invec, void *inoutvec, int *len, MPI_Datatype *datatype)
Internal reduction callback for packed search metrics.
Definition logging.c:61
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvOpenRunCsv()

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.

The record lives in dir: the run's analysis directory (simCtx->analysis_dir) or log directory (simCtx->log_dir). This owns the file's lifecycle; the caller owns the columns:

  • header (starting step, or section,) is written whenever the file is empty, so it appears once, at the top;
  • on the run's first open of the file, whenever it falls, a PICURV_CSV_TRUNCATE_ON_FRESH record is emptied first unless the run is a continuation (simCtx->continueMode), and a continuation writes # Continuation from step <StartStep>, so a reader can tell a resumed run from a discontinuity in the data. Every other call appends.

The run's first open is tracked here, by path, in simCtx->runCsvWritten, so a record written at the output cadence, from step 0, or by several calls in one step needs no flag of its own.

Call on rank 0 only - the file is a serial artifact, and a collective write to it would interleave. The caller closes the handle.

Parameters
[in,out]simCtxSimulation context supplying the continuation state and StartStep, and recording the files the run has opened.
[in]dirDirectory of the file.
[in]filenameBasename of the CSV, including the extension.
[in]headerColumn header written to an empty file, without a trailing newline.
[in]lifecycleWhether a fresh run's first write empties the file.
[in]requiredPETSC_TRUE: a file that cannot be opened is an error. PETSC_FALSE: it is a warning and *file is NULL, for a diagnostic whose loss must not stop or change the run.
[out]fileOpen handle positioned at the end of the file; NULL only when required is false and the file could not be opened.
Returns
PetscErrorCode 0 on success; PETSC_ERR_FILE_OPEN if a required file cannot be opened.

Opens one of the run's CSV records (diagnostics, solver history, profiling) for writing.

Full API contract is documented with the header declaration in include/logging.h.

See also
PicurvOpenRunCsv()

Definition at line 3552 of file logging.c.

3554{
3555 char path[PETSC_MAX_PATH_LEN + 128];
3556 FILE *handle = NULL;
3557 uint64_t key = 0xCBF29CE484222325ULL; /* FNV-1a of the path */
3558 PetscBool first_write = PETSC_TRUE;
3559
3560 PetscFunctionBeginUser;
3562 PetscCheck(simCtx && dir && filename && header && file, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
3563 "A diagnostics CSV needs a context, a directory, a name, a header, and somewhere to "
3564 "return the handle.");
3565 *file = NULL;
3566
3567 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/%s", dir, filename));
3568 for (const char *c = path; *c; ++c) key = (key ^ (uint64_t)(unsigned char)*c) * 0x100000001B3ULL;
3569 for (PetscInt n = 0; n < simCtx->runCsvWrittenCount && first_write; ++n) {
3570 if (simCtx->runCsvWritten[n] == key) first_write = PETSC_FALSE;
3571 }
3572 PetscCheck(!first_write || simCtx->runCsvWrittenCount < PICURV_RUN_CSV_CAPACITY, PETSC_COMM_SELF, PETSC_ERR_PLIB,
3573 "A run writes more than %d CSV records; raise PICURV_RUN_CSV_CAPACITY.", PICURV_RUN_CSV_CAPACITY);
3574 handle = fopen(path, (lifecycle == PICURV_CSV_TRUNCATE_ON_FRESH && first_write && !simCtx->continueMode) ? "w" : "a");
3575 if (!handle) {
3576 PetscCheck(!required, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to open diagnostics file '%s'.", path);
3577 LOG_ALLOW(LOCAL, LOG_WARNING, "Could not open diagnostics file '%s'; its rows are not recorded.\n", path);
3579 PetscFunctionReturn(0);
3580 }
3581 if (first_write) simCtx->runCsvWritten[simCtx->runCsvWrittenCount++] = key;
3582
3583 if (ftell(handle) == 0) fprintf(handle, "%s\n", header);
3584 /* Written once per continuation, so that a reader can tell a resumed run from a jump in
3585 the data itself. */
3586 if (first_write && simCtx->continueMode) {
3587 fprintf(handle, "# Continuation from step %" PetscInt_FMT "\n", simCtx->StartStep);
3588 }
3589
3590 *file = handle;
3592 PetscFunctionReturn(0);
3593}
PetscBool continueMode
Definition variables.h:935
uint64_t runCsvWritten[256]
Rank 0 only: path hashes of the CSV records this run has opened (see PicurvOpenRunCsv()).
Definition variables.h:1124
#define PICURV_RUN_CSV_CAPACITY
Most distinct CSV records one run opens through PicurvOpenRunCsv(): about twenty, plus a few per bloc...
Definition variables.h:75
PetscInt runCsvWrittenCount
Entries of runCsvWritten in use.
Definition variables.h:1125
Here is the caller graph for this function:

◆ PicurvOpenDiagnosticsCsv()

static PetscErrorCode PicurvOpenDiagnosticsCsv ( SimCtx *  simCtx,
const char *  dir,
const char *  filename,
const char *  header,
FILE **  file 
)
inlinestatic

Opens a per-step diagnostics CSV: PicurvOpenRunCsv() with the common settings.

For a record written every step and kept across runs: PICURV_CSV_APPEND, and a file that cannot be opened is an error.

Parameters
[in,out]simCtxSimulation context, as PicurvOpenRunCsv() takes it.
[in]dirDirectory of the file (simCtx->analysis_dir or simCtx->log_dir).
[in]filenameBasename of the CSV, including the extension.
[in]headerColumn header written to an empty file, without a trailing newline.
[out]fileOpen append handle, never NULL on success.
Returns
PetscErrorCode 0 on success; PETSC_ERR_FILE_OPEN if the file cannot be opened.

Definition at line 1197 of file logging.h.

1199{
1200 return PicurvOpenRunCsv(simCtx, dir, filename, header, PICURV_CSV_APPEND, PETSC_TRUE, file);
1201}
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
Here is the call graph for this function:
Here is the caller graph for this function:

Variable Documentation

◆ _picurv_log_level

const LogLevel* const _picurv_log_level
extern

Read-only view of the cached logging level; -1 until the first get_log_level() call.

Only logging.c writes the level. The view lets get_log_level() be inlined into every logging macro, so a disabled message in a per-particle loop costs a load and a compare rather than a function call.

Definition at line 21 of file logging.c.

◆ _picurv_profile_helpers_on

const PetscBool* const _picurv_profile_helpers_on
extern

Read-only view: whether profiling.helpers enables any helper timer.

False until ProfilingInitialize() applies a non-empty list. While it is false every helper event is switched off, so PROFILE_HELPER_BEGIN skips PETSc's per-event check.

Definition at line 1934 of file logging.c.