PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Functions
postprocessor.h File Reference
#include "io.h"
#include "variables.h"
#include "logging.h"
#include "ParticleSwarm.h"
#include "interpolation.h"
#include "grid.h"
#include "setup.h"
#include "Metric.h"
#include "postprocessing_kernels.h"
#include "vtk_io.h"
#include "particle_statistics.h"
#include "ParticleMotion.h"
Include dependency graph for postprocessor.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Functions

PetscErrorCode SetupPostProcessSwarm (UserCtx *user, PostProcessParams *pps)
 Creates a new, dedicated DMSwarm for post-processing tasks.
 
PetscErrorCode WriteEulerianFile (UserCtx *user, PostProcessParams *pps, PetscInt ti)
 Orchestrates the writing of a combined, multi-field VTK file for a single time step.
 
PetscErrorCode EulerianDataProcessingPipeline (UserCtx *user, PostProcessParams *pps)
 Parses the processing pipeline string and executes the requested kernels.
 
PetscErrorCode ParticleDataProcessingPipeline (UserCtx *user, PostProcessParams *pps)
 Parses and executes the particle pipeline using a robust two-pass approach.
 
PetscErrorCode WriteParticleFile (UserCtx *user, PostProcessParams *pps, PetscInt ti)
 Writes particle data to a VTP file using the Prepare-Write-Cleanup pattern.
 
PetscErrorCode GlobalStatisticsPipeline (UserCtx *user, PostProcessParams *pps, PetscInt ti)
 Executes the global statistics pipeline, computing aggregate reductions over all particles.
 
PetscErrorCode ResolvePostProcessingSteps (PostProcessParams *pps, PetscInt **steps, PetscInt *count)
 Resolve the ordered steps one post-processing run processes.
 
PetscErrorCode FieldStatisticsPipeline (UserCtx *user, PostProcessParams *pps, PetscInt ti)
 Derives and writes field statistics for the windows a recipe requests.
 

Function Documentation

◆ SetupPostProcessSwarm()

PetscErrorCode SetupPostProcessSwarm ( UserCtx *  user,
PostProcessParams *  pps 
)

Creates a new, dedicated DMSwarm for post-processing tasks.

This function is called once at startup. It creates an empty DMSwarm and associates it with the same grid DM as the primary swarm and registers all the required fields.

Parameters
userThe UserCtx where user->post_swarm will be created.
ppsThe PostProcessParams containing the particle_pipeline string for field registration.
Returns
PetscErrorCode

Creates a new, dedicated DMSwarm for post-processing tasks.

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

See also
SetupPostProcessSwarm()

Definition at line 21 of file postprocessor.c.

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}
PetscErrorCode RegisterSwarmField(DM swarm, const char *fieldName, PetscInt fieldDim, PetscDataType dtype)
Registers a swarm field without finalizing registration.
void TrimWhitespace(char *str)
Removes leading and trailing ASCII whitespace from a mutable string.
Definition io.c:486
#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
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
@ 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
DM post_swarm
Definition variables.h:1280
char particle_pipeline[1024]
Definition variables.h:809
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteEulerianFile()

PetscErrorCode WriteEulerianFile ( UserCtx *  user,
PostProcessParams *  pps,
PetscInt  ti 
)

Orchestrates the writing of a combined, multi-field VTK file for a single time step.

This function is the primary driver for generating output. It performs these steps:

  1. Prepares the subsampled coordinate array required for the legacy grid format.
  2. Parses the user-requested list of fields from the configuration.
  3. For each field, prepares a corresponding subsampled data array.
  4. Assembles all prepared arrays into a single VTKMetaData struct.
  5. Calls the low-level VTK writer to generate the final .vts file.
  6. Frees all temporary memory allocated during the preparation phase.
Parameters
userThe UserCtx for the finest grid level.
ppsThe post-processing configuration struct.
tiThe current time step index.
Returns
PetscErrorCode

Orchestrates the writing of a combined, multi-field VTK file for a single time step.

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

See also
WriteEulerianFile()

