Actual source code: ex6.c

  1: static char help[] = "Solves a simple time-dependent linear PDE (the heat equation).\n\
  2: Input parameters include:\n\
  3:   -m <points>, where <points> = number of grid points\n\
  4:   -time_dependent_rhs : Treat the problem as having a time-dependent right-hand side\n\
  5:   -debug              : Activate debugging printouts\n\
  6:   -nox                : Deactivate x-window graphics\n\n";

  8: /* ------------------------------------------------------------------------

 10:    This program solves the one-dimensional heat equation (also called the
 11:    diffusion equation),
 12:        u_t = u_xx,
 13:    on the domain 0 <= x <= 1, with the boundary conditions
 14:        u(t,0) = 0, u(t,1) = 0,
 15:    and the initial condition
 16:        u(0,x) = sin(6*pi*x) + 3*sin(2*pi*x).
 17:    This is a linear, second-order, parabolic equation.

 19:    We discretize the right-hand side using finite differences with
 20:    uniform grid spacing h:
 21:        u_xx = (u_{i+1} - 2u_{i} + u_{i-1})/(h^2)
 22:    We then demonstrate time evolution using the various TS methods by
 23:    running the program via
 24:        ex3 -ts_type <timestepping solver>

 26:    We compare the approximate solution with the exact solution, given by
 27:        u_exact(x,t) = exp(-36*pi*pi*t) * sin(6*pi*x) +
 28:                       3*exp(-4*pi*pi*t) * sin(2*pi*x)

 30:    Notes:
 31:    This code demonstrates the TS solver interface to two variants of
 32:    linear problems, u_t = f(u,t), namely
 33:      - time-dependent f:   f(u,t) is a function of t
 34:      - time-independent f: f(u,t) is simply f(u)

 36:     The parallel version of this code is ts/tutorials/ex4.c

 38:   ------------------------------------------------------------------------- */

 40: /*
 41:    Include "petscts.h" so that we can use the TS ODE integrators.  Note that this file
 42:    automatically includes:
 43:      petscsys.h  - base PETSc routines
 44:      petscis.h   - index sets
 45:      petscvec.h  - vectors
 46:      petscmat.h  - matrices
 47:      petscpc.h   - preconditioners
 48:      petscksp.h  - Krylov subspace methods
 49:      petscsnes.h - nonlinear solvers
 50: */

 52: #include <petscts.h>
 53: #include <petscdraw.h>

 55: /*
 56:    User-defined application context - contains data needed by the
 57:    application-provided call-back routines.
 58: */
 59: typedef struct {
 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:   PetscViewer viewer1, viewer2; /* viewers for the solution and error */
 65:   PetscReal   norm_2, norm_max; /* error norms */
 66: } AppCtx;

 68: /*
 69:    User-defined routines
 70: */
 71: extern PetscErrorCode InitialConditions(Vec, AppCtx *);
 72: extern PetscErrorCode RHSMatrixHeat(TS, PetscReal, Vec, Mat, Mat, void *);
 73: extern PetscErrorCode Monitor(TS, PetscInt, PetscReal, Vec, void *);
 74: extern PetscErrorCode ExactSolution(PetscReal, Vec, AppCtx *);
 75: extern PetscErrorCode MyBCRoutine(TS, PetscReal, Vec, void *);

 77: int main(int argc, char **argv)
 78: {
 79:   AppCtx      appctx;                 /* user-defined application context */
 80:   TS          ts;                     /* timestepping context */
 81:   Mat         A;                      /* matrix data structure */
 82:   Vec         u;                      /* approximate solution vector */
 83:   PetscReal   time_total_max = 100.0; /* default max total time */
 84:   PetscInt    time_steps_max = 100;   /* default max timesteps */
 85:   PetscDraw   draw;                   /* drawing context */
 86:   PetscInt    steps, m;
 87:   PetscMPIInt size;
 88:   PetscReal   dt;
 89:   PetscReal   ftime;
 90:   PetscBool   flg;
 91:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 92:      Initialize program and set problem parameters
 93:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

 95:   PetscFunctionBeginUser;
 96:   PetscCall(PetscInitialize(&argc, &argv, NULL, help));
 97:   MPI_Comm_size(PETSC_COMM_WORLD, &size);
 98:   PetscCheck(size == 1, PETSC_COMM_WORLD, PETSC_ERR_WRONG_MPI_SIZE, "This is a uniprocessor example only!");

100:   m = 60;
101:   PetscCall(PetscOptionsGetInt(NULL, NULL, "-m", &m, NULL));
102:   PetscCall(PetscOptionsHasName(NULL, NULL, "-debug", &appctx.debug));

104:   appctx.m        = m;
105:   appctx.h        = 1.0 / (m - 1.0);
106:   appctx.norm_2   = 0.0;
107:   appctx.norm_max = 0.0;

109:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "Solving a linear TS problem on 1 processor\n"));

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

115:   /*
116:      Create vector data structures for approximate and exact solutions
117:   */
118:   PetscCall(VecCreateSeq(PETSC_COMM_SELF, m, &u));
119:   PetscCall(VecDuplicate(u, &appctx.solution));

121:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
122:      Set up displays to show graphs of the solution and error
123:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

125:   PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, "", 80, 380, 400, 160, &appctx.viewer1));
126:   PetscCall(PetscViewerDrawGetDraw(appctx.viewer1, 0, &draw));
127:   PetscCall(PetscDrawSetDoubleBuffer(draw));
128:   PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, "", 80, 0, 400, 160, &appctx.viewer2));
129:   PetscCall(PetscViewerDrawGetDraw(appctx.viewer2, 0, &draw));
130:   PetscCall(PetscDrawSetDoubleBuffer(draw));

132:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
133:      Create timestepping solver context
134:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

136:   PetscCall(TSCreate(PETSC_COMM_SELF, &ts));
137:   PetscCall(TSSetProblemType(ts, TS_LINEAR));

139:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
140:      Set optional user-defined monitoring routine
141:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

143:   PetscCall(TSMonitorSet(ts, Monitor, &appctx, NULL));

145:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

147:      Create matrix data structure; set matrix evaluation routine.
148:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

150:   PetscCall(MatCreate(PETSC_COMM_SELF, &A));
151:   PetscCall(MatSetSizes(A, PETSC_DECIDE, PETSC_DECIDE, m, m));
152:   PetscCall(MatSetFromOptions(A));
153:   PetscCall(MatSetUp(A));

155:   PetscCall(PetscOptionsHasName(NULL, NULL, "-time_dependent_rhs", &flg));
156:   if (flg) {
157:     /*
158:        For linear problems with a time-dependent f(u,t) in the equation
159:        u_t = f(u,t), the user provides the discretized right-hand-side
160:        as a time-dependent matrix.
161:     */
162:     PetscCall(TSSetRHSFunction(ts, NULL, TSComputeRHSFunctionLinear, &appctx));
163:     PetscCall(TSSetRHSJacobian(ts, A, A, RHSMatrixHeat, &appctx));
164:   } else {
165:     /*
166:        For linear problems with a time-independent f(u) in the equation
167:        u_t = f(u), the user provides the discretized right-hand side
168:        as a matrix only once, and then sets a null matrix evaluation
169:        routine.
170:     */
171:     PetscCall(RHSMatrixHeat(ts, 0.0, u, A, A, &appctx));
172:     PetscCall(TSSetRHSFunction(ts, NULL, TSComputeRHSFunctionLinear, &appctx));
173:     PetscCall(TSSetRHSJacobian(ts, A, A, TSComputeRHSJacobianConstant, &appctx));
174:   }

176:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
177:      Set solution vector and initial timestep
178:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

180:   dt = appctx.h * appctx.h / 2.0;
181:   PetscCall(TSSetTimeStep(ts, dt));
182:   PetscCall(TSSetSolution(ts, u));

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

194:   PetscCall(TSSetMaxSteps(ts, time_steps_max));
195:   PetscCall(TSSetMaxTime(ts, time_total_max));
196:   PetscCall(TSSetExactFinalTime(ts, TS_EXACTFINALTIME_STEPOVER));
197:   PetscCall(TSSetFromOptions(ts));

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

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

208:   /*
209:      Run the timestepping solver
210:   */
211:   PetscCall(TSSolve(ts, u));
212:   PetscCall(TSGetSolveTime(ts, &ftime));
213:   PetscCall(TSGetStepNumber(ts, &steps));

215:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
216:      View timestepping solver info
217:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

219:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "avg. error (2 norm) = %g, avg. error (max norm) = %g\n", (double)(appctx.norm_2 / steps), (double)(appctx.norm_max / steps)));
220:   PetscCall(TSView(ts, PETSC_VIEWER_STDOUT_SELF));

222:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
223:      Free work space.  All PETSc objects should be destroyed when they
224:      are no longer needed.
225:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

227:   PetscCall(TSDestroy(&ts));
228:   PetscCall(MatDestroy(&A));
229:   PetscCall(VecDestroy(&u));
230:   PetscCall(PetscViewerDestroy(&appctx.viewer1));
231:   PetscCall(PetscViewerDestroy(&appctx.viewer2));
232:   PetscCall(VecDestroy(&appctx.solution));

234:   /*
235:      Always call PetscFinalize() before exiting a program.  This routine
236:        - finalizes the PETSc libraries as well as MPI
237:        - provides summary and diagnostic information if certain runtime
238:          options are chosen (e.g., -log_view).
239:   */
240:   PetscCall(PetscFinalize());
241:   return 0;
242: }
243: /* --------------------------------------------------------------------- */
244: /*
245:    InitialConditions - Computes the solution at the initial time.

247:    Input Parameter:
248:    u - uninitialized solution vector (global)
249:    appctx - user-defined application context

251:    Output Parameter:
252:    u - vector with solution at initial time (global)
253: */
254: PetscErrorCode InitialConditions(Vec u, AppCtx *appctx)
255: {
256:   PetscScalar *u_localptr;
257:   PetscInt     i;

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

271:   /*
272:      We initialize the solution array by simply writing the solution
273:      directly into the array locations.  Alternatively, we could use
274:      VecSetValues() or VecSetValuesLocal().
275:   */
276:   for (i = 0; i < appctx->m; i++) u_localptr[i] = PetscSinReal(PETSC_PI * i * 6. * appctx->h) + 3. * PetscSinReal(PETSC_PI * i * 2. * appctx->h);

278:   /*
279:      Restore vector
280:   */
281:   PetscCall(VecRestoreArray(u, &u_localptr));

283:   /*
284:      Print debugging information if desired
285:   */
286:   if (appctx->debug) PetscCall(VecView(u, PETSC_VIEWER_STDOUT_SELF));
287:   PetscFunctionReturn(PETSC_SUCCESS);
288: }
289: /* --------------------------------------------------------------------- */
290: /*
291:    ExactSolution - Computes the exact solution at a given time.

293:    Input Parameters:
294:    t - current time
295:    solution - vector in which exact solution will be computed
296:    appctx - user-defined application context

298:    Output Parameter:
299:    solution - vector with the newly computed exact solution
300: */
301: PetscErrorCode ExactSolution(PetscReal t, Vec solution, AppCtx *appctx)
302: {
303:   PetscScalar *s_localptr, h = appctx->h, ex1, ex2, sc1, sc2;
304:   PetscInt     i;

306:   PetscFunctionBeginUser;
307:   /*
308:      Get a pointer to vector data.
309:   */
310:   PetscCall(VecGetArray(solution, &s_localptr));

312:   /*
313:      Simply write the solution directly into the array locations.
314:      Alternatively, we culd use VecSetValues() or VecSetValuesLocal().
315:   */
316:   ex1 = PetscExpReal(-36. * PETSC_PI * PETSC_PI * t);
317:   ex2 = PetscExpReal(-4. * PETSC_PI * PETSC_PI * t);
318:   sc1 = PETSC_PI * 6. * h;
319:   sc2 = PETSC_PI * 2. * h;
320:   for (i = 0; i < appctx->m; i++) s_localptr[i] = PetscSinReal(PetscRealPart(sc1) * (PetscReal)i) * ex1 + 3. * PetscSinReal(PetscRealPart(sc2) * (PetscReal)i) * ex2;

322:   /*
323:      Restore vector
324:   */
325:   PetscCall(VecRestoreArray(solution, &s_localptr));
326:   PetscFunctionReturn(PETSC_SUCCESS);
327: }
328: /* --------------------------------------------------------------------- */
329: /*
330:    Monitor - User-provided routine to monitor the solution computed at
331:    each timestep.  This example plots the solution and computes the
332:    error in two different norms.

334:    This example also demonstrates changing the timestep via TSSetTimeStep().

336:    Input Parameters:
337:    ts     - the timestep context
338:    step   - the count of the current step (with 0 meaning the
339:              initial condition)
340:    crtime  - the current time
341:    u      - the solution at this timestep
342:    ctx    - the user-provided context for this monitoring routine.
343:             In this case we use the application context which contains
344:             information about the problem size, workspace and the exact
345:             solution.
346: */
347: PetscErrorCode Monitor(TS ts, PetscInt step, PetscReal crtime, Vec u, PetscCtx ctx)
348: {
349:   AppCtx   *appctx = (AppCtx *)ctx; /* user-defined application context */
350:   PetscReal norm_2, norm_max, dt, dttol;
351:   PetscBool flg;

353:   PetscFunctionBeginUser;
354:   /*
355:      View a graph of the current iterate
356:   */
357:   PetscCall(VecView(u, appctx->viewer2));

359:   /*
360:      Compute the exact solution
361:   */
362:   PetscCall(ExactSolution(crtime, appctx->solution, appctx));

364:   /*
365:      Print debugging information if desired
366:   */
367:   if (appctx->debug) {
368:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "Computed solution vector\n"));
369:     PetscCall(VecView(u, PETSC_VIEWER_STDOUT_SELF));
370:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "Exact solution vector\n"));
371:     PetscCall(VecView(appctx->solution, PETSC_VIEWER_STDOUT_SELF));
372:   }

374:   /*
375:      Compute the 2-norm and max-norm of the error
376:   */
377:   PetscCall(VecAXPY(appctx->solution, -1.0, u));
378:   PetscCall(VecNorm(appctx->solution, NORM_2, &norm_2));
379:   norm_2 = PetscSqrtReal(appctx->h) * norm_2;
380:   PetscCall(VecNorm(appctx->solution, NORM_MAX, &norm_max));

382:   PetscCall(TSGetTimeStep(ts, &dt));
383:   if (norm_2 > 1.e-2) PetscCall(PetscPrintf(PETSC_COMM_SELF, "Timestep %" PetscInt_FMT ": step size = %g, time = %g, 2-norm error = %g, max norm error = %g\n", step, (double)dt, (double)crtime, (double)norm_2, (double)norm_max));
384:   appctx->norm_2 += norm_2;
385:   appctx->norm_max += norm_max;

387:   dttol = .0001;
388:   PetscCall(PetscOptionsGetReal(NULL, NULL, "-dttol", &dttol, &flg));
389:   if (dt < dttol) {
390:     dt *= .999;
391:     PetscCall(TSSetTimeStep(ts, dt));
392:   }

394:   /*
395:      View a graph of the error
396:   */
397:   PetscCall(VecView(appctx->solution, appctx->viewer1));

399:   /*
400:      Print debugging information if desired
401:   */
402:   if (appctx->debug) {
403:     PetscCall(PetscPrintf(PETSC_COMM_SELF, "Error vector\n"));
404:     PetscCall(VecView(appctx->solution, PETSC_VIEWER_STDOUT_SELF));
405:   }
406:   PetscFunctionReturn(PETSC_SUCCESS);
407: }
408: /* --------------------------------------------------------------------- */
409: /*
410:    RHSMatrixHeat - User-provided routine to compute the right-hand-side
411:    matrix for the heat equation.

413:    Input Parameters:
414:    ts - the TS context
415:    t - current time
416:    global_in - global input vector
417:    dummy - optional user-defined context, as set by TSetRHSJacobian()

419:    Output Parameters:
420:    AA - Jacobian matrix
421:    BB - optionally different matrix used to construct the preconditioner

423:    Notes:
424:    Recall that MatSetValues() uses 0-based row and column numbers
425:    in Fortran as well as in C.
426: */
427: PetscErrorCode RHSMatrixHeat(TS ts, PetscReal t, Vec X, Mat AA, Mat BB, PetscCtx ctx)
428: {
429:   Mat         A      = AA;            /* Jacobian matrix */
430:   AppCtx     *appctx = (AppCtx *)ctx; /* user-defined application context */
431:   PetscInt    mstart = 0;
432:   PetscInt    mend   = appctx->m;
433:   PetscInt    i, idx[3];
434:   PetscScalar v[3], stwo = -2. / (appctx->h * appctx->h), sone = -.5 * stwo;

436:   PetscFunctionBeginUser;
437:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
438:      Compute entries for the locally owned part of the matrix
439:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
440:   /*
441:      Set matrix rows corresponding to boundary data
442:   */

444:   mstart = 0;
445:   v[0]   = 1.0;
446:   PetscCall(MatSetValues(A, 1, &mstart, 1, &mstart, v, INSERT_VALUES));
447:   mstart++;

449:   mend--;
450:   v[0] = 1.0;
451:   PetscCall(MatSetValues(A, 1, &mend, 1, &mend, v, INSERT_VALUES));

453:   /*
454:      Set matrix rows corresponding to interior data.  We construct the
455:      matrix one row at a time.
456:   */
457:   v[0] = sone;
458:   v[1] = stwo;
459:   v[2] = sone;
460:   for (i = mstart; i < mend; i++) {
461:     idx[0] = i - 1;
462:     idx[1] = i;
463:     idx[2] = i + 1;
464:     PetscCall(MatSetValues(A, 1, &i, 3, idx, v, INSERT_VALUES));
465:   }

467:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
468:      Complete the matrix assembly process and set some options
469:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
470:   /*
471:      Assemble matrix, using the 2-step process:
472:        MatAssemblyBegin(), MatAssemblyEnd()
473:      Computations can be done while messages are in transition
474:      by placing code between these two statements.
475:   */
476:   PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
477:   PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));

479:   /*
480:      Set and option to indicate that we will never add a new nonzero location
481:      to the matrix. If we do, it will generate an error.
482:   */
483:   PetscCall(MatSetOption(A, MAT_NEW_NONZERO_LOCATION_ERR, PETSC_TRUE));
484:   PetscFunctionReturn(PETSC_SUCCESS);
485: }
486: /* --------------------------------------------------------------------- */
487: /*
488:    Input Parameters:
489:    ts - the TS context
490:    t - current time
491:    f - function
492:    ctx - optional user-defined context, as set by TSetBCFunction()
493:  */
494: PetscErrorCode MyBCRoutine(TS ts, PetscReal t, Vec f, PetscCtx ctx)
495: {
496:   AppCtx      *appctx = (AppCtx *)ctx; /* user-defined application context */
497:   PetscInt     m      = appctx->m;
498:   PetscScalar *fa;

500:   PetscFunctionBeginUser;
501:   PetscCall(VecGetArray(f, &fa));
502:   fa[0]     = 0.0;
503:   fa[m - 1] = 1.0;
504:   PetscCall(VecRestoreArray(f, &fa));
505:   PetscCall(PetscPrintf(PETSC_COMM_SELF, "t=%g\n", (double)t));
506:   PetscFunctionReturn(PETSC_SUCCESS);
507: }

509: /*TEST

511:     test:
512:       args: -nox -ts_max_steps 4

514: TEST*/