Actual source code: ex1.c

  2: /* Program usage:  ex4 [-help] [all PETSc options] */

  4: static char help[] = "Solves a nonlinear system on 1 processor with SNES. We\n\
  5: solve the Bratu (SFI - solid fuel ignition) problem in a 2D rectangular domain.\n\
  6: This example also illustrates the use of matrix coloring.  Runtime options include:\n\
  7:   -par <parameter>, where <parameter> indicates the problem's nonlinearity\n\
  8:      problem SFI:  <parameter> = Bratu parameter (0 <= par <= 6.81)\n\
  9:   -mx <xg>, where <xg> = number of grid points in the x-direction\n\
 10:   -my <yg>, where <yg> = number of grid points in the y-direction\n\n";

 12: /*T
 13:    Concepts: SNES^sequential Bratu example
 14:    Processors: 1
 15: T*/

 17: /* ------------------------------------------------------------------------

 19:     Solid Fuel Ignition (SFI) problem.  This problem is modeled by
 20:     the partial differential equation
 21:   
 22:             -Laplacian u - lambda*exp(u) = 0,  0 < x,y < 1,
 23:   
 24:     with boundary conditions
 25:    
 26:              u = 0  for  x = 0, x = 1, y = 0, y = 1.
 27:   
 28:     A finite difference approximation with the usual 5-point stencil
 29:     is used to discretize the boundary value problem to obtain a nonlinear 
 30:     system of equations.

 32:     The parallel version of this code is snes/examples/tutorials/ex5.c

 34:   ------------------------------------------------------------------------- */

 36: /* 
 37:    Include "petscsnes.h" so that we can use SNES solvers.  Note that
 38:    this file automatically includes:
 39:      petscsys.h       - base PETSc routines   petscvec.h - vectors
 40:      petscmat.h - matrices
 41:      petscis.h     - index sets            petscksp.h - Krylov subspace methods
 42:      petscviewer.h - viewers               petscpc.h  - preconditioners
 43:      petscksp.h   - linear solvers
 44: */

 46:  #include petscsnes.h

 48: /* 
 49:    User-defined application context - contains data needed by the 
 50:    application-provided call-back routines, FormJacobian() and
 51:    FormFunction().
 52: */
 53: typedef struct {
 54:       PetscReal   param;        /* test problem parameter */
 55:       PetscInt    mx;           /* Discretization in x-direction */
 56:       PetscInt    my;           /* Discretization in y-direction */
 57: } AppCtx;

 59: /* 
 60:    User-defined routines
 61: */

 68: int main(int argc,char **argv)
 69: {
 70:   SNES           snes;                 /* nonlinear solver context */
 71:   Vec            x,r;                 /* solution, residual vectors */
 72:   Mat            J;                    /* Jacobian matrix */
 73:   AppCtx         user;                 /* user-defined application context */
 75:   PetscInt       i,its,N,hist_its[50];
 76:   PetscMPIInt    size;
 77:   PetscReal      bratu_lambda_max = 6.81,bratu_lambda_min = 0.,history[50];
 78:   MatFDColoring  fdcoloring;
 79:   PetscTruth     matrix_free = PETSC_FALSE,flg,fd_coloring = PETSC_FALSE;

 81:   PetscInitialize(&argc,&argv,(char *)0,help);
 82:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
 83:   if (size != 1) SETERRQ(1,"This is a uniprocessor example only!");

 85:   /*
 86:      Initialize problem parameters
 87:   */
 88:   user.mx = 4; user.my = 4; user.param = 6.0;
 89:   PetscOptionsGetInt(PETSC_NULL,"-mx",&user.mx,PETSC_NULL);
 90:   PetscOptionsGetInt(PETSC_NULL,"-my",&user.my,PETSC_NULL);
 91:   PetscOptionsGetReal(PETSC_NULL,"-par",&user.param,PETSC_NULL);
 92:   if (user.param >= bratu_lambda_max || user.param <= bratu_lambda_min) {
 93:     SETERRQ(1,"Lambda is out of range");
 94:   }
 95:   N = user.mx*user.my;
 96: 
 97:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 98:      Create nonlinear solver context
 99:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

101:   SNESCreate(PETSC_COMM_WORLD,&snes);

103:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
104:      Create vector data structures; set function evaluation routine
105:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

107:   VecCreate(PETSC_COMM_WORLD,&x);
108:   VecSetSizes(x,PETSC_DECIDE,N);
109:   VecSetFromOptions(x);
110:   VecDuplicate(x,&r);

112:   /* 
113:      Set function evaluation routine and vector.  Whenever the nonlinear
114:      solver needs to evaluate the nonlinear function, it will call this
115:      routine.
116:       - Note that the final routine argument is the user-defined
117:         context that provides application-specific data for the
118:         function evaluation routine.
119:   */
120:   SNESSetFunction(snes,r,FormFunction,(void*)&user);

122:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
123:      Create matrix data structure; set Jacobian evaluation routine
124:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

126:   /*
127:      Create matrix. Here we only approximately preallocate storage space
128:      for the Jacobian.  See the users manual for a discussion of better 
129:      techniques for preallocating matrix memory.
130:   */
131:   PetscOptionsGetTruth(PETSC_NULL,"-snes_mf",&matrix_free,PETSC_NULL);
132:   if (!matrix_free) {
133:     PetscTruth matrix_free_operator = PETSC_FALSE;
134:     PetscOptionsGetTruth(PETSC_NULL,"-snes_mf_operator",&matrix_free_operator,PETSC_NULL);
135:     if (matrix_free_operator) matrix_free = PETSC_FALSE;
136:   }
137:   if (!matrix_free) {
138:     MatCreateSeqAIJ(PETSC_COMM_WORLD,N,N,5,PETSC_NULL,&J);
139:   }

141:   /*
142:      This option will cause the Jacobian to be computed via finite differences
143:     efficiently using a coloring of the columns of the matrix.
144:   */
145:   PetscOptionsGetTruth(PETSC_NULL,"-snes_fd_coloring",&fd_coloring,PETSC_NULL);

147:   if (matrix_free && fd_coloring)  SETERRQ(1,"Use only one of -snes_mf, -snes_fd_coloring options!\n\
148:                                                 You can do -snes_mf_operator -snes_fd_coloring");

150:   if (fd_coloring) {
151:     ISColoring   iscoloring;
152:     MatStructure str;

154:     /* 
155:       This initializes the nonzero structure of the Jacobian. This is artificial
156:       because clearly if we had a routine to compute the Jacobian we won't need
157:       to use finite differences.
158:     */
159:     FormJacobian(snes,x,&J,&J,&str,&user);

161:     /*
162:        Color the matrix, i.e. determine groups of columns that share no common 
163:       rows. These columns in the Jacobian can all be computed simulataneously.
164:     */
165:     MatGetColoring(J,MATCOLORING_NATURAL,&iscoloring);
166:     /*
167:        Create the data structure that SNESDefaultComputeJacobianColor() uses
168:        to compute the actual Jacobians via finite differences.
169:     */
170:     MatFDColoringCreate(J,iscoloring,&fdcoloring);
171:     MatFDColoringSetFunction(fdcoloring,(PetscErrorCode (*)(void))FormFunction,&user);
172:     MatFDColoringSetFromOptions(fdcoloring);
173:     /*
174:         Tell SNES to use the routine SNESDefaultComputeJacobianColor()
175:       to compute Jacobians.
176:     */
177:     SNESSetJacobian(snes,J,J,SNESDefaultComputeJacobianColor,fdcoloring);
178:     ISColoringDestroy(iscoloring);
179:   }
180:   /* 
181:      Set Jacobian matrix data structure and default Jacobian evaluation
182:      routine.  Whenever the nonlinear solver needs to compute the
183:      Jacobian matrix, it will call this routine.
184:       - Note that the final routine argument is the user-defined
185:         context that provides application-specific data for the
186:         Jacobian evaluation routine.
187:       - The user can override with:
188:          -snes_fd : default finite differencing approximation of Jacobian
189:          -snes_mf : matrix-free Newton-Krylov method with no preconditioning
190:                     (unless user explicitly sets preconditioner) 
191:          -snes_mf_operator : form preconditioning matrix as set by the user,
192:                              but use matrix-free approx for Jacobian-vector
193:                              products within Newton-Krylov method
194:   */
195:   else if (!matrix_free) {
196:     SNESSetJacobian(snes,J,J,FormJacobian,(void*)&user);
197:   }

199:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
200:      Customize nonlinear solver; set runtime options
201:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

203:   /*
204:      Set runtime options (e.g., -snes_monitor -snes_rtol <rtol> -ksp_type <type>)
205:   */
206:   SNESSetFromOptions(snes);

208:   /*
209:      Set array that saves the function norms.  This array is intended
210:      when the user wants to save the convergence history for later use
211:      rather than just to view the function norms via -snes_monitor.
212:   */
213:   SNESSetConvergenceHistory(snes,history,hist_its,50,PETSC_TRUE);

215:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
216:      Evaluate initial guess; then solve nonlinear system
217:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
218:   /*
219:      Note: The user should initialize the vector, x, with the initial guess
220:      for the nonlinear solver prior to calling SNESSolve().  In particular,
221:      to employ an initial guess of zero, the user should explicitly set
222:      this vector to zero by calling VecSet().
223:   */
224:   FormInitialGuess(&user,x);
225:   SNESSolve(snes,PETSC_NULL,x);
226:   SNESGetIterationNumber(snes,&its);
227:   PetscPrintf(PETSC_COMM_WORLD,"Number of Newton iterations = %D\n",its);


230:   /* 
231:      Print the convergence history.  This is intended just to demonstrate
232:      use of the data attained via SNESSetConvergenceHistory().  
233:   */
234:   PetscOptionsHasName(PETSC_NULL,"-print_history",&flg);
235:   if (flg) {
236:     for (i=0; i<its+1; i++) {
237:       PetscPrintf(PETSC_COMM_WORLD,"iteration %D: Linear iterations %D Function norm = %G\n",i,hist_its[i],history[i]);
238:     }
239:   }

241:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
242:      Free work space.  All PETSc objects should be destroyed when they
243:      are no longer needed.
244:    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

246:   if (!matrix_free) {
247:     MatDestroy(J);
248:   }
249:   if (fd_coloring) {
250:     MatFDColoringDestroy(fdcoloring);
251:   }
252:   VecDestroy(x);
253:   VecDestroy(r);
254:   SNESDestroy(snes);
255:   PetscFinalize();

257:   return 0;
258: }
259: /* ------------------------------------------------------------------- */
262: /* 
263:    FormInitialGuess - Forms initial approximation.

265:    Input Parameters:
266:    user - user-defined application context
267:    X - vector

269:    Output Parameter:
270:    X - vector
271:  */
272: PetscErrorCode FormInitialGuess(AppCtx *user,Vec X)
273: {
274:   PetscInt       i,j,row,mx,my;
276:   PetscReal      lambda,temp1,temp,hx,hy;
277:   PetscScalar    *x;

279:   mx         = user->mx;
280:   my         = user->my;
281:   lambda = user->param;

283:   hx    = 1.0 / (PetscReal)(mx-1);
284:   hy    = 1.0 / (PetscReal)(my-1);

286:   /*
287:      Get a pointer to vector data.
288:        - For default PETSc vectors, VecGetArray() returns a pointer to
289:          the data array.  Otherwise, the routine is implementation dependent.
290:        - You MUST call VecRestoreArray() when you no longer need access to
291:          the array.
292:   */
293:   VecGetArray(X,&x);
294:   temp1 = lambda/(lambda + 1.0);
295:   for (j=0; j<my; j++) {
296:     temp = (PetscReal)(PetscMin(j,my-j-1))*hy;
297:     for (i=0; i<mx; i++) {
298:       row = i + j*mx;
299:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
300:         x[row] = 0.0;
301:         continue;
302:       }
303:       x[row] = temp1*sqrt(PetscMin((PetscReal)(PetscMin(i,mx-i-1))*hx,temp));
304:     }
305:   }

307:   /*
308:      Restore vector
309:   */
310:   VecRestoreArray(X,&x);
311:   return 0;
312: }
313: /* ------------------------------------------------------------------- */
316: /* 
317:    FormFunction - Evaluates nonlinear function, F(x).

319:    Input Parameters:
320: .  snes - the SNES context
321: .  X - input vector
322: .  ptr - optional user-defined context, as set by SNESSetFunction()

324:    Output Parameter:
325: .  F - function vector
326:  */
327: PetscErrorCode FormFunction(SNES snes,Vec X,Vec F,void *ptr)
328: {
329:   AppCtx         *user = (AppCtx*)ptr;
330:   PetscInt       i,j,row,mx,my;
332:   PetscReal      two = 2.0,one = 1.0,lambda,hx,hy,hxdhy,hydhx;
333:   PetscScalar    ut,ub,ul,ur,u,uxx,uyy,sc,*x,*f;

335:   mx         = user->mx;
336:   my         = user->my;
337:   lambda = user->param;
338:   hx     = one / (PetscReal)(mx-1);
339:   hy     = one / (PetscReal)(my-1);
340:   sc     = hx*hy;
341:   hxdhy  = hx/hy;
342:   hydhx  = hy/hx;

344:   /*
345:      Get pointers to vector data
346:   */
347:   VecGetArray(X,&x);
348:   VecGetArray(F,&f);

350:   /*
351:      Compute function 
352:   */
353:   for (j=0; j<my; j++) {
354:     for (i=0; i<mx; i++) {
355:       row = i + j*mx;
356:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
357:         f[row] = x[row];
358:         continue;
359:       }
360:       u = x[row];
361:       ub = x[row - mx];
362:       ul = x[row - 1];
363:       ut = x[row + mx];
364:       ur = x[row + 1];
365:       uxx = (-ur + two*u - ul)*hydhx;
366:       uyy = (-ut + two*u - ub)*hxdhy;
367:       f[row] = uxx + uyy - sc*lambda*PetscExpScalar(u);
368:     }
369:   }

371:   /*
372:      Restore vectors
373:   */
374:   VecRestoreArray(X,&x);
375:   VecRestoreArray(F,&f);
376:   return 0;
377: }
378: /* ------------------------------------------------------------------- */
381: /*
382:    FormJacobian - Evaluates Jacobian matrix.

384:    Input Parameters:
385: .  snes - the SNES context
386: .  x - input vector
387: .  ptr - optional user-defined context, as set by SNESSetJacobian()

389:    Output Parameters:
390: .  A - Jacobian matrix
391: .  B - optionally different preconditioning matrix
392: .  flag - flag indicating matrix structure
393: */
394: PetscErrorCode FormJacobian(SNES snes,Vec X,Mat *J,Mat *B,MatStructure *flag,void *ptr)
395: {
396:   AppCtx         *user = (AppCtx*)ptr;   /* user-defined applicatin context */
397:   Mat            jac = *B;                /* Jacobian matrix */
398:   PetscInt       i,j,row,mx,my,col[5];
400:   PetscScalar    two = 2.0,one = 1.0,lambda,v[5],sc,*x;
401:   PetscReal      hx,hy,hxdhy,hydhx;

403:   mx         = user->mx;
404:   my         = user->my;
405:   lambda = user->param;
406:   hx     = 1.0 / (PetscReal)(mx-1);
407:   hy     = 1.0 / (PetscReal)(my-1);
408:   sc     = hx*hy;
409:   hxdhy  = hx/hy;
410:   hydhx  = hy/hx;

412:   /*
413:      Get pointer to vector data
414:   */
415:   VecGetArray(X,&x);

417:   /* 
418:      Compute entries of the Jacobian
419:   */
420:   for (j=0; j<my; j++) {
421:     for (i=0; i<mx; i++) {
422:       row = i + j*mx;
423:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
424:         MatSetValues(jac,1,&row,1,&row,&one,INSERT_VALUES);
425:         continue;
426:       }
427:       v[0] = -hxdhy; col[0] = row - mx;
428:       v[1] = -hydhx; col[1] = row - 1;
429:       v[2] = two*(hydhx + hxdhy) - sc*lambda*PetscExpScalar(x[row]); col[2] = row;
430:       v[3] = -hydhx; col[3] = row + 1;
431:       v[4] = -hxdhy; col[4] = row + mx;
432:       MatSetValues(jac,1,&row,5,col,v,INSERT_VALUES);
433:     }
434:   }

436:   /*
437:      Restore vector
438:   */
439:   VecRestoreArray(X,&x);

441:   /* 
442:      Assemble matrix
443:   */
444:   MatAssemblyBegin(jac,MAT_FINAL_ASSEMBLY);
445:   MatAssemblyEnd(jac,MAT_FINAL_ASSEMBLY);

447:   if (jac != *J) {
448:     MatAssemblyBegin(*J,MAT_FINAL_ASSEMBLY);
449:     MatAssemblyEnd(*J,MAT_FINAL_ASSEMBLY);
450:   }

452:   /*
453:      Set flag to indicate that the Jacobian matrix retains an identical
454:      nonzero structure throughout all nonlinear iterations (although the
455:      values of the entries change). Thus, we can save some work in setting
456:      up the preconditioner (e.g., no need to redo symbolic factorization for
457:      ILU/ICC preconditioners).
458:       - If the nonzero structure of the matrix is different during
459:         successive linear solves, then the flag DIFFERENT_NONZERO_PATTERN
460:         must be used instead.  If you are unsure whether the matrix
461:         structure has changed or not, use the flag DIFFERENT_NONZERO_PATTERN.
462:       - Caution:  If you specify SAME_NONZERO_PATTERN, PETSc
463:         believes your assertion and does not check the structure
464:         of the matrix.  If you erroneously claim that the structure
465:         is the same when it actually is not, the new preconditioner
466:         will not function correctly.  Thus, use this optimization
467:         feature with caution!
468:   */
469:   *flag = SAME_NONZERO_PATTERN;
470:   return 0;
471: }