xref: /honee/src/spanstats/turbulence.c (revision 9018c49aeac90a17270a47871327cf384358a98c)
1 // SPDX-FileCopyrightText: Copyright (c) 2017-2024, HONEE contributors.
2 // SPDX-License-Identifier: Apache-2.0 OR BSD-2-Clause
3 /// @file
4 /// Functions for setting up and performing spanwise-statistics collection of turbulence quantities
5 
6 #include "../../qfunctions/spanstats/turbulence.h"
7 
8 #include <ceed.h>
9 #include <petscdmplex.h>
10 #include <petscsf.h>
11 #include <spanstats.h>
12 
13 #include <navierstokes.h>
14 #include <petsc_ops.h>
15 
16 // @brief Create CeedOperator for statistics collection
17 static PetscErrorCode CreateStatisticCollectionOperator(Honee honee, SpanStatsCtx spanstats, SpanStatsSetupData stats_data, ProblemData problem) {
18   Ceed                        ceed           = honee->ceed;
19   CeedInt                     num_comp_stats = spanstats->num_comp_stats, q_data_size;
20   PetscInt                    num_comp_q, num_comp_x;
21   Turbulence_SpanStatsContext collect_ctx;
22   NewtonianIdealGasContext    newtonian_ig_ctx;
23   CeedQFunctionContext        collect_qfctx;
24   CeedQFunction               qf_stats_collect;
25   CeedOperator                op_stats_collect;
26   CeedVector                  q_data;
27   CeedElemRestriction         elem_restr_qd, elem_restr_q;
28   CeedBasis                   basis_q;
29 
30   PetscFunctionBeginUser;
31   PetscCall(DMGetCoordinateNumComps(honee->dm, &num_comp_x));
32   PetscCall(DMGetFieldNumComps(honee->dm, 0, &num_comp_q));
33 
34   // Create Operator for statistics collection
35   switch (honee->phys->state_var) {
36     case STATEVAR_PRIMITIVE:
37       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, ChildStatsCollection_Prim, ChildStatsCollection_Prim_loc, &qf_stats_collect));
38       break;
39     case STATEVAR_CONSERVATIVE:
40       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, ChildStatsCollection_Conserv, ChildStatsCollection_Conserv_loc, &qf_stats_collect));
41       break;
42     case STATEVAR_ENTROPY:
43       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, ChildStatsCollection_Entropy, ChildStatsCollection_Entropy_loc, &qf_stats_collect));
44       break;
45   }
46 
47   if (spanstats->do_mms_test) {
48     PetscCallCeed(ceed, CeedQFunctionDestroy(&qf_stats_collect));
49     PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, ChildStatsCollectionMMSTest, ChildStatsCollectionMMSTest_loc, &qf_stats_collect));
50   }
51 
52   PetscCall(DMPlexCeedElemRestrictionCreate(ceed, honee->dm, DMLABEL_DEFAULT, DMLABEL_DEFAULT_VALUE, 0, 0, &elem_restr_q));
53   PetscCall(DMPlexCeedBasisCreate(ceed, honee->dm, DMLABEL_DEFAULT, DMLABEL_DEFAULT_VALUE, 0, 0, &basis_q));
54   PetscCall(QDataGet(ceed, honee->dm, DMLABEL_DEFAULT, DMLABEL_DEFAULT_VALUE, &elem_restr_qd, &q_data, &q_data_size));
55 
56   {  // Setup Collection Context
57     PetscCall(PetscNew(&collect_ctx));
58     PetscCallCeed(ceed, CeedQFunctionContextGetData(problem->apply_vol_rhs.qfctx, CEED_MEM_HOST, &newtonian_ig_ctx));
59     collect_ctx->newt_ctx = *newtonian_ig_ctx;
60 
61     PetscCallCeed(ceed, CeedQFunctionContextCreate(honee->ceed, &collect_qfctx));
62     PetscCallCeed(ceed, CeedQFunctionContextSetData(collect_qfctx, CEED_MEM_HOST, CEED_USE_POINTER, sizeof(*collect_ctx), collect_ctx));
63     PetscCallCeed(ceed, CeedQFunctionContextSetDataDestroy(collect_qfctx, CEED_MEM_HOST, FreeContextPetsc));
64 
65     PetscCallCeed(ceed, CeedQFunctionContextRegisterDouble(collect_qfctx, "solution time",
66                                                            offsetof(struct Turbulence_SpanStatsContext_, solution_time), 1, "Current solution time"));
67     PetscCallCeed(ceed,
68                   CeedQFunctionContextRegisterDouble(collect_qfctx, "previous time", offsetof(struct Turbulence_SpanStatsContext_, previous_time), 1,
69                                                      "Previous time statistics collection was done"));
70 
71     PetscCallCeed(ceed, CeedQFunctionContextRestoreData(problem->apply_vol_rhs.qfctx, &newtonian_ig_ctx));
72   }
73 
74   PetscCallCeed(ceed, CeedQFunctionSetContext(qf_stats_collect, collect_qfctx));
75   PetscCallCeed(ceed, CeedQFunctionContextDestroy(&collect_qfctx));
76   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_stats_collect, "q", num_comp_q, CEED_EVAL_INTERP));
77   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_stats_collect, "q_data", q_data_size, CEED_EVAL_NONE));
78   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_stats_collect, "x", num_comp_x, CEED_EVAL_INTERP));
79   PetscCallCeed(ceed, CeedQFunctionAddOutput(qf_stats_collect, "v", num_comp_stats, CEED_EVAL_NONE));
80 
81   PetscCallCeed(ceed, CeedOperatorCreate(ceed, qf_stats_collect, NULL, NULL, &op_stats_collect));
82   PetscCallCeed(ceed, CeedOperatorSetField(op_stats_collect, "q", elem_restr_q, basis_q, CEED_VECTOR_ACTIVE));
83   PetscCallCeed(ceed, CeedOperatorSetField(op_stats_collect, "q_data", elem_restr_qd, CEED_BASIS_NONE, q_data));
84   PetscCallCeed(ceed, CeedOperatorSetField(op_stats_collect, "x", honee->elem_restr_x, honee->basis_x, honee->x_coord));
85   PetscCallCeed(ceed, CeedOperatorSetField(op_stats_collect, "v", stats_data->elem_restr_child_colloc, CEED_BASIS_NONE, CEED_VECTOR_ACTIVE));
86 
87   PetscCallCeed(ceed, CeedOperatorGetContextFieldLabel(op_stats_collect, "solution time", &spanstats->solution_time_label));
88   PetscCallCeed(ceed, CeedOperatorGetContextFieldLabel(op_stats_collect, "previous time", &spanstats->previous_time_label));
89 
90   PetscCall(OperatorApplyContextCreate(honee->dm, spanstats->dm, honee->ceed, op_stats_collect, honee->q_ceed, NULL, NULL, NULL,
91                                        &spanstats->op_stats_collect_ctx));
92 
93   PetscCall(CeedOperatorCreateLocalVecs(op_stats_collect, DMReturnVecType(spanstats->dm), PETSC_COMM_SELF, NULL, &spanstats->Child_Stats_loc));
94   PetscCall(VecZeroEntries(spanstats->Child_Stats_loc));
95 
96   PetscCallCeed(ceed, CeedVectorDestroy(&q_data));
97   PetscCallCeed(ceed, CeedElemRestrictionDestroy(&elem_restr_qd));
98   PetscCallCeed(ceed, CeedElemRestrictionDestroy(&elem_restr_q));
99   PetscCallCeed(ceed, CeedBasisDestroy(&basis_q));
100   PetscCallCeed(ceed, CeedQFunctionDestroy(&qf_stats_collect));
101   PetscCallCeed(ceed, CeedOperatorDestroy(&op_stats_collect));
102   PetscFunctionReturn(PETSC_SUCCESS);
103 }
104 
105 // @brief Creates operator for calculating error of method of manufactured solution (MMS) test
106 static PetscErrorCode SetupMMSErrorChecking(Honee honee, SpanStatsCtx spanstats, SpanStatsSetupData stats_data) {
107   Ceed                ceed           = honee->ceed;
108   CeedInt             num_comp_stats = spanstats->num_comp_stats, num_comp_x, q_data_size;
109   CeedQFunction       qf_error;
110   CeedOperator        op_error;
111   CeedVector          x_ceed, y_ceed;
112   CeedVector          q_data;
113   CeedElemRestriction elem_restr_parent_qd;
114 
115   PetscFunctionBeginUser;
116   PetscCall(QDataGet(ceed, spanstats->dm, DMLABEL_DEFAULT, DMLABEL_DEFAULT_VALUE, &elem_restr_parent_qd, &q_data, &q_data_size));
117   PetscCallCeed(ceed, CeedBasisGetNumComponents(stats_data->basis_x, &num_comp_x));
118 
119   PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, ChildStatsCollectionMMSTest_Error, ChildStatsCollectionMMSTest_Error_loc, &qf_error));
120   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_error, "q", num_comp_stats, CEED_EVAL_INTERP));
121   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_error, "qdata", q_data_size, CEED_EVAL_NONE));
122   PetscCallCeed(ceed, CeedQFunctionAddInput(qf_error, "x", num_comp_x, CEED_EVAL_INTERP));
123   PetscCallCeed(ceed, CeedQFunctionAddOutput(qf_error, "v", num_comp_stats, CEED_EVAL_INTERP));
124 
125   PetscCallCeed(ceed, CeedOperatorCreate(ceed, qf_error, NULL, NULL, &op_error));
126   PetscCallCeed(ceed, CeedOperatorSetField(op_error, "q", stats_data->elem_restr_parent_stats, stats_data->basis_stats, CEED_VECTOR_ACTIVE));
127   PetscCallCeed(ceed, CeedOperatorSetField(op_error, "qdata", elem_restr_parent_qd, CEED_BASIS_NONE, q_data));
128   PetscCallCeed(ceed, CeedOperatorSetField(op_error, "x", stats_data->elem_restr_parent_x, stats_data->basis_x, stats_data->x_coord));
129   PetscCallCeed(ceed, CeedOperatorSetField(op_error, "v", stats_data->elem_restr_parent_stats, stats_data->basis_stats, CEED_VECTOR_ACTIVE));
130 
131   PetscCallCeed(ceed, CeedElemRestrictionCreateVector(stats_data->elem_restr_parent_stats, &x_ceed, NULL));
132   PetscCallCeed(ceed, CeedElemRestrictionCreateVector(stats_data->elem_restr_parent_stats, &y_ceed, NULL));
133   PetscCall(OperatorApplyContextCreate(spanstats->dm, spanstats->dm, honee->ceed, op_error, x_ceed, y_ceed, NULL, NULL, &spanstats->mms_error_ctx));
134 
135   PetscCallCeed(ceed, CeedVectorDestroy(&q_data));
136   PetscCallCeed(ceed, CeedVectorDestroy(&x_ceed));
137   PetscCallCeed(ceed, CeedVectorDestroy(&y_ceed));
138   PetscCallCeed(ceed, CeedElemRestrictionDestroy(&elem_restr_parent_qd));
139   PetscCallCeed(ceed, CeedQFunctionDestroy(&qf_error));
140   PetscCallCeed(ceed, CeedOperatorDestroy(&op_error));
141   PetscFunctionReturn(PETSC_SUCCESS);
142 }
143 
144 // @brief Setup for statistics collection for turbulence quantities
145 PetscErrorCode SpanwiseStatisticsSetup_Turbulence(TS ts, PetscViewerAndFormat *ctx) {
146   Honee              honee;
147   SpanStatsSetupData stats_setup_data;
148   SpanStatsCtx       spanstats;
149   const char        *prefix = "ts_monitor_spanstats_turbulence_";
150   PetscBool          is_ascii;
151 
152   PetscFunctionBeginUser;
153   PetscCall(TSGetApplicationContext(ts, &honee));
154   PetscCall(PetscObjectTypeCompare((PetscObject)ctx->viewer, PETSCVIEWERASCII, &is_ascii));
155   PetscCheck(!is_ascii || honee->app_ctx->test_type != TESTTYPE_NONE, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP,
156              "Turbulence spanwise statistics does not support ASCII viewers");
157 
158   PetscCall(SpanwiseStatisticsSetupInitialize(honee, honee->app_ctx->degree, TURB_NUM_COMPONENTS, prefix, &stats_setup_data, &spanstats));
159 
160   {  // Create Section for data
161     PetscSection section;
162 
163     PetscCall(DMGetLocalSection(spanstats->dm, &section));
164     PetscCall(PetscSectionSetFieldName(section, 0, ""));
165     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_DENSITY, "MeanDensity"));
166     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_PRESSURE, "MeanPressure"));
167     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_PRESSURE_SQUARED, "MeanPressureSquared"));
168     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_PRESSURE_VELOCITY_X, "MeanPressureVelocityX"));
169     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_PRESSURE_VELOCITY_Y, "MeanPressureVelocityY"));
170     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_PRESSURE_VELOCITY_Z, "MeanPressureVelocityZ"));
171     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_DENSITY_TEMPERATURE, "MeanDensityTemperature"));
172     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_DENSITY_TEMPERATURE_FLUX_X, "MeanDensityTemperatureFluxX"));
173     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_DENSITY_TEMPERATURE_FLUX_Y, "MeanDensityTemperatureFluxY"));
174     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_DENSITY_TEMPERATURE_FLUX_Z, "MeanDensityTemperatureFluxZ"));
175     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUM_X, "MeanMomentumX"));
176     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUM_Y, "MeanMomentumY"));
177     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUM_Z, "MeanMomentumZ"));
178     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_XX, "MeanMomentumFluxXX"));
179     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_YY, "MeanMomentumFluxYY"));
180     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_ZZ, "MeanMomentumFluxZZ"));
181     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_YZ, "MeanMomentumFluxYZ"));
182     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_XZ, "MeanMomentumFluxXZ"));
183     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_MOMENTUMFLUX_XY, "MeanMomentumFluxXY"));
184     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_VELOCITY_X, "MeanVelocityX"));
185     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_VELOCITY_Y, "MeanVelocityY"));
186     PetscCall(PetscSectionSetComponentName(section, 0, TURB_MEAN_VELOCITY_Z, "MeanVelocityZ"));
187   }
188 
189   // Create CeedOperators for statistics collection
190   PetscCall(CreateStatisticCollectionOperator(honee, spanstats, stats_setup_data, honee->problem_data));
191 
192   PetscCall(PetscOptionsGetBool(NULL, NULL, "-ts_monitor_spanstats_turbulence_mms", &spanstats->do_mms_test, NULL));
193   if (spanstats->do_mms_test) {
194     PetscCall(SetupMMSErrorChecking(honee, spanstats, stats_setup_data));
195   }
196 
197   ctx->data         = spanstats;
198   ctx->data_destroy = (PetscCtxDestroyFn *)SpanStatsCtxDestroy;
199 
200   PetscCall(SpanwiseStatisticsSetupFinalize(ts, honee, spanstats, ctx, &stats_setup_data));
201   PetscFunctionReturn(PETSC_SUCCESS);
202 }
203 
204 // @brief TSMonitor for collection and processing of turbulence statistics
205 PetscErrorCode TSMonitor_SpanwiseStatisticsTurbulence(TS ts, PetscInt steps, PetscReal solution_time, Vec Q, PetscViewerAndFormat *ctx) {
206   Honee             honee;
207   Vec               stats;
208   TSConvergedReason reason;
209   SpanStatsCtx      spanstats        = ctx->data;
210   PetscInt          collect_interval = spanstats->collect_interval, viewer_interval = ctx->view_interval;
211 
212   PetscFunctionBeginUser;
213   PetscCall(TSGetApplicationContext(ts, &honee));
214   PetscCall(TSGetConvergedReason(ts, &reason));
215   // Do not collect or process on the first step of the run (ie. on the initial condition)
216   if (steps == honee->app_ctx->cont_steps) PetscFunctionReturn(PETSC_SUCCESS);
217 
218   PetscBool run_processing_and_viewer = (steps % viewer_interval == 0 && viewer_interval != -1) || reason != TS_CONVERGED_ITERATING;
219 
220   if (steps % collect_interval == 0 || run_processing_and_viewer) {
221     PetscCall(SpanwiseStatisticsCollect(honee, spanstats, solution_time, Q));
222 
223     if (run_processing_and_viewer) {
224       PetscCall(DMSetOutputSequenceNumber(spanstats->dm, steps, solution_time));
225       PetscCall(DMGetGlobalVector(spanstats->dm, &stats));
226       PetscCall(SpanwiseStatisticsProcess(honee, spanstats, stats));
227       if (honee->app_ctx->test_type == TESTTYPE_NONE) {
228         PetscCall(PetscViewerPushFormat(ctx->viewer, ctx->format));
229         PetscCall(VecView(stats, ctx->viewer));
230         PetscCall(PetscViewerPopFormat(ctx->viewer));
231         {
232           PetscInt    tab_level;
233           PetscViewer viewer = PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));
234           CeedScalar  second = honee->units->second;
235           const char *filename;
236 
237           PetscCall(PetscViewerFileGetName(ctx->viewer, &filename));
238           PetscCall(PetscObjectGetTabLevel((PetscObject)ts, &tab_level));
239           PetscCall(PetscViewerASCIIAddTab(viewer, tab_level + 1));
240           if (filename) {
241             PetscCall(PetscViewerASCIIPrintf(viewer,
242                                              "Spanwise turbulent statistics written to %s for time span (%0.12e,%0.12e] and step span [%" PetscInt_FMT
243                                              ",%" PetscInt_FMT "]\n",
244                                              filename, spanstats->initial_solution_time / second, solution_time / second,
245                                              spanstats->initial_solution_step, steps));
246           } else {
247             PetscCall(PetscViewerASCIIPrintf(
248                 viewer, "Spanwise statistics (%s) file written for time span (%0.12e,%0.12e] and step span [%" PetscInt_FMT ",%" PetscInt_FMT "]\n",
249                 spanstats->prefix, spanstats->initial_solution_time / second, solution_time / second, spanstats->initial_solution_step, steps));
250           }
251           PetscCall(PetscViewerASCIISubtractTab(viewer, tab_level + 1));
252         }
253       }
254       if (honee->app_ctx->test_type == TESTTYPE_TURB_SPANSTATS && reason != TS_CONVERGED_ITERATING) {
255         PetscCall(RegressionTest(honee->app_ctx, stats));
256       }
257       if (spanstats->do_mms_test && reason != TS_CONVERGED_ITERATING) {
258         Vec error;
259         PetscCall(VecDuplicate(stats, &error));
260         PetscCall(ApplyCeedOperatorGlobalToGlobal(stats, error, spanstats->mms_error_ctx));
261         PetscScalar error_sq = 0;
262         PetscCall(VecSum(error, &error_sq));
263         PetscScalar l2_error = sqrt(error_sq);
264         PetscCall(PetscPrintf(PETSC_COMM_WORLD, "l2 error: %.5e\n", l2_error));
265       }
266       PetscCall(DMRestoreGlobalVector(spanstats->dm, &stats));
267     }
268   }
269   PetscFunctionReturn(PETSC_SUCCESS);
270 }
271