Actual source code: ex15.c

petsc-master 2016-04-30
Report Typos and Errors
  1: static const char help[] = "p-Bratu nonlinear PDE in 2d.\n\
  2: We solve the  p-Laplacian (nonlinear diffusion) combined with\n\
  3: the Bratu (solid fuel ignition) nonlinearity in a 2D rectangular\n\
  4: domain, using distributed arrays (DAs) to partition the parallel grid.\n\
  5: The command line options include:\n\
  6:   -p <2>: `p' in p-Laplacian term\n\
  7:   -epsilon <1e-05>: Strain-regularization in p-Laplacian\n\
  8:   -lambda <6>: Bratu parameter\n\
  9:   -blocks <bx,by>: number of coefficient interfaces in x and y direction\n\
 10:   -kappa <1e-3>: diffusivity in odd regions\n\
 11: \n";


The $p$-Bratu problem is a combination of the $p$-Laplacian (nonlinear diffusion) and the Brutu solid fuel ignition problem.
This problem is modeled by the partial differential equation

\begin{equation*}
-\nabla\cdot (\eta \nabla u) - \lambda \exp(u) = 0
\end{equation*}

on $\Omega = (-1,1)^2$ with closure

\begin{align*}
\eta(\gamma) &= (\epsilon^2 + \gamma)^{(p-2)/2} & \gamma &= \frac 1 2 |\nabla u|^2
\end{align*}

and boundary conditions $u = 0$ for $(x,y) \in \partial \Omega$

A 9-point finite difference stencil is used to discretize
the boundary value problem to obtain a nonlinear system of equations.
This would be a 5-point stencil if not for the $p$-Laplacian's nonlinearity.
 35: /*
 36:       mpiexec -n 2 ./ex15 -snes_monitor -ksp_monitor log_summary
 37: */

 39: /*
 40:    Include "petscdmda.h" so that we can use distributed arrays (DMDAs).
 41:    Include "petscsnes.h" so that we can use SNES solvers.  Note that this
 42:    file automatically includes:
 43:      petsc.h       - base PETSc routines   petscvec.h - vectors
 44:      petscsys.h    - system routines       petscmat.h - matrices
 45:      petscis.h     - index sets            petscksp.h - Krylov subspace methods
 46:      petscviewer.h - viewers               petscpc.h  - preconditioners
 47:      petscksp.h   - linear solvers
 48: */
 49: #include <petscdm.h>
 50: #include <petscdmda.h>
 51: #include <petscsnes.h>

 53: /* These functions _should_ be internal, but currently have a reverse dependency so cannot be set with
 54:  * DMDASNESSetPicardLocal.  This hack needs to be fixed in PETSc. */
 55: PETSC_EXTERN PetscErrorCode SNESPicardComputeFunction(SNES,Vec,Vec,void*);
 56: PETSC_EXTERN PetscErrorCode SNESPicardComputeJacobian(SNES,Vec,Mat,Mat,void*);

 58: typedef enum {JAC_BRATU,JAC_PICARD,JAC_STAR,JAC_NEWTON} JacType;
 59: static const char *const JacTypes[] = {"BRATU","PICARD","STAR","NEWTON","JacType","JAC_",0};

 61: /*
 62:    User-defined application context - contains data needed by the
 63:    application-provided call-back routines, FormJacobianLocal() and
 64:    FormFunctionLocal().
 65: */
 66: typedef struct {
 67:   PetscReal   lambda;         /* Bratu parameter */
 68:   PetscReal   p;              /* Exponent in p-Laplacian */
 69:   PetscReal   epsilon;        /* Regularization */
 70:   PetscReal   source;         /* Source term */
 71:   JacType     jtype;          /* What type of Jacobian to assemble */
 72:   PetscBool   picard;
 73:   PetscInt    blocks[2];
 74:   PetscReal   kappa;
 75:   PetscInt    initial;        /* initial conditions type */
 76: } AppCtx;

 78: /*
 79:    User-defined routines
 80: */
 81: static PetscErrorCode FormRHS(AppCtx*,DM,Vec);
 82: static PetscErrorCode FormInitialGuess(AppCtx*,DM,Vec);
 83: static PetscErrorCode FormFunctionLocal(DMDALocalInfo*,PetscScalar**,PetscScalar**,AppCtx*);
 84: static PetscErrorCode FormFunctionPicardLocal(DMDALocalInfo*,PetscScalar**,PetscScalar**,AppCtx*);
 85: static PetscErrorCode FormJacobianLocal(DMDALocalInfo*,PetscScalar**,Mat,Mat,AppCtx*);
 86: static PetscErrorCode NonlinearGS(SNES,Vec,Vec,void*);

 88: typedef struct _n_PreCheck *PreCheck;
 89: struct _n_PreCheck {
 90:   MPI_Comm    comm;
 91:   PetscReal   angle;
 92:   Vec         Ylast;
 93:   PetscViewer monitor;
 94: };
 95: PetscErrorCode PreCheckCreate(MPI_Comm,PreCheck*);
 96: PetscErrorCode PreCheckDestroy(PreCheck*);
 97: PetscErrorCode PreCheckFunction(SNESLineSearch,Vec,Vec,PetscBool*,void*);
 98: PetscErrorCode PreCheckSetFromOptions(PreCheck);

