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