PICurv 0.1.0
A Parallel Particle-In-Cell Solver for Curvilinear LES
 
Loading...
Searching...
No Matches
Data Structures | Macros | Typedefs | Functions
statistics_accumulator.h File Reference

Per-window PETSc accumulator storage and pointwise application. More...

#include "variables.h"
#include "statistics_window.h"
Include dependency graph for statistics_accumulator.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  PicurvWindowStorage
 Independent accumulator state for one window on one block. More...
 
struct  PicurvStatisticsPayload
 One checkpointable accumulator vector, resolved by enumeration index. More...
 
struct  PicurvDerivedField
 One derived output field, resolved by enumeration index. More...
 

Macros

#define PICURV_STATISTICS_PAYLOAD_NAME_LENGTH   96
 Maximum stored length of a payload name, including the terminator.
 
#define PICURV_STATISTICS_VARIANCE_FLOOR   1.0e-12
 Tolerance within which a negative variance is treated as floating-point noise.
 

Typedefs

typedef struct PicurvWindowStorage PicurvWindowStorage
 Independent accumulator state for one window on one block.
 

Functions

PetscErrorCode PicurvWindowStoragePayloadCount (const PicurvWindowStorage *storage, PetscInt *count)
 Reports how many checkpointable vectors one window's storage holds.
 
PetscErrorCode PicurvWindowStoragePayload (UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, PetscInt index, PicurvStatisticsPayload *payload)
 Resolves one enumerated payload of a window's storage.
 
PetscErrorCode PicurvStatisticsComponentDM (UserCtx *user, PetscInt components, DM *dm)
 Resolves the DM carrying a given number of accumulator components.
 
PetscErrorCode PicurvProductComponentCount (PetscInt dof, PetscInt *count)
 Reports how many symmetric product components a field's second moment needs.
 
PetscErrorCode PicurvCovarianceComponentCount (PetscInt dof_a, PetscInt dof_b, PetscInt *count)
 Reports how many components a covariance between two fields needs.
 
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.
 
PetscErrorCode PicurvWindowDerivedCount (const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, PetscInt *count)
 Reports how many derived fields a requested output set produces.
 
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.
 
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.
 
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.
 
PetscErrorCode PicurvWindowAccumulate (UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage, PetscReal weight)
 Applies one accepted completed state to a window's accumulators.
 
PetscErrorCode PicurvWindowStorageFromParticles (UserCtx *user, const PicurvWindowDefinition *definition, PicurvWindowStorage *storage)
 Fills a window's storage from the particles sampling each cell at one instant.
 
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.
 

Detailed Description

Per-window PETSc accumulator storage and pointwise application.

Holds the independent state each named window owns, and applies one accepted completed state to it, per 4. Accumulated State and Component Order.

Storage is allocated once by the vector factory and released once at teardown. Application is strictly pointwise: it reads a source field value at an owned point and updates that point's accumulator, so it performs no halo exchange and allocates nothing.

Definition in file statistics_accumulator.h.


Data Structure Documentation

◆ PicurvWindowStorage

struct PicurvWindowStorage

Independent accumulator state for one window on one block.

Per-point occupancy is tracked separately from the field moments because the fluid mask can move: a point contributes only to the states in which it was valid, so its own count and weight are what normalize its moments.

A particle-sampled field (FIELD_CAPABILITY_PARTICLE_SAMPLED) is a measurement only in the states in which its cell held particles, so it is accumulated over a second sample set, the occupied states, with occupancy of its own. A covariance pairing it with an ordinary field is taken over the occupied states too, and needs the ordinary member's mean over those same states; that mean is kept beside the member's own. A window requesting no particle-sampled field holds none of this.

Every product is one vector carrying all of its components, not one vector per component. A symmetric second-order tensor is a single object: splitting it would cost six memory streams in the per-step accumulation loop instead of one cache line, and six collective gathers per checkpoint instead of one. Component counts that neither da nor fda provides are carried by a DM mirroring the block decomposition at that degree of freedom.

Definition at line 41 of file statistics_accumulator.h.

Data Fields
PetscInt field_count Fields accumulated.
PetscInt covariance_count Covariance pairs accumulated.
Vec count Per-point accepted sample count.
Vec weight Per-point valid weight.
Vec weight_sq Per-point squared-weight sum.
Vec * mean One per field, matching that field's layout.
Vec * m2 One per field; NULL when no second moment was requested.
Vec * cm One per covariance pair.
Vec occupied_count Occupied-state count; NULL without a particle-sampled field.
Vec occupied_weight Occupied-state weight; NULL without a particle-sampled field.
Vec occupied_weight_sq Occupied-state squared weight; NULL likewise.
Vec * occupied_mean Per field: its mean over the occupied states, for an ordinary field paired with a particle-sampled one; NULL otherwise.
PetscBool physical_units Holds physical units, as an ensemble of a dimensionalized load does, so derivation applies no scale; otherwise solver units.

◆ PicurvStatisticsPayload

struct PicurvStatisticsPayload

One checkpointable accumulator vector, resolved by enumeration index.

The enumeration order is the persistence contract: the manifest inventory, the checkpoint writer, and the restart reader all walk it identically, so a payload lands in the vector it came from without a separate lookup table.

Definition at line 69 of file statistics_accumulator.h.

Data Fields
char name[96] File basename, no extension.
Vec vec Borrowed accumulator vector; never owned by the caller.
PetscInt components Degrees of freedom the vector carries.
const char * role Inventory role: occupancy, mean, second_moment, co_moment.
const char * layout Catalog layout name for the inventory entry.

◆ PicurvDerivedField

struct PicurvDerivedField

One derived output field, resolved by enumeration index.

Definition at line 159 of file statistics_accumulator.h.

Data Fields
char name[96] Output field name, window qualified.
PetscInt components One or three.
PetscBool occupied Measured over the occupied states, so undefined where they are absent.
PetscBool point_averaged Reduced over homogeneous directions as the equal-weight mean of point values, not from the pooled sample set.

Macro Definition Documentation

◆ PICURV_STATISTICS_PAYLOAD_NAME_LENGTH

#define PICURV_STATISTICS_PAYLOAD_NAME_LENGTH   96

Maximum stored length of a payload name, including the terminator.

Definition at line 60 of file statistics_accumulator.h.

◆ PICURV_STATISTICS_VARIANCE_FLOOR

#define PICURV_STATISTICS_VARIANCE_FLOOR   1.0e-12

Tolerance within which a negative variance is treated as floating-point noise.

Definition at line 156 of file statistics_accumulator.h.

Typedef Documentation

◆ PicurvWindowStorage

Independent accumulator state for one window on one block.

Per-point occupancy is tracked separately from the field moments because the fluid mask can move: a point contributes only to the states in which it was valid, so its own count and weight are what normalize its moments.

A particle-sampled field (FIELD_CAPABILITY_PARTICLE_SAMPLED) is a measurement only in the states in which its cell held particles, so it is accumulated over a second sample set, the occupied states, with occupancy of its own. A covariance pairing it with an ordinary field is taken over the occupied states too, and needs the ordinary member's mean over those same states; that mean is kept beside the member's own. A window requesting no particle-sampled field holds none of this.

Every product is one vector carrying all of its components, not one vector per component. A symmetric second-order tensor is a single object: splitting it would cost six memory streams in the per-step accumulation loop instead of one cache line, and six collective gathers per checkpoint instead of one. Component counts that neither da nor fda provides are carried by a DM mirroring the block decomposition at that degree of freedom.

Function Documentation

◆ PicurvWindowStoragePayloadCount()

PetscErrorCode PicurvWindowStoragePayloadCount ( const PicurvWindowStorage *  storage,
PetscInt *  count 
)

Reports how many checkpointable vectors one window's storage holds.

Parameters
[in]storageStorage to measure.
[out]countPayload count, including the three occupancy vectors.
Returns
Zero on success, or PETSC_ERR_ARG_NULL for a null argument.

Reports how many checkpointable vectors one window's storage holds.

See also
PicurvWindowStoragePayloadCount()

Definition at line 386 of file statistics_accumulator.c.

387{
388 PetscFunctionBeginUser;
390 PetscCheck(storage != NULL && count != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
391 "Storage and count output are required.");
392 *count = 3 + storage->field_count + storage->covariance_count + (storage->occupied_count ? 3 : 0);
393 for (PetscInt field_index = 0; storage->occupied_mean && field_index < storage->field_count; ++field_index) {
394 if (storage->occupied_mean[field_index]) *count += 1;
395 }
396 /* A field without a requested second moment holds no product vector, so the
397 * enumeration skips it rather than emitting an empty payload. */
398 for (PetscInt field_index = 0; storage->m2 && field_index < storage->field_count; ++field_index) {
399 if (storage->m2[field_index]) *count += 1;
400 }
402 PetscFunctionReturn(0);
403}
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
PetscInt field_count
Fields accumulated.
PetscInt covariance_count
Covariance pairs accumulated.
Vec occupied_count
Occupied-state count; NULL without a particle-sampled field.
Vec * m2
One per field; NULL when no second moment was requested.
Vec * occupied_mean
Per field: its mean over the occupied states, for an ordinary field paired with a particle-sampled on...
Here is the caller graph for this function:

◆ PicurvWindowStoragePayload()

PetscErrorCode PicurvWindowStoragePayload ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
const PicurvWindowStorage *  storage,
PetscInt  index,
PicurvStatisticsPayload *  payload 
)

Resolves one enumerated payload of a window's storage.

Names are derived from catalogued field names and fixed component suffixes, so they are stable across runs, rank counts, and configuration reorderings.

Parameters
[in]userBlock context the storage belongs to.
[in]definitionWindow definition naming the accumulated fields and pairs.
[in]storageStorage to enumerate.
[in]indexPayload index in [0, count).
[out]payloadResolved payload; the vector is borrowed, not duplicated.
Returns
Zero on success, or PETSC_ERR_ARG_OUTOFRANGE for an index outside the range.

Resolves one enumerated payload of a window's storage.

See also
PicurvWindowStoragePayload()

Definition at line 409 of file statistics_accumulator.c.

