PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
test_io.c File Reference

C unit tests for I/O helpers, parsers, and startup-banner output. More...

#include "test_support.h"
#include "checksum.h"
#include "io.h"
#include "statistics_accumulator.h"
#include "statistics_window.h"
#include "field_catalog.h"
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
Include dependency graph for test_io.c:

Go to the source code of this file.

Functions

static PetscErrorCode TestShouldWriteDataOutput (void)
 Tests cadence-based Eulerian output triggering.
 
static PetscErrorCode TestVerifyPathExistence (void)
 Tests filesystem existence checks for files and directories.
 
static PetscErrorCode TestBoundaryCheckpointsCanBeSkipped (void)
 Tests that turned-off boundary checkpoints are skipped while cadence ones are written.
 
static PetscErrorCode WriteAndReadSimulationFields (PetscBool write_mpiio, PetscBool read_mpiio)
 Writes a checkpoint and reloads its core Eulerian fields, each side optionally through PETSc's rank-0 relay (-viewer_binary_mpiio false) instead of MPI-IO.
 
static PetscErrorCode TestWriteAndReadSimulationFields (void)
 Tests writing and reloading core Eulerian field vectors through MPI-IO.
 
static PetscErrorCode TestFieldPayloadsAreTransportIndependent (void)
 Tests that payloads written through the rank-0 relay load through MPI-IO and back: -viewer_binary_mpiio changes how a file is moved, never its format.
 
static PetscErrorCode TestPostprocessorReadScalesEachLoadOnce (void)
 Tests that a dimensionalizing post-processor scales each loaded field once per load.
 
static PicurvWindowDefinition StatisticsFixtureDefinition (void)
 Builds the statistics fixture: one Ucat/P window with a second moment.
 
static PetscErrorCode AttachStatisticsFixture (SimCtx *simCtx, UserCtx *user, PicurvWindow *window, PicurvWindowStorage *storage, const PicurvWindowDefinition *definition)
 Attaches one accumulating window to a fixture context and primes it with samples.
 
static PetscErrorCode DetachStatisticsFixture (SimCtx *simCtx, UserCtx *user, PicurvWindowStorage *storage)
 Detaches the statistics fixture without disturbing the shared teardown.
 
static PetscErrorCode WriteCompletedStatisticsWindow (SimCtx *simCtx, UserCtx *user, PicurvWindow *window, PicurvWindowStorage *storage, const PicurvWindowDefinition *definition)
 Rewrites the bundle holding a window that closed well before the checkpoint time.
 
static PetscErrorCode TestCheckpointStatisticsRoundTrip (void)
 Verifies accumulated statistics survive a checkpoint round trip unchanged.
 
static PetscErrorCode TestCheckpointStatisticsContinuationGuards (void)
 Verifies continuation refuses every state that would corrupt an average.
 
static PetscErrorCode TestCheckpointStatisticsPayloadIsValidated (void)
 A damaged statistics payload must fail bundle validation, not load silently.
 
static PetscErrorCode TestCheckpointStatisticsAbsentWhenDisabled (void)
 A run without statistics writes no statistics subtree and refuses to fake one.
 
static PetscErrorCode TestCheckpointSameStepRewriteIsRejected (void)
 Verifies a committed checkpoint step is rewritten neither silently nor inconsistently.
 
static PetscErrorCode TestCheckpointSHA256KnownVector (void)
 Verifies the dependency-free SHA-256 implementation against a standard vector.
 
static PetscErrorCode TestParsePostProcessingSettings (void)
 Tests parsing of post-processing control settings from a file.
 
static PetscErrorCode TestTrimWhitespace (void)
 Tests trimming of leading and trailing whitespace.
 
static PetscErrorCode TestBoundaryConditionStringParsers (void)
 Tests boundary-condition string parsers for face, type, and handler names.
 
static PetscErrorCode TestValidateBCHandlerForBCType (void)
 Tests validation of boundary-type and handler compatibility.
 
static PetscErrorCode TestParseScalingInformation (void)
 Tests scaling-reference parsing and derived pressure scaling.
 
static PetscErrorCode CaptureBannerOutput (SimCtx *simCtx, char *captured, size_t captured_len)
 Captures the startup banner into a temporary file-backed buffer.
 
static PetscErrorCode AssertCapturedContains (const char *captured, const char *needle, const char *message)
 Asserts that captured banner output contains one expected substring.
 
static PetscErrorCode AssertCapturedOmits (const char *captured, const char *needle, const char *message)
 Asserts that captured banner output omits one forbidden substring.
 
static PetscErrorCode TestDisplayBannerReportsStatisticsCadence (void)
 Tests that the startup banner reports statistics monitoring in every state.
 
static PetscErrorCode TestDisplayBannerTracksConditionalStartupFields (void)
 Tests conditional startup-banner fields across particle and analytical cases.
 
int main (int argc, char **argv)
 Runs the unit-io PETSc test binary.
 

Detailed Description

C unit tests for I/O helpers, parsers, and startup-banner output.

Definition in file test_io.c.

Function Documentation

◆ TestShouldWriteDataOutput()

static PetscErrorCode TestShouldWriteDataOutput ( void  )
static

Tests cadence-based Eulerian output triggering.

Definition at line 23 of file test_io.c.

24{
25 SimCtx simCtx;
26
27 PetscFunctionBeginUser;
28 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
29 simCtx.tiout = 5;
30
31 PetscCall(PicurvAssertBool((PetscBool)!ShouldWriteDataOutput(NULL, 5), "NULL SimCtx should never request output"));
32 PetscCall(PicurvAssertBool((PetscBool)!ShouldWriteDataOutput(&simCtx, 4), "non-cadence step should not trigger output"));
33 PetscCall(PicurvAssertBool(ShouldWriteDataOutput(&simCtx, 10), "cadence-aligned step should trigger output"));
34 PetscFunctionReturn(0);
35}
PetscBool ShouldWriteDataOutput(const SimCtx *simCtx, PetscInt completed_step)
Returns whether full field/restart output should be written for the.
Definition io.c:521
PetscErrorCode PicurvAssertBool(PetscBool value, const char *context)
Asserts that one boolean condition is true.
PetscInt tiout
Definition variables.h:928
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestVerifyPathExistence()

static PetscErrorCode TestVerifyPathExistence ( void  )
static

Tests filesystem existence checks for files and directories.

Definition at line 40 of file test_io.c.