102: int main(int argc,char **argv)
103: {
104:   SNES                snes;                    /* nonlinear solver */
105:   Vec                 x,r,b;                   /* solution, residual, rhs vectors */
106:   Mat                 A,B;                     /* Jacobian and preconditioning matrices */
107:   AppCtx              user;                    /* user-defined work context */
108:   PetscInt            its;                     /* iterations for convergence */
109:   SNESConvergedReason reason;                  /* Check convergence */
110:   PetscBool           alloc_star;              /* Only allocate for the STAR stencil  */
111:   PetscBool           write_output;
112:   char                filename[PETSC_MAX_PATH_LEN] = "ex15.vts";
113:   PetscReal           bratu_lambda_max             = 6.81,bratu_lambda_min = 0.;
114:   DM                  da,dastar;               /* distributed array data structure */
115:   PreCheck            precheck = NULL;    /* precheck context for version in this file */
116:   PetscInt            use_precheck;      /* 0=none, 1=version in this file, 2=SNES-provided version */
117:   PetscReal           precheck_angle;    /* When manually setting the SNES-provided precheck function */
118:   PetscErrorCode      ierr;
119:   SNESLineSearch      linesearch;

121:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
122:      Initialize program
123:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

125:   PetscInitialize(&argc,&argv,(char*)0,help);

127:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
128:      Initialize problem parameters
129:   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
130:   user.lambda    = 0.0; user.p = 2.0; user.epsilon = 1e-5; user.source = 0.1; user.jtype = JAC_NEWTON;user.initial=-1;
131:   user.blocks[0] = 1; user.blocks[1] = 1; user.kappa = 1e-3;
132:   alloc_star     = PETSC_FALSE;
133:   use_precheck   = 0; precheck_angle = 10.;
134:   user.picard    = PETSC_FALSE;
135:   PetscOptionsBegin(PETSC_COMM_WORLD,NULL,"p-Bratu options",__FILE__);
136:   {
137:     PetscInt two=2;
138:     PetscOptionsReal("-lambda","Bratu parameter","",user.lambda,&user.lambda,NULL);
139:     PetscOptionsReal("-p","Exponent `p' in p-Laplacian","",user.p,&user.p,NULL);
140:     PetscOptionsReal("-epsilon","Strain-regularization in p-Laplacian","",user.epsilon,&user.epsilon,NULL);
141:     PetscOptionsReal("-source","Constant source term","",user.source,&user.source,NULL);
142:     PetscOptionsEnum("-jtype","Jacobian approximation to assemble","",JacTypes,(PetscEnum)user.jtype,(PetscEnum*)&user.jtype,NULL);
143:     PetscOptionsName("-picard","Solve with defect-correction Picard iteration","",&user.picard);
144:     if (user.picard) {user.jtype = JAC_PICARD; user.p = 3;}
145:     PetscOptionsBool("-alloc_star","Allocate for STAR stencil (5-point)","",alloc_star,&alloc_star,NULL);
146:     PetscOptionsInt("-precheck","Use a pre-check correction intended for use with Picard iteration 1=this version, 2=library","",use_precheck,&use_precheck,NULL);
147:     PetscOptionsInt("-initial","Initial conditions type (-1: default, 0: zero-valued, 1: peaked guess)","",user.initial,&user.initial,NULL);
148:     if (use_precheck == 2) {    /* Using library version, get the angle */
149:       PetscOptionsReal("-precheck_angle","Angle in degrees between successive search directions necessary to activate step correction","",precheck_angle,&precheck_angle,NULL);
150:     }
151:     PetscOptionsIntArray("-blocks","number of coefficient interfaces in x and y direction","",user.blocks,&two,NULL);
152:     PetscOptionsReal("-kappa","diffusivity in odd regions","",user.kappa,&user.kappa,NULL);
153:     PetscOptionsString("-o","Output solution in vts format","",filename,filename,sizeof(filename),&write_output);
154:   }
155:   PetscOptionsEnd();
156:   if (user.lambda > bratu_lambda_max || user.lambda < bratu_lambda_min) {
157:     PetscPrintf(PETSC_COMM_WORLD,"WARNING: lambda %g out of range for p=2\n",user.lambda);
158:   }

160:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
161:      Create nonlinear solver context
162:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
163:   SNESCreate(PETSC_COMM_WORLD,&snes);

165:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
166:      Create distributed array (DMDA) to manage parallel grid and vectors
167:   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
168:   DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_BOX,-4,-4,PETSC_DECIDE,PETSC_DECIDE,
169:                       1,1,NULL,NULL,&da);
170:   DMDACreate2d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,DM_BOUNDARY_NONE,DMDA_STENCIL_STAR,-4,-4,PETSC_DECIDE,PETSC_DECIDE,
171:                       1,1,NULL,NULL,&dastar);


174:   /*  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
175:      Extract global vectors from DM; then duplicate for remaining
176:      vectors that are the same types
177:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
178:   DMCreateGlobalVector(da,&x);
179:   VecDuplicate(x,&r);
180:   VecDuplicate(x,&b);

182:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
183:      Create matrix data structure; set Jacobian evaluation routine

185:      Set Jacobian matrix data structure and default Jacobian evaluation
186:      routine. User can override with:
187:      -snes_mf : matrix-free Newton-Krylov method with no preconditioning
188:                 (unless user explicitly sets preconditioner)
189:      -snes_mf_operator : form preconditioning matrix as set by the user,
190:                          but use matrix-free approx for Jacobian-vector
191:                          products within Newton-Krylov method

193:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
194:   /* B can be type of MATAIJ,MATBAIJ or MATSBAIJ */
195:   DMCreateMatrix(alloc_star ? dastar : da,&B);
196:   A    = B;

198:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
199:      Set local function evaluation routine
200:   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
201:   DMSetApplicationContext(da, &user);
202:   SNESSetDM(snes,da);
203:   if (user.picard) {
204:     /*
205:         This is not really right requiring the user to call SNESSetFunction/Jacobian but the DMDASNESSetPicardLocal() cannot access
206:         the SNES to set it
207:     */
208:     DMDASNESSetPicardLocal(da,INSERT_VALUES,(PetscErrorCode (*)(DMDALocalInfo*,void*,void*,void*))FormFunctionPicardLocal,
209:                                   (PetscErrorCode (*)(DMDALocalInfo*,void*,Mat,Mat,void*))FormJacobianLocal,&user);
210:     SNESSetFunction(snes,NULL,SNESPicardComputeFunction,&user);
211:     SNESSetJacobian(snes,NULL,NULL,SNESPicardComputeJacobian,&user);
212:   } else {
213:     DMDASNESSetFunctionLocal(da,INSERT_VALUES,(PetscErrorCode (*)(DMDALocalInfo*,void*,void*,void*))FormFunctionLocal,&user);
214:     DMDASNESSetJacobianLocal(da,(PetscErrorCode (*)(DMDALocalInfo*,void*,Mat,Mat,void*))FormJacobianLocal,&user);
215:   }


218:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
219:      Customize nonlinear solver; set runtime options
220:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
221:   SNESSetFromOptions(snes);
222:   SNESSetNGS(snes,NonlinearGS,&user);
223:   SNESGetLineSearch(snes, &linesearch);
224:   /* Set up the precheck context if requested */
225:   if (use_precheck == 1) {      /* Use the precheck routines in this file */
226:     PreCheckCreate(PETSC_COMM_WORLD,&precheck);
227:     PreCheckSetFromOptions(precheck);
228:     SNESLineSearchSetPreCheck(linesearch,PreCheckFunction,precheck);
229:   } else if (use_precheck == 2) { /* Use the version provided by the library */
230:     SNESLineSearchSetPreCheck(linesearch,SNESLineSearchPreCheckPicard,&precheck_angle);
231:   }

233:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
234:      Evaluate initial guess
235:      Note: The user should initialize the vector, x, with the initial guess
236:      for the nonlinear solver prior to calling SNESSolve().  In particular,
237:      to employ an initial guess of zero, the user should explicitly set
238:      this vector to zero by calling VecSet().
239:   */

241:   FormInitialGuess(&user,da,x);
242:   FormRHS(&user,da,b);

244:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
245:      Solve nonlinear system
246:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
247:   SNESSolve(snes,b,x);
248:   SNESGetIterationNumber(snes,&its);
249:   SNESGetConvergedReason(snes,&reason);

251:   PetscPrintf(PETSC_COMM_WORLD,"%s Number of nonlinear iterations = %D\n",SNESConvergedReasons[reason],its);

253:   if (write_output) {
254:     PetscViewer viewer;
255:     PetscViewerVTKOpen(PETSC_COMM_WORLD,filename,FILE_MODE_WRITE,&viewer);
256:     VecView(x,viewer);
257:     PetscViewerDestroy(&viewer);
258:   }

260:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
261:      Free work space.  All PETSc objects should be destroyed when they
262:      are no longer needed.
263:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

265:   if (A != B) {
266:     MatDestroy(&A);
267:   }
268:   MatDestroy(&B);
269:   VecDestroy(&x);
270:   VecDestroy(&r);
271:   VecDestroy(&b);
272:   SNESDestroy(&snes);
273:   DMDestroy(&da);
274:   DMDestroy(&dastar);
275:   PreCheckDestroy(&precheck);
276:   PetscFinalize();
277:   return 0;
278: }

280: /* ------------------------------------------------------------------- */
283: /*
284:    FormInitialGuess - Forms initial approximation.

286:    Input Parameters:
287:    user - user-defined application context
288:    X - vector

290:    Output Parameter:
291:    X - vector
292:  */
293: static PetscErrorCode FormInitialGuess(AppCtx *user,DM da,Vec X)
294: {
295:   PetscInt       i,j,Mx,My,xs,ys,xm,ym;
297:   PetscReal      temp1,temp,hx,hy;
298:   PetscScalar    **x;

301:   DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,
302:                      PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE);

304:   hx    = 1.0/(PetscReal)(Mx-1);
305:   hy    = 1.0/(PetscReal)(My-1);
306:   temp1 = user->lambda / (user->lambda + 1.);

308:   /*
309:      Get a pointer to vector data.
310:        - For default PETSc vectors, VecGetArray() returns a pointer to
311:          the data array.  Otherwise, the routine is implementation dependent.
312:        - You MUST call VecRestoreArray() when you no longer need access to
313:          the array.
314:   */
315:   DMDAVecGetArray(da,X,&x);

317:   /*
318:      Get local grid boundaries (for 2-dimensional DA):
319:        xs, ys   - starting grid indices (no ghost points)
320:        xm, ym   - widths of local grid (no ghost points)

322:   */
323:   DMDAGetCorners(da,&xs,&ys,NULL,&xm,&ym,NULL);

