Actual source code: ts.c

petsc-master 2017-09-23
Report Typos and Errors
  1:  #include <petsc/private/tsimpl.h>
  2:  #include <petscdmshell.h>
  3:  #include <petscdmda.h>
  4:  #include <petscviewer.h>
  5:  #include <petscdraw.h>

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

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

 13: struct _n_TSMonitorDrawCtx {
 14:   PetscViewer   viewer;
 15:   Vec           initialsolution;
 16:   PetscBool     showinitial;
 17:   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
 18:   PetscBool     showtimestepandtime;
 19: };

 21: /*@C
 22:    TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

 24:    Collective on TS

 26:    Input Parameters:
 27: +  ts - TS object you wish to monitor
 28: .  name - the monitor type one is seeking
 29: .  help - message indicating what monitoring is done
 30: .  manual - manual page for the monitor
 31: .  monitor - the monitor function
 32: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects

 34:    Level: developer

 36: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
 37:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
 38:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
 39:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
 40:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
 41:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
 42:           PetscOptionsFList(), PetscOptionsEList()
 43: @*/
 44: PetscErrorCode  TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
 45: {
 46:   PetscErrorCode    ierr;
 47:   PetscViewer       viewer;
 48:   PetscViewerFormat format;
 49:   PetscBool         flg;

 52:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
 53:   if (flg) {
 54:     PetscViewerAndFormat *vf;
 55:     PetscViewerAndFormatCreate(viewer,format,&vf);
 56:     PetscObjectDereference((PetscObject)viewer);
 57:     if (monitorsetup) {
 58:       (*monitorsetup)(ts,vf);
 59:     }
 60:     TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
 61:   }
 62:   return(0);
 63: }

 65: /*@C
 66:    TSAdjointMonitorSensi - monitors the first lambda sensitivity

 68:    Level: intermediate

 70: .keywords: TS, set, monitor

 72: .seealso: TSAdjointMonitorSet()
 73: @*/
 74: PetscErrorCode TSAdjointMonitorSensi(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
 75: {
 77:   PetscViewer    viewer = vf->viewer;

 81:   PetscViewerPushFormat(viewer,vf->format);
 82:   VecView(lambda[0],viewer);
 83:   PetscViewerPopFormat(viewer);
 84:   return(0);
 85: }

 87: /*@C
 88:    TSAdjointMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

 90:    Collective on TS

 92:    Input Parameters:
 93: +  ts - TS object you wish to monitor
 94: .  name - the monitor type one is seeking
 95: .  help - message indicating what monitoring is done
 96: .  manual - manual page for the monitor
 97: .  monitor - the monitor function
 98: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects

100:    Level: developer

102: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
103:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
104:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
105:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
106:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
107:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
108:           PetscOptionsFList(), PetscOptionsEList()
109: @*/
110: PetscErrorCode  TSAdjointMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
111: {
112:   PetscErrorCode    ierr;
113:   PetscViewer       viewer;
114:   PetscViewerFormat format;
115:   PetscBool         flg;

118:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
119:   if (flg) {
120:     PetscViewerAndFormat *vf;
121:     PetscViewerAndFormatCreate(viewer,format,&vf);
122:     PetscObjectDereference((PetscObject)viewer);
123:     if (monitorsetup) {
124:       (*monitorsetup)(ts,vf);
125:     }
126:     TSAdjointMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
127:   }
128:   return(0);
129: }

131: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
132: {

138:   if (!((PetscObject)adapt)->type_name) {
139:     TSAdaptSetType(adapt,default_type);
140:   }
141:   return(0);
142: }

144: /*@
145:    TSSetFromOptions - Sets various TS parameters from user options.

147:    Collective on TS

149:    Input Parameter:
150: .  ts - the TS context obtained from TSCreate()

152:    Options Database Keys:
153: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE
154: .  -ts_save_trajectory - checkpoint the solution at each time-step
155: .  -ts_max_time <time> - maximum time to compute to
156: .  -ts_max_steps <steps> - maximum number of time-steps to take
157: .  -ts_init_time <time> - initial time to start computation
158: .  -ts_final_time <time> - final time to compute to
159: .  -ts_dt <dt> - initial time step
160: .  -ts_exact_final_time <stepover,interpolate,matchstep> whether to stop at the exact given final time and how to compute the solution at that ti,e
161: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
162: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
163: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
164: .  -ts_rtol <rtol> - relative tolerance for local truncation error
165: .  -ts_atol <atol> Absolute tolerance for local truncation error
166: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
167: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
168: .  -ts_monitor - print information at each timestep
169: .  -ts_monitor_lg_solution - Monitor solution graphically
170: .  -ts_monitor_lg_error - Monitor error graphically
171: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
172: .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
173: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
174: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
175: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
176: .  -ts_monitor_draw_solution - Monitor solution graphically
177: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
178: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
179: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
180: .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
181: .  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
182: .  -ts_adjoint_monitor - print information at each adjoint time step
183: -  -ts_adjoint_monitor_draw_sensi - monitor the sensitivity of the first cost function wrt initial conditions (lambda[0]) graphically

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

187:    Level: beginner

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

191: .seealso: TSGetType()
192: @*/
193: PetscErrorCode  TSSetFromOptions(TS ts)
194: {
195:   PetscBool              opt,flg,tflg;
196:   PetscErrorCode         ierr;
197:   char                   monfilename[PETSC_MAX_PATH_LEN];
198:   PetscReal              time_step;
199:   TSExactFinalTimeOption eftopt;
200:   char                   dir[16];
201:   TSIFunction            ifun;
202:   const char             *defaultType;
203:   char                   typeName[256];


208:   TSRegisterAll();
209:   TSGetIFunction(ts,NULL,&ifun,NULL);

211:   PetscObjectOptionsBegin((PetscObject)ts);
212:   if (((PetscObject)ts)->type_name)
213:     defaultType = ((PetscObject)ts)->type_name;
214:   else
215:     defaultType = ifun ? TSBEULER : TSEULER;
216:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
217:   if (opt) {
218:     TSSetType(ts,typeName);
219:   } else {
220:     TSSetType(ts,defaultType);
221:   }

223:   /* Handle generic TS options */
224:   PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
225:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL);
226:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
227:   PetscOptionsReal("-ts_final_time","Final time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
228:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
229:   if (flg) {TSSetTimeStep(ts,time_step);}
230:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
231:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
232:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
233:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
234:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
235:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
236:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

238: #if defined(PETSC_HAVE_SAWS)
239:   {
240:   PetscBool set;
241:   flg  = PETSC_FALSE;
242:   PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
243:   if (set) {
244:     PetscObjectSAWsSetBlock((PetscObject)ts,flg);
245:   }
246:   }
247: #endif

249:   /* Monitor options */
250:   TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
251:   TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);
252:   TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor","Monitor adjoint timestep size","TSAdjointMonitorDefault",TSAdjointMonitorDefault,NULL);
253:   TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor_sensi","Monitor sensitivity in the adjoint computation","TSAdjointMonitorSensi",TSAdjointMonitorSensi,NULL);

255:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
256:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

258:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
259:   if (opt) {
260:     TSMonitorLGCtx ctx;
261:     PetscInt       howoften = 1;

263:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
264:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
265:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
266:   }

268:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
269:   if (opt) {
270:     TSMonitorLGCtx ctx;
271:     PetscInt       howoften = 1;

273:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
274:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
275:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
276:   }

278:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
279:   if (opt) {
280:     TSMonitorLGCtx ctx;
281:     PetscInt       howoften = 1;

283:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
284:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
285:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
286:   }
287:   PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
288:   if (opt) {
289:     TSMonitorLGCtx ctx;
290:     PetscInt       howoften = 1;

292:     PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
293:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
294:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
295:     ctx->semilogy = PETSC_TRUE;
296:   }

298:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
299:   if (opt) {
300:     TSMonitorLGCtx ctx;
301:     PetscInt       howoften = 1;

303:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
304:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
305:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
306:   }
307:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
308:   if (opt) {
309:     TSMonitorLGCtx ctx;
310:     PetscInt       howoften = 1;

312:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
313:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
314:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
315:   }
316:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
317:   if (opt) {
318:     TSMonitorSPEigCtx ctx;
319:     PetscInt          howoften = 1;

321:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
322:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
323:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
324:   }
325:   opt  = PETSC_FALSE;
326:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
327:   if (opt) {
328:     TSMonitorDrawCtx ctx;
329:     PetscInt         howoften = 1;

331:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
332:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
333:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
334:   }
335:   opt  = PETSC_FALSE;
336:   PetscOptionsName("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",&opt);
337:   if (opt) {
338:     TSMonitorDrawCtx ctx;
339:     PetscInt         howoften = 1;

341:     PetscOptionsInt("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",howoften,&howoften,NULL);
342:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
343:     TSAdjointMonitorSet(ts,TSAdjointMonitorDrawSensi,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
344:   }
345:   opt  = PETSC_FALSE;
346:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
347:   if (opt) {
348:     TSMonitorDrawCtx ctx;
349:     PetscReal        bounds[4];
350:     PetscInt         n = 4;
351:     PetscDraw        draw;
352:     PetscDrawAxis    axis;

354:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
355:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
356:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
357:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
358:     PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
359:     PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
360:     PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
361:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
362:   }
363:   opt  = PETSC_FALSE;
364:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
365:   if (opt) {
366:     TSMonitorDrawCtx ctx;
367:     PetscInt         howoften = 1;

369:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
370:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
371:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
372:   }

374:   opt  = PETSC_FALSE;
375:   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);
376:   if (flg) {
377:     const char *ptr,*ptr2;
378:     char       *filetemplate;
379:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
380:     /* Do some cursory validation of the input. */
381:     PetscStrstr(monfilename,"%",(char**)&ptr);
382:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
383:     for (ptr++; ptr && *ptr; ptr++) {
384:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
385:       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");
386:       if (ptr2) break;
387:     }
388:     PetscStrallocpy(monfilename,&filetemplate);
389:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
390:   }

392:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
393:   if (flg) {
394:     TSMonitorDMDARayCtx *rayctx;
395:     int                  ray = 0;
396:     DMDADirection        ddir;
397:     DM                   da;
398:     PetscMPIInt          rank;

400:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
401:     if (dir[0] == 'x') ddir = DMDA_X;
402:     else if (dir[0] == 'y') ddir = DMDA_Y;
403:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
404:     sscanf(dir+2,"%d",&ray);

406:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
407:     PetscNew(&rayctx);
408:     TSGetDM(ts,&da);
409:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
410:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
411:     if (!rank) {
412:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
413:     }
414:     rayctx->lgctx = NULL;
415:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
416:   }
417:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
418:   if (flg) {
419:     TSMonitorDMDARayCtx *rayctx;
420:     int                 ray = 0;
421:     DMDADirection       ddir;
422:     DM                  da;
423:     PetscInt            howoften = 1;

425:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
426:     if      (dir[0] == 'x') ddir = DMDA_X;
427:     else if (dir[0] == 'y') ddir = DMDA_Y;
428:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
429:     sscanf(dir+2, "%d", &ray);

431:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);
432:     PetscNew(&rayctx);
433:     TSGetDM(ts, &da);
434:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
435:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
436:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
437:   }

439:   PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);
440:   if (opt) {
441:     TSMonitorEnvelopeCtx ctx;

443:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
444:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
445:   }

447:   flg  = PETSC_FALSE;
448:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
449:   if (flg) {
450:     DM   dm;
451:     DMTS tdm;

453:     TSGetDM(ts, &dm);
454:     DMGetDMTS(dm, &tdm);
455:     tdm->ijacobianctx = NULL;
456:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);
457:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
458:   }

460:   /* Handle specific TS options */
461:   if (ts->ops->setfromoptions) {
462:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
463:   }

465:   /* Handle TSAdapt options */
466:   TSGetAdapt(ts,&ts->adapt);
467:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
468:   TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);

470:   /* TS trajectory must be set after TS, since it may use some TS options above */
471:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
472:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
473:   if (tflg) {
474:     TSSetSaveTrajectory(ts);
475:   }
476:   tflg = ts->adjoint_solve ? PETSC_TRUE : PETSC_FALSE;
477:   PetscOptionsBool("-ts_adjoint_solve","Solve the adjoint problem immediately after solving the forward problem","",tflg,&tflg,&flg);
478:   if (flg) {
479:     TSSetSaveTrajectory(ts);
480:     ts->adjoint_solve = tflg;
481:   }

483:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
484:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
485:   PetscOptionsEnd();

487:   if (ts->trajectory) {
488:     TSTrajectorySetFromOptions(ts->trajectory,ts);
489:   }

491:   TSGetSNES(ts,&ts->snes);
492:   if (ts->problem_type == TS_LINEAR) {SNESSetType(ts->snes,SNESKSPONLY);}
493:   SNESSetFromOptions(ts->snes);
494:   return(0);
495: }

497: /*@
498:    TSGetTrajectory - Gets the trajectory from a TS if it exists

500:    Collective on TS

502:    Input Parameters:
503: .  ts - the TS context obtained from TSCreate()

505:    Output Parameters;
506: .  tr - the TSTrajectory object, if it exists

508:    Note: This routine should be called after all TS options have been set

510:    Level: advanced

512: .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectory, TSTrajectoryCreate()

514: .keywords: TS, set, checkpoint,
515: @*/
516: PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
517: {
520:   *tr = ts->trajectory;
521:   return(0);
522: }

524: /*@
525:    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object

527:    Collective on TS

529:    Input Parameters:
530: .  ts - the TS context obtained from TSCreate()

532:    Options Database:
533: +  -ts_save_trajectory - saves the trajectory to a file
534: -  -ts_trajectory_type type

536: Note: This routine should be called after all TS options have been set

538:     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/bin/PetscBinaryIOTrajectory.py and 
539:    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m

541:    Level: intermediate

543: .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectoryType, TSSetTrajectoryType()

545: .keywords: TS, set, checkpoint,
546: @*/
547: PetscErrorCode  TSSetSaveTrajectory(TS ts)
548: {

553:   if (!ts->trajectory) {
554:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
555:     TSTrajectorySetFromOptions(ts->trajectory,ts);
556:   }
557:   return(0);
558: }

560: /*@
561:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
562:       set with TSSetRHSJacobian().

564:    Collective on TS and Vec

566:    Input Parameters:
567: +  ts - the TS context
568: .  t - current timestep
569: -  U - input vector

571:    Output Parameters:
572: +  A - Jacobian matrix
573: .  B - optional preconditioning matrix
574: -  flag - flag indicating matrix structure

576:    Notes:
577:    Most users should not need to explicitly call this routine, as it
578:    is used internally within the nonlinear solvers.

580:    See KSPSetOperators() for important information about setting the
581:    flag parameter.

583:    Level: developer

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

587: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
588: @*/
589: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
590: {
591:   PetscErrorCode   ierr;
592:   PetscObjectState Ustate;
593:   PetscObjectId    Uid;
594:   DM               dm;
595:   DMTS             tsdm;
596:   TSRHSJacobian    rhsjacobianfunc;
597:   void             *ctx;
598:   TSIJacobian      ijacobianfunc;
599:   TSRHSFunction    rhsfunction;

605:   TSGetDM(ts,&dm);
606:   DMGetDMTS(dm,&tsdm);
607:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
608:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
609:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
610:   PetscObjectStateGet((PetscObject)U,&Ustate);
611:   PetscObjectGetId((PetscObject)U,&Uid);
612:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
613:     return(0);
614:   }

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

618:   if (ts->rhsjacobian.reuse) {
619:     MatShift(A,-ts->rhsjacobian.shift);
620:     MatScale(A,1./ts->rhsjacobian.scale);
621:     if (A != B) {
622:       MatShift(B,-ts->rhsjacobian.shift);
623:       MatScale(B,1./ts->rhsjacobian.scale);
624:     }
625:     ts->rhsjacobian.shift = 0;
626:     ts->rhsjacobian.scale = 1.;
627:   }

629:   if (rhsjacobianfunc) {
630:     PetscBool missing;
631:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
632:     PetscStackPush("TS user Jacobian function");
633:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
634:     PetscStackPop;
635:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
636:     if (A) {
637:       MatMissingDiagonal(A,&missing,NULL);
638:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
639:     }
640:     if (B && B != A) {
641:       MatMissingDiagonal(B,&missing,NULL);
642:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
643:     }
644:   } else {
645:     MatZeroEntries(A);
646:     if (A != B) {MatZeroEntries(B);}
647:   }
648:   ts->rhsjacobian.time       = t;
649:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
650:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
651:   return(0);
652: }

654: /*@
655:    TSComputeRHSFunction - Evaluates the right-hand-side function.

657:    Collective on TS and Vec

659:    Input Parameters:
660: +  ts - the TS context
661: .  t - current time
662: -  U - state vector

664:    Output Parameter:
665: .  y - right hand side

667:    Note:
668:    Most users should not need to explicitly call this routine, as it
669:    is used internally within the nonlinear solvers.

671:    Level: developer

673: .keywords: TS, compute

675: .seealso: TSSetRHSFunction(), TSComputeIFunction()
676: @*/
677: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
678: {
680:   TSRHSFunction  rhsfunction;
681:   TSIFunction    ifunction;
682:   void           *ctx;
683:   DM             dm;

689:   TSGetDM(ts,&dm);
690:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
691:   DMTSGetIFunction(dm,&ifunction,NULL);

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

695:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
696:   if (rhsfunction) {
697:     PetscStackPush("TS user right-hand-side function");
698:     (*rhsfunction)(ts,t,U,y,ctx);
699:     PetscStackPop;
700:   } else {
701:     VecZeroEntries(y);
702:   }

704:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
705:   return(0);
706: }

708: /*@
709:    TSComputeSolutionFunction - Evaluates the solution function.

711:    Collective on TS and Vec

713:    Input Parameters:
714: +  ts - the TS context
715: -  t - current time

717:    Output Parameter:
718: .  U - the solution

720:    Note:
721:    Most users should not need to explicitly call this routine, as it
722:    is used internally within the nonlinear solvers.

724:    Level: developer

726: .keywords: TS, compute

728: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
729: @*/
730: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
731: {
732:   PetscErrorCode     ierr;
733:   TSSolutionFunction solutionfunction;
734:   void               *ctx;
735:   DM                 dm;

740:   TSGetDM(ts,&dm);
741:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

743:   if (solutionfunction) {
744:     PetscStackPush("TS user solution function");
745:     (*solutionfunction)(ts,t,U,ctx);
746:     PetscStackPop;
747:   }
748:   return(0);
749: }
750: /*@
751:    TSComputeForcingFunction - Evaluates the forcing function.

753:    Collective on TS and Vec

755:    Input Parameters:
756: +  ts - the TS context
757: -  t - current time

759:    Output Parameter:
760: .  U - the function value

762:    Note:
763:    Most users should not need to explicitly call this routine, as it
764:    is used internally within the nonlinear solvers.

766:    Level: developer

768: .keywords: TS, compute

770: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
771: @*/
772: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
773: {
774:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
775:   void               *ctx;
776:   DM                 dm;

781:   TSGetDM(ts,&dm);
782:   DMTSGetForcingFunction(dm,&forcing,&ctx);

784:   if (forcing) {
785:     PetscStackPush("TS user forcing function");
786:     (*forcing)(ts,t,U,ctx);
787:     PetscStackPop;
788:   }
789:   return(0);
790: }

792: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
793: {
794:   Vec            F;

798:   *Frhs = NULL;
799:   TSGetIFunction(ts,&F,NULL,NULL);
800:   if (!ts->Frhs) {
801:     VecDuplicate(F,&ts->Frhs);
802:   }
803:   *Frhs = ts->Frhs;
804:   return(0);
805: }

807: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
808: {
809:   Mat            A,B;
811:   TSIJacobian    ijacobian;

814:   if (Arhs) *Arhs = NULL;
815:   if (Brhs) *Brhs = NULL;
816:   TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
817:   if (Arhs) {
818:     if (!ts->Arhs) {
819:       if (ijacobian) {
820:         MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
821:       } else {
822:         ts->Arhs = A;
823:         PetscObjectReference((PetscObject)A);
824:       }
825:     } else {
826:       PetscBool flg;
827:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
828:       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
829:       if (flg && !ijacobian && ts->Arhs == ts->Brhs){
830:         PetscObjectDereference((PetscObject)ts->Arhs);
831:         ts->Arhs = A;
832:         PetscObjectReference((PetscObject)A);
833:       }
834:     }
835:     *Arhs = ts->Arhs;
836:   }
837:   if (Brhs) {
838:     if (!ts->Brhs) {
839:       if (A != B) {
840:         if (ijacobian) {
841:           MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
842:         } else {
843:           ts->Brhs = B;
844:           PetscObjectReference((PetscObject)B);
845:         }
846:       } else {
847:         PetscObjectReference((PetscObject)ts->Arhs);
848:         ts->Brhs = ts->Arhs;
849:       }
850:     }
851:     *Brhs = ts->Brhs;
852:   }
853:   return(0);
854: }

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

859:    Collective on TS and Vec

861:    Input Parameters:
862: +  ts - the TS context
863: .  t - current time
864: .  U - state vector
865: .  Udot - time derivative of state vector
866: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

868:    Output Parameter:
869: .  Y - right hand side

871:    Note:
872:    Most users should not need to explicitly call this routine, as it
873:    is used internally within the nonlinear solvers.

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

878:    Level: developer

880: .keywords: TS, compute

882: .seealso: TSSetIFunction(), TSComputeRHSFunction()
883: @*/
884: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
885: {
887:   TSIFunction    ifunction;
888:   TSRHSFunction  rhsfunction;
889:   void           *ctx;
890:   DM             dm;


898:   TSGetDM(ts,&dm);
899:   DMTSGetIFunction(dm,&ifunction,&ctx);
900:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

904:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
905:   if (ifunction) {
906:     PetscStackPush("TS user implicit function");
907:     (*ifunction)(ts,t,U,Udot,Y,ctx);
908:     PetscStackPop;
909:   }
910:   if (imex) {
911:     if (!ifunction) {
912:       VecCopy(Udot,Y);
913:     }
914:   } else if (rhsfunction) {
915:     if (ifunction) {
916:       Vec Frhs;
917:       TSGetRHSVec_Private(ts,&Frhs);
918:       TSComputeRHSFunction(ts,t,U,Frhs);
919:       VecAXPY(Y,-1,Frhs);
920:     } else {
921:       TSComputeRHSFunction(ts,t,U,Y);
922:       VecAYPX(Y,-1,Udot);
923:     }
924:   }
925:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
926:   return(0);
927: }