412{
413 PetscInt total = 0;
414 PetscInt cursor = index;
415
416 PetscFunctionBeginUser;
418 PetscCheck(user != NULL && definition != NULL && storage != NULL && payload != NULL,
419 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
420 "Context, definition, storage, and payload output are required.");
421 PetscCall(PicurvWindowStoragePayloadCount(storage, &total));
422 PetscCheck(index >= 0 && index < total, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
423 "Payload index %" PetscInt_FMT " is outside [0, %" PetscInt_FMT ").", index, total);
424 PetscCall(PetscMemzero(payload, sizeof(*payload)));
425
426 /* Occupancy first, then means, then products, then co-moments. The order is the
427 * persistence contract: the manifest inventory, the writer, and the reader all
428 * walk it identically. The occupied set's occupancy follows the shared one and its
429 * means follow the field means, so a window without it keeps its layout. */
430 {
431 static const char *const occupancy_name[6] = {"count", "weight", "weight_sq", "occupied_count",
432 "occupied_weight", "occupied_weight_sq"};
433 const Vec occupancy[6] = {storage->count, storage->weight, storage->weight_sq, storage->occupied_count,
434 storage->occupied_weight, storage->occupied_weight_sq};
435 const PetscInt occupancy_count = storage->occupied_count ? 6 : 3;
436
437 if (cursor < occupancy_count) {
438 PetscCall(PetscStrncpy(payload->name, occupancy_name[cursor], sizeof(payload->name)));
439 payload->vec = occupancy[cursor];
440 payload->components = 1;
441 payload->role = "occupancy";
444 PetscFunctionReturn(0);
445 }
446 cursor -= occupancy_count;
447 }
448
449 if (cursor < storage->field_count) {
450 const FieldDescriptor *descriptor = NULL;
451
452 PetscCall(FieldGetDescriptor((FieldId)definition->fields[cursor].field_id, &descriptor));
453 PetscCall(PetscSNPrintf(payload->name, sizeof(payload->name), "%s_mean",
454 descriptor->canonical_name));
455 payload->vec = storage->mean[cursor];
456 payload->components = descriptor->dof;
457 payload->role = "mean";
458 payload->layout = FieldLayoutName(descriptor->layout);
460 PetscFunctionReturn(0);
461 }
462 cursor -= storage->field_count;
463 for (PetscInt field_index = 0; storage->occupied_mean && field_index < storage->field_count; ++field_index) {
464 const FieldDescriptor *descriptor = NULL;
465
466 if (!storage->occupied_mean[field_index]) continue;
467 if (cursor-- != 0) continue;
468 PetscCall(FieldGetDescriptor((FieldId)definition->fields[field_index].field_id, &descriptor));
469 PetscCall(PetscSNPrintf(payload->name, sizeof(payload->name), "%s_occupied_mean",
470 descriptor->canonical_name));
471 payload->vec = storage->occupied_mean[field_index];
472 payload->components = descriptor->dof;
473 payload->role = "mean";
474 payload->layout = FieldLayoutName(descriptor->layout);
476 PetscFunctionReturn(0);
477 }
478
479 {
480 PetscInt product_count = 0;
481 PetscInt seen = 0;
482
483 for (PetscInt field_index = 0; storage->m2 && field_index < storage->field_count; ++field_index) {
484 if (storage->m2[field_index]) ++product_count;
485 }
486 if (cursor < product_count) {
487 for (PetscInt field_index = 0; field_index < storage->field_count; ++field_index) {
488 const FieldDescriptor *descriptor = NULL;
489
490 if (!storage->m2[field_index]) continue;
491 if (seen++ != cursor) continue;
492 PetscCall(FieldGetDescriptor((FieldId)definition->fields[field_index].field_id, &descriptor));
493 PetscCall(PetscSNPrintf(payload->name, sizeof(payload->name), "%s_m2",
494 descriptor->canonical_name));
495 payload->vec = storage->m2[field_index];
496 PetscCall(PicurvProductComponentCount(descriptor->dof, &payload->components));
497 payload->role = "second_moment";
498 payload->layout = FieldLayoutName(descriptor->layout);
500 PetscFunctionReturn(0);
501 }
502 }
503 cursor -= product_count;
504 }
505
506 {
507 const FieldDescriptor *first = NULL;
508 const FieldDescriptor *second = NULL;
509
510 PetscCheck(cursor >= 0 && cursor < storage->covariance_count, PETSC_COMM_SELF, PETSC_ERR_PLIB,
511 "Payload index %" PetscInt_FMT " fell through the storage enumeration.", index);
512 PetscCall(FieldGetDescriptor((FieldId)definition->covariances[cursor].first, &first));
513 PetscCall(FieldGetDescriptor((FieldId)definition->covariances[cursor].second, &second));
514 PetscCall(PetscSNPrintf(payload->name, sizeof(payload->name), "%s_%s_cm",
515 first->canonical_name, second->canonical_name));
516 payload->vec = storage->cm[cursor];
517 PetscCall(PicurvCovarianceComponentCount(first->dof, second->dof, &payload->components));
518 payload->role = "co_moment";
519 payload->layout = FieldLayoutName(first->layout);
520 }
522 PetscFunctionReturn(0);
523}
FieldLayout layout
@ FIELD_LAYOUT_CELL_CENTERED
const char * canonical_name
const char * FieldLayoutName(FieldLayout layout)
Return a stable printable label for a field layout.
PetscErrorCode FieldGetDescriptor(FieldId field_id, const FieldDescriptor **descriptor)
Return immutable metadata for a valid field identifier.
FieldId
Compile-time identity for a catalogued Eulerian field.
Immutable metadata for one field identity.
PetscErrorCode PicurvProductComponentCount(PetscInt dof, PetscInt *count)
Implementation of PicurvProductComponentCount().
PetscErrorCode PicurvCovarianceComponentCount(PetscInt dof_a, PetscInt dof_b, PetscInt *count)
Implementation of PicurvCovarianceComponentCount().
PetscErrorCode PicurvWindowStoragePayloadCount(const PicurvWindowStorage *storage, PetscInt *count)
Implementation of PicurvWindowStoragePayloadCount().
Vec weight
Per-point valid weight.
PetscInt components
Degrees of freedom the vector carries.
Vec occupied_weight_sq
Occupied-state squared weight; NULL likewise.
Vec weight_sq
Per-point squared-weight sum.
Vec * mean
One per field, matching that field's layout.
Vec occupied_weight
Occupied-state weight; NULL without a particle-sampled field.
Vec vec
Borrowed accumulator vector; never owned by the caller.
const char * role
Inventory role: occupancy, mean, second_moment, co_moment.
Vec count
Per-point accepted sample count.
char name[96]
File basename, no extension.
const char * layout
Catalog layout name for the inventory entry.
Vec * cm
One per covariance pair.
PetscInt first
First member; must also appear in the field list.
PicurvWindowFieldRequest fields[16]
PetscInt second
Second member; must also appear in the field list.
PicurvWindowCovarianceRequest covariances[16]
PetscInt field_id
Catalogued Eulerian field identity.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvStatisticsComponentDM()

PetscErrorCode PicurvStatisticsComponentDM ( UserCtx *  user,
PetscInt  components,
DM *  dm 
)

Resolves the DM carrying a given number of accumulator components.

Component counts of one and three reuse the DMs the block already owns; six is carried by the symmetric-tensor DM created alongside them. Every one of these mirrors the block decomposition exactly, so a pointwise loop can read a source field and write an accumulator at the same index.

Parameters
[in]userBlock context owning the DMs.
[in]componentsComponent count to place.
[out]dmResolved DM; borrowed, never destroyed by the caller.
Returns
Zero on success, or PETSC_ERR_ARG_OUTOFRANGE for an unsupported count.

Resolves the DM carrying a given number of accumulator components.

See also
PicurvStatisticsComponentDM()

Definition at line 126 of file statistics_accumulator.c.

127{
128 PetscFunctionBeginUser;
130 PetscCheck(user != NULL && dm != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
131 "Context and DM output are required.");
132 switch (components) {
133 case 1: *dm = user->da; break;
134 case 3: *dm = user->fda; break;
135 case 6: *dm = user->fda6; break;
136 default:
137 SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
138 "No block DM carries %" PetscInt_FMT " accumulator components.", components);
139 }
140 PetscCheck(*dm != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
141 "The block DM for %" PetscInt_FMT " accumulator components was never created.",
142 components);
144 PetscFunctionReturn(0);
145}
Here is the caller graph for this function:

◆ PicurvProductComponentCount()

PetscErrorCode PicurvProductComponentCount ( PetscInt  dof,
PetscInt *  count 
)

Reports how many symmetric product components a field's second moment needs.

Parameters
[in]dofDegree of freedom of the field.
[out]countComponent count: one for a scalar, six for a three-vector.
Returns
Zero on success, or PETSC_ERR_ARG_OUTOFRANGE for an unsupported dof.

Reports how many symmetric product components a field's second moment needs.

See also
PicurvProductComponentCount()

Definition at line 90 of file statistics_accumulator.c.

