Actual source code: ex21.c

petsc-master 2017-07-18
Report Typos and Errors

  2: static char help[] ="Solves a time-dependent nonlinear PDE with lower and upper bounds on the interior grid points. Uses implicit\n\
  3: timestepping.  Runtime options include:\n\
  4:   -M <xg>, where <xg> = number of grid points\n\
  5:   -debug : Activate debugging printouts\n\
  6:   -nox   : Deactivate x-window graphics\n\
  7:   -ul   : lower bound\n\
  8:   -uh  : upper bound\n\n";

 10: /*
 11:    Concepts: TS^time-dependent nonlinear problems
 12:    Concepts: TS^Variational inequality nonlinear solver
 13:    Processors: n
 14: */

 16: /* ------------------------------------------------------------------------

 18:    This is a variation of ex2.c to solve the PDE

 20:                u * u_xx
 21:          u_t = ---------
 22:                2*(t+1)^2

 24:     with box constraints on the interior grid points
 25:     ul <= u(t,x) <= uh with x != 0,1
 26:     on the domain 0 <= x <= 1, with boundary conditions
 27:          u(t,0) = t + 1,  u(t,1) = 2*t + 2,
 28:     and initial condition
 29:          u(0,x) = 1 + x*x.

 31:     The exact solution is:
 32:          u(t,x) = (1 + x*x) * (1 + t)

 34:     We use by default the backward Euler method.

 36:   ------------------------------------------------------------------------- */

 38: /*
 39:    Include "petscts.h" to use the PETSc timestepping routines. Note that
 40:    this file automatically includes "petscsys.h" and other lower-level
 41:    PETSc include files.

 43:    Include the "petscdmda.h" to allow us to use the distributed array data
 44:    structures to manage the parallel grid.
 45: */
 46:  #include <petscts.h>
 47:  #include <petscdm.h>
 48:  #include <petscdmda.h>
 49:  #include <petscdraw.h>

 51: /*
 52:    User-defined application context - contains data needed by the
 53:    application-provided callback routines.
 54: */
 55: typedef struct {
 56:   MPI_Comm  comm;           /* communicator */
 57:   DM        da;             /* distributed array data structure */
 58:   Vec       localwork;      /* local ghosted work vector */
 59:   Vec       u_local;        /* local ghosted approximate solution vector */
 60:   Vec       solution;       /* global exact solution vector */
 61:   PetscInt  m;              /* total number of grid points */
 62:   PetscReal h;              /* mesh width: h = 1/(m-1) */
 63:   PetscBool debug;          /* flag (1 indicates activation of debugging printouts) */
 64: } AppCtx;

 66: /*
 67:    User-defined routines, provided below.
 68: */
 69: extern PetscErrorCode InitialConditions(Vec,AppCtx*);
 70: extern PetscErrorCode RHSFunction(TS,PetscReal,Vec,Vec,void*);
 71: extern PetscErrorCode RHSJacobian(TS,PetscReal,Vec,Mat,Mat,void*);
 72: extern PetscErrorCode Monitor(TS,PetscInt,PetscReal,Vec,void*);
 73: extern PetscErrorCode ExactSolution(PetscReal,Vec,AppCtx*);
 74: extern PetscErrorCode SetBounds(Vec,Vec,PetscScalar,PetscScalar,AppCtx*);

 76: int main(int argc,char **argv)
 77: {
 78:   AppCtx         appctx;                 /* user-defined application context */
 79:   TS             ts;                     /* timestepping context */
 80:   Mat            A;                      /* Jacobian matrix data structure */
 81:   Vec            u;                      /* approximate solution vector */
 82:   Vec            r;                      /* residual vector */
 83:   PetscInt       time_steps_max = 1000;  /* default max timesteps */
 85:   PetscReal      dt;
 86:   PetscReal      time_total_max = 100.0; /* default max total time */
 87:   Vec            xl,xu; /* Lower and upper bounds on variables */
 88:   PetscScalar    ul=0.0,uh = 3.0;
 89:   PetscBool      mymonitor;
 90:   PetscReal      bounds[] = {1.0, 3.3};

 92:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 93:      Initialize program and set problem parameters
 94:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 96:   PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;
 97:   PetscViewerDrawSetBounds(PETSC_VIEWER_DRAW_(PETSC_COMM_WORLD),1,bounds);

 99:   appctx.comm = PETSC_COMM_WORLD;
100:   appctx.m    = 60;
101:   PetscOptionsGetInt(NULL,NULL,"-M",&appctx.m,NULL);
102:   PetscOptionsGetScalar(NULL,NULL,"-ul",&ul,NULL);
103:   PetscOptionsGetScalar(NULL,NULL,"-uh",&uh,NULL);
104:   PetscOptionsHasName(NULL,NULL,"-debug",&appctx.debug);
105:   PetscOptionsHasName(NULL,NULL,"-mymonitor",&mymonitor);
106:   appctx.h    = 1.0/(appctx.m-1.0);

108:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
109:      Create vector data structures
110:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

112:   /*
113:      Create distributed array (DMDA) to manage parallel grid and vectors
114:      and to set up the ghost point communication pattern.  There are M
115:      total grid values spread equally among all the processors.
116:   */
117:   DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,appctx.m,1,1,NULL,&appctx.da);
118:   DMSetFromOptions(appctx.da);
119:   DMSetUp(appctx.da);

121:   /*
122:      Extract global and local vectors from DMDA; we use these to store the
123:      approximate solution.  Then duplicate these for remaining vectors that
124:      have the same types.
125:   */
126:   DMCreateGlobalVector(appctx.da,&u);
127:   DMCreateLocalVector(appctx.da,&appctx.u_local);

129:   /*
130:      Create local work vector for use in evaluating right-hand-side function;
131:      create global work vector for storing exact solution.
132:   */
133:   VecDuplicate(appctx.u_local,&appctx.localwork);
134:   VecDuplicate(u,&appctx.solution);

136:   /* Create residual vector */
137:   VecDuplicate(u,&r);
138:   /* Create lower and upper bound vectors */
139:   VecDuplicate(u,&xl);
140:   VecDuplicate(u,&xu);
141:   SetBounds(xl,xu,ul,uh,&appctx);

143:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
144:      Create timestepping solver context; set callback routine for
145:      right-hand-side function evaluation.
146:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

148:   TSCreate(PETSC_COMM_WORLD,&ts);
149:   TSSetProblemType(ts,TS_NONLINEAR);
150:   TSSetRHSFunction(ts,r,RHSFunction,&appctx);

152:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
153:      Set optional user-defined monitoring routine
154:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

156:   if (mymonitor) {
157:     TSMonitorSet(ts,Monitor,&appctx,NULL);
158:   }

160:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
161:      For nonlinear problems, the user can provide a Jacobian evaluation
162:      routine (or use a finite differencing approximation).

164:      Create matrix data structure; set Jacobian evaluation routine.
165:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

167:   MatCreate(PETSC_COMM_WORLD,&A);
168:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,appctx.m,appctx.m);
169:   MatSetFromOptions(A);
170:   MatSetUp(A);
171:   TSSetRHSJacobian(ts,A,A,RHSJacobian,&appctx);

173:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
174:      Set solution vector and initial timestep
175:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

177:   dt   = appctx.h/2.0;
178:   TSSetInitialTimeStep(ts,0.0,dt);

180:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
181:      Customize timestepping solver:
182:        - Set the solution method to be the Backward Euler method.
183:        - Set timestepping duration info
184:      Then set runtime options, which can override these defaults.
185:      For example,
186:           -ts_max_steps <maxsteps> -ts_final_time <maxtime>
187:      to override the defaults set by TSSetDuration().
188:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

190:   TSSetType(ts,TSBEULER);
191:   TSSetDuration(ts,time_steps_max,time_total_max);
192:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);
193:   /* Set lower and upper bound on the solution vector for each time step */
194:   TSVISetVariableBounds(ts,xl,xu);
195:   TSSetFromOptions(ts);

197:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
198:      Solve the problem
199:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

201:   /*
202:      Evaluate initial conditions
203:   */
204:   InitialConditions(u,&appctx);

206:   /*
207:      Run the timestepping solver
208:   */
209:   TSSolve(ts,u);

211:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
212:      Free work space.  All PETSc objects should be destroyed when they
213:      are no longer needed.
214:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

216:   VecDestroy(&r);
217:   VecDestroy(&xl);
218:   VecDestroy(&xu);
219:   TSDestroy(&ts);
220:   VecDestroy(&u);
221:   MatDestroy(&A);
222:   DMDestroy(&appctx.da);
223:   VecDestroy(&appctx.localwork);
224:   VecDestroy(&appctx.solution);
225:   VecDestroy(&appctx.u_local);

227:   /*
228:      Always call PetscFinalize() before exiting a program.  This routine
229:        - finalizes the PETSc libraries as well as MPI
230:        - provides summary and diagnostic information if certain runtime
231:          options are chosen (e.g., -log_view).
232:   */
233:   PetscFinalize();
234:   return ierr;
235: }
236: /* --------------------------------------------------------------------- */
237: /*
238:    InitialConditions - Computes the solution at the initial time.

240:    Input Parameters:
241:    u - uninitialized solution vector (global)
242:    appctx - user-defined application context

244:    Output Parameter:
245:    u - vector with solution at initial time (global)
246: */
247: PetscErrorCode InitialConditions(Vec u,AppCtx *appctx)
248: {
249:   PetscScalar    *u_localptr,h = appctx->h,x;
250:   PetscInt       i,mybase,myend;

253:   /*
254:      Determine starting point of each processor's range of
255:      grid values.
256:   */
257:   VecGetOwnershipRange(u,&mybase,&myend);

259:   /*
260:     Get a pointer to vector data.
261:     - For default PETSc vectors, VecGetArray() returns a pointer to
262:       the data array.  Otherwise, the routine is implementation dependent.
263:     - You MUST call VecRestoreArray() when you no longer need access to
264:       the array.
265:     - Note that the Fortran interface to VecGetArray() differs from the
266:       C version.  See the users manual for details.
267:   */
268:   VecGetArray(u,&u_localptr);

270:   /*
271:      We initialize the solution array by simply writing the solution
272:      directly into the array locations.  Alternatively, we could use
273:      VecSetValues() or VecSetValuesLocal().
274:   */
275:   for (i=mybase; i<myend; i++) {
276:     x = h*(PetscReal)i; /* current location in global grid */
277:     u_localptr[i-mybase] = 1.0 + x*x;
278:   }

280:   /*
281:      Restore vector
282:   */
283:   VecRestoreArray(u,&u_localptr);

285:   /*
286:      Print debugging information if desired
287:   */
288:   if (appctx->debug) {
289:      PetscPrintf(appctx->comm,"initial guess vector\n");
290:      VecView(u,PETSC_VIEWER_STDOUT_WORLD);
291:   }

293:   return 0;
294: }

296: /* --------------------------------------------------------------------- */
297: /*
298:   SetBounds - Sets the lower and uper bounds on the interior points

300:   Input parameters:
301:   xl - vector of lower bounds
302:   xu - vector of upper bounds
303:   ul - constant lower bound for all variables
304:   uh - constant upper bound for all variables
305:   appctx - Application context
306:  */
307: PetscErrorCode SetBounds(Vec xl, Vec xu, PetscScalar ul, PetscScalar uh,AppCtx *appctx)
308: {
309:   PetscErrorCode    ierr;
310:   const PetscScalar *l,*u;
311:   PetscMPIInt       rank,size;
312:   PetscInt          localsize;

315:   VecSet(xl,ul);
316:   VecSet(xu,uh);
317:   VecGetLocalSize(xl,&localsize);
318:   VecGetArrayRead(xl,&l);
319:   VecGetArrayRead(xu,&u);

321:   MPI_Comm_rank(appctx->comm,&rank);
322:   MPI_Comm_size(appctx->comm,&size);
323:   if (!rank) {
324:     l[0] = -PETSC_INFINITY;
325:     u[0] =  PETSC_INFINITY;
326:   }
327:   if (rank == size-1) {
328:     l[localsize-1] = -PETSC_INFINITY;
329:     u[localsize-1] = PETSC_INFINITY;
330:   }
331:   VecRestoreArrayRead(xl,&l);
332:   VecRestoreArrayRead(xu,&u);
333:   return(0);
334: }

336: /* --------------------------------------------------------------------- */
337: /*
338:    ExactSolution - Computes the exact solution at a given time.

340:    Input Parameters:
341:    t - current time
342:    solution - vector in which exact solution will be computed
343:    appctx - user-defined application context

345:    Output Parameter:
346:    solution - vector with the newly computed exact solution
347: */
348: PetscErrorCode ExactSolution(PetscReal t,Vec solution,AppCtx *appctx)
349: {
350:   PetscScalar    *s_localptr,h = appctx->h,x;
351:   PetscInt       i,mybase,myend;

354:   /*
355:      Determine starting and ending points of each processor's
356:      range of grid values
357:   */
358:   VecGetOwnershipRange(solution,&mybase,&myend);

360:   /*
361:      Get a pointer to vector data.
362:   */
363:   VecGetArray(solution,&s_localptr);

365:   /*
366:      Simply write the solution directly into the array locations.
367:      Alternatively, we could use VecSetValues() or VecSetValuesLocal().
368:   */
369:   for (i=mybase; i<myend; i++) {
370:     x = h*(PetscReal)i;
371:     s_localptr[i-mybase] = (t + 1.0)*(1.0 + x*x);
372:   }

374:   /*
375:      Restore vector
376:   */
377:   VecRestoreArray(solution,&s_localptr);
378:   return 0;
379: }
380: /* --------------------------------------------------------------------- */
381: /*
382:    Monitor - User-provided routine to monitor the solution computed at
383:    each timestep.  This example plots the solution and computes the
384:    error in two different norms.

386:    Input Parameters:
387:    ts     - the timestep context
388:    step   - the count of the current step (with 0 meaning the
389:             initial condition)
390:    time   - the current time
391:    u      - the solution at this timestep
392:    ctx    - the user-provided context for this monitoring routine.
393:             In this case we use the application context which contains
394:             information about the problem size, workspace and the exact
395:             solution.
396: */
397: PetscErrorCode Monitor(TS ts,PetscInt step,PetscReal time,Vec u,void *ctx)
398: {
399:   AppCtx         *appctx = (AppCtx*) ctx;   /* user-defined application context */
401:   PetscReal      en2,en2s,enmax;
402:   PetscDraw      draw;

404:   /*
405:      We use the default X windows viewer
406:              PETSC_VIEWER_DRAW_(appctx->comm)
407:      that is associated with the current communicator. This saves
408:      the effort of calling PetscViewerDrawOpen() to create the window.
409:      Note that if we wished to plot several items in separate windows we
410:      would create each viewer with PetscViewerDrawOpen() and store them in
411:      the application context, appctx.

413:      PetscReal buffering makes graphics look better.
414:   */
415:   PetscViewerDrawGetDraw(PETSC_VIEWER_DRAW_(appctx->comm),0,&draw);
416:   PetscDrawSetDoubleBuffer(draw);
417:   VecView(u,PETSC_VIEWER_DRAW_(appctx->comm));

419:   /*
420:      Compute the exact solution at this timestep
421:   */
422:   ExactSolution(time,appctx->solution,appctx);

424:   /*
425:      Print debugging information if desired
426:   */
427:   if (appctx->debug) {
428:     PetscPrintf(appctx->comm,"Computed solution vector\n");
429:     VecView(u,PETSC_VIEWER_STDOUT_WORLD);
430:     PetscPrintf(appctx->comm,"Exact solution vector\n");
431:     VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
432:   }

434:   /*
435:      Compute the 2-norm and max-norm of the error
436:   */
437:   VecAXPY(appctx->solution,-1.0,u);
438:   VecNorm(appctx->solution,NORM_2,&en2);
439:   en2s = PetscSqrtReal(appctx->h)*en2;  /* scale the 2-norm by the grid spacing */
440:   VecNorm(appctx->solution,NORM_MAX,&enmax);

442:   /*
443:      PetscPrintf() causes only the first processor in this
444:      communicator to print the timestep information.
445:   */
446:   PetscPrintf(appctx->comm,"Timestep %D: time = %g,2-norm error = %g, max norm error = %g\n",step,(double)time,(double)en2s,(double)enmax);

448:   /*
449:      Print debugging information if desired
450:    */
451:   /*  if (appctx->debug) {
452:      PetscPrintf(appctx->comm,"Error vector\n");
453:      VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
454:    } */
455:   return 0;
456: }
457: /* --------------------------------------------------------------------- */
458: /*
459:    RHSFunction - User-provided routine that evalues the right-hand-side
460:    function of the ODE.  This routine is set in the main program by
461:    calling TSSetRHSFunction().  We compute:
462:           global_out = F(global_in)

464:    Input Parameters:
465:    ts         - timesteping context
466:    t          - current time
467:    global_in  - vector containing the current iterate
468:    ctx        - (optional) user-provided context for function evaluation.
469:                 In this case we use the appctx defined above.

471:    Output Parameter:
472:    global_out - vector containing the newly evaluated function
473: */
474: PetscErrorCode RHSFunction(TS ts,PetscReal t,Vec global_in,Vec global_out,void *ctx)
475: {
476:   AppCtx            *appctx   = (AppCtx*) ctx;     /* user-defined application context */
477:   DM                da        = appctx->da;        /* distributed array */
478:   Vec               local_in  = appctx->u_local;   /* local ghosted input vector */
479:   Vec               localwork = appctx->localwork; /* local ghosted work vector */
480:   PetscErrorCode    ierr;
481:   PetscInt          i,localsize;
482:   PetscMPIInt       rank,size;
483:   PetscScalar       *copyptr,sc;
484:   const PetscScalar *localptr;

486:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
487:      Get ready for local function computations
488:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
489:   /*
490:      Scatter ghost points to local vector, using the 2-step process
491:         DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
492:      By placing code between these two statements, computations can be
493:      done while messages are in transition.
494:   */
495:   DMGlobalToLocalBegin(da,global_in,INSERT_VALUES,local_in);
496:   DMGlobalToLocalEnd(da,global_in,INSERT_VALUES,local_in);

498:   /*
499:       Access directly the values in our local INPUT work array
500:   */
501:   VecGetArrayRead(local_in,&localptr);

503:   /*
504:       Access directly the values in our local OUTPUT work array
505:   */
506:   VecGetArray(localwork,&copyptr);

508:   sc = 1.0/(appctx->h*appctx->h*2.0*(1.0+t)*(1.0+t));

510:   /*
511:       Evaluate our function on the nodes owned by this processor
512:   */
513:   VecGetLocalSize(local_in,&localsize);

515:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
516:      Compute entries for the locally owned part
517:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

519:   /*
520:      Handle boundary conditions: This is done by using the boundary condition
521:         u(t,boundary) = g(t,boundary)
522:      for some function g. Now take the derivative with respect to t to obtain
523:         u_{t}(t,boundary) = g_{t}(t,boundary)

525:      In our case, u(t,0) = t + 1, so that u_{t}(t,0) = 1
526:              and  u(t,1) = 2t+ 2, so that u_{t}(t,1) = 2
527:   */
528:   MPI_Comm_rank(appctx->comm,&rank);
529:   MPI_Comm_size(appctx->comm,&size);
530:   if (!rank) copyptr[0] = 1.0;
531:   if (rank == size-1) copyptr[localsize-1] = (t < .5) ? 2.0 : 0.0;

533:   /*
534:      Handle the interior nodes where the PDE is replace by finite
535:      difference operators.
536:   */
537:   for (i=1; i<localsize-1; i++) copyptr[i] =  localptr[i] * sc * (localptr[i+1] + localptr[i-1] - 2.0*localptr[i]);

539:   /*
540:      Restore vectors
541:   */
542:   VecRestoreArrayRead(local_in,&localptr);
543:   VecRestoreArray(localwork,&copyptr);

545:   /*
546:      Insert values from the local OUTPUT vector into the global
547:      output vector
548:   */
549:   DMLocalToGlobalBegin(da,localwork,INSERT_VALUES,global_out);
550:   DMLocalToGlobalEnd(da,localwork,INSERT_VALUES,global_out);

552:   /* Print debugging information if desired */
553:   /*  if (appctx->debug) {
554:      PetscPrintf(appctx->comm,"RHS function vector\n");
555:      VecView(global_out,PETSC_VIEWER_STDOUT_WORLD);
556:    } */

558:   return 0;
559: }
560: /* --------------------------------------------------------------------- */
561: /*
562:    RHSJacobian - User-provided routine to compute the Jacobian of
563:    the nonlinear right-hand-side function of the ODE.

565:    Input Parameters:
566:    ts - the TS context
567:    t - current time
568:    global_in - global input vector
569:    dummy - optional user-defined context, as set by TSetRHSJacobian()

571:    Output Parameters:
572:    AA - Jacobian matrix
573:    BB - optionally different preconditioning matrix
574:    str - flag indicating matrix structure

576:   Notes:
577:   RHSJacobian computes entries for the locally owned part of the Jacobian.
578:    - Currently, all PETSc parallel matrix formats are partitioned by
579:      contiguous chunks of rows across the processors.
580:    - Each processor needs to insert only elements that it owns
581:      locally (but any non-local elements will be sent to the
582:      appropriate processor during matrix assembly).
583:    - Always specify global row and columns of matrix entries when
584:      using MatSetValues().
585:    - Here, we set all entries for a particular row at once.
586:    - Note that MatSetValues() uses 0-based row and column numbers
587:      in Fortran as well as in C.
588: */
589: PetscErrorCode RHSJacobian(TS ts,PetscReal t,Vec global_in,Mat AA,Mat B,void *ctx)
590: {
591:   AppCtx            *appctx  = (AppCtx*)ctx;    /* user-defined application context */
592:   Vec               local_in = appctx->u_local;   /* local ghosted input vector */
593:   DM                da       = appctx->da;        /* distributed array */
594:   PetscScalar       v[3],sc;
595:   const PetscScalar *localptr;
596:   PetscErrorCode    ierr;
597:   PetscInt          i,mstart,mend,mstarts,mends,idx[3],is;

599:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
600:      Get ready for local Jacobian computations
601:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
602:   /*
603:      Scatter ghost points to local vector, using the 2-step process
604:         DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
605:      By placing code between these two statements, computations can be
606:      done while messages are in transition.
607:   */
608:   DMGlobalToLocalBegin(da,global_in,INSERT_VALUES,local_in);
609:   DMGlobalToLocalEnd(da,global_in,INSERT_VALUES,local_in);

611:   /*
612:      Get pointer to vector data
613:   */
614:   VecGetArrayRead(local_in,&localptr);

616:   /*
617:      Get starting and ending locally owned rows of the matrix
618:   */
619:   MatGetOwnershipRange(B,&mstarts,&mends);
620:   mstart = mstarts; mend = mends;

622:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
623:      Compute entries for the locally owned part of the Jacobian.
624:       - Currently, all PETSc parallel matrix formats are partitioned by
625:         contiguous chunks of rows across the processors.
626:       - Each processor needs to insert only elements that it owns
627:         locally (but any non-local elements will be sent to the
628:         appropriate processor during matrix assembly).
629:       - Here, we set all entries for a particular row at once.
630:       - We can set matrix entries either using either
631:         MatSetValuesLocal() or MatSetValues().
632:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

634:   /*
635:      Set matrix rows corresponding to boundary data
636:   */
637:   if (mstart == 0) {
638:     v[0] = 0.0;
639:     MatSetValues(B,1,&mstart,1,&mstart,v,INSERT_VALUES);
640:     mstart++;
641:   }
642:   if (mend == appctx->m) {
643:     mend--;
644:     v[0] = 0.0;
645:     MatSetValues(B,1,&mend,1,&mend,v,INSERT_VALUES);
646:   }

648:   /*
649:      Set matrix rows corresponding to interior data.  We construct the
650:      matrix one row at a time.
651:   */
652:   sc = 1.0/(appctx->h*appctx->h*2.0*(1.0+t)*(1.0+t));
653:   for (i=mstart; i<mend; i++) {
654:     idx[0] = i-1; idx[1] = i; idx[2] = i+1;
655:     is     = i - mstart + 1;
656:     v[0]   = sc*localptr[is];
657:     v[1]   = sc*(localptr[is+1] + localptr[is-1] - 4.0*localptr[is]);
658:     v[2]   = sc*localptr[is];
659:     MatSetValues(B,1,&i,3,idx,v,INSERT_VALUES);
660:   }

662:   /*
663:      Restore vector
664:   */
665:   VecRestoreArrayRead(local_in,&localptr);

667:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
668:      Complete the matrix assembly process and set some options
669:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
670:   /*
671:      Assemble matrix, using the 2-step process:
672:        MatAssemblyBegin(), MatAssemblyEnd()
673:      Computations can be done while messages are in transition
674:      by placing code between these two statements.
675:   */
676:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
677:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

679:   /*
680:      Set and option to indicate that we will never add a new nonzero location
681:      to the matrix. If we do, it will generate an error.
682:   */
683:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

685:   return 0;
686: }