929: /*@
930:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

932:    Collective on TS and Vec

934:    Input
935:       Input Parameters:
936: +  ts - the TS context
937: .  t - current timestep
938: .  U - state vector
939: .  Udot - time derivative of state vector
940: .  shift - shift to apply, see note below
941: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

943:    Output Parameters:
944: +  A - Jacobian matrix
945: -  B - matrix from which the preconditioner is constructed; often the same as A

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

950:    dF/dU + shift*dF/dUdot

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

955:    Level: developer

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

959: .seealso:  TSSetIJacobian()
960: @*/
961: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
962: {
964:   TSIJacobian    ijacobian;
965:   TSRHSJacobian  rhsjacobian;
966:   DM             dm;
967:   void           *ctx;


978:   TSGetDM(ts,&dm);
979:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
980:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

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

984:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
985:   if (ijacobian) {
986:     PetscBool missing;
987:     PetscStackPush("TS user implicit Jacobian");
988:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
989:     PetscStackPop;
990:     MatMissingDiagonal(A,&missing,NULL);
991:     if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
992:     if (B != A) {
993:       MatMissingDiagonal(B,&missing,NULL);
994:       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
995:     }
996:   }
997:   if (imex) {
998:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
999:       PetscBool assembled;
1000:       MatZeroEntries(A);
1001:       MatAssembled(A,&assembled);
1002:       if (!assembled) {
1003:         MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
1004:         MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
1005:       }
1006:       MatShift(A,shift);
1007:       if (A != B) {
1008:         MatZeroEntries(B);
1009:         MatAssembled(B,&assembled);
1010:         if (!assembled) {
1011:           MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
1012:           MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
1013:         }
1014:         MatShift(B,shift);
1015:       }
1016:     }
1017:   } else {
1018:     Mat Arhs = NULL,Brhs = NULL;
1019:     if (rhsjacobian) {
1020:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
1021:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
1022:     }
1023:     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
1024:       PetscBool flg;
1025:       ts->rhsjacobian.scale = -1;
1026:       ts->rhsjacobian.shift = shift;
1027:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
1028:       /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
1029:       if (!flg) {
1030:         MatScale(A,-1);
1031:         MatShift(A,shift);
1032:       }
1033:       if (A != B) {
1034:         MatScale(B,-1);
1035:         MatShift(B,shift);
1036:       }
1037:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
1038:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1039:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
1040:         MatZeroEntries(A);
1041:         MatShift(A,shift);
1042:         if (A != B) {
1043:           MatZeroEntries(B);
1044:           MatShift(B,shift);
1045:         }
1046:       }
1047:       MatAXPY(A,-1,Arhs,axpy);
1048:       if (A != B) {
1049:         MatAXPY(B,-1,Brhs,axpy);
1050:       }
1051:     }
1052:   }
1053:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
1054:   return(0);
1055: }

1057: /*@C
1058:     TSSetRHSFunction - Sets the routine for evaluating the function,
1059:     where U_t = G(t,u).

1061:     Logically Collective on TS

1063:     Input Parameters:
1064: +   ts - the TS context obtained from TSCreate()
1065: .   r - vector to put the computed right hand side (or NULL to have it created)
1066: .   f - routine for evaluating the right-hand-side function
1067: -   ctx - [optional] user-defined context for private data for the
1068:           function evaluation routine (may be NULL)

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

1073: +   t - current timestep
1074: .   u - input vector
1075: .   F - function vector
1076: -   ctx - [optional] user-defined function context

1078:     Level: beginner

1080:     Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.

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

1084: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1085: @*/
1086: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1087: {
1089:   SNES           snes;
1090:   Vec            ralloc = NULL;
1091:   DM             dm;


1097:   TSGetDM(ts,&dm);
1098:   DMTSSetRHSFunction(dm,f,ctx);
1099:   TSGetSNES(ts,&snes);
1100:   if (!r && !ts->dm && ts->vec_sol) {
1101:     VecDuplicate(ts->vec_sol,&ralloc);
1102:     r = ralloc;
1103:   }
1104:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1105:   VecDestroy(&ralloc);
1106:   return(0);
1107: }

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

1112:     Logically Collective on TS

1114:     Input Parameters:
1115: +   ts - the TS context obtained from TSCreate()
1116: .   f - routine for evaluating the solution
1117: -   ctx - [optional] user-defined context for private data for the
1118:           function evaluation routine (may be NULL)

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

1123: +   t - current timestep
1124: .   u - output vector
1125: -   ctx - [optional] user-defined function context

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

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

1134:     Level: beginner

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

1138: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
1139: @*/
1140: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1141: {
1143:   DM             dm;

1147:   TSGetDM(ts,&dm);
1148:   DMTSSetSolutionFunction(dm,f,ctx);
1149:   return(0);
1150: }

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

1155:     Logically Collective on TS

1157:     Input Parameters:
1158: +   ts - the TS context obtained from TSCreate()
1159: .   func - routine for evaluating the forcing function
1160: -   ctx - [optional] user-defined context for private data for the
1161:           function evaluation routine (may be NULL)

1163:     Calling sequence of func:
1164: $     func (TS ts,PetscReal t,Vec f,void *ctx);

1166: +   t - current timestep
1167: .   f - output vector
1168: -   ctx - [optional] user-defined function context

1170:     Notes:
1171:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1172:     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1173:     definition of the problem you are solving and hence possibly introducing bugs.

1175:     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0

1177:     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1178:     parameters can be passed in the ctx variable.

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

1182:     Level: beginner

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

1186: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1187: @*/
1188: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1189: {
1191:   DM             dm;

1195:   TSGetDM(ts,&dm);
1196:   DMTSSetForcingFunction(dm,func,ctx);
1197:   return(0);
1198: }

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

1204:    Logically Collective on TS

1206:    Input Parameters:
1207: +  ts  - the TS context obtained from TSCreate()
1208: .  Amat - (approximate) Jacobian matrix
1209: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1210: .  f   - the Jacobian evaluation routine
1211: -  ctx - [optional] user-defined context for private data for the
1212:          Jacobian evaluation routine (may be NULL)

1214:    Calling sequence of f:
1215: $     func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);

1217: +  t - current timestep
1218: .  u - input vector
1219: .  Amat - (approximate) Jacobian matrix
1220: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1221: -  ctx - [optional] user-defined context for matrix evaluation routine

1223:    Notes:
1224:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

1226:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1227:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

1229:    Level: beginner

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

1233: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()

1235: @*/
1236: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1237: {
1239:   SNES           snes;
1240:   DM             dm;
1241:   TSIJacobian    ijacobian;


1250:   TSGetDM(ts,&dm);
1251:   DMTSSetRHSJacobian(dm,f,ctx);
1252:   if (f == TSComputeRHSJacobianConstant) {
1253:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1254:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1255:   }
1256:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1257:   TSGetSNES(ts,&snes);
1258:   if (!ijacobian) {
1259:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1260:   }
1261:   if (Amat) {
1262:     PetscObjectReference((PetscObject)Amat);
1263:     MatDestroy(&ts->Arhs);
1264:     ts->Arhs = Amat;
1265:   }
1266:   if (Pmat) {
1267:     PetscObjectReference((PetscObject)Pmat);
1268:     MatDestroy(&ts->Brhs);
1269:     ts->Brhs = Pmat;
1270:   }
1271:   return(0);
1272: }

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

1277:    Logically Collective on TS

1279:    Input Parameters:
1280: +  ts  - the TS context obtained from TSCreate()
1281: .  r   - vector to hold the residual (or NULL to have it created internally)
1282: .  f   - the function evaluation routine
1283: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

1288: +  t   - time at step/stage being solved
1289: .  u   - state vector
1290: .  u_t - time derivative of state vector
1291: .  F   - function vector
1292: -  ctx - [optional] user-defined context for matrix evaluation routine

1294:    Important:
1295:    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.

1297:    Level: beginner

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

1301: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1302: @*/
1303: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1304: {
1306:   SNES           snes;
1307:   Vec            ralloc = NULL;
1308:   DM             dm;


1314:   TSGetDM(ts,&dm);
1315:   DMTSSetIFunction(dm,f,ctx);

1317:   TSGetSNES(ts,&snes);
1318:   if (!r && !ts->dm && ts->vec_sol) {
1319:     VecDuplicate(ts->vec_sol,&ralloc);
1320:     r  = ralloc;
1321:   }
1322:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
1323:   VecDestroy(&ralloc);
1324:   return(0);
1325: }

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

1330:    Not Collective

1332:    Input Parameter:
1333: .  ts - the TS context

1335:    Output Parameter:
1336: +  r - vector to hold residual (or NULL)
1337: .  func - the function to compute residual (or NULL)
1338: -  ctx - the function context (or NULL)

1340:    Level: advanced

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

1344: .seealso: TSSetIFunction(), SNESGetFunction()
1345: @*/
1346: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1347: {
1349:   SNES           snes;
1350:   DM             dm;

1354:   TSGetSNES(ts,&snes);
1355:   SNESGetFunction(snes,r,NULL,NULL);
1356:   TSGetDM(ts,&dm);
1357:   DMTSGetIFunction(dm,func,ctx);
1358:   return(0);
1359: }

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

1364:    Not Collective

1366:    Input Parameter:
1367: .  ts - the TS context

1369:    Output Parameter:
1370: +  r - vector to hold computed right hand side (or NULL)
1371: .  func - the function to compute right hand side (or NULL)
1372: -  ctx - the function context (or NULL)

1374:    Level: advanced

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

1378: .seealso: TSSetRHSFunction(), SNESGetFunction()
1379: @*/
1380: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1381: {
1383:   SNES           snes;
1384:   DM             dm;

1388:   TSGetSNES(ts,&snes);
1389:   SNESGetFunction(snes,r,NULL,NULL);
1390:   TSGetDM(ts,&dm);
1391:   DMTSGetRHSFunction(dm,func,ctx);
1392:   return(0);
1393: }

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

1399:    Logically Collective on TS

1401:    Input Parameters:
1402: +  ts  - the TS context obtained from TSCreate()
1403: .  Amat - (approximate) Jacobian matrix
1404: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1405: .  f   - the Jacobian evaluation routine
1406: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

1411: +  t    - time at step/stage being solved
1412: .  U    - state vector
1413: .  U_t  - time derivative of state vector
1414: .  a    - shift
1415: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1416: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1417: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

1422:    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1423:    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

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

1432:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

1434:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1435:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

1437:    Level: beginner

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

1441: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()

1443: @*/
1444: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1445: {
1447:   SNES           snes;
1448:   DM             dm;


1457:   TSGetDM(ts,&dm);
1458:   DMTSSetIJacobian(dm,f,ctx);

1460:   TSGetSNES(ts,&snes);
1461:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1462:   return(0);
1463: }

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

1471:    Logically Collective

1473:    Input Arguments:
1474: +  ts - TS context obtained from TSCreate()
1475: -  reuse - PETSC_TRUE if the RHS Jacobian

1477:    Level: intermediate

1479: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1480: @*/
1481: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1482: {
1484:   ts->rhsjacobian.reuse = reuse;
1485:   return(0);
1486: }

1488: /*@C
1489:    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.

1491:    Logically Collective on TS

1493:    Input Parameters:
1494: +  ts  - the TS context obtained from TSCreate()
1495: .  F   - vector to hold the residual (or NULL to have it created internally)
1496: .  fun - the function evaluation routine
1497: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1499:    Calling sequence of fun:
1500: $  fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);

1502: +  t    - time at step/stage being solved
1503: .  U    - state vector
1504: .  U_t  - time derivative of state vector
1505: .  U_tt - second time derivative of state vector
1506: .  F    - function vector
1507: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

1509:    Level: beginner

1511: .keywords: TS, timestep, set, ODE, DAE, Function

1513: .seealso: TSSetI2Jacobian()
1514: @*/
1515: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1516: {
1517:   DM             dm;

1523:   TSSetIFunction(ts,F,NULL,NULL);
1524:   TSGetDM(ts,&dm);
1525:   DMTSSetI2Function(dm,fun,ctx);
1526:   return(0);
1527: }

1529: /*@C
1530:   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.

1532:   Not Collective

1534:   Input Parameter:
1535: . ts - the TS context

1537:   Output Parameter:
1538: + r - vector to hold residual (or NULL)
1539: . fun - the function to compute residual (or NULL)
1540: - ctx - the function context (or NULL)

1542:   Level: advanced

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

1546: .seealso: TSSetI2Function(), SNESGetFunction()
1547: @*/
1548: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1549: {
1551:   SNES           snes;
1552:   DM             dm;

1556:   TSGetSNES(ts,&snes);
1557:   SNESGetFunction(snes,r,NULL,NULL);
1558:   TSGetDM(ts,&dm);
1559:   DMTSGetI2Function(dm,fun,ctx);
1560:   return(0);
1561: }

1563: /*@C
1564:    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1565:         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().

1567:    Logically Collective on TS

1569:    Input Parameters:
1570: +  ts  - the TS context obtained from TSCreate()
1571: .  J   - Jacobian matrix
1572: .  P   - preconditioning matrix for J (may be same as J)
1573: .  jac - the Jacobian evaluation routine
1574: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

1576:    Calling sequence of jac:
1577: $  jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);

1579: +  t    - time at step/stage being solved
1580: .  U    - state vector
1581: .  U_t  - time derivative of state vector
1582: .  U_tt - second time derivative of state vector
1583: .  v    - shift for U_t
1584: .  a    - shift for U_tt
1585: .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1586: .  P    - preconditioning matrix for J, may be same as J
1587: -  ctx  - [optional] user-defined context for matrix evaluation routine

1589:    Notes:
1590:    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.

1592:    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1593:    the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
1594:    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1595:    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.

1597:    Level: beginner

1599: .keywords: TS, timestep, set, ODE, DAE, Jacobian

1601: .seealso: TSSetI2Function()
1602: @*/
1603: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1604: {
1605:   DM             dm;

1612:   TSSetIJacobian(ts,J,P,NULL,NULL);
1613:   TSGetDM(ts,&dm);
1614:   DMTSSetI2Jacobian(dm,jac,ctx);
1615:   return(0);
1616: }

1618: /*@C
1619:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

1623:   Input Parameter:
1624: . ts  - The TS context obtained from TSCreate()

1626:   Output Parameters:
1627: + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1628: . P - The matrix from which the preconditioner is constructed, often the same as J
1629: . jac - The function to compute the Jacobian matrices
1630: - ctx - User-defined context for Jacobian evaluation routine

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

1634:   Level: advanced

1636: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

1638: .keywords: TS, timestep, get, matrix, Jacobian
1639: @*/
1640: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1641: {
1643:   SNES           snes;
1644:   DM             dm;

1647:   TSGetSNES(ts,&snes);
1648:   SNESSetUpMatrices(snes);
1649:   SNESGetJacobian(snes,J,P,NULL,NULL);
1650:   TSGetDM(ts,&dm);
1651:   DMTSGetI2Jacobian(dm,jac,ctx);
1652:   return(0);
1653: }

1655: /*@
1656:   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0

1658:   Collective on TS and Vec

1660:   Input Parameters:
1661: + ts - the TS context
1662: . t - current time
1663: . U - state vector
1664: . V - time derivative of state vector (U_t)
1665: - A - second time derivative of state vector (U_tt)

1667:   Output Parameter:
1668: . F - the residual vector

1670:   Note:
1671:   Most users should not need to explicitly call this routine, as it
1672:   is used internally within the nonlinear solvers.

1674:   Level: developer

1676: .keywords: TS, compute, function, vector

1678: .seealso: TSSetI2Function()
1679: @*/
1680: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1681: {
1682:   DM             dm;
1683:   TSI2Function   I2Function;
1684:   void           *ctx;
1685:   TSRHSFunction  rhsfunction;


1695:   TSGetDM(ts,&dm);
1696:   DMTSGetI2Function(dm,&I2Function,&ctx);
1697:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

1699:   if (!I2Function) {
1700:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
1701:     return(0);
1702:   }

1704:   PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);

1706:   PetscStackPush("TS user implicit function");
1707:   I2Function(ts,t,U,V,A,F,ctx);
1708:   PetscStackPop;

1710:   if (rhsfunction) {
1711:     Vec Frhs;
1712:     TSGetRHSVec_Private(ts,&Frhs);
1713:     TSComputeRHSFunction(ts,t,U,Frhs);
1714:     VecAXPY(F,-1,Frhs);
1715:   }

1717:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
1718:   return(0);
1719: }

1721: /*@
1722:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

1724:   Collective on TS and Vec

1726:   Input Parameters:
1727: + ts - the TS context
1728: . t - current timestep
1729: . U - state vector
1730: . V - time derivative of state vector
1731: . A - second time derivative of state vector
1732: . shiftV - shift to apply, see note below
1733: - shiftA - shift to apply, see note below

1735:   Output Parameters:
1736: + J - Jacobian matrix
1737: - P - optional preconditioning matrix

1739:   Notes:
1740:   If F(t,U,V,A)=0 is the DAE, the required Jacobian is

1742:   dF/dU + shiftV*dF/dV + shiftA*dF/dA

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

1747:   Level: developer

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

1751: .seealso:  TSSetI2Jacobian()
1752: @*/
1753: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1754: {
1755:   DM             dm;
1756:   TSI2Jacobian   I2Jacobian;
1757:   void           *ctx;
1758:   TSRHSJacobian  rhsjacobian;


1769:   TSGetDM(ts,&dm);
1770:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
1771:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

1773:   if (!I2Jacobian) {
1774:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
1775:     return(0);
1776:   }

1778:   PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);

1780:   PetscStackPush("TS user implicit Jacobian");
1781:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
1782:   PetscStackPop;

1784:   if (rhsjacobian) {
1785:     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1786:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
1787:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
1788:     MatAXPY(J,-1,Jrhs,axpy);
1789:     if (P != J) {MatAXPY(P,-1,Prhs,axpy);}
1790:   }

1792:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
1793:   return(0);
1794: }

1796: /*@
1797:    TS2SetSolution - Sets the initial solution and time derivative vectors
1798:    for use by the TS routines handling second order equations.

1800:    Logically Collective on TS and Vec

1802:    Input Parameters:
1803: +  ts - the TS context obtained from TSCreate()
1804: .  u - the solution vector
1805: -  v - the time derivative vector

1807:    Level: beginner

1809: .keywords: TS, timestep, set, solution, initial conditions
1810: @*/
1811: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1812: {

1819:   TSSetSolution(ts,u);
1820:   PetscObjectReference((PetscObject)v);
1821:   VecDestroy(&ts->vec_dot);
1822:   ts->vec_dot = v;
1823:   return(0);
1824: }

1826: /*@
1827:    TS2GetSolution - Returns the solution and time derivative at the present timestep
1828:    for second order equations. It is valid to call this routine inside the function
1829:    that you are evaluating in order to move to the new timestep. This vector not
1830:    changed until the solution at the next timestep has been calculated.

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

1834:    Input Parameter:
1835: .  ts - the TS context obtained from TSCreate()

1837:    Output Parameter:
1838: +  u - the vector containing the solution
1839: -  v - the vector containing the time derivative

1841:    Level: intermediate

1843: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()

1845: .keywords: TS, timestep, get, solution
1846: @*/
1847: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1848: {
1853:   if (u) *u = ts->vec_sol;
1854:   if (v) *v = ts->vec_dot;
1855:   return(0);
1856: }

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

1861:   Collective on PetscViewer

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

1868:    Level: intermediate

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

1873:   Notes for advanced users:
1874:   Most users should not need to know the details of the binary storage
1875:   format, since TSLoad() and TSView() completely hide these details.
1876:   But for anyone who's interested, the standard binary matrix storage
1877:   format is
1878: .vb
1879:      has not yet been determined
1880: .ve

1882: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1883: @*/
1884: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1885: {
1887:   PetscBool      isbinary;
1888:   PetscInt       classid;
1889:   char           type[256];
1890:   DMTS           sdm;
1891:   DM             dm;

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

1899:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1900:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1901:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1902:   TSSetType(ts, type);
1903:   if (ts->ops->load) {
1904:     (*ts->ops->load)(ts,viewer);
1905:   }
1906:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1907:   DMLoad(dm,viewer);
1908:   TSSetDM(ts,dm);
1909:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1910:   VecLoad(ts->vec_sol,viewer);
1911:   DMGetDMTS(ts->dm,&sdm);
1912:   DMTSLoad(sdm,viewer);
1913:   return(0);
1914: }

1916:  #include <petscdraw.h>
1917: #if defined(PETSC_HAVE_SAWS)
1918:  #include <petscviewersaws.h>
1919: #endif
1920: /*@C
1921:     TSView - Prints the TS data structure.

1923:     Collective on TS

1925:     Input Parameters:
1926: +   ts - the TS context obtained from TSCreate()
1927: -   viewer - visualization context

1929:     Options Database Key:
1930: .   -ts_view - calls TSView() at end of TSStep()

1932:     Notes:
1933:     The available visualization contexts include
1934: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1935: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1936:          output where only the first processor opens
1937:          the file.  All other processors send their
1938:          data to the first processor to print.

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

1943:     Level: beginner

1945: .keywords: TS, timestep, view

1947: .seealso: PetscViewerASCIIOpen()
1948: @*/
1949: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1950: {
1952:   TSType         type;
1953:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1954:   DMTS           sdm;
1955: #if defined(PETSC_HAVE_SAWS)
1956:   PetscBool      issaws;
1957: #endif

1961:   if (!viewer) {
1962:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1963:   }

1967:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1968:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1969:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1970:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1971: #if defined(PETSC_HAVE_SAWS)
1972:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1973: #endif
1974:   if (iascii) {
1975:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1976:     if (ts->ops->view) {
1977:       PetscViewerASCIIPushTab(viewer);
1978:       (*ts->ops->view)(ts,viewer);
1979:       PetscViewerASCIIPopTab(viewer);
1980:     }
1981:     if (ts->max_steps < PETSC_MAX_INT) {
1982:       PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
1983:     }
1984:     if (ts->max_time < PETSC_MAX_REAL) {
1985:       PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
1986:     }
1987:     if (ts->usessnes) {
1988:       PetscBool lin;
1989:       if (ts->problem_type == TS_NONLINEAR) {
1990:         PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
1991:       }
1992:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
1993:       PetscObjectTypeCompare((PetscObject)ts->snes,SNESKSPONLY,&lin);
1994:       PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
1995:     }
1996:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
1997:     if (ts->vrtol) {
1998:       PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");
1999:     } else {
2000:       PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);
2001:     }
2002:     if (ts->vatol) {
2003:       PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");
2004:     } else {
2005:       PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);
2006:     }
2007:     TSAdaptView(ts->adapt,viewer);
2008:     if (ts->snes && ts->usessnes)  {SNESView(ts->snes,viewer);}
2009:     DMGetDMTS(ts->dm,&sdm);
2010:     DMTSView(sdm,viewer);
2011:   } else if (isstring) {
2012:     TSGetType(ts,&type);
2013:     PetscViewerStringSPrintf(viewer," %-7.7s",type);
2014:   } else if (isbinary) {
2015:     PetscInt    classid = TS_FILE_CLASSID;
2016:     MPI_Comm    comm;
2017:     PetscMPIInt rank;
2018:     char        type[256];

2020:     PetscObjectGetComm((PetscObject)ts,&comm);
2021:     MPI_Comm_rank(comm,&rank);
2022:     if (!rank) {
2023:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
2024:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
2025:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
2026:     }
2027:     if (ts->ops->view) {
2028:       (*ts->ops->view)(ts,viewer);
2029:     }
2030:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2031:     DMView(ts->dm,viewer);
2032:     VecView(ts->vec_sol,viewer);
2033:     DMGetDMTS(ts->dm,&sdm);
2034:     DMTSView(sdm,viewer);
2035:   } else if (isdraw) {
2036:     PetscDraw draw;
2037:     char      str[36];
2038:     PetscReal x,y,bottom,h;

2040:     PetscViewerDrawGetDraw(viewer,0,&draw);
2041:     PetscDrawGetCurrentPoint(draw,&x,&y);
2042:     PetscStrcpy(str,"TS: ");
2043:     PetscStrcat(str,((PetscObject)ts)->type_name);
2044:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
2045:     bottom = y - h;
2046:     PetscDrawPushCurrentPoint(draw,x,bottom);
2047:     if (ts->ops->view) {
2048:       (*ts->ops->view)(ts,viewer);
2049:     }
2050:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
2051:     if (ts->snes)  {SNESView(ts->snes,viewer);}
2052:     PetscDrawPopCurrentPoint(draw);
2053: #if defined(PETSC_HAVE_SAWS)
2054:   } else if (issaws) {
2055:     PetscMPIInt rank;
2056:     const char  *name;

2058:     PetscObjectGetName((PetscObject)ts,&name);
2059:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
2060:     if (!((PetscObject)ts)->amsmem && !rank) {
2061:       char       dir[1024];

2063:       PetscObjectViewSAWs((PetscObject)ts,viewer);
2064:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
2065:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2066:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
2067:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2068:     }
2069:     if (ts->ops->view) {
2070:       (*ts->ops->view)(ts,viewer);
2071:     }
2072: #endif
2073:   }

2075:   PetscViewerASCIIPushTab(viewer);
2076:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
2077:   PetscViewerASCIIPopTab(viewer);
2078:   return(0);
2079: }

2081: /*@
2082:    TSSetApplicationContext - Sets an optional user-defined context for
2083:    the timesteppers.

2085:    Logically Collective on TS

2087:    Input Parameters:
2088: +  ts - the TS context obtained from TSCreate()
2089: -  usrP - optional user context

2091:    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2092:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

2094:    Level: intermediate

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

2098: .seealso: TSGetApplicationContext()
2099: @*/
2100: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2101: {
2104:   ts->user = usrP;
2105:   return(0);
2106: }

2108: /*@
2109:     TSGetApplicationContext - Gets the user-defined context for the
2110:     timestepper.

2112:     Not Collective

2114:     Input Parameter:
2115: .   ts - the TS context obtained from TSCreate()

2117:     Output Parameter:
2118: .   usrP - user context

2120:    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2121:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

2123:     Level: intermediate

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

2127: .seealso: TSSetApplicationContext()
2128: @*/
2129: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2130: {
2133:   *(void**)usrP = ts->user;
2134:   return(0);
2135: }

2137: /*@
2138:    TSGetStepNumber - Gets the number of steps completed.

2140:    Not Collective

2142:    Input Parameter:
2143: .  ts - the TS context obtained from TSCreate()

2145:    Output Parameter:
2146: .  steps - number of steps completed so far

2148:    Level: intermediate

2150: .keywords: TS, timestep, get, iteration, number
2151: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2152: @*/
2153: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2154: {
2158:   *steps = ts->steps;
2159:   return(0);
2160: }

2162: /*@
2163:    TSSetStepNumber - Sets the number of steps completed.

2165:    Logically Collective on TS

2167:    Input Parameters:
2168: +  ts - the TS context
2169: -  steps - number of steps completed so far

2171:    Notes:
2172:    For most uses of the TS solvers the user need not explicitly call
2173:    TSSetStepNumber(), as the step counter is appropriately updated in
2174:    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
2175:    reinitialize timestepping by setting the step counter to zero (and time
2176:    to the initial time) to solve a similar problem with different initial
2177:    conditions or parameters. Other possible use case is to continue
2178:    timestepping from a previously interrupted run in such a way that TS
2179:    monitors will be called with a initial nonzero step counter.

2181:    Level: advanced

2183: .keywords: TS, timestep, set, iteration, number
2184: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
2185: @*/
2186: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
2187: {
2191:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
2192:   ts->steps = steps;
2193:   return(0);
2194: }

2196: /*@
2197:    TSSetTimeStep - Allows one to reset the timestep at any time,
2198:    useful for simple pseudo-timestepping codes.

2200:    Logically Collective on TS

2202:    Input Parameters:
2203: +  ts - the TS context obtained from TSCreate()
2204: -  time_step - the size of the timestep

2206:    Level: intermediate

2208: .seealso: TSGetTimeStep(), TSSetTime()

2210: .keywords: TS, set, timestep
2211: @*/
2212: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2213: {
2217:   ts->time_step = time_step;
2218:   return(0);
2219: }

2221: /*@
2222:    TSSetExactFinalTime - Determines whether to adapt the final time step to
2223:      match the exact final time, interpolate solution to the exact final time,
2224:      or just return at the final time TS computed.

2226:   Logically Collective on TS

2228:    Input Parameter:
2229: +   ts - the time-step context
2230: -   eftopt - exact final time option

2232: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2233: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2234: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

2236:    Options Database:
2237: .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime

2239:    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2240:     then the final time you selected.

2242:    Level: beginner

2244: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
2245: @*/
2246: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2247: {
2251:   ts->exact_final_time = eftopt;
2252:   return(0);
2253: }

2255: /*@
2256:    TSGetExactFinalTime - Gets the exact final time option.

2258:    Not Collective

2260:    Input Parameter:
2261: .  ts - the TS context

2263:    Output Parameter:
2264: .  eftopt - exact final time option

2266:    Level: beginner

2268: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
2269: @*/
2270: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2271: {
2275:   *eftopt = ts->exact_final_time;
2276:   return(0);
2277: }

2279: /*@
2280:    TSGetTimeStep - Gets the current timestep size.

2282:    Not Collective

2284:    Input Parameter:
2285: .  ts - the TS context obtained from TSCreate()

2287:    Output Parameter:
2288: .  dt - the current timestep size

2290:    Level: intermediate

2292: .seealso: TSSetTimeStep(), TSGetTime()

2294: .keywords: TS, get, timestep
2295: @*/
2296: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2297: {
2301:   *dt = ts->time_step;
2302:   return(0);
2303: }

2305: /*@
2306:    TSGetSolution - Returns the solution at the present timestep. It
2307:    is valid to call this routine inside the function that you are evaluating
2308:    in order to move to the new timestep. This vector not changed until
2309:    the solution at the next timestep has been calculated.

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

2313:    Input Parameter:
2314: .  ts - the TS context obtained from TSCreate()

2316:    Output Parameter:
2317: .  v - the vector containing the solution

2319:    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2320:    final time. It returns the solution at the next timestep.

2322:    Level: intermediate

2324: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime(), TSGetSolutionComponents()

2326: .keywords: TS, timestep, get, solution
2327: @*/
2328: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2329: {
2333:   *v = ts->vec_sol;
2334:   return(0);
2335: }

2337: /*@
2338:    TSGetSolutionComponents - Returns any solution components at the present 
2339:    timestep, if available for the time integration method being used. 
2340:    Solution components are quantities that share the same size and 
2341:    structure as the solution vector.

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

2345:    Parameters :
2346: .  ts - the TS context obtained from TSCreate() (input parameter).
2347: .  n - If v is PETSC_NULL, then the number of solution components is
2348:        returned through n, else the n-th solution component is 
2349:        returned in v.
2350: .  v - the vector containing the n-th solution component 
2351:        (may be PETSC_NULL to use this function to find out
2352:         the number of solutions components).

2354:    Level: advanced

2356: .seealso: TSGetSolution()

2358: .keywords: TS, timestep, get, solution
2359: @*/
2360: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2361: {

2366:   if (!ts->ops->getsolutioncomponents) *n = 0;
2367:   else {
2368:     (*ts->ops->getsolutioncomponents)(ts,n,v);
2369:   }
2370:   return(0);
2371: }

2373: /*@
2374:    TSGetAuxSolution - Returns an auxiliary solution at the present 
2375:    timestep, if available for the time integration method being used.

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

2379:    Parameters :
2380: .  ts - the TS context obtained from TSCreate() (input parameter).
2381: .  v - the vector containing the auxiliary solution 

2383:    Level: intermediate

2385: .seealso: TSGetSolution()

2387: .keywords: TS, timestep, get, solution
2388: @*/
2389: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2390: {

2395:   if (ts->ops->getauxsolution) {
2396:     (*ts->ops->getauxsolution)(ts,v);
2397:   } else {
2398:     VecZeroEntries(*v);
2399:   }
2400:   return(0);
2401: }

2403: /*@
2404:    TSGetTimeError - Returns the estimated error vector, if the chosen
2405:    TSType has an error estimation functionality.

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

2409:    Note: MUST call after TSSetUp()

2411:    Parameters :
2412: .  ts - the TS context obtained from TSCreate() (input parameter).
2413: .  n - current estimate (n=0) or previous one (n=-1)
2414: .  v - the vector containing the error (same size as the solution).

2416:    Level: intermediate

2418: .seealso: TSGetSolution(), TSSetTimeError()

2420: .keywords: TS, timestep, get, error
2421: @*/
2422: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2423: {

2428:   if (ts->ops->gettimeerror) {
2429:     (*ts->ops->gettimeerror)(ts,n,v);
2430:   } else {
2431:     VecZeroEntries(*v);
2432:   }
2433:   return(0);
2434: }

2436: /*@
2437:    TSSetTimeError - Sets the estimated error vector, if the chosen
2438:    TSType has an error estimation functionality. This can be used
2439:    to restart such a time integrator with a given error vector.

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

2443:    Parameters :
2444: .  ts - the TS context obtained from TSCreate() (input parameter).
2445: .  v - the vector containing the error (same size as the solution).

2447:    Level: intermediate

2449: .seealso: TSSetSolution(), TSGetTimeError)

2451: .keywords: TS, timestep, get, error
2452: @*/
2453: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2454: {

2459:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2460:   if (ts->ops->settimeerror) {
2461:     (*ts->ops->settimeerror)(ts,v);
2462:   }
2463:   return(0);
2464: }

2466: /*@
2467:    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()

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

2471:    Input Parameter:
2472: .  ts - the TS context obtained from TSCreate()

2474:    Output Parameter:
2475: +  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2476: -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters

2478:    Level: intermediate

2480: .seealso: TSGetTimeStep()

2482: .keywords: TS, timestep, get, sensitivity
2483: @*/
2484: PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2485: {
2488:   if (numcost) *numcost = ts->numcost;
2489:   if (lambda)  *lambda  = ts->vecs_sensi;
2490:   if (mu)      *mu      = ts->vecs_sensip;
2491:   return(0);
2492: }

2494: /* ----- Routines to initialize and destroy a timestepper ---- */
2495: /*@
2496:   TSSetProblemType - Sets the type of problem to be solved.

2498:   Not collective

2500:   Input Parameters:
2501: + ts   - The TS
2502: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2503: .vb
2504:          U_t - A U = 0      (linear)
2505:          U_t - A(t) U = 0   (linear)
2506:          F(t,U,U_t) = 0     (nonlinear)
2507: .ve

2509:    Level: beginner

2511: .keywords: TS, problem type
2512: .seealso: TSSetUp(), TSProblemType, TS
2513: @*/
2514: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2515: {

2520:   ts->problem_type = type;
2521:   if (type == TS_LINEAR) {
2522:     SNES snes;
2523:     TSGetSNES(ts,&snes);
2524:     SNESSetType(snes,SNESKSPONLY);
2525:   }
2526:   return(0);
2527: }

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

2532:   Not collective

2534:   Input Parameter:
2535: . ts   - The TS

2537:   Output Parameter:
2538: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2539: .vb
2540:          M U_t = A U
2541:          M(t) U_t = A(t) U
2542:          F(t,U,U_t)
2543: .ve

2545:    Level: beginner

2547: .keywords: TS, problem type
2548: .seealso: TSSetUp(), TSProblemType, TS
2549: @*/
2550: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2551: {
2555:   *type = ts->problem_type;
2556:   return(0);
2557: }

2559: /*@
2560:    TSSetUp - Sets up the internal data structures for the later use
2561:    of a timestepper.

2563:    Collective on TS

2565:    Input Parameter:
2566: .  ts - the TS context obtained from TSCreate()

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

2575:    Level: advanced

2577: .keywords: TS, timestep, setup

2579: .seealso: TSCreate(), TSStep(), TSDestroy()
2580: @*/
2581: PetscErrorCode  TSSetUp(TS ts)
2582: {
2584:   DM             dm;
2585:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2586:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2587:   TSIFunction    ifun;
2588:   TSIJacobian    ijac;
2589:   TSI2Jacobian   i2jac;
2590:   TSRHSJacobian  rhsjac;
2591:   PetscBool      isnone;

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

2597:   if (!((PetscObject)ts)->type_name) {
2598:     TSGetIFunction(ts,NULL,&ifun,NULL);
2599:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
2600:   }

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

2604:   if (ts->rhsjacobian.reuse) {
2605:     Mat Amat,Pmat;
2606:     SNES snes;
2607:     TSGetSNES(ts,&snes);
2608:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
2609:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2610:      * have displaced the RHS matrix */
2611:     if (Amat == ts->Arhs) {
2612:       /* we need to copy the values of the matrix because for the constant Jacobian case the user will never set the numerical values in this new location */
2613:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
2614:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
2615:       MatDestroy(&Amat);
2616:     }
2617:     if (Pmat == ts->Brhs) {
2618:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
2619:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
2620:       MatDestroy(&Pmat);
2621:     }
2622:   }

2624:   TSGetAdapt(ts,&ts->adapt);
2625:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

2627:   if (ts->ops->setup) {
2628:     (*ts->ops->setup)(ts);
2629:   }

2631:   /* Attempt to check/preset a default value for the exact final time option */
2632:   PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
2633:   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED)
2634:     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;

2636:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2637:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2638:    */
2639:   TSGetDM(ts,&dm);
2640:   DMSNESGetFunction(dm,&func,NULL);
2641:   if (!func) {
2642:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
2643:   }
2644:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2645:      Otherwise, the SNES will use coloring internally to form the Jacobian.
2646:    */
2647:   DMSNESGetJacobian(dm,&jac,NULL);
2648:   DMTSGetIJacobian(dm,&ijac,NULL);
2649:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
2650:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
2651:   if (!jac && (ijac || i2jac || rhsjac)) {
2652:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
2653:   }

2655:   /* if time integration scheme has a starting method, call it */
2656:   if (ts->ops->startingmethod) {
2657:     (*ts->ops->startingmethod)(ts);
2658:   }

2660:   ts->setupcalled = PETSC_TRUE;
2661:   return(0);
2662: }

2664: /*@
2665:    TSAdjointSetUp - Sets up the internal data structures for the later use
2666:    of an adjoint solver

2668:    Collective on TS

2670:    Input Parameter:
2671: .  ts - the TS context obtained from TSCreate()

2673:    Level: advanced

2675: .keywords: TS, timestep, setup

2677: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2678: @*/
2679: PetscErrorCode  TSAdjointSetUp(TS ts)
2680: {

2685:   if (ts->adjointsetupcalled) return(0);
2686:   if (!ts->vecs_sensi) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");
2687:   if (ts->vecs_sensip && !ts->Jacp) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"Must call TSAdjointSetRHSJacobian() first");

2689:   if (ts->vec_costintegral) { /* if there is integral in the cost function */
2690:     VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);
2691:     if (ts->vecs_sensip){
2692:       VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);
2693:     }
2694:   }

2696:   if (ts->ops->adjointsetup) {
2697:     (*ts->ops->adjointsetup)(ts);
2698:   }
2699:   ts->adjointsetupcalled = PETSC_TRUE;
2700:   return(0);
2701: }

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

2706:    Collective on TS

2708:    Input Parameter:
2709: .  ts - the TS context obtained from TSCreate()

2711:    Level: beginner

2713: .keywords: TS, timestep, reset

2715: .seealso: TSCreate(), TSSetup(), TSDestroy()
2716: @*/
2717: PetscErrorCode  TSReset(TS ts)
2718: {


2724:   if (ts->ops->reset) {
2725:     (*ts->ops->reset)(ts);
2726:   }
2727:   if (ts->snes) {SNESReset(ts->snes);}
2728:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

2730:   MatDestroy(&ts->Arhs);
2731:   MatDestroy(&ts->Brhs);
2732:   VecDestroy(&ts->Frhs);
2733:   VecDestroy(&ts->vec_sol);
2734:   VecDestroy(&ts->vec_dot);
2735:   VecDestroy(&ts->vatol);
2736:   VecDestroy(&ts->vrtol);
2737:   VecDestroyVecs(ts->nwork,&ts->work);

2739:   VecDestroyVecs(ts->numcost,&ts->vecs_drdy);
2740:   VecDestroyVecs(ts->numcost,&ts->vecs_drdp);

2742:   MatDestroy(&ts->Jacp);
2743:   VecDestroy(&ts->vec_costintegral);
2744:   VecDestroy(&ts->vec_costintegrand);

2746:   PetscFree(ts->vecs_fwdsensipacked);

2748:   ts->setupcalled = PETSC_FALSE;
2749:   return(0);
2750: }

2752: /*@
2753:    TSDestroy - Destroys the timestepper context that was created
2754:    with TSCreate().

2756:    Collective on TS

2758:    Input Parameter:
2759: .  ts - the TS context obtained from TSCreate()

2761:    Level: beginner

2763: .keywords: TS, timestepper, destroy

2765: .seealso: TSCreate(), TSSetUp(), TSSolve()
2766: @*/
2767: PetscErrorCode  TSDestroy(TS *ts)
2768: {

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

2776:   TSReset((*ts));

2778:   /* if memory was published with SAWs then destroy it */
2779:   PetscObjectSAWsViewOff((PetscObject)*ts);
2780:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

2782:   TSTrajectoryDestroy(&(*ts)->trajectory);

2784:   TSAdaptDestroy(&(*ts)->adapt);
2785:   TSEventDestroy(&(*ts)->event);

2787:   SNESDestroy(&(*ts)->snes);
2788:   DMDestroy(&(*ts)->dm);
2789:   TSMonitorCancel((*ts));
2790:   TSAdjointMonitorCancel((*ts));

2792:   PetscHeaderDestroy(ts);
2793:   return(0);
2794: }

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

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

2802:    Input Parameter:
2803: .  ts - the TS context obtained from TSCreate()

2805:    Output Parameter:
2806: .  snes - the nonlinear solver context

2808:    Notes:
2809:    The user can then directly manipulate the SNES context to set various
2810:    options, etc.  Likewise, the user can then extract and manipulate the
2811:    KSP, KSP, and PC contexts as well.

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

2816:    Level: beginner

2818: .keywords: timestep, get, SNES
2819: @*/
2820: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2821: {

2827:   if (!ts->snes) {
2828:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2829:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2830:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2831:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2832:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2833:     if (ts->problem_type == TS_LINEAR) {
2834:       SNESSetType(ts->snes,SNESKSPONLY);
2835:     }
2836:   }
2837:   *snes = ts->snes;
2838:   return(0);
2839: }

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

2844:    Collective

2846:    Input Parameter:
2847: +  ts - the TS context obtained from TSCreate()
2848: -  snes - the nonlinear solver context

2850:    Notes:
2851:    Most users should have the TS created by calling TSGetSNES()

2853:    Level: developer

2855: .keywords: timestep, set, SNES
2856: @*/
2857: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2858: {
2860:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2865:   PetscObjectReference((PetscObject)snes);
2866:   SNESDestroy(&ts->snes);

2868:   ts->snes = snes;

2870:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2871:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2872:   if (func == SNESTSFormJacobian) {
2873:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2874:   }
2875:   return(0);
2876: }

2878: /*@
2879:    TSGetKSP - Returns the KSP (linear solver) associated with
2880:    a TS (timestepper) context.

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

2884:    Input Parameter:
2885: .  ts - the TS context obtained from TSCreate()

2887:    Output Parameter:
2888: .  ksp - the nonlinear solver context

2890:    Notes:
2891:    The user can then directly manipulate the KSP context to set various
2892:    options, etc.  Likewise, the user can then extract and manipulate the
2893:    KSP and PC contexts as well.

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

2898:    Level: beginner

2900: .keywords: timestep, get, KSP
2901: @*/
2902: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2903: {
2905:   SNES           snes;

2910:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2911:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2912:   TSGetSNES(ts,&snes);
2913:   SNESGetKSP(snes,ksp);
2914:   return(0);
2915: }

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

2919: /*@
2920:    TSSetMaxSteps - Sets the maximum number of steps to use.

2922:    Logically Collective on TS

2924:    Input Parameters:
2925: +  ts - the TS context obtained from TSCreate()
2926: -  maxsteps - maximum number of steps to use

2928:    Options Database Keys:
2929: .  -ts_max_steps <maxsteps> - Sets maxsteps

2931:    Notes:
2932:    The default maximum number of steps is 5000

2934:    Level: intermediate

2936: .keywords: TS, timestep, set, maximum, steps

2938: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
2939: @*/
2940: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2941: {
2945:   if (maxsteps < 0 ) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2946:   ts->max_steps = maxsteps;
2947:   return(0);
2948: }

2950: /*@
2951:    TSGetMaxSteps - Gets the maximum number of steps to use.

2953:    Not Collective

2955:    Input Parameters:
2956: .  ts - the TS context obtained from TSCreate()

2958:    Output Parameter:
2959: .  maxsteps - maximum number of steps to use

2961:    Level: advanced

2963: .keywords: TS, timestep, get, maximum, steps

2965: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
2966: @*/
2967: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2968: {
2972:   *maxsteps = ts->max_steps;
2973:   return(0);
2974: }

2976: /*@
2977:    TSSetMaxTime - Sets the maximum (or final) time for timestepping.

2979:    Logically Collective on TS

2981:    Input Parameters:
2982: +  ts - the TS context obtained from TSCreate()
2983: -  maxtime - final time to step to

2985:    Options Database Keys:
2986: .  -ts_max_time <maxtime> - Sets maxtime

2988:    Notes:
2989:    The default maximum time is 5.0

2991:    Level: intermediate

2993: .keywords: TS, timestep, set, maximum, time

2995: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
2996: @*/
2997: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
2998: {
3002:   ts->max_time = maxtime;
3003:   return(0);
3004: }

3006: /*@
3007:    TSGetMaxTime - Gets the maximum (or final) time for timestepping.

3009:    Not Collective

3011:    Input Parameters:
3012: .  ts - the TS context obtained from TSCreate()

3014:    Output Parameter:
3015: .  maxtime - final time to step to

3017:    Level: advanced

3019: .keywords: TS, timestep, get, maximum, time

3021: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
3022: @*/
3023: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3024: {
3028:   *maxtime = ts->max_time;
3029:   return(0);
3030: }

3032: /*@
3033:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().
3034: @*/
3035: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3036: {
3040:   TSSetTime(ts,initial_time);
3041:   TSSetTimeStep(ts,time_step);
3042:   return(0);
3043: }

3045: /*@
3046:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().
3047: @*/
3048: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3049: {
3052:   if (maxsteps) {
3054:     *maxsteps = ts->max_steps;
3055:   }
3056:   if (maxtime) {
3058:     *maxtime = ts->max_time;
3059:   }
3060:   return(0);
3061: }

3063: /*@
3064:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().
3065: @*/
3066: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3067: {
3072:   if (maxsteps >= 0) ts->max_steps = maxsteps;
3073:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3074:   return(0);
3075: }

3077: /*@
3078:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().
3079: @*/
3080: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

3082: /*@
3083:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().
3084: @*/
3085: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

3087: /*@
3088:    TSSetSolution - Sets the initial solution vector
3089:    for use by the TS routines.

3091:    Logically Collective on TS and Vec

3093:    Input Parameters:
3094: +  ts - the TS context obtained from TSCreate()
3095: -  u - the solution vector

3097:    Level: beginner

3099: .keywords: TS, timestep, set, solution, initial values
3100: @*/
3101: PetscErrorCode  TSSetSolution(TS ts,Vec u)
3102: {
3104:   DM             dm;

3109:   PetscObjectReference((PetscObject)u);
3110:   VecDestroy(&ts->vec_sol);
3111:   ts->vec_sol = u;

3113:   TSGetDM(ts,&dm);
3114:   DMShellSetGlobalVector(dm,u);
3115:   return(0);
3116: }

3118: /*@
3119:    TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time

3121:    Logically Collective on TS

3123:    Input Parameters:
3124: +  ts - the TS context obtained from TSCreate()
3125: .  steps - number of steps to use

3127:    Level: intermediate

3129:    Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
3130:           so as to integrate back to less than the original timestep

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

3134: .seealso: TSSetExactFinalTime()
3135: @*/
3136: PetscErrorCode  TSAdjointSetSteps(TS ts,PetscInt steps)
3137: {
3141:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
3142:   if (steps > ts->steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
3143:   ts->adjoint_max_steps = steps;
3144:   return(0);
3145: }

3147: /*@
3148:    TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial values and w.r.t. the problem parameters
3149:       for use by the TSAdjoint routines.

3151:    Logically Collective on TS and Vec

3153:    Input Parameters:
3154: +  ts - the TS context obtained from TSCreate()
3155: .  lambda - gradients with respect to the initial condition variables, the dimension and parallel layout of these vectors is the same as the ODE solution vector
3156: -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters

3158:    Level: beginner

3160:    Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime  mu_i = df/dp|finaltime

3162: .keywords: TS, timestep, set, sensitivity, initial values
3163: @*/
3164: PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
3165: {
3169:   ts->vecs_sensi  = lambda;
3170:   ts->vecs_sensip = mu;
3171:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostIntegrand");
3172:   ts->numcost  = numcost;
3173:   return(0);
3174: }

3176: /*@C
3177:   TSAdjointSetRHSJacobian - Sets the function that computes the Jacobian of G w.r.t. the parameters p where y_t = G(y,p,t), as well as the location to store the matrix.

3179:   Logically Collective on TS

3181:   Input Parameters:
3182: + ts   - The TS context obtained from TSCreate()
3183: - func - The function

3185:   Calling sequence of func:
3186: $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
3187: +   t - current timestep
3188: .   y - input vector (current ODE solution)
3189: .   A - output matrix
3190: -   ctx - [optional] user-defined function context

3192:   Level: intermediate

3194:   Notes: Amat has the same number of rows and the same row parallel layout as u, Amat has the same number of columns and parallel layout as p

3196: .keywords: TS, sensitivity
3197: .seealso:
3198: @*/
3199: PetscErrorCode  TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
3200: {


3207:   ts->rhsjacobianp    = func;
3208:   ts->rhsjacobianpctx = ctx;
3209:   if(Amat) {
3210:     PetscObjectReference((PetscObject)Amat);
3211:     MatDestroy(&ts->Jacp);
3212:     ts->Jacp = Amat;
3213:   }
3214:   return(0);
3215: }

3217: /*@C
3218:   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.

3220:   Collective on TS

3222:   Input Parameters:
3223: . ts   - The TS context obtained from TSCreate()

3225:   Level: developer

3227: .keywords: TS, sensitivity
3228: .seealso: TSAdjointSetRHSJacobian()
3229: @*/
3230: PetscErrorCode  TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
3231: {


3239:   PetscStackPush("TS user JacobianP function for sensitivity analysis");
3240:   (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx);
3241:   PetscStackPop;
3242:   return(0);
3243: }

3245: /*@C
3246:     TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions

3248:     Logically Collective on TS

3250:     Input Parameters:
3251: +   ts - the TS context obtained from TSCreate()
3252: .   numcost - number of gradients to be computed, this is the number of cost functions
3253: .   costintegral - vector that stores the integral values
3254: .   rf - routine for evaluating the integrand function
3255: .   drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
3256: .   drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
3257: .   fwd - flag indicating whether to evaluate cost integral in the forward run or the adjoint run
3258: -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)

3260:     Calling sequence of rf:
3261: $   PetscErrorCode rf(TS ts,PetscReal t,Vec y,Vec f,void *ctx);

3263:     Calling sequence of drdyf:
3264: $   PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);

3266:     Calling sequence of drdpf:
3267: $   PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);

3269:     Level: intermediate

3271:     Notes: For optimization there is usually a single cost function (numcost = 1). For sensitivities there may be multiple cost functions

3273: .keywords: TS, sensitivity analysis, timestep, set, quadrature, function

3275: .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
3276: @*/
3277: PetscErrorCode  TSSetCostIntegrand(TS ts,PetscInt numcost,Vec costintegral,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
3278:                                                           PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
3279:                                                           PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
3280:                                                           PetscBool fwd,void *ctx)
3281: {

3287:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostGradients() or TSForwardSetIntegralGradients()");
3288:   if (!ts->numcost) ts->numcost=numcost;

3290:   if (costintegral) {
3291:     PetscObjectReference((PetscObject)costintegral);
3292:     VecDestroy(&ts->vec_costintegral);
3293:     ts->vec_costintegral = costintegral;
3294:   } else {
3295:     if (!ts->vec_costintegral) { /* Create a seq vec if user does not provide one */
3296:       VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);
3297:     } else {
3298:       VecSet(ts->vec_costintegral,0.0);
3299:     }
3300:   }
3301:   if (!ts->vec_costintegrand) {
3302:     VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);
3303:   } else {
3304:     VecSet(ts->vec_costintegrand,0.0);
3305:   }
3306:   ts->costintegralfwd  = fwd; /* Evaluate the cost integral in forward run if fwd is true */
3307:   ts->costintegrand    = rf;
3308:   ts->costintegrandctx = ctx;
3309:   ts->drdyfunction     = drdyf;
3310:   ts->drdpfunction     = drdpf;
3311:   return(0);
3312: }

3314: /*@
3315:    TSGetCostIntegral - Returns the values of the integral term in the cost functions.
3316:    It is valid to call the routine after a backward run.

3318:    Not Collective

3320:    Input Parameter:
3321: .  ts - the TS context obtained from TSCreate()

3323:    Output Parameter:
3324: .  v - the vector containing the integrals for each cost function

3326:    Level: intermediate

3328: .seealso: TSSetCostIntegrand()

3330: .keywords: TS, sensitivity analysis
3331: @*/
3332: PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
3333: {
3337:   *v = ts->vec_costintegral;
3338:   return(0);
3339: }

3341: /*@
3342:    TSComputeCostIntegrand - Evaluates the integral function in the cost functions.

3344:    Input Parameters:
3345: +  ts - the TS context
3346: .  t - current time
3347: -  y - state vector, i.e. current solution

3349:    Output Parameter:
3350: .  q - vector of size numcost to hold the outputs

3352:    Note:
3353:    Most users should not need to explicitly call this routine, as it
3354:    is used internally within the sensitivity analysis context.

3356:    Level: developer

3358: .keywords: TS, compute

3360: .seealso: TSSetCostIntegrand()
3361: @*/
3362: PetscErrorCode TSComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3363: {


3371:   PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);
3372:   if (ts->costintegrand) {
3373:     PetscStackPush("TS user integrand in the cost function");
3374:     (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);
3375:     PetscStackPop;
3376:   } else {
3377:     VecZeroEntries(q);
3378:   }

3380:   PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
3381:   return(0);
3382: }

3384: /*@
3385:   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.

3387:   Collective on TS

3389:   Input Parameters:
3390: . ts   - The TS context obtained from TSCreate()

3392:   Notes:
3393:   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3394:   so most users would not generally call this routine themselves.

3396:   Level: developer

3398: .keywords: TS, sensitivity
3399: .seealso: TSAdjointComputeDRDYFunction()
3400: @*/
3401: PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3402: {


3409:   PetscStackPush("TS user DRDY function for sensitivity analysis");
3410:   (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx);
3411:   PetscStackPop;
3412:   return(0);
3413: }

3415: /*@
3416:   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.

3418:   Collective on TS

3420:   Input Parameters:
3421: . ts   - The TS context obtained from TSCreate()

3423:   Notes:
3424:   TSDRDPFunction() is typically used for sensitivity implementation,
3425:   so most users would not generally call this routine themselves.

3427:   Level: developer

3429: .keywords: TS, sensitivity
3430: .seealso: TSAdjointSetDRDPFunction()
3431: @*/
3432: PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3433: {


3440:   PetscStackPush("TS user DRDP function for sensitivity analysis");
3441:   (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx);
3442:   PetscStackPop;
3443:   return(0);
3444: }

3446: /*@C
3447:   TSSetPreStep - Sets the general-purpose function
3448:   called once at the beginning of each time step.

3450:   Logically Collective on TS

3452:   Input Parameters:
3453: + ts   - The TS context obtained from TSCreate()
3454: - func - The function

3456:   Calling sequence of func:
3457: . func (TS ts);

3459:   Level: intermediate

3461: .keywords: TS, timestep
3462: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3463: @*/
3464: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3465: {
3468:   ts->prestep = func;
3469:   return(0);
3470: }

3472: /*@
3473:   TSPreStep - Runs the user-defined pre-step function.

3475:   Collective on TS

3477:   Input Parameters:
3478: . ts   - The TS context obtained from TSCreate()

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

3484:   Level: developer

3486: .keywords: TS, timestep
3487: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3488: @*/
3489: PetscErrorCode  TSPreStep(TS ts)
3490: {

3495:   if (ts->prestep) {
3496:     Vec              U;
3497:     PetscObjectState sprev,spost;

3499:     TSGetSolution(ts,&U);
3500:     PetscObjectStateGet((PetscObject)U,&sprev);
3501:     PetscStackCallStandard((*ts->prestep),(ts));
3502:     PetscObjectStateGet((PetscObject)U,&spost);
3503:     if (sprev != spost) ts->steprestart = PETSC_TRUE;
3504:   }
3505:   return(0);
3506: }

3508: /*@C
3509:   TSSetPreStage - Sets the general-purpose function
3510:   called once at the beginning of each stage.

3512:   Logically Collective on TS

3514:   Input Parameters:
3515: + ts   - The TS context obtained from TSCreate()
3516: - func - The function

3518:   Calling sequence of func:
3519: . PetscErrorCode func(TS ts, PetscReal stagetime);

3521:   Level: intermediate

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

3528: .keywords: TS, timestep
3529: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3530: @*/
3531: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3532: {
3535:   ts->prestage = func;
3536:   return(0);
3537: }

3539: /*@C
3540:   TSSetPostStage - Sets the general-purpose function
3541:   called once at the end of each stage.

3543:   Logically Collective on TS

3545:   Input Parameters:
3546: + ts   - The TS context obtained from TSCreate()
3547: - func - The function

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

3552:   Level: intermediate

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

3559: .keywords: TS, timestep
3560: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3561: @*/
3562: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3563: {
3566:   ts->poststage = func;
3567:   return(0);
3568: }

3570: /*@C
3571:   TSSetPostEvaluate - Sets the general-purpose function
3572:   called once at the end of each step evaluation.

3574:   Logically Collective on TS

3576:   Input Parameters:
3577: + ts   - The TS context obtained from TSCreate()
3578: - func - The function

3580:   Calling sequence of func:
3581: . PetscErrorCode func(TS ts);

3583:   Level: intermediate

3585:   Note:
3586:   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling 
3587:   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep() 
3588:   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step 
3589:   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step 
3590:   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()

3592: .keywords: TS, timestep
3593: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3594: @*/
3595: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3596: {
3599:   ts->postevaluate = func;
3600:   return(0);
3601: }

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

3606:   Collective on TS

3608:   Input Parameters:
3609: . ts          - The TS context obtained from TSCreate()
3610:   stagetime   - The absolute time of the current stage

3612:   Notes:
3613:   TSPreStage() is typically used within time stepping implementations,
3614:   most users would not generally call this routine themselves.

3616:   Level: developer

3618: .keywords: TS, timestep
3619: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3620: @*/
3621: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3622: {

3627:   if (ts->prestage) {
3628:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3629:   }
3630:   return(0);
3631: }

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

3636:   Collective on TS

3638:   Input Parameters:
3639: . ts          - The TS context obtained from TSCreate()
3640:   stagetime   - The absolute time of the current stage
3641:   stageindex  - Stage number
3642:   Y           - Array of vectors (of size = total number
3643:                 of stages) with the stage solutions

3645:   Notes:
3646:   TSPostStage() is typically used within time stepping implementations,
3647:   most users would not generally call this routine themselves.

3649:   Level: developer

3651: .keywords: TS, timestep
3652: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3653: @*/
3654: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3655: {

3660:   if (ts->poststage) {
3661:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3662:   }
3663:   return(0);
3664: }

3666: /*@
3667:   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()

3669:   Collective on TS

3671:   Input Parameters:
3672: . ts          - The TS context obtained from TSCreate()

3674:   Notes:
3675:   TSPostEvaluate() is typically used within time stepping implementations,
3676:   most users would not generally call this routine themselves.

3678:   Level: developer

3680: .keywords: TS, timestep
3681: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3682: @*/
3683: PetscErrorCode  TSPostEvaluate(TS ts)
3684: {

3689:   if (ts->postevaluate) {
3690:     PetscStackCallStandard((*ts->postevaluate),(ts));
3691:   }
3692:   return(0);
3693: }

3695: /*@C
3696:   TSSetPostStep - Sets the general-purpose function
3697:   called once at the end of each time step.

3699:   Logically Collective on TS

3701:   Input Parameters:
3702: + ts   - The TS context obtained from TSCreate()
3703: - func - The function

3705:   Calling sequence of func:
3706: $ func (TS ts);

3708:   Notes:
3709:   The function set by TSSetPostStep() is called after each successful step. The solution vector X
3710:   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
3711:   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.

3713:   Level: intermediate

3715: .keywords: TS, timestep
3716: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime()
3717: @*/
3718: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3719: {
3722:   ts->poststep = func;
3723:   return(0);
3724: }

3726: /*@
3727:   TSPostStep - Runs the user-defined post-step function.

3729:   Collective on TS

3731:   Input Parameters:
3732: . ts   - The TS context obtained from TSCreate()

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

3738:   Level: developer

3740: .keywords: TS, timestep
3741: @*/
3742: PetscErrorCode  TSPostStep(TS ts)
3743: {

3748:   if (ts->poststep) {
3749:     Vec              U;
3750:     PetscObjectState sprev,spost;

3752:     TSGetSolution(ts,&U);
3753:     PetscObjectStateGet((PetscObject)U,&sprev);
3754:     PetscStackCallStandard((*ts->poststep),(ts));
3755:     PetscObjectStateGet((PetscObject)U,&spost);
3756:     if (sprev != spost) ts->steprestart = PETSC_TRUE;
3757:   }
3758:   return(0);
3759: }

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

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

3767:    Logically Collective on TS

3769:    Input Parameters:
3770: +  ts - the TS context obtained from TSCreate()
3771: .  monitor - monitoring routine
3772: .  mctx - [optional] user-defined context for private data for the
3773:              monitor routine (use NULL if no context is desired)
3774: -  monitordestroy - [optional] routine that frees monitor context
3775:           (may be NULL)

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

3780: +    ts - the TS context
3781: .    steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
3782: .    time - current time
3783: .    u - current iterate
3784: -    mctx - [optional] monitoring context

3786:    Notes:
3787:    This routine adds an additional monitor to the list of monitors that
3788:    already has been loaded.

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

3792:    Level: intermediate

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

3796: .seealso: TSMonitorDefault(), TSMonitorCancel()
3797: @*/
3798: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3799: {
3801:   PetscInt       i;
3802:   PetscBool      identical;
3803: 
3806:   for (i=0; i<ts->numbermonitors;i++) {
3807:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
3808:     if (identical) return(0);
3809:   }
3810:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3811:   ts->monitor[ts->numbermonitors]          = monitor;
3812:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3813:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3814:   return(0);
3815: }

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

3820:    Logically Collective on TS

3822:    Input Parameters:
3823: .  ts - the TS context obtained from TSCreate()

3825:    Notes:
3826:    There is no way to remove a single, specific monitor.

3828:    Level: intermediate

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

3832: .seealso: TSMonitorDefault(), TSMonitorSet()
3833: @*/
3834: PetscErrorCode  TSMonitorCancel(TS ts)
3835: {
3837:   PetscInt       i;

3841:   for (i=0; i<ts->numbermonitors; i++) {
3842:     if (ts->monitordestroy[i]) {
3843:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
3844:     }
3845:   }
3846:   ts->numbermonitors = 0;
3847:   return(0);
3848: }

3850: /*@C
3851:    TSMonitorDefault - The Default monitor, prints the timestep and time for each step

3853:    Level: intermediate

3855: .keywords: TS, set, monitor

3857: .seealso:  TSMonitorSet()
3858: @*/
3859: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3860: {
3862:   PetscViewer    viewer =  vf->viewer;
3863:   PetscBool      iascii,ibinary;

3867:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
3868:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
3869:   PetscViewerPushFormat(viewer,vf->format);
3870:   if (iascii) {
3871:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
3872:     if (step == -1){ /* this indicates it is an interpolated solution */
3873:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
3874:     } else {
3875:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
3876:     }
3877:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
3878:   } else if (ibinary) {
3879:     PetscMPIInt rank;
3880:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
3881:     if (!rank) {
3882:       PetscBool skipHeader;
3883:       PetscInt  classid = REAL_FILE_CLASSID;

3885:       PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
3886:       if (!skipHeader) {
3887:          PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
3888:        }
3889:       PetscRealView(1,&ptime,viewer);
3890:     } else {
3891:       PetscRealView(0,&ptime,viewer);
3892:     }
3893:   }
3894:   PetscViewerPopFormat(viewer);
3895:   return(0);
3896: }

3898: /*@C
3899:    TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3900:    timestep to display the iteration's  progress.

3902:    Logically Collective on TS

3904:    Input Parameters:
3905: +  ts - the TS context obtained from TSCreate()
3906: .  adjointmonitor - monitoring routine
3907: .  adjointmctx - [optional] user-defined context for private data for the
3908:              monitor routine (use NULL if no context is desired)
3909: -  adjointmonitordestroy - [optional] routine that frees monitor context
3910:           (may be NULL)

3912:    Calling sequence of monitor:
3913: $    int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)

3915: +    ts - the TS context
3916: .    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
3917:                                been interpolated to)
3918: .    time - current time
3919: .    u - current iterate
3920: .    numcost - number of cost functionos
3921: .    lambda - sensitivities to initial conditions
3922: .    mu - sensitivities to parameters
3923: -    adjointmctx - [optional] adjoint monitoring context

3925:    Notes:
3926:    This routine adds an additional monitor to the list of monitors that
3927:    already has been loaded.

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

3931:    Level: intermediate

3933: .keywords: TS, timestep, set, adjoint, monitor

3935: .seealso: TSAdjointMonitorCancel()
3936: @*/
3937: PetscErrorCode  TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3938: {
3940:   PetscInt       i;
3941:   PetscBool      identical;

3945:   for (i=0; i<ts->numbermonitors;i++) {
3946:     PetscMonitorCompare((PetscErrorCode (*)(void))adjointmonitor,adjointmctx,adjointmdestroy,(PetscErrorCode (*)(void))ts->adjointmonitor[i],ts->adjointmonitorcontext[i],ts->adjointmonitordestroy[i],&identical);
3947:     if (identical) return(0);
3948:   }
3949:   if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3950:   ts->adjointmonitor[ts->numberadjointmonitors]          = adjointmonitor;
3951:   ts->adjointmonitordestroy[ts->numberadjointmonitors]   = adjointmdestroy;
3952:   ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3953:   return(0);
3954: }

3956: /*@C
3957:    TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.

3959:    Logically Collective on TS

3961:    Input Parameters:
3962: .  ts - the TS context obtained from TSCreate()

3964:    Notes:
3965:    There is no way to remove a single, specific monitor.

3967:    Level: intermediate

3969: .keywords: TS, timestep, set, adjoint, monitor

3971: .seealso: TSAdjointMonitorSet()
3972: @*/
3973: PetscErrorCode  TSAdjointMonitorCancel(TS ts)
3974: {
3976:   PetscInt       i;

3980:   for (i=0; i<ts->numberadjointmonitors; i++) {
3981:     if (ts->adjointmonitordestroy[i]) {
3982:       (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);
3983:     }
3984:   }
3985:   ts->numberadjointmonitors = 0;
3986:   return(0);
3987: }

3989: /*@C
3990:    TSAdjointMonitorDefault - the default monitor of adjoint computations

3992:    Level: intermediate

3994: .keywords: TS, set, monitor

3996: .seealso: TSAdjointMonitorSet()
3997: @*/
3998: PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3999: {
4001:   PetscViewer    viewer = vf->viewer;

4005:   PetscViewerPushFormat(viewer,vf->format);
4006:   PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
4007:   PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
4008:   PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
4009:   PetscViewerPopFormat(viewer);
4010:   return(0);
4011: }

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

4016:    Collective on TS

4018:    Input Argument:
4019: +  ts - time stepping context
4020: -  t - time to interpolate to

4022:    Output Argument:
4023: .  U - state at given time

4025:    Level: intermediate

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

4030: .keywords: TS, set

4032: .seealso: TSSetExactFinalTime(), TSSolve()
4033: @*/
4034: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
4035: {

4041:   if (t < ts->ptime_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_prev,(double)ts->ptime);
4042:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
4043:   (*ts->ops->interpolate)(ts,t,U);
4044:   return(0);
4045: }

