Actual source code: ex1.c

petsc-3.6.1 2015-08-06
Report Typos and Errors
  2: static char help[] ="Solves the time independent Bratu problem using pseudo-timestepping.";

  4: /*
  5:    Concepts: TS^pseudo-timestepping
  6:    Concepts: pseudo-timestepping
  7:    Concepts: TS^nonlinear problems
  8:    Processors: 1

 10: */

 12: /* ------------------------------------------------------------------------

 14:     This code demonstrates how one may solve a nonlinear problem
 15:     with pseudo-timestepping. In this simple example, the pseudo-timestep
 16:     is the same for all grid points, i.e., this is equivalent to using
 17:     the backward Euler method with a variable timestep.

 19:     Note: This example does not require pseudo-timestepping since it
 20:     is an easy nonlinear problem, but it is included to demonstrate how
 21:     the pseudo-timestepping may be done.

 23:     See snes/examples/tutorials/ex4.c[ex4f.F] and
 24:     snes/examples/tutorials/ex5.c[ex5f.F] where the problem is described
 25:     and solved using Newton's method alone.

 27:   ----------------------------------------------------------------------------- */
 28: /*
 29:     Include "petscts.h" to use the PETSc timestepping routines. Note that
 30:     this file automatically includes "petscsys.h" and other lower-level
 31:     PETSc include files.
 32: */
 33: #include <petscts.h>

 35: /*
 36:   Create an application context to contain data needed by the
 37:   application-provided call-back routines, FormJacobian() and
 38:   FormFunction().
 39: */
 40: typedef struct {
 41:   PetscReal param;          /* test problem parameter */
 42:   PetscInt  mx;             /* Discretization in x-direction */
 43:   PetscInt  my;             /* Discretization in y-direction */
 44: } AppCtx;

 46: /*
 47:    User-defined routines
 48: */
 49: extern PetscErrorCode  FormJacobian(TS,PetscReal,Vec,Mat,Mat,void*), FormFunction(TS,PetscReal,Vec,Vec,void*), FormInitialGuess(Vec,AppCtx*);

 53: int main(int argc,char **argv)
 54: {
 55:   TS             ts;                 /* timestepping context */
 56:   Vec            x,r;               /* solution, residual vectors */
 57:   Mat            J;                  /* Jacobian matrix */
 58:   AppCtx         user;               /* user-defined work context */
 59:   PetscInt       its,N;                /* iterations for convergence */
 61:   PetscReal      param_max = 6.81,param_min = 0.,dt;
 62:   PetscReal      ftime;
 63:   PetscMPIInt    size;

 65:   PetscInitialize(&argc,&argv,NULL,help);
 66:   MPI_Comm_size(PETSC_COMM_WORLD,&size);
 67:   if (size != 1) SETERRQ(PETSC_COMM_WORLD,PETSC_ERR_SUP,"This is a uniprocessor example only");

 69:   user.mx    = 4;
 70:   user.my    = 4;
 71:   user.param = 6.0;

 73:   /*
 74:      Allow user to set the grid dimensions and nonlinearity parameter at run-time
 75:   */
 76:   PetscOptionsGetInt(NULL,"-mx",&user.mx,NULL);
 77:   PetscOptionsGetInt(NULL,"-my",&user.my,NULL);
 78:   N  = user.mx*user.my;
 79:   dt = .5/PetscMax(user.mx,user.my);
 80:   PetscOptionsGetReal(NULL,"-param",&user.param,NULL);
 81:   if (user.param >= param_max || user.param <= param_min) SETERRQ(PETSC_COMM_SELF,1,"Parameter is out of range");

 83:   /*
 84:       Create vectors to hold the solution and function value
 85:   */
 86:   VecCreateSeq(PETSC_COMM_SELF,N,&x);
 87:   VecDuplicate(x,&r);

 89:   /*
 90:     Create matrix to hold Jacobian. Preallocate 5 nonzeros per row
 91:     in the sparse matrix. Note that this is not the optimal strategy; see
 92:     the Performance chapter of the users manual for information on
 93:     preallocating memory in sparse matrices.
 94:   */
 95:   MatCreateSeqAIJ(PETSC_COMM_SELF,N,N,5,0,&J);

 97:   /*
 98:      Create timestepper context
 99:   */
100:   TSCreate(PETSC_COMM_WORLD,&ts);
101:   TSSetProblemType(ts,TS_NONLINEAR);

103:   /*
104:      Tell the timestepper context where to compute solutions
105:   */
106:   TSSetSolution(ts,x);

108:   /*
109:      Provide the call-back for the nonlinear function we are
110:      evaluating. Thus whenever the timestepping routines need the
111:      function they will call this routine. Note the final argument
112:      is the application context used by the call-back functions.
113:   */
114:   TSSetRHSFunction(ts,NULL,FormFunction,&user);

116:   /*
117:      Set the Jacobian matrix and the function used to compute
118:      Jacobians.
119:   */
120:   TSSetRHSJacobian(ts,J,J,FormJacobian,&user);

122:   /*
123:        Form the initial guess for the problem
124:   */
125:   FormInitialGuess(x,&user);

127:   /*
128:        This indicates that we are using pseudo timestepping to
129:      find a steady state solution to the nonlinear problem.
130:   */
131:   TSSetType(ts,TSPSEUDO);

133:   /*
134:        Set the initial time to start at (this is arbitrary for
135:      steady state problems); and the initial timestep given above
136:   */
137:   TSSetInitialTimeStep(ts,0.0,dt);

139:   /*
140:       Set a large number of timesteps and final duration time
141:      to insure convergence to steady state.
142:   */
143:   TSSetDuration(ts,1000,1.e12);

145:   /*
146:       Use the default strategy for increasing the timestep
147:   */
148:   TSPseudoSetTimeStep(ts,TSPseudoTimeStepDefault,0);

150:   /*
151:       Set any additional options from the options database. This
152:      includes all options for the nonlinear and linear solvers used
153:      internally the timestepping routines.
154:   */
155:   TSSetFromOptions(ts);

157:   TSSetUp(ts);

159:   /*
160:       Perform the solve. This is where the timestepping takes place.
161:   */
162:   TSSolve(ts,x);
163:   TSGetSolveTime(ts,&ftime);

165:   /*
166:       Get the number of steps
167:   */
168:   TSGetTimeStepNumber(ts,&its);

170:   PetscPrintf(PETSC_COMM_WORLD,"Number of pseudo timesteps = %D final time %4.2e\n",its,(double)ftime);

172:   /*
173:      Free the data structures constructed above
174:   */
175:   VecDestroy(&x);
176:   VecDestroy(&r);
177:   MatDestroy(&J);
178:   TSDestroy(&ts);
179:   PetscFinalize();

181:   return 0;
182: }
183: /* ------------------------------------------------------------------ */
184: /*           Bratu (Solid Fuel Ignition) Test Problem                 */
185: /* ------------------------------------------------------------------ */

