xref: /petsc/src/ts/tutorials/ex11.c (revision ebead697dbf761eb322f829370bbe90b3bd93fa3)
1 static char help[] = "Second Order TVD Finite Volume Example.\n";
2 /*F
3 
4 We use a second order TVD finite volume method to evolve a system of PDEs. Our simple upwinded residual evaluation loops
5 over all mesh faces and uses a Riemann solver to produce the flux given the face geometry and cell values,
6 \begin{equation}
7   f_i = \mathrm{riemann}(\mathrm{phys}, p_\mathrm{centroid}, \hat n, x^L, x^R)
8 \end{equation}
9 and then update the cell values given the cell volume.
10 \begin{eqnarray}
11     f^L_i &-=& \frac{f_i}{vol^L} \\
12     f^R_i &+=& \frac{f_i}{vol^R}
13 \end{eqnarray}
14 
15 As an example, we can consider the shallow water wave equation,
16 \begin{eqnarray}
17      h_t + \nabla\cdot \left( uh                              \right) &=& 0 \\
18   (uh)_t + \nabla\cdot \left( u\otimes uh + \frac{g h^2}{2} I \right) &=& 0
19 \end{eqnarray}
20 where $h$ is wave height, $u$ is wave velocity, and $g$ is the acceleration due to gravity.
21 
22 A representative Riemann solver for the shallow water equations is given in the PhysicsRiemann_SW() function,
23 \begin{eqnarray}
24   f^{L,R}_h    &=& uh^{L,R} \cdot \hat n \\
25   f^{L,R}_{uh} &=& \frac{f^{L,R}_h}{h^{L,R}} uh^{L,R} + g (h^{L,R})^2 \hat n \\
26   c^{L,R}      &=& \sqrt{g h^{L,R}} \\
27   s            &=& \max\left( \left|\frac{uh^L \cdot \hat n}{h^L}\right| + c^L, \left|\frac{uh^R \cdot \hat n}{h^R}\right| + c^R \right) \\
28   f_i          &=& \frac{A_\mathrm{face}}{2} \left( f^L_i + f^R_i + s \left( x^L_i - x^R_i \right) \right)
29 \end{eqnarray}
30 where $c$ is the local gravity wave speed and $f_i$ is a Rusanov flux.
31 
32 The more sophisticated residual evaluation in RHSFunctionLocal_LS() uses a least-squares fit to a quadratic polynomial
33 over a neighborhood of the given element.
34 
35 The mesh is read in from an ExodusII file, usually generated by Cubit.
36 F*/
37 #include <petscdmplex.h>
38 #include <petscdmforest.h>
39 #include <petscds.h>
40 #include <petscts.h>
41 
42 #define DIM 2                   /* Geometric dimension */
43 
44 static PetscFunctionList PhysicsList, PhysicsRiemannList_SW;
45 
46 /* Represents continuum physical equations. */
47 typedef struct _n_Physics *Physics;
48 
49 /* Physical model includes boundary conditions, initial conditions, and functionals of interest. It is
50  * discretization-independent, but its members depend on the scenario being solved. */
51 typedef struct _n_Model *Model;
52 
53 /* 'User' implements a discretization of a continuous model. */
54 typedef struct _n_User *User;
55 typedef PetscErrorCode (*SolutionFunction)(Model,PetscReal,const PetscReal*,PetscScalar*,void*);
56 typedef PetscErrorCode (*SetUpBCFunction)(DM,PetscDS,Physics);
57 typedef PetscErrorCode (*FunctionalFunction)(Model,PetscReal,const PetscReal*,const PetscScalar*,PetscReal*,void*);
58 typedef PetscErrorCode (*SetupFields)(Physics,PetscSection);
59 static PetscErrorCode ModelSolutionSetDefault(Model,SolutionFunction,void*);
60 static PetscErrorCode ModelFunctionalRegister(Model,const char*,PetscInt*,FunctionalFunction,void*);
61 static PetscErrorCode OutputVTK(DM,const char*,PetscViewer*);
62 
63 struct FieldDescription {
64   const char *name;
65   PetscInt dof;
66 };
67 
68 typedef struct _n_FunctionalLink *FunctionalLink;
69 struct _n_FunctionalLink {
70   char               *name;
71   FunctionalFunction func;
72   void               *ctx;
73   PetscInt           offset;
74   FunctionalLink     next;
75 };
76 
77 struct _n_Physics {
78   PetscRiemannFunc riemann;
79   PetscInt         dof;          /* number of degrees of freedom per cell */
80   PetscReal        maxspeed;     /* kludge to pick initial time step, need to add monitoring and step control */
81   void             *data;
82   PetscInt         nfields;
83   const struct FieldDescription *field_desc;
84 };
85 
86 struct _n_Model {
87   MPI_Comm         comm;        /* Does not do collective communicaton, but some error conditions can be collective */
88   Physics          physics;
89   FunctionalLink   functionalRegistry;
90   PetscInt         maxComputed;
91   PetscInt         numMonitored;
92   FunctionalLink   *functionalMonitored;
93   PetscInt         numCall;
94   FunctionalLink   *functionalCall;
95   SolutionFunction solution;
96   SetUpBCFunction  setupbc;
97   void             *solutionctx;
98   PetscReal        maxspeed;    /* estimate of global maximum speed (for CFL calculation) */
99   PetscReal        bounds[2*DIM];
100   PetscErrorCode   (*errorIndicator)(PetscInt, PetscReal, PetscInt, const PetscScalar[], const PetscScalar[], PetscReal *, void *);
101   void             *errorCtx;
102 };
103 
104 struct _n_User {
105   PetscInt vtkInterval;   /* For monitor */
106   char outputBasename[PETSC_MAX_PATH_LEN]; /* Basename for output files */
107   PetscInt monitorStepOffset;
108   Model    model;
109   PetscBool vtkmon;
110 };
111 
112 static inline PetscReal DotDIMReal(const PetscReal *x,const PetscReal *y)
113 {
114   PetscInt  i;
115   PetscReal prod=0.0;
116 
117   for (i=0; i<DIM; i++) prod += x[i]*y[i];
118   return prod;
119 }
120 static inline PetscReal NormDIM(const PetscReal *x) { return PetscSqrtReal(PetscAbsReal(DotDIMReal(x,x))); }
121 
122 static inline PetscReal Dot2Real(const PetscReal *x,const PetscReal *y) { return x[0]*y[0] + x[1]*y[1];}
123 static inline PetscReal Norm2Real(const PetscReal *x) { return PetscSqrtReal(PetscAbsReal(Dot2Real(x,x)));}
124 static inline void Normalize2Real(PetscReal *x) { PetscReal a = 1./Norm2Real(x); x[0] *= a; x[1] *= a; }
125 static inline void Waxpy2Real(PetscReal a,const PetscReal *x,const PetscReal *y,PetscReal *w) { w[0] = a*x[0] + y[0]; w[1] = a*x[1] + y[1]; }
126 static inline void Scale2Real(PetscReal a,const PetscReal *x,PetscReal *y) { y[0] = a*x[0]; y[1] = a*x[1]; }
127 
128 /******************* Advect ********************/
129 typedef enum {ADVECT_SOL_TILTED,ADVECT_SOL_BUMP,ADVECT_SOL_BUMP_CAVITY} AdvectSolType;
130 static const char *const AdvectSolTypes[] = {"TILTED","BUMP","BUMP_CAVITY","AdvectSolType","ADVECT_SOL_",0};
131 typedef enum {ADVECT_SOL_BUMP_CONE,ADVECT_SOL_BUMP_COS} AdvectSolBumpType;
132 static const char *const AdvectSolBumpTypes[] = {"CONE","COS","AdvectSolBumpType","ADVECT_SOL_BUMP_",0};
133 
134 typedef struct {
135   PetscReal wind[DIM];
136 } Physics_Advect_Tilted;
137 typedef struct {
138   PetscReal         center[DIM];
139   PetscReal         radius;
140   AdvectSolBumpType type;
141 } Physics_Advect_Bump;
142 
143 typedef struct {
144   PetscReal     inflowState;
145   AdvectSolType soltype;
146   union {
147     Physics_Advect_Tilted tilted;
148     Physics_Advect_Bump   bump;
149   } sol;
150   struct {
151     PetscInt Solution;
152     PetscInt Error;
153   } functional;
154 } Physics_Advect;
155 
156 static const struct FieldDescription PhysicsFields_Advect[] = {{"U",1},{NULL,0}};
157 
158 static PetscErrorCode PhysicsBoundary_Advect_Inflow(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *xI, PetscScalar *xG, void *ctx)
159 {
160   Physics        phys    = (Physics)ctx;
161   Physics_Advect *advect = (Physics_Advect*)phys->data;
162 
163   PetscFunctionBeginUser;
164   xG[0] = advect->inflowState;
165   PetscFunctionReturn(0);
166 }
167 
168 static PetscErrorCode PhysicsBoundary_Advect_Outflow(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *xI, PetscScalar *xG, void *ctx)
169 {
170   PetscFunctionBeginUser;
171   xG[0] = xI[0];
172   PetscFunctionReturn(0);
173 }
174 
175 static void PhysicsRiemann_Advect(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const PetscScalar *xL, const PetscScalar *xR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, Physics phys)
176 {
177   Physics_Advect *advect = (Physics_Advect*)phys->data;
178   PetscReal      wind[DIM],wn;
179 
180   switch (advect->soltype) {
181   case ADVECT_SOL_TILTED: {
182     Physics_Advect_Tilted *tilted = &advect->sol.tilted;
183     wind[0] = tilted->wind[0];
184     wind[1] = tilted->wind[1];
185   } break;
186   case ADVECT_SOL_BUMP:
187     wind[0] = -qp[1];
188     wind[1] = qp[0];
189     break;
190   case ADVECT_SOL_BUMP_CAVITY:
191     {
192       PetscInt  i;
193       PetscReal comp2[3] = {0.,0.,0.}, rad2;
194 
195       rad2 = 0.;
196       for (i = 0; i < dim; i++) {
197         comp2[i] = qp[i] * qp[i];
198         rad2    += comp2[i];
199       }
200 
201       wind[0] = -qp[1];
202       wind[1] = qp[0];
203       if (rad2 > 1.) {
204         PetscInt  maxI = 0;
205         PetscReal maxComp2 = comp2[0];
206 
207         for (i = 1; i < dim; i++) {
208           if (comp2[i] > maxComp2) {
209             maxI     = i;
210             maxComp2 = comp2[i];
211           }
212         }
213         wind[maxI] = 0.;
214       }
215     }
216     break;
217   default:
218   {
219     PetscInt i;
220     for (i = 0; i < DIM; ++i) wind[i] = 0.0;
221   }
222   /* default: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for solution type %s",AdvectSolBumpTypes[advect->soltype]); */
223   }
224   wn      = Dot2Real(wind, n);
225   flux[0] = (wn > 0 ? xL[0] : xR[0]) * wn;
226 }
227 
228 static PetscErrorCode PhysicsSolution_Advect(Model mod,PetscReal time,const PetscReal *x,PetscScalar *u,void *ctx)
229 {
230   Physics        phys    = (Physics)ctx;
231   Physics_Advect *advect = (Physics_Advect*)phys->data;
232 
233   PetscFunctionBeginUser;
234   switch (advect->soltype) {
235   case ADVECT_SOL_TILTED: {
236     PetscReal             x0[DIM];
237     Physics_Advect_Tilted *tilted = &advect->sol.tilted;
238     Waxpy2Real(-time,tilted->wind,x,x0);
239     if (x0[1] > 0) u[0] = 1.*x[0] + 3.*x[1];
240     else u[0] = advect->inflowState;
241   } break;
242   case ADVECT_SOL_BUMP_CAVITY:
243   case ADVECT_SOL_BUMP: {
244     Physics_Advect_Bump *bump = &advect->sol.bump;
245     PetscReal           x0[DIM],v[DIM],r,cost,sint;
246     cost  = PetscCosReal(time);
247     sint  = PetscSinReal(time);
248     x0[0] = cost*x[0] + sint*x[1];
249     x0[1] = -sint*x[0] + cost*x[1];
250     Waxpy2Real(-1,bump->center,x0,v);
251     r = Norm2Real(v);
252     switch (bump->type) {
253     case ADVECT_SOL_BUMP_CONE:
254       u[0] = PetscMax(1 - r/bump->radius,0);
255       break;
256     case ADVECT_SOL_BUMP_COS:
257       u[0] = 0.5 + 0.5*PetscCosReal(PetscMin(r/bump->radius,1)*PETSC_PI);
258       break;
259     }
260   } break;
261   default: SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"Unknown solution type");
262   }
263   PetscFunctionReturn(0);
264 }
265 
266 static PetscErrorCode PhysicsFunctional_Advect(Model mod,PetscReal time,const PetscReal *x,const PetscScalar *y,PetscReal *f,void *ctx)
267 {
268   Physics        phys    = (Physics)ctx;
269   Physics_Advect *advect = (Physics_Advect*)phys->data;
270   PetscScalar    yexact[1] = {0.0};
271 
272   PetscFunctionBeginUser;
273   PetscCall(PhysicsSolution_Advect(mod,time,x,yexact,phys));
274   f[advect->functional.Solution] = PetscRealPart(y[0]);
275   f[advect->functional.Error] = PetscAbsScalar(y[0]-yexact[0]);
276   PetscFunctionReturn(0);
277 }
278 
279 static PetscErrorCode SetUpBC_Advect(DM dm, PetscDS prob, Physics phys)
280 {
281   const PetscInt inflowids[] = {100,200,300},outflowids[] = {101};
282   DMLabel        label;
283 
284   PetscFunctionBeginUser;
285   /* Register "canned" boundary conditions and defaults for where to apply. */
286   PetscCall(DMGetLabel(dm, "Face Sets", &label));
287   PetscCall(PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "inflow",  label, PETSC_STATIC_ARRAY_LENGTH(inflowids),  inflowids,  0, 0, NULL, (void (*)(void)) PhysicsBoundary_Advect_Inflow, NULL,  phys, NULL));
288   PetscCall(PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "outflow", label, PETSC_STATIC_ARRAY_LENGTH(outflowids), outflowids, 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Advect_Outflow, NULL, phys, NULL));
289   PetscFunctionReturn(0);
290 }
291 
292 static PetscErrorCode PhysicsCreate_Advect(Model mod,Physics phys,PetscOptionItems *PetscOptionsObject)
293 {
294   Physics_Advect *advect;
295 
296   PetscFunctionBeginUser;
297   phys->field_desc = PhysicsFields_Advect;
298   phys->riemann    = (PetscRiemannFunc)PhysicsRiemann_Advect;
299   PetscCall(PetscNew(&advect));
300   phys->data       = advect;
301   mod->setupbc = SetUpBC_Advect;
302 
303   PetscOptionsHeadBegin(PetscOptionsObject,"Advect options");
304   {
305     PetscInt two = 2,dof = 1;
306     advect->soltype = ADVECT_SOL_TILTED;
307     PetscCall(PetscOptionsEnum("-advect_sol_type","solution type","",AdvectSolTypes,(PetscEnum)advect->soltype,(PetscEnum*)&advect->soltype,NULL));
308     switch (advect->soltype) {
309     case ADVECT_SOL_TILTED: {
310       Physics_Advect_Tilted *tilted = &advect->sol.tilted;
311       two = 2;
312       tilted->wind[0] = 0.0;
313       tilted->wind[1] = 1.0;
314       PetscCall(PetscOptionsRealArray("-advect_tilted_wind","background wind vx,vy","",tilted->wind,&two,NULL));
315       advect->inflowState = -2.0;
316       PetscCall(PetscOptionsRealArray("-advect_tilted_inflow","Inflow state","",&advect->inflowState,&dof,NULL));
317       phys->maxspeed = Norm2Real(tilted->wind);
318     } break;
319     case ADVECT_SOL_BUMP_CAVITY:
320     case ADVECT_SOL_BUMP: {
321       Physics_Advect_Bump *bump = &advect->sol.bump;
322       two = 2;
323       bump->center[0] = 2.;
324       bump->center[1] = 0.;
325       PetscCall(PetscOptionsRealArray("-advect_bump_center","location of center of bump x,y","",bump->center,&two,NULL));
326       bump->radius = 0.9;
327       PetscCall(PetscOptionsReal("-advect_bump_radius","radius of bump","",bump->radius,&bump->radius,NULL));
328       bump->type = ADVECT_SOL_BUMP_CONE;
329       PetscCall(PetscOptionsEnum("-advect_bump_type","type of bump","",AdvectSolBumpTypes,(PetscEnum)bump->type,(PetscEnum*)&bump->type,NULL));
330       phys->maxspeed = 3.;       /* radius of mesh, kludge */
331     } break;
332     }
333   }
334   PetscOptionsHeadEnd();
335   /* Initial/transient solution with default boundary conditions */
336   PetscCall(ModelSolutionSetDefault(mod,PhysicsSolution_Advect,phys));
337   /* Register "canned" functionals */
338   PetscCall(ModelFunctionalRegister(mod,"Solution",&advect->functional.Solution,PhysicsFunctional_Advect,phys));
339   PetscCall(ModelFunctionalRegister(mod,"Error",&advect->functional.Error,PhysicsFunctional_Advect,phys));
340   PetscFunctionReturn(0);
341 }
342 
343 /******************* Shallow Water ********************/
344 typedef struct {
345   PetscReal gravity;
346   PetscReal boundaryHeight;
347   struct {
348     PetscInt Height;
349     PetscInt Speed;
350     PetscInt Energy;
351   } functional;
352 } Physics_SW;
353 typedef struct {
354   PetscReal h;
355   PetscReal uh[DIM];
356 } SWNode;
357 typedef union {
358   SWNode    swnode;
359   PetscReal vals[DIM+1];
360 } SWNodeUnion;
361 
362 static const struct FieldDescription PhysicsFields_SW[] = {{"Height",1},{"Momentum",DIM},{NULL,0}};
363 
364 /*
365  * h_t + div(uh) = 0
366  * (uh)_t + div (u\otimes uh + g h^2 / 2 I) = 0
367  *
368  * */
369 static PetscErrorCode SWFlux(Physics phys,const PetscReal *n,const SWNode *x,SWNode *f)
370 {
371   Physics_SW  *sw = (Physics_SW*)phys->data;
372   PetscReal   uhn,u[DIM];
373   PetscInt     i;
374 
375   PetscFunctionBeginUser;
376   Scale2Real(1./x->h,x->uh,u);
377   uhn  = x->uh[0] * n[0] + x->uh[1] * n[1];
378   f->h = uhn;
379   for (i=0; i<DIM; i++) f->uh[i] = u[i] * uhn + sw->gravity * PetscSqr(x->h) * n[i];
380   PetscFunctionReturn(0);
381 }
382 
383 static PetscErrorCode PhysicsBoundary_SW_Wall(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *xI, PetscScalar *xG, void *ctx)
384 {
385   PetscFunctionBeginUser;
386   xG[0] = xI[0];
387   xG[1] = -xI[1];
388   xG[2] = -xI[2];
389   PetscFunctionReturn(0);
390 }
391 
392 static void PhysicsRiemann_SW_HLL(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const PetscScalar *xL, const PetscScalar *xR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, Physics phys)
393 {
394   Physics_SW *sw = (Physics_SW *) phys->data;
395   PetscReal aL, aR;
396   PetscReal nn[DIM];
397 #if !defined(PETSC_USE_COMPLEX)
398   const SWNode *uL = (const SWNode *) xL, *uR = (const SWNode *) xR;
399 #else
400   SWNodeUnion  uLreal, uRreal;
401   const SWNode *uL = &uLreal.swnode;
402   const SWNode *uR = &uRreal.swnode;
403 #endif
404   SWNodeUnion fL, fR;
405   PetscInt i;
406   PetscReal zero = 0.;
407 
408 #if defined(PETSC_USE_COMPLEX)
409   uLreal.swnode.h = 0; uRreal.swnode.h = 0;
410   for (i = 0; i < 1+dim; i++) uLreal.vals[i] = PetscRealPart(xL[i]);
411   for (i = 0; i < 1+dim; i++) uRreal.vals[i] = PetscRealPart(xR[i]);
412 #endif
413   if (uL->h <= 0 || uR->h <= 0) {
414     for (i = 0; i < 1 + dim; i++) flux[i] = zero;
415     return;
416   } /* SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Reconstructed thickness is negative"); */
417   nn[0] = n[0];
418   nn[1] = n[1];
419   Normalize2Real(nn);
420   SWFlux(phys, nn, uL, &(fL.swnode));
421   SWFlux(phys, nn, uR, &(fR.swnode));
422   /* gravity wave speed */
423   aL = PetscSqrtReal(sw->gravity * uL->h);
424   aR = PetscSqrtReal(sw->gravity * uR->h);
425   // Defining u_tilda and v_tilda as u and v
426   PetscReal u_L, u_R;
427   u_L = Dot2Real(uL->uh,nn)/uL->h;
428   u_R = Dot2Real(uR->uh,nn)/uR->h;
429   PetscReal sL, sR;
430   sL = PetscMin(u_L - aL, u_R - aR);
431   sR = PetscMax(u_L + aL, u_R + aR);
432   if (sL > zero) {
433     for (i = 0; i < dim + 1; i++) {
434       flux[i] = fL.vals[i] * Norm2Real(n);
435     }
436   } else if (sR < zero) {
437     for (i = 0; i < dim + 1; i++) {
438       flux[i] = fR.vals[i] * Norm2Real(n);
439     }
440   } else {
441     for (i = 0; i < dim + 1; i++) {
442       flux[i] = ((sR * fL.vals[i] - sL * fR.vals[i] + sR * sL * (xR[i] - xL[i])) / (sR - sL)) * Norm2Real(n);
443     }
444   }
445 }
446 
447 static void PhysicsRiemann_SW_Rusanov(PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n, const PetscScalar *xL, const PetscScalar *xR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, Physics phys)
448 {
449   Physics_SW   *sw = (Physics_SW*)phys->data;
450   PetscReal    cL,cR,speed;
451   PetscReal    nn[DIM];
452 #if !defined(PETSC_USE_COMPLEX)
453   const SWNode *uL = (const SWNode*)xL,*uR = (const SWNode*)xR;
454 #else
455   SWNodeUnion  uLreal, uRreal;
456   const SWNode *uL = &uLreal.swnode;
457   const SWNode *uR = &uRreal.swnode;
458 #endif
459   SWNodeUnion  fL,fR;
460   PetscInt     i;
461   PetscReal    zero=0.;
462 
463 #if defined(PETSC_USE_COMPLEX)
464   uLreal.swnode.h = 0; uRreal.swnode.h = 0;
465   for (i = 0; i < 1+dim; i++) uLreal.vals[i] = PetscRealPart(xL[i]);
466   for (i = 0; i < 1+dim; i++) uRreal.vals[i] = PetscRealPart(xR[i]);
467 #endif
468   if (uL->h < 0 || uR->h < 0) {for (i=0; i<1+dim; i++) flux[i] = zero/zero; return;} /* reconstructed thickness is negative */
469   nn[0] = n[0];
470   nn[1] = n[1];
471   Normalize2Real(nn);
472   SWFlux(phys,nn,uL,&(fL.swnode));
473   SWFlux(phys,nn,uR,&(fR.swnode));
474   cL    = PetscSqrtReal(sw->gravity*uL->h);
475   cR    = PetscSqrtReal(sw->gravity*uR->h); /* gravity wave speed */
476   speed = PetscMax(PetscAbsReal(Dot2Real(uL->uh,nn)/uL->h) + cL,PetscAbsReal(Dot2Real(uR->uh,nn)/uR->h) + cR);
477   for (i=0; i<1+dim; i++) flux[i] = (0.5*(fL.vals[i] + fR.vals[i]) + 0.5*speed*(xL[i] - xR[i])) * Norm2Real(n);
478 }
479 
480 static PetscErrorCode PhysicsSolution_SW(Model mod,PetscReal time,const PetscReal *x,PetscScalar *u,void *ctx)
481 {
482   PetscReal dx[2],r,sigma;
483 
484   PetscFunctionBeginUser;
485   PetscCheck(time == 0.0,mod->comm,PETSC_ERR_SUP,"No solution known for time %g",(double)time);
486   dx[0] = x[0] - 1.5;
487   dx[1] = x[1] - 1.0;
488   r     = Norm2Real(dx);
489   sigma = 0.5;
490   u[0]  = 1 + 2*PetscExpReal(-PetscSqr(r)/(2*PetscSqr(sigma)));
491   u[1]  = 0.0;
492   u[2]  = 0.0;
493   PetscFunctionReturn(0);
494 }
495 
496 static PetscErrorCode PhysicsFunctional_SW(Model mod,PetscReal time,const PetscReal *coord,const PetscScalar *xx,PetscReal *f,void *ctx)
497 {
498   Physics      phys = (Physics)ctx;
499   Physics_SW   *sw  = (Physics_SW*)phys->data;
500   const SWNode *x   = (const SWNode*)xx;
501   PetscReal  u[2];
502   PetscReal    h;
503 
504   PetscFunctionBeginUser;
505   h = x->h;
506   Scale2Real(1./x->h,x->uh,u);
507   f[sw->functional.Height] = h;
508   f[sw->functional.Speed]  = Norm2Real(u) + PetscSqrtReal(sw->gravity*h);
509   f[sw->functional.Energy] = 0.5*(Dot2Real(x->uh,u) + sw->gravity*PetscSqr(h));
510   PetscFunctionReturn(0);
511 }
512 
513 static PetscErrorCode SetUpBC_SW(DM dm, PetscDS prob,Physics phys)
514 {
515   const PetscInt wallids[] = {100,101,200,300};
516   DMLabel        label;
517 
518   PetscFunctionBeginUser;
519   PetscCall(DMGetLabel(dm, "Face Sets", &label));
520   PetscCall(PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall", label, PETSC_STATIC_ARRAY_LENGTH(wallids), wallids, 0, 0, NULL, (void (*)(void)) PhysicsBoundary_SW_Wall, NULL, phys, NULL));
521   PetscFunctionReturn(0);
522 }
523 
524 static PetscErrorCode PhysicsCreate_SW(Model mod,Physics phys,PetscOptionItems *PetscOptionsObject)
525 {
526   Physics_SW     *sw;
527   char           sw_riemann[64] = "rusanov";
528 
529   PetscFunctionBeginUser;
530   phys->field_desc = PhysicsFields_SW;
531   PetscCall(PetscNew(&sw));
532   phys->data    = sw;
533   mod->setupbc  = SetUpBC_SW;
534 
535   PetscFunctionListAdd(&PhysicsRiemannList_SW, "rusanov", PhysicsRiemann_SW_Rusanov);
536   PetscFunctionListAdd(&PhysicsRiemannList_SW, "hll", PhysicsRiemann_SW_HLL);
537 
538   PetscOptionsHeadBegin(PetscOptionsObject,"SW options");
539   {
540     void (*PhysicsRiemann_SW)(PetscInt, PetscInt, const PetscReal *, const PetscReal *, const PetscScalar *, const PetscScalar *, PetscInt, const PetscScalar, PetscScalar *, Physics);
541     sw->gravity = 1.0;
542     PetscCall(PetscOptionsReal("-sw_gravity","Gravitational constant","",sw->gravity,&sw->gravity,NULL));
543     PetscCall(PetscOptionsFList("-sw_riemann","Riemann solver","",PhysicsRiemannList_SW,sw_riemann,sw_riemann,sizeof sw_riemann,NULL));
544     PetscCall(PetscFunctionListFind(PhysicsRiemannList_SW,sw_riemann,&PhysicsRiemann_SW));
545     phys->riemann = (PetscRiemannFunc) PhysicsRiemann_SW;
546   }
547   PetscOptionsHeadEnd();
548   phys->maxspeed = PetscSqrtReal(2.0*sw->gravity); /* Mach 1 for depth of 2 */
549 
550   PetscCall(ModelSolutionSetDefault(mod,PhysicsSolution_SW,phys));
551   PetscCall(ModelFunctionalRegister(mod,"Height",&sw->functional.Height,PhysicsFunctional_SW,phys));
552   PetscCall(ModelFunctionalRegister(mod,"Speed",&sw->functional.Speed,PhysicsFunctional_SW,phys));
553   PetscCall(ModelFunctionalRegister(mod,"Energy",&sw->functional.Energy,PhysicsFunctional_SW,phys));
554 
555   PetscFunctionReturn(0);
556 }
557 
558 /******************* Euler Density Shock (EULER_IV_SHOCK,EULER_SS_SHOCK) ********************/
559 /* An initial-value and self-similar solutions of the compressible Euler equations */
560 /* Ravi Samtaney and D. I. Pullin */
561 /* Phys. Fluids 8, 2650 (1996); http://dx.doi.org/10.1063/1.869050 */
562 typedef enum {EULER_PAR_GAMMA,EULER_PAR_RHOR,EULER_PAR_AMACH,EULER_PAR_ITANA,EULER_PAR_SIZE} EulerParamIdx;
563 typedef enum {EULER_IV_SHOCK,EULER_SS_SHOCK,EULER_SHOCK_TUBE,EULER_LINEAR_WAVE} EulerType;
564 typedef struct {
565   PetscReal r;
566   PetscReal ru[DIM];
567   PetscReal E;
568 } EulerNode;
569 typedef union {
570   EulerNode eulernode;
571   PetscReal vals[DIM+2];
572 } EulerNodeUnion;
573 typedef PetscErrorCode (*EquationOfState)(const PetscReal*, const EulerNode*, PetscReal*);
574 typedef struct {
575   EulerType       type;
576   PetscReal       pars[EULER_PAR_SIZE];
577   EquationOfState sound;
578   struct {
579     PetscInt Density;
580     PetscInt Momentum;
581     PetscInt Energy;
582     PetscInt Pressure;
583     PetscInt Speed;
584   } monitor;
585 } Physics_Euler;
586 
587 static const struct FieldDescription PhysicsFields_Euler[] = {{"Density",1},{"Momentum",DIM},{"Energy",1},{NULL,0}};
588 
589 /* initial condition */
590 int initLinearWave(EulerNode *ux, const PetscReal gamma, const PetscReal coord[], const PetscReal Lx);
591 static PetscErrorCode PhysicsSolution_Euler(Model mod, PetscReal time, const PetscReal *x, PetscScalar *u, void *ctx)
592 {
593   PetscInt i;
594   Physics         phys = (Physics)ctx;
595   Physics_Euler   *eu  = (Physics_Euler*)phys->data;
596   EulerNode       *uu  = (EulerNode*)u;
597   PetscReal        p0,gamma,c;
598   PetscFunctionBeginUser;
599   PetscCheck(time == 0.0,mod->comm,PETSC_ERR_SUP,"No solution known for time %g",(double)time);
600 
601   for (i=0; i<DIM; i++) uu->ru[i] = 0.0; /* zero out initial velocity */
602   /* set E and rho */
603   gamma = eu->pars[EULER_PAR_GAMMA];
604 
605   if (eu->type==EULER_IV_SHOCK || eu->type==EULER_SS_SHOCK) {
606     /******************* Euler Density Shock ********************/
607     /* On initial-value and self-similar solutions of the compressible Euler equations */
608     /* Ravi Samtaney and D. I. Pullin */
609     /* Phys. Fluids 8, 2650 (1996); http://dx.doi.org/10.1063/1.869050 */
610     /* initial conditions 1: left of shock, 0: left of discontinuity 2: right of discontinuity,  */
611     p0 = 1.;
612     if (x[0] < 0.0 + x[1]*eu->pars[EULER_PAR_ITANA]) {
613       if (x[0] < mod->bounds[0]*0.5) { /* left of shock (1) */
614         PetscReal amach,rho,press,gas1,p1;
615         amach = eu->pars[EULER_PAR_AMACH];
616         rho = 1.;
617         press = p0;
618         p1 = press*(1.0+2.0*gamma/(gamma+1.0)*(amach*amach-1.0));
619         gas1 = (gamma-1.0)/(gamma+1.0);
620         uu->r = rho*(p1/press+gas1)/(gas1*p1/press+1.0);
621         uu->ru[0]   = ((uu->r - rho)*PetscSqrtReal(gamma*press/rho)*amach);
622         uu->E = p1/(gamma-1.0) + .5/uu->r*uu->ru[0]*uu->ru[0];
623       }
624       else { /* left of discontinuity (0) */
625         uu->r = 1.; /* rho = 1 */
626         uu->E = p0/(gamma-1.0);
627       }
628     }
629     else { /* right of discontinuity (2) */
630       uu->r = eu->pars[EULER_PAR_RHOR];
631       uu->E = p0/(gamma-1.0);
632     }
633   }
634   else if (eu->type==EULER_SHOCK_TUBE) {
635     /* For (x<x0) set (rho,u,p)=(8,0,10) and for (x>x0) set (rho,u,p)=(1,0,1). Choose x0 to the midpoint of the domain in the x-direction. */
636     if (x[0] < 0.0) {
637       uu->r = 8.;
638       uu->E = 10./(gamma-1.);
639     }
640     else {
641       uu->r = 1.;
642       uu->E = 1./(gamma-1.);
643     }
644   }
645   else if (eu->type==EULER_LINEAR_WAVE) {
646     initLinearWave( uu, gamma, x, mod->bounds[1] - mod->bounds[0]);
647   }
648   else SETERRQ(mod->comm,PETSC_ERR_SUP,"Unknown type %d",eu->type);
649 
650   /* set phys->maxspeed: (mod->maxspeed = phys->maxspeed) in main; */
651   eu->sound(&gamma,uu,&c);
652   c = (uu->ru[0]/uu->r) + c;
653   if (c > phys->maxspeed) phys->maxspeed = c;
654 
655   PetscFunctionReturn(0);
656 }
657 
658 static PetscErrorCode Pressure_PG(const PetscReal gamma,const EulerNode *x,PetscReal *p)
659 {
660   PetscReal ru2;
661 
662   PetscFunctionBeginUser;
663   ru2  = DotDIMReal(x->ru,x->ru);
664   (*p)=(x->E - 0.5*ru2/x->r)*(gamma - 1.0); /* (E - rho V^2/2)(gamma-1) = e rho (gamma-1) */
665   PetscFunctionReturn(0);
666 }
667 
668 static PetscErrorCode SpeedOfSound_PG(const PetscReal *gamma, const EulerNode *x, PetscReal *c)
669 {
670   PetscReal p;
671 
672   PetscFunctionBeginUser;
673   Pressure_PG(*gamma,x,&p);
674   PetscCheck(p>=0.,PETSC_COMM_WORLD,PETSC_ERR_SUP,"negative pressure time %g -- NEED TO FIX!!!!!!",(double) p);
675   /* pars[EULER_PAR_GAMMA] = heat capacity ratio */
676   (*c)=PetscSqrtReal(*gamma * p / x->r);
677   PetscFunctionReturn(0);
678 }
679 
680 /*
681  * x = (rho,rho*(u_1),...,rho*e)^T
682  * x_t+div(f_1(x))+...+div(f_DIM(x)) = 0
683  *
684  * f_i(x) = u_i*x+(0,0,...,p,...,p*u_i)^T
685  *
686  */
687 static PetscErrorCode EulerFlux(Physics phys,const PetscReal *n,const EulerNode *x,EulerNode *f)
688 {
689   Physics_Euler *eu = (Physics_Euler*)phys->data;
690   PetscReal     nu,p;
691   PetscInt      i;
692 
693   PetscFunctionBeginUser;
694   Pressure_PG(eu->pars[EULER_PAR_GAMMA],x,&p);
695   nu = DotDIMReal(x->ru,n);
696   f->r = nu;   /* A rho u */
697   nu /= x->r;  /* A u */
698   for (i=0; i<DIM; i++) f->ru[i] = nu * x->ru[i] + n[i]*p;  /* r u^2 + p */
699   f->E = nu * (x->E + p); /* u(e+p) */
700   PetscFunctionReturn(0);
701 }
702 
703 /* PetscReal* => EulerNode* conversion */
704 static PetscErrorCode PhysicsBoundary_Euler_Wall(PetscReal time, const PetscReal *c, const PetscReal *n, const PetscScalar *a_xI, PetscScalar *a_xG, void *ctx)
705 {
706   PetscInt    i;
707   const EulerNode *xI = (const EulerNode*)a_xI;
708   EulerNode       *xG = (EulerNode*)a_xG;
709   Physics         phys = (Physics)ctx;
710   Physics_Euler   *eu  = (Physics_Euler*)phys->data;
711   PetscFunctionBeginUser;
712   xG->r = xI->r;           /* ghost cell density - same */
713   xG->E = xI->E;           /* ghost cell energy - same */
714   if (n[1] != 0.) {        /* top and bottom */
715     xG->ru[0] =  xI->ru[0]; /* copy tang to wall */
716     xG->ru[1] = -xI->ru[1]; /* reflect perp to t/b wall */
717   }
718   else { /* sides */
719     for (i=0; i<DIM; i++) xG->ru[i] = xI->ru[i]; /* copy */
720   }
721   if (eu->type == EULER_LINEAR_WAVE) { /* debug */
722 #if 0
723     PetscPrintf(PETSC_COMM_WORLD,"%s coord=%g,%g\n",PETSC_FUNCTION_NAME,(double)c[0],(double)c[1]);
724 #endif
725   }
726   PetscFunctionReturn(0);
727 }
728 int godunovflux( const PetscScalar *ul, const PetscScalar *ur, PetscScalar *flux, const PetscReal *nn, const int *ndim, const PetscReal *gamma);
729 /* PetscReal* => EulerNode* conversion */
730 static void PhysicsRiemann_Euler_Godunov( PetscInt dim, PetscInt Nf, const PetscReal *qp, const PetscReal *n,
731                                           const PetscScalar *xL, const PetscScalar *xR, PetscInt numConstants, const PetscScalar constants[], PetscScalar *flux, Physics phys)
732 {
733   Physics_Euler   *eu = (Physics_Euler*)phys->data;
734   PetscReal       cL,cR,speed,velL,velR,nn[DIM],s2;
735   PetscInt        i;
736   PetscErrorCode  ierr;
737 
738   PetscFunctionBeginUser;
739   for (i=0,s2=0.; i<DIM; i++) {
740     nn[i] = n[i];
741     s2 += nn[i]*nn[i];
742   }
743   s2 = PetscSqrtReal(s2); /* |n|_2 = sum(n^2)^1/2 */
744   for (i=0.; i<DIM; i++) nn[i] /= s2;
745   if (0) { /* Rusanov */
746     const EulerNode *uL = (const EulerNode*)xL,*uR = (const EulerNode*)xR;
747     EulerNodeUnion  fL,fR;
748     EulerFlux(phys,nn,uL,&(fL.eulernode));
749     EulerFlux(phys,nn,uR,&(fR.eulernode));
750     ierr = eu->sound(&eu->pars[EULER_PAR_GAMMA],uL,&cL);if (ierr) exit(13);
751     ierr = eu->sound(&eu->pars[EULER_PAR_GAMMA],uR,&cR);if (ierr) exit(14);
752     velL = DotDIMReal(uL->ru,nn)/uL->r;
753     velR = DotDIMReal(uR->ru,nn)/uR->r;
754     speed = PetscMax(velR + cR, velL + cL);
755     for (i=0; i<2+dim; i++) flux[i] = 0.5*((fL.vals[i]+fR.vals[i]) + speed*(xL[i] - xR[i]))*s2;
756   }
757   else {
758     int dim = DIM;
759     /* int iwave =  */
760     godunovflux(xL, xR, flux, nn, &dim, &eu->pars[EULER_PAR_GAMMA]);
761     for (i=0; i<2+dim; i++) flux[i] *= s2;
762   }
763   PetscFunctionReturnVoid();
764 }
765 
766 static PetscErrorCode PhysicsFunctional_Euler(Model mod,PetscReal time,const PetscReal *coord,const PetscScalar *xx,PetscReal *f,void *ctx)
767 {
768   Physics         phys = (Physics)ctx;
769   Physics_Euler   *eu  = (Physics_Euler*)phys->data;
770   const EulerNode *x   = (const EulerNode*)xx;
771   PetscReal       p;
772 
773   PetscFunctionBeginUser;
774   f[eu->monitor.Density]  = x->r;
775   f[eu->monitor.Momentum] = NormDIM(x->ru);
776   f[eu->monitor.Energy]   = x->E;
777   f[eu->monitor.Speed]    = NormDIM(x->ru)/x->r;
778   Pressure_PG(eu->pars[EULER_PAR_GAMMA], x, &p);
779   f[eu->monitor.Pressure] = p;
780   PetscFunctionReturn(0);
781 }
782 
783 static PetscErrorCode SetUpBC_Euler(DM dm, PetscDS prob,Physics phys)
784 {
785   Physics_Euler   *eu = (Physics_Euler *) phys->data;
786   DMLabel         label;
787 
788   PetscFunctionBeginUser;
789   PetscCall(DMGetLabel(dm, "Face Sets", &label));
790   if (eu->type == EULER_LINEAR_WAVE) {
791     const PetscInt wallids[] = {100,101};
792     PetscCall(PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall", label, PETSC_STATIC_ARRAY_LENGTH(wallids), wallids, 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Wall, NULL, phys, NULL));
793   }
794   else {
795     const PetscInt wallids[] = {100,101,200,300};
796     PetscCall(PetscDSAddBoundary(prob, DM_BC_NATURAL_RIEMANN, "wall", label, PETSC_STATIC_ARRAY_LENGTH(wallids), wallids, 0, 0, NULL, (void (*)(void)) PhysicsBoundary_Euler_Wall, NULL, phys, NULL));
797   }
798   PetscFunctionReturn(0);
799 }
800 
801 static PetscErrorCode PhysicsCreate_Euler(Model mod,Physics phys,PetscOptionItems *PetscOptionsObject)
802 {
803   Physics_Euler   *eu;
804 
805   PetscFunctionBeginUser;
806   phys->field_desc = PhysicsFields_Euler;
807   phys->riemann = (PetscRiemannFunc) PhysicsRiemann_Euler_Godunov;
808   PetscCall(PetscNew(&eu));
809   phys->data    = eu;
810   mod->setupbc = SetUpBC_Euler;
811   PetscOptionsHeadBegin(PetscOptionsObject,"Euler options");
812   {
813     PetscReal alpha;
814     char type[64] = "linear_wave";
815     PetscBool  is;
816     eu->pars[EULER_PAR_GAMMA] = 1.4;
817     eu->pars[EULER_PAR_AMACH] = 2.02;
818     eu->pars[EULER_PAR_RHOR] = 3.0;
819     eu->pars[EULER_PAR_ITANA] = 0.57735026918963; /* angle of Euler self similar (SS) shock */
820     PetscCall(PetscOptionsReal("-eu_gamma","Heat capacity ratio","",eu->pars[EULER_PAR_GAMMA],&eu->pars[EULER_PAR_GAMMA],NULL));
821     PetscCall(PetscOptionsReal("-eu_amach","Shock speed (Mach)","",eu->pars[EULER_PAR_AMACH],&eu->pars[EULER_PAR_AMACH],NULL));
822     PetscCall(PetscOptionsReal("-eu_rho2","Density right of discontinuity","",eu->pars[EULER_PAR_RHOR],&eu->pars[EULER_PAR_RHOR],NULL));
823     alpha = 60.;
824     PetscCall(PetscOptionsReal("-eu_alpha","Angle of discontinuity","",alpha,&alpha,NULL));
825     PetscCheck(alpha>0. && alpha<=90.,PETSC_COMM_WORLD,PETSC_ERR_SUP,"Alpha bust be > 0 and <= 90 (%g)",(double)alpha);
826     eu->pars[EULER_PAR_ITANA] = 1./PetscTanReal( alpha * PETSC_PI / 180.0);
827     PetscCall(PetscOptionsString("-eu_type","Type of Euler test","",type,type,sizeof(type),NULL));
828     PetscCall(PetscStrcmp(type,"linear_wave", &is));
829     if (is) {
830       /* Remember this should be periodic */
831       eu->type = EULER_LINEAR_WAVE;
832       PetscCall(PetscPrintf(PETSC_COMM_WORLD,"%s set Euler type: %s\n",PETSC_FUNCTION_NAME,"linear_wave"));
833     }
834     else {
835       PetscCheck(DIM == 2,PETSC_COMM_WORLD,PETSC_ERR_SUP,"DIM must be 2 unless linear wave test %s",type);
836       PetscCall(PetscStrcmp(type,"iv_shock", &is));
837       if (is) {
838         eu->type = EULER_IV_SHOCK;
839         PetscCall(PetscPrintf(PETSC_COMM_WORLD,"%s set Euler type: %s\n",PETSC_FUNCTION_NAME,"iv_shock"));
840       }
841       else {
842         PetscCall(PetscStrcmp(type,"ss_shock", &is));
843         if (is) {
844           eu->type = EULER_SS_SHOCK;
845           PetscCall(PetscPrintf(PETSC_COMM_WORLD,"%s set Euler type: %s\n",PETSC_FUNCTION_NAME,"ss_shock"));
846         }
847         else {
848           PetscCall(PetscStrcmp(type,"shock_tube", &is));
849           if (is) eu->type = EULER_SHOCK_TUBE;
850           else SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"Unknown Euler type %s",type);
851           PetscCall(PetscPrintf(PETSC_COMM_WORLD,"%s set Euler type: %s\n",PETSC_FUNCTION_NAME,"shock_tube"));
852         }
853       }
854     }
855   }
856   PetscOptionsHeadEnd();
857   eu->sound = SpeedOfSound_PG;
858   phys->maxspeed = 0.; /* will get set in solution */
859   PetscCall(ModelSolutionSetDefault(mod,PhysicsSolution_Euler,phys));
860   PetscCall(ModelFunctionalRegister(mod,"Speed",&eu->monitor.Speed,PhysicsFunctional_Euler,phys));
861   PetscCall(ModelFunctionalRegister(mod,"Energy",&eu->monitor.Energy,PhysicsFunctional_Euler,phys));
862   PetscCall(ModelFunctionalRegister(mod,"Density",&eu->monitor.Density,PhysicsFunctional_Euler,phys));
863   PetscCall(ModelFunctionalRegister(mod,"Momentum",&eu->monitor.Momentum,PhysicsFunctional_Euler,phys));
864   PetscCall(ModelFunctionalRegister(mod,"Pressure",&eu->monitor.Pressure,PhysicsFunctional_Euler,phys));
865 
866   PetscFunctionReturn(0);
867 }
868 
869 static PetscErrorCode ErrorIndicator_Simple(PetscInt dim, PetscReal volume, PetscInt numComps, const PetscScalar u[], const PetscScalar grad[], PetscReal *error, void *ctx)
870 {
871   PetscReal      err = 0.;
872   PetscInt       i, j;
873 
874   PetscFunctionBeginUser;
875   for (i = 0; i < numComps; i++) {
876     for (j = 0; j < dim; j++) {
877       err += PetscSqr(PetscRealPart(grad[i * dim + j]));
878     }
879   }
880   *error = volume * err;
881   PetscFunctionReturn(0);
882 }
883 
884 PetscErrorCode CreatePartitionVec(DM dm, DM *dmCell, Vec *partition)
885 {
886   PetscSF        sfPoint;
887   PetscSection   coordSection;
888   Vec            coordinates;
889   PetscSection   sectionCell;
890   PetscScalar    *part;
891   PetscInt       cStart, cEnd, c;
892   PetscMPIInt    rank;
893 
894   PetscFunctionBeginUser;
895   PetscCall(DMGetCoordinateSection(dm, &coordSection));
896   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
897   PetscCall(DMClone(dm, dmCell));
898   PetscCall(DMGetPointSF(dm, &sfPoint));
899   PetscCall(DMSetPointSF(*dmCell, sfPoint));
900   PetscCall(DMSetCoordinateSection(*dmCell, PETSC_DETERMINE, coordSection));
901   PetscCall(DMSetCoordinatesLocal(*dmCell, coordinates));
902   PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)dm), &rank));
903   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionCell));
904   PetscCall(DMPlexGetHeightStratum(*dmCell, 0, &cStart, &cEnd));
905   PetscCall(PetscSectionSetChart(sectionCell, cStart, cEnd));
906   for (c = cStart; c < cEnd; ++c) {
907     PetscCall(PetscSectionSetDof(sectionCell, c, 1));
908   }
909   PetscCall(PetscSectionSetUp(sectionCell));
910   PetscCall(DMSetLocalSection(*dmCell, sectionCell));
911   PetscCall(PetscSectionDestroy(&sectionCell));
912   PetscCall(DMCreateLocalVector(*dmCell, partition));
913   PetscCall(PetscObjectSetName((PetscObject)*partition, "partition"));
914   PetscCall(VecGetArray(*partition, &part));
915   for (c = cStart; c < cEnd; ++c) {
916     PetscScalar *p;
917 
918     PetscCall(DMPlexPointLocalRef(*dmCell, c, part, &p));
919     p[0] = rank;
920   }
921   PetscCall(VecRestoreArray(*partition, &part));
922   PetscFunctionReturn(0);
923 }
924 
925 PetscErrorCode CreateMassMatrix(DM dm, Vec *massMatrix, User user)
926 {
927   DM                plex, dmMass, dmFace, dmCell, dmCoord;
928   PetscSection      coordSection;
929   Vec               coordinates, facegeom, cellgeom;
930   PetscSection      sectionMass;
931   PetscScalar       *m;
932   const PetscScalar *fgeom, *cgeom, *coords;
933   PetscInt          vStart, vEnd, v;
934 
935   PetscFunctionBeginUser;
936   PetscCall(DMConvert(dm, DMPLEX, &plex));
937   PetscCall(DMGetCoordinateSection(dm, &coordSection));
938   PetscCall(DMGetCoordinatesLocal(dm, &coordinates));
939   PetscCall(DMClone(dm, &dmMass));
940   PetscCall(DMSetCoordinateSection(dmMass, PETSC_DETERMINE, coordSection));
941   PetscCall(DMSetCoordinatesLocal(dmMass, coordinates));
942   PetscCall(PetscSectionCreate(PetscObjectComm((PetscObject)dm), &sectionMass));
943   PetscCall(DMPlexGetDepthStratum(dm, 0, &vStart, &vEnd));
944   PetscCall(PetscSectionSetChart(sectionMass, vStart, vEnd));
945   for (v = vStart; v < vEnd; ++v) {
946     PetscInt numFaces;
947 
948     PetscCall(DMPlexGetSupportSize(dmMass, v, &numFaces));
949     PetscCall(PetscSectionSetDof(sectionMass, v, numFaces*numFaces));
950   }
951   PetscCall(PetscSectionSetUp(sectionMass));
952   PetscCall(DMSetLocalSection(dmMass, sectionMass));
953   PetscCall(PetscSectionDestroy(&sectionMass));
954   PetscCall(DMGetLocalVector(dmMass, massMatrix));
955   PetscCall(VecGetArray(*massMatrix, &m));
956   PetscCall(DMPlexGetGeometryFVM(plex, &facegeom, &cellgeom, NULL));
957   PetscCall(VecGetDM(facegeom, &dmFace));
958   PetscCall(VecGetArrayRead(facegeom, &fgeom));
959   PetscCall(VecGetDM(cellgeom, &dmCell));
960   PetscCall(VecGetArrayRead(cellgeom, &cgeom));
961   PetscCall(DMGetCoordinateDM(dm, &dmCoord));
962   PetscCall(VecGetArrayRead(coordinates, &coords));
963   for (v = vStart; v < vEnd; ++v) {
964     const PetscInt        *faces;
965     PetscFVFaceGeom       *fgA, *fgB, *cg;
966     PetscScalar           *vertex;
967     PetscInt               numFaces, sides[2], f, g;
968 
969     PetscCall(DMPlexPointLocalRead(dmCoord, v, coords, &vertex));
970     PetscCall(DMPlexGetSupportSize(dmMass, v, &numFaces));
971     PetscCall(DMPlexGetSupport(dmMass, v, &faces));
972     for (f = 0; f < numFaces; ++f) {
973       sides[0] = faces[f];
974       PetscCall(DMPlexPointLocalRead(dmFace, faces[f], fgeom, &fgA));
975       for (g = 0; g < numFaces; ++g) {
976         const PetscInt *cells = NULL;
977         PetscReal      area   = 0.0;
978         PetscInt       numCells;
979 
980         sides[1] = faces[g];
981         PetscCall(DMPlexPointLocalRead(dmFace, faces[g], fgeom, &fgB));
982         PetscCall(DMPlexGetJoin(dmMass, 2, sides, &numCells, &cells));
983         PetscCheck(numCells == 1,PETSC_COMM_SELF, PETSC_ERR_LIB, "Invalid join for faces");
984         PetscCall(DMPlexPointLocalRead(dmCell, cells[0], cgeom, &cg));
985         area += PetscAbsScalar((vertex[0] - cg->centroid[0])*(fgA->centroid[1] - cg->centroid[1]) - (vertex[1] - cg->centroid[1])*(fgA->centroid[0] - cg->centroid[0]));
986         area += PetscAbsScalar((vertex[0] - cg->centroid[0])*(fgB->centroid[1] - cg->centroid[1]) - (vertex[1] - cg->centroid[1])*(fgB->centroid[0] - cg->centroid[0]));
987         m[f*numFaces+g] = Dot2Real(fgA->normal, fgB->normal)*area*0.5;
988         PetscCall(DMPlexRestoreJoin(dmMass, 2, sides, &numCells, &cells));
989       }
990     }
991   }
992   PetscCall(VecRestoreArrayRead(facegeom, &fgeom));
993   PetscCall(VecRestoreArrayRead(cellgeom, &cgeom));
994   PetscCall(VecRestoreArrayRead(coordinates, &coords));
995   PetscCall(VecRestoreArray(*massMatrix, &m));
996   PetscCall(DMDestroy(&dmMass));
997   PetscCall(DMDestroy(&plex));
998   PetscFunctionReturn(0);
999 }
1000 
1001 /* Behavior will be different for multi-physics or when using non-default boundary conditions */
1002 static PetscErrorCode ModelSolutionSetDefault(Model mod,SolutionFunction func,void *ctx)
1003 {
1004   PetscFunctionBeginUser;
1005   mod->solution    = func;
1006   mod->solutionctx = ctx;
1007   PetscFunctionReturn(0);
1008 }
1009 
1010 static PetscErrorCode ModelFunctionalRegister(Model mod,const char *name,PetscInt *offset,FunctionalFunction func,void *ctx)
1011 {
1012   FunctionalLink link,*ptr;
1013   PetscInt       lastoffset = -1;
1014 
1015   PetscFunctionBeginUser;
1016   for (ptr=&mod->functionalRegistry; *ptr; ptr = &(*ptr)->next) lastoffset = (*ptr)->offset;
1017   PetscCall(PetscNew(&link));
1018   PetscCall(PetscStrallocpy(name,&link->name));
1019   link->offset = lastoffset + 1;
1020   link->func   = func;
1021   link->ctx    = ctx;
1022   link->next   = NULL;
1023   *ptr         = link;
1024   *offset      = link->offset;
1025   PetscFunctionReturn(0);
1026 }
1027 
1028 static PetscErrorCode ModelFunctionalSetFromOptions(Model mod,PetscOptionItems *PetscOptionsObject)
1029 {
1030   PetscInt       i,j;
1031   FunctionalLink link;
1032   char           *names[256];
1033 
1034   PetscFunctionBeginUser;
1035   mod->numMonitored = PETSC_STATIC_ARRAY_LENGTH(names);
1036   PetscCall(PetscOptionsStringArray("-monitor","list of functionals to monitor","",names,&mod->numMonitored,NULL));
1037   /* Create list of functionals that will be computed somehow */
1038   PetscCall(PetscMalloc1(mod->numMonitored,&mod->functionalMonitored));
1039   /* Create index of calls that we will have to make to compute these functionals (over-allocation in general). */
1040   PetscCall(PetscMalloc1(mod->numMonitored,&mod->functionalCall));
1041   mod->numCall = 0;
1042   for (i=0; i<mod->numMonitored; i++) {
1043     for (link=mod->functionalRegistry; link; link=link->next) {
1044       PetscBool match;
1045       PetscCall(PetscStrcasecmp(names[i],link->name,&match));
1046       if (match) break;
1047     }
1048     PetscCheck(link,mod->comm,PETSC_ERR_USER,"No known functional '%s'",names[i]);
1049     mod->functionalMonitored[i] = link;
1050     for (j=0; j<i; j++) {
1051       if (mod->functionalCall[j]->func == link->func && mod->functionalCall[j]->ctx == link->ctx) goto next_name;
1052     }
1053     mod->functionalCall[mod->numCall++] = link; /* Just points to the first link using the result. There may be more results. */
1054 next_name:
1055     PetscCall(PetscFree(names[i]));
1056   }
1057 
1058   /* Find out the maximum index of any functional computed by a function we will be calling (even if we are not using it) */
1059   mod->maxComputed = -1;
1060   for (link=mod->functionalRegistry; link; link=link->next) {
1061     for (i=0; i<mod->numCall; i++) {
1062       FunctionalLink call = mod->functionalCall[i];
1063       if (link->func == call->func && link->ctx == call->ctx) {
1064         mod->maxComputed = PetscMax(mod->maxComputed,link->offset);
1065       }
1066     }
1067   }
1068   PetscFunctionReturn(0);
1069 }
1070 
1071 static PetscErrorCode FunctionalLinkDestroy(FunctionalLink *link)
1072 {
1073   FunctionalLink l,next;
1074 
1075   PetscFunctionBeginUser;
1076   if (!link) PetscFunctionReturn(0);
1077   l     = *link;
1078   *link = NULL;
1079   for (; l; l=next) {
1080     next = l->next;
1081     PetscCall(PetscFree(l->name));
1082     PetscCall(PetscFree(l));
1083   }
1084   PetscFunctionReturn(0);
1085 }
1086 
1087 /* put the solution callback into a functional callback */
1088 static PetscErrorCode SolutionFunctional(PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *modctx)
1089 {
1090   Model          mod;
1091   PetscFunctionBegin;
1092   mod  = (Model) modctx;
1093   PetscCall((*mod->solution)(mod, time, x, u, mod->solutionctx));
1094   PetscFunctionReturn(0);
1095 }
1096 
1097 PetscErrorCode SetInitialCondition(DM dm, Vec X, User user)
1098 {
1099   PetscErrorCode     (*func[1]) (PetscInt dim, PetscReal time, const PetscReal x[], PetscInt Nf, PetscScalar *u, void *ctx);
1100   void               *ctx[1];
1101   Model              mod = user->model;
1102 
1103   PetscFunctionBeginUser;
1104   func[0] = SolutionFunctional;
1105   ctx[0]  = (void *) mod;
1106   PetscCall(DMProjectFunction(dm,0.0,func,ctx,INSERT_ALL_VALUES,X));
1107   PetscFunctionReturn(0);
1108 }
1109 
1110 static PetscErrorCode OutputVTK(DM dm, const char *filename, PetscViewer *viewer)
1111 {
1112   PetscFunctionBeginUser;
1113   PetscCall(PetscViewerCreate(PetscObjectComm((PetscObject)dm), viewer));
1114   PetscCall(PetscViewerSetType(*viewer, PETSCVIEWERVTK));
1115   PetscCall(PetscViewerFileSetName(*viewer, filename));
1116   PetscFunctionReturn(0);
1117 }
1118 
1119 static PetscErrorCode MonitorVTK(TS ts,PetscInt stepnum,PetscReal time,Vec X,void *ctx)
1120 {
1121   User           user = (User)ctx;
1122   DM             dm, plex;
1123   PetscViewer    viewer;
1124   char           filename[PETSC_MAX_PATH_LEN],*ftable = NULL;
1125   PetscReal      xnorm;
1126 
1127   PetscFunctionBeginUser;
1128   PetscCall(PetscObjectSetName((PetscObject) X, "u"));
1129   PetscCall(VecGetDM(X,&dm));
1130   PetscCall(VecNorm(X,NORM_INFINITY,&xnorm));
1131 
1132   if (stepnum >= 0) {
1133     stepnum += user->monitorStepOffset;
1134   }
1135   if (stepnum >= 0) {           /* No summary for final time */
1136     Model             mod = user->model;
1137     Vec               cellgeom;
1138     PetscInt          c,cStart,cEnd,fcount,i;
1139     size_t            ftableused,ftablealloc;
1140     const PetscScalar *cgeom,*x;
1141     DM                dmCell;
1142     DMLabel           vtkLabel;
1143     PetscReal         *fmin,*fmax,*fintegral,*ftmp;
1144 
1145     PetscCall(DMConvert(dm, DMPLEX, &plex));
1146     PetscCall(DMPlexGetGeometryFVM(plex, NULL, &cellgeom, NULL));
1147     fcount = mod->maxComputed+1;
1148     PetscCall(PetscMalloc4(fcount,&fmin,fcount,&fmax,fcount,&fintegral,fcount,&ftmp));
1149     for (i=0; i<fcount; i++) {
1150       fmin[i]      = PETSC_MAX_REAL;
1151       fmax[i]      = PETSC_MIN_REAL;
1152       fintegral[i] = 0;
1153     }
1154     PetscCall(VecGetDM(cellgeom,&dmCell));
1155     PetscCall(DMPlexGetSimplexOrBoxCells(dmCell,0,&cStart,&cEnd));
1156     PetscCall(VecGetArrayRead(cellgeom,&cgeom));
1157     PetscCall(VecGetArrayRead(X,&x));
1158     PetscCall(DMGetLabel(dm,"vtk",&vtkLabel));
1159     for (c = cStart; c < cEnd; ++c) {
1160       PetscFVCellGeom       *cg;
1161       const PetscScalar     *cx    = NULL;
1162       PetscInt              vtkVal = 0;
1163 
1164       /* not that these two routines as currently implemented work for any dm with a
1165        * localSection/globalSection */
1166       PetscCall(DMPlexPointLocalRead(dmCell,c,cgeom,&cg));
1167       PetscCall(DMPlexPointGlobalRead(dm,c,x,&cx));
1168       if (vtkLabel) PetscCall(DMLabelGetValue(vtkLabel,c,&vtkVal));
1169       if (!vtkVal || !cx) continue;        /* ghost, or not a global cell */
1170       for (i=0; i<mod->numCall; i++) {
1171         FunctionalLink flink = mod->functionalCall[i];
1172         PetscCall((*flink->func)(mod,time,cg->centroid,cx,ftmp,flink->ctx));
1173       }
1174       for (i=0; i<fcount; i++) {
1175         fmin[i]       = PetscMin(fmin[i],ftmp[i]);
1176         fmax[i]       = PetscMax(fmax[i],ftmp[i]);
1177         fintegral[i] += cg->volume * ftmp[i];
1178       }
1179     }
1180     PetscCall(VecRestoreArrayRead(cellgeom,&cgeom));
1181     PetscCall(VecRestoreArrayRead(X,&x));
1182     PetscCall(DMDestroy(&plex));
1183     PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE,fmin,fcount,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts)));
1184     PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE,fmax,fcount,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
1185     PetscCallMPI(MPI_Allreduce(MPI_IN_PLACE,fintegral,fcount,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts)));
1186 
1187     ftablealloc = fcount * 100;
1188     ftableused  = 0;
1189     PetscCall(PetscMalloc1(ftablealloc,&ftable));
1190     for (i=0; i<mod->numMonitored; i++) {
1191       size_t         countused;
1192       char           buffer[256],*p;
1193       FunctionalLink flink = mod->functionalMonitored[i];
1194       PetscInt       id    = flink->offset;
1195       if (i % 3) {
1196         PetscCall(PetscArraycpy(buffer,"  ",2));
1197         p    = buffer + 2;
1198       } else if (i) {
1199         char newline[] = "\n";
1200         PetscCall(PetscMemcpy(buffer,newline,sizeof(newline)-1));
1201         p    = buffer + sizeof(newline) - 1;
1202       } else {
1203         p = buffer;
1204       }
1205       PetscCall(PetscSNPrintfCount(p,sizeof buffer-(p-buffer),"%12s [%10.7g,%10.7g] int %10.7g",&countused,flink->name,(double)fmin[id],(double)fmax[id],(double)fintegral[id]));
1206       countused--;
1207       countused += p - buffer;
1208       if (countused > ftablealloc-ftableused-1) { /* reallocate */
1209         char *ftablenew;
1210         ftablealloc = 2*ftablealloc + countused;
1211         PetscCall(PetscMalloc(ftablealloc,&ftablenew));
1212         PetscCall(PetscArraycpy(ftablenew,ftable,ftableused));
1213         PetscCall(PetscFree(ftable));
1214         ftable = ftablenew;
1215       }
1216       PetscCall(PetscArraycpy(ftable+ftableused,buffer,countused));
1217       ftableused += countused;
1218       ftable[ftableused] = 0;
1219     }
1220     PetscCall(PetscFree4(fmin,fmax,fintegral,ftmp));
1221 
1222     PetscCall(PetscPrintf(PetscObjectComm((PetscObject)ts),"% 3" PetscInt_FMT "  time %8.4g  |x| %8.4g  %s\n",stepnum,(double)time,(double)xnorm,ftable ? ftable : ""));
1223     PetscCall(PetscFree(ftable));
1224   }
1225   if (user->vtkInterval < 1) PetscFunctionReturn(0);
1226   if ((stepnum == -1) ^ (stepnum % user->vtkInterval == 0)) {
1227     if (stepnum == -1) {        /* Final time is not multiple of normal time interval, write it anyway */
1228       PetscCall(TSGetStepNumber(ts,&stepnum));
1229     }
1230     PetscCall(PetscSNPrintf(filename,sizeof filename,"%s-%03" PetscInt_FMT ".vtu",user->outputBasename,stepnum));
1231     PetscCall(OutputVTK(dm,filename,&viewer));
1232     PetscCall(VecView(X,viewer));
1233     PetscCall(PetscViewerDestroy(&viewer));
1234   }
1235   PetscFunctionReturn(0);
1236 }
1237 
1238 static PetscErrorCode initializeTS(DM dm, User user, TS *ts)
1239 {
1240   PetscFunctionBegin;
1241   PetscCall(TSCreate(PetscObjectComm((PetscObject)dm), ts));
1242   PetscCall(TSSetType(*ts, TSSSP));
1243   PetscCall(TSSetDM(*ts, dm));
1244   if (user->vtkmon) PetscCall(TSMonitorSet(*ts,MonitorVTK,user,NULL));
1245   PetscCall(DMTSSetBoundaryLocal(dm, DMPlexTSComputeBoundary, user));
1246   PetscCall(DMTSSetRHSFunctionLocal(dm, DMPlexTSComputeRHSFunctionFVM, user));
1247   PetscCall(TSSetMaxTime(*ts,2.0));
1248   PetscCall(TSSetExactFinalTime(*ts,TS_EXACTFINALTIME_STEPOVER));
1249   PetscFunctionReturn(0);
1250 }
1251 
1252 static PetscErrorCode adaptToleranceFVM(PetscFV fvm, TS ts, Vec sol, VecTagger refineTag, VecTagger coarsenTag, User user, TS *tsNew, Vec *solNew)
1253 {
1254   DM                dm, gradDM, plex, cellDM, adaptedDM = NULL;
1255   Vec               cellGeom, faceGeom;
1256   PetscBool         isForest, computeGradient;
1257   Vec               grad, locGrad, locX, errVec;
1258   PetscInt          cStart, cEnd, c, dim, nRefine, nCoarsen;
1259   PetscReal         minMaxInd[2] = {PETSC_MAX_REAL, PETSC_MIN_REAL}, minMaxIndGlobal[2], minInd, maxInd, time;
1260   PetscScalar       *errArray;
1261   const PetscScalar *pointVals;
1262   const PetscScalar *pointGrads;
1263   const PetscScalar *pointGeom;
1264   DMLabel           adaptLabel = NULL;
1265   IS                refineIS, coarsenIS;
1266 
1267   PetscFunctionBegin;
1268   PetscCall(TSGetTime(ts,&time));
1269   PetscCall(VecGetDM(sol, &dm));
1270   PetscCall(DMGetDimension(dm,&dim));
1271   PetscCall(PetscFVGetComputeGradients(fvm,&computeGradient));
1272   PetscCall(PetscFVSetComputeGradients(fvm,PETSC_TRUE));
1273   PetscCall(DMIsForest(dm, &isForest));
1274   PetscCall(DMConvert(dm, DMPLEX, &plex));
1275   PetscCall(DMPlexGetDataFVM(plex, fvm, &cellGeom, &faceGeom, &gradDM));
1276   PetscCall(DMCreateLocalVector(plex,&locX));
1277   PetscCall(DMPlexInsertBoundaryValues(plex, PETSC_TRUE, locX, 0.0, faceGeom, cellGeom, NULL));
1278   PetscCall(DMGlobalToLocalBegin(plex, sol, INSERT_VALUES, locX));
1279   PetscCall(DMGlobalToLocalEnd  (plex, sol, INSERT_VALUES, locX));
1280   PetscCall(DMCreateGlobalVector(gradDM, &grad));
1281   PetscCall(DMPlexReconstructGradientsFVM(plex, locX, grad));
1282   PetscCall(DMCreateLocalVector(gradDM, &locGrad));
1283   PetscCall(DMGlobalToLocalBegin(gradDM, grad, INSERT_VALUES, locGrad));
1284   PetscCall(DMGlobalToLocalEnd(gradDM, grad, INSERT_VALUES, locGrad));
1285   PetscCall(VecDestroy(&grad));
1286   PetscCall(DMPlexGetSimplexOrBoxCells(plex,0,&cStart,&cEnd));
1287   PetscCall(VecGetArrayRead(locGrad,&pointGrads));
1288   PetscCall(VecGetArrayRead(cellGeom,&pointGeom));
1289   PetscCall(VecGetArrayRead(locX,&pointVals));
1290   PetscCall(VecGetDM(cellGeom,&cellDM));
1291   PetscCall(DMLabelCreate(PETSC_COMM_SELF,"adapt",&adaptLabel));
1292   PetscCall(VecCreateMPI(PetscObjectComm((PetscObject)plex),cEnd-cStart,PETSC_DETERMINE,&errVec));
1293   PetscCall(VecSetUp(errVec));
1294   PetscCall(VecGetArray(errVec,&errArray));
1295   for (c = cStart; c < cEnd; c++) {
1296     PetscReal             errInd = 0.;
1297     PetscScalar           *pointGrad;
1298     PetscScalar           *pointVal;
1299     PetscFVCellGeom       *cg;
1300 
1301     PetscCall(DMPlexPointLocalRead(gradDM,c,pointGrads,&pointGrad));
1302     PetscCall(DMPlexPointLocalRead(cellDM,c,pointGeom,&cg));
1303     PetscCall(DMPlexPointLocalRead(plex,c,pointVals,&pointVal));
1304 
1305     PetscCall((user->model->errorIndicator)(dim,cg->volume,user->model->physics->dof,pointVal,pointGrad,&errInd,user->model->errorCtx));
1306     errArray[c-cStart] = errInd;
1307     minMaxInd[0] = PetscMin(minMaxInd[0],errInd);
1308     minMaxInd[1] = PetscMax(minMaxInd[1],errInd);
1309   }
1310   PetscCall(VecRestoreArray(errVec,&errArray));
1311   PetscCall(VecRestoreArrayRead(locX,&pointVals));
1312   PetscCall(VecRestoreArrayRead(cellGeom,&pointGeom));
1313   PetscCall(VecRestoreArrayRead(locGrad,&pointGrads));
1314   PetscCall(VecDestroy(&locGrad));
1315   PetscCall(VecDestroy(&locX));
1316   PetscCall(DMDestroy(&plex));
1317 
1318   PetscCall(VecTaggerComputeIS(refineTag,errVec,&refineIS,NULL));
1319   PetscCall(VecTaggerComputeIS(coarsenTag,errVec,&coarsenIS,NULL));
1320   PetscCall(ISGetSize(refineIS,&nRefine));
1321   PetscCall(ISGetSize(coarsenIS,&nCoarsen));
1322   if (nRefine) PetscCall(DMLabelSetStratumIS(adaptLabel,DM_ADAPT_REFINE,refineIS));
1323   if (nCoarsen) PetscCall(DMLabelSetStratumIS(adaptLabel,DM_ADAPT_COARSEN,coarsenIS));
1324   PetscCall(ISDestroy(&coarsenIS));
1325   PetscCall(ISDestroy(&refineIS));
1326   PetscCall(VecDestroy(&errVec));
1327 
1328   PetscCall(PetscFVSetComputeGradients(fvm,computeGradient));
1329   minMaxInd[1] = -minMaxInd[1];
1330   PetscCallMPI(MPI_Allreduce(minMaxInd,minMaxIndGlobal,2,MPIU_REAL,MPI_MIN,PetscObjectComm((PetscObject)dm)));
1331   minInd = minMaxIndGlobal[0];
1332   maxInd = -minMaxIndGlobal[1];
1333   PetscCall(PetscInfo(ts, "error indicator range (%E, %E)\n", (double)minInd, (double)maxInd));
1334   if (nRefine || nCoarsen) { /* at least one cell is over the refinement threshold */
1335     PetscCall(DMAdaptLabel(dm,adaptLabel,&adaptedDM));
1336   }
1337   PetscCall(DMLabelDestroy(&adaptLabel));
1338   if (adaptedDM) {
1339     PetscCall(PetscInfo(ts, "Adapted mesh, marking %" PetscInt_FMT " cells for refinement, and %" PetscInt_FMT " cells for coarsening\n", nRefine, nCoarsen));
1340     if (tsNew) PetscCall(initializeTS(adaptedDM, user, tsNew));
1341     if (solNew) {
1342       PetscCall(DMCreateGlobalVector(adaptedDM, solNew));
1343       PetscCall(PetscObjectSetName((PetscObject) *solNew, "solution"));
1344       PetscCall(DMForestTransferVec(dm, sol, adaptedDM, *solNew, PETSC_TRUE, time));
1345     }
1346     if (isForest) PetscCall(DMForestSetAdaptivityForest(adaptedDM,NULL)); /* clear internal references to the previous dm */
1347     PetscCall(DMDestroy(&adaptedDM));
1348   } else {
1349     if (tsNew)  *tsNew  = NULL;
1350     if (solNew) *solNew = NULL;
1351   }
1352   PetscFunctionReturn(0);
1353 }
1354 
1355 int main(int argc, char **argv)
1356 {
1357   MPI_Comm          comm;
1358   PetscDS           prob;
1359   PetscFV           fvm;
1360   PetscLimiter      limiter = NULL, noneLimiter = NULL;
1361   User              user;
1362   Model             mod;
1363   Physics           phys;
1364   DM                dm, plex;
1365   PetscReal         ftime, cfl, dt, minRadius;
1366   PetscInt          dim, nsteps;
1367   TS                ts;
1368   TSConvergedReason reason;
1369   Vec               X;
1370   PetscViewer       viewer;
1371   PetscBool         vtkCellGeom, useAMR;
1372   PetscInt          adaptInterval;
1373   char              physname[256]  = "advect";
1374   VecTagger         refineTag = NULL, coarsenTag = NULL;
1375 
1376   PetscFunctionBeginUser;
1377   PetscCall(PetscInitialize(&argc, &argv, (char*) 0, help));
1378   comm = PETSC_COMM_WORLD;
1379 
1380   PetscCall(PetscNew(&user));
1381   PetscCall(PetscNew(&user->model));
1382   PetscCall(PetscNew(&user->model->physics));
1383   mod           = user->model;
1384   phys          = mod->physics;
1385   mod->comm     = comm;
1386   useAMR        = PETSC_FALSE;
1387   adaptInterval = 1;
1388 
1389   /* Register physical models to be available on the command line */
1390   PetscCall(PetscFunctionListAdd(&PhysicsList,"advect"          ,PhysicsCreate_Advect));
1391   PetscCall(PetscFunctionListAdd(&PhysicsList,"sw"              ,PhysicsCreate_SW));
1392   PetscCall(PetscFunctionListAdd(&PhysicsList,"euler"           ,PhysicsCreate_Euler));
1393 
1394   PetscOptionsBegin(comm,NULL,"Unstructured Finite Volume Mesh Options","");
1395   {
1396     cfl  = 0.9 * 4; /* default SSPRKS2 with s=5 stages is stable for CFL number s-1 */
1397     PetscCall(PetscOptionsReal("-ufv_cfl","CFL number per step","",cfl,&cfl,NULL));
1398     user->vtkInterval = 1;
1399     PetscCall(PetscOptionsInt("-ufv_vtk_interval","VTK output interval (0 to disable)","",user->vtkInterval,&user->vtkInterval,NULL));
1400     user->vtkmon = PETSC_TRUE;
1401     PetscCall(PetscOptionsBool("-ufv_vtk_monitor","Use VTKMonitor routine","",user->vtkmon,&user->vtkmon,NULL));
1402     vtkCellGeom = PETSC_FALSE;
1403     PetscCall(PetscStrcpy(user->outputBasename, "ex11"));
1404     PetscCall(PetscOptionsString("-ufv_vtk_basename","VTK output basename","",user->outputBasename,user->outputBasename,sizeof(user->outputBasename),NULL));
1405     PetscCall(PetscOptionsBool("-ufv_vtk_cellgeom","Write cell geometry (for debugging)","",vtkCellGeom,&vtkCellGeom,NULL));
1406     PetscCall(PetscOptionsBool("-ufv_use_amr","use local adaptive mesh refinement","",useAMR,&useAMR,NULL));
1407     PetscCall(PetscOptionsInt("-ufv_adapt_interval","time steps between AMR","",adaptInterval,&adaptInterval,NULL));
1408   }
1409   PetscOptionsEnd();
1410 
1411   if (useAMR) {
1412     VecTaggerBox refineBox, coarsenBox;
1413 
1414     refineBox.min  = refineBox.max  = PETSC_MAX_REAL;
1415     coarsenBox.min = coarsenBox.max = PETSC_MIN_REAL;
1416 
1417     PetscCall(VecTaggerCreate(comm,&refineTag));
1418     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)refineTag,"refine_"));
1419     PetscCall(VecTaggerSetType(refineTag,VECTAGGERABSOLUTE));
1420     PetscCall(VecTaggerAbsoluteSetBox(refineTag,&refineBox));
1421     PetscCall(VecTaggerSetFromOptions(refineTag));
1422     PetscCall(VecTaggerSetUp(refineTag));
1423     PetscCall(PetscObjectViewFromOptions((PetscObject)refineTag,NULL,"-tag_view"));
1424 
1425     PetscCall(VecTaggerCreate(comm,&coarsenTag));
1426     PetscCall(PetscObjectSetOptionsPrefix((PetscObject)coarsenTag,"coarsen_"));
1427     PetscCall(VecTaggerSetType(coarsenTag,VECTAGGERABSOLUTE));
1428     PetscCall(VecTaggerAbsoluteSetBox(coarsenTag,&coarsenBox));
1429     PetscCall(VecTaggerSetFromOptions(coarsenTag));
1430     PetscCall(VecTaggerSetUp(coarsenTag));
1431     PetscCall(PetscObjectViewFromOptions((PetscObject)coarsenTag,NULL,"-tag_view"));
1432   }
1433 
1434   PetscOptionsBegin(comm,NULL,"Unstructured Finite Volume Physics Options","");
1435   {
1436     PetscErrorCode (*physcreate)(Model,Physics,PetscOptionItems*);
1437     PetscCall(PetscOptionsFList("-physics","Physics module to solve","",PhysicsList,physname,physname,sizeof physname,NULL));
1438     PetscCall(PetscFunctionListFind(PhysicsList,physname,&physcreate));
1439     PetscCall(PetscMemzero(phys,sizeof(struct _n_Physics)));
1440     PetscCall((*physcreate)(mod,phys,PetscOptionsObject));
1441     /* Count number of fields and dofs */
1442     for (phys->nfields=0,phys->dof=0; phys->field_desc[phys->nfields].name; phys->nfields++) phys->dof += phys->field_desc[phys->nfields].dof;
1443     PetscCheck(phys->dof > 0,comm,PETSC_ERR_ARG_WRONGSTATE,"Physics '%s' did not set dof",physname);
1444     PetscCall(ModelFunctionalSetFromOptions(mod,PetscOptionsObject));
1445   }
1446   PetscOptionsEnd();
1447 
1448   /* Create mesh */
1449   {
1450     PetscInt i;
1451 
1452     PetscCall(DMCreate(comm, &dm));
1453     PetscCall(DMSetType(dm, DMPLEX));
1454     PetscCall(DMSetFromOptions(dm));
1455     for (i = 0; i < DIM; i++) { mod->bounds[2*i] = 0.; mod->bounds[2*i+1] = 1.;};
1456     dim = DIM;
1457     { /* a null name means just do a hex box */
1458       PetscInt  cells[3] = {1, 1, 1}, n = 3;
1459       PetscBool flg2, skew = PETSC_FALSE;
1460       PetscInt nret2 = 2*DIM;
1461       PetscOptionsBegin(comm,NULL,"Rectangular mesh options","");
1462       PetscCall(PetscOptionsRealArray("-grid_bounds","bounds of the mesh in each direction (i.e., x_min,x_max,y_min,y_max","",mod->bounds,&nret2,&flg2));
1463       PetscCall(PetscOptionsBool("-grid_skew_60","Skew grid for 60 degree shock mesh","",skew,&skew,NULL));
1464       PetscCall(PetscOptionsIntArray("-dm_plex_box_faces", "Number of faces along each dimension", "", cells, &n, NULL));
1465       PetscOptionsEnd();
1466       /* TODO Rewrite this with Mark, and remove grid_bounds at that time */
1467       if (flg2) {
1468         PetscInt dimEmbed, i;
1469         PetscInt nCoords;
1470         PetscScalar *coords;
1471         Vec coordinates;
1472 
1473         PetscCall(DMGetCoordinatesLocal(dm,&coordinates));
1474         PetscCall(DMGetCoordinateDim(dm,&dimEmbed));
1475         PetscCall(VecGetLocalSize(coordinates,&nCoords));
1476         PetscCheck(!(nCoords % dimEmbed),PETSC_COMM_SELF,PETSC_ERR_ARG_SIZ,"Coordinate vector the wrong size");
1477         PetscCall(VecGetArray(coordinates,&coords));
1478         for (i = 0; i < nCoords; i += dimEmbed) {
1479           PetscInt j;
1480 
1481           PetscScalar *coord = &coords[i];
1482           for (j = 0; j < dimEmbed; j++) {
1483             coord[j] = mod->bounds[2 * j] + coord[j] * (mod->bounds[2 * j + 1] - mod->bounds[2 * j]);
1484             if (dim==2 && cells[1]==1 && j==0 && skew) {
1485               if (cells[0] == 2 && i == 8) {
1486                 coord[j] = .57735026918963; /* hack to get 60 deg skewed mesh */
1487               } else if (cells[0] == 3) {
1488                 if (i==2 || i==10) coord[j] = mod->bounds[1]/4.;
1489                 else if (i==4) coord[j] = mod->bounds[1]/2.;
1490                 else if (i==12) coord[j] = 1.57735026918963*mod->bounds[1]/2.;
1491               }
1492             }
1493           }
1494         }
1495         PetscCall(VecRestoreArray(coordinates,&coords));
1496         PetscCall(DMSetCoordinatesLocal(dm,coordinates));
1497       }
1498     }
1499   }
1500   PetscCall(DMViewFromOptions(dm, NULL, "-orig_dm_view"));
1501   PetscCall(DMGetDimension(dm, &dim));
1502 
1503   /* set up BCs, functions, tags */
1504   PetscCall(DMCreateLabel(dm, "Face Sets"));
1505   mod->errorIndicator = ErrorIndicator_Simple;
1506 
1507   {
1508     DM gdm;
1509 
1510     PetscCall(DMPlexConstructGhostCells(dm, NULL, NULL, &gdm));
1511     PetscCall(DMDestroy(&dm));
1512     dm   = gdm;
1513     PetscCall(DMViewFromOptions(dm, NULL, "-dm_view"));
1514   }
1515 
1516   PetscCall(PetscFVCreate(comm, &fvm));
1517   PetscCall(PetscFVSetFromOptions(fvm));
1518   PetscCall(PetscFVSetNumComponents(fvm, phys->dof));
1519   PetscCall(PetscFVSetSpatialDimension(fvm, dim));
1520   PetscCall(PetscObjectSetName((PetscObject) fvm,""));
1521   {
1522     PetscInt f, dof;
1523     for (f=0,dof=0; f < phys->nfields; f++) {
1524       PetscInt newDof = phys->field_desc[f].dof;
1525 
1526       if (newDof == 1) {
1527         PetscCall(PetscFVSetComponentName(fvm,dof,phys->field_desc[f].name));
1528       }
1529       else {
1530         PetscInt j;
1531 
1532         for (j = 0; j < newDof; j++) {
1533           char     compName[256]  = "Unknown";
1534 
1535           PetscCall(PetscSNPrintf(compName,sizeof(compName),"%s_%" PetscInt_FMT,phys->field_desc[f].name,j));
1536           PetscCall(PetscFVSetComponentName(fvm,dof+j,compName));
1537         }
1538       }
1539       dof += newDof;
1540     }
1541   }
1542   /* FV is now structured with one field having all physics as components */
1543   PetscCall(DMAddField(dm, NULL, (PetscObject) fvm));
1544   PetscCall(DMCreateDS(dm));
1545   PetscCall(DMGetDS(dm, &prob));
1546   PetscCall(PetscDSSetRiemannSolver(prob, 0, user->model->physics->riemann));
1547   PetscCall(PetscDSSetContext(prob, 0, user->model->physics));
1548   PetscCall((*mod->setupbc)(dm, prob,phys));
1549   PetscCall(PetscDSSetFromOptions(prob));
1550   {
1551     char      convType[256];
1552     PetscBool flg;
1553 
1554     PetscOptionsBegin(comm, "", "Mesh conversion options", "DMPLEX");
1555     PetscCall(PetscOptionsFList("-dm_type","Convert DMPlex to another format","ex12",DMList,DMPLEX,convType,256,&flg));
1556     PetscOptionsEnd();
1557     if (flg) {
1558       DM dmConv;
1559 
1560       PetscCall(DMConvert(dm,convType,&dmConv));
1561       if (dmConv) {
1562         PetscCall(DMViewFromOptions(dmConv, NULL, "-dm_conv_view"));
1563         PetscCall(DMDestroy(&dm));
1564         dm   = dmConv;
1565         PetscCall(DMSetFromOptions(dm));
1566       }
1567     }
1568   }
1569 
1570   PetscCall(initializeTS(dm, user, &ts));
1571 
1572   PetscCall(DMCreateGlobalVector(dm, &X));
1573   PetscCall(PetscObjectSetName((PetscObject) X, "solution"));
1574   PetscCall(SetInitialCondition(dm, X, user));
1575   if (useAMR) {
1576     PetscInt adaptIter;
1577 
1578     /* use no limiting when reconstructing gradients for adaptivity */
1579     PetscCall(PetscFVGetLimiter(fvm, &limiter));
1580     PetscCall(PetscObjectReference((PetscObject) limiter));
1581     PetscCall(PetscLimiterCreate(PetscObjectComm((PetscObject) fvm), &noneLimiter));
1582     PetscCall(PetscLimiterSetType(noneLimiter, PETSCLIMITERNONE));
1583 
1584     PetscCall(PetscFVSetLimiter(fvm, noneLimiter));
1585     for (adaptIter = 0; ; ++adaptIter) {
1586       PetscLogDouble bytes;
1587       TS             tsNew = NULL;
1588 
1589       PetscCall(PetscMemoryGetCurrentUsage(&bytes));
1590       PetscCall(PetscInfo(ts, "refinement loop %" PetscInt_FMT ": memory used %g\n", adaptIter, (double)bytes));
1591       PetscCall(DMViewFromOptions(dm, NULL, "-initial_dm_view"));
1592       PetscCall(VecViewFromOptions(X, NULL, "-initial_vec_view"));
1593 #if 0
1594       if (viewInitial) {
1595         PetscViewer viewer;
1596         char        buf[256];
1597         PetscBool   isHDF5, isVTK;
1598 
1599         PetscCall(PetscViewerCreate(comm,&viewer));
1600         PetscCall(PetscViewerSetType(viewer,PETSCVIEWERVTK));
1601         PetscCall(PetscViewerSetOptionsPrefix(viewer,"initial_"));
1602         PetscCall(PetscViewerSetFromOptions(viewer));
1603         PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERHDF5,&isHDF5));
1604         PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERVTK,&isVTK));
1605         if (isHDF5) {
1606           PetscCall(PetscSNPrintf(buf, 256, "ex11-initial-%" PetscInt_FMT ".h5", adaptIter));
1607         } else if (isVTK) {
1608           PetscCall(PetscSNPrintf(buf, 256, "ex11-initial-%" PetscInt_FMT ".vtu", adaptIter));
1609           PetscCall(PetscViewerPushFormat(viewer,PETSC_VIEWER_VTK_VTU));
1610         }
1611         PetscCall(PetscViewerFileSetMode(viewer,FILE_MODE_WRITE));
1612         PetscCall(PetscViewerFileSetName(viewer,buf));
1613         if (isHDF5) {
1614           PetscCall(DMView(dm,viewer));
1615           PetscCall(PetscViewerFileSetMode(viewer,FILE_MODE_UPDATE));
1616         }
1617         PetscCall(VecView(X,viewer));
1618         PetscCall(PetscViewerDestroy(&viewer));
1619       }
1620 #endif
1621 
1622       PetscCall(adaptToleranceFVM(fvm, ts, X, refineTag, coarsenTag, user, &tsNew, NULL));
1623       if (!tsNew) {
1624         break;
1625       } else {
1626         PetscCall(DMDestroy(&dm));
1627         PetscCall(VecDestroy(&X));
1628         PetscCall(TSDestroy(&ts));
1629         ts   = tsNew;
1630         PetscCall(TSGetDM(ts,&dm));
1631         PetscCall(PetscObjectReference((PetscObject)dm));
1632         PetscCall(DMCreateGlobalVector(dm,&X));
1633         PetscCall(PetscObjectSetName((PetscObject) X, "solution"));
1634         PetscCall(SetInitialCondition(dm, X, user));
1635       }
1636     }
1637     /* restore original limiter */
1638     PetscCall(PetscFVSetLimiter(fvm, limiter));
1639   }
1640 
1641   PetscCall(DMConvert(dm, DMPLEX, &plex));
1642   if (vtkCellGeom) {
1643     DM  dmCell;
1644     Vec cellgeom, partition;
1645 
1646     PetscCall(DMPlexGetGeometryFVM(plex, NULL, &cellgeom, NULL));
1647     PetscCall(OutputVTK(dm, "ex11-cellgeom.vtk", &viewer));
1648     PetscCall(VecView(cellgeom, viewer));
1649     PetscCall(PetscViewerDestroy(&viewer));
1650     PetscCall(CreatePartitionVec(dm, &dmCell, &partition));
1651     PetscCall(OutputVTK(dmCell, "ex11-partition.vtk", &viewer));
1652     PetscCall(VecView(partition, viewer));
1653     PetscCall(PetscViewerDestroy(&viewer));
1654     PetscCall(VecDestroy(&partition));
1655     PetscCall(DMDestroy(&dmCell));
1656   }
1657   /* collect max maxspeed from all processes -- todo */
1658   PetscCall(DMPlexGetGeometryFVM(plex, NULL, NULL, &minRadius));
1659   PetscCall(DMDestroy(&plex));
1660   PetscCallMPI(MPI_Allreduce(&phys->maxspeed,&mod->maxspeed,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
1661   PetscCheck(mod->maxspeed > 0,comm,PETSC_ERR_ARG_WRONGSTATE,"Physics '%s' did not set maxspeed",physname);
1662   dt   = cfl * minRadius / mod->maxspeed;
1663   PetscCall(TSSetTimeStep(ts,dt));
1664   PetscCall(TSSetFromOptions(ts));
1665   if (!useAMR) {
1666     PetscCall(TSSolve(ts,X));
1667     PetscCall(TSGetSolveTime(ts,&ftime));
1668     PetscCall(TSGetStepNumber(ts,&nsteps));
1669   } else {
1670     PetscReal finalTime;
1671     PetscInt  adaptIter;
1672     TS        tsNew = NULL;
1673     Vec       solNew = NULL;
1674 
1675     PetscCall(TSGetMaxTime(ts,&finalTime));
1676     PetscCall(TSSetMaxSteps(ts,adaptInterval));
1677     PetscCall(TSSolve(ts,X));
1678     PetscCall(TSGetSolveTime(ts,&ftime));
1679     PetscCall(TSGetStepNumber(ts,&nsteps));
1680     for (adaptIter = 0;ftime < finalTime;adaptIter++) {
1681       PetscLogDouble bytes;
1682 
1683       PetscCall(PetscMemoryGetCurrentUsage(&bytes));
1684       PetscCall(PetscInfo(ts, "AMR time step loop %" PetscInt_FMT ": memory used %g\n", adaptIter, bytes));
1685       PetscCall(PetscFVSetLimiter(fvm,noneLimiter));
1686       PetscCall(adaptToleranceFVM(fvm,ts,X,refineTag,coarsenTag,user,&tsNew,&solNew));
1687       PetscCall(PetscFVSetLimiter(fvm,limiter));
1688       if (tsNew) {
1689         PetscCall(PetscInfo(ts, "AMR used\n"));
1690         PetscCall(DMDestroy(&dm));
1691         PetscCall(VecDestroy(&X));
1692         PetscCall(TSDestroy(&ts));
1693         ts   = tsNew;
1694         X    = solNew;
1695         PetscCall(TSSetFromOptions(ts));
1696         PetscCall(VecGetDM(X,&dm));
1697         PetscCall(PetscObjectReference((PetscObject)dm));
1698         PetscCall(DMConvert(dm, DMPLEX, &plex));
1699         PetscCall(DMPlexGetGeometryFVM(dm, NULL, NULL, &minRadius));
1700         PetscCall(DMDestroy(&plex));
1701         PetscCallMPI(MPI_Allreduce(&phys->maxspeed,&mod->maxspeed,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
1702         PetscCheck(mod->maxspeed > 0,comm,PETSC_ERR_ARG_WRONGSTATE,"Physics '%s' did not set maxspeed",physname);
1703         dt   = cfl * minRadius / mod->maxspeed;
1704         PetscCall(TSSetStepNumber(ts,nsteps));
1705         PetscCall(TSSetTime(ts,ftime));
1706         PetscCall(TSSetTimeStep(ts,dt));
1707       } else {
1708         PetscCall(PetscInfo(ts, "AMR not used\n"));
1709       }
1710       user->monitorStepOffset = nsteps;
1711       PetscCall(TSSetMaxSteps(ts,nsteps+adaptInterval));
1712       PetscCall(TSSolve(ts,X));
1713       PetscCall(TSGetSolveTime(ts,&ftime));
1714       PetscCall(TSGetStepNumber(ts,&nsteps));
1715     }
1716   }
1717   PetscCall(TSGetConvergedReason(ts,&reason));
1718   PetscCall(PetscPrintf(PETSC_COMM_WORLD,"%s at time %g after %" PetscInt_FMT " steps\n",TSConvergedReasons[reason],(double)ftime,nsteps));
1719   PetscCall(TSDestroy(&ts));
1720 
1721   PetscCall(VecTaggerDestroy(&refineTag));
1722   PetscCall(VecTaggerDestroy(&coarsenTag));
1723   PetscCall(PetscFunctionListDestroy(&PhysicsList));
1724   PetscCall(PetscFunctionListDestroy(&PhysicsRiemannList_SW));
1725   PetscCall(FunctionalLinkDestroy(&user->model->functionalRegistry));
1726   PetscCall(PetscFree(user->model->functionalMonitored));
1727   PetscCall(PetscFree(user->model->functionalCall));
1728   PetscCall(PetscFree(user->model->physics->data));
1729   PetscCall(PetscFree(user->model->physics));
1730   PetscCall(PetscFree(user->model));
1731   PetscCall(PetscFree(user));
1732   PetscCall(VecDestroy(&X));
1733   PetscCall(PetscLimiterDestroy(&limiter));
1734   PetscCall(PetscLimiterDestroy(&noneLimiter));
1735   PetscCall(PetscFVDestroy(&fvm));
1736   PetscCall(DMDestroy(&dm));
1737   PetscCall(PetscFinalize());
1738   return 0;
1739 }
1740 
1741 /* Godunov fluxs */
1742 PetscScalar cvmgp_(PetscScalar *a, PetscScalar *b, PetscScalar *test)
1743 {
1744     /* System generated locals */
1745     PetscScalar ret_val;
1746 
1747     if (PetscRealPart(*test) > 0.) {
1748         goto L10;
1749     }
1750     ret_val = *b;
1751     return ret_val;
1752 L10:
1753     ret_val = *a;
1754     return ret_val;
1755 } /* cvmgp_ */
1756 
1757 PetscScalar cvmgm_(PetscScalar *a, PetscScalar *b, PetscScalar *test)
1758 {
1759     /* System generated locals */
1760     PetscScalar ret_val;
1761 
1762     if (PetscRealPart(*test) < 0.) {
1763         goto L10;
1764     }
1765     ret_val = *b;
1766     return ret_val;
1767 L10:
1768     ret_val = *a;
1769     return ret_val;
1770 } /* cvmgm_ */
1771 
1772 int riem1mdt( PetscScalar *gaml, PetscScalar *gamr, PetscScalar *rl, PetscScalar *pl,
1773               PetscScalar *uxl, PetscScalar *rr, PetscScalar *pr,
1774               PetscScalar *uxr, PetscScalar *rstarl, PetscScalar *rstarr, PetscScalar *
1775               pstar, PetscScalar *ustar)
1776 {
1777     /* Initialized data */
1778 
1779     static PetscScalar smallp = 1e-8;
1780 
1781     /* System generated locals */
1782     int i__1;
1783     PetscScalar d__1, d__2;
1784 
1785     /* Local variables */
1786     static int i0;
1787     static PetscScalar cl, cr, wl, zl, wr, zr, pst, durl, skpr1, skpr2;
1788     static int iwave;
1789     static PetscScalar gascl4, gascr4, cstarl, dpstar, cstarr;
1790     /* static PetscScalar csqrl, csqrr, gascl1, gascl2, gascl3, gascr1, gascr2, gascr3; */
1791     static int iterno;
1792     static PetscScalar ustarl, ustarr, rarepr1, rarepr2;
1793 
1794     /* gascl1 = *gaml - 1.; */
1795     /* gascl2 = (*gaml + 1.) * .5; */
1796     /* gascl3 = gascl2 / *gaml; */
1797     gascl4 = 1. / (*gaml - 1.);
1798 
1799     /* gascr1 = *gamr - 1.; */
1800     /* gascr2 = (*gamr + 1.) * .5; */
1801     /* gascr3 = gascr2 / *gamr; */
1802     gascr4 = 1. / (*gamr - 1.);
1803     iterno = 10;
1804 /*        find pstar: */
1805     cl = PetscSqrtScalar(*gaml * *pl / *rl);
1806     cr = PetscSqrtScalar(*gamr * *pr / *rr);
1807     wl = *rl * cl;
1808     wr = *rr * cr;
1809     /* csqrl = wl * wl; */
1810     /* csqrr = wr * wr; */
1811     *pstar = (wl * *pr + wr * *pl) / (wl + wr);
1812     *pstar = PetscMax(PetscRealPart(*pstar),PetscRealPart(smallp));
1813     pst = *pl / *pr;
1814     skpr1 = cr * (pst - 1.) * PetscSqrtScalar(2. / (*gamr * (*gamr - 1. + (*gamr + 1.) * pst)));
1815     d__1 = (*gamr - 1.) / (*gamr * 2.);
1816     rarepr2 = gascr4 * 2. * cr * (1. - PetscPowScalar(pst, d__1));
1817     pst = *pr / *pl;
1818     skpr2 = cl * (pst - 1.) * PetscSqrtScalar(2. / (*gaml * (*gaml - 1. + (*gaml + 1.) * pst)));
1819     d__1 = (*gaml - 1.) / (*gaml * 2.);
1820     rarepr1 = gascl4 * 2. * cl * (1. - PetscPowScalar(pst, d__1));
1821     durl = *uxr - *uxl;
1822     if (PetscRealPart(*pr) < PetscRealPart(*pl)) {
1823         if (PetscRealPart(durl) >= PetscRealPart(rarepr1)) {
1824             iwave = 100;
1825         } else if (PetscRealPart(durl) <= PetscRealPart(-skpr1)) {
1826             iwave = 300;
1827         } else {
1828             iwave = 400;
1829         }
1830     } else {
1831         if (PetscRealPart(durl) >= PetscRealPart(rarepr2)) {
1832             iwave = 100;
1833         } else if (PetscRealPart(durl) <= PetscRealPart(-skpr2)) {
1834             iwave = 300;
1835         } else {
1836             iwave = 200;
1837         }
1838     }
1839     if (iwave == 100) {
1840 /*     1-wave: rarefaction wave, 3-wave: rarefaction wave */
1841 /*     case (100) */
1842         i__1 = iterno;
1843         for (i0 = 1; i0 <= i__1; ++i0) {
1844             d__1 = *pstar / *pl;
1845             d__2 = 1. / *gaml;
1846             *rstarl = *rl * PetscPowScalar(d__1, d__2);
1847             cstarl = PetscSqrtScalar(*gaml * *pstar / *rstarl);
1848             ustarl = *uxl - gascl4 * 2. * (cstarl - cl);
1849             zl = *rstarl * cstarl;
1850             d__1 = *pstar / *pr;
1851             d__2 = 1. / *gamr;
1852             *rstarr = *rr * PetscPowScalar(d__1, d__2);
1853             cstarr = PetscSqrtScalar(*gamr * *pstar / *rstarr);
1854             ustarr = *uxr + gascr4 * 2. * (cstarr - cr);
1855             zr = *rstarr * cstarr;
1856             dpstar = zl * zr * (ustarr - ustarl) / (zl + zr);
1857             *pstar -= dpstar;
1858             *pstar = PetscMax(PetscRealPart(*pstar),PetscRealPart(smallp));
1859             if (PetscAbsScalar(dpstar) / PetscRealPart(*pstar) <= 1e-8) {
1860 #if 0
1861         break;
1862 #endif
1863             }
1864         }
1865 /*     1-wave: shock wave, 3-wave: rarefaction wave */
1866     } else if (iwave == 200) {
1867 /*     case (200) */
1868         i__1 = iterno;
1869         for (i0 = 1; i0 <= i__1; ++i0) {
1870             pst = *pstar / *pl;
1871             ustarl = *uxl - (pst - 1.) * cl * PetscSqrtScalar(2. / (*gaml * (*gaml - 1. + (*gaml + 1.) * pst)));
1872             zl = *pl / cl * PetscSqrtScalar(*gaml * 2. * (*gaml - 1. + (*gaml + 1.) * pst)) * (*gaml - 1. + (*gaml + 1.) * pst) / (*gaml * 3. - 1. + (*gaml + 1.) * pst);
1873             d__1 = *pstar / *pr;
1874             d__2 = 1. / *gamr;
1875             *rstarr = *rr * PetscPowScalar(d__1, d__2);
1876             cstarr = PetscSqrtScalar(*gamr * *pstar / *rstarr);
1877             zr = *rstarr * cstarr;
1878             ustarr = *uxr + gascr4 * 2. * (cstarr - cr);
1879             dpstar = zl * zr * (ustarr - ustarl) / (zl + zr);
1880             *pstar -= dpstar;
1881             *pstar = PetscMax(PetscRealPart(*pstar),PetscRealPart(smallp));
1882             if (PetscAbsScalar(dpstar) / PetscRealPart(*pstar) <= 1e-8) {
1883 #if 0
1884         break;
1885 #endif
1886             }
1887         }
1888 /*     1-wave: shock wave, 3-wave: shock */
1889     } else if (iwave == 300) {
1890 /*     case (300) */
1891         i__1 = iterno;
1892         for (i0 = 1; i0 <= i__1; ++i0) {
1893             pst = *pstar / *pl;
1894             ustarl = *uxl - (pst - 1.) * cl * PetscSqrtScalar(2. / (*gaml * (*gaml - 1. + (*gaml + 1.) * pst)));
1895             zl = *pl / cl * PetscSqrtScalar(*gaml * 2. * (*gaml - 1. + (*gaml + 1.) * pst)) * (*gaml - 1. + (*gaml + 1.) * pst) / (*gaml * 3. - 1. + (*gaml + 1.) * pst);
1896             pst = *pstar / *pr;
1897             ustarr = *uxr + (pst - 1.) * cr * PetscSqrtScalar(2. / (*gamr * (*gamr - 1. + (*gamr + 1.) * pst)));
1898             zr = *pr / cr * PetscSqrtScalar(*gamr * 2. * (*gamr - 1. + (*gamr + 1.) * pst)) * (*gamr - 1. + (*gamr + 1.) * pst) / (*gamr * 3. - 1. + (*gamr + 1.) * pst);
1899             dpstar = zl * zr * (ustarr - ustarl) / (zl + zr);
1900             *pstar -= dpstar;
1901             *pstar = PetscMax(PetscRealPart(*pstar),PetscRealPart(smallp));
1902             if (PetscAbsScalar(dpstar) / PetscRealPart(*pstar) <= 1e-8) {
1903 #if 0
1904         break;
1905 #endif
1906             }
1907         }
1908 /*     1-wave: rarefaction wave, 3-wave: shock */
1909     } else if (iwave == 400) {
1910 /*     case (400) */
1911         i__1 = iterno;
1912         for (i0 = 1; i0 <= i__1; ++i0) {
1913             d__1 = *pstar / *pl;
1914             d__2 = 1. / *gaml;
1915             *rstarl = *rl * PetscPowScalar(d__1, d__2);
1916             cstarl = PetscSqrtScalar(*gaml * *pstar / *rstarl);
1917             ustarl = *uxl - gascl4 * 2. * (cstarl - cl);
1918             zl = *rstarl * cstarl;
1919             pst = *pstar / *pr;
1920             ustarr = *uxr + (pst - 1.) * cr * PetscSqrtScalar(2. / (*gamr * (*gamr - 1. + (*gamr + 1.) * pst)));
1921             zr = *pr / cr * PetscSqrtScalar(*gamr * 2. * (*gamr - 1. + (*gamr + 1.) * pst)) * (*gamr - 1. + (*gamr + 1.) * pst) / (*gamr * 3. - 1. + (*gamr + 1.) * pst);
1922             dpstar = zl * zr * (ustarr - ustarl) / (zl + zr);
1923             *pstar -= dpstar;
1924             *pstar = PetscMax(PetscRealPart(*pstar),PetscRealPart(smallp));
1925             if (PetscAbsScalar(dpstar) / PetscRealPart(*pstar) <= 1e-8) {
1926 #if 0
1927               break;
1928 #endif
1929             }
1930         }
1931     }
1932 
1933     *ustar = (zl * ustarr + zr * ustarl) / (zl + zr);
1934     if (PetscRealPart(*pstar) > PetscRealPart(*pl)) {
1935         pst = *pstar / *pl;
1936         *rstarl = ((*gaml + 1.) * pst + *gaml - 1.) / ((*gaml - 1.) * pst + *
1937                 gaml + 1.) * *rl;
1938     }
1939     if (PetscRealPart(*pstar) > PetscRealPart(*pr)) {
1940         pst = *pstar / *pr;
1941         *rstarr = ((*gamr + 1.) * pst + *gamr - 1.) / ((*gamr - 1.) * pst + *
1942                 gamr + 1.) * *rr;
1943     }
1944     return iwave;
1945 }
1946 
1947 PetscScalar sign(PetscScalar x)
1948 {
1949     if (PetscRealPart(x) > 0) return 1.0;
1950     if (PetscRealPart(x) < 0) return -1.0;
1951     return 0.0;
1952 }
1953 /*        Riemann Solver */
1954 /* -------------------------------------------------------------------- */
1955 int riemannsolver(PetscScalar *xcen, PetscScalar *xp,
1956                    PetscScalar *dtt, PetscScalar *rl, PetscScalar *uxl, PetscScalar *pl,
1957                    PetscScalar *utl, PetscScalar *ubl, PetscScalar *gaml, PetscScalar *rho1l,
1958                    PetscScalar *rr, PetscScalar *uxr, PetscScalar *pr, PetscScalar *utr,
1959                    PetscScalar *ubr, PetscScalar *gamr, PetscScalar *rho1r, PetscScalar *rx,
1960                    PetscScalar *uxm, PetscScalar *px, PetscScalar *utx, PetscScalar *ubx,
1961                    PetscScalar *gam, PetscScalar *rho1)
1962 {
1963     /* System generated locals */
1964     PetscScalar d__1, d__2;
1965 
1966     /* Local variables */
1967     static PetscScalar s, c0, p0, r0, u0, w0, x0, x2, ri, cx, sgn0, wsp0, gasc1, gasc2, gasc3, gasc4;
1968     static PetscScalar cstar, pstar, rstar, ustar, xstar, wspst, ushock, streng, rstarl, rstarr, rstars;
1969     int iwave;
1970 
1971     if (*rl == *rr && *pr == *pl && *uxl == *uxr && *gaml == *gamr) {
1972         *rx = *rl;
1973         *px = *pl;
1974         *uxm = *uxl;
1975         *gam = *gaml;
1976         x2 = *xcen + *uxm * *dtt;
1977 
1978         if (PetscRealPart(*xp) >= PetscRealPart(x2)) {
1979             *utx = *utr;
1980             *ubx = *ubr;
1981             *rho1 = *rho1r;
1982         } else {
1983             *utx = *utl;
1984             *ubx = *ubl;
1985             *rho1 = *rho1l;
1986         }
1987         return 0;
1988     }
1989     iwave = riem1mdt(gaml, gamr, rl, pl, uxl, rr, pr, uxr, &rstarl, &rstarr, &pstar, &ustar);
1990 
1991     x2 = *xcen + ustar * *dtt;
1992     d__1 = *xp - x2;
1993     sgn0 = sign(d__1);
1994 /*            x is in 3-wave if sgn0 = 1 */
1995 /*            x is in 1-wave if sgn0 = -1 */
1996     r0 = cvmgm_(rl, rr, &sgn0);
1997     p0 = cvmgm_(pl, pr, &sgn0);
1998     u0 = cvmgm_(uxl, uxr, &sgn0);
1999     *gam = cvmgm_(gaml, gamr, &sgn0);
2000     gasc1 = *gam - 1.;
2001     gasc2 = (*gam + 1.) * .5;
2002     gasc3 = gasc2 / *gam;
2003     gasc4 = 1. / (*gam - 1.);
2004     c0 = PetscSqrtScalar(*gam * p0 / r0);
2005     streng = pstar - p0;
2006     w0 = *gam * r0 * p0 * (gasc3 * streng / p0 + 1.);
2007     rstars = r0 / (1. - r0 * streng / w0);
2008     d__1 = p0 / pstar;
2009     d__2 = -1. / *gam;
2010     rstarr = r0 * PetscPowScalar(d__1, d__2);
2011     rstar = cvmgm_(&rstarr, &rstars, &streng);
2012     w0 = PetscSqrtScalar(w0);
2013     cstar = PetscSqrtScalar(*gam * pstar / rstar);
2014     wsp0 = u0 + sgn0 * c0;
2015     wspst = ustar + sgn0 * cstar;
2016     ushock = ustar + sgn0 * w0 / rstar;
2017     wspst = cvmgp_(&ushock, &wspst, &streng);
2018     wsp0 = cvmgp_(&ushock, &wsp0, &streng);
2019     x0 = *xcen + wsp0 * *dtt;
2020     xstar = *xcen + wspst * *dtt;
2021 /*           using gas formula to evaluate rarefaction wave */
2022 /*            ri : reiman invariant */
2023     ri = u0 - sgn0 * 2. * gasc4 * c0;
2024     cx = sgn0 * .5 * gasc1 / gasc2 * ((*xp - *xcen) / *dtt - ri);
2025     *uxm = ri + sgn0 * 2. * gasc4 * cx;
2026     s = p0 / PetscPowScalar(r0, *gam);
2027     d__1 = cx * cx / (*gam * s);
2028     *rx = PetscPowScalar(d__1, gasc4);
2029     *px = cx * cx * *rx / *gam;
2030     d__1 = sgn0 * (x0 - *xp);
2031     *rx = cvmgp_(rx, &r0, &d__1);
2032     d__1 = sgn0 * (x0 - *xp);
2033     *px = cvmgp_(px, &p0, &d__1);
2034     d__1 = sgn0 * (x0 - *xp);
2035     *uxm = cvmgp_(uxm, &u0, &d__1);
2036     d__1 = sgn0 * (xstar - *xp);
2037     *rx = cvmgm_(rx, &rstar, &d__1);
2038     d__1 = sgn0 * (xstar - *xp);
2039     *px = cvmgm_(px, &pstar, &d__1);
2040     d__1 = sgn0 * (xstar - *xp);
2041     *uxm = cvmgm_(uxm, &ustar, &d__1);
2042     if (PetscRealPart(*xp) >= PetscRealPart(x2)) {
2043         *utx = *utr;
2044         *ubx = *ubr;
2045         *rho1 = *rho1r;
2046     } else {
2047         *utx = *utl;
2048         *ubx = *ubl;
2049         *rho1 = *rho1l;
2050     }
2051     return iwave;
2052 }
2053 int godunovflux( const PetscScalar *ul, const PetscScalar *ur,
2054                  PetscScalar *flux, const PetscReal *nn, const int *ndim,
2055                  const PetscReal *gamma)
2056 {
2057     /* System generated locals */
2058   int i__1,iwave;
2059     PetscScalar d__1, d__2, d__3;
2060 
2061     /* Local variables */
2062     static int k;
2063     static PetscScalar bn[3], fn, ft, tg[3], pl, rl, pm, pr, rr, xp, ubl, ubm,
2064             ubr, dtt, unm, tmp, utl, utm, uxl, utr, uxr, gaml, gamm, gamr,
2065             xcen, rhom, rho1l, rho1m, rho1r;
2066 
2067     /* Function Body */
2068     xcen = 0.;
2069     xp = 0.;
2070     i__1 = *ndim;
2071     for (k = 1; k <= i__1; ++k) {
2072         tg[k - 1] = 0.;
2073         bn[k - 1] = 0.;
2074     }
2075     dtt = 1.;
2076     if (*ndim == 3) {
2077         if (nn[0] == 0. && nn[1] == 0.) {
2078             tg[0] = 1.;
2079         } else {
2080             tg[0] = -nn[1];
2081             tg[1] = nn[0];
2082         }
2083 /*           tmp=dsqrt(tg(1)**2+tg(2)**2) */
2084 /*           tg=tg/tmp */
2085         bn[0] = -nn[2] * tg[1];
2086         bn[1] = nn[2] * tg[0];
2087         bn[2] = nn[0] * tg[1] - nn[1] * tg[0];
2088 /* Computing 2nd power */
2089         d__1 = bn[0];
2090 /* Computing 2nd power */
2091         d__2 = bn[1];
2092 /* Computing 2nd power */
2093         d__3 = bn[2];
2094         tmp = PetscSqrtScalar(d__1 * d__1 + d__2 * d__2 + d__3 * d__3);
2095         i__1 = *ndim;
2096         for (k = 1; k <= i__1; ++k) {
2097             bn[k - 1] /= tmp;
2098         }
2099     } else if (*ndim == 2) {
2100         tg[0] = -nn[1];
2101         tg[1] = nn[0];
2102 /*           tmp=dsqrt(tg(1)**2+tg(2)**2) */
2103 /*           tg=tg/tmp */
2104         bn[0] = 0.;
2105         bn[1] = 0.;
2106         bn[2] = 1.;
2107     }
2108     rl = ul[0];
2109     rr = ur[0];
2110     uxl = 0.;
2111     uxr = 0.;
2112     utl = 0.;
2113     utr = 0.;
2114     ubl = 0.;
2115     ubr = 0.;
2116     i__1 = *ndim;
2117     for (k = 1; k <= i__1; ++k) {
2118         uxl += ul[k] * nn[k-1];
2119         uxr += ur[k] * nn[k-1];
2120         utl += ul[k] * tg[k - 1];
2121         utr += ur[k] * tg[k - 1];
2122         ubl += ul[k] * bn[k - 1];
2123         ubr += ur[k] * bn[k - 1];
2124     }
2125     uxl /= rl;
2126     uxr /= rr;
2127     utl /= rl;
2128     utr /= rr;
2129     ubl /= rl;
2130     ubr /= rr;
2131 
2132     gaml = *gamma;
2133     gamr = *gamma;
2134 /* Computing 2nd power */
2135     d__1 = uxl;
2136 /* Computing 2nd power */
2137     d__2 = utl;
2138 /* Computing 2nd power */
2139     d__3 = ubl;
2140     pl = (*gamma - 1.) * (ul[*ndim + 1] - rl * .5 * (d__1 * d__1 + d__2 * d__2 + d__3 * d__3));
2141 /* Computing 2nd power */
2142     d__1 = uxr;
2143 /* Computing 2nd power */
2144     d__2 = utr;
2145 /* Computing 2nd power */
2146     d__3 = ubr;
2147     pr = (*gamma - 1.) * (ur[*ndim + 1] - rr * .5 * (d__1 * d__1 + d__2 * d__2 + d__3 * d__3));
2148     rho1l = rl;
2149     rho1r = rr;
2150 
2151     iwave = riemannsolver(&xcen, &xp, &dtt, &rl, &uxl, &pl, &utl, &ubl, &gaml, &
2152                           rho1l, &rr, &uxr, &pr, &utr, &ubr, &gamr, &rho1r, &rhom, &unm, &
2153                           pm, &utm, &ubm, &gamm, &rho1m);
2154 
2155     flux[0] = rhom * unm;
2156     fn = rhom * unm * unm + pm;
2157     ft = rhom * unm * utm;
2158 /*           flux(2)=fn*nn(1)+ft*nn(2) */
2159 /*           flux(3)=fn*tg(1)+ft*tg(2) */
2160     flux[1] = fn * nn[0] + ft * tg[0];
2161     flux[2] = fn * nn[1] + ft * tg[1];
2162 /*           flux(2)=rhom*unm*(unm)+pm */
2163 /*           flux(3)=rhom*(unm)*utm */
2164     if (*ndim == 3) {
2165         flux[3] = rhom * unm * ubm;
2166     }
2167     flux[*ndim + 1] = (rhom * .5 * (unm * unm + utm * utm + ubm * ubm) + gamm / (gamm - 1.) * pm) * unm;
2168     return iwave;
2169 } /* godunovflux_ */
2170 
2171 /* Subroutine to set up the initial conditions for the */
2172 /* Shock Interface interaction or linear wave (Ravi Samtaney,Mark Adams). */
2173 /* ----------------------------------------------------------------------- */
2174 int projecteqstate(PetscReal wc[], const PetscReal ueq[], PetscReal lv[][3])
2175 {
2176   int j,k;
2177 /*      Wc=matmul(lv,Ueq) 3 vars */
2178   for (k = 0; k < 3; ++k) {
2179     wc[k] = 0.;
2180     for (j = 0; j < 3; ++j) {
2181       wc[k] += lv[k][j]*ueq[j];
2182     }
2183   }
2184   return 0;
2185 }
2186 /* ----------------------------------------------------------------------- */
2187 int projecttoprim(PetscReal v[], const PetscReal wc[], PetscReal rv[][3])
2188 {
2189   int k,j;
2190   /*      V=matmul(rv,WC) 3 vars */
2191   for (k = 0; k < 3; ++k) {
2192     v[k] = 0.;
2193     for (j = 0; j < 3; ++j) {
2194       v[k] += rv[k][j]*wc[j];
2195     }
2196   }
2197   return 0;
2198 }
2199 /* ---------------------------------------------------------------------- */
2200 int eigenvectors(PetscReal rv[][3], PetscReal lv[][3], const PetscReal ueq[], PetscReal gamma)
2201 {
2202   int j,k;
2203   PetscReal rho,csnd,p0;
2204   /* PetscScalar u; */
2205 
2206   for (k = 0; k < 3; ++k) for (j = 0; j < 3; ++j) { lv[k][j] = 0.; rv[k][j] = 0.; }
2207   rho = ueq[0];
2208   /* u = ueq[1]; */
2209   p0 = ueq[2];
2210   csnd = PetscSqrtReal(gamma * p0 / rho);
2211   lv[0][1] = rho * .5;
2212   lv[0][2] = -.5 / csnd;
2213   lv[1][0] = csnd;
2214   lv[1][2] = -1. / csnd;
2215   lv[2][1] = rho * .5;
2216   lv[2][2] = .5 / csnd;
2217   rv[0][0] = -1. / csnd;
2218   rv[1][0] = 1. / rho;
2219   rv[2][0] = -csnd;
2220   rv[0][1] = 1. / csnd;
2221   rv[0][2] = 1. / csnd;
2222   rv[1][2] = 1. / rho;
2223   rv[2][2] = csnd;
2224   return 0;
2225 }
2226 
2227 int initLinearWave(EulerNode *ux, const PetscReal gamma, const PetscReal coord[], const PetscReal Lx)
2228 {
2229   PetscReal p0,u0,wcp[3],wc[3];
2230   PetscReal lv[3][3];
2231   PetscReal vp[3];
2232   PetscReal rv[3][3];
2233   PetscReal eps, ueq[3], rho0, twopi;
2234 
2235   /* Function Body */
2236   twopi = 2.*PETSC_PI;
2237   eps = 1e-4; /* perturbation */
2238   rho0 = 1e3;   /* density of water */
2239   p0 = 101325.; /* init pressure of 1 atm (?) */
2240   u0 = 0.;
2241   ueq[0] = rho0;
2242   ueq[1] = u0;
2243   ueq[2] = p0;
2244   /* Project initial state to characteristic variables */
2245   eigenvectors(rv, lv, ueq, gamma);
2246   projecteqstate(wc, ueq, lv);
2247   wcp[0] = wc[0];
2248   wcp[1] = wc[1];
2249   wcp[2] = wc[2] + eps * PetscCosReal(coord[0] * 2. * twopi / Lx);
2250   projecttoprim(vp, wcp, rv);
2251   ux->r = vp[0]; /* density */
2252   ux->ru[0] = vp[0] * vp[1]; /* x momentum */
2253   ux->ru[1] = 0.;
2254 #if defined DIM > 2
2255   if (dim>2) ux->ru[2] = 0.;
2256 #endif
2257   /* E = rho * e + rho * v^2/2 = p/(gam-1) + rho*v^2/2 */
2258   ux->E = vp[2]/(gamma - 1.) + 0.5*vp[0]*vp[1]*vp[1];
2259   return 0;
2260 }
2261 
2262 /*TEST
2263 
2264   testset:
2265     args: -dm_plex_adj_cone -dm_plex_adj_closure 0
2266 
2267     test:
2268       suffix: adv_2d_tri_0
2269       requires: triangle
2270       TODO: how did this ever get in main when there is no support for this
2271       args: -ufv_vtk_interval 0 -simplex -dm_refine 3 -dm_plex_faces 1,1 -dm_plex_separate_marker -bc_inflow 1,2,4 -bc_outflow 3
2272 
2273     test:
2274       suffix: adv_2d_tri_1
2275       requires: triangle
2276       TODO: how did this ever get in main when there is no support for this
2277       args: -ufv_vtk_interval 0 -simplex -dm_refine 5 -dm_plex_faces 1,1 -dm_plex_separate_marker -grid_bounds -0.5,0.5,-0.5,0.5 -bc_inflow 1,2,4 -bc_outflow 3 -advect_sol_type bump -advect_bump_center 0.25,0 -advect_bump_radius 0.1
2278 
2279     test:
2280       suffix: tut_1
2281       requires: exodusii
2282       nsize: 1
2283       args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside.exo
2284 
2285     test:
2286       suffix: tut_2
2287       requires: exodusii
2288       nsize: 1
2289       args: -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside.exo -ts_type rosw
2290 
2291     test:
2292       suffix: tut_3
2293       requires: exodusii
2294       nsize: 4
2295       args: -dm_distribute_overlap 1 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/annulus-20.exo -monitor Error -advect_sol_type bump -petscfv_type leastsquares -petsclimiter_type sin
2296 
2297     test:
2298       suffix: tut_4
2299       requires: exodusii
2300       nsize: 4
2301       args: -dm_distribute_overlap 1 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/annulus-20.exo -physics sw -monitor Height,Energy -petscfv_type leastsquares -petsclimiter_type minmod
2302 
2303   testset:
2304     args: -dm_plex_adj_cone -dm_plex_adj_closure 0 -dm_plex_simplex 0 -dm_plex_box_faces 1,1,1
2305 
2306     # 2D Advection 0-10
2307     test:
2308       suffix: 0
2309       requires: exodusii
2310       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside.exo
2311 
2312     test:
2313       suffix: 1
2314       requires: exodusii
2315       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad-15.exo
2316 
2317     test:
2318       suffix: 2
2319       requires: exodusii
2320       nsize: 2
2321       args: -dm_distribute_overlap 1 -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside.exo
2322 
2323     test:
2324       suffix: 3
2325       requires: exodusii
2326       nsize: 2
2327       args: -dm_distribute_overlap 1 -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad-15.exo
2328 
2329     test:
2330       suffix: 4
2331       requires: exodusii
2332       nsize: 8
2333       args: -dm_distribute_overlap 1 -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo
2334 
2335     test:
2336       suffix: 5
2337       requires: exodusii
2338       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside.exo -ts_type rosw -ts_adapt_reject_safety 1
2339 
2340     test:
2341       suffix: 7
2342       requires: exodusii
2343       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad-15.exo -dm_refine 1
2344 
2345     test:
2346       suffix: 8
2347       requires: exodusii
2348       nsize: 2
2349       args: -dm_distribute_overlap 1 -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad-15.exo -dm_refine 1
2350 
2351     test:
2352       suffix: 9
2353       requires: exodusii
2354       nsize: 8
2355       args: -dm_distribute_overlap 1 -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad-15.exo -dm_refine 1
2356 
2357     test:
2358       suffix: 10
2359       requires: exodusii
2360       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/sevenside-quad.exo
2361 
2362     # 2D Shallow water
2363     test:
2364       suffix: sw_0
2365       requires: exodusii
2366       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/annulus-20.exo -bc_wall 100,101 -physics sw -ufv_cfl 5 -petscfv_type   leastsquares -petsclimiter_type sin -ts_max_time 1 -ts_ssp_type rks2 -ts_ssp_nstages 10 -monitor height,energy
2367 
2368     test:
2369       suffix: sw_hll
2370       args: -ufv_vtk_interval 0 -bc_wall 1,2,3,4 -physics sw -ufv_cfl 3 -petscfv_type leastsquares -petsclimiter_type sin -ts_max_steps 5 -ts_ssp_type rks2 -ts_ssp_nstages 10 -monitor height,energy -grid_bounds 0,5,0,5 -dm_plex_box_faces 25,25 -sw_riemann hll
2371 
2372     # 2D Advection: p4est
2373     test:
2374       suffix: p4est_advec_2d
2375       requires: p4est
2376       args: -ufv_vtk_interval 0 -dm_type p4est -dm_forest_minimum_refinement 1 -dm_forest_initial_refinement 2 -dm_p4est_refine_pattern hash   -dm_forest_maximum_refinement 5
2377 
2378     # Advection in a box
2379     test:
2380       suffix: adv_2d_quad_0
2381       args: -ufv_vtk_interval 0 -dm_refine 3 -dm_plex_separate_marker -bc_inflow 1,2,4 -bc_outflow 3
2382 
2383     test:
2384       suffix: adv_2d_quad_1
2385       args: -ufv_vtk_interval 0 -dm_refine 3 -dm_plex_separate_marker -grid_bounds -0.5,0.5,-0.5,0.5 -bc_inflow 1,2,4 -bc_outflow 3 -advect_sol_type bump -advect_bump_center 0.25,0 -advect_bump_radius 0.1
2386       timeoutfactor: 3
2387 
2388     test:
2389       suffix: adv_2d_quad_p4est_0
2390       requires: p4est
2391       args: -ufv_vtk_interval 0 -dm_refine 5 -dm_type p4est -dm_plex_separate_marker -bc_inflow 1,2,4 -bc_outflow 3
2392 
2393     test:
2394       suffix: adv_2d_quad_p4est_1
2395       requires: p4est
2396       args: -ufv_vtk_interval 0 -dm_refine 5 -dm_type p4est -dm_plex_separate_marker -grid_bounds -0.5,0.5,-0.5,0.5 -bc_inflow 1,2,4 -bc_outflow   3 -advect_sol_type bump -advect_bump_center 0.25,0 -advect_bump_radius 0.1
2397       timeoutfactor: 3
2398 
2399     test:
2400       suffix: adv_2d_quad_p4est_adapt_0
2401       requires: p4est !__float128 #broken for quad precision
2402       args: -ufv_vtk_interval 0 -dm_refine 3 -dm_type p4est -dm_plex_separate_marker -grid_bounds -0.5,0.5,-0.5,0.5 -bc_inflow 1,2,4 -bc_outflow   3 -advect_sol_type bump -advect_bump_center 0.25,0 -advect_bump_radius 0.1 -ufv_use_amr -refine_vec_tagger_box 0.005,inf -coarsen_vec_tagger_box   0,1.e-5 -petscfv_type leastsquares -ts_max_time 0.01
2403       timeoutfactor: 3
2404 
2405     test:
2406       suffix: adv_0
2407       requires: exodusii
2408       args: -ufv_vtk_interval 0 -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/blockcylinder-50.exo -bc_inflow 100,101,200 -bc_outflow 201
2409 
2410     test:
2411       suffix: shock_0
2412       requires: p4est !single !complex
2413       args: -dm_plex_box_faces 2,1 -grid_bounds -1,1.,0.,1 -grid_skew_60 \
2414       -dm_type p4est -dm_forest_partition_overlap 1 -dm_forest_maximum_refinement 6 -dm_forest_minimum_refinement 2 -dm_forest_initial_refinement 2 \
2415       -ufv_use_amr -refine_vec_tagger_box 0.5,inf -coarsen_vec_tagger_box 0,1.e-2 -refine_tag_view -coarsen_tag_view \
2416       -bc_wall 1,2,3,4 -physics euler -eu_type iv_shock -ufv_cfl 10 -eu_alpha 60. -eu_gamma 1.4 -eu_amach 2.02 -eu_rho2 3. \
2417       -petscfv_type leastsquares -petsclimiter_type minmod -petscfv_compute_gradients 0 \
2418       -ts_max_time 0.5 -ts_ssp_type rks2 -ts_ssp_nstages 10 \
2419       -ufv_vtk_basename ${wPETSC_DIR}/ex11 -ufv_vtk_interval 0 -monitor density,energy
2420       timeoutfactor: 3
2421 
2422     # Test GLVis visualization of PetscFV fields
2423     test:
2424       suffix: glvis_adv_2d_tet
2425       args: -ufv_vtk_interval 0 -ufv_vtk_monitor 0 \
2426             -dm_plex_filename ${wPETSC_DIR}/share/petsc/datafiles/meshes/square_periodic.msh -dm_plex_gmsh_periodic 0 \
2427             -ts_monitor_solution glvis: -ts_max_steps 0
2428 
2429     test:
2430       suffix: glvis_adv_2d_quad
2431       args: -ufv_vtk_interval 0 -ufv_vtk_monitor 0 -bc_inflow 1,2,4 -bc_outflow 3 \
2432             -dm_refine 5 -dm_plex_separate_marker \
2433             -ts_monitor_solution glvis: -ts_max_steps 0
2434 
2435 TEST*/
2436