91{
92 PetscFunctionBeginUser;
94 PetscCheck(count != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Count output is required.");
95 PetscCheck(dof == 1 || dof == 3, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
96 "Self-products are supported for scalar and three-vector fields, got dof %" PetscInt_FMT ".", dof);
97 *count = (dof == 1) ? 1 : 6;
99 PetscFunctionReturn(0);
100}
Here is the caller graph for this function:

◆ PicurvCovarianceComponentCount()

PetscErrorCode PicurvCovarianceComponentCount ( PetscInt  dof_a,
PetscInt  dof_b,
PetscInt *  count 
)

Reports how many components a covariance between two fields needs.

Parameters
[in]dof_aDegree of freedom of the first member.
[in]dof_bDegree of freedom of the second member.
[out]countComponent count.
Returns
Zero on success, or PETSC_ERR_ARG_OUTOFRANGE for an unsupported pairing.

Reports how many components a covariance between two fields needs.

See also
PicurvCovarianceComponentCount()

Definition at line 106 of file statistics_accumulator.c.

107{
108 PetscFunctionBeginUser;
110 PetscCheck(count != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Count output is required.");
111 /* Scalar-scalar and vector-scalar pairs only; a vector-vector cross product
112 * would need a nine-component carrier that nothing allocates. */
113 PetscCheck((dof_a == 1 && dof_b == 1) || (dof_a == 3 && dof_b == 1) || (dof_a == 1 && dof_b == 3),
114 PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
115 "Covariance is supported for scalar-scalar and vector-scalar pairs, got dof %" PetscInt_FMT
116 " and %" PetscInt_FMT ".", dof_a, dof_b);
117 *count = (dof_a == 3 || dof_b == 3) ? 3 : 1;
119 PetscFunctionReturn(0);
120}
Here is the caller graph for this function:

◆ PicurvWindowStorageCreate()

PetscErrorCode PicurvWindowStorageCreate ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
PicurvWindowStorage *  storage 
)

Allocates the accumulator state one window owns on one block.

Every vector is duplicated from one the factory already built, so no new DM or layout decision is introduced.

Parameters
[in]userBlock context supplying the source fields.
[in]definitionWindow definition naming the requested fields and pairs.
[out]storageStorage to populate; zeroed on entry.
Returns
Zero on success, or a PETSc error for an unknown field or unsupported layout.

Allocates the accumulator state one window owns on one block.

See also
PicurvWindowStorageCreate()

Definition at line 223 of file statistics_accumulator.c.

225{
226 PetscFunctionBeginUser;
228 PetscCheck(user != NULL && definition != NULL && storage != NULL,
229 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, definition, and storage are required.");
230 PetscCall(PetscMemzero(storage, sizeof(*storage)));
231 storage->field_count = definition->field_count;
232 storage->covariance_count = definition->covariance_count;
233
234 /* Occupancy is per point and scalar regardless of what is accumulated. */
235 PetscCall(DMCreateGlobalVector(user->da, &storage->count));
236 PetscCall(VecSet(storage->count, 0.0));
237 PetscCall(DMCreateGlobalVector(user->da, &storage->weight));
238 PetscCall(VecSet(storage->weight, 0.0));
239 PetscCall(DMCreateGlobalVector(user->da, &storage->weight_sq));
240 PetscCall(VecSet(storage->weight_sq, 0.0));
241
242 if (definition->field_count > 0) {
243 PetscCall(PetscCalloc1((size_t)definition->field_count, &storage->mean));
244 PetscCall(PetscCalloc1((size_t)definition->field_count, &storage->m2));
245 }
246 for (PetscInt field_index = 0; field_index < definition->field_count; ++field_index) {
247 FieldView view;
248 PetscInt components = 0;
249 DM product_dm = NULL;
250
251 PetscCall(FieldGetView(user, (FieldId)definition->fields[field_index].field_id, &view));
252 /* The mean matches the source field's own layout, so it comes from that
253 * field's DM and inherits its decomposition. */
254 PetscCall(DMCreateGlobalVector(view.dm, &storage->mean[field_index]));
255 PetscCall(VecSet(storage->mean[field_index], 0.0));
256 if (!definition->fields[field_index].want_second) continue;
257 PetscCall(PicurvProductComponentCount(view.descriptor->dof, &components));
258 PetscCall(PicurvStatisticsComponentDM(user, components, &product_dm));
259 PetscCall(DMCreateGlobalVector(product_dm, &storage->m2[field_index]));
260 PetscCall(VecSet(storage->m2[field_index], 0.0));
261 }
262
263 if (definition->covariance_count > 0) {
264 PetscCall(PetscCalloc1((size_t)definition->covariance_count, &storage->cm));
265 }
266 /* The occupied sample set exists only when something is measured over it. */
267 for (PetscInt field_index = 0; field_index < definition->field_count; ++field_index) {
268 if (RequestSampleSet(definition, field_index, -1) != SAMPLE_SET_OCCUPIED) continue;
269 PetscCall(DMCreateGlobalVector(user->da, &storage->occupied_count));
270 PetscCall(VecSet(storage->occupied_count, 0.0));
271 PetscCall(VecDuplicate(storage->occupied_count, &storage->occupied_weight));
272 PetscCall(VecSet(storage->occupied_weight, 0.0));
273 PetscCall(VecDuplicate(storage->occupied_count, &storage->occupied_weight_sq));
274 PetscCall(VecSet(storage->occupied_weight_sq, 0.0));
275 PetscCall(PetscCalloc1((size_t)definition->field_count, &storage->occupied_mean));
276 break;
277 }
278 for (PetscInt pair_index = 0; pair_index < definition->covariance_count; ++pair_index) {
279 FieldView view_a, view_b;
280 PetscInt components = 0;
281 DM pair_dm = NULL;
282
283 PetscCall(FieldGetView(user, (FieldId)definition->covariances[pair_index].first, &view_a));
284 PetscCall(FieldGetView(user, (FieldId)definition->covariances[pair_index].second, &view_b));
285 PetscCall(PicurvCovarianceComponentCount(view_a.descriptor->dof, view_b.descriptor->dof, &components));
286 PetscCall(PicurvStatisticsComponentDM(user, components, &pair_dm));
287 PetscCall(DMCreateGlobalVector(pair_dm, &storage->cm[pair_index]));
288 PetscCall(VecSet(storage->cm[pair_index], 0.0));
289
290 /* An ordinary member of an occupied pair is centred on its occupied-state mean. */
291 for (PetscInt member = 0; member < 2 && RequestSampleSet(definition, -1, pair_index) == SAMPLE_SET_OCCUPIED; ++member) {
292 const PetscInt field_id = member ? definition->covariances[pair_index].second
293 : definition->covariances[pair_index].first;
294 PetscInt slot = 0;
295
296 if (FieldIsParticleSampled(field_id)) continue;
297 PetscCall(FindFieldSlot(definition, field_id, &slot));
298 if (storage->occupied_mean[slot]) continue;
299 PetscCall(VecDuplicate(storage->mean[slot], &storage->occupied_mean[slot]));
300 PetscCall(VecSet(storage->occupied_mean[slot], 0.0));
301 }
302 }
303
304 /* Report what this window costs and what it covers, once per block at setup.
305 * The point count is a function of layout, dimensions, and periodicity alone, so
306 * it tells an operator what "per point" will mean before any sample is taken. */
307 {
309 PetscInt payloads = 0;
310 PetscInt points = 0;
311
312 PetscCall(PicurvWindowStoragePayloadCount(storage, &payloads));
313 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
315 PetscCall(SpatialTargetPlanGlobalPointCount(&plan, PETSC_COMM_WORLD, &points));
317 "Statistics window '%s' block %d: %d accumulator vector(s) over %d point(s).\n",
318 definition->name, (int)user->_this, (int)payloads, (int)points);
319 }
321 PetscFunctionReturn(0);
322}
const FieldDescriptor * descriptor
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
Non-owning runtime objects resolved for one field and UserCtx.
#define LOCAL
Logging scope definitions for controlling message output.
Definition logging.h:45
#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
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
@ SAMPLE_SET_OCCUPIED
The accepted states in which the cell held particles.
static PetscErrorCode FindFieldSlot(const PicurvWindowDefinition *definition, PetscInt field_id, PetscInt *slot)
Internal helper: locates the storage slot holding one field's running mean.
PetscErrorCode PicurvStatisticsComponentDM(UserCtx *user, PetscInt components, DM *dm)
Implementation of PicurvStatisticsComponentDM().
static PetscBool FieldIsParticleSampled(PetscInt field_id)
Internal helper: whether a catalogued field is measured only where particles are.
static SampleSet RequestSampleSet(const PicurvWindowDefinition *definition, PetscInt slot, PetscInt pair)
Internal helper: the sample set one field slot, or one covariance pair, uses.
@ PICURV_STATISTICS_MASK_FLUID
PetscErrorCode SpatialTargetPlanGlobalPointCount(const SpatialTargetPlan *plan, MPI_Comm comm, PetscInt *count)
Counts the points contributed across a communicator.
PetscErrorCode SpatialTargetPlanCreate(UserCtx *user, FieldId field_id, PicurvStatisticsMask mask, SpatialTargetPlan *plan)
Resolves the iteration domain for one field on one block.
Resolved iteration domain for one field on one block.
PetscBool want_second
Also keep the centered second moment.
PetscInt _this
Definition variables.h:1175
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowStorageDestroy()

PetscErrorCode PicurvWindowStorageDestroy ( PicurvWindowStorage *  storage)

Releases accumulator state previously created for one window.

Parameters
[in,out]storageStorage to release; safe to call on zeroed storage.
Returns
Zero on success.

Releases accumulator state previously created for one window.

See also
PicurvWindowStorageDestroy()

Definition at line 328 of file statistics_accumulator.c.

329{
330 PetscFunctionBeginUser;
332 if (storage == NULL) { PROFILE_HELPER_END; PetscFunctionReturn(0); }
333 if (storage->count) PetscCall(VecDestroy(&storage->count));
334 if (storage->weight) PetscCall(VecDestroy(&storage->weight));
335 if (storage->weight_sq) PetscCall(VecDestroy(&storage->weight_sq));
336 for (PetscInt field_index = 0; storage->mean && field_index < storage->field_count; ++field_index) {
337 if (storage->mean[field_index]) PetscCall(VecDestroy(&storage->mean[field_index]));
338 }
339 for (PetscInt field_index = 0; storage->m2 && field_index < storage->field_count; ++field_index) {
340 if (storage->m2[field_index]) PetscCall(VecDestroy(&storage->m2[field_index]));
341 }
342 for (PetscInt pair_index = 0; storage->cm && pair_index < storage->covariance_count; ++pair_index) {
343 if (storage->cm[pair_index]) PetscCall(VecDestroy(&storage->cm[pair_index]));
344 }
345 for (PetscInt field_index = 0; storage->occupied_mean && field_index < storage->field_count; ++field_index) {
346 if (storage->occupied_mean[field_index]) PetscCall(VecDestroy(&storage->occupied_mean[field_index]));
347 }
348 if (storage->occupied_count) PetscCall(VecDestroy(&storage->occupied_count));
349 if (storage->occupied_weight) PetscCall(VecDestroy(&storage->occupied_weight));
350 if (storage->occupied_weight_sq) PetscCall(VecDestroy(&storage->occupied_weight_sq));
351 if (storage->occupied_mean) PetscCall(PetscFree(storage->occupied_mean));
352 if (storage->mean) PetscCall(PetscFree(storage->mean));
353 if (storage->m2) PetscCall(PetscFree(storage->m2));
354 if (storage->cm) PetscCall(PetscFree(storage->cm));
355 PetscCall(PetscMemzero(storage, sizeof(*storage)));
357 PetscFunctionReturn(0);
358}
#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
Here is the caller graph for this function:

◆ PicurvWindowDerivedCount()

PetscErrorCode PicurvWindowDerivedCount ( const PicurvWindowDefinition *  definition,
const PicurvWindowStorage *  storage,
const char *  outputs,
PetscInt *  count 
)

Reports how many derived fields a requested output set produces.

Parameters
[in]definitionWindow definition naming the accumulated fields and pairs.
[in]storageAccumulator state the outputs are derived from.
[in]outputsComma-separated output kinds: mean, reynolds_stress, rms, tke, flux, point_variance.
[out]countNumber of derived fields.
Returns
Zero on success, or PETSC_ERR_ARG_WRONG for an unknown output kind.

Reports how many derived fields a requested output set produces.

See also
PicurvWindowDerivedCount()

Definition at line 654 of file statistics_accumulator.c.

657{
658 PetscBool wanted[DERIVED_KIND_COUNT];
659
660 PetscFunctionBeginUser;
662 PetscCheck(definition != NULL && storage != NULL && count != NULL,
663 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Definition, storage, and count are required.");
664 PetscCall(ParseDerivedKinds(outputs, wanted));
665 *count = 0;
666 for (PetscInt k = 0; k < DERIVED_KIND_COUNT; ++k) {
667 PetscInt extent = 0;
668
669 if (!wanted[k]) continue;
670 PetscCall(DerivedKindExtent(definition, storage, (DerivedKind)k, &extent));
671 *count += extent;
672 }
674 PetscFunctionReturn(0);
675}
static PetscErrorCode ParseDerivedKinds(const char *outputs, PetscBool wanted[DERIVED_KIND_COUNT])
Internal helper: reports which output kinds a recipe requested.
DerivedKind
Output kinds a postprocessing recipe may request, in enumeration order.
@ DERIVED_KIND_COUNT
static PetscErrorCode DerivedKindExtent(const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, DerivedKind kind, PetscInt *count)
Internal helper: counts the derived fields each kind contributes.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowDerive()

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.

Normalizes in exactly one place: R_ij = C_ij / W, RMS_i = sqrt(R_ii), k = (R_xx + R_yy + R_zz) / 2, and a flux is the co-moment over the same weight. Each uses the moment kernels rather than repeating the division, so the online and offline halves of the pipeline cannot disagree about what centered state means.

A variance that comes out slightly negative through floating-point cancellation is clamped only where a square root would otherwise fail, and only within PICURV_STATISTICS_VARIANCE_FLOOR. Stored state is never modified.

Points the window never sampled are left at zero rather than divided by a zero weight; the valid-fraction range reports how much of the domain that covers.

Parameters
[in]userBlock context supplying the target domain.
[in]definitionWindow definition.
[in]storageAccumulator state to read.
[in]outputsComma-separated output kinds.
[in]indexDerived field index in [0, count).
[out]scalar_targetScalar destination, used when the field has one component.
[out]vector_targetVector destination, used when the field has three.
[out]fieldResolved name and component count of the derived field.
Returns
Zero on success, or a PETSc error.

Derives one output field from centered accumulator state.

See also
PicurvWindowDerive()

Definition at line 735 of file statistics_accumulator.c.

739{
740 PetscBool wanted[DERIVED_KIND_COUNT];
743 PetscReal ***weight_arr = NULL, ***weight_sq_arr = NULL, ***count_arr = NULL;
744 PetscScalar ****source = NULL, ****target = NULL;
745 const FieldDescriptor *descriptor = NULL;
746 DM source_dm = NULL;
747 Vec source_vec = NULL;
748 PetscInt offset = 0, slot = 0, member = 0;
750 Vec count_vec = NULL, weight_vec = NULL, weight_sq_vec = NULL;
751 /* Resolved where the branch knows which fields it read; 1.0 leaves the result in
752 * solver units, which is also what an undeclared scale falls back to. */
753 PetscReal dimensional_factor = 1.0;
754 /* The source's component count is not the output's: a scalar RMS reads a
755 * six-component tensor, so each needs its own DM. */
756 PetscInt source_components = 0;
757
758 PetscFunctionBeginUser;
760 PetscCheck(user != NULL && definition != NULL && storage != NULL && field != NULL,
761 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
762 "Context, definition, storage, and output are required.");
763 PetscCheck(index >= 0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
764 "Derived index %" PetscInt_FMT " is negative.", index);
765 PetscCall(PetscMemzero(field, sizeof(*field)));
766 /* The output list is parsed once and the extents walked once. Resolving the
767 * index is what bounds-checks it, so counting first would repeat both. */
768 PetscCall(ParseDerivedKinds(outputs, wanted));
769 PetscCall(ResolveDerivedIndex(definition, storage, wanted, index, &kind, &offset));
770
771 /* Locate the accumulator slot and component this index selects, and the sample
772 * set that slot or pair was measured over. */
773 switch (kind) {
774 case DERIVED_MEAN:
775 slot = offset;
776 PetscCall(FieldGetDescriptor((FieldId)definition->fields[slot].field_id, &descriptor));
777 source_vec = storage->mean[slot];
778 set = RequestSampleSet(definition, slot, -1);
779 field->components = descriptor->dof;
780 source_components = descriptor->dof;
781 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_mean",
782 definition->name, descriptor->canonical_name));
783 break;
784 case DERIVED_TKE:
785 for (slot = 0; slot < storage->field_count; ++slot) {
786 if (!storage->m2[slot]) continue;
787 PetscCall(FieldGetDescriptor((FieldId)definition->fields[slot].field_id, &descriptor));
788 if (descriptor->dof != 3) continue;
789 if (offset-- == 0) break;
790 }
791 source_vec = storage->m2[slot];
792 set = RequestSampleSet(definition, slot, -1);
793 field->components = 1;
794 PetscCall(PicurvProductComponentCount(descriptor->dof, &source_components));
795 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_tke",
796 definition->name, descriptor->canonical_name));
797 break;
798 case DERIVED_FLUX:
799 slot = offset;
800 {
801 const FieldDescriptor *first = NULL;
802 const FieldDescriptor *second = NULL;
803
804 PetscCall(FieldGetDescriptor((FieldId)definition->covariances[slot].first, &first));
805 PetscCall(FieldGetDescriptor((FieldId)definition->covariances[slot].second, &second));
806 PetscCall(PicurvCovarianceComponentCount(first->dof, second->dof, &field->components));
807 source_components = field->components;
808 source_vec = storage->cm[slot];
809 set = RequestSampleSet(definition, -1, slot);
810 if (user->simCtx->pps && user->simCtx->pps->dimensionalize && !storage->physical_units) {
811 PetscReal first_scale = 1.0, second_scale = 1.0;
812
813 /* A co-moment carries the product of its two fields' dimensions. */
814 PetscCall(PicurvFieldReferenceScale(user->simCtx, first->canonical_name,
815 &first_scale, NULL, 0));
816 PetscCall(PicurvFieldReferenceScale(user->simCtx, second->canonical_name,
817 &second_scale, NULL, 0));
818 dimensional_factor = first_scale * second_scale;
819 }
820 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_%s_flux",
821 definition->name, first->canonical_name, second->canonical_name));
822 }
823 break;
824 default:
825 /* Stress and RMS both walk the fields carrying a product; stress emits every
826 * symmetric component, RMS only the diagonal. */
827 for (slot = 0; slot < storage->field_count; ++slot) {
828 PetscInt extent = 0;
829
830 if (!storage->m2[slot]) continue;
831 PetscCall(FieldGetDescriptor((FieldId)definition->fields[slot].field_id, &descriptor));
832 PetscCall(PicurvProductComponentCount(descriptor->dof, &extent));
833 if (kind == DERIVED_RMS || kind == DERIVED_POINT_VARIANCE) extent = descriptor->dof;
834 if (offset < extent) { member = offset; break; }
835 offset -= extent;
836 }
837 source_vec = storage->m2[slot];
838 set = RequestSampleSet(definition, slot, -1);
839 field->components = 1;
840 PetscCall(PicurvProductComponentCount(descriptor->dof, &source_components));
841 if (kind == DERIVED_RMS || kind == DERIVED_POINT_VARIANCE) {
842 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_%s%s",
843 definition->name, descriptor->canonical_name,
844 kind == DERIVED_RMS ? "rms" : "point_variance",
845 descriptor->dof == 1 ? "" : kAxisName[member]));
846 field->point_averaged = (PetscBool)(kind == DERIVED_POINT_VARIANCE);
847 } else if (descriptor->dof == 1) {
848 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_variance",
849 definition->name, descriptor->canonical_name));
850 } else {
851 char label[8];
852
853 PetscCall(ProductComponentLabel(member, label, sizeof(label)));
854 PetscCall(PetscSNPrintf(field->name, sizeof(field->name), "%s_%s_R_%s",
855 definition->name, descriptor->canonical_name, label));
856 }
857 break;
858 }
859
860 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
862 PetscCall(PicurvStatisticsComponentDM(user, source_components, &source_dm));
863 {
864 Vec destination = (field->components == 1) ? scalar_target : vector_target;
865 DM destination_dm = NULL;
866
867 PetscCheck(destination != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
868 "Derived field '%s' needs a %d-component destination.",
869 field->name, (int)field->components);
870 PetscCall(PicurvStatisticsComponentDM(user, field->components, &destination_dm));
871 PetscCall(VecZeroEntries(destination));
872
873 field->occupied = (PetscBool)(set == SAMPLE_SET_OCCUPIED);
874 SampleSetOccupancy(storage, set, &count_vec, &weight_vec, &weight_sq_vec);
875 PetscCall(DMDAVecGetArrayRead(user->da, weight_vec, &weight_arr));
876 PetscCall(DMDAVecGetArrayRead(user->da, weight_sq_vec, &weight_sq_arr));
877 PetscCall(DMDAVecGetArrayRead(user->da, count_vec, &count_arr));
878 PetscCall(DMDAVecGetArrayDOFRead(source_dm, source_vec, &source));
879 PetscCall(DMDAVecGetArrayDOF(destination_dm, destination, &target));
880
881 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k) {
882 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j) {
883 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
885
886 /* A point the window never sampled has no average at all, so it
887 * is left at zero rather than divided by a zero weight. */
888 if (weight_arr[k][j][i] <= 0.0) continue;
889 pair.count = count_arr[k][j][i];
890 pair.weight = weight_arr[k][j][i];
891 pair.weight_sq = weight_sq_arr[k][j][i];
892 pair.mean_x = 0.0;
893 pair.mean_y = 0.0;
894
895 if (kind == DERIVED_MEAN) {
896 for (PetscInt c = 0; c < field->components; ++c) {
897 target[k][j][i][c] = source[k][j][i][c];
898 }
899 } else if (kind == DERIVED_TKE) {
900 /* The trace of the stress tensor, halved: components 0, 3
901 * and 5 are xx, yy and zz in the stored symmetric order. */
902 PetscReal trace = 0.0;
903
904 for (PetscInt c = 0; c < 3; ++c) {
905 pair.cm = source[k][j][i][ProductDiagonalIndex(c)];
906 trace += PicurvCoMomentStateCovariance(&pair);
907 }
908 target[k][j][i][0] = 0.5 * trace;
909 } else if (kind == DERIVED_RMS || kind == DERIVED_POINT_VARIANCE) {
910 PetscReal deviation = 0.0;
911
912 pair.cm = source[k][j][i][(descriptor->dof == 1)
913 ? 0 : ProductDiagonalIndex(member)];
915 field->name, &deviation));
916 target[k][j][i][0] = (kind == DERIVED_RMS) ? deviation : deviation * deviation;
917 } else if (kind == DERIVED_FLUX) {
918 for (PetscInt c = 0; c < field->components; ++c) {
919 pair.cm = source[k][j][i][c];
920 target[k][j][i][c] = PicurvCoMomentStateCovariance(&pair);
921 }
922 } else {
923 pair.cm = source[k][j][i][member];
924 target[k][j][i][0] = PicurvCoMomentStateCovariance(&pair);
925 }
926 }
927 }
928 }
929
930 PetscCall(DMDAVecRestoreArrayDOF(destination_dm, destination, &target));
931 PetscCall(DMDAVecRestoreArrayDOFRead(source_dm, source_vec, &source));
932 PetscCall(DMDAVecRestoreArrayRead(user->da, count_vec, &count_arr));
933 PetscCall(DMDAVecRestoreArrayRead(user->da, weight_sq_vec, &weight_sq_arr));
934 PetscCall(DMDAVecRestoreArrayRead(user->da, weight_vec, &weight_arr));
935
936 /* Applied once, here, so the VTK field and the convergence-history CSV - which
937 * both read this staging vector - cannot end up in different unit systems. */
938 if (user->simCtx->pps && user->simCtx->pps->dimensionalize && !storage->physical_units) {
939 if (kind != DERIVED_FLUX && descriptor) {
940 PetscReal base = 1.0;
941
942 PetscCall(PicurvFieldReferenceScale(user->simCtx, descriptor->canonical_name,
943 &base, NULL, 0));
944 dimensional_factor = PetscPowRealInt(base, kDerivedKindScaleExponent[kind]);
945 }
946 if (PetscAbsReal(dimensional_factor - 1.0) > PETSC_MACHINE_EPSILON) {
947 PetscCall(VecScale(destination, dimensional_factor));
948 LOG_ALLOW(GLOBAL, LOG_DEBUG, "Scaled derived '%s' by %.4e.\n",
949 kDerivedKindName[kind], (double)dimensional_factor);
950 }
951 }
952 }
954 PetscFunctionReturn(0);
955}
PetscErrorCode PicurvFieldReferenceScale(SimCtx *simCtx, const char *field_name, PetscReal *scale, char *description, size_t description_length)
Physical scale one field is multiplied by to leave non-dimensional form.
Definition io.c:3006
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
static const char *const kDerivedKindName[DERIVED_KIND_COUNT]
Recipe spellings of the output kinds.
static const char *const kAxisName[3]
Axis labels indexing the pair table above.
static PetscInt ProductDiagonalIndex(PetscInt component)
Internal helper: the product index carrying one component's own variance.
SampleSet
The sample set a field or pair is measured over.
@ SAMPLE_SET_ALL
Every accepted state at the point.
static PetscErrorCode ResolveDerivedIndex(const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const PetscBool wanted[DERIVED_KIND_COUNT], PetscInt index, DerivedKind *kind, PetscInt *offset)
Internal helper: resolves which kind and member one derived index selects.
@ DERIVED_POINT_VARIANCE
static PetscErrorCode ProductComponentLabel(PetscInt index, char *out, size_t size)
Internal helper: writes the two-axis label of one product component.
static const PetscInt kDerivedKindScaleExponent[DERIVED_KIND_COUNT]
Power of the source field's reference scale each derived kind carries.
static PetscErrorCode SafeStandardDeviation(PetscReal variance, const char *label, PetscReal *result)
Internal helper: takes a square root of a variance that may be barely negative.
static void SampleSetOccupancy(const PicurvWindowStorage *storage, SampleSet set, Vec *count, Vec *weight, Vec *weight_sq)
Internal helper: the occupancy vectors of one sample set.
PetscInt components
One or three.
char name[96]
Output field name, window qualified.
PetscBool point_averaged
Reduced over homogeneous directions as the equal-weight mean of point values, not from the pooled sam...
PetscBool occupied
Measured over the occupied states, so undefined where they are absent.
PetscBool physical_units
Holds physical units, as an ensemble of a dimensionalized load does, so derivation applies no scale; ...
PetscReal weight_sq
Sum of squared weights W2.
PetscReal mean_y
Weighted mean of the second member.
PetscReal count
Number of accepted samples.
PetscReal cm
Centered co-moment sum C.
PetscReal PicurvCoMomentStateCovariance(const PicurvCoMomentState *state)
Returns the weighted covariance C/W, or zero when no weight accumulated.
PetscReal mean_x
Weighted mean of the first member.
PetscReal weight
Total weight W.
Weighted centered co-moment state for one ordered pair of quantities.
PetscInt end[3]
Exclusive end per dimension (i, j, k).
PetscInt start[3]
Inclusive start per dimension (i, j, k).
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
PostProcessParams * pps
Definition variables.h:1131
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowSpatialMean()

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.