41{
42 char tmpdir[PETSC_MAX_PATH_LEN];
43 char filepath[PETSC_MAX_PATH_LEN];
44 FILE *file = NULL;
45 PetscBool exists = PETSC_FALSE;
46
47 PetscFunctionBeginUser;
48 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
49 PetscCall(PetscSNPrintf(filepath, sizeof(filepath), "%s/sample.txt", tmpdir));
50
51 file = fopen(filepath, "w");
52 PetscCheck(file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to create temp file '%s'.", filepath);
53 fputs("picurv\n", file);
54 fclose(file);
55
56 PetscCall(VerifyPathExistence(tmpdir, PETSC_TRUE, PETSC_FALSE, "temp directory", &exists));
57 PetscCall(PicurvAssertBool(exists, "VerifyPathExistence should find the temp directory"));
58
59 PetscCall(VerifyPathExistence(filepath, PETSC_FALSE, PETSC_FALSE, "temp file", &exists));
60 PetscCall(PicurvAssertBool(exists, "VerifyPathExistence should find the temp file"));
61 PetscCall(PicurvRemoveTempDir(tmpdir));
62 PetscFunctionReturn(0);
63}
PetscErrorCode VerifyPathExistence(const char *path, PetscBool is_dir, PetscBool is_optional, const char *description, PetscBool *exists)
A parallel-safe helper to verify the existence of a generic file or directory path.
Definition io.c:1202
PetscErrorCode PicurvMakeTempDir(char *path, size_t path_len)
Creates a unique temporary directory for one test case.
PetscErrorCode PicurvRemoveTempDir(const char *path)
Recursively removes a temporary directory created by PicurvMakeTempDir.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestBoundaryCheckpointsCanBeSkipped()

static PetscErrorCode TestBoundaryCheckpointsCanBeSkipped ( void  )
static

Tests that turned-off boundary checkpoints are skipped while cadence ones are written.

With io.write_initial_checkpoint and io.write_final_checkpoint false, the initial, branch_start and final bundles write nothing; a cadence bundle still commits.

Definition at line 69 of file test_io.c.

70{
71 SimCtx *simCtx = NULL;
72 UserCtx *user = NULL;
73 char tmpdir[PETSC_MAX_PATH_LEN];
74 char path[PETSC_MAX_PATH_LEN];
75 PetscBool exists = PETSC_FALSE;
76 const char *skipped[] = {"initial", "branch_start", "final"};
77
78 PetscFunctionBeginUser;
79 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
80 tmpdir[0] = '\0';
81 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
82 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
83 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
84 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
85 PetscCall(PicurvPopulateIdentityMetrics(user));
86 simCtx->skipInitialCheckpoint = PETSC_TRUE;
87 simCtx->skipFinalCheckpoint = PETSC_TRUE;
88
89 for (size_t r = 0; r < sizeof(skipped) / sizeof(skipped[0]); ++r) {
90 PetscCall(WriteCheckpointBundle(simCtx, skipped[r]));
91 }
92 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/checkpoints/step_000000000001/COMMITTED", tmpdir));
93 PetscCall(PetscTestFile(path, 'r', &exists));
94 PetscCall(PicurvAssertBool((PetscBool)!exists, "turned-off boundary checkpoints write no bundle"));
95
96 PetscCall(WriteCheckpointBundle(simCtx, "cadence"));
97 PetscCall(PetscTestFile(path, 'r', &exists));
98 PetscCall(PicurvAssertBool(exists, "a cadence checkpoint is written regardless"));
99
100 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
101 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
102 PetscFunctionReturn(0);
103}
PetscErrorCode WriteCheckpointBundle(SimCtx *simCtx, const char *reason)
Write and atomically publish one complete checkpoint bundle.
Definition io.c:2501
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 PicurvDestroyMinimalContexts(SimCtx **simCtx_ptr, UserCtx **user_ptr)
Destroys minimal SimCtx/UserCtx fixtures and all owned PETSc objects.
PetscErrorCode PicurvPopulateIdentityMetrics(UserCtx *user)
Populates identity metric vectors on the minimal grid fixture.
PetscMPIInt rank
Definition variables.h:919
char output_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:940
PetscBool skipFinalCheckpoint
io.write_final_checkpoint false: no end-of-run bundle.
Definition variables.h:930
PetscBool skipInitialCheckpoint
io.write_initial_checkpoint false: no initial/branch_start bundle.
Definition variables.h:929
char restart_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:939
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteAndReadSimulationFields()

static PetscErrorCode WriteAndReadSimulationFields ( PetscBool  write_mpiio,
PetscBool  read_mpiio 
)
static

Writes a checkpoint and reloads its core Eulerian fields, each side optionally through PETSc's rank-0 relay (-viewer_binary_mpiio false) instead of MPI-IO.

Definition at line 109 of file test_io.c.

110{
111 SimCtx *simCtx = NULL;
112 UserCtx *user = NULL;
113 char tmpdir[PETSC_MAX_PATH_LEN];
114 char path[PETSC_MAX_PATH_LEN];
115 PetscBool exists = PETSC_FALSE;
116
117 PetscFunctionBeginUser;
118 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
119 tmpdir[0] = '\0';
120 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
121 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
122
123 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
124 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
125 PetscCall(VecSet(user->P, 4.5));
126 PetscCall(VecSet(user->Nvert, 0.0));
127 PetscCall(VecSet(user->Ucat, 2.0));
128 PetscCall(VecSet(user->Ucont, 3.0));
129 PetscCall(VecSet(user->Ucont_rm1, 1.25));
130 simCtx->ti = 0.35;
131 PetscCall(PicurvPopulateIdentityMetrics(user));
132
133 PetscCall(PetscOptionsSetValue(NULL, "-viewer_binary_mpiio", write_mpiio ? "true" : "false"));
134 PetscCall(WriteCheckpointBundle(simCtx, "test"));
135 PetscCall(PetscOptionsSetValue(NULL, "-viewer_binary_mpiio", read_mpiio ? "true" : "false"));
136 PetscCall(PetscSNPrintf(path, sizeof(path),
137 "%s/checkpoints/step_000000000001/checkpoint.meta", tmpdir));
138 PetscCall(PetscTestFile(path, 'r', &exists));
139 PetscCall(PicurvAssertBool(exists, "checkpoint coordinator should write checkpoint.meta"));
140 PetscCall(PetscSNPrintf(path, sizeof(path),
141 "%s/checkpoints/step_000000000001/COMMITTED", tmpdir));
142 PetscCall(PetscTestFile(path, 'r', &exists));
143 PetscCall(PicurvAssertBool(exists, "checkpoint coordinator should write COMMITTED last"));
144 PetscCall(PetscSNPrintf(path, sizeof(path),
145 "%s/checkpoints/step_000000000001/eulerian/block_0000/Ucat.dat", tmpdir));
146 PetscCall(PetscTestFile(path, 'r', &exists));
147 PetscCall(PicurvAssertBool(exists, "checkpoint should use catalogued canonical field names"));
148 PetscCall(VecZeroEntries(user->P));
149 PetscCall(VecZeroEntries(user->Ucat));
150 PetscCall(VecZeroEntries(user->Ucont));
151 PetscCall(VecZeroEntries(user->Ucont_rm1));
152 simCtx->ti = 0.0;
153
154 PetscCall(ReadSimulationFields(user, simCtx->step));
155 PetscCall(PicurvAssertVecConstant(user->P, 4.5, 1.0e-12, "ReadSimulationFields should restore P"));
156 PetscCall(PicurvAssertVecConstant(user->Ucat, 2.0, 1.0e-12, "ReadSimulationFields should restore Ucat"));
157 PetscCall(PicurvAssertVecConstant(user->Ucont, 3.0, 1.0e-12, "ReadSimulationFields should restore Ucont"));
158 PetscCall(PicurvAssertVecConstant(user->Ucont_rm1, 1.25, 1.0e-12,
159 "ReadSimulationFields should restore BDF2 history"));
160 PetscCall(PicurvAssertRealNear(0.35, simCtx->ti, 1.0e-12,
161 "checkpoint physical time should be authoritative"));
162
163 /* A payload of the wrong length is refused: the scalar P file cannot load into vector Ucat. */
164 {
165 PetscErrorCode load_ierr;
166
167 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/checkpoints/step_000000000001/eulerian/block_0000", tmpdir));
168 simCtx->current_io_directory = path;
169 PetscCall(PetscPushErrorHandler(PetscReturnErrorHandler, NULL));
170 load_ierr = ReadFieldData(user, "P", user->Ucat, "dat");
171 PetscCall(PetscPopErrorHandler());
172 simCtx->current_io_directory = NULL;
173 PetscCall(PicurvAssertIntEqual(PETSC_ERR_FILE_UNEXPECTED, load_ierr,
174 "a payload of the wrong length must be refused"));
175 }
176
177 PetscCall(PetscOptionsClearValue(NULL, "-viewer_binary_mpiio"));
178 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
179 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
180 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
181 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
182 PetscFunctionReturn(0);
183}
PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti)
Reads binary field data for velocity, pressure, and other required vectors.
Definition io.c:1387
PetscErrorCode ReadFieldData(UserCtx *user, const char *field_name, Vec field_vec, const char *ext)
Reads data for a specific field from a file into the provided vector.
Definition io.c:1248
PetscErrorCode PicurvAssertRealNear(PetscReal expected, PetscReal actual, PetscReal tol, const char *context)
Asserts that two real values agree within tolerance.
PetscErrorCode PicurvAssertVecConstant(Vec vec, PetscScalar expected, PetscReal tol, const char *context)
Asserts that a PETSc vector is spatially constant within tolerance.
PetscErrorCode PicurvAssertIntEqual(PetscInt expected, PetscInt actual, const char *context)
Asserts that two integer values are equal.
Vec Ucont
Definition variables.h:1197
char * current_io_directory
Definition variables.h:944
Vec Ucont_rm1
Definition variables.h:1207
PetscInt step
Definition variables.h:924
Vec Nvert
Definition variables.h:1197
PetscReal ti
Definition variables.h:925
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestWriteAndReadSimulationFields()

static PetscErrorCode TestWriteAndReadSimulationFields ( void  )
static

Tests writing and reloading core Eulerian field vectors through MPI-IO.

Definition at line 188 of file test_io.c.

189{
190 PetscFunctionBeginUser;
191 PetscCall(WriteAndReadSimulationFields(PETSC_TRUE, PETSC_TRUE));
192 PetscFunctionReturn(0);
193}
static PetscErrorCode WriteAndReadSimulationFields(PetscBool write_mpiio, PetscBool read_mpiio)
Writes a checkpoint and reloads its core Eulerian fields, each side optionally through PETSc's rank-0...
Definition test_io.c:109
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestFieldPayloadsAreTransportIndependent()

static PetscErrorCode TestFieldPayloadsAreTransportIndependent ( void  )
static

Tests that payloads written through the rank-0 relay load through MPI-IO and back: -viewer_binary_mpiio changes how a file is moved, never its format.

Definition at line 199 of file test_io.c.

200{
201 PetscFunctionBeginUser;
202 PetscCall(WriteAndReadSimulationFields(PETSC_FALSE, PETSC_TRUE));
203 PetscCall(WriteAndReadSimulationFields(PETSC_TRUE, PETSC_FALSE));
204 PetscFunctionReturn(0);
205}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestPostprocessorReadScalesEachLoadOnce()

static PetscErrorCode TestPostprocessorReadScalesEachLoadOnce ( void  )
static

Tests that a dimensionalizing post-processor scales each loaded field once per load.

Scaling happens as a field is read, so reading the same checkpoint twice yields the same physical values both times: a field is scaled by its own catalog dimension, never again on a later step. At L=2, U=3, rho=5 velocity scales by 3, a face flux by 12, and pressure by 45.

Definition at line 214 of file test_io.c.

215{
216 SimCtx *simCtx = NULL;
217 UserCtx *user = NULL;
218 char tmpdir[PETSC_MAX_PATH_LEN];
219
220 PetscFunctionBeginUser;
221 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
222 tmpdir[0] = '\0';
223 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
224 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
225
226 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
227 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
228 PetscCall(VecSet(user->P, 2.0));
229 PetscCall(VecSet(user->Nvert, 0.0));
230 PetscCall(VecSet(user->Ucat, 1.0));
231 PetscCall(VecSet(user->Ucont, 1.0));
232 PetscCall(VecSet(user->Ucont_rm1, 1.0));
233 PetscCall(PicurvPopulateIdentityMetrics(user));
234 PetscCall(WriteCheckpointBundle(simCtx, "test"));
235
236 PetscCall(PetscCalloc1(1, &simCtx->pps));
237 simCtx->pps->dimensionalize = PETSC_TRUE;
238 PetscCall(PetscStrncpy(simCtx->pps->source_dir, tmpdir, sizeof(simCtx->pps->source_dir)));
240 simCtx->scaling.L_ref = 2.0;
241 simCtx->scaling.U_ref = 3.0;
242 simCtx->scaling.rho_ref = 5.0;
243 simCtx->scaling.P_ref = 45.0;
244
245 for (PetscInt pass = 0; pass < 2; ++pass) {
246 PetscCall(ReadSimulationFields(user, simCtx->step));
247 PetscCall(PicurvAssertVecConstant(user->Ucat, 3.0, 1.0e-12, "loaded velocity is scaled by U once"));
248 PetscCall(PicurvAssertVecConstant(user->Ucont, 12.0, 1.0e-12, "loaded face flux is scaled by U L^2 once"));
249 PetscCall(PicurvAssertVecConstant(user->P, 90.0, 1.0e-12, "loaded pressure is scaled by rho U^2 once"));
250 }
251
252 simCtx->exec_mode = EXEC_MODE_SOLVER;
253 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
254 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
255 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
256 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
257 PetscFunctionReturn(0);
258}
PetscBool dimensionalize
Whether derived output leaves non-dimensional form, from global_operations.dimensionalize.
Definition variables.h:828
PetscReal L_ref
Definition variables.h:898
char source_dir[PETSC_MAX_PATH_LEN]
Definition variables.h:795
ScalingCtx scaling
Definition variables.h:1003
PostProcessParams * pps
Definition variables.h:1131
@ EXEC_MODE_SOLVER
Definition variables.h:888
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
PetscReal P_ref
Definition variables.h:901
ExecutionMode exec_mode
Definition variables.h:937
PetscReal rho_ref
Definition variables.h:900
PetscReal U_ref
Definition variables.h:899
Here is the call graph for this function:
Here is the caller graph for this function:

◆ StatisticsFixtureDefinition()

static PicurvWindowDefinition StatisticsFixtureDefinition ( void  )
static

Builds the statistics fixture: one Ucat/P window with a second moment.

Definition at line 261 of file test_io.c.

