Actual source code: ts.c

petsc-dev 2014-02-02
Report Typos and Errors
  2: #include <petsc-private/tsimpl.h>        /*I "petscts.h"  I*/
  3: #include <petscdmshell.h>
  4: #include <petscdmda.h>
  5: #include <petscviewer.h>
  6: #include <petscdraw.h>

  8: /* Logging support */
  9: PetscClassId  TS_CLASSID, DMTS_CLASSID;
 10: PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;

 12: const char *const TSExactFinalTimeOptions[] = {"STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};

 16: /*
 17:   TSSetTypeFromOptions - Sets the type of ts from user options.

 19:   Collective on TS

 21:   Input Parameter:
 22: . ts - The ts

 24:   Level: intermediate

 26: .keywords: TS, set, options, database, type
 27: .seealso: TSSetFromOptions(), TSSetType()
 28: */
 29: static PetscErrorCode TSSetTypeFromOptions(TS ts)
 30: {
 31:   PetscBool      opt;
 32:   const char     *defaultType;
 33:   char           typeName[256];

 37:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
 38:   else defaultType = TSEULER;

 40:   if (!TSRegisterAllCalled) {TSRegisterAll();}
 41:   PetscOptionsFList("-ts_type", "TS method"," TSSetType", TSList, defaultType, typeName, 256, &opt);
 42:   if (opt) {
 43:     TSSetType(ts, typeName);
 44:   } else {
 45:     TSSetType(ts, defaultType);
 46:   }
 47:   return(0);
 48: }

 50: struct _n_TSMonitorDrawCtx {
 51:   PetscViewer   viewer;
 52:   PetscDrawAxis axis;
 53:   Vec           initialsolution;
 54:   PetscBool     showinitial;
 55:   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
 56:   PetscBool     showtimestepandtime;
 57:   int           color;
 58: };

 62: /*@
 63:    TSSetFromOptions - Sets various TS parameters from user options.

 65:    Collective on TS

 67:    Input Parameter:
 68: .  ts - the TS context obtained from TSCreate()

 70:    Options Database Keys:
 71: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSGL, TSSSP
 72: .  -ts_max_steps maxsteps - maximum number of time-steps to take
 73: .  -ts_final_time time - maximum time to compute to
 74: .  -ts_dt dt - initial time step
 75: .  -ts_monitor - print information at each timestep
 76: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
 77: .  -ts_monitor_lg_solution - Monitor solution graphically
 78: .  -ts_monitor_lg_error - Monitor error graphically
 79: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
 80: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
 81: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
 82: .  -ts_monitor_draw_solution - Monitor solution graphically
 83: .  -ts_monitor_draw_solution_phase - Monitor solution graphically with phase diagram
 84: .  -ts_monitor_draw_error - Monitor error graphically
 85: .  -ts_monitor_solution_binary <filename> - Save each solution to a binary file
 86: -  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts

 88:    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified

 90:    Level: beginner

 92: .keywords: TS, timestep, set, options, database

 94: .seealso: TSGetType()
 95: @*/
 96: PetscErrorCode  TSSetFromOptions(TS ts)
 97: {
 98:   PetscBool              opt,flg;
 99:   PetscErrorCode         ierr;
100:   PetscViewer            monviewer;
101:   char                   monfilename[PETSC_MAX_PATH_LEN];
102:   SNES                   snes;
103:   TSAdapt                adapt;
104:   PetscReal              time_step;
105:   TSExactFinalTimeOption eftopt;
106:   char                   dir[16];

110:   PetscObjectOptionsBegin((PetscObject)ts);
111:   /* Handle TS type options */
112:   TSSetTypeFromOptions(ts);

114:   /* Handle generic TS options */
115:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);
116:   PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);
117:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
118:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
119:   if (flg) {
120:     TSSetTimeStep(ts,time_step);
121:   }
122:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
123:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
124:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
125:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
126:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
127:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
128:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

130: #if defined(PETSC_HAVE_SAWS)
131:   {
132:   PetscBool set;
133:   flg  = PETSC_FALSE;
134:   PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
135:   if (set) {
136:     PetscObjectSAWsSetBlock((PetscObject)ts,flg);
137:   }
138:   }
139: #endif

141:   /* Monitor options */
142:   PetscOptionsString("-ts_monitor","Monitor timestep size","TSMonitorDefault","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
143:   if (flg) {
144:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)ts),monfilename,&monviewer);
145:     TSMonitorSet(ts,TSMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
146:   }
147:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
148:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

150:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
151:   if (opt) {
152:     TSMonitorLGCtx ctx;
153:     PetscInt       howoften = 1;

155:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
156:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
157:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
158:   }
159:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
160:   if (opt) {
161:     TSMonitorLGCtx ctx;
162:     PetscInt       howoften = 1;

164:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
165:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
166:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
167:   }
168:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
169:   if (opt) {
170:     TSMonitorLGCtx ctx;
171:     PetscInt       howoften = 1;

173:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
174:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
175:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
176:   }
177:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
178:   if (opt) {
179:     TSMonitorLGCtx ctx;
180:     PetscInt       howoften = 1;

182:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
183:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
184:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
185:   }
186:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
187:   if (opt) {
188:     TSMonitorLGCtx ctx;
189:     PetscInt       howoften = 1;

191:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
192:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
193:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
194:   }
195:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
196:   if (opt) {
197:     TSMonitorSPEigCtx ctx;
198:     PetscInt          howoften = 1;

200:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
201:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
202:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
203:   }
204:   opt  = PETSC_FALSE;
205:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
206:   if (opt) {
207:     TSMonitorDrawCtx ctx;
208:     PetscInt         howoften = 1;

210:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
211:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
212:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
213:   }
214:   opt  = PETSC_FALSE;
215:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
216:   if (opt) {
217:     TSMonitorDrawCtx ctx;
218:     PetscReal        bounds[4];
219:     PetscInt         n = 4;
220:     PetscDraw        draw;

222:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
223:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
224:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,1,&ctx);
225:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
226:     PetscDrawClear(draw);
227:     PetscDrawAxisCreate(draw,&ctx->axis);
228:     PetscDrawAxisSetLimits(ctx->axis,bounds[0],bounds[2],bounds[1],bounds[3]);
229:     PetscDrawAxisSetLabels(ctx->axis,"Phase Diagram","Variable 1","Variable 2");
230:     PetscDrawAxisDraw(ctx->axis);
231:     /* PetscDrawSetCoordinates(draw,bounds[0],bounds[1],bounds[2],bounds[3]); */
232:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
233:   }
234:   opt  = PETSC_FALSE;
235:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
236:   if (opt) {
237:     TSMonitorDrawCtx ctx;
238:     PetscInt         howoften = 1;

240:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
241:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
242:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
243:   }
244:   opt  = PETSC_FALSE;
245:   PetscOptionsString("-ts_monitor_solution_binary","Save each solution to a binary file","TSMonitorSolutionBinary",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
246:   if (flg) {
247:     PetscViewer ctx;
248:     if (monfilename[0]) {
249:       PetscViewerBinaryOpen(PetscObjectComm((PetscObject)ts),monfilename,FILE_MODE_WRITE,&ctx);
250:       TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
251:     } else {
252:       ctx = PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)ts));
253:       TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))NULL);
254:     }
255:   }
256:   opt  = PETSC_FALSE;
257:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
258:   if (flg) {
259:     const char *ptr,*ptr2;
260:     char       *filetemplate;
261:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
262:     /* Do some cursory validation of the input. */
263:     PetscStrstr(monfilename,"%",(char**)&ptr);
264:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
265:     for (ptr++; ptr && *ptr; ptr++) {
266:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
267:       if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
268:       if (ptr2) break;
269:     }
270:     PetscStrallocpy(monfilename,&filetemplate);
271:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
272:   }

274:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
275:   if (flg) {
276:     TSMonitorDMDARayCtx *rayctx;
277:     int                  ray = 0;
278:     DMDADirection        ddir;
279:     DM                   da;
280:     PetscMPIInt          rank;

282:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
283:     if (dir[0] == 'x') ddir = DMDA_X;
284:     else if (dir[0] == 'y') ddir = DMDA_Y;
285:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
286:     sscanf(dir+2,"%d",&ray);

288:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
289:     PetscNew(&rayctx);
290:     TSGetDM(ts,&da);
291:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
292:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
293:     if (!rank) {
294:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
295:     }
296:     rayctx->lgctx = NULL;
297:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
298:   }
299:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
300:   if (flg) {
301:     TSMonitorDMDARayCtx *rayctx;
302:     int                 ray = 0;
303:     DMDADirection       ddir;
304:     DM                  da;
305:     PetscInt            howoften = 1;

307:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
308:     if      (dir[0] == 'x') ddir = DMDA_X;
309:     else if (dir[0] == 'y') ddir = DMDA_Y;
310:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
311:     sscanf(dir+2, "%d", &ray);

313:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);
314:     PetscNew(&rayctx);
315:     TSGetDM(ts, &da);
316:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
317:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
318:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
319:   }

321:   /*
322:      This code is all wrong. One is creating objects inside the TSSetFromOptions() so if run with the options gui
323:      will bleed memory. Also one is using a PetscOptionsBegin() inside a PetscOptionsBegin()
324:   */
325:   TSGetAdapt(ts,&adapt);
326:   TSAdaptSetFromOptions(adapt);

328:   TSGetSNES(ts,&snes);
329:   if (ts->problem_type == TS_LINEAR) {SNESSetType(snes,SNESKSPONLY);}

331:   /* Handle specific TS options */
332:   if (ts->ops->setfromoptions) {
333:     (*ts->ops->setfromoptions)(ts);
334:   }

336:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
337:   PetscObjectProcessOptionsHandlers((PetscObject)ts);
338:   PetscOptionsEnd();
339:   return(0);
340: }

345: /*@
346:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
347:       set with TSSetRHSJacobian().

349:    Collective on TS and Vec

351:    Input Parameters:
352: +  ts - the TS context
353: .  t - current timestep
354: -  U - input vector

356:    Output Parameters:
357: +  A - Jacobian matrix
358: .  B - optional preconditioning matrix
359: -  flag - flag indicating matrix structure

361:    Notes:
362:    Most users should not need to explicitly call this routine, as it
363:    is used internally within the nonlinear solvers.

365:    See KSPSetOperators() for important information about setting the
366:    flag parameter.

368:    Level: developer

370: .keywords: SNES, compute, Jacobian, matrix

372: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
373: @*/
374: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg)
375: {
377:   PetscObjectState Ustate;
378:   DM             dm;
379:   DMTS           tsdm;
380:   TSRHSJacobian  rhsjacobianfunc;
381:   void           *ctx;
382:   TSIJacobian    ijacobianfunc;

388:   TSGetDM(ts,&dm);
389:   DMGetDMTS(dm,&tsdm);
390:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
391:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
392:   PetscObjectStateGet((PetscObject)U,&Ustate);
393:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate))) {
394:     *flg = ts->rhsjacobian.mstructure;
395:     return(0);
396:   }

398:   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

400:   if (ts->rhsjacobian.reuse) {
401:     MatShift(*A,-ts->rhsjacobian.shift);
402:     MatScale(*A,1./ts->rhsjacobian.scale);
403:     if (*A != *B) {
404:       MatShift(*B,-ts->rhsjacobian.shift);
405:       MatScale(*B,1./ts->rhsjacobian.scale);
406:     }
407:     ts->rhsjacobian.shift = 0;
408:     ts->rhsjacobian.scale = 1.;
409:   }

411:   if (rhsjacobianfunc) {
412:     PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);
413:     *flg = DIFFERENT_NONZERO_PATTERN;
414:     PetscStackPush("TS user Jacobian function");
415:     (*rhsjacobianfunc)(ts,t,U,A,B,flg,ctx);
416:     PetscStackPop;
417:     PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);
418:     /* make sure user returned a correct Jacobian and preconditioner */
421:   } else {
422:     MatZeroEntries(*A);
423:     if (*A != *B) {MatZeroEntries(*B);}
424:     *flg = SAME_NONZERO_PATTERN;
425:   }
426:   ts->rhsjacobian.time       = t;
427:   ts->rhsjacobian.X          = U;
428:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
429:   ts->rhsjacobian.mstructure = *flg;
430:   return(0);
431: }

435: /*@
436:    TSComputeRHSFunction - Evaluates the right-hand-side function.

438:    Collective on TS and Vec

440:    Input Parameters:
441: +  ts - the TS context
442: .  t - current time
443: -  U - state vector

445:    Output Parameter:
446: .  y - right hand side

448:    Note:
449:    Most users should not need to explicitly call this routine, as it
450:    is used internally within the nonlinear solvers.

452:    Level: developer

454: .keywords: TS, compute

456: .seealso: TSSetRHSFunction(), TSComputeIFunction()
457: @*/
458: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
459: {
461:   TSRHSFunction  rhsfunction;
462:   TSIFunction    ifunction;
463:   void           *ctx;
464:   DM             dm;

470:   TSGetDM(ts,&dm);
471:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
472:   DMTSGetIFunction(dm,&ifunction,NULL);

474:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

476:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
477:   if (rhsfunction) {
478:     PetscStackPush("TS user right-hand-side function");
479:     (*rhsfunction)(ts,t,U,y,ctx);
480:     PetscStackPop;
481:   } else {
482:     VecZeroEntries(y);
483:   }

485:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
486:   return(0);
487: }

491: /*@
492:    TSComputeSolutionFunction - Evaluates the solution function.

494:    Collective on TS and Vec

496:    Input Parameters:
497: +  ts - the TS context
498: -  t - current time

500:    Output Parameter:
501: .  U - the solution

503:    Note:
504:    Most users should not need to explicitly call this routine, as it
505:    is used internally within the nonlinear solvers.

507:    Level: developer

509: .keywords: TS, compute

511: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
512: @*/
513: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
514: {
515:   PetscErrorCode     ierr;
516:   TSSolutionFunction solutionfunction;
517:   void               *ctx;
518:   DM                 dm;

523:   TSGetDM(ts,&dm);
524:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

526:   if (solutionfunction) {
527:     PetscStackPush("TS user solution function");
528:     (*solutionfunction)(ts,t,U,ctx);
529:     PetscStackPop;
530:   }
531:   return(0);
532: }
535: /*@
536:    TSComputeForcingFunction - Evaluates the forcing function.

538:    Collective on TS and Vec

540:    Input Parameters:
541: +  ts - the TS context
542: -  t - current time

544:    Output Parameter:
545: .  U - the function value

547:    Note:
548:    Most users should not need to explicitly call this routine, as it
549:    is used internally within the nonlinear solvers.

551:    Level: developer

553: .keywords: TS, compute

555: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
556: @*/
557: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
558: {
559:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
560:   void               *ctx;
561:   DM                 dm;

566:   TSGetDM(ts,&dm);
567:   DMTSGetForcingFunction(dm,&forcing,&ctx);

569:   if (forcing) {
570:     PetscStackPush("TS user forcing function");
571:     (*forcing)(ts,t,U,ctx);
572:     PetscStackPop;
573:   }
574:   return(0);
575: }

579: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
580: {
581:   Vec            F;

585:   *Frhs = NULL;
586:   TSGetIFunction(ts,&F,NULL,NULL);
587:   if (!ts->Frhs) {
588:     VecDuplicate(F,&ts->Frhs);
589:   }
590:   *Frhs = ts->Frhs;
591:   return(0);
592: }

596: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
597: {
598:   Mat            A,B;

602:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
603:   if (Arhs) {
604:     if (!ts->Arhs) {
605:       MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
606:     }
607:     *Arhs = ts->Arhs;
608:   }
609:   if (Brhs) {
610:     if (!ts->Brhs) {
611:       if (A != B) {
612:         MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
613:       } else {
614:         ts->Brhs = ts->Arhs;
615:         PetscObjectReference((PetscObject)ts->Arhs);
616:       }
617:     }
618:     *Brhs = ts->Brhs;
619:   }
620:   return(0);
621: }

625: /*@
626:    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0

628:    Collective on TS and Vec

630:    Input Parameters:
631: +  ts - the TS context
632: .  t - current time
633: .  U - state vector
634: .  Udot - time derivative of state vector
635: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

637:    Output Parameter:
638: .  Y - right hand side

640:    Note:
641:    Most users should not need to explicitly call this routine, as it
642:    is used internally within the nonlinear solvers.

644:    If the user did did not write their equations in implicit form, this
645:    function recasts them in implicit form.

647:    Level: developer

649: .keywords: TS, compute

651: .seealso: TSSetIFunction(), TSComputeRHSFunction()
652: @*/
653: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
654: {
656:   TSIFunction    ifunction;
657:   TSRHSFunction  rhsfunction;
658:   void           *ctx;
659:   DM             dm;


667:   TSGetDM(ts,&dm);
668:   DMTSGetIFunction(dm,&ifunction,&ctx);
669:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

671:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

673:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
674:   if (ifunction) {
675:     PetscStackPush("TS user implicit function");
676:     (*ifunction)(ts,t,U,Udot,Y,ctx);
677:     PetscStackPop;
678:   }
679:   if (imex) {
680:     if (!ifunction) {
681:       VecCopy(Udot,Y);
682:     }
683:   } else if (rhsfunction) {
684:     if (ifunction) {
685:       Vec Frhs;
686:       TSGetRHSVec_Private(ts,&Frhs);
687:       TSComputeRHSFunction(ts,t,U,Frhs);
688:       VecAXPY(Y,-1,Frhs);
689:     } else {
690:       TSComputeRHSFunction(ts,t,U,Y);
691:       VecAYPX(Y,-1,Udot);
692:     }
693:   }
694:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
695:   return(0);
696: }

700: /*@
701:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

703:    Collective on TS and Vec

705:    Input
706:       Input Parameters:
707: +  ts - the TS context
708: .  t - current timestep
709: .  U - state vector
710: .  Udot - time derivative of state vector
711: .  shift - shift to apply, see note below
712: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

714:    Output Parameters:
715: +  A - Jacobian matrix
716: .  B - optional preconditioning matrix
717: -  flag - flag indicating matrix structure

719:    Notes:
720:    If F(t,U,Udot)=0 is the DAE, the required Jacobian is

722:    dF/dU + shift*dF/dUdot

724:    Most users should not need to explicitly call this routine, as it
725:    is used internally within the nonlinear solvers.

727:    Level: developer

729: .keywords: TS, compute, Jacobian, matrix

731: .seealso:  TSSetIJacobian()
732: @*/
733: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,PetscBool imex)
734: {
736:   TSIJacobian    ijacobian;
737:   TSRHSJacobian  rhsjacobian;
738:   DM             dm;
739:   void           *ctx;


751:   TSGetDM(ts,&dm);
752:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
753:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

755:   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

757:   *flg = SAME_NONZERO_PATTERN;  /* In case we're solving a linear problem in which case it wouldn't get initialized below. */
758:   PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);
759:   if (ijacobian) {
760:     *flg = DIFFERENT_NONZERO_PATTERN;
761:     PetscStackPush("TS user implicit Jacobian");
762:     (*ijacobian)(ts,t,U,Udot,shift,A,B,flg,ctx);
763:     PetscStackPop;
764:     /* make sure user returned a correct Jacobian and preconditioner */
767:   }
768:   if (imex) {
769:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
770:       MatZeroEntries(*A);
771:       MatShift(*A,shift);
772:       if (*A != *B) {
773:         MatZeroEntries(*B);
774:         MatShift(*B,shift);
775:       }
776:       *flg = SAME_PRECONDITIONER;
777:     }
778:   } else {
779:     Mat Arhs = NULL,Brhs = NULL;
780:     MatStructure flg2;
781:     if (rhsjacobian) {
782:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
783:       TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);
784:     }
785:     if (Arhs == *A) {           /* No IJacobian, so we only have the RHS matrix */
786:       ts->rhsjacobian.scale = -1;
787:       ts->rhsjacobian.shift = shift;
788:       MatScale(*A,-1);
789:       MatShift(*A,shift);
790:       if (*A != *B) {
791:         MatScale(*B,-1);
792:         MatShift(*B,shift);
793:       }
794:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
795:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
796:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
797:         MatZeroEntries(*A);
798:         MatShift(*A,shift);
799:         if (*A != *B) {
800:           MatZeroEntries(*B);
801:           MatShift(*B,shift);
802:         }
803:       }
804:       MatAXPY(*A,-1,Arhs,axpy);
805:       if (*A != *B) {
806:         MatAXPY(*B,-1,Brhs,axpy);
807:       }
808:       *flg = PetscMin(*flg,flg2);
809:     }
810:   }

812:   PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);
813:   return(0);
814: }

818: /*@C
819:     TSSetRHSFunction - Sets the routine for evaluating the function,
820:     where U_t = G(t,u).

822:     Logically Collective on TS

824:     Input Parameters:
825: +   ts - the TS context obtained from TSCreate()
826: .   r - vector to put the computed right hand side (or NULL to have it created)
827: .   f - routine for evaluating the right-hand-side function
828: -   ctx - [optional] user-defined context for private data for the
829:           function evaluation routine (may be NULL)

831:     Calling sequence of func:
832: $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);

834: +   t - current timestep
835: .   u - input vector
836: .   F - function vector
837: -   ctx - [optional] user-defined function context

839:     Level: beginner

841: .keywords: TS, timestep, set, right-hand-side, function

843: .seealso: TSSetRHSJacobian(), TSSetIJacobian()
844: @*/
845: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
846: {
848:   SNES           snes;
849:   Vec            ralloc = NULL;
850:   DM             dm;


856:   TSGetDM(ts,&dm);
857:   DMTSSetRHSFunction(dm,f,ctx);
858:   TSGetSNES(ts,&snes);
859:   if (!r && !ts->dm && ts->vec_sol) {
860:     VecDuplicate(ts->vec_sol,&ralloc);
861:     r    = ralloc;
862:   }
863:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
864:   VecDestroy(&ralloc);
865:   return(0);
866: }

870: /*@C
871:     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE

873:     Logically Collective on TS

875:     Input Parameters:
876: +   ts - the TS context obtained from TSCreate()
877: .   f - routine for evaluating the solution
878: -   ctx - [optional] user-defined context for private data for the
879:           function evaluation routine (may be NULL)

881:     Calling sequence of func:
882: $     func (TS ts,PetscReal t,Vec u,void *ctx);

884: +   t - current timestep
885: .   u - output vector
886: -   ctx - [optional] user-defined function context

888:     Notes:
889:     This routine is used for testing accuracy of time integration schemes when you already know the solution.
890:     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
891:     create closed-form solutions with non-physical forcing terms.

893:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

895:     Level: beginner

897: .keywords: TS, timestep, set, right-hand-side, function

899: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
900: @*/
901: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
902: {
904:   DM             dm;

908:   TSGetDM(ts,&dm);
909:   DMTSSetSolutionFunction(dm,f,ctx);
910:   return(0);
911: }

915: /*@C
916:     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE

918:     Logically Collective on TS

920:     Input Parameters:
921: +   ts - the TS context obtained from TSCreate()
922: .   f - routine for evaluating the forcing function
923: -   ctx - [optional] user-defined context for private data for the
924:           function evaluation routine (may be NULL)

926:     Calling sequence of func:
927: $     func (TS ts,PetscReal t,Vec u,void *ctx);

929: +   t - current timestep
930: .   u - output vector
931: -   ctx - [optional] user-defined function context

933:     Notes:
934:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
935:     create closed-form solutions with a non-physical forcing term.

937:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

939:     Level: beginner

941: .keywords: TS, timestep, set, right-hand-side, function

943: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
944: @*/
945: PetscErrorCode  TSSetForcingFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
946: {
948:   DM             dm;

952:   TSGetDM(ts,&dm);
953:   DMTSSetForcingFunction(dm,f,ctx);
954:   return(0);
955: }

959: /*@C
960:    TSSetRHSJacobian - Sets the function to compute the Jacobian of F,
961:    where U_t = G(U,t), as well as the location to store the matrix.

963:    Logically Collective on TS

965:    Input Parameters:
966: +  ts  - the TS context obtained from TSCreate()
967: .  Amat - (approximate) Jacobian matrix
968: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
969: .  f   - the Jacobian evaluation routine
970: -  ctx - [optional] user-defined context for private data for the
971:          Jacobian evaluation routine (may be NULL)

973:    Calling sequence of func:
974: $     func (TS ts,PetscReal t,Vec u,Mat *A,Mat *B,MatStructure *flag,void *ctx);

976: +  t - current timestep
977: .  u - input vector
978: .  Amat - (approximate) Jacobian matrix
979: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
980: .  flag - flag indicating information about the preconditioner matrix
981:           structure (same as flag in KSPSetOperators())
982: -  ctx - [optional] user-defined context for matrix evaluation routine

984:    Notes:
985:    See KSPSetOperators() for important information about setting the flag
986:    output parameter in the routine func().  Be sure to read this information!

988:    The routine func() takes Mat * as the matrix arguments rather than Mat.
989:    This allows the matrix evaluation routine to replace A and/or B with a
990:    completely new matrix structure (not just different matrix elements)
991:    when appropriate, for instance, if the nonzero structure is changing
992:    throughout the global iterations.

994:    Level: beginner

996: .keywords: TS, timestep, set, right-hand-side, Jacobian

998: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse()

1000: @*/
1001: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1002: {
1004:   SNES           snes;
1005:   DM             dm;
1006:   TSIJacobian    ijacobian;


1015:   TSGetDM(ts,&dm);
1016:   DMTSSetRHSJacobian(dm,f,ctx);
1017:   if (f == TSComputeRHSJacobianConstant) {
1018:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1019:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1020:   }
1021:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1022:   TSGetSNES(ts,&snes);
1023:   if (!ijacobian) {
1024:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1025:   }
1026:   if (Amat) {
1027:     PetscObjectReference((PetscObject)Amat);
1028:     MatDestroy(&ts->Arhs);

1030:     ts->Arhs = Amat;
1031:   }
1032:   if (Pmat) {
1033:     PetscObjectReference((PetscObject)Pmat);
1034:     MatDestroy(&ts->Brhs);

1036:     ts->Brhs = Pmat;
1037:   }
1038:   return(0);
1039: }


1044: /*@C
1045:    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.

1047:    Logically Collective on TS

1049:    Input Parameters:
1050: +  ts  - the TS context obtained from TSCreate()
1051: .  r   - vector to hold the residual (or NULL to have it created internally)
1052: .  f   - the function evaluation routine
1053: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1055:    Calling sequence of f:
1056: $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);

1058: +  t   - time at step/stage being solved
1059: .  u   - state vector
1060: .  u_t - time derivative of state vector
1061: .  F   - function vector
1062: -  ctx - [optional] user-defined context for matrix evaluation routine

1064:    Important:
1065:    The user MUST call either this routine, TSSetRHSFunction().  This routine must be used when not solving an ODE, for example a DAE.

1067:    Level: beginner

1069: .keywords: TS, timestep, set, DAE, Jacobian

1071: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1072: @*/
1073: PetscErrorCode  TSSetIFunction(TS ts,Vec res,TSIFunction f,void *ctx)
1074: {
1076:   SNES           snes;
1077:   Vec            resalloc = NULL;
1078:   DM             dm;


1084:   TSGetDM(ts,&dm);
1085:   DMTSSetIFunction(dm,f,ctx);

1087:   TSGetSNES(ts,&snes);
1088:   if (!res && !ts->dm && ts->vec_sol) {
1089:     VecDuplicate(ts->vec_sol,&resalloc);
1090:     res  = resalloc;
1091:   }
1092:   SNESSetFunction(snes,res,SNESTSFormFunction,ts);
1093:   VecDestroy(&resalloc);
1094:   return(0);
1095: }

1099: /*@C
1100:    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.

1102:    Not Collective

1104:    Input Parameter:
1105: .  ts - the TS context

1107:    Output Parameter:
1108: +  r - vector to hold residual (or NULL)
1109: .  func - the function to compute residual (or NULL)
1110: -  ctx - the function context (or NULL)

1112:    Level: advanced

1114: .keywords: TS, nonlinear, get, function

1116: .seealso: TSSetIFunction(), SNESGetFunction()
1117: @*/
1118: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1119: {
1121:   SNES           snes;
1122:   DM             dm;

1126:   TSGetSNES(ts,&snes);
1127:   SNESGetFunction(snes,r,NULL,NULL);
1128:   TSGetDM(ts,&dm);
1129:   DMTSGetIFunction(dm,func,ctx);
1130:   return(0);
1131: }

