xref: /honee/src/misc.c (revision a7dac1d5ea2c290013c59d7aded6988900433c47)
1727da7e7SJeremy L Thompson // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2727da7e7SJeremy L Thompson // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3a515125bSLeila Ghaffari //
4727da7e7SJeremy L Thompson // SPDX-License-Identifier: BSD-2-Clause
5a515125bSLeila Ghaffari //
6727da7e7SJeremy L Thompson // This file is part of CEED:  http://github.com/ceed
7a515125bSLeila Ghaffari 
8a515125bSLeila Ghaffari /// @file
9a515125bSLeila Ghaffari /// Miscellaneous utility functions
10a515125bSLeila Ghaffari 
11e419654dSJeremy L Thompson #include <ceed.h>
12e419654dSJeremy L Thompson #include <petscdm.h>
13926a6279SJames Wright #include <petscsf.h>
14e419654dSJeremy L Thompson #include <petscts.h>
15e419654dSJeremy L Thompson 
16a515125bSLeila Ghaffari #include "../navierstokes.h"
179f59f36eSJames Wright #include "../qfunctions/mass.h"
18a515125bSLeila Ghaffari 
192b916ea7SJeremy L Thompson PetscErrorCode ICs_FixMultiplicity(DM dm, CeedData ceed_data, User user, Vec Q_loc, Vec Q, CeedScalar time) {
20b4c37c5cSJames Wright   Ceed         ceed = user->ceed;
21b2948607SJames Wright   CeedVector   mult_vec;
22b2948607SJames Wright   PetscMemType m_mem_type;
23b2948607SJames Wright   Vec          Multiplicity, Multiplicity_loc;
24b2948607SJames Wright 
25a515125bSLeila Ghaffari   PetscFunctionBeginUser;
26b4c37c5cSJames Wright   if (user->phys->ics_time_label) PetscCallCeed(ceed, CeedOperatorSetContextDouble(ceed_data->op_ics_ctx->op, user->phys->ics_time_label, &time));
278f18bb8bSJames Wright   PetscCall(ApplyCeedOperatorLocalToGlobal(NULL, Q, ceed_data->op_ics_ctx));
28a515125bSLeila Ghaffari 
29b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedElemRestrictionCreateVector(ceed_data->elem_restr_q, &mult_vec, NULL));
30a515125bSLeila Ghaffari 
31a515125bSLeila Ghaffari   // -- Get multiplicity
32b2948607SJames Wright   PetscCall(DMGetLocalVector(dm, &Multiplicity_loc));
33*a7dac1d5SJames Wright   PetscCall(VecPetscToCeed(Multiplicity_loc, &m_mem_type, mult_vec));
34b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedElemRestrictionGetMultiplicity(ceed_data->elem_restr_q, mult_vec));
35*a7dac1d5SJames Wright   PetscCall(VecCeedToPetsc(mult_vec, m_mem_type, Multiplicity_loc));
36a515125bSLeila Ghaffari 
37b2948607SJames Wright   PetscCall(DMGetGlobalVector(dm, &Multiplicity));
38b2948607SJames Wright   PetscCall(VecZeroEntries(Multiplicity));
39b2948607SJames Wright   PetscCall(DMLocalToGlobal(dm, Multiplicity_loc, ADD_VALUES, Multiplicity));
40a515125bSLeila Ghaffari 
41a515125bSLeila Ghaffari   // -- Fix multiplicity
42b2948607SJames Wright   PetscCall(VecPointwiseDivide(Q, Q, Multiplicity));
43b2948607SJames Wright   PetscCall(VecPointwiseDivide(Q_loc, Q_loc, Multiplicity_loc));
44a515125bSLeila Ghaffari 
45b2948607SJames Wright   PetscCall(DMRestoreLocalVector(dm, &Multiplicity_loc));
46b2948607SJames Wright   PetscCall(DMRestoreGlobalVector(dm, &Multiplicity));
47b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedVectorDestroy(&mult_vec));
48d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
49a515125bSLeila Ghaffari }
50a515125bSLeila Ghaffari 
51c56e8d5bSJames Wright // Record boundary values from initial condition
52c56e8d5bSJames Wright PetscErrorCode SetBCsFromICs(DM dm, Vec Q, Vec Q_loc) {
53c56e8d5bSJames Wright   Vec Qbc, boundary_mask;
54c56e8d5bSJames Wright 
55c56e8d5bSJames Wright   PetscFunctionBeginUser;
56c56e8d5bSJames Wright   PetscCall(DMGetNamedLocalVector(dm, "Qbc", &Qbc));
57c56e8d5bSJames Wright   PetscCall(VecCopy(Q_loc, Qbc));
58c56e8d5bSJames Wright   PetscCall(VecZeroEntries(Q_loc));
59c56e8d5bSJames Wright   PetscCall(DMGlobalToLocal(dm, Q, INSERT_VALUES, Q_loc));
60c56e8d5bSJames Wright   PetscCall(VecAXPY(Qbc, -1., Q_loc));
61c56e8d5bSJames Wright   PetscCall(DMRestoreNamedLocalVector(dm, "Qbc", &Qbc));
62c56e8d5bSJames Wright   PetscCall(PetscObjectComposeFunction((PetscObject)dm, "DMPlexInsertBoundaryValues_C", DMPlexInsertBoundaryValues_FromICs));
63c56e8d5bSJames Wright 
64c56e8d5bSJames Wright   PetscCall(DMGetNamedLocalVector(dm, "boundary mask", &boundary_mask));
65c56e8d5bSJames Wright   PetscCall(DMGetGlobalVector(dm, &Q));
66c56e8d5bSJames Wright   PetscCall(VecZeroEntries(boundary_mask));
67c56e8d5bSJames Wright   PetscCall(VecSet(Q, 1.0));
68c56e8d5bSJames Wright   PetscCall(DMGlobalToLocal(dm, Q, INSERT_VALUES, boundary_mask));
69c56e8d5bSJames Wright   PetscCall(DMRestoreNamedLocalVector(dm, "boundary mask", &boundary_mask));
70c56e8d5bSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
71c56e8d5bSJames Wright }
72c56e8d5bSJames Wright 
73c56e8d5bSJames Wright PetscErrorCode DMPlexInsertBoundaryValues_FromICs(DM dm, PetscBool insert_essential, Vec Q_loc, PetscReal time, Vec face_geom_FVM, Vec cell_geom_FVM,
742b916ea7SJeremy L Thompson                                                   Vec grad_FVM) {
759d437337SJames Wright   Vec Qbc, boundary_mask;
76a515125bSLeila Ghaffari 
7706f41313SJames Wright   PetscFunctionBeginUser;
782eb7bf1fSJames Wright   // Mask (zero) Strong BC entries
799d437337SJames Wright   PetscCall(DMGetNamedLocalVector(dm, "boundary mask", &boundary_mask));
809d437337SJames Wright   PetscCall(VecPointwiseMult(Q_loc, Q_loc, boundary_mask));
819d437337SJames Wright   PetscCall(DMRestoreNamedLocalVector(dm, "boundary mask", &boundary_mask));
829d437337SJames Wright 
832b916ea7SJeremy L Thompson   PetscCall(DMGetNamedLocalVector(dm, "Qbc", &Qbc));
842b916ea7SJeremy L Thompson   PetscCall(VecAXPY(Q_loc, 1., Qbc));
852b916ea7SJeremy L Thompson   PetscCall(DMRestoreNamedLocalVector(dm, "Qbc", &Qbc));
86d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
87a515125bSLeila Ghaffari }
88a515125bSLeila Ghaffari 
89e7754af5SKenneth E. Jansen // @brief Load vector from binary file, possibly with embedded solution time and step number
90e7754af5SKenneth E. Jansen PetscErrorCode LoadFluidsBinaryVec(MPI_Comm comm, PetscViewer viewer, Vec Q, PetscReal *time, PetscInt *step_number) {
91e1233009SJames Wright   PetscInt   file_step_number;
92e1233009SJames Wright   PetscInt32 token;
93e7754af5SKenneth E. Jansen   PetscReal  file_time;
94e7754af5SKenneth E. Jansen 
9506f41313SJames Wright   PetscFunctionBeginUser;
96e1233009SJames Wright   PetscCall(PetscViewerBinaryRead(viewer, &token, 1, NULL, PETSC_INT32));
97e1233009SJames Wright   if (token == FLUIDS_FILE_TOKEN_32 || token == FLUIDS_FILE_TOKEN_64 ||
98e1233009SJames Wright       token == FLUIDS_FILE_TOKEN) {  // New style format; we're reading a file with step number and time in the header
99e7754af5SKenneth E. Jansen     PetscCall(PetscViewerBinaryRead(viewer, &file_step_number, 1, NULL, PETSC_INT));
100e7754af5SKenneth E. Jansen     PetscCall(PetscViewerBinaryRead(viewer, &file_time, 1, NULL, PETSC_REAL));
101e7754af5SKenneth E. Jansen     if (time) *time = file_time;
102e7754af5SKenneth E. Jansen     if (step_number) *step_number = file_step_number;
103e7754af5SKenneth E. Jansen   } else if (token == VEC_FILE_CLASSID) {  // Legacy format of just the vector, encoded as [VEC_FILE_CLASSID, length, ]
104e7754af5SKenneth E. Jansen     PetscInt length, N;
105e7754af5SKenneth E. Jansen     PetscCall(PetscViewerBinaryRead(viewer, &length, 1, NULL, PETSC_INT));
106e7754af5SKenneth E. Jansen     PetscCall(VecGetSize(Q, &N));
107e7754af5SKenneth E. Jansen     PetscCheck(length == N, comm, PETSC_ERR_ARG_INCOMP, "File Vec has length %" PetscInt_FMT " but DM has global Vec size %" PetscInt_FMT, length, N);
108e7754af5SKenneth E. Jansen     PetscCall(PetscViewerBinarySetSkipHeader(viewer, PETSC_TRUE));
109e7754af5SKenneth E. Jansen   } else SETERRQ(comm, PETSC_ERR_FILE_UNEXPECTED, "Not a fluids header token or a PETSc Vec in file");
110e7754af5SKenneth E. Jansen 
111e7754af5SKenneth E. Jansen   PetscCall(VecLoad(Q, viewer));
112d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
113e7754af5SKenneth E. Jansen }
114e7754af5SKenneth E. Jansen 
115a515125bSLeila Ghaffari // Compare reference solution values with current test run for CI
116c56e8d5bSJames Wright PetscErrorCode RegressionTest(AppCtx app_ctx, Vec Q) {
117a515125bSLeila Ghaffari   Vec         Qref;
118a515125bSLeila Ghaffari   PetscViewer viewer;
119a515125bSLeila Ghaffari   PetscReal   error, Qrefnorm;
120e7754af5SKenneth E. Jansen   MPI_Comm    comm = PetscObjectComm((PetscObject)Q);
121a515125bSLeila Ghaffari 
12206f41313SJames Wright   PetscFunctionBeginUser;
123a515125bSLeila Ghaffari   // Read reference file
1242b916ea7SJeremy L Thompson   PetscCall(VecDuplicate(Q, &Qref));
125e7754af5SKenneth E. Jansen   PetscCall(PetscViewerBinaryOpen(comm, app_ctx->test_file_path, FILE_MODE_READ, &viewer));
126e7754af5SKenneth E. Jansen   PetscCall(LoadFluidsBinaryVec(comm, viewer, Qref, NULL, NULL));
127a515125bSLeila Ghaffari 
128a515125bSLeila Ghaffari   // Compute error with respect to reference solution
1292b916ea7SJeremy L Thompson   PetscCall(VecAXPY(Q, -1.0, Qref));
1302b916ea7SJeremy L Thompson   PetscCall(VecNorm(Qref, NORM_MAX, &Qrefnorm));
1312b916ea7SJeremy L Thompson   PetscCall(VecScale(Q, 1. / Qrefnorm));
1322b916ea7SJeremy L Thompson   PetscCall(VecNorm(Q, NORM_MAX, &error));
133a515125bSLeila Ghaffari 
134a515125bSLeila Ghaffari   // Check error
135a515125bSLeila Ghaffari   if (error > app_ctx->test_tol) {
1362b916ea7SJeremy L Thompson     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Test failed with error norm %g\n", (double)error));
137a515125bSLeila Ghaffari   }
138a515125bSLeila Ghaffari 
139a515125bSLeila Ghaffari   // Cleanup
1402b916ea7SJeremy L Thompson   PetscCall(PetscViewerDestroy(&viewer));
1412b916ea7SJeremy L Thompson   PetscCall(VecDestroy(&Qref));
142d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
143a515125bSLeila Ghaffari }
144a515125bSLeila Ghaffari 
145a515125bSLeila Ghaffari // Get error for problems with exact solutions
146c56e8d5bSJames Wright PetscErrorCode PrintError(CeedData ceed_data, DM dm, User user, Vec Q, PetscScalar final_time) {
147a515125bSLeila Ghaffari   PetscInt  loc_nodes;
148a515125bSLeila Ghaffari   Vec       Q_exact, Q_exact_loc;
149a515125bSLeila Ghaffari   PetscReal rel_error, norm_error, norm_exact;
150a515125bSLeila Ghaffari 
15106f41313SJames Wright   PetscFunctionBeginUser;
152a515125bSLeila Ghaffari   // Get exact solution at final time
153b2948607SJames Wright   PetscCall(DMGetGlobalVector(dm, &Q_exact));
1542b916ea7SJeremy L Thompson   PetscCall(DMGetLocalVector(dm, &Q_exact_loc));
1552b916ea7SJeremy L Thompson   PetscCall(VecGetSize(Q_exact_loc, &loc_nodes));
1562b916ea7SJeremy L Thompson   PetscCall(ICs_FixMultiplicity(dm, ceed_data, user, Q_exact_loc, Q_exact, final_time));
157a515125bSLeila Ghaffari 
158a515125bSLeila Ghaffari   // Get |exact solution - obtained solution|
1592b916ea7SJeremy L Thompson   PetscCall(VecNorm(Q_exact, NORM_1, &norm_exact));
1602b916ea7SJeremy L Thompson   PetscCall(VecAXPY(Q, -1.0, Q_exact));
1612b916ea7SJeremy L Thompson   PetscCall(VecNorm(Q, NORM_1, &norm_error));
162a515125bSLeila Ghaffari 
163a515125bSLeila Ghaffari   rel_error = norm_error / norm_exact;
1642b916ea7SJeremy L Thompson   PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Relative Error: %g\n", (double)rel_error));
1652b916ea7SJeremy L Thompson   PetscCall(DMRestoreLocalVector(dm, &Q_exact_loc));
166b2948607SJames Wright   PetscCall(DMRestoreGlobalVector(dm, &Q_exact));
167d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
168a515125bSLeila Ghaffari }
169a515125bSLeila Ghaffari 
170a515125bSLeila Ghaffari // Post-processing
171c56e8d5bSJames Wright PetscErrorCode PostProcess(TS ts, CeedData ceed_data, DM dm, ProblemData *problem, User user, Vec Q, PetscScalar final_time) {
172a515125bSLeila Ghaffari   PetscInt          steps;
173f0784ed3SJed Brown   TSConvergedReason reason;
174a515125bSLeila Ghaffari 
17506f41313SJames Wright   PetscFunctionBeginUser;
176a515125bSLeila Ghaffari   // Print relative error
1770e1e9333SJames Wright   if (problem->non_zero_time && user->app_ctx->test_type == TESTTYPE_NONE) {
178c56e8d5bSJames Wright     PetscCall(PrintError(ceed_data, dm, user, Q, final_time));
179a515125bSLeila Ghaffari   }
180a515125bSLeila Ghaffari 
181a515125bSLeila Ghaffari   // Print final time and number of steps
1822b916ea7SJeremy L Thompson   PetscCall(TSGetStepNumber(ts, &steps));
183f0784ed3SJed Brown   PetscCall(TSGetConvergedReason(ts, &reason));
1840e1e9333SJames Wright   if (user->app_ctx->test_type == TESTTYPE_NONE) {
185f0784ed3SJed Brown     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Time integrator %s on time step %" PetscInt_FMT " with final time %g\n", TSConvergedReasons[reason],
186f0784ed3SJed Brown                           steps, (double)final_time));
187a515125bSLeila Ghaffari   }
188a515125bSLeila Ghaffari 
189a515125bSLeila Ghaffari   // Output numerical values from command line
1902b916ea7SJeremy L Thompson   PetscCall(VecViewFromOptions(Q, NULL, "-vec_view"));
191a515125bSLeila Ghaffari 
192a515125bSLeila Ghaffari   // Compare reference solution values with current test run for CI
1930e1e9333SJames Wright   if (user->app_ctx->test_type == TESTTYPE_SOLVER) {
194c56e8d5bSJames Wright     PetscCall(RegressionTest(user->app_ctx, Q));
195a515125bSLeila Ghaffari   }
196d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
197a515125bSLeila Ghaffari }
198a515125bSLeila Ghaffari 
199e1233009SJames Wright const PetscInt32 FLUIDS_FILE_TOKEN    = 0xceedf00;  // for backwards compatibility
200e1233009SJames Wright const PetscInt32 FLUIDS_FILE_TOKEN_32 = 0xceedf32;
201e1233009SJames Wright const PetscInt32 FLUIDS_FILE_TOKEN_64 = 0xceedf64;
2029293eaa1SJed Brown 
203a515125bSLeila Ghaffari // Gather initial Q values in case of continuation of simulation
204a515125bSLeila Ghaffari PetscErrorCode SetupICsFromBinary(MPI_Comm comm, AppCtx app_ctx, Vec Q) {
205a515125bSLeila Ghaffari   PetscViewer viewer;
2062b916ea7SJeremy L Thompson 
20706f41313SJames Wright   PetscFunctionBeginUser;
2082b916ea7SJeremy L Thompson   PetscCall(PetscViewerBinaryOpen(comm, app_ctx->cont_file, FILE_MODE_READ, &viewer));
209e7754af5SKenneth E. Jansen   PetscCall(LoadFluidsBinaryVec(comm, viewer, Q, &app_ctx->cont_time, &app_ctx->cont_steps));
2102b916ea7SJeremy L Thompson   PetscCall(PetscViewerDestroy(&viewer));
211d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
212a515125bSLeila Ghaffari }
213a515125bSLeila Ghaffari 
21415a3537eSJed Brown // Free a plain data context that was allocated using PETSc; returning libCEED error codes
21515a3537eSJed Brown int FreeContextPetsc(void *data) {
2162b916ea7SJeremy L Thompson   if (PetscFree(data)) return CeedError(NULL, CEED_ERROR_ACCESS, "PetscFree failed");
21715a3537eSJed Brown   return CEED_ERROR_SUCCESS;
21815a3537eSJed Brown }
2199f59f36eSJames Wright 
2209f59f36eSJames Wright // Return mass qfunction specification for number of components N
2219f59f36eSJames Wright PetscErrorCode CreateMassQFunction(Ceed ceed, CeedInt N, CeedInt q_data_size, CeedQFunction *qf) {
2229f59f36eSJames Wright   PetscFunctionBeginUser;
2239f59f36eSJames Wright   switch (N) {
2249f59f36eSJames Wright     case 1:
225b4c37c5cSJames Wright       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, Mass_1, Mass_1_loc, qf));
2269f59f36eSJames Wright       break;
2279f59f36eSJames Wright     case 5:
228b4c37c5cSJames Wright       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, Mass_5, Mass_5_loc, qf));
2299f59f36eSJames Wright       break;
230c38c977aSJames Wright     case 7:
231b4c37c5cSJames Wright       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, Mass_7, Mass_7_loc, qf));
232c38c977aSJames Wright       break;
2339f59f36eSJames Wright     case 9:
234b4c37c5cSJames Wright       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, Mass_9, Mass_9_loc, qf));
2359f59f36eSJames Wright       break;
2369f59f36eSJames Wright     case 22:
237b4c37c5cSJames Wright       PetscCallCeed(ceed, CeedQFunctionCreateInterior(ceed, 1, Mass_22, Mass_22_loc, qf));
2389f59f36eSJames Wright       break;
2399f59f36eSJames Wright     default:
2406f539f71SJames Wright       SETERRQ(PETSC_COMM_WORLD, PETSC_ERR_SUP, "Could not find mass qfunction of size %d", N);
2419f59f36eSJames Wright   }
2429f59f36eSJames Wright 
243b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedQFunctionAddInput(*qf, "u", N, CEED_EVAL_INTERP));
244b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedQFunctionAddInput(*qf, "qdata", q_data_size, CEED_EVAL_NONE));
245b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedQFunctionAddOutput(*qf, "v", N, CEED_EVAL_INTERP));
2463170c09fSJames Wright   PetscCallCeed(ceed, CeedQFunctionSetUserFlopsEstimate(*qf, N));
247d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
2489f59f36eSJames Wright }
249e5e81594SJames Wright 
250457a5831SJames Wright PetscErrorCode NodalProjectionDataDestroy(NodalProjectionData context) {
251457a5831SJames Wright   PetscFunctionBeginUser;
252d949ddfcSJames Wright   if (context == NULL) PetscFunctionReturn(PETSC_SUCCESS);
253457a5831SJames Wright 
254457a5831SJames Wright   PetscCall(DMDestroy(&context->dm));
255457a5831SJames Wright   PetscCall(KSPDestroy(&context->ksp));
256457a5831SJames Wright 
257457a5831SJames Wright   PetscCall(OperatorApplyContextDestroy(context->l2_rhs_ctx));
258457a5831SJames Wright 
259457a5831SJames Wright   PetscCall(PetscFree(context));
260d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
261457a5831SJames Wright }
262457a5831SJames Wright 
263676080b4SJames Wright /*
264676080b4SJames Wright  * @brief Open a PHASTA *.dat file, grabbing dimensions and file pointer
265676080b4SJames Wright  *
266676080b4SJames Wright  * This function opens the file specified by `path` using `PetscFOpen` and passes the file pointer in `fp`.
267676080b4SJames Wright  * It is not closed in this function, thus `fp` must be closed sometime after this function has been called (using `PetscFClose` for example).
268676080b4SJames Wright  *
269676080b4SJames Wright  * Assumes that the first line of the file has the number of rows and columns as the only two entries, separated by a single space.
270676080b4SJames Wright  *
271676080b4SJames Wright  * @param[in]  comm           MPI_Comm for the program
272676080b4SJames Wright  * @param[in]  path           Path to the file
273676080b4SJames Wright  * @param[in]  char_array_len Length of the character array that should contain each line
274676080b4SJames Wright  * @param[out] dims           Dimensions of the file, taken from the first line of the file
275676080b4SJames Wright  * @param[out] fp File        pointer to the opened file
276676080b4SJames Wright  */
27742454adaSJames Wright PetscErrorCode PhastaDatFileOpen(const MPI_Comm comm, const char path[PETSC_MAX_PATH_LEN], const PetscInt char_array_len, PetscInt dims[2],
278676080b4SJames Wright                                  FILE **fp) {
279defe8520SJames Wright   int    ndims;
280676080b4SJames Wright   char   line[char_array_len];
281676080b4SJames Wright   char **array;
282676080b4SJames Wright 
283676080b4SJames Wright   PetscFunctionBeginUser;
284676080b4SJames Wright   PetscCall(PetscFOpen(comm, path, "r", fp));
285676080b4SJames Wright   PetscCall(PetscSynchronizedFGets(comm, *fp, char_array_len, line));
286676080b4SJames Wright   PetscCall(PetscStrToArray(line, ' ', &ndims, &array));
287defe8520SJames Wright   PetscCheck(ndims == 2, comm, PETSC_ERR_FILE_UNEXPECTED, "Found %d dimensions instead of 2 on the first line of %s", ndims, path);
288676080b4SJames Wright 
289676080b4SJames Wright   for (PetscInt i = 0; i < ndims; i++) dims[i] = atoi(array[i]);
290676080b4SJames Wright   PetscCall(PetscStrToArrayDestroy(ndims, array));
291d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
292676080b4SJames Wright }
293676080b4SJames Wright 
294676080b4SJames Wright /*
295676080b4SJames Wright  * @brief Get the number of rows for the PHASTA file at path.
296676080b4SJames Wright  *
297676080b4SJames Wright  * Assumes that the first line of the file has the number of rows and columns as the only two entries, separated by a single space.
298676080b4SJames Wright  *
299676080b4SJames Wright  * @param[in]  comm  MPI_Comm for the program
300676080b4SJames Wright  * @param[in]  path  Path to the file
301676080b4SJames Wright  * @param[out] nrows Number of rows
302676080b4SJames Wright  */
30342454adaSJames Wright PetscErrorCode PhastaDatFileGetNRows(const MPI_Comm comm, const char path[PETSC_MAX_PATH_LEN], PetscInt *nrows) {
304676080b4SJames Wright   const PetscInt char_array_len = 512;
305676080b4SJames Wright   PetscInt       dims[2];
306676080b4SJames Wright   FILE          *fp;
307676080b4SJames Wright 
308676080b4SJames Wright   PetscFunctionBeginUser;
30942454adaSJames Wright   PetscCall(PhastaDatFileOpen(comm, path, char_array_len, dims, &fp));
310676080b4SJames Wright   *nrows = dims[0];
311676080b4SJames Wright   PetscCall(PetscFClose(comm, fp));
312d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
313676080b4SJames Wright }
31462b7942eSJames Wright 
31542454adaSJames Wright PetscErrorCode PhastaDatFileReadToArrayReal(MPI_Comm comm, const char path[PETSC_MAX_PATH_LEN], PetscReal array[]) {
316defe8520SJames Wright   PetscInt       dims[2];
317defe8520SJames Wright   int            ndims;
31862b7942eSJames Wright   FILE          *fp;
31962b7942eSJames Wright   const PetscInt char_array_len = 512;
32062b7942eSJames Wright   char           line[char_array_len];
32162b7942eSJames Wright   char         **row_array;
32262b7942eSJames Wright 
32306f41313SJames Wright   PetscFunctionBeginUser;
32442454adaSJames Wright   PetscCall(PhastaDatFileOpen(comm, path, char_array_len, dims, &fp));
32562b7942eSJames Wright 
32662b7942eSJames Wright   for (PetscInt i = 0; i < dims[0]; i++) {
32762b7942eSJames Wright     PetscCall(PetscSynchronizedFGets(comm, fp, char_array_len, line));
32862b7942eSJames Wright     PetscCall(PetscStrToArray(line, ' ', &ndims, &row_array));
3295d28dccaSJames Wright     PetscCheck(ndims == dims[1], comm, PETSC_ERR_FILE_UNEXPECTED,
330defe8520SJames Wright                "Line %" PetscInt_FMT " of %s does not contain enough columns (%d instead of %" PetscInt_FMT ")", i, path, ndims, dims[1]);
33162b7942eSJames Wright 
33262b7942eSJames Wright     for (PetscInt j = 0; j < dims[1]; j++) {
33362b7942eSJames Wright       array[i * dims[1] + j] = (PetscReal)atof(row_array[j]);
33462b7942eSJames Wright     }
33562b7942eSJames Wright   }
33662b7942eSJames Wright 
33762b7942eSJames Wright   PetscCall(PetscFClose(comm, fp));
338d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
33962b7942eSJames Wright }
3407eedc94cSJames Wright 
3417eedc94cSJames Wright PetscLogEvent       FLUIDS_CeedOperatorApply;
3427eedc94cSJames Wright PetscLogEvent       FLUIDS_CeedOperatorAssemble;
3437eedc94cSJames Wright PetscLogEvent       FLUIDS_CeedOperatorAssembleDiagonal;
3447eedc94cSJames Wright PetscLogEvent       FLUIDS_CeedOperatorAssemblePointBlockDiagonal;
345ad2e713eSRiccardo Balin PetscLogEvent       FLUIDS_SmartRedis_Init;
346ad2e713eSRiccardo Balin PetscLogEvent       FLUIDS_SmartRedis_Meta;
347ad2e713eSRiccardo Balin PetscLogEvent       FLUIDS_SmartRedis_Train;
348ad2e713eSRiccardo Balin PetscLogEvent       FLUIDS_TrainDataCompute;
349855536edSJames Wright PetscLogEvent       FLUIDS_DifferentialFilter;
350855536edSJames Wright PetscLogEvent       FLUIDS_VelocityGradientProjection;
351855536edSJames Wright static PetscClassId libCEED_classid, onlineTrain_classid, misc_classid;
3527eedc94cSJames Wright 
3537eedc94cSJames Wright PetscErrorCode RegisterLogEvents() {
3547eedc94cSJames Wright   PetscFunctionBeginUser;
3557eedc94cSJames Wright   PetscCall(PetscClassIdRegister("libCEED", &libCEED_classid));
3567eedc94cSJames Wright   PetscCall(PetscLogEventRegister("CeedOpApply", libCEED_classid, &FLUIDS_CeedOperatorApply));
3577eedc94cSJames Wright   PetscCall(PetscLogEventRegister("CeedOpAsm", libCEED_classid, &FLUIDS_CeedOperatorAssemble));
3587eedc94cSJames Wright   PetscCall(PetscLogEventRegister("CeedOpAsmD", libCEED_classid, &FLUIDS_CeedOperatorAssembleDiagonal));
3597eedc94cSJames Wright   PetscCall(PetscLogEventRegister("CeedOpAsmPBD", libCEED_classid, &FLUIDS_CeedOperatorAssemblePointBlockDiagonal));
360ad2e713eSRiccardo Balin 
361ad2e713eSRiccardo Balin   PetscCall(PetscClassIdRegister("onlineTrain", &onlineTrain_classid));
362ad2e713eSRiccardo Balin   PetscCall(PetscLogEventRegister("SmartRedis_Init", onlineTrain_classid, &FLUIDS_SmartRedis_Init));
363ad2e713eSRiccardo Balin   PetscCall(PetscLogEventRegister("SmartRedis_Meta", onlineTrain_classid, &FLUIDS_SmartRedis_Meta));
364ad2e713eSRiccardo Balin   PetscCall(PetscLogEventRegister("SmartRedis_Train", onlineTrain_classid, &FLUIDS_SmartRedis_Train));
365ad2e713eSRiccardo Balin   PetscCall(PetscLogEventRegister("TrainDataCompute", onlineTrain_classid, &FLUIDS_TrainDataCompute));
366855536edSJames Wright 
367855536edSJames Wright   PetscCall(PetscClassIdRegister("Miscellaneous", &misc_classid));
368855536edSJames Wright   PetscCall(PetscLogEventRegister("DiffFilter", misc_classid, &FLUIDS_DifferentialFilter));
369855536edSJames Wright   PetscCall(PetscLogEventRegister("VeloGradProj", misc_classid, &FLUIDS_VelocityGradientProjection));
370d949ddfcSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
3717eedc94cSJames Wright }
372defe8520SJames Wright 
373926a6279SJames Wright // Print information about the given simulation run
374926a6279SJames Wright PetscErrorCode PrintRunInfo(User user, Physics phys_ctx, ProblemData *problem, MPI_Comm comm) {
375b4c37c5cSJames Wright   Ceed ceed = user->ceed;
376926a6279SJames Wright   PetscFunctionBeginUser;
377926a6279SJames Wright   // Header and rank
378926a6279SJames Wright   char        host_name[PETSC_MAX_PATH_LEN];
379926a6279SJames Wright   PetscMPIInt rank, comm_size;
380926a6279SJames Wright   PetscCall(PetscGetHostName(host_name, sizeof host_name));
381926a6279SJames Wright   PetscCallMPI(MPI_Comm_rank(comm, &rank));
382926a6279SJames Wright   PetscCallMPI(MPI_Comm_size(comm, &comm_size));
383926a6279SJames Wright   PetscCall(PetscPrintf(comm,
384926a6279SJames Wright                         "\n-- Navier-Stokes solver - libCEED + PETSc --\n"
385926a6279SJames Wright                         "  MPI:\n"
386926a6279SJames Wright                         "    Host Name                          : %s\n"
387926a6279SJames Wright                         "    Total ranks                        : %d\n",
388926a6279SJames Wright                         host_name, comm_size));
389926a6279SJames Wright 
390926a6279SJames Wright   // Problem specific info
3912d49c0afSJames Wright   PetscCall(problem->print_info(user, problem, user->app_ctx));
392926a6279SJames Wright 
393926a6279SJames Wright   // libCEED
394926a6279SJames Wright   const char *used_resource;
395926a6279SJames Wright   CeedMemType mem_type_backend;
396b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedGetResource(user->ceed, &used_resource));
397b4c37c5cSJames Wright   PetscCallCeed(ceed, CeedGetPreferredMemType(user->ceed, &mem_type_backend));
398926a6279SJames Wright   PetscCall(PetscPrintf(comm,
399926a6279SJames Wright                         "  libCEED:\n"
400926a6279SJames Wright                         "    libCEED Backend                    : %s\n"
401926a6279SJames Wright                         "    libCEED Backend MemType            : %s\n",
402926a6279SJames Wright                         used_resource, CeedMemTypes[mem_type_backend]));
403926a6279SJames Wright   // PETSc
404926a6279SJames Wright   char box_faces_str[PETSC_MAX_PATH_LEN] = "3,3,3";
405926a6279SJames Wright   if (problem->dim == 2) box_faces_str[3] = '\0';
406926a6279SJames Wright   PetscCall(PetscOptionsGetString(NULL, NULL, "-dm_plex_box_faces", box_faces_str, sizeof(box_faces_str), NULL));
40765149b89SJames Wright   MatType amat_type = user->app_ctx->amat_type, pmat_type;
408926a6279SJames Wright   VecType vec_type;
40965149b89SJames Wright   PetscCall(DMGetMatType(user->dm, &pmat_type));
41065149b89SJames Wright   if (!amat_type) amat_type = pmat_type;
411926a6279SJames Wright   PetscCall(DMGetVecType(user->dm, &vec_type));
412926a6279SJames Wright   PetscCall(PetscPrintf(comm,
413926a6279SJames Wright                         "  PETSc:\n"
414926a6279SJames Wright                         "    Box Faces                          : %s\n"
41565149b89SJames Wright                         "    A MatType                          : %s\n"
41665149b89SJames Wright                         "    P MatType                          : %s\n"
417926a6279SJames Wright                         "    DM VecType                         : %s\n"
418926a6279SJames Wright                         "    Time Stepping Scheme               : %s\n",
41965149b89SJames Wright                         box_faces_str, amat_type, pmat_type, vec_type, phys_ctx->implicit ? "implicit" : "explicit"));
420926a6279SJames Wright   if (user->app_ctx->cont_steps) {
421926a6279SJames Wright     PetscCall(PetscPrintf(comm,
422926a6279SJames Wright                           "  Continue:\n"
423926a6279SJames Wright                           "    Filename:                          : %s\n"
424926a6279SJames Wright                           "    Step:                              : %" PetscInt_FMT "\n"
425926a6279SJames Wright                           "    Time:                              : %g\n",
426926a6279SJames Wright                           user->app_ctx->cont_file, user->app_ctx->cont_steps, user->app_ctx->cont_time));
427926a6279SJames Wright   }
428926a6279SJames Wright   // Mesh
429926a6279SJames Wright   const PetscInt num_comp_q = 5;
430926a6279SJames Wright   PetscInt       glob_dofs, owned_dofs, local_dofs;
431926a6279SJames Wright   const CeedInt  num_P = user->app_ctx->degree + 1, num_Q = num_P + user->app_ctx->q_extra;
432926a6279SJames Wright   PetscCall(DMGetGlobalVectorInfo(user->dm, &owned_dofs, &glob_dofs, NULL));
433926a6279SJames Wright   PetscCall(DMGetLocalVectorInfo(user->dm, &local_dofs, NULL, NULL));
434926a6279SJames Wright   PetscCall(PetscPrintf(comm,
435926a6279SJames Wright                         "  Mesh:\n"
436926a6279SJames Wright                         "    Number of 1D Basis Nodes (P)       : %" CeedInt_FMT "\n"
437926a6279SJames Wright                         "    Number of 1D Quadrature Points (Q) : %" CeedInt_FMT "\n"
438926a6279SJames Wright                         "    Global DoFs                        : %" PetscInt_FMT "\n"
439926a6279SJames Wright                         "    DoFs per node                      : %" PetscInt_FMT "\n"
440dfeb939dSJames Wright                         "    Global %" PetscInt_FMT "-DoF nodes                 : %" PetscInt_FMT "\n",
441dfeb939dSJames Wright                         num_P, num_Q, glob_dofs, num_comp_q, num_comp_q, glob_dofs / num_comp_q));
442926a6279SJames Wright   // -- Get Partition Statistics
443926a6279SJames Wright   PetscCall(PetscPrintf(comm, "  Partition:                             (min,max,median,max/median)\n"));
444926a6279SJames Wright   {
445926a6279SJames Wright     PetscInt *gather_buffer = NULL;
446dfeb939dSJames Wright     PetscInt  part_owned_dofs[3], part_local_dofs[3], part_boundary_dofs[3], part_neighbors[3];
447926a6279SJames Wright     PetscInt  median_index = comm_size % 2 ? comm_size / 2 : comm_size / 2 - 1;
448926a6279SJames Wright     if (!rank) PetscCall(PetscMalloc1(comm_size, &gather_buffer));
449926a6279SJames Wright 
450dfeb939dSJames Wright     PetscCallMPI(MPI_Gather(&owned_dofs, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
451926a6279SJames Wright     if (!rank) {
452926a6279SJames Wright       PetscCall(PetscSortInt(comm_size, gather_buffer));
453926a6279SJames Wright       part_owned_dofs[0]             = gather_buffer[0];              // min
454926a6279SJames Wright       part_owned_dofs[1]             = gather_buffer[comm_size - 1];  // max
455926a6279SJames Wright       part_owned_dofs[2]             = gather_buffer[median_index];   // median
456926a6279SJames Wright       PetscReal part_owned_dof_ratio = (PetscReal)part_owned_dofs[1] / (PetscReal)part_owned_dofs[2];
457dfeb939dSJames Wright       PetscCall(PetscPrintf(
458dfeb939dSJames Wright           comm, "    Global Vector %" PetscInt_FMT "-DoF nodes          : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n", num_comp_q,
459926a6279SJames Wright           part_owned_dofs[0] / num_comp_q, part_owned_dofs[1] / num_comp_q, part_owned_dofs[2] / num_comp_q, part_owned_dof_ratio));
460926a6279SJames Wright     }
461926a6279SJames Wright 
462dfeb939dSJames Wright     PetscCallMPI(MPI_Gather(&local_dofs, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
463926a6279SJames Wright     if (!rank) {
464926a6279SJames Wright       PetscCall(PetscSortInt(comm_size, gather_buffer));
465926a6279SJames Wright       part_local_dofs[0]             = gather_buffer[0];              // min
466926a6279SJames Wright       part_local_dofs[1]             = gather_buffer[comm_size - 1];  // max
467926a6279SJames Wright       part_local_dofs[2]             = gather_buffer[median_index];   // median
468926a6279SJames Wright       PetscReal part_local_dof_ratio = (PetscReal)part_local_dofs[1] / (PetscReal)part_local_dofs[2];
469dfeb939dSJames Wright       PetscCall(PetscPrintf(
470dfeb939dSJames Wright           comm, "    Local Vector %" PetscInt_FMT "-DoF nodes           : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n", num_comp_q,
471926a6279SJames Wright           part_local_dofs[0] / num_comp_q, part_local_dofs[1] / num_comp_q, part_local_dofs[2] / num_comp_q, part_local_dof_ratio));
472926a6279SJames Wright     }
473926a6279SJames Wright 
47445abf96eSJames Wright     if (comm_size != 1) {
475dfeb939dSJames Wright       PetscInt num_remote_roots_total = 0, num_remote_leaves_total = 0, num_ghost_interface_ranks = 0, num_owned_interface_ranks = 0;
476926a6279SJames Wright       {
477926a6279SJames Wright         PetscSF            sf;
478dfeb939dSJames Wright         PetscInt           nrranks, niranks;
479dfeb939dSJames Wright         const PetscInt    *roffset, *rmine, *rremote, *ioffset, *irootloc;
480dfeb939dSJames Wright         const PetscMPIInt *rranks, *iranks;
481926a6279SJames Wright         PetscCall(DMGetSectionSF(user->dm, &sf));
482926a6279SJames Wright         PetscCall(PetscSFGetRootRanks(sf, &nrranks, &rranks, &roffset, &rmine, &rremote));
483dfeb939dSJames Wright         PetscCall(PetscSFGetLeafRanks(sf, &niranks, &iranks, &ioffset, &irootloc));
484926a6279SJames Wright         for (PetscInt i = 0; i < nrranks; i++) {
485926a6279SJames Wright           if (rranks[i] == rank) continue;  // Ignore same-part global->local transfers
486926a6279SJames Wright           num_remote_roots_total += roffset[i + 1] - roffset[i];
487dfeb939dSJames Wright           num_ghost_interface_ranks++;
488dfeb939dSJames Wright         }
489dfeb939dSJames Wright         for (PetscInt i = 0; i < niranks; i++) {
490dfeb939dSJames Wright           if (iranks[i] == rank) continue;
491dfeb939dSJames Wright           num_remote_leaves_total += ioffset[i + 1] - ioffset[i];
492dfeb939dSJames Wright           num_owned_interface_ranks++;
493926a6279SJames Wright         }
494926a6279SJames Wright       }
495dfeb939dSJames Wright       PetscCallMPI(MPI_Gather(&num_remote_roots_total, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
496926a6279SJames Wright       if (!rank) {
497926a6279SJames Wright         PetscCall(PetscSortInt(comm_size, gather_buffer));
498dfeb939dSJames Wright         part_boundary_dofs[0]           = gather_buffer[0];              // min
499dfeb939dSJames Wright         part_boundary_dofs[1]           = gather_buffer[comm_size - 1];  // max
500dfeb939dSJames Wright         part_boundary_dofs[2]           = gather_buffer[median_index];   // median
501dfeb939dSJames Wright         PetscReal part_shared_dof_ratio = (PetscReal)part_boundary_dofs[1] / (PetscReal)part_boundary_dofs[2];
502dfeb939dSJames Wright         PetscCall(PetscPrintf(
50345abf96eSJames Wright             comm, "    Ghost Interface %" PetscInt_FMT "-DoF nodes        : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n",
50445abf96eSJames Wright             num_comp_q, part_boundary_dofs[0] / num_comp_q, part_boundary_dofs[1] / num_comp_q, part_boundary_dofs[2] / num_comp_q,
50545abf96eSJames Wright             part_shared_dof_ratio));
506dfeb939dSJames Wright       }
507dfeb939dSJames Wright 
508dfeb939dSJames Wright       PetscCallMPI(MPI_Gather(&num_ghost_interface_ranks, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
509dfeb939dSJames Wright       if (!rank) {
510dfeb939dSJames Wright         PetscCall(PetscSortInt(comm_size, gather_buffer));
511dfeb939dSJames Wright         part_neighbors[0]              = gather_buffer[0];              // min
512dfeb939dSJames Wright         part_neighbors[1]              = gather_buffer[comm_size - 1];  // max
513dfeb939dSJames Wright         part_neighbors[2]              = gather_buffer[median_index];   // median
514dfeb939dSJames Wright         PetscReal part_neighbors_ratio = (PetscReal)part_neighbors[1] / (PetscReal)part_neighbors[2];
515dfeb939dSJames Wright         PetscCall(PetscPrintf(comm, "    Ghost Interface Ranks              : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n",
516dfeb939dSJames Wright                               part_neighbors[0], part_neighbors[1], part_neighbors[2], part_neighbors_ratio));
517dfeb939dSJames Wright       }
518dfeb939dSJames Wright 
519dfeb939dSJames Wright       PetscCallMPI(MPI_Gather(&num_remote_leaves_total, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
520dfeb939dSJames Wright       if (!rank) {
521dfeb939dSJames Wright         PetscCall(PetscSortInt(comm_size, gather_buffer));
522dfeb939dSJames Wright         part_boundary_dofs[0]           = gather_buffer[0];              // min
523dfeb939dSJames Wright         part_boundary_dofs[1]           = gather_buffer[comm_size - 1];  // max
524dfeb939dSJames Wright         part_boundary_dofs[2]           = gather_buffer[median_index];   // median
525dfeb939dSJames Wright         PetscReal part_shared_dof_ratio = (PetscReal)part_boundary_dofs[1] / (PetscReal)part_boundary_dofs[2];
526dfeb939dSJames Wright         PetscCall(PetscPrintf(
52745abf96eSJames Wright             comm, "    Owned Interface %" PetscInt_FMT "-DoF nodes        : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n",
52845abf96eSJames Wright             num_comp_q, part_boundary_dofs[0] / num_comp_q, part_boundary_dofs[1] / num_comp_q, part_boundary_dofs[2] / num_comp_q,
52945abf96eSJames Wright             part_shared_dof_ratio));
530dfeb939dSJames Wright       }
531dfeb939dSJames Wright 
532dfeb939dSJames Wright       PetscCallMPI(MPI_Gather(&num_owned_interface_ranks, 1, MPIU_INT, gather_buffer, 1, MPIU_INT, 0, comm));
533dfeb939dSJames Wright       if (!rank) {
534dfeb939dSJames Wright         PetscCall(PetscSortInt(comm_size, gather_buffer));
535dfeb939dSJames Wright         part_neighbors[0]              = gather_buffer[0];              // min
536dfeb939dSJames Wright         part_neighbors[1]              = gather_buffer[comm_size - 1];  // max
537dfeb939dSJames Wright         part_neighbors[2]              = gather_buffer[median_index];   // median
538dfeb939dSJames Wright         PetscReal part_neighbors_ratio = (PetscReal)part_neighbors[1] / (PetscReal)part_neighbors[2];
539dfeb939dSJames Wright         PetscCall(PetscPrintf(comm, "    Owned Interface Ranks              : %" PetscInt_FMT ", %" PetscInt_FMT ", %" PetscInt_FMT ", %f\n",
540dfeb939dSJames Wright                               part_neighbors[0], part_neighbors[1], part_neighbors[2], part_neighbors_ratio));
541926a6279SJames Wright       }
54245abf96eSJames Wright     }
543926a6279SJames Wright 
544926a6279SJames Wright     if (!rank) PetscCall(PetscFree(gather_buffer));
545926a6279SJames Wright   }
546926a6279SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
547926a6279SJames Wright }
548