Actual source code: ex3.c
1: /*$Id: ex3.c,v 1.24 2001/04/10 19:37:12 bsmith Exp $*/
3: /* Program usage: ex3 [-help] [all PETSc options] */
5: static char help[] ="Solves a simple time-dependent linear PDE (the heat equation).n
6: Input parameters include:n
7: -m <points>, where <points> = number of grid pointsn
8: -time_dependent_rhs : Treat the problem as having a time-dependent right-hand siden
9: -time_dependent_bc : Treat the problem as having time-dependent boundary conditionsn
10: -debug : Activate debugging printoutsn
11: -nox : Deactivate x-window graphicsnn";
13: /*
14: Concepts: TS^time-dependent linear problems
15: Concepts: TS^heat equation
16: Concepts: TS^diffusion equation
17: Processors: 1
18: */
20: /* ------------------------------------------------------------------------
22: This program solves the one-dimensional heat equation (also called the
23: diffusion equation),
24: u_t = u_xx,
25: on the domain 0 <= x <= 1, with the boundary conditions
26: u(t,0) = 0, u(t,1) = 0,
27: and the initial condition
28: u(0,x) = sin(6*pi*x) + 3*sin(2*pi*x).
29: This is a linear, second-order, parabolic equation.
31: We discretize the right-hand side using finite differences with
32: uniform grid spacing h:
33: u_xx = (u_{i+1} - 2u_{i} + u_{i-1})/(h^2)
34: We then demonstrate time evolution using the various TS methods by
35: running the program via
36: ex3 -ts_type <timestepping solver>
38: We compare the approximate solution with the exact solution, given by
39: u_exact(x,t) = exp(-36*pi*pi*t) * sin(6*pi*x) +
40: 3*exp(-4*pi*pi*t) * sin(2*pi*x)
42: Notes:
43: This code demonstrates the TS solver interface to two variants of
44: linear problems, u_t = f(u,t), namely
45: - time-dependent f: f(u,t) is a function of t
46: - time-independent f: f(u,t) is simply f(u)
48: The parallel version of this code is ts/examples/tutorials/ex4.c
50: ------------------------------------------------------------------------- */
52: /*
53: Include "petscts.h" so that we can use TS solvers. Note that this file
54: automatically includes:
55: petsc.h - base PETSc routines petscvec.h - vectors
56: petscsys.h - system routines petscmat.h - matrices
57: petscis.h - index sets petscksp.h - Krylov subspace methods
58: petscviewer.h - viewers petscpc.h - preconditioners
59: petscsles.h - linear solvers petscsnes.h - nonlinear solvers
60: */
62: #include petscts.h
64: /*
65: User-defined application context - contains data needed by the
66: application-provided call-back routines.
67: */
68: typedef struct {
69: Vec solution; /* global exact solution vector */
70: int m; /* total number of grid points */
71: double h; /* mesh width h = 1/(m-1) */
72: PetscTruth debug; /* flag (1 indicates activation of debugging printouts) */
73: PetscViewer viewer1,viewer2; /* viewers for the solution and error */
74: double norm_2,norm_max; /* error norms */
75: } AppCtx;
77: /*
78: User-defined routines
79: */
80: extern int InitialConditions(Vec,AppCtx*);
81: extern int RHSMatrixHeat(TS,double,Mat*,Mat*,MatStructure*,void*);
82: extern int Monitor(TS,int,double,Vec,void*);
83: extern int ExactSolution(double,Vec,AppCtx*);
84: extern int MyBCRoutine(TS,double,Vec,void*);
86: int main(int argc,char **argv)
87: {
88: AppCtx appctx; /* user-defined application context */
89: TS ts; /* timestepping context */
90: Mat A; /* matrix data structure */
91: Vec u; /* approximate solution vector */
92: double time_total_max = 100.0; /* default max total time */
93: int time_steps_max = 100; /* default max timesteps */
94: PetscDraw draw; /* drawing context */
95: int ierr,steps,size,m;
96: double dt,ftime;
97: PetscTruth flg;
99: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
100: Initialize program and set problem parameters
101: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
102:
103: PetscInitialize(&argc,&argv,(char*)0,help);
104: MPI_Comm_size(PETSC_COMM_WORLD,&size);
105: if (size != 1) SETERRQ(1,"This is a uniprocessor example only!");
107: m = 60;
108: PetscOptionsGetInt(PETSC_NULL,"-m",&m,PETSC_NULL);
109: PetscOptionsHasName(PETSC_NULL,"-debug",&appctx.debug);
110: appctx.m = m;
111: appctx.h = 1.0/(m-1.0);
112: appctx.norm_2 = 0.0;
113: appctx.norm_max = 0.0;
114: PetscPrintf(PETSC_COMM_SELF,"Solving a linear TS problem on 1 processorn");
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_LINEAR,&ts);
143: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
144: Set optional user-defined monitoring routine
145: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
147: TSSetMonitor(ts,Monitor,&appctx,PETSC_NULL);
149: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
151: Create matrix data structure; set matrix evaluation routine.
152: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
154: MatCreate(PETSC_COMM_SELF,PETSC_DECIDE,PETSC_DECIDE,m,m,&A);
155: MatSetFromOptions(A);
157: PetscOptionsHasName(PETSC_NULL,"-time_dependent_rhs",&flg);
158: if (flg) {
159: /*
160: For linear problems with a time-dependent f(u,t) in the equation
161: u_t = f(u,t), the user provides the discretized right-hand-side
162: as a time-dependent matrix.
163: */
164: TSSetRHSMatrix(ts,A,A,RHSMatrixHeat,&appctx);
165: } else {
166: /*
167: For linear problems with a time-independent f(u) in the equation
168: u_t = f(u), the user provides the discretized right-hand-side
169: as a matrix only once, and then sets a null matrix evaluation
170: routine.
171: */
172: MatStructure A_structure;
173: RHSMatrixHeat(ts,0.0,&A,&A,&A_structure,&appctx);
174: TSSetRHSMatrix(ts,A,A,PETSC_NULL,&appctx);
175: }
177: /* Treat the problem as having time-dependent boundary conditions */
178: PetscOptionsHasName(PETSC_NULL,"-time_dependent_bc",&flg);
179: if (flg) {
180: TSSetRHSBoundaryConditions(ts,MyBCRoutine,&appctx);
181: }
183: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
184: Set solution vector and initial timestep
185: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
187: dt = appctx.h*appctx.h/2.0;
188: TSSetInitialTimeStep(ts,0.0,dt);
189: TSSetSolution(ts,u);
191: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
192: Customize timestepping solver:
193: - Set the solution method to be the Backward Euler method.
194: - Set timestepping duration info
195: Then set runtime options, which can override these defaults.
196: For example,
197: -ts_max_steps <maxsteps> -ts_max_time <maxtime>
198: to override the defaults set by TSSetDuration().
199: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
201: TSSetDuration(ts,time_steps_max,time_total_max);
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: TSStep(ts,&steps,&ftime);
218: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
219: View timestepping solver info
220: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
222: PetscPrintf(PETSC_COMM_SELF,"avg. error (2 norm) = %g, avg. error (max norm) = %gn",
223: appctx.norm_2/steps,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_summary).
243: */
244: PetscFinalize();
245: return 0;
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: int InitialConditions(Vec u,AppCtx *appctx)
259: {
260: Scalar *u_localptr,h = appctx->h;
261: int i,ierr;
263: /*
264: Get a pointer to vector data.
265: - For default PETSc vectors, VecGetArray() returns a pointer to
266: the data array. Otherwise, the routine is implementation dependent.
267: - You MUST call VecRestoreArray() when you no longer need access to
268: the array.
269: - Note that the Fortran interface to VecGetArray() differs from the
270: C version. See the users manual for details.
271: */
272: VecGetArray(u,&u_localptr);
274: /*
275: We initialize the solution array by simply writing the solution
276: directly into the array locations. Alternatively, we could use
277: VecSetValues() or VecSetValuesLocal().
278: */
279: for (i=0; i<appctx->m; i++) {
280: u_localptr[i] = PetscSinScalar(PETSC_PI*i*6.*h) + 3.*PetscSinScalar(PETSC_PI*i*2.*h);
281: }
283: /*
284: Restore vector
285: */
286: VecRestoreArray(u,&u_localptr);
288: /*
289: Print debugging information if desired
290: */
291: if (appctx->debug) {
292: printf("initial guess vectorn");
293: VecView(u,PETSC_VIEWER_STDOUT_SELF);
294: }
296: return 0;
297: }
298: /* --------------------------------------------------------------------- */
299: /*
300: ExactSolution - Computes the exact solution at a given time.
302: Input Parameters:
303: t - current time
304: solution - vector in which exact solution will be computed
305: appctx - user-defined application context
307: Output Parameter:
308: solution - vector with the newly computed exact solution
309: */
310: int ExactSolution(double t,Vec solution,AppCtx *appctx)
311: {
312: Scalar *s_localptr,h = appctx->h,ex1,ex2,sc1,sc2;
313: int i,ierr;
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*t);
325: ex2 = PetscExpScalar(-4.*PETSC_PI*PETSC_PI*t);
326: sc1 = PETSC_PI*6.*h; sc2 = PETSC_PI*2.*h;
327: for (i=0; i<appctx->m; i++) {
328: s_localptr[i] = PetscSinScalar(sc1*(double)i)*ex1 + 3.*PetscSinScalar(sc2*(double)i)*ex2;
329: }
331: /*
332: Restore vector
333: */
334: VecRestoreArray(solution,&s_localptr);
335: return 0;
336: }
337: /* --------------------------------------------------------------------- */
338: /*
339: Monitor - User-provided routine to monitor the solution computed at
340: each timestep. This example plots the solution and computes the
341: error in two different norms.
343: This example also demonstrates changing the timestep via TSSetTimeStep().
345: Input Parameters:
346: ts - the timestep context
347: step - the count of the current step (with 0 meaning the
348: initial condition)
349: time - the current time
350: u - the solution at this timestep
351: ctx - the user-provided context for this monitoring routine.
352: In this case we use the application context which contains
353: information about the problem size, workspace and the exact
354: solution.
355: */
356: int Monitor(TS ts,int step,double time,Vec u,void *ctx)
357: {
358: AppCtx *appctx = (AppCtx*) ctx; /* user-defined application context */
359: int ierr;
360: double norm_2,norm_max,dt,dttol;
361: Scalar mone = -1.0;
362: /*
363: View a graph of the current iterate
364: */
365: VecView(u,appctx->viewer2);
367: /*
368: Compute the exact solution
369: */
370: ExactSolution(time,appctx->solution,appctx);
372: /*
373: Print debugging information if desired
374: */
375: if (appctx->debug) {
376: printf("Computed solution vectorn");
377: VecView(u,PETSC_VIEWER_STDOUT_SELF);
378: printf("Exact solution vectorn");
379: VecView(appctx->solution,PETSC_VIEWER_STDOUT_SELF);
380: }
382: /*
383: Compute the 2-norm and max-norm of the error
384: */
385: VecAXPY(&mone,u,appctx->solution);
386: VecNorm(appctx->solution,NORM_2,&norm_2);
387: norm_2 = sqrt(appctx->h)*norm_2;
388: VecNorm(appctx->solution,NORM_MAX,&norm_max);
390: TSGetTimeStep(ts,&dt);
391: printf("Timestep %3d: step size = %-11g, time = %-11g, 2-norm error = %-11g, max norm error = %-11gn",
392: step,dt,time,norm_2,norm_max);
393: appctx->norm_2 += norm_2;
394: appctx->norm_max += norm_max;
396: dttol = .0001;
397: PetscOptionsGetDouble(PETSC_NULL,"-dttol",&dttol,PETSC_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: printf("Error vectorn");
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: int RHSMatrixHeat(TS ts,double t,Mat *AA,Mat *BB,MatStructure *str,void *ctx)
439: {
440: Mat A = *AA; /* Jacobian matrix */
441: AppCtx *appctx = (AppCtx*)ctx; /* user-defined application context */
442: int mstart = 0;
443: int mend = appctx->m;
444: int ierr,i,idx[3];
445: Scalar v[3],stwo = -2./(appctx->h*appctx->h),sone = -.5*stwo;
447: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
448: Compute entries for the locally owned part of the matrix
449: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
450: /*
451: Set matrix rows corresponding to boundary data
452: */
454: mstart = 0;
455: v[0] = 1.0;
456: MatSetValues(A,1,&mstart,1,&mstart,v,INSERT_VALUES);
457: mstart++;
459: mend--;
460: v[0] = 1.0;
461: MatSetValues(A,1,&mend,1,&mend,v,INSERT_VALUES);
463: /*
464: Set matrix rows corresponding to interior data. We construct the
465: matrix one row at a time.
466: */
467: v[0] = sone; v[1] = stwo; v[2] = sone;
468: for (i=mstart; i<mend; i++) {
469: idx[0] = i-1; idx[1] = i; idx[2] = i+1;
470: MatSetValues(A,1,&i,3,idx,v,INSERT_VALUES);
471: }
473: /* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
474: Complete the matrix assembly process and set some options
475: - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
476: /*
477: Assemble matrix, using the 2-step process:
478: MatAssemblyBegin(), MatAssemblyEnd()
479: Computations can be done while messages are in transition
480: by placing code between these two statements.
481: */
482: MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
483: MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
485: /*
486: Set flag to indicate that the Jacobian matrix retains an identical
487: nonzero structure throughout all timestepping iterations (although the
488: values of the entries change). Thus, we can save some work in setting
489: up the preconditioner (e.g., no need to redo symbolic factorization for
490: ILU/ICC preconditioners).
491: - If the nonzero structure of the matrix is different during
492: successive linear solves, then the flag DIFFERENT_NONZERO_PATTERN
493: must be used instead. If you are unsure whether the matrix
494: structure has changed or not, use the flag DIFFERENT_NONZERO_PATTERN.
495: - Caution: If you specify SAME_NONZERO_PATTERN, PETSc
496: believes your assertion and does not check the structure
497: of the matrix. If you erroneously claim that the structure
498: is the same when it actually is not, the new preconditioner
499: will not function correctly. Thus, use this optimization
500: feature with caution!
501: */
502: *str = SAME_NONZERO_PATTERN;
504: /*
505: Set and option to indicate that we will never add a new nonzero location
506: to the matrix. If we do, it will generate an error.
507: */
508: MatSetOption(A,MAT_NEW_NONZERO_LOCATION_ERR);
510: return 0;
511: }
512: /* --------------------------------------------------------------------- */
513: /*
514: Input Parameters:
515: ts - the TS context
516: t - current time
517: f - function
518: ctx - optional user-defined context, as set by TSetBCFunction()
519: */
520: int MyBCRoutine(TS ts,double t,Vec f,void *ctx)
521: {
522: AppCtx *appctx = (AppCtx*)ctx; /* user-defined application context */
523: int ierr,m = appctx->m;
524: Scalar *fa;
526: VecGetArray(f,&fa);
527: fa[0] = 0.0;
528: fa[m-1] = 0.0;
529: VecRestoreArray(f,&fa);
530: printf("t=%gn",t);
531:
532: return 0;
533: }