The average is taken over targeted points that actually accumulated weight, not over the whole vector. A derived field is zero everywhere outside the target domain and at any point the mask never admitted, and those zeros are absences rather than measurements: including them would scale the answer down by the fraction of the vector the window never covered.

Performs a collective reduction, so callers use it for reporting rather than per point.

Parameters
[in]userBlock context supplying the target domain.
[in]definitionWindow definition naming the accumulated fields.
[in]storageAccumulator state supplying per-point occupancy.
[in]fieldDerived field to average, on the cell-centred scalar DM.
[out]meanSpatial mean; zero when the window sampled no point.
Returns
Zero on success, or a PETSc error.

Reports the spatial mean of a derived field over the points a window sampled.

See also
PicurvWindowSpatialMean()

Definition at line 961 of file statistics_accumulator.c.

964{
966 /* Every direction collapses: a window mean is one number for the domain. */
967 const PetscBool whole_domain[3] = {PETSC_TRUE, PETSC_TRUE, PETSC_TRUE};
968
969 PetscFunctionBeginUser;
971 PetscCheck(user != NULL && definition != NULL && storage != NULL && field != NULL && mean != NULL,
972 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
973 "Context, definition, storage, field, and output are required.");
974 *mean = 0.0;
975 if (definition->field_count == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
976
977 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
979 /* No denominator means each admitted point counts once, so the result is the mean
980 * of the field over those points rather than a volume-weighted average. The
981 * accumulated weight is passed as the inclusion mask: a point the window never
982 * sampled holds a zero that means "never measured", and averaging it in would
983 * scale the answer down by the fraction of the domain the window never covered. */
984 PetscCall(PicurvSpatialRatioAverage(user, &plan, field, NULL, storage->weight,
985 whole_domain, PETSC_COMM_WORLD, NULL, mean));
987 PetscFunctionReturn(0);
988}
PetscErrorCode PicurvSpatialRatioAverage(UserCtx *user, const SpatialTargetPlan *plan, Vec numerator, Vec denominator, Vec inclusion, const PetscBool average_direction[3], MPI_Comm comm, Vec ratio, PetscReal *reduced)
Averages two fields over a target domain and divides the results.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowValidFractionRange()

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.

A point contributes only to the states in which the mask accepted it, so with a moving immersed body different points carry different sample counts. The ratio of a point's own count to the window's accepted-sample count is its valid fraction, and the range of that ratio is the window's mask-health indicator: a minimum of one means every point saw every state, and a minimum of zero means some point contributed nothing at all.

Performs a collective reduction, so callers gate it on an already-active reporting path rather than calling it every step.

Parameters
[in]userBlock context supplying the target domain and mask.
[in]definitionWindow definition naming the accumulated fields.
[in]storageAccumulator state to inspect.
[in]sample_countAccepted states the window has recorded.
[out]minimumSmallest valid fraction; one when no point is targeted.
[out]maximumLargest valid fraction; zero when no point is targeted.
Returns
Zero on success, or a PETSc error.

Reports the range of per-point valid fraction across a window's domain.

See also
PicurvWindowValidFractionRange()

Definition at line 994 of file statistics_accumulator.c.

997{
999 PetscReal ***nvert = NULL;
1000 PetscReal ***count_arr = NULL;
1001 PetscReal local_min = PETSC_MAX_REAL;
1002 PetscReal local_max = 0.0;
1003 PetscReal reduced_min = 0.0, reduced_max = 0.0;
1004
1005 PetscFunctionBeginUser;
1007 PetscCheck(user != NULL && definition != NULL && storage != NULL &&
1008 minimum != NULL && maximum != NULL,
1009 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, definition, storage, and outputs are required.");
1010 *minimum = 1.0;
1011 *maximum = 0.0;
1012 if (definition->field_count == 0 || sample_count <= 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1013
1014 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
1016 PetscCall(DMDAVecGetArrayRead(user->da, user->Nvert, &nvert));
1017 PetscCall(DMDAVecGetArrayRead(user->da, storage->count, &count_arr));
1018 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k) {
1019 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j) {
1020 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1021 /* The mask is evaluated at the current state, but a point excluded
1022 * now may have contributed earlier, so its stored count is what
1023 * decides its fraction rather than its present eligibility. */
1024 const PetscReal fraction = count_arr[k][j][i] / (PetscReal)sample_count;
1025
1026 local_min = PetscMin(local_min, fraction);
1027 local_max = PetscMax(local_max, fraction);
1028 }
1029 }
1030 }
1031 PetscCall(DMDAVecRestoreArrayRead(user->da, storage->count, &count_arr));
1032 PetscCall(DMDAVecRestoreArrayRead(user->da, user->Nvert, &nvert));
1033
1034 /* A rank owning no targeted point must not drag the minimum down, so its
1035 * sentinel is neutral under the reduction rather than zero. */
1036 PetscCallMPI(MPI_Allreduce(&local_min, &reduced_min, 1, MPIU_REAL, MPIU_MIN, PETSC_COMM_WORLD));
1037 PetscCallMPI(MPI_Allreduce(&local_max, &reduced_max, 1, MPIU_REAL, MPIU_MAX, PETSC_COMM_WORLD));
1038 *minimum = (reduced_min == PETSC_MAX_REAL) ? 1.0 : reduced_min;
1039 *maximum = reduced_max;
1041 PetscFunctionReturn(0);
1042}
Vec Nvert
Definition variables.h:1197
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowAccumulate()