187: /* --------------------  Form initial approximation ----------------- */

191: PetscErrorCode FormInitialGuess(Vec X,AppCtx *user)
192: {
193:   PetscInt       i,j,row,mx,my;
195:   PetscReal      one = 1.0,lambda;
196:   PetscReal      temp1,temp,hx,hy;
197:   PetscScalar    *x;

199:   mx     = user->mx;
200:   my     = user->my;
201:   lambda = user->param;

203:   hx = one / (PetscReal)(mx-1);
204:   hy = one / (PetscReal)(my-1);

206:   VecGetArray(X,&x);
207:   temp1 = lambda/(lambda + one);
208:   for (j=0; j<my; j++) {
209:     temp = (PetscReal)(PetscMin(j,my-j-1))*hy;
210:     for (i=0; i<mx; i++) {
211:       row = i + j*mx;
212:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
213:         x[row] = 0.0;
214:         continue;
215:       }
216:       x[row] = temp1*PetscSqrtReal(PetscMin((PetscReal)(PetscMin(i,mx-i-1))*hx,temp));
217:     }
218:   }
219:   VecRestoreArray(X,&x);
220:   return 0;
221: }
222: /* --------------------  Evaluate Function F(x) --------------------- */

226: PetscErrorCode FormFunction(TS ts,PetscReal t,Vec X,Vec F,void *ptr)
227: {
228:   AppCtx            *user = (AppCtx*)ptr;
229:   PetscErrorCode    ierr;
230:   PetscInt          i,j,row,mx,my;
231:   PetscReal         two = 2.0,one = 1.0,lambda;
232:   PetscReal         hx,hy,hxdhy,hydhx;
233:   PetscScalar       ut,ub,ul,ur,u,uxx,uyy,sc,*f;
234:   const PetscScalar *x;

236:   mx     = user->mx;
237:   my     = user->my;
238:   lambda = user->param;

240:   hx    = one / (PetscReal)(mx-1);
241:   hy    = one / (PetscReal)(my-1);
242:   sc    = hx*hy;
243:   hxdhy = hx/hy;
244:   hydhx = hy/hx;

246:   VecGetArrayRead(X,&x);
247:   VecGetArray(F,&f);
248:   for (j=0; j<my; j++) {
249:     for (i=0; i<mx; i++) {
250:       row = i + j*mx;
251:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
252:         f[row] = x[row];
253:         continue;
254:       }
255:       u      = x[row];
256:       ub     = x[row - mx];
257:       ul     = x[row - 1];
258:       ut     = x[row + mx];
259:       ur     = x[row + 1];
260:       uxx    = (-ur + two*u - ul)*hydhx;
261:       uyy    = (-ut + two*u - ub)*hxdhy;
262:       f[row] = -uxx + -uyy + sc*lambda*PetscExpScalar(u);
263:     }
264:   }
265:   VecRestoreArrayRead(X,&x);
266:   VecRestoreArray(F,&f);
267:   return 0;
268: }
269: /* --------------------  Evaluate Jacobian F'(x) -------------------- */

