Actual source code: ex9.c

petsc-master 2017-02-17
Report Typos and Errors
  1: static const char help[] = "1D periodic Finite Volume solver in slope-limiter form with semidiscrete time stepping.\n"
  2:   "Solves scalar and vector problems, choose the physical model with -physics\n"
  3:   "  advection   - Constant coefficient scalar advection\n"
  4:   "                u_t       + (a*u)_x               = 0\n"
  5:   "  burgers     - Burgers equation\n"
  6:   "                u_t       + (u^2/2)_x             = 0\n"
  7:   "  traffic     - Traffic equation\n"
  8:   "                u_t       + (u*(1-u))_x           = 0\n"
  9:   "  acoustics   - Acoustic wave propagation\n"
 10:   "                u_t       + (c*z*v)_x             = 0\n"
 11:   "                v_t       + (c/z*u)_x             = 0\n"
 12:   "  isogas      - Isothermal gas dynamics\n"
 13:   "                rho_t     + (rho*u)_x             = 0\n"
 14:   "                (rho*u)_t + (rho*u^2 + c^2*rho)_x = 0\n"
 15:   "  shallow     - Shallow water equations\n"
 16:   "                h_t       + (h*u)_x               = 0\n"
 17:   "                (h*u)_t   + (h*u^2 + g*h^2/2)_x   = 0\n"
 18:   "Some of these physical models have multiple Riemann solvers, select these with -physics_xxx_riemann\n"
 19:   "  exact       - Exact Riemann solver which usually needs to perform a Newton iteration to connect\n"
 20:   "                the states across shocks and rarefactions\n"
 21:   "  roe         - Linearized scheme, usually with an entropy fix inside sonic rarefactions\n"
 22:   "The systems provide a choice of reconstructions with -physics_xxx_reconstruct\n"
 23:   "  characteristic - Limit the characteristic variables, this is usually preferred (default)\n"
 24:   "  conservative   - Limit the conservative variables directly, can cause undesired interaction of waves\n\n"
 25:   "A variety of limiters for high-resolution TVD limiters are available with -limit\n"
 26:   "  upwind,minmod,superbee,mc,vanleer,vanalbada,koren,cada-torillhon (last two are nominally third order)\n"
 27:   "  and non-TVD schemes lax-wendroff,beam-warming,fromm\n\n"
 28:   "To preserve the TVD property, one should time step with a strong stability preserving method.\n"
 29:   "The optimal high order explicit Runge-Kutta methods in TSSSP are recommended for non-stiff problems.\n\n"
 30:   "Several initial conditions can be chosen with -initial N\n\n"
 31:   "The problem size should be set with -da_grid_x M\n\n";

 33:  #include <petscts.h>
 34:  #include <petscdm.h>
 35:  #include <petscdmda.h>
 36:  #include <petscdraw.h>

 38: #include <petsc/private/kernels/blockinvert.h> /* For the Kernel_*_gets_* stuff for BAIJ */

 40: PETSC_STATIC_INLINE PetscReal Sgn(PetscReal a) { return (a<0) ? -1 : 1; }
 41: PETSC_STATIC_INLINE PetscReal Abs(PetscReal a) { return (a<0) ? 0 : a; }
 42: PETSC_STATIC_INLINE PetscReal Sqr(PetscReal a) { return a*a; }
 43: PETSC_STATIC_INLINE PetscReal MaxAbs(PetscReal a,PetscReal b) { return (PetscAbs(a) > PetscAbs(b)) ? a : b; }
 44: PETSC_UNUSED PETSC_STATIC_INLINE PetscReal MinAbs(PetscReal a,PetscReal b) { return (PetscAbs(a) < PetscAbs(b)) ? a : b; }
 45: PETSC_STATIC_INLINE PetscReal MinMod2(PetscReal a,PetscReal b) { return (a*b<0) ? 0 : Sgn(a)*PetscMin(PetscAbs(a),PetscAbs(b)); }
 46: PETSC_STATIC_INLINE PetscReal MaxMod2(PetscReal a,PetscReal b) { return (a*b<0) ? 0 : Sgn(a)*PetscMax(PetscAbs(a),PetscAbs(b)); }
 47: PETSC_STATIC_INLINE PetscReal MinMod3(PetscReal a,PetscReal b,PetscReal c) {return (a*b<0 || a*c<0) ? 0 : Sgn(a)*PetscMin(PetscAbs(a),PetscMin(PetscAbs(b),PetscAbs(c))); }

 49: PETSC_STATIC_INLINE PetscReal RangeMod(PetscReal a,PetscReal xmin,PetscReal xmax) { PetscReal range = xmax-xmin; return xmin +PetscFmodReal(range+PetscFmodReal(a,range),range); }


 52: /* ----------------------- Lots of limiters, these could go in a separate library ------------------------- */
 53: typedef struct _LimitInfo {
 54:   PetscReal hx;
 55:   PetscInt  m;
 56: } *LimitInfo;
 57: static void Limit_Upwind(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 58: {
 59:   PetscInt i;
 60:   for (i=0; i<info->m; i++) lmt[i] = 0;
 61: }
 62: static void Limit_LaxWendroff(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 63: {
 64:   PetscInt i;
 65:   for (i=0; i<info->m; i++) lmt[i] = jR[i];
 66: }
 67: static void Limit_BeamWarming(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 68: {
 69:   PetscInt i;
 70:   for (i=0; i<info->m; i++) lmt[i] = jL[i];
 71: }
 72: static void Limit_Fromm(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 73: {
 74:   PetscInt i;
 75:   for (i=0; i<info->m; i++) lmt[i] = 0.5*(jL[i] + jR[i]);
 76: }
 77: static void Limit_Minmod(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 78: {
 79:   PetscInt i;
 80:   for (i=0; i<info->m; i++) lmt[i] = MinMod2(jL[i],jR[i]);
 81: }
 82: static void Limit_Superbee(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 83: {
 84:   PetscInt i;
 85:   for (i=0; i<info->m; i++) lmt[i] = MaxMod2(MinMod2(jL[i],2*jR[i]),MinMod2(2*jL[i],jR[i]));
 86: }
 87: static void Limit_MC(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 88: {
 89:   PetscInt i;
 90:   for (i=0; i<info->m; i++) lmt[i] = MinMod3(2*jL[i],0.5*(jL[i]+jR[i]),2*jR[i]);
 91: }
 92: static void Limit_VanLeer(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
 93: { /* phi = (t + abs(t)) / (1 + abs(t)) */
 94:   PetscInt i;
 95:   for (i=0; i<info->m; i++) lmt[i] = (jL[i]*Abs(jR[i]) + Abs(jL[i])*jR[i]) / (Abs(jL[i]) + Abs(jR[i]) + 1e-15);
 96: }
 97: static void Limit_VanAlbada(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt) /* differentiable */
 98: { /* phi = (t + t^2) / (1 + t^2) */
 99:   PetscInt i;
100:   for (i=0; i<info->m; i++) lmt[i] = (jL[i]*Sqr(jR[i]) + Sqr(jL[i])*jR[i]) / (Sqr(jL[i]) + Sqr(jR[i]) + 1e-15);
101: }
102: static void Limit_VanAlbadaTVD(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
103: { /* phi = (t + t^2) / (1 + t^2) */
104:   PetscInt i;
105:   for (i=0; i<info->m; i++) lmt[i] = (jL[i]*jR[i]<0) ? 0 : (jL[i]*Sqr(jR[i]) + Sqr(jL[i])*jR[i]) / (Sqr(jL[i]) + Sqr(jR[i]) + 1e-15);
106: }
107: static void Limit_Koren(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt) /* differentiable */
108: { /* phi = (t + 2*t^2) / (2 - t + 2*t^2) */
109:   PetscInt i;
110:   for (i=0; i<info->m; i++) lmt[i] = ((jL[i]*Sqr(jR[i]) + 2*Sqr(jL[i])*jR[i])/(2*Sqr(jL[i]) - jL[i]*jR[i] + 2*Sqr(jR[i]) + 1e-15));
111: }
112: static void Limit_KorenSym(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt) /* differentiable */
113: { /* Symmetric version of above */
114:   PetscInt i;
115:   for (i=0; i<info->m; i++) lmt[i] = (1.5*(jL[i]*Sqr(jR[i]) + Sqr(jL[i])*jR[i])/(2*Sqr(jL[i]) - jL[i]*jR[i] + 2*Sqr(jR[i]) + 1e-15));
116: }
117: static void Limit_Koren3(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
118: { /* Eq 11 of Cada-Torrilhon 2009 */
119:   PetscInt i;
120:   for (i=0; i<info->m; i++) lmt[i] = MinMod3(2*jL[i],(jL[i]+2*jR[i])/3,2*jR[i]);
121: }
122: static PetscReal CadaTorrilhonPhiHatR_Eq13(PetscReal L,PetscReal R)
123: {
124:   return PetscMax(0,PetscMin((L+2*R)/3,PetscMax(-0.5*L,PetscMin(2*L,PetscMin((L+2*R)/3,1.6*R)))));
125: }
126: static void Limit_CadaTorrilhon2(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
127: { /* Cada-Torrilhon 2009, Eq 13 */
128:   PetscInt i;
129:   for (i=0; i<info->m; i++) lmt[i] = CadaTorrilhonPhiHatR_Eq13(jL[i],jR[i]);
130: }
131: static void Limit_CadaTorrilhon3R(PetscReal r,LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
132: { /* Cada-Torrilhon 2009, Eq 22 */
133:   /* They recommend 0.001 < r < 1, but larger values are more accurate in smooth regions */
134:   const PetscReal eps = 1e-7,hx = info->hx;
135:   PetscInt        i;
136:   for (i=0; i<info->m; i++) {
137:     const PetscReal eta = (Sqr(jL[i]) + Sqr(jR[i])) / Sqr(r*hx);
138:     lmt[i] = ((eta < 1-eps) ? (jL[i] + 2*jR[i]) / 3 : ((eta > 1+eps) ? CadaTorrilhonPhiHatR_Eq13(jL[i],jR[i]) : 0.5*((1-(eta-1)/eps)*(jL[i]+2*jR[i])/3 + (1+(eta+1)/eps)*CadaTorrilhonPhiHatR_Eq13(jL[i],jR[i]))));
139:   }
140: }
141: static void Limit_CadaTorrilhon3R0p1(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
142: {
143:   Limit_CadaTorrilhon3R(0.1,info,jL,jR,lmt);
144: }
145: static void Limit_CadaTorrilhon3R1(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
146: {
147:   Limit_CadaTorrilhon3R(1,info,jL,jR,lmt);
148: }
149: static void Limit_CadaTorrilhon3R10(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
150: {
151:   Limit_CadaTorrilhon3R(10,info,jL,jR,lmt);
152: }
153: static void Limit_CadaTorrilhon3R100(LimitInfo info,const PetscScalar *jL,const PetscScalar *jR,PetscScalar *lmt)
154: {
155:   Limit_CadaTorrilhon3R(100,info,jL,jR,lmt);
156: }


159: /* --------------------------------- Finite Volume data structures ----------------------------------- */

161: typedef enum {FVBC_PERIODIC, FVBC_OUTFLOW} FVBCType;
162: static const char *FVBCTypes[] = {"PERIODIC","OUTFLOW","FVBCType","FVBC_",0};
163: typedef PetscErrorCode (*RiemannFunction)(void*,PetscInt,const PetscScalar*,const PetscScalar*,PetscScalar*,PetscReal*);
164: typedef PetscErrorCode (*ReconstructFunction)(void*,PetscInt,const PetscScalar*,PetscScalar*,PetscScalar*,PetscReal*);

166: typedef struct {
167:   PetscErrorCode      (*sample)(void*,PetscInt,FVBCType,PetscReal,PetscReal,PetscReal,PetscReal,PetscReal*);
168:   RiemannFunction     riemann;
169:   ReconstructFunction characteristic;
170:   PetscErrorCode      (*destroy)(void*);
171:   void                *user;
172:   PetscInt            dof;
173:   char                *fieldname[16];
174: } PhysicsCtx;

176: typedef struct {
177:   void        (*limit)(LimitInfo,const PetscScalar*,const PetscScalar*,PetscScalar*);
178:   PhysicsCtx  physics;
179:   MPI_Comm    comm;
180:   char        prefix[256];

182:   /* Local work arrays */
183:   PetscScalar *R,*Rinv;         /* Characteristic basis, and it's inverse.  COLUMN-MAJOR */
184:   PetscScalar *cjmpLR;          /* Jumps at left and right edge of cell, in characteristic basis, len=2*dof */
185:   PetscScalar *cslope;          /* Limited slope, written in characteristic basis */
186:   PetscScalar *uLR;             /* Solution at left and right of interface, conservative variables, len=2*dof */
187:   PetscScalar *flux;            /* Flux across interface */
188:   PetscReal   *speeds;          /* Speeds of each wave */

190:   PetscReal   cfl_idt;            /* Max allowable value of 1/Delta t */
191:   PetscReal   cfl;
192:   PetscReal   xmin,xmax;
193:   PetscInt    initial;
194:   PetscBool   exact;
195:   FVBCType    bctype;
196: } FVCtx;

198: PetscErrorCode RiemannListAdd(PetscFunctionList *flist,const char *name,RiemannFunction rsolve)
199: {

203:   PetscFunctionListAdd(flist,name,rsolve);
204:   return(0);
205: }

207: PetscErrorCode RiemannListFind(PetscFunctionList flist,const char *name,RiemannFunction *rsolve)
208: {

212:   PetscFunctionListFind(flist,name,rsolve);
213:   if (!*rsolve) SETERRQ1(PETSC_COMM_SELF,1,"Riemann solver \"%s\" could not be found",name);
214:   return(0);
215: }

217: PetscErrorCode ReconstructListAdd(PetscFunctionList *flist,const char *name,ReconstructFunction r)
218: {

222:   PetscFunctionListAdd(flist,name,r);
223:   return(0);
224: }

226: PetscErrorCode ReconstructListFind(PetscFunctionList flist,const char *name,ReconstructFunction *r)
227: {

231:   PetscFunctionListFind(flist,name,r);
232:   if (!*r) SETERRQ1(PETSC_COMM_SELF,1,"Reconstruction \"%s\" could not be found",name);
233:   return(0);
234: }

236: /* --------------------------------- Physics ----------------------------------- */
237: /**
238: * Each physical model consists of Riemann solver and a function to determine the basis to use for reconstruction.  These
239: * are set with the PhysicsCreate_XXX function which allocates private storage and sets these methods as well as the
240: * number of fields and their names, and a function to deallocate private storage.
241: **/

243: /* First a few functions useful to several different physics */
244: static PetscErrorCode PhysicsCharacteristic_Conservative(void *vctx,PetscInt m,const PetscScalar *u,PetscScalar *X,PetscScalar *Xi,PetscReal *speeds)
245: {
246:   PetscInt i,j;

249:   for (i=0; i<m; i++) {
250:     for (j=0; j<m; j++) Xi[i*m+j] = X[i*m+j] = (PetscScalar)(i==j);
251:     speeds[i] = PETSC_MAX_REAL; /* Indicates invalid */
252:   }
253:   return(0);
254: }

256: static PetscErrorCode PhysicsDestroy_SimpleFree(void *vctx)
257: {

261:   PetscFree(vctx);
262:   return(0);
263: }



267: /* --------------------------------- Advection ----------------------------------- */

269: typedef struct {
270:   PetscReal a;                  /* advective velocity */
271: } AdvectCtx;

273: static PetscErrorCode PhysicsRiemann_Advect(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
274: {
275:   AdvectCtx *ctx = (AdvectCtx*)vctx;
276:   PetscReal speed;

279:   speed     = ctx->a;
280:   flux[0]   = PetscMax(0,speed)*uL[0] + PetscMin(0,speed)*uR[0];
281:   *maxspeed = speed;
282:   return(0);
283: }

285: static PetscErrorCode PhysicsCharacteristic_Advect(void *vctx,PetscInt m,const PetscScalar *u,PetscScalar *X,PetscScalar *Xi,PetscReal *speeds)
286: {
287:   AdvectCtx *ctx = (AdvectCtx*)vctx;

290:   X[0]      = 1.;
291:   Xi[0]     = 1.;
292:   speeds[0] = ctx->a;
293:   return(0);
294: }

296: static PetscErrorCode PhysicsSample_Advect(void *vctx,PetscInt initial,FVBCType bctype,PetscReal xmin,PetscReal xmax,PetscReal t,PetscReal x,PetscReal *u)
297: {
298:   AdvectCtx *ctx = (AdvectCtx*)vctx;
299:   PetscReal a    = ctx->a,x0;

302:   switch (bctype) {
303:     case FVBC_OUTFLOW:   x0 = x-a*t; break;
304:     case FVBC_PERIODIC: x0 = RangeMod(x-a*t,xmin,xmax); break;
305:     default: SETERRQ(PETSC_COMM_SELF,1,"unknown BCType");
306:   }
307:   switch (initial) {
308:     case 0: u[0] = (x0 < 0) ? 1 : -1; break;
309:     case 1: u[0] = (x0 < 0) ? -1 : 1; break;
310:     case 2: u[0] = (0 < x0 && x0 < 1) ? 1 : 0; break;
311:     case 3: u[0] = PetscSinReal(2*PETSC_PI*x0); break;
312:     case 4: u[0] = PetscAbs(x0); break;
313:     case 5: u[0] = (x0 < 0 || x0 > 0.5) ? 0 : PetscSqr(PetscSinReal(2*PETSC_PI*x0)); break;
314:     case 6: u[0] = (x0 < 0) ? 0 : ((x0 < 1) ? x0 : ((x0 < 2) ? 2-x0 : 0)); break;
315:     default: SETERRQ(PETSC_COMM_SELF,1,"unknown initial condition");
316:   }
317:   return(0);
318: }

320: static PetscErrorCode PhysicsCreate_Advect(FVCtx *ctx)
321: {
323:   AdvectCtx      *user;

326:   PetscNew(&user);
327:   ctx->physics.sample         = PhysicsSample_Advect;
328:   ctx->physics.riemann        = PhysicsRiemann_Advect;
329:   ctx->physics.characteristic = PhysicsCharacteristic_Advect;
330:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
331:   ctx->physics.user           = user;
332:   ctx->physics.dof            = 1;
333:   PetscStrallocpy("u",&ctx->physics.fieldname[0]);
334:   user->a = 1;
335:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for advection","");
336:   {
337:     PetscOptionsReal("-physics_advect_a","Speed","",user->a,&user->a,NULL);
338:   }
339:   PetscOptionsEnd();
340:   return(0);
341: }

343: /* --------------------------------- Burgers ----------------------------------- */

345: typedef struct {
346:   PetscReal lxf_speed;
347: } BurgersCtx;

349: static PetscErrorCode PhysicsSample_Burgers(void *vctx,PetscInt initial,FVBCType bctype,PetscReal xmin,PetscReal xmax,PetscReal t,PetscReal x,PetscReal *u)
350: {
352:   if (bctype == FVBC_PERIODIC && t > 0) SETERRQ(PETSC_COMM_SELF,1,"Exact solution not implemented for periodic");
353:   switch (initial) {
354:     case 0: u[0] = (x < 0) ? 1 : -1; break;
355:     case 1:
356:       if       (x < -t) u[0] = -1;
357:       else if  (x < t)  u[0] = x/t;
358:       else              u[0] = 1;
359:       break;
360:     case 2:
361:       if      (x < 0)       u[0] = 0;
362:       else if (x <= t)      u[0] = x/t;
363:       else if (x < 1+0.5*t) u[0] = 1;
364:       else                  u[0] = 0;
365:       break;
366:     case 3:
367:       if       (x < 0.2*t) u[0] = 0.2;
368:       else if  (x < t) u[0] = x/t;
369:       else             u[0] = 1;
370:       break;
371:     case 4:
372:       if (t > 0) SETERRQ(PETSC_COMM_SELF,1,"Only initial condition available");
373:       u[0] = 0.7 + 0.3*PetscSinReal(2*PETSC_PI*((x-xmin)/(xmax-xmin)));
374:       break;
375:     case 5:                     /* Pure shock solution */
376:       if (x < 0.5*t) u[0] = 1;
377:       else u[0] = 0;
378:       break;
379:     default: SETERRQ(PETSC_COMM_SELF,1,"unknown initial condition");
380:   }
381:   return(0);
382: }

384: static PetscErrorCode PhysicsRiemann_Burgers_Exact(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
385: {
387:   if (uL[0] < uR[0]) {          /* rarefaction */
388:     flux[0] = (uL[0]*uR[0] < 0)
389:       ? 0                       /* sonic rarefaction */
390:       : 0.5*PetscMin(PetscSqr(uL[0]),PetscSqr(uR[0]));
391:   } else {                      /* shock */
392:     flux[0] = 0.5*PetscMax(PetscSqr(uL[0]),PetscSqr(uR[0]));
393:   }
394:   *maxspeed = (PetscAbs(uL[0]) > PetscAbs(uR[0])) ? uL[0] : uR[0];
395:   return(0);
396: }

398: static PetscErrorCode PhysicsRiemann_Burgers_Roe(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
399: {
400:   PetscReal speed;

403:   speed   = 0.5*(uL[0] + uR[0]);
404:   flux[0] = 0.25*(PetscSqr(uL[0]) + PetscSqr(uR[0])) - 0.5*PetscAbs(speed)*(uR[0]-uL[0]);
405:   if (uL[0] <= 0 && 0 <= uR[0]) flux[0] = 0; /* Entropy fix for sonic rarefaction */
406:   *maxspeed = speed;
407:   return(0);
408: }

410: static PetscErrorCode PhysicsRiemann_Burgers_LxF(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
411: {
412:   PetscReal   c;
413:   PetscScalar fL,fR;

416:   c         = ((BurgersCtx*)vctx)->lxf_speed;
417:   fL        = 0.5*PetscSqr(uL[0]);
418:   fR        = 0.5*PetscSqr(uR[0]);
419:   flux[0]   = 0.5*(fL + fR) - 0.5*c*(uR[0] - uL[0]);
420:   *maxspeed = c;
421:   return(0);
422: }

424: static PetscErrorCode PhysicsRiemann_Burgers_Rusanov(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
425: {
426:   PetscReal   c;
427:   PetscScalar fL,fR;

430:   c         = PetscMax(PetscAbs(uL[0]),PetscAbs(uR[0]));
431:   fL        = 0.5*PetscSqr(uL[0]);
432:   fR        = 0.5*PetscSqr(uR[0]);
433:   flux[0]   = 0.5*(fL + fR) - 0.5*c*(uR[0] - uL[0]);
434:   *maxspeed = c;
435:   return(0);
436: }

438: static PetscErrorCode PhysicsCreate_Burgers(FVCtx *ctx)
439: {
440:   BurgersCtx        *user;
441:   PetscErrorCode    ierr;
442:   RiemannFunction   r;
443:   PetscFunctionList rlist      = 0;
444:   char              rname[256] = "exact";

447:   PetscNew(&user);

449:   ctx->physics.sample         = PhysicsSample_Burgers;
450:   ctx->physics.characteristic = PhysicsCharacteristic_Conservative;
451:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
452:   ctx->physics.user           = user;
453:   ctx->physics.dof            = 1;

455:   PetscStrallocpy("u",&ctx->physics.fieldname[0]);
456:   RiemannListAdd(&rlist,"exact",  PhysicsRiemann_Burgers_Exact);
457:   RiemannListAdd(&rlist,"roe",    PhysicsRiemann_Burgers_Roe);
458:   RiemannListAdd(&rlist,"lxf",    PhysicsRiemann_Burgers_LxF);
459:   RiemannListAdd(&rlist,"rusanov",PhysicsRiemann_Burgers_Rusanov);
460:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for advection","");
461:   {
462:     PetscOptionsFList("-physics_burgers_riemann","Riemann solver","",rlist,rname,rname,sizeof(rname),NULL);
463:   }
464:   PetscOptionsEnd();
465:   RiemannListFind(rlist,rname,&r);
466:   PetscFunctionListDestroy(&rlist);
467:   ctx->physics.riemann = r;

469:   /* *
470:   * Hack to deal with LxF in semi-discrete form
471:   * max speed is 1 for the basic initial conditions (where |u| <= 1)
472:   * */
473:   if (r == PhysicsRiemann_Burgers_LxF) user->lxf_speed = 1;
474:   return(0);
475: }

477: /* --------------------------------- Traffic ----------------------------------- */

479: typedef struct {
480:   PetscReal lxf_speed;
481:   PetscReal a;
482: } TrafficCtx;

484: PETSC_STATIC_INLINE PetscScalar TrafficFlux(PetscScalar a,PetscScalar u) { return a*u*(1-u); }

486: static PetscErrorCode PhysicsSample_Traffic(void *vctx,PetscInt initial,FVBCType bctype,PetscReal xmin,PetscReal xmax,PetscReal t,PetscReal x,PetscReal *u)
487: {
488:   PetscReal a = ((TrafficCtx*)vctx)->a;

491:   if (bctype == FVBC_PERIODIC && t > 0) SETERRQ(PETSC_COMM_SELF,1,"Exact solution not implemented for periodic");
492:   switch (initial) {
493:     case 0:
494:       u[0] = (-a*t < x) ? 2 : 0; break;
495:     case 1:
496:       if      (x < PetscMin(2*a*t,0.5+a*t)) u[0] = -1;
497:       else if (x < 1)                       u[0] = 0;
498:       else                                  u[0] = 1;
499:       break;
500:     case 2:
501:       if (t > 0) SETERRQ(PETSC_COMM_SELF,1,"Only initial condition available");
502:       u[0] = 0.7 + 0.3*PetscSinReal(2*PETSC_PI*((x-xmin)/(xmax-xmin)));
503:       break;
504:     default: SETERRQ(PETSC_COMM_SELF,1,"unknown initial condition");
505:   }
506:   return(0);
507: }

509: static PetscErrorCode PhysicsRiemann_Traffic_Exact(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
510: {
511:   PetscReal a = ((TrafficCtx*)vctx)->a;

514:   if (uL[0] < uR[0]) {
515:     flux[0] = PetscMin(TrafficFlux(a,uL[0]),TrafficFlux(a,uR[0]));
516:   } else {
517:     flux[0] = (uR[0] < 0.5 && 0.5 < uL[0]) ? TrafficFlux(a,0.5) : PetscMax(TrafficFlux(a,uL[0]),TrafficFlux(a,uR[0]));
518:   }
519:   *maxspeed = a*MaxAbs(1-2*uL[0],1-2*uR[0]);
520:   return(0);
521: }

523: static PetscErrorCode PhysicsRiemann_Traffic_Roe(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
524: {
525:   PetscReal a = ((TrafficCtx*)vctx)->a;
526:   PetscReal speed;

529:   speed = a*(1 - (uL[0] + uR[0]));
530:   flux[0] = 0.5*(TrafficFlux(a,uL[0]) + TrafficFlux(a,uR[0])) - 0.5*PetscAbs(speed)*(uR[0]-uL[0]);
531:   *maxspeed = speed;
532:   return(0);
533: }

535: static PetscErrorCode PhysicsRiemann_Traffic_LxF(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
536: {
537:   TrafficCtx *phys = (TrafficCtx*)vctx;
538:   PetscReal  a     = phys->a;
539:   PetscReal  speed;

542:   speed     = a*(1 - (uL[0] + uR[0]));
543:   flux[0]   = 0.5*(TrafficFlux(a,uL[0]) + TrafficFlux(a,uR[0])) - 0.5*phys->lxf_speed*(uR[0]-uL[0]);
544:   *maxspeed = speed;
545:   return(0);
546: }

548: static PetscErrorCode PhysicsRiemann_Traffic_Rusanov(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
549: {
550:   PetscReal a = ((TrafficCtx*)vctx)->a;
551:   PetscReal speed;

554:   speed     = a*PetscMax(PetscAbs(1-2*uL[0]),PetscAbs(1-2*uR[0]));
555:   flux[0]   = 0.5*(TrafficFlux(a,uL[0]) + TrafficFlux(a,uR[0])) - 0.5*speed*(uR[0]-uL[0]);
556:   *maxspeed = speed;
557:   return(0);
558: }

560: static PetscErrorCode PhysicsCreate_Traffic(FVCtx *ctx)
561: {
562:   PetscErrorCode    ierr;
563:   TrafficCtx        *user;
564:   RiemannFunction   r;
565:   PetscFunctionList rlist      = 0;
566:   char              rname[256] = "exact";

569:   PetscNew(&user);
570:   ctx->physics.sample         = PhysicsSample_Traffic;
571:   ctx->physics.characteristic = PhysicsCharacteristic_Conservative;
572:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
573:   ctx->physics.user           = user;
574:   ctx->physics.dof            = 1;

576:   PetscStrallocpy("density",&ctx->physics.fieldname[0]);
577:   user->a = 0.5;
578:   RiemannListAdd(&rlist,"exact",  PhysicsRiemann_Traffic_Exact);
579:   RiemannListAdd(&rlist,"roe",    PhysicsRiemann_Traffic_Roe);
580:   RiemannListAdd(&rlist,"lxf",    PhysicsRiemann_Traffic_LxF);
581:   RiemannListAdd(&rlist,"rusanov",PhysicsRiemann_Traffic_Rusanov);
582:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for Traffic","");
583:     PetscOptionsReal("-physics_traffic_a","Flux = a*u*(1-u)","",user->a,&user->a,NULL);
584:     PetscOptionsFList("-physics_traffic_riemann","Riemann solver","",rlist,rname,rname,sizeof(rname),NULL);
585:   PetscOptionsEnd();

587:   RiemannListFind(rlist,rname,&r);
588:   PetscFunctionListDestroy(&rlist);

590:   ctx->physics.riemann = r;

592:   /* *
593:   * Hack to deal with LxF in semi-discrete form
594:   * max speed is 3*a for the basic initial conditions (-1 <= u <= 2)
595:   * */
596:   if (r == PhysicsRiemann_Traffic_LxF) user->lxf_speed = 3*user->a;
597:   return(0);
598: }

600: /* --------------------------------- Linear Acoustics ----------------------------------- */

602: /* Flux: u_t + (A u)_x
603:  * z = sqrt(rho*bulk), c = sqrt(rho/bulk)
604:  * Spectral decomposition: A = R * D * Rinv
605:  * [    cz] = [-z   z] [-c    ] [-1/2z  1/2]
606:  * [c/z   ] = [ 1   1] [     c] [ 1/2z  1/2]
607:  *
608:  * We decompose this into the left-traveling waves Al = R * D^- Rinv
609:  * and the right-traveling waves Ar = R * D^+ * Rinv
610:  * Multiplying out these expressions produces the following two matrices
611:  */

613: typedef struct {
614:   PetscReal c;                  /* speed of sound: c = sqrt(bulk/rho) */
615:   PetscReal z;                  /* impedence: z = sqrt(rho*bulk) */
616: } AcousticsCtx;

618: PETSC_UNUSED PETSC_STATIC_INLINE void AcousticsFlux(AcousticsCtx *ctx,const PetscScalar *u,PetscScalar *f)
619: {
620:   f[0] = ctx->c*ctx->z*u[1];
621:   f[1] = ctx->c/ctx->z*u[0];
622: }

624: static PetscErrorCode PhysicsCharacteristic_Acoustics(void *vctx,PetscInt m,const PetscScalar *u,PetscScalar *X,PetscScalar *Xi,PetscReal *speeds)
625: {
626:   AcousticsCtx *phys = (AcousticsCtx*)vctx;
627:   PetscReal    z     = phys->z,c = phys->c;

630:   X[0*2+0]  = -z;
631:   X[0*2+1]  = z;
632:   X[1*2+0]  = 1;
633:   X[1*2+1]  = 1;
634:   Xi[0*2+0] = -1./(2*z);
635:   Xi[0*2+1] = 1./2;
636:   Xi[1*2+0] = 1./(2*z);
637:   Xi[1*2+1] = 1./2;
638:   speeds[0] = -c;
639:   speeds[1] = c;
640:   return(0);
641: }

643: static PetscErrorCode PhysicsSample_Acoustics_Initial(AcousticsCtx *phys,PetscInt initial,PetscReal xmin,PetscReal xmax,PetscReal x,PetscReal *u)
644: {
646:   switch (initial) {
647:   case 0:
648:     u[0] = (PetscAbs((x - xmin)/(xmax - xmin) - 0.2) < 0.1) ? 1 : 0.5;
649:     u[1] = (PetscAbs((x - xmin)/(xmax - xmin) - 0.7) < 0.1) ? 1 : -0.5;
650:     break;
651:   case 1:
652:     u[0] = PetscCosReal(3 * 2*PETSC_PI*x/(xmax-xmin));
653:     u[1] = PetscExpReal(-PetscSqr(x - (xmax + xmin)/2) / (2*PetscSqr(0.2*(xmax - xmin)))) - 0.5;
654:     break;
655:   default: SETERRQ(PETSC_COMM_SELF,1,"unknown initial condition");
656:   }
657:   return(0);
658: }

660: static PetscErrorCode PhysicsSample_Acoustics(void *vctx,PetscInt initial,FVBCType bctype,PetscReal xmin,PetscReal xmax,PetscReal t,PetscReal x,PetscReal *u)
661: {
662:   AcousticsCtx   *phys = (AcousticsCtx*)vctx;
663:   PetscReal      c     = phys->c;
664:   PetscReal      x0a,x0b,u0a[2],u0b[2],tmp[2];
665:   PetscReal      X[2][2],Xi[2][2],dummy[2];

669:   switch (bctype) {
670:   case FVBC_OUTFLOW:
671:     x0a = x+c*t;
672:     x0b = x-c*t;
673:     break;
674:   case FVBC_PERIODIC:
675:     x0a = RangeMod(x+c*t,xmin,xmax);
676:     x0b = RangeMod(x-c*t,xmin,xmax);
677:     break;
678:   default: SETERRQ(PETSC_COMM_SELF,1,"unknown BCType");
679:   }
680:   PhysicsSample_Acoustics_Initial(phys,initial,xmin,xmax,x0a,u0a);
681:   PhysicsSample_Acoustics_Initial(phys,initial,xmin,xmax,x0b,u0b);
682:   PhysicsCharacteristic_Acoustics(vctx,2,u,&X[0][0],&Xi[0][0],dummy);
683:   tmp[0] = Xi[0][0]*u0a[0] + Xi[0][1]*u0a[1];
684:   tmp[1] = Xi[1][0]*u0b[0] + Xi[1][1]*u0b[1];
685:   u[0]   = X[0][0]*tmp[0] + X[0][1]*tmp[1];
686:   u[1]   = X[1][0]*tmp[0] + X[1][1]*tmp[1];
687:   return(0);
688: }

690: static PetscErrorCode PhysicsRiemann_Acoustics_Exact(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
691: {
692:   AcousticsCtx *phys = (AcousticsCtx*)vctx;
693:   PetscReal    c     = phys->c,z = phys->z;
694:   PetscReal
695:     Al[2][2] = {{-c/2     , c*z/2  },
696:                 {c/(2*z)  , -c/2   }}, /* Left traveling waves */
697:     Ar[2][2] = {{c/2      , c*z/2  },
698:                 {c/(2*z)  , c/2    }}; /* Right traveling waves */

701:   flux[0]   = Al[0][0]*uR[0] + Al[0][1]*uR[1] + Ar[0][0]*uL[0] + Ar[0][1]*uL[1];
702:   flux[1]   = Al[1][0]*uR[0] + Al[1][1]*uR[1] + Ar[1][0]*uL[0] + Ar[1][1]*uL[1];
703:   *maxspeed = c;
704:   return(0);
705: }

707: static PetscErrorCode PhysicsCreate_Acoustics(FVCtx *ctx)
708: {
709:   PetscErrorCode    ierr;
710:   AcousticsCtx      *user;
711:   PetscFunctionList rlist      = 0,rclist = 0;
712:   char              rname[256] = "exact",rcname[256] = "characteristic";

715:   PetscNew(&user);
716:   ctx->physics.sample         = PhysicsSample_Acoustics;
717:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
718:   ctx->physics.user           = user;
719:   ctx->physics.dof            = 2;

721:   PetscStrallocpy("u",&ctx->physics.fieldname[0]);
722:   PetscStrallocpy("v",&ctx->physics.fieldname[1]);

724:   user->c = 1;
725:   user->z = 1;

727:   RiemannListAdd(&rlist,"exact",  PhysicsRiemann_Acoustics_Exact);
728:   ReconstructListAdd(&rclist,"characteristic",PhysicsCharacteristic_Acoustics);
729:   ReconstructListAdd(&rclist,"conservative",PhysicsCharacteristic_Conservative);
730:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for linear Acoustics","");
731:   {
732:     PetscOptionsReal("-physics_acoustics_c","c = sqrt(bulk/rho)","",user->c,&user->c,NULL);
733:     PetscOptionsReal("-physics_acoustics_z","z = sqrt(bulk*rho)","",user->z,&user->z,NULL);
734:     PetscOptionsFList("-physics_acoustics_riemann","Riemann solver","",rlist,rname,rname,sizeof(rname),NULL);
735:     PetscOptionsFList("-physics_acoustics_reconstruct","Reconstruction","",rclist,rcname,rcname,sizeof(rcname),NULL);
736:   }
737:   PetscOptionsEnd();
738:   RiemannListFind(rlist,rname,&ctx->physics.riemann);
739:   ReconstructListFind(rclist,rcname,&ctx->physics.characteristic);
740:   PetscFunctionListDestroy(&rlist);
741:   PetscFunctionListDestroy(&rclist);
742:   return(0);
743: }

745: /* --------------------------------- Isothermal Gas Dynamics ----------------------------------- */

747: typedef struct {
748:   PetscReal acoustic_speed;
749: } IsoGasCtx;

751: PETSC_STATIC_INLINE void IsoGasFlux(PetscReal c,const PetscScalar *u,PetscScalar *f)
752: {
753:   f[0] = u[1];
754:   f[1] = PetscSqr(u[1])/u[0] + c*c*u[0];
755: }

757: static PetscErrorCode PhysicsSample_IsoGas(void *vctx,PetscInt initial,FVBCType bctype,PetscReal xmin,PetscReal xmax,PetscReal t,PetscReal x,PetscReal *u)
758: {
760:   if (t > 0) SETERRQ(PETSC_COMM_SELF,1,"Exact solutions not implemented for t > 0");
761:   switch (initial) {
762:     case 0:
763:       u[0] = (x < 0) ? 1 : 0.5;
764:       u[1] = (x < 0) ? 1 : 0.7;
765:       break;
766:     case 1:
767:       u[0] = 1+0.5*PetscSinReal(2*PETSC_PI*x);
768:       u[1] = 1*u[0];
769:       break;
770:     default: SETERRQ(PETSC_COMM_SELF,1,"unknown initial condition");
771:   }
772:   return(0);
773: }

775: static PetscErrorCode PhysicsRiemann_IsoGas_Roe(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
776: {
777:   IsoGasCtx   *phys = (IsoGasCtx*)vctx;
778:   PetscReal   c     = phys->acoustic_speed;
779:   PetscScalar ubar,du[2],a[2],fL[2],fR[2],lam[2],ustar[2],R[2][2];
780:   PetscInt    i;

783:   ubar = (uL[1]/PetscSqrtScalar(uL[0]) + uR[1]/PetscSqrtScalar(uR[0])) / (PetscSqrtScalar(uL[0]) + PetscSqrtScalar(uR[0]));
784:   /* write fluxuations in characteristic basis */
785:   du[0] = uR[0] - uL[0];
786:   du[1] = uR[1] - uL[1];
787:   a[0]  = (1/(2*c)) * ((ubar + c)*du[0] - du[1]);
788:   a[1]  = (1/(2*c)) * ((-ubar + c)*du[0] + du[1]);
789:   /* wave speeds */
790:   lam[0] = ubar - c;
791:   lam[1] = ubar + c;
792:   /* Right eigenvectors */
793:   R[0][0] = 1; R[0][1] = ubar-c;
794:   R[1][0] = 1; R[1][1] = ubar+c;
795:   /* Compute state in star region (between the 1-wave and 2-wave) */
796:   for (i=0; i<2; i++) ustar[i] = uL[i] + a[0]*R[0][i];
797:   if (uL[1]/uL[0] < c && c < ustar[1]/ustar[0]) { /* 1-wave is sonic rarefaction */
798:     PetscScalar ufan[2];
799:     ufan[0] = uL[0]*PetscExpScalar(uL[1]/(uL[0]*c) - 1);
800:     ufan[1] = c*ufan[0];
801:     IsoGasFlux(c,ufan,flux);
802:   } else if (ustar[1]/ustar[0] < -c && -c < uR[1]/uR[0]) { /* 2-wave is sonic rarefaction */
803:     PetscScalar ufan[2];
804:     ufan[0] = uR[0]*PetscExpScalar(-uR[1]/(uR[0]*c) - 1);
805:     ufan[1] = -c*ufan[0];
806:     IsoGasFlux(c,ufan,flux);
807:   } else {                      /* Centered form */
808:     IsoGasFlux(c,uL,fL);
809:     IsoGasFlux(c,uR,fR);
810:     for (i=0; i<2; i++) {
811:       PetscScalar absdu = PetscAbsScalar(lam[0])*a[0]*R[0][i] + PetscAbsScalar(lam[1])*a[1]*R[1][i];
812:       flux[i] = 0.5*(fL[i]+fR[i]) - 0.5*absdu;
813:     }
814:   }
815:   *maxspeed = MaxAbs(lam[0],lam[1]);
816:   return(0);
817: }

819: static PetscErrorCode PhysicsRiemann_IsoGas_Exact(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
820: {
821:   IsoGasCtx                   *phys = (IsoGasCtx*)vctx;
822:   PetscReal                   c     = phys->acoustic_speed;
823:   PetscScalar                 ustar[2];
824:   struct {PetscScalar rho,u;} L = {uL[0],uL[1]/uL[0]},R = {uR[0],uR[1]/uR[0]},star;
825:   PetscInt                    i;
826:   PetscErrorCode              ierr;

829:   if (!(L.rho > 0 && R.rho > 0)) SETERRQ(PETSC_COMM_SELF,1,"Reconstructed density is negative");
830:   {
831:     /* Solve for star state */
832:     PetscScalar res,tmp,rho = 0.5*(L.rho + R.rho); /* initial guess */
833:     for (i=0; i<20; i++) {
834:       PetscScalar fr,fl,dfr,dfl;
835:       fl = (L.rho < rho)
836:         ? (rho-L.rho)/PetscSqrtScalar(L.rho*rho)       /* shock */
837:         : PetscLogScalar(rho) - PetscLogScalar(L.rho); /* rarefaction */
838:       fr = (R.rho < rho)
839:         ? (rho-R.rho)/PetscSqrtScalar(R.rho*rho)       /* shock */
840:         : PetscLogScalar(rho) - PetscLogScalar(R.rho); /* rarefaction */
841:       res = R.u-L.u + c*(fr+fl);
842:       PetscIsInfOrNanScalar(res);
843:       if (PetscAbsScalar(res) < 1e-10) {
844:         star.rho = rho;
845:         star.u   = L.u - c*fl;
846:         goto converged;
847:       }
848:       dfl = (L.rho < rho) ? 1/PetscSqrtScalar(L.rho*rho)*(1 - 0.5*(rho-L.rho)/rho) : 1/rho;
849:       dfr = (R.rho < rho) ? 1/PetscSqrtScalar(R.rho*rho)*(1 - 0.5*(rho-R.rho)/rho) : 1/rho;
850:       tmp = rho - res/(c*(dfr+dfl));
851:       if (tmp <= 0) rho /= 2;   /* Guard against Newton shooting off to a negative density */
852:       else rho = tmp;
853:       if (!((rho > 0) && PetscIsNormalScalar(rho))) SETERRQ1(PETSC_COMM_SELF,1,"non-normal iterate rho=%g",(double)PetscRealPart(rho));
854:     }
855:     SETERRQ1(PETSC_COMM_SELF,1,"Newton iteration for star.rho diverged after %D iterations",i);
856:   }
857: converged:
858:   if (L.u-c < 0 && 0 < star.u-c) { /* 1-wave is sonic rarefaction */
859:     PetscScalar ufan[2];
860:     ufan[0] = L.rho*PetscExpScalar(L.u/c - 1);
861:     ufan[1] = c*ufan[0];
862:     IsoGasFlux(c,ufan,flux);
863:   } else if (star.u+c < 0 && 0 < R.u+c) { /* 2-wave is sonic rarefaction */
864:     PetscScalar ufan[2];
865:     ufan[0] = R.rho*PetscExpScalar(-R.u/c - 1);
866:     ufan[1] = -c*ufan[0];
867:     IsoGasFlux(c,ufan,flux);
868:   } else if ((L.rho >= star.rho && L.u-c >= 0) || (L.rho < star.rho && (star.rho*star.u-L.rho*L.u)/(star.rho-L.rho) > 0)) {
869:     /* 1-wave is supersonic rarefaction, or supersonic shock */
870:     IsoGasFlux(c,uL,flux);
871:   } else if ((star.rho <= R.rho && R.u+c <= 0) || (star.rho > R.rho && (R.rho*R.u-star.rho*star.u)/(R.rho-star.rho) < 0)) {
872:     /* 2-wave is supersonic rarefaction or supersonic shock */
873:     IsoGasFlux(c,uR,flux);
874:   } else {
875:     ustar[0] = star.rho;
876:     ustar[1] = star.rho*star.u;
877:     IsoGasFlux(c,ustar,flux);
878:   }
879:   *maxspeed = MaxAbs(MaxAbs(star.u-c,star.u+c),MaxAbs(L.u-c,R.u+c));
880:   return(0);
881: }

883: static PetscErrorCode PhysicsRiemann_IsoGas_Rusanov(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
884: {
885:   IsoGasCtx                   *phys = (IsoGasCtx*)vctx;
886:   PetscScalar                 c = phys->acoustic_speed,fL[2],fR[2],s;
887:   struct {PetscScalar rho,u;} L = {uL[0],uL[1]/uL[0]},R = {uR[0],uR[1]/uR[0]};

890:   if (!(L.rho > 0 && R.rho > 0)) SETERRQ(PETSC_COMM_SELF,1,"Reconstructed density is negative");
891:   IsoGasFlux(c,uL,fL);
892:   IsoGasFlux(c,uR,fR);
893:   s         = PetscMax(PetscAbs(L.u),PetscAbs(R.u))+c;
894:   flux[0]   = 0.5*(fL[0] + fR[0]) + 0.5*s*(uL[0] - uR[0]);
895:   flux[1]   = 0.5*(fL[1] + fR[1]) + 0.5*s*(uL[1] - uR[1]);
896:   *maxspeed = s;
897:   return(0);
898: }

900: static PetscErrorCode PhysicsCharacteristic_IsoGas(void *vctx,PetscInt m,const PetscScalar *u,PetscScalar *X,PetscScalar *Xi,PetscReal *speeds)
901: {
902:   IsoGasCtx      *phys = (IsoGasCtx*)vctx;
903:   PetscReal      c     = phys->acoustic_speed;

907:   speeds[0] = u[1]/u[0] - c;
908:   speeds[1] = u[1]/u[0] + c;
909:   X[0*2+0]  = 1;
910:   X[0*2+1]  = speeds[0];
911:   X[1*2+0]  = 1;
912:   X[1*2+1]  = speeds[1];
913:   PetscMemcpy(Xi,X,4*sizeof(X[0]));
914:   PetscKernel_A_gets_inverse_A_2(Xi,0,PETSC_FALSE,NULL);
915:   return(0);
916: }

918: static PetscErrorCode PhysicsCreate_IsoGas(FVCtx *ctx)
919: {
920:   PetscErrorCode    ierr;
921:   IsoGasCtx         *user;
922:   PetscFunctionList rlist = 0,rclist = 0;
923:   char              rname[256] = "exact",rcname[256] = "characteristic";

926:   PetscNew(&user);
927:   ctx->physics.sample         = PhysicsSample_IsoGas;
928:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
929:   ctx->physics.user           = user;
930:   ctx->physics.dof            = 2;

932:   PetscStrallocpy("density",&ctx->physics.fieldname[0]);
933:   PetscStrallocpy("momentum",&ctx->physics.fieldname[1]);

935:   user->acoustic_speed = 1;

937:   RiemannListAdd(&rlist,"exact",  PhysicsRiemann_IsoGas_Exact);
938:   RiemannListAdd(&rlist,"roe",    PhysicsRiemann_IsoGas_Roe);
939:   RiemannListAdd(&rlist,"rusanov",PhysicsRiemann_IsoGas_Rusanov);
940:   ReconstructListAdd(&rclist,"characteristic",PhysicsCharacteristic_IsoGas);
941:   ReconstructListAdd(&rclist,"conservative",PhysicsCharacteristic_Conservative);
942:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for IsoGas","");
943:     PetscOptionsReal("-physics_isogas_acoustic_speed","Acoustic speed","",user->acoustic_speed,&user->acoustic_speed,NULL);
944:     PetscOptionsFList("-physics_isogas_riemann","Riemann solver","",rlist,rname,rname,sizeof(rname),NULL);
945:     PetscOptionsFList("-physics_isogas_reconstruct","Reconstruction","",rclist,rcname,rcname,sizeof(rcname),NULL);
946:   PetscOptionsEnd();
947:   RiemannListFind(rlist,rname,&ctx->physics.riemann);
948:   ReconstructListFind(rclist,rcname,&ctx->physics.characteristic);
949:   PetscFunctionListDestroy(&rlist);
950:   PetscFunctionListDestroy(&rclist);
951:   return(0);
952: }

954: /* --------------------------------- Shallow Water ----------------------------------- */
955: typedef struct {
956:   PetscReal gravity;
957: } ShallowCtx;

959: PETSC_STATIC_INLINE void ShallowFlux(ShallowCtx *phys,const PetscScalar *u,PetscScalar *f)
960: {
961:   f[0] = u[1];
962:   f[1] = PetscSqr(u[1])/u[0] + 0.5*phys->gravity*PetscSqr(u[0]);
963: }

965: static PetscErrorCode PhysicsRiemann_Shallow_Exact(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
966: {
967:   ShallowCtx                *phys = (ShallowCtx*)vctx;
968:   PetscScalar               g    = phys->gravity,ustar[2],cL,cR,c,cstar;
969:   struct {PetscScalar h,u;} L = {uL[0],uL[1]/uL[0]},R = {uR[0],uR[1]/uR[0]},star;
970:   PetscInt                  i;
971:   PetscErrorCode            ierr;

974:   if (!(L.h > 0 && R.h > 0)) SETERRQ(PETSC_COMM_SELF,1,"Reconstructed thickness is negative");
975:   cL = PetscSqrtScalar(g*L.h);
976:   cR = PetscSqrtScalar(g*R.h);
977:   c  = PetscMax(cL,cR);
978:   {
979:     /* Solve for star state */
980:     const PetscInt maxits = 50;
981:     PetscScalar tmp,res,res0=0,h0,h = 0.5*(L.h + R.h); /* initial guess */
982:     h0 = h;
983:     for (i=0; i<maxits; i++) {
984:       PetscScalar fr,fl,dfr,dfl;
985:       fl = (L.h < h)
986:         ? PetscSqrtScalar(0.5*g*(h*h - L.h*L.h)*(1/L.h - 1/h)) /* shock */
987:         : 2*PetscSqrtScalar(g*h) - 2*PetscSqrtScalar(g*L.h);   /* rarefaction */
988:       fr = (R.h < h)
989:         ? PetscSqrtScalar(0.5*g*(h*h - R.h*R.h)*(1/R.h - 1/h)) /* shock */
990:         : 2*PetscSqrtScalar(g*h) - 2*PetscSqrtScalar(g*R.h);   /* rarefaction */
991:       res = R.u - L.u + fr + fl;
992:       PetscIsInfOrNanScalar(res);
993:       if (PetscAbsScalar(res) < 1e-8 || (i > 0 && PetscAbsScalar(h-h0) < 1e-8)) {
994:         star.h = h;
995:         star.u = L.u - fl;
996:         goto converged;
997:       } else if (i > 0 && PetscAbsScalar(res) >= PetscAbsScalar(res0)) {        /* Line search */
998:         h = 0.8*h0 + 0.2*h;
999:         continue;
1000:       }
1001:       /* Accept the last step and take another */
1002:       res0 = res;
1003:       h0 = h;
1004:       dfl = (L.h < h) ? 0.5/fl*0.5*g*(-L.h*L.h/(h*h) - 1 + 2*h/L.h) : PetscSqrtScalar(g/h);
1005:       dfr = (R.h < h) ? 0.5/fr*0.5*g*(-R.h*R.h/(h*h) - 1 + 2*h/R.h) : PetscSqrtScalar(g/h);
1006:       tmp = h - res/(dfr+dfl);
1007:       if (tmp <= 0) h /= 2;   /* Guard against Newton shooting off to a negative thickness */
1008:       else h = tmp;
1009:       if (!((h > 0) && PetscIsNormalScalar(h))) SETERRQ1(PETSC_COMM_SELF,1,"non-normal iterate h=%g",(double)h);
1010:     }
1011:     SETERRQ1(PETSC_COMM_SELF,1,"Newton iteration for star.h diverged after %D iterations",i);
1012:   }
1013: converged:
1014:   cstar = PetscSqrtScalar(g*star.h);
1015:   if (L.u-cL < 0 && 0 < star.u-cstar) { /* 1-wave is sonic rarefaction */
1016:     PetscScalar ufan[2];
1017:     ufan[0] = 1/g*PetscSqr(L.u/3 + 2./3*cL);
1018:     ufan[1] = PetscSqrtScalar(g*ufan[0])*ufan[0];
1019:     ShallowFlux(phys,ufan,flux);
1020:   } else if (star.u+cstar < 0 && 0 < R.u+cR) { /* 2-wave is sonic rarefaction */
1021:     PetscScalar ufan[2];
1022:     ufan[0] = 1/g*PetscSqr(R.u/3 - 2./3*cR);
1023:     ufan[1] = -PetscSqrtScalar(g*ufan[0])*ufan[0];
1024:     ShallowFlux(phys,ufan,flux);
1025:   } else if ((L.h >= star.h && L.u-c >= 0) || (L.h<star.h && (star.h*star.u-L.h*L.u)/(star.h-L.h) > 0)) {
1026:     /* 1-wave is right-travelling shock (supersonic) */
1027:     ShallowFlux(phys,uL,flux);
1028:   } else if ((star.h <= R.h && R.u+c <= 0) || (star.h>R.h && (R.h*R.u-star.h*star.h)/(R.h-star.h) < 0)) {
1029:     /* 2-wave is left-travelling shock (supersonic) */
1030:     ShallowFlux(phys,uR,flux);
1031:   } else {
1032:     ustar[0] = star.h;
1033:     ustar[1] = star.h*star.u;
1034:     ShallowFlux(phys,ustar,flux);
1035:   }
1036:   *maxspeed = MaxAbs(MaxAbs(star.u-cstar,star.u+cstar),MaxAbs(L.u-cL,R.u+cR));
1037:   return(0);
1038: }

1040: static PetscErrorCode PhysicsRiemann_Shallow_Rusanov(void *vctx,PetscInt m,const PetscScalar *uL,const PetscScalar *uR,PetscScalar *flux,PetscReal *maxspeed)
1041: {
1042:   ShallowCtx                *phys = (ShallowCtx*)vctx;
1043:   PetscScalar               g = phys->gravity,fL[2],fR[2],s;
1044:   struct {PetscScalar h,u;} L = {uL[0],uL[1]/uL[0]},R = {uR[0],uR[1]/uR[0]};

1047:   if (!(L.h > 0 && R.h > 0)) SETERRQ(PETSC_COMM_SELF,1,"Reconstructed thickness is negative");
1048:   ShallowFlux(phys,uL,fL);
1049:   ShallowFlux(phys,uR,fR);
1050:   s         = PetscMax(PetscAbs(L.u)+PetscSqrtScalar(g*L.h),PetscAbs(R.u)+PetscSqrtScalar(g*R.h));
1051:   flux[0]   = 0.5*(fL[0] + fR[0]) + 0.5*s*(uL[0] - uR[0]);
1052:   flux[1]   = 0.5*(fL[1] + fR[1]) + 0.5*s*(uL[1] - uR[1]);
1053:   *maxspeed = s;
1054:   return(0);
1055: }

1057: static PetscErrorCode PhysicsCharacteristic_Shallow(void *vctx,PetscInt m,const PetscScalar *u,PetscScalar *X,PetscScalar *Xi,PetscReal *speeds)
1058: {
1059:   ShallowCtx     *phys = (ShallowCtx*)vctx;
1060:   PetscReal      c;

1064:   c         = PetscSqrtScalar(u[0]*phys->gravity);
1065:   speeds[0] = u[1]/u[0] - c;
1066:   speeds[1] = u[1]/u[0] + c;
1067:   X[0*2+0]  = 1;
1068:   X[0*2+1]  = speeds[0];
1069:   X[1*2+0]  = 1;
1070:   X[1*2+1]  = speeds[1];
1071:   PetscMemcpy(Xi,X,4*sizeof(X[0]));
1072:   PetscKernel_A_gets_inverse_A_2(Xi,0,PETSC_FALSE,NULL);
1073:   return(0);
1074: }

1076: static PetscErrorCode PhysicsCreate_Shallow(FVCtx *ctx)
1077: {
1078:   PetscErrorCode    ierr;
1079:   ShallowCtx        *user;
1080:   PetscFunctionList rlist = 0,rclist = 0;
1081:   char              rname[256] = "exact",rcname[256] = "characteristic";

1084:   PetscNew(&user);
1085:   /* Shallow water and Isothermal Gas dynamics are similar so we reuse initial conditions for now */
1086:   ctx->physics.sample         = PhysicsSample_IsoGas;
1087:   ctx->physics.destroy        = PhysicsDestroy_SimpleFree;
1088:   ctx->physics.user           = user;
1089:   ctx->physics.dof            = 2;

1091:   PetscStrallocpy("density",&ctx->physics.fieldname[0]);
1092:   PetscStrallocpy("momentum",&ctx->physics.fieldname[1]);

1094:   user->gravity = 1;

1096:   RiemannListAdd(&rlist,"exact",  PhysicsRiemann_Shallow_Exact);
1097:   RiemannListAdd(&rlist,"rusanov",PhysicsRiemann_Shallow_Rusanov);
1098:   ReconstructListAdd(&rclist,"characteristic",PhysicsCharacteristic_Shallow);
1099:   ReconstructListAdd(&rclist,"conservative",PhysicsCharacteristic_Conservative);
1100:   PetscOptionsBegin(ctx->comm,ctx->prefix,"Options for Shallow","");
1101:     PetscOptionsReal("-physics_shallow_gravity","Gravity","",user->gravity,&user->gravity,NULL);
1102:     PetscOptionsFList("-physics_shallow_riemann","Riemann solver","",rlist,rname,rname,sizeof(rname),NULL);
1103:     PetscOptionsFList("-physics_shallow_reconstruct","Reconstruction","",rclist,rcname,rcname,sizeof(rcname),NULL);
1104:   PetscOptionsEnd();
1105:   RiemannListFind(rlist,rname,&ctx->physics.riemann);
1106:   ReconstructListFind(rclist,rcname,&ctx->physics.characteristic);
1107:   PetscFunctionListDestroy(&rlist);
1108:   PetscFunctionListDestroy(&rclist);
1109:   return(0);
1110: }

1112: /* --------------------------------- Finite Volume Solver ----------------------------------- */

1114: static PetscErrorCode FVRHSFunction(TS ts,PetscReal time,Vec X,Vec F,void *vctx)
1115: {
1116:   FVCtx             *ctx = (FVCtx*)vctx;
1117:   PetscErrorCode    ierr;
1118:   PetscInt          i,j,k,Mx,dof,xs,xm;
1119:   PetscReal         hx,cfl_idt = 0;
1120:   PetscScalar       *x,*f,*slope;
1121:   Vec               Xloc;
1122:   DM                da;

1125:   TSGetDM(ts,&da);
1126:   DMGetLocalVector(da,&Xloc);
1127:   DMDAGetInfo(da,0, &Mx,0,0, 0,0,0, &dof,0,0,0,0,0);
1128:   hx   = (ctx->xmax - ctx->xmin)/Mx;
1129:   DMGlobalToLocalBegin(da,X,INSERT_VALUES,Xloc);
1130:   DMGlobalToLocalEnd  (da,X,INSERT_VALUES,Xloc);

1132:   VecZeroEntries(F);

1134:   DMDAVecGetArray(da,Xloc,&x);
1135:   DMDAVecGetArray(da,F,&f);
1136:   DMDAGetArray(da,PETSC_TRUE,&slope);

1138:   DMDAGetCorners(da,&xs,0,0,&xm,0,0);

1140:   if (ctx->bctype == FVBC_OUTFLOW) {
1141:     for (i=xs-2; i<0; i++) {
1142:       for (j=0; j<dof; j++) x[i*dof+j] = x[j];
1143:     }
1144:     for (i=Mx; i<xs+xm+2; i++) {
1145:       for (j=0; j<dof; j++) x[i*dof+j] = x[(xs+xm-1)*dof+j];
1146:     }
1147:   }
1148:   for (i=xs-1; i<xs+xm+1; i++) {
1149:     struct _LimitInfo info;
1150:     PetscScalar       *cjmpL,*cjmpR;
1151:     /* Determine the right eigenvectors R, where A = R \Lambda R^{-1} */
1152:     (*ctx->physics.characteristic)(ctx->physics.user,dof,&x[i*dof],ctx->R,ctx->Rinv,ctx->speeds);
1153:     /* Evaluate jumps across interfaces (i-1, i) and (i, i+1), put in characteristic basis */
1154:     PetscMemzero(ctx->cjmpLR,2*dof*sizeof(ctx->cjmpLR[0]));
1155:     cjmpL = &ctx->cjmpLR[0];
1156:     cjmpR = &ctx->cjmpLR[dof];
1157:     for (j=0; j<dof; j++) {
1158:       PetscScalar jmpL,jmpR;
1159:       jmpL = x[(i+0)*dof+j] - x[(i-1)*dof+j];
1160:       jmpR = x[(i+1)*dof+j] - x[(i+0)*dof+j];
1161:       for (k=0; k<dof; k++) {
1162:         cjmpL[k] += ctx->Rinv[k+j*dof] * jmpL;
1163:         cjmpR[k] += ctx->Rinv[k+j*dof] * jmpR;
1164:       }
1165:     }
1166:     /* Apply limiter to the left and right characteristic jumps */
1167:     info.m  = dof;
1168:     info.hx = hx;
1169:     (*ctx->limit)(&info,cjmpL,cjmpR,ctx->cslope);
1170:     for (j=0; j<dof; j++) ctx->cslope[j] /= hx; /* rescale to a slope */
1171:     for (j=0; j<dof; j++) {
1172:       PetscScalar tmp = 0;
1173:       for (k=0; k<dof; k++) tmp += ctx->R[j+k*dof] * ctx->cslope[k];
1174:       slope[i*dof+j] = tmp;
1175:     }
1176:   }

1178:   for (i=xs; i<xs+xm+1; i++) {
1179:     PetscReal   maxspeed;
1180:     PetscScalar *uL,*uR;
1181:     uL = &ctx->uLR[0];
1182:     uR = &ctx->uLR[dof];
1183:     for (j=0; j<dof; j++) {
1184:       uL[j] = x[(i-1)*dof+j] + slope[(i-1)*dof+j]*hx/2;
1185:       uR[j] = x[(i-0)*dof+j] - slope[(i-0)*dof+j]*hx/2;
1186:     }
1187:     (*ctx->physics.riemann)(ctx->physics.user,dof,uL,uR,ctx->flux,&maxspeed);
1188:     cfl_idt = PetscMax(cfl_idt,PetscAbsScalar(maxspeed/hx)); /* Max allowable value of 1/Delta t */

1190:     if (i > xs) {
1191:       for (j=0; j<dof; j++) f[(i-1)*dof+j] -= ctx->flux[j]/hx;
1192:     }
1193:     if (i < xs+xm) {
1194:       for (j=0; j<dof; j++) f[i*dof+j] += ctx->flux[j]/hx;
1195:     }
1196:   }

1198:   DMDAVecRestoreArray(da,Xloc,&x);
1199:   DMDAVecRestoreArray(da,F,&f);
1200:   DMDARestoreArray(da,PETSC_TRUE,&slope);
1201:   DMRestoreLocalVector(da,&Xloc);

1203:   MPI_Allreduce(&cfl_idt,&ctx->cfl_idt,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)da));
1204:   if (0) {
1205:     /* We need to a way to inform the TS of a CFL constraint, this is a debugging fragment */
1206:     PetscReal dt,tnow;
1207:     TSGetTimeStep(ts,&dt);
1208:     TSGetTime(ts,&tnow);
1209:     if (dt > 0.5/ctx->cfl_idt) {
1210:       if (1) {
1211:         PetscPrintf(ctx->comm,"Stability constraint exceeded at t=%g, dt %g > %g\n",(double)tnow,(double)dt,(double)(0.5/ctx->cfl_idt));
1212:       } else SETERRQ2(PETSC_COMM_SELF,1,"Stability constraint exceeded, %g > %g",(double)dt,(double)(ctx->cfl/ctx->cfl_idt));
1213:     }
1214:   }
1215:   return(0);
1216: }

1218: static PetscErrorCode SmallMatMultADB(PetscScalar *C,PetscInt bs,const PetscScalar *A,const PetscReal *D,const PetscScalar *B)
1219: {
1220:   PetscInt i,j,k;

1223:   for (i=0; i<bs; i++) {
1224:     for (j=0; j<bs; j++) {
1225:       PetscScalar tmp = 0;
1226:       for (k=0; k<bs; k++) tmp += A[i*bs+k] * D[k] * B[k*bs+j];
1227:       C[i*bs+j] = tmp;
1228:     }
1229:   }
1230:   return(0);
1231: }


1234: static PetscErrorCode FVIJacobian(TS ts,PetscReal t,Vec X,Vec Xdot,PetscReal shift,Mat A,Mat B,void *vctx)
1235: {
1236:   FVCtx             *ctx = (FVCtx*)vctx;
1237:   PetscErrorCode    ierr;
1238:   PetscInt          i,j,dof = ctx->physics.dof;
1239:   PetscScalar       *J;
1240:   const PetscScalar *x;
1241:   PetscReal         hx;
1242:   DM                da;
1243:   DMDALocalInfo     dainfo;

1246:   TSGetDM(ts,&da);
1247:   DMDAVecGetArrayRead(da,X,(void*)&x);
1248:   DMDAGetLocalInfo(da,&dainfo);
1249:   hx   = (ctx->xmax - ctx->xmin)/dainfo.mx;
1250:   PetscMalloc1(dof*dof,&J);
1251:   for (i=dainfo.xs; i<dainfo.xs+dainfo.xm; i++) {
1252:     (*ctx->physics.characteristic)(ctx->physics.user,dof,&x[i*dof],ctx->R,ctx->Rinv,ctx->speeds);
1253:     for (j=0; j<dof; j++) ctx->speeds[j] = PetscAbs(ctx->speeds[j]);
1254:     SmallMatMultADB(J,dof,ctx->R,ctx->speeds,ctx->Rinv);
1255:     for (j=0; j<dof*dof; j++) J[j] = J[j]/hx + shift*(j/dof == j%dof);
1256:     MatSetValuesBlocked(B,1,&i,1,&i,J,INSERT_VALUES);
1257:   }
1258:   PetscFree(J);
1259:   DMDAVecRestoreArrayRead(da,X,(void*)&x);

1261:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1262:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1263:   if (A != B) {
1264:     MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1265:     MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1266:   }
1267:   return(0);
1268: }

1270: static PetscErrorCode FVSample(FVCtx *ctx,DM da,PetscReal time,Vec U)
1271: {
1273:   PetscScalar    *u,*uj;
1274:   PetscInt       i,j,k,dof,xs,xm,Mx;

1277:   if (!ctx->physics.sample) SETERRQ(PETSC_COMM_SELF,1,"Physics has not provided a sampling function");
1278:   DMDAGetInfo(da,0, &Mx,0,0, 0,0,0, &dof,0,0,0,0,0);
1279:   DMDAGetCorners(da,&xs,0,0,&xm,0,0);
1280:   DMDAVecGetArray(da,U,&u);
1281:   PetscMalloc1(dof,&uj);
1282:   for (i=xs; i<xs+xm; i++) {
1283:     const PetscReal h = (ctx->xmax-ctx->xmin)/Mx,xi = ctx->xmin+h/2+i*h;
1284:     const PetscInt  N = 200;
1285:     /* Integrate over cell i using trapezoid rule with N points. */
1286:     for (k=0; k<dof; k++) u[i*dof+k] = 0;
1287:     for (j=0; j<N+1; j++) {
1288:       PetscScalar xj = xi+h*(j-N/2)/(PetscReal)N;
1289:       (*ctx->physics.sample)(ctx->physics.user,ctx->initial,ctx->bctype,ctx->xmin,ctx->xmax,time,xj,uj);
1290:       for (k=0; k<dof; k++) u[i*dof+k] += ((j==0 || j==N) ? 0.5 : 1.0)*uj[k]/N;
1291:     }
1292:   }
1293:   DMDAVecRestoreArray(da,U,&u);
1294:   PetscFree(uj);
1295:   return(0);
1296: }

1298: static PetscErrorCode SolutionStatsView(DM da,Vec X,PetscViewer viewer)
1299: {
1300:   PetscErrorCode    ierr;
1301:   PetscReal         xmin,xmax;
1302:   PetscScalar       sum,tvsum,tvgsum;
1303:   const PetscScalar *x;
1304:   PetscInt          imin,imax,Mx,i,j,xs,xm,dof;
1305:   Vec               Xloc;
1306:   PetscBool         iascii;

1309:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1310:   if (iascii) {
1311:     /* PETSc lacks a function to compute total variation norm (difficult in multiple dimensions), we do it here */
1312:     DMGetLocalVector(da,&Xloc);
1313:     DMGlobalToLocalBegin(da,X,INSERT_VALUES,Xloc);
1314:     DMGlobalToLocalEnd  (da,X,INSERT_VALUES,Xloc);
1315:     DMDAVecGetArrayRead(da,Xloc,(void*)&x);
1316:     DMDAGetCorners(da,&xs,0,0,&xm,0,0);
1317:     DMDAGetInfo(da,0, &Mx,0,0, 0,0,0, &dof,0,0,0,0,0);
1318:     tvsum = 0;
1319:     for (i=xs; i<xs+xm; i++) {
1320:       for (j=0; j<dof; j++) tvsum += PetscAbsScalar(x[i*dof+j] - x[(i-1)*dof+j]);
1321:     }
1322:     MPI_Allreduce(&tvsum,&tvgsum,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)da));
1323:     DMDAVecRestoreArrayRead(da,Xloc,(void*)&x);
1324:     DMRestoreLocalVector(da,&Xloc);

1326:     VecMin(X,&imin,&xmin);
1327:     VecMax(X,&imax,&xmax);
1328:     VecSum(X,&sum);
1329:     PetscViewerASCIIPrintf(viewer,"Solution range [%8.5f,%8.5f] with extrema at %D and %D, mean %8.5f, ||x||_TV %8.5f\n",(double)xmin,(double)xmax,imin,imax,(double)(sum/Mx),(double)(tvgsum/Mx));
1330:   } else SETERRQ(PETSC_COMM_SELF,1,"Viewer type not supported");
1331:   return(0);
1332: }

1334: static PetscErrorCode SolutionErrorNorms(FVCtx *ctx,DM da,PetscReal t,Vec X,PetscReal *nrm1,PetscReal *nrmsup)
1335: {
1337:   Vec            Y;
1338:   PetscInt       Mx;

1341:   VecGetSize(X,&Mx);
1342:   VecDuplicate(X,&Y);
1343:   FVSample(ctx,da,t,Y);
1344:   VecAYPX(Y,-1,X);
1345:   VecNorm(Y,NORM_1,nrm1);
1346:   VecNorm(Y,NORM_INFINITY,nrmsup);
1347:   *nrm1 /= Mx;
1348:   VecDestroy(&Y);
1349:   return(0);
1350: }

1352: int main(int argc,char *argv[])
1353: {
1354:   char              lname[256] = "mc",physname[256] = "advect",final_fname[256] = "solution.m";
1355:   PetscFunctionList limiters   = 0,physics = 0;
1356:   MPI_Comm          comm;
1357:   TS                ts;
1358:   DM                da;
1359:   Vec               X,X0,R;
1360:   Mat               B;
1361:   FVCtx             ctx;
1362:   PetscInt          i,dof,xs,xm,Mx,draw = 0;
1363:   PetscBool         view_final = PETSC_FALSE;
1364:   PetscReal         ptime;
1365:   PetscErrorCode    ierr;

1367:   PetscInitialize(&argc,&argv,0,help);
1368:   comm = PETSC_COMM_WORLD;
1369:   PetscMemzero(&ctx,sizeof(ctx));

1371:   /* Register limiters to be available on the command line */
1372:   PetscFunctionListAdd(&limiters,"upwind"              ,Limit_Upwind);
1373:   PetscFunctionListAdd(&limiters,"lax-wendroff"        ,Limit_LaxWendroff);
1374:   PetscFunctionListAdd(&limiters,"beam-warming"        ,Limit_BeamWarming);
1375:   PetscFunctionListAdd(&limiters,"fromm"               ,Limit_Fromm);
1376:   PetscFunctionListAdd(&limiters,"minmod"              ,Limit_Minmod);
1377:   PetscFunctionListAdd(&limiters,"superbee"            ,Limit_Superbee);
1378:   PetscFunctionListAdd(&limiters,"mc"                  ,Limit_MC);
1379:   PetscFunctionListAdd(&limiters,"vanleer"             ,Limit_VanLeer);
1380:   PetscFunctionListAdd(&limiters,"vanalbada"           ,Limit_VanAlbada);
1381:   PetscFunctionListAdd(&limiters,"vanalbadatvd"        ,Limit_VanAlbadaTVD);
1382:   PetscFunctionListAdd(&limiters,"koren"               ,Limit_Koren);
1383:   PetscFunctionListAdd(&limiters,"korensym"            ,Limit_KorenSym);
1384:   PetscFunctionListAdd(&limiters,"koren3"              ,Limit_Koren3);
1385:   PetscFunctionListAdd(&limiters,"cada-torrilhon2"     ,Limit_CadaTorrilhon2);
1386:   PetscFunctionListAdd(&limiters,"cada-torrilhon3-r0p1",Limit_CadaTorrilhon3R0p1);
1387:   PetscFunctionListAdd(&limiters,"cada-torrilhon3-r1"  ,Limit_CadaTorrilhon3R1);
1388:   PetscFunctionListAdd(&limiters,"cada-torrilhon3-r10" ,Limit_CadaTorrilhon3R10);
1389:   PetscFunctionListAdd(&limiters,"cada-torrilhon3-r100",Limit_CadaTorrilhon3R100);

1391:   /* Register physical models to be available on the command line */
1392:   PetscFunctionListAdd(&physics,"advect"          ,PhysicsCreate_Advect);
1393:   PetscFunctionListAdd(&physics,"burgers"         ,PhysicsCreate_Burgers);
1394:   PetscFunctionListAdd(&physics,"traffic"         ,PhysicsCreate_Traffic);
1395:   PetscFunctionListAdd(&physics,"acoustics"       ,PhysicsCreate_Acoustics);
1396:   PetscFunctionListAdd(&physics,"isogas"          ,PhysicsCreate_IsoGas);
1397:   PetscFunctionListAdd(&physics,"shallow"         ,PhysicsCreate_Shallow);

1399:   ctx.comm = comm;
1400:   ctx.cfl  = 0.9; ctx.bctype = FVBC_PERIODIC;
1401:   ctx.xmin = -1; ctx.xmax = 1;
1402:   PetscOptionsBegin(comm,NULL,"Finite Volume solver options","");
1403:     PetscOptionsReal("-xmin","X min","",ctx.xmin,&ctx.xmin,NULL);
1404:     PetscOptionsReal("-xmax","X max","",ctx.xmax,&ctx.xmax,NULL);
1405:     PetscOptionsFList("-limit","Name of flux limiter to use","",limiters,lname,lname,sizeof(lname),NULL);
1406:     PetscOptionsFList("-physics","Name of physics (Riemann solver and characteristics) to use","",physics,physname,physname,sizeof(physname),NULL);
1407:     PetscOptionsInt("-draw","Draw solution vector, bitwise OR of (1=initial,2=final,4=final error)","",draw,&draw,NULL);
1408:     PetscOptionsString("-view_final","Write final solution in ASCII MATLAB format to given file name","",final_fname,final_fname,sizeof(final_fname),&view_final);
1409:     PetscOptionsInt("-initial","Initial condition (depends on the physics)","",ctx.initial,&ctx.initial,NULL);
1410:     PetscOptionsBool("-exact","Compare errors with exact solution","",ctx.exact,&ctx.exact,NULL);
1411:     PetscOptionsReal("-cfl","CFL number to time step at","",ctx.cfl,&ctx.cfl,NULL);
1412:     PetscOptionsEnum("-bc_type","Boundary condition","",FVBCTypes,(PetscEnum)ctx.bctype,(PetscEnum*)&ctx.bctype,NULL);
1413:   PetscOptionsEnd();

1415:   /* Choose the limiter from the list of registered limiters */
1416:   PetscFunctionListFind(limiters,lname,&ctx.limit);
1417:   if (!ctx.limit) SETERRQ1(PETSC_COMM_SELF,1,"Limiter '%s' not found",lname);

1419:   /* Choose the physics from the list of registered models */
1420:   {
1421:     PetscErrorCode (*r)(FVCtx*);
1422:     PetscFunctionListFind(physics,physname,&r);
1423:     if (!r) SETERRQ1(PETSC_COMM_SELF,1,"Physics '%s' not found",physname);
1424:     /* Create the physics, will set the number of fields and their names */
1425:     (*r)(&ctx);
1426:   }

1428:   /* Create a DMDA to manage the parallel grid */
1429:   DMDACreate1d(comm,DM_BOUNDARY_PERIODIC,50,ctx.physics.dof,2,NULL,&da);
1430:   DMSetFromOptions(da);
1431:   DMSetUp(da);
1432:   /* Inform the DMDA of the field names provided by the physics. */
1433:   /* The names will be shown in the title bars when run with -ts_monitor_draw_solution */
1434:   for (i=0; i<ctx.physics.dof; i++) {
1435:     DMDASetFieldName(da,i,ctx.physics.fieldname[i]);
1436:   }
1437:   DMDAGetInfo(da,0, &Mx,0,0, 0,0,0, &dof,0,0,0,0,0);
1438:   DMDAGetCorners(da,&xs,0,0,&xm,0,0);

1440:   /* Set coordinates of cell centers */
1441:   DMDASetUniformCoordinates(da,ctx.xmin+0.5*(ctx.xmax-ctx.xmin)/Mx,ctx.xmax+0.5*(ctx.xmax-ctx.xmin)/Mx,0,0,0,0);

1443:   /* Allocate work space for the Finite Volume solver (so it doesn't have to be reallocated on each function evaluation) */
1444:   PetscMalloc4(dof*dof,&ctx.R,dof*dof,&ctx.Rinv,2*dof,&ctx.cjmpLR,1*dof,&ctx.cslope);
1445:   PetscMalloc3(2*dof,&ctx.uLR,dof,&ctx.flux,dof,&ctx.speeds);

1447:   /* Create a vector to store the solution and to save the initial state */
1448:   DMCreateGlobalVector(da,&X);
1449:   VecDuplicate(X,&X0);
1450:   VecDuplicate(X,&R);

1452:   DMCreateMatrix(da,&B);

1454:   /* Create a time-stepping object */
1455:   TSCreate(comm,&ts);
1456:   TSSetDM(ts,da);
1457:   TSSetRHSFunction(ts,R,FVRHSFunction,&ctx);
1458:   TSSetIJacobian(ts,B,B,FVIJacobian,&ctx);
1459:   TSSetType(ts,TSSSP);
1460:   TSSetDuration(ts,1000,10);
1461:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);
1462: 
1463:   /* Compute initial conditions and starting time step */
1464:   FVSample(&ctx,da,0,X0);
1465:   FVRHSFunction(ts,0,X0,X,(void*)&ctx); /* Initial function evaluation, only used to determine max speed */
1466:   VecCopy(X0,X);                        /* The function value was not used so we set X=X0 again */
1467:   TSSetInitialTimeStep(ts,0,ctx.cfl/ctx.cfl_idt);
1468:   TSSetFromOptions(ts); /* Take runtime options */
1469:   SolutionStatsView(da,X,PETSC_VIEWER_STDOUT_WORLD);
1470:   {
1471:     PetscReal nrm1,nrmsup;
1472:     PetscInt  steps;

1474:     TSSolve(ts,X);
1475:     TSGetSolveTime(ts,&ptime);
1476:     TSGetTimeStepNumber(ts,&steps);

1478:     PetscPrintf(comm,"Final time %8.5f, steps %D\n",(double)ptime,steps);
1479:     if (ctx.exact) {
1480:       SolutionErrorNorms(&ctx,da,ptime,X,&nrm1,&nrmsup);
1481:       PetscPrintf(comm,"Error ||x-x_e||_1 %8.4e  ||x-x_e||_sup %8.4e\n",(double)nrm1,(double)nrmsup);
1482:     }
1483:   }

1485:   SolutionStatsView(da,X,PETSC_VIEWER_STDOUT_WORLD);
1486:   if (draw & 0x1) {VecView(X0,PETSC_VIEWER_DRAW_WORLD);}
1487:   if (draw & 0x2) {VecView(X,PETSC_VIEWER_DRAW_WORLD);}
1488:   if (draw & 0x4) {
1489:     Vec Y;
1490:     VecDuplicate(X,&Y);
1491:     FVSample(&ctx,da,ptime,Y);
1492:     VecAYPX(Y,-1,X);
1493:     VecView(Y,PETSC_VIEWER_DRAW_WORLD);
1494:     VecDestroy(&Y);
1495:   }

1497:   if (view_final) {
1498:     PetscViewer viewer;
1499:     PetscViewerASCIIOpen(PETSC_COMM_WORLD,final_fname,&viewer);
1500:     PetscViewerPushFormat(viewer,PETSC_VIEWER_ASCII_MATLAB);
1501:     VecView(X,viewer);
1502:     PetscViewerPopFormat(viewer);
1503:     PetscViewerDestroy(&viewer);
1504:   }

1506:   /* Clean up */
1507:   (*ctx.physics.destroy)(ctx.physics.user);
1508:   for (i=0; i<ctx.physics.dof; i++) {PetscFree(ctx.physics.fieldname[i]);}
1509:   PetscFree4(ctx.R,ctx.Rinv,ctx.cjmpLR,ctx.cslope);
1510:   PetscFree3(ctx.uLR,ctx.flux,ctx.speeds);
1511:   VecDestroy(&X);
1512:   VecDestroy(&X0);
1513:   VecDestroy(&R);
1514:   MatDestroy(&B);
1515:   DMDestroy(&da);
1516:   TSDestroy(&ts);
1517:   PetscFunctionListDestroy(&limiters);
1518:   PetscFunctionListDestroy(&physics);
1519:   PetscFinalize();
1520:   return ierr;
1521: }