4047: /*@
4048:    TSStep - Steps one time step

4050:    Collective on TS

4052:    Input Parameter:
4053: .  ts - the TS context obtained from TSCreate()

4055:    Level: developer

4057:    Notes:
4058:    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.

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

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

4066: .keywords: TS, timestep, solve

4068: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
4069: @*/
4070: PetscErrorCode  TSStep(TS ts)
4071: {
4072:   PetscErrorCode   ierr;
4073:   static PetscBool cite = PETSC_FALSE;
4074:   PetscReal        ptime;

4078:   PetscCitationsRegister("@techreport{tspaper,\n"
4079:                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
4080:                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
4081:                                 "  type        = {Preprint},\n"
4082:                                 "  number      = {ANL/MCS-P5061-0114},\n"
4083:                                 "  institution = {Argonne National Laboratory},\n"
4084:                                 "  year        = {2014}\n}\n",&cite);

4086:   TSSetUp(ts);
4087:   TSTrajectorySetUp(ts->trajectory,ts);

4089:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
4090:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
4091:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

4093:   if (!ts->steps) ts->ptime_prev = ts->ptime;
4094:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
4095:   ts->reason = TS_CONVERGED_ITERATING;
4096:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
4097:   PetscLogEventBegin(TS_Step,ts,0,0,0);
4098:   (*ts->ops->step)(ts);
4099:   PetscLogEventEnd(TS_Step,ts,0,0,0);
4100:   ts->ptime_prev = ptime;
4101:   ts->steps++;
4102:   ts->steprollback = PETSC_FALSE;
4103:   ts->steprestart  = PETSC_FALSE;

4105:   if (ts->reason < 0) {
4106:     if (ts->errorifstepfailed) {
4107:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) 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]);
4108:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
4109:     }
4110:   } else if (!ts->reason) {
4111:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4112:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4113:   }
4114:   return(0);
4115: }

4117: /*@
4118:    TSAdjointStep - Steps one time step backward in the adjoint run

4120:    Collective on TS

4122:    Input Parameter:
4123: .  ts - the TS context obtained from TSCreate()

4125:    Level: intermediate

4127: .keywords: TS, adjoint, step

4129: .seealso: TSAdjointSetUp(), TSAdjointSolve()
4130: @*/
4131: PetscErrorCode  TSAdjointStep(TS ts)
4132: {
4133:   DM               dm;
4134:   PetscErrorCode   ierr;

4138:   TSGetDM(ts,&dm);
4139:   TSAdjointSetUp(ts);

4141:   VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");

4143:   ts->reason = TS_CONVERGED_ITERATING;
4144:   ts->ptime_prev = ts->ptime;
4145:   if (!ts->ops->adjointstep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed because the adjoint of  %s has not been implemented, try other time stepping methods for adjoint sensitivity analysis",((PetscObject)ts)->type_name);
4146:   PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);
4147:   (*ts->ops->adjointstep)(ts);
4148:   PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);
4149:   ts->adjoint_steps++; ts->steps--;

4151:   if (ts->reason < 0) {
4152:     if (ts->errorifstepfailed) {
4153:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) 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]);
4154:       else if (ts->reason == TS_DIVERGED_STEP_REJECTED) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_reject or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
4155:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
4156:     }
4157:   } else if (!ts->reason) {
4158:     if (ts->adjoint_steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
4159:   }
4160:   return(0);
4161: }

4163: /*@
4164:    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
4165:    at the end of a time step with a given order of accuracy.

4167:    Collective on TS

4169:    Input Arguments:
4170: +  ts - time stepping context
4171: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
4172: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

4174:    Output Arguments:
4175: +  order - optional, the actual order of the error evaluation
4176: -  wlte - the weighted local truncation error norm

4178:    Level: advanced

4180:    Notes:
4181:    If the timestepper cannot evaluate the error in a particular step
4182:    (eg. in the first step or restart steps after event handling),
4183:    this routine returns wlte=-1.0 .

4185: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
4186: @*/
4187: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
4188: {

4198:   if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
4199:   if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
4200:   (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
4201:   return(0);
4202: }

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

4207:    Collective on TS

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

4214:    Output Arguments:
4215: .  U - state at the end of the current step

4217:    Level: advanced

4219:    Notes:
4220:    This function cannot be called until all stages have been evaluated.
4221:    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.

4223: .seealso: TSStep(), TSAdapt
4224: @*/
4225: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
4226: {

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

4238: /*@
4239:    TSForwardCostIntegral - Evaluate the cost integral in the forward run.

4241:    Collective on TS

4243:    Input Arguments:
4244: .  ts - time stepping context

4246:    Level: advanced

4248:    Notes:
4249:    This function cannot be called until TSStep() has been completed.

4251: .seealso: TSSolve(), TSAdjointCostIntegral()
4252: @*/
4253: PetscErrorCode TSForwardCostIntegral(TS ts)
4254: {
4257:   if (!ts->ops->forwardintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the forward run",((PetscObject)ts)->type_name);
4258:   (*ts->ops->forwardintegral)(ts);
4259:   return(0);
4260: }

4262: /*@
4263:    TSSolve - Steps the requested number of timesteps.

4265:    Collective on TS

4267:    Input Parameter:
4268: +  ts - the TS context obtained from TSCreate()
4269: -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
4270:                              otherwise must contain the initial conditions and will contain the solution at the final requested time

4272:    Level: beginner

4274:    Notes:
4275:    The final time returned by this function may be different from the time of the internally
4276:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
4277:    stepped over the final time.

4279: .keywords: TS, timestep, solve

4281: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
4282: @*/
4283: PetscErrorCode TSSolve(TS ts,Vec u)
4284: {
4285:   Vec               solution;
4286:   PetscErrorCode    ierr;


4292:   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 */
4294:     if (!ts->vec_sol || u == ts->vec_sol) {
4295:       VecDuplicate(u,&solution);
4296:       TSSetSolution(ts,solution);
4297:       VecDestroy(&solution); /* grant ownership */
4298:     }
4299:     VecCopy(u,ts->vec_sol);
4300:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
4301:   } else if (u) {
4302:     TSSetSolution(ts,u);
4303:   }
4304:   TSSetUp(ts);
4305:   TSTrajectorySetUp(ts->trajectory,ts);

4307:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
4308:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
4309:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

4311:   if (ts->forward_solve) {
4312:     TSForwardSetUp(ts);
4313:   }

4315:   /* reset number of steps only when the step is not restarted. ARKIMEX
4316:      restarts the step after an event. Resetting these counters in such case causes
4317:      TSTrajectory to incorrectly save the output files
4318:   */
4319:   /* reset time step and iteration counters */

4321:   if (!ts->steps) {
4322:     ts->ksp_its           = 0;
4323:     ts->snes_its          = 0;
4324:     ts->num_snes_failures = 0;
4325:     ts->reject            = 0;
4326:     ts->steprestart       = PETSC_TRUE;
4327:     ts->steprollback      = PETSC_FALSE;
4328:   }
4329:   ts->reason = TS_CONVERGED_ITERATING;

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

4333:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4334:     (*ts->ops->solve)(ts);
4335:     if (u) {VecCopy(ts->vec_sol,u);}
4336:     ts->solvetime = ts->ptime;
4337:     solution = ts->vec_sol;
4338:   } else { /* Step the requested number of timesteps. */
4339:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4340:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

4342:     if (!ts->steps) {
4343:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4344:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
4345:     }

4347:     while (!ts->reason) {
4348:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
4349:       if (!ts->steprollback) {
4350:         TSPreStep(ts);
4351:       }
4352:       TSStep(ts);
4353:       if (ts->vec_costintegral && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4354:         TSForwardCostIntegral(ts);
4355:       }
4356:       if (!ts->steprollback && ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
4357:         TSForwardStep(ts);
4358:       }
4359:       TSPostEvaluate(ts);
4360:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4361:       if (!ts->steprollback) {
4362:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
4363:         TSPostStep(ts);
4364:       }
4365:     }
4366:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

4368:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4369:       TSInterpolate(ts,ts->max_time,u);
4370:       ts->solvetime = ts->max_time;
4371:       solution = u;
4372:       TSMonitor(ts,-1,ts->solvetime,solution);
4373:     } else {
4374:       if (u) {VecCopy(ts->vec_sol,u);}
4375:       ts->solvetime = ts->ptime;
4376:       solution = ts->vec_sol;
4377:     }
4378:   }

4380:   TSViewFromOptions(ts,NULL,"-ts_view");
4381:   VecViewFromOptions(solution,NULL,"-ts_view_solution");
4382:   PetscObjectSAWsBlock((PetscObject)ts);
4383:   if (ts->adjoint_solve) {
4384:     TSAdjointSolve(ts);
4385:   }
4386:   return(0);
4387: }

4389: /*@
4390:  TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4391:  
4392:  Collective on TS
4393:  
4394:  Input Arguments:
4395:  .  ts - time stepping context
4396:  
4397:  Level: advanced
4398:  
4399:  Notes:
4400:  This function cannot be called until TSAdjointStep() has been completed.
4401:  
4402:  .seealso: TSAdjointSolve(), TSAdjointStep
4403:  @*/
4404: PetscErrorCode TSAdjointCostIntegral(TS ts)
4405: {
4408:     if (!ts->ops->adjointintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the adjoint run",((PetscObject)ts)->type_name);
4409:     (*ts->ops->adjointintegral)(ts);
4410:     return(0);
4411: }

4413: /*@
4414:    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE

4416:    Collective on TS

4418:    Input Parameter:
4419: .  ts - the TS context obtained from TSCreate()

4421:    Options Database:
4422: . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial values

4424:    Level: intermediate

4426:    Notes:
4427:    This must be called after a call to TSSolve() that solves the forward problem

4429:    By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time

4431: .keywords: TS, timestep, solve

4433: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4434: @*/
4435: PetscErrorCode TSAdjointSolve(TS ts)
4436: {
4437:   PetscErrorCode    ierr;

4441:   TSAdjointSetUp(ts);

4443:   /* reset time step and iteration counters */
4444:   ts->adjoint_steps     = 0;
4445:   ts->ksp_its           = 0;
4446:   ts->snes_its          = 0;
4447:   ts->num_snes_failures = 0;
4448:   ts->reject            = 0;
4449:   ts->reason            = TS_CONVERGED_ITERATING;

4451:   if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->steps;
4452:   if (ts->adjoint_steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;

4454:   while (!ts->reason) {
4455:     TSTrajectoryGet(ts->trajectory,ts,ts->steps,&ts->ptime);
4456:     TSAdjointMonitor(ts,ts->steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4457:     TSAdjointEventHandler(ts);
4458:     TSAdjointStep(ts);
4459:     if (ts->vec_costintegral && !ts->costintegralfwd) {
4460:       TSAdjointCostIntegral(ts);
4461:     }
4462:   }
4463:   TSTrajectoryGet(ts->trajectory,ts,ts->steps,&ts->ptime);
4464:   TSAdjointMonitor(ts,ts->steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);
4465:   ts->solvetime = ts->ptime;
4466:   TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");
4467:   VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");
4468:   return(0);
4469: }

4471: /*@C
4472:    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()

4474:    Collective on TS

4476:    Input Parameters:
4477: +  ts - time stepping context obtained from TSCreate()
4478: .  step - step number that has just completed
4479: .  ptime - model time of the state
4480: -  u - state at the current model time

4482:    Notes:
4483:    TSMonitor() is typically used automatically within the time stepping implementations.
4484:    Users would almost never call this routine directly.

4486:    A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions

4488:    Level: developer

4490: .keywords: TS, timestep
4491: @*/
4492: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4493: {
4494:   DM             dm;
4495:   PetscInt       i,n = ts->numbermonitors;


4502:   TSGetDM(ts,&dm);
4503:   DMSetOutputSequenceNumber(dm,step,ptime);

4505:   VecLockPush(u);
4506:   for (i=0; i<n; i++) {
4507:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
4508:   }
4509:   VecLockPop(u);
4510:   return(0);
4511: }

4513: /*@C
4514:    TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()

4516:    Collective on TS

4518:    Input Parameters:
4519: +  ts - time stepping context obtained from TSCreate()
4520: .  step - step number that has just completed
4521: .  ptime - model time of the state
4522: .  u - state at the current model time
4523: .  numcost - number of cost functions (dimension of lambda  or mu)
4524: .  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4525: -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters

4527:    Notes:
4528:    TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4529:    Users would almost never call this routine directly.

4531:    Level: developer

4533: .keywords: TS, timestep
4534: @*/
4535: PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4536: {
4538:   PetscInt       i,n = ts->numberadjointmonitors;

4543:   VecLockPush(u);
4544:   for (i=0; i<n; i++) {
4545:     (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);
4546:   }
4547:   VecLockPop(u);
4548:   return(0);
4549: }

4551: /* ------------------------------------------------------------------------*/
4552: /*@C
4553:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4554:    TS to monitor the solution process graphically in various ways

4556:    Collective on TS

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

4565:    Output Parameter:
4566: .  ctx - the context

4568:    Options Database Key:
4569: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4570: +  -ts_monitor_lg_timestep_log - automatically sets line graph monitor
4571: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4572: .  -ts_monitor_lg_error -  monitor the error
4573: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4574: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4575: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

4577:    Notes:
4578:    Use TSMonitorLGCtxDestroy() to destroy.

4580:    One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()

4582:    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4583:    first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
4584:    as the first argument.

4586:    One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()

4588:    Level: intermediate

4590: .keywords: TS, monitor, line graph, residual

4592: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4593:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4594:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4595:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4596:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

4598: @*/
4599: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4600: {
4601:   PetscDraw      draw;

4605:   PetscNew(ctx);
4606:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
4607:   PetscDrawSetFromOptions(draw);
4608:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
4609:   PetscDrawLGSetFromOptions((*ctx)->lg);
4610:   PetscDrawDestroy(&draw);
4611:   (*ctx)->howoften = howoften;
4612:   return(0);
4613: }

4615: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4616: {
4617:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4618:   PetscReal      x   = ptime,y;

4622:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
4623:   if (!step) {
4624:     PetscDrawAxis axis;
4625:     const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
4626:     PetscDrawLGGetAxis(ctx->lg,&axis);
4627:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
4628:     PetscDrawLGReset(ctx->lg);
4629:   }
4630:   TSGetTimeStep(ts,&y);
4631:   if (ctx->semilogy) y = PetscLog10Real(y);
4632:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
4633:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4634:     PetscDrawLGDraw(ctx->lg);
4635:     PetscDrawLGSave(ctx->lg);
4636:   }
4637:   return(0);
4638: }

4640: /*@C
4641:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4642:    with TSMonitorLGCtxCreate().

4644:    Collective on TSMonitorLGCtx

4646:    Input Parameter:
4647: .  ctx - the monitor context

4649:    Level: intermediate

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

4653: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4654: @*/
4655: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4656: {

4660:   if ((*ctx)->transformdestroy) {
4661:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
4662:   }
4663:   PetscDrawLGDestroy(&(*ctx)->lg);
4664:   PetscStrArrayDestroy(&(*ctx)->names);
4665:   PetscStrArrayDestroy(&(*ctx)->displaynames);
4666:   PetscFree((*ctx)->displayvariables);
4667:   PetscFree((*ctx)->displayvalues);
4668:   PetscFree(*ctx);
4669:   return(0);
4670: }

4672: /*@
4673:    TSGetTime - Gets the time of the most recently completed step.

4675:    Not Collective

4677:    Input Parameter:
4678: .  ts - the TS context obtained from TSCreate()

4680:    Output Parameter:
4681: .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().

4683:    Level: beginner

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

4689: .seealso:  TSGetSolveTime(), TSSetTime(), TSGetTimeStep()

4691: .keywords: TS, get, time
4692: @*/
4693: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4694: {
4698:   *t = ts->ptime;
4699:   return(0);
4700: }

4702: /*@
4703:    TSGetPrevTime - Gets the starting time of the previously completed step.

4705:    Not Collective

4707:    Input Parameter:
4708: .  ts - the TS context obtained from TSCreate()

4710:    Output Parameter:
4711: .  t  - the previous time

4713:    Level: beginner

4715: .seealso: TSGetTime(), TSGetSolveTime(), TSGetTimeStep()

4717: .keywords: TS, get, time
4718: @*/
4719: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4720: {
4724:   *t = ts->ptime_prev;
4725:   return(0);
4726: }

4728: /*@
4729:    TSSetTime - Allows one to reset the time.

4731:    Logically Collective on TS

4733:    Input Parameters:
4734: +  ts - the TS context obtained from TSCreate()
4735: -  time - the time

4737:    Level: intermediate

4739: .seealso: TSGetTime(), TSSetMaxSteps()

4741: .keywords: TS, set, time
4742: @*/
4743: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4744: {
4748:   ts->ptime = t;
4749:   return(0);
4750: }

4752: /*@C
4753:    TSSetOptionsPrefix - Sets the prefix used for searching for all
4754:    TS options in the database.

4756:    Logically Collective on TS

4758:    Input Parameter:
4759: +  ts     - The TS context
4760: -  prefix - The prefix to prepend to all option names

4762:    Notes:
4763:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4764:    The first character of all runtime options is AUTOMATICALLY the
4765:    hyphen.

4767:    Level: advanced

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

4771: .seealso: TSSetFromOptions()

4773: @*/
4774: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4775: {
4777:   SNES           snes;

4781:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
4782:   TSGetSNES(ts,&snes);
4783:   SNESSetOptionsPrefix(snes,prefix);
4784:   return(0);
4785: }

4787: /*@C
4788:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4789:    TS options in the database.

4791:    Logically Collective on TS

4793:    Input Parameter:
4794: +  ts     - The TS context
4795: -  prefix - The prefix to prepend to all option names

4797:    Notes:
4798:    A hyphen (-) must NOT be given at the beginning of the prefix name.
4799:    The first character of all runtime options is AUTOMATICALLY the
4800:    hyphen.

4802:    Level: advanced

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

4806: .seealso: TSGetOptionsPrefix()

4808: @*/
4809: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4810: {
4812:   SNES           snes;

4816:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
4817:   TSGetSNES(ts,&snes);
4818:   SNESAppendOptionsPrefix(snes,prefix);
4819:   return(0);
4820: }

4822: /*@C
4823:    TSGetOptionsPrefix - Sets the prefix used for searching for all
4824:    TS options in the database.

4826:    Not Collective

4828:    Input Parameter:
4829: .  ts - The TS context

4831:    Output Parameter:
4832: .  prefix - A pointer to the prefix string used

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

4837:    Level: intermediate

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

4841: .seealso: TSAppendOptionsPrefix()
4842: @*/
4843: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4844: {

4850:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
4851:   return(0);
4852: }

4854: /*@C
4855:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

4859:    Input Parameter:
4860: .  ts  - The TS context obtained from TSCreate()

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

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

4870:    Level: intermediate

4872: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

4874: .keywords: TS, timestep, get, matrix, Jacobian
4875: @*/
4876: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4877: {
4879:   DM             dm;

4882:   if (Amat || Pmat) {
4883:     SNES snes;
4884:     TSGetSNES(ts,&snes);
4885:     SNESSetUpMatrices(snes);
4886:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4887:   }
4888:   TSGetDM(ts,&dm);
4889:   DMTSGetRHSJacobian(dm,func,ctx);
4890:   return(0);
4891: }

4893: /*@C
4894:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

4898:    Input Parameter:
4899: .  ts  - The TS context obtained from TSCreate()

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

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

4909:    Level: advanced

4911: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

4913: .keywords: TS, timestep, get, matrix, Jacobian
4914: @*/
4915: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4916: {
4918:   DM             dm;

4921:   if (Amat || Pmat) {
4922:     SNES snes;
4923:     TSGetSNES(ts,&snes);
4924:     SNESSetUpMatrices(snes);
4925:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
4926:   }
4927:   TSGetDM(ts,&dm);
4928:   DMTSGetIJacobian(dm,f,ctx);
4929:   return(0);
4930: }

4932: /*@C
4933:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4934:    VecView() for the solution at each timestep

4936:    Collective on TS

4938:    Input Parameters:
4939: +  ts - the TS context
4940: .  step - current time-step
4941: .  ptime - current time
4942: -  dummy - either a viewer or NULL

4944:    Options Database:
4945: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

4947:    Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4948:        will look bad

4950:    Level: intermediate

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

4954: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4955: @*/
4956: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4957: {
4958:   PetscErrorCode   ierr;
4959:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4960:   PetscDraw        draw;

4963:   if (!step && ictx->showinitial) {
4964:     if (!ictx->initialsolution) {
4965:       VecDuplicate(u,&ictx->initialsolution);
4966:     }
4967:     VecCopy(u,ictx->initialsolution);
4968:   }
4969:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

4971:   if (ictx->showinitial) {
4972:     PetscReal pause;
4973:     PetscViewerDrawGetPause(ictx->viewer,&pause);
4974:     PetscViewerDrawSetPause(ictx->viewer,0.0);
4975:     VecView(ictx->initialsolution,ictx->viewer);
4976:     PetscViewerDrawSetPause(ictx->viewer,pause);
4977:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
4978:   }
4979:   VecView(u,ictx->viewer);
4980:   if (ictx->showtimestepandtime) {
4981:     PetscReal xl,yl,xr,yr,h;
4982:     char      time[32];

4984:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
4985:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
4986:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
4987:     h    = yl + .95*(yr - yl);
4988:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
4989:     PetscDrawFlush(draw);
4990:   }

4992:   if (ictx->showinitial) {
4993:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
4994:   }
4995:   return(0);
4996: }

4998: /*@C
4999:    TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
5000:    VecView() for the sensitivities to initial states at each timestep

5002:    Collective on TS

5004:    Input Parameters:
5005: +  ts - the TS context
5006: .  step - current time-step
5007: .  ptime - current time
5008: .  u - current state
5009: .  numcost - number of cost functions
5010: .  lambda - sensitivities to initial conditions
5011: .  mu - sensitivities to parameters
5012: -  dummy - either a viewer or NULL

5014:    Level: intermediate

5016: .keywords: TS,  vector, adjoint, monitor, view

5018: .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
5019: @*/
5020: PetscErrorCode  TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
5021: {
5022:   PetscErrorCode   ierr;
5023:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
5024:   PetscDraw        draw;
5025:   PetscReal        xl,yl,xr,yr,h;
5026:   char             time[32];

5029:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

5031:   VecView(lambda[0],ictx->viewer);
5032:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
5033:   PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
5034:   PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
5035:   h    = yl + .95*(yr - yl);
5036:   PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
5037:   PetscDrawFlush(draw);
5038:   return(0);
5039: }

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

5044:    Collective on TS

5046:    Input Parameters:
5047: +  ts - the TS context
5048: .  step - current time-step
5049: .  ptime - current time
5050: -  dummy - either a viewer or NULL

5052:    Level: intermediate

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

5056: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5057: @*/
5058: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5059: {
5060:   PetscErrorCode    ierr;
5061:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
5062:   PetscDraw         draw;
5063:   PetscDrawAxis     axis;
5064:   PetscInt          n;
5065:   PetscMPIInt       size;
5066:   PetscReal         U0,U1,xl,yl,xr,yr,h;
5067:   char              time[32];
5068:   const PetscScalar *U;

5071:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
5072:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
5073:   VecGetSize(u,&n);
5074:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

5076:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
5077:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
5078:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
5079:   if (!step) {
5080:     PetscDrawClear(draw);
5081:     PetscDrawAxisDraw(axis);
5082:   }

5084:   VecGetArrayRead(u,&U);
5085:   U0 = PetscRealPart(U[0]);
5086:   U1 = PetscRealPart(U[1]);
5087:   VecRestoreArrayRead(u,&U);
5088:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

5090:   PetscDrawCollectiveBegin(draw);
5091:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
5092:   if (ictx->showtimestepandtime) {
5093:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
5094:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
5095:     h    = yl + .95*(yr - yl);
5096:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
5097:   }
5098:   PetscDrawCollectiveEnd(draw);
5099:   PetscDrawFlush(draw);
5100:   PetscDrawPause(draw);
5101:   PetscDrawSave(draw);
5102:   return(0);
5103: }

5105: /*@C
5106:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

5108:    Collective on TS

5110:    Input Parameters:
5111: .    ctx - the monitor context

5113:    Level: intermediate

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

5117: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
5118: @*/
5119: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
5120: {

5124:   PetscViewerDestroy(&(*ictx)->viewer);
5125:   VecDestroy(&(*ictx)->initialsolution);
5126:   PetscFree(*ictx);
5127:   return(0);
5128: }

5130: /*@C
5131:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

5133:    Collective on TS

5135:    Input Parameter:
5136: .    ts - time-step context

5138:    Output Patameter:
5139: .    ctx - the monitor context

5141:    Options Database:
5142: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

5144:    Level: intermediate

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

5148: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
5149: @*/
5150: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
5151: {
5152:   PetscErrorCode   ierr;

5155:   PetscNew(ctx);
5156:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
5157:   PetscViewerSetFromOptions((*ctx)->viewer);

5159:   (*ctx)->howoften    = howoften;
5160:   (*ctx)->showinitial = PETSC_FALSE;
5161:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

5163:   (*ctx)->showtimestepandtime = PETSC_FALSE;
5164:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
5165:   return(0);
5166: }

5168: /*@C
5169:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
5170:    VecView() for the error at each timestep

5172:    Collective on TS

5174:    Input Parameters:
5175: +  ts - the TS context
5176: .  step - current time-step
5177: .  ptime - current time
5178: -  dummy - either a viewer or NULL

5180:    Level: intermediate

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

5184: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5185: @*/
5186: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5187: {
5188:   PetscErrorCode   ierr;
5189:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
5190:   PetscViewer      viewer = ctx->viewer;
5191:   Vec              work;

5194:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
5195:   VecDuplicate(u,&work);
5196:   TSComputeSolutionFunction(ts,ptime,work);
5197:   VecAXPY(work,-1.0,u);
5198:   VecView(work,viewer);
5199:   VecDestroy(&work);
5200:   return(0);
5201: }

5203:  #include <petsc/private/dmimpl.h>
5204: /*@
5205:    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS

5207:    Logically Collective on TS and DM

5209:    Input Parameters:
5210: +  ts - the ODE integrator object
5211: -  dm - the dm, cannot be NULL

5213:    Level: intermediate

5215: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
5216: @*/
5217: PetscErrorCode  TSSetDM(TS ts,DM dm)
5218: {
5220:   SNES           snes;
5221:   DMTS           tsdm;

5226:   PetscObjectReference((PetscObject)dm);
5227:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
5228:     if (ts->dm->dmts && !dm->dmts) {
5229:       DMCopyDMTS(ts->dm,dm);
5230:       DMGetDMTS(ts->dm,&tsdm);
5231:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
5232:         tsdm->originaldm = dm;
5233:       }
5234:     }
5235:     DMDestroy(&ts->dm);
5236:   }
5237:   ts->dm = dm;

5239:   TSGetSNES(ts,&snes);
5240:   SNESSetDM(snes,dm);
5241:   return(0);
5242: }

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

5247:    Not Collective

5249:    Input Parameter:
5250: . ts - the preconditioner context

5252:    Output Parameter:
5253: .  dm - the dm

5255:    Level: intermediate

5257: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
5258: @*/
5259: PetscErrorCode  TSGetDM(TS ts,DM *dm)
5260: {

5265:   if (!ts->dm) {
5266:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
5267:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
5268:   }
5269:   *dm = ts->dm;
5270:   return(0);
5271: }

5273: /*@
5274:    SNESTSFormFunction - Function to evaluate nonlinear residual

5276:    Logically Collective on SNES

5278:    Input Parameter:
5279: + snes - nonlinear solver
5280: . U - the current state at which to evaluate the residual
5281: - ctx - user context, must be a TS

5283:    Output Parameter:
5284: . F - the nonlinear residual

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

5290:    Level: advanced

5292: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
5293: @*/
5294: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
5295: {
5296:   TS             ts = (TS)ctx;

5304:   (ts->ops->snesfunction)(snes,U,F,ts);
5305:   return(0);
5306: }

5308: /*@
5309:    SNESTSFormJacobian - Function to evaluate the Jacobian

5311:    Collective on SNES

5313:    Input Parameter:
5314: + snes - nonlinear solver
5315: . U - the current state at which to evaluate the residual
5316: - ctx - user context, must be a TS

5318:    Output Parameter:
5319: + A - the Jacobian
5320: . B - the preconditioning matrix (may be the same as A)
5321: - flag - indicates any structure change in the matrix

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

5326:    Level: developer

5328: .seealso: SNESSetJacobian()
5329: @*/
5330: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5331: {
5332:   TS             ts = (TS)ctx;

5343:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
5344:   return(0);
5345: }

5347: /*@C
5348:    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only

5350:    Collective on TS

5352:    Input Arguments:
5353: +  ts - time stepping context
5354: .  t - time at which to evaluate
5355: .  U - state at which to evaluate
5356: -  ctx - context

5358:    Output Arguments:
5359: .  F - right hand side

5361:    Level: intermediate

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

5367: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5368: @*/
5369: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5370: {
5372:   Mat            Arhs,Brhs;

5375:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
5376:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
5377:   MatMult(Arhs,U,F);
5378:   return(0);
5379: }

5381: /*@C
5382:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

5384:    Collective on TS

5386:    Input Arguments:
5387: +  ts - time stepping context
5388: .  t - time at which to evaluate
5389: .  U - state at which to evaluate
5390: -  ctx - context

5392:    Output Arguments:
5393: +  A - pointer to operator
5394: .  B - pointer to preconditioning matrix
5395: -  flg - matrix structure flag

5397:    Level: intermediate

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

5402: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5403: @*/
5404: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5405: {
5407:   return(0);
5408: }

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

5413:    Collective on TS

5415:    Input Arguments:
5416: +  ts - time stepping context
5417: .  t - time at which to evaluate
5418: .  U - state at which to evaluate
5419: .  Udot - time derivative of state vector
5420: -  ctx - context

5422:    Output Arguments:
5423: .  F - left hand side

5425:    Level: intermediate

5427:    Notes:
5428:    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
5429:    user is required to write their own TSComputeIFunction.
5430:    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5431:    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().

5433:    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U

5435: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5436: @*/
5437: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5438: {
5440:   Mat            A,B;

5443:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
5444:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
5445:   MatMult(A,Udot,F);
5446:   return(0);
5447: }

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

5452:    Collective on TS

5454:    Input Arguments:
5455: +  ts - time stepping context
5456: .  t - time at which to evaluate
5457: .  U - state at which to evaluate
5458: .  Udot - time derivative of state vector
5459: .  shift - shift to apply
5460: -  ctx - context

5462:    Output Arguments:
5463: +  A - pointer to operator
5464: .  B - pointer to preconditioning matrix
5465: -  flg - matrix structure flag

5467:    Level: advanced

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

5472:    It is only appropriate for problems of the form

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

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

5480: $    shift*M + J

5482:   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
5483:   a copy of M or reassemble it when requested.

5485: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5486: @*/
5487: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5488: {

5492:   MatScale(A, shift / ts->ijacobian.shift);
5493:   ts->ijacobian.shift = shift;
5494:   return(0);
5495: }

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

5500:    Not Collective

5502:    Input Parameter:
5503: .  ts - the TS context

5505:    Output Parameter:
5506: .  equation_type - see TSEquationType

5508:    Level: beginner

5510: .keywords: TS, equation type

5512: .seealso: TSSetEquationType(), TSEquationType
5513: @*/
5514: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5515: {
5519:   *equation_type = ts->equation_type;
5520:   return(0);
5521: }

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

5526:    Not Collective

5528:    Input Parameter:
5529: +  ts - the TS context
5530: -  equation_type - see TSEquationType

5532:    Level: advanced

5534: .keywords: TS, equation type

5536: .seealso: TSGetEquationType(), TSEquationType
5537: @*/
5538: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5539: {
5542:   ts->equation_type = equation_type;
5543:   return(0);
5544: }

5546: /*@
5547:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

5549:    Not Collective

5551:    Input Parameter:
5552: .  ts - the TS context

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

5558:    Level: beginner

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

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

5565: .seealso: TSSetConvergenceTest(), TSConvergedReason
5566: @*/
5567: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5568: {
5572:   *reason = ts->reason;
5573:   return(0);
5574: }

5576: /*@
5577:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

5579:    Not Collective

5581:    Input Parameter:
5582: +  ts - the TS context
5583: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5584:             manual pages for the individual convergence tests for complete lists

5586:    Level: advanced

5588:    Notes:
5589:    Can only be called during TSSolve() is active.

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

5593: .seealso: TSConvergedReason
5594: @*/
5595: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5596: {
5599:   ts->reason = reason;
5600:   return(0);
5601: }

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

5606:    Not Collective

5608:    Input Parameter:
5609: .  ts - the TS context

5611:    Output Parameter:
5612: .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()

5614:    Level: beginner

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

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

5621: .seealso: TSSetConvergenceTest(), TSConvergedReason
5622: @*/
5623: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5624: {
5628:   *ftime = ts->solvetime;
5629:   return(0);
5630: }

5632: /*@
5633:    TSGetSNESIterations - Gets the total number of nonlinear iterations
5634:    used by the time integrator.

5636:    Not Collective

5638:    Input Parameter:
5639: .  ts - TS context

5641:    Output Parameter:
5642: .  nits - number of nonlinear iterations

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

5647:    Level: intermediate

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

5651: .seealso:  TSGetKSPIterations()
5652: @*/
5653: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5654: {
5658:   *nits = ts->snes_its;
5659:   return(0);
5660: }

5662: /*@
5663:    TSGetKSPIterations - Gets the total number of linear iterations
5664:    used by the time integrator.

5666:    Not Collective

5668:    Input Parameter:
5669: .  ts - TS context

5671:    Output Parameter:
5672: .  lits - number of linear iterations

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

5677:    Level: intermediate

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

5681: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5682: @*/
5683: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5684: {
5688:   *lits = ts->ksp_its;
5689:   return(0);
5690: }

5692: /*@
5693:    TSGetStepRejections - Gets the total number of rejected steps.

5695:    Not Collective

5697:    Input Parameter:
5698: .  ts - TS context

5700:    Output Parameter:
5701: .  rejects - number of steps rejected

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

5706:    Level: intermediate

5708: .keywords: TS, get, number

5710: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5711: @*/
5712: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5713: {
5717:   *rejects = ts->reject;
5718:   return(0);
5719: }

5721: /*@
5722:    TSGetSNESFailures - Gets the total number of failed SNES solves

5724:    Not Collective

5726:    Input Parameter:
5727: .  ts - TS context

5729:    Output Parameter:
5730: .  fails - number of failed nonlinear solves

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

5735:    Level: intermediate

5737: .keywords: TS, get, number

5739: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5740: @*/
5741: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5742: {
5746:   *fails = ts->num_snes_failures;
5747:   return(0);
5748: }

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

5753:    Not Collective

5755:    Input Parameter:
5756: +  ts - TS context
5757: -  rejects - maximum number of rejected steps, pass -1 for unlimited

5759:    Notes:
5760:    The counter is reset to zero for each step

5762:    Options Database Key:
5763:  .  -ts_max_reject - Maximum number of step rejections before a step fails

5765:    Level: intermediate

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

5769: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5770: @*/
5771: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5772: {
5775:   ts->max_reject = rejects;
5776:   return(0);
5777: }

5779: /*@
5780:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

5782:    Not Collective

5784:    Input Parameter:
5785: +  ts - TS context
5786: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

5791:    Options Database Key:
5792:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

5794:    Level: intermediate

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

5798: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5799: @*/
5800: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5801: {
5804:   ts->max_snes_failures = fails;
5805:   return(0);
5806: }

5808: /*@
5809:    TSSetErrorIfStepFails - Error if no step succeeds

5811:    Not Collective

5813:    Input Parameter:
5814: +  ts - TS context
5815: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

5817:    Options Database Key:
5818:  .  -ts_error_if_step_fails - Error if no step succeeds

5820:    Level: intermediate

5822: .keywords: TS, set, error

5824: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5825: @*/
5826: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5827: {
5830:   ts->errorifstepfailed = err;
5831:   return(0);
5832: }

5834: /*@C
5835:    TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object

5837:    Collective on TS

5839:    Input Parameters:
5840: +  ts - the TS context
5841: .  step - current time-step
5842: .  ptime - current time
5843: .  u - current state
5844: -  vf - viewer and its format

5846:    Level: intermediate

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

5850: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5851: @*/
5852: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5853: {

5857:   PetscViewerPushFormat(vf->viewer,vf->format);
5858:   VecView(u,vf->viewer);
5859:   PetscViewerPopFormat(vf->viewer);
5860:   return(0);
5861: }

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

5866:    Collective on TS

5868:    Input Parameters:
5869: +  ts - the TS context
5870: .  step - current time-step
5871: .  ptime - current time
5872: .  u - current state
5873: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

5875:    Level: intermediate

5877:    Notes:
5878:    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.
5879:    These are named according to the file name template.

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

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

5885: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5886: @*/
5887: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5888: {
5890:   char           filename[PETSC_MAX_PATH_LEN];
5891:   PetscViewer    viewer;

5894:   if (step < 0) return(0); /* -1 indicates interpolated solution */
5895:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
5896:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
5897:   VecView(u,viewer);
5898:   PetscViewerDestroy(&viewer);
5899:   return(0);
5900: }

5902: /*@C
5903:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

5905:    Collective on TS

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

5910:    Level: intermediate

5912:    Note:
5913:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

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

5917: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5918: @*/
5919: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5920: {

5924:   PetscFree(*(char**)filenametemplate);
5925:   return(0);
5926: }

5928: /*@
5929:    TSGetAdapt - Get the adaptive controller context for the current method

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

5933:    Input Arguments:
5934: .  ts - time stepping context

5936:    Output Arguments:
5937: .  adapt - adaptive controller

5939:    Level: intermediate

5941: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5942: @*/
5943: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5944: {

5950:   if (!ts->adapt) {
5951:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
5952:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
5953:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
5954:   }
5955:   *adapt = ts->adapt;
5956:   return(0);
5957: }

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

5962:    Logically Collective

5964:    Input Arguments:
5965: +  ts - time integration context
5966: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5967: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5968: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5969: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

5971:    Options Database keys:
5972: +  -ts_rtol <rtol> - relative tolerance for local truncation error
5973: -  -ts_atol <atol> Absolute tolerance for local truncation error

5975:    Notes:
5976:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5977:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5978:    computed only for the differential or the algebraic part then this can be done using the vector of
5979:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5980:    differential part and infinity for the algebraic part, the LTE calculation will include only the
5981:    differential variables.

5983:    Level: beginner

5985: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5986: @*/
5987: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5988: {

5992:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5993:   if (vatol) {
5994:     PetscObjectReference((PetscObject)vatol);
5995:     VecDestroy(&ts->vatol);
5996:     ts->vatol = vatol;
5997:   }
5998:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5999:   if (vrtol) {
6000:     PetscObjectReference((PetscObject)vrtol);
6001:     VecDestroy(&ts->vrtol);
6002:     ts->vrtol = vrtol;
6003:   }
6004:   return(0);
6005: }

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

6010:    Logically Collective

6012:    Input Arguments:
6013: .  ts - time integration context

6015:    Output Arguments:
6016: +  atol - scalar absolute tolerances, NULL to ignore
6017: .  vatol - vector of absolute tolerances, NULL to ignore
6018: .  rtol - scalar relative tolerances, NULL to ignore
6019: -  vrtol - vector of relative tolerances, NULL to ignore

6021:    Level: beginner

6023: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
6024: @*/
6025: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
6026: {
6028:   if (atol)  *atol  = ts->atol;
6029:   if (vatol) *vatol = ts->vatol;
6030:   if (rtol)  *rtol  = ts->rtol;
6031:   if (vrtol) *vrtol = ts->vrtol;
6032:   return(0);
6033: }

6035: /*@
6036:    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors

6038:    Collective on TS

6040:    Input Arguments:
6041: +  ts - time stepping context
6042: .  U - state vector, usually ts->vec_sol
6043: -  Y - state vector to be compared to U

6045:    Output Arguments:
6046: .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6047: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6048: .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6050:    Level: developer

6052: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
6053: @*/
6054: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6055: {
6056:   PetscErrorCode    ierr;
6057:   PetscInt          i,n,N,rstart;
6058:   PetscInt          n_loc,na_loc,nr_loc;
6059:   PetscReal         n_glb,na_glb,nr_glb;
6060:   const PetscScalar *u,*y;
6061:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
6062:   PetscReal         tol,tola,tolr;
6063:   PetscReal         err_loc[6],err_glb[6];

6075:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

6077:   VecGetSize(U,&N);
6078:   VecGetLocalSize(U,&n);
6079:   VecGetOwnershipRange(U,&rstart,NULL);
6080:   VecGetArrayRead(U,&u);
6081:   VecGetArrayRead(Y,&y);
6082:   sum  = 0.; n_loc  = 0;
6083:   suma = 0.; na_loc = 0;
6084:   sumr = 0.; nr_loc = 0;
6085:   if (ts->vatol && ts->vrtol) {
6086:     const PetscScalar *atol,*rtol;
6087:     VecGetArrayRead(ts->vatol,&atol);
6088:     VecGetArrayRead(ts->vrtol,&rtol);
6089:     for (i=0; i<n; i++) {
6090:       diff = PetscAbsScalar(y[i] - u[i]);
6091:       tola = PetscRealPart(atol[i]);
6092:       if(tola>0.){
6093:         suma  += PetscSqr(diff/tola);
6094:         na_loc++;
6095:       }
6096:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6097:       if(tolr>0.){
6098:         sumr  += PetscSqr(diff/tolr);
6099:         nr_loc++;
6100:       }
6101:       tol=tola+tolr;
6102:       if(tol>0.){
6103:         sum  += PetscSqr(diff/tol);
6104:         n_loc++;
6105:       }
6106:     }
6107:     VecRestoreArrayRead(ts->vatol,&atol);
6108:     VecRestoreArrayRead(ts->vrtol,&rtol);
6109:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6110:     const PetscScalar *atol;
6111:     VecGetArrayRead(ts->vatol,&atol);
6112:     for (i=0; i<n; i++) {
6113:       diff = PetscAbsScalar(y[i] - u[i]);
6114:       tola = PetscRealPart(atol[i]);
6115:       if(tola>0.){
6116:         suma  += PetscSqr(diff/tola);
6117:         na_loc++;
6118:       }
6119:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6120:       if(tolr>0.){
6121:         sumr  += PetscSqr(diff/tolr);
6122:         nr_loc++;
6123:       }
6124:       tol=tola+tolr;
6125:       if(tol>0.){
6126:         sum  += PetscSqr(diff/tol);
6127:         n_loc++;
6128:       }
6129:     }
6130:     VecRestoreArrayRead(ts->vatol,&atol);
6131:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6132:     const PetscScalar *rtol;
6133:     VecGetArrayRead(ts->vrtol,&rtol);
6134:     for (i=0; i<n; i++) {
6135:       diff = PetscAbsScalar(y[i] - u[i]);
6136:       tola = ts->atol;
6137:       if(tola>0.){
6138:         suma  += PetscSqr(diff/tola);
6139:         na_loc++;
6140:       }
6141:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6142:       if(tolr>0.){
6143:         sumr  += PetscSqr(diff/tolr);
6144:         nr_loc++;
6145:       }
6146:       tol=tola+tolr;
6147:       if(tol>0.){
6148:         sum  += PetscSqr(diff/tol);
6149:         n_loc++;
6150:       }
6151:     }
6152:     VecRestoreArrayRead(ts->vrtol,&rtol);
6153:   } else {                      /* scalar atol, scalar rtol */
6154:     for (i=0; i<n; i++) {
6155:       diff = PetscAbsScalar(y[i] - u[i]);
6156:      tola = ts->atol;
6157:       if(tola>0.){
6158:         suma  += PetscSqr(diff/tola);
6159:         na_loc++;
6160:       }
6161:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6162:       if(tolr>0.){
6163:         sumr  += PetscSqr(diff/tolr);
6164:         nr_loc++;
6165:       }
6166:       tol=tola+tolr;
6167:       if(tol>0.){
6168:         sum  += PetscSqr(diff/tol);
6169:         n_loc++;
6170:       }
6171:     }
6172:   }
6173:   VecRestoreArrayRead(U,&u);
6174:   VecRestoreArrayRead(Y,&y);

6176:   err_loc[0] = sum;
6177:   err_loc[1] = suma;
6178:   err_loc[2] = sumr;
6179:   err_loc[3] = (PetscReal)n_loc;
6180:   err_loc[4] = (PetscReal)na_loc;
6181:   err_loc[5] = (PetscReal)nr_loc;

6183:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

6185:   gsum   = err_glb[0];
6186:   gsuma  = err_glb[1];
6187:   gsumr  = err_glb[2];
6188:   n_glb  = err_glb[3];
6189:   na_glb = err_glb[4];
6190:   nr_glb = err_glb[5];

6192:   *norm  = 0.;
6193:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6194:   *norma = 0.;
6195:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6196:   *normr = 0.;
6197:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6199:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6200:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6201:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6202:   return(0);
6203: }

6205: /*@
6206:    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors

6208:    Collective on TS

6210:    Input Arguments:
6211: +  ts - time stepping context
6212: .  U - state vector, usually ts->vec_sol
6213: -  Y - state vector to be compared to U

6215:    Output Arguments:
6216: .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6217: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6218: .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6220:    Level: developer

6222: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
6223: @*/
6224: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6225: {
6226:   PetscErrorCode    ierr;
6227:   PetscInt          i,n,N,rstart;
6228:   const PetscScalar *u,*y;
6229:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
6230:   PetscReal         tol,tola,tolr,diff;
6231:   PetscReal         err_loc[3],err_glb[3];
6232: 
6243:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

6245:   VecGetSize(U,&N);
6246:   VecGetLocalSize(U,&n);
6247:   VecGetOwnershipRange(U,&rstart,NULL);
6248:   VecGetArrayRead(U,&u);
6249:   VecGetArrayRead(Y,&y);

6251:   max=0.;
6252:   maxa=0.;
6253:   maxr=0.;

6255:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6256:     const PetscScalar *atol,*rtol;
6257:     VecGetArrayRead(ts->vatol,&atol);
6258:     VecGetArrayRead(ts->vrtol,&rtol);

6260:     for (i=0; i<n; i++) {
6261:       diff = PetscAbsScalar(y[i] - u[i]);
6262:       tola = PetscRealPart(atol[i]);
6263:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6264:       tol  = tola+tolr;
6265:       if(tola>0.){
6266:         maxa = PetscMax(maxa,diff / tola);
6267:       }
6268:       if(tolr>0.){
6269:         maxr = PetscMax(maxr,diff / tolr);
6270:       }
6271:       if(tol>0.){
6272:         max = PetscMax(max,diff / tol);
6273:       }
6274:     }
6275:     VecRestoreArrayRead(ts->vatol,&atol);
6276:     VecRestoreArrayRead(ts->vrtol,&rtol);
6277:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6278:     const PetscScalar *atol;
6279:     VecGetArrayRead(ts->vatol,&atol);
6280:     for (i=0; i<n; i++) {
6281:       diff = PetscAbsScalar(y[i] - u[i]);
6282:       tola = PetscRealPart(atol[i]);
6283:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6284:       tol  = tola+tolr;
6285:       if(tola>0.){
6286:         maxa = PetscMax(maxa,diff / tola);
6287:       }
6288:       if(tolr>0.){
6289:         maxr = PetscMax(maxr,diff / tolr);
6290:       }
6291:       if(tol>0.){
6292:         max = PetscMax(max,diff / tol);
6293:       }
6294:     }
6295:     VecRestoreArrayRead(ts->vatol,&atol);
6296:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6297:     const PetscScalar *rtol;
6298:     VecGetArrayRead(ts->vrtol,&rtol);

6300:     for (i=0; i<n; i++) {
6301:       diff = PetscAbsScalar(y[i] - u[i]);
6302:       tola = ts->atol;
6303:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6304:       tol  = tola+tolr;
6305:       if(tola>0.){
6306:         maxa = PetscMax(maxa,diff / tola);
6307:       }
6308:       if(tolr>0.){
6309:         maxr = PetscMax(maxr,diff / tolr);
6310:       }
6311:       if(tol>0.){
6312:         max = PetscMax(max,diff / tol);
6313:       }
6314:     }
6315:     VecRestoreArrayRead(ts->vrtol,&rtol);
6316:   } else {                      /* scalar atol, scalar rtol */

6318:     for (i=0; i<n; i++) {
6319:       diff = PetscAbsScalar(y[i] - u[i]);
6320:       tola = ts->atol;
6321:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6322:       tol  = tola+tolr;
6323:       if(tola>0.){
6324:         maxa = PetscMax(maxa,diff / tola);
6325:       }
6326:       if(tolr>0.){
6327:         maxr = PetscMax(maxr,diff / tolr);
6328:       }
6329:       if(tol>0.){
6330:         max = PetscMax(max,diff / tol);
6331:       }
6332:     }
6333:   }
6334:   VecRestoreArrayRead(U,&u);
6335:   VecRestoreArrayRead(Y,&y);
6336:   err_loc[0] = max;
6337:   err_loc[1] = maxa;
6338:   err_loc[2] = maxr;
6339:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6340:   gmax   = err_glb[0];
6341:   gmaxa  = err_glb[1];
6342:   gmaxr  = err_glb[2];

6344:   *norm = gmax;
6345:   *norma = gmaxa;
6346:   *normr = gmaxr;
6347:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6348:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6349:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6350:   return(0);
6351: }

6353: /*@
6354:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances

6356:    Collective on TS

6358:    Input Arguments:
6359: +  ts - time stepping context
6360: .  U - state vector, usually ts->vec_sol
6361: .  Y - state vector to be compared to U
6362: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6364:    Output Arguments:
6365: .  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6366: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6367: .  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6369:    Options Database Keys:
6370: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6372:    Level: developer

6374: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
6375: @*/
6376: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6377: {

6381:   if (wnormtype == NORM_2) {
6382:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
6383:   } else if(wnormtype == NORM_INFINITY) {
6384:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
6385:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6386:   return(0);
6387: }


6390: /*@
6391:    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances

6393:    Collective on TS

6395:    Input Arguments:
6396: +  ts - time stepping context
6397: .  E - error vector
6398: .  U - state vector, usually ts->vec_sol
6399: -  Y - state vector, previous time step

6401:    Output Arguments:
6402: .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6403: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6404: .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6406:    Level: developer

6408: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
6409: @*/
6410: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6411: {
6412:   PetscErrorCode    ierr;
6413:   PetscInt          i,n,N,rstart;
6414:   PetscInt          n_loc,na_loc,nr_loc;
6415:   PetscReal         n_glb,na_glb,nr_glb;
6416:   const PetscScalar *e,*u,*y;
6417:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
6418:   PetscReal         tol,tola,tolr;
6419:   PetscReal         err_loc[6],err_glb[6];


6435:   VecGetSize(E,&N);
6436:   VecGetLocalSize(E,&n);
6437:   VecGetOwnershipRange(E,&rstart,NULL);
6438:   VecGetArrayRead(E,&e);
6439:   VecGetArrayRead(U,&u);
6440:   VecGetArrayRead(Y,&y);
6441:   sum  = 0.; n_loc  = 0;
6442:   suma = 0.; na_loc = 0;
6443:   sumr = 0.; nr_loc = 0;
6444:   if (ts->vatol && ts->vrtol) {
6445:     const PetscScalar *atol,*rtol;
6446:     VecGetArrayRead(ts->vatol,&atol);
6447:     VecGetArrayRead(ts->vrtol,&rtol);
6448:     for (i=0; i<n; i++) {
6449:       err = PetscAbsScalar(e[i]);
6450:       tola = PetscRealPart(atol[i]);
6451:       if(tola>0.){
6452:         suma  += PetscSqr(err/tola);
6453:         na_loc++;
6454:       }
6455:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6456:       if(tolr>0.){
6457:         sumr  += PetscSqr(err/tolr);
6458:         nr_loc++;
6459:       }
6460:       tol=tola+tolr;
6461:       if(tol>0.){
6462:         sum  += PetscSqr(err/tol);
6463:         n_loc++;
6464:       }
6465:     }
6466:     VecRestoreArrayRead(ts->vatol,&atol);
6467:     VecRestoreArrayRead(ts->vrtol,&rtol);
6468:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6469:     const PetscScalar *atol;
6470:     VecGetArrayRead(ts->vatol,&atol);
6471:     for (i=0; i<n; i++) {
6472:       err = PetscAbsScalar(e[i]);
6473:       tola = PetscRealPart(atol[i]);
6474:       if(tola>0.){
6475:         suma  += PetscSqr(err/tola);
6476:         na_loc++;
6477:       }
6478:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6479:       if(tolr>0.){
6480:         sumr  += PetscSqr(err/tolr);
6481:         nr_loc++;
6482:       }
6483:       tol=tola+tolr;
6484:       if(tol>0.){
6485:         sum  += PetscSqr(err/tol);
6486:         n_loc++;
6487:       }
6488:     }
6489:     VecRestoreArrayRead(ts->vatol,&atol);
6490:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6491:     const PetscScalar *rtol;
6492:     VecGetArrayRead(ts->vrtol,&rtol);
6493:     for (i=0; i<n; i++) {
6494:       err = PetscAbsScalar(e[i]);
6495:       tola = ts->atol;
6496:       if(tola>0.){
6497:         suma  += PetscSqr(err/tola);
6498:         na_loc++;
6499:       }
6500:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6501:       if(tolr>0.){
6502:         sumr  += PetscSqr(err/tolr);
6503:         nr_loc++;
6504:       }
6505:       tol=tola+tolr;
6506:       if(tol>0.){
6507:         sum  += PetscSqr(err/tol);
6508:         n_loc++;
6509:       }
6510:     }
6511:     VecRestoreArrayRead(ts->vrtol,&rtol);
6512:   } else {                      /* scalar atol, scalar rtol */
6513:     for (i=0; i<n; i++) {
6514:       err = PetscAbsScalar(e[i]);
6515:      tola = ts->atol;
6516:       if(tola>0.){
6517:         suma  += PetscSqr(err/tola);
6518:         na_loc++;
6519:       }
6520:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6521:       if(tolr>0.){
6522:         sumr  += PetscSqr(err/tolr);
6523:         nr_loc++;
6524:       }
6525:       tol=tola+tolr;
6526:       if(tol>0.){
6527:         sum  += PetscSqr(err/tol);
6528:         n_loc++;
6529:       }
6530:     }
6531:   }
6532:   VecRestoreArrayRead(E,&e);
6533:   VecRestoreArrayRead(U,&u);
6534:   VecRestoreArrayRead(Y,&y);

6536:   err_loc[0] = sum;
6537:   err_loc[1] = suma;
6538:   err_loc[2] = sumr;
6539:   err_loc[3] = (PetscReal)n_loc;
6540:   err_loc[4] = (PetscReal)na_loc;
6541:   err_loc[5] = (PetscReal)nr_loc;

6543:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

6545:   gsum   = err_glb[0];
6546:   gsuma  = err_glb[1];
6547:   gsumr  = err_glb[2];
6548:   n_glb  = err_glb[3];
6549:   na_glb = err_glb[4];
6550:   nr_glb = err_glb[5];

6552:   *norm  = 0.;
6553:   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6554:   *norma = 0.;
6555:   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6556:   *normr = 0.;
6557:   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

6559:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6560:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6561:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6562:   return(0);
6563: }

6565: /*@
6566:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6567:    Collective on TS

6569:    Input Arguments:
6570: +  ts - time stepping context
6571: .  E - error vector
6572: .  U - state vector, usually ts->vec_sol
6573: -  Y - state vector, previous time step

6575:    Output Arguments:
6576: .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6577: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6578: .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

6580:    Level: developer

6582: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6583: @*/
6584: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6585: {
6586:   PetscErrorCode    ierr;
6587:   PetscInt          i,n,N,rstart;
6588:   const PetscScalar *e,*u,*y;
6589:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6590:   PetscReal         tol,tola,tolr;
6591:   PetscReal         err_loc[3],err_glb[3];


6607:   VecGetSize(E,&N);
6608:   VecGetLocalSize(E,&n);
6609:   VecGetOwnershipRange(E,&rstart,NULL);
6610:   VecGetArrayRead(E,&e);
6611:   VecGetArrayRead(U,&u);
6612:   VecGetArrayRead(Y,&y);

6614:   max=0.;
6615:   maxa=0.;
6616:   maxr=0.;

6618:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6619:     const PetscScalar *atol,*rtol;
6620:     VecGetArrayRead(ts->vatol,&atol);
6621:     VecGetArrayRead(ts->vrtol,&rtol);

6623:     for (i=0; i<n; i++) {
6624:       err = PetscAbsScalar(e[i]);
6625:       tola = PetscRealPart(atol[i]);
6626:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6627:       tol  = tola+tolr;
6628:       if(tola>0.){
6629:         maxa = PetscMax(maxa,err / tola);
6630:       }
6631:       if(tolr>0.){
6632:         maxr = PetscMax(maxr,err / tolr);
6633:       }
6634:       if(tol>0.){
6635:         max = PetscMax(max,err / tol);
6636:       }
6637:     }
6638:     VecRestoreArrayRead(ts->vatol,&atol);
6639:     VecRestoreArrayRead(ts->vrtol,&rtol);
6640:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6641:     const PetscScalar *atol;
6642:     VecGetArrayRead(ts->vatol,&atol);
6643:     for (i=0; i<n; i++) {
6644:       err = PetscAbsScalar(e[i]);
6645:       tola = PetscRealPart(atol[i]);
6646:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6647:       tol  = tola+tolr;
6648:       if(tola>0.){
6649:         maxa = PetscMax(maxa,err / tola);
6650:       }
6651:       if(tolr>0.){
6652:         maxr = PetscMax(maxr,err / tolr);
6653:       }
6654:       if(tol>0.){
6655:         max = PetscMax(max,err / tol);
6656:       }
6657:     }
6658:     VecRestoreArrayRead(ts->vatol,&atol);
6659:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6660:     const PetscScalar *rtol;
6661:     VecGetArrayRead(ts->vrtol,&rtol);

6663:     for (i=0; i<n; i++) {
6664:       err = PetscAbsScalar(e[i]);
6665:       tola = ts->atol;
6666:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6667:       tol  = tola+tolr;
6668:       if(tola>0.){
6669:         maxa = PetscMax(maxa,err / tola);
6670:       }
6671:       if(tolr>0.){
6672:         maxr = PetscMax(maxr,err / tolr);
6673:       }
6674:       if(tol>0.){
6675:         max = PetscMax(max,err / tol);
6676:       }
6677:     }
6678:     VecRestoreArrayRead(ts->vrtol,&rtol);
6679:   } else {                      /* scalar atol, scalar rtol */

6681:     for (i=0; i<n; i++) {
6682:       err = PetscAbsScalar(e[i]);
6683:       tola = ts->atol;
6684:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6685:       tol  = tola+tolr;
6686:       if(tola>0.){
6687:         maxa = PetscMax(maxa,err / tola);
6688:       }
6689:       if(tolr>0.){
6690:         maxr = PetscMax(maxr,err / tolr);
6691:       }
6692:       if(tol>0.){
6693:         max = PetscMax(max,err / tol);
6694:       }
6695:     }
6696:   }
6697:   VecRestoreArrayRead(E,&e);
6698:   VecRestoreArrayRead(U,&u);
6699:   VecRestoreArrayRead(Y,&y);
6700:   err_loc[0] = max;
6701:   err_loc[1] = maxa;
6702:   err_loc[2] = maxr;
6703:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
6704:   gmax   = err_glb[0];
6705:   gmaxa  = err_glb[1];
6706:   gmaxr  = err_glb[2];

6708:   *norm = gmax;
6709:   *norma = gmaxa;
6710:   *normr = gmaxr;
6711:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6712:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6713:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6714:   return(0);
6715: }

6717: /*@
6718:    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances

6720:    Collective on TS

6722:    Input Arguments:
6723: +  ts - time stepping context
6724: .  E - error vector
6725: .  U - state vector, usually ts->vec_sol
6726: .  Y - state vector, previous time step
6727: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

6729:    Output Arguments:
6730: .  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6731: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6732: .  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

6734:    Options Database Keys:
6735: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

6737:    Level: developer

6739: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6740: @*/
6741: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6742: {

6746:   if (wnormtype == NORM_2) {
6747:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
6748:   } else if(wnormtype == NORM_INFINITY) {
6749:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
6750:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6751:   return(0);
6752: }


6755: /*@
6756:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

6758:    Logically Collective on TS

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

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

6767:    Level: intermediate

6769: .seealso: TSGetCFLTime(), TSADAPTCFL
6770: @*/
6771: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6772: {
6775:   ts->cfltime_local = cfltime;
6776:   ts->cfltime       = -1.;
6777:   return(0);
6778: }

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

6783:    Collective on TS

6785:    Input Arguments:
6786: .  ts - time stepping context

6788:    Output Arguments:
6789: .  cfltime - maximum stable time step for forward Euler

6791:    Level: advanced

6793: .seealso: TSSetCFLTimeLocal()
6794: @*/
6795: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6796: {

6800:   if (ts->cfltime < 0) {
6801:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
6802:   }
6803:   *cfltime = ts->cfltime;
6804:   return(0);
6805: }

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

6810:    Input Parameters:
6811: .  ts   - the TS context.
6812: .  xl   - lower bound.
6813: .  xu   - upper bound.

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

6819:    Level: advanced

6821: @*/
6822: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6823: {
6825:   SNES           snes;

6828:   TSGetSNES(ts,&snes);
6829:   SNESVISetVariableBounds(snes,xl,xu);
6830:   return(0);
6831: }

6833: #if defined(PETSC_HAVE_MATLAB_ENGINE)
6834: #include <mex.h>

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

6838: /*
6839:    TSComputeFunction_Matlab - Calls the function that has been set with
6840:                          TSSetFunctionMatlab().

6842:    Collective on TS

6844:    Input Parameters:
6845: +  snes - the TS context
6846: -  u - input vector

6848:    Output Parameter:
6849: .  y - function vector, as set by TSSetFunction()

6851:    Notes:
6852:    TSComputeFunction() is typically used within nonlinear solvers
6853:    implementations, so most users would not generally call this routine
6854:    themselves.

6856:    Level: developer

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

6860: .seealso: TSSetFunction(), TSGetFunction()
6861: */
6862: PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6863: {
6864:   PetscErrorCode  ierr;
6865:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6866:   int             nlhs  = 1,nrhs = 7;
6867:   mxArray         *plhs[1],*prhs[7];
6868:   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;


6878:   PetscMemcpy(&ls,&snes,sizeof(snes));
6879:   PetscMemcpy(&lx,&u,sizeof(u));
6880:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
6881:   PetscMemcpy(&ly,&y,sizeof(u));

6883:   prhs[0] =  mxCreateDoubleScalar((double)ls);
6884:   prhs[1] =  mxCreateDoubleScalar(time);
6885:   prhs[2] =  mxCreateDoubleScalar((double)lx);
6886:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6887:   prhs[4] =  mxCreateDoubleScalar((double)ly);
6888:   prhs[5] =  mxCreateString(sctx->funcname);
6889:   prhs[6] =  sctx->ctx;
6890:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
6891:    mxGetScalar(plhs[0]);
6892:   mxDestroyArray(prhs[0]);
6893:   mxDestroyArray(prhs[1]);
6894:   mxDestroyArray(prhs[2]);
6895:   mxDestroyArray(prhs[3]);
6896:   mxDestroyArray(prhs[4]);
6897:   mxDestroyArray(prhs[5]);
6898:   mxDestroyArray(plhs[0]);
6899:   return(0);
6900: }

6902: /*
6903:    TSSetFunctionMatlab - Sets the function evaluation routine and function
6904:    vector for use by the TS routines in solving ODEs
6905:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

6907:    Logically Collective on TS

6909:    Input Parameters:
6910: +  ts - the TS context
6911: -  func - function evaluation routine

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

6916:    Level: beginner

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

6920: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6921: */
6922: PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6923: {
6924:   PetscErrorCode  ierr;
6925:   TSMatlabContext *sctx;

6928:   /* currently sctx is memory bleed */
6929:   PetscNew(&sctx);
6930:   PetscStrallocpy(func,&sctx->funcname);
6931:   /*
6932:      This should work, but it doesn't
6933:   sctx->ctx = ctx;
6934:   mexMakeArrayPersistent(sctx->ctx);
6935:   */
6936:   sctx->ctx = mxDuplicateArray(ctx);

6938:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
6939:   return(0);
6940: }

6942: /*
6943:    TSComputeJacobian_Matlab - Calls the function that has been set with
6944:                          TSSetJacobianMatlab().

6946:    Collective on TS

6948:    Input Parameters:
6949: +  ts - the TS context
6950: .  u - input vector
6951: .  A, B - the matrices
6952: -  ctx - user context

6954:    Level: developer

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

6958: .seealso: TSSetFunction(), TSGetFunction()
6959: @*/
6960: PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6961: {
6962:   PetscErrorCode  ierr;
6963:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6964:   int             nlhs  = 2,nrhs = 9;
6965:   mxArray         *plhs[2],*prhs[9];
6966:   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;


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

6974:   PetscMemcpy(&ls,&ts,sizeof(ts));
6975:   PetscMemcpy(&lx,&u,sizeof(u));
6976:   PetscMemcpy(&lxdot,&udot,sizeof(u));
6977:   PetscMemcpy(&lA,A,sizeof(u));
6978:   PetscMemcpy(&lB,B,sizeof(u));

6980:   prhs[0] =  mxCreateDoubleScalar((double)ls);
6981:   prhs[1] =  mxCreateDoubleScalar((double)time);
6982:   prhs[2] =  mxCreateDoubleScalar((double)lx);
6983:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6984:   prhs[4] =  mxCreateDoubleScalar((double)shift);
6985:   prhs[5] =  mxCreateDoubleScalar((double)lA);
6986:   prhs[6] =  mxCreateDoubleScalar((double)lB);
6987:   prhs[7] =  mxCreateString(sctx->funcname);
6988:   prhs[8] =  sctx->ctx;
6989:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
6990:    mxGetScalar(plhs[0]);
6991:   mxDestroyArray(prhs[0]);
6992:   mxDestroyArray(prhs[1]);
6993:   mxDestroyArray(prhs[2]);
6994:   mxDestroyArray(prhs[3]);
6995:   mxDestroyArray(prhs[4]);
6996:   mxDestroyArray(prhs[5]);
6997:   mxDestroyArray(prhs[6]);
6998:   mxDestroyArray(prhs[7]);
6999:   mxDestroyArray(plhs[0]);
7000:   mxDestroyArray(plhs[1]);
7001:   return(0);
7002: }

7004: /*
7005:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
7006:    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

7008:    Logically Collective on TS

7010:    Input Parameters:
7011: +  ts - the TS context
7012: .  A,B - Jacobian matrices
7013: .  func - function evaluation routine
7014: -  ctx - user context

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

7019:    Level: developer

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

7023: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
7024: */
7025: PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
7026: {
7027:   PetscErrorCode  ierr;
7028:   TSMatlabContext *sctx;

7031:   /* currently sctx is memory bleed */
7032:   PetscNew(&sctx);
7033:   PetscStrallocpy(func,&sctx->funcname);
7034:   /*
7035:      This should work, but it doesn't
7036:   sctx->ctx = ctx;
7037:   mexMakeArrayPersistent(sctx->ctx);
7038:   */
7039:   sctx->ctx = mxDuplicateArray(ctx);

7041:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
7042:   return(0);
7043: }

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

7048:    Collective on TS

7050: .seealso: TSSetFunction(), TSGetFunction()
7051: @*/
7052: PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
7053: {
7054:   PetscErrorCode  ierr;
7055:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
7056:   int             nlhs  = 1,nrhs = 6;
7057:   mxArray         *plhs[1],*prhs[6];
7058:   long long int   lx = 0,ls = 0;


7064:   PetscMemcpy(&ls,&ts,sizeof(ts));
7065:   PetscMemcpy(&lx,&u,sizeof(u));

7067:   prhs[0] =  mxCreateDoubleScalar((double)ls);
7068:   prhs[1] =  mxCreateDoubleScalar((double)it);
7069:   prhs[2] =  mxCreateDoubleScalar((double)time);
7070:   prhs[3] =  mxCreateDoubleScalar((double)lx);
7071:   prhs[4] =  mxCreateString(sctx->funcname);
7072:   prhs[5] =  sctx->ctx;
7073:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
7074:    mxGetScalar(plhs[0]);
7075:   mxDestroyArray(prhs[0]);
7076:   mxDestroyArray(prhs[1]);
7077:   mxDestroyArray(prhs[2]);
7078:   mxDestroyArray(prhs[3]);
7079:   mxDestroyArray(prhs[4]);
7080:   mxDestroyArray(plhs[0]);
7081:   return(0);
7082: }

7084: /*
7085:    TSMonitorSetMatlab - Sets the monitor function from Matlab

7087:    Level: developer

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

7091: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
7092: */
7093: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
7094: {
7095:   PetscErrorCode  ierr;
7096:   TSMatlabContext *sctx;

7099:   /* currently sctx is memory bleed */
7100:   PetscNew(&sctx);
7101:   PetscStrallocpy(func,&sctx->funcname);
7102:   /*
7103:      This should work, but it doesn't
7104:   sctx->ctx = ctx;
7105:   mexMakeArrayPersistent(sctx->ctx);
7106:   */
7107:   sctx->ctx = mxDuplicateArray(ctx);

7109:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
7110:   return(0);
7111: }
7112: #endif

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

7118:    Collective on TS

7120:    Input Parameters:
7121: +  ts - the TS context
7122: .  step - current time-step
7123: .  ptime - current time
7124: .  u - current solution
7125: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

7127:    Options Database:
7128: .   -ts_monitor_lg_solution_variables

7130:    Level: intermediate

7132:    Notes: Each process in a parallel run displays its component solutions in a separate window

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

7136: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
7137:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
7138:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
7139:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
7140: @*/
7141: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7142: {
7143:   PetscErrorCode    ierr;
7144:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
7145:   const PetscScalar *yy;
7146:   Vec               v;

7149:   if (step < 0) return(0); /* -1 indicates interpolated solution */
7150:   if (!step) {
7151:     PetscDrawAxis axis;
7152:     PetscInt      dim;
7153:     PetscDrawLGGetAxis(ctx->lg,&axis);
7154:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
7155:     if (!ctx->names) {
7156:       PetscBool flg;
7157:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
7158:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
7159:       if (flg) {
7160:         PetscInt i,n;
7161:         char     **names;
7162:         VecGetSize(u,&n);
7163:         PetscMalloc1(n+1,&names);
7164:         for (i=0; i<n; i++) {
7165:           PetscMalloc1(5,&names[i]);
7166:           PetscSNPrintf(names[i],5,"%D",i);
7167:         }
7168:         names[n] = NULL;
7169:         ctx->names = names;
7170:       }
7171:     }
7172:     if (ctx->names && !ctx->displaynames) {
7173:       char      **displaynames;
7174:       PetscBool flg;
7175:       VecGetLocalSize(u,&dim);
7176:       PetscMalloc1(dim+1,&displaynames);
7177:       PetscMemzero(displaynames,(dim+1)*sizeof(char*));
7178:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
7179:       if (flg) {
7180:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
7181:       }
7182:       PetscStrArrayDestroy(&displaynames);
7183:     }
7184:     if (ctx->displaynames) {
7185:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
7186:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
7187:     } else if (ctx->names) {
7188:       VecGetLocalSize(u,&dim);
7189:       PetscDrawLGSetDimension(ctx->lg,dim);
7190:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
7191:     } else {
7192:       VecGetLocalSize(u,&dim);
7193:       PetscDrawLGSetDimension(ctx->lg,dim);
7194:     }
7195:     PetscDrawLGReset(ctx->lg);
7196:   }

7198:   if (!ctx->transform) v = u;
7199:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
7200:   VecGetArrayRead(v,&yy);
7201:   if (ctx->displaynames) {
7202:     PetscInt i;
7203:     for (i=0; i<ctx->ndisplayvariables; i++)
7204:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
7205:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
7206:   } else {
7207: #if defined(PETSC_USE_COMPLEX)
7208:     PetscInt  i,n;
7209:     PetscReal *yreal;
7210:     VecGetLocalSize(v,&n);
7211:     PetscMalloc1(n,&yreal);
7212:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
7213:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
7214:     PetscFree(yreal);
7215: #else
7216:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
7217: #endif
7218:   }
7219:   VecRestoreArrayRead(v,&yy);
7220:   if (ctx->transform) {VecDestroy(&v);}

7222:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
7223:     PetscDrawLGDraw(ctx->lg);
7224:     PetscDrawLGSave(ctx->lg);
7225:   }
7226:   return(0);
7227: }

7229: /*@C
7230:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

7232:    Collective on TS

7234:    Input Parameters:
7235: +  ts - the TS context
7236: -  names - the names of the components, final string must be NULL

7238:    Level: intermediate

7240:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

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

7244: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
7245: @*/
7246: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
7247: {
7248:   PetscErrorCode    ierr;
7249:   PetscInt          i;

7252:   for (i=0; i<ts->numbermonitors; i++) {
7253:     if (ts->monitor[i] == TSMonitorLGSolution) {
7254:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
7255:       break;
7256:     }
7257:   }
7258:   return(0);
7259: }

7261: /*@C
7262:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

7264:    Collective on TS

7266:    Input Parameters:
7267: +  ts - the TS context
7268: -  names - the names of the components, final string must be NULL

7270:    Level: intermediate

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

7274: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
7275: @*/
7276: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
7277: {
7278:   PetscErrorCode    ierr;

7281:   PetscStrArrayDestroy(&ctx->names);
7282:   PetscStrArrayallocpy(names,&ctx->names);
7283:   return(0);
7284: }

7286: /*@C
7287:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

7289:    Collective on TS

7291:    Input Parameter:
7292: .  ts - the TS context

7294:    Output Parameter:
7295: .  names - the names of the components, final string must be NULL

7297:    Level: intermediate

7299:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

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

7303: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7304: @*/
7305: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
7306: {
7307:   PetscInt       i;

7310:   *names = NULL;
7311:   for (i=0; i<ts->numbermonitors; i++) {
7312:     if (ts->monitor[i] == TSMonitorLGSolution) {
7313:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
7314:       *names = (const char *const *)ctx->names;
7315:       break;
7316:     }
7317:   }
7318:   return(0);
7319: }

7321: /*@C
7322:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

7324:    Collective on TS

7326:    Input Parameters:
7327: +  ctx - the TSMonitorLG context
7328: .  displaynames - the names of the components, final string must be NULL

7330:    Level: intermediate

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

7334: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
7335: @*/
7336: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
7337: {
7338:   PetscInt          j = 0,k;
7339:   PetscErrorCode    ierr;

7342:   if (!ctx->names) return(0);
7343:   PetscStrArrayDestroy(&ctx->displaynames);
7344:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
7345:   while (displaynames[j]) j++;
7346:   ctx->ndisplayvariables = j;
7347:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
7348:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
7349:   j = 0;
7350:   while (displaynames[j]) {
7351:     k = 0;
7352:     while (ctx->names[k]) {
7353:       PetscBool flg;
7354:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
7355:       if (flg) {
7356:         ctx->displayvariables[j] = k;
7357:         break;
7358:       }
7359:       k++;
7360:     }
7361:     j++;
7362:   }
7363:   return(0);
7364: }

7366: /*@C
7367:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

7369:    Collective on TS

7371:    Input Parameters:
7372: +  ts - the TS context
7373: .  displaynames - the names of the components, final string must be NULL

7375:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

7377:    Level: intermediate

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

7381: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
7382: @*/
7383: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
7384: {
7385:   PetscInt          i;
7386:   PetscErrorCode    ierr;

7389:   for (i=0; i<ts->numbermonitors; i++) {
7390:     if (ts->monitor[i] == TSMonitorLGSolution) {
7391:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
7392:       break;
7393:     }
7394:   }
7395:   return(0);
7396: }

7398: /*@C
7399:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

7401:    Collective on TS

7403:    Input Parameters:
7404: +  ts - the TS context
7405: .  transform - the transform function
7406: .  destroy - function to destroy the optional context
7407: -  ctx - optional context used by transform function

7409:    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

7411:    Level: intermediate

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

7415: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
7416: @*/
7417: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
7418: {
7419:   PetscInt          i;
7420:   PetscErrorCode    ierr;

7423:   for (i=0; i<ts->numbermonitors; i++) {
7424:     if (ts->monitor[i] == TSMonitorLGSolution) {
7425:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
7426:     }
7427:   }
7428:   return(0);
7429: }

7431: /*@C
7432:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

7434:    Collective on TSLGCtx

7436:    Input Parameters:
7437: +  ts - the TS context
7438: .  transform - the transform function
7439: .  destroy - function to destroy the optional context
7440: -  ctx - optional context used by transform function

7442:    Level: intermediate

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

7446: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
7447: @*/
7448: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
7449: {
7451:   ctx->transform    = transform;
7452:   ctx->transformdestroy = destroy;
7453:   ctx->transformctx = tctx;
7454:   return(0);
7455: }

7457: /*@C
7458:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
7459:        in a time based line graph

7461:    Collective on TS

7463:    Input Parameters:
7464: +  ts - the TS context
7465: .  step - current time-step
7466: .  ptime - current time
7467: .  u - current solution
7468: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

7470:    Level: intermediate

7472:    Notes: Each process in a parallel run displays its component errors in a separate window

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

7476:    Options Database Keys:
7477: .  -ts_monitor_lg_error - create a graphical monitor of error history

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

7481: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
7482: @*/
7483: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
7484: {
7485:   PetscErrorCode    ierr;
7486:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
7487:   const PetscScalar *yy;
7488:   Vec               y;

7491:   if (!step) {
7492:     PetscDrawAxis axis;
7493:     PetscInt      dim;
7494:     PetscDrawLGGetAxis(ctx->lg,&axis);
7495:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
7496:     VecGetLocalSize(u,&dim);
7497:     PetscDrawLGSetDimension(ctx->lg,dim);
7498:     PetscDrawLGReset(ctx->lg);
7499:   }
7500:   VecDuplicate(u,&y);
7501:   TSComputeSolutionFunction(ts,ptime,y);
7502:   VecAXPY(y,-1.0,u);
7503:   VecGetArrayRead(y,&yy);
7504: #if defined(PETSC_USE_COMPLEX)
7505:   {
7506:     PetscReal *yreal;
7507:     PetscInt  i,n;
7508:     VecGetLocalSize(y,&n);
7509:     PetscMalloc1(n,&yreal);
7510:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
7511:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
7512:     PetscFree(yreal);
7513:   }
7514: #else
7515:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
7516: #endif
7517:   VecRestoreArrayRead(y,&yy);
7518:   VecDestroy(&y);
7519:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
7520:     PetscDrawLGDraw(ctx->lg);
7521:     PetscDrawLGSave(ctx->lg);
7522:   }
7523:   return(0);
7524: }

7526: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7527: {
7528:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7529:   PetscReal      x   = ptime,y;
7531:   PetscInt       its;

7534:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7535:   if (!n) {
7536:     PetscDrawAxis axis;
7537:     PetscDrawLGGetAxis(ctx->lg,&axis);
7538:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
7539:     PetscDrawLGReset(ctx->lg);
7540:     ctx->snes_its = 0;
7541:   }
7542:   TSGetSNESIterations(ts,&its);
7543:   y    = its - ctx->snes_its;
7544:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7545:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7546:     PetscDrawLGDraw(ctx->lg);
7547:     PetscDrawLGSave(ctx->lg);
7548:   }
7549:   ctx->snes_its = its;
7550:   return(0);
7551: }

7553: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7554: {
7555:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7556:   PetscReal      x   = ptime,y;
7558:   PetscInt       its;

7561:   if (n < 0) return(0); /* -1 indicates interpolated solution */
7562:   if (!n) {
7563:     PetscDrawAxis axis;
7564:     PetscDrawLGGetAxis(ctx->lg,&axis);
7565:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
7566:     PetscDrawLGReset(ctx->lg);
7567:     ctx->ksp_its = 0;
7568:   }
7569:   TSGetKSPIterations(ts,&its);
7570:   y    = its - ctx->ksp_its;
7571:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
7572:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7573:     PetscDrawLGDraw(ctx->lg);
7574:     PetscDrawLGSave(ctx->lg);
7575:   }
7576:   ctx->ksp_its = its;
7577:   return(0);
7578: }

7580: /*@
7581:    TSComputeLinearStability - computes the linear stability function at a point

7583:    Collective on TS and Vec

7585:    Input Parameters:
7586: +  ts - the TS context
7587: -  xr,xi - real and imaginary part of input arguments

7589:    Output Parameters:
7590: .  yr,yi - real and imaginary part of function value

7592:    Level: developer

7594: .keywords: TS, compute

7596: .seealso: TSSetRHSFunction(), TSComputeIFunction()
7597: @*/
7598: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
7599: {

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

7609: /* ------------------------------------------------------------------------*/
7610: /*@C
7611:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

7613:    Collective on TS

7615:    Input Parameters:
7616: .  ts  - the ODE solver object

7618:    Output Parameter:
7619: .  ctx - the context

7621:    Level: intermediate

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

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

7627: @*/
7628: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
7629: {

7633:   PetscNew(ctx);
7634:   return(0);
7635: }

7637: /*@C
7638:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

7640:    Collective on TS

7642:    Input Parameters:
7643: +  ts - the TS context
7644: .  step - current time-step
7645: .  ptime - current time
7646: .  u  - current solution
7647: -  dctx - the envelope context

7649:    Options Database:
7650: .  -ts_monitor_envelope

7652:    Level: intermediate

7654:    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

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

7658: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7659: @*/
7660: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7661: {
7662:   PetscErrorCode       ierr;
7663:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

7666:   if (!ctx->max) {
7667:     VecDuplicate(u,&ctx->max);
7668:     VecDuplicate(u,&ctx->min);
7669:     VecCopy(u,ctx->max);
7670:     VecCopy(u,ctx->min);
7671:   } else {
7672:     VecPointwiseMax(ctx->max,u,ctx->max);
7673:     VecPointwiseMin(ctx->min,u,ctx->min);
7674:   }
7675:   return(0);
7676: }

7678: /*@C
7679:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

7681:    Collective on TS

7683:    Input Parameter:
7684: .  ts - the TS context

7686:    Output Parameter:
7687: +  max - the maximum values
7688: -  min - the minimum values

7690:    Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

7692:    Level: intermediate

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

7696: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7697: @*/
7698: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7699: {
7700:   PetscInt i;

7703:   if (max) *max = NULL;
7704:   if (min) *min = NULL;
7705:   for (i=0; i<ts->numbermonitors; i++) {
7706:     if (ts->monitor[i] == TSMonitorEnvelope) {
7707:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7708:       if (max) *max = ctx->max;
7709:       if (min) *min = ctx->min;
7710:       break;
7711:     }
7712:   }
7713:   return(0);
7714: }

7716: /*@C
7717:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

7719:    Collective on TSMonitorEnvelopeCtx

7721:    Input Parameter:
7722: .  ctx - the monitor context

7724:    Level: intermediate

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

7728: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7729: @*/
7730: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7731: {

7735:   VecDestroy(&(*ctx)->min);
7736:   VecDestroy(&(*ctx)->max);
7737:   PetscFree(*ctx);
7738:   return(0);
7739: }

7741: /*@
7742:    TSRollBack - Rolls back one time step

7744:    Collective on TS

7746:    Input Parameter:
7747: .  ts - the TS context obtained from TSCreate()

7749:    Level: advanced

7751: .keywords: TS, timestep, rollback

7753: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7754: @*/
7755: PetscErrorCode  TSRollBack(TS ts)
7756: {

7761:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7762:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7763:   (*ts->ops->rollback)(ts);
7764:   ts->time_step = ts->ptime - ts->ptime_prev;
7765:   ts->ptime = ts->ptime_prev;
7766:   ts->ptime_prev = ts->ptime_prev_rollback;
7767:   ts->steps--;
7768:   TSPostEvaluate(ts);
7769:   ts->steprollback = PETSC_TRUE;
7770:   return(0);
7771: }

7773: /*@
7774:    TSGetStages - Get the number of stages and stage values

7776:    Input Parameter:
7777: .  ts - the TS context obtained from TSCreate()

7779:    Level: advanced

7781: .keywords: TS, getstages

7783: .seealso: TSCreate()
7784: @*/
7785: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7786: {


7793:   if (!ts->ops->getstages) *ns=0;
7794:   else {
7795:     (*ts->ops->getstages)(ts,ns,Y);
7796:   }
7797:   return(0);
7798: }

7800: /*@C
7801:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

7803:   Collective on SNES

7805:   Input Parameters:
7806: + ts - the TS context
7807: . t - current timestep
7808: . U - state vector
7809: . Udot - time derivative of state vector
7810: . shift - shift to apply, see note below
7811: - ctx - an optional user context

7813:   Output Parameters:
7814: + J - Jacobian matrix (not altered in this routine)
7815: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

7817:   Level: intermediate

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

7822:   dF/dU + shift*dF/dUdot

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

7827:   This will first try to get the coloring from the DM.  If the DM type has no coloring
7828:   routine, then it will try to get the coloring from the matrix.  This requires that the
7829:   matrix have nonzero entries precomputed.

7831: .keywords: TS, finite differences, Jacobian, coloring, sparse
7832: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7833: @*/
7834: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7835: {
7836:   SNES           snes;
7837:   MatFDColoring  color;
7838:   PetscBool      hascolor, matcolor = PETSC_FALSE;

7842:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
7843:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
7844:   if (!color) {
7845:     DM         dm;
7846:     ISColoring iscoloring;

7848:     TSGetDM(ts, &dm);
7849:     DMHasColoring(dm, &hascolor);
7850:     if (hascolor && !matcolor) {
7851:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
7852:       MatFDColoringCreate(B, iscoloring, &color);
7853:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7854:       MatFDColoringSetFromOptions(color);
7855:       MatFDColoringSetUp(B, iscoloring, color);
7856:       ISColoringDestroy(&iscoloring);
7857:     } else {
7858:       MatColoring mc;

7860:       MatColoringCreate(B, &mc);
7861:       MatColoringSetDistance(mc, 2);
7862:       MatColoringSetType(mc, MATCOLORINGSL);
7863:       MatColoringSetFromOptions(mc);
7864:       MatColoringApply(mc, &iscoloring);
7865:       MatColoringDestroy(&mc);
7866:       MatFDColoringCreate(B, iscoloring, &color);
7867:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
7868:       MatFDColoringSetFromOptions(color);
7869:       MatFDColoringSetUp(B, iscoloring, color);
7870:       ISColoringDestroy(&iscoloring);
7871:     }
7872:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
7873:     PetscObjectDereference((PetscObject) color);
7874:   }
7875:   TSGetSNES(ts, &snes);
7876:   MatFDColoringApply(B, color, U, snes);
7877:   if (J != B) {
7878:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
7879:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
7880:   }
7881:   return(0);
7882: }

7884: /*@
7885:     TSSetFunctionDomainError - Set the function testing if the current state vector is valid

7887:     Input Parameters:
7888:     ts - the TS context
7889:     func - function called within TSFunctionDomainError

7891:     Level: intermediate

7893: .keywords: TS, state, domain
7894: .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7895: @*/

7897: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7898: {
7901:   ts->functiondomainerror = func;
7902:   return(0);
7903: }

7905: /*@
7906:     TSFunctionDomainError - Check if the current state is valid

7908:     Input Parameters:
7909:     ts - the TS context
7910:     stagetime - time of the simulation
7911:     Y - state vector to check.

7913:     Output Parameter:
7914:     accept - Set to PETSC_FALSE if the current state vector is valid.

7916:     Note:
7917:     This function should be used to ensure the state is in a valid part of the space.
7918:     For example, one can ensure here all values are positive.

7920:     Level: advanced
7921: @*/
7922: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7923: {


7929:   *accept = PETSC_TRUE;
7930:   if (ts->functiondomainerror) {
7931:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7932:   }
7933:   return(0);
7934: }

7936: /*@C
7937:   TSClone - This function clones a time step object.

7939:   Collective on MPI_Comm

7941:   Input Parameter:
7942: . tsin    - The input TS

7944:   Output Parameter:
7945: . tsout   - The output TS (cloned)

7947:   Notes:
7948:   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly.

7950:   When using TSDestroy() on a clone the user has to first reset the correct TS reference in the embedded SNES object: e.g.: by running SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); TSSetSNES(ts,snes_dup);

7952:   Level: developer

7954: .keywords: TS, clone
7955: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7956: @*/
7957: PetscErrorCode  TSClone(TS tsin, TS *tsout)
7958: {
7959:   TS             t;
7961:   SNES           snes_start;
7962:   DM             dm;
7963:   TSType         type;

7967:   *tsout = NULL;

7969:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

7971:   /* General TS description */
7972:   t->numbermonitors    = 0;
7973:   t->setupcalled       = 0;
7974:   t->ksp_its           = 0;
7975:   t->snes_its          = 0;
7976:   t->nwork             = 0;
7977:   t->rhsjacobian.time  = -1e20;
7978:   t->rhsjacobian.scale = 1.;
7979:   t->ijacobian.shift   = 1.;

7981:   TSGetSNES(tsin,&snes_start);
7982:   TSSetSNES(t,snes_start);

7984:   TSGetDM(tsin,&dm);
7985:   TSSetDM(t,dm);

7987:   t->adapt = tsin->adapt;
7988:   PetscObjectReference((PetscObject)t->adapt);

7990:   t->trajectory = tsin->trajectory;
7991:   PetscObjectReference((PetscObject)t->trajectory);

7993:   t->event = tsin->event;
7994:   if (t->event) t->event->refct++;

7996:   t->problem_type      = tsin->problem_type;
7997:   t->ptime             = tsin->ptime;
7998:   t->ptime_prev        = tsin->ptime_prev;
7999:   t->time_step         = tsin->time_step;
8000:   t->max_time          = tsin->max_time;
8001:   t->steps             = tsin->steps;
8002:   t->max_steps         = tsin->max_steps;
8003:   t->equation_type     = tsin->equation_type;
8004:   t->atol              = tsin->atol;
8005:   t->rtol              = tsin->rtol;
8006:   t->max_snes_failures = tsin->max_snes_failures;
8007:   t->max_reject        = tsin->max_reject;
8008:   t->errorifstepfailed = tsin->errorifstepfailed;

8010:   TSGetType(tsin,&type);
8011:   TSSetType(t,type);

8013:   t->vec_sol           = NULL;

8015:   t->cfltime          = tsin->cfltime;
8016:   t->cfltime_local    = tsin->cfltime_local;
8017:   t->exact_final_time = tsin->exact_final_time;

8019:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

8021:   if (((PetscObject)tsin)->fortran_func_pointers) {
8022:     PetscInt i;
8023:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
8024:     for (i=0; i<10; i++) {
8025:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
8026:     }
8027:   }
8028:   *tsout = t;
8029:   return(0);
8030: }