Actual source code: ex21.c

petsc-3.7.3 2016-08-01
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*);

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

 94:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 95:      Initialize program and set problem parameters
 96:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 98:   PetscInitialize(&argc,&argv,(char*)0,help);
 99:   PetscViewerDrawSetBounds(PETSC_VIEWER_DRAW_(PETSC_COMM_WORLD),1,bounds);

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

110:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
111:      Create vector data structures
112:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

243:    Input Parameters:
244:    u - uninitialized solution vector (global)
245:    appctx - user-defined application context

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

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

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

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

283:   /*
284:      Restore vector
285:   */
286:   VecRestoreArray(u,&u_localptr);

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

296:   return 0;
297: }

299: /* --------------------------------------------------------------------- */
302: /*
303:   SetBounds - Sets the lower and uper bounds on the interior points

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

320:   VecSet(xl,ul);
321:   VecSet(xu,uh);
322:   VecGetLocalSize(xl,&localsize);
323:   VecGetArrayRead(xl,&l);
324:   VecGetArrayRead(xu,&u);

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

341: /* --------------------------------------------------------------------- */
344: /*
345:    ExactSolution - Computes the exact solution at a given time.

347:    Input Parameters:
348:    t - current time
349:    solution - vector in which exact solution will be computed
350:    appctx - user-defined application context

352:    Output Parameter:
353:    solution - vector with the newly computed exact solution
354: */
355: PetscErrorCode ExactSolution(PetscReal t,Vec solution,AppCtx *appctx)
356: {
357:   PetscScalar    *s_localptr,h = appctx->h,x;
358:   PetscInt       i,mybase,myend;

361:   /*
362:      Determine starting and ending points of each processor's
363:      range of grid values
364:   */
365:   VecGetOwnershipRange(solution,&mybase,&myend);

367:   /*
368:      Get a pointer to vector data.
369:   */
370:   VecGetArray(solution,&s_localptr);

372:   /*
373:      Simply write the solution directly into the array locations.
374:      Alternatively, we could use VecSetValues() or VecSetValuesLocal().
375:   */
376:   for (i=mybase; i<myend; i++) {
377:     x = h*(PetscReal)i;
378:     s_localptr[i-mybase] = (t + 1.0)*(1.0 + x*x);
379:   }

381:   /*
382:      Restore vector
383:   */
384:   VecRestoreArray(solution,&s_localptr);
385:   return 0;
386: }
387: /* --------------------------------------------------------------------- */
390: /*
391:    Monitor - User-provided routine to monitor the solution computed at
392:    each timestep.  This example plots the solution and computes the
393:    error in two different norms.

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

413:   /*
414:      We use the default X windows viewer
415:              PETSC_VIEWER_DRAW_(appctx->comm)
416:      that is associated with the current communicator. This saves
417:      the effort of calling PetscViewerDrawOpen() to create the window.
418:      Note that if we wished to plot several items in separate windows we
419:      would create each viewer with PetscViewerDrawOpen() and store them in
420:      the application context, appctx.

422:      PetscReal buffering makes graphics look better.
423:   */
424:   PetscViewerDrawGetDraw(PETSC_VIEWER_DRAW_(appctx->comm),0,&draw);
425:   PetscDrawSetDoubleBuffer(draw);
426:   VecView(u,PETSC_VIEWER_DRAW_(appctx->comm));

428:   /*
429:      Compute the exact solution at this timestep
430:   */
431:   ExactSolution(time,appctx->solution,appctx);

433:   /*
434:      Print debugging information if desired
435:   */
436:   if (appctx->debug) {
437:     PetscPrintf(appctx->comm,"Computed solution vector\n");
438:     VecView(u,PETSC_VIEWER_STDOUT_WORLD);
439:     PetscPrintf(appctx->comm,"Exact solution vector\n");
440:     VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
441:   }

443:   /*
444:      Compute the 2-norm and max-norm of the error
445:   */
446:   VecAXPY(appctx->solution,-1.0,u);
447:   VecNorm(appctx->solution,NORM_2,&en2);
448:   en2s = PetscSqrtReal(appctx->h)*en2;  /* scale the 2-norm by the grid spacing */
449:   VecNorm(appctx->solution,NORM_MAX,&enmax);

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

457:   /*
458:      Print debugging information if desired
459:    */
460:   /*  if (appctx->debug) {
461:      PetscPrintf(appctx->comm,"Error vector\n");
462:      VecView(appctx->solution,PETSC_VIEWER_STDOUT_WORLD);
463:    } */
464:   return 0;
465: }
466: /* --------------------------------------------------------------------- */
469: /*
470:    RHSFunction - User-provided routine that evalues the right-hand-side
471:    function of the ODE.  This routine is set in the main program by
472:    calling TSSetRHSFunction().  We compute:
473:           global_out = F(global_in)

475:    Input Parameters:
476:    ts         - timesteping context
477:    t          - current time
478:    global_in  - vector containing the current iterate
479:    ctx        - (optional) user-provided context for function evaluation.
480:                 In this case we use the appctx defined above.

482:    Output Parameter:
483:    global_out - vector containing the newly evaluated function
484: */
485: PetscErrorCode RHSFunction(TS ts,PetscReal t,Vec global_in,Vec global_out,void *ctx)
486: {
487:   AppCtx            *appctx   = (AppCtx*) ctx;     /* user-defined application context */
488:   DM                da        = appctx->da;        /* distributed array */
489:   Vec               local_in  = appctx->u_local;   /* local ghosted input vector */
490:   Vec               localwork = appctx->localwork; /* local ghosted work vector */
491:   PetscErrorCode    ierr;
492:   PetscInt          i,localsize;
493:   PetscMPIInt       rank,size;
494:   PetscScalar       *copyptr,sc;
495:   const PetscScalar *localptr;

497:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
498:      Get ready for local function computations
499:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
500:   /*
501:      Scatter ghost points to local vector, using the 2-step process
502:         DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
503:      By placing code between these two statements, computations can be
504:      done while messages are in transition.
505:   */
506:   DMGlobalToLocalBegin(da,global_in,INSERT_VALUES,local_in);
507:   DMGlobalToLocalEnd(da,global_in,INSERT_VALUES,local_in);

509:   /*
510:       Access directly the values in our local INPUT work array
511:   */
512:   VecGetArrayRead(local_in,&localptr);

514:   /*
515:       Access directly the values in our local OUTPUT work array
516:   */
517:   VecGetArray(localwork,&copyptr);

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

521:   /*
522:       Evaluate our function on the nodes owned by this processor
523:   */
524:   VecGetLocalSize(local_in,&localsize);

526:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
527:      Compute entries for the locally owned part
528:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

530:   /*
531:      Handle boundary conditions: This is done by using the boundary condition
532:         u(t,boundary) = g(t,boundary)
533:      for some function g. Now take the derivative with respect to t to obtain
534:         u_{t}(t,boundary) = g_{t}(t,boundary)

536:      In our case, u(t,0) = t + 1, so that u_{t}(t,0) = 1
537:              and  u(t,1) = 2t+ 2, so that u_{t}(t,1) = 2
538:   */
539:   MPI_Comm_rank(appctx->comm,&rank);
540:   MPI_Comm_size(appctx->comm,&size);
541:   if (!rank) copyptr[0] = 1.0;
542:   if (rank == size-1) copyptr[localsize-1] = (t < .5) ? 2.0 : 0.0;

544:   /*
545:      Handle the interior nodes where the PDE is replace by finite
546:      difference operators.
547:   */
548:   for (i=1; i<localsize-1; i++) copyptr[i] =  localptr[i] * sc * (localptr[i+1] + localptr[i-1] - 2.0*localptr[i]);

550:   /*
551:      Restore vectors
552:   */
553:   VecRestoreArrayRead(local_in,&localptr);
554:   VecRestoreArray(localwork,&copyptr);

556:   /*
557:      Insert values from the local OUTPUT vector into the global
558:      output vector
559:   */
560:   DMLocalToGlobalBegin(da,localwork,INSERT_VALUES,global_out);
561:   DMLocalToGlobalEnd(da,localwork,INSERT_VALUES,global_out);

563:   /* Print debugging information if desired */
564:   /*  if (appctx->debug) {
565:      PetscPrintf(appctx->comm,"RHS function vector\n");
566:      VecView(global_out,PETSC_VIEWER_STDOUT_WORLD);
567:    } */

569:   return 0;
570: }
571: /* --------------------------------------------------------------------- */
574: /*
575:    RHSJacobian - User-provided routine to compute the Jacobian of
576:    the nonlinear right-hand-side function of the ODE.

578:    Input Parameters:
579:    ts - the TS context
580:    t - current time
581:    global_in - global input vector
582:    dummy - optional user-defined context, as set by TSetRHSJacobian()

584:    Output Parameters:
585:    AA - Jacobian matrix
586:    BB - optionally different preconditioning matrix
587:    str - flag indicating matrix structure

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

612:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
613:      Get ready for local Jacobian computations
614:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
615:   /*
616:      Scatter ghost points to local vector, using the 2-step process
617:         DMGlobalToLocalBegin(), DMGlobalToLocalEnd().
618:      By placing code between these two statements, computations can be
619:      done while messages are in transition.
620:   */
621:   DMGlobalToLocalBegin(da,global_in,INSERT_VALUES,local_in);
622:   DMGlobalToLocalEnd(da,global_in,INSERT_VALUES,local_in);

624:   /*
625:      Get pointer to vector data
626:   */
627:   VecGetArrayRead(local_in,&localptr);

629:   /*
630:      Get starting and ending locally owned rows of the matrix
631:   */
632:   MatGetOwnershipRange(B,&mstarts,&mends);
633:   mstart = mstarts; mend = mends;

635:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
636:      Compute entries for the locally owned part of the Jacobian.
637:       - Currently, all PETSc parallel matrix formats are partitioned by
638:         contiguous chunks of rows across the processors.
639:       - Each processor needs to insert only elements that it owns
640:         locally (but any non-local elements will be sent to the
641:         appropriate processor during matrix assembly).
642:       - Here, we set all entries for a particular row at once.
643:       - We can set matrix entries either using either
644:         MatSetValuesLocal() or MatSetValues().
645:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

647:   /*
648:      Set matrix rows corresponding to boundary data
649:   */
650:   if (mstart == 0) {
651:     v[0] = 0.0;
652:     MatSetValues(B,1,&mstart,1,&mstart,v,INSERT_VALUES);
653:     mstart++;
654:   }
655:   if (mend == appctx->m) {
656:     mend--;
657:     v[0] = 0.0;
658:     MatSetValues(B,1,&mend,1,&mend,v,INSERT_VALUES);
659:   }

661:   /*
662:      Set matrix rows corresponding to interior data.  We construct the
663:      matrix one row at a time.
664:   */
665:   sc = 1.0/(appctx->h*appctx->h*2.0*(1.0+t)*(1.0+t));
666:   for (i=mstart; i<mend; i++) {
667:     idx[0] = i-1; idx[1] = i; idx[2] = i+1;
668:     is     = i - mstart + 1;
669:     v[0]   = sc*localptr[is];
670:     v[1]   = sc*(localptr[is+1] + localptr[is-1] - 4.0*localptr[is]);
671:     v[2]   = sc*localptr[is];
672:     MatSetValues(B,1,&i,3,idx,v,INSERT_VALUES);
673:   }

675:   /*
676:      Restore vector
677:   */
678:   VecRestoreArrayRead(local_in,&localptr);

680:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
681:      Complete the matrix assembly process and set some options
682:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
683:   /*
684:      Assemble matrix, using the 2-step process:
685:        MatAssemblyBegin(), MatAssemblyEnd()
686:      Computations can be done while messages are in transition
687:      by placing code between these two statements.
688:   */
689:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
690:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);

692:   /*
693:      Set and option to indicate that we will never add a new nonzero location
694:      to the matrix. If we do, it will generate an error.
695:   */
696:   MatSetOption(B,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

698:   return 0;
699: }