262{
264
265 memset(&d, 0, sizeof(d));
266 strncpy(d.name, "production", PICURV_WINDOW_NAME_LENGTH - 1);
269 d.step_cadence = 1;
270 d.field_count = 2;
271 d.fields[0].field_id = FIELD_ID_UCAT; d.fields[0].want_second = PETSC_TRUE;
272 d.fields[1].field_id = FIELD_ID_P; d.fields[1].want_second = PETSC_TRUE;
273 return d;
274}
@ FIELD_ID_UCAT
@ FIELD_ID_P
PicurvWindowFieldRequest fields[16]
PicurvCadenceKind cadence_kind
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.
PetscBool want_second
Also keep the centered second moment.
PetscInt field_id
Catalogued Eulerian field identity.
@ PICURV_WEIGHTING_SAMPLE
Equal weight per accepted state.
@ PICURV_CADENCE_STEP
Every n completed steps from activation.
The scientifically immutable definition of one window.
Here is the caller graph for this function:

◆ AttachStatisticsFixture()

static PetscErrorCode AttachStatisticsFixture ( SimCtx *  simCtx,
UserCtx *  user,
PicurvWindow *  window,
PicurvWindowStorage *  storage,
const PicurvWindowDefinition *  definition 
)
static

Attaches one accumulating window to a fixture context and primes it with samples.

Definition at line 277 of file test_io.c.

280{
281 PetscFunctionBeginUser;
282 PetscCall(PicurvWindowInit(window, definition));
283 PetscCall(PicurvWindowStorageCreate(user, definition, storage));
284 simCtx->fieldStatisticsEnabled = PETSC_TRUE;
285 simCtx->fieldStatisticsWindowCount = 1;
286 simCtx->fieldStatisticsWindows = window;
287 user->fieldStatisticsStorage = storage;
288 PetscFunctionReturn(0);
289}
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
PetscErrorCode PicurvWindowInit(PicurvWindow *window, const PicurvWindowDefinition *definition)
Validates a definition and initializes a window to the pending state.
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
PetscBool fieldStatisticsEnabled
Definition variables.h:988
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
Here is the call graph for this function:
Here is the caller graph for this function:

◆ DetachStatisticsFixture()

static PetscErrorCode DetachStatisticsFixture ( SimCtx *  simCtx,
UserCtx *  user,
PicurvWindowStorage *  storage 
)
static

Detaches the statistics fixture without disturbing the shared teardown.

Definition at line 292 of file test_io.c.

294{
295 PetscFunctionBeginUser;
296 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
297 simCtx->fieldStatisticsWindowCount = 0;
298 simCtx->fieldStatisticsWindows = NULL;
299 user->fieldStatisticsStorage = NULL;
300 PetscCall(PicurvWindowStorageDestroy(storage));
301 PetscFunctionReturn(0);
302}
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteCompletedStatisticsWindow()

static PetscErrorCode WriteCompletedStatisticsWindow ( SimCtx *  simCtx,
UserCtx *  user,
PicurvWindow *  window,
PicurvWindowStorage *  storage,
const PicurvWindowDefinition *  definition 
)
static

Rewrites the bundle holding a window that closed well before the checkpoint time.

Reproduces the shape a real run reaches when a bounded window finished and the simulation kept going: the saved state is complete, and its end sits behind the checkpoint by far more than one step.

Definition at line 311 of file test_io.c.

315{
316 PicurvWindowDefinition bounded = *definition;
317 PetscBool accepted = PETSC_FALSE;
318 PetscReal weight = 0.0;
319 char step_directory[PETSC_MAX_PATH_LEN];
320
321 PetscFunctionBeginUser;
322 bounded.bounded = PETSC_TRUE;
323 bounded.end_time = 1.0;
324 PetscCall(PicurvWindowInit(window, &bounded));
325 PetscCall(PicurvWindowOfferState(window, 0, 0.0, &accepted, &weight));
326 PetscCall(PicurvWindowOfferState(window, 1, 1.0, &accepted, &weight));
327 if (accepted) PetscCall(PicurvWindowAccumulate(user, &bounded, storage, weight));
328 PetscCall(PicurvAssertBool((PetscBool)(window->state == PICURV_WINDOW_COMPLETE),
329 "the fixture window reaches its bounded end"));
330
331 /* The run continued well past the window's end before this checkpoint. */
332 simCtx->ti = 5.0;
333 PetscCall(PetscSNPrintf(step_directory, sizeof(step_directory),
334 "%s/checkpoints/step_000000000001", simCtx->output_dir));
335 if (simCtx->rank == 0) PetscCall(PetscRMTree(step_directory));
336 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
337 PetscCall(WriteCheckpointBundle(simCtx, "test"));
338 PetscFunctionReturn(0);
339}
PetscErrorCode PicurvWindowAccumulate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage, PetscReal weight)
Applies one accepted completed state to a window's accumulators.
PicurvWindowState state
PetscReal end_time
Requested end; ignored when bounded is false.
@ PICURV_WINDOW_COMPLETE
Bounded end reached; accepts nothing further.
PetscErrorCode PicurvWindowOfferState(PicurvWindow *window, PetscInt step, PetscReal time, PetscBool *accepted, PetscReal *weight)
Offers one completed state to a window and reports the decision.
PetscBool bounded
False for an open-ended window.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointStatisticsRoundTrip()

static PetscErrorCode TestCheckpointStatisticsRoundTrip ( void  )
static

Verifies accumulated statistics survive a checkpoint round trip unchanged.

Both halves of the state matter and are checked separately: the per-point accumulator vectors, and the window's scalar bookkeeping. Restoring only the vectors would silently resume with a broken schedule, and restoring only the scalars would report a sample count the fields do not support.

Definition at line 349 of file test_io.c.

350{
351 SimCtx *simCtx = NULL;
352 UserCtx *user = NULL;
353 PicurvWindow window;
354 PicurvWindowStorage storage;
356 char tmpdir[PETSC_MAX_PATH_LEN];
357 char path[PETSC_MAX_PATH_LEN];
358 PetscBool exists = PETSC_FALSE;
359 PetscInt payload_count = 0;
360 Vec *reference = NULL;
361
362 PetscFunctionBeginUser;
363 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
364 tmpdir[0] = '\0';
365 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
366 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
367 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
368 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
369 PetscCall(PicurvPopulateIdentityMetrics(user));
370 PetscCall(VecSet(user->Nvert, 0.0));
371 PetscCall(AttachStatisticsFixture(simCtx, user, &window, &storage, &definition));
372
373 /* Three accepted states at unit weight: P takes 1, 2 and 6, so its per-point
374 * mean is 3 and its centered second moment is 14. */
375 {
376 const PetscReal scalars[3] = {1.0, 2.0, 6.0};
377
378 for (PetscInt s = 0; s < 3; ++s) {
379 PetscBool accepted = PETSC_FALSE;
380 PetscReal weight = 0.0;
381
382 PetscCall(VecSet(user->P, scalars[s]));
383 PetscCall(VecSet(user->Ucat, scalars[s]));
384 PetscCall(PicurvWindowOfferState(&window, s, (PetscReal)s, &accepted, &weight));
385 if (accepted) PetscCall(PicurvWindowAccumulate(user, &definition, &storage, weight));
386 }
387 }
388 PetscCall(PicurvAssertIntEqual(2, window.sample_count, "the anchoring state is not itself a sample"));
389
390 PetscCall(WriteCheckpointBundle(simCtx, "test"));
391 PetscCall(PetscSNPrintf(path, sizeof(path),
392 "%s/checkpoints/step_000000000001/statistics/window_0000/block_0000/P_mean.dat",
393 tmpdir));
394 PetscCall(PetscTestFile(path, 'r', &exists));
395 PetscCall(PicurvAssertBool(exists, "statistics payloads use their enumerated names"));
396 PetscCall(PetscSNPrintf(path, sizeof(path),
397 "%s/checkpoints/step_000000000001/statistics/window_0000/block_0000/Ucat_m2.dat",
398 tmpdir));
399 PetscCall(PetscTestFile(path, 'r', &exists));
400 PetscCall(PicurvAssertBool(exists, "the symmetric product is one payload, not six"));
401
402 /* Keep a reference copy of every payload, then discard the in-memory state so a
403 * restore that did nothing cannot pass. */
404 PetscCall(PicurvWindowStoragePayloadCount(&storage, &payload_count));
405 PetscCall(PetscCalloc1((size_t)payload_count, &reference));
406 for (PetscInt index = 0; index < payload_count; ++index) {
408
409 PetscCall(PicurvWindowStoragePayload(user, &definition, &storage, index, &payload));
410 PetscCall(VecDuplicate(payload.vec, &reference[index]));
411 PetscCall(VecCopy(payload.vec, reference[index]));
412 PetscCall(VecZeroEntries(payload.vec));
413 }
414 PetscCall(PicurvWindowInit(&window, &definition));
415 PetscCall(PicurvAssertIntEqual(0, window.sample_count, "the fixture is reset before restoring"));
416
417 simCtx->fieldStatisticsContinue = PETSC_TRUE;
418 PetscCall(RestoreFieldStatisticsState(simCtx, simCtx->step));
419
420 PetscCall(PicurvAssertIntEqual(2, window.sample_count, "the sample count is restored"));
421 PetscCall(PicurvAssertRealNear(2.0, window.total_weight, 1.0e-12, "the total weight is restored"));
422 PetscCall(PicurvAssertRealNear(2.0, window.represented_time, 1.0e-12,
423 "the represented time is restored"));
424 PetscCall(PicurvAssertRealNear(2.0, window.last_accepted_time, 1.0e-12,
425 "the quadrature origin is restored"));
426 PetscCall(PicurvAssertIntEqual(0, window.activation_step, "the schedule anchor is restored"));
427 PetscCall(PicurvAssertIntEqual(2, window.last_event_step,
428 "the duplicate-event guard survives the restart"));
429 PetscCall(PicurvAssertIntEqual(1, window.restart_count, "the restart lineage advances on resume"));
430 PetscCall(PicurvAssertBool((PetscBool)(window.state == PICURV_WINDOW_ACTIVE),
431 "an open window resumes active"));
432
433 /* Every payload must come back bit for bit. The binary format stores IEEE
434 * doubles and the natural ordering is decomposition independent, so anything
435 * short of an exact match is a defect rather than rounding. */
436 for (PetscInt index = 0; index < payload_count; ++index) {
438 PetscReal difference = 0.0;
439 char context[192];
440
441 PetscCall(PicurvWindowStoragePayload(user, &definition, &storage, index, &payload));
442 PetscCall(VecAXPY(reference[index], -1.0, payload.vec));
443 PetscCall(VecNorm(reference[index], NORM_INFINITY, &difference));
444 PetscCall(PetscSNPrintf(context, sizeof(context),
445 "payload '%s' is restored bit for bit", payload.name));
446 PetscCall(PicurvAssertBool((PetscBool)(difference == 0.0), context));
447 PetscCall(VecDestroy(&reference[index]));
448 }
449 PetscCall(PetscFree(reference));
450
451 /* Spot-check one interior point against the analytically known value, so the
452 * comparison above cannot pass by restoring two identically wrong vectors. */
453 {
454 PetscReal ***mean = NULL;
455
456 PetscCall(DMDAVecGetArrayRead(user->da, storage.mean[1], &mean));
457 if (user->info.xs <= 2 && 2 < user->info.xs + user->info.xm &&
458 user->info.ys <= 2 && 2 < user->info.ys + user->info.ym &&
459 user->info.zs <= 2 && 2 < user->info.zs + user->info.zm) {
460 PetscCall(PicurvAssertRealNear(4.0, mean[2][2][2], 1.0e-12,
461 "the restored scalar mean holds the accumulated value"));
462 }
463 PetscCall(DMDAVecRestoreArrayRead(user->da, storage.mean[1], &mean));
464 }
465
466 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
467 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
468 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
469 PetscCall(DetachStatisticsFixture(simCtx, user, &storage));
470 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
471 PetscFunctionReturn(0);
472}
PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Restores field-statistics window state and accumulators from a checkpoint.
Definition io.c:1604
Vec * mean
One per field, matching that field's layout.
Vec vec
Borrowed accumulator vector; never owned by the caller.
PetscErrorCode PicurvWindowStoragePayload(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt index, PicurvStatisticsPayload *payload)
Resolves one enumerated payload of a window's storage.
char name[96]
File basename, no extension.
PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count)
Reports how many checkpointable vectors one window's storage holds.
One checkpointable accumulator vector, resolved by enumeration index.
Independent accumulator state for one window on one block.
PetscInt last_event_step
Guards against a step being offered twice.
PetscInt sample_count
PetscReal last_accepted_time
Right edge of the last represented interval.
PetscInt restart_count
Restart segments this state descends from.
PetscReal total_weight
@ PICURV_WINDOW_ACTIVE
Accepting due states.
PetscInt activation_step
Step at which the window became active.
PetscReal represented_time
Physical time the window covers.
Runtime state of one window.
static PetscErrorCode DetachStatisticsFixture(SimCtx *simCtx, UserCtx *user, PicurvWindowStorage *storage)
Detaches the statistics fixture without disturbing the shared teardown.
Definition test_io.c:292
static PicurvWindowDefinition StatisticsFixtureDefinition(void)
Builds the statistics fixture: one Ucat/P window with a second moment.
Definition test_io.c:261
static PetscErrorCode AttachStatisticsFixture(SimCtx *simCtx, UserCtx *user, PicurvWindow *window, PicurvWindowStorage *storage, const PicurvWindowDefinition *definition)
Attaches one accumulating window to a fixture context and primes it with samples.
Definition test_io.c:277
DMDALocalInfo info
Definition variables.h:1169
PetscBool fieldStatisticsContinue
Definition variables.h:995
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointStatisticsContinuationGuards()

static PetscErrorCode TestCheckpointStatisticsContinuationGuards ( void  )
static

Verifies continuation refuses every state that would corrupt an average.

A silent reset is the failure mode this guards: resuming from zero, or merging samples taken under a different definition, both produce a window whose reported sample count no longer describes the numbers it carries.

Definition at line 481 of file test_io.c.

482{
483 SimCtx *simCtx = NULL;
484 UserCtx *user = NULL;
485 PicurvWindow window;
486 PicurvWindowStorage storage;
489 char tmpdir[PETSC_MAX_PATH_LEN];
490 PetscErrorCode bad = 0;
491
492 PetscFunctionBeginUser;
493 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
494 tmpdir[0] = '\0';
495 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
496 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
497 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
498 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
499 PetscCall(PicurvPopulateIdentityMetrics(user));
500 PetscCall(VecSet(user->Nvert, 0.0));
501 PetscCall(AttachStatisticsFixture(simCtx, user, &window, &storage, &definition));
502 {
503 PetscBool accepted = PETSC_FALSE;
504 PetscReal weight = 0.0;
505
506 PetscCall(PicurvWindowOfferState(&window, 0, 0.0, &accepted, &weight));
507 PetscCall(PicurvWindowOfferState(&window, 1, 1.0, &accepted, &weight));
508 if (accepted) PetscCall(PicurvWindowAccumulate(user, &definition, &storage, weight));
509 }
510 PetscCall(WriteCheckpointBundle(simCtx, "test"));
511
512 /* A hashed property changed: the saved samples describe a different average. */
513 changed = definition;
515 PetscCall(PicurvWindowInit(&window, &changed));
516 simCtx->fieldStatisticsContinue = PETSC_TRUE;
517 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
518 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
519 PetscCall(PetscPopErrorHandler());
520 PetscCall(PicurvAssertIntEqual(PETSC_ERR_ARG_INCOMP, bad,
521 "a changed definition is refused rather than merged"));
522
523 /* A window renamed under the same index is a different window. */
524 changed = definition;
525 strncpy(changed.name, "other", PICURV_WINDOW_NAME_LENGTH - 1);
526 PetscCall(PicurvWindowInit(&window, &changed));
527 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
528 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
529 PetscCall(PetscPopErrorHandler());
530 PetscCall(PicurvAssertIntEqual(PETSC_ERR_ARG_INCOMP, bad, "a renamed window is refused"));
531
532 /* Shortening a window would discard represented time it already claims. */
533 changed = definition;
534 changed.bounded = PETSC_TRUE;
535 changed.end_time = 0.5;
536 PetscCall(PicurvWindowInit(&window, &changed));
537 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
538 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
539 PetscCall(PetscPopErrorHandler());
540 PetscCall(PicurvAssertIntEqual(PETSC_ERR_ARG_INCOMP, bad, "a shortened window is refused"));
541
542 /* Extending it forward is permitted, because end_time is outside the hash. The
543 * saved window is still open here, so there is no former end to leave a gap
544 * after and the extension is accepted. */
545 changed = definition;
546 changed.bounded = PETSC_TRUE;
547 changed.end_time = 40.0;
548 PetscCall(PicurvWindowInit(&window, &changed));
549 PetscCall(RestoreFieldStatisticsState(simCtx, simCtx->step));
550 PetscCall(PicurvAssertIntEqual(1, window.sample_count, "an extended window keeps its samples"));
551 PetscCall(PicurvAssertBool((PetscBool)(window.state == PICURV_WINDOW_ACTIVE),
552 "an extended window resumes active"));
553
554 /* Reopening a window that already closed, across time it never sampled, would
555 * weight that gap into the first new interval. */
556 simCtx->dt = 0.1;
557 PetscCall(WriteCompletedStatisticsWindow(simCtx, user, &window, &storage, &definition));
558 changed = definition;
559 changed.bounded = PETSC_TRUE;
560 changed.end_time = 40.0;
561 PetscCall(PicurvWindowInit(&window, &changed));
562 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
563 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
564 PetscCall(PetscPopErrorHandler());
565 PetscCall(PicurvAssertIntEqual(PETSC_ERR_ARG_INCOMP, bad,
566 "reopening a closed window across an unsampled gap is refused"));
567
568 /* Without an explicit request, a restart starts from zero and says so. */
569 PetscCall(PicurvWindowInit(&window, &definition));
570 simCtx->fieldStatisticsContinue = PETSC_FALSE;
571 PetscCall(RestoreFieldStatisticsState(simCtx, simCtx->step));
572 PetscCall(PicurvAssertIntEqual(0, window.sample_count,
573 "statistics start fresh when continuation is not requested"));
574
575 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
576 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
577 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
578 PetscCall(DetachStatisticsFixture(simCtx, user, &storage));
579 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
580 PetscFunctionReturn(0);
581}
@ PICURV_WEIGHTING_PHYSICAL_TIME
Weight is the represented interval.
static PetscErrorCode WriteCompletedStatisticsWindow(SimCtx *simCtx, UserCtx *user, PicurvWindow *window, PicurvWindowStorage *storage, const PicurvWindowDefinition *definition)
Rewrites the bundle holding a window that closed well before the checkpoint time.
Definition test_io.c:311
PetscReal dt
Definition variables.h:933
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointStatisticsPayloadIsValidated()

static PetscErrorCode TestCheckpointStatisticsPayloadIsValidated ( void  )
static

A damaged statistics payload must fail bundle validation, not load silently.

Statistics payloads are validated because they enter the manifest inventory the existing validator already walks. That is an easy property to believe and an easy one to lose, so it is checked by damaging a payload rather than by inspection.

Definition at line 590 of file test_io.c.

591{
592 SimCtx *simCtx = NULL;
593 UserCtx *user = NULL;
594 PicurvWindow window;
595 PicurvWindowStorage storage;
597 char tmpdir[PETSC_MAX_PATH_LEN];
598 char payload_path[PETSC_MAX_PATH_LEN];
599 PetscErrorCode bad = 0;
600
601 PetscFunctionBeginUser;
602 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
603 tmpdir[0] = '\0';
604 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
605 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
606 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
607 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
608 PetscCall(PicurvPopulateIdentityMetrics(user));
609 PetscCall(VecSet(user->Nvert, 0.0));
610 PetscCall(AttachStatisticsFixture(simCtx, user, &window, &storage, &definition));
611 {
612 PetscBool accepted = PETSC_FALSE;
613 PetscReal weight = 0.0;
614
615 PetscCall(PicurvWindowOfferState(&window, 0, 0.0, &accepted, &weight));
616 PetscCall(PicurvWindowOfferState(&window, 1, 1.0, &accepted, &weight));
617 if (accepted) PetscCall(PicurvWindowAccumulate(user, &definition, &storage, weight));
618 }
619 PetscCall(WriteCheckpointBundle(simCtx, "test"));
620
621 /* Truncating one payload leaves the manifest and its commit marker intact, so
622 * only the inventory's recorded byte size can catch it. */
623 PetscCall(PetscSNPrintf(payload_path, sizeof(payload_path),
624 "%s/checkpoints/step_000000000001/statistics/window_0000/block_0000/P_mean.dat",
625 tmpdir));
626 if (simCtx->rank == 0) {
627 FILE *damaged = fopen(payload_path, "w");
628
629 PetscCheck(damaged != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
630 "Unable to truncate '%s'.", payload_path);
631 PetscCheck(fclose(damaged) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
632 "Unable to close '%s'.", payload_path);
633 }
634 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
635
636 simCtx->fieldStatisticsContinue = PETSC_TRUE;
637 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
638 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
639 PetscCall(PetscPopErrorHandler());
640 PetscCall(PicurvAssertIntEqual(PETSC_ERR_FILE_UNEXPECTED, bad,
641 "a truncated statistics payload fails bundle validation"));
642
643 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
644 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
645 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
646 PetscCall(DetachStatisticsFixture(simCtx, user, &storage));
647 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
648 PetscFunctionReturn(0);
649}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointStatisticsAbsentWhenDisabled()

static PetscErrorCode TestCheckpointStatisticsAbsentWhenDisabled ( void  )
static

A run without statistics writes no statistics subtree and refuses to fake one.

Definition at line 652 of file test_io.c.

653{
654 SimCtx *simCtx = NULL;
655 UserCtx *user = NULL;
656 PicurvWindow window;
657 PicurvWindowStorage storage;
659 char tmpdir[PETSC_MAX_PATH_LEN];
660 char path[PETSC_MAX_PATH_LEN];
661 PetscBool exists = PETSC_TRUE;
662 PetscErrorCode bad = 0;
663
664 PetscFunctionBeginUser;
665 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
666 tmpdir[0] = '\0';
667 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
668 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
669 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
670 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
671 PetscCall(PicurvPopulateIdentityMetrics(user));
672
673 PetscCall(WriteCheckpointBundle(simCtx, "test"));
674 PetscCall(PetscSNPrintf(path, sizeof(path), "%s/checkpoints/step_000000000001/statistics", tmpdir));
675 PetscCall(PetscTestDirectory(path, 'r', &exists));
676 PetscCall(PicurvAssertBool((PetscBool)!exists,
677 "a run without statistics writes no statistics subtree"));
678
679 /* Continuing from that bundle must fail loudly rather than resume from zero. */
680 PetscCall(AttachStatisticsFixture(simCtx, user, &window, &storage, &definition));
681 simCtx->fieldStatisticsContinue = PETSC_TRUE;
682 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
683 bad = RestoreFieldStatisticsState(simCtx, simCtx->step);
684 PetscCall(PetscPopErrorHandler());
685 PetscCall(PicurvAssertIntEqual(PETSC_ERR_ARG_INCOMP, bad,
686 "missing statistics state is fatal, never silently zeroed"));
687
688 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
689 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
690 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
691 PetscCall(DetachStatisticsFixture(simCtx, user, &storage));
692 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
693 PetscFunctionReturn(0);
694}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointSameStepRewriteIsRejected()

static PetscErrorCode TestCheckpointSameStepRewriteIsRejected ( void  )
static

Verifies a committed checkpoint step is rewritten neither silently nor inconsistently.

WriteCheckpointBundle revalidates an already-committed step instead of rewriting it, so a repeated call at the same step must leave the payloads byte-identical even when the in-memory state has since diverged. The same guard must reject a repeat call whose physical time disagrees with the committed bundle, because that means the step number no longer identifies the same solver state.

Definition at line 705 of file test_io.c.

706{
707 SimCtx *simCtx = NULL;
708 UserCtx *user = NULL;
709 char tmpdir[PETSC_MAX_PATH_LEN];
710 char payload_path[PETSC_MAX_PATH_LEN];
711 struct stat first_stat;
712 struct stat second_stat;
713 PetscErrorCode mismatch_ierr = 0;
714
715 PetscFunctionBeginUser;
716 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
717 tmpdir[0] = '\0';
718 if (simCtx->rank == 0) PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
719 PetscCallMPI(MPI_Bcast(tmpdir, sizeof(tmpdir), MPI_CHAR, 0, PETSC_COMM_WORLD));
720
721 PetscCall(PetscStrncpy(simCtx->output_dir, tmpdir, sizeof(simCtx->output_dir)));
722 PetscCall(PetscStrncpy(simCtx->restart_dir, tmpdir, sizeof(simCtx->restart_dir)));
723 PetscCall(VecSet(user->P, 4.5));
724 PetscCall(VecSet(user->Nvert, 0.0));
725 PetscCall(VecSet(user->Ucat, 2.0));
726 PetscCall(VecSet(user->Ucont, 3.0));
727 PetscCall(VecSet(user->Ucont_rm1, 1.25));
728 simCtx->ti = 0.35;
729 PetscCall(PicurvPopulateIdentityMetrics(user));
730
731 PetscCall(WriteCheckpointBundle(simCtx, "cadence"));
732 PetscCall(PetscSNPrintf(payload_path, sizeof(payload_path),
733 "%s/checkpoints/step_000000000001/eulerian/block_0000/Ucat.dat", tmpdir));
734 PetscCall(PicurvAssertBool((PetscBool)(stat(payload_path, &first_stat) == 0),
735 "first checkpoint write should produce a Ucat payload"));
736
737 /* Diverge the in-memory state so a rewrite would be observable in the payload bytes. */
738 PetscCall(VecSet(user->Ucat, 99.0));
739 PetscCall(WriteCheckpointBundle(simCtx, "cadence"));
740
741 PetscCall(PicurvAssertBool((PetscBool)(stat(payload_path, &second_stat) == 0),
742 "repeated checkpoint write should leave the Ucat payload in place"));
743 /* Nanosecond resolution: a same-second rewrite would still move this. */
744 PetscCall(PicurvAssertBool((PetscBool)(first_stat.st_mtim.tv_sec == second_stat.st_mtim.tv_sec &&
745 first_stat.st_mtim.tv_nsec == second_stat.st_mtim.tv_nsec),
746 "repeated checkpoint write at a committed step should not touch payload mtime"));
747 PetscCall(PicurvAssertBool((PetscBool)(first_stat.st_size == second_stat.st_size),
748 "repeated checkpoint write at a committed step should not resize payloads"));
749
750 PetscCall(VecZeroEntries(user->Ucat));
751 PetscCall(ReadSimulationFields(user, simCtx->step));
752 PetscCall(PicurvAssertVecConstant(user->Ucat, 2.0, 1.0e-12,
753 "repeated checkpoint write must not overwrite committed payload contents"));
754
755 /* A same-step call whose physical time disagrees is a state-identity error, not a no-op. */
756 simCtx->ti = 0.75;
757 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
758 mismatch_ierr = WriteCheckpointBundle(simCtx, "cadence");
759 PetscCall(PetscPopErrorHandler());
760 PetscCall(PicurvAssertIntEqual(PETSC_ERR_FILE_UNEXPECTED, mismatch_ierr,
761 "same-step checkpoint write with a different physical time should fail"));
762
763 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
764 if (simCtx->rank == 0) PetscCall(PicurvRemoveTempDir(tmpdir));
765 PetscCallMPI(MPI_Barrier(PETSC_COMM_WORLD));
766 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
767 PetscFunctionReturn(0);
768}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestCheckpointSHA256KnownVector()

static PetscErrorCode TestCheckpointSHA256KnownVector ( void  )
static

Verifies the dependency-free SHA-256 implementation against a standard vector.

Definition at line 771 of file test_io.c.

772{
773 PicurvSHA256Context context;
774 char digest[65];
775
776 PetscFunctionBeginUser;
777 PicurvSHA256Init(&context);
778 PicurvSHA256Update(&context, "abc", 3);
779 PicurvSHA256FinalHex(&context, digest);
780 PetscCall(PicurvAssertBool(
781 (PetscBool)!strcmp(digest, "ba7816bf8f01cfea414140de5dae2223"
782 "b00361a396177a9cb410ff61f20015ad"),
783 "SHA-256 implementation should match the standard abc test vector"));
784 PetscFunctionReturn(0);
785}
void PicurvSHA256Init(PicurvSHA256Context *context)
Initialize an incremental SHA-256 calculation.
Definition checksum.c:62
void PicurvSHA256Update(PicurvSHA256Context *context, const void *data, size_t length)
Add bytes to an incremental SHA-256 calculation.
Definition checksum.c:74
void PicurvSHA256FinalHex(PicurvSHA256Context *context, char digest_hex[65])
Finish a SHA-256 calculation and return a lowercase hexadecimal digest.
Definition checksum.c:98
Incremental SHA-256 state.
Definition checksum.h:14
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestParsePostProcessingSettings()

static PetscErrorCode TestParsePostProcessingSettings ( void  )
static

Tests parsing of post-processing control settings from a file.

Definition at line 790 of file test_io.c.