1135: /*@C
1136:    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.

1138:    Not Collective

1140:    Input Parameter:
1141: .  ts - the TS context

1143:    Output Parameter:
1144: +  r - vector to hold computed right hand side (or NULL)
1145: .  func - the function to compute right hand side (or NULL)
1146: -  ctx - the function context (or NULL)

1148:    Level: advanced

1150: .keywords: TS, nonlinear, get, function

1152: .seealso: TSSetRhsfunction(), SNESGetFunction()
1153: @*/
1154: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1155: {
1157:   SNES           snes;
1158:   DM             dm;

1162:   TSGetSNES(ts,&snes);
1163:   SNESGetFunction(snes,r,NULL,NULL);
1164:   TSGetDM(ts,&dm);
1165:   DMTSGetRHSFunction(dm,func,ctx);
1166:   return(0);
1167: }

1171: /*@C
1172:    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1173:         you provided with TSSetIFunction().

1175:    Logically Collective on TS

1177:    Input Parameters:
1178: +  ts  - the TS context obtained from TSCreate()
1179: .  Amat - (approximate) Jacobian matrix
1180: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1181: .  f   - the Jacobian evaluation routine
1182: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

1184:    Calling sequence of f:
1185: $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat *Amat,Mat *Pmat,MatStructure *flag,void *ctx);

1187: +  t    - time at step/stage being solved
1188: .  U    - state vector
1189: .  U_t  - time derivative of state vector
1190: .  a    - shift
1191: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1192: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1193: .  flag - flag indicating information about the preconditioner matrix
1194:           structure (same as flag in KSPSetOperators())
1195: -  ctx  - [optional] user-defined context for matrix evaluation routine

1197:    Notes:
1198:    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.

1200:    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1201:    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1202:    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1203:    a and vector W depend on the integration method, step size, and past states. For example with
1204:    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1205:    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt

1207:    Level: beginner

1209: .keywords: TS, timestep, DAE, Jacobian

1211: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault()

1213: @*/
1214: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1215: {
1217:   SNES           snes;
1218:   DM             dm;


1227:   TSGetDM(ts,&dm);
1228:   DMTSSetIJacobian(dm,f,ctx);

1230:   TSGetSNES(ts,&snes);
1231:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1232:   return(0);
1233: }

1237: /*@
1238:    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1239:    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1240:    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1241:    not been changed by the TS.

1243:    Logically Collective

1245:    Input Arguments:
1246: +  ts - TS context obtained from TSCreate()
1247: -  reuse - PETSC_TRUE if the RHS Jacobian

1249:    Level: intermediate

1251: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1252: @*/
1253: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1254: {
1256:   ts->rhsjacobian.reuse = reuse;
1257:   return(0);
1258: }

1262: /*@C
1263:   TSLoad - Loads a KSP that has been stored in binary  with KSPView().

1265:   Collective on PetscViewer

1267:   Input Parameters:
1268: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1269:            some related function before a call to TSLoad().
1270: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()

1272:    Level: intermediate

1274:   Notes:
1275:    The type is determined by the data in the file, any type set into the TS before this call is ignored.

1277:   Notes for advanced users:
1278:   Most users should not need to know the details of the binary storage
1279:   format, since TSLoad() and TSView() completely hide these details.
1280:   But for anyone who's interested, the standard binary matrix storage
1281:   format is
1282: .vb
1283:      has not yet been determined
1284: .ve

1286: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1287: @*/
1288: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1289: {
1291:   PetscBool      isbinary;
1292:   PetscInt       classid;
1293:   char           type[256];
1294:   DMTS           sdm;
1295:   DM             dm;

1300:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1301:   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

1303:   PetscViewerBinaryRead(viewer,&classid,1,PETSC_INT);
1304:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1305:   PetscViewerBinaryRead(viewer,type,256,PETSC_CHAR);
1306:   TSSetType(ts, type);
1307:   if (ts->ops->load) {
1308:     (*ts->ops->load)(ts,viewer);
1309:   }
1310:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1311:   DMLoad(dm,viewer);
1312:   TSSetDM(ts,dm);
1313:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1314:   VecLoad(ts->vec_sol,viewer);
1315:   DMGetDMTS(ts->dm,&sdm);
1316:   DMTSLoad(sdm,viewer);
1317:   return(0);
1318: }

1320: #include <petscdraw.h>
1321: #if defined(PETSC_HAVE_SAWS)
1322: #include <petscviewersaws.h>
1323: #endif
1326: /*@C
1327:     TSView - Prints the TS data structure.

1329:     Collective on TS

1331:     Input Parameters:
1332: +   ts - the TS context obtained from TSCreate()
1333: -   viewer - visualization context

1335:     Options Database Key:
1336: .   -ts_view - calls TSView() at end of TSStep()

1338:     Notes:
1339:     The available visualization contexts include
1340: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1341: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1342:          output where only the first processor opens
1343:          the file.  All other processors send their
1344:          data to the first processor to print.

1346:     The user can open an alternative visualization context with
1347:     PetscViewerASCIIOpen() - output to a specified file.

1349:     Level: beginner

1351: .keywords: TS, timestep, view

1353: .seealso: PetscViewerASCIIOpen()
1354: @*/
1355: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1356: {
1358:   TSType         type;
1359:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1360:   DMTS           sdm;
1361: #if defined(PETSC_HAVE_SAWS)
1362:   PetscBool      isams;
1363: #endif

1367:   if (!viewer) {
1368:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1369:   }

1373:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1374:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1375:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1376:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1377: #if defined(PETSC_HAVE_SAWS)
1378:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&isams);
1379: #endif
1380:   if (iascii) {
1381:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1382:     PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
1383:     PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
1384:     if (ts->problem_type == TS_NONLINEAR) {
1385:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
1386:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
1387:     }
1388:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
1389:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
1390:     DMGetDMTS(ts->dm,&sdm);
1391:     DMTSView(sdm,viewer);
1392:     if (ts->ops->view) {
1393:       PetscViewerASCIIPushTab(viewer);
1394:       (*ts->ops->view)(ts,viewer);
1395:       PetscViewerASCIIPopTab(viewer);
1396:     }
1397:   } else if (isstring) {
1398:     TSGetType(ts,&type);
1399:     PetscViewerStringSPrintf(viewer," %-7.7s",type);
1400:   } else if (isbinary) {
1401:     PetscInt    classid = TS_FILE_CLASSID;
1402:     MPI_Comm    comm;
1403:     PetscMPIInt rank;
1404:     char        type[256];

1406:     PetscObjectGetComm((PetscObject)ts,&comm);
1407:     MPI_Comm_rank(comm,&rank);
1408:     if (!rank) {
1409:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
1410:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
1411:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
1412:     }
1413:     if (ts->ops->view) {
1414:       (*ts->ops->view)(ts,viewer);
1415:     }
1416:     DMView(ts->dm,viewer);
1417:     VecView(ts->vec_sol,viewer);
1418:     DMGetDMTS(ts->dm,&sdm);
1419:     DMTSView(sdm,viewer);
1420:   } else if (isdraw) {
1421:     PetscDraw draw;
1422:     char      str[36];
1423:     PetscReal x,y,bottom,h;

1425:     PetscViewerDrawGetDraw(viewer,0,&draw);
1426:     PetscDrawGetCurrentPoint(draw,&x,&y);
1427:     PetscStrcpy(str,"TS: ");
1428:     PetscStrcat(str,((PetscObject)ts)->type_name);
1429:     PetscDrawBoxedString(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
1430:     bottom = y - h;
1431:     PetscDrawPushCurrentPoint(draw,x,bottom);
1432:     if (ts->ops->view) {
1433:       (*ts->ops->view)(ts,viewer);
1434:     }
1435:     PetscDrawPopCurrentPoint(draw);
1436: #if defined(PETSC_HAVE_SAWS)
1437:   } else if (isams) {
1438:     PetscMPIInt rank;
1439:     const char  *name;

1441:     PetscObjectGetName((PetscObject)ts,&name);
1442:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1443:     if (!((PetscObject)ts)->amsmem && !rank) {
1444:       char       dir[1024];

1446:       PetscObjectViewSAWs((PetscObject)ts,viewer);
1447:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
1448:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1449:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
1450:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1451:     }
1452:     if (ts->ops->view) {
1453:       (*ts->ops->view)(ts,viewer);
1454:     }
1455: #endif
1456:   }

1458:   PetscViewerASCIIPushTab(viewer);
1459:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
1460:   PetscViewerASCIIPopTab(viewer);
1461:   return(0);
1462: }


1467: /*@
1468:    TSSetApplicationContext - Sets an optional user-defined context for
1469:    the timesteppers.

1471:    Logically Collective on TS

1473:    Input Parameters:
1474: +  ts - the TS context obtained from TSCreate()
1475: -  usrP - optional user context

1477:    Level: intermediate

1479: .keywords: TS, timestep, set, application, context

1481: .seealso: TSGetApplicationContext()
1482: @*/
1483: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
1484: {
1487:   ts->user = usrP;
1488:   return(0);
1489: }

1493: /*@
1494:     TSGetApplicationContext - Gets the user-defined context for the
1495:     timestepper.

1497:     Not Collective

1499:     Input Parameter:
1500: .   ts - the TS context obtained from TSCreate()

1502:     Output Parameter:
1503: .   usrP - user context

1505:     Level: intermediate

1507: .keywords: TS, timestep, get, application, context

1509: .seealso: TSSetApplicationContext()
1510: @*/
1511: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
1512: {
1515:   *(void**)usrP = ts->user;
1516:   return(0);
1517: }

1521: /*@
1522:    TSGetTimeStepNumber - Gets the number of time steps completed.

1524:    Not Collective

1526:    Input Parameter:
1527: .  ts - the TS context obtained from TSCreate()

1529:    Output Parameter:
1530: .  iter - number of steps completed so far

1532:    Level: intermediate

1534: .keywords: TS, timestep, get, iteration, number
1535: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
1536: @*/
1537: PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
1538: {
1542:   *iter = ts->steps;
1543:   return(0);
1544: }

1548: /*@
1549:    TSSetInitialTimeStep - Sets the initial timestep to be used,
1550:    as well as the initial time.

1552:    Logically Collective on TS

1554:    Input Parameters:
1555: +  ts - the TS context obtained from TSCreate()
1556: .  initial_time - the initial time
1557: -  time_step - the size of the timestep

1559:    Level: intermediate

1561: .seealso: TSSetTimeStep(), TSGetTimeStep()

1563: .keywords: TS, set, initial, timestep
1564: @*/
1565: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
1566: {

1571:   TSSetTimeStep(ts,time_step);
1572:   TSSetTime(ts,initial_time);
1573:   return(0);
1574: }

1578: /*@
1579:    TSSetTimeStep - Allows one to reset the timestep at any time,
1580:    useful for simple pseudo-timestepping codes.

1582:    Logically Collective on TS

1584:    Input Parameters:
1585: +  ts - the TS context obtained from TSCreate()
1586: -  time_step - the size of the timestep

1588:    Level: intermediate

1590: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

1592: .keywords: TS, set, timestep
1593: @*/
1594: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
1595: {
1599:   ts->time_step      = time_step;
1600:   ts->time_step_orig = time_step;
1601:   return(0);
1602: }

1606: /*@
1607:    TSSetExactFinalTime - Determines whether to adapt the final time step to
1608:      match the exact final time, interpolate solution to the exact final time,
1609:      or just return at the final time TS computed.

1611:   Logically Collective on TS

1613:    Input Parameter:
1614: +   ts - the time-step context
1615: -   eftopt - exact final time option

1617:    Level: beginner

1619: .seealso: TSExactFinalTimeOption
1620: @*/
1621: PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
1622: {
1626:   ts->exact_final_time = eftopt;
1627:   return(0);
1628: }

1632: /*@
1633:    TSGetTimeStep - Gets the current timestep size.

1635:    Not Collective

1637:    Input Parameter:
1638: .  ts - the TS context obtained from TSCreate()

1640:    Output Parameter:
1641: .  dt - the current timestep size

1643:    Level: intermediate

1645: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

1647: .keywords: TS, get, timestep
1648: @*/
1649: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
1650: {
1654:   *dt = ts->time_step;
1655:   return(0);
1656: }

1660: /*@
1661:    TSGetSolution - Returns the solution at the present timestep. It
1662:    is valid to call this routine inside the function that you are evaluating
1663:    in order to move to the new timestep. This vector not changed until
1664:    the solution at the next timestep has been calculated.

1666:    Not Collective, but Vec returned is parallel if TS is parallel

1668:    Input Parameter:
1669: .  ts - the TS context obtained from TSCreate()

1671:    Output Parameter:
1672: .  v - the vector containing the solution

1674:    Level: intermediate

1676: .seealso: TSGetTimeStep()

1678: .keywords: TS, timestep, get, solution
1679: @*/
1680: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
1681: {
1685:   *v = ts->vec_sol;
1686:   return(0);
1687: }

1689: /* ----- Routines to initialize and destroy a timestepper ---- */
1692: /*@
1693:   TSSetProblemType - Sets the type of problem to be solved.

1695:   Not collective

1697:   Input Parameters:
1698: + ts   - The TS
1699: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1700: .vb
1701:          U_t - A U = 0      (linear)
1702:          U_t - A(t) U = 0   (linear)
1703:          F(t,U,U_t) = 0     (nonlinear)
1704: .ve

1706:    Level: beginner

1708: .keywords: TS, problem type
1709: .seealso: TSSetUp(), TSProblemType, TS
1710: @*/
1711: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
1712: {

1717:   ts->problem_type = type;
1718:   if (type == TS_LINEAR) {
1719:     SNES snes;
1720:     TSGetSNES(ts,&snes);
1721:     SNESSetType(snes,SNESKSPONLY);
1722:   }
1723:   return(0);
1724: }

1728: /*@C
1729:   TSGetProblemType - Gets the type of problem to be solved.

1731:   Not collective

1733:   Input Parameter:
1734: . ts   - The TS

1736:   Output Parameter:
1737: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1738: .vb
1739:          M U_t = A U
1740:          M(t) U_t = A(t) U
1741:          F(t,U,U_t)
1742: .ve

1744:    Level: beginner

1746: .keywords: TS, problem type
1747: .seealso: TSSetUp(), TSProblemType, TS
1748: @*/
1749: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
1750: {
1754:   *type = ts->problem_type;
1755:   return(0);
1756: }