PetscErrorCode PicurvWindowAccumulate ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
PicurvWindowStorage *  storage,
PetscReal  weight 
)

Applies one accepted completed state to a window's accumulators.

Iterates the pointwise target domain, skipping points the mask rejects, and updates each point's occupancy and every requested moment and co-moment through the centered kernels.

Parameters
[in]userBlock context supplying the source fields.
[in]definitionWindow definition.
[in,out]storageAccumulator state to update.
[in]weightWeight the window assigned to this state; must be positive.
Returns
Zero on success, or a PETSc error.

Applies one accepted completed state to a window's accumulators.

See also
PicurvWindowAccumulate()

Definition at line 1048 of file statistics_accumulator.c.

1050{
1051 SpatialTargetPlan plan;
1052 PetscReal ***nvert = NULL, ***particles = NULL;
1053 /* Occupancy of each sample set, indexed by SampleSet. */
1054 PetscReal ***count_arr[2] = {NULL, NULL}, ***weight_arr[2] = {NULL, NULL}, ***weight_sq_arr[2] = {NULL, NULL};
1055 const PetscBool occupied_set = (PetscBool)(storage != NULL && storage->occupied_count != NULL);
1056
1057 PetscFunctionBeginUser;
1059 PetscCheck(user != NULL && definition != NULL && storage != NULL,
1060 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, definition, and storage are required.");
1061 PetscCheck(weight > 0.0, PETSC_COMM_SELF, PETSC_ERR_ARG_OUTOFRANGE,
1062 "Accepted states carry a positive weight, got %g.", (double)weight);
1063 if (definition->field_count == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1064
1065 /* Every requested field shares the pointwise cell-centered domain, so the plan
1066 * is resolved once rather than per field. */
1067 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
1069
1070 PetscCall(DMDAVecGetArrayRead(user->da, user->Nvert, &nvert));
1071 for (PetscInt set = 0; set < (occupied_set ? 2 : 1); ++set) {
1072 Vec count = NULL, sum = NULL, sum_sq = NULL;
1073
1074 SampleSetOccupancy(storage, (SampleSet)set, &count, &sum, &sum_sq);
1075 PetscCall(DMDAVecGetArray(user->da, count, &count_arr[set]));
1076 PetscCall(DMDAVecGetArray(user->da, sum, &weight_arr[set]));
1077 PetscCall(DMDAVecGetArray(user->da, sum_sq, &weight_sq_arr[set]));
1078 }
1079 /* A cell is occupied in this state when it holds a particle now; the count is the
1080 * one the scatter just computed for this state. */
1081 if (occupied_set) PetscCall(DMDAVecGetArrayRead(user->da, user->ParticleCount, &particles));
1082
1083 /* Pass one advances per-point occupancy, so every field pass afterwards can
1084 * recover the pre-state weight uniformly as (stored weight - this weight).
1085 * Occupancy is per point and per accepted state, never per field. */
1086 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k) {
1087 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j) {
1088 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1089 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) continue;
1090 for (PetscInt set = 0; set < (occupied_set ? 2 : 1); ++set) {
1091 if (set == SAMPLE_SET_OCCUPIED && particles[k][j][i] <= 0.0) continue;
1092 count_arr[set][k][j][i] += 1.0;
1093 weight_arr[set][k][j][i] += weight;
1094 weight_sq_arr[set][k][j][i] += weight * weight;
1095 }
1096 }
1097 }
1098 }
1099
1100 /* Pass two updates every cross-field co-moment. It runs before any mean is
1101 * written back, because a co-moment needs the pre-update mean of *both*
1102 * members, and pass three overwrites them field by field. */
1103 for (PetscInt pair = 0; pair < definition->covariance_count; ++pair) {
1104 const SampleSet set = RequestSampleSet(definition, -1, pair);
1105 FieldView view_a, view_b;
1106 PetscScalar ****src_a = NULL, ****mean_a = NULL;
1107 PetscScalar ****src_b = NULL, ****mean_b = NULL;
1108 PetscScalar ****co_moment = NULL;
1109 DM pair_dm = NULL;
1110 PetscInt slot_a = 0, slot_b = 0, dof_a = 0, dof_b = 0, components = 0;
1111
1112 PetscCall(FindFieldSlot(definition, definition->covariances[pair].first, &slot_a));
1113 PetscCall(FindFieldSlot(definition, definition->covariances[pair].second, &slot_b));
1114 PetscCall(FieldGetView(user, (FieldId)definition->covariances[pair].first, &view_a));
1115 PetscCall(FieldGetView(user, (FieldId)definition->covariances[pair].second, &view_b));
1116 dof_a = view_a.descriptor->dof;
1117 dof_b = view_b.descriptor->dof;
1118 PetscCall(PicurvCovarianceComponentCount(dof_a, dof_b, &components));
1119 PetscCall(PicurvStatisticsComponentDM(user, components, &pair_dm));
1120
1121 /* A component-indexed view serves every degree of freedom, so the loop
1122 * below needs no scalar-versus-vector branching. Each member is centred on
1123 * its mean over the pair's own sample set. */
1124 PetscCall(DMDAVecGetArrayDOFRead(view_a.dm, view_a.global_vec, &src_a));
1125 PetscCall(DMDAVecGetArrayDOFRead(view_a.dm, SampleSetMean(storage, set, slot_a), &mean_a));
1126 PetscCall(DMDAVecGetArrayDOFRead(view_b.dm, view_b.global_vec, &src_b));
1127 PetscCall(DMDAVecGetArrayDOFRead(view_b.dm, SampleSetMean(storage, set, slot_b), &mean_b));
1128 PetscCall(DMDAVecGetArrayDOF(pair_dm, storage->cm[pair], &co_moment));
1129
1130 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k) {
1131 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j) {
1132 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1133 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) continue;
1134 if (set == SAMPLE_SET_OCCUPIED && particles[k][j][i] <= 0.0) continue;
1135 for (PetscInt c = 0; c < components; ++c) {
1136 /* A scalar member contributes its single value against every
1137 * component of a vector member, which is what makes a
1138 * vector-scalar covariance a three-component object. */
1139 const PetscInt component_a = (dof_a == 3) ? c : 0;
1140 const PetscInt component_b = (dof_b == 3) ? c : 0;
1141 PicurvCoMomentState state;
1142
1143 state.count = count_arr[set][k][j][i] - 1.0;
1144 state.weight = weight_arr[set][k][j][i] - weight;
1145 state.weight_sq = weight_sq_arr[set][k][j][i] - weight * weight;
1146 state.mean_x = mean_a[k][j][i][component_a];
1147 state.mean_y = mean_b[k][j][i][component_b];
1148 state.cm = co_moment[k][j][i][c];
1149 PetscCall(PicurvCoMomentStateUpdate(&state,
1150 src_a[k][j][i][component_a],
1151 src_b[k][j][i][component_b], weight));
1152 co_moment[k][j][i][c] = state.cm;
1153 }
1154 }
1155 }
1156 }
1157
1158 PetscCall(DMDAVecRestoreArrayDOF(pair_dm, storage->cm[pair], &co_moment));
1159 PetscCall(DMDAVecRestoreArrayDOFRead(view_b.dm, SampleSetMean(storage, set, slot_b), &mean_b));
1160 PetscCall(DMDAVecRestoreArrayDOFRead(view_b.dm, view_b.global_vec, &src_b));
1161 PetscCall(DMDAVecRestoreArrayDOFRead(view_a.dm, SampleSetMean(storage, set, slot_a), &mean_a));
1162 PetscCall(DMDAVecRestoreArrayDOFRead(view_a.dm, view_a.global_vec, &src_a));
1163 }
1164
1165 /* Pass three updates each requested field's mean and, when asked, its centered
1166 * self-product. A three-vector's self-product is the six symmetric co-moments
1167 * between component pairs, not three per-component variances, so the co-moment
1168 * kernel drives every product component including the diagonal. An ordinary field
1169 * paired with a particle-sampled one also advances its occupied-state mean. */
1170 for (PetscInt field_index = 0; field_index < definition->field_count; ++field_index) {
1171 const SampleSet set = RequestSampleSet(definition, field_index, -1);
1172 const PetscBool second = definition->fields[field_index].want_second;
1173 Vec occupied_mean = (storage->occupied_mean) ? storage->occupied_mean[field_index] : NULL;
1174 FieldView view;
1175 PetscScalar ****src = NULL, ****mean = NULL, ****product = NULL, ****occupied = NULL;
1176 DM product_dm = NULL;
1177 PetscInt dof = 0, components = 0;
1178
1179 PetscCall(FieldGetView(user, (FieldId)definition->fields[field_index].field_id, &view));
1180 dof = view.descriptor->dof;
1181 PetscCall(DMDAVecGetArrayDOFRead(view.dm, view.global_vec, &src));
1182 PetscCall(DMDAVecGetArrayDOF(view.dm, storage->mean[field_index], &mean));
1183 if (occupied_mean) PetscCall(DMDAVecGetArrayDOF(view.dm, occupied_mean, &occupied));
1184 if (second) {
1185 PetscCall(PicurvProductComponentCount(dof, &components));
1186 PetscCall(PicurvStatisticsComponentDM(user, components, &product_dm));
1187 PetscCall(DMDAVecGetArrayDOF(product_dm, storage->m2[field_index], &product));
1188 }
1189
1190 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k) {
1191 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j) {
1192 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1193 PetscReal prior_weight = 0.0;
1194 PetscReal prior_weight_sq = 0.0;
1195 PetscReal prior_count = 0.0;
1196
1197 if (!SpatialTargetPlanMaskAllows(&plan, nvert[k][j][i])) continue;
1198 if (occupied && particles[k][j][i] > 0.0) {
1199 for (PetscInt c = 0; c < dof; ++c) {
1200 PicurvMomentState moment;
1201
1202 moment.count = count_arr[SAMPLE_SET_OCCUPIED][k][j][i] - 1.0;
1203 moment.weight = weight_arr[SAMPLE_SET_OCCUPIED][k][j][i] - weight;
1204 moment.weight_sq = weight_sq_arr[SAMPLE_SET_OCCUPIED][k][j][i] - weight * weight;
1205 moment.mean = occupied[k][j][i][c];
1206 moment.m2 = 0.0;
1207 PetscCall(PicurvMomentStateUpdate(&moment, src[k][j][i][c], weight));
1208 occupied[k][j][i][c] = moment.mean;
1209 }
1210 }
1211 if (set == SAMPLE_SET_OCCUPIED && particles[k][j][i] <= 0.0) continue;
1212
1213 prior_weight = weight_arr[set][k][j][i] - weight;
1214 prior_weight_sq = weight_sq_arr[set][k][j][i] - weight * weight;
1215 prior_count = count_arr[set][k][j][i] - 1.0;
1216
1217 /* Products are updated before the means are written back,
1218 * because the co-moment kernel needs the pre-update means. */
1219 for (PetscInt c = 0; c < components; ++c) {
1220 const PetscInt a = (dof == 1) ? 0 : kProductFirst[c];
1221 const PetscInt b = (dof == 1) ? 0 : kProductSecond[c];
1222 PicurvCoMomentState state;
1223
1224 state.count = prior_count;
1225 state.weight = prior_weight;
1226 state.weight_sq = prior_weight_sq;
1227 state.mean_x = mean[k][j][i][a];
1228 state.mean_y = mean[k][j][i][b];
1229 state.cm = product[k][j][i][c];
1230 PetscCall(PicurvCoMomentStateUpdate(&state, src[k][j][i][a],
1231 src[k][j][i][b], weight));
1232 product[k][j][i][c] = state.cm;
1233 }
1234
1235 for (PetscInt c = 0; c < dof; ++c) {
1236 PicurvMomentState moment;
1237
1238 moment.count = prior_count;
1239 moment.weight = prior_weight;
1240 moment.weight_sq = prior_weight_sq;
1241 moment.mean = mean[k][j][i][c];
1242 moment.m2 = 0.0;
1243 PetscCall(PicurvMomentStateUpdate(&moment, src[k][j][i][c], weight));
1244 mean[k][j][i][c] = moment.mean;
1245 }
1246 }
1247 }
1248 }
1249
1250 if (second) PetscCall(DMDAVecRestoreArrayDOF(product_dm, storage->m2[field_index], &product));
1251 if (occupied_mean) PetscCall(DMDAVecRestoreArrayDOF(view.dm, occupied_mean, &occupied));
1252 PetscCall(DMDAVecRestoreArrayDOF(view.dm, storage->mean[field_index], &mean));
1253 PetscCall(DMDAVecRestoreArrayDOFRead(view.dm, view.global_vec, &src));
1254 }
1255
1256 if (occupied_set) PetscCall(DMDAVecRestoreArrayRead(user->da, user->ParticleCount, &particles));
1257 for (PetscInt set = (occupied_set ? 1 : 0); set >= 0; --set) {
1258 Vec count = NULL, sum = NULL, sum_sq = NULL;
1259
1260 SampleSetOccupancy(storage, (SampleSet)set, &count, &sum, &sum_sq);
1261 PetscCall(DMDAVecRestoreArray(user->da, sum_sq, &weight_sq_arr[set]));
1262 PetscCall(DMDAVecRestoreArray(user->da, sum, &weight_arr[set]));
1263 PetscCall(DMDAVecRestoreArray(user->da, count, &count_arr[set]));
1264 }
1265 PetscCall(DMDAVecRestoreArrayRead(user->da, user->Nvert, &nvert));
1267 PetscFunctionReturn(0);
1268}
static const PetscInt kProductFirst[6]
Upper-triangular row-major component pairs for a three-vector self-product.
static const PetscInt kProductSecond[6]
static Vec SampleSetMean(const PicurvWindowStorage *storage, SampleSet set, PetscInt slot)
Internal helper: the mean a field slot is centred on within one sample set.
PetscReal weight_sq
Sum of squared weights W2.
PetscErrorCode PicurvCoMomentStateUpdate(PicurvCoMomentState *state, PetscReal value_x, PetscReal value_y, PetscReal weight)
Applies one weighted paired sample to a co-moment accumulator.
PetscReal weight
Total weight W.
PetscReal m2
Centered second-moment sum M2.
PetscReal mean
Weighted mean mu.
PetscErrorCode PicurvMomentStateUpdate(PicurvMomentState *state, PetscReal value, PetscReal weight)
Applies one weighted sample to a scalar moment accumulator.
PetscReal count
Number of accepted samples.
Weighted centered state for one scalar quantity at one point.
PetscBool SpatialTargetPlanMaskAllows(const SpatialTargetPlan *plan, PetscReal nvert_value)
Reports whether a point passes the plan's mask.
Vec ParticleCount
Definition variables.h:1276
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowStorageFromParticles()

