Actual source code: ex9.c

petsc-3.8.4 2018-03-24
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;

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

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

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

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

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

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

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

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

934:   user->acoustic_speed = 1;

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

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

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

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

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

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

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

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

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

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

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

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

1092:   user->gravity = 1;

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

1110: /* --------------------------------- Finite Volume Solver ----------------------------------- */

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

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

1130:   VecZeroEntries(F);

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

1324:     VecMin(X,&imin,&xmin);
1325:     VecMax(X,&imax,&xmax);
1326:     VecSum(X,&sum);
1327:     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));
1328:   } else SETERRQ(PETSC_COMM_SELF,1,"Viewer type not supported");
1329:   return(0);
1330: }

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

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

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

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

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

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

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

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

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

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

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

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

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

1450:   DMCreateMatrix(da,&B);

1452:   /* Create a time-stepping object */
1453:   TSCreate(comm,&ts);
1454:   TSSetDM(ts,da);
1455:   TSSetRHSFunction(ts,R,FVRHSFunction,&ctx);
1456:   TSSetIJacobian(ts,B,B,FVIJacobian,&ctx);
1457:   TSSetType(ts,TSSSP);
1458:   TSSetMaxTime(ts,10);
1459:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);

1461:   /* Compute initial conditions and starting time step */
1462:   FVSample(&ctx,da,0,X0);
1463:   FVRHSFunction(ts,0,X0,X,(void*)&ctx); /* Initial function evaluation, only used to determine max speed */
1464:   VecCopy(X0,X);                        /* The function value was not used so we set X=X0 again */
1465:   TSSetTimeStep(ts,ctx.cfl/ctx.cfl_idt);
1466:   TSSetFromOptions(ts); /* Take runtime options */
1467:   SolutionStatsView(da,X,PETSC_VIEWER_STDOUT_WORLD);
1468:   {
1469:     PetscReal nrm1,nrmsup;
1470:     PetscInt  steps;

1472:     TSSolve(ts,X);
1473:     TSGetSolveTime(ts,&ptime);
1474:     TSGetStepNumber(ts,&steps);

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

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

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

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