791{
792 SimCtx *simCtx = NULL;
793 UserCtx *user = NULL;
794 char tmpdir[PETSC_MAX_PATH_LEN];
795 char cfg_path[PETSC_MAX_PATH_LEN];
796 FILE *file = NULL;
797
798 PetscFunctionBeginUser;
799 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
800 PetscCall(PetscCalloc1(1, &simCtx->pps));
801 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
802 PetscCall(PetscSNPrintf(cfg_path, sizeof(cfg_path), "%s/post.run", tmpdir));
803 PetscCall(PetscStrncpy(simCtx->PostprocessingControlFile, cfg_path, sizeof(simCtx->PostprocessingControlFile)));
804
805 file = fopen(cfg_path, "w");
806 PetscCheck(file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to create temp config file '%s'.", cfg_path);
807 fputs("startTime = 2\n", file);
808 fputs("endTime = 6\n", file);
809 fputs("timeStep = 2\n", file);
810 fputs("output_particles = true\n", file);
811 fputs("output_prefix = SmokeField\n", file);
812 fclose(file);
813
814 PetscCall(ParsePostProcessingSettings(simCtx));
815 PetscCall(PicurvAssertIntEqual(2, simCtx->pps->startTime, "ParsePostProcessingSettings should parse startTime"));
816 PetscCall(PicurvAssertIntEqual(6, simCtx->pps->endTime, "ParsePostProcessingSettings should parse endTime"));
817 PetscCall(PicurvAssertIntEqual(2, simCtx->pps->timeStep, "ParsePostProcessingSettings should parse timeStep"));
818 PetscCall(PicurvAssertBool(simCtx->pps->outputParticles, "ParsePostProcessingSettings should parse output_particles"));
819 PetscCall(PicurvAssertBool((PetscBool)(strcmp(simCtx->pps->output_prefix, "SmokeField") == 0),
820 "ParsePostProcessingSettings should parse output_prefix"));
821
822 /* File and command-line ingress both guard the loop after override precedence. */
823 const PetscInt intervals[] = {1, 0, -1, 1, 1, 0};
824 const char *overrides[] = {NULL, NULL, NULL, "0", "-1", "1"};
825 for (size_t n = 0; n < sizeof(intervals) / sizeof(intervals[0]); ++n) {
826 PetscErrorCode parse_ierr;
827 file = fopen(cfg_path, "w");
828 PetscCheck(file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to reopen post config.");
829 fprintf(file, "startTime = 100\nendTime = 100\ntimeStep = %d\n", (int)intervals[n]);
830 fclose(file);
831 if (overrides[n]) PetscCall(PetscOptionsSetValue(NULL, "-timeStep", overrides[n]));
832 PetscCall(PetscPushErrorHandler(PetscIgnoreErrorHandler, NULL));
833 parse_ierr = ParsePostProcessingSettings(simCtx);
834 PetscCall(PetscPopErrorHandler());
835 PetscCall(PetscOptionsClearValue(NULL, "-timeStep"));
836 PetscCall(PicurvAssertIntEqual((n == 0 || n == 5) ? 0 : PETSC_ERR_ARG_OUTOFRANGE,
837 parse_ierr, "post interval must be positive after command-line overrides"));
838 }
839
840 PetscCall(PicurvRemoveTempDir(tmpdir));
841 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
842 PetscFunctionReturn(0);
843}
PetscErrorCode ParsePostProcessingSettings(SimCtx *simCtx)
Initializes post-processing settings from a config file and command-line overrides.
Definition io.c:3051
char output_prefix[256]
Definition variables.h:808
PetscInt timeStep
Definition variables.h:800
PetscBool outputParticles
Definition variables.h:803
PetscInt startTime
Definition variables.h:798
char PostprocessingControlFile[PETSC_MAX_PATH_LEN]
Definition variables.h:1130
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestTrimWhitespace()

static PetscErrorCode TestTrimWhitespace ( void  )
static

Tests trimming of leading and trailing whitespace.

Definition at line 849 of file test_io.c.

850{
851 char value_a[] = " inlet_value ";
852 char value_b[] = " ";
853
854 PetscFunctionBeginUser;
855 TrimWhitespace(value_a);
856 PetscCall(PicurvAssertBool((PetscBool)(strcmp(value_a, "inlet_value") == 0),
857 "TrimWhitespace should remove leading and trailing whitespace"));
858
859 TrimWhitespace(value_b);
860 PetscCall(PicurvAssertBool((PetscBool)(strcmp(value_b, "") == 0),
861 "TrimWhitespace should reduce all-whitespace strings to empty"));
862 PetscFunctionReturn(0);
863}
void TrimWhitespace(char *str)
Removes leading and trailing ASCII whitespace from a mutable string.
Definition io.c:486
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestBoundaryConditionStringParsers()

static PetscErrorCode TestBoundaryConditionStringParsers ( void  )
static

Tests boundary-condition string parsers for face, type, and handler names.

Definition at line 868 of file test_io.c.

869{
870 BCFace face = BC_FACE_NEG_X;
871 BCType type = WALL;
873
874 PetscFunctionBeginUser;
875 PetscCall(StringToBCFace("+Zeta", &face));
876 PetscCall(PicurvAssertIntEqual(BC_FACE_POS_Z, face, "StringToBCFace should parse +Zeta"));
877
878 PetscCall(StringToBCType("periodic", &type));
879 PetscCall(PicurvAssertIntEqual(PERIODIC, type, "StringToBCType should parse PERIODIC case-insensitively"));
880
881 PetscCall(StringToBCHandlerType("constant_flux", &handler));
883 "StringToBCHandlerType should parse constant_flux"));
884 PetscCall(StringToBCHandlerType("prescribed_velocity", &handler));
886 "StringToBCHandlerType should parse prescribed_velocity"));
887 PetscFunctionReturn(0);
888}
PetscErrorCode StringToBCHandlerType(const char *str, BCHandlerType *handler_out)
Converts a BC handler token (implementation strategy) to BCHandlerType.
Definition io.c:773
PetscErrorCode StringToBCFace(const char *str, BCFace *face_out)
Converts a face-token string (e.g., "-Xi", "+Eta") to the internal BCFace enum.
Definition io.c:736
PetscErrorCode StringToBCType(const char *str, BCType *type_out)
Converts a mathematical BC type string (e.g., "PERIODIC", "WALL") to BCType.
Definition io.c:753
BCType
Defines the general mathematical/physical Category of a boundary.
Definition variables.h:316
@ PERIODIC
Definition variables.h:325
@ WALL
Definition variables.h:319
BCHandlerType
Defines the specific computational "strategy" for a boundary handler.
Definition variables.h:343
@ BC_HANDLER_PERIODIC_DRIVEN_CONSTANT_FLUX
Definition variables.h:354
@ BC_HANDLER_INLET_PRESCRIBED_VELOCITY
Definition variables.h:348
@ BC_HANDLER_WALL_NOSLIP
Definition variables.h:345
BCFace
Identifies the six logical faces of a structured computational block.
Definition variables.h:308
@ BC_FACE_NEG_X
Definition variables.h:309
@ BC_FACE_POS_Z
Definition variables.h:311
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestValidateBCHandlerForBCType()

static PetscErrorCode TestValidateBCHandlerForBCType ( void  )
static

Tests validation of boundary-type and handler compatibility.

Definition at line 893 of file test_io.c.

894{
895 PetscFunctionBeginUser;
897 "WALL + noslip should be a valid combination"));
899 "PERIODIC + geometric should be a valid combination"));
901 "INLET + prescribed_velocity should be a valid combination"));
903 "INLET + noslip should be rejected"));
904 PetscFunctionReturn(0);
905}
PetscErrorCode ValidateBCHandlerForBCType(BCType type, BCHandlerType handler)
Validates that a selected handler is compatible with a mathematical BC type.
Definition io.c:793
@ INLET
Definition variables.h:323
@ BC_HANDLER_PERIODIC_GEOMETRIC
Definition variables.h:352
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestParseScalingInformation()

static PetscErrorCode TestParseScalingInformation ( void  )
static

Tests scaling-reference parsing and derived pressure scaling.

Definition at line 910 of file test_io.c.

911{
912 SimCtx simCtx;
913
914 PetscFunctionBeginUser;
915 PetscCall(PetscMemzero(&simCtx, sizeof(simCtx)));
916
917 PetscCall(PetscOptionsClearValue(NULL, "-scaling_L_ref"));
918 PetscCall(PetscOptionsClearValue(NULL, "-scaling_U_ref"));
919 PetscCall(PetscOptionsClearValue(NULL, "-scaling_rho_ref"));
920
921 PetscCall(ParseScalingInformation(&simCtx));
922 PetscCall(PicurvAssertRealNear(1.0, simCtx.scaling.L_ref, 1.0e-12, "Default scaling_L_ref should be 1.0"));
923 PetscCall(PicurvAssertRealNear(1.0, simCtx.scaling.U_ref, 1.0e-12, "Default scaling_U_ref should be 1.0"));
924 PetscCall(PicurvAssertRealNear(1.0, simCtx.scaling.rho_ref, 1.0e-12, "Default scaling_rho_ref should be 1.0"));
925 PetscCall(PicurvAssertRealNear(1.0, simCtx.scaling.P_ref, 1.0e-12, "Default scaling_P_ref should be 1.0"));
926
927 PetscCall(PetscOptionsSetValue(NULL, "-scaling_L_ref", "2.5"));
928 PetscCall(PetscOptionsSetValue(NULL, "-scaling_U_ref", "4.0"));
929 PetscCall(PetscOptionsSetValue(NULL, "-scaling_rho_ref", "1.2"));
930
931 PetscCall(ParseScalingInformation(&simCtx));
932 PetscCall(PicurvAssertRealNear(2.5, simCtx.scaling.L_ref, 1.0e-12, "scaling_L_ref should honor options"));
933 PetscCall(PicurvAssertRealNear(4.0, simCtx.scaling.U_ref, 1.0e-12, "scaling_U_ref should honor options"));
934 PetscCall(PicurvAssertRealNear(1.2, simCtx.scaling.rho_ref, 1.0e-12, "scaling_rho_ref should honor options"));
935 PetscCall(PicurvAssertRealNear(19.2, simCtx.scaling.P_ref, 1.0e-12, "scaling_P_ref should be rho_ref*U_ref^2"));
936
937 PetscCall(PetscOptionsClearValue(NULL, "-scaling_L_ref"));
938 PetscCall(PetscOptionsClearValue(NULL, "-scaling_U_ref"));
939 PetscCall(PetscOptionsClearValue(NULL, "-scaling_rho_ref"));
940 PetscFunctionReturn(0);
941}
PetscErrorCode ParseScalingInformation(SimCtx *simCtx)
Parses physical scaling parameters from command-line options.
Definition io.c:3256
Here is the call graph for this function:
Here is the caller graph for this function:

◆ CaptureBannerOutput()

static PetscErrorCode CaptureBannerOutput ( SimCtx *  simCtx,
char *  captured,
size_t  captured_len 
)
static

Captures the startup banner into a temporary file-backed buffer.

Definition at line 945 of file test_io.c.

946{
947 char tmpdir[PETSC_MAX_PATH_LEN];
948 char capture_path[PETSC_MAX_PATH_LEN];
949 FILE *capture_file = NULL;
950 int saved_stdout = -1;
951 int capture_fd = -1;
952 size_t bytes_read = 0;
953 PetscErrorCode ierr;
954
955 PetscFunctionBeginUser;
956 PetscCheck(simCtx != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "SimCtx cannot be NULL.");
957 PetscCheck(captured != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Capture buffer cannot be NULL.");
958 PetscCheck(captured_len > 0, PETSC_COMM_SELF, PETSC_ERR_ARG_SIZ, "Capture buffer must be non-empty.");
959
960 PetscCall(PicurvMakeTempDir(tmpdir, sizeof(tmpdir)));
961 PetscCall(PetscSNPrintf(capture_path, sizeof(capture_path), "%s/banner.log", tmpdir));
962
963 fflush(stdout);
964 saved_stdout = dup(STDOUT_FILENO);
965 PetscCheck(saved_stdout >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup(STDOUT_FILENO) failed.");
966 capture_fd = open(capture_path, O_CREAT | O_TRUNC | O_WRONLY, 0600);
967 PetscCheck(capture_fd >= 0, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to open capture file '%s'.", capture_path);
968 PetscCheck(dup2(capture_fd, STDOUT_FILENO) >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup2() failed while redirecting stdout.");
969 close(capture_fd);
970 capture_fd = -1;
971
972 ierr = DisplayBanner(simCtx);
973 fflush(stdout);
974 PetscCheck(dup2(saved_stdout, STDOUT_FILENO) >= 0, PETSC_COMM_SELF, PETSC_ERR_SYS, "dup2() failed while restoring stdout.");
975 close(saved_stdout);
976 saved_stdout = -1;
977 PetscCall(ierr);
978
979 capture_file = fopen(capture_path, "r");
980 PetscCheck(capture_file != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Failed to read capture file '%s'.", capture_path);
981 bytes_read = fread(captured, 1, captured_len - 1, capture_file);
982 captured[bytes_read] = '\0';
983 fclose(capture_file);
984 PetscCall(PicurvRemoveTempDir(tmpdir));
985 PetscCallMPI(MPI_Bcast(captured, (PetscMPIInt)captured_len, MPI_CHAR, 0, PETSC_COMM_WORLD));
986 PetscFunctionReturn(0);
987}
PetscErrorCode DisplayBanner(SimCtx *simCtx)
Displays a structured banner summarizing the simulation configuration.
Definition io.c:2635
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssertCapturedContains()

static PetscErrorCode AssertCapturedContains ( const char *  captured,
const char *  needle,
const char *  message 
)
static

Asserts that captured banner output contains one expected substring.

Definition at line 991 of file test_io.c.

992{
993 PetscFunctionBeginUser;
994 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, needle) != NULL), message));
995 PetscFunctionReturn(0);
996}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ AssertCapturedOmits()

static PetscErrorCode AssertCapturedOmits ( const char *  captured,
const char *  needle,
const char *  message 
)
static

Asserts that captured banner output omits one forbidden substring.

Definition at line 1000 of file test_io.c.

1001{
1002 PetscFunctionBeginUser;
1003 PetscCall(PicurvAssertBool((PetscBool)(strstr(captured, needle) == NULL), message));
1004 PetscFunctionReturn(0);
1005}
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestDisplayBannerReportsStatisticsCadence()

static PetscErrorCode TestDisplayBannerReportsStatisticsCadence ( void  )
static

Tests that the startup banner reports statistics monitoring in every state.

The banner is the one place a log records whether monitoring was active, so all three states must be distinguishable after the fact: a live cadence, a subsystem that is accumulating with the console silenced, and a run that configured no window at all. The banner reads only the window array and the console cadence, so this fixture sets those directly rather than allocating accumulator storage it would never touch.

Definition at line 1016 of file test_io.c.

1017{
1018 SimCtx *simCtx = NULL;
1019 UserCtx *user = NULL;
1020 PicurvWindow window;
1022 char captured[16384];
1023
1024 PetscFunctionBeginUser;
1025 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1026 PetscCall(PicurvWindowInit(&window, &definition));
1027 simCtx->OnlySetup = PETSC_FALSE;
1028 simCtx->StepsToRun = 5;
1029 PetscCall(PetscStrncpy(simCtx->eulerianSource, "solve", sizeof(simCtx->eulerianSource)));
1030
1031 /* A run with statistics accumulating and the console cadence live. */
1032 simCtx->fieldStatisticsEnabled = PETSC_TRUE;
1033 simCtx->fieldStatisticsWindowCount = 1;
1034 simCtx->fieldStatisticsWindows = &window;
1035 simCtx->statisticsConsoleOutputFreq = 5;
1036 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1037 PetscCall(AssertCapturedContains(captured, "Statistics Console Cadence : every 5 step(s), 1 window(s)",
1038 "DisplayBanner should report the live statistics console cadence"));
1039
1040 /* Accumulating, but with console reporting switched off. */
1041 simCtx->statisticsConsoleOutputFreq = 0;
1042 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1043 PetscCall(AssertCapturedContains(captured, "Statistics Console Cadence : DISABLED (1 window(s) accumulating)",
1044 "DisplayBanner should distinguish a silenced console from an inactive subsystem"));
1045
1046 /* No window configured: the row still appears, so its absence is never ambiguous. */
1047 simCtx->fieldStatisticsEnabled = PETSC_FALSE;
1048 simCtx->fieldStatisticsWindowCount = 0;
1049 simCtx->fieldStatisticsWindows = NULL;
1050 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1051 PetscCall(AssertCapturedContains(captured, "Statistics Console Cadence : DISABLED (no window configured)",
1052 "DisplayBanner should record that no statistics window was configured"));
1053
1054 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1055 PetscFunctionReturn(0);
1056}
static PetscErrorCode AssertCapturedContains(const char *captured, const char *needle, const char *message)
Asserts that captured banner output contains one expected substring.
Definition test_io.c:991
static PetscErrorCode CaptureBannerOutput(SimCtx *simCtx, char *captured, size_t captured_len)
Captures the startup banner into a temporary file-backed buffer.
Definition test_io.c:945
PetscInt statisticsConsoleOutputFreq
Definition variables.h:991
PetscInt StepsToRun
Definition variables.h:927
PetscBool OnlySetup
Definition variables.h:934
char eulerianSource[PETSC_MAX_PATH_LEN]
Definition variables.h:938
Here is the call graph for this function:
Here is the caller graph for this function:

◆ TestDisplayBannerTracksConditionalStartupFields()

static PetscErrorCode TestDisplayBannerTracksConditionalStartupFields ( void  )
static

Tests conditional startup-banner fields across particle and analytical cases.

Definition at line 1061 of file test_io.c.

1062{
1063 SimCtx *simCtx = NULL;
1064 UserCtx *user = NULL;
1065 char captured[16384];
1066
1067 PetscFunctionBeginUser;
1068 PetscCall(PicurvCreateMinimalContexts(&simCtx, &user, 4, 4, 4));
1069 simCtx->OnlySetup = PETSC_FALSE;
1070 simCtx->StepsToRun = 5;
1071 simCtx->immersed = PETSC_FALSE;
1072 PetscCall(PetscStrncpy(simCtx->eulerianSource, "solve", sizeof(simCtx->eulerianSource)));
1073 simCtx->particleConsoleOutputFreq = 7;
1074 simCtx->LoggingFrequency = 4;
1077
1078 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1079 PetscCall(AssertCapturedContains(captured, "Run Mode : Full Simulation",
1080 "DisplayBanner should include the run mode"));
1081 PetscCall(AssertCapturedContains(captured, "Field/Restart Cadence : every 2 step(s)",
1082 "DisplayBanner should include field/restart cadence"));
1083 PetscCall(AssertCapturedContains(captured, "Immersed Boundary : DISABLED",
1084 "DisplayBanner should include immersed-boundary state"));
1085 PetscCall(AssertCapturedContains(captured, "Periodic Axes (BC-derived) : I=NO, J=NO, K=NO",
1086 "DisplayBanner should include BC-derived periodic axes"));
1087 PetscCall(AssertCapturedContains(captured, "Number of Particles : 0",
1088 "DisplayBanner should include the total particle count"));
1089 PetscCall(AssertCapturedContains(captured, "Eulerian State Source : initial condition (Source)",
1090 "DisplayBanner should identify a fresh solve IC as the Eulerian source"));
1091 PetscCall(AssertCapturedOmits(captured, "Particle Console Cadence",
1092 "DisplayBanner should omit particle console cadence when no particles are configured"));
1093 PetscCall(AssertCapturedOmits(captured, "Particle Log Row Sampling",
1094 "DisplayBanner should omit particle row sampling when no particles are configured"));
1095 PetscCall(AssertCapturedOmits(captured, "Particle Restart Mode",
1096 "DisplayBanner should omit particle restart mode when no particles are configured"));
1097 PetscCall(AssertCapturedOmits(captured, "Particle Initialization Mode",
1098 "DisplayBanner should omit particle initialization mode when no particles are configured"));
1099 PetscCall(AssertCapturedOmits(captured, "Interpolation Method",
1100 "DisplayBanner should omit interpolation method when no particles are configured"));
1101 PetscCall(AssertCapturedContains(captured, "Initial Pseudo-CFL (Courant)",
1102 "DisplayBanner should report pseudo-CFL for the dual-time momentum solver"));
1103 PetscCall(AssertCapturedContains(captured, "Pseudo-CFL Adaptation",
1104 "DisplayBanner should report the active dual-time controller"));
1105 PetscCall(AssertCapturedContains(captured, "Console Log Level",
1106 "DisplayBanner should report the effective console log level"));
1107 PetscCall(AssertCapturedContains(captured, "Profiling Timestep Output",
1108 "DisplayBanner should report profiling mode"));
1109 PetscCall(AssertCapturedContains(captured, "Runtime Memory Log",
1110 "DisplayBanner should report runtime-memory logging state"));
1111
1113 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1114 PetscCall(AssertCapturedContains(captured, "Momentum Equation Solver : Newton Krylov",
1115 "DisplayBanner should identify the selected Newton-Krylov solver"));
1116 PetscCall(AssertCapturedOmits(captured, "Initial Pseudo-CFL (Courant)",
1117 "DisplayBanner must not report pseudo-CFL for Newton-Krylov"));
1118 PetscCall(AssertCapturedContains(captured, "Newton-Krylov PETSc Controls",
1119 "DisplayBanner should report the active Newton-Krylov control family"));
1121
1123 simCtx->solutionConvergencePeriodSteps = 11;
1124 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1125 PetscCall(AssertCapturedContains(captured, "Solution Convergence Mode : PERIODIC_DETERMINISTIC",
1126 "DisplayBanner should identify the active periodic convergence mode"));
1127 PetscCall(AssertCapturedContains(captured, "Convergence Period : 11 step(s)",
1128 "DisplayBanner should report the active periodic convergence period"));
1130 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1131 PetscCall(AssertCapturedOmits(captured, "Convergence Period",
1132 "DisplayBanner should omit periodic-only convergence fields when inactive"));
1133
1134 simCtx->StartStep = 3;
1135 simCtx->np = 8;
1136 simCtx->i_periodic = 1;
1137 user->periodic_translation_valid[0] = PETSC_TRUE;
1138 user->periodic_translation[0] = (Cmpnts){1.0, 0.0, 0.0};
1139 simCtx->particleConsoleOutputFreq = 0;
1140 simCtx->LoggingFrequency = 4;
1141 PetscCall(PetscStrncpy(simCtx->particleRestartMode, "load", sizeof(simCtx->particleRestartMode)));
1142 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1143 PetscCall(AssertCapturedContains(captured, "Eulerian State Source : restart step 3",
1144 "DisplayBanner should identify restart authority"));
1145 PetscCall(AssertCapturedOmits(captured, "initial condition (",
1146 "DisplayBanner should not present an IC as active during restart"));
1147 PetscCall(AssertCapturedContains(captured, "Number of Particles : 8",
1148 "DisplayBanner should include the active particle count"));
1149 PetscCall(AssertCapturedContains(captured, "Periodic I Translation",
1150 "DisplayBanner should include validated periodic translation"));
1151 PetscCall(AssertCapturedOmits(captured, "Particle Periodic Wrapping",
1152 "DisplayBanner should not report particle wrapping as unsupported"));
1153 PetscCall(AssertCapturedContains(captured, "Particle Console Cadence : DISABLED",
1154 "DisplayBanner should show disabled particle console cadence when particles are configured"));
1155 PetscCall(AssertCapturedContains(captured, "Particle Log Row Sampling : every 4 particle(s)",
1156 "DisplayBanner should include particle row sampling when particles are configured"));
1157 PetscCall(AssertCapturedContains(captured, "Particle Restart Mode : load",
1158 "DisplayBanner should include particle restart mode for restarted particle runs"));
1159 PetscCall(AssertCapturedContains(captured, "Particle Initialization Mode: Point Source",
1160 "DisplayBanner should include particle initialization mode when particles are configured"));
1161 PetscCall(AssertCapturedContains(captured, "Interpolation Method : Trilinear (direct cell-center)",
1162 "DisplayBanner should include default interpolation method when particles are configured"));
1163 PetscCall(AssertCapturedOmits(captured, "Particles Initialized At",
1164 "DisplayBanner should omit inlet-face placement details for point-source particle initialization"));
1165
1166 simCtx->StartStep = 0;
1167 PetscCall(PetscStrncpy(simCtx->eulerianSource, "load", sizeof(simCtx->eulerianSource)));
1168 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1169 PetscCall(AssertCapturedContains(captured, "Eulerian State Source : load",
1170 "DisplayBanner should identify load authority"));
1171 PetscCall(AssertCapturedOmits(captured, "initial condition (",
1172 "DisplayBanner should not present an IC as active in load mode"));
1173
1174 simCtx->StartStep = 0;
1175 simCtx->particleConsoleOutputFreq = 6;
1177 user->inletFaceDefined = PETSC_TRUE;
1178 user->identifiedInletBCFace = (BCFace)0;
1179 PetscCall(PetscStrncpy(simCtx->eulerianSource, "analytical", sizeof(simCtx->eulerianSource)));
1180 PetscCall(CaptureBannerOutput(simCtx, captured, sizeof(captured)));
1181 PetscCall(AssertCapturedContains(captured, "Eulerian State Source : analytical (Source)",
1182 "DisplayBanner should include the analytical solution type for analytical runs"));
1183 PetscCall(AssertCapturedContains(captured, "Particle Console Cadence : every 6 step(s)",
1184 "DisplayBanner should include active particle console cadence when particles are configured"));
1185 PetscCall(AssertCapturedContains(captured, "Particle Initialization Mode: Surface: Random",
1186 "DisplayBanner should include particle initialization mode for analytical particle runs"));
1187 PetscCall(AssertCapturedContains(captured, "Particles Initialized At",
1188 "DisplayBanner should include inlet-face placement details for surface particle initialization"));
1189
1190 PetscCall(PicurvDestroyMinimalContexts(&simCtx, &user));
1191 PetscFunctionReturn(0);
1192}
static PetscErrorCode AssertCapturedOmits(const char *captured, const char *needle, const char *message)
Asserts that captured banner output omits one forbidden substring.
Definition test_io.c:1000
PetscBool inletFaceDefined
Definition variables.h:1183
BCFace identifiedInletBCFace
Definition variables.h:1184
@ PARTICLE_INIT_SURFACE_RANDOM
Random placement on the inlet face.
Definition variables.h:747
@ PARTICLE_INIT_POINT_SOURCE
All particles at a fixed (psrc_x,psrc_y,psrc_z) — for validation.
Definition variables.h:749
PetscInt np
Definition variables.h:1049
PetscInt StartStep
Definition variables.h:926
@ MOMENTUM_SOLVER_DUALTIME_PICARD_JAMESON_RK
Definition variables.h:731
@ MOMENTUM_SOLVER_NEWTON_KRYLOV
Definition variables.h:732
PetscInt solutionConvergencePeriodSteps
Definition variables.h:982
char particleRestartMode[16]
Definition variables.h:1056
ParticleInitializationType ParticleInitialization
Definition variables.h:1054
PetscInt particleConsoleOutputFreq
Definition variables.h:931
PetscInt i_periodic
Definition variables.h:1010
Cmpnts periodic_translation[3]
Definition variables.h:1178
@ SOLUTION_CONVERGENCE_PERIODIC_DETERMINISTIC
Definition variables.h:740
@ SOLUTION_CONVERGENCE_STEADY_DETERMINISTIC
Definition variables.h:739
PetscBool periodic_translation_valid[3]
Definition variables.h:1179
SolutionConvergenceMode solutionConvergenceMode
Definition variables.h:981
MomentumSolverType mom_solver_type
Definition variables.h:958
PetscInt immersed
Definition variables.h:950
PetscInt LoggingFrequency
Definition variables.h:1087
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ main()

int main ( int  argc,
char **  argv 
)

Runs the unit-io PETSc test binary.

Definition at line 1197 of file test_io.c.

1198{
1199 PetscErrorCode ierr;
1200 const PicurvTestCase cases[] = {
1201 {"should-write-data-output", TestShouldWriteDataOutput},
1202 {"verify-path-existence", TestVerifyPathExistence},
1203 {"write-and-read-simulation-fields", TestWriteAndReadSimulationFields},
1204 {"boundary-checkpoints-can-be-skipped", TestBoundaryCheckpointsCanBeSkipped},
1205 {"field-payloads-are-transport-independent", TestFieldPayloadsAreTransportIndependent},
1206 {"postprocessor-read-scales-each-load-once", TestPostprocessorReadScalesEachLoadOnce},
1207 {"checkpoint-same-step-rewrite-rejected", TestCheckpointSameStepRewriteIsRejected},
1208 {"display-banner-reports-statistics-cadence", TestDisplayBannerReportsStatisticsCadence},
1209 {"checkpoint-statistics-round-trip", TestCheckpointStatisticsRoundTrip},
1210 {"checkpoint-statistics-continuation-guards", TestCheckpointStatisticsContinuationGuards},
1211 {"checkpoint-statistics-payload-is-validated", TestCheckpointStatisticsPayloadIsValidated},
1212 {"checkpoint-statistics-absent-when-disabled", TestCheckpointStatisticsAbsentWhenDisabled},
1213 {"checkpoint-sha256-known-vector", TestCheckpointSHA256KnownVector},
1214 {"parse-post-processing-settings", TestParsePostProcessingSettings},
1215 {"trim-whitespace", TestTrimWhitespace},
1216 {"bc-string-parsers", TestBoundaryConditionStringParsers},
1217 {"validate-bc-handler-for-type", TestValidateBCHandlerForBCType},
1218 {"parse-scaling-information", TestParseScalingInformation},
1219 {"display-banner-startup-summary", TestDisplayBannerTracksConditionalStartupFields},
1220 };
1221
1222 ierr = PetscInitialize(&argc, &argv, NULL, "PICurv I/O tests");
1223 if (ierr) {
1224 return (int)ierr;
1225 }
1226
1227 ierr = PicurvRunTests("unit-io", cases, sizeof(cases) / sizeof(cases[0]));
1228 if (ierr) {
1229 PetscFinalize();
1230 return (int)ierr;
1231 }
1232
1233 ierr = PetscFinalize();
1234 return (int)ierr;
1235}
static PetscErrorCode TestCheckpointSameStepRewriteIsRejected(void)
Verifies a committed checkpoint step is rewritten neither silently nor inconsistently.
Definition test_io.c:705
static PetscErrorCode TestParseScalingInformation(void)
Tests scaling-reference parsing and derived pressure scaling.
Definition test_io.c:910
static PetscErrorCode TestBoundaryCheckpointsCanBeSkipped(void)
Tests that turned-off boundary checkpoints are skipped while cadence ones are written.
Definition test_io.c:69
static PetscErrorCode TestValidateBCHandlerForBCType(void)
Tests validation of boundary-type and handler compatibility.
Definition test_io.c:893
static PetscErrorCode TestFieldPayloadsAreTransportIndependent(void)
Tests that payloads written through the rank-0 relay load through MPI-IO and back: -viewer_binary_mpi...
Definition test_io.c:199
static PetscErrorCode TestCheckpointStatisticsContinuationGuards(void)
Verifies continuation refuses every state that would corrupt an average.
Definition test_io.c:481
static PetscErrorCode TestPostprocessorReadScalesEachLoadOnce(void)
Tests that a dimensionalizing post-processor scales each loaded field once per load.
Definition test_io.c:214
static PetscErrorCode TestParsePostProcessingSettings(void)
Tests parsing of post-processing control settings from a file.
Definition test_io.c:790
static PetscErrorCode TestCheckpointStatisticsPayloadIsValidated(void)
A damaged statistics payload must fail bundle validation, not load silently.
Definition test_io.c:590
static PetscErrorCode TestCheckpointStatisticsAbsentWhenDisabled(void)
A run without statistics writes no statistics subtree and refuses to fake one.
Definition test_io.c:652
static PetscErrorCode TestCheckpointSHA256KnownVector(void)
Verifies the dependency-free SHA-256 implementation against a standard vector.
Definition test_io.c:771
static PetscErrorCode TestDisplayBannerTracksConditionalStartupFields(void)
Tests conditional startup-banner fields across particle and analytical cases.
Definition test_io.c:1061
static PetscErrorCode TestDisplayBannerReportsStatisticsCadence(void)
Tests that the startup banner reports statistics monitoring in every state.
Definition test_io.c:1016
static PetscErrorCode TestVerifyPathExistence(void)
Tests filesystem existence checks for files and directories.
Definition test_io.c:40
static PetscErrorCode TestTrimWhitespace(void)
Tests trimming of leading and trailing whitespace.
Definition test_io.c:849
static PetscErrorCode TestShouldWriteDataOutput(void)
Tests cadence-based Eulerian output triggering.
Definition test_io.c:23
static PetscErrorCode TestCheckpointStatisticsRoundTrip(void)
Verifies accumulated statistics survive a checkpoint round trip unchanged.
Definition test_io.c:349
static PetscErrorCode TestBoundaryConditionStringParsers(void)
Tests boundary-condition string parsers for face, type, and handler names.
Definition test_io.c:868
static PetscErrorCode TestWriteAndReadSimulationFields(void)
Tests writing and reloading core Eulerian field vectors through MPI-IO.
Definition test_io.c:188
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.
Named test case descriptor consumed by PicurvRunTests.
Here is the call graph for this function: