PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
statistics_accumulator.h
Go to the documentation of this file.
1/**
2 * @file statistics_accumulator.h
3 * @brief Per-window PETSc accumulator storage and pointwise application.
4 *
5 * Holds the independent state each named window owns, and applies one accepted
6 * completed state to it, per @ref p58_state_sec.
7 *
8 * Storage is allocated once by the vector factory and released once at teardown.
9 * Application is strictly pointwise: it reads a source field value at an owned
10 * point and updates that point's accumulator, so it performs no halo exchange and
11 * allocates nothing.
12 */
13
14#ifndef PICURV_STATISTICS_ACCUMULATOR_H
15#define PICURV_STATISTICS_ACCUMULATOR_H
16
17#include "variables.h"
18#include "statistics_window.h"
19
20/**
21 * @brief Independent accumulator state for one window on one block.
22 *
23 * Per-point occupancy is tracked separately from the field moments because the
24 * fluid mask can move: a point contributes only to the states in which it was
25 * valid, so its own count and weight are what normalize its moments.
26 *
27 * A particle-sampled field (`FIELD_CAPABILITY_PARTICLE_SAMPLED`) is a measurement
28 * only in the states in which its cell held particles, so it is accumulated over a
29 * second sample set, the occupied states, with occupancy of its own. A covariance
30 * pairing it with an ordinary field is taken over the occupied states too, and needs
31 * the ordinary member's mean over those same states; that mean is kept beside the
32 * member's own. A window requesting no particle-sampled field holds none of this.
33 *
34 * Every product is one vector carrying all of its components, not one vector per
35 * component. A symmetric second-order tensor is a single object: splitting it would
36 * cost six memory streams in the per-step accumulation loop instead of one cache
37 * line, and six collective gathers per checkpoint instead of one. Component counts
38 * that neither `da` nor `fda` provides are carried by a DM mirroring the block
39 * decomposition at that degree of freedom.
40 */
41typedef struct PicurvWindowStorage {
42 PetscInt field_count; /**< Fields accumulated. */
43 PetscInt covariance_count; /**< Covariance pairs accumulated. */
44 Vec count; /**< Per-point accepted sample count. */
45 Vec weight; /**< Per-point valid weight. */
46 Vec weight_sq; /**< Per-point squared-weight sum. */
47 Vec *mean; /**< One per field, matching that field's layout. */
48 Vec *m2; /**< One per field; NULL when no second moment was requested. */
49 Vec *cm; /**< One per covariance pair. */
50 Vec occupied_count; /**< Occupied-state count; NULL without a particle-sampled field. */
51 Vec occupied_weight; /**< Occupied-state weight; NULL without a particle-sampled field. */
52 Vec occupied_weight_sq; /**< Occupied-state squared weight; NULL likewise. */
53 Vec *occupied_mean; /**< Per field: its mean over the occupied states, for an ordinary
54 field paired with a particle-sampled one; NULL otherwise. */
55 PetscBool physical_units; /**< Holds physical units, as an ensemble of a dimensionalized load
56 does, so derivation applies no scale; otherwise solver units. */
58
59/** @brief Maximum stored length of a payload name, including the terminator. */
60#define PICURV_STATISTICS_PAYLOAD_NAME_LENGTH 96
61
62/**
63 * @brief One checkpointable accumulator vector, resolved by enumeration index.
64 *
65 * The enumeration order is the persistence contract: the manifest inventory, the
66 * checkpoint writer, and the restart reader all walk it identically, so a payload
67 * lands in the vector it came from without a separate lookup table.
68 */
69typedef struct {
70 char name[PICURV_STATISTICS_PAYLOAD_NAME_LENGTH]; /**< File basename, no extension. */
71 Vec vec; /**< Borrowed accumulator vector; never owned by the caller. */
72 PetscInt components; /**< Degrees of freedom the vector carries. */
73 const char *role; /**< Inventory role: occupancy, mean, second_moment, co_moment. */
74 const char *layout; /**< Catalog layout name for the inventory entry. */
76
77/**
78 * @brief Reports how many checkpointable vectors one window's storage holds.
79 * @param[in] storage Storage to measure.
80 * @param[out] count Payload count, including the three occupancy vectors.
81 * @return Zero on success, or `PETSC_ERR_ARG_NULL` for a null argument.
82 */
83PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count);
84
85/**
86 * @brief Resolves one enumerated payload of a window's storage.
87 *
88 * Names are derived from catalogued field names and fixed component suffixes, so
89 * they are stable across runs, rank counts, and configuration reorderings.
90 *
91 * @param[in] user Block context the storage belongs to.
92 * @param[in] definition Window definition naming the accumulated fields and pairs.
93 * @param[in] storage Storage to enumerate.
94 * @param[in] index Payload index in `[0, count)`.
95 * @param[out] payload Resolved payload; the vector is borrowed, not duplicated.
96 * @return Zero on success, or `PETSC_ERR_ARG_OUTOFRANGE` for an index outside the range.
97 */
98PetscErrorCode PicurvWindowStoragePayload(UserCtx *user, const PicurvWindowDefinition *definition,
99 const PicurvWindowStorage *storage, PetscInt index,
100 PicurvStatisticsPayload *payload);
101
102/**
103 * @brief Resolves the DM carrying a given number of accumulator components.
104 *
105 * Component counts of one and three reuse the DMs the block already owns; six is
106 * carried by the symmetric-tensor DM created alongside them. Every one of these
107 * mirrors the block decomposition exactly, so a pointwise loop can read a source
108 * field and write an accumulator at the same index.
109 *
110 * @param[in] user Block context owning the DMs.
111 * @param[in] components Component count to place.
112 * @param[out] dm Resolved DM; borrowed, never destroyed by the caller.
113 * @return Zero on success, or `PETSC_ERR_ARG_OUTOFRANGE` for an unsupported count.
114 */
115PetscErrorCode PicurvStatisticsComponentDM(UserCtx *user, PetscInt components, DM *dm);
116
117/**
118 * @brief Reports how many symmetric product components a field's second moment needs.
119 * @param[in] dof Degree of freedom of the field.
120 * @param[out] count Component count: one for a scalar, six for a three-vector.
121 * @return Zero on success, or `PETSC_ERR_ARG_OUTOFRANGE` for an unsupported dof.
122 */
123PetscErrorCode PicurvProductComponentCount(PetscInt dof, PetscInt *count);
124
125/**
126 * @brief Reports how many components a covariance between two fields needs.
127 * @param[in] dof_a Degree of freedom of the first member.
128 * @param[in] dof_b Degree of freedom of the second member.
129 * @param[out] count Component count.
130 * @return Zero on success, or `PETSC_ERR_ARG_OUTOFRANGE` for an unsupported pairing.
131 */
132PetscErrorCode PicurvCovarianceComponentCount(PetscInt dof_a, PetscInt dof_b, PetscInt *count);
133
134/**
135 * @brief Allocates the accumulator state one window owns on one block.
136 *
137 * Every vector is duplicated from one the factory already built, so no new DM or
138 * layout decision is introduced.
139 *
140 * @param[in] user Block context supplying the source fields.
141 * @param[in] definition Window definition naming the requested fields and pairs.
142 * @param[out] storage Storage to populate; zeroed on entry.
143 * @return Zero on success, or a PETSc error for an unknown field or unsupported layout.
144 */
145PetscErrorCode PicurvWindowStorageCreate(UserCtx *user, const PicurvWindowDefinition *definition,
146 PicurvWindowStorage *storage);
147
148/**
149 * @brief Releases accumulator state previously created for one window.
150 * @param[in,out] storage Storage to release; safe to call on zeroed storage.
151 * @return Zero on success.
152 */
153PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage);
154
155/** @brief Tolerance within which a negative variance is treated as floating-point noise. */
156#define PICURV_STATISTICS_VARIANCE_FLOOR 1.0e-12
157
158/** @brief One derived output field, resolved by enumeration index. */
159typedef struct {
160 char name[PICURV_STATISTICS_PAYLOAD_NAME_LENGTH]; /**< Output field name, window qualified. */
161 PetscInt components; /**< One or three. */
162 PetscBool occupied; /**< Measured over the occupied states, so undefined where they are absent. */
163 PetscBool point_averaged; /**< Reduced over homogeneous directions as the equal-weight mean of
164 point values, not from the pooled sample set. */
166
167/**
168 * @brief Reports how many derived fields a requested output set produces.
169 * @param[in] definition Window definition naming the accumulated fields and pairs.
170 * @param[in] storage Accumulator state the outputs are derived from.
171 * @param[in] outputs Comma-separated output kinds: mean, reynolds_stress, rms, tke, flux,
172 * point_variance.
173 * @param[out] count Number of derived fields.
174 * @return Zero on success, or `PETSC_ERR_ARG_WRONG` for an unknown output kind.
175 */
176PetscErrorCode PicurvWindowDerivedCount(const PicurvWindowDefinition *definition,
177 const PicurvWindowStorage *storage,
178 const char *outputs, PetscInt *count);
179
180/**
181 * @brief Derives one output field from centered accumulator state.
182 *
183 * Normalizes in exactly one place: `R_ij = C_ij / W`, `RMS_i = sqrt(R_ii)`,
184 * `k = (R_xx + R_yy + R_zz) / 2`, and a flux is the co-moment over the same weight.
185 * Each uses the moment kernels rather than repeating the division, so the online and
186 * offline halves of the pipeline cannot disagree about what centered state means.
187 *
188 * A variance that comes out slightly negative through floating-point cancellation is
189 * clamped only where a square root would otherwise fail, and only within
190 * `PICURV_STATISTICS_VARIANCE_FLOOR`. Stored state is never modified.
191 *
192 * Points the window never sampled are left at zero rather than divided by a zero
193 * weight; the valid-fraction range reports how much of the domain that covers.
194 *
195 * @param[in] user Block context supplying the target domain.
196 * @param[in] definition Window definition.
197 * @param[in] storage Accumulator state to read.
198 * @param[in] outputs Comma-separated output kinds.
199 * @param[in] index Derived field index in `[0, count)`.
200 * @param[out] scalar_target Scalar destination, used when the field has one component.
201 * @param[out] vector_target Vector destination, used when the field has three.
202 * @param[out] field Resolved name and component count of the derived field.
203 * @return Zero on success, or a PETSc error.
204 */
205PetscErrorCode PicurvWindowDerive(UserCtx *user, const PicurvWindowDefinition *definition,
206 const PicurvWindowStorage *storage, const char *outputs,
207 PetscInt index, Vec scalar_target, Vec vector_target,
208 PicurvDerivedField *field);
209
210/**
211 * @brief Reports the spatial mean of a derived field over the points a window sampled.
212 *
213 * The average is taken over targeted points that actually accumulated weight, not
214 * over the whole vector. A derived field is zero everywhere outside the target
215 * domain and at any point the mask never admitted, and those zeros are absences
216 * rather than measurements: including them would scale the answer down by the
217 * fraction of the vector the window never covered.
218 *
219 * Performs a collective reduction, so callers use it for reporting rather than per
220 * point.
221 *
222 * @param[in] user Block context supplying the target domain.
223 * @param[in] definition Window definition naming the accumulated fields.
224 * @param[in] storage Accumulator state supplying per-point occupancy.
225 * @param[in] field Derived field to average, on the cell-centred scalar DM.
226 * @param[out] mean Spatial mean; zero when the window sampled no point.
227 * @return Zero on success, or a PETSc error.
228 */
229PetscErrorCode PicurvWindowSpatialMean(UserCtx *user, const PicurvWindowDefinition *definition,
230 const PicurvWindowStorage *storage, Vec field,
231 PetscReal *mean);
232
233/**
234 * @brief Reports the range of per-point valid fraction across a window's domain.
235 *
236 * A point contributes only to the states in which the mask accepted it, so with a
237 * moving immersed body different points carry different sample counts. The ratio of
238 * a point's own count to the window's accepted-sample count is its valid fraction,
239 * and the range of that ratio is the window's mask-health indicator: a minimum of
240 * one means every point saw every state, and a minimum of zero means some point
241 * contributed nothing at all.
242 *
243 * Performs a collective reduction, so callers gate it on an already-active reporting
244 * path rather than calling it every step.
245 *
246 * @param[in] user Block context supplying the target domain and mask.
247 * @param[in] definition Window definition naming the accumulated fields.
248 * @param[in] storage Accumulator state to inspect.
249 * @param[in] sample_count Accepted states the window has recorded.
250 * @param[out] minimum Smallest valid fraction; one when no point is targeted.
251 * @param[out] maximum Largest valid fraction; zero when no point is targeted.
252 * @return Zero on success, or a PETSc error.
253 */
254PetscErrorCode PicurvWindowValidFractionRange(UserCtx *user, const PicurvWindowDefinition *definition,
255 const PicurvWindowStorage *storage, PetscInt sample_count,
256 PetscReal *minimum, PetscReal *maximum);
257
258/**
259 * @brief Applies one accepted completed state to a window's accumulators.
260 *
261 * Iterates the pointwise target domain, skipping points the mask rejects, and
262 * updates each point's occupancy and every requested moment and co-moment through
263 * the centered kernels.
264 *
265 * @param[in] user Block context supplying the source fields.
266 * @param[in] definition Window definition.
267 * @param[in,out] storage Accumulator state to update.
268 * @param[in] weight Weight the window assigned to this state; must be positive.
269 * @return Zero on success, or a PETSc error.
270 */
271PetscErrorCode PicurvWindowAccumulate(UserCtx *user, const PicurvWindowDefinition *definition,
272 PicurvWindowStorage *storage, PetscReal weight);
273
274/**
275 * @brief Fills a window's storage from the particles sampling each cell at one instant.
276 *
277 * The particles a cell holds are that cell's samples, each of unit weight, so the
278 * stored state is the cell's particle ensemble: its count, the ensemble mean of every
279 * requested field, and the centred sums of every requested self-product and
280 * covariance. Each field is identified by its Eulerian scatter target, which fixes its
281 * layout and the names its derived outputs carry.
282 *
283 * The runtime accumulator streams states it sees once, so it updates running means
284 * sample by sample. A snapshot holds every sample at once, which admits the two-pass
285 * form instead: the means first, through the same particle sum the runtime scatter
286 * uses, then the centred products about them. That is the more accurate of the two,
287 * needs no division per sample, and does not depend on particle order. Both produce
288 * the same stored state, so derivation and output treat the two alike.
289 *
290 * A particle contributes wherever its cell lies in this rank's ghosted patch, and the
291 * patch sums are added onto their owners, so a particle need not sit on the rank that
292 * owns its cell. One outside the patch is skipped, as in the scatter.
293 *
294 * @param[in] user Block context supplying the swarm and the grid.
295 * @param[in] definition Fields and pairs to accumulate, by Eulerian scatter target.
296 * @param[in,out] storage Freshly created storage for @p definition; overwritten.
297 * @return Zero on success, or a PETSc error, including for a field no particle field
298 * scatters to.
299 */
300PetscErrorCode PicurvWindowStorageFromParticles(UserCtx *user, const PicurvWindowDefinition *definition,
301 PicurvWindowStorage *storage);
302
303/**
304 * @brief Merges a window's pointwise state over homogeneous directions.
305 *
306 * Every point of a retained slot is combined into one state through the weighted
307 * merge: the slot mean is the weight-averaged point mean, and the slot co-moment adds
308 * to the point co-moments the spread of the point means about it,
309 * \f$C = \sum_p [C_p + W_p (\mu_{a,p} - \mu_a)(\mu_{b,p} - \mu_b)] / \sum_p W_p\f$.
310 * It is the moment of the slot's whole sample set, which an average of the point
311 * statistics is not.
312 *
313 * The result is written back at every point of its slot, as a state of unit weight
314 * holding the merged mean and the merged co-moments already divided by the merged
315 * weight. The derivation therefore applies to it unchanged, and a point carries
316 * weight only where its slot was sampled. Its occupancy totals are not the slot's.
317 *
318 * @param[in] user Block context supplying the target domain and mask.
319 * @param[in] definition Window definition.
320 * @param[in] storage Pointwise state to merge.
321 * @param[in] average_direction Directions to merge over, in `(i, j, k)` order.
322 * @param[out] reduced Storage created for @p definition; overwritten.
323 * @return Zero on success, or a PETSc error.
324 */
325PetscErrorCode PicurvWindowStorageReduce(UserCtx *user, const PicurvWindowDefinition *definition,
326 const PicurvWindowStorage *storage,
327 const PetscBool average_direction[3],
328 PicurvWindowStorage *reduced);
329
330#endif /* PICURV_STATISTICS_ACCUMULATOR_H */
Vec weight
Per-point valid weight.
PetscInt components
Degrees of freedom the vector carries.
PetscInt components
One or three.
PetscErrorCode PicurvProductComponentCount(PetscInt dof, PetscInt *count)
Reports how many symmetric product components a field's second moment needs.
#define PICURV_STATISTICS_PAYLOAD_NAME_LENGTH
Maximum stored length of a payload name, including the terminator.
Vec occupied_weight_sq
Occupied-state squared weight; NULL likewise.
Vec weight_sq
Per-point squared-weight sum.
PetscErrorCode PicurvWindowStorageReduce(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const PetscBool average_direction[3], PicurvWindowStorage *reduced)
Merges a window's pointwise state over homogeneous directions.
PetscInt field_count
Fields accumulated.
PetscInt covariance_count
Covariance pairs accumulated.
PetscErrorCode PicurvWindowDerive(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, PetscInt index, Vec scalar_target, Vec vector_target, PicurvDerivedField *field)
Derives one output field from centered accumulator state.
Vec occupied_count
Occupied-state count; NULL without a particle-sampled field.
Vec * mean
One per field, matching that field's layout.
PetscBool point_averaged
Reduced over homogeneous directions as the equal-weight mean of point values, not from the pooled sam...
Vec occupied_weight
Occupied-state weight; NULL without a particle-sampled field.
Vec vec
Borrowed accumulator vector; never owned by the caller.
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 PicurvCovarianceComponentCount(PetscInt dof_a, PetscInt dof_b, PetscInt *count)
Reports how many components a covariance between two fields needs.
PetscErrorCode PicurvWindowStorageFromParticles(UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
Fills a window's storage from the particles sampling each cell at one instant.
PetscErrorCode PicurvWindowStoragePayload(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt index, PicurvStatisticsPayload *payload)
Resolves one enumerated payload of a window's storage.
Vec * m2
One per field; NULL when no second moment was requested.
const char * role
Inventory role: occupancy, mean, second_moment, co_moment.
PetscErrorCode PicurvWindowValidFractionRange(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt sample_count, PetscReal *minimum, PetscReal *maximum)
Reports the range of per-point valid fraction across a window's domain.
PetscBool occupied
Measured over the occupied states, so undefined where they are absent.
Vec * occupied_mean
Per field: its mean over the occupied states, for an ordinary field paired with a particle-sampled on...
PetscErrorCode PicurvStatisticsComponentDM(UserCtx *user, PetscInt components, DM *dm)
Resolves the DM carrying a given number of accumulator components.
PetscErrorCode PicurvWindowSpatialMean(UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, Vec field, PetscReal *mean)
Reports the spatial mean of a derived field over the points a window sampled.
Vec count
Per-point accepted sample count.
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.
const char * layout
Catalog layout name for the inventory entry.
PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count)
Reports how many checkpointable vectors one window's storage holds.
Vec * cm
One per covariance pair.
PetscBool physical_units
Holds physical units, as an ensemble of a dimensionalized load does, so derivation applies no scale; ...
One derived output field, resolved by enumeration index.
One checkpointable accumulator vector, resolved by enumeration index.
Independent accumulator state for one window on one block.
Window lifecycle, scheduling, and weighting for the field-statistics pipeline.
The scientifically immutable definition of one window.
Main header file for a complex fluid dynamics solver.
User-defined context containing data specific to a single computational grid level.
Definition variables.h:1157