PetscErrorCode PicurvWindowStorageFromParticles ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
PicurvWindowStorage *  storage 
)

Fills a window's storage from the particles sampling each cell at one instant.

The particles a cell holds are that cell's samples, each of unit weight, so the stored state is the cell's particle ensemble: its count, the ensemble mean of every requested field, and the centred sums of every requested self-product and covariance. Each field is identified by its Eulerian scatter target, which fixes its layout and the names its derived outputs carry.

The runtime accumulator streams states it sees once, so it updates running means sample by sample. A snapshot holds every sample at once, which admits the two-pass form instead: the means first, through the same particle sum the runtime scatter uses, then the centred products about them. That is the more accurate of the two, needs no division per sample, and does not depend on particle order. Both produce the same stored state, so derivation and output treat the two alike.

A particle contributes wherever its cell lies in this rank's ghosted patch, and the patch sums are added onto their owners, so a particle need not sit on the rank that owns its cell. One outside the patch is skipped, as in the scatter.

Parameters
[in]userBlock context supplying the swarm and the grid.
[in]definitionFields and pairs to accumulate, by Eulerian scatter target.
[in,out]storageFreshly created storage for definition; overwritten.
Returns
Zero on success, or a PETSc error, including for a field no particle field scatters to.

Fills a window's storage from the particles sampling each cell at one instant.

