Actual source code: ex35.cxx

  1: static const char help[] = "Time-dependent Brusselator reaction-diffusion PDE in 1d. Demonstrates IMEX methods and uses MOAB.\n";
  2: /*
  3:    u_t - alpha u_xx = A + u^2 v - (B+1) u
  4:    v_t - alpha v_xx = B u - u^2 v
  5:    0 < x < 1;
  6:    A = 1, B = 3, alpha = 1/50

  8:    Initial conditions:
  9:    u(x,0) = 1 + sin(2 pi x)
 10:    v(x,0) = 3

 12:    Boundary conditions:
 13:    u(0,t) = u(1,t) = 1
 14:    v(0,t) = v(1,t) = 3
 15: */

 17: // PETSc includes:
 18: #include <petscts.h>
 19: #include <petscdmmoab.h>

 21: typedef struct {
 22:   PetscScalar u,v;
 23: } Field;

 25: struct pUserCtx {
 26:   PetscReal A,B;        /* Reaction coefficients */
 27:   PetscReal alpha;      /* Diffusion coefficient */
 28:   Field leftbc;         /* Dirichlet boundary conditions at left boundary */
 29:   Field rightbc;        /* Dirichlet boundary conditions at right boundary */
 30:   PetscInt  n,npts;       /* Number of mesh points */
 31:   PetscInt  ntsteps;    /* Number of time steps */
 32:   PetscInt nvars;       /* Number of variables in the equation system */
 33:   PetscBool io;
 34: };
 35: typedef pUserCtx* UserCtx;

 37: PetscErrorCode Initialize_AppContext(UserCtx *puser)
 38: {
 39:   UserCtx           user;
 40:   PetscErrorCode    ierr;

 43:   PetscNew(&user);

 45:   PetscOptionsBegin(PETSC_COMM_WORLD,NULL,"Advection-reaction options","ex35.cxx");
 46:   {
 47:     user->nvars  = 2;
 48:     user->A      = 1;
 49:     user->B      = 3;
 50:     user->alpha  = 0.02;
 51:     user->leftbc.u  = 1;
 52:     user->rightbc.u = 1;
 53:     user->leftbc.v  = 3;
 54:     user->rightbc.v = 3;
 55:     user->n      = 10;
 56:     user->ntsteps = 10000;
 57:     user->io = PETSC_FALSE;
 58:     PetscOptionsReal("-A","Reaction rate","ex35.cxx",user->A,&user->A,NULL);
 59:     PetscOptionsReal("-B","Reaction rate","ex35.cxx",user->B,&user->B,NULL);
 60:     PetscOptionsReal("-alpha","Diffusion coefficient","ex35.cxx",user->alpha,&user->alpha,NULL);
 61:     PetscOptionsScalar("-uleft","Dirichlet boundary condition","ex35.cxx",user->leftbc.u,&user->leftbc.u,NULL);
 62:     PetscOptionsScalar("-uright","Dirichlet boundary condition","ex35.cxx",user->rightbc.u,&user->rightbc.u,NULL);
 63:     PetscOptionsScalar("-vleft","Dirichlet boundary condition","ex35.cxx",user->leftbc.v,&user->leftbc.v,NULL);
 64:     PetscOptionsScalar("-vright","Dirichlet boundary condition","ex35.cxx",user->rightbc.v,&user->rightbc.v,NULL);
 65:     PetscOptionsInt("-n","Number of 1-D elements","ex35.cxx",user->n,&user->n,NULL);
 66:     PetscOptionsInt("-ndt","Number of time steps","ex35.cxx",user->ntsteps,&user->ntsteps,NULL);
 67:     PetscOptionsBool("-io","Write the mesh and solution output to a file.","ex35.cxx",user->io,&user->io,NULL);
 68:     user->npts   = user->n+1;
 69:   }
 70:   PetscOptionsEnd();

 72:   *puser = user;
 73:   return(0);
 74: }

 76: PetscErrorCode Destroy_AppContext(UserCtx *user)
 77: {

 81:   PetscFree(*user);
 82:   return(0);
 83: }

 85: static PetscErrorCode FormInitialSolution(TS,Vec,void*);
 86: static PetscErrorCode FormRHSFunction(TS,PetscReal,Vec,Vec,void*);
 87: static PetscErrorCode FormIFunction(TS,PetscReal,Vec,Vec,Vec,void*);
 88: static PetscErrorCode FormIJacobian(TS,PetscReal,Vec,Vec,PetscReal,Mat,Mat,void*);

 90: /****************
 91:  *              *
 92:  *     MAIN     *
 93:  *              *
 94:  ****************/
 95: int main(int argc,char **argv)
 96: {
 97:   TS                ts;         /* nonlinear solver */
 98:   Vec               X;          /* solution, residual vectors */
 99:   Mat               J;          /* Jacobian matrix */
100:   PetscInt          steps,mx;
101:   PetscErrorCode    ierr;
102:   PetscReal         hx,dt,ftime;
103:   UserCtx           user;       /* user-defined work context */
104:   TSConvergedReason reason;

106:   DM                dm;
107:   const char        *fields[2] = {"U","V"};

109:   PetscInitialize(&argc,&argv,(char *)0,help);if (ierr) return ierr;

111:   /* Initialize the user context struct */
112:   Initialize_AppContext(&user);

114:   /* Fill in the user defined work context: */
115:   DMMoabCreateBoxMesh(PETSC_COMM_WORLD, 1, PETSC_FALSE, NULL, user->n, 1, &dm);
116:   DMMoabSetFieldNames(dm, user->nvars, fields);
117:   DMMoabSetBlockSize(dm, user->nvars);
118:   DMSetFromOptions(dm);

120:   /* SetUp the data structures for DMMOAB */
121:   DMSetUp(dm);

123:   /*  Create timestepping solver context */
124:   TSCreate(PETSC_COMM_WORLD,&ts);
125:   TSSetDM(ts, dm);
126:   TSSetType(ts,TSARKIMEX);
127:   TSSetEquationType(ts,TS_EQ_DAE_IMPLICIT_INDEX1);
128:   DMSetMatType(dm,MATBAIJ);
129:   DMCreateMatrix(dm,&J);

131:   TSSetRHSFunction(ts,NULL,FormRHSFunction,user);
132:   TSSetIFunction(ts,NULL,FormIFunction,user);
133:   TSSetIJacobian(ts,J,J,FormIJacobian,user);

135:   ftime = 10.0;
136:   TSSetMaxSteps(ts,user->ntsteps);
137:   TSSetMaxTime(ts,ftime);
138:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);

140:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
141:      Create the solution vector and set the initial conditions
142:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
143:   DMCreateGlobalVector(dm, &X);

145:   FormInitialSolution(ts,X,user);
146:   TSSetSolution(ts,X);
147:   VecGetSize(X,&mx);
148:   hx = 1.0/(PetscReal)(mx/2-1);
149:   dt = 0.4 * PetscSqr(hx) / user->alpha; /* Diffusive stability limit */
150:   TSSetTimeStep(ts,dt);

152:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153:      Set runtime options
154:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
155:   TSSetFromOptions(ts);

157:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
158:      Solve nonlinear system
159:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
160:   TSSolve(ts,X);
161:   TSGetSolveTime(ts,&ftime);
162:   TSGetStepNumber(ts,&steps);
163:   TSGetConvergedReason(ts,&reason);
164:   PetscPrintf(PETSC_COMM_WORLD,"%s at time %g after %D steps\n",TSConvergedReasons[reason],ftime,steps);

166:   if (user->io) {
167:     /* Print the numerical solution to screen and then dump to file */
168:     VecView(X,PETSC_VIEWER_STDOUT_WORLD);

170:     /* Write out the solution along with the mesh */
171:     DMMoabSetGlobalFieldVector(dm, X);
172: #ifdef MOAB_HAVE_HDF5
173:     DMMoabOutput(dm, "ex35.h5m", "");
174: #else
175:     /* MOAB does not support true parallel writers that aren't HDF5 based
176:        And so if you are using VTK as the output format in parallel,
177:        the data could be jumbled due to the order in which the processors
178:        write out their parts of the mesh and solution tags
179:     */
180:     DMMoabOutput(dm, "ex35.vtk", "");
181: #endif
182:   }

184:   /* Free work space.
185:      Free all PETSc related resources: */
186:   MatDestroy(&J);
187:   VecDestroy(&X);
188:   TSDestroy(&ts);
189:   DMDestroy(&dm);

191:   /* Free all MOAB related resources: */
192:   Destroy_AppContext(&user);
193:   PetscFinalize();
194:   return ierr;
195: }

197: /*
198:   IJacobian - Compute IJacobian = dF/dU + a dF/dUdot
199: */
200: PetscErrorCode FormIJacobian(TS ts,PetscReal t,Vec X,Vec Xdot,PetscReal a,Mat J,Mat Jpre,void *ptr)
201: {
202:   UserCtx             user = (UserCtx)ptr;
203:   PetscErrorCode      ierr;
204:   PetscInt            dof;
205:   PetscReal           hx;
206:   DM                  dm;
207:   const moab::Range   *vlocal;
208:   PetscBool           vonboundary;

211:   TSGetDM(ts, &dm);

213:   /* get the essential MOAB mesh related quantities needed for FEM assembly */
214:   DMMoabGetLocalVertices(dm, &vlocal, NULL);

216:   /* compute local element sizes - structured grid */
217:   hx = 1.0/user->n;

219:   /* Compute function over the locally owned part of the grid
220:      Assemble the operator by looping over edges and computing
221:      contribution for each vertex dof                         */
222:   for (moab::Range::iterator iter = vlocal->begin(); iter != vlocal->end(); iter++) {
223:     const moab::EntityHandle vhandle = *iter;

225:     DMMoabGetDofsBlocked(dm, 1, &vhandle, &dof);

227:     /* check if vertex is on the boundary */
228:     DMMoabIsEntityOnBoundary(dm,vhandle,&vonboundary);

230:     if (vonboundary) {
231:       const PetscScalar bcvals[2][2] = {{hx,0},{0,hx}};
232:       MatSetValuesBlocked(Jpre,1,&dof,1,&dof,&bcvals[0][0],INSERT_VALUES);
233:     }
234:     else {
235:       const PetscInt    row           = dof,col[] = {dof-1,dof,dof+1};
236:       const PetscScalar dxxL          = -user->alpha/hx,dxx0 = 2.*user->alpha/hx,dxxR = -user->alpha/hx;
237:       const PetscScalar vals[2][3][2] = {{{dxxL,0},{a *hx+dxx0,0},{dxxR,0}},
238:                                          {{0,dxxL},{0,a*hx+dxx0},{0,dxxR}}};
239:       MatSetValuesBlocked(Jpre,1,&row,3,col,&vals[0][0][0],INSERT_VALUES);
240:     }
241:   }

243:   MatAssemblyBegin(Jpre,MAT_FINAL_ASSEMBLY);
244:   MatAssemblyEnd(Jpre,MAT_FINAL_ASSEMBLY);
245:   if (J != Jpre) {
246:     MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
247:     MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
248:   }
249:   return(0);
250: }

252: static PetscErrorCode FormRHSFunction(TS ts,PetscReal t,Vec X,Vec F,void *ptr)
253: {
254:   UserCtx           user = (UserCtx)ptr;
255:   DM                dm;
256:   PetscReal         hx;
257:   const Field       *x;
258:   Field             *f;
259:   PetscInt          dof;
260:   const moab::Range *ownedvtx;
261:   PetscErrorCode    ierr;

264:   hx = 1.0/user->n;
265:   TSGetDM(ts,&dm);

267:   /* Get pointers to vector data */
268:   VecSet(F,0.0);

270:   DMMoabVecGetArrayRead(dm, X, &x);
271:   DMMoabVecGetArray(dm, F, &f);

273:   DMMoabGetLocalVertices(dm, &ownedvtx, NULL);

275:   /* Compute function over the locally owned part of the grid */
276:   for (moab::Range::iterator iter = ownedvtx->begin(); iter != ownedvtx->end(); iter++) {
277:     const moab::EntityHandle vhandle = *iter;
278:     DMMoabGetDofsBlockedLocal(dm, 1, &vhandle, &dof);

280:     PetscScalar u = x[dof].u,v = x[dof].v;
281:     f[dof].u = hx*(user->A + u*u*v - (user->B+1)*u);
282:     f[dof].v = hx*(user->B*u - u*u*v);
283:   }

285:   /* Restore vectors */
286:   DMMoabVecRestoreArrayRead(dm, X, &x);
287:   DMMoabVecRestoreArray(dm, F, &f);
288:   return(0);
289: }

291: static PetscErrorCode FormIFunction(TS ts,PetscReal t,Vec X,Vec Xdot,Vec F,void *ctx)
292: {
293:   UserCtx         user = (UserCtx)ctx;
294:   DM              dm;
295:   Field           *x,*xdot,*f;
296:   PetscReal       hx;
297:   Vec             Xloc;
298:   PetscErrorCode  ierr;
299:   PetscInt        i,bcindx;
300:   PetscBool       elem_on_boundary;
301:   const moab::Range   *vlocal;

304:   hx = 1.0/user->n;
305:   TSGetDM(ts, &dm);

307:   /* get the essential MOAB mesh related quantities needed for FEM assembly */
308:   DMMoabGetLocalVertices(dm, &vlocal, NULL);

310:   /* reset the residual vector */
311:   VecSet(F,0.0);

313:   DMGetLocalVector(dm,&Xloc);
314:   DMGlobalToLocalBegin(dm,X,INSERT_VALUES,Xloc);
315:   DMGlobalToLocalEnd(dm,X,INSERT_VALUES,Xloc);

317:   /* get the local representation of the arrays from Vectors */
318:   DMMoabVecGetArrayRead(dm, Xloc, &x);
319:   DMMoabVecGetArrayRead(dm, Xdot, &xdot);
320:   DMMoabVecGetArray(dm, F, &f);

322:   /* loop over local elements */
323:   for (moab::Range::iterator iter = vlocal->begin(); iter != vlocal->end(); iter++) {
324:     const moab::EntityHandle vhandle = *iter;

326:     DMMoabGetDofsBlockedLocal(dm,1,&vhandle,&i);

328:     /* check if vertex is on the boundary */
329:     DMMoabIsEntityOnBoundary(dm,vhandle,&elem_on_boundary);

331:     if (elem_on_boundary) {
332:       DMMoabGetDofsBlocked(dm, 1, &vhandle, &bcindx);
333:       if (bcindx == 0) {  /* Apply left BC */
334:         f[i].u = hx * (x[i].u - user->leftbc.u);
335:         f[i].v = hx * (x[i].v - user->leftbc.v);
336:       } else {       /* Apply right BC */
337:         f[i].u = hx * (x[i].u - user->rightbc.u);
338:         f[i].v = hx * (x[i].v - user->rightbc.v);
339:       }
340:     }
341:     else {
342:       f[i].u = hx * xdot[i].u - user->alpha * (x[i-1].u - 2.*x[i].u + x[i+1].u) / hx;
343:       f[i].v = hx * xdot[i].v - user->alpha * (x[i-1].v - 2.*x[i].v + x[i+1].v) / hx;
344:     }
345:   }

347:   /* Restore data */
348:   DMMoabVecRestoreArrayRead(dm, Xloc, &x);
349:   DMMoabVecRestoreArrayRead(dm, Xdot, &xdot);
350:   DMMoabVecRestoreArray(dm, F, &f);
351:   DMRestoreLocalVector(dm, &Xloc);
352:   return(0);
353: }

355: PetscErrorCode FormInitialSolution(TS ts,Vec X,void *ctx)
356: {
357:   UserCtx           user = (UserCtx)ctx;
358:   PetscReal         vpos[3];
359:   DM                dm;
360:   Field             *x;
361:   PetscErrorCode    ierr;
362:   const moab::Range *vowned;
363:   PetscInt          dof;
364:   moab::Range::iterator iter;

367:   TSGetDM(ts, &dm);

369:   /* get the essential MOAB mesh related quantities needed for FEM assembly */
370:   DMMoabGetLocalVertices(dm, &vowned, NULL);

372:   VecSet(X, 0.0);

374:   /* Get pointers to vector data */
375:   DMMoabVecGetArray(dm, X, &x);

377:   /* Compute function over the locally owned part of the grid */
378:   for (moab::Range::iterator iter = vowned->begin(); iter != vowned->end(); iter++) {
379:     const moab::EntityHandle vhandle = *iter;
380:     DMMoabGetDofsBlockedLocal(dm, 1, &vhandle, &dof);

382:     /* compute the mid-point of the element and use a 1-point lumped quadrature */
383:     DMMoabGetVertexCoordinates(dm,1,&vhandle,vpos);

385:     PetscReal xi = vpos[0];
386:     x[dof].u = user->leftbc.u*(1.-xi) + user->rightbc.u*xi + PetscSinReal(2.*PETSC_PI*xi);
387:     x[dof].v = user->leftbc.v*(1.-xi) + user->rightbc.v*xi;
388:   }

390:   /* Restore vectors */
391:   DMMoabVecRestoreArray(dm, X, &x);
392:   return(0);
393: }

395: /*TEST

397:     build:
398:       requires: moab

400:     test:
401:       args: -n 20 -ts_type rosw -ts_rosw_type 2p -ts_dt 5e-2 -ts_adapt_type none

403:     test:
404:       suffix: 2
405:       nsize: 2
406:       args: -n 50 -ts_type glee -ts_adapt_type none -ts_dt 0.1 -io
407:       TODO:

409: TEST*/