Definition at line 197 of file postprocessor.c.

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}
Vec Qcrit_nodal
Q-criterion averaged to grid nodes; the field a .vts can place correctly.
Definition variables.h:1284
Vec P_nodal
Definition variables.h:1281
PetscInt num_components
Definition variables.h:854
PetscMPIInt rank
Definition variables.h:919
PetscInt num_point_data_fields
Definition variables.h:879
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
char output_prefix[256]
Definition variables.h:808
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
#define MAX_FILENAME_LENGTH
Definition variables.h:785
char output_fields_instantaneous[1024]
Definition variables.h:807
char name[64]
Definition variables.h:853
VTKFieldInfo point_data_fields[20]
Definition variables.h:878
Vec Psi_nodal
Definition variables.h:1285
PetscInt mz
Definition variables.h:873
PetscInt my
Definition variables.h:873
PetscInt mx
Definition variables.h:873
One VTK file being assembled collectively.
Definition variables.h:871
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
Here is the call graph for this function:
Here is the caller graph for this function:

◆ EulerianDataProcessingPipeline()

PetscErrorCode EulerianDataProcessingPipeline ( UserCtx *  user,
PostProcessParams *  pps 
)

Parses the processing pipeline string and executes the requested kernels.

Parameters
userThe UserCtx containing the data to be transformed.
ppsThe PostProcessParams containing the pipeline string.
Returns
PetscErrorCode

Parses the processing pipeline string and executes the requested kernels.

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

See also
EulerianDataProcessingPipeline()

Definition at line 105 of file postprocessor.c.

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}
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
PetscErrorCode ComputeQCriterion(UserCtx *user)
Computes the Q-criterion diagnostic from the local velocity-gradient tensor.
PetscErrorCode NormalizeRelativeField(UserCtx *user, const char *relative_field_name)
Normalizes pressure using the value at the configured logical grid point.
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.
char process_pipeline[1024]
Definition variables.h:806
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ParticleDataProcessingPipeline()

PetscErrorCode ParticleDataProcessingPipeline ( UserCtx *  user,
PostProcessParams *  pps 
)

Parses and executes the particle pipeline using a robust two-pass approach.

This function ensures correctness and efficiency by separating field registration from kernel execution.

PASS 1 (Registration): The pipeline string is parsed to identify all new fields that will be created. These fields are registered with the DMSwarm.

Finalize: After Pass 1, DMSwarmFinalizeFieldRegister is called exactly once if any new fields were added, preparing the swarm's memory layout.

PASS 2 (Execution): The pipeline string is parsed again, and this time the actual compute kernels are executed, filling the now-valid fields.

Parameters
userThe UserCtx containing the DMSwarm.
ppsThe PostProcessParams struct containing the particle_pipeline string.
Returns
PetscErrorCode

Parses and executes the particle pipeline using a robust two-pass approach.

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

See also
ParticleDataProcessingPipeline()

Definition at line 499 of file postprocessor.c.

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}
PetscErrorCode ComputeSpecificKE(UserCtx *user, const char *velocity_field, const char *ske_field)
Computes the specific kinetic energy (KE per unit mass) for each particle.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ WriteParticleFile()

PetscErrorCode WriteParticleFile ( UserCtx *  user,
PostProcessParams *  pps,
PetscInt  ti 
)

Writes particle data to a VTP file using the Prepare-Write-Cleanup pattern.

Parameters
userPrimary UserCtx input for the operation.
ppsPost-processing configuration for the operation.
tiSource timestep written into the VTP filename and metadata.
Returns
PetscErrorCode 0 on success.

Writes particle data to a VTP file using the Prepare-Write-Cleanup pattern.

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

See also
WriteParticleFile()

Definition at line 620 of file postprocessor.c.

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}
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
PetscInt npoints
Definition variables.h:874
char particle_output_prefix[256]
Definition variables.h:811
PetscInt * connectivity
Definition variables.h:880
PetscInt * offsets
Definition variables.h:881
PetscScalar * data
Definition variables.h:855
PetscScalar * coords
Definition variables.h:877
char particle_fields[1024]
Definition variables.h:810
PetscBool outputParticles
Definition variables.h:803
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
Here is the call graph for this function:
Here is the caller graph for this function:

◆ GlobalStatisticsPipeline()

PetscErrorCode GlobalStatisticsPipeline ( UserCtx *  user,
PostProcessParams *  pps,
PetscInt  ti 
)

Executes the global statistics pipeline, computing aggregate reductions over all particles.

Parses the semicolon-delimited pps->statistics_pipeline string and dispatches to the appropriate kernel (e.g. ComputeParticleMSD). Each kernel appends one row to its own CSV file and logs a summary via LOG_INFO. All MPI reductions happen inside each kernel. This pipeline is independent of the per-particle VTK pipeline; it produces no .vtp output.

