PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
postprocessor.c
Go to the documentation of this file.
1/**
2 * @file postprocessor.c
3 * @brief Offline post-processing tool driving the derived-output pipelines.
4 *
5 * Reads committed checkpoint bundles over a step range and dispatches the
6 * Eulerian, Lagrangian, particle-statistics, and field-statistics pipelines that
7 * a recipe selected, writing one output family per enabled pipeline.
8 */
9
10#include "postprocessor.h"
12#include "statistics_window.h"
13
14
15/**
16 * @brief Implementation of \ref SetupPostProcessSwarm().
17 * @details Full API contract (arguments, ownership, side effects) is documented with
18 * the header declaration in `include/postprocessor.h`.
19 * @see SetupPostProcessSwarm()
20 */
22{
23 PetscErrorCode ierr;
24 PetscFunctionBeginUser;
26 char *pipeline_copy, *step_token, *step_saveptr;
27 PetscBool finalize_needed = PETSC_FALSE;
28
29 ierr = DMCreate(PETSC_COMM_WORLD, &user->post_swarm); CHKERRQ(ierr);
30 ierr = DMSetType(user->post_swarm, DMSWARM); CHKERRQ(ierr);
31 ierr = DMSetDimension(user->post_swarm, 3); CHKERRQ(ierr);
32 ierr = DMSwarmSetType(user->post_swarm, DMSWARM_BASIC); CHKERRQ(ierr);
33 // Associate it with the same grid as the solver's swarm
34 if (user->da) {
35 ierr = DMSwarmSetCellDM(user->post_swarm, user->da); CHKERRQ(ierr);
36 LOG_ALLOW(LOCAL,LOG_INFO,"Associated DMSwarm with Cell DM (user->da).\n");
37 } else {
38 // If user->da is essential for your simulation logic with particles, this should be a fatal error.
39 LOG_ALLOW(GLOBAL, LOG_WARNING, "user->da (Cell DM for Swarm) is NULL. Cell-based swarm operations might fail.\n");
40 // SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "CreateParticleSwarm - user->da (Cell DM) is NULL but required.");
41 }
42
43 LOG_ALLOW(GLOBAL, LOG_INFO, "Created dedicated DMSwarm for post-processing.\n");
44
45 LOG_ALLOW(GLOBAL, LOG_DEBUG, " --- Setting up Post-Processing Pipeline fields-- \n");
46
47 ierr = PetscStrallocpy(pps->particle_pipeline, &pipeline_copy); CHKERRQ(ierr);
48 step_token = strtok_r(pipeline_copy, ";", &step_saveptr);
49 while (step_token) {
50 TrimWhitespace(step_token);
51 if (strlen(step_token) == 0) { step_token = strtok_r(NULL, ";", &step_saveptr); continue; }
52
53 char *keyword = strtok(step_token, ":");
54 char *args_str = strtok(NULL, "");
55 TrimWhitespace(keyword);
56 PetscInt output_field_dimensions = 1; // Default to scalar output fields
57
58 if (strcasecmp(keyword, "ComputeSpecificKE") == 0) {
59 if (!args_str) SETERRQ(PETSC_COMM_SELF, 1, "Error (ComputeSpecificKE): Missing arguments.");
60 char *input_field = strtok(args_str, ">");
61 char *output_field = strtok(NULL, ">");
62 output_field_dimensions = 1; // SKE is scalar
63 if (!input_field) SETERRQ(PETSC_COMM_SELF, 1, "Error (ComputeSpecificKE): Missing input field in 'in>out' syntax.");
64 if (!output_field) SETERRQ(PETSC_COMM_SELF, 1, "Error (ComputeSpecificKE): Missing output field in 'in>out' syntax.");
65 TrimWhitespace(input_field);
66 TrimWhitespace(output_field);
67 if (strlen(input_field) == 0) SETERRQ(PETSC_COMM_SELF, 1, "Error (ComputeSpecificKE): Empty input field name.");
68 if (strlen(output_field) == 0) SETERRQ(PETSC_COMM_SELF, 1, "Error (ComputeSpecificKE): Empty output field name.");
69 // Register the output field
70 ierr = RegisterSwarmField(user->post_swarm, output_field, output_field_dimensions,PETSC_REAL); CHKERRQ(ierr);
71 LOG_ALLOW(GLOBAL, LOG_INFO, "Registered particle field '%s' (ComputeSpecificKE input='%s').\n", output_field, input_field);
72 finalize_needed = PETSC_TRUE;
73 } else {
74 LOG_ALLOW(GLOBAL, LOG_WARNING, "Warning: Unknown particle transformation keyword '%s'. Skipping.\n", keyword);
75 }
76
77 // Add other 'else if' blocks here for other kernels that create output fields
78
79 step_token = strtok_r(NULL, ";", &step_saveptr);
80 } // while step_token
81
82 ierr = PetscFree(pipeline_copy); CHKERRQ(ierr);
83
84 // --- FINALIZE STEP ---
85 if (finalize_needed) {
86 LOG_ALLOW(GLOBAL, LOG_INFO, "Finalizing registered particle fields for the post-processing swarm.\n");
87 } else {
88 LOG_ALLOW(GLOBAL, LOG_INFO, "No custom particle fields requested; finalizing an empty post-processing swarm for safe use.\n");
89 }
90 ierr = DMSwarmFinalizeFieldRegister(user->post_swarm); CHKERRQ(ierr);
91
92 LOG_ALLOW(GLOBAL, LOG_INFO, "Post-Processing DMSwarm setup complete.\n");
93
95 PetscFunctionReturn(0);
96}
97
98
99/**
100 * @brief Implementation of \ref EulerianDataProcessingPipeline().
101 * @details Full API contract (arguments, ownership, side effects) is documented with
102 * the header declaration in `include/postprocessor.h`.
103 * @see EulerianDataProcessingPipeline()
104 */
106{
107 PetscErrorCode ierr;
108 char *pipeline_copy, *step_token, *step_saveptr;
109
110 PetscFunctionBeginUser;
112 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting Data Transformation Pipeline ---\n");
113
114 // Do nothing if the pipeline string is empty
115 if (pps->process_pipeline[0] == '\0') {
116 LOG_ALLOW(GLOBAL, LOG_INFO, "Processing pipeline is empty. No transformations will be run.\n");
118 PetscFunctionReturn(0);
119 }
120
121 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Pipeline string: [%s]\n", pps->process_pipeline);
122
123 // Make a writable copy for strtok_r, as it modifies the string
124 ierr = PetscStrallocpy(pps->process_pipeline, &pipeline_copy); CHKERRQ(ierr);
125
126 // --- Outer Loop: Tokenize by Semicolon (;) to get each processing step ---
127 step_token = strtok_r(pipeline_copy, ";", &step_saveptr);
128 while (step_token) {
129 TrimWhitespace(step_token);
130 if (strlen(step_token) == 0) {
131 step_token = strtok_r(NULL, ";", &step_saveptr);
132 continue;
133 }
134
135 char *keyword = strtok(step_token, ":");
136 char *args_str = strtok(NULL, ""); // Get the rest of the string as arguments
137
138 if (!keyword) { // Should not happen with TrimWhitespace, but is a safe check
139 step_token = strtok_r(NULL, ";", &step_saveptr);
140 continue;
141 }
142
143 TrimWhitespace(keyword);
144 if (args_str) TrimWhitespace(args_str);
145
146 LOG_ALLOW(GLOBAL, LOG_INFO, "Executing Transformation: '%s' on args: '%s'\n", keyword, args_str ? args_str : "None");
147
148 // --- DISPATCHER: Route to the correct kernel based on the keyword ---
149 if (strcasecmp(keyword, "CellToNodeAverage") == 0) {
150 if (!args_str) SETERRQ(PETSC_COMM_SELF, 1, "CellToNodeAverage requires arguments in 'in_field>out_field' format.");
151 char *in_field = strtok(args_str, ">");
152 char *out_field = strtok(NULL, ">");
153 if (!in_field || !out_field) SETERRQ(PETSC_COMM_SELF, 1, "CellToNodeAverage requires 'in>out' syntax (e.g., P>P_nodal).");
154 if(strcmp(in_field,out_field)==0) SETERRQ(PETSC_COMM_SELF, 1, "CellToNodeAverage input and output fields must be different.");
155 if(!ParticlesEnabled(user->simCtx) && (strcmp(out_field,"Psi_nodal")==0 || strcmp(in_field,"Psi_nodal")==0)){
156 LOG(GLOBAL,LOG_WARNING,"CellToNodeAverage cannot process 'Psi_nodal' when no particles are present in the simulation.\n");
157 step_token = strtok_r(NULL, ";", &step_saveptr);
158 continue;
159 }
160 TrimWhitespace(in_field); TrimWhitespace(out_field);
161 ierr = ComputeNodalAverage(user, in_field, out_field); CHKERRQ(ierr);
162 }
163 else if (strcasecmp(keyword, "ComputeQCriterion") == 0) {
164 ierr = ComputeQCriterion(user); CHKERRQ(ierr);
165 }
166 else if (strcasecmp(keyword, "DimensionalizeAllLoadedFields") == 0) {
167 /* Accepted and does nothing: loaded fields are scaled as they are read, the only
168 * point that knows which fields a step loaded, so scaling them here would scale
169 * them twice. Locked recipes may still carry the token. */
170 }
171 else if (strcasecmp(keyword, "NormalizeRelativeField") == 0) {
172 if (!args_str) SETERRQ(PETSC_COMM_SELF, 1, "NormalizePressure requires the pressure field name (e.g., 'P') as an argument.");
173 ierr = NormalizeRelativeField(user, args_str); CHKERRQ(ierr);
174 }
175 // *** Add new kernels here in the future using 'else if' ***
176 // else if (strcasecmp(keyword, "ComputeVorticity") == 0) { ... }
177 else {
178 LOG_ALLOW(GLOBAL, LOG_WARNING, "Unknown transformation keyword '%s'. Skipping.\n", keyword);
179 }
180
181 step_token = strtok_r(NULL, ";", &step_saveptr);
182 }
183
184 ierr = PetscFree(pipeline_copy); CHKERRQ(ierr);
185 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Data Transformation Pipeline Complete ---\n");
187 PetscFunctionReturn(0);
188}
189
190
191/**
192 * @brief Implementation of \ref WriteEulerianFile().
193 * @details Full API contract (arguments, ownership, side effects) is documented with
194 * the header declaration in `include/postprocessor.h`.
195 * @see WriteEulerianFile()
196 */
197PetscErrorCode WriteEulerianFile(UserCtx* user, PostProcessParams* pps, PetscInt ti)
198{
199 PetscErrorCode ierr;
200 VTKMetaData meta;
201 char filename[MAX_FILENAME_LENGTH];
202
203 PetscFunctionBeginUser;
205
206 if (pps->output_fields_instantaneous[0] == '\0') {
207 LOG_ALLOW(GLOBAL, LOG_DEBUG, "No instantaneous fields requested for output at ti=%" PetscInt_FMT ". Skipping.\n", ti);
209 PetscFunctionReturn(0);
210 }
211
212 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting VTK File Writing for ti = %" PetscInt_FMT " ---\n", ti);
213
214 /* 1) Metadata init */
215 /* 2) Metadata and coordinates, through the shared assembly the statistics
216 * stage also uses, so both producers build a file the same way. */
217 ierr = BeginStructuredVTKOutput(user, &meta); CHKERRQ(ierr);
218 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Using coords linearization order: fast=i mid=j slow=k (sizes: %" PetscInt_FMT " x %" PetscInt_FMT " x %" PetscInt_FMT ")\n",
219 meta.mx, meta.my, meta.mz);
220
221 /* 3) Field preparation is collective because each append gathers a
222 * distributed Vec. Rank zero alone owns the packed output buffers, but
223 * every rank must resolve the same field list and enter each append. */
224 {
225 char *fields_copy, *field_name;
226 ierr = PetscStrallocpy(pps->output_fields_instantaneous, &fields_copy); CHKERRQ(ierr);
227
228 field_name = strtok(fields_copy, ",");
229 while (field_name) {
230 TrimWhitespace(field_name);
231 if (!*field_name) { field_name = strtok(NULL, ","); continue; }
232
233 LOG_ALLOW(LOCAL, LOG_DEBUG, "Preparing field '%s' for output.\n", field_name);
234
235 Vec field_vec = NULL;
236 PetscInt num_components = 0;
237
238 if (!strcasecmp(field_name, "P_nodal")) {
239 field_vec = user->P_nodal; num_components = 1;
240 } else if (!strcasecmp(field_name, "Ucat_nodal")) {
241 field_vec = user->Ucat_nodal; num_components = 3;
242 } else if (!strcasecmp(field_name, "Qcrit_nodal")) {
243 field_vec = user->Qcrit_nodal; num_components = 1;
244 } else if (!strcasecmp(field_name, "Qcrit")) {
245 /* Qcrit is cell-centred; written as point data it would sit half a cell
246 from the node the file assigns it. The conductor refuses this too. */
247 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
248 "Field 'Qcrit' is cell-centred and cannot be written as point data. "
249 "Add a nodal_average task (input_field: Qcrit, output_field: Qcrit_nodal) and write 'Qcrit_nodal'.");
250 } else if (!strcasecmp(field_name, "Psi_nodal")){
251 if(!ParticlesEnabled(user->simCtx)){
252 LOG_ALLOW(LOCAL, LOG_WARNING, "Field 'Psi_nodal' requested but no particles are present. Skipping.\n");
253 field_name = strtok(NULL, ",");
254 continue;
255 }
256 field_vec = user->Psi_nodal; num_components = 1;
257 } else {
258 LOG_ALLOW(LOCAL, LOG_WARNING, "Field '%s' not recognized. Skipping.\n", field_name);
259 field_name = strtok(NULL, ",");
260 continue;
261 }
262
263 // --- Add field to metadata ---
264 ierr = AppendStructuredVTKField(user, &meta, field_name, field_vec, num_components); CHKERRQ(ierr);
265
266
267 field_name = strtok(NULL, ",");
268 }
269
270 ierr = PetscFree(fields_copy); CHKERRQ(ierr);
271
272
273 if (user->simCtx->rank == 0) {
274 /* Field summary */
275 LOG_ALLOW(GLOBAL, LOG_INFO, "PointData fields to write: %d\n", (int)meta.num_point_data_fields);
276 for (PetscInt ii=0; ii<meta.num_point_data_fields; ++ii) {
277 LOG_ALLOW(GLOBAL, LOG_INFO, " # %2" PetscInt_FMT " Field Name = %s Components = %d\n",
278 ii, meta.point_data_fields[ii].name, (int)meta.point_data_fields[ii].num_components);
279 }
280 }
281 }
282
283 /* 4) Write the VTS */
284 ierr = PetscSNPrintf(filename, sizeof(filename), "%s_%05" PetscInt_FMT ".vts", pps->output_prefix, ti); CHKERRQ(ierr);
285 ierr = FinishStructuredVTKOutput(&meta, filename); CHKERRQ(ierr);
286
287 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Eulerian File Writing for ti = %" PetscInt_FMT " Complete ---\n", ti);
289 PetscFunctionReturn(0);
290}
291
292
293/**
294 * @brief Writes one window's or ensemble's derived output for a step.
295 * @details Local to this translation unit. The `.vts` carries every requested output
296 * pointwise; with `csv` and homogeneous directions selected, a profile CSV
297 * carries them merged over those directions.
298 */
299static PetscErrorCode WriteWindowStatistics(UserCtx *user, PostProcessParams *pps,
300 const PicurvWindowDefinition *definition,
301 const PicurvWindowStorage *storage,
302 PetscBool want_vtk, PetscBool want_csv, PetscInt ti)
303{
304 PetscFunctionBeginUser;
306 if (want_vtk) {
307 VTKMetaData meta;
308 PetscInt derived_count = 0;
309 char filename[PETSC_MAX_PATH_LEN];
310
311 PetscCall(PicurvWindowDerivedCount(definition, storage, pps->field_statistics_outputs, &derived_count));
312 /* An output kind resolves against what the window accumulated, so asking
313 * for stresses from a means-only window yields nothing. Report it the way
314 * an unrecognized Eulerian output field is reported, rather than writing a
315 * quietly short file. */
316 if (derived_count == 0) {
318 "Outputs '%s' produce no field for window '%s'; it accumulates none of "
319 "the state they need. Skipping.\n",
320 pps->field_statistics_outputs, definition->name);
321 }
322 /* One file per window. The point-data cap is per file, and a single
323 * window with every output already fills most of it. */
324 PetscCall(BeginStructuredVTKOutput(user, &meta));
325 for (PetscInt index = 0; index < derived_count; ++index) {
326 char name[MAX_VTK_FIELD_NAME_LENGTH];
327 Vec nodal = NULL;
328 PetscInt components = 0;
329
330 PetscCall(ComputeWindowStatisticNodal(user, definition, storage, pps->field_statistics_outputs,
331 index, name, sizeof(name), &nodal, &components));
332 /* The staging vector is reused for the next field, which is safe
333 * because appending copies the values out. */
334 PetscCall(AppendStructuredVTKField(user, &meta, name, nodal, components));
335 }
336 PetscCall(PetscSNPrintf(filename, sizeof(filename), "%s_statistics_%s_%05" PetscInt_FMT ".vts",
337 pps->output_prefix, definition->name, ti));
338 LOG_ALLOW(GLOBAL, LOG_INFO, "Wrote %d derived field(s) for window '%s' to %s\n",
339 (int)meta.num_point_data_fields, definition->name, filename);
340 PetscCall(FinishStructuredVTKOutput(&meta, filename));
341 }
342 if (want_csv && (pps->field_statistics_homogeneous[0] || pps->field_statistics_homogeneous[1] ||
344 PetscCall(ComputeWindowStatisticsProfile(user, definition, storage, pps->field_statistics_outputs,
347 }
349 PetscFunctionReturn(0);
350}
351
352/**
353 * @brief Fills one recipe ensemble's storage from the loaded step.
354 * @details Local to this translation unit. A particle ensemble takes each cell's
355 * particles as its samples; an Eulerian one takes the cell's own state as its
356 * single sample, which is one accepted state of unit weight. A dimensionalized
357 * post run has already scaled what it loaded, so the storage is marked as
358 * holding physical units and derivation applies no further scale.
359 */
360static PetscErrorCode FillStatisticsEnsemble(UserCtx *user, PostProcessParams *pps, PetscInt index,
361 PicurvWindowStorage *storage)
362{
363 const PicurvWindowDefinition *definition = &pps->field_statistics_ensembles[index].definition;
364
365 PetscFunctionBeginUser;
368 PetscCall(PicurvWindowStorageFromParticles(user, definition, storage));
369 } else {
370 PetscCall(PicurvWindowAccumulate(user, definition, storage, 1.0));
371 }
372 storage->physical_units = pps->dimensionalize;
374 PetscFunctionReturn(0);
375}
376
377/**
378 * @brief Implementation of \ref FieldStatisticsPipeline().
379 * @details Full API contract (arguments, ownership, side effects) is documented with
380 * the header declaration in `include/postprocessor.h`.
381 * @see FieldStatisticsPipeline()
382 */
383PetscErrorCode FieldStatisticsPipeline(UserCtx *user, PostProcessParams *pps, PetscInt ti)
384{
385 PetscErrorCode ierr;
386 SimCtx *simCtx = NULL;
387 char *windows_copy = NULL;
388 char *window_name = NULL;
389 PetscInt source_step = 0;
390 PetscBool want_vtk = PETSC_FALSE, want_csv = PETSC_FALSE;
391
392 PetscFunctionBeginUser;
394 if (pps->field_statistics_windows[0] == '\0' && pps->field_statistics_ensemble_count == 0) {
395 PROFILE_FUNCTION_END; PetscFunctionReturn(0);
396 }
397 simCtx = user->simCtx;
398
399 {
400 char formats[MAX_FIELD_LIST_LENGTH];
401 char *token = NULL;
402
403 ierr = PetscStrncpy(formats, pps->field_statistics_formats, sizeof(formats)); CHKERRQ(ierr);
404 token = strtok(formats, ",");
405 while (token) {
406 TrimWhitespace(token);
407 if (!strcasecmp(token, "vtk")) want_vtk = PETSC_TRUE;
408 else if (!strcasecmp(token, "csv")) want_csv = PETSC_TRUE;
410 "Unknown field-statistics format '%s'. Known formats are vtk and csv.\n", token);
411 token = strtok(NULL, ",");
412 }
413 }
414 if (!want_vtk && !want_csv) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
415
416 if (pps->field_statistics_windows[0] != '\0') {
417 PetscCheck(FieldStatisticsIsActive(simCtx), PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE,
418 "Field-statistics post-processing was requested, but the run's control configures "
419 "no statistics window.");
420 /* An explicit source step pins every processed step to one bundle; otherwise each
421 * step derives from its own, which is what turns a multi-step recipe into a
422 * convergence history rather than the same picture repeated. */
423 source_step = (pps->field_statistics_source_step >= 0) ? pps->field_statistics_source_step : ti;
424
425 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting Field Statistics Pipeline (step %" PetscInt_FMT ") ---\n",
426 source_step);
427 simCtx->fieldStatisticsContinue = PETSC_TRUE;
428 ierr = RestoreFieldStatisticsState(simCtx, source_step); CHKERRQ(ierr);
429
430 ierr = PetscStrallocpy(pps->field_statistics_windows, &windows_copy); CHKERRQ(ierr);
431 window_name = strtok(windows_copy, ",");
432 while (window_name) {
433 PetscInt window_index = -1;
434 const PicurvWindow *window = NULL;
435
436 TrimWhitespace(window_name);
437 if (!*window_name) { window_name = strtok(NULL, ","); continue; }
438
439 for (PetscInt w = 0; w < simCtx->fieldStatisticsWindowCount; ++w) {
440 PetscBool matches = PETSC_FALSE;
441
442 ierr = PetscStrcmp(simCtx->fieldStatisticsWindows[w].definition.name,
443 window_name, &matches); CHKERRQ(ierr);
444 if (matches) { window_index = w; break; }
445 }
446 if (window_index < 0) {
447 ierr = PetscFree(windows_copy); CHKERRQ(ierr);
448 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG,
449 "Field-statistics post-processing requested window '%s', which this run does "
450 "not configure.", window_name);
451 }
452 window = &simCtx->fieldStatisticsWindows[window_index];
453
454 /* A window that has not started by this step is not an error: a recipe
455 * spanning a whole run legitimately reaches bundles from before it began. */
456 if (window->sample_count <= 0) {
458 "Statistics window '%s' had accumulated no sample by step %" PetscInt_FMT
459 "; nothing to derive yet.\n", window->definition.name, source_step);
460 window_name = strtok(NULL, ",");
461 continue;
462 }
463
464 ierr = WriteWindowStatistics(user, pps, &window->definition, &user->fieldStatisticsStorage[window_index],
465 want_vtk, want_csv, ti); CHKERRQ(ierr);
466 if (want_csv) {
467 ierr = ComputeWindowStatisticsSummary(user, window_index,
469 ti); CHKERRQ(ierr);
470 }
471
472 window_name = strtok(NULL, ",");
473 }
474 ierr = PetscFree(windows_copy); CHKERRQ(ierr);
475 }
476
477 /* Recipe ensembles are built from the step just loaded, so they need no bundle. */
478 for (PetscInt index = 0; index < pps->field_statistics_ensemble_count; ++index) {
479 const PicurvWindowDefinition *definition = &pps->field_statistics_ensembles[index].definition;
480 PicurvWindowStorage storage;
481
482 ierr = PicurvWindowStorageCreate(user, definition, &storage); CHKERRQ(ierr);
483 ierr = FillStatisticsEnsemble(user, pps, index, &storage); CHKERRQ(ierr);
484 ierr = WriteWindowStatistics(user, pps, definition, &storage, want_vtk, want_csv, ti); CHKERRQ(ierr);
485 ierr = PicurvWindowStorageDestroy(&storage); CHKERRQ(ierr);
486 }
487
488 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Field Statistics Pipeline Complete ---\n");
490 PetscFunctionReturn(0);
491}
492
493/**
494 * @brief Implementation of \ref ParticleDataProcessingPipeline().
495 * @details Full API contract (arguments, ownership, side effects) is documented with
496 * the header declaration in `include/postprocessor.h`.
497 * @see ParticleDataProcessingPipeline()
498 */
500{
501 PetscErrorCode ierr;
502 char *pipeline_copy, *step_token, *step_saveptr;
503
504 PetscFunctionBeginUser;
505
507
508 if (pps->particle_pipeline[0] == '\0') {
510 PetscFunctionReturn(0);
511 }
512
513 // --- Timestep Setup: Synchronize post_swarm size ---
514 PetscInt n_local_source;
515 ierr = DMSwarmGetLocalSize(user->swarm, &n_local_source); CHKERRQ(ierr);
516
517 // Derived entries use the same local index as their source particle.
518 ierr = DMSwarmSetLocalSizes(user->post_swarm, n_local_source, -1); CHKERRQ(ierr);
519
520 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting Particle Data Transformation Pipeline ---\n");
521 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Particle Pipeline string: [%s]\n", pps->particle_pipeline);
522
523 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Executing compute kernels...\n");
524 ierr = PetscStrallocpy(pps->particle_pipeline, &pipeline_copy); CHKERRQ(ierr);
525 step_token = strtok_r(pipeline_copy, ";", &step_saveptr);
526 while (step_token) {
527 TrimWhitespace(step_token);
528 if (strlen(step_token) == 0) { step_token = strtok_r(NULL, ";", &step_saveptr); continue; }
529
530 char *keyword = strtok(step_token, ":");
531 char *args_str = strtok(NULL, "");
532 TrimWhitespace(keyword);
533 if (args_str) TrimWhitespace(args_str);
534
535 LOG_ALLOW(GLOBAL, LOG_INFO, "Executing Particle Transformation: '%s' on args: '%s'\n", keyword, args_str ? args_str : "None");
536
537 if (strcasecmp(keyword, "ComputeSpecificKE") == 0) {
538 if (!args_str) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "ComputeSpecificKE requires 'input_field>output_field' arguments.");
539 char *velocity_field = strtok(args_str, ">");
540 char *ske_field = strtok(NULL, ">");
541 if (!velocity_field || !ske_field) {
542 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "ComputeSpecificKE requires 'input_field>output_field' arguments.");
543 }
544 TrimWhitespace(velocity_field); TrimWhitespace(ske_field);
545 if (strlen(velocity_field) == 0 || strlen(ske_field) == 0) {
546 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "ComputeSpecificKE does not allow empty input/output field names.");
547 }
548
549 ierr = ComputeSpecificKE(user, velocity_field, ske_field); CHKERRQ(ierr);
550 }
551 else {
552 LOG_ALLOW(GLOBAL, LOG_WARNING, "Unknown particle transformation keyword '%s'. Skipping.\n", keyword);
553 }
554
555 step_token = strtok_r(NULL, ";", &step_saveptr);
556 }
557 ierr = PetscFree(pipeline_copy); CHKERRQ(ierr);
558
559 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Particle Data Transformation Pipeline Complete ---\n");
560
562 PetscFunctionReturn(0);
563}
564
565/**
566 * @brief Implementation of \ref GlobalStatisticsPipeline().
567 * @details Full API contract (arguments, ownership, side effects) is documented with
568 * the header declaration in `include/postprocessor.h`.
569 * @see GlobalStatisticsPipeline()
570 */
571PetscErrorCode GlobalStatisticsPipeline(UserCtx *user, PostProcessParams *pps, PetscInt ti)
572{
573 PetscErrorCode ierr;
574 char *pipeline_copy, *step_token, *step_saveptr;
575
576 PetscFunctionBeginUser;
578
579 if (pps->statistics_pipeline[0] == '\0') { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
580
581 PetscInt n_global;
582 ierr = DMSwarmGetSize(user->swarm, &n_global); CHKERRQ(ierr);
583 if (n_global == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
584
585 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting Global Statistics Pipeline ---\n");
586
587 ierr = PetscStrallocpy(pps->statistics_pipeline, &pipeline_copy); CHKERRQ(ierr);
588 step_token = strtok_r(pipeline_copy, ";", &step_saveptr);
589 while (step_token) {
590 TrimWhitespace(step_token);
591 if (strlen(step_token) == 0) {
592 step_token = strtok_r(NULL, ";", &step_saveptr); continue;
593 }
594 char *keyword = strtok(step_token, ":");
595 TrimWhitespace(keyword);
596
597 if (strcasecmp(keyword, "ComputeMSD") == 0) {
598 ierr = ComputeParticleMSD(user, pps->statistics_output_prefix, ti); CHKERRQ(ierr);
599 } else {
601 "Unknown statistics keyword '%s'. Skipping.\n", keyword);
602 }
603 /* Additional kernels should add else-if branches here when implemented. */
604
605 step_token = strtok_r(NULL, ";", &step_saveptr);
606 }
607 ierr = PetscFree(pipeline_copy); CHKERRQ(ierr);
608
609 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Global Statistics Pipeline Complete ---\n");
611 PetscFunctionReturn(0);
612}
613
614/**
615 * @brief Implementation of \ref WriteParticleFile().
616 * @details Full API contract (arguments, ownership, side effects) is documented with
617 * the header declaration in `include/postprocessor.h`.
618 * @see WriteParticleFile()
619 */
620PetscErrorCode WriteParticleFile(UserCtx* user, PostProcessParams* pps, PetscInt ti)
621{
622 PetscErrorCode ierr;
623 VTKMetaData part_meta;
624 char filename[MAX_FILENAME_LENGTH];
625 PetscInt n_total_particles_before_subsample;
626
627 PetscFunctionBeginUser;
629
630 // These checks can be done on all ranks
631 if (!pps->outputParticles || pps->particle_fields[0] == '\0') {
633 PetscFunctionReturn(0);
634 }
635 ierr = PetscMemzero(&part_meta, sizeof(VTKMetaData)); CHKERRQ(ierr);
636
637 // --- 1. PREPARE (Collective Call); an empty swarm allocates nothing and writes no file ---
638 ierr = PrepareOutputParticleData(user, pps, &part_meta, &n_total_particles_before_subsample); CHKERRQ(ierr);
639 if (n_total_particles_before_subsample == 0) {
640 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Swarm is empty for ti=%" PetscInt_FMT ". Skipping particle file write.\n", ti);
642 PetscFunctionReturn(0);
643 }
644
645 // --- 2. WRITE (Collective) and CLEANUP ---
646 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Starting VTP Particle File Writing for ti = %" PetscInt_FMT " (writing %" PetscInt_FMT " of %" PetscInt_FMT " particles) ---\n",
647 ti, part_meta.npoints, n_total_particles_before_subsample);
648 LOG_ALLOW(GLOBAL, LOG_INFO, "Particle Data fields to write: %d\n", (int)part_meta.num_point_data_fields);
649 for (PetscInt ii=0; ii<part_meta.num_point_data_fields; ++ii) {
650 LOG_ALLOW(GLOBAL, LOG_INFO, " # %2" PetscInt_FMT " Field Name = %s Components = %d\n",
651 ii, part_meta.point_data_fields[ii].name, (int)part_meta.point_data_fields[ii].num_components);
652 }
653 ierr = PetscSNPrintf(filename, sizeof(filename), "%s_%05" PetscInt_FMT ".vtp", pps->particle_output_prefix, ti); CHKERRQ(ierr);
654 ierr = CreateVTKFileFromMetadata(filename, &part_meta, PETSC_COMM_WORLD); CHKERRQ(ierr);
655
656 for (PetscInt field = 0; field < part_meta.num_point_data_fields; ++field) {
657 ierr = PetscFree(part_meta.point_data_fields[field].data); CHKERRQ(ierr);
658 }
659 ierr = PetscFree(part_meta.coords); CHKERRQ(ierr);
660 ierr = PetscFree(part_meta.connectivity); CHKERRQ(ierr);
661 ierr = PetscFree(part_meta.offsets); CHKERRQ(ierr);
662
663 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Particle File Writing for ti = %" PetscInt_FMT " Complete ---\n", ti);
665 PetscFunctionReturn(0);
666}
667
668/**
669 * @brief Implementation of \ref ResolvePostProcessingSteps().
670 * @details Full API contract (arguments, ownership, side effects) is documented with
671 * the header declaration in `include/postprocessor.h`.
672 * @see ResolvePostProcessingSteps()
673 */
674PetscErrorCode ResolvePostProcessingSteps(PostProcessParams *pps, PetscInt **steps, PetscInt *count)
675{
676 PetscMPIInt rank;
677
678 PetscFunctionBeginUser;
680 *steps = NULL;
681 *count = 0;
682 if (pps->step_list_file[0] == '\0') {
683 PetscInt n = (pps->endTime >= pps->startTime) ? (pps->endTime - pps->startTime) / pps->timeStep + 1 : 0;
684 PetscCall(PetscMalloc1(n > 0 ? n : 1, steps));
685 for (PetscInt k = 0; k < n; ++k) (*steps)[k] = pps->startTime + k * pps->timeStep;
686 *count = n;
688 PetscFunctionReturn(0);
689 }
690
691 rank = PetscGlobalRank;
692 /* Rank 0 reads; a failure is broadcast as a negative count so every rank stops
693 together instead of the others waiting in the broadcast. */
694 PetscInt n = 0, capacity = 0;
695 PetscInt *list = NULL;
696 char bad_line[256] = "";
697 if (rank == 0) {
698 char line[256];
699 FILE *file = fopen(pps->step_list_file, "r");
700 if (!file) n = -1;
701 while (file && n >= 0 && fgets(line, sizeof(line), file)) {
702 char *end = NULL;
703 long value;
704 TrimWhitespace(line);
705 if (line[0] == '\0' || line[0] == '#') continue;
706 value = strtol(line, &end, 10);
707 if (end == line || *end != '\0') {
708 PetscCall(PetscStrncpy(bad_line, line, sizeof(bad_line)));
709 n = -2;
710 break;
711 }
712 if (n == capacity) {
713 PetscInt *grown = NULL;
714 capacity = capacity ? 2 * capacity : 64;
715 PetscCall(PetscMalloc1(capacity, &grown));
716 if (n) PetscCall(PetscArraycpy(grown, list, n));
717 PetscCall(PetscFree(list));
718 list = grown;
719 }
720 list[n++] = (PetscInt)value;
721 }
722 if (file) fclose(file);
723 }
724 PetscCallMPI(MPI_Bcast(&n, 1, MPIU_INT, 0, PETSC_COMM_WORLD));
725 if (n < 0) {
726 PetscCall(PetscFree(list));
727 PetscCheck(n != -1, PETSC_COMM_WORLD, PETSC_ERR_FILE_OPEN,
728 "Step list file '%s' is missing. It is written when picurv launches the post "
729 "stage; launch post-processing through picurv.", pps->step_list_file);
730 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_FILE_UNEXPECTED,
731 "Step list file '%s' has a non-integer line '%s'.", pps->step_list_file, bad_line);
732 }
733 if (rank != 0) PetscCall(PetscMalloc1(n > 0 ? n : 1, &list));
734 if (n > 0) PetscCallMPI(MPI_Bcast(list, (PetscMPIInt)n, MPIU_INT, 0, PETSC_COMM_WORLD));
735 *steps = list;
736 *count = n;
738 PetscFunctionReturn(0);
739}
740
741#ifndef PICURV_POSTPROCESSOR_NO_MAIN
742/**
743 * @brief Entry point for the postprocessor executable.
744 * @details Initializes PETSc, loads post-processing inputs, executes the
745 * requested pipelines, and finalizes runtime resources before exit.
746 */
747int main(int argc, char **argv)
748{
749 PetscErrorCode ierr;
750 SimCtx *simCtx = NULL;
751
752 if (PicurvHandleVersionArgument(argc, argv, "postprocessor")) return 0;
753 if (PicurvCheckLinkedPetscIndexWidth(argc, argv, "postprocessor")) return 1;
754 // === I. INITIALIZE PETSC & MPI ===========================================
755 ierr = PetscInitialize(&argc, &argv, (char *)0, "Unified Post-Processing Tool"); CHKERRQ(ierr);
756
757 // === II. CONFIGURE SIMULATION & POST-PROCESSING CONTEXTS =================
758 ierr = CreateSimulationContext(argc, argv, &simCtx); CHKERRQ(ierr);
759 ierr = PetscPrintf(PETSC_COMM_WORLD, "Postprocessor MPI processes: %d\n", (int)simCtx->size); CHKERRQ(ierr);
760 // === IIB. SET EXECUTION MODE (SOLVER vs POST-PROCESSOR) =====
762 // == IIC. CONFIGURE SIMULATION ENVIRONMENT & DIRECTORIES =====
763 ierr = SetupSimulationEnvironment(simCtx); CHKERRQ(ierr);
764 // === III. SETUP GRID & DATA STRUCTURES ===================================
765 ierr = SetupGridAndSolvers(simCtx); CHKERRQ(ierr);
766 // === IV. SETUP DOMAIN DECOMPOSITION INFORMATION =========================
767 ierr = SetupDomainRankInfo(simCtx); CHKERRQ(ierr);
768 // === V. SETUP BOUNDARY CONDITIONS ====================================
769 ierr = SetupBoundaryConditions(simCtx); CHKERRQ(ierr);
770 // === VI. SETUP USER CONTEXT & DATA STRUCTURES ============================
771 // Get the finest-level user context, as this is where we'll load data
772 UserCtx *user = simCtx->usermg.mgctx[simCtx->usermg.mglevels-1].user;
773 PostProcessParams *pps = simCtx->pps;
774
775 // === VI. CAPABILITY DISPATCH ============================================
776 // Each stage declares what it needs rather than inferring it from another
777 // stage's configuration. Field statistics are Eulerian and must not require a
778 // swarm: a turbulence run normally carries no particles at all.
779 PetscBool needs_particle_ensembles = PETSC_FALSE;
780 for (PetscInt index = 0; index < pps->field_statistics_ensemble_count; ++index) {
781 if (pps->field_statistics_ensemble_from_particles[index]) needs_particle_ensembles = PETSC_TRUE;
782 }
783 PetscBool needs_particle_stage = (pps->outputParticles || pps->particle_pipeline[0] != '\0' || pps->statistics_pipeline[0] != '\0' || needs_particle_ensembles) ? PETSC_TRUE : PETSC_FALSE;
784 if(needs_particle_stage) {
785 if(ParticlesEnabled(simCtx)){
786 ierr = InitializeParticleSwarm(simCtx); CHKERRQ(ierr);
787 // Create a post-processing specific DMSwarm
788 ierr = SetupPostProcessSwarm(user,pps); CHKERRQ(ierr);
789 }else{
790 SETERRQ(PETSC_COMM_SELF,1,
791 "Particle post-processing requested (particle output, a particle statistics pipeline, "
792 "or a particle statistics ensemble) "
793 "but np=0. Please set np>0 during solver run to enable particle post-processing.");
794 }
795 }
796
797 LOG_ALLOW(GLOBAL, LOG_INFO, "=============================================================\n");
798
799
800 // The grid is loaded once, so it is dimensionalized once; the per-step pipeline
801 // scales only the fields it reloads.
802 PetscBool coordinates_dimensionalized = PETSC_FALSE;
803
804 // === VII. MAIN POST-PROCESSING LOOP ======================================
805 PetscInt *steps = NULL, step_count = 0;
806 ierr = ResolvePostProcessingSteps(pps, &steps, &step_count); CHKERRQ(ierr);
807 LOG_ALLOW(GLOBAL, LOG_INFO, "Processing %" PetscInt_FMT " step(s).\n", step_count);
808 for (PetscInt k = 0; k < step_count; ++k) {
809 const PetscInt ti = steps[k];
810 LOG_ALLOW(GLOBAL, LOG_INFO, "--- Processing Time Step %" PetscInt_FMT " ---\n", ti);
811
812 // 1. Load Data (UpdateLocalGhosts is called inside the kernels)
813 ierr = ReadSimulationFields(user, ti); CHKERRQ(ierr);
814
815 // After the first read, which validates the checkpoint against the grid in
816 // nondimensional units and caches that geometry digest.
817 if (pps->dimensionalize && !coordinates_dimensionalized) {
818 ierr = DimensionalizeField(user, "Coordinates"); CHKERRQ(ierr);
819 coordinates_dimensionalized = PETSC_TRUE;
820 }
821
822 // 2. Transform Data
823 ierr = EulerianDataProcessingPipeline(user, pps); CHKERRQ(ierr);
824
825 // 3. Write Output
826 ierr = WriteEulerianFile(user, pps, ti); CHKERRQ(ierr);
827
828 if(needs_particle_stage) {
829 // 1. Resize swarm based on particle count in this timestep's file
830 ierr = PreCheckAndResizeSwarm(user, ti, pps->particleExt); CHKERRQ(ierr);
831
832 // 2. Load particle data into the correctly sized swarm
833 ierr = ReadAllSwarmFields(user, ti); CHKERRQ(ierr);
834
835 // A cell ensemble counts the particles in each cell's ghosted patch, and a
836 // particle is read onto whichever rank its file position falls to, so move
837 // each to the rank owning its recorded cell first.
838 if (needs_particle_ensembles) {
839 ierr = MigrateRestartParticlesUsingCellID(user); CHKERRQ(ierr);
840 }
841
842 // 3. Global statistical reductions (MSD, etc.) → CSV files. These compare
843 // against nondimensional theory, so they read the positions as loaded.
844 ierr = GlobalStatisticsPipeline(user, pps, ti); CHKERRQ(ierr);
845
846 // 4. Dimensionalize the loaded particle fields before anything derives from
847 // or writes them; they are loaded after the Eulerian pipeline has run.
848 if (pps->dimensionalize) {
849 // Every loaded particle field with a physical dimension, each once.
850 for (PetscInt raw_id = 0; raw_id < PARTICLE_FIELD_ID_COUNT; ++raw_id) {
851 const ParticleFieldDescriptor *descriptor = NULL;
852
853 ierr = ParticleFieldGetDescriptor((ParticleFieldId)raw_id, &descriptor); CHKERRQ(ierr);
854 if (!(descriptor->capabilities & PARTICLE_FIELD_CAPABILITY_CHECKPOINT)) continue;
855 if (descriptor->dimension.kind != FIELD_DIMENSION_FIXED) continue;
856 ierr = DimensionalizeField(user, descriptor->canonical_name); CHKERRQ(ierr);
857 }
858 }
859
860 // 5. Transform particle data
861 ierr = ParticleDataProcessingPipeline(user, pps); CHKERRQ(ierr);
862
863 // 6. Write particle output (optional)
864 if (pps->outputParticles) {
865 ierr = WriteParticleFile(user, pps, ti); CHKERRQ(ierr);
866 }
867 }
868
869 // 4. Accumulated Eulerian window statistics → derived fields and history.
870 // Eulerian and independent of the swarm, so it sits outside the particle
871 // block: a turbulence run normally carries no particles at all.
872 ierr = FieldStatisticsPipeline(user, pps, ti); CHKERRQ(ierr);
873
874 if(simCtx->rank == 0){
875 PetscReal currentTime = (PetscReal)ti*simCtx->dt;
876 PrintProgressBar(k, 0, step_count, currentTime, 0.0, -1);
877 if(get_log_level()>LOG_ERROR)PetscPrintf(PETSC_COMM_SELF,"\n");
878 }
879 ierr = RuntimeMemoryLogSample(simCtx, ti, "Post", "-"); CHKERRQ(ierr);
880 }
881
882 // End the progress bar's line so subsequent terminal output starts on a fresh line.
883 if (simCtx->rank == 0 && step_count > 0) {
884 PetscPrintf(PETSC_COMM_SELF, "\n");
885 fflush(stdout);
886 }
887 const PetscInt last_step = step_count > 0 ? steps[step_count - 1] : pps->endTime;
888 ierr = PetscFree(steps); CHKERRQ(ierr);
889
890 LOG_ALLOW(GLOBAL, LOG_INFO, "=============================================================\n");
891 LOG_ALLOW(GLOBAL, LOG_INFO, "Post-processing finished successfully.\n");
892
893
894 // === VIII. FINALIZE =========================================================
895 ierr = RuntimeMemoryLogSample(simCtx, last_step, "Final", "Complete"); CHKERRQ(ierr);
896 ierr = ProfilingFinalize(simCtx); CHKERRQ(ierr);
897 ierr = FinalizeSimulation(simCtx); CHKERRQ(ierr);
898 ierr = PetscFinalize();
899 return ierr;
900}
901#endif
PetscErrorCode MigrateRestartParticlesUsingCellID(UserCtx *user)
Fast-path migration for restart particles using preloaded Cell IDs.
PetscErrorCode PreCheckAndResizeSwarm(UserCtx *user, PetscInt ti, const char *ext)
Checks particle count in the reference file and resizes the swarm if needed.
PetscErrorCode InitializeParticleSwarm(SimCtx *simCtx)
High-level particle initialization orchestrator for a simulation run.
PetscErrorCode RegisterSwarmField(DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
Registers a swarm field without finalizing registration.
@ FIELD_DIMENSION_FIXED
The exponents are the field's dimension.
FieldDimensionKind kind
PetscErrorCode CreateVTKFileFromMetadata(const char *filename, const VTKMetaData *meta, MPI_Comm comm)
Creates a VTK file from prepared metadata and field payloads.
Definition vtk_io.c:172
PetscErrorCode ReadSimulationFields(UserCtx *user, PetscInt ti)
Reads binary field data for velocity, pressure, and other required vectors.
Definition io.c:1387
void TrimWhitespace(char *str)
Removes leading and trailing ASCII whitespace from a mutable string.
Definition io.c:486
PetscErrorCode ReadAllSwarmFields(UserCtx *user, PetscInt ti)
Reads multiple fields (positions, velocity, CellID, and weight) into a DMSwarm.
Definition io.c:1815
PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Restores field-statistics window state and accumulators from a checkpoint.
Definition io.c:1604
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
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
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
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
@ LOG_ERROR
Critical errors that may halt the program.
Definition logging.h:29
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_WARNING
Non-critical issues that warrant attention.
Definition logging.h:30
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_COUNT
@ PARTICLE_FIELD_CAPABILITY_CHECKPOINT
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
Immutable metadata for one persistent particle field.
PetscErrorCode ComputeParticleMSD(UserCtx *user, const char *stats_prefix, PetscInt ti)
Computes the mean-squared displacement (MSD) of a particle cloud.
PetscErrorCode ComputeQCriterion(UserCtx *user)
Computes the Q-criterion diagnostic from the local velocity-gradient tensor.
PetscErrorCode ComputeWindowStatisticsProfile(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, const PetscBool average_direction[3], const char *output_prefix, PetscInt ti)
Writes a window's statistics merged over homogeneous directions as a profile.
PetscErrorCode ComputeWindowStatisticNodal(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, PetscInt output_index, char *out_name, size_t name_size, Vec *out_vec, PetscInt *out_components)
Derives one accumulated statistic and converts it to nodal values.
PetscErrorCode ComputeSpecificKE(UserCtx *user, const char *velocity_field, const char *ske_field)
Computes the specific kinetic energy (KE per unit mass) for each particle.
PetscErrorCode NormalizeRelativeField(UserCtx *user, const char *relative_field_name)
Normalizes pressure using the value at the configured logical grid point.
PetscErrorCode ComputeWindowStatisticsSummary(UserCtx *user, PetscInt window_index, const char *output_prefix, PetscInt ti)
Appends one convergence row for an accumulated window to its CSV history.
PetscErrorCode DimensionalizeField(UserCtx *user, const char *field_name)
Scales a specified field from non-dimensional to dimensional units in-place.
PetscErrorCode ComputeNodalAverage(UserCtx *user, const char *in_field_name, const char *out_field_name)
Interpolates a cell-centered field to nodal locations using local stencil averaging.
PetscErrorCode EulerianDataProcessingPipeline(UserCtx *user, PostProcessParams *pps)
Implementation of EulerianDataProcessingPipeline().
PetscErrorCode WriteEulerianFile(UserCtx *user, PostProcessParams *pps, PetscInt ti)
Implementation of WriteEulerianFile().
PetscErrorCode GlobalStatisticsPipeline(UserCtx *user, PostProcessParams *pps, PetscInt ti)
Implementation of GlobalStatisticsPipeline().
int main(int argc, char **argv)
Entry point for the postprocessor executable.
PetscErrorCode ResolvePostProcessingSteps(PostProcessParams *pps, PetscInt **steps, PetscInt *count)
Implementation of ResolvePostProcessingSteps().
PetscErrorCode ParticleDataProcessingPipeline(UserCtx *user, PostProcessParams *pps)
Implementation of ParticleDataProcessingPipeline().
static PetscErrorCode WriteWindowStatistics(UserCtx *user, PostProcessParams *pps, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscBool want_vtk, PetscBool want_csv, PetscInt ti)
Writes one window's or ensemble's derived output for a step.
PetscErrorCode WriteParticleFile(UserCtx *user, PostProcessParams *pps, PetscInt ti)
Implementation of WriteParticleFile().
PetscErrorCode FieldStatisticsPipeline(UserCtx *user, PostProcessParams *pps, PetscInt ti)
Implementation of FieldStatisticsPipeline().
static PetscErrorCode FillStatisticsEnsemble(UserCtx *user, PostProcessParams *pps, PetscInt index, PicurvWindowStorage *storage)
Fills one recipe ensemble's storage from the loaded step.
PetscErrorCode SetupPostProcessSwarm(UserCtx *user, PostProcessParams *pps)
Implementation of SetupPostProcessSwarm().
int PicurvCheckLinkedPetscIndexWidth(int argc, char **argv, const char *executable_name)
Refuse to start when the loaded libpetsc's PetscInt width differs from this build's.
Definition setup.c:79
PetscErrorCode SetupDomainRankInfo(SimCtx *simCtx)
Sets up the full rank communication infrastructure, including neighbor ranks and bounding box exchang...
Definition setup.c:3242
PetscErrorCode SetupGridAndSolvers(SimCtx *simCtx)
The main orchestrator for setting up all grid-related components.
Definition setup.c:2066
PetscErrorCode SetupSimulationEnvironment(SimCtx *simCtx)
Verifies and prepares the complete I/O environment for a simulation run.
Definition setup.c:1728
int PicurvHandleVersionArgument(int argc, char **argv, const char *executable_name)
Print the shared native build identity when a version flag is present.
Definition setup.c:119
PetscErrorCode CreateSimulationContext(int argc, char **argv, SimCtx **p_simCtx)
Allocates and populates the master SimulationContext object.
Definition setup.c:453
PetscErrorCode SetupBoundaryConditions(SimCtx *simCtx)
(Orchestrator) Sets up all boundary conditions for the simulation.
Definition setup.c:2755
PetscErrorCode FinalizeSimulation(SimCtx *simCtx)
Main cleanup function for the entire simulation context.
Definition setup.c:4137
Per-window PETSc accumulator storage and pointwise application.
PetscErrorCode PicurvWindowDerivedCount(const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, PetscInt *count)
Reports how many derived fields a requested output set produces.
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
PetscErrorCode PicurvWindowStorageFromParticles(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Fills a window's storage from the particles sampling each cell at one instant.
PetscErrorCode PicurvWindowAccumulate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage, PetscReal weight)
Applies one accepted completed state to a window's accumulators.
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
PetscBool physical_units
Holds physical units, as an ensemble of a dimensionalized load does, so derivation applies no scale; ...
Independent accumulator state for one window on one block.
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
PetscInt sample_count
PicurvWindowDefinition definition
PetscBool FieldStatisticsIsActive(const struct SimCtx *simCtx)
Reports whether this run has live field-statistics state.
Runtime state of one window.
The scientifically immutable definition of one window.
Vec Qcrit_nodal
Q-criterion averaged to grid nodes; the field a .vts can place correctly.
Definition variables.h:1284
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
char statistics_output_prefix[256]
basename for CSV output, e.g.
Definition variables.h:816
Vec P_nodal
Definition variables.h:1281
UserCtx * user
Definition variables.h:768
PetscInt npoints
Definition variables.h:874
PetscInt num_components
Definition variables.h:854
char particle_output_prefix[256]
Definition variables.h:811
PetscMPIInt rank
Definition variables.h:919
PetscInt num_point_data_fields
Definition variables.h:879
struct PicurvWindow * field_statistics_ensembles
Definition variables.h:835
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
char output_prefix[256]
Definition variables.h:808
PetscBool dimensionalize
Whether derived output leaves non-dimensional form, from global_operations.dimensionalize.
Definition variables.h:828
char field_statistics_output_prefix[PETSC_MAX_PATH_LEN]
Analysis prefix for CSV summaries; VTK continues to use output_prefix.
Definition variables.h:826
UserMG usermg
Definition variables.h:1082
#define MAX_FIELD_LIST_LENGTH
Definition variables.h:784
DM post_swarm
Definition variables.h:1280
char step_list_file[PETSC_MAX_PATH_LEN]
File listing the exact steps to process, one per line; empty uses the time controls.
Definition variables.h:802
PetscReal dt
Definition variables.h:933
PetscInt * connectivity
Definition variables.h:880
PetscInt * offsets
Definition variables.h:881
Vec Ucat_nodal
Definition variables.h:1282
static PetscBool ParticlesEnabled(const SimCtx *simCtx)
Whether the run carries particles: a seeded or restored population, or inlets that inject them.
Definition variables.h:1143
PetscInt timeStep
Definition variables.h:800
#define MAX_FILENAME_LENGTH
Definition variables.h:785
char statistics_pipeline[1024]
e.g.
Definition variables.h:815
char field_statistics_formats[1024]
Comma-separated formats: vtk for derived fields, csv for the convergence history.
Definition variables.h:824
char output_fields_instantaneous[1024]
Definition variables.h:807
PetscScalar * data
Definition variables.h:855
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
char particle_pipeline[1024]
Definition variables.h:809
char name[64]
Definition variables.h:853
PetscScalar * coords
Definition variables.h:877
PetscInt mglevels
Definition variables.h:775
PetscBool * field_statistics_ensemble_from_particles
Whether each ensemble samples the particles in a cell rather than the cell's state.
Definition variables.h:837
char process_pipeline[1024]
Definition variables.h:806
char particle_fields[1024]
Definition variables.h:810
PetscBool outputParticles
Definition variables.h:803
VTKFieldInfo point_data_fields[20]
Definition variables.h:878
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
Vec Psi_nodal
Definition variables.h:1285
PetscInt field_statistics_ensemble_count
Recipe-defined single-instant windows, derived at every processed step.
Definition variables.h:834
PetscInt mz
Definition variables.h:873
PostProcessParams * pps
Definition variables.h:1131
PetscMPIInt size
Definition variables.h:920
@ EXEC_MODE_POSTPROCESSOR
Definition variables.h:889
PetscInt field_statistics_source_step
Committed step supplying the state; negative means the step being processed.
Definition variables.h:830
char particleExt[8]
Definition variables.h:841
char field_statistics_windows[1024]
Comma-separated window names to derive; empty disables the pipeline.
Definition variables.h:820
char field_statistics_outputs[1024]
Comma-separated outputs: mean, reynolds_stress, rms, tke, flux, point_variance.
Definition variables.h:822
MGCtx * mgctx
Definition variables.h:778
ExecutionMode exec_mode
Definition variables.h:937
PetscInt startTime
Definition variables.h:798
PetscInt my
Definition variables.h:873
PetscBool field_statistics_homogeneous[3]
Directions profiles merge over, in (i, j, k) order; none selected writes no profile.
Definition variables.h:832
PetscInt mx
Definition variables.h:873
#define MAX_VTK_FIELD_NAME_LENGTH
Maximum length for VTK field names.
Definition variables.h:788
PetscBool fieldStatisticsContinue
Definition variables.h:995
Holds all configuration parameters for a post-processing run.
Definition variables.h:793
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
One VTK file being assembled collectively.
Definition variables.h:871
Head of a generic C-style linked list.
Definition variables.h:504
PetscErrorCode FinishStructuredVTKOutput(VTKMetaData *meta, const char *filename)
Writes an assembled structured VTK file and releases its buffers.
Definition vtk_io.c:336
PetscErrorCode BeginStructuredVTKOutput(UserCtx *user, VTKMetaData *meta)
Begins one structured VTK file: clears the metadata and builds its coordinates.
Definition vtk_io.c:285
PetscErrorCode AppendStructuredVTKField(UserCtx *user, VTKMetaData *meta, const char *name, Vec field_vec, PetscInt components)
Adds one point-data field to a structured VTK file being assembled.
Definition vtk_io.c:305
PetscErrorCode PrepareOutputParticleData(UserCtx *user, PostProcessParams *pps, VTKMetaData *meta, PetscInt *p_n_total)
Prepares this rank's part of the subsampled particle VTK output.
Definition vtk_io.c:384