1760: /*@
1761:    TSSetUp - Sets up the internal data structures for the later use
1762:    of a timestepper.

1764:    Collective on TS

1766:    Input Parameter:
1767: .  ts - the TS context obtained from TSCreate()

1769:    Notes:
1770:    For basic use of the TS solvers the user need not explicitly call
1771:    TSSetUp(), since these actions will automatically occur during
1772:    the call to TSStep().  However, if one wishes to control this
1773:    phase separately, TSSetUp() should be called after TSCreate()
1774:    and optional routines of the form TSSetXXX(), but before TSStep().

1776:    Level: advanced

1778: .keywords: TS, timestep, setup

1780: .seealso: TSCreate(), TSStep(), TSDestroy()
1781: @*/
1782: PetscErrorCode  TSSetUp(TS ts)
1783: {
1785:   DM             dm;
1786:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
1787:   PetscErrorCode (*jac)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
1788:   TSIJacobian    ijac;
1789:   TSRHSJacobian  rhsjac;

1793:   if (ts->setupcalled) return(0);

1795:   if (!((PetscObject)ts)->type_name) {
1796:     TSSetType(ts,TSEULER);
1797:   }

1799:   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");

1801:   TSGetAdapt(ts,&ts->adapt);

1803:   if (ts->rhsjacobian.reuse) {
1804:     Mat Amat,Pmat;
1805:     SNES snes;
1806:     TSGetSNES(ts,&snes);
1807:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
1808:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
1809:      * have displaced the RHS matrix */
1810:     if (Amat == ts->Arhs) {
1811:       MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);
1812:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
1813:       MatDestroy(&Amat);
1814:     }
1815:     if (Pmat == ts->Brhs) {
1816:       MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);
1817:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
1818:       MatDestroy(&Pmat);
1819:     }
1820:   }

1822:   if (ts->ops->setup) {
1823:     (*ts->ops->setup)(ts);
1824:   }

1826:   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
1827:    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
1828:    */
1829:   TSGetDM(ts,&dm);
1830:   DMSNESGetFunction(dm,&func,NULL);
1831:   if (!func) {
1832:     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);
1833:   }
1834:   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
1835:      Otherwise, the SNES will use coloring internally to form the Jacobian.
1836:    */
1837:   DMSNESGetJacobian(dm,&jac,NULL);
1838:   DMTSGetIJacobian(dm,&ijac,NULL);
1839:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
1840:   if (!jac && (ijac || rhsjac)) {
1841:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
1842:   }
1843:   ts->setupcalled = PETSC_TRUE;
1844:   return(0);
1845: }

1849: /*@
1850:    TSReset - Resets a TS context and removes any allocated Vecs and Mats.

1852:    Collective on TS

1854:    Input Parameter:
1855: .  ts - the TS context obtained from TSCreate()

1857:    Level: beginner

1859: .keywords: TS, timestep, reset

1861: .seealso: TSCreate(), TSSetup(), TSDestroy()
1862: @*/
1863: PetscErrorCode  TSReset(TS ts)
1864: {

1869:   if (ts->ops->reset) {
1870:     (*ts->ops->reset)(ts);
1871:   }
1872:   if (ts->snes) {SNESReset(ts->snes);}

1874:   MatDestroy(&ts->Arhs);
1875:   MatDestroy(&ts->Brhs);
1876:   VecDestroy(&ts->Frhs);
1877:   VecDestroy(&ts->vec_sol);
1878:   VecDestroy(&ts->vatol);
1879:   VecDestroy(&ts->vrtol);
1880:   VecDestroyVecs(ts->nwork,&ts->work);

1882:   ts->setupcalled = PETSC_FALSE;
1883:   return(0);
1884: }

1888: /*@
1889:    TSDestroy - Destroys the timestepper context that was created
1890:    with TSCreate().

1892:    Collective on TS

1894:    Input Parameter:
1895: .  ts - the TS context obtained from TSCreate()

1897:    Level: beginner

1899: .keywords: TS, timestepper, destroy

1901: .seealso: TSCreate(), TSSetUp(), TSSolve()
1902: @*/
1903: PetscErrorCode  TSDestroy(TS *ts)
1904: {

1908:   if (!*ts) return(0);
1910:   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; return(0);}

1912:   TSReset((*ts));

1914:   /* if memory was published with SAWs then destroy it */
1915:   PetscObjectSAWsViewOff((PetscObject)*ts);
1916:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

1918:   TSAdaptDestroy(&(*ts)->adapt);
1919:   SNESDestroy(&(*ts)->snes);
1920:   DMDestroy(&(*ts)->dm);
1921:   TSMonitorCancel((*ts));

1923:   PetscHeaderDestroy(ts);
1924:   return(0);
1925: }

1929: /*@
1930:    TSGetSNES - Returns the SNES (nonlinear solver) associated with
1931:    a TS (timestepper) context. Valid only for nonlinear problems.

1933:    Not Collective, but SNES is parallel if TS is parallel

1935:    Input Parameter:
1936: .  ts - the TS context obtained from TSCreate()

1938:    Output Parameter:
1939: .  snes - the nonlinear solver context

1941:    Notes:
1942:    The user can then directly manipulate the SNES context to set various
1943:    options, etc.  Likewise, the user can then extract and manipulate the
1944:    KSP, KSP, and PC contexts as well.

1946:    TSGetSNES() does not work for integrators that do not use SNES; in
1947:    this case TSGetSNES() returns NULL in snes.

1949:    Level: beginner

1951: .keywords: timestep, get, SNES
1952: @*/
1953: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
1954: {

1960:   if (!ts->snes) {
1961:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
1962:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
1963:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
1964:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
1965:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
1966:     if (ts->problem_type == TS_LINEAR) {
1967:       SNESSetType(ts->snes,SNESKSPONLY);
1968:     }
1969:   }
1970:   *snes = ts->snes;
1971:   return(0);
1972: }

1976: /*@
1977:    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context

1979:    Collective

1981:    Input Parameter:
1982: +  ts - the TS context obtained from TSCreate()
1983: -  snes - the nonlinear solver context

1985:    Notes:
1986:    Most users should have the TS created by calling TSGetSNES()

1988:    Level: developer

1990: .keywords: timestep, set, SNES
1991: @*/
1992: PetscErrorCode TSSetSNES(TS ts,SNES snes)
1993: {
1995:   PetscErrorCode (*func)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);

2000:   PetscObjectReference((PetscObject)snes);
2001:   SNESDestroy(&ts->snes);

2003:   ts->snes = snes;

2005:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2006:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2007:   if (func == SNESTSFormJacobian) {
2008:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2009:   }
2010:   return(0);
2011: }

2015: /*@
2016:    TSGetKSP - Returns the KSP (linear solver) associated with
2017:    a TS (timestepper) context.

2019:    Not Collective, but KSP is parallel if TS is parallel

2021:    Input Parameter:
2022: .  ts - the TS context obtained from TSCreate()

2024:    Output Parameter:
2025: .  ksp - the nonlinear solver context

2027:    Notes:
2028:    The user can then directly manipulate the KSP context to set various
2029:    options, etc.  Likewise, the user can then extract and manipulate the
2030:    KSP and PC contexts as well.

2032:    TSGetKSP() does not work for integrators that do not use KSP;
2033:    in this case TSGetKSP() returns NULL in ksp.

2035:    Level: beginner

2037: .keywords: timestep, get, KSP
2038: @*/
2039: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2040: {
2042:   SNES           snes;

2047:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2048:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2049:   TSGetSNES(ts,&snes);
2050:   SNESGetKSP(snes,ksp);
2051:   return(0);
2052: }

2054: /* ----------- Routines to set solver parameters ---------- */

2058: /*@
2059:    TSGetDuration - Gets the maximum number of timesteps to use and
2060:    maximum time for iteration.

2062:    Not Collective

2064:    Input Parameters:
2065: +  ts       - the TS context obtained from TSCreate()
2066: .  maxsteps - maximum number of iterations to use, or NULL
2067: -  maxtime  - final time to iterate to, or NULL

2069:    Level: intermediate

2071: .keywords: TS, timestep, get, maximum, iterations, time
2072: @*/
2073: PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2074: {
2077:   if (maxsteps) {
2079:     *maxsteps = ts->max_steps;
2080:   }
2081:   if (maxtime) {
2083:     *maxtime = ts->max_time;
2084:   }
2085:   return(0);
2086: }

2090: /*@
2091:    TSSetDuration - Sets the maximum number of timesteps to use and
2092:    maximum time for iteration.

2094:    Logically Collective on TS

2096:    Input Parameters:
2097: +  ts - the TS context obtained from TSCreate()
2098: .  maxsteps - maximum number of iterations to use
2099: -  maxtime - final time to iterate to

2101:    Options Database Keys:
2102: .  -ts_max_steps <maxsteps> - Sets maxsteps
2103: .  -ts_final_time <maxtime> - Sets maxtime

2105:    Notes:
2106:    The default maximum number of iterations is 5000. Default time is 5.0

2108:    Level: intermediate

2110: .keywords: TS, timestep, set, maximum, iterations

2112: .seealso: TSSetExactFinalTime()
2113: @*/
2114: PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2115: {
2120:   if (maxsteps >= 0) ts->max_steps = maxsteps;
2121:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2122:   return(0);
2123: }

2127: /*@
2128:    TSSetSolution - Sets the initial solution vector
2129:    for use by the TS routines.

2131:    Logically Collective on TS and Vec

2133:    Input Parameters:
2134: +  ts - the TS context obtained from TSCreate()
2135: -  u - the solution vector

2137:    Level: beginner

2139: .keywords: TS, timestep, set, solution, initial conditions
2140: @*/
2141: PetscErrorCode  TSSetSolution(TS ts,Vec u)
2142: {
2144:   DM             dm;

2149:   PetscObjectReference((PetscObject)u);
2150:   VecDestroy(&ts->vec_sol);

2152:   ts->vec_sol = u;

2154:   TSGetDM(ts,&dm);
2155:   DMShellSetGlobalVector(dm,u);
2156:   return(0);
2157: }

2161: /*@C
2162:   TSSetPreStep - Sets the general-purpose function
2163:   called once at the beginning of each time step.

2165:   Logically Collective on TS

2167:   Input Parameters:
2168: + ts   - The TS context obtained from TSCreate()
2169: - func - The function

2171:   Calling sequence of func:
2172: . func (TS ts);

2174:   Level: intermediate

2176:   Note:
2177:   If a step is rejected, TSStep() will call this routine again before each attempt.
2178:   The last completed time step number can be queried using TSGetTimeStepNumber(), the
2179:   size of the step being attempted can be obtained using TSGetTimeStep().

2181: .keywords: TS, timestep
2182: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
2183: @*/
2184: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2185: {
2188:   ts->prestep = func;
2189:   return(0);
2190: }

2194: /*@
2195:   TSPreStep - Runs the user-defined pre-step function.

2197:   Collective on TS

2199:   Input Parameters:
2200: . ts   - The TS context obtained from TSCreate()

2202:   Notes:
2203:   TSPreStep() is typically used within time stepping implementations,
2204:   so most users would not generally call this routine themselves.

2206:   Level: developer

2208: .keywords: TS, timestep
2209: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
2210: @*/
2211: PetscErrorCode  TSPreStep(TS ts)
2212: {

2217:   if (ts->prestep) {
2218:     PetscStackCallStandard((*ts->prestep),(ts));
2219:   }
2220:   return(0);
2221: }

2225: /*@C
2226:   TSSetPreStage - Sets the general-purpose function
2227:   called once at the beginning of each stage.

2229:   Logically Collective on TS

2231:   Input Parameters:
2232: + ts   - The TS context obtained from TSCreate()
2233: - func - The function

2235:   Calling sequence of func:
2236: . PetscErrorCode func(TS ts, PetscReal stagetime);

2238:   Level: intermediate

2240:   Note:
2241:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2242:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2243:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

2245: .keywords: TS, timestep
2246: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2247: @*/
2248: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2249: {
2252:   ts->prestage = func;
2253:   return(0);
2254: }

2258: /*@C
2259:   TSSetPostStage - Sets the general-purpose function
2260:   called once at the end of each stage.

2262:   Logically Collective on TS

2264:   Input Parameters:
2265: + ts   - The TS context obtained from TSCreate()
2266: - func - The function

2268:   Calling sequence of func:
2269: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);

2271:   Level: intermediate

2273:   Note:
2274:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2275:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2276:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

2278: .keywords: TS, timestep
2279: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2280: @*/
2281: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
2282: {
2285:   ts->poststage = func;
2286:   return(0);
2287: }

2291: /*@
2292:   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()

2294:   Collective on TS

2296:   Input Parameters:
2297: . ts          - The TS context obtained from TSCreate()
2298:   stagetime   - The absolute time of the current stage

2300:   Notes:
2301:   TSPreStage() is typically used within time stepping implementations,
2302:   most users would not generally call this routine themselves.

2304:   Level: developer

2306: .keywords: TS, timestep
2307: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2308: @*/
2309: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
2310: {

2315:   if (ts->prestage) {
2316:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
2317:   }
2318:   return(0);
2319: }

2323: /*@
2324:   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()

2326:   Collective on TS

2328:   Input Parameters:
2329: . ts          - The TS context obtained from TSCreate()
2330:   stagetime   - The absolute time of the current stage
2331:   stageindex  - Stage number
2332:   Y           - Array of vectors (of size = total number
2333:                 of stages) with the stage solutions

2335:   Notes:
2336:   TSPostStage() is typically used within time stepping implementations,
2337:   most users would not generally call this routine themselves.

2339:   Level: developer

2341: .keywords: TS, timestep
2342: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2343: @*/
2344: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
2345: {

2350:   if (ts->prestage) {
2351:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
2352:   }
2353:   return(0);
2354: }

2358: /*@C
2359:   TSSetPostStep - Sets the general-purpose function
2360:   called once at the end of each time step.

2362:   Logically Collective on TS

2364:   Input Parameters:
2365: + ts   - The TS context obtained from TSCreate()
2366: - func - The function

2368:   Calling sequence of func:
2369: $ func (TS ts);

2371:   Level: intermediate

2373: .keywords: TS, timestep
2374: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2375: @*/
2376: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2377: {
2380:   ts->poststep = func;
2381:   return(0);
2382: }

2386: /*@
2387:   TSPostStep - Runs the user-defined post-step function.

2389:   Collective on TS

2391:   Input Parameters:
2392: . ts   - The TS context obtained from TSCreate()

2394:   Notes:
2395:   TSPostStep() is typically used within time stepping implementations,
2396:   so most users would not generally call this routine themselves.

2398:   Level: developer

2400: .keywords: TS, timestep
2401: @*/
2402: PetscErrorCode  TSPostStep(TS ts)
2403: {

2408:   if (ts->poststep) {
2409:     PetscStackCallStandard((*ts->poststep),(ts));
2410:   }
2411:   return(0);
2412: }