273: /*
274:    Calculate the Jacobian matrix J(X,t).

276:    Note: We put the Jacobian in the preconditioner storage B instead of J. This
277:    way we can give the -snes_mf_operator flag to check our work. This replaces
278:    J with a finite difference approximation, using our analytic Jacobian B for
279:    the preconditioner.
280: */
281: PetscErrorCode FormJacobian(TS ts,PetscReal t,Vec X,Mat J,Mat B,void *ptr)
282: {
283:   AppCtx            *user = (AppCtx*)ptr;
284:   PetscInt          i,j,row,mx,my,col[5];
285:   PetscErrorCode    ierr;
286:   PetscScalar       two = 2.0,one = 1.0,lambda,v[5],sc;
287:   const PetscScalar *x;
288:   PetscReal         hx,hy,hxdhy,hydhx;


291:   mx     = user->mx;
292:   my     = user->my;
293:   lambda = user->param;

295:   hx    = 1.0 / (PetscReal)(mx-1);
296:   hy    = 1.0 / (PetscReal)(my-1);
297:   sc    = hx*hy;
298:   hxdhy = hx/hy;
299:   hydhx = hy/hx;

301:   VecGetArrayRead(X,&x);
302:   for (j=0; j<my; j++) {
303:     for (i=0; i<mx; i++) {
304:       row = i + j*mx;
305:       if (i == 0 || j == 0 || i == mx-1 || j == my-1) {
306:         MatSetValues(B,1,&row,1,&row,&one,INSERT_VALUES);
307:         continue;
308:       }
309:       v[0] = hxdhy; col[0] = row - mx;
310:       v[1] = hydhx; col[1] = row - 1;
311:       v[2] = -two*(hydhx + hxdhy) + sc*lambda*PetscExpScalar(x[row]); col[2] = row;
312:       v[3] = hydhx; col[3] = row + 1;
313:       v[4] = hxdhy; col[4] = row + mx;
314:       MatSetValues(B,1,&row,5,col,v,INSERT_VALUES);
315:     }
316:   }
317:   VecRestoreArrayRead(X,&x);
318:   MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
319:   MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
320:   if (J != B) {
321:     MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
322:     MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
323:   }
324:   return 0;
325: }