PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
test_logging.c
Go to the documentation of this file.
1/**
2 * @file test_logging.c
3 * @brief C unit tests for runtime log-level, allow-list, conversion, and profiling helpers.
4 */
5
6#include "test_support.h"
9
10#include "logging.h"
11#include "interpolation.h"
12#include "les.h"
13#include "setup.h"
15#include "statistics_window.h"
16
17#include <fcntl.h>
18#include <math.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <string.h>
22#include <unistd.h>
23/**
24 * @brief Asserts that one text file contains a required substring.
25 */
26
27static PetscErrorCode AssertFileContains(const char *path, const char *needle, const char *context)
28{
29 FILE *fp = NULL;
30 long file_size = 0;
31 char *buffer = NULL;
32
33 PetscFunctionBeginUser;
34 fp = fopen(path, "rb");
35 if (!fp) {
36 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to open '%s' for assertion.", path);
37 }
38 if (fseek(fp, 0, SEEK_END) != 0) {
39 fclose(fp);
40 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to seek '%s'.", path);
41 }
42 file_size = ftell(fp);
43 if (file_size < 0) {
44 fclose(fp);
45 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to measure '%s'.", path);
46 }
47 if (fseek(fp, 0, SEEK_SET) != 0) {
48 fclose(fp);
49 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to rewind '%s'.", path);
50 }
51
52 PetscCall(PetscMalloc1((size_t)file_size + 1, &buffer));
53 if (file_size > 0) {
54 size_t bytes_read = fread(buffer, 1, (size_t)file_size, fp);
55 if (bytes_read != (size_t)file_size) {
56 fclose(fp);
57 PetscCall(PetscFree(buffer));
58 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to read '%s'.", path);
59 }
60 }
61 buffer[file_size] = '\0';
62 fclose(fp);
63
64 PetscCall(PicurvAssertBool((PetscBool)(strstr(buffer, needle) != NULL), context));
65 PetscCall(PetscFree(buffer));
66 PetscFunctionReturn(0);
67}
68/**
69 * @brief Asserts that one text file does not contain an excluded substring.
70 */
71
72static PetscErrorCode AssertFileNotContains(const char *path, const char *needle, const char *context)
73{
74 FILE *fp = NULL;
75 long file_size = 0;
76 char *buffer = NULL;
77
78 PetscFunctionBeginUser;
79 fp = fopen(path, "rb");
80 if (!fp) {
81 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to open '%s' for assertion.", path);
82 }
83 if (fseek(fp, 0, SEEK_END) != 0) {
84 fclose(fp);
85 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to seek '%s'.", path);
86 }
87 file_size = ftell(fp);
88 if (file_size < 0) {
89 fclose(fp);
90 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to measure '%s'.", path);
91 }
92 if (fseek(fp, 0, SEEK_SET) != 0) {
93 fclose(fp);
94 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to rewind '%s'.", path);
95 }
96
97 PetscCall(PetscMalloc1((size_t)file_size + 1, &buffer));
98 if (file_size > 0) {
99 size_t bytes_read = fread(buffer, 1, (size_t)file_size, fp);
100 if (bytes_read != (size_t)file_size) {
101 fclose(fp);
102 PetscCall(PetscFree(buffer));
103 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to read '%s'.", path);
104 }
105 }
106 buffer[file_size] = '\0';
107 fclose(fp);
108
109 PetscCall(PicurvAssertBool((PetscBool)(strstr(buffer, needle) == NULL), context));
110 PetscCall(PetscFree(buffer));
111 PetscFunctionReturn(0);
112}
113
114/**
115 * @brief Reads the column header and the requested 1-based data row from a
116 * comma-separated solution-convergence CSV.
117 *
118 * Lines starting with '=' (banner) or '-' (separator) are skipped. The first
119 * non-skipped line is treated as the column header; subsequent non-skipped
120 * lines are data rows numbered from 1.
121 */
122static PetscErrorCode ReadLogHeaderAndRow(const char *path,
123 PetscInt row_index,
124 char *header,
125 size_t header_len,
126 char *row,
127 size_t row_len)
128{
129 FILE *fp = NULL;
130 PetscInt current_row = 0;
131 char line[8192];
132 PetscBool header_found = PETSC_FALSE;
133
134 PetscFunctionBeginUser;
135 PetscCheck(path != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log path cannot be NULL.");
136 PetscCheck(header != NULL && header_len > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log header buffer cannot be NULL.");
137 PetscCheck(row != NULL && row_len > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log row buffer cannot be NULL.");
138 PetscCheck(row_index >= 1, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE, "Log row index must be >= 1.");
139
140 fp = fopen(path, "r");
141 PetscCheck(fp != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to open log '%s'.", path);
142
143 while (fgets(line, sizeof(line), fp) != NULL) {
144 if (line[0] == '#' || line[0] == '\n' || line[0] == '\r') continue; /* Comments and blank lines */
145 if (!header_found) {
146 PetscCall(PetscStrncpy(header, line, header_len));
147 header_found = PETSC_TRUE;
148 continue;
149 }
150 current_row++;
151 if (current_row == row_index) {
152 PetscCall(PetscStrncpy(row, line, row_len));
153 fclose(fp);
154 PetscFunctionReturn(0);
155 }
156 }
157
158 fclose(fp);
159 if (!header_found) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Log '%s' has no column header.", path);
160 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_FILE_READ, "Log '%s' does not contain data row %d.", path, (int)row_index);
161}
162
163/**
164 * @brief Returns the zero-based column index for one comma-separated header field.
165 */
166static PetscErrorCode LogFindColumnIndex(const char *header, const char *column_name, PetscInt *index_out)
167{
168 char local_header[8192];
169 char *saveptr = NULL;
170 char *token = NULL;
171 PetscInt index = 0;
172
173 PetscFunctionBeginUser;
174 PetscCheck(header != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log header cannot be NULL.");
175 PetscCheck(column_name != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log column name cannot be NULL.");
176 PetscCheck(index_out != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log column index output cannot be NULL.");
177
178 PetscCall(PetscStrncpy(local_header, header, sizeof(local_header)));
179 token = strtok_r(local_header, ",\r\n", &saveptr);
180 while (token != NULL) {
181 while (*token == ' ') token++;
182 char *end = token + strlen(token) - 1;
183 while (end > token && (*end == ' ' || *end == '\r' || *end == '\n')) end--;
184 *(end + 1) = '\0';
185 if (strcmp(token, column_name) == 0) {
186 *index_out = index;
187 PetscFunctionReturn(0);
188 }
189 token = strtok_r(NULL, ",\r\n", &saveptr);
190 index++;
191 }
192 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Log column '%s' was not found.", column_name);
193}
194
195/**
196 * @brief Extracts one comma-separated log cell as text by header name.
197 */
198static PetscErrorCode LogGetColumnText(const char *header,
199 const char *row,
200 const char *column_name,
201 char *value,
202 size_t value_len)
203{
204 char local_row[8192];
205 char *saveptr = NULL;
206 char *token = NULL;
207 PetscInt target_index = -1;
208 PetscInt index = 0;
209
210 PetscFunctionBeginUser;
211 PetscCheck(row != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log row cannot be NULL.");
212 PetscCheck(value != NULL && value_len > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log value buffer cannot be NULL.");
213
214 PetscCall(LogFindColumnIndex(header, column_name, &target_index));
215 PetscCall(PetscStrncpy(local_row, row, sizeof(local_row)));
216
217 token = strtok_r(local_row, ",\r\n", &saveptr);
218 while (token != NULL) {
219 if (index == target_index) {
220 while (*token == ' ') token++;
221 char *end = token + strlen(token) - 1;
222 while (end > token && (*end == ' ' || *end == '\r' || *end == '\n')) end--;
223 *(end + 1) = '\0';
224 PetscCall(PetscStrncpy(value, token, value_len));
225 PetscFunctionReturn(0);
226 }
227 token = strtok_r(NULL, ",\r\n", &saveptr);
228 index++;
229 }
230 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Log row is missing column '%s'.", column_name);
231}
232
233/**
234 * @brief Extracts one comma-separated log cell as an integer by header name.
235 */
236static PetscErrorCode LogGetColumnInt(const char *header, const char *row, const char *column_name, PetscInt *value_out)
237{
238 char text[256];
239 char *endptr = NULL;
240 long parsed = 0;
241
242 PetscFunctionBeginUser;
243 PetscCheck(value_out != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log integer output cannot be NULL.");
244 PetscCall(LogGetColumnText(header, row, column_name, text, sizeof(text)));
245 parsed = strtol(text, &endptr, 10);
246 PetscCheck(endptr != text, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Log column '%s' did not contain an integer.", column_name);
247 *value_out = (PetscInt)parsed;
248 PetscFunctionReturn(0);
249}
250
251/**
252 * @brief Extracts one comma-separated log cell as a real by header name.
253 */
254static PetscErrorCode LogGetColumnReal(const char *header, const char *row, const char *column_name, PetscReal *value_out)
255{
256 char text[256];
257 char *endptr = NULL;
258 double parsed = 0.0;
259
260 PetscFunctionBeginUser;
261 PetscCheck(value_out != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Log real output cannot be NULL.");
262 PetscCall(LogGetColumnText(header, row, column_name, text, sizeof(text)));
263 parsed = strtod(text, &endptr);
264 PetscCheck(endptr != text, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Log column '%s' did not contain a real value.", column_name);
265 *value_out = (PetscReal)parsed;
266 PetscFunctionReturn(0);
267}
268
269typedef PetscErrorCode (*CapturedLoggingFn)(UserCtx *user, SimCtx *simCtx, void *ctx);
270
275
276/**
277 * @brief Captures stdout emitted by one logging helper into a temporary file-backed buffer.
278 */
279static PetscErrorCode CaptureLoggingOutput(UserCtx *user,
280 SimCtx *simCtx,
282 void *ctx,
283 char *captured,
284 size_t captured_len)
285{
286 char tmpdir[PETSC_MAX_PATH_LEN];
287 char capture_path[PETSC_MAX_PATH_LEN];
288 FILE *capture_file = NULL;
289 int saved_stdout = -1;
290 int capture_fd = -1;
291 size_t bytes_read = 0;
292 PetscErrorCode ierr;
293
294 PetscFunctionBeginUser;
295 PetscCheck(fn != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Capture callback cannot be NULL.");
296 PetscCheck(captured != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Capture buffer cannot be NULL.");
297 PetscCheck(captured_len > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Capture buffer must be non-empty.");
298
299 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
300 PetscCall(PetscSNPrintf(capture_path, sizeof(capture_path), "%s/logging.out", tmpdir));
301
302 fflush(stdout);
303 saved_stdout = dup(STDOUT_FILENO);
304 PetscCheck(saved_stdout >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup(STDOUT_FILENO) failed.");
305 capture_fd = open(capture_path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
306 PetscCheck(capture_fd >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to open capture file '%s'.", capture_path);
307 PetscCheck(dup2(capture_fd, STDOUT_FILENO) >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup2() failed while redirecting stdout.");
308 close(capture_fd);
309 capture_fd = -1;
310
311 ierr = fn(user, simCtx, ctx);
312 fflush(stdout);
313 PetscCheck(dup2(saved_stdout, STDOUT_FILENO) >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup2() failed while restoring stdout.");
314 close(saved_stdout);
315 saved_stdout = -1;
316 PetscCall(ierr);
317
318 capture_file = fopen(capture_path, "r");
319 PetscCheck(capture_file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to read capture file '%s'.", capture_path);
320 bytes_read = fread(captured, 1, captured_len - 1, capture_file);
321 captured[bytes_read] = '\0';
322 fclose(capture_file);
323 PetscCall(PicurvRemoveTempDir(tmpdir));
324 PetscFunctionReturn(0);
325}
326
327/**
328 * @brief Adapts `LOG_PARTICLE_FIELDS()` to the generic stdout-capture callback shape.
329 */
330static PetscErrorCode InvokeParticleFieldLog(UserCtx *user, SimCtx *simCtx, void *ctx)
331{
332 PetscInt print_interval = *((PetscInt *)ctx);
333
334 PetscFunctionBeginUser;
335 (void)simCtx;
336 PetscCall(LOG_PARTICLE_FIELDS(user, print_interval));
337 PetscFunctionReturn(0);
338}
339
340/**
341 * @brief Adapts `EmitParticleConsoleSnapshot()` to the generic stdout-capture callback shape.
342 */
343static PetscErrorCode InvokeParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, void *ctx)
344{
345 PetscInt step = *((PetscInt *)ctx);
346
347 PetscFunctionBeginUser;
348 PetscCall(EmitParticleConsoleSnapshot(user, simCtx, step));
349 PetscFunctionReturn(0);
350}
351
352/**
353 * @brief Adapts `EmitStatisticsConsoleSnapshot()` to the generic stdout-capture callback shape.
354 */
355static PetscErrorCode InvokeStatisticsConsoleSnapshot(UserCtx *user, SimCtx *simCtx, void *ctx)
356{
357 PetscInt step = *((PetscInt *)ctx);
358
359 PetscFunctionBeginUser;
360 PetscCall(EmitStatisticsConsoleSnapshot(user, simCtx, step));
361 PetscFunctionReturn(0);
362}
363
364/**
365 * @brief Adapts `LOG_FIELD_ANATOMY()` to the generic stdout-capture callback shape.
366 */
367static PetscErrorCode InvokeFieldAnatomyLog(UserCtx *user, SimCtx *simCtx, void *ctx)
368{
369 const AnatomyCaptureCtx *anatomy_ctx = (const AnatomyCaptureCtx *)ctx;
370
371 PetscFunctionBeginUser;
372 (void)simCtx;
373 PetscCall(LOG_FIELD_ANATOMY(user, anatomy_ctx->field_id, anatomy_ctx->stage_name));
374 PetscFunctionReturn(0);
375}
376
377/**
378 * @brief Creates a small particle-bearing runtime fixture used by logging tests.
379 */
380static PetscErrorCode SeedLoggingParticleFixture(SimCtx **simCtx_out, UserCtx **user_out)
381{
382 PetscReal *positions = NULL;
383 PetscReal *velocities = NULL;
384 PetscReal *weights = NULL;
385 PetscInt *cell_ids = NULL;
386 PetscInt *status = NULL;
387 PetscReal *psi = NULL;
388
389 PetscFunctionBeginUser;
390 PetscCall(PicurvCreateMinimalContexts(simCtx_out, user_out, 4, 4, 4));
391 PetscCall(PicurvCreateSwarmPair(*user_out, 2, "ske"));
392 (*simCtx_out)->np = 2;
393 (*simCtx_out)->particleConsoleOutputFreq = 2;
394 (*simCtx_out)->LoggingFrequency = 1;
395
396 PetscCall(DMSwarmGetField((*user_out)->swarm, "position", NULL, NULL, (void **)&positions));
397 PetscCall(DMSwarmGetField((*user_out)->swarm, "velocity", NULL, NULL, (void **)&velocities));
398 PetscCall(DMSwarmGetField((*user_out)->swarm, "weight", NULL, NULL, (void **)&weights));
399 PetscCall(DMSwarmGetField((*user_out)->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
400 PetscCall(DMSwarmGetField((*user_out)->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
401 PetscCall(DMSwarmGetField((*user_out)->swarm, "Psi", NULL, NULL, (void **)&psi));
402
403 positions[0] = 0.25; positions[1] = 0.50; positions[2] = 0.75;
404 positions[3] = 0.50; positions[4] = 0.50; positions[5] = 0.50;
405 velocities[0] = 1.0; velocities[1] = 2.0; velocities[2] = 3.0;
406 velocities[3] = 4.0; velocities[4] = 5.0; velocities[5] = 6.0;
407 weights[0] = 0.2; weights[1] = 0.3; weights[2] = 0.4;
408 weights[3] = 0.5; weights[4] = 0.5; weights[5] = 0.5;
409 cell_ids[0] = 0; cell_ids[1] = 0; cell_ids[2] = 0;
410 cell_ids[3] = 1; cell_ids[4] = 1; cell_ids[5] = 1;
411 status[0] = ACTIVE_AND_LOCATED;
412 status[1] = ACTIVE_AND_LOCATED;
413 psi[0] = 1.0;
414 psi[1] = 3.0;
415
416 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "Psi", NULL, NULL, (void **)&psi));
417 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
418 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
419 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "weight", NULL, NULL, (void **)&weights));
420 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "velocity", NULL, NULL, (void **)&velocities));
421 PetscCall(DMSwarmRestoreField((*user_out)->swarm, "position", NULL, NULL, (void **)&positions));
422 PetscFunctionReturn(0);
423}
424
425/**
426 * @brief Fills one Cartesian velocity field with a uniform constant state.
427 */
428static PetscErrorCode SetUniformVelocityField(UserCtx *user, Vec field, PetscReal ux, PetscReal uy, PetscReal uz)
429{
430 Cmpnts ***arr = NULL;
431
432 PetscFunctionBeginUser;
433 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
434 PetscCheck(field != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Velocity field cannot be NULL.");
435
436 PetscCall(DMDAVecGetArray(user->fda, field, &arr));
437 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
438 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
439 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
440 arr[k][j][i].x = ux;
441 arr[k][j][i].y = uy;
442 arr[k][j][i].z = uz;
443 }
444 }
445 }
446 PetscCall(DMDAVecRestoreArray(user->fda, field, &arr));
447 PetscFunctionReturn(0);
448}
449
450/**
451 * @brief Fills one scalar field with a uniform constant state.
452 */
453static PetscErrorCode SetUniformScalarField(UserCtx *user, Vec field, PetscReal value)
454{
455 PetscReal ***arr = NULL;
456
457 PetscFunctionBeginUser;
458 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
459 PetscCheck(field != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Scalar field cannot be NULL.");
460
461 PetscCall(DMDAVecGetArray(user->da, field, &arr));
462 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
463 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
464 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
465 arr[k][j][i] = value;
466 }
467 }
468 }
469 PetscCall(DMDAVecRestoreArray(user->da, field, &arr));
470 PetscFunctionReturn(0);
471}
472/**
473 * @brief Fills one Cartesian velocity field with u=0, v=v_amp*sin(2π*k/km), w=w_const.
474 *
475 * Sets the sinusoidal profile at ALL owned nodes (including the periodic duplicate endpoint),
476 * matching how the IC routines populate fields before any periodic-endpoint fix is applied.
477 */
478static PetscErrorCode SetSinusoidalVZField(UserCtx *user, Vec field, PetscReal v_amp, PetscReal w_const)
479{
480 Cmpnts ***arr = NULL;
481 /* Production layout: physical cells occupy 1..mz-2; 0 and mz-1 are ghost layers,
482 which on a periodic axis hold copies of the opposite physical cell. */
483 const PetscInt ncells = user->info.mz - 2;
484
485 PetscFunctionBeginUser;
486 PetscCheck(user != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx cannot be NULL.");
487 PetscCheck(field != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Velocity field cannot be NULL.");
488
489 PetscCall(DMDAVecGetArray(user->fda, field, &arr));
490 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
491 const PetscInt cell = (k == 0) ? ncells : (k == user->info.mz - 1) ? 1 : k;
492 PetscReal z_phase = (2.0 * PETSC_PI * (PetscReal)(cell - 1)) / (PetscReal)ncells;
493 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
494 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
495 arr[k][j][i].x = 0.0;
496 arr[k][j][i].y = v_amp * PetscSinReal(z_phase);
497 arr[k][j][i].z = w_const;
498 }
499 }
500 }
501 PetscCall(DMDAVecRestoreArray(user->fda, field, &arr));
502 PetscFunctionReturn(0);
503}
504
505/**
506 * @brief Tests string-conversion helpers for configured enums and unknown values.
507 */
508
509static PetscErrorCode TestStringConversionHelpers(void)
510{
511 PetscFunctionBeginUser;
512 PetscCall(PicurvAssertBool(strcmp(BCFaceToString(BC_FACE_NEG_X), "-Xi (I-Min)") == 0,
513 "BCFaceToString should report the negative-x face"));
515 "ParticleInitializationToString should report the volume mode"));
516 PetscCall(PicurvAssertBool(strcmp(LESModelToString(CONSTANT_SMAGORINSKY), "Constant Smagorinsky") == 0,
517 "LESModelToString should report the constant model"));
518 PetscCall(PicurvAssertBool(strcmp(MomentumSolverTypeToString(MOMENTUM_SOLVER_EXPLICIT_RK), "Explicit 4 stage Runge-Kutta ") == 0,
519 "MomentumSolverTypeToString should report the explicit solver"));
520 PetscCall(PicurvAssertBool(strcmp(MomentumSolverTypeToString(MOMENTUM_SOLVER_NEWTON_KRYLOV), "Newton Krylov") == 0,
521 "MomentumSolverTypeToString should report the Newton Krylov solver"));
522 PetscCall(PicurvAssertBool(strcmp(BCTypeToString(PERIODIC), "PERIODIC") == 0,
523 "BCTypeToString should report periodic boundaries"));
525 "BCHandlerTypeToString should report the driven periodic handler"));
526 PetscCall(PicurvAssertBool(strcmp(ParticleLocationStatusToString(LOST), "LOST") == 0,
527 "ParticleLocationStatusToString should report LOST state"));
528 PetscCall(PicurvAssertBool(strcmp(ParticleLocationStatusToString(EXITED), "EXITED") == 0,
529 "ParticleLocationStatusToString should report EXITED state"));
530 PetscFunctionReturn(0);
531}
532/**
533 * @brief Tests that log level selection honors the environment variable.
534 */
535
536static PetscErrorCode TestGetLogLevelFromEnvironment(void)
537{
538 PetscFunctionBeginUser;
540 "get_log_level should honor LOG_LEVEL=INFO in this test binary"));
541 PetscCall(print_log_level());
542 PetscFunctionReturn(0);
543}
544/**
545 * @brief Tests the function allow-list filter used by the logging layer.
546 */
547
548static PetscErrorCode TestAllowedFunctionsFilter(void)
549{
550 const char *allow_list[] = {"ComputeSpecificKE", "WriteEulerianFile"};
551
552 PetscFunctionBeginUser;
553 set_allowed_functions(allow_list, 2);
554 PetscCall(PicurvAssertBool(is_function_allowed("ComputeSpecificKE"),
555 "Allowed list should include ComputeSpecificKE"));
556 PetscCall(PicurvAssertBool((PetscBool)!is_function_allowed("UnlistedFunction"),
557 "Allowed list should exclude unknown function names"));
558
559 set_allowed_functions(NULL, 0);
560 PetscCall(PicurvAssertBool(is_function_allowed("AnyFunction"),
561 "Empty allow-list should permit all functions"));
562 PetscFunctionReturn(0);
563}
564/**
565 * @brief Tests periodic particle console snapshot enablement and cadence.
566 */
567
568static PetscErrorCode TestParticleConsoleSnapshotCadence(void)
569{
570 SimCtx simCtx;
571
572 PetscFunctionBeginUser;
573 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
574 simCtx.np = 32;
575 simCtx.particleConsoleOutputFreq = 4;
576
578 "Particle snapshot contract should be enabled when particles and cadence are configured"));
580 "Snapshot should emit on cadence-aligned completed steps"));
581 PetscCall(PicurvAssertBool((PetscBool)!ShouldEmitPeriodicParticleConsoleSnapshot(&simCtx, 7),
582 "Snapshot should not emit off-cadence"));
583
584 simCtx.particleConsoleOutputFreq = 0;
585 PetscCall(PicurvAssertBool((PetscBool)!IsParticleConsoleSnapshotEnabled(&simCtx),
586 "Zero cadence should disable periodic particle snapshots"));
587 PetscCall(PicurvAssertBool((PetscBool)!ShouldEmitPeriodicParticleConsoleSnapshot(NULL, 4),
588 "NULL SimCtx should never emit periodic snapshots"));
589 PetscFunctionReturn(0);
590}
591/**
592 * @brief Builds the window definition backing this suite's statistics console fixture.
593 *
594 * One bounded pressure window on a per-step cadence: bounded so the snapshot exercises
595 * its percentage-progress branch, and a single field so the fixture stays cheap.
596 */
598{
599 PicurvWindowDefinition definition;
600
601 memset(&definition, 0, sizeof(definition));
602 strncpy(definition.name, "console_window", PICURV_WINDOW_NAME_LENGTH - 1);
605 definition.step_cadence = 1;
606 definition.bounded = PETSC_TRUE;
607 definition.end_time = 4.0;
608 definition.field_count = 1;
609 definition.fields[0].field_id = FIELD_ID_P;
610 return definition;
611}
612/**
613 * @brief Tests periodic statistics console snapshot enablement and cadence.
614 */
615
616static PetscErrorCode TestStatisticsConsoleSnapshotCadence(void)
617{
618 SimCtx simCtx;
619 PicurvWindow window;
621
622 PetscFunctionBeginUser;
623 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
624 PetscCall(PicurvWindowInit(&window, &definition));
625 simCtx.fieldStatisticsEnabled = PETSC_TRUE;
627 simCtx.fieldStatisticsWindows = &window;
629
631 "Statistics snapshot contract should be enabled when a window and cadence are configured"));
633 "Snapshot should emit on cadence-aligned completed steps"));
634 PetscCall(PicurvAssertBool((PetscBool)!ShouldEmitPeriodicStatisticsConsoleSnapshot(&simCtx, 7),
635 "Snapshot should not emit off-cadence"));
636 PetscCall(PicurvAssertBool((PetscBool)!ShouldEmitPeriodicStatisticsConsoleSnapshot(&simCtx, -1),
637 "Snapshot should not emit for a step that has not completed"));
638
640 PetscCall(PicurvAssertBool((PetscBool)!IsStatisticsConsoleSnapshotEnabled(&simCtx),
641 "Zero cadence should disable periodic statistics snapshots"));
642 PetscCall(PicurvAssertBool((PetscBool)!ShouldEmitPeriodicStatisticsConsoleSnapshot(&simCtx, 0),
643 "Zero cadence should not emit even on the step that opens a run"));
644
645 /* The console cadence is a reporting contract layered on the subsystem gate: with
646 * nothing accumulating there is nothing to report, whatever the cadence says. */
649 PetscCall(PicurvAssertBool((PetscBool)!IsStatisticsConsoleSnapshotEnabled(&simCtx),
650 "A configured cadence should not enable snapshots without an accumulating window"));
651
653 simCtx.fieldStatisticsEnabled = PETSC_FALSE;
654 PetscCall(PicurvAssertBool((PetscBool)!IsStatisticsConsoleSnapshotEnabled(&simCtx),
655 "A disabled subsystem should not emit statistics snapshots"));
656
658 "NULL SimCtx should never emit periodic snapshots"));
659 PetscFunctionReturn(0);
660}
661/**
662 * @brief Tests logging-side file parsing, helper formatting, and progress utilities.
663 */
664
666{
667 char tmpdir[PETSC_MAX_PATH_LEN];
668 char allow_path[PETSC_MAX_PATH_LEN];
669 char dual_log_path[PETSC_MAX_PATH_LEN];
670 FILE *file = NULL;
671 char **funcs = NULL;
672 PetscInt nfuncs = 0;
673 Cell cell;
674 PetscReal distances[6] = {1.0, 2.0, 3.0, 4.0, 5.0, 6.0};
675 DualMonitorCtx *monctx = NULL;
676 void *ctx = NULL;
677
678 PetscFunctionBeginUser;
679 PetscCall(PetscMemzero(&cell, sizeof(cell)));
680 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
681 PetscCall(PetscSNPrintf(allow_path, sizeof(allow_path), "%s/allowed_functions.txt", tmpdir));
682 PetscCall(PetscSNPrintf(dual_log_path, sizeof(dual_log_path), "%s/dual-monitor.log", tmpdir));
683
684 file = fopen(allow_path, "w");
685 PetscCheck(file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to create allow-list file '%s'.", allow_path);
686 fputs(" ComputeSpecificKE \n", file);
687 fputs("# comment-only line\n", file);
688 for (PetscInt i = 0; i < 17; ++i) {
689 fprintf(file, "Helper_%02d # trailing comment\n", (int)i);
690 }
691 fclose(file);
692 file = NULL;
693
694 PetscCall(LoadAllowedFunctionsFromFile(allow_path, &funcs, &nfuncs));
695 PetscCall(PicurvAssertIntEqual(18, nfuncs, "LoadAllowedFunctionsFromFile should trim comments and keep all identifiers"));
696 PetscCall(PicurvAssertBool((PetscBool)(strcmp(funcs[0], "ComputeSpecificKE") == 0),
697 "LoadAllowedFunctionsFromFile should trim leading and trailing whitespace"));
698 PetscCall(PicurvAssertBool((PetscBool)(strcmp(funcs[17], "Helper_16") == 0),
699 "LoadAllowedFunctionsFromFile should grow past the initial pointer capacity"));
700 PetscCall(FreeAllowedFunctions(funcs, nfuncs));
701
702 for (PetscInt i = 0; i < 8; ++i) {
703 cell.vertices[i].x = (PetscReal)i;
704 cell.vertices[i].y = (PetscReal)(i + 1);
705 cell.vertices[i].z = (PetscReal)(i + 2);
706 }
707 PetscCall(LOG_CELL_VERTICES(&cell, 0));
708 PetscCall(LOG_FACE_DISTANCES(distances));
709
710 PetscCall(PetscCalloc1(1, &monctx));
711 monctx->file_handle = fopen(dual_log_path, "w");
712 PetscCheck(monctx->file_handle != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to create dual-monitor log '%s'.", dual_log_path);
713 ctx = monctx;
714 PetscCall(DualMonitorDestroy(&ctx));
715 PetscCall(PicurvAssertBool((PetscBool)(ctx == NULL),
716 "DualMonitorDestroy should clear the caller-owned context pointer"));
717
718 PrintProgressBar(0, 0, 4, 0.10, 0.0, -1);
719 PrintProgressBar(3, 0, 4, 0.40, 1.5, 7);
720 PrintProgressBar(0, 0, 0, 0.00, 0.0, -1);
721 PetscCall(PetscPrintf(PETSC_COMM_SELF, "\n"));
722
723 PetscCall(PicurvRemoveTempDir(tmpdir));
724 PetscFunctionReturn(0);
725}
726/**
727 * @brief Tests continuity, min/max, and anatomy logging helpers on minimal runtime fixtures.
728 */
729
731{
732 SimCtx *simCtx = NULL;
733 UserCtx *user = NULL;
734 char tmpdir[PETSC_MAX_PATH_LEN];
735 char continuity_path[PETSC_MAX_PATH_LEN];
736 PetscReal ***p = NULL;
737 Cmpnts ***ucat = NULL;
738 Cmpnts ***ucont = NULL;
739 PetscErrorCode ierr_minmax = 0;
740
741 PetscFunctionBeginUser;
742 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
743 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
744 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
745
746 simCtx->StartStep = 0;
747 simCtx->step = 1;
748 simCtx->MaxDiv = 1.25;
749 simCtx->MaxDivx = 1;
750 simCtx->MaxDivy = 2;
751 simCtx->MaxDivz = 3;
752 simCtx->MaxDivFlatArg = 17;
753 simCtx->poissonSourceImbalance = 8.5;
754 simCtx->FluxInSum = 5.0;
755 simCtx->FluxOutSum = 3.25;
756 PetscCall(LOG_CONTINUITY_METRICS(user));
757
758 simCtx->step = 2;
759 simCtx->MaxDiv = 0.75;
760 simCtx->poissonSourceImbalance = 4.5;
761 simCtx->FluxInSum = 2.5;
762 simCtx->FluxOutSum = 1.0;
763 PetscCall(LOG_CONTINUITY_METRICS(user));
764
765 PetscCall(PetscSNPrintf(continuity_path, sizeof(continuity_path), "%s/Continuity_Metrics.csv", simCtx->log_dir));
766 PetscCall(PicurvAssertFileExists(continuity_path, "continuity metrics CSV should be written"));
767 PetscCall(AssertFileContains(continuity_path, "step,block,max_divergence,max_divergence_k", "continuity metrics CSV should include the header"));
768 PetscCall(AssertFileContains(continuity_path, "1,0,1.2500000000e+00,3,2,1,17,", "continuity metrics CSV should record the divergence and its [k][j][i] location"));
769 PetscCall(AssertFileContains(continuity_path, "\n2,0,7.5000000000e-01,", "continuity metrics CSV should append later timesteps"));
770
771 PetscCall(DMDAVecGetArray(user->da, user->P, &p));
772 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
773 PetscCall(DMDAVecGetArray(user->fda, user->Ucont, &ucont));
774 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
775 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
776 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
777 p[k][j][i] = (PetscReal)(i + j + k);
778 ucat[k][j][i].x = (PetscReal)i;
779 ucat[k][j][i].y = (PetscReal)(-j);
780 ucat[k][j][i].z = (PetscReal)(2 * k);
781 ucont[k][j][i].x = (PetscReal)(10 + i);
782 ucont[k][j][i].y = (PetscReal)(20 + j);
783 ucont[k][j][i].z = (PetscReal)(30 + k);
784 }
785 }
786 }
787 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucont, &ucont));
788 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
789 PetscCall(DMDAVecRestoreArray(user->da, user->P, &p));
790
791 PetscCall(DMGlobalToLocalBegin(user->da, user->P, INSERT_VALUES, user->lP));
792 PetscCall(DMGlobalToLocalEnd(user->da, user->P, INSERT_VALUES, user->lP));
793 PetscCall(DMGlobalToLocalBegin(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
794 PetscCall(DMGlobalToLocalEnd(user->fda, user->Ucat, INSERT_VALUES, user->lUcat));
795 PetscCall(DMGlobalToLocalBegin(user->fda, user->Ucont, INSERT_VALUES, user->lUcont));
796 PetscCall(DMGlobalToLocalEnd(user->fda, user->Ucont, INSERT_VALUES, user->lUcont));
797
798 PetscCall(LOG_FIELD_MIN_MAX(user, FIELD_ID_P));
799 PetscCall(LOG_FIELD_MIN_MAX(user, FIELD_ID_UCAT));
800 PetscCall(LOG_FIELD_MIN_MAX(user, FIELD_ID_COORDINATES));
801 PetscCall(LOG_FIELD_MIN_MAX(user, FIELD_ID_UCONT));
802
803 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
804 ierr_minmax = LOG_FIELD_MIN_MAX(user, FIELD_ID_INVALID);
805 PetscCall(PetscPopErrorHandler());
806 PetscCall(PicurvAssertBool((PetscBool)(ierr_minmax != 0),
807 "LOG_FIELD_MIN_MAX should reject invalid field IDs"));
808
809 PetscCall(PicurvRemoveTempDir(tmpdir));
810 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
811 PetscFunctionReturn(0);
812}
813/**
814 * @brief Tests interpolation-error logging against an analytically matched particle field.
815 */
816
817static PetscErrorCode TestInterpolationErrorLogging(void)
818{
819 SimCtx *simCtx = NULL;
820 UserCtx *user = NULL;
821 PetscReal (*pos_arr)[3] = NULL;
822 PetscReal (*vel_arr)[3] = NULL;
823 Vec position_vec = NULL;
824 Vec analytical_vec = NULL;
825 const PetscScalar *analytical_arr = NULL;
826 char tmpdir[PETSC_MAX_PATH_LEN];
827 char metrics_path[PETSC_MAX_PATH_LEN];
828
829 PetscFunctionBeginUser;
830 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
831 PetscCall(PicurvCreateSwarmPair(user, 2, "ske"));
832 PetscCall(PicurvPopulateIdentityMetrics(user));
833 simCtx->ti = 0.25;
834 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_frame", "cartesian"));
835 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_0", "sin(x)*cos(y)*cos(z)*exp(-2*t)"));
836 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_1", "(-cos(x)*sin(y)*cos(z)*exp(-2*t))"));
837 PetscCall(PetscOptionsSetValue(NULL, "-ic_source_expr_2", "0"));
838 PetscCall(AnalyticalSolutionEngine(simCtx));
839 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
840 PetscCall(PetscStrncpy(simCtx->analysis_dir, tmpdir, sizeof(simCtx->analysis_dir)));
841 simCtx->ren = 1.0;
842 /* ti is physical time, not a step count. The CSV once wrote ti * dt, which read
843 2.5e-03 here instead of 0.25. */
844 simCtx->step = 25;
845 simCtx->dt = 0.01;
846 simCtx->ti = 0.25;
847
848 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void *)&pos_arr));
849 pos_arr[0][0] = 0.5 * PETSC_PI; pos_arr[0][1] = 0.0; pos_arr[0][2] = 0.0;
850 pos_arr[1][0] = 0.0; pos_arr[1][1] = 0.5 * PETSC_PI; pos_arr[1][2] = 0.0;
851 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void *)&pos_arr));
852
853 PetscCall(DMSwarmCreateGlobalVectorFromField(user->swarm, "position", &position_vec));
854 PetscCall(VecDuplicate(position_vec, &analytical_vec));
855 PetscCall(VecCopy(position_vec, analytical_vec));
856 PetscCall(SetAnalyticalSolutionForParticles(analytical_vec, simCtx));
857
858 PetscCall(DMSwarmGetField(user->swarm, "velocity", NULL, NULL, (void *)&vel_arr));
859 PetscCall(VecGetArrayRead(analytical_vec, &analytical_arr));
860 for (PetscInt particle = 0; particle < 2; ++particle) {
861 vel_arr[particle][0] = PetscRealPart(analytical_arr[3 * particle + 0]);
862 vel_arr[particle][1] = PetscRealPart(analytical_arr[3 * particle + 1]);
863 vel_arr[particle][2] = PetscRealPart(analytical_arr[3 * particle + 2]);
864 }
865 PetscCall(VecRestoreArrayRead(analytical_vec, &analytical_arr));
866 PetscCall(DMSwarmRestoreField(user->swarm, "velocity", NULL, NULL, (void *)&vel_arr));
867
868 PetscCall(VecDestroy(&analytical_vec));
869 PetscCall(DMSwarmDestroyGlobalVectorFromField(user->swarm, "position", &position_vec));
870 PetscCall(LOG_INTERPOLATION_ERROR(user));
871
872 PetscCall(PetscSNPrintf(metrics_path, sizeof(metrics_path), "%s/interpolation_error.csv", simCtx->analysis_dir));
873 PetscCall(PicurvAssertFileExists(metrics_path, "LOG_INTERPOLATION_ERROR should write interpolation_error.csv"));
874 PetscCall(AssertFileContains(metrics_path, "25,2.500000e-01,",
875 "interpolation_error.csv should record physical time, not time multiplied by dt"));
876 PetscCall(AnalyticalFieldDestroy(simCtx));
877 PetscCall(PicurvRemoveTempDir(tmpdir));
878 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
879 PetscFunctionReturn(0);
880}
881/**
882 * @brief Tests that the constant Smagorinsky model reports its configured coefficient, not a measured one.
883 *
884 * cs_effective is the dynamic procedure's Germano contraction ratio. The constant model has
885 * none, so the row carries nan there and the configured Cs in cs_mean; it once wrote 0,
886 * which reads like a measurement.
887 */
889{
890 SimCtx *simCtx = NULL;
891 UserCtx *user = NULL;
892 char tmpdir[PETSC_MAX_PATH_LEN];
893 char metrics_path[PETSC_MAX_PATH_LEN];
894
895 PetscFunctionBeginUser;
896 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 5, 5, 5));
897 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
898 PetscCall(PetscStrncpy(simCtx->analysis_dir, tmpdir, sizeof(simCtx->analysis_dir)));
899 simCtx->les = CONSTANT_SMAGORINSKY;
900 simCtx->les_config.constant_cs = 0.2;
901 simCtx->les_config.diagnostics_enabled = PETSC_TRUE;
903 simCtx->ren = 1.0;
904 simCtx->step = 3;
905 simCtx->ti = 0.5;
906 PetscCall(DMCreateLocalVector(user->da, &user->lNu_t));
907 PetscCall(VecSet(user->lNu_t, 0.0));
908 PetscCall(VecSet(user->lAj, 1.0));
909
910 PetscCall(LogLESDiagnostics(user));
911
912 PetscCall(PetscSNPrintf(metrics_path, sizeof(metrics_path), "%s/les_coefficient.csv", simCtx->analysis_dir));
913 PetscCall(PicurvAssertFileExists(metrics_path, "LogLESDiagnostics should write les_coefficient.csv"));
914 PetscCall(AssertFileContains(metrics_path, "3,5.000000e-01,nan,2.000000e-01,4.000000e-02,",
915 "the constant model should write nan for cs_effective and its Cs in cs_mean"));
916 PetscCall(PicurvRemoveTempDir(tmpdir));
917 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
918 PetscFunctionReturn(0);
919}
920
921/**
922 * @brief Tests file-backed scatter metrics logging against a fully occupied constant field.
923 */
924
925static PetscErrorCode TestScatterMetricsLogging(void)
926{
927 SimCtx *simCtx = NULL;
928 UserCtx *user = NULL;
929 char tmpdir[PETSC_MAX_PATH_LEN];
930 char metrics_path[PETSC_MAX_PATH_LEN];
931 PetscReal *positions = NULL;
932 PetscReal *psi = NULL;
933 PetscInt *cell_ids = NULL;
934 PetscInt *status = NULL;
935 PetscInt particle = 0;
936
937 PetscFunctionBeginUser;
938 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
939 PetscCall(PicurvCreateSwarmPair(user, 27, "ske"));
940 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
941 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
942 /* The metrics CSV goes to analysis_dir; left empty it would be written at /scatter_metrics.csv. */
943 PetscCall(PetscStrncpy(simCtx->analysis_dir, tmpdir, sizeof(simCtx->analysis_dir)));
944 simCtx->np = 27;
945 simCtx->step = 3;
946 simCtx->ti = 0.3;
947 PetscCall(VerificationFieldCompile("2.0", &simCtx->verificationScalar));
948
949 PetscCall(DMSwarmGetField(user->swarm, "position", NULL, NULL, (void **)&positions));
950 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
951 PetscCall(DMSwarmGetField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
952 PetscCall(DMSwarmGetField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
953
954 for (PetscInt k = 0; k < 3; ++k) {
955 for (PetscInt j = 0; j < 3; ++j) {
956 for (PetscInt i = 0; i < 3; ++i) {
957 positions[3 * particle + 0] = (i + 0.5) / 4.0;
958 positions[3 * particle + 1] = (j + 0.5) / 4.0;
959 positions[3 * particle + 2] = (k + 0.5) / 4.0;
960 cell_ids[3 * particle + 0] = i;
961 cell_ids[3 * particle + 1] = j;
962 cell_ids[3 * particle + 2] = k;
963 status[particle] = ACTIVE_AND_LOCATED;
964 psi[particle] = 2.0;
965 ++particle;
966 }
967 }
968 }
969
970 PetscCall(DMSwarmRestoreField(user->swarm, "Psi", NULL, NULL, (void **)&psi));
971 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_location_status", NULL, NULL, (void **)&status));
972 PetscCall(DMSwarmRestoreField(user->swarm, "DMSwarm_CellID", NULL, NULL, (void **)&cell_ids));
973 PetscCall(DMSwarmRestoreField(user->swarm, "position", NULL, NULL, (void **)&positions));
974
976 PetscCall(LOG_SCATTER_METRICS(user));
977
978 PetscCall(PetscSNPrintf(metrics_path, sizeof(metrics_path), "%s/scatter_metrics.csv", simCtx->analysis_dir));
979 PetscCall(PicurvAssertFileExists(metrics_path, "LOG_SCATTER_METRICS should write scatter_metrics.csv"));
980 PetscCall(AssertFileContains(metrics_path, "relative_L2_error",
981 "Scatter metrics CSV header should include relative_L2_error"));
982 PetscCall(AssertFileContains(metrics_path,
983 "3,3.000000e-01,27,27,27,1.000000e+00,1.000000e+00,5.400000e+01,5.400000e+01,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00,0.000000e+00",
984 "Scatter metrics CSV should record the expected constant-field zero-error row"));
985
986 PetscCall(PicurvRemoveTempDir(tmpdir));
987 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
988 PetscFunctionReturn(0);
989}
990/**
991 * @brief Tests stdout particle-table logging on a production-like swarm fixture.
992 */
993
994static PetscErrorCode TestParticleFieldTableLogging(void)
995{
996 SimCtx *simCtx = NULL;
997 UserCtx *user = NULL;
998 PetscInt print_interval = 1;
999 char captured[8192];
1000
1001 PetscFunctionBeginUser;
1002 PetscCall(SeedLoggingParticleFixture(&simCtx, &user));
1003 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeParticleFieldLog, &print_interval, captured, sizeof(captured)));
1004 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Position (x,y,z)") != NULL),
1005 "LOG_PARTICLE_FIELDS should print the particle table header"));
1006 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Weights (a1,a2,a3)") != NULL),
1007 "LOG_PARTICLE_FIELDS should print the weight-column header"));
1008 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1009 PetscFunctionReturn(0);
1010}
1011/**
1012 * @brief Tests console snapshot logging against the public periodic-snapshot helper.
1013 */
1014
1015static PetscErrorCode TestParticleConsoleSnapshotLogging(void)
1016{
1017 SimCtx *simCtx = NULL;
1018 UserCtx *user = NULL;
1019 PetscInt step = 4;
1020 char captured[8192];
1021
1022 PetscFunctionBeginUser;
1023 PetscCall(SeedLoggingParticleFixture(&simCtx, &user));
1024 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeParticleConsoleSnapshot, &step, captured, sizeof(captured)));
1025 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Particle states at step 4") != NULL),
1026 "EmitParticleConsoleSnapshot should print the step banner"));
1027 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Position (x,y,z)") != NULL),
1028 "EmitParticleConsoleSnapshot should reuse the particle table output"));
1029 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1030 PetscFunctionReturn(0);
1031}
1032/**
1033 * @brief Tests statistics console snapshot content, and its silence when disabled.
1034 *
1035 * Covers both halves of the monitoring contract from one fixture: an active window
1036 * reports its window-level scalars, and the identical call on a disabled subsystem
1037 * writes nothing at all, which is the observable form of the gate the runloop relies
1038 * on to keep a non-statistics run's log untouched.
1039 */
1040
1041static PetscErrorCode TestStatisticsConsoleSnapshotLogging(void)
1042{
1043 SimCtx *simCtx = NULL;
1044 UserCtx *user = NULL;
1045 PicurvWindow window;
1046 PicurvWindowStorage storage;
1048 PetscInt step = 2;
1049 char captured[8192];
1050
1051 PetscFunctionBeginUser;
1052 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1053 PetscCall(VecSet(user->Nvert, 0.0));
1054 PetscCall(PicurvWindowInit(&window, &definition));
1055 PetscCall(PicurvWindowStorageCreate(user, &definition, &storage));
1056
1057 simCtx->fieldStatisticsEnabled = PETSC_TRUE;
1058 simCtx->fieldStatisticsWindowCount = 1;
1059 simCtx->fieldStatisticsWindows = &window;
1060 simCtx->statisticsConsoleOutputFreq = 1;
1061 user->fieldStatisticsStorage = &storage;
1062
1063 /* Step 0 anchors the origin without sampling; steps 1 and 2 each represent one
1064 * unit of time, so the snapshot has two accepted samples to report. */
1065 for (PetscInt offered = 0; offered <= step; ++offered) {
1066 PetscCall(FieldStatisticsUpdateWindows(simCtx, offered, (PetscReal)offered));
1067 }
1068
1069 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeStatisticsConsoleSnapshot, &step,
1070 captured, sizeof(captured)));
1071 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Statistics windows at step 2") != NULL),
1072 "EmitStatisticsConsoleSnapshot should print the step banner"));
1073 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "console_window") != NULL),
1074 "EmitStatisticsConsoleSnapshot should name each configured window"));
1075 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "samples=2") != NULL),
1076 "EmitStatisticsConsoleSnapshot should report the accepted sample count"));
1077 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "valid=[") != NULL),
1078 "EmitStatisticsConsoleSnapshot should report mask coverage once storage carries samples"));
1079
1080 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
1081 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeStatisticsConsoleSnapshot, &step,
1082 captured, sizeof(captured)));
1083 PetscCall(PicurvAssertIntEqual(0, (PetscInt)strlen(captured),
1084 "a disabled subsystem emits no statistics console output"));
1085
1086 simCtx->fieldStatisticsWindows = NULL;
1087 simCtx->fieldStatisticsWindowCount = 0;
1088 user->fieldStatisticsStorage = NULL;
1089 PetscCall(PicurvWindowStorageDestroy(&storage));
1090 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1091 PetscFunctionReturn(0);
1092}
1093/**
1094 * @brief Sets the pressure field to a uniform value across the owned range.
1095 */
1096static PetscErrorCode SetUniformPressure(UserCtx *user, PetscReal value)
1097{
1098 PetscReal ***p = NULL;
1099 const DMDALocalInfo info = user->info;
1100
1101 PetscFunctionBeginUser;
1102 PetscCall(DMDAVecGetArray(user->da, user->P, &p));
1103 for (PetscInt k = info.zs; k < info.zs + info.zm; ++k)
1104 for (PetscInt j = info.ys; j < info.ys + info.ym; ++j)
1105 for (PetscInt i = info.xs; i < info.xs + info.xm; ++i) p[k][j][i] = value;
1106 PetscCall(DMDAVecRestoreArray(user->da, user->P, &p));
1107 PetscFunctionReturn(0);
1108}
1109/**
1110 * @brief Drives one accumulation run at a given console cadence, in the runloop's order.
1111 *
1112 * Reproduces the sequence the run loop applies for each completed step so the console
1113 * observes exactly the states a real run would present to it.
1114 */
1115static PetscErrorCode AccumulateAtConsoleCadence(SimCtx *simCtx, UserCtx *user,
1116 PicurvWindow *window,
1117 PicurvWindowStorage *storage,
1118 const PicurvWindowDefinition *definition,
1119 PetscInt console_frequency)
1120{
1121 PetscFunctionBeginUser;
1122 PetscCall(PicurvWindowInit(window, definition));
1123 simCtx->fieldStatisticsEnabled = PETSC_TRUE;
1124 simCtx->fieldStatisticsWindowCount = 1;
1125 simCtx->fieldStatisticsWindows = window;
1126 simCtx->statisticsConsoleOutputFreq = console_frequency;
1127 user->fieldStatisticsStorage = storage;
1128
1129 for (PetscInt step = 0; step <= 3; ++step) {
1130 PetscCall(SetUniformPressure(user, 1.0 + (PetscReal)step));
1131 PetscCall(FieldStatisticsUpdateWindows(simCtx, step, (PetscReal)step));
1133 PetscCall(EmitStatisticsConsoleSnapshot(user, simCtx, step));
1134 }
1135 }
1136 PetscFunctionReturn(0);
1137}
1138/**
1139 * @brief Asserts two accumulator vectors are bit-identical.
1140 */
1141static PetscErrorCode AssertVecsIdentical(Vec expected, Vec actual, const char *context)
1142{
1143 PetscBool equal = PETSC_FALSE;
1144
1145 PetscFunctionBeginUser;
1146 PetscCall(VecEqual(expected, actual, &equal));
1147 PetscCall(PicurvAssertBool(equal, context));
1148 PetscFunctionReturn(0);
1149}
1150/**
1151 * @brief Tests that the console cadence has no effect on any accumulated result.
1152 *
1153 * This is the observable form of the console cadence's exclusion from the window
1154 * definition hash: two runs over an identical field series, one reporting every step
1155 * and one reporting never, must leave bit-identical accumulator state. Running it
1156 * where the log level is at least `LOG_INFO` matters, because a snapshot that silently
1157 * declined to emit would make the comparison vacuous.
1158 */
1159
1161{
1162 SimCtx *simCtx = NULL;
1163 UserCtx *user = NULL;
1164 PicurvWindow reported, silent;
1165 PicurvWindowStorage reported_storage, silent_storage;
1167 char captured[8192];
1168 PetscInt step = 3;
1169
1170 PetscFunctionBeginUser;
1171 definition.fields[0].want_second = PETSC_TRUE;
1172 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1173 PetscCall(VecSet(user->Nvert, 0.0));
1174 PetscCall(PicurvWindowStorageCreate(user, &definition, &reported_storage));
1175 PetscCall(PicurvWindowStorageCreate(user, &definition, &silent_storage));
1176
1177 PetscCall(AccumulateAtConsoleCadence(simCtx, user, &reported, &reported_storage, &definition, 1));
1178 PetscCall(AccumulateAtConsoleCadence(simCtx, user, &silent, &silent_storage, &definition, 0));
1179
1180 PetscCall(PicurvAssertIntEqual(reported.sample_count, silent.sample_count,
1181 "both cadences accept the same states"));
1182 PetscCall(PicurvAssertRealNear(reported.total_weight, silent.total_weight, 0.0,
1183 "both cadences accumulate the same total weight"));
1184 PetscCall(AssertVecsIdentical(reported_storage.count, silent_storage.count,
1185 "per-point sample counts are independent of the console cadence"));
1186 PetscCall(AssertVecsIdentical(reported_storage.weight, silent_storage.weight,
1187 "per-point weights are independent of the console cadence"));
1188 PetscCall(AssertVecsIdentical(reported_storage.mean[0], silent_storage.mean[0],
1189 "means are independent of the console cadence"));
1190 PetscCall(AssertVecsIdentical(reported_storage.m2[0], silent_storage.m2[0],
1191 "second moments are independent of the console cadence"));
1192
1193 /* The reporting cadence did drive real output, so the comparison above compared a
1194 * reported run against a silent one rather than two silent ones. */
1195 simCtx->statisticsConsoleOutputFreq = 1;
1196 simCtx->fieldStatisticsWindows = &reported;
1197 user->fieldStatisticsStorage = &reported_storage;
1198 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeStatisticsConsoleSnapshot, &step,
1199 captured, sizeof(captured)));
1200 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "console_window") != NULL),
1201 "the reporting cadence emits console output at this log level"));
1202
1203 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
1204 simCtx->fieldStatisticsWindows = NULL;
1205 simCtx->fieldStatisticsWindowCount = 0;
1206 user->fieldStatisticsStorage = NULL;
1207 PetscCall(PicurvWindowStorageDestroy(&silent_storage));
1208 PetscCall(PicurvWindowStorageDestroy(&reported_storage));
1209 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1210 PetscFunctionReturn(0);
1211}
1212/**
1213 * @brief Tests file-backed particle metrics logging after derived metrics are computed.
1214 */
1215
1216static PetscErrorCode TestParticleMetricsLogging(void)
1217{
1218 SimCtx *simCtx = NULL;
1219 UserCtx *user = NULL;
1220 char tmpdir[PETSC_MAX_PATH_LEN];
1221 char metrics_path[PETSC_MAX_PATH_LEN];
1222
1223 PetscFunctionBeginUser;
1224 PetscCall(SeedLoggingParticleFixture(&simCtx, &user));
1225 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1226 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1227 PetscCall(PetscStrncpy(simCtx->analysis_dir, tmpdir, sizeof(simCtx->analysis_dir)));
1228 simCtx->StartStep = 0;
1229 simCtx->step = 1;
1230 simCtx->particlesLostLastStep = 1;
1231 simCtx->particlesLostCumulative = 7;
1232 simCtx->particlesMigratedLastStep = 2;
1233 simCtx->migrationPassesLastStep = 3;
1234
1235 PetscCall(CalculateParticleCountPerCell(user));
1236 {
1237 /* A count in a dummy cell (index 0 on every axis) must not reach the per-cell statistics. */
1238 PetscScalar ***count = NULL;
1239 PetscCall(DMDAVecGetArray(user->da, user->ParticleCount, &count));
1240 count[0][0][0] = 5.0;
1241 PetscCall(DMDAVecRestoreArray(user->da, user->ParticleCount, &count));
1242 }
1243 PetscCall(CalculateAdvancedParticleMetrics(user));
1244 {
1245 const PetscInt cells = (user->info.mx - 2) * (user->info.my - 2) * (user->info.mz - 2);
1246 PetscCall(PicurvAssertIntEqual(2, simCtx->occupiedCellCount, "the two particles occupy two cells"));
1247 PetscCall(PicurvAssertIntEqual(0, simCtx->particlesPerCellMin, "most cells are empty"));
1248 PetscCall(PicurvAssertIntEqual(1, simCtx->particlesPerCellMax, "no physical cell holds two particles"));
1249 PetscCall(PicurvAssertRealNear(2.0 / (PetscReal)cells, simCtx->particlesPerCellMean, 1.0e-12,
1250 "the mean is the particles in cells over the physical cell count"));
1251 }
1252 PetscCall(LOG_SEARCH_METRICS(user));
1253
1254 /* The per-step particle metrics, occupied cells included, are search_metrics.csv's. */
1255 PetscCall(PetscSNPrintf(metrics_path, sizeof(metrics_path), "%s/search_metrics.csv", simCtx->analysis_dir));
1256 PetscCall(PicurvAssertFileExists(metrics_path, "LOG_SEARCH_METRICS should write search_metrics.csv"));
1257 PetscCall(AssertFileContains(metrics_path, ",occupied_cells,particles_per_cell_min,particles_per_cell_mean,particles_per_cell_max",
1258 "search_metrics.csv should carry the occupied-cell count and the per-cell statistics"));
1259 PetscCall(AssertFileContains(metrics_path, ",1,7,2,3,", "search_metrics.csv should record lost, cumulative lost, migrated and passes in order"));
1260 PetscCall(PicurvRemoveTempDir(tmpdir));
1261 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1262 PetscFunctionReturn(0);
1263}
1264/**
1265 * @brief Tests file-backed search metrics logging with the compact CSV contract.
1266 */
1267
1268static PetscErrorCode TestSearchMetricsLogging(void)
1269{
1270 SimCtx *simCtx = NULL;
1271 UserCtx *user = NULL;
1272 char tmpdir[PETSC_MAX_PATH_LEN];
1273 char metrics_path[PETSC_MAX_PATH_LEN];
1274
1275 PetscFunctionBeginUser;
1276 PetscCall(SeedLoggingParticleFixture(&simCtx, &user));
1277 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1278 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1279 /* The metrics CSV goes to analysis_dir; left empty it would be written at /search_metrics.csv. */
1280 PetscCall(PetscStrncpy(simCtx->analysis_dir, tmpdir, sizeof(simCtx->analysis_dir)));
1281 simCtx->step = 2;
1282 simCtx->ti = 0.2;
1283 simCtx->particlesLostLastStep = 1;
1284 simCtx->particlesLostCumulative = 7;
1285 simCtx->particlesMigratedLastStep = 2;
1286 simCtx->migrationPassesLastStep = 3;
1287 simCtx->particleLoadImbalance = 1.5;
1288 simCtx->searchMetrics.searchAttempts = 4;
1289 simCtx->searchMetrics.searchPopulation = 2;
1291 simCtx->searchMetrics.searchLostCount = 1;
1292 simCtx->searchMetrics.traversalStepsSum = 10;
1293 simCtx->searchMetrics.reSearchCount = 2;
1294 simCtx->searchMetrics.maxTraversalSteps = 6;
1296 simCtx->searchMetrics.tieBreakCount = 1;
1301
1302 PetscCall(LOG_SEARCH_METRICS(user));
1303
1304 PetscCall(PetscSNPrintf(metrics_path, sizeof(metrics_path), "%s/search_metrics.csv", simCtx->analysis_dir));
1305 PetscCall(PicurvAssertFileExists(metrics_path, "LOG_SEARCH_METRICS should write search_metrics.csv"));
1306 PetscCall(AssertFileContains(metrics_path, "search_attempts", "Search metrics CSV header should include search_attempts"));
1307 PetscCall(AssertFileContains(metrics_path, "search_population", "Search metrics CSV header should include search_population"));
1308 PetscCall(AssertFileContains(metrics_path, "max_particle_pass_depth", "Search metrics CSV header should include max_particle_pass_depth"));
1309 PetscCall(AssertFileContains(metrics_path, "search_work_index", "Search metrics CSV header should include search_work_index"));
1310 PetscCall(AssertFileContains(metrics_path, "re_search_fraction", "Search metrics CSV header should include re_search_fraction"));
1311 PetscCall(AssertFileContains(metrics_path, "lost_cumulative", "Search metrics CSV header should include the cumulative-loss column"));
1312 PetscCall(AssertFileContains(metrics_path, "2,2.000000e-01,2,1,7,2,3,4,2.500000e+00,6,1,2,3,1,3,1.500000e+00,2,1,1,10,2,1,5.000000e-01,5.000000e+00,1.000000e+00", "Search metrics CSV should record the V2 raw and derived search metrics"));
1313 PetscCall(PicurvRemoveTempDir(tmpdir));
1314 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1315 PetscFunctionReturn(0);
1316}
1317/**
1318 * @brief Tests stdout field-anatomy logging on the corrected production-like DM fixture.
1319 */
1320
1321static PetscErrorCode TestFieldAnatomyLogging(void)
1322{
1323 SimCtx *simCtx = NULL;
1324 UserCtx *user = NULL;
1325 char captured[8192];
1326 AnatomyCaptureCtx anatomy_ctx = {FIELD_ID_P, "unit-test"};
1327
1328 PetscFunctionBeginUser;
1329 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1330 PetscCall(VecSet(user->P, 7.0));
1331 PetscCall(DMGlobalToLocalBegin(user->da, user->P, INSERT_VALUES, user->lP));
1332 PetscCall(DMGlobalToLocalEnd(user->da, user->P, INSERT_VALUES, user->lP));
1333 PetscCall(CaptureLoggingOutput(user, simCtx, InvokeFieldAnatomyLog, &anatomy_ctx, captured, sizeof(captured)));
1334 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Field Anatomy Log: [P]") != NULL),
1335 "LOG_FIELD_ANATOMY should print the requested field name"));
1336 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, "Layout: [Cell-Centered]") != NULL),
1337 "LOG_FIELD_ANATOMY should report the inferred data layout"));
1338 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1339 PetscFunctionReturn(0);
1340}
1341/* Profiled stand-ins: the profiling macros name their PETSc event by __func__. */
1342/** @brief Profiled stand-in: an aggregate named FlowSolver. */
1344/** @brief Profiled stand-in: an aggregate the per-step list does not select. */
1346/** @brief Profiled stand-in: a helper that profiling.helpers names. */
1348/** @brief Profiled stand-in: a helper that profiling.helpers does not name. */
1350
1351/**
1352 * @brief Tests profiling helper lifecycle logging for timestep and final-summary outputs.
1353 * @details Aggregates are always timed; a helper is timed only when `profiling.helpers` names
1354 * it; the per-step file lists selected aggregates; the summary lists every timed PICurv
1355 * function and then PETSc's own events.
1356 */
1357static PetscErrorCode TestProfilingLifecycleHelpers(void)
1358{
1359 SimCtx simCtx;
1360 char tmpdir[PETSC_MAX_PATH_LEN];
1361 char timestep_path[PETSC_MAX_PATH_LEN];
1362 char summary_path[PETSC_MAX_PATH_LEN];
1363 static char selected_name[] = "ProfiledFlowSolver";
1364 static char helper_name[] = "ProfiledEnabledHelper";
1365 char *selected_funcs[] = {selected_name};
1366 char *helpers[] = {helper_name};
1367
1368 PetscFunctionBeginUser;
1369 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
1370 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1371 PetscCall(PetscStrncpy(simCtx.log_dir, tmpdir, sizeof(simCtx.log_dir)));
1372 PetscCall(PetscStrncpy(simCtx.profilingTimestepMode, "selected", sizeof(simCtx.profilingTimestepMode)));
1373 simCtx.rank = 0;
1374 simCtx.exec_mode = EXEC_MODE_SOLVER;
1375 simCtx.StartStep = 0;
1376 simCtx.nProfilingSelectedFuncs = 1;
1377 simCtx.profilingSelectedFuncs = selected_funcs;
1378 simCtx.nProfilingHelpers = 1;
1379 simCtx.profilingHelpers = helpers;
1380 simCtx.profilingFinalSummary = PETSC_TRUE;
1381
1382 PetscCall(ProfilingInitialize(&simCtx));
1383 PetscCall(ProfilingResetTimestepCounters());
1384
1389 PetscCall(ProfilingLogTimestepSummary(&simCtx, 1));
1390
1392 PetscCall(ProfilingResetTimestepCounters());
1393 PetscCall(ProfilingLogTimestepSummary(&simCtx, 2));
1394 PetscCall(ProfilingFinalize(&simCtx));
1395
1396 PetscCall(PetscSNPrintf(timestep_path, sizeof(timestep_path), "%s/Profiling_Timestep_Summary.csv", simCtx.log_dir));
1397 PetscCall(PetscSNPrintf(summary_path, sizeof(summary_path), "%s/ProfilingSummary_Solver.csv", simCtx.log_dir));
1398 PetscCall(PicurvAssertFileExists(timestep_path, "profiling timestep summary should be written"));
1399 PetscCall(PicurvAssertFileExists(summary_path, "profiling final summary should be written"));
1400 PetscCall(AssertFileContains(timestep_path, "step,function,calls,step_time_s",
1401 "profiling timestep summary should contain the CSV header"));
1402 PetscCall(AssertFileContains(timestep_path, "1,ProfiledFlowSolver,1,",
1403 "profiling timestep summary should log selected functions"));
1404 PetscCall(AssertFileNotContains(timestep_path, "2,ProfiledFlowSolver",
1405 "a call before the step interval was reset belongs to no step"));
1406 PetscCall(AssertFileNotContains(timestep_path, "UnselectedAggregate",
1407 "profiling timestep summary should omit unselected functions in selected mode"));
1408 PetscCall(AssertFileContains(summary_path, "section,function,max_time_s,max_rank",
1409 "profiling final summary should be a CSV with its header"));
1410 PetscCall(AssertFileContains(summary_path, "picurv,ProfiledFlowSolver,",
1411 "profiling final summary should include selected functions in the picurv section"));
1412 PetscCall(AssertFileContains(summary_path, "UnselectedAggregate",
1413 "profiling final summary should include total-time entries for unselected functions"));
1414 PetscCall(AssertFileContains(summary_path, "EnabledHelper",
1415 "a helper named in profiling.helpers is timed"));
1416 PetscCall(AssertFileNotContains(summary_path, "DisabledHelper",
1417 "a helper not named in profiling.helpers records nothing"));
1418 PetscCall(AssertFileContains(summary_path, "\npetsc,",
1419 "the summary should list PETSc's own events in the petsc section"));
1420 PetscCall(PicurvRemoveTempDir(tmpdir));
1421 PetscFunctionReturn(0);
1422}
1423
1424/**
1425 * @brief Tests runtime memory log header, step rows, final rows, and disabled mode.
1426 */
1427static PetscErrorCode TestRuntimeMemoryLogHelpers(void)
1428{
1429 SimCtx simCtx;
1430 char tmpdir[PETSC_MAX_PATH_LEN];
1431 char memory_path[PETSC_MAX_PATH_LEN];
1432
1433 PetscFunctionBeginUser;
1434 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
1435 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1436 PetscCall(PetscStrncpy(simCtx.log_dir, tmpdir, sizeof(simCtx.log_dir)));
1437 simCtx.rank = 0;
1438 simCtx.runtimeMemoryLogEnabled = PETSC_TRUE;
1439 simCtx.runtimeMemoryLogHasPrevious = PETSC_FALSE;
1440 simCtx.continueMode = PETSC_FALSE;
1441 simCtx.StartStep = 0;
1442 PetscCall(PetscMemorySetGetMaximumUsage());
1443
1444 PetscCall(RuntimeMemoryLogSample(&simCtx, 1, "Step", "-"));
1445 PetscCall(RuntimeMemoryLogSample(&simCtx, 1, "Final", "Complete"));
1446 PetscCall(PetscSNPrintf(memory_path, sizeof(memory_path), "%s/Runtime_Memory.csv", simCtx.log_dir));
1447 PetscCall(PicurvAssertFileExists(memory_path, "runtime memory log should be written"));
1448 PetscCall(AssertFileContains(memory_path, "step,event,process_current_mb_max,",
1449 "runtime memory log should be a CSV with its header"));
1450 PetscCall(AssertFileContains(memory_path, "\n1,Step,",
1451 "runtime memory log should contain a step row"));
1452 PetscCall(AssertFileContains(memory_path, "\n1,Final,",
1453 "runtime memory log should contain a final row"));
1454 PetscCall(AssertFileContains(memory_path, ",Complete,",
1455 "runtime memory log should record final reason"));
1456
1457 simCtx.runtimeMemoryLogEnabled = PETSC_FALSE;
1458 PetscCall(PicurvAssertBool((PetscBool)(remove(memory_path) == 0), "enabled runtime memory log should be removable"));
1459 PetscCall(RuntimeMemoryLogSample(&simCtx, 2, "Step", "-"));
1460 PetscCall(PicurvAssertBool((PetscBool)(access(memory_path, F_OK) != 0),
1461 "disabled runtime memory log should not create a file"));
1462 PetscCall(PicurvRemoveTempDir(tmpdir));
1463 PetscFunctionReturn(0);
1464}
1465
1466/**
1467 * @brief The run's first open of a CSV record is found by path, whenever it falls: a step-0
1468 * write survives a later open on a fresh run, and a continuation is marked once, at its
1469 * first write, even when that is not in step StartStep + 1.
1470 */
1471static PetscErrorCode TestRunCsvFirstOpenIsTrackedPerRun(void)
1472{
1473 SimCtx *simCtx = NULL;
1474 char tmpdir[PETSC_MAX_PATH_LEN], path[PETSC_MAX_PATH_LEN];
1475 FILE *f = NULL;
1476
1477 PetscFunctionBeginUser;
1478 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1479 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/history.csv", tmpdir));
1480
1481 PetscCall(PetscCalloc1(1, &simCtx));
1482 for (PetscInt step = 0; step < 2; ++step) {
1483 PetscCall(PicurvOpenRunCsv(simCtx, tmpdir, "history.csv", "step,value", PICURV_CSV_TRUNCATE_ON_FRESH, PETSC_TRUE, &f));
1484 fprintf(f, "%d,fresh\n", (int)step);
1485 fclose(f);
1486 }
1487 PetscCall(AssertFileContains(path, "step,value\n0,fresh\n1,fresh\n", "a later open must not truncate the step-0 rows"));
1488 PetscCall(PetscFree(simCtx));
1489
1490 PetscCall(PetscCalloc1(1, &simCtx));
1491 simCtx->continueMode = PETSC_TRUE;
1492 simCtx->StartStep = 10;
1493 for (PetscInt step = 15; step <= 20; step += 5) {
1494 PetscCall(PicurvOpenRunCsv(simCtx, tmpdir, "history.csv", "step,value", PICURV_CSV_TRUNCATE_ON_FRESH, PETSC_TRUE, &f));
1495 fprintf(f, "%d,continued\n", (int)step);
1496 fclose(f);
1497 }
1498 PetscCall(AssertFileContains(path, "1,fresh\n# Continuation from step 10\n15,continued\n20,continued\n",
1499 "a continuation is marked once, at its first write"));
1500 PetscCall(PetscFree(simCtx));
1501 PetscCall(PicurvRemoveTempDir(tmpdir));
1502 PetscFunctionReturn(0);
1503}
1504
1505/**
1506 * @brief Verifies -solution_convergence_enabled=false suppresses the convergence writer.
1507 */
1508static PetscErrorCode TestSolutionConvergenceDisabled(void)
1509{
1510 SimCtx *simCtx = NULL;
1511 UserCtx *user = NULL;
1512 char tmpdir[PETSC_MAX_PATH_LEN];
1513 char log_path[PETSC_MAX_PATH_LEN];
1514 PetscBool exists = PETSC_FALSE;
1515
1516 PetscFunctionBeginUser;
1517 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1518 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1519 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1520 simCtx->solutionConvergenceEnabled = PETSC_FALSE;
1521
1522 PetscCall(InitializeSolutionConvergenceState(simCtx));
1523 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1524 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1525 PetscCall(PetscTestFile(log_path, 'r', &exists));
1526 PetscCall(PicurvAssertBool((PetscBool)!exists,
1527 "disabled solution convergence must not create a log"));
1528
1529 PetscCall(PicurvRemoveTempDir(tmpdir));
1530 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1531 PetscFunctionReturn(0);
1532}
1533
1534/**
1535 * @brief Tests steady solution-convergence log output, IBM masking, and gauge-invariant pressure drift.
1536 */
1537static PetscErrorCode TestSolutionConvergenceSteadyLogging(void)
1538{
1539 SimCtx *simCtx = NULL;
1540 UserCtx *user = NULL;
1541 char tmpdir[PETSC_MAX_PATH_LEN];
1542 char log_path[PETSC_MAX_PATH_LEN];
1543 char header[4096];
1544 char row1[4096];
1545 char row2[4096];
1546 char mode[128];
1547 Cmpnts ***ucat = NULL;
1548 PetscReal ***nvert = NULL;
1549 PetscReal mean_speed = NAN;
1550 PetscReal mean_speed_ref = NAN;
1551 PetscReal mean_speed_abs = NAN;
1552 PetscReal p_abs = NAN;
1553 PetscInt has_reference_1 = 0;
1554 PetscInt has_reference_2 = 0;
1555
1556 PetscFunctionBeginUser;
1557 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1558 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1559 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1561
1562 PetscCall(InitializeSolutionConvergenceState(simCtx));
1563
1564 simCtx->step = 1;
1565 simCtx->ti = 0.1;
1566 PetscCall(SetUniformVelocityField(user, user->Ucat, 1.0, 0.0, 0.0));
1567 PetscCall(SetUniformScalarField(user, user->P, 11.0));
1568 PetscCall(DMDAVecGetArray(user->da, user->Nvert, &nvert));
1569 nvert[1][1][1] = 1.0;
1570 PetscCall(DMDAVecRestoreArray(user->da, user->Nvert, &nvert));
1571 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
1572 ucat[1][1][1].x = 999.0;
1573 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
1574 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1575
1576 simCtx->step = 2;
1577 simCtx->ti = 0.2;
1578 PetscCall(SetUniformVelocityField(user, user->Ucat, 1.0, 0.0, 0.0));
1579 PetscCall(SetUniformVelocityField(user, user->Ucat_o, 0.5, 0.0, 0.0));
1580 PetscCall(SetUniformScalarField(user, user->P, 11.0));
1581 PetscCall(SetUniformScalarField(user, user->P_o, 7.0));
1582 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &ucat));
1583 ucat[1][1][1].x = 999.0;
1584 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &ucat));
1585 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1586
1587 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1588 PetscCall(PicurvAssertFileExists(log_path, "steady solution-convergence logging should write the log"));
1589 PetscCall(ReadLogHeaderAndRow(log_path, 1, header, sizeof(header), row1, sizeof(row1)));
1590 PetscCall(ReadLogHeaderAndRow(log_path, 2, header, sizeof(header), row2, sizeof(row2)));
1591 PetscCall(LogGetColumnText(header, row1, "mode", mode, sizeof(mode)));
1592 PetscCall(LogGetColumnInt(header, row1, "ref", &has_reference_1));
1593 PetscCall(LogGetColumnInt(header, row2, "ref", &has_reference_2));
1594 PetscCall(LogGetColumnReal(header, row2, "mean_speed", &mean_speed));
1595 PetscCall(LogGetColumnReal(header, row2, "spd_ref", &mean_speed_ref));
1596 PetscCall(LogGetColumnReal(header, row2, "spd_abs", &mean_speed_abs));
1597 PetscCall(LogGetColumnReal(header, row2, "p_abs_l2", &p_abs));
1598
1599 PetscCall(PicurvAssertBool((PetscBool)(strcmp(mode, "steady_deterministic") == 0),
1600 "steady solution convergence row should record the mode name"));
1601 PetscCall(PicurvAssertIntEqual(0, has_reference_1,
1602 "the first steady solution-convergence row should be a warmup row"));
1603 PetscCall(PicurvAssertIntEqual(1, has_reference_2,
1604 "steady solution convergence should compare against the previous solved step"));
1605 PetscCall(PicurvAssertRealNear(1.0, mean_speed, 1.0e-12,
1606 "steady solution convergence should mask IBM-marked solid cells"));
1607 PetscCall(PicurvAssertRealNear(0.5, mean_speed_ref, 1.0e-12,
1608 "steady solution convergence should report the previous-step mean speed"));
1609 PetscCall(PicurvAssertRealNear(0.5, mean_speed_abs, 1.0e-12,
1610 "steady solution convergence should report mean-speed drift"));
1611 PetscCall(PicurvAssertRealNear(0.0, p_abs, 1.0e-12,
1612 "steady solution convergence pressure drift should be gauge invariant"));
1613
1614 PetscCall(PicurvRemoveTempDir(tmpdir));
1615 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1616 PetscFunctionReturn(0);
1617}
1618
1619/**
1620 * @brief Tests periodic solution-convergence warmup and phase-aligned reference reuse.
1621 */
1623{
1624 SimCtx *simCtx = NULL;
1625 UserCtx *user = NULL;
1626 char tmpdir[PETSC_MAX_PATH_LEN];
1627 char log_path[PETSC_MAX_PATH_LEN];
1628 char header[4096];
1629 char row1[4096];
1630 char row2[4096];
1631 char row3[4096];
1632 PetscInt has_reference_1 = 0;
1633 PetscInt has_reference_2 = 0;
1634 PetscInt has_reference_3 = 0;
1635 PetscInt phase_step_1 = -1;
1636 PetscInt phase_step_2 = -1;
1637 PetscInt phase_step_3 = -1;
1638 PetscReal mean_speed_ref_2 = NAN;
1639 PetscReal mean_speed_abs_2 = NAN;
1640
1641 PetscFunctionBeginUser;
1642 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1643 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1644 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1647
1648 PetscCall(InitializeSolutionConvergenceState(simCtx));
1649
1650 simCtx->step = 1;
1651 simCtx->ti = 0.1;
1652 PetscCall(SetUniformVelocityField(user, user->Ucat, 1.0, 0.0, 0.0));
1653 PetscCall(SetUniformScalarField(user, user->P, 2.0));
1654 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1655
1656 simCtx->step = 2;
1657 simCtx->ti = 0.2;
1658 PetscCall(SetUniformVelocityField(user, user->Ucat, 2.0, 0.0, 0.0));
1659 PetscCall(SetUniformScalarField(user, user->P, 5.0));
1660 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1661
1662 simCtx->step = 3;
1663 simCtx->ti = 0.3;
1664 PetscCall(SetUniformVelocityField(user, user->Ucat, 1.25, 0.0, 0.0));
1665 PetscCall(SetUniformScalarField(user, user->P, 9.0));
1666 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1667
1668 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1669 PetscCall(PicurvAssertFileExists(log_path, "periodic solution-convergence logging should write the log"));
1670 PetscCall(ReadLogHeaderAndRow(log_path, 1, header, sizeof(header), row1, sizeof(row1)));
1671 PetscCall(ReadLogHeaderAndRow(log_path, 2, header, sizeof(header), row2, sizeof(row2)));
1672 PetscCall(ReadLogHeaderAndRow(log_path, 3, header, sizeof(header), row3, sizeof(row3)));
1673 PetscCall(LogGetColumnInt(header, row1, "ref", &has_reference_1));
1674 PetscCall(LogGetColumnInt(header, row2, "ref", &has_reference_2));
1675 PetscCall(LogGetColumnInt(header, row3, "ref", &has_reference_3));
1676 PetscCall(LogGetColumnInt(header, row1, "ph", &phase_step_1));
1677 PetscCall(LogGetColumnInt(header, row2, "ph", &phase_step_2));
1678 PetscCall(LogGetColumnInt(header, row3, "ph", &phase_step_3));
1679 PetscCall(LogGetColumnReal(header, row3, "spd_ref", &mean_speed_ref_2));
1680 PetscCall(LogGetColumnReal(header, row3, "spd_abs", &mean_speed_abs_2));
1681
1682 PetscCall(PicurvAssertIntEqual(0, has_reference_1,
1683 "the first periodic phase visit should log warmup without a reference"));
1684 PetscCall(PicurvAssertIntEqual(0, has_reference_2,
1685 "the first periodic cycle should fully warm up before comparisons begin"));
1686 PetscCall(PicurvAssertIntEqual(1, has_reference_3,
1687 "the repeated periodic phase visit should compare against the stored reference"));
1688 PetscCall(PicurvAssertIntEqual(1, phase_step_1,
1689 "periodic solution convergence should log the current phase slot"));
1690 PetscCall(PicurvAssertIntEqual(0, phase_step_2,
1691 "periodic solution convergence should log distinct phase slots during warmup"));
1692 PetscCall(PicurvAssertIntEqual(1, phase_step_3,
1693 "periodic solution convergence should reuse the same phase slot on later cycles"));
1694 PetscCall(PicurvAssertRealNear(1.0, mean_speed_ref_2, 1.0e-12,
1695 "periodic solution convergence should report the stored phase-aligned reference"));
1696 PetscCall(PicurvAssertRealNear(0.25, mean_speed_abs_2, 1.0e-12,
1697 "periodic solution convergence should report the phase-aligned drift"));
1698
1699 PetscCall(PicurvRemoveTempDir(tmpdir));
1700 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1701 PetscFunctionReturn(0);
1702}
1703
1704/**
1705 * @brief Tests statistical solution-convergence sliding-window metrics.
1706 */
1708{
1709 SimCtx *simCtx = NULL;
1710 UserCtx *user = NULL;
1711 char tmpdir[PETSC_MAX_PATH_LEN];
1712 char log_path[PETSC_MAX_PATH_LEN];
1713 char header[4096];
1714 char row[4096];
1715 PetscReal mean_speed_window = NAN;
1716 PetscReal mean_speed_window_prev = NAN;
1717 PetscReal mean_speed_window_abs = NAN;
1718 PetscReal mean_speed_rms_window = NAN;
1719 PetscReal mean_ke_window = NAN;
1720 PetscReal mean_ke_window_prev = NAN;
1721 PetscReal mean_ke_window_abs = NAN;
1722 PetscReal mean_ke_rms_window_abs = NAN;
1723 PetscInt has_reference = 0;
1724 const PetscReal speed_samples[4] = {1.0, 3.0, 2.0, 4.0};
1725
1726 PetscFunctionBeginUser;
1727 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1728 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1729 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1732
1733 PetscCall(InitializeSolutionConvergenceState(simCtx));
1734 for (PetscInt step = 0; step < 4; ++step) {
1735 simCtx->step = step + 1;
1736 simCtx->ti = 0.1 * (PetscReal)(step + 1);
1737 PetscCall(SetUniformVelocityField(user, user->Ucat, speed_samples[step], 0.0, 0.0));
1738 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1739 }
1740
1741 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1742 PetscCall(PicurvAssertFileExists(log_path, "statistical solution-convergence logging should write the log"));
1743 PetscCall(ReadLogHeaderAndRow(log_path, 4, header, sizeof(header), row, sizeof(row)));
1744 PetscCall(LogGetColumnInt(header, row, "ref", &has_reference));
1745 PetscCall(LogGetColumnReal(header, row, "spd_win", &mean_speed_window));
1746 PetscCall(LogGetColumnReal(header, row, "spd_win_prev", &mean_speed_window_prev));
1747 PetscCall(LogGetColumnReal(header, row, "spd_win_abs", &mean_speed_window_abs));
1748 PetscCall(LogGetColumnReal(header, row, "spd_rms_win", &mean_speed_rms_window));
1749 PetscCall(LogGetColumnReal(header, row, "ke_win", &mean_ke_window));
1750 PetscCall(LogGetColumnReal(header, row, "ke_win_prev", &mean_ke_window_prev));
1751 PetscCall(LogGetColumnReal(header, row, "ke_win_abs", &mean_ke_window_abs));
1752 PetscCall(LogGetColumnReal(header, row, "ke_rms_abs", &mean_ke_rms_window_abs));
1753
1754 PetscCall(PicurvAssertIntEqual(1, has_reference,
1755 "statistical solution convergence should emit adjacent-window drift once two windows exist"));
1756 PetscCall(PicurvAssertRealNear(3.0, mean_speed_window, 1.0e-12,
1757 "statistical solution convergence should report the current mean-speed window"));
1758 PetscCall(PicurvAssertRealNear(2.0, mean_speed_window_prev, 1.0e-12,
1759 "statistical solution convergence should report the previous mean-speed window"));
1760 PetscCall(PicurvAssertRealNear(1.0, mean_speed_window_abs, 1.0e-12,
1761 "statistical solution convergence should report mean-speed window drift"));
1762 PetscCall(PicurvAssertRealNear(1.0, mean_speed_rms_window, 1.0e-12,
1763 "statistical solution convergence should report current mean-speed RMS"));
1764 PetscCall(PicurvAssertRealNear(5.0, mean_ke_window, 1.0e-12,
1765 "statistical solution convergence should report the current kinetic-energy window"));
1766 PetscCall(PicurvAssertRealNear(2.5, mean_ke_window_prev, 1.0e-12,
1767 "statistical solution convergence should report the previous kinetic-energy window"));
1768 PetscCall(PicurvAssertRealNear(2.5, mean_ke_window_abs, 1.0e-12,
1769 "statistical solution convergence should report kinetic-energy window drift"));
1770 PetscCall(PicurvAssertRealNear(1.0, mean_ke_rms_window_abs, 1.0e-12,
1771 "statistical solution convergence should report RMS kinetic-energy drift"));
1772
1773 PetscCall(PicurvRemoveTempDir(tmpdir));
1774 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1775 PetscFunctionReturn(0);
1776}
1777/**
1778 * @brief Regression test: convergence observables ignore the ghost layers of a walled box.
1779 *
1780 * Interior cells carry speed 1 and every ghost layer carries speed 100, as a
1781 * boundary-condition image may. The volume-averaged mean speed must be exactly 1: the
1782 * loops once ran over the ghost layers too, which put wall images into every mean.
1783 */
1785{
1786 SimCtx *simCtx = NULL;
1787 UserCtx *user = NULL;
1788 char tmpdir[PETSC_MAX_PATH_LEN];
1789 char log_path[PETSC_MAX_PATH_LEN];
1790 char header[4096];
1791 char row[4096];
1792 PetscReal mean_speed = NAN;
1793 Cmpnts ***arr = NULL;
1794
1795 PetscFunctionBeginUser;
1796 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 6, 6, 6));
1797 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1798 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1799 PetscCall(PicurvPopulateIdentityMetrics(user));
1800 PetscCall(DMDAVecGetArray(user->fda, user->Ucat, &arr));
1801 for (PetscInt k = user->info.zs; k < user->info.zs + user->info.zm; ++k) {
1802 for (PetscInt j = user->info.ys; j < user->info.ys + user->info.ym; ++j) {
1803 for (PetscInt i = user->info.xs; i < user->info.xs + user->info.xm; ++i) {
1804 const PetscBool ghost = (PetscBool)(i == 0 || j == 0 || k == 0 || i == user->info.mx - 1 ||
1805 j == user->info.my - 1 || k == user->info.mz - 1);
1806 arr[k][j][i].x = 0.0;
1807 arr[k][j][i].y = 0.0;
1808 arr[k][j][i].z = ghost ? 100.0 : 1.0;
1809 }
1810 }
1811 }
1812 PetscCall(DMDAVecRestoreArray(user->fda, user->Ucat, &arr));
1813
1815 PetscCall(InitializeSolutionConvergenceState(simCtx));
1816 simCtx->step = 1;
1817 simCtx->ti = 0.1;
1818 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1819
1820 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1821 PetscCall(ReadLogHeaderAndRow(log_path, 1, header, sizeof(header), row, sizeof(row)));
1822 PetscCall(LogGetColumnReal(header, row, "mean_speed", &mean_speed));
1823 PetscCall(PicurvAssertRealNear(1.0, mean_speed, 1.0e-12,
1824 "mean speed must average physical cells only, not wall ghost images"));
1825
1826 PetscCall(PicurvRemoveTempDir(tmpdir));
1827 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1828 PetscFunctionReturn(0);
1829}
1830/**
1831 * @brief Regression test: volume-averaged mean KE of a sinusoidal field in a fully periodic domain.
1832 *
1833 * For u=0, v=0.1*sin(2πz), w=1 on a uniform [0,1]³ grid the exact continuous mean KE is 0.5025.
1834 * With identity metrics (Aj=1) the discrete mean over the N physical cells also equals 0.5025
1835 * for any N >= 3, because Σ_{k=0}^{N-1} sin²(2πk/N) = N/2.
1836 *
1837 * The physical cells are 1..mz-2. The ghost layers at 0 and mz-1 hold periodic copies of the
1838 * opposite cells, so counting either one weights a cell twice. The loops once counted the
1839 * upper ghost, and later still counted the lower one; this test requires both excluded.
1840 */
1841static PetscErrorCode TestPeriodicSinusoidalMeanKE(void)
1842{
1843 const PetscInt km_values[] = {8, 16};
1844 const PetscInt n_cases = (PetscInt)(sizeof(km_values) / sizeof(km_values[0]));
1845
1846 PetscFunctionBeginUser;
1847 for (PetscInt t = 0; t < n_cases; ++t) {
1848 const PetscInt km = km_values[t];
1849 SimCtx *simCtx = NULL;
1850 UserCtx *user = NULL;
1851 char tmpdir[PETSC_MAX_PATH_LEN];
1852 char log_path[PETSC_MAX_PATH_LEN];
1853 char header[4096];
1854 char row[4096];
1855 PetscReal mean_ke = NAN;
1856
1857 PetscCall(PicurvCreateMinimalContextsWithPeriodicity(&simCtx, &user, km, km, km,
1858 PETSC_TRUE, PETSC_TRUE, PETSC_TRUE));
1859 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
1860 PetscCall(PetscStrncpy(simCtx->log_dir, tmpdir, sizeof(simCtx->log_dir)));
1861 PetscCall(PicurvPopulateIdentityMetrics(user));
1862 PetscCall(SetSinusoidalVZField(user, user->Ucat, 0.1, 1.0));
1863
1866 PetscCall(InitializeSolutionConvergenceState(simCtx));
1867
1868 simCtx->step = 1;
1869 simCtx->ti = 0.1;
1870 PetscCall(LOG_SOLUTION_CONVERGENCE(simCtx));
1871
1872 PetscCall(PetscSNPrintf(log_path, sizeof(log_path), "%s/solution_convergence.csv", simCtx->log_dir));
1873 PetscCall(ReadLogHeaderAndRow(log_path, 1, header, sizeof(header), row, sizeof(row)));
1874 PetscCall(LogGetColumnReal(header, row, "mean_ke", &mean_ke));
1875 PetscCall(PicurvAssertRealNear(0.5025, mean_ke, 1.0e-10,
1876 "periodic sinusoidal field mean KE must equal 0.5025 (no duplicate endpoint)"));
1877
1878 PetscCall(PicurvRemoveTempDir(tmpdir));
1879 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1880 }
1881 PetscFunctionReturn(0);
1882}
1883
1884/**
1885 * @brief Runs the unit-logging PETSc test binary.
1886 */
1887
1888int main(int argc, char **argv)
1889{
1890 PetscErrorCode ierr;
1891 const PicurvTestCase cases[] = {
1892 {"string-conversion-helpers", TestStringConversionHelpers},
1893 {"get-log-level-from-environment", TestGetLogLevelFromEnvironment},
1894 {"allowed-functions-filter", TestAllowedFunctionsFilter},
1895 {"particle-console-snapshot-cadence", TestParticleConsoleSnapshotCadence},
1896 {"statistics-console-snapshot-cadence", TestStatisticsConsoleSnapshotCadence},
1897 {"logging-file-parsing-and-formatting-helpers", TestLoggingFileParsingAndFormattingHelpers},
1898 {"logging-continuity-and-field-diagnostics", TestLoggingContinuityAndFieldDiagnostics},
1899 {"interpolation-error-logging", TestInterpolationErrorLogging},
1900 {"les-diagnostics-constant-model-has-no-measured-coefficient", TestLESDiagnosticsConstantModelHasNoMeasuredCoefficient},
1901 {"scatter-metrics-logging", TestScatterMetricsLogging},
1902 {"particle-field-table-logging", TestParticleFieldTableLogging},
1903 {"particle-console-snapshot-logging", TestParticleConsoleSnapshotLogging},
1904 {"statistics-console-snapshot-logging", TestStatisticsConsoleSnapshotLogging},
1905 {"console-cadence-does-not-change-accumulation", TestConsoleCadenceDoesNotChangeAccumulation},
1906 {"particle-metrics-logging", TestParticleMetricsLogging},
1907 {"search-metrics-logging", TestSearchMetricsLogging},
1908 {"field-anatomy-logging", TestFieldAnatomyLogging},
1909 {"profiling-lifecycle-helpers", TestProfilingLifecycleHelpers},
1910 {"runtime-memory-log-helpers", TestRuntimeMemoryLogHelpers},
1911 {"run-csv-first-open-is-tracked-per-run", TestRunCsvFirstOpenIsTrackedPerRun},
1912 {"solution-convergence-disabled", TestSolutionConvergenceDisabled},
1913 {"solution-convergence-steady-logging", TestSolutionConvergenceSteadyLogging},
1914 {"solution-convergence-periodic-logging", TestSolutionConvergencePeriodicLogging},
1915 {"solution-convergence-statistical-logging", TestSolutionConvergenceStatisticalLogging},
1916 {"periodic-sinusoidal-mean-ke", TestPeriodicSinusoidalMeanKE},
1917 {"solution-convergence-means-exclude-ghost-layers", TestSolutionConvergenceMeansExcludeGhostLayers},
1918 };
1919
1920 (void)setenv("LOG_LEVEL", "INFO", 1);
1921
1922 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv logging tests");
1923 if (ierr) {
1924 return (int)ierr;
1925 }
1926
1927 ierr = PicurvRunTests("unit-logging", cases, sizeof(cases) / sizeof(cases[0]));
1928 if (ierr) {
1929 PetscFinalize();
1930 return (int)ierr;
1931 }
1932
1933 set_allowed_functions(NULL, 0);
1934
1935 ierr = PetscFinalize();
1936 return (int)ierr;
1937}
PetscErrorCode AnalyticalFieldDestroy(SimCtx *simCtx)
Release what AnalyticalSolutionEngine() keeps from step to step, if anything.
PetscErrorCode AnalyticalSolutionEngine(SimCtx *simCtx)
Sets the Eulerian fields from the case's source (-ic_source_*) at the step's time.
PetscErrorCode SetAnalyticalSolutionForParticles(Vec tempVec, SimCtx *simCtx)
Evaluates the analytical velocity at particle positions.
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
FieldId
Compile-time identity for a catalogued Eulerian field.
@ FIELD_ID_UCAT
@ FIELD_ID_COORDINATES
@ FIELD_ID_UCONT
@ FIELD_ID_INVALID
@ FIELD_ID_P
PetscErrorCode ScatterAllParticleFieldsToEulerFields(UserCtx *user)
Scatters a predefined set of particle fields to their corresponding Eulerian fields.
PetscErrorCode LogLESDiagnostics(UserCtx *user)
Appends one row of LES coefficient statistics to the run's log directory.
Definition les.c:991
Logging utilities and macros for PETSc-based applications.
PetscErrorCode LOG_FIELD_MIN_MAX(UserCtx *user, FieldId field_id)
Computes and logs the local and global min/max values of a 3-component vector field.
Definition logging.c:2501
void set_allowed_functions(const char **functionList, int count)
Sets the global list of function names that are allowed to log.
Definition logging.c:176
PetscErrorCode PicurvOpenRunCsv(SimCtx *simCtx, const char *dir, const char *filename, const char *header, PicurvCsvLifecycle lifecycle, PetscBool required, FILE **file)
Opens one of the run's CSV records (diagnostics, solver history, profiling) for writing.
Definition logging.c:3552
PetscBool ShouldEmitPeriodicStatisticsConsoleSnapshot(const struct SimCtx *simCtx, PetscInt completed_step)
Reports whether a completed step falls on the console snapshot cadence.
@ PICURV_CSV_TRUNCATE_ON_FRESH
A fresh run's first write empties the file; a continued run appends.
Definition logging.h:1146
const char * BCHandlerTypeToString(BCHandlerType handler_type)
Converts a BCHandlerType enum to its string representation.
Definition logging.c:888
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
PetscErrorCode DualMonitorDestroy(void **ctx)
Destroys the DualMonitorCtx.
Definition logging.c:927
PetscBool IsStatisticsConsoleSnapshotEnabled(const struct SimCtx *simCtx)
Reports whether the periodic statistics console snapshot is enabled.
PetscErrorCode LOG_INTERPOLATION_ERROR(UserCtx *user)
Logs the interpolation error between the analytical and computed solutions.
Definition logging.c:3024
PetscBool ShouldEmitPeriodicParticleConsoleSnapshot(const SimCtx *simCtx, PetscInt completed_step)
Returns whether a particle console snapshot should be emitted for the completed timestep.
Definition logging.c:501
const char * BCFaceToString(BCFace face)
Returns the canonical log token for a boundary-face enum value.
Definition logging.c:640
PetscErrorCode FreeAllowedFunctions(char **funcs, PetscInt n)
Free an array previously returned by LoadAllowedFunctionsFromFile().
Definition logging.c:619
PetscBool IsParticleConsoleSnapshotEnabled(const SimCtx *simCtx)
Returns whether periodic particle console snapshots are enabled.
Definition logging.c:484
PetscErrorCode print_log_level(void)
Prints the current logging level to the console.
Definition logging.c:138
#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
PetscErrorCode EmitParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, PetscInt step)
Emits one particle console snapshot into the main solver log.
Definition logging.c:518
void PrintProgressBar(PetscInt step, PetscInt startStep, PetscInt totalSteps, PetscReal currentTime, PetscReal seconds_per_step, PetscInt64 lost_cumulative)
Prints a progress bar to the console.
Definition logging.c:2446
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
PetscErrorCode ProfilingFinalize(SimCtx *simCtx)
Writes the end-of-run profiling summary across all ranks; collective on PETSC_COMM_WORLD.
Definition logging.c:2380
PetscErrorCode LoadAllowedFunctionsFromFile(const char filename[], char ***funcsOut, PetscInt *nOut)
Load function names from a text file.
Definition logging.c:561
PetscErrorCode EmitStatisticsConsoleSnapshot(UserCtx *user, const struct SimCtx *simCtx, PetscInt step)
Emits one console snapshot of window progress.
PetscErrorCode RuntimeMemoryLogSample(SimCtx *simCtx, PetscInt step, const char *event, const char *reason)
Append a reduced runtime memory sample to the configured memory log.
Definition logging.c:2170
PetscErrorCode ProfilingLogTimestepSummary(SimCtx *simCtx, PetscInt step)
Logs the performance summary for the current timestep and resets timers.
Definition logging.c:2100
PetscErrorCode LOG_FACE_DISTANCES(PetscReal *d)
Prints the signed distances to each face of the cell.
Definition logging.c:256
PetscErrorCode LOG_PARTICLE_FIELDS(UserCtx *user, PetscInt printInterval)
Prints particle fields in a table that automatically adjusts its column widths.
Definition logging.c:399
const char * BCTypeToString(BCType type)
Returns the canonical log token for a boundary mathematical type.
Definition logging.c:828
PetscErrorCode CalculateAdvancedParticleMetrics(UserCtx *user)
Computes advanced particle statistics and stores them in SimCtx.
Definition logging.c:3484
const char * ParticleLocationStatusToString(ParticleLocationStatus level)
A function that outputs the name of the current level in the ParticleLocation enum.
Definition logging.c:1905
PetscErrorCode LOG_SCATTER_METRICS(UserCtx *user)
Logs particle-to-grid scatter verification metrics for the prescribed scalar truth path.
Definition logging.c:3101
PetscErrorCode LOG_SOLUTION_CONVERGENCE(SimCtx *simCtx)
Logs physical solution-convergence metrics once per completed timestep.
Definition logging.c:1714
PetscErrorCode LOG_CONTINUITY_METRICS(UserCtx *user)
Logs continuity metrics for a single block to a file.
Definition logging.c:1866
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific gri...
Definition logging.c:2903
PetscErrorCode LOG_SEARCH_METRICS(UserCtx *user)
Writes compact runtime search metrics to CSV and optionally to console.
Definition logging.c:3288
PetscErrorCode ProfilingInitialize(SimCtx *simCtx)
Applies the profiling configuration from SimCtx to PICurv's PETSc log events.
Definition logging.c:2015
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
const char * LESModelToString(LESModelType LESFlag)
Returns the canonical log token for an LES model selector.
Definition logging.c:682
PetscErrorCode LOG_CELL_VERTICES(const Cell *cell, PetscMPIInt rank)
Prints the coordinates of a cell's vertices.
Definition logging.c:229
PetscErrorCode ProfilingResetTimestepCounters(void)
Starts a new per-step profiling interval.
Definition logging.c:2087
const char * MomentumSolverTypeToString(MomentumSolverType SolverFlag)
Returns the canonical log token for a momentum-solver selector.
Definition logging.c:808
FILE * file_handle
Definition logging.h:57
const char * ParticleInitializationToString(ParticleInitializationType ParticleInitialization)
Returns the canonical log token for a particle-initialization mode.
Definition logging.c:662
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
Context for a dual-purpose KSP monitor.
Definition logging.h:56
PetscErrorCode InitializeSolutionConvergenceState(SimCtx *simCtx)
Allocates any runtime storage required by solution-convergence logging.
Definition setup.c:176
Per-window PETSc accumulator storage and pointwise application.
Vec weight
Per-point valid weight.
Vec * mean
One per field, matching that field's layout.
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
Vec * m2
One per field; NULL when no second moment was requested.
Vec count
Per-point accepted sample count.
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
Independent accumulator state for one window on one block.
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
PetscInt sample_count
PicurvWindowFieldRequest fields[16]
PetscErrorCode FieldStatisticsUpdateWindows(struct SimCtx *simCtx, PetscInt step, PetscReal time)
Offers one completed state to every configured window.
PetscReal end_time
Requested end; ignored when bounded is false.
PicurvCadenceKind cadence_kind
PetscReal total_weight
PetscInt step_cadence
Used when cadence_kind is step; must be positive.
#define PICURV_WINDOW_NAME_LENGTH
Maximum stored length of a window name, including the terminator.
PetscErrorCode PicurvWindowInit(PicurvWindow *window, const PicurvWindowDefinition *definition)
Validates a definition and initializes a window to the pending state.
PetscBool want_second
Also keep the centered second moment.
PetscBool bounded
False for an open-ended window.
PetscInt field_id
Catalogued Eulerian field identity.
@ PICURV_WEIGHTING_SAMPLE
Equal weight per accepted state.
@ PICURV_CADENCE_STEP
Every n completed steps from activation.
Runtime state of one window.
The scientifically immutable definition of one window.
static PetscErrorCode TestParticleConsoleSnapshotCadence(void)
Tests periodic particle console snapshot enablement and cadence.
static PetscErrorCode SetUniformScalarField(UserCtx *user, Vec field, PetscReal value)
Fills one scalar field with a uniform constant state.
static PetscErrorCode TestFieldAnatomyLogging(void)
Tests stdout field-anatomy logging on the corrected production-like DM fixture.
static PetscErrorCode LogGetColumnText(const char *header, const char *row, const char *column_name, char *value, size_t value_len)
Extracts one comma-separated log cell as text by header name.
static PetscErrorCode InvokeParticleConsoleSnapshot(UserCtx *user, SimCtx *simCtx, void *ctx)
Adapts EmitParticleConsoleSnapshot() to the generic stdout-capture callback shape.
static void ProfiledUnselectedAggregate(void)
Profiled stand-in: an aggregate the per-step list does not select.
static PetscErrorCode TestStatisticsConsoleSnapshotLogging(void)
Tests statistics console snapshot content, and its silence when disabled.
static PetscErrorCode TestParticleConsoleSnapshotLogging(void)
Tests console snapshot logging against the public periodic-snapshot helper.
static PetscErrorCode TestStatisticsConsoleSnapshotCadence(void)
Tests periodic statistics console snapshot enablement and cadence.
static PetscErrorCode CaptureLoggingOutput(UserCtx *user, SimCtx *simCtx, CapturedLoggingFn fn, void *ctx, char *captured, size_t captured_len)
Captures stdout emitted by one logging helper into a temporary file-backed buffer.
static PetscErrorCode TestGetLogLevelFromEnvironment(void)
Tests that log level selection honors the environment variable.
int main(int argc, char **argv)
Runs the unit-logging PETSc test binary.
static PetscErrorCode TestLoggingContinuityAndFieldDiagnostics(void)
Tests continuity, min/max, and anatomy logging helpers on minimal runtime fixtures.
static PetscErrorCode AssertVecsIdentical(Vec expected, Vec actual, const char *context)
Asserts two accumulator vectors are bit-identical.
static PetscErrorCode TestPeriodicSinusoidalMeanKE(void)
Regression test: volume-averaged mean KE of a sinusoidal field in a fully periodic domain.
PetscErrorCode(* CapturedLoggingFn)(UserCtx *user, SimCtx *simCtx, void *ctx)
static PetscErrorCode TestSolutionConvergenceStatisticalLogging(void)
Tests statistical solution-convergence sliding-window metrics.
static PetscErrorCode SetUniformPressure(UserCtx *user, PetscReal value)
Sets the pressure field to a uniform value across the owned range.
static PetscErrorCode AssertFileNotContains(const char *path, const char *needle, const char *context)
Asserts that one text file does not contain an excluded substring.
static PetscErrorCode AccumulateAtConsoleCadence(SimCtx *simCtx, UserCtx *user, PicurvWindow *window, PicurvWindowStorage *storage, const PicurvWindowDefinition *definition, PetscInt console_frequency)
Drives one accumulation run at a given console cadence, in the runloop's order.
static PicurvWindowDefinition LoggingStatisticsDefinition(void)
Builds the window definition backing this suite's statistics console fixture.
static PetscErrorCode InvokeFieldAnatomyLog(UserCtx *user, SimCtx *simCtx, void *ctx)
Adapts LOG_FIELD_ANATOMY() to the generic stdout-capture callback shape.
static PetscErrorCode TestSolutionConvergenceMeansExcludeGhostLayers(void)
Regression test: convergence observables ignore the ghost layers of a walled box.
static void ProfiledEnabledHelper(void)
Profiled stand-in: a helper that profiling.helpers names.
static PetscErrorCode TestSolutionConvergencePeriodicLogging(void)
Tests periodic solution-convergence warmup and phase-aligned reference reuse.
static PetscErrorCode TestStringConversionHelpers(void)
Tests string-conversion helpers for configured enums and unknown values.
static PetscErrorCode SetSinusoidalVZField(UserCtx *user, Vec field, PetscReal v_amp, PetscReal w_const)
Fills one Cartesian velocity field with u=0, v=v_amp*sin(2π*k/km), w=w_const.
static PetscErrorCode TestLoggingFileParsingAndFormattingHelpers(void)
Tests logging-side file parsing, helper formatting, and progress utilities.
static PetscErrorCode TestAllowedFunctionsFilter(void)
Tests the function allow-list filter used by the logging layer.
static PetscErrorCode TestInterpolationErrorLogging(void)
Tests interpolation-error logging against an analytically matched particle field.
static PetscErrorCode SeedLoggingParticleFixture(SimCtx **simCtx_out, UserCtx **user_out)
Creates a small particle-bearing runtime fixture used by logging tests.
static PetscErrorCode TestScatterMetricsLogging(void)
Tests file-backed scatter metrics logging against a fully occupied constant field.
static PetscErrorCode TestParticleMetricsLogging(void)
Tests file-backed particle metrics logging after derived metrics are computed.
static PetscErrorCode TestSearchMetricsLogging(void)
Tests file-backed search metrics logging with the compact CSV contract.
static PetscErrorCode InvokeStatisticsConsoleSnapshot(UserCtx *user, SimCtx *simCtx, void *ctx)
Adapts EmitStatisticsConsoleSnapshot() to the generic stdout-capture callback shape.
static PetscErrorCode TestParticleFieldTableLogging(void)
Tests stdout particle-table logging on a production-like swarm fixture.
static void ProfiledFlowSolver(void)
Profiled stand-in: an aggregate named FlowSolver.
static PetscErrorCode TestSolutionConvergenceDisabled(void)
Verifies -solution_convergence_enabled=false suppresses the convergence writer.
static PetscErrorCode LogFindColumnIndex(const char *header, const char *column_name, PetscInt *index_out)
Returns the zero-based column index for one comma-separated header field.
static PetscErrorCode SetUniformVelocityField(UserCtx *user, Vec field, PetscReal ux, PetscReal uy, PetscReal uz)
Fills one Cartesian velocity field with a uniform constant state.
static PetscErrorCode TestRunCsvFirstOpenIsTrackedPerRun(void)
The run's first open of a CSV record is found by path, whenever it falls: a step-0 write survives a l...
static PetscErrorCode ReadLogHeaderAndRow(const char *path, PetscInt row_index, char *header, size_t header_len, char *row, size_t row_len)
Reads the column header and the requested 1-based data row from a comma-separated solution-convergenc...
static PetscErrorCode TestLESDiagnosticsConstantModelHasNoMeasuredCoefficient(void)
Tests that the constant Smagorinsky model reports its configured coefficient, not a measured one.
static PetscErrorCode AssertFileContains(const char *path, const char *needle, const char *context)
Asserts that one text file contains a required substring.
static PetscErrorCode LogGetColumnReal(const char *header, const char *row, const char *column_name, PetscReal *value_out)
Extracts one comma-separated log cell as a real by header name.
static PetscErrorCode TestSolutionConvergenceSteadyLogging(void)
Tests steady solution-convergence log output, IBM masking, and gauge-invariant pressure drift.
static PetscErrorCode TestProfilingLifecycleHelpers(void)
Tests profiling helper lifecycle logging for timestep and final-summary outputs.
static PetscErrorCode LogGetColumnInt(const char *header, const char *row, const char *column_name, PetscInt *value_out)
Extracts one comma-separated log cell as an integer by header name.
static void ProfiledDisabledHelper(void)
Profiled stand-in: a helper that profiling.helpers does not name.
static PetscErrorCode TestConsoleCadenceDoesNotChangeAccumulation(void)
Tests that the console cadence has no effect on any accumulated result.
const char * stage_name
static PetscErrorCode InvokeParticleFieldLog(UserCtx *user, SimCtx *simCtx, void *ctx)
Adapts LOG_PARTICLE_FIELDS() to the generic stdout-capture callback shape.
static PetscErrorCode TestRuntimeMemoryLogHelpers(void)
Tests runtime memory log header, step rows, final rows, and disabled mode.
PetscErrorCode PicurvMakeTempDir(char *path, size_t path_len)
Creates a unique temporary directory for one test case.
PetscErrorCode PicurvCreateMinimalContexts(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz)
Builds minimal SimCtx and UserCtx fixtures for C unit tests.
PetscErrorCode PicurvAssertRealNear(PetscReal expected, PetscReal actual, PetscReal tol, const char *context)
Asserts that two real values agree within tolerance.
PetscErrorCode PicurvDestroyMinimalContexts(SimCtx **simCtx_ptr, UserCtx **user_ptr)
Destroys minimal SimCtx/UserCtx fixtures and all owned PETSc objects.
PetscErrorCode PicurvCreateMinimalContextsWithPeriodicity(SimCtx **simCtx_out, UserCtx **user_out, PetscInt mx, PetscInt my, PetscInt mz, PetscBool x_periodic, PetscBool y_periodic, PetscBool z_periodic)
Builds minimal SimCtx and UserCtx fixtures for C unit tests with configurable periodicity.
PetscErrorCode PicurvCreateSwarmPair(UserCtx *user, PetscInt nlocal, const char *post_field_name)
Creates matched solver and post-processing swarms for tests.
PetscErrorCode PicurvRunTests(const char *suite_name, const PicurvTestCase *cases, size_t case_count)
Runs a named C test suite and prints pass/fail progress markers.
PetscErrorCode PicurvAssertFileExists(const char *path, const char *context)
Asserts that a filesystem path exists as a readable file.
PetscErrorCode PicurvAssertIntEqual(PetscInt expected, PetscInt actual, const char *context)
Asserts that two integer values are equal.
PetscErrorCode PicurvPopulateIdentityMetrics(UserCtx *user)
Populates identity metric vectors on the minimal grid fixture.
PetscErrorCode PicurvAssertBool(PetscBool value, const char *context)
Asserts that one boolean condition is true.
PetscErrorCode PicurvRemoveTempDir(const char *path)
Recursively removes a temporary directory created by PicurvMakeTempDir.
Shared declarations for the PICurv C test fixture and assertion layer.
Named test case descriptor consumed by PicurvRunTests.
PetscInt particlesPerCellMin
Fewest particles in any cell after the step.
Definition variables.h:1069
@ CONSTANT_SMAGORINSKY
Definition variables.h:585
PetscInt particlesPerCellMax
Most particles in any cell after the step.
Definition variables.h:1070
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
@ PERIODIC
Definition variables.h:325
PetscBool continueMode
Definition variables.h:935
PetscBool profilingFinalSummary
Definition variables.h:1107
PetscMPIInt rank
Definition variables.h:919
PetscInt64 searchLocatedCount
Definition variables.h:283
PetscInt statisticsConsoleOutputFreq
Definition variables.h:991
PetscInt64 searchLostCount
Definition variables.h:284
LESConfig les_config
Parameters of the LES closure selected by les.
Definition variables.h:1046
@ PARTICLE_INIT_VOLUME
Random volumetric distribution across the domain.
Definition variables.h:748
@ LOST
The search failed for a particle believed to be inside the domain.
Definition variables.h:190
@ ACTIVE_AND_LOCATED
Definition variables.h:188
@ EXITED
The particle crossed a domain-boundary face whose particle policy removes it.
Definition variables.h:192
PetscReal FluxOutSum
Definition variables.h:1016
PetscBool runtimeMemoryLogEnabled
Enable the rank-reduced runtime memory log (log_dir/Runtime_Memory.csv).
Definition variables.h:1123
PetscInt64 boundaryClampCount
Definition variables.h:290
PetscInt particlesLostLastStep
Particles removed this step because their search failed.
Definition variables.h:1057
PetscInt64 traversalStepsSum
Definition variables.h:285
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
PetscReal ren
Definition variables.h:965
PetscReal poissonSourceImbalance
Definition variables.h:1095
PetscInt64 searchPopulation
Definition variables.h:282
PetscBool solutionConvergenceEnabled
Definition variables.h:980
PetscReal dt
Definition variables.h:933
PetscInt occupiedCellCount
Definition variables.h:1068
char profilingTimestepMode[32]
Definition variables.h:1106
PetscInt np
Definition variables.h:1049
PetscBool fieldStatisticsEnabled
Definition variables.h:988
Vec Ucont
Definition variables.h:1197
PetscInt StartStep
Definition variables.h:926
@ MOMENTUM_SOLVER_EXPLICIT_RK
Definition variables.h:730
@ MOMENTUM_SOLVER_NEWTON_KRYLOV
Definition variables.h:732
PetscInt solutionConvergencePeriodSteps
Definition variables.h:982
PetscScalar x
Definition variables.h:145
PetscInt64 reSearchCount
Definition variables.h:286
PetscReal MaxDiv
Definition variables.h:1096
PetscInt64 bboxGuessFallbackCount
Definition variables.h:292
Vec Ucat_o
Definition variables.h:1204
PetscInt MaxDivx
Definition variables.h:1097
PetscInt MaxDivy
Definition variables.h:1097
char analysis_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:942
PetscInt64 bboxGuessSuccessCount
Definition variables.h:291
PetscInt MaxDivz
Definition variables.h:1097
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
char log_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:941
PetscInt MaxDivFlatArg
Definition variables.h:1097
Vec lNu_t
Definition variables.h:1259
PetscReal FluxInSum
Definition variables.h:1016
PetscInt64 maxParticlePassDepth
Definition variables.h:293
PetscInt64 maxTraversalSteps
Definition variables.h:287
PetscInt64 particlesLostCumulative
Definition variables.h:1058
PetscScalar z
Definition variables.h:145
Vec ParticleCount
Definition variables.h:1276
PetscInt diagnostics_cadence
Steps between diagnostic rows.
Definition variables.h:679
PetscReal particlesPerCellMean
Particles counted in cells divided by the cell count.
Definition variables.h:1071
PetscBool runtimeMemoryLogHasPrevious
True after the first process-memory sample.
Definition variables.h:1126
char ** profilingSelectedFuncs
Definition variables.h:1101
PetscBool diagnostics_enabled
Append per-step coefficient statistics to the run log directory.
Definition variables.h:678
PetscReal constant_cs
Fixed Cs for CONSTANT_SMAGORINSKY; unused by the dynamic model.
Definition variables.h:666
PetscInt solutionConvergenceWindowSteps
Definition variables.h:983
PetscInt nProfilingSelectedFuncs
Definition variables.h:1102
PetscInt particlesMigratedLastStep
Definition variables.h:1067
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
PetscInt particleConsoleOutputFreq
Definition variables.h:931
SearchMetricsState searchMetrics
Definition variables.h:1073
Vec lUcont
Definition variables.h:1197
PetscInt step
Definition variables.h:924
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscInt migrationPassesLastStep
Definition variables.h:1066
PetscScalar y
Definition variables.h:145
@ EXEC_MODE_SOLVER
Definition variables.h:888
PetscInt les
Active LES closure; an LESModelType value.
Definition variables.h:1041
Vec Nvert
Definition variables.h:1197
@ SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC
Definition variables.h:740
@ SOLUTION_CONVERGENCE_STATISTICAL_STEADY
Definition variables.h:741
@ SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC
Definition variables.h:739
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
char ** profilingHelpers
Helper functions whose timers are enabled (-profiling_helpers).
Definition variables.h:1103
PetscInt64 searchAttempts
Definition variables.h:281
ExecutionMode exec_mode
Definition variables.h:937
PetscInt64 tieBreakCount
Definition variables.h:289
PetscReal ti
Definition variables.h:925
PetscInt64 maxTraversalFailCount
Definition variables.h:288
PetscInt nProfilingHelpers
Definition variables.h:1104
VerificationFieldConfig verificationScalar
Definition variables.h:997
Cmpnts vertices[8]
Coordinates of the eight vertices of the cell.
Definition variables.h:219
PetscReal particleLoadImbalance
Definition variables.h:1072
@ BC_FACE_NEG_X
Definition variables.h:309
Defines the vertices of a single hexahedral grid cell.
Definition variables.h:218
A 3D point or vector with PetscScalar components.
Definition variables.h:144
The master context for the entire simulation.
Definition variables.h:916
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
PetscErrorCode VerificationFieldCompile(const char *text, VerificationFieldConfig *field)
Compiles a verification field's expression, in physical x, y, z and t, and enables the field.