2414: /* ------------ Routines to set performance monitoring options ----------- */

2418: /*@C
2419:    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
2420:    timestep to display the iteration's  progress.

2422:    Logically Collective on TS

2424:    Input Parameters:
2425: +  ts - the TS context obtained from TSCreate()
2426: .  monitor - monitoring routine
2427: .  mctx - [optional] user-defined context for private data for the
2428:              monitor routine (use NULL if no context is desired)
2429: -  monitordestroy - [optional] routine that frees monitor context
2430:           (may be NULL)

2432:    Calling sequence of monitor:
2433: $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)

2435: +    ts - the TS context
2436: .    steps - iteration number (after the final time step the monitor routine is called with a step of -1, this is at the final time which may have
2437:                                been interpolated to)
2438: .    time - current time
2439: .    u - current iterate
2440: -    mctx - [optional] monitoring context

2442:    Notes:
2443:    This routine adds an additional monitor to the list of monitors that
2444:    already has been loaded.

2446:    Fortran notes: Only a single monitor function can be set for each TS object

2448:    Level: intermediate

2450: .keywords: TS, timestep, set, monitor

2452: .seealso: TSMonitorDefault(), TSMonitorCancel()
2453: @*/
2454: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
2455: {
2458:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
2459:   ts->monitor[ts->numbermonitors]          = monitor;
2460:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
2461:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
2462:   return(0);
2463: }

2467: /*@C
2468:    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.

2470:    Logically Collective on TS

2472:    Input Parameters:
2473: .  ts - the TS context obtained from TSCreate()

2475:    Notes:
2476:    There is no way to remove a single, specific monitor.

2478:    Level: intermediate

2480: .keywords: TS, timestep, set, monitor

2482: .seealso: TSMonitorDefault(), TSMonitorSet()
2483: @*/
2484: PetscErrorCode  TSMonitorCancel(TS ts)
2485: {
2487:   PetscInt       i;

2491:   for (i=0; i<ts->numbermonitors; i++) {
2492:     if (ts->monitordestroy[i]) {
2493:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
2494:     }
2495:   }
2496:   ts->numbermonitors = 0;
2497:   return(0);
2498: }

2502: /*@
2503:    TSMonitorDefault - Sets the Default monitor

2505:    Level: intermediate

2507: .keywords: TS, set, monitor

2509: .seealso: TSMonitorDefault(), TSMonitorSet()
2510: @*/
2511: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
2512: {
2514:   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));

2517:   PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
2518:   PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g\n",step,(double)ts->time_step,(double)ptime);
2519:   PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
2520:   return(0);
2521: }

2525: /*@
2526:    TSSetRetainStages - Request that all stages in the upcoming step be stored so that interpolation will be available.

2528:    Logically Collective on TS

2530:    Input Argument:
2531: .  ts - time stepping context

2533:    Output Argument:
2534: .  flg - PETSC_TRUE or PETSC_FALSE

2536:    Level: intermediate

2538: .keywords: TS, set

2540: .seealso: TSInterpolate(), TSSetPostStep()
2541: @*/
2542: PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
2543: {
2546:   ts->retain_stages = flg;
2547:   return(0);
2548: }

2552: /*@
2553:    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval

2555:    Collective on TS

2557:    Input Argument:
2558: +  ts - time stepping context
2559: -  t - time to interpolate to

2561:    Output Argument:
2562: .  U - state at given time

2564:    Notes:
2565:    The user should call TSSetRetainStages() before taking a step in which interpolation will be requested.

2567:    Level: intermediate

2569:    Developer Notes:
2570:    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.

2572: .keywords: TS, set

2574: .seealso: TSSetRetainStages(), TSSetPostStep()
2575: @*/
2576: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
2577: {

2583:   if (t < ts->ptime - ts->time_step_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)(ts->ptime-ts->time_step_prev),(double)ts->ptime);
2584:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
2585:   (*ts->ops->interpolate)(ts,t,U);
2586:   return(0);
2587: }

2591: /*@
2592:    TSStep - Steps one time step

2594:    Collective on TS

2596:    Input Parameter:
2597: .  ts - the TS context obtained from TSCreate()

2599:    Level: intermediate

2601:    Notes:
2602:    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
2603:    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.

2605:    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
2606:    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.

2608: .keywords: TS, timestep, solve

2610: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
2611: @*/
2612: PetscErrorCode  TSStep(TS ts)
2613: {
2614:   PetscReal      ptime_prev;

2619:   TSSetUp(ts);

2621:   ts->reason = TS_CONVERGED_ITERATING;
2622:   ptime_prev = ts->ptime;

2624:   PetscLogEventBegin(TS_Step,ts,0,0,0);
2625:   (*ts->ops->step)(ts);
2626:   PetscLogEventEnd(TS_Step,ts,0,0,0);

2628:   ts->time_step_prev = ts->ptime - ptime_prev;

2630:   if (ts->reason < 0) {
2631:     if (ts->errorifstepfailed) {
2632:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
2633:         SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
2634:       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
2635:     }
2636:   } else if (!ts->reason) {
2637:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
2638:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
2639:   }
2640:   return(0);
2641: }

2645: /*@
2646:    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.

2648:    Collective on TS

2650:    Input Arguments:
2651: +  ts - time stepping context
2652: .  order - desired order of accuracy
2653: -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)

2655:    Output Arguments:
2656: .  U - state at the end of the current step

2658:    Level: advanced

2660:    Notes:
2661:    This function cannot be called until all stages have been evaluated.
2662:    It is normally called by adaptive controllers before a step has been accepted and may also be called by the user after TSStep() has returned.

2664: .seealso: TSStep(), TSAdapt
2665: @*/
2666: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
2667: {

2674:   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
2675:   (*ts->ops->evaluatestep)(ts,order,U,done);
2676:   return(0);
2677: }

2681: /*@
2682:    TSSolve - Steps the requested number of timesteps.

2684:    Collective on TS

2686:    Input Parameter:
2687: +  ts - the TS context obtained from TSCreate()
2688: -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)

2690:    Level: beginner

2692:    Notes:
2693:    The final time returned by this function may be different from the time of the internally
2694:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
2695:    stepped over the final time.

2697: .keywords: TS, timestep, solve

2699: .seealso: TSCreate(), TSSetSolution(), TSStep()
2700: @*/
2701: PetscErrorCode TSSolve(TS ts,Vec u)
2702: {
2703:   Vec               solution;
2704:   PetscErrorCode    ierr;

2709:   if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE) {   /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
2711:     if (!ts->vec_sol || u == ts->vec_sol) {
2712:       VecDuplicate(u,&solution);
2713:       TSSetSolution(ts,solution);
2714:       VecDestroy(&solution); /* grant ownership */
2715:     }
2716:     VecCopy(u,ts->vec_sol);
2717:   } else if (u) {
2718:     TSSetSolution(ts,u);
2719:   }
2720:   TSSetUp(ts);
2721:   /* reset time step and iteration counters */
2722:   ts->steps             = 0;
2723:   ts->ksp_its           = 0;
2724:   ts->snes_its          = 0;
2725:   ts->num_snes_failures = 0;
2726:   ts->reject            = 0;
2727:   ts->reason            = TS_CONVERGED_ITERATING;

2729:   TSViewFromOptions(ts,NULL,"-ts_view_pre");

2731:   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
2732:     (*ts->ops->solve)(ts);
2733:     VecCopy(ts->vec_sol,u);
2734:     ts->solvetime = ts->ptime;
2735:   } else {
2736:     /* steps the requested number of timesteps. */
2737:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
2738:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
2739:     while (!ts->reason) {
2740:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
2741:       TSStep(ts);
2742:       TSPostStep(ts);
2743:     }
2744:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
2745:       TSInterpolate(ts,ts->max_time,u);
2746:       ts->solvetime = ts->max_time;
2747:       solution = u;
2748:     } else {
2749:       if (u) {VecCopy(ts->vec_sol,u);}
2750:       ts->solvetime = ts->ptime;
2751:       solution = ts->vec_sol;
2752:     }
2753:     TSMonitor(ts,ts->steps,ts->solvetime,solution);
2754:   }
2755:   TSViewFromOptions(ts,NULL,"-ts_view");
2756:   PetscObjectSAWsBlock((PetscObject)ts);
2757:   return(0);
2758: }

2762: /*@
2763:    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()

2765:    Collective on TS

2767:    Input Parameters:
2768: +  ts - time stepping context obtained from TSCreate()
2769: .  step - step number that has just completed
2770: .  ptime - model time of the state
2771: -  u - state at the current model time

2773:    Notes:
2774:    TSMonitor() is typically used within the time stepping implementations.
2775:    Users might call this function when using the TSStep() interface instead of TSSolve().

2777:    Level: advanced

2779: .keywords: TS, timestep
2780: @*/
2781: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
2782: {
2784:   PetscInt       i,n = ts->numbermonitors;

2789:   for (i=0; i<n; i++) {
2790:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
2791:   }
2792:   return(0);
2793: }

2795: /* ------------------------------------------------------------------------*/
2798: /*@C
2799:    TSMonitorLGCtxCreate - Creates a line graph context for use with
2800:    TS to monitor the solution process graphically in various ways

2802:    Collective on TS

2804:    Input Parameters:
2805: +  host - the X display to open, or null for the local machine
2806: .  label - the title to put in the title bar
2807: .  x, y - the screen coordinates of the upper left coordinate of the window
2808: .  m, n - the screen width and height in pixels
2809: -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time

2811:    Output Parameter:
2812: .  ctx - the context

2814:    Options Database Key:
2815: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
2816: .  -ts_monitor_lg_solution -
2817: .  -ts_monitor_lg_error -
2818: .  -ts_monitor_lg_ksp_iterations -
2819: .  -ts_monitor_lg_snes_iterations -
2820: -  -lg_indicate_data_points <true,false> - indicate the data points (at each time step) on the plot; default is true

2822:    Notes:
2823:    Use TSMonitorLGCtxDestroy() to destroy.

2825:    Level: intermediate

2827: .keywords: TS, monitor, line graph, residual, seealso

2829: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

2831: @*/
2832: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
2833: {
2834:   PetscDraw      win;

2838:   PetscNew(ctx);
2839:   PetscDrawCreate(comm,host,label,x,y,m,n,&win);
2840:   PetscDrawSetFromOptions(win);
2841:   PetscDrawLGCreate(win,1,&(*ctx)->lg);
2842:   PetscLogObjectParent((PetscObject)(*ctx)->lg,(PetscObject)win);
2843:   PetscDrawLGIndicateDataPoints((*ctx)->lg,PETSC_TRUE);
2844:   PetscDrawLGSetFromOptions((*ctx)->lg);
2845:   (*ctx)->howoften = howoften;
2846:   return(0);
2847: }

2851: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
2852: {
2853:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
2854:   PetscReal      x   = ptime,y;

2858:   if (!step) {
2859:     PetscDrawAxis axis;
2860:     PetscDrawLGGetAxis(ctx->lg,&axis);
2861:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");
2862:     PetscDrawLGReset(ctx->lg);
2863:     PetscDrawLGIndicateDataPoints(ctx->lg,PETSC_TRUE);
2864:   }
2865:   TSGetTimeStep(ts,&y);
2866:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
2867:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
2868:     PetscDrawLGDraw(ctx->lg);
2869:   }
2870:   return(0);
2871: }

2875: /*@C
2876:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
2877:    with TSMonitorLGCtxCreate().

2879:    Collective on TSMonitorLGCtx

2881:    Input Parameter:
2882: .  ctx - the monitor context

2884:    Level: intermediate

2886: .keywords: TS, monitor, line graph, destroy

2888: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
2889: @*/
2890: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
2891: {
2892:   PetscDraw      draw;

2896:   PetscDrawLGGetDraw((*ctx)->lg,&draw);
2897:   PetscDrawDestroy(&draw);
2898:   PetscDrawLGDestroy(&(*ctx)->lg);
2899:   PetscFree(*ctx);
2900:   return(0);
2901: }

2905: /*@
2906:    TSGetTime - Gets the time of the most recently completed step.

2908:    Not Collective

2910:    Input Parameter:
2911: .  ts - the TS context obtained from TSCreate()

2913:    Output Parameter:
2914: .  t  - the current time

2916:    Level: beginner

2918:    Note:
2919:    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
2920:    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.

2922: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

2924: .keywords: TS, get, time
2925: @*/
2926: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
2927: {
2931:   *t = ts->ptime;
2932:   return(0);
2933: }

2937: /*@
2938:    TSSetTime - Allows one to reset the time.

2940:    Logically Collective on TS

2942:    Input Parameters:
2943: +  ts - the TS context obtained from TSCreate()
2944: -  time - the time

2946:    Level: intermediate

2948: .seealso: TSGetTime(), TSSetDuration()

2950: .keywords: TS, set, time
2951: @*/
2952: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
2953: {
2957:   ts->ptime = t;
2958:   return(0);
2959: }

2963: /*@C
2964:    TSSetOptionsPrefix - Sets the prefix used for searching for all
2965:    TS options in the database.

2967:    Logically Collective on TS

2969:    Input Parameter:
2970: +  ts     - The TS context
2971: -  prefix - The prefix to prepend to all option names

2973:    Notes:
2974:    A hyphen (-) must NOT be given at the beginning of the prefix name.
2975:    The first character of all runtime options is AUTOMATICALLY the
2976:    hyphen.

2978:    Level: advanced

2980: .keywords: TS, set, options, prefix, database

2982: .seealso: TSSetFromOptions()

2984: @*/
2985: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
2986: {
2988:   SNES           snes;

2992:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
2993:   TSGetSNES(ts,&snes);
2994:   SNESSetOptionsPrefix(snes,prefix);
2995:   return(0);
2996: }


3001: /*@C
3002:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3003:    TS options in the database.

3005:    Logically Collective on TS

3007:    Input Parameter:
3008: +  ts     - The TS context
3009: -  prefix - The prefix to prepend to all option names

3011:    Notes:
3012:    A hyphen (-) must NOT be given at the beginning of the prefix name.
3013:    The first character of all runtime options is AUTOMATICALLY the
3014:    hyphen.

3016:    Level: advanced

3018: .keywords: TS, append, options, prefix, database

3020: .seealso: TSGetOptionsPrefix()

3022: @*/
3023: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
3024: {
3026:   SNES           snes;

3030:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
3031:   TSGetSNES(ts,&snes);
3032:   SNESAppendOptionsPrefix(snes,prefix);
3033:   return(0);
3034: }