Parameters
userThe UserCtx containing the primary DMSwarm (user->swarm).
ppsThe PostProcessParams containing statistics_pipeline and statistics_output_prefix.
tiCurrent time-step index (passed through to kernels for time computation).
Returns
PetscErrorCode

Executes the global statistics pipeline, computing aggregate reductions over all particles.

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

See also
GlobalStatisticsPipeline()

Definition at line 571 of file postprocessor.c.

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}
PetscErrorCode ComputeParticleMSD(UserCtx *user, const char *stats_prefix, PetscInt ti)
Computes the mean-squared displacement (MSD) of a particle cloud.
char statistics_output_prefix[256]
basename for CSV output, e.g.
Definition variables.h:816
char statistics_pipeline[1024]
e.g.
Definition variables.h:815
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ResolvePostProcessingSteps()

PetscErrorCode ResolvePostProcessingSteps ( PostProcessParams *  pps,
PetscInt **  steps,
PetscInt *  count 
)

Resolve the ordered steps one post-processing run processes.

A step list file, written by the conductor when a job starts, names exactly the steps whose output is missing or stale; without one the time controls define an evenly spaced window. Rank 0 reads the file and broadcasts it, so every rank iterates the same steps.

Parameters
[in]ppsPost-processing settings holding the time controls and list file.
[out]stepsNewly allocated array of steps; the caller frees it with PetscFree().
[out]countNumber of entries in steps.
Returns
PetscErrorCode 0 on success; an error when the list file cannot be read.

Resolve the ordered steps one post-processing run processes.

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

See also
ResolvePostProcessingSteps()

Definition at line 674 of file postprocessor.c.

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}
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
PetscInt timeStep
Definition variables.h:800
PetscInt startTime
Definition variables.h:798
Head of a generic C-style linked list.
Definition variables.h:504
Here is the call graph for this function:
Here is the caller graph for this function:

◆ FieldStatisticsPipeline()

PetscErrorCode FieldStatisticsPipeline ( UserCtx *  user,
PostProcessParams *  pps,
PetscInt  ti 
)

Derives and writes field statistics for the windows a recipe requests.

Runs once per processed step, beside the particle statistics pipeline, because a window's accumulated state is a property of the bundle at that step. A recipe spanning several steps therefore produces a convergence history rather than the same picture repeated; pinning field_statistics_source_step collapses it back to a single bundle.

Each window is written to its own file. The VTK point-data cap is per file, and one window carrying every output already fills most of it.

Does nothing when no window is requested. A window the run does not configure is fatal; a window that has not yet accumulated a sample is skipped with a note, since a recipe covering a whole run legitimately reaches bundles from before it began.

Parameters
[in]userFinest-level block context holding accumulators and staging fields.
[in]ppsPost-processing recipe naming the windows, outputs, and formats.
[in]tiStep being processed; names the output and selects the bundle.
Returns
Zero on success, or a PETSc error.

Derives and writes field statistics for the windows a recipe requests.

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

See also
FieldStatisticsPipeline()

Definition at line 383 of file postprocessor.c.

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}
PetscErrorCode RestoreFieldStatisticsState(SimCtx *simCtx, PetscInt ti)
Restores field-statistics window state and accumulators from a checkpoint.
Definition io.c:1604
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.
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.
static PetscErrorCode FillStatisticsEnsemble(UserCtx *user, PostProcessParams *pps, PetscInt index, PicurvWindowStorage *storage)
Fills one recipe ensemble's storage from the loaded step.
PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Allocates the accumulator state one window owns on one block.
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
Independent accumulator state for one window on one block.
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.
PetscInt fieldStatisticsWindowCount
Definition variables.h:989
struct PicurvWindow * field_statistics_ensembles
Definition variables.h:835
char field_statistics_output_prefix[PETSC_MAX_PATH_LEN]
Analysis prefix for CSV summaries; VTK continues to use output_prefix.
Definition variables.h:826
#define MAX_FIELD_LIST_LENGTH
Definition variables.h:784
char field_statistics_formats[1024]
Comma-separated formats: vtk for derived fields, csv for the convergence history.
Definition variables.h:824
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
PetscInt field_statistics_ensemble_count
Recipe-defined single-instant windows, derived at every processed step.
Definition variables.h:834
PetscInt field_statistics_source_step
Committed step supplying the state; negative means the step being processed.
Definition variables.h:830
char field_statistics_windows[1024]
Comma-separated window names to derive; empty disables the pipeline.
Definition variables.h:820
PetscBool fieldStatisticsContinue
Definition variables.h:995
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: