xref: /libCEED/examples/fluids/src/setupts.c (revision ee4ca9cbfe2be39196684117442f3ce8d00b6506)
1 // Copyright (c) 2017-2022, Lawrence Livermore National Security, LLC and other CEED contributors.
2 // All Rights Reserved. See the top-level LICENSE and NOTICE files for details.
3 //
4 // SPDX-License-Identifier: BSD-2-Clause
5 //
6 // This file is part of CEED:  http://github.com/ceed
7 
8 /// @file
9 /// Time-stepping functions for Navier-Stokes example using PETSc
10 
11 #include <ceed.h>
12 #include <petscdmplex.h>
13 #include <petscts.h>
14 
15 #include "../navierstokes.h"
16 #include "../qfunctions/newtonian_state.h"
17 
18 // Compute mass matrix for explicit scheme
19 PetscErrorCode ComputeLumpedMassMatrix(Ceed ceed, DM dm, CeedData ceed_data, Vec M) {
20   CeedQFunction        qf_mass;
21   CeedOperator         op_mass;
22   OperatorApplyContext op_mass_ctx;
23   Vec                  Ones_loc;
24   CeedInt              num_comp_q, q_data_size;
25   PetscFunctionBeginUser;
26 
27   // CEED Restriction
28   CeedElemRestrictionGetNumComponents(ceed_data->elem_restr_q, &num_comp_q);
29   CeedElemRestrictionGetNumComponents(ceed_data->elem_restr_qd_i, &q_data_size);
30 
31   // CEED QFunction
32   PetscCall(CreateMassQFunction(ceed, num_comp_q, q_data_size, &qf_mass));
33 
34   // CEED Operator
35   CeedOperatorCreate(ceed, qf_mass, NULL, NULL, &op_mass);
36   CeedOperatorSetField(op_mass, "u", ceed_data->elem_restr_q, ceed_data->basis_q, CEED_VECTOR_ACTIVE);
37   CeedOperatorSetField(op_mass, "qdata", ceed_data->elem_restr_qd_i, CEED_BASIS_COLLOCATED, ceed_data->q_data);
38   CeedOperatorSetField(op_mass, "v", ceed_data->elem_restr_q, ceed_data->basis_q, CEED_VECTOR_ACTIVE);
39 
40   PetscCall(OperatorApplyContextCreate(NULL, dm, ceed, op_mass, NULL, NULL, NULL, NULL, &op_mass_ctx));
41 
42   PetscCall(DMGetLocalVector(dm, &Ones_loc));
43   PetscCall(VecSet(Ones_loc, 1));
44   PetscCall(ApplyCeedOperatorLocalToGlobal(Ones_loc, M, op_mass_ctx));
45 
46   // Invert diagonally lumped mass vector for RHS function
47   PetscCall(VecReciprocal(M));
48 
49   // Cleanup
50   PetscCall(OperatorApplyContextDestroy(op_mass_ctx));
51   PetscCall(DMRestoreLocalVector(dm, &Ones_loc));
52   CeedQFunctionDestroy(&qf_mass);
53   CeedOperatorDestroy(&op_mass);
54 
55   PetscFunctionReturn(PETSC_SUCCESS);
56 }
57 
58 // Insert Boundary values if it's a new time
59 PetscErrorCode UpdateBoundaryValues(User user, Vec Q_loc, PetscReal t) {
60   PetscFunctionBeginUser;
61   if (user->time_bc_set != t) {
62     PetscCall(DMPlexInsertBoundaryValues(user->dm, PETSC_TRUE, Q_loc, t, NULL, NULL, NULL));
63     user->time_bc_set = t;
64   }
65   PetscFunctionReturn(PETSC_SUCCESS);
66 }
67 
68 // @brief Update the context label value to new value if necessary.
69 // @note This only supports labels with scalar label values (ie. not arrays)
70 PetscErrorCode UpdateContextLabel(MPI_Comm comm, PetscScalar update_value, CeedOperator op, CeedContextFieldLabel label) {
71   PetscScalar label_value;
72 
73   PetscFunctionBeginUser;
74   PetscCheck(label, comm, PETSC_ERR_ARG_BADPTR, "Label should be non-NULL");
75 
76   {
77     size_t             num_elements;
78     const PetscScalar *label_values;
79     CeedOperatorGetContextDoubleRead(op, label, &num_elements, &label_values);
80     PetscCheck(num_elements == 1, comm, PETSC_ERR_SUP, "%s does not support labels with more than 1 value. Label has %zu values", __func__,
81                num_elements);
82     label_value = *label_values;
83     CeedOperatorRestoreContextDoubleRead(op, label, &label_values);
84   }
85 
86   if (label_value != update_value) {
87     CeedOperatorSetContextDouble(op, label, &update_value);
88   }
89   PetscFunctionReturn(PETSC_SUCCESS);
90 }
91 
92 // RHS (Explicit time-stepper) function setup
93 //   This is the RHS of the ODE, given as u_t = G(t,u)
94 //   This function takes in a state vector Q and writes into G
95 PetscErrorCode RHS_NS(TS ts, PetscReal t, Vec Q, Vec G, void *user_data) {
96   User        user = *(User *)user_data;
97   MPI_Comm    comm = PetscObjectComm((PetscObject)ts);
98   PetscScalar dt;
99   Vec         Q_loc = user->Q_loc;
100   PetscFunctionBeginUser;
101 
102   // Update time dependent data
103   PetscCall(UpdateBoundaryValues(user, Q_loc, t));
104   if (user->phys->solution_time_label) PetscCall(UpdateContextLabel(comm, t, user->op_rhs_ctx->op, user->phys->solution_time_label));
105   PetscCall(TSGetTimeStep(ts, &dt));
106   if (user->phys->timestep_size_label) PetscCall(UpdateContextLabel(comm, dt, user->op_rhs_ctx->op, user->phys->timestep_size_label));
107 
108   PetscCall(ApplyCeedOperatorGlobalToGlobal(Q, G, user->op_rhs_ctx));
109 
110   // Inverse of the lumped mass matrix (M is Minv)
111   PetscCall(VecPointwiseMult(G, G, user->M_inv));
112 
113   PetscFunctionReturn(PETSC_SUCCESS);
114 }
115 
116 // Surface forces function setup
117 static PetscErrorCode Surface_Forces_NS(DM dm, Vec G_loc, PetscInt num_walls, const PetscInt walls[], PetscScalar *reaction_force) {
118   DMLabel            face_label;
119   const PetscScalar *g;
120   PetscInt           dof, dim = 3;
121   MPI_Comm           comm;
122   PetscSection       s;
123 
124   PetscFunctionBeginUser;
125   PetscCall(PetscArrayzero(reaction_force, num_walls * dim));
126   PetscCall(PetscObjectGetComm((PetscObject)dm, &comm));
127   PetscCall(DMGetLabel(dm, "Face Sets", &face_label));
128   PetscCall(VecGetArrayRead(G_loc, &g));
129   for (PetscInt w = 0; w < num_walls; w++) {
130     const PetscInt wall = walls[w];
131     IS             wall_is;
132     PetscCall(DMGetLocalSection(dm, &s));
133     PetscCall(DMLabelGetStratumIS(face_label, wall, &wall_is));
134     if (wall_is) {  // There exist such points on this process
135       PetscInt        num_points;
136       PetscInt        num_comp = 0;
137       const PetscInt *points;
138       PetscCall(PetscSectionGetFieldComponents(s, 0, &num_comp));
139       PetscCall(ISGetSize(wall_is, &num_points));
140       PetscCall(ISGetIndices(wall_is, &points));
141       for (PetscInt i = 0; i < num_points; i++) {
142         const PetscInt           p = points[i];
143         const StateConservative *r;
144         PetscCall(DMPlexPointLocalRead(dm, p, g, &r));
145         PetscCall(PetscSectionGetDof(s, p, &dof));
146         for (PetscInt node = 0; node < dof / num_comp; node++) {
147           for (PetscInt j = 0; j < 3; j++) {
148             reaction_force[w * dim + j] -= r[node].momentum[j];
149           }
150         }
151       }
152       PetscCall(ISRestoreIndices(wall_is, &points));
153     }
154     PetscCall(ISDestroy(&wall_is));
155   }
156   PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE, reaction_force, dim * num_walls, MPIU_SCALAR, MPI_SUM, comm));
157   //  Restore Vectors
158   PetscCall(VecRestoreArrayRead(G_loc, &g));
159 
160   PetscFunctionReturn(PETSC_SUCCESS);
161 }
162 
163 // Implicit time-stepper function setup
164 PetscErrorCode IFunction_NS(TS ts, PetscReal t, Vec Q, Vec Q_dot, Vec G, void *user_data) {
165   User         user = *(User *)user_data;
166   MPI_Comm     comm = PetscObjectComm((PetscObject)ts);
167   PetscScalar  dt;
168   Vec          Q_loc = user->Q_loc, Q_dot_loc = user->Q_dot_loc, G_loc;
169   PetscMemType q_mem_type, q_dot_mem_type, g_mem_type;
170   PetscFunctionBeginUser;
171 
172   // Get local vectors
173   PetscCall(DMGetNamedLocalVector(user->dm, "ResidualLocal", &G_loc));
174 
175   // Update time dependent data
176   PetscCall(UpdateBoundaryValues(user, Q_loc, t));
177   if (user->phys->solution_time_label) PetscCall(UpdateContextLabel(comm, t, user->op_ifunction, user->phys->solution_time_label));
178   PetscCall(TSGetTimeStep(ts, &dt));
179   if (user->phys->timestep_size_label) PetscCall(UpdateContextLabel(comm, dt, user->op_ifunction, user->phys->timestep_size_label));
180 
181   // Global-to-local
182   PetscCall(DMGlobalToLocalBegin(user->dm, Q, INSERT_VALUES, Q_loc));
183   PetscCall(DMGlobalToLocalBegin(user->dm, Q_dot, INSERT_VALUES, Q_dot_loc));
184   PetscCall(DMGlobalToLocalEnd(user->dm, Q, INSERT_VALUES, Q_loc));
185   PetscCall(DMGlobalToLocalEnd(user->dm, Q_dot, INSERT_VALUES, Q_dot_loc));
186 
187   // Place PETSc vectors in CEED vectors
188   PetscCall(VecReadP2C(Q_loc, &q_mem_type, user->q_ceed));
189   PetscCall(VecReadP2C(Q_dot_loc, &q_dot_mem_type, user->q_dot_ceed));
190   PetscCall(VecP2C(G_loc, &g_mem_type, user->g_ceed));
191 
192   // Apply CEED operator
193   PetscCall(PetscLogEventBegin(FLUIDS_CeedOperatorApply, Q, G, 0, 0));
194   PetscCall(PetscLogGpuTimeBegin());
195   CeedOperatorApply(user->op_ifunction, user->q_ceed, user->g_ceed, CEED_REQUEST_IMMEDIATE);
196   PetscCall(PetscLogGpuTimeEnd());
197   PetscCall(PetscLogEventEnd(FLUIDS_CeedOperatorApply, Q, G, 0, 0));
198 
199   // Restore vectors
200   PetscCall(VecReadC2P(user->q_ceed, q_mem_type, Q_loc));
201   PetscCall(VecReadC2P(user->q_dot_ceed, q_dot_mem_type, Q_dot_loc));
202   PetscCall(VecC2P(user->g_ceed, g_mem_type, G_loc));
203 
204   if (user->app_ctx->sgs_model_type == SGS_MODEL_DATA_DRIVEN) {
205     PetscCall(SGS_DD_ModelApplyIFunction(user, Q_loc, G_loc));
206   }
207 
208   // Local-to-Global
209   PetscCall(VecZeroEntries(G));
210   PetscCall(DMLocalToGlobal(user->dm, G_loc, ADD_VALUES, G));
211 
212   // Restore vectors
213   PetscCall(DMRestoreNamedLocalVector(user->dm, "ResidualLocal", &G_loc));
214 
215   PetscFunctionReturn(PETSC_SUCCESS);
216 }
217 
218 static PetscErrorCode FormPreallocation(User user, PetscBool pbdiagonal, Mat J, CeedVector *coo_values) {
219   PetscCount ncoo;
220   PetscInt  *rows, *cols;
221 
222   PetscFunctionBeginUser;
223   if (pbdiagonal) {
224     CeedSize l_size;
225     CeedOperatorGetActiveVectorLengths(user->op_ijacobian, &l_size, NULL);
226     ncoo = l_size * 5;
227     rows = malloc(ncoo * sizeof(rows[0]));
228     cols = malloc(ncoo * sizeof(cols[0]));
229     for (PetscCount n = 0; n < l_size / 5; n++) {
230       for (PetscInt i = 0; i < 5; i++) {
231         for (PetscInt j = 0; j < 5; j++) {
232           rows[(n * 5 + i) * 5 + j] = n * 5 + i;
233           cols[(n * 5 + i) * 5 + j] = n * 5 + j;
234         }
235       }
236     }
237   } else {
238     PetscCall(CeedOperatorLinearAssembleSymbolic(user->op_ijacobian, &ncoo, &rows, &cols));
239   }
240   PetscCall(MatSetPreallocationCOOLocal(J, ncoo, rows, cols));
241   free(rows);
242   free(cols);
243   CeedVectorCreate(user->ceed, ncoo, coo_values);
244   PetscFunctionReturn(PETSC_SUCCESS);
245 }
246 
247 static PetscErrorCode FormSetValues(User user, PetscBool pbdiagonal, Mat J, CeedVector coo_values) {
248   CeedMemType        mem_type = CEED_MEM_HOST;
249   const PetscScalar *values;
250   MatType            mat_type;
251 
252   PetscFunctionBeginUser;
253   PetscCall(MatGetType(J, &mat_type));
254   if (strstr(mat_type, "kokkos") || strstr(mat_type, "cusparse")) mem_type = CEED_MEM_DEVICE;
255   if (pbdiagonal) {
256     PetscCall(PetscLogEventBegin(FLUIDS_CeedOperatorAssemblePointBlockDiagonal, J, 0, 0, 0));
257     PetscCall(PetscLogGpuTimeBegin());
258     CeedOperatorLinearAssemblePointBlockDiagonal(user->op_ijacobian, coo_values, CEED_REQUEST_IMMEDIATE);
259     PetscCall(PetscLogGpuTimeEnd());
260     PetscCall(PetscLogEventEnd(FLUIDS_CeedOperatorAssemblePointBlockDiagonal, J, 0, 0, 0));
261   } else {
262     PetscCall(PetscLogEventBegin(FLUIDS_CeedOperatorAssemble, J, 0, 0, 0));
263     PetscCall(PetscLogGpuTimeBegin());
264     CeedOperatorLinearAssemble(user->op_ijacobian, coo_values);
265     PetscCall(PetscLogGpuTimeEnd());
266     PetscCall(PetscLogEventEnd(FLUIDS_CeedOperatorAssemble, J, 0, 0, 0));
267   }
268   CeedVectorGetArrayRead(coo_values, mem_type, &values);
269   PetscCall(MatSetValuesCOO(J, values, INSERT_VALUES));
270   CeedVectorRestoreArrayRead(coo_values, &values);
271   PetscFunctionReturn(PETSC_SUCCESS);
272 }
273 
274 PetscErrorCode FormIJacobian_NS(TS ts, PetscReal t, Vec Q, Vec Q_dot, PetscReal shift, Mat J, Mat J_pre, void *user_data) {
275   User      user = *(User *)user_data;
276   PetscBool J_is_shell, J_is_mffd, J_pre_is_shell;
277   PetscFunctionBeginUser;
278   if (user->phys->ijacobian_time_shift_label) CeedOperatorSetContextDouble(user->op_ijacobian, user->phys->ijacobian_time_shift_label, &shift);
279   PetscCall(PetscObjectTypeCompare((PetscObject)J, MATMFFD, &J_is_mffd));
280   PetscCall(PetscObjectTypeCompare((PetscObject)J, MATSHELL, &J_is_shell));
281   PetscCall(PetscObjectTypeCompare((PetscObject)J_pre, MATSHELL, &J_pre_is_shell));
282   if (!user->matrices_set_up) {
283     if (J_is_shell) {
284       OperatorApplyContext op_ijacobian_ctx;
285       OperatorApplyContextCreate(user->dm, user->dm, user->ceed, user->op_ijacobian, user->q_ceed, user->g_ceed, user->Q_dot_loc, NULL,
286                                  &op_ijacobian_ctx);
287       PetscCall(MatShellSetContext(J, op_ijacobian_ctx));
288       PetscCall(MatShellSetContextDestroy(J, (PetscErrorCode(*)(void *))OperatorApplyContextDestroy));
289       PetscCall(MatShellSetOperation(J, MATOP_MULT, (void (*)(void))MatMult_Ceed));
290       PetscCall(MatShellSetOperation(J, MATOP_GET_DIAGONAL, (void (*)(void))MatGetDiag_Ceed));
291       PetscCall(MatSetUp(J));
292     }
293     if (!J_pre_is_shell) {
294       PetscCall(FormPreallocation(user, user->app_ctx->pmat_pbdiagonal, J_pre, &user->coo_values_pmat));
295     }
296     if (J != J_pre && !J_is_shell && !J_is_mffd) {
297       PetscCall(FormPreallocation(user, PETSC_FALSE, J, &user->coo_values_amat));
298     }
299     user->matrices_set_up = true;
300   }
301   if (!J_pre_is_shell) {
302     PetscCall(FormSetValues(user, user->app_ctx->pmat_pbdiagonal, J_pre, user->coo_values_pmat));
303   }
304   if (user->coo_values_amat) {
305     PetscCall(FormSetValues(user, PETSC_FALSE, J, user->coo_values_amat));
306   } else if (J_is_mffd) {
307     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
308     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
309   }
310   PetscFunctionReturn(PETSC_SUCCESS);
311 }
312 
313 PetscErrorCode WriteOutput(User user, Vec Q, PetscInt step_no, PetscScalar time) {
314   Vec         Q_loc;
315   char        file_path[PETSC_MAX_PATH_LEN];
316   PetscViewer viewer;
317   PetscFunctionBeginUser;
318 
319   if (user->app_ctx->checkpoint_vtk) {
320     // Set up output
321     PetscCall(DMGetLocalVector(user->dm, &Q_loc));
322     PetscCall(PetscObjectSetName((PetscObject)Q_loc, "StateVec"));
323     PetscCall(VecZeroEntries(Q_loc));
324     PetscCall(DMGlobalToLocal(user->dm, Q, INSERT_VALUES, Q_loc));
325 
326     // Output
327     PetscCall(PetscSNPrintf(file_path, sizeof file_path, "%s/ns-%03" PetscInt_FMT ".vtu", user->app_ctx->output_dir, step_no));
328 
329     PetscCall(PetscViewerVTKOpen(PetscObjectComm((PetscObject)Q), file_path, FILE_MODE_WRITE, &viewer));
330     PetscCall(VecView(Q_loc, viewer));
331     PetscCall(PetscViewerDestroy(&viewer));
332     if (user->dm_viz) {
333       Vec         Q_refined, Q_refined_loc;
334       char        file_path_refined[PETSC_MAX_PATH_LEN];
335       PetscViewer viewer_refined;
336 
337       PetscCall(DMGetGlobalVector(user->dm_viz, &Q_refined));
338       PetscCall(DMGetLocalVector(user->dm_viz, &Q_refined_loc));
339       PetscCall(PetscObjectSetName((PetscObject)Q_refined_loc, "Refined"));
340 
341       PetscCall(MatInterpolate(user->interp_viz, Q, Q_refined));
342       PetscCall(VecZeroEntries(Q_refined_loc));
343       PetscCall(DMGlobalToLocal(user->dm_viz, Q_refined, INSERT_VALUES, Q_refined_loc));
344 
345       PetscCall(
346           PetscSNPrintf(file_path_refined, sizeof file_path_refined, "%s/nsrefined-%03" PetscInt_FMT ".vtu", user->app_ctx->output_dir, step_no));
347 
348       PetscCall(PetscViewerVTKOpen(PetscObjectComm((PetscObject)Q_refined), file_path_refined, FILE_MODE_WRITE, &viewer_refined));
349       PetscCall(VecView(Q_refined_loc, viewer_refined));
350       PetscCall(DMRestoreLocalVector(user->dm_viz, &Q_refined_loc));
351       PetscCall(DMRestoreGlobalVector(user->dm_viz, &Q_refined));
352       PetscCall(PetscViewerDestroy(&viewer_refined));
353     }
354     PetscCall(DMRestoreLocalVector(user->dm, &Q_loc));
355   }
356 
357   // Save data in a binary file for continuation of simulations
358   if (user->app_ctx->add_stepnum2bin) {
359     PetscCall(PetscSNPrintf(file_path, sizeof file_path, "%s/ns-solution-%" PetscInt_FMT ".bin", user->app_ctx->output_dir, step_no));
360   } else {
361     PetscCall(PetscSNPrintf(file_path, sizeof file_path, "%s/ns-solution.bin", user->app_ctx->output_dir));
362   }
363   PetscCall(PetscViewerBinaryOpen(user->comm, file_path, FILE_MODE_WRITE, &viewer));
364 
365   PetscInt token = FLUIDS_FILE_TOKEN;
366   PetscCall(PetscViewerBinaryWrite(viewer, &token, 1, PETSC_INT));
367   PetscCall(PetscViewerBinaryWrite(viewer, &step_no, 1, PETSC_INT));
368   time /= user->units->second;  // Dimensionalize time back
369   PetscCall(PetscViewerBinaryWrite(viewer, &time, 1, PETSC_REAL));
370   PetscCall(VecView(Q, viewer));
371   PetscCall(PetscViewerDestroy(&viewer));
372   PetscFunctionReturn(PETSC_SUCCESS);
373 }
374 
375 // CSV Monitor
376 PetscErrorCode TSMonitor_WallForce(TS ts, PetscInt step_no, PetscReal time, Vec Q, void *ctx) {
377   User              user = ctx;
378   Vec               G_loc;
379   PetscInt          num_wall = user->app_ctx->wall_forces.num_wall, dim = 3;
380   const PetscInt   *walls  = user->app_ctx->wall_forces.walls;
381   PetscViewer       viewer = user->app_ctx->wall_forces.viewer;
382   PetscViewerFormat format = user->app_ctx->wall_forces.viewer_format;
383   PetscScalar      *reaction_force;
384   PetscBool         iascii;
385 
386   PetscFunctionBeginUser;
387   if (!viewer) PetscFunctionReturn(PETSC_SUCCESS);
388   PetscCall(DMGetNamedLocalVector(user->dm, "ResidualLocal", &G_loc));
389   PetscCall(PetscMalloc1(num_wall * dim, &reaction_force));
390   PetscCall(Surface_Forces_NS(user->dm, G_loc, num_wall, walls, reaction_force));
391   PetscCall(DMRestoreNamedLocalVector(user->dm, "ResidualLocal", &G_loc));
392 
393   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
394 
395   if (iascii) {
396     if (format == PETSC_VIEWER_ASCII_CSV && !user->app_ctx->wall_forces.header_written) {
397       PetscCall(PetscViewerASCIIPrintf(viewer, "Step,Time,Wall,ForceX,ForceY,ForceZ\n"));
398       user->app_ctx->wall_forces.header_written = PETSC_TRUE;
399     }
400     for (PetscInt w = 0; w < num_wall; w++) {
401       PetscInt wall = walls[w];
402       if (format == PETSC_VIEWER_ASCII_CSV) {
403         PetscCall(PetscViewerASCIIPrintf(viewer, "%" PetscInt_FMT ",%g,%" PetscInt_FMT ",%g,%g,%g\n", step_no, time, wall,
404                                          reaction_force[w * dim + 0], reaction_force[w * dim + 1], reaction_force[w * dim + 2]));
405 
406       } else {
407         PetscCall(PetscViewerASCIIPrintf(viewer, "Wall %" PetscInt_FMT " Forces: Force_x = %12g, Force_y = %12g, Force_z = %12g\n", wall,
408                                          reaction_force[w * dim + 0], reaction_force[w * dim + 1], reaction_force[w * dim + 2]));
409       }
410     }
411   }
412   PetscCall(PetscFree(reaction_force));
413   PetscFunctionReturn(PETSC_SUCCESS);
414 }
415 
416 // User provided TS Monitor
417 PetscErrorCode TSMonitor_NS(TS ts, PetscInt step_no, PetscReal time, Vec Q, void *ctx) {
418   User user = ctx;
419   PetscFunctionBeginUser;
420 
421   // Print every 'checkpoint_interval' steps
422   if (user->app_ctx->checkpoint_interval <= 0 || step_no % user->app_ctx->checkpoint_interval != 0 ||
423       (user->app_ctx->cont_steps == step_no && step_no != 0)) {
424     PetscFunctionReturn(PETSC_SUCCESS);
425   }
426 
427   PetscCall(WriteOutput(user, Q, step_no, time));
428 
429   PetscFunctionReturn(PETSC_SUCCESS);
430 }
431 
432 // TS: Create, setup, and solve
433 PetscErrorCode TSSolve_NS(DM dm, User user, AppCtx app_ctx, Physics phys, Vec *Q, PetscScalar *f_time, TS *ts) {
434   MPI_Comm    comm = user->comm;
435   TSAdapt     adapt;
436   PetscScalar final_time;
437   PetscFunctionBeginUser;
438 
439   PetscCall(TSCreate(comm, ts));
440   PetscCall(TSSetDM(*ts, dm));
441   if (phys->implicit) {
442     PetscCall(TSSetType(*ts, TSBDF));
443     if (user->op_ifunction) {
444       PetscCall(TSSetIFunction(*ts, NULL, IFunction_NS, &user));
445     } else {  // Implicit integrators can fall back to using an RHSFunction
446       PetscCall(TSSetRHSFunction(*ts, NULL, RHS_NS, &user));
447     }
448     if (user->op_ijacobian) {
449       PetscCall(DMTSSetIJacobian(dm, FormIJacobian_NS, &user));
450       if (app_ctx->amat_type) {
451         Mat Pmat, Amat;
452         PetscCall(DMCreateMatrix(dm, &Pmat));
453         PetscCall(DMSetMatType(dm, app_ctx->amat_type));
454         PetscCall(DMCreateMatrix(dm, &Amat));
455         PetscCall(TSSetIJacobian(*ts, Amat, Pmat, NULL, NULL));
456         PetscCall(MatDestroy(&Amat));
457         PetscCall(MatDestroy(&Pmat));
458       }
459     }
460   } else {
461     PetscCheck(user->op_rhs_ctx, comm, PETSC_ERR_ARG_NULL, "Problem does not provide RHSFunction");
462     PetscCall(TSSetType(*ts, TSRK));
463     PetscCall(TSRKSetType(*ts, TSRK5F));
464     PetscCall(TSSetRHSFunction(*ts, NULL, RHS_NS, &user));
465   }
466   PetscCall(TSSetMaxTime(*ts, 500. * user->units->second));
467   PetscCall(TSSetExactFinalTime(*ts, TS_EXACTFINALTIME_STEPOVER));
468   if (app_ctx->test_type == TESTTYPE_NONE) PetscCall(TSSetErrorIfStepFails(*ts, PETSC_FALSE));
469   PetscCall(TSSetTimeStep(*ts, 1.e-2 * user->units->second));
470   if (app_ctx->test_type != TESTTYPE_NONE) {
471     PetscCall(TSSetMaxSteps(*ts, 10));
472   }
473   PetscCall(TSGetAdapt(*ts, &adapt));
474   PetscCall(TSAdaptSetStepLimits(adapt, 1.e-12 * user->units->second, 1.e2 * user->units->second));
475   PetscCall(TSSetFromOptions(*ts));
476   user->time_bc_set = -1.0;   // require all BCs be updated
477   if (app_ctx->cont_steps) {  // continue from previous timestep data
478     PetscInt    count;
479     PetscViewer viewer;
480 
481     if (app_ctx->cont_time <= 0) {  // Legacy files did not include step number and time
482       PetscCall(PetscViewerBinaryOpen(comm, app_ctx->cont_time_file, FILE_MODE_READ, &viewer));
483       PetscCall(PetscViewerBinaryRead(viewer, &app_ctx->cont_time, 1, &count, PETSC_REAL));
484       PetscCall(PetscViewerDestroy(&viewer));
485       PetscCheck(app_ctx->cont_steps != -1, comm, PETSC_ERR_ARG_INCOMP,
486                  "-continue step number not specified, but checkpoint file does not contain a step number (likely written by older code version)");
487     }
488     PetscCall(TSSetTime(*ts, app_ctx->cont_time * user->units->second));
489     PetscCall(TSSetStepNumber(*ts, app_ctx->cont_steps));
490   }
491   if (app_ctx->test_type == TESTTYPE_NONE) {
492     PetscCall(TSMonitorSet(*ts, TSMonitor_NS, user, NULL));
493   }
494   if (app_ctx->wall_forces.viewer) {
495     PetscCall(TSMonitorSet(*ts, TSMonitor_WallForce, user, NULL));
496   }
497   if (app_ctx->turb_spanstats_enable) {
498     PetscCall(TSMonitorSet(*ts, TSMonitor_TurbulenceStatistics, user, NULL));
499     CeedScalar previous_time = app_ctx->cont_time * user->units->second;
500     CeedOperatorSetContextDouble(user->spanstats.op_stats_collect_ctx->op, user->spanstats.previous_time_label, &previous_time);
501   }
502   if (app_ctx->diff_filter_monitor) PetscCall(TSMonitorSet(*ts, TSMonitor_DifferentialFilter, user, NULL));
503 
504   // Solve
505   PetscReal start_time;
506   PetscInt  start_step;
507   PetscCall(TSGetTime(*ts, &start_time));
508   PetscCall(TSGetStepNumber(*ts, &start_step));
509 
510   PetscPreLoadBegin(PETSC_FALSE, "Fluids Solve");
511   PetscCall(TSSetTime(*ts, start_time));
512   PetscCall(TSSetStepNumber(*ts, start_step));
513   if (PetscPreLoadingOn) {
514     // LCOV_EXCL_START
515     SNES      snes;
516     Vec       Q_preload;
517     PetscReal rtol;
518     PetscCall(VecDuplicate(*Q, &Q_preload));
519     PetscCall(VecCopy(*Q, Q_preload));
520     PetscCall(TSGetSNES(*ts, &snes));
521     PetscCall(SNESGetTolerances(snes, NULL, &rtol, NULL, NULL, NULL));
522     PetscCall(SNESSetTolerances(snes, PETSC_DEFAULT, .99, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT));
523     PetscCall(TSSetSolution(*ts, *Q));
524     PetscCall(TSStep(*ts));
525     PetscCall(SNESSetTolerances(snes, PETSC_DEFAULT, rtol, PETSC_DEFAULT, PETSC_DEFAULT, PETSC_DEFAULT));
526     PetscCall(VecDestroy(&Q_preload));
527     // LCOV_EXCL_STOP
528   } else {
529     PetscCall(PetscBarrier((PetscObject)*ts));
530     PetscCall(TSSolve(*ts, *Q));
531   }
532   PetscPreLoadEnd();
533 
534   PetscCall(TSGetSolveTime(*ts, &final_time));
535   *f_time = final_time;
536 
537   if (app_ctx->test_type == TESTTYPE_NONE) {
538     PetscInt step_no;
539     PetscCall(TSGetStepNumber(*ts, &step_no));
540     if (user->app_ctx->checkpoint_interval > 0 || user->app_ctx->checkpoint_interval == -1) {
541       PetscCall(WriteOutput(user, *Q, step_no, final_time));
542     }
543 
544     PetscLogStage stage_id;
545     PetscStageLog stage_log;
546 
547     PetscCall(PetscLogStageGetId("Fluids Solve", &stage_id));
548     PetscCall(PetscLogGetStageLog(&stage_log));
549     PetscCall(PetscPrintf(PETSC_COMM_WORLD, "Time taken for solution (sec): %g\n", stage_log->stageInfo[stage_id].perfInfo.time));
550   }
551   PetscFunctionReturn(PETSC_SUCCESS);
552 }
553