See also
PicurvWindowStorageFromParticles()

Definition at line 1357 of file statistics_accumulator.c.

1359{
1362 Vec centre[PICURV_WINDOW_MAX_REQUESTS] = {NULL};
1363
1364 PetscFunctionBeginUser;
1366 PetscCheck(user != NULL && definition != NULL && storage != NULL && user->swarm != NULL,
1367 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, swarm, definition, and storage are required.");
1368
1369 /* Unit weights: count, weight and squared weight are all the particle count. Every
1370 * sample is a particle, so the occupied set is the whole sample set. */
1371 PetscCall(CalculateParticleCountPerCell(user));
1372 for (PetscInt set = 0; set < (storage->occupied_count ? 2 : 1); ++set) {
1373 Vec count = NULL, weight = NULL, weight_sq = NULL;
1374
1375 SampleSetOccupancy(storage, (SampleSet)set, &count, &weight, &weight_sq);
1376 PetscCall(VecCopy(user->ParticleCount, count));
1377 PetscCall(VecCopy(user->ParticleCount, weight));
1378 PetscCall(VecCopy(user->ParticleCount, weight_sq));
1379 }
1380
1381 /* Pass one: each field's cell mean, the particle sum divided by the count. */
1382 for (PetscInt f = 0; f < definition->field_count; ++f) {
1383 PetscCall(ParticleFieldIdFromScatterTarget((FieldId)definition->fields[f].field_id, &particle[f]));
1384 PetscCall(FieldGetView(user, (FieldId)definition->fields[f].field_id, &view[f]));
1385 PetscCall(ScatterParticleFieldCellMean(user, particle[f], view[f].dm, storage->count, PETSC_FALSE, storage->mean[f]));
1386 if (storage->occupied_mean && storage->occupied_mean[f]) {
1387 PetscCall(VecCopy(storage->mean[f], storage->occupied_mean[f]));
1388 }
1389 /* The second pass reads each particle's own cell mean, which may be a ghost. */
1390 PetscCall(DMCreateLocalVector(view[f].dm, &centre[f]));
1391 PetscCall(DMGlobalToLocalBegin(view[f].dm, storage->mean[f], INSERT_VALUES, centre[f]));
1392 PetscCall(DMGlobalToLocalEnd(view[f].dm, storage->mean[f], INSERT_VALUES, centre[f]));
1393 }
1394
1395 /* Pass two: centred self-products, then cross-field covariances. */
1396 for (PetscInt f = 0; f < definition->field_count; ++f) {
1397 const PetscInt dof = view[f].descriptor->dof;
1398 PetscInt components = 0, first[6], second[6];
1399 DM product_dm = NULL;
1400
1401 if (!definition->fields[f].want_second) continue;
1402 PetscCall(PicurvProductComponentCount(dof, &components));
1403 PetscCall(PicurvStatisticsComponentDM(user, components, &product_dm));
1404 ProductComponents(PETSC_TRUE, dof, dof, components, first, second);
1405 PetscCall(AccumulateParticleCentredProducts(user, particle[f], particle[f], view[f].dm, centre[f],
1406 view[f].dm, centre[f], components, first, second,
1407 product_dm, storage->m2[f]));
1408 }
1409 for (PetscInt pair = 0; pair < definition->covariance_count; ++pair) {
1410 PetscInt a = 0, b = 0, components = 0, first[6], second[6];
1411 DM pair_dm = NULL;
1412
1413 PetscCall(FindFieldSlot(definition, definition->covariances[pair].first, &a));
1414 PetscCall(FindFieldSlot(definition, definition->covariances[pair].second, &b));
1415 PetscCall(PicurvCovarianceComponentCount(view[a].descriptor->dof, view[b].descriptor->dof, &components));
1416 PetscCall(PicurvStatisticsComponentDM(user, components, &pair_dm));
1417 ProductComponents(PETSC_FALSE, view[a].descriptor->dof, view[b].descriptor->dof, components, first, second);
1418 PetscCall(AccumulateParticleCentredProducts(user, particle[a], particle[b], view[a].dm, centre[a],
1419 view[b].dm, centre[b], components, first, second,
1420 pair_dm, storage->cm[pair]));
1421 }
1422
1423 for (PetscInt f = 0; f < definition->field_count; ++f) PetscCall(VecDestroy(&centre[f]));
1425 PetscFunctionReturn(0);
1426}
PetscErrorCode CalculateParticleCountPerCell(UserCtx *user)
Counts particles in each cell of the DMDA 'da' and stores the result in user->ParticleCount.
PetscErrorCode ScatterParticleFieldCellMean(UserCtx *user, ParticleFieldId particle_field_id, DM dataDM, Vec countVec, PetscBool recount, Vec meanVec)
Cell mean of a particle field: the field summed over each cell's particles, divided by the cell's cou...
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
PetscErrorCode ParticleFieldIdFromScatterTarget(FieldId target, ParticleFieldId *field_id)
Find the particle field that scatters to an Eulerian field.
static void ProductComponents(PetscBool self, PetscInt dof_a, PetscInt dof_b, PetscInt components, PetscInt first[6], PetscInt second[6])
Internal helper: the component pairs one stored product carries.
static PetscErrorCode AccumulateParticleCentredProducts(UserCtx *user, ParticleFieldId field_a, ParticleFieldId field_b, DM dm_a, Vec mean_a, DM dm_b, Vec mean_b, PetscInt components, const PetscInt first[6], const PetscInt second[6], DM product_dm, Vec product)
Internal helper: adds every particle's centred product into its cell.
#define PICURV_WINDOW_MAX_REQUESTS
Maximum fields or covariance pairs one window may request.
Here is the call graph for this function:
Here is the caller graph for this function:

◆ PicurvWindowStorageReduce()

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.

Every point of a retained slot is combined into one state through the weighted merge: the slot mean is the weight-averaged point mean, and the slot co-moment adds to the point co-moments the spread of the point means about it, \(C = \sum_p [C_p + W_p (\mu_{a,p} - \mu_a)(\mu_{b,p} - \mu_b)] / \sum_p W_p\). It is the moment of the slot's whole sample set, which an average of the point statistics is not.

The result is written back at every point of its slot, as a state of unit weight holding the merged mean and the merged co-moments already divided by the merged weight. The derivation therefore applies to it unchanged, and a point carries weight only where its slot was sampled. Its occupancy totals are not the slot's.

Parameters
[in]userBlock context supplying the target domain and mask.
[in]definitionWindow definition.
[in]storagePointwise state to merge.
[in]average_directionDirections to merge over, in (i, j, k) order.
[out]reducedStorage created for definition; overwritten.
Returns
Zero on success, or a PETSc error.

Merges a window's pointwise state over homogeneous directions.

See also
PicurvWindowStorageReduce()

Definition at line 1467 of file statistics_accumulator.c.

1471{
1472 SpatialTargetPlan plan;
1473 const PetscInt set_count = (storage && storage->occupied_count) ? 2 : 1;
1474
1475 PetscFunctionBeginUser;
1477 PetscCheck(user != NULL && definition != NULL && storage != NULL && reduced != NULL && average_direction != NULL,
1478 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, definition, and both storages are required.");
1479 reduced->physical_units = storage->physical_units;
1480 if (definition->field_count == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
1481 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
1483
1484 /* Slot means, each over its field's own sample set, then the occupied-state means
1485 * of ordinary fields that an occupied pair centres on. */
1486 for (PetscInt f = 0; f < definition->field_count; ++f) {
1487 FieldView view;
1488 Vec count = NULL, weight = NULL, weight_sq = NULL;
1489
1490 PetscCall(FieldGetView(user, (FieldId)definition->fields[f].field_id, &view));
1491 SampleSetOccupancy(storage, RequestSampleSet(definition, f, -1), &count, &weight, &weight_sq);
1492 PetscCall(ReduceSampleSetMean(user, &plan, view.dm, view.descriptor->dof, storage->mean[f], weight,
1493 average_direction, reduced->mean[f]));
1494 if (storage->occupied_mean && storage->occupied_mean[f]) {
1495 PetscCall(ReduceSampleSetMean(user, &plan, view.dm, view.descriptor->dof, storage->occupied_mean[f],
1496 storage->occupied_weight, average_direction, reduced->occupied_mean[f]));
1497 }
1498 }
1499
1500 /* Slot co-moments: every point's own co-moment plus the spread of its means about
1501 * the slot means, divided by the slot weight, all over the request's sample set.
1502 * Self-products, then cross pairs. */
1503 for (PetscInt index = 0; index < storage->field_count + storage->covariance_count; ++index) {
1504 const PetscBool self = (PetscBool)(index < storage->field_count);
1505 const PetscInt pair = index - storage->field_count;
1506 const SampleSet set = self ? RequestSampleSet(definition, index, -1) : RequestSampleSet(definition, -1, pair);
1507 PetscInt a = index, b = index, components = 0, first[6], second[6];
1508 FieldView view_a, view_b;
1509 PetscScalar ****point_a = NULL, ****point_b = NULL, ****slot_a = NULL, ****slot_b = NULL;
1510 PetscScalar ****moment = NULL, ****total = NULL;
1511 PetscReal ***weight = NULL;
1512 Vec source = NULL, target = NULL, scratch = NULL, count_vec = NULL, weight_vec = NULL, weight_sq_vec = NULL;
1513 DM product_dm = NULL;
1514
1515 if (self) {
1516 if (!storage->m2[index]) continue;
1517 source = storage->m2[index];
1518 target = reduced->m2[index];
1519 } else {
1520 PetscCall(FindFieldSlot(definition, definition->covariances[pair].first, &a));
1521 PetscCall(FindFieldSlot(definition, definition->covariances[pair].second, &b));
1522 source = storage->cm[pair];
1523 target = reduced->cm[pair];
1524 }
1525 SampleSetOccupancy(storage, set, &count_vec, &weight_vec, &weight_sq_vec);
1526 PetscCall(FieldGetView(user, (FieldId)definition->fields[a].field_id, &view_a));
1527 PetscCall(FieldGetView(user, (FieldId)definition->fields[b].field_id, &view_b));
1528 PetscCall(VecGetDM(source, &product_dm));
1529 PetscCall(DMDAGetInfo(product_dm, NULL, NULL, NULL, NULL, NULL, NULL, NULL, &components,
1530 NULL, NULL, NULL, NULL, NULL));
1531 ProductComponents(self, view_a.descriptor->dof, view_b.descriptor->dof, components, first, second);
1532
1533 PetscCall(VecDuplicate(source, &scratch));
1534 PetscCall(DMDAVecGetArrayRead(user->da, weight_vec, &weight));
1535 PetscCall(DMDAVecGetArrayDOFRead(view_a.dm, SampleSetMean(storage, set, a), &point_a));
1536 PetscCall(DMDAVecGetArrayDOFRead(view_b.dm, SampleSetMean(storage, set, b), &point_b));
1537 PetscCall(DMDAVecGetArrayDOFRead(view_a.dm, SampleSetMean(reduced, set, a), &slot_a));
1538 PetscCall(DMDAVecGetArrayDOFRead(view_b.dm, SampleSetMean(reduced, set, b), &slot_b));
1539 PetscCall(DMDAVecGetArrayDOFRead(product_dm, source, &moment));
1540 PetscCall(DMDAVecGetArrayDOF(product_dm, scratch, &total));
1541 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k)
1542 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j)
1543 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1544 for (PetscInt c = 0; c < components; ++c) {
1545 total[k][j][i][c] = moment[k][j][i][c] + weight[k][j][i] *
1546 (point_a[k][j][i][first[c]] - slot_a[k][j][i][first[c]]) *
1547 (point_b[k][j][i][second[c]] - slot_b[k][j][i][second[c]]);
1548 }
1549 }
1550 PetscCall(DMDAVecRestoreArrayDOF(product_dm, scratch, &total));
1551 PetscCall(DMDAVecRestoreArrayDOFRead(product_dm, source, &moment));
1552 PetscCall(DMDAVecRestoreArrayDOFRead(view_b.dm, SampleSetMean(reduced, set, b), &slot_b));
1553 PetscCall(DMDAVecRestoreArrayDOFRead(view_a.dm, SampleSetMean(reduced, set, a), &slot_a));
1554 PetscCall(DMDAVecRestoreArrayDOFRead(view_b.dm, SampleSetMean(storage, set, b), &point_b));
1555 PetscCall(DMDAVecRestoreArrayDOFRead(view_a.dm, SampleSetMean(storage, set, a), &point_a));
1556 PetscCall(DMDAVecRestoreArrayRead(user->da, weight_vec, &weight));
1557 PetscCall(PicurvSpatialRatioAverage(user, &plan, scratch, weight_vec, weight_vec,
1558 average_direction, PETSC_COMM_WORLD, target, NULL));
1559 PetscCall(VecDestroy(&scratch));
1560 }
1561
1562 /* Unit weight wherever a set's slot was sampled, so derivation reads the stored
1563 * values as they are. The averaged weight is positive exactly there. */
1564 for (PetscInt set = 0; set < set_count; ++set) {
1565 Vec count = NULL, weight = NULL, weight_sq = NULL, merged_count = NULL, merged = NULL, merged_sq = NULL;
1566 PetscReal ***occupied = NULL;
1567
1568 SampleSetOccupancy(storage, (SampleSet)set, &count, &weight, &weight_sq);
1569 SampleSetOccupancy(reduced, (SampleSet)set, &merged_count, &merged, &merged_sq);
1570 PetscCall(PicurvSpatialRatioAverage(user, &plan, weight, NULL, weight, average_direction,
1571 PETSC_COMM_WORLD, merged, NULL));
1572 PetscCall(DMDAVecGetArray(user->da, merged, &occupied));
1573 for (PetscInt k = plan.start[2]; k < plan.end[2]; ++k)
1574 for (PetscInt j = plan.start[1]; j < plan.end[1]; ++j)
1575 for (PetscInt i = plan.start[0]; i < plan.end[0]; ++i) {
1576 occupied[k][j][i] = (occupied[k][j][i] > 0.0) ? 1.0 : 0.0;
1577 }
1578 PetscCall(DMDAVecRestoreArray(user->da, merged, &occupied));
1579 PetscCall(VecCopy(merged, merged_count));
1580 PetscCall(VecCopy(merged, merged_sq));
1581 }
1583 PetscFunctionReturn(0);
1584}
static PetscErrorCode ReduceSampleSetMean(UserCtx *user, const SpatialTargetPlan *plan, DM dm, PetscInt dof, Vec point_mean, Vec weight, const PetscBool average_direction[3], Vec slot_mean)
Internal helper: merges one point-mean field into its slot means over a sample set.
Here is the call graph for this function:
Here is the caller graph for this function: