Actual source code: ex3.c

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

9: /*
10:    Concepts: TS^time-dependent linear problems
11:    Concepts: TS^heat equation
12:    Concepts: TS^diffusion equation
13:    Processors: 1
14: */

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

18:    This program solves the one-dimensional heat equation (also called the
19:    diffusion equation),
20:        u_t = u_xx,
21:    on the domain 0 <= x <= 1, with the boundary conditions
22:        u(t,0) = 0, u(t,1) = 0,
23:    and the initial condition
24:        u(0,x) = sin(6*pi*x) + 3*sin(2*pi*x).
25:    This is a linear, second-order, parabolic equation.

27:    We discretize the right-hand side using finite differences with
28:    uniform grid spacing h:
29:        u_xx = (u_{i+1} - 2u_{i} + u_{i-1})/(h^2)
30:    We then demonstrate time evolution using the various TS methods by
31:    running the program via
32:        ex3 -ts_type <timestepping solver>

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

38:    Notes:
39:    This code demonstrates the TS solver interface to two variants of
40:    linear problems, u_t = f(u,t), namely
41:      - time-dependent f:   f(u,t) is a function of t
42:      - time-independent f: f(u,t) is simply f(u)

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

46:   ------------------------------------------------------------------------- */

48: /*
49:    Include "petscts.h" so that we can use TS solvers.  Note that this file
50:    automatically includes:
51:      petscsys.h       - base PETSc routines   petscvec.h  - vectors
52:      petscmat.h  - matrices
53:      petscis.h     - index sets            petscksp.h  - Krylov subspace methods
54:      petscviewer.h - viewers               petscpc.h   - preconditioners
55:      petscksp.h   - linear solvers        petscsnes.h - nonlinear solvers
56: */

58:  #include <petscts.h>
59:  #include <petscdraw.h>

61: /*
62:    User-defined application context - contains data needed by the
63:    application-provided call-back routines.
64: */
65: typedef struct {
66:   Vec         solution;          /* global exact solution vector */
67:   PetscInt    m;                 /* total number of grid points */
68:   PetscReal   h;                 /* mesh width h = 1/(m-1) */
69:   PetscBool   debug;             /* flag (1 indicates activation of debugging printouts) */
70:   PetscViewer viewer1,viewer2;  /* viewers for the solution and error */
71:   PetscReal   norm_2,norm_max;  /* error norms */
72: } AppCtx;

74: /*
75:    User-defined routines
76: */
77: extern PetscErrorCode InitialConditions(Vec,AppCtx*);
78: extern PetscErrorCode RHSMatrixHeat(TS,PetscReal,Vec,Mat,Mat,void*);
79: extern PetscErrorCode Monitor(TS,PetscInt,PetscReal,Vec,void*);
80: extern PetscErrorCode ExactSolution(PetscReal,Vec,AppCtx*);

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

97:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
98:      Initialize program and set problem parameters
99:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

101:   PetscInitialize(&argc,&argv,(char*)0,help);if (ierr) return ierr;
102:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
103:   if (size != 1) SETERRQ(PETSC_COMM_SELF,1,"This is a uniprocessor example only!");

105:   m    = 60;
106:   PetscOptionsGetInt(NULL,NULL,"-m",&m,NULL);
107:   PetscOptionsHasName(NULL,NULL,"-debug",&appctx.debug);

109:   appctx.m        = m;
110:   appctx.h        = 1.0/(m-1.0);
111:   appctx.norm_2   = 0.0;
112:   appctx.norm_max = 0.0;

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

116:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
117:      Create vector data structures
118:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

120:   /*
121:      Create vector data structures for approximate and exact solutions
122:   */
123:   VecCreateSeq(PETSC_COMM_SELF,m,&u);
124:   VecDuplicate(u,&appctx.solution);

126:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
127:      Set up displays to show graphs of the solution and error
128:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

130:   PetscViewerDrawOpen(PETSC_COMM_SELF,0,"",80,380,400,160,&appctx.viewer1);
131:   PetscViewerDrawGetDraw(appctx.viewer1,0,&draw);
132:   PetscDrawSetDoubleBuffer(draw);
133:   PetscViewerDrawOpen(PETSC_COMM_SELF,0,"",80,0,400,160,&appctx.viewer2);
134:   PetscViewerDrawGetDraw(appctx.viewer2,0,&draw);
135:   PetscDrawSetDoubleBuffer(draw);

137:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
138:      Create timestepping solver context
139:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

141:   TSCreate(PETSC_COMM_SELF,&ts);
142:   TSSetProblemType(ts,TS_LINEAR);

144:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
145:      Set optional user-defined monitoring routine
146:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

148:   TSMonitorSet(ts,Monitor,&appctx,NULL);

150:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

152:      Create matrix data structure; set matrix evaluation routine.
153:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

155:   MatCreate(PETSC_COMM_SELF,&A);
156:   MatSetSizes(A,PETSC_DECIDE,PETSC_DECIDE,m,m);
157:   MatSetFromOptions(A);
158:   MatSetUp(A);

160:   flg  = PETSC_FALSE;
161:   PetscOptionsGetBool(NULL,NULL,"-time_dependent_rhs",&flg,NULL);
162:   if (flg) {
163:     /*
164:        For linear problems with a time-dependent f(u,t) in the equation
165:        u_t = f(u,t), the user provides the discretized right-hand-side
166:        as a time-dependent matrix.
167:     */
168:     TSSetRHSFunction(ts,NULL,TSComputeRHSFunctionLinear,&appctx);
169:     TSSetRHSJacobian(ts,A,A,RHSMatrixHeat,&appctx);
170:   } else {
171:     /*
172:        For linear problems with a time-independent f(u) in the equation
173:        u_t = f(u), the user provides the discretized right-hand-side
174:        as a matrix only once, and then sets the special Jacobian evaluation
175:        routine TSComputeRHSJacobianConstant() which will NOT recompute the Jacobian.
176:     */
177:     RHSMatrixHeat(ts,0.0,u,A,A,&appctx);
178:     TSSetRHSFunction(ts,NULL,TSComputeRHSFunctionLinear,&appctx);
179:     TSSetRHSJacobian(ts,A,A,TSComputeRHSJacobianConstant,&appctx);
180:   }

182:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
183:      Set solution vector and initial timestep
184:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

186:   dt   = appctx.h*appctx.h/2.0;
187:   TSSetTimeStep(ts,dt);

189:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
190:      Customize timestepping solver:
191:        - Set the solution method to be the Backward Euler method.
192:        - Set timestepping duration info
193:      Then set runtime options, which can override these defaults.
194:      For example,
195:           -ts_max_steps <maxsteps> -ts_final_time <maxtime>
196:      to override the defaults set by TSSetMaxSteps()/TSSetMaxTime().
197:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

199:   TSSetMaxSteps(ts,time_steps_max);
200:   TSSetMaxTime(ts,time_total_max);
201:   TSSetExactFinalTime(ts,TS_EXACTFINALTIME_STEPOVER);
202:   TSSetFromOptions(ts);

204:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
205:      Solve the problem
206:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

208:   /*
209:      Evaluate initial conditions
210:   */
211:   InitialConditions(u,&appctx);

213:   /*
214:      Run the timestepping solver
215:   */
216:   TSSolve(ts,u);
217:   TSGetStepNumber(ts,&steps);

219:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
220:      View timestepping solver info
221:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

223:   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));
224:   TSView(ts,PETSC_VIEWER_STDOUT_SELF);

226:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
227:      Free work space.  All PETSc objects should be destroyed when they
228:      are no longer needed.
229:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */

231:   TSDestroy(&ts);
232:   MatDestroy(&A);
233:   VecDestroy(&u);
234:   PetscViewerDestroy(&appctx.viewer1);
235:   PetscViewerDestroy(&appctx.viewer2);
236:   VecDestroy(&appctx.solution);

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

251:    Input Parameter:
252:    u - uninitialized solution vector (global)
253:    appctx - user-defined application context

255:    Output Parameter:
256:    u - vector with solution at initial time (global)
257: */
258: PetscErrorCode InitialConditions(Vec u,AppCtx *appctx)
259: {
260:   PetscScalar    *u_localptr,h = appctx->h;
262:   PetscInt       i;

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

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

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

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

295:   return 0;
296: }
297: /* --------------------------------------------------------------------- */
298: /*
299:    ExactSolution - Computes the exact solution at a given time.

301:    Input Parameters:
302:    t - current time
303:    solution - vector in which exact solution will be computed
304:    appctx - user-defined application context

306:    Output Parameter:
307:    solution - vector with the newly computed exact solution
308: */
309: PetscErrorCode ExactSolution(PetscReal t,Vec solution,AppCtx *appctx)
310: {
311:   PetscScalar    *s_localptr,h = appctx->h,ex1,ex2,sc1,sc2,tc = t;
313:   PetscInt       i;

315:   /*
316:      Get a pointer to vector data.
317:   */
318:   VecGetArray(solution,&s_localptr);

320:   /*
321:      Simply write the solution directly into the array locations.
322:      Alternatively, we culd use VecSetValues() or VecSetValuesLocal().
323:   */
324:   ex1 = PetscExpScalar(-36.*PETSC_PI*PETSC_PI*tc);
325:   ex2 = PetscExpScalar(-4.*PETSC_PI*PETSC_PI*tc);
326:   sc1 = PETSC_PI*6.*h;                 sc2 = PETSC_PI*2.*h;
327:   for (i=0; i<appctx->m; i++) s_localptr[i] = PetscSinScalar(sc1*(PetscReal)i)*ex1 + 3.*PetscSinScalar(sc2*(PetscReal)i)*ex2;

329:   /*
330:      Restore vector
331:   */
332:   VecRestoreArray(solution,&s_localptr);
333:   return 0;
334: }
335: /* --------------------------------------------------------------------- */
336: /*
337:    Monitor - User-provided routine to monitor the solution computed at
338:    each timestep.  This example plots the solution and computes the
339:    error in two different norms.

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

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

360:   /*
361:      View a graph of the current iterate
362:   */
363:   VecView(u,appctx->viewer2);

365:   /*
366:      Compute the exact solution
367:   */
368:   ExactSolution(time,appctx->solution,appctx);

370:   /*
371:      Print debugging information if desired
372:   */
373:   if (appctx->debug) {
374:     PetscPrintf(PETSC_COMM_SELF,"Computed solution vector\n");
375:     VecView(u,PETSC_VIEWER_STDOUT_SELF);
376:     PetscPrintf(PETSC_COMM_SELF,"Exact solution vector\n");
377:     VecView(appctx->solution,PETSC_VIEWER_STDOUT_SELF);
378:   }

380:   /*
381:      Compute the 2-norm and max-norm of the error
382:   */
383:   VecAXPY(appctx->solution,-1.0,u);
384:   VecNorm(appctx->solution,NORM_2,&norm_2);
385:   norm_2 = PetscSqrtReal(appctx->h)*norm_2;
386:   VecNorm(appctx->solution,NORM_MAX,&norm_max);
387:   if (norm_2   < 1e-14) norm_2   = 0;
388:   if (norm_max < 1e-14) norm_max = 0;

390:   TSGetTimeStep(ts,&dt);
391:   PetscPrintf(PETSC_COMM_WORLD,"Timestep %3D: step size = %g, time = %g, 2-norm error = %g, max norm error = %g\n",step,(double)dt,(double)time,(double)norm_2,(double)norm_max);

393:   appctx->norm_2   += norm_2;
394:   appctx->norm_max += norm_max;

396:   dttol = .0001;
397:   PetscOptionsGetReal(NULL,NULL,"-dttol",&dttol,NULL);
398:   if (dt < dttol) {
399:     dt  *= .999;
400:     TSSetTimeStep(ts,dt);
401:   }

403:   /*
404:      View a graph of the error
405:   */
406:   VecView(appctx->solution,appctx->viewer1);

408:   /*
409:      Print debugging information if desired
410:   */
411:   if (appctx->debug) {
412:     PetscPrintf(PETSC_COMM_SELF,"Error vector\n");
413:     VecView(appctx->solution,PETSC_VIEWER_STDOUT_SELF);
414:   }

416:   return 0;
417: }
418: /* --------------------------------------------------------------------- */
419: /*
420:    RHSMatrixHeat - User-provided routine to compute the right-hand-side
421:    matrix for the heat equation.

423:    Input Parameters:
424:    ts - the TS context
425:    t - current time
426:    global_in - global input vector
427:    dummy - optional user-defined context, as set by TSetRHSJacobian()

429:    Output Parameters:
430:    AA - Jacobian matrix
431:    BB - optionally different preconditioning matrix
432:    str - flag indicating matrix structure

434:    Notes:
435:    Recall that MatSetValues() uses 0-based row and column numbers
436:    in Fortran as well as in C.
437: */
438: PetscErrorCode RHSMatrixHeat(TS ts,PetscReal t,Vec X,Mat AA,Mat BB,void *ctx)
439: {
440:   Mat            A       = AA;                /* Jacobian matrix */
441:   AppCtx         *appctx = (AppCtx*)ctx;     /* user-defined application context */
442:   PetscInt       mstart  = 0;
443:   PetscInt       mend    = appctx->m;
445:   PetscInt       i,idx[3];
446:   PetscScalar    v[3],stwo = -2./(appctx->h*appctx->h),sone = -.5*stwo;

448:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
449:      Compute entries for the locally owned part of the matrix
450:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
451:   /*
452:      Set matrix rows corresponding to boundary data
453:   */

455:   mstart = 0;
456:   v[0]   = 1.0;
457:   MatSetValues(A,1,&mstart,1,&mstart,v,INSERT_VALUES);
458:   mstart++;

460:   mend--;
461:   v[0] = 1.0;
462:   MatSetValues(A,1,&mend,1,&mend,v,INSERT_VALUES);

464:   /*
465:      Set matrix rows corresponding to interior data.  We construct the
466:      matrix one row at a time.
467:   */
468:   v[0] = sone; v[1] = stwo; v[2] = sone;
469:   for (i=mstart; i<mend; i++) {
470:     idx[0] = i-1; idx[1] = i; idx[2] = i+1;
471:     MatSetValues(A,1,&i,3,idx,v,INSERT_VALUES);
472:   }

474:   /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
475:      Complete the matrix assembly process and set some options
476:      - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
477:   /*
478:      Assemble matrix, using the 2-step process:
479:        MatAssemblyBegin(), MatAssemblyEnd()
480:      Computations can be done while messages are in transition
481:      by placing code between these two statements.
482:   */
483:   MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
484:   MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);

486:   /*
487:      Set and option to indicate that we will never add a new nonzero location
488:      to the matrix. If we do, it will generate an error.
489:   */
490:   MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR,PETSC_TRUE);

492:   return 0;
493: }

495: /*TEST

497:     test:
498:       args: -nox -ts_type ssp -ts_dt 0.0005

500:     test:
501:       suffix: 2
502:       args: -nox -ts_type ssp -ts_dt 0.0005 -time_dependent_rhs 1

504:     test:
505:       suffix: 3
506:       args:  -nox -ts_type rosw -ts_max_steps 3 -ksp_converged_reason
507:       filter: sed "s/ATOL/RTOL/g"
508:       requires: !single

510:     test:
511:       suffix: 4
512:       args: -nox -ts_type beuler -ts_max_steps 3 -ksp_converged_reason
513:       filter: sed "s/ATOL/RTOL/g"

515:     test:
516:       suffix: 5
517:       args: -nox -ts_type beuler -ts_max_steps 3 -ksp_converged_reason -time_dependent_rhs
518:       filter: sed "s/ATOL/RTOL/g"

520:     test:
521:       requires: !single
522:       suffix: pod_guess
523:       args: -nox -ts_type beuler -ts_dt 0.0005 -ksp_guess_type pod -pc_type none -ksp_converged_reason

525:     test:
526:       requires: !single
527:       suffix: pod_guess_Ainner
528:       args: -nox -ts_type beuler -ts_dt 0.0005 -ksp_guess_type pod -ksp_guess_pod_Ainner -pc_type none -ksp_converged_reason

530:     test:
531:       requires: !single
532:       suffix: fischer_guess
533:       args: -nox -ts_type beuler -ts_dt 0.0005 -ksp_guess_type fischer -pc_type none -ksp_converged_reason

535:     test:
536:       requires: !single
537:       suffix: fischer_guess_2
538:       args: -nox -ts_type beuler -ts_dt 0.0005 -ksp_guess_type fischer -ksp_guess_fischer_model 2,10 -pc_type none -ksp_converged_reason
539: TEST*/
```