3038: /*@C
3039:    TSGetOptionsPrefix - Sets the prefix used for searching for all
3040:    TS options in the database.

3042:    Not Collective

3044:    Input Parameter:
3045: .  ts - The TS context

3047:    Output Parameter:
3048: .  prefix - A pointer to the prefix string used

3050:    Notes: On the fortran side, the user should pass in a string 'prifix' of
3051:    sufficient length to hold the prefix.

3053:    Level: intermediate

3055: .keywords: TS, get, options, prefix, database

3057: .seealso: TSAppendOptionsPrefix()
3058: @*/
3059: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
3060: {

3066:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
3067:   return(0);
3068: }

3072: /*@C
3073:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

3075:    Not Collective, but parallel objects are returned if TS is parallel

3077:    Input Parameter:
3078: .  ts  - The TS context obtained from TSCreate()

3080:    Output Parameters:
3081: +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
3082: .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
3083: .  func - Function to compute the Jacobian of the RHS  (or NULL)
3084: -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)

3086:    Notes: You can pass in NULL for any return argument you do not need.

3088:    Level: intermediate

3090: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

3092: .keywords: TS, timestep, get, matrix, Jacobian
3093: @*/
3094: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
3095: {
3097:   SNES           snes;
3098:   DM             dm;

3101:   TSGetSNES(ts,&snes);
3102:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
3103:   TSGetDM(ts,&dm);
3104:   DMTSGetRHSJacobian(dm,func,ctx);
3105:   return(0);
3106: }

3110: /*@C
3111:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

3113:    Not Collective, but parallel objects are returned if TS is parallel

3115:    Input Parameter:
3116: .  ts  - The TS context obtained from TSCreate()

3118:    Output Parameters:
3119: +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
3120: .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
3121: .  f   - The function to compute the matrices
3122: - ctx - User-defined context for Jacobian evaluation routine

3124:    Notes: You can pass in NULL for any return argument you do not need.

3126:    Level: advanced

3128: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

3130: .keywords: TS, timestep, get, matrix, Jacobian
3131: @*/
3132: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
3133: {
3135:   SNES           snes;
3136:   DM             dm;

3139:   TSGetSNES(ts,&snes);
3140:   SNESSetUpMatrices(snes);
3141:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
3142:   TSGetDM(ts,&dm);
3143:   DMTSGetIJacobian(dm,f,ctx);
3144:   return(0);
3145: }


3150: /*@C
3151:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
3152:    VecView() for the solution at each timestep

3154:    Collective on TS

3156:    Input Parameters:
3157: +  ts - the TS context
3158: .  step - current time-step
3159: .  ptime - current time
3160: -  dummy - either a viewer or NULL

3162:    Options Database:
3163: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

3165:    Notes: the initial solution and current solution are not displayed with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
3166:        will look bad

3168:    Level: intermediate

3170: .keywords: TS,  vector, monitor, view

3172: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3173: @*/
3174: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3175: {
3176:   PetscErrorCode   ierr;
3177:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
3178:   PetscDraw        draw;

3181:   if (!step && ictx->showinitial) {
3182:     if (!ictx->initialsolution) {
3183:       VecDuplicate(u,&ictx->initialsolution);
3184:     }
3185:     VecCopy(u,ictx->initialsolution);
3186:   }
3187:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

3189:   if (ictx->showinitial) {
3190:     PetscReal pause;
3191:     PetscViewerDrawGetPause(ictx->viewer,&pause);
3192:     PetscViewerDrawSetPause(ictx->viewer,0.0);
3193:     VecView(ictx->initialsolution,ictx->viewer);
3194:     PetscViewerDrawSetPause(ictx->viewer,pause);
3195:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
3196:   }
3197:   VecView(u,ictx->viewer);
3198:   if (ictx->showtimestepandtime) {
3199:     PetscReal xl,yl,xr,yr,tw,w,h;
3200:     char      time[32];
3201:     size_t    len;

3203:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
3204:     PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);
3205:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
3206:      PetscStrlen(time,&len);
3207:     PetscDrawStringGetSize(draw,&tw,NULL);
3208:     w    = xl + .5*(xr - xl) - .5*len*tw;
3209:     h    = yl + .95*(yr - yl);
3210:     PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);
3211:     PetscDrawFlush(draw);
3212:   }

3214:   if (ictx->showinitial) {
3215:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
3216:   }
3217:   return(0);
3218: }

3222: /*@C
3223:    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram

3225:    Collective on TS

3227:    Input Parameters:
3228: +  ts - the TS context
3229: .  step - current time-step
3230: .  ptime - current time
3231: -  dummy - either a viewer or NULL

3233:    Level: intermediate

3235: .keywords: TS,  vector, monitor, view

3237: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3238: @*/
3239: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3240: {
3241:   PetscErrorCode    ierr;
3242:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
3243:   PetscDraw         draw;
3244:   MPI_Comm          comm;
3245:   PetscInt          n;
3246:   PetscMPIInt       size;
3247:   PetscReal         xl,yl,xr,yr,tw,w,h;
3248:   char              time[32];
3249:   size_t            len;
3250:   const PetscScalar *U;

3253:   PetscObjectGetComm((PetscObject)ts,&comm);
3254:   MPI_Comm_size(comm,&size);
3255:   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
3256:   VecGetSize(u,&n);
3257:   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");

3259:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);

3261:   VecGetArrayRead(u,&U);
3262:   PetscDrawAxisGetLimits(ictx->axis,&xl,&xr,&yl,&yr);
3263:   if ((PetscRealPart(U[0]) < xl) || (PetscRealPart(U[1]) < yl) || (PetscRealPart(U[0]) > xr) || (PetscRealPart(U[1]) > yr)) {
3264:       VecRestoreArrayRead(u,&U);
3265:       return(0);
3266:   }
3267:   if (!step) ictx->color++;
3268:   PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);
3269:   VecRestoreArrayRead(u,&U);

3271:   if (ictx->showtimestepandtime) {
3272:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
3273:     PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);
3274:     PetscStrlen(time,&len);
3275:     PetscDrawStringGetSize(draw,&tw,NULL);
3276:     w    = xl + .5*(xr - xl) - .5*len*tw;
3277:     h    = yl + .95*(yr - yl);
3278:     PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);
3279:   }
3280:   PetscDrawFlush(draw);
3281:   return(0);
3282: }


3287: /*@C
3288:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

3290:    Collective on TS

3292:    Input Parameters:
3293: .    ctx - the monitor context

3295:    Level: intermediate

3297: .keywords: TS,  vector, monitor, view

3299: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
3300: @*/
3301: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
3302: {

3306:   PetscDrawAxisDestroy(&(*ictx)->axis);
3307:   PetscViewerDestroy(&(*ictx)->viewer);
3308:   VecDestroy(&(*ictx)->initialsolution);
3309:   PetscFree(*ictx);
3310:   return(0);
3311: }

3315: /*@C
3316:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

3318:    Collective on TS

3320:    Input Parameter:
3321: .    ts - time-step context

3323:    Output Patameter:
3324: .    ctx - the monitor context

3326:    Options Database:
3327: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

3329:    Level: intermediate

3331: .keywords: TS,  vector, monitor, view

3333: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
3334: @*/
3335: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
3336: {
3337:   PetscErrorCode   ierr;

3340:   PetscNew(ctx);
3341:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
3342:   PetscViewerSetFromOptions((*ctx)->viewer);

3344:   (*ctx)->howoften    = howoften;
3345:   (*ctx)->showinitial = PETSC_FALSE;
3346:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

3348:   (*ctx)->showtimestepandtime = PETSC_FALSE;
3349:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
3350:   (*ctx)->color = PETSC_DRAW_WHITE;
3351:   return(0);
3352: }

3356: /*@C
3357:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
3358:    VecView() for the error at each timestep

3360:    Collective on TS

3362:    Input Parameters:
3363: +  ts - the TS context
3364: .  step - current time-step
3365: .  ptime - current time
3366: -  dummy - either a viewer or NULL

3368:    Level: intermediate

3370: .keywords: TS,  vector, monitor, view

3372: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3373: @*/
3374: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3375: {
3376:   PetscErrorCode   ierr;
3377:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
3378:   PetscViewer      viewer = ctx->viewer;
3379:   Vec              work;

3382:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
3383:   VecDuplicate(u,&work);
3384:   TSComputeSolutionFunction(ts,ptime,work);
3385:   VecAXPY(work,-1.0,u);
3386:   VecView(work,viewer);
3387:   VecDestroy(&work);
3388:   return(0);
3389: }

3391: #include <petsc-private/dmimpl.h>
3394: /*@
3395:    TSSetDM - Sets the DM that may be used by some preconditioners

3397:    Logically Collective on TS and DM

3399:    Input Parameters:
3400: +  ts - the preconditioner context
3401: -  dm - the dm

3403:    Level: intermediate


3406: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
3407: @*/
3408: PetscErrorCode  TSSetDM(TS ts,DM dm)
3409: {
3411:   SNES           snes;
3412:   DMTS           tsdm;

3416:   PetscObjectReference((PetscObject)dm);
3417:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
3418:     if (ts->dm->dmts && !dm->dmts) {
3419:       DMCopyDMTS(ts->dm,dm);
3420:       DMGetDMTS(ts->dm,&tsdm);
3421:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
3422:         tsdm->originaldm = dm;
3423:       }
3424:     }
3425:     DMDestroy(&ts->dm);
3426:   }
3427:   ts->dm = dm;

3429:   TSGetSNES(ts,&snes);
3430:   SNESSetDM(snes,dm);
3431:   return(0);
3432: }

3436: /*@
3437:    TSGetDM - Gets the DM that may be used by some preconditioners

3439:    Not Collective

3441:    Input Parameter:
3442: . ts - the preconditioner context

3444:    Output Parameter:
3445: .  dm - the dm

3447:    Level: intermediate


3450: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
3451: @*/
3452: PetscErrorCode  TSGetDM(TS ts,DM *dm)
3453: {

3458:   if (!ts->dm) {
3459:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
3460:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
3461:   }
3462:   *dm = ts->dm;
3463:   return(0);
3464: }

3468: /*@
3469:    SNESTSFormFunction - Function to evaluate nonlinear residual

3471:    Logically Collective on SNES

3473:    Input Parameter:
3474: + snes - nonlinear solver
3475: . U - the current state at which to evaluate the residual
3476: - ctx - user context, must be a TS

3478:    Output Parameter:
3479: . F - the nonlinear residual

3481:    Notes:
3482:    This function is not normally called by users and is automatically registered with the SNES used by TS.
3483:    It is most frequently passed to MatFDColoringSetFunction().

3485:    Level: advanced

3487: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
3488: @*/
3489: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
3490: {
3491:   TS             ts = (TS)ctx;

3499:   (ts->ops->snesfunction)(snes,U,F,ts);
3500:   return(0);
3501: }

3505: /*@
3506:    SNESTSFormJacobian - Function to evaluate the Jacobian

3508:    Collective on SNES

3510:    Input Parameter:
3511: + snes - nonlinear solver
3512: . U - the current state at which to evaluate the residual
3513: - ctx - user context, must be a TS

3515:    Output Parameter:
3516: + A - the Jacobian
3517: . B - the preconditioning matrix (may be the same as A)
3518: - flag - indicates any structure change in the matrix

3520:    Notes:
3521:    This function is not normally called by users and is automatically registered with the SNES used by TS.

3523:    Level: developer

3525: .seealso: SNESSetJacobian()
3526: @*/
3527: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat *A,Mat *B,MatStructure *flag,void *ctx)
3528: {
3529:   TS             ts = (TS)ctx;

3541:   (ts->ops->snesjacobian)(snes,U,A,B,flag,ts);
3542:   return(0);
3543: }

3547: /*@C
3548:    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems only

3550:    Collective on TS

3552:    Input Arguments:
3553: +  ts - time stepping context
3554: .  t - time at which to evaluate
3555: .  U - state at which to evaluate
3556: -  ctx - context

3558:    Output Arguments:
3559: .  F - right hand side

3561:    Level: intermediate

3563:    Notes:
3564:    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
3565:    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().

3567: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
3568: @*/
3569: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
3570: {
3572:   Mat            Arhs,Brhs;
3573:   MatStructure   flg2;

3576:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
3577:   TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);
3578:   MatMult(Arhs,U,F);
3579:   return(0);
3580: }

3584: /*@C
3585:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

3587:    Collective on TS

3589:    Input Arguments:
3590: +  ts - time stepping context
3591: .  t - time at which to evaluate
3592: .  U - state at which to evaluate
3593: -  ctx - context

3595:    Output Arguments:
3596: +  A - pointer to operator
3597: .  B - pointer to preconditioning matrix
3598: -  flg - matrix structure flag

3600:    Level: intermediate

3602:    Notes:
3603:    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.

3605: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
3606: @*/
3607: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg,void *ctx)
3608: {
3610:   *flg = SAME_PRECONDITIONER;
3611:   return(0);
3612: }

3616: /*@C
3617:    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only

3619:    Collective on TS

3621:    Input Arguments:
3622: +  ts - time stepping context
3623: .  t - time at which to evaluate
3624: .  U - state at which to evaluate
3625: .  Udot - time derivative of state vector
3626: -  ctx - context

3628:    Output Arguments:
3629: .  F - left hand side

3631:    Level: intermediate

3633:    Notes:
3634:    The assumption here is that the left hand side is of the form A*Udot (and not A*Udot + B*U). For other cases, the
3635:    user is required to write their own TSComputeIFunction.
3636:    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
3637:    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().

3639: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
3640: @*/
3641: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
3642: {
3644:   Mat            A,B;
3645:   MatStructure   flg2;

3648:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
3649:   TSComputeIJacobian(ts,t,U,Udot,1.0,&A,&B,&flg2,PETSC_TRUE);
3650:   MatMult(A,Udot,F);
3651:   return(0);
3652: }

3656: /*@C
3657:    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE

3659:    Collective on TS

3661:    Input Arguments:
3662: +  ts - time stepping context
3663: .  t - time at which to evaluate
3664: .  U - state at which to evaluate
3665: .  Udot - time derivative of state vector
3666: .  shift - shift to apply
3667: -  ctx - context

3669:    Output Arguments:
3670: +  A - pointer to operator
3671: .  B - pointer to preconditioning matrix
3672: -  flg - matrix structure flag

3674:    Level: advanced

3676:    Notes:
3677:    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.

3679:    It is only appropriate for problems of the form

3681: $     M Udot = F(U,t)

3683:   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
3684:   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
3685:   an implicit operator of the form

3687: $    shift*M + J

3689:   where J is the Jacobian of -F(U).  Support may be added in a future version of PETSc, but for now, the user must store
3690:   a copy of M or reassemble it when requested.

3692: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
3693: @*/
3694: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,void *ctx)
3695: {

3699:   MatScale(*A, shift / ts->ijacobian.shift);
3700:   ts->ijacobian.shift = shift;
3701:   *flg = SAME_PRECONDITIONER;
3702:   return(0);
3703: }

3707: /*@
3708:    TSGetEquationType - Gets the type of the equation that TS is solving.

3710:    Not Collective

3712:    Input Parameter:
3713: .  ts - the TS context

3715:    Output Parameter:
3716: .  equation_type - see TSEquationType

3718:    Level: beginner

3720: .keywords: TS, equation type

3722: .seealso: TSSetEquationType(), TSEquationType
3723: @*/
3724: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
3725: {
3729:   *equation_type = ts->equation_type;
3730:   return(0);
3731: }

3735: /*@
3736:    TSSetEquationType - Sets the type of the equation that TS is solving.

3738:    Not Collective

3740:    Input Parameter:
3741: +  ts - the TS context
3742: .  equation_type - see TSEquationType

3744:    Level: advanced

3746: .keywords: TS, equation type

3748: .seealso: TSGetEquationType(), TSEquationType
3749: @*/
3750: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
3751: {
3754:   ts->equation_type = equation_type;
3755:   return(0);
3756: }

3760: /*@
3761:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

3763:    Not Collective

3765:    Input Parameter:
3766: .  ts - the TS context

3768:    Output Parameter:
3769: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
3770:             manual pages for the individual convergence tests for complete lists

3772:    Level: beginner

3774:    Notes:
3775:    Can only be called after the call to TSSolve() is complete.

3777: .keywords: TS, nonlinear, set, convergence, test

3779: .seealso: TSSetConvergenceTest(), TSConvergedReason
3780: @*/
3781: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
3782: {
3786:   *reason = ts->reason;
3787:   return(0);
3788: }

3792: /*@
3793:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

3795:    Not Collective

3797:    Input Parameter:
3798: +  ts - the TS context
3799: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
3800:             manual pages for the individual convergence tests for complete lists

3802:    Level: advanced

3804:    Notes:
3805:    Can only be called during TSSolve() is active.

3807: .keywords: TS, nonlinear, set, convergence, test

3809: .seealso: TSConvergedReason
3810: @*/
3811: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
3812: {
3815:   ts->reason = reason;
3816:   return(0);
3817: }

3821: /*@
3822:    TSGetSolveTime - Gets the time after a call to TSSolve()

3824:    Not Collective

3826:    Input Parameter:
3827: .  ts - the TS context

3829:    Output Parameter:
3830: .  ftime - the final time. This time should correspond to the final time set with TSSetDuration()

3832:    Level: beginner

3834:    Notes:
3835:    Can only be called after the call to TSSolve() is complete.

3837: .keywords: TS, nonlinear, set, convergence, test

3839: .seealso: TSSetConvergenceTest(), TSConvergedReason
3840: @*/
3841: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
3842: {
3846:   *ftime = ts->solvetime;
3847:   return(0);
3848: }

3852: /*@
3853:    TSGetSNESIterations - Gets the total number of nonlinear iterations
3854:    used by the time integrator.

3856:    Not Collective

3858:    Input Parameter:
3859: .  ts - TS context

3861:    Output Parameter:
3862: .  nits - number of nonlinear iterations

3864:    Notes:
3865:    This counter is reset to zero for each successive call to TSSolve().

3867:    Level: intermediate

3869: .keywords: TS, get, number, nonlinear, iterations

3871: .seealso:  TSGetKSPIterations()
3872: @*/
3873: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
3874: {
3878:   *nits = ts->snes_its;
3879:   return(0);
3880: }

3884: /*@
3885:    TSGetKSPIterations - Gets the total number of linear iterations
3886:    used by the time integrator.

3888:    Not Collective

3890:    Input Parameter:
3891: .  ts - TS context

3893:    Output Parameter:
3894: .  lits - number of linear iterations

3896:    Notes:
3897:    This counter is reset to zero for each successive call to TSSolve().

3899:    Level: intermediate

3901: .keywords: TS, get, number, linear, iterations

3903: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
3904: @*/
3905: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
3906: {
3910:   *lits = ts->ksp_its;
3911:   return(0);
3912: }

3916: /*@
3917:    TSGetStepRejections - Gets the total number of rejected steps.

3919:    Not Collective

3921:    Input Parameter:
3922: .  ts - TS context

3924:    Output Parameter:
3925: .  rejects - number of steps rejected

3927:    Notes:
3928:    This counter is reset to zero for each successive call to TSSolve().

3930:    Level: intermediate

3932: .keywords: TS, get, number

3934: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
3935: @*/
3936: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
3937: {
3941:   *rejects = ts->reject;
3942:   return(0);
3943: }

3947: /*@
3948:    TSGetSNESFailures - Gets the total number of failed SNES solves

3950:    Not Collective

3952:    Input Parameter:
3953: .  ts - TS context

3955:    Output Parameter:
3956: .  fails - number of failed nonlinear solves

3958:    Notes:
3959:    This counter is reset to zero for each successive call to TSSolve().

3961:    Level: intermediate

3963: .keywords: TS, get, number

3965: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
3966: @*/
3967: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
3968: {
3972:   *fails = ts->num_snes_failures;
3973:   return(0);
3974: }

3978: /*@
3979:    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails

3981:    Not Collective

3983:    Input Parameter:
3984: +  ts - TS context
3985: -  rejects - maximum number of rejected steps, pass -1 for unlimited

3987:    Notes:
3988:    The counter is reset to zero for each step

3990:    Options Database Key:
3991:  .  -ts_max_reject - Maximum number of step rejections before a step fails

3993:    Level: intermediate

3995: .keywords: TS, set, maximum, number

3997: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
3998: @*/
3999: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4000: {
4003:   ts->max_reject = rejects;
4004:   return(0);
4005: }

4009: /*@
4010:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

4012:    Not Collective

4014:    Input Parameter:
4015: +  ts - TS context
4016: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

4018:    Notes:
4019:    The counter is reset to zero for each successive call to TSSolve().

4021:    Options Database Key:
4022:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

4024:    Level: intermediate

4026: .keywords: TS, set, maximum, number

4028: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4029: @*/
4030: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4031: {
4034:   ts->max_snes_failures = fails;
4035:   return(0);
4036: }

4040: /*@
4041:    TSSetErrorIfStepFails - Error if no step succeeds

4043:    Not Collective

4045:    Input Parameter:
4046: +  ts - TS context
4047: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

4049:    Options Database Key:
4050:  .  -ts_error_if_step_fails - Error if no step succeeds

4052:    Level: intermediate

4054: .keywords: TS, set, error

4056: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4057: @*/
4058: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4059: {
4062:   ts->errorifstepfailed = err;
4063:   return(0);
4064: }

4068: /*@C
4069:    TSMonitorSolutionBinary - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file

4071:    Collective on TS

4073:    Input Parameters:
4074: +  ts - the TS context
4075: .  step - current time-step
4076: .  ptime - current time
4077: .  u - current state
4078: -  viewer - binary viewer

4080:    Level: intermediate

4082: .keywords: TS,  vector, monitor, view

4084: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4085: @*/
4086: PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
4087: {
4089:   PetscViewer    v = (PetscViewer)viewer;

4092:   VecView(u,v);
4093:   return(0);
4094: }

4098: /*@C
4099:    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.

4101:    Collective on TS

4103:    Input Parameters:
4104: +  ts - the TS context
4105: .  step - current time-step
4106: .  ptime - current time
4107: .  u - current state
4108: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

4110:    Level: intermediate

4112:    Notes:
4113:    The VTK format does not allow writing multiple time steps in the same file, therefore a different file will be written for each time step.
4114:    These are named according to the file name template.

4116:    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().

4118: .keywords: TS,  vector, monitor, view

4120: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4121: @*/
4122: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
4123: {
4125:   char           filename[PETSC_MAX_PATH_LEN];
4126:   PetscViewer    viewer;

4129:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
4130:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
4131:   VecView(u,viewer);
4132:   PetscViewerDestroy(&viewer);
4133:   return(0);
4134: }

4138: /*@C
4139:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

4141:    Collective on TS

4143:    Input Parameters:
4144: .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

4146:    Level: intermediate

4148:    Note:
4149:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

4151: .keywords: TS,  vector, monitor, view

4153: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
4154: @*/
4155: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
4156: {

4160:   PetscFree(*(char**)filenametemplate);
4161:   return(0);
4162: }

4166: /*@
4167:    TSGetAdapt - Get the adaptive controller context for the current method

4169:    Collective on TS if controller has not been created yet

4171:    Input Arguments:
4172: .  ts - time stepping context

4174:    Output Arguments:
4175: .  adapt - adaptive controller

4177:    Level: intermediate

4179: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4180: @*/
4181: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4182: {

4188:   if (!ts->adapt) {
4189:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
4190:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
4191:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
4192:   }
4193:   *adapt = ts->adapt;
4194:   return(0);
4195: }

4199: /*@
4200:    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller

4202:    Logically Collective

4204:    Input Arguments:
4205: +  ts - time integration context
4206: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
4207: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4208: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
4209: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

4211:    Level: beginner

4213: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
4214: @*/
4215: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
4216: {

4220:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4221:   if (vatol) {
4222:     PetscObjectReference((PetscObject)vatol);
4223:     VecDestroy(&ts->vatol);

4225:     ts->vatol = vatol;
4226:   }
4227:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
4228:   if (vrtol) {
4229:     PetscObjectReference((PetscObject)vrtol);
4230:     VecDestroy(&ts->vrtol);

4232:     ts->vrtol = vrtol;
4233:   }
4234:   return(0);
4235: }

4239: /*@
4240:    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller

4242:    Logically Collective

4244:    Input Arguments:
4245: .  ts - time integration context

4247:    Output Arguments:
4248: +  atol - scalar absolute tolerances, NULL to ignore
4249: .  vatol - vector of absolute tolerances, NULL to ignore
4250: .  rtol - scalar relative tolerances, NULL to ignore
4251: -  vrtol - vector of relative tolerances, NULL to ignore

4253:    Level: beginner

4255: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
4256: @*/
4257: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4258: {
4260:   if (atol)  *atol  = ts->atol;
4261:   if (vatol) *vatol = ts->vatol;
4262:   if (rtol)  *rtol  = ts->rtol;
4263:   if (vrtol) *vrtol = ts->vrtol;
4264:   return(0);
4265: }

4269: /*@
4270:    TSErrorNormWRMS - compute a weighted norm of the difference between a vector and the current state

4272:    Collective on TS

4274:    Input Arguments:
4275: +  ts - time stepping context
4276: -  Y - state vector to be compared to ts->vec_sol

4278:    Output Arguments:
4279: .  norm - weighted norm, a value of 1.0 is considered small

4281:    Level: developer

4283: .seealso: TSSetTolerances()
4284: @*/
4285: PetscErrorCode TSErrorNormWRMS(TS ts,Vec Y,PetscReal *norm)
4286: {
4287:   PetscErrorCode    ierr;
4288:   PetscInt          i,n,N;
4289:   const PetscScalar *u,*y;
4290:   Vec               U;
4291:   PetscReal         sum,gsum;

4297:   U = ts->vec_sol;
4299:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"Y cannot be the TS solution vector");

4301:   VecGetSize(U,&N);
4302:   VecGetLocalSize(U,&n);
4303:   VecGetArrayRead(U,&u);
4304:   VecGetArrayRead(Y,&y);
4305:   sum  = 0.;
4306:   if (ts->vatol && ts->vrtol) {
4307:     const PetscScalar *atol,*rtol;
4308:     VecGetArrayRead(ts->vatol,&atol);
4309:     VecGetArrayRead(ts->vrtol,&rtol);
4310:     for (i=0; i<n; i++) {
4311:       PetscReal tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4312:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4313:     }
4314:     VecRestoreArrayRead(ts->vatol,&atol);
4315:     VecRestoreArrayRead(ts->vrtol,&rtol);
4316:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
4317:     const PetscScalar *atol;
4318:     VecGetArrayRead(ts->vatol,&atol);
4319:     for (i=0; i<n; i++) {
4320:       PetscReal tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4321:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4322:     }
4323:     VecRestoreArrayRead(ts->vatol,&atol);
4324:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
4325:     const PetscScalar *rtol;
4326:     VecGetArrayRead(ts->vrtol,&rtol);
4327:     for (i=0; i<n; i++) {
4328:       PetscReal tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4329:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4330:     }
4331:     VecRestoreArrayRead(ts->vrtol,&rtol);
4332:   } else {                      /* scalar atol, scalar rtol */
4333:     for (i=0; i<n; i++) {
4334:       PetscReal tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4335:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4336:     }
4337:   }
4338:   VecRestoreArrayRead(U,&u);
4339:   VecRestoreArrayRead(Y,&y);

4341:   MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
4342:   *norm = PetscSqrtReal(gsum / N);
4343:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
4344:   return(0);
4345: }

4349: /*@
4350:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

4352:    Logically Collective on TS

4354:    Input Arguments:
4355: +  ts - time stepping context
4356: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

4358:    Note:
4359:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

4361:    Level: intermediate

4363: .seealso: TSGetCFLTime(), TSADAPTCFL
4364: @*/
4365: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
4366: {
4369:   ts->cfltime_local = cfltime;
4370:   ts->cfltime       = -1.;
4371:   return(0);
4372: }

4376: /*@
4377:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

4379:    Collective on TS

4381:    Input Arguments:
4382: .  ts - time stepping context

4384:    Output Arguments:
4385: .  cfltime - maximum stable time step for forward Euler

4387:    Level: advanced

4389: .seealso: TSSetCFLTimeLocal()
4390: @*/
4391: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
4392: {

4396:   if (ts->cfltime < 0) {
4397:     MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
4398:   }
4399:   *cfltime = ts->cfltime;
4400:   return(0);
4401: }

4405: /*@
4406:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

4408:    Input Parameters:
4409: .  ts   - the TS context.
4410: .  xl   - lower bound.
4411: .  xu   - upper bound.

4413:    Notes:
4414:    If this routine is not called then the lower and upper bounds are set to
4415:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

4417:    Level: advanced

4419: @*/
4420: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
4421: {
4423:   SNES           snes;

4426:   TSGetSNES(ts,&snes);
4427:   SNESVISetVariableBounds(snes,xl,xu);
4428:   return(0);
4429: }

4431: #if defined(PETSC_HAVE_MATLAB_ENGINE)
4432: #include <mex.h>

4434: typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;

4438: /*
4439:    TSComputeFunction_Matlab - Calls the function that has been set with
4440:                          TSSetFunctionMatlab().

4442:    Collective on TS

4444:    Input Parameters:
4445: +  snes - the TS context
4446: -  u - input vector

4448:    Output Parameter:
4449: .  y - function vector, as set by TSSetFunction()

4451:    Notes:
4452:    TSComputeFunction() is typically used within nonlinear solvers
4453:    implementations, so most users would not generally call this routine
4454:    themselves.

4456:    Level: developer

4458: .keywords: TS, nonlinear, compute, function

4460: .seealso: TSSetFunction(), TSGetFunction()
4461: */
4462: PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
4463: {
4464:   PetscErrorCode  ierr;
4465:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4466:   int             nlhs  = 1,nrhs = 7;
4467:   mxArray         *plhs[1],*prhs[7];
4468:   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;


4478:   PetscMemcpy(&ls,&snes,sizeof(snes));
4479:   PetscMemcpy(&lx,&u,sizeof(u));
4480:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
4481:   PetscMemcpy(&ly,&y,sizeof(u));

4483:   prhs[0] =  mxCreateDoubleScalar((double)ls);
4484:   prhs[1] =  mxCreateDoubleScalar(time);
4485:   prhs[2] =  mxCreateDoubleScalar((double)lx);
4486:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
4487:   prhs[4] =  mxCreateDoubleScalar((double)ly);
4488:   prhs[5] =  mxCreateString(sctx->funcname);
4489:   prhs[6] =  sctx->ctx;
4490:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
4491:    mxGetScalar(plhs[0]);
4492:   mxDestroyArray(prhs[0]);
4493:   mxDestroyArray(prhs[1]);
4494:   mxDestroyArray(prhs[2]);
4495:   mxDestroyArray(prhs[3]);
4496:   mxDestroyArray(prhs[4]);
4497:   mxDestroyArray(prhs[5]);
4498:   mxDestroyArray(plhs[0]);
4499:   return(0);
4500: }


4505: /*
4506:    TSSetFunctionMatlab - Sets the function evaluation routine and function
4507:    vector for use by the TS routines in solving ODEs
4508:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

4510:    Logically Collective on TS

4512:    Input Parameters:
4513: +  ts - the TS context
4514: -  func - function evaluation routine

4516:    Calling sequence of func:
4517: $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);

4519:    Level: beginner

4521: .keywords: TS, nonlinear, set, function

4523: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4524: */
4525: PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
4526: {
4527:   PetscErrorCode  ierr;
4528:   TSMatlabContext *sctx;

4531:   /* currently sctx is memory bleed */
4532:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
4533:   PetscStrallocpy(func,&sctx->funcname);
4534:   /*
4535:      This should work, but it doesn't
4536:   sctx->ctx = ctx;
4537:   mexMakeArrayPersistent(sctx->ctx);
4538:   */
4539:   sctx->ctx = mxDuplicateArray(ctx);

4541:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
4542:   return(0);
4543: }

4547: /*
4548:    TSComputeJacobian_Matlab - Calls the function that has been set with
4549:                          TSSetJacobianMatlab().

4551:    Collective on TS

4553:    Input Parameters:
4554: +  ts - the TS context
4555: .  u - input vector
4556: .  A, B - the matrices
4557: -  ctx - user context

4559:    Output Parameter:
4560: .  flag - structure of the matrix

4562:    Level: developer

4564: .keywords: TS, nonlinear, compute, function

4566: .seealso: TSSetFunction(), TSGetFunction()
4567: @*/
4568: PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flag, void *ctx)
4569: {
4570:   PetscErrorCode  ierr;
4571:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4572:   int             nlhs  = 2,nrhs = 9;
4573:   mxArray         *plhs[2],*prhs[9];
4574:   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;


4580:   /* call Matlab function in ctx with arguments u and y */

4582:   PetscMemcpy(&ls,&ts,sizeof(ts));
4583:   PetscMemcpy(&lx,&u,sizeof(u));
4584:   PetscMemcpy(&lxdot,&udot,sizeof(u));
4585:   PetscMemcpy(&lA,A,sizeof(u));
4586:   PetscMemcpy(&lB,B,sizeof(u));

4588:   prhs[0] =  mxCreateDoubleScalar((double)ls);
4589:   prhs[1] =  mxCreateDoubleScalar((double)time);
4590:   prhs[2] =  mxCreateDoubleScalar((double)lx);
4591:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
4592:   prhs[4] =  mxCreateDoubleScalar((double)shift);
4593:   prhs[5] =  mxCreateDoubleScalar((double)lA);
4594:   prhs[6] =  mxCreateDoubleScalar((double)lB);
4595:   prhs[7] =  mxCreateString(sctx->funcname);
4596:   prhs[8] =  sctx->ctx;
4597:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
4598:    mxGetScalar(plhs[0]);
4599:   *flag   =  (MatStructure) mxGetScalar(plhs[1]);
4600:   mxDestroyArray(prhs[0]);
4601:   mxDestroyArray(prhs[1]);
4602:   mxDestroyArray(prhs[2]);
4603:   mxDestroyArray(prhs[3]);
4604:   mxDestroyArray(prhs[4]);
4605:   mxDestroyArray(prhs[5]);
4606:   mxDestroyArray(prhs[6]);
4607:   mxDestroyArray(prhs[7]);
4608:   mxDestroyArray(plhs[0]);
4609:   mxDestroyArray(plhs[1]);
4610:   return(0);
4611: }


4616: /*
4617:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
4618:    vector for use by the TS routines in solving ODEs from MATLAB. Here the function is a string containing the name of a MATLAB function

4620:    Logically Collective on TS

4622:    Input Parameters:
4623: +  ts - the TS context
4624: .  A,B - Jacobian matrices
4625: .  func - function evaluation routine
4626: -  ctx - user context

4628:    Calling sequence of func:
4629: $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);


4632:    Level: developer

4634: .keywords: TS, nonlinear, set, function

4636: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4637: */
4638: PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
4639: {
4640:   PetscErrorCode  ierr;
4641:   TSMatlabContext *sctx;

4644:   /* currently sctx is memory bleed */
4645:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
4646:   PetscStrallocpy(func,&sctx->funcname);
4647:   /*
4648:      This should work, but it doesn't
4649:   sctx->ctx = ctx;
4650:   mexMakeArrayPersistent(sctx->ctx);
4651:   */
4652:   sctx->ctx = mxDuplicateArray(ctx);

4654:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
4655:   return(0);
4656: }

4660: /*
4661:    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().

4663:    Collective on TS

4665: .seealso: TSSetFunction(), TSGetFunction()
4666: @*/
4667: PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
4668: {
4669:   PetscErrorCode  ierr;
4670:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4671:   int             nlhs  = 1,nrhs = 6;
4672:   mxArray         *plhs[1],*prhs[6];
4673:   long long int   lx = 0,ls = 0;


4679:   PetscMemcpy(&ls,&ts,sizeof(ts));
4680:   PetscMemcpy(&lx,&u,sizeof(u));

4682:   prhs[0] =  mxCreateDoubleScalar((double)ls);
4683:   prhs[1] =  mxCreateDoubleScalar((double)it);
4684:   prhs[2] =  mxCreateDoubleScalar((double)time);
4685:   prhs[3] =  mxCreateDoubleScalar((double)lx);
4686:   prhs[4] =  mxCreateString(sctx->funcname);
4687:   prhs[5] =  sctx->ctx;
4688:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
4689:    mxGetScalar(plhs[0]);
4690:   mxDestroyArray(prhs[0]);
4691:   mxDestroyArray(prhs[1]);
4692:   mxDestroyArray(prhs[2]);
4693:   mxDestroyArray(prhs[3]);
4694:   mxDestroyArray(prhs[4]);
4695:   mxDestroyArray(plhs[0]);
4696:   return(0);
4697: }


4702: /*
4703:    TSMonitorSetMatlab - Sets the monitor function from Matlab

4705:    Level: developer

4707: .keywords: TS, nonlinear, set, function

4709: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4710: */
4711: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
4712: {
4713:   PetscErrorCode  ierr;
4714:   TSMatlabContext *sctx;

4717:   /* currently sctx is memory bleed */
4718:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
4719:   PetscStrallocpy(func,&sctx->funcname);
4720:   /*
4721:      This should work, but it doesn't
4722:   sctx->ctx = ctx;
4723:   mexMakeArrayPersistent(sctx->ctx);
4724:   */
4725:   sctx->ctx = mxDuplicateArray(ctx);

4727:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
4728:   return(0);
4729: }
4730: #endif



4736: /*@C
4737:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
4738:        in a time based line graph

4740:    Collective on TS

4742:    Input Parameters:
4743: +  ts - the TS context
4744: .  step - current time-step
4745: .  ptime - current time
4746: -  lg - a line graph object

4748:    Level: intermediate

4750:     Notes: each process in a parallel run displays its component solutions in a separate window

4752: .keywords: TS,  vector, monitor, view

4754: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4755: @*/
4756: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4757: {
4758:   PetscErrorCode    ierr;
4759:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
4760:   const PetscScalar *yy;
4761:   PetscInt          dim;

4764:   if (!step) {
4765:     PetscDrawAxis axis;
4766:     PetscDrawLGGetAxis(ctx->lg,&axis);
4767:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
4768:     VecGetLocalSize(u,&dim);
4769:     PetscDrawLGSetDimension(ctx->lg,dim);
4770:     PetscDrawLGReset(ctx->lg);
4771:   }
4772:   VecGetArrayRead(u,&yy);
4773: #if defined(PETSC_USE_COMPLEX)
4774:   {
4775:     PetscReal *yreal;
4776:     PetscInt  i,n;
4777:     VecGetLocalSize(u,&n);
4778:     PetscMalloc1(n,&yreal);
4779:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
4780:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
4781:     PetscFree(yreal);
4782:   }
4783: #else
4784:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
4785: #endif
4786:   VecRestoreArrayRead(u,&yy);
4787:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4788:     PetscDrawLGDraw(ctx->lg);
4789:   }
4790:   return(0);
4791: }

4795: /*@C
4796:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
4797:        in a time based line graph

4799:    Collective on TS

4801:    Input Parameters:
4802: +  ts - the TS context
4803: .  step - current time-step
4804: .  ptime - current time
4805: -  lg - a line graph object

4807:    Level: intermediate

4809:    Notes:
4810:    Only for sequential solves.

4812:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

4814:    Options Database Keys:
4815: .  -ts_monitor_lg_error - create a graphical monitor of error history

4817: .keywords: TS,  vector, monitor, view

4819: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4820: @*/
4821: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4822: {
4823:   PetscErrorCode    ierr;
4824:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
4825:   const PetscScalar *yy;
4826:   Vec               y;
4827:   PetscInt          dim;

4830:   if (!step) {
4831:     PetscDrawAxis axis;
4832:     PetscDrawLGGetAxis(ctx->lg,&axis);
4833:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
4834:     VecGetLocalSize(u,&dim);
4835:     PetscDrawLGSetDimension(ctx->lg,dim);
4836:     PetscDrawLGReset(ctx->lg);
4837:   }
4838:   VecDuplicate(u,&y);
4839:   TSComputeSolutionFunction(ts,ptime,y);
4840:   VecAXPY(y,-1.0,u);
4841:   VecGetArrayRead(y,&yy);
4842: #if defined(PETSC_USE_COMPLEX)
4843:   {
4844:     PetscReal *yreal;
4845:     PetscInt  i,n;
4846:     VecGetLocalSize(y,&n);
4847:     PetscMalloc1(n,&yreal);
4848:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
4849:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
4850:     PetscFree(yreal);
4851:   }
4852: #else
4853:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
4854: #endif
4855:   VecRestoreArrayRead(y,&yy);
4856:   VecDestroy(&y);
4857:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4858:     PetscDrawLGDraw(ctx->lg);
4859:   }
4860:   return(0);
4861: }

4865: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
4866: {
4867:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4868:   PetscReal      x   = ptime,y;
4870:   PetscInt       its;

4873:   if (!n) {
4874:     PetscDrawAxis axis;

4876:     PetscDrawLGGetAxis(ctx->lg,&axis);
4877:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
4878:     PetscDrawLGReset(ctx->lg);

4880:     ctx->snes_its = 0;
4881:   }
4882:   TSGetSNESIterations(ts,&its);
4883:   y    = its - ctx->snes_its;
4884:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4885:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
4886:     PetscDrawLGDraw(ctx->lg);
4887:   }
4888:   ctx->snes_its = its;
4889:   return(0);
4890: }

4894: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
4895: {
4896:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4897:   PetscReal      x   = ptime,y;
4899:   PetscInt       its;

4902:   if (!n) {
4903:     PetscDrawAxis axis;

4905:     PetscDrawLGGetAxis(ctx->lg,&axis);
4906:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
4907:     PetscDrawLGReset(ctx->lg);

4909:     ctx->ksp_its = 0;
4910:   }
4911:   TSGetKSPIterations(ts,&its);
4912:   y    = its - ctx->ksp_its;
4913:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4914:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
4915:     PetscDrawLGDraw(ctx->lg);
4916:   }
4917:   ctx->ksp_its = its;
4918:   return(0);
4919: }

4923: /*@
4924:    TSComputeLinearStability - computes the linear stability function at a point

4926:    Collective on TS and Vec

4928:    Input Parameters:
4929: +  ts - the TS context
4930: -  xr,xi - real and imaginary part of input arguments

4932:    Output Parameters:
4933: .  yr,yi - real and imaginary part of function value

4935:    Level: developer

4937: .keywords: TS, compute

4939: .seealso: TSSetRHSFunction(), TSComputeIFunction()
4940: @*/
4941: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
4942: {

4947:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
4948:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
4949:   return(0);
4950: }