325:   /*
326:      Compute initial guess over the locally owned part of the grid
327:   */
328:   for (j=ys; j<ys+ym; j++) {
329:     temp = (PetscReal)(PetscMin(j,My-j-1))*hy;
330:     for (i=xs; i<xs+xm; i++) {
331:       if (i == 0 || j == 0 || i == Mx-1 || j == My-1) {
332:         /* boundary conditions are all zero Dirichlet */
333:         x[j][i] = 0.0;
334:       } else {
335:         if (user->initial == -1) {
336:           if (user->lambda != 0) {
337:             x[j][i] = temp1*PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i,Mx-i-1))*hx,temp));
338:           } else {
339:             /* The solution above is an exact solution for lambda=0, this avoids "accidentally" starting
340:              * with an exact solution. */
341:             const PetscReal
342:               xx = 2*(PetscReal)i/(Mx-1) - 1,
343:               yy = 2*(PetscReal)j/(My-1) - 1;
344:             x[j][i] = (1 - xx*xx) * (1-yy*yy) * xx * yy;
345:           }
346:         } else if (user->initial == 0) {
347:           x[j][i] = 0.;
348:         } else if (user->initial == 1) {
349:           const PetscReal
350:             xx = 2*(PetscReal)i/(Mx-1) - 1,
351:             yy = 2*(PetscReal)j/(My-1) - 1;
352:           x[j][i] = (1 - xx*xx) * (1-yy*yy) * xx * yy;
353:         } else {
354:           if (user->lambda != 0) {
355:             x[j][i] = temp1*PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i,Mx-i-1))*hx,temp));
356:           } else {
357:             x[j][i] = 0.5*PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i,Mx-i-1))*hx,temp));
358:           }
359:         }
360:       }
361:     }
362:   }
363:   /*
364:      Restore vector
365:   */
366:   DMDAVecRestoreArray(da,X,&x);
367:   return(0);
368: }

372: /*
373:    FormRHS - Forms constant RHS for the problem.

375:    Input Parameters:
376:    user - user-defined application context
377:    B - RHS vector

379:    Output Parameter:
380:    B - vector
381:  */
382: static PetscErrorCode FormRHS(AppCtx *user,DM da,Vec B)
383: {
384:   PetscInt       i,j,Mx,My,xs,ys,xm,ym;
386:   PetscReal      hx,hy;
387:   PetscScalar    **b;

390:   DMDAGetInfo(da,PETSC_IGNORE,&Mx,&My,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE,PETSC_IGNORE);

392:   hx    = 1.0/(PetscReal)(Mx-1);
393:   hy    = 1.0/(PetscReal)(My-1);
394:   DMDAVecGetArray(da,B,&b);
395:   DMDAGetCorners(da,&xs,&ys,NULL,&xm,&ym,NULL);
396:   for (j=ys; j<ys+ym; j++) {
397:     for (i=xs; i<xs+xm; i++) {
398:       if (i == 0 || j == 0 || i == Mx-1 || j == My-1) {
399:         b[j][i] = 0.0;
400:       } else {
401:         b[j][i] = hx*hy*user->source;
402:       }
403:     }
404:   }
405:   DMDAVecRestoreArray(da,B,&b);
406:   return(0);
407: }

409: PETSC_STATIC_INLINE PetscReal kappa(const AppCtx *ctx,PetscReal x,PetscReal y)
410: {
411:   return (((PetscInt)(x*ctx->blocks[0])) + ((PetscInt)(y*ctx->blocks[1]))) % 2 ? ctx->kappa : 1.0;
412: }
413: /* p-Laplacian diffusivity */
414: PETSC_STATIC_INLINE PetscScalar eta(const AppCtx *ctx,PetscReal x,PetscReal y,PetscScalar ux,PetscScalar uy)
415: {
416:   return kappa(ctx,x,y) * PetscPowScalar(PetscSqr(ctx->epsilon)+0.5*(ux*ux + uy*uy),0.5*(ctx->p-2.));
417: }
418: PETSC_STATIC_INLINE PetscScalar deta(const AppCtx *ctx,PetscReal x,PetscReal y,PetscScalar ux,PetscScalar uy)
419: {
420:   return (ctx->p == 2)
421:          ? 0
422:          : kappa(ctx,x,y)*PetscPowScalar(PetscSqr(ctx->epsilon)+0.5*(ux*ux + uy*uy),0.5*(ctx->p-4)) * 0.5 * (ctx->p-2.);
423: }


426: /* ------------------------------------------------------------------- */
429: /*
430:    FormFunctionLocal - Evaluates nonlinear function, F(x).
431:  */
432: static PetscErrorCode FormFunctionLocal(DMDALocalInfo *info,PetscScalar **x,PetscScalar **f,AppCtx *user)
433: {
434:   PetscReal      hx,hy,dhx,dhy,sc;
435:   PetscInt       i,j;
436:   PetscScalar    eu;


441:   hx     = 1.0/(PetscReal)(info->mx-1);
442:   hy     = 1.0/(PetscReal)(info->my-1);
443:   sc     = hx*hy*user->lambda;
444:   dhx    = 1/hx;
445:   dhy    = 1/hy;
446:   /*
447:      Compute function over the locally owned part of the grid
448:   */
449:   for (j=info->ys; j<info->ys+info->ym; j++) {
450:     for (i=info->xs; i<info->xs+info->xm; i++) {
451:       PetscReal xx = i*hx,yy = j*hy;
452:       if (i == 0 || j == 0 || i == info->mx-1 || j == info->my-1) {
453:         f[j][i] = x[j][i];
454:       } else {
455:         const PetscScalar
456:           u    = x[j][i],
457:           ux_E = dhx*(x[j][i+1]-x[j][i]),
458:           uy_E = 0.25*dhy*(x[j+1][i]+x[j+1][i+1]-x[j-1][i]-x[j-1][i+1]),
459:           ux_W = dhx*(x[j][i]-x[j][i-1]),
460:           uy_W = 0.25*dhy*(x[j+1][i-1]+x[j+1][i]-x[j-1][i-1]-x[j-1][i]),
461:           ux_N = 0.25*dhx*(x[j][i+1]+x[j+1][i+1]-x[j][i-1]-x[j+1][i-1]),
462:           uy_N = dhy*(x[j+1][i]-x[j][i]),
463:           ux_S = 0.25*dhx*(x[j-1][i+1]+x[j][i+1]-x[j-1][i-1]-x[j][i-1]),
464:           uy_S = dhy*(x[j][i]-x[j-1][i]),
465:           e_E  = eta(user,xx,yy,ux_E,uy_E),
466:           e_W  = eta(user,xx,yy,ux_W,uy_W),
467:           e_N  = eta(user,xx,yy,ux_N,uy_N),
468:           e_S  = eta(user,xx,yy,ux_S,uy_S),
469:           uxx  = -hy * (e_E*ux_E - e_W*ux_W),
470:           uyy  = -hx * (e_N*uy_N - e_S*uy_S);
471:         if (sc) eu = PetscExpScalar(u);
472:         else    eu = 0.;
473:         /** For p=2, these terms decay to:
474:         * uxx = (2.0*u - x[j][i-1] - x[j][i+1])*hydhx
475:         * uyy = (2.0*u - x[j-1][i] - x[j+1][i])*hxdhy
476:         **/
477:         f[j][i] = uxx + uyy - sc*eu;
478:       }
479:     }
480:   }
481:   PetscLogFlops(info->xm*info->ym*(72.0));
482:   return(0);
483: }

487: /*
488:     This is the opposite sign of the part of FormFunctionLocal that excludes the A(x) x part of the operation,
489:     that is FormFunction applies A(x) x - b(x) while this applies b(x) because for Picard we think of it as solving A(x) x = b(x)

491: */
492: static PetscErrorCode FormFunctionPicardLocal(DMDALocalInfo *info,PetscScalar **x,PetscScalar **f,AppCtx *user)
493: {
494:   PetscReal hx,hy,sc;
495:   PetscInt  i,j;

499:   hx     = 1.0/(PetscReal)(info->mx-1);
500:   hy     = 1.0/(PetscReal)(info->my-1);
501:   sc     = hx*hy*user->lambda;
502:   /*
503:      Compute function over the locally owned part of the grid
504:   */
505:   for (j=info->ys; j<info->ys+info->ym; j++) {
506:     for (i=info->xs; i<info->xs+info->xm; i++) {
507:       if (!(i == 0 || j == 0 || i == info->mx-1 || j == info->my-1)) {
508:         const PetscScalar u = x[j][i];
509:         f[j][i] = sc*PetscExpScalar(u);
510:       }
511:     }
512:   }
513:   PetscLogFlops(info->xm*info->ym*2.0);
514:   return(0);
515: }

519: /*
520:    FormJacobianLocal - Evaluates Jacobian matrix.
521: */
522: static PetscErrorCode FormJacobianLocal(DMDALocalInfo *info,PetscScalar **x,Mat J,Mat B,AppCtx *user)
523: {
525:   PetscInt       i,j;
526:   MatStencil     col[9],row;
527:   PetscScalar    v[9];
528:   PetscReal      hx,hy,hxdhy,hydhx,dhx,dhy,sc;

531:   hx    = 1.0/(PetscReal)(info->mx-1);
532:   hy    = 1.0/(PetscReal)(info->my-1);
533:   sc    = hx*hy*user->lambda;
534:   dhx   = 1/hx;
535:   dhy   = 1/hy;
536:   hxdhy = hx/hy;
537:   hydhx = hy/hx;

539:   /*
540:      Compute entries for the locally owned part of the Jacobian.
541:       - PETSc parallel matrix formats are partitioned by
542:         contiguous chunks of rows across the processors.
543:       - Each processor needs to insert only elements that it owns
544:         locally (but any non-local elements will be sent to the
545:         appropriate processor during matrix assembly).
546:       - Here, we set all entries for a particular row at once.
547:   */
548:   for (j=info->ys; j<info->ys+info->ym; j++) {
549:     for (i=info->xs; i<info->xs+info->xm; i++) {
550:       PetscReal xx = i*hx,yy = j*hy;
551:       row.j = j; row.i = i;
552:       /* boundary points */
553:       if (i == 0 || j == 0 || i == info->mx-1 || j == info->my-1) {
554:         v[0] = 1.0;
555:         MatSetValuesStencil(B,1,&row,1,&row,v,INSERT_VALUES);
556:       } else {
557:         /* interior grid points */
558:         const PetscScalar
559:           ux_E     = dhx*(x[j][i+1]-x[j][i]),
560:           uy_E     = 0.25*dhy*(x[j+1][i]+x[j+1][i+1]-x[j-1][i]-x[j-1][i+1]),
561:           ux_W     = dhx*(x[j][i]-x[j][i-1]),
562:           uy_W     = 0.25*dhy*(x[j+1][i-1]+x[j+1][i]-x[j-1][i-1]-x[j-1][i]),
563:           ux_N     = 0.25*dhx*(x[j][i+1]+x[j+1][i+1]-x[j][i-1]-x[j+1][i-1]),
564:           uy_N     = dhy*(x[j+1][i]-x[j][i]),
565:           ux_S     = 0.25*dhx*(x[j-1][i+1]+x[j][i+1]-x[j-1][i-1]-x[j][i-1]),
566:           uy_S     = dhy*(x[j][i]-x[j-1][i]),
567:           u        = x[j][i],
568:           e_E      = eta(user,xx,yy,ux_E,uy_E),
569:           e_W      = eta(user,xx,yy,ux_W,uy_W),
570:           e_N      = eta(user,xx,yy,ux_N,uy_N),
571:           e_S      = eta(user,xx,yy,ux_S,uy_S),
572:           de_E     = deta(user,xx,yy,ux_E,uy_E),
573:           de_W     = deta(user,xx,yy,ux_W,uy_W),
574:           de_N     = deta(user,xx,yy,ux_N,uy_N),
575:           de_S     = deta(user,xx,yy,ux_S,uy_S),
576:           skew_E   = de_E*ux_E*uy_E,
577:           skew_W   = de_W*ux_W*uy_W,
578:           skew_N   = de_N*ux_N*uy_N,
579:           skew_S   = de_S*ux_S*uy_S,
580:           cross_EW = 0.25*(skew_E - skew_W),
581:           cross_NS = 0.25*(skew_N - skew_S),
582:           newt_E   = e_E+de_E*PetscSqr(ux_E),
583:           newt_W   = e_W+de_W*PetscSqr(ux_W),
584:           newt_N   = e_N+de_N*PetscSqr(uy_N),
585:           newt_S   = e_S+de_S*PetscSqr(uy_S);
586:         /* interior grid points */
587:         switch (user->jtype) {
588:         case JAC_BRATU:
589:           /* Jacobian from p=2 */
590:           v[0] = -hxdhy;                                           col[0].j = j-1;   col[0].i = i;
591:           v[1] = -hydhx;                                           col[1].j = j;     col[1].i = i-1;
592:           v[2] = 2.0*(hydhx + hxdhy) - sc*PetscExpScalar(u);       col[2].j = row.j; col[2].i = row.i;
593:           v[3] = -hydhx;                                           col[3].j = j;     col[3].i = i+1;
594:           v[4] = -hxdhy;                                           col[4].j = j+1;   col[4].i = i;
595:           MatSetValuesStencil(B,1,&row,5,col,v,INSERT_VALUES);
596:           break;
597:         case JAC_PICARD:
598:           /* Jacobian arising from Picard linearization */
599:           v[0] = -hxdhy*e_S;                                           col[0].j = j-1;   col[0].i = i;
600:           v[1] = -hydhx*e_W;                                           col[1].j = j;     col[1].i = i-1;
601:           v[2] = (e_W+e_E)*hydhx + (e_S+e_N)*hxdhy;                    col[2].j = row.j; col[2].i = row.i;
602:           v[3] = -hydhx*e_E;                                           col[3].j = j;     col[3].i = i+1;
603:           v[4] = -hxdhy*e_N;                                           col[4].j = j+1;   col[4].i = i;
604:           MatSetValuesStencil(B,1,&row,5,col,v,INSERT_VALUES);
605:           break;
606:         case JAC_STAR:
607:           /* Full Jacobian, but only a star stencil */
608:           col[0].j = j-1; col[0].i = i;
609:           col[1].j = j;   col[1].i = i-1;
610:           col[2].j = j;   col[2].i = i;
611:           col[3].j = j;   col[3].i = i+1;
612:           col[4].j = j+1; col[4].i = i;
613:           v[0]     = -hxdhy*newt_S + cross_EW;
614:           v[1]     = -hydhx*newt_W + cross_NS;
615:           v[2]     = hxdhy*(newt_N + newt_S) + hydhx*(newt_E + newt_W) - sc*PetscExpScalar(u);
616:           v[3]     = -hydhx*newt_E - cross_NS;
617:           v[4]     = -hxdhy*newt_N - cross_EW;
618:           MatSetValuesStencil(B,1,&row,5,col,v,INSERT_VALUES);
619:           break;
620:         case JAC_NEWTON:
621:           /** The Jacobian is
622:           *
623:           * -div [ eta (grad u) + deta (grad u0 . grad u) grad u0 ] - (eE u0) u
624:           *
625:           **/
626:           col[0].j = j-1; col[0].i = i-1;
627:           col[1].j = j-1; col[1].i = i;
628:           col[2].j = j-1; col[2].i = i+1;
629:           col[3].j = j;   col[3].i = i-1;
630:           col[4].j = j;   col[4].i = i;
631:           col[5].j = j;   col[5].i = i+1;
632:           col[6].j = j+1; col[6].i = i-1;
633:           col[7].j = j+1; col[7].i = i;
634:           col[8].j = j+1; col[8].i = i+1;
635:           v[0]     = -0.25*(skew_S + skew_W);
636:           v[1]     = -hxdhy*newt_S + cross_EW;
637:           v[2]     =  0.25*(skew_S + skew_E);
638:           v[3]     = -hydhx*newt_W + cross_NS;
639:           v[4]     = hxdhy*(newt_N + newt_S) + hydhx*(newt_E + newt_W) - sc*PetscExpScalar(u);
640:           v[5]     = -hydhx*newt_E - cross_NS;
641:           v[6]     =  0.25*(skew_N + skew_W);
642:           v[7]     = -hxdhy*newt_N - cross_EW;
643:           v[8]     = -0.25*(skew_N + skew_E);
644:           MatSetValuesStencil(B,1,&row,9,col,v,INSERT_VALUES);
645:           break;
646:         default:
647:           SETERRQ1(PetscObjectComm((PetscObject)info->da),PETSC_ERR_SUP,"Jacobian type %d not implemented",user->jtype);
648:         }
649:       }
650:     }
651:   }

653:   /*
654:      Assemble matrix, using the 2-step process:
655:        MatAssemblyBegin(), MatAssemblyEnd().
656:   */
657:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
658:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

660:   if (J != B) {
661:     MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
662:     MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
663:   }

665:   /*
666:      Tell the matrix we will never add a new nonzero location to the
667:      matrix. If we do, it will generate an error.
668:   */
669:   if (user->jtype == JAC_NEWTON) {
670:     PetscLogFlops(info->xm*info->ym*(131.0));
671:   }
672:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);
673:   return(0);
674: }

676: /***********************************************************
677:  * PreCheck implementation
678:  ***********************************************************/
681: PetscErrorCode PreCheckSetFromOptions(PreCheck precheck)
682: {
684:   PetscBool      flg;

687:   PetscOptionsBegin(precheck->comm,NULL,"PreCheck Options","none");
688:   PetscOptionsReal("-precheck_angle","Angle in degrees between successive search directions necessary to activate step correction","",precheck->angle,&precheck->angle,NULL);
689:   flg  = PETSC_FALSE;
690:   PetscOptionsBool("-precheck_monitor","Monitor choices made by precheck routine","",flg,&flg,NULL);
691:   if (flg) {
692:     PetscViewerASCIIOpen(precheck->comm,"stdout",&precheck->monitor);
693:   }
694:   PetscOptionsEnd();
695:   return(0);
696: }

700: /*
701:   Compare the direction of the current and previous step, modify the current step accordingly
702: */
703: PetscErrorCode PreCheckFunction(SNESLineSearch linesearch,Vec X,Vec Y,PetscBool *changed, void *ctx)
704: {
706:   PreCheck       precheck;
707:   Vec            Ylast;
708:   PetscScalar    dot;
709:   PetscInt       iter;
710:   PetscReal      ynorm,ylastnorm,theta,angle_radians;
711:   SNES           snes;

714:   SNESLineSearchGetSNES(linesearch, &snes);
715:   precheck = (PreCheck)ctx;
716:   if (!precheck->Ylast) {VecDuplicate(Y,&precheck->Ylast);}
717:   Ylast = precheck->Ylast;
718:   SNESGetIterationNumber(snes,&iter);
719:   if (iter < 1) {
720:     VecCopy(Y,Ylast);
721:     *changed = PETSC_FALSE;
722:     return(0);
723:   }

725:   VecDot(Y,Ylast,&dot);
726:   VecNorm(Y,NORM_2,&ynorm);
727:   VecNorm(Ylast,NORM_2,&ylastnorm);
728:   /* Compute the angle between the vectors Y and Ylast, clip to keep inside the domain of acos() */
729:   theta         = PetscAcosReal((PetscReal)PetscClipInterval(PetscAbsScalar(dot) / (ynorm * ylastnorm),-1.0,1.0));
730:   angle_radians = precheck->angle * PETSC_PI / 180.;
731:   if (PetscAbsReal(theta) < angle_radians || PetscAbsReal(theta - PETSC_PI) < angle_radians) {
732:     /* Modify the step Y */
733:     PetscReal alpha,ydiffnorm;
734:     VecAXPY(Ylast,-1.0,Y);
735:     VecNorm(Ylast,NORM_2,&ydiffnorm);
736:     alpha = ylastnorm / ydiffnorm;
737:     VecCopy(Y,Ylast);
738:     VecScale(Y,alpha);
739:     if (precheck->monitor) {
740:       PetscViewerASCIIPrintf(precheck->monitor,"Angle %E degrees less than threshold %g, corrected step by alpha=%g\n",(double)(theta*180./PETSC_PI),(double)precheck->angle,(double)alpha);
741:     }
742:   } else {
743:     VecCopy(Y,Ylast);
744:     *changed = PETSC_FALSE;
745:     if (precheck->monitor) {
746:       PetscViewerASCIIPrintf(precheck->monitor,"Angle %E degrees exceeds threshold %g, no correction applied\n",(double)(theta*180./PETSC_PI),(double)precheck->angle);
747:     }
748:   }
749:   return(0);
750: }

754: PetscErrorCode PreCheckDestroy(PreCheck *precheck)
755: {

759:   if (!*precheck) return(0);
760:   VecDestroy(&(*precheck)->Ylast);
761:   PetscViewerDestroy(&(*precheck)->monitor);
762:   PetscFree(*precheck);
763:   return(0);
764: }

768: PetscErrorCode PreCheckCreate(MPI_Comm comm,PreCheck *precheck)
769: {

773:   PetscMalloc(sizeof(struct _n_PreCheck),precheck);
774:   PetscMemzero(*precheck,sizeof(struct _n_PreCheck));

776:   (*precheck)->comm  = comm;
777:   (*precheck)->angle = 10.;     /* only active if angle is less than 10 degrees */
778:   return(0);
779: }

783: /*
784:       Applies some sweeps on nonlinear Gauss-Seidel on each process

786:  */
787: PetscErrorCode NonlinearGS(SNES snes,Vec X, Vec B, void *ctx)
788: {
789:   PetscInt       i,j,k,xs,ys,xm,ym,its,tot_its,sweeps,l,m;
791:   PetscReal      hx,hy,hxdhy,hydhx,dhx,dhy,sc;
792:   PetscScalar    **x,**b,bij,F,F0=0,J,y,u,eu;
793:   PetscReal      atol,rtol,stol;
794:   DM             da;
795:   AppCtx         *user = (AppCtx*)ctx;
796:   Vec            localX,localB;
797:   DMDALocalInfo  info;

800:   SNESGetDM(snes,&da);
801:   DMDAGetLocalInfo(da,&info);

803:   hx     = 1.0/(PetscReal)(info.mx-1);
804:   hy     = 1.0/(PetscReal)(info.my-1);
805:   sc     = hx*hy*user->lambda;
806:   dhx    = 1/hx;
807:   dhy    = 1/hy;
808:   hxdhy  = hx/hy;
809:   hydhx  = hy/hx;

811:   tot_its = 0;
812:   SNESNGSGetSweeps(snes,&sweeps);
813:   SNESNGSGetTolerances(snes,&atol,&rtol,&stol,&its);
814:   DMGetLocalVector(da,&localX);
815:   if (B) {
816:     DMGetLocalVector(da,&localB);
817:   }
818:   if (B) {
819:     DMGlobalToLocalBegin(da,B,INSERT_VALUES,localB);
820:     DMGlobalToLocalEnd(da,B,INSERT_VALUES,localB);
821:   }
822:   if (B) DMDAVecGetArrayRead(da,localB,&b);
823:   DMGlobalToLocalBegin(da,X,INSERT_VALUES,localX);
824:   DMGlobalToLocalEnd(da,X,INSERT_VALUES,localX);
825:   DMDAVecGetArray(da,localX,&x);
826:   for (l=0; l<sweeps; l++) {
827:     /*
828:      Get local grid boundaries (for 2-dimensional DMDA):
829:      xs, ys   - starting grid indices (no ghost points)
830:      xm, ym   - widths of local grid (no ghost points)
831:      */
832:     DMDAGetCorners(da,&xs,&ys,NULL,&xm,&ym,NULL);
833:     for (m=0; m<2; m++) {
834:       for (j=ys; j<ys+ym; j++) {
835:         for (i=xs+(m+j)%2; i<xs+xm; i+=2) {
836:           PetscReal xx = i*hx,yy = j*hy;
837:           if (B) bij = b[j][i];
838:           else   bij = 0.;

840:           if (i == 0 || j == 0 || i == info.mx-1 || j == info.my-1) {
841:             /* boundary conditions are all zero Dirichlet */
842:             x[j][i] = 0.0 + bij;
843:           } else {
844:             const PetscScalar
845:               u_E = x[j][i+1],
846:               u_W = x[j][i-1],
847:               u_N = x[j+1][i],
848:               u_S = x[j-1][i];
849:             const PetscScalar
850:               uy_E   = 0.25*dhy*(x[j+1][i]+x[j+1][i+1]-x[j-1][i]-x[j-1][i+1]),
851:               uy_W   = 0.25*dhy*(x[j+1][i-1]+x[j+1][i]-x[j-1][i-1]-x[j-1][i]),
852:               ux_N   = 0.25*dhx*(x[j][i+1]+x[j+1][i+1]-x[j][i-1]-x[j+1][i-1]),
853:               ux_S   = 0.25*dhx*(x[j-1][i+1]+x[j][i+1]-x[j-1][i-1]-x[j][i-1]);
854:             u = x[j][i];
855:             for (k=0; k<its; k++) {
856:               const PetscScalar
857:                 ux_E   = dhx*(u_E-u),
858:                 ux_W   = dhx*(u-u_W),
859:                 uy_N   = dhy*(u_N-u),
860:                 uy_S   = dhy*(u-u_S),
861:                 e_E    = eta(user,xx,yy,ux_E,uy_E),
862:                 e_W    = eta(user,xx,yy,ux_W,uy_W),
863:                 e_N    = eta(user,xx,yy,ux_N,uy_N),
864:                 e_S    = eta(user,xx,yy,ux_S,uy_S),
865:                 de_E   = deta(user,xx,yy,ux_E,uy_E),
866:                 de_W   = deta(user,xx,yy,ux_W,uy_W),
867:                 de_N   = deta(user,xx,yy,ux_N,uy_N),
868:                 de_S   = deta(user,xx,yy,ux_S,uy_S),
869:                 newt_E = e_E+de_E*PetscSqr(ux_E),
870:                 newt_W = e_W+de_W*PetscSqr(ux_W),
871:                 newt_N = e_N+de_N*PetscSqr(uy_N),
872:                 newt_S = e_S+de_S*PetscSqr(uy_S),
873:                 uxx    = -hy * (e_E*ux_E - e_W*ux_W),
874:                 uyy    = -hx * (e_N*uy_N - e_S*uy_S);

876:               if (sc) eu = PetscExpScalar(u);
877:               else    eu = 0;

879:               F = uxx + uyy - sc*eu - bij;
880:               if (k == 0) F0 = F;
881:               J  = hxdhy*(newt_N + newt_S) + hydhx*(newt_E + newt_W) - sc*eu;
882:               y  = F/J;
883:               u -= y;
884:               tot_its++;
885:               if (atol > PetscAbsReal(PetscRealPart(F)) ||
886:                   rtol*PetscAbsReal(PetscRealPart(F0)) > PetscAbsReal(PetscRealPart(F)) ||
887:                   stol*PetscAbsReal(PetscRealPart(u)) > PetscAbsReal(PetscRealPart(y))) {
888:                 break;
889:               }
890:             }
891:             x[j][i] = u;
892:           }
893:         }
894:       }
895:     }
896:     /*
897: x     Restore vector
898:      */
899:   }
900:   DMDAVecRestoreArray(da,localX,&x);
901:   DMLocalToGlobalBegin(da,localX,INSERT_VALUES,X);
902:   DMLocalToGlobalEnd(da,localX,INSERT_VALUES,X);
903:   PetscLogFlops(tot_its*(118.0));
904:   DMRestoreLocalVector(da,&localX);
905:   if (B) {
906:     DMDAVecRestoreArrayRead(da,localB,&b);
907:     DMRestoreLocalVector(da,&localB);
908:   }
909:   return(0);
910: }