PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
particle_statistics.c
Go to the documentation of this file.
1/**
2 * @file particle_statistics.c
3 * @brief Global statistical reduction kernels for the Statistics Pipeline.
4 *
5 * Each kernel in this file:
6 * - Performs an MPI_Allreduce over all particles across all ranks.
7 * - Maintains one logical CSV row per processed step in its output file.
8 * - Logs a one-line summary via LOG_INFO on rank 0.
9 * - Produces O(1) output regardless of particle count, making these kernels
10 * the primary quantitative diagnostic path for large (100M+) particle runs.
11 *
12 * To add a new statistic:
13 * 1. Implement PetscErrorCode ComputeXxx(UserCtx*, const char*, PetscInt) here.
14 * 2. Declare it in include/particle_statistics.h.
15 * 3. Add one else-if in GlobalStatisticsPipeline() in src/postprocessor.c.
16 */
17
18#include "particle_statistics.h"
20#include <math.h>
21#include <mpi.h>
22#include <stdlib.h>
23#include <string.h>
24
25static const char *PARTICLE_MSD_CSV_HEADER =
26 "step,t,N,MSD_x,MSD_y,MSD_z,MSD_total,"
27 "r_rms_meas,r_rms_theory,rel_err_pct,"
28 "com_x,com_y,com_z,"
29 "frac_1sigma_pct,frac_2sigma_pct,frac_3sigma_pct\n";
30
31/**
32 * @brief Return whether a CSV row belongs to the requested timestep.
33 * @param[in] line CSV row text to inspect.
34 * @param[in] ti Requested timestep id.
35 * @return PETSC_TRUE when the row begins with the requested step id.
36 */
37static PetscBool MSDCSVLineMatchesStep(const char *line, PetscInt ti)
38{
40 char *endptr = NULL;
41 long parsed_step;
42
43 if (!line) { PROFILE_HELPER_END; return PETSC_FALSE; }
44 parsed_step = strtol(line, &endptr, 10);
45 if (endptr == line) { PROFILE_HELPER_END; return PETSC_FALSE; }
46 while (*endptr == ' ' || *endptr == '\t') endptr++;
47 if (*endptr != ',') { PROFILE_HELPER_END; return PETSC_FALSE; }
49 return (PetscBool)(parsed_step == (long)ti ? PETSC_TRUE : PETSC_FALSE);
50}
51
52/**
53 * @brief Rewrite the MSD CSV so the requested timestep appears exactly once.
54 * @param[in] csv_path Target CSV path.
55 * @param[in] ti Timestep being written.
56 * @param[in] row_line Fully formatted CSV row for the timestep.
57 * @return Petsc error code.
58 */
59static PetscErrorCode RewriteParticleMSDCSV(const char *csv_path, PetscInt ti, const char *row_line)
60{
61 char tmp_path[PETSC_MAX_PATH_LEN];
62 FILE *src = NULL;
63 FILE *dst = NULL;
64 char line[4096];
65 PetscBool wrote_header = PETSC_FALSE;
66 PetscBool inserted_row = PETSC_FALSE;
67
68 PetscFunctionBeginUser;
70 PetscCall(PetscSNPrintf(tmp_path, sizeof(tmp_path), "%s.tmp", csv_path));
71
72 dst = fopen(tmp_path, "w");
73 if (!dst) {
75 "ComputeParticleMSD: could not open '%s' for writing.\n", tmp_path);
77 PetscFunctionReturn(0);
78 }
79
80 src = fopen(csv_path, "r");
81 if (src) {
82 while (fgets(line, sizeof(line), src)) {
83 if (!wrote_header) {
84 if (strncmp(line, "step,", 5) == 0) {
85 fputs(line, dst);
86 wrote_header = PETSC_TRUE;
87 continue;
88 }
89 fputs(PARTICLE_MSD_CSV_HEADER, dst);
90 wrote_header = PETSC_TRUE;
91 }
92
93 if (MSDCSVLineMatchesStep(line, ti)) {
94 if (!inserted_row) {
95 fputs(row_line, dst);
96 inserted_row = PETSC_TRUE;
97 }
98 continue;
99 }
100 fputs(line, dst);
101 }
102 fclose(src);
103 src = NULL;
104 }
105
106 if (!wrote_header) {
107 fputs(PARTICLE_MSD_CSV_HEADER, dst);
108 }
109 if (!inserted_row) {
110 fputs(row_line, dst);
111 }
112
113 if (fclose(dst) != 0) {
114 remove(tmp_path);
116 "ComputeParticleMSD: could not finalize '%s'.\n", tmp_path);
118 PetscFunctionReturn(0);
119 }
120
121 if (rename(tmp_path, csv_path) != 0) {
122 remove(tmp_path);
124 "ComputeParticleMSD: could not replace '%s'.\n", csv_path);
125 }
127 PetscFunctionReturn(0);
128}
129
130/**
131 * @brief Internal helper implementation: `ComputeParticleMSD()`.
132 * @details Local to this translation unit.
133 */
134PetscErrorCode ComputeParticleMSD(UserCtx *user, const char *stats_prefix, PetscInt ti)
135{
136 PetscErrorCode ierr;
137 SimCtx *simCtx = user->simCtx;
138 PetscMPIInt rank;
139
140 PetscFunctionBeginUser;
142
143 rank = simCtx->rank;
144
145 /* ------------------------------------------------------------------ *
146 * Physics parameters *
147 * ------------------------------------------------------------------ */
148 const PetscReal Re = (simCtx->ren > 0.0) ? simCtx->ren : 1.0;
149 const PetscReal Sc = (simCtx->schmidt_number > 0.0) ? simCtx->schmidt_number : 1.0;
150 const PetscReal D = 1.0 / (Re * Sc);
151 const PetscReal t = (PetscReal)ti * simCtx->dt;
152 const PetscReal x0 = simCtx->psrc_x;
153 const PetscReal y0 = simCtx->psrc_y;
154 const PetscReal z0 = simCtx->psrc_z;
155
156 /* ------------------------------------------------------------------ *
157 * Pass 1: local accumulation *
158 * ------------------------------------------------------------------ */
159 PetscInt n_local;
160 const PetscReal (*pos_arr)[3];
161
162 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
163 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
164
165 PetscReal local_sq_x = 0.0, local_sq_y = 0.0, local_sq_z = 0.0;
166 PetscReal local_sx = 0.0, local_sy = 0.0, local_sz = 0.0;
167
168 for (PetscInt p = 0; p < n_local; p++) {
169 const PetscReal dx = pos_arr[p][0] - x0;
170 const PetscReal dy = pos_arr[p][1] - y0;
171 const PetscReal dz = pos_arr[p][2] - z0;
172 local_sq_x += dx * dx;
173 local_sq_y += dy * dy;
174 local_sq_z += dz * dz;
175 local_sx += dx;
176 local_sy += dy;
177 local_sz += dz;
178 }
179
180 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
181
182 /* ------------------------------------------------------------------ *
183 * MPI reduction — 7 doubles + count *
184 * ------------------------------------------------------------------ */
185 PetscReal local_buf[7] = { local_sq_x, local_sq_y, local_sq_z,
186 local_sx, local_sy, local_sz,
187 (PetscReal)n_local };
188 PetscReal global_buf[7] = {0};
189 ierr = MPI_Allreduce(local_buf, global_buf, 7, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
190
191 const PetscReal N_total = global_buf[6];
192 if (N_total < 1.0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); } /* no particles */
193
194 const PetscReal MSD_x = global_buf[0] / N_total;
195 const PetscReal MSD_y = global_buf[1] / N_total;
196 const PetscReal MSD_z = global_buf[2] / N_total;
197 const PetscReal com_x = global_buf[3] / N_total;
198 const PetscReal com_y = global_buf[4] / N_total;
199 const PetscReal com_z = global_buf[5] / N_total;
200
201 const PetscReal MSD_total = MSD_x + MSD_y + MSD_z;
202 const PetscReal r_rms_meas = PetscSqrtReal(MSD_total);
203 const PetscReal r_theory = (t > 1e-300) ? PetscSqrtReal(6.0 * D * t) : 0.0;
204 const PetscReal rel_err_pct = (r_theory > 1e-12)
205 ? PetscAbsReal(r_rms_meas - r_theory) / r_theory * 100.0
206 : 0.0;
207
208 /* ------------------------------------------------------------------ *
209 * Pass 2: fraction inside σ-shells *
210 * ------------------------------------------------------------------ */
211 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
212
213 PetscInt local_n1 = 0, local_n2 = 0, local_n3 = 0;
214 const PetscReal r1 = r_theory;
215 const PetscReal r2 = 2.0 * r_theory;
216 const PetscReal r3 = 3.0 * r_theory;
217
218 for (PetscInt p = 0; p < n_local; p++) {
219 const PetscReal dx = pos_arr[p][0] - x0;
220 const PetscReal dy = pos_arr[p][1] - y0;
221 const PetscReal dz = pos_arr[p][2] - z0;
222 const PetscReal r = PetscSqrtReal(dx*dx + dy*dy + dz*dz);
223 if (r < r1) local_n1++;
224 if (r < r2) local_n2++;
225 if (r < r3) local_n3++;
226 }
227
228 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
229
230 PetscReal local_counts[3] = { (PetscReal)local_n1,
231 (PetscReal)local_n2,
232 (PetscReal)local_n3 };
233 PetscReal global_counts[3] = {0};
234 ierr = MPI_Allreduce(local_counts, global_counts, 3, MPI_DOUBLE, MPI_SUM, PETSC_COMM_WORLD); CHKERRMPI(ierr);
235
236 const PetscReal frac_1s = global_counts[0] / N_total * 100.0;
237 const PetscReal frac_2s = global_counts[1] / N_total * 100.0;
238 const PetscReal frac_3s = global_counts[2] / N_total * 100.0;
239
240 /* ------------------------------------------------------------------ *
241 * Output: CSV + LOG_INFO (rank 0 only) *
242 * ------------------------------------------------------------------ */
243 /* The comparison with theory is made in solver units above. A dimensionalizing
244 * post-processor then reports every dimensional column physically; the relative error
245 * and shell fractions are ratios and are the same in either system. */
246 PetscReal time_scale = 1.0, length_scale = 1.0;
247 if (simCtx->pps && simCtx->pps->dimensionalize) {
248 const FieldDimension time_dimension = FIELD_DIM_TIME;
249 const FieldDimension length_dimension = FIELD_DIM_LENGTH;
250
251 ierr = FieldDimensionReferenceScale(&simCtx->scaling, time_dimension, &time_scale); CHKERRQ(ierr);
252 ierr = FieldDimensionReferenceScale(&simCtx->scaling, length_dimension, &length_scale); CHKERRQ(ierr);
253 }
254 const PetscReal area_scale = length_scale * length_scale;
255
256 if (rank == 0) {
257 char csv_path[PETSC_MAX_PATH_LEN];
258 char row_line[1024];
259 PetscSNPrintf(csv_path, sizeof(csv_path), "%s_msd.csv", stats_prefix);
260 PetscSNPrintf(
261 row_line,
262 sizeof(row_line),
263 "%d,%.6e,%.0f,%.6e,%.6e,%.6e,%.6e,%.6e,%.6e,%.4f,%.6e,%.6e,%.6e,%.2f,%.2f,%.2f\n",
264 (int)ti, t * time_scale, N_total,
265 MSD_x * area_scale, MSD_y * area_scale, MSD_z * area_scale, MSD_total * area_scale,
266 r_rms_meas * length_scale, r_theory * length_scale, rel_err_pct,
267 com_x * length_scale, com_y * length_scale, com_z * length_scale,
268 frac_1s, frac_2s, frac_3s
269 );
270 PetscCall(RewriteParticleMSDCSV(csv_path, ti, row_line));
271
273 "[MSD ti=%d t=%.4f] total=%.4e theory=%.4e err=%.2f%% | "
274 "fracs: %.1f/%.1f/%.1f%% | COM: (%.2e,%.2e,%.2e)\n",
275 (int)ti, t, MSD_total, r_theory * r_theory, rel_err_pct,
276 frac_1s, frac_2s, frac_3s,
277 com_x, com_y, com_z);
278 }
279
281 PetscFunctionReturn(0);
282}
PetscErrorCode FieldDimensionReferenceScale(const ScalingCtx *scaling, FieldDimension dimension, PetscReal *scale)
Return the factor that turns a solver value of one dimension into physical units.
#define FIELD_DIM_LENGTH
#define FIELD_DIM_TIME
Physical dimension as exponents of the reference length, velocity, and density.
#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_HELPER_BEGIN
Marks the beginning of a profiled helper: timed only when enabled by name.
Definition logging.h:1014
#define PROFILE_HELPER_END
Alias of PROFILE_FUNCTION_END for a function that began with PROFILE_HELPER_BEGIN.
Definition logging.h:1033
#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
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
Typed identities and metadata for persistent solver-particle fields.
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_POSITION
static const char * PARTICLE_MSD_CSV_HEADER
static PetscErrorCode RewriteParticleMSDCSV(const char *csv_path, PetscInt ti, const char *row_line)
Rewrite the MSD CSV so the requested timestep appears exactly once.
static PetscBool MSDCSVLineMatchesStep(const char *line, PetscInt ti)
Return whether a CSV row belongs to the requested timestep.
PetscErrorCode ComputeParticleMSD(UserCtx *user, const char *stats_prefix, PetscInt ti)
Internal helper implementation: ComputeParticleMSD().
Global statistics kernels for the Statistics Pipeline.
PetscReal schmidt_number
Definition variables.h:1005
PetscMPIInt rank
Definition variables.h:919
SimCtx * simCtx
Back-pointer to the master simulation context.
Definition variables.h:1160
PetscBool dimensionalize
Whether derived output leaves non-dimensional form, from global_operations.dimensionalize.
Definition variables.h:828
PetscReal psrc_x
Definition variables.h:1002
PetscReal ren
Definition variables.h:965
PetscReal dt
Definition variables.h:933
PetscReal psrc_z
Point source location for PARTICLE_INIT_POINT_SOURCE.
Definition variables.h:1002
ScalingCtx scaling
Definition variables.h:1003
PetscReal psrc_y
Definition variables.h:1002
PostProcessParams * pps
Definition variables.h:1131
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