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

Go to the source code of this file.

Functions

PetscErrorCode ComputeNodalAverage (UserCtx *user, const char *in_field_name, const char *out_field_name)
 Interpolates a cell-centered field to nodal locations using local stencil averaging.
 
PetscErrorCode ComputeQCriterion (UserCtx *user)
 Computes the Q-criterion diagnostic from the local velocity-gradient tensor.
 
PetscErrorCode NormalizeRelativeField (UserCtx *user, const char *relative_field_name)
 Normalizes pressure using the value at the configured logical grid point.
 
PetscErrorCode DimensionalizeField (UserCtx *user, const char *field_name)
 Scales a specified field from non-dimensional to dimensional units in-place.
 
PetscErrorCode ComputeSpecificKE (UserCtx *user, const char *velocity_field, const char *ske_field)
 Computes the specific kinetic energy (KE per unit mass) for each particle.
 
PetscErrorCode ComputeDisplacement (UserCtx *user, const char *disp_field)
 Computes the displacement magnitude |r_i - r_0| for each particle (per-particle VTK kernel).
 
PetscErrorCode ComputeWindowStatisticNodal (UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, PetscInt output_index, char *out_name, size_t name_size, Vec *out_vec, PetscInt *out_components)
 Derives one accumulated statistic and converts it to nodal values.
 
PetscErrorCode ComputeWindowStatisticsProfile (UserCtx *user, const PicurvWindowDefinition *definition, const PicurvWindowStorage *storage, const char *outputs, const PetscBool average_direction[3], const char *output_prefix, PetscInt ti)
 Writes a window's statistics merged over homogeneous directions as a profile.
 
PetscErrorCode ComputeWindowStatisticsSummary (UserCtx *user, PetscInt window_index, const char *output_prefix, PetscInt ti)
 Appends one convergence row for an accumulated window to its CSV history.
 

Function Documentation

◆ ComputeNodalAverage()

PetscErrorCode ComputeNodalAverage ( UserCtx *  user,
const char *  in_field_name,
const char *  out_field_name 
)

Interpolates a cell-centered field to nodal locations using local stencil averaging.

The kernel reads the input field by name, computes nodal values, and stores the output in the named destination field. Both fields must already exist in the current UserCtx.

Parameters
[in,out]userBlock-level context that owns the source and destination vectors.
[in]in_field_nameName of the input field to sample.
[in]out_field_nameName of the output field to populate.
Returns
PetscErrorCode 0 on success.

Interpolates a cell-centered field to nodal locations using local stencil averaging.

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

See also
ComputeNodalAverage()

Definition at line 96 of file postprocessing_kernels.c.

97{
98 PetscErrorCode ierr;
99 FieldId in_field_id;
100 Vec in_vec_local = NULL, out_vec_global = NULL;
101 DM dm_in = NULL, dm_out = NULL;
102 PetscInt dof = 0;
103
104 PetscFunctionBeginUser;
106 LOG_ALLOW(GLOBAL, LOG_INFO, "-> KERNEL: Running ComputeNodalAverage on '%s' -> '%s'.\n", in_field_name, out_field_name);
107
108 // --- 1. Map string names to PETSc objects ---
109 if (strcasecmp(in_field_name, "P") == 0) { in_vec_local = user->lP; dm_in = user->da; dof = 1; }
110 else if (strcasecmp(in_field_name, "Ucat") == 0) { in_vec_local = user->lUcat; dm_in = user->fda; dof = 3; }
111 else if (strcasecmp(in_field_name, "Psi") == 0) { in_vec_local = user->lPsi; dm_in = user->da; dof = 1; }
112 else if (strcasecmp(in_field_name, "Qcrit") == 0) { in_vec_local = user->lQcrit; dm_in = user->da; dof = 1; }
113 /* The staging pair carries derived statistics, which are config-counted and so
114 * cannot be named by a compile-time member of their own. */
115 else if (strcasecmp(in_field_name, "PostScalar") == 0) { in_vec_local = user->lPostScalar; dm_in = user->da; dof = 1; }
116 else if (strcasecmp(in_field_name, "PostVector") == 0) { in_vec_local = user->lPostVector; dm_in = user->fda; dof = 3; }
117 // ... (add other fields as needed) ...
118 else SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Unknown input field name for nodal averaging: %s", in_field_name);
119
120 if (strcasecmp(out_field_name, "P_nodal") == 0) { out_vec_global = user->P_nodal; dm_out = user->da; }
121 else if (strcasecmp(out_field_name, "Ucat_nodal") == 0) { out_vec_global = user->Ucat_nodal; dm_out = user->fda; }
122 else if (strcasecmp(out_field_name, "Psi_nodal") == 0) { out_vec_global = user->Psi_nodal; dm_out = user->da; }
123 else if (strcasecmp(out_field_name, "Qcrit_nodal") == 0) { out_vec_global = user->Qcrit_nodal; dm_out = user->da; }
124 else if (strcasecmp(out_field_name, "PostScalarNodal") == 0) { out_vec_global = user->PostScalarNodal; dm_out = user->da; }
125 else if (strcasecmp(out_field_name, "PostVectorNodal") == 0) { out_vec_global = user->PostVectorNodal; dm_out = user->fda; }
126 // ... (add other fields as needed) ...
127 else SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONG, "Unknown output field name for nodal averaging: %s", out_field_name);
128
129 // --- 2. Ensure Input Data Ghosts are Up-to-Date ---
130 ierr = FieldIdFromName(in_field_name, &in_field_id); CHKERRQ(ierr);
131 ierr = UpdateLocalGhosts(user, in_field_id); CHKERRQ(ierr);
132 /* The boundary node average reads the dummy cells, so show them before averaging. */
133 if (get_log_level() >= LOG_VERBOSE && is_function_allowed(__func__)) {
134 ierr = LOG_FIELD_ANATOMY(user, in_field_id, "PreNodalAverage"); CHKERRQ(ierr);
135 }
136
137 // --- 3. Get DMDA info and array pointers ---
138 DMDALocalInfo info;
139 info = user->info; // dm_out is user->da or user->fda, which share one decomposition
140 /* Every owned output point is valid except the global high layout plane.
141 * A rank interface is not a boundary: its +1 source value is in the halo. */
142 const PetscInt i_end = PetscMin(info.xs + info.xm, info.mx - 1);
143 const PetscInt j_end = PetscMin(info.ys + info.ym, info.my - 1);
144 const PetscInt k_end = PetscMin(info.zs + info.zm, info.mz - 1);
145
146 if (dof == 1) { // --- Scalar Field Averaging ---
147 const PetscReal ***l_in_arr;
148 PetscReal ***g_out_arr;
149 ierr = DMDAVecGetArrayRead(dm_in,in_vec_local, (void*)&l_in_arr); CHKERRQ(ierr);
150 ierr = DMDAVecGetArray(dm_out,out_vec_global, (void*)&g_out_arr); CHKERRQ(ierr);
151
152 // Loop over the output NODE locations. The loop bounds match the required
153 // size of the final subsampled grid.
154 for (PetscInt k = info.zs; k < k_end; k++) {
155 for (PetscInt j = info.ys; j < j_end; j++) {
156 for (PetscInt i = info.xs; i < i_end; i++) {
157 g_out_arr[k][j][i] = 0.125 * (l_in_arr[k][j][i] + l_in_arr[k][j][i+1] +
158 l_in_arr[k][j+1][i] + l_in_arr[k][j+1][i+1] +
159 l_in_arr[k+1][j][i] + l_in_arr[k+1][j][i+1] +
160 l_in_arr[k+1][j+1][i] + l_in_arr[k+1][j+1][i+1]);
161 }
162 }
163 }
164 ierr = DMDAVecRestoreArrayRead(dm_in,in_vec_local, (void*)&l_in_arr); CHKERRQ(ierr);
165 ierr = DMDAVecRestoreArray(dm_out,out_vec_global, (void*)&g_out_arr); CHKERRQ(ierr);
166
167 } else if (dof == 3) { // --- Vector Field Averaging ---
168 const Cmpnts ***l_in_arr;
169 Cmpnts ***g_out_arr;
170 ierr = DMDAVecGetArrayRead(dm_in,in_vec_local, (void*)&l_in_arr); CHKERRQ(ierr);
171 ierr = DMDAVecGetArray(dm_out,out_vec_global, (void*)&g_out_arr); CHKERRQ(ierr);
172
173 for (PetscInt k = info.zs; k < k_end; k++) {
174 for (PetscInt j = info.ys; j < j_end; j++) {
175 for (PetscInt i = info.xs; i < i_end; i++) {
176 g_out_arr[k][j][i].x = 0.125 * (l_in_arr[k][j][i].x + l_in_arr[k][j][i+1].x +
177 l_in_arr[k][j+1][i].x + l_in_arr[k][j+1][i+1].x +
178 l_in_arr[k+1][j][i].x + l_in_arr[k+1][j][i+1].x +
179 l_in_arr[k+1][j+1][i].x + l_in_arr[k+1][j+1][i+1].x);
180
181 g_out_arr[k][j][i].y = 0.125 * (l_in_arr[k][j][i].y + l_in_arr[k][j][i+1].y +
182 l_in_arr[k][j+1][i].y + l_in_arr[k][j+1][i+1].y +
183 l_in_arr[k+1][j][i].y + l_in_arr[k+1][j][i+1].y +
184 l_in_arr[k+1][j+1][i].y + l_in_arr[k+1][j+1][i+1].y);
185
186 g_out_arr[k][j][i].z = 0.125 * (l_in_arr[k][j][i].z + l_in_arr[k][j][i+1].z +
187 l_in_arr[k][j+1][i].z + l_in_arr[k][j+1][i+1].z +
188 l_in_arr[k+1][j][i].z + l_in_arr[k+1][j][i+1].z +
189 l_in_arr[k+1][j+1][i].z + l_in_arr[k+1][j+1][i+1].z);
190 }
191 }
192 }
193 ierr = DMDAVecRestoreArrayRead(dm_in,in_vec_local, (void*)&l_in_arr); CHKERRQ(ierr);
194 ierr = DMDAVecRestoreArray(dm_out,out_vec_global, (void*)&g_out_arr); CHKERRQ(ierr);
195 }
197 PetscFunctionReturn(0);
198}
PetscErrorCode FieldIdFromName(const char *field_name, FieldId *field_id)
Resolve a user-facing field name once into its typed identity.
FieldId
Compile-time identity for a catalogued Eulerian field.
PetscBool is_function_allowed(const char *functionName)
Checks if a given function is in the allow-list.
Definition logging.c:207
#define GLOBAL
Scope for global logging across all processes.
Definition logging.h:46
#define LOG_ALLOW(scope, level, fmt,...)
Logging macro that checks both the log level and whether the calling function is in the allowed-funct...
Definition logging.h:214
#define PROFILE_FUNCTION_END
Marks the end of a profiled code block.
Definition logging.h:1029
PetscErrorCode LOG_FIELD_ANATOMY(UserCtx *user, FieldId field_id, const char *stage_name)
Logs the anatomy of a specified field at key boundary locations, respecting the solver's specific gri...
Definition logging.c:2903
@ LOG_INFO
Informational messages about program execution.
Definition logging.h:31
@ LOG_VERBOSE
Extremely detailed logs, typically for development use only.
Definition logging.h:34
#define PROFILE_FUNCTION_BEGIN
Marks the beginning of a profiled function: an always-on aggregate timer.
Definition logging.h:1000
static LogLevel get_log_level(void)
Retrieves the current logging level from the environment variable LOG_LEVEL.
Definition logging.h:496
PetscErrorCode UpdateLocalGhosts(UserCtx *user, FieldId field_id)
Updates the local vector (including ghost points) from its corresponding global vector.
Definition setup.c:2593
Vec Qcrit_nodal
Q-criterion averaged to grid nodes; the field a .vts can place correctly.
Definition variables.h:1284
Vec lPostScalar
Definition variables.h:1219
Vec P_nodal
Definition variables.h:1281
Vec Ucat_nodal
Definition variables.h:1282
Vec PostScalarNodal
Definition variables.h:1219
PetscScalar x
Definition variables.h:145
PetscScalar z
Definition variables.h:145
Vec PostVectorNodal
Definition variables.h:1220
Vec Psi_nodal
Definition variables.h:1285
Vec lPostVector
Definition variables.h:1220
DMDALocalInfo info
Definition variables.h:1169
Vec lUcat
Definition variables.h:1197
PetscScalar y
Definition variables.h:145
Vec lQcrit
Cell-centred Q-criterion and its ghosted copy for nodal averaging.
Definition variables.h:1283
A 3D point or vector with PetscScalar components.
Definition variables.h:144
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeQCriterion()

PetscErrorCode ComputeQCriterion ( UserCtx *  user)

Computes the Q-criterion diagnostic from the local velocity-gradient tensor.

This kernel evaluates rotational versus strain-rate dominance and writes the result into the configured Q-criterion output vector for visualization and flow feature identification.

Parameters
[in,out]userBlock-level context containing velocity fields and target output storage.
Returns
PetscErrorCode 0 on success.

Computes the Q-criterion diagnostic from the local velocity-gradient tensor.

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

See also
ComputeQCriterion()

Definition at line 486 of file postprocessing_kernels.c.

487{
488 PetscErrorCode ierr;
489 DMDALocalInfo info;
490 const Cmpnts ***lucat, ***lcsi, ***leta, ***lzet;
491 const PetscReal***laj, ***lnvert;
492 PetscReal ***gq;
493
494 PetscFunctionBeginUser;
496 LOG_ALLOW(GLOBAL, LOG_INFO, "-> KERNEL: Running ComputeQCriterion.\n");
497
498 // --- 1. Ensure all required ghost values are up-to-date ---
499 ierr = UpdateLocalGhosts(user, FIELD_ID_UCAT); CHKERRQ(ierr);
500 ierr = UpdateLocalGhosts(user, FIELD_ID_CSI); CHKERRQ(ierr);
501 ierr = UpdateLocalGhosts(user, FIELD_ID_ETA); CHKERRQ(ierr);
502 ierr = UpdateLocalGhosts(user, FIELD_ID_ZET); CHKERRQ(ierr);
503 ierr = UpdateLocalGhosts(user, FIELD_ID_AJ); CHKERRQ(ierr);
504 ierr = UpdateLocalGhosts(user, FIELD_ID_NVERT); CHKERRQ(ierr);
505
506 // --- 2. Get DMDA info and array pointers ---
507 info = user->info;
508
509 ierr = DMDAVecGetArrayRead(user->fda, user->lUcat, (void*)&lucat); CHKERRQ(ierr);
510 ierr = DMDAVecGetArrayRead(user->fda, user->lCsi, (void*)&lcsi); CHKERRQ(ierr);
511 ierr = DMDAVecGetArrayRead(user->fda, user->lEta, (void*)&leta); CHKERRQ(ierr);
512 ierr = DMDAVecGetArrayRead(user->fda, user->lZet, (void*)&lzet); CHKERRQ(ierr);
513 ierr = DMDAVecGetArrayRead(user->da, user->lAj, (void*)&laj); CHKERRQ(ierr);
514 ierr = DMDAVecGetArrayRead(user->da, user->lNvert, (void*)&lnvert); CHKERRQ(ierr);
515 ierr = DMDAVecGetArray(user->da, user->Qcrit, (void*)&gq); CHKERRQ(ierr);
516
517 // --- 3. Define Loop Bounds for INTERIOR Cells ---
518 PetscInt i_start = (info.xs == 0) ? 1 : info.xs;
519 PetscInt i_end = (info.xs + info.xm == info.mx) ? info.mx - 1 : info.xs + info.xm;
520 PetscInt j_start = (info.ys == 0) ? 1 : info.ys;
521 PetscInt j_end = (info.ys + info.ym == info.my) ? info.my - 1 : info.ys + info.ym;
522 PetscInt k_start = (info.zs == 0) ? 1 : info.zs;
523 PetscInt k_end = (info.zs + info.zm == info.mz) ? info.mz - 1 : info.zs + info.zm;
524
525 // --- 4. Main Computation Loop ---
526 for (PetscInt k = k_start; k < k_end; k++) {
527 for (PetscInt j = j_start; j < j_end; j++) {
528 for (PetscInt i = i_start; i < i_end; i++) {
529
530 // Calculate velocity derivatives in computational space (central differences)
531 PetscReal uc = 0.5 * (lucat[k][j][i+1].x - lucat[k][j][i-1].x);
532 PetscReal vc = 0.5 * (lucat[k][j][i+1].y - lucat[k][j][i-1].y);
533 PetscReal wc = 0.5 * (lucat[k][j][i+1].z - lucat[k][j][i-1].z);
534
535 PetscReal ue = 0.5 * (lucat[k][j+1][i].x - lucat[k][j-1][i].x);
536 PetscReal ve = 0.5 * (lucat[k][j+1][i].y - lucat[k][j-1][i].y);
537 PetscReal we = 0.5 * (lucat[k][j+1][i].z - lucat[k][j-1][i].z);
538
539 PetscReal uz = 0.5 * (lucat[k+1][j][i].x - lucat[k-1][j][i].x);
540 PetscReal vz = 0.5 * (lucat[k+1][j][i].y - lucat[k-1][j][i].y);
541 PetscReal wz = 0.5 * (lucat[k+1][j][i].z - lucat[k-1][j][i].z);
542
543 // Average metrics to the cell center
544 PetscReal csi1 = 0.5 * (lcsi[k][j][i].x + lcsi[k][j][i-1].x) * laj[k][j][i];
545 PetscReal csi2 = 0.5 * (lcsi[k][j][i].y + lcsi[k][j][i-1].y) * laj[k][j][i];
546 PetscReal csi3 = 0.5 * (lcsi[k][j][i].z + lcsi[k][j][i-1].z) * laj[k][j][i];
547
548 PetscReal eta1 = 0.5 * (leta[k][j][i].x + leta[k][j-1][i].x) * laj[k][j][i];
549 PetscReal eta2 = 0.5 * (leta[k][j][i].y + leta[k][j-1][i].y) * laj[k][j][i];
550 PetscReal eta3 = 0.5 * (leta[k][j][i].z + leta[k][j-1][i].z) * laj[k][j][i];
551
552 PetscReal zet1 = 0.5 * (lzet[k][j][i].x + lzet[k-1][j][i].x) * laj[k][j][i];
553 PetscReal zet2 = 0.5 * (lzet[k][j][i].y + lzet[k-1][j][i].y) * laj[k][j][i];
554 PetscReal zet3 = 0.5 * (lzet[k][j][i].z + lzet[k-1][j][i].z) * laj[k][j][i];
555
556 // Calculate velocity gradient tensor components d_ij = du_i/dx_j
557 PetscReal d11 = uc * csi1 + ue * eta1 + uz * zet1;
558 PetscReal d12 = uc * csi2 + ue * eta2 + uz * zet2;
559 PetscReal d13 = uc * csi3 + ue * eta3 + uz * zet3;
560
561 PetscReal d21 = vc * csi1 + ve * eta1 + vz * zet1;
562 PetscReal d22 = vc * csi2 + ve * eta2 + vz * zet2;
563 PetscReal d23 = vc * csi3 + ve * eta3 + vz * zet3;
564
565 PetscReal d31 = wc * csi1 + we * eta1 + wz * zet1;
566 PetscReal d32 = wc * csi2 + we * eta2 + wz * zet2;
567 PetscReal d33 = wc * csi3 + we * eta3 + wz * zet3;
568
569 // Strain-Rate Tensor S_ij = 0.5 * (d_ij + d_ji)
570 PetscReal s11 = d11;
571 PetscReal s12 = 0.5 * (d12 + d21);
572 PetscReal s13 = 0.5 * (d13 + d31);
573 PetscReal s22 = d22;
574 PetscReal s23 = 0.5 * (d23 + d32);
575 PetscReal s33 = d33;
576
577 // Vorticity Tensor Omega_ij = 0.5 * (d_ij - d_ji)
578 PetscReal w12 = 0.5 * (d12 - d21);
579 PetscReal w13 = 0.5 * (d13 - d31);
580 PetscReal w23 = 0.5 * (d23 - d32);
581
582 // Squared norms of the tensors
583 PetscReal s_norm_sq = s11*s11 + s22*s22 + s33*s33 + 2.0*(s12*s12 + s13*s13 + s23*s23);
584 PetscReal w_norm_sq = 2.0 * (w12*w12 + w13*w13 + w23*w23);
585
586 gq[k][j][i] = 0.5 * (w_norm_sq - s_norm_sq);
587
588 if (lnvert[k][j][i] > 0.1) {
589 gq[k][j][i] = 0.0;
590 }
591 }
592 }
593 }
594
595 // --- 5. Restore arrays ---
596 ierr = DMDAVecRestoreArrayRead(user->fda, user->lUcat, (void*)&lucat); CHKERRQ(ierr);
597 ierr = DMDAVecRestoreArrayRead(user->fda, user->lCsi, (void*)&lcsi); CHKERRQ(ierr);
598 ierr = DMDAVecRestoreArrayRead(user->fda, user->lEta, (void*)&leta); CHKERRQ(ierr);
599 ierr = DMDAVecRestoreArrayRead(user->fda, user->lZet, (void*)&lzet); CHKERRQ(ierr);
600 ierr = DMDAVecRestoreArrayRead(user->da, user->lAj, (void*)&laj); CHKERRQ(ierr);
601 ierr = DMDAVecRestoreArrayRead(user->da, user->lNvert, (void*)&lnvert); CHKERRQ(ierr);
602 ierr = DMDAVecRestoreArray(user->da, user->Qcrit, (void*)&gq); CHKERRQ(ierr);
603
604 /* With dimensionalize on, Ucat already carries U_ref but the metrics are still
605 * nondimensional, so the gradients above are U_ref/L_ref short of physical by one
606 * factor of L_ref each: Q came out U_ref^2 Q* instead of (U_ref/L_ref)^2 Q*. */
607 if (user->simCtx->pps && user->simCtx->pps->dimensionalize) {
608 PetscReal length_scale = 1.0;
609 if (!PicurvFieldReferenceScale(user->simCtx, "Coordinates", &length_scale, NULL, 0) &&
610 length_scale > 0.0) {
611 ierr = VecScale(user->Qcrit, 1.0 / (length_scale * length_scale)); CHKERRQ(ierr);
612 }
613 }
614
615 /* The loop above skips the layout boundary, so fill it before anything reads
616 * Qcrit with a stencil. Q is not a moment: it does not vanish at a wall, so only
617 * the periodic case is defined, and the cell synchronizer writes only that case. */
618 {
619 const FieldId qcrit[] = {FIELD_ID_QCRIT};
620 ierr = SynchronizePeriodicCellFields(user, 1, qcrit); CHKERRQ(ierr);
621 }
622
624 PetscFunctionReturn(0);
625}
PetscErrorCode SynchronizePeriodicCellFields(UserCtx *user, PetscInt num_fields, const FieldId field_ids[])
Synchronizes periodic endpoint cells for a list of cell-centered fields.
@ FIELD_ID_CSI
@ FIELD_ID_NVERT
@ FIELD_ID_UCAT
@ FIELD_ID_AJ
@ FIELD_ID_ETA
@ FIELD_ID_QCRIT
@ FIELD_ID_ZET
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
Vec lNvert
Definition variables.h:1197
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
Vec Qcrit
Definition variables.h:1283
PostProcessParams * pps
Definition variables.h:1131
Here is the call graph for this function:
Here is the caller graph for this function:

◆ NormalizeRelativeField()

PetscErrorCode NormalizeRelativeField ( UserCtx *  user,
const char *  relative_field_name 
)

Normalizes pressure using the value at the configured logical grid point.

The owning rank reads the reference value, shares it collectively, and every rank subtracts it in-place from its distributed portion of the field.

Parameters
[in,out]userBlock-level context containing pressure and reference configuration.
[in]relative_field_nameName of the field to normalize.
Returns
PetscErrorCode 0 on success.

Normalizes pressure using the value at the configured logical grid point.

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

See also
NormalizeRelativeField()

Definition at line 633 of file postprocessing_kernels.c.

634{
635 PetscErrorCode ierr;
636 Vec P_vec = NULL;
637 DMDALocalInfo info;
638 PetscInt ip=1, jp=1, kp=1; // Default reference point
639 PetscReal p_ref = 0.0;
640 PetscReal p_ref_local = 0.0;
641 PetscInt found_local = 0, found_global = 0;
642 PostProcessParams *pps = user->simCtx->pps;
643
644 // Fetch the logical reference point from pps.
645 ip = pps->reference[0];
646 jp = pps->reference[1];
647 kp = pps->reference[2];
648
649 PetscFunctionBeginUser;
651 LOG_ALLOW(GLOBAL, LOG_INFO, "-> KERNEL: Running NormalizeRelativeField on '%s'.\n", relative_field_name);
652
653 // --- 1. Map string argument to the PETSc Vec ---
654 if (strcasecmp(relative_field_name, "P") == 0) {
655 P_vec = user->P;
656 } else {
657 SETERRQ(PETSC_COMM_SELF, 1, "NormalizeRelativeField only supports the primary 'P' field , not '%s' currently.", relative_field_name);
658 }
659
660 // --- 2. Read the logical reference point from whichever rank owns it ---
661 info = user->info;
662 PetscCheck(ip >= 0 && ip < info.mx && jp >= 0 && jp < info.my &&
663 kp >= 0 && kp < info.mz,
664 PETSC_COMM_WORLD, PETSC_ERR_ARG_OUTOFRANGE,
665 "Reference point (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT
666 ") lies outside the %" PetscInt_FMT "x%" PetscInt_FMT "x%" PetscInt_FMT
667 " pressure layout.", ip, jp, kp, info.mx, info.my, info.mz);
668 if (ip >= info.xs && ip < info.xs + info.xm &&
669 jp >= info.ys && jp < info.ys + info.ym &&
670 kp >= info.zs && kp < info.zs + info.zm) {
671 const PetscReal ***pressure = NULL;
672
673 ierr = DMDAVecGetArrayRead(user->da, P_vec, &pressure); CHKERRQ(ierr);
674 p_ref_local = pressure[kp][jp][ip];
675 ierr = DMDAVecRestoreArrayRead(user->da, P_vec, &pressure); CHKERRQ(ierr);
676 found_local = 1;
677 }
678 ierr = MPI_Allreduce(&p_ref_local, &p_ref, 1, MPIU_REAL, MPI_SUM,
679 PETSC_COMM_WORLD); CHKERRQ(ierr);
680 ierr = MPI_Allreduce(&found_local, &found_global, 1, MPIU_INT, MPI_SUM,
681 PETSC_COMM_WORLD); CHKERRQ(ierr);
682 PetscCheck(found_global == 1, PETSC_COMM_WORLD, PETSC_ERR_PLIB,
683 "Reference pressure point must have exactly one owner; found %" PetscInt_FMT ".",
684 found_global);
686 "%s reference point (%" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT
687 ") has value %g.\n", relative_field_name, ip, jp, kp, (double)p_ref);
688
689 // --- 3. Perform the normalization (in-place shift) on the full distributed vector ---
690 ierr = VecShift(P_vec, -p_ref); CHKERRQ(ierr);
691 LOG_ALLOW(GLOBAL, LOG_DEBUG, "%s field normalized by subtracting %g.\n", relative_field_name, p_ref);
692
694 PetscFunctionReturn(0);
695}
@ LOG_DEBUG
Detailed debugging information.
Definition logging.h:32
PetscInt reference[3]
Definition variables.h:844
Holds all configuration parameters for a post-processing run.
Definition variables.h:793
Here is the caller graph for this function:

◆ DimensionalizeField()

PetscErrorCode DimensionalizeField ( UserCtx *  user,
const char *  field_name 
)

Scales a specified field from non-dimensional to dimensional units in-place.

Resolves the name in the Eulerian field catalog, then the particle field catalog, and scales the field's storage (its global Vec, the DM coordinates, or its DMSwarm field) by the reference scale of the dimension recorded on its catalog entry.

Parameters
[in,out]userThe UserCtx whose storage is modified.
[in]field_nameCase-insensitive catalogued name or alias, e.g. "Ucat", "Nu_t", "Coordinates", "ParticlePosition".
Returns
Zero on success; PETSC_ERR_ARG_UNKNOWN_TYPE for a name in neither catalog, and PETSC_ERR_ARG_WRONGSTATE for a field without a fixed dimension or without storage in this run.

Scales a specified field from non-dimensional to dimensional units in-place.

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

See also
DimensionalizeField()

Definition at line 14 of file postprocessing_kernels.c.

15{
16 PetscErrorCode ierr;
17 SimCtx *simCtx = NULL;
18 Vec target_vec = NULL;
19 PetscReal scale_factor = 1.0;
20 char field_type[64] = "Unknown";
21 PetscBool is_swarm_field = PETSC_FALSE; // Flag for special swarm handling
22 const char *swarm_field_name = NULL; // Name of the field within the swarm
23 FieldId field_id = FIELD_ID_INVALID;
25 PetscBool found = PETSC_FALSE;
26
27 PetscFunctionBeginUser;
29 if (!user) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "UserCtx is NULL.");
30 if (!field_name) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "field_name is NULL.");
31 simCtx = user->simCtx;
32
33 // --- 1. Resolve the field in either catalog; its entry records its dimension ---
34 ierr = FieldTryIdFromName(field_name, &field_id, &found); CHKERRQ(ierr);
35 if (found && field_id == FIELD_ID_COORDINATES) {
36 target_vec = user->Coor;
37 } else if (found) {
38 FieldView view;
39
40 ierr = FieldGetView(user, field_id, &view); CHKERRQ(ierr);
41 target_vec = view.global_vec;
42 } else {
43 const ParticleFieldDescriptor *descriptor = NULL;
44
45 ierr = ParticleFieldTryIdFromName(field_name, &particle_id, &found); CHKERRQ(ierr);
46 PetscCheck(found, PETSC_COMM_SELF, PETSC_ERR_ARG_UNKNOWN_TYPE,
47 "DimensionalizeField: '%s' is in neither field catalog.", field_name);
48 ierr = ParticleFieldGetDescriptor(particle_id, &descriptor); CHKERRQ(ierr);
49 is_swarm_field = PETSC_TRUE;
50 swarm_field_name = descriptor->canonical_name;
51 }
52 ierr = PicurvFieldReferenceScale(simCtx, field_name, &scale_factor,
53 field_type, sizeof(field_type)); CHKERRQ(ierr);
54
55 // --- 2. Check for trivial scaling ---
56 if (PetscAbsReal(scale_factor - 1.0) < PETSC_MACHINE_EPSILON) {
57 LOG(GLOBAL, LOG_DEBUG, "DimensionalizeField: Scaling factor for '%s' is 1.0. Skipping operation.\n", field_name);
59 PetscFunctionReturn(0);
60 }
61
62 // --- 3. Perform the in-place scaling operation ---
63 LOG(GLOBAL, LOG_INFO, "Scaling '%s' field (%s) by factor %.4e.\n", field_name, field_type, scale_factor);
64
65 if (is_swarm_field) {
66 // Special handling for DMSwarm fields
67 ierr = DMSwarmCreateGlobalVectorFromField(user->swarm, swarm_field_name, &target_vec); CHKERRQ(ierr);
68 ierr = VecScale(target_vec, scale_factor); CHKERRQ(ierr);
69 ierr = DMSwarmDestroyGlobalVectorFromField(user->swarm, swarm_field_name, &target_vec); CHKERRQ(ierr);
70 } else {
71 // Standard handling for PETSc Vecs
72 if (target_vec) {
73 ierr = VecScale(target_vec, scale_factor); CHKERRQ(ierr);
74 } else {
75 SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_ARG_WRONGSTATE, "Target vector for field '%s' was not found or is NULL.", field_name);
76 }
77 }
78
79 // --- 4. Post-scaling updates for special cases ---
80 if (strcasecmp(field_name, "Coordinates") == 0) {
81 ierr = UpdateLocalGhosts(user, FIELD_ID_COORDINATES); CHKERRQ(ierr);
82 }
83
85 PetscFunctionReturn(0);
86}
PetscErrorCode FieldGetView(UserCtx *user, FieldId field_id, FieldView *view)
Resolve the existing DM and global/local vectors for one field.
PetscErrorCode FieldTryIdFromName(const char *field_name, FieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
@ FIELD_ID_COORDINATES
@ FIELD_ID_INVALID
Non-owning runtime objects resolved for one field and UserCtx.
#define LOG(scope, level, fmt,...)
Logging macro for PETSc-based applications with scope control.
Definition logging.h:86
ParticleFieldId
Compile-time identity for a persistent solver-particle field.
@ PARTICLE_FIELD_ID_INVALID
PetscErrorCode ParticleFieldGetDescriptor(ParticleFieldId field_id, const ParticleFieldDescriptor **descriptor)
Return immutable metadata for a valid particle field ID.
PetscErrorCode ParticleFieldTryIdFromName(const char *field_name, ParticleFieldId *field_id, PetscBool *found)
Look a name up without treating an unknown name as an error.
Immutable metadata for one persistent particle field.
The master context for the entire simulation.
Definition variables.h:916
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeSpecificKE()

PetscErrorCode ComputeSpecificKE ( UserCtx *  user,
const char *  velocity_field,
const char *  ske_field 
)

Computes the specific kinetic energy (KE per unit mass) for each particle.

This kernel calculates SKE = 0.5 * |velocity|^2. It requires that the velocity field exists and will populate the specific kinetic energy field. The output field must be registered before this kernel is called.

Parameters
userThe UserCtx containing the DMSwarm.
velocity_fieldThe name of the input vector field for particle velocity.
ske_fieldThe name of the output scalar field to store specific KE.
Returns
PetscErrorCode

Computes the specific kinetic energy (KE per unit mass) for each particle.

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

See also
ComputeSpecificKE()

Definition at line 706 of file postprocessing_kernels.c.

707{
708 PetscErrorCode ierr;
709 PetscInt n_local;
710 const PetscScalar (*vel_arr)[3]; // Access velocity as array of 3-component vectors
711 PetscScalar *ske_arr;
712
713 PetscFunctionBeginUser;
715 LOG_ALLOW(GLOBAL, LOG_INFO, "-> KERNEL: Running ComputeSpecificKE ('%s' -> '%s').\n", velocity_field, ske_field);
716
717 // Get local data arrays from the DMSwarm
718 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
719 if (n_local == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
720
721 // Get read-only access to velocity and write access to the output field
722 ierr = DMSwarmGetField(user->swarm, velocity_field, NULL, NULL, (void**)&vel_arr); CHKERRQ(ierr);
723 ierr = DMSwarmGetField(user->post_swarm, ske_field, NULL, NULL, (void**)&ske_arr); CHKERRQ(ierr);
724
725 // Main computation loop
726 for (PetscInt p = 0; p < n_local; p++) {
727 const PetscScalar u = vel_arr[p][0];
728 const PetscScalar v = vel_arr[p][1];
729 const PetscScalar w = vel_arr[p][2];
730 const PetscScalar vel_sq = u*u + v*v + w*w;
731 ske_arr[p] = 0.5 * vel_sq;
732 }
733
734 // Restore arrays
735 ierr = DMSwarmRestoreField(user->swarm, velocity_field, NULL, NULL, (void**)&vel_arr); CHKERRQ(ierr);
736 ierr = DMSwarmRestoreField(user->post_swarm, ske_field, NULL, NULL, (void**)&ske_arr); CHKERRQ(ierr);
737
739 PetscFunctionReturn(0);
740}
DM post_swarm
Definition variables.h:1280
Here is the caller graph for this function:

◆ ComputeDisplacement()

PetscErrorCode ComputeDisplacement ( UserCtx *  user,
const char *  disp_field 
)

Computes the displacement magnitude |r_i - r_0| for each particle (per-particle VTK kernel).

Reference point r_0 = (simCtx->psrc_x, psrc_y, psrc_z). Writes the scalar displacement to post_swarm[disp_field]. This is a visualisation kernel only — use ComputeParticleMSD from particle_statistics.h for quantitative global statistics.

Parameters
userThe UserCtx containing the DMSwarms.
disp_fieldName of the output scalar field in post_swarm.
Returns
PetscErrorCode

Computes the displacement magnitude |r_i - r_0| for each particle (per-particle VTK kernel).

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

See also
ComputeDisplacement()

Definition at line 748 of file postprocessing_kernels.c.

749{
750 PetscErrorCode ierr;
751 PetscInt n_local;
752 const PetscReal (*pos_arr)[3];
753 PetscScalar *disp_out;
754 SimCtx *simCtx = user->simCtx;
755
756 PetscFunctionBeginUser;
758 LOG_ALLOW(GLOBAL, LOG_INFO, "-> KERNEL: Running ComputeDisplacement (-> '%s').\n", disp_field);
759
760 ierr = DMSwarmGetLocalSize(user->swarm, &n_local); CHKERRQ(ierr);
761 if (n_local == 0) { PROFILE_FUNCTION_END; PetscFunctionReturn(0); }
762
763 const PetscReal x0 = simCtx->psrc_x;
764 const PetscReal y0 = simCtx->psrc_y;
765 const PetscReal z0 = simCtx->psrc_z;
766
767 ierr = DMSwarmGetField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
768 ierr = DMSwarmGetField(user->post_swarm, disp_field, NULL, NULL, (void**)&disp_out); CHKERRQ(ierr);
769
770 for (PetscInt p = 0; p < n_local; p++) {
771 const PetscReal dx = pos_arr[p][0] - x0;
772 const PetscReal dy = pos_arr[p][1] - y0;
773 const PetscReal dz = pos_arr[p][2] - z0;
774 disp_out[p] = PetscSqrtReal(dx*dx + dy*dy + dz*dz);
775 }
776
777 ierr = DMSwarmRestoreField(user->swarm, ParticleFieldName(PARTICLE_FIELD_ID_POSITION), NULL, NULL, (void**)&pos_arr); CHKERRQ(ierr);
778 ierr = DMSwarmRestoreField(user->post_swarm, disp_field, NULL, NULL, (void**)&disp_out); CHKERRQ(ierr);
779
781 PetscFunctionReturn(0);
782}
const char * ParticleFieldName(ParticleFieldId field_id)
Return the canonical PETSc DMSwarm name for an ID.
@ PARTICLE_FIELD_ID_POSITION
PetscReal psrc_x
Definition variables.h:1002
PetscReal psrc_z
Point source location for PARTICLE_INIT_POINT_SOURCE.
Definition variables.h:1002
PetscReal psrc_y
Definition variables.h:1002
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeWindowStatisticNodal()

PetscErrorCode ComputeWindowStatisticNodal ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
const PicurvWindowStorage *  storage,
const char *  outputs,
PetscInt  output_index,
char *  out_name,
size_t  name_size,
Vec *  out_vec,
PetscInt *  out_components 
)

Derives one accumulated statistic and converts it to nodal values.

The counterpart of ComputeNodalAverage() for accumulated window state: it takes an index into a window's requested output set, normalizes the centered state behind it, and leaves the result in the shared post-processing staging field ready for output. The staging vectors are reused between calls, so a caller must consume the result before requesting the next one.

With global_operations.dimensionalize set, the result carries physical units: the source field's reference scale raised to the power the derived kind carries: a mean and an RMS are linear in it, a Reynolds stress and a turbulent kinetic energy quadratic. A co-moment flux relates two possibly different fields, so its factor is the product of their scales rather than one squared. That is what the per-field scaling table alone cannot express, and why one blanket velocity factor would have been wrong for three of the five kinds.

Parameters
[in]userBlock context holding the staging fields.
[in]definitionWindow or ensemble whose state is derived.
[in]storageIts accumulated state.
[in]outputsComma-separated output kinds the recipe requested.
[in]output_indexIndex into that output set.
[out]out_nameName of the derived field, window qualified.
[in]name_sizeCapacity of out_name.
[out]out_vecNodal vector holding the result; borrowed, not owned.
[out]out_componentsComponent count of the result.
Returns
Zero on success, or a PETSc error.

Derives one accumulated statistic and converts it to nodal values.

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

See also
ComputeWindowStatisticNodal()

Definition at line 207 of file postprocessing_kernels.c.

212{
213 PetscErrorCode ierr;
214 PicurvDerivedField derived;
215
216 PetscFunctionBeginUser;
218 PetscCheck(user != NULL && definition != NULL && storage != NULL && out_name != NULL &&
219 out_vec != NULL && out_components != NULL,
220 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, state, and outputs are required.");
221
222 /* Derive into the cell-centred staging pair, then reach the nodal path by
223 * catalogued name. A per-window accumulator has no compile-time offset, so
224 * staging is what lets the shared ghost and nodal kernels address it at all. */
225 ierr = PicurvWindowDerive(user, definition, storage,
226 outputs, output_index, user->PostScalar, user->PostVector,
227 &derived); CHKERRQ(ierr);
228 /* The derivation writes the physical interior only, so the layout boundary would
229 * otherwise reach the nodal average as structural zeros. On periodic axes the
230 * shared cell synchronizer fills the dummy planes from the wrapped physical
231 * planes; the ghost update then carries the written values outward. */
232 if (derived.components == 1) {
233 const FieldId staged[] = {FIELD_ID_POST_SCALAR};
234 ierr = SynchronizePeriodicCellFields(user, 1, staged); CHKERRQ(ierr);
235 ierr = UpdateLocalGhosts(user, FIELD_ID_POST_SCALAR); CHKERRQ(ierr);
236 ierr = ComputeNodalAverage(user, "PostScalar", "PostScalarNodal"); CHKERRQ(ierr);
237 *out_vec = user->PostScalarNodal;
238 } else {
239 const FieldId staged[] = {FIELD_ID_POST_VECTOR};
240 ierr = SynchronizePeriodicCellFields(user, 1, staged); CHKERRQ(ierr);
241 ierr = UpdateLocalGhosts(user, FIELD_ID_POST_VECTOR); CHKERRQ(ierr);
242 ierr = ComputeNodalAverage(user, "PostVector", "PostVectorNodal"); CHKERRQ(ierr);
243 *out_vec = user->PostVectorNodal;
244 }
245 *out_components = derived.components;
246 ierr = PetscStrncpy(out_name, derived.name, name_size); CHKERRQ(ierr);
247
248 LOG_ALLOW(GLOBAL, LOG_DEBUG, "-> KERNEL: Derived '%s' (%d component(s)).\n",
249 out_name, (int)derived.components);
251 PetscFunctionReturn(0);
252}
@ FIELD_ID_POST_VECTOR
@ FIELD_ID_POST_SCALAR
PetscErrorCode ComputeNodalAverage(UserCtx *user, const char *in_field_name, const char *out_field_name)
Implementation of ComputeNodalAverage().
PetscInt components
One or three.
char name[96]
Output field name, window qualified.
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.
One derived output field, resolved by enumeration index.
Vec PostScalar
Definition variables.h:1219
Vec PostVector
Definition variables.h:1220
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeWindowStatisticsProfile()

PetscErrorCode ComputeWindowStatisticsProfile ( UserCtx *  user,
const PicurvWindowDefinition *  definition,
const PicurvWindowStorage *  storage,
const char *  outputs,
const PetscBool  average_direction[3],
const char *  output_prefix,
PetscInt  ti 
)

Writes a window's statistics merged over homogeneous directions as a profile.

Merges the pointwise state over the selected directions through PicurvWindowStorageReduce(), derives every requested output from the merged state, and writes one CSV row per retained slot the window sampled: the slot's 0-based cell index along each retained direction, its mean cell-centre coordinates, and each derived output, a vector one column per component. A variance or stress is that of the slot's whole sample set, including the spread of the point means across it. point_variance is the exception: it is derived at each point first and averaged over the points of the slot that sampled it, each counted once, so it excludes that spread. Selecting every direction gives one row for the whole domain.

With global_operations.dimensionalize set, the outputs and coordinates are physical.

Parameters
[in]userBlock context holding the staging fields.
[in]definitionWindow or ensemble whose state is reduced.
[in]storageIts pointwise state.
[in]outputsComma-separated output kinds the recipe requested.
[in]average_directionDirections to merge over, in (i, j, k) order.
[in]output_prefixOutput path prefix; _profile_<name>_<step>.csv is appended.
[in]tiStep being processed.
Returns
Zero on success, or a PETSc error.

Writes a window's statistics merged over homogeneous directions as a profile.

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

See also
ComputeWindowStatisticsProfile()

Definition at line 260 of file postprocessing_kernels.c.

264{
265 static const char *const axis_index[3] = {"i", "j", "k"};
266 static const char *const axis_coordinate[3] = {"x", "y", "z"};
267 PicurvWindowStorage reduced;
269 DMDALocalInfo info;
270 PetscInt extent[3], slots = 1, derived_count = 0, entries = 0;
271 PetscInt *components = NULL;
272 PetscBool *particle_sampled = NULL;
273 PetscReal *occupied = NULL, *with_particles = NULL, *centre = NULL, *values = NULL, length_scale = 1.0;
274 char (*names)[PICURV_STATISTICS_PAYLOAD_NAME_LENGTH] = NULL;
275
276 PetscFunctionBeginUser;
278 PetscCheck(user != NULL && definition != NULL && storage != NULL && output_prefix != NULL,
279 PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "Context, state, and output prefix are required.");
280 PetscCall(PicurvWindowStorageCreate(user, definition, &reduced));
281 PetscCall(PicurvWindowStorageReduce(user, definition, storage, average_direction, &reduced));
282 PetscCall(PicurvWindowDerivedCount(definition, &reduced, outputs, &derived_count));
283 PetscCall(SpatialTargetPlanCreate(user, (FieldId)definition->fields[0].field_id,
285 info = user->info;
286 extent[0] = average_direction[0] ? 1 : info.mx;
287 extent[1] = average_direction[1] ? 1 : info.my;
288 extent[2] = average_direction[2] ? 1 : info.mz;
289 slots = extent[0] * extent[1] * extent[2];
290
291 /* Occupancy and coordinates are reduced like the outputs, so every column of a row
292 * describes the same set of points. The merged weight is one wherever the slot was
293 * sampled, so its average marks the rows to write. */
294 PetscCall(PetscCalloc4(slots, &occupied, 3 * slots, &centre, PetscMax(derived_count, 1), &components,
295 PetscMax(derived_count, 1), &names));
296 PetscCall(PetscCalloc2(slots, &with_particles, PetscMax(derived_count, 1), &particle_sampled));
297 PetscCall(PicurvSpatialRatioAverage(user, &plan, reduced.weight, NULL, reduced.weight, average_direction,
298 PETSC_COMM_WORLD, NULL, occupied));
299 /* An output measured over the occupied states has no value in a slot no particle
300 * ever reached; it is left empty there rather than written as a zero. */
301 if (reduced.occupied_weight) {
302 PetscCall(PicurvSpatialRatioAverage(user, &plan, reduced.occupied_weight, NULL, reduced.occupied_weight,
303 average_direction, PETSC_COMM_WORLD, NULL, with_particles));
304 }
305 PetscCall(PicurvSpatialRatioAverage(user, &plan, user->Cent, NULL, reduced.weight, average_direction,
306 PETSC_COMM_WORLD, NULL, centre));
307 PetscCall(PetscCalloc1(PetscMax(3 * derived_count * slots, 1), &values));
308 for (PetscInt index = 0; index < derived_count; ++index) {
309 PicurvDerivedField derived;
310
311 /* Each output is staged, then reduced into its own block of the table: `slots`
312 * rows of up to three components, interleaved per slot. */
313 PetscCall(PicurvWindowDerive(user, definition, &reduced, outputs, index,
314 user->PostScalar, user->PostVector, &derived));
315 if (derived.point_averaged) {
316 /* The equal-weight mean, over the points that sampled it, of each point's own
317 * statistic: derived before merging, so the spread of the point means about the
318 * slot mean, which the pooled rule adds, stays out. */
319 PetscCall(PicurvWindowDerive(user, definition, storage, outputs, index,
320 user->PostScalar, user->PostVector, &derived));
321 PetscCall(PicurvSpatialRatioAverage(user, &plan, derived.components == 1 ? user->PostScalar : user->PostVector,
322 NULL, derived.occupied ? storage->occupied_weight : storage->weight,
323 average_direction, PETSC_COMM_WORLD, NULL, values + entries));
324 } else {
325 PetscCall(PicurvSpatialRatioAverage(user, &plan, derived.components == 1 ? user->PostScalar : user->PostVector,
326 NULL, reduced.weight, average_direction, PETSC_COMM_WORLD,
327 NULL, values + entries));
328 }
329 components[index] = derived.components;
330 particle_sampled[index] = derived.occupied;
331 PetscCall(PetscStrncpy(names[index], derived.name, sizeof(names[index])));
332 entries += derived.components * slots;
333 }
334 if (user->simCtx->pps && user->simCtx->pps->dimensionalize) {
335 PetscCall(PicurvFieldReferenceScale(user->simCtx, "Cent", &length_scale, NULL, 0));
336 }
337
338 if (user->simCtx->rank == 0) {
339 char path[PETSC_MAX_PATH_LEN];
340 FILE *csv = NULL;
341
342 PetscCall(PetscSNPrintf(path, sizeof(path), "%s_profile_%s_%05" PetscInt_FMT ".csv",
343 output_prefix, definition->name, ti));
344 csv = fopen(path, "w");
345 PetscCheck(csv != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN, "Unable to open profile '%s'.", path);
346 for (PetscInt axis = 0; axis < 3; ++axis) if (!average_direction[axis]) fprintf(csv, "%s,", axis_index[axis]);
347 fprintf(csv, "x,y,z");
348 for (PetscInt index = 0; index < derived_count; ++index) {
349 for (PetscInt c = 0; c < components[index]; ++c) {
350 fprintf(csv, ",%s%s%s", names[index], components[index] == 1 ? "" : "_",
351 components[index] == 1 ? "" : axis_coordinate[c]);
352 }
353 }
354 fprintf(csv, "\n");
355 for (PetscInt slot = 0; slot < slots; ++slot) {
356 const PetscInt index[3] = {slot % extent[0], (slot / extent[0]) % extent[1], slot / (extent[0] * extent[1])};
357 PetscInt offset = 0;
358
359 /* A slot no point of the window reached has nothing to report. */
360 if (occupied[slot] <= 0.0) continue;
361 /* Storage carries a boundary layer at index zero, so cell c is entry c + 1. */
362 for (PetscInt axis = 0; axis < 3; ++axis) {
363 if (!average_direction[axis]) fprintf(csv, "%d,", (int)(index[axis] - 1));
364 }
365 fprintf(csv, "%.16e,%.16e,%.16e", (double)(centre[3 * slot + 0] * length_scale),
366 (double)(centre[3 * slot + 1] * length_scale), (double)(centre[3 * slot + 2] * length_scale));
367 for (PetscInt output = 0; output < derived_count; ++output) {
368 for (PetscInt c = 0; c < components[output]; ++c) {
369 if (particle_sampled[output] && with_particles[slot] <= 0.0) fprintf(csv, ",");
370 else fprintf(csv, ",%.16e", (double)values[offset + components[output] * slot + c]);
371 }
372 offset += components[output] * slots;
373 }
374 fprintf(csv, "\n");
375 }
376 PetscCheck(fclose(csv) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE, "Unable to close profile '%s'.", path);
377 }
378
379 PetscCall(PetscFree(values));
380 PetscCall(PetscFree2(with_particles, particle_sampled));
381 PetscCall(PetscFree4(occupied, centre, components, names));
382 PetscCall(PicurvWindowStorageDestroy(&reduced));
383 LOG_ALLOW(GLOBAL, LOG_DEBUG, "-> KERNEL: Profiled '%s' at step %" PetscInt_FMT ".\n", definition->name, ti);
385 PetscFunctionReturn(0);
386}
Vec weight
Per-point valid weight.
#define PICURV_STATISTICS_PAYLOAD_NAME_LENGTH
Maximum stored length of a payload name, including the terminator.
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.
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.
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.
PetscBool occupied
Measured over the occupied states, so undefined where they are absent.
PetscErrorCode PicurvWindowStorageDestroy(PicurvWindowStorage *storage)
Releases accumulator state previously created for one window.
Independent accumulator state for one window on one block.
@ PICURV_STATISTICS_MASK_FLUID
PetscErrorCode SpatialTargetPlanCreate(UserCtx *user, FieldId field_id, PicurvStatisticsMask mask, SpatialTargetPlan *plan)
Resolves the iteration domain for one field on one block.
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.
Resolved iteration domain for one field on one block.
PicurvWindowFieldRequest fields[16]
PetscInt field_id
Catalogued Eulerian field identity.
PetscMPIInt rank
Definition variables.h:919
Here is the call graph for this function:
Here is the caller graph for this function:

◆ ComputeWindowStatisticsSummary()

PetscErrorCode ComputeWindowStatisticsSummary ( UserCtx *  user,
PetscInt  window_index,
const char *  output_prefix,
PetscInt  ti 
)

Appends one convergence row for an accumulated window to its CSV history.

The counterpart of ComputeParticleMSD() for Eulerian window state: it reduces the window to the few numbers that answer whether it has run long enough — sample count, total weight, represented time, the per-point valid-fraction range, and the mean turbulent kinetic energy — and appends them as one row per processed step. No single field snapshot can answer that question, which is why the history exists beside the field output rather than instead of it.

The mean is taken over the fluid cells the window actually sampled. Cells outside the target domain, and cells a moving mask excluded, hold zeros that mean "never measured"; averaging over them would scale the result down by the fraction of the grid the window never covered.

Parameters
[in]userBlock context holding the accumulators and staging fields.
[in]window_indexWindow to summarize.
[in]output_prefixOutput path prefix; the window name and .csv are appended.
[in]tiStep being processed, recorded as the row's key.
Returns
Zero on success, or a PETSc error.

Appends one convergence row for an accumulated window to its CSV history.

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

See also
ComputeWindowStatisticsSummary()

Definition at line 394 of file postprocessing_kernels.c.

396{
397 PetscErrorCode ierr;
398 SimCtx *simCtx = NULL;
399 const PicurvWindow *window = NULL;
400 const PicurvWindowStorage *storage = NULL;
401 PetscReal lowest = 1.0, highest = 0.0;
402 PetscReal mean_tke = 0.0;
403 PetscBool has_tke = PETSC_FALSE;
404 PetscInt derived_count = 0;
405 char path[PETSC_MAX_PATH_LEN];
406
407 PetscFunctionBeginUser;
409 PetscCheck(user != NULL && output_prefix != NULL, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL,
410 "Context and output prefix are required.");
411 simCtx = user->simCtx;
412 PetscCheck(FieldStatisticsIsActive(simCtx) && user->fieldStatisticsStorage != NULL,
413 PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE,
414 "No accumulated window state exists to summarize.");
415 window = &simCtx->fieldStatisticsWindows[window_index];
416 storage = &user->fieldStatisticsStorage[window_index];
417
418 ierr = PicurvWindowValidFractionRange(user, &window->definition, storage,
419 window->sample_count, &lowest, &highest); CHKERRQ(ierr);
420
421 /* A single domain number is what makes the row plottable against step. It is
422 * produced by the same derivation the field output uses, so the scalar and the
423 * field can never disagree about what the window holds. */
424 ierr = PicurvWindowDerivedCount(&window->definition, storage, "tke", &derived_count); CHKERRQ(ierr);
425 if (derived_count > 0) {
426 PicurvDerivedField derived;
427
428 ierr = PicurvWindowDerive(user, &window->definition, storage, "tke", 0,
429 user->PostScalar, user->PostVector, &derived); CHKERRQ(ierr);
430 /* Averaged over the fluid cells the window actually sampled. A whole-vector
431 * mean would divide by boundary and dummy entries the derivation never
432 * writes, scaling the answer down by the fraction it never covered. */
433 ierr = PicurvWindowSpatialMean(user, &window->definition, storage,
434 user->PostScalar, &mean_tke); CHKERRQ(ierr);
435 has_tke = PETSC_TRUE;
436 }
437
438 /* The window's clock is solver time. A dimensionalized summary reports its derived
439 * statistics physically, so the times beside them are reported in seconds too; a
440 * time-weighted total weight is a time, a sample-weighted one is a count. */
441 PetscReal time_scale = 1.0;
442 if (simCtx->pps && simCtx->pps->dimensionalize) {
443 const FieldDimension time_dimension = FIELD_DIM_TIME;
444
445 ierr = FieldDimensionReferenceScale(&simCtx->scaling, time_dimension, &time_scale); CHKERRQ(ierr);
446 }
447 const PetscReal weight_scale =
448 (window->definition.weighting == PICURV_WEIGHTING_PHYSICAL_TIME) ? time_scale : 1.0;
449
450 if (simCtx->rank == 0) {
451 FILE *csv = NULL;
452 PetscBool exists = PETSC_FALSE;
453
454 ierr = PetscSNPrintf(path, sizeof(path), "%s_statistics_%s.csv",
455 output_prefix, window->definition.name); CHKERRQ(ierr);
456 ierr = PetscTestFile(path, 'r', &exists); CHKERRQ(ierr);
457 csv = fopen(path, exists ? "a" : "w");
458 PetscCheck(csv != NULL, PETSC_COMM_SELF, PETSC_ERR_FILE_OPEN,
459 "Unable to open statistics summary '%s'.", path);
460 if (!exists) {
461 fprintf(csv, "step,state,samples,total_weight,represented_time,"
462 "valid_fraction_min,valid_fraction_max,mean_tke\n");
463 }
464 fprintf(csv, "%" PetscInt_FMT ",%s,%" PetscInt_FMT ",%.10e,%.10e,%.6f,%.6f,",
465 ti, PicurvWindowStateName(window->state), window->sample_count,
466 (double)(window->total_weight * weight_scale),
467 (double)(window->represented_time * time_scale),
468 (double)lowest, (double)highest);
469 if (has_tke) fprintf(csv, "%.10e\n", (double)mean_tke);
470 else fprintf(csv, "\n");
471 PetscCheck(fclose(csv) == 0, PETSC_COMM_SELF, PETSC_ERR_FILE_WRITE,
472 "Unable to close statistics summary '%s'.", path);
473 }
474 LOG_ALLOW(GLOBAL, LOG_DEBUG, "-> KERNEL: Summarized window '%s' at step %" PetscInt_FMT ".\n",
475 window->definition.name, ti);
477 PetscFunctionReturn(0);
478}
PetscErrorCode FieldDimensionReferenceScale(const ScalingCtx *scaling, FieldDimension dimension, PetscReal *scale)
Return the factor that turns a solver value of one dimension into physical units.
#define FIELD_DIM_TIME
Physical dimension as exponents of the reference length, velocity, and density.
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 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.
PetscInt sample_count
PicurvWindowState state
PetscReal total_weight
const char * PicurvWindowStateName(PicurvWindowState state)
Returns a stable human-readable name for a window state.
PicurvWindowDefinition definition
PetscBool FieldStatisticsIsActive(const struct SimCtx *simCtx)
Reports whether this run has live field-statistics state.
@ PICURV_WEIGHTING_PHYSICAL_TIME
Weight is the represented interval.
PetscReal represented_time
Physical time the window covers.
Runtime state of one window.
struct PicurvWindow * fieldStatisticsWindows
Definition variables.h:990
ScalingCtx scaling
Definition variables.h:1003
struct PicurvWindowStorage * fieldStatisticsStorage
Definition variables.h:1222
Here is the call graph for this function:
Here is the caller graph for this function: