xref: /petsc/src/ts/interface/ts.c (revision d67e68b7b7c6faac19633dd452ade18af02e67b7)
1 
2 #include <petsc-private/tsimpl.h>        /*I "petscts.h"  I*/
3 #include <petscdmshell.h>
4 #include <petscdmda.h>
5 #include <petscviewer.h>
6 #include <petscdraw.h>
7 
8 /* Logging support */
9 PetscClassId  TS_CLASSID, DMTS_CLASSID;
10 PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
11 
12 const char *const TSExactFinalTimeOptions[] = {"STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};
13 
14 #undef __FUNCT__
15 #define __FUNCT__ "TSSetTypeFromOptions_Private"
16 /*
17   TSSetTypeFromOptions - Sets the type of ts from user options.
18 
19   Collective on TS
20 
21   Input Parameter:
22 . ts - The ts
23 
24   Level: intermediate
25 
26 .keywords: TS, set, options, database, type
27 .seealso: TSSetFromOptions(), TSSetType()
28 */
29 static PetscErrorCode TSSetTypeFromOptions_Private(PetscOptions *PetscOptionsObject,TS ts)
30 {
31   PetscBool      opt;
32   const char     *defaultType;
33   char           typeName[256];
34   PetscErrorCode ierr;
35 
36   PetscFunctionBegin;
37   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
38   else defaultType = TSEULER;
39 
40   if (!TSRegisterAllCalled) {ierr = TSRegisterAll();CHKERRQ(ierr);}
41   ierr = PetscOptionsFList("-ts_type", "TS method"," TSSetType", TSList, defaultType, typeName, 256, &opt);CHKERRQ(ierr);
42   if (opt) {
43     ierr = TSSetType(ts, typeName);CHKERRQ(ierr);
44   } else {
45     ierr = TSSetType(ts, defaultType);CHKERRQ(ierr);
46   }
47   PetscFunctionReturn(0);
48 }
49 
50 struct _n_TSMonitorDrawCtx {
51   PetscViewer   viewer;
52   PetscDrawAxis axis;
53   Vec           initialsolution;
54   PetscBool     showinitial;
55   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
56   PetscBool     showtimestepandtime;
57   int           color;
58 };
59 
60 #undef __FUNCT__
61 #define __FUNCT__ "TSSetFromOptions"
62 /*@
63    TSSetFromOptions - Sets various TS parameters from user options.
64 
65    Collective on TS
66 
67    Input Parameter:
68 .  ts - the TS context obtained from TSCreate()
69 
70    Options Database Keys:
71 +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSGL, TSSSP
72 .  -ts_checkpoint - checkpoint for adjoint sensitivity analysis
73 .  -ts_max_steps maxsteps - maximum number of time-steps to take
74 .  -ts_final_time time - maximum time to compute to
75 .  -ts_dt dt - initial time step
76 .  -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
77 .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
78 .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
79 .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
80 .  -ts_rtol <rtol> - relative tolerance for local truncation error
81 .  -ts_atol <atol> Absolute tolerance for local truncation error
82 .  -ts_monitor - print information at each timestep
83 .  -ts_monitor_lg_timestep - Monitor timestep size graphically
84 .  -ts_monitor_lg_solution - Monitor solution graphically
85 .  -ts_monitor_lg_error - Monitor error graphically
86 .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
87 .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
88 .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
89 .  -ts_monitor_draw_solution - Monitor solution graphically
90 .  -ts_monitor_draw_solution_phase - Monitor solution graphically with phase diagram
91 .  -ts_monitor_draw_error - Monitor error graphically
92 .  -ts_monitor_solution_binary <filename> - Save each solution to a binary file
93 -  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts
94 
95    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
96 
97    Level: beginner
98 
99 .keywords: TS, timestep, set, options, database
100 
101 .seealso: TSGetType()
102 @*/
103 PetscErrorCode  TSSetFromOptions(TS ts)
104 {
105   PetscBool              opt,flg;
106   PetscErrorCode         ierr;
107   PetscViewer            monviewer;
108   char                   monfilename[PETSC_MAX_PATH_LEN];
109   SNES                   snes;
110   TSAdapt                adapt;
111   PetscReal              time_step;
112   TSExactFinalTimeOption eftopt;
113   char                   dir[16];
114 
115   PetscFunctionBegin;
116   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
117   ierr = PetscObjectOptionsBegin((PetscObject)ts);CHKERRQ(ierr);
118   /* Handle TS type options */
119   ierr = TSSetTypeFromOptions_Private(PetscOptionsObject,ts);CHKERRQ(ierr);
120 
121   /* Handle generic TS options */
122   ierr = PetscOptionsBool("-ts_checkpoint","Checkpoint for adjoint sensitivity analysis","TSSetCheckpoint",ts->checkpoint,&ts->checkpoint,NULL);CHKERRQ(ierr);
123   ierr = PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);CHKERRQ(ierr);
124   ierr = PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);CHKERRQ(ierr);
125   ierr = PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);CHKERRQ(ierr);
126   ierr = PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);CHKERRQ(ierr);
127   if (flg) {
128     ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
129   }
130   ierr = PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);CHKERRQ(ierr);
131   if (flg) {ierr = TSSetExactFinalTime(ts,eftopt);CHKERRQ(ierr);}
132   ierr = PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);CHKERRQ(ierr);
133   ierr = PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);CHKERRQ(ierr);
134   ierr = PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);CHKERRQ(ierr);
135   ierr = PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);CHKERRQ(ierr);
136   ierr = PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);CHKERRQ(ierr);
137 
138 #if defined(PETSC_HAVE_SAWS)
139   {
140   PetscBool set;
141   flg  = PETSC_FALSE;
142   ierr = PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);CHKERRQ(ierr);
143   if (set) {
144     ierr = PetscObjectSAWsSetBlock((PetscObject)ts,flg);CHKERRQ(ierr);
145   }
146   }
147 #endif
148 
149   /* Monitor options */
150   ierr = PetscOptionsString("-ts_monitor","Monitor timestep size","TSMonitorDefault","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
151   if (flg) {
152     ierr = PetscViewerASCIIOpen(PetscObjectComm((PetscObject)ts),monfilename,&monviewer);CHKERRQ(ierr);
153     ierr = TSMonitorSet(ts,TSMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
154   }
155   ierr = PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
156   if (flg) {ierr = PetscPythonMonitorSet((PetscObject)ts,monfilename);CHKERRQ(ierr);}
157 
158   ierr = PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);CHKERRQ(ierr);
159   if (opt) {
160     TSMonitorLGCtx ctx;
161     PetscInt       howoften = 1;
162 
163     ierr = PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);CHKERRQ(ierr);
164     ierr = TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
165     ierr = TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
166   }
167   ierr = PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);CHKERRQ(ierr);
168   if (opt) {
169     TSMonitorLGCtx ctx;
170     PetscInt       howoften = 1;
171 
172     ierr = PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
173     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
174     ierr = TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
175   }
176   ierr = PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);CHKERRQ(ierr);
177   if (opt) {
178     TSMonitorLGCtx ctx;
179     PetscInt       howoften = 1;
180 
181     ierr = PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);CHKERRQ(ierr);
182     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
183     ierr = TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
184   }
185   ierr = PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);CHKERRQ(ierr);
186   if (opt) {
187     TSMonitorLGCtx ctx;
188     PetscInt       howoften = 1;
189 
190     ierr = PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
191     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
192     ierr = TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
193   }
194   ierr = PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);CHKERRQ(ierr);
195   if (opt) {
196     TSMonitorLGCtx ctx;
197     PetscInt       howoften = 1;
198 
199     ierr = PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
200     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
201     ierr = TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
202   }
203   ierr = PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);CHKERRQ(ierr);
204   if (opt) {
205     TSMonitorSPEigCtx ctx;
206     PetscInt          howoften = 1;
207 
208     ierr = PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);CHKERRQ(ierr);
209     ierr = TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
210     ierr = TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);CHKERRQ(ierr);
211   }
212   opt  = PETSC_FALSE;
213   ierr = PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);CHKERRQ(ierr);
214   if (opt) {
215     TSMonitorDrawCtx ctx;
216     PetscInt         howoften = 1;
217 
218     ierr = PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
219     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
220     ierr = TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
221   }
222   opt  = PETSC_FALSE;
223   ierr = PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);CHKERRQ(ierr);
224   if (opt) {
225     TSMonitorDrawCtx ctx;
226     PetscReal        bounds[4];
227     PetscInt         n = 4;
228     PetscDraw        draw;
229 
230     ierr = PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);CHKERRQ(ierr);
231     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
232     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,1,&ctx);CHKERRQ(ierr);
233     ierr = PetscViewerDrawGetDraw(ctx->viewer,0,&draw);CHKERRQ(ierr);
234     ierr = PetscDrawClear(draw);CHKERRQ(ierr);
235     ierr = PetscDrawAxisCreate(draw,&ctx->axis);CHKERRQ(ierr);
236     ierr = PetscDrawAxisSetLimits(ctx->axis,bounds[0],bounds[2],bounds[1],bounds[3]);CHKERRQ(ierr);
237     ierr = PetscDrawAxisSetLabels(ctx->axis,"Phase Diagram","Variable 1","Variable 2");CHKERRQ(ierr);
238     ierr = PetscDrawAxisDraw(ctx->axis);CHKERRQ(ierr);
239     /* ierr = PetscDrawSetCoordinates(draw,bounds[0],bounds[1],bounds[2],bounds[3]);CHKERRQ(ierr); */
240     ierr = TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
241   }
242   opt  = PETSC_FALSE;
243   ierr = PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);CHKERRQ(ierr);
244   if (opt) {
245     TSMonitorDrawCtx ctx;
246     PetscInt         howoften = 1;
247 
248     ierr = PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);CHKERRQ(ierr);
249     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
250     ierr = TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
251   }
252   opt  = PETSC_FALSE;
253   ierr = PetscOptionsString("-ts_monitor_solution_binary","Save each solution to a binary file","TSMonitorSolutionBinary",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
254   if (flg) {
255     PetscViewer ctx;
256     if (monfilename[0]) {
257       ierr = PetscViewerBinaryOpen(PetscObjectComm((PetscObject)ts),monfilename,FILE_MODE_WRITE,&ctx);CHKERRQ(ierr);
258       ierr = TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
259     } else {
260       ctx = PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)ts));
261       ierr = TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))NULL);CHKERRQ(ierr);
262     }
263   }
264   opt  = PETSC_FALSE;
265   ierr = 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);CHKERRQ(ierr);
266   if (flg) {
267     const char *ptr,*ptr2;
268     char       *filetemplate;
269     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
270     /* Do some cursory validation of the input. */
271     ierr = PetscStrstr(monfilename,"%",(char**)&ptr);CHKERRQ(ierr);
272     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
273     for (ptr++; ptr && *ptr; ptr++) {
274       ierr = PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);CHKERRQ(ierr);
275       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");
276       if (ptr2) break;
277     }
278     ierr = PetscStrallocpy(monfilename,&filetemplate);CHKERRQ(ierr);
279     ierr = TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);CHKERRQ(ierr);
280   }
281 
282   ierr = PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);CHKERRQ(ierr);
283   if (flg) {
284     TSMonitorDMDARayCtx *rayctx;
285     int                  ray = 0;
286     DMDADirection        ddir;
287     DM                   da;
288     PetscMPIInt          rank;
289 
290     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
291     if (dir[0] == 'x') ddir = DMDA_X;
292     else if (dir[0] == 'y') ddir = DMDA_Y;
293     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
294     sscanf(dir+2,"%d",&ray);
295 
296     ierr = PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);CHKERRQ(ierr);
297     ierr = PetscNew(&rayctx);CHKERRQ(ierr);
298     ierr = TSGetDM(ts,&da);CHKERRQ(ierr);
299     ierr = DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);CHKERRQ(ierr);
300     ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);CHKERRQ(ierr);
301     if (!rank) {
302       ierr = PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);CHKERRQ(ierr);
303     }
304     rayctx->lgctx = NULL;
305     ierr = TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);CHKERRQ(ierr);
306   }
307   ierr = PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);CHKERRQ(ierr);
308   if (flg) {
309     TSMonitorDMDARayCtx *rayctx;
310     int                 ray = 0;
311     DMDADirection       ddir;
312     DM                  da;
313     PetscInt            howoften = 1;
314 
315     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
316     if      (dir[0] == 'x') ddir = DMDA_X;
317     else if (dir[0] == 'y') ddir = DMDA_Y;
318     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
319     sscanf(dir+2, "%d", &ray);
320 
321     ierr = PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);CHKERRQ(ierr);
322     ierr = PetscNew(&rayctx);CHKERRQ(ierr);
323     ierr = TSGetDM(ts, &da);CHKERRQ(ierr);
324     ierr = DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);CHKERRQ(ierr);
325     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);CHKERRQ(ierr);
326     ierr = TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);CHKERRQ(ierr);
327   }
328 
329   /*
330      This code is all wrong. One is creating objects inside the TSSetFromOptions() so if run with the options gui
331      will bleed memory. Also one is using a PetscOptionsBegin() inside a PetscOptionsBegin()
332   */
333   ierr = TSGetAdapt(ts,&adapt);CHKERRQ(ierr);
334   ierr = TSAdaptSetFromOptions(PetscOptionsObject,adapt);CHKERRQ(ierr);
335 
336   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
337   if (ts->problem_type == TS_LINEAR) {ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);}
338 
339   /* Handle specific TS options */
340   if (ts->ops->setfromoptions) {
341     ierr = (*ts->ops->setfromoptions)(PetscOptionsObject,ts);CHKERRQ(ierr);
342   }
343 
344   /* process any options handlers added with PetscObjectAddOptionsHandler() */
345   ierr = PetscObjectProcessOptionsHandlers((PetscObject)ts);CHKERRQ(ierr);
346   ierr = PetscOptionsEnd();CHKERRQ(ierr);
347   PetscFunctionReturn(0);
348 }
349 
350 #undef __FUNCT__
351 #define __FUNCT__ "TSSetCheckpoint"
352 /*@
353    TSSetCheckpoint - Allows one to checkpoint the forward run,
354    useful for adjoint sensitivity analysis.
355 
356    Collective on TS
357 
358    Input Parameters:
359 +  ts - the TS context obtained from TSCreate()
360 -  checkpoint - flag that indicates if the forward solution will be checkpointed
361 
362    Level: intermediate
363 
364 .seealso:
365 
366 .keywords: TS, set, checkpoint
367 @*/
368 PetscErrorCode  TSSetCheckpoint(TS ts,PetscBool checkpoint)
369 {
370   PetscFunctionBegin;
371   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
372   ts->checkpoint = checkpoint;
373   PetscFunctionReturn(0);
374 }
375 
376 #undef __FUNCT__
377 #define __FUNCT__ "TSComputeRHSJacobian"
378 /*@
379    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
380       set with TSSetRHSJacobian().
381 
382    Collective on TS and Vec
383 
384    Input Parameters:
385 +  ts - the TS context
386 .  t - current timestep
387 -  U - input vector
388 
389    Output Parameters:
390 +  A - Jacobian matrix
391 .  B - optional preconditioning matrix
392 -  flag - flag indicating matrix structure
393 
394    Notes:
395    Most users should not need to explicitly call this routine, as it
396    is used internally within the nonlinear solvers.
397 
398    See KSPSetOperators() for important information about setting the
399    flag parameter.
400 
401    Level: developer
402 
403 .keywords: SNES, compute, Jacobian, matrix
404 
405 .seealso:  TSSetRHSJacobian(), KSPSetOperators()
406 @*/
407 PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
408 {
409   PetscErrorCode ierr;
410   PetscObjectState Ustate;
411   DM             dm;
412   DMTS           tsdm;
413   TSRHSJacobian  rhsjacobianfunc;
414   void           *ctx;
415   TSIJacobian    ijacobianfunc;
416 
417   PetscFunctionBegin;
418   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
419   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
420   PetscCheckSameComm(ts,1,U,3);
421   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
422   ierr = DMGetDMTS(dm,&tsdm);CHKERRQ(ierr);
423   ierr = DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);CHKERRQ(ierr);
424   ierr = DMTSGetIJacobian(dm,&ijacobianfunc,NULL);CHKERRQ(ierr);
425   ierr = PetscObjectStateGet((PetscObject)U,&Ustate);CHKERRQ(ierr);
426   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate))) {
427     PetscFunctionReturn(0);
428   }
429 
430   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
431 
432   if (ts->rhsjacobian.reuse) {
433     ierr = MatShift(A,-ts->rhsjacobian.shift);CHKERRQ(ierr);
434     ierr = MatScale(A,1./ts->rhsjacobian.scale);CHKERRQ(ierr);
435     if (A != B) {
436       ierr = MatShift(B,-ts->rhsjacobian.shift);CHKERRQ(ierr);
437       ierr = MatScale(B,1./ts->rhsjacobian.scale);CHKERRQ(ierr);
438     }
439     ts->rhsjacobian.shift = 0;
440     ts->rhsjacobian.scale = 1.;
441   }
442 
443   if (rhsjacobianfunc) {
444     ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
445     PetscStackPush("TS user Jacobian function");
446     ierr = (*rhsjacobianfunc)(ts,t,U,A,B,ctx);CHKERRQ(ierr);
447     PetscStackPop;
448     ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
449     /* make sure user returned a correct Jacobian and preconditioner */
450     PetscValidHeaderSpecific(A,MAT_CLASSID,4);
451     PetscValidHeaderSpecific(B,MAT_CLASSID,5);
452   } else {
453     ierr = MatZeroEntries(A);CHKERRQ(ierr);
454     if (A != B) {ierr = MatZeroEntries(B);CHKERRQ(ierr);}
455   }
456   ts->rhsjacobian.time       = t;
457   ts->rhsjacobian.X          = U;
458   ierr                       = PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);CHKERRQ(ierr);
459   PetscFunctionReturn(0);
460 }
461 
462 #undef __FUNCT__
463 #define __FUNCT__ "TSComputeRHSFunction"
464 /*@
465    TSComputeRHSFunction - Evaluates the right-hand-side function.
466 
467    Collective on TS and Vec
468 
469    Input Parameters:
470 +  ts - the TS context
471 .  t - current time
472 -  U - state vector
473 
474    Output Parameter:
475 .  y - right hand side
476 
477    Note:
478    Most users should not need to explicitly call this routine, as it
479    is used internally within the nonlinear solvers.
480 
481    Level: developer
482 
483 .keywords: TS, compute
484 
485 .seealso: TSSetRHSFunction(), TSComputeIFunction()
486 @*/
487 PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
488 {
489   PetscErrorCode ierr;
490   TSRHSFunction  rhsfunction;
491   TSIFunction    ifunction;
492   void           *ctx;
493   DM             dm;
494 
495   PetscFunctionBegin;
496   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
497   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
498   PetscValidHeaderSpecific(y,VEC_CLASSID,4);
499   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
500   ierr = DMTSGetRHSFunction(dm,&rhsfunction,&ctx);CHKERRQ(ierr);
501   ierr = DMTSGetIFunction(dm,&ifunction,NULL);CHKERRQ(ierr);
502 
503   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
504 
505   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
506   if (rhsfunction) {
507     PetscStackPush("TS user right-hand-side function");
508     ierr = (*rhsfunction)(ts,t,U,y,ctx);CHKERRQ(ierr);
509     PetscStackPop;
510   } else {
511     ierr = VecZeroEntries(y);CHKERRQ(ierr);
512   }
513 
514   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
515   PetscFunctionReturn(0);
516 }
517 
518 #undef __FUNCT__
519 #define __FUNCT__ "TSComputeSolutionFunction"
520 /*@
521    TSComputeSolutionFunction - Evaluates the solution function.
522 
523    Collective on TS and Vec
524 
525    Input Parameters:
526 +  ts - the TS context
527 -  t - current time
528 
529    Output Parameter:
530 .  U - the solution
531 
532    Note:
533    Most users should not need to explicitly call this routine, as it
534    is used internally within the nonlinear solvers.
535 
536    Level: developer
537 
538 .keywords: TS, compute
539 
540 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
541 @*/
542 PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
543 {
544   PetscErrorCode     ierr;
545   TSSolutionFunction solutionfunction;
546   void               *ctx;
547   DM                 dm;
548 
549   PetscFunctionBegin;
550   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
551   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
552   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
553   ierr = DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);CHKERRQ(ierr);
554 
555   if (solutionfunction) {
556     PetscStackPush("TS user solution function");
557     ierr = (*solutionfunction)(ts,t,U,ctx);CHKERRQ(ierr);
558     PetscStackPop;
559   }
560   PetscFunctionReturn(0);
561 }
562 #undef __FUNCT__
563 #define __FUNCT__ "TSComputeForcingFunction"
564 /*@
565    TSComputeForcingFunction - Evaluates the forcing function.
566 
567    Collective on TS and Vec
568 
569    Input Parameters:
570 +  ts - the TS context
571 -  t - current time
572 
573    Output Parameter:
574 .  U - the function value
575 
576    Note:
577    Most users should not need to explicitly call this routine, as it
578    is used internally within the nonlinear solvers.
579 
580    Level: developer
581 
582 .keywords: TS, compute
583 
584 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
585 @*/
586 PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
587 {
588   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
589   void               *ctx;
590   DM                 dm;
591 
592   PetscFunctionBegin;
593   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
594   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
595   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
596   ierr = DMTSGetForcingFunction(dm,&forcing,&ctx);CHKERRQ(ierr);
597 
598   if (forcing) {
599     PetscStackPush("TS user forcing function");
600     ierr = (*forcing)(ts,t,U,ctx);CHKERRQ(ierr);
601     PetscStackPop;
602   }
603   PetscFunctionReturn(0);
604 }
605 
606 #undef __FUNCT__
607 #define __FUNCT__ "TSGetRHSVec_Private"
608 static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
609 {
610   Vec            F;
611   PetscErrorCode ierr;
612 
613   PetscFunctionBegin;
614   *Frhs = NULL;
615   ierr  = TSGetIFunction(ts,&F,NULL,NULL);CHKERRQ(ierr);
616   if (!ts->Frhs) {
617     ierr = VecDuplicate(F,&ts->Frhs);CHKERRQ(ierr);
618   }
619   *Frhs = ts->Frhs;
620   PetscFunctionReturn(0);
621 }
622 
623 #undef __FUNCT__
624 #define __FUNCT__ "TSGetRHSMats_Private"
625 static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
626 {
627   Mat            A,B;
628   PetscErrorCode ierr;
629 
630   PetscFunctionBegin;
631   if (Arhs) *Arhs = NULL;
632   if (Brhs) *Brhs = NULL;
633   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
634   if (Arhs) {
635     if (!ts->Arhs) {
636       ierr = MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);CHKERRQ(ierr);
637     }
638     *Arhs = ts->Arhs;
639   }
640   if (Brhs) {
641     if (!ts->Brhs) {
642       if (A != B) {
643         ierr = MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);CHKERRQ(ierr);
644       } else {
645         ts->Brhs = ts->Arhs;
646         ierr = PetscObjectReference((PetscObject)ts->Arhs);CHKERRQ(ierr);
647       }
648     }
649     *Brhs = ts->Brhs;
650   }
651   PetscFunctionReturn(0);
652 }
653 
654 #undef __FUNCT__
655 #define __FUNCT__ "TSComputeIFunction"
656 /*@
657    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
658 
659    Collective on TS and Vec
660 
661    Input Parameters:
662 +  ts - the TS context
663 .  t - current time
664 .  U - state vector
665 .  Udot - time derivative of state vector
666 -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
667 
668    Output Parameter:
669 .  Y - right hand side
670 
671    Note:
672    Most users should not need to explicitly call this routine, as it
673    is used internally within the nonlinear solvers.
674 
675    If the user did did not write their equations in implicit form, this
676    function recasts them in implicit form.
677 
678    Level: developer
679 
680 .keywords: TS, compute
681 
682 .seealso: TSSetIFunction(), TSComputeRHSFunction()
683 @*/
684 PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
685 {
686   PetscErrorCode ierr;
687   TSIFunction    ifunction;
688   TSRHSFunction  rhsfunction;
689   void           *ctx;
690   DM             dm;
691 
692   PetscFunctionBegin;
693   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
694   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
695   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
696   PetscValidHeaderSpecific(Y,VEC_CLASSID,5);
697 
698   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
699   ierr = DMTSGetIFunction(dm,&ifunction,&ctx);CHKERRQ(ierr);
700   ierr = DMTSGetRHSFunction(dm,&rhsfunction,NULL);CHKERRQ(ierr);
701 
702   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
703 
704   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
705   if (ifunction) {
706     PetscStackPush("TS user implicit function");
707     ierr = (*ifunction)(ts,t,U,Udot,Y,ctx);CHKERRQ(ierr);
708     PetscStackPop;
709   }
710   if (imex) {
711     if (!ifunction) {
712       ierr = VecCopy(Udot,Y);CHKERRQ(ierr);
713     }
714   } else if (rhsfunction) {
715     if (ifunction) {
716       Vec Frhs;
717       ierr = TSGetRHSVec_Private(ts,&Frhs);CHKERRQ(ierr);
718       ierr = TSComputeRHSFunction(ts,t,U,Frhs);CHKERRQ(ierr);
719       ierr = VecAXPY(Y,-1,Frhs);CHKERRQ(ierr);
720     } else {
721       ierr = TSComputeRHSFunction(ts,t,U,Y);CHKERRQ(ierr);
722       ierr = VecAYPX(Y,-1,Udot);CHKERRQ(ierr);
723     }
724   }
725   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
726   PetscFunctionReturn(0);
727 }
728 
729 #undef __FUNCT__
730 #define __FUNCT__ "TSComputeIJacobian"
731 /*@
732    TSComputeIJacobian - Evaluates the Jacobian of the DAE
733 
734    Collective on TS and Vec
735 
736    Input
737       Input Parameters:
738 +  ts - the TS context
739 .  t - current timestep
740 .  U - state vector
741 .  Udot - time derivative of state vector
742 .  shift - shift to apply, see note below
743 -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
744 
745    Output Parameters:
746 +  A - Jacobian matrix
747 .  B - optional preconditioning matrix
748 -  flag - flag indicating matrix structure
749 
750    Notes:
751    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
752 
753    dF/dU + shift*dF/dUdot
754 
755    Most users should not need to explicitly call this routine, as it
756    is used internally within the nonlinear solvers.
757 
758    Level: developer
759 
760 .keywords: TS, compute, Jacobian, matrix
761 
762 .seealso:  TSSetIJacobian()
763 @*/
764 PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
765 {
766   PetscErrorCode ierr;
767   TSIJacobian    ijacobian;
768   TSRHSJacobian  rhsjacobian;
769   DM             dm;
770   void           *ctx;
771 
772   PetscFunctionBegin;
773   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
774   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
775   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
776   PetscValidPointer(A,6);
777   PetscValidHeaderSpecific(A,MAT_CLASSID,6);
778   PetscValidPointer(B,7);
779   PetscValidHeaderSpecific(B,MAT_CLASSID,7);
780 
781   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
782   ierr = DMTSGetIJacobian(dm,&ijacobian,&ctx);CHKERRQ(ierr);
783   ierr = DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);CHKERRQ(ierr);
784 
785   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
786 
787   ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
788   if (ijacobian) {
789     PetscStackPush("TS user implicit Jacobian");
790     ierr = (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);CHKERRQ(ierr);
791     PetscStackPop;
792     /* make sure user returned a correct Jacobian and preconditioner */
793     PetscValidHeaderSpecific(A,MAT_CLASSID,4);
794     PetscValidHeaderSpecific(B,MAT_CLASSID,5);
795   }
796   if (imex) {
797     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
798       ierr = MatZeroEntries(A);CHKERRQ(ierr);
799       ierr = MatShift(A,shift);CHKERRQ(ierr);
800       if (A != B) {
801         ierr = MatZeroEntries(B);CHKERRQ(ierr);
802         ierr = MatShift(B,shift);CHKERRQ(ierr);
803       }
804     }
805   } else {
806     Mat Arhs = NULL,Brhs = NULL;
807     if (rhsjacobian) {
808       if (ijacobian) {
809         ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
810       } else {
811         ierr = TSGetIJacobian(ts,&Arhs,&Brhs,NULL,NULL);CHKERRQ(ierr);
812       }
813       ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
814     }
815     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
816       ts->rhsjacobian.scale = -1;
817       ts->rhsjacobian.shift = shift;
818       ierr = MatScale(A,-1);CHKERRQ(ierr);
819       ierr = MatShift(A,shift);CHKERRQ(ierr);
820       if (A != B) {
821         ierr = MatScale(B,-1);CHKERRQ(ierr);
822         ierr = MatShift(B,shift);CHKERRQ(ierr);
823       }
824     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
825       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
826       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
827         ierr = MatZeroEntries(A);CHKERRQ(ierr);
828         ierr = MatShift(A,shift);CHKERRQ(ierr);
829         if (A != B) {
830           ierr = MatZeroEntries(B);CHKERRQ(ierr);
831           ierr = MatShift(B,shift);CHKERRQ(ierr);
832         }
833       }
834       ierr = MatAXPY(A,-1,Arhs,axpy);CHKERRQ(ierr);
835       if (A != B) {
836         ierr = MatAXPY(B,-1,Brhs,axpy);CHKERRQ(ierr);
837       }
838     }
839   }
840   ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
841   PetscFunctionReturn(0);
842 }
843 
844 #undef __FUNCT__
845 #define __FUNCT__ "TSSetRHSFunction"
846 /*@C
847     TSSetRHSFunction - Sets the routine for evaluating the function,
848     where U_t = G(t,u).
849 
850     Logically Collective on TS
851 
852     Input Parameters:
853 +   ts - the TS context obtained from TSCreate()
854 .   r - vector to put the computed right hand side (or NULL to have it created)
855 .   f - routine for evaluating the right-hand-side function
856 -   ctx - [optional] user-defined context for private data for the
857           function evaluation routine (may be NULL)
858 
859     Calling sequence of func:
860 $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);
861 
862 +   t - current timestep
863 .   u - input vector
864 .   F - function vector
865 -   ctx - [optional] user-defined function context
866 
867     Level: beginner
868 
869 .keywords: TS, timestep, set, right-hand-side, function
870 
871 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
872 @*/
873 PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
874 {
875   PetscErrorCode ierr;
876   SNES           snes;
877   Vec            ralloc = NULL;
878   DM             dm;
879 
880   PetscFunctionBegin;
881   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
882   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
883 
884   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
885   ierr = DMTSSetRHSFunction(dm,f,ctx);CHKERRQ(ierr);
886   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
887   if (!r && !ts->dm && ts->vec_sol) {
888     ierr = VecDuplicate(ts->vec_sol,&ralloc);CHKERRQ(ierr);
889     r    = ralloc;
890   }
891   ierr = SNESSetFunction(snes,r,SNESTSFormFunction,ts);CHKERRQ(ierr);
892   ierr = VecDestroy(&ralloc);CHKERRQ(ierr);
893   PetscFunctionReturn(0);
894 }
895 
896 #undef __FUNCT__
897 #define __FUNCT__ "TSSetSolutionFunction"
898 /*@C
899     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
900 
901     Logically Collective on TS
902 
903     Input Parameters:
904 +   ts - the TS context obtained from TSCreate()
905 .   f - routine for evaluating the solution
906 -   ctx - [optional] user-defined context for private data for the
907           function evaluation routine (may be NULL)
908 
909     Calling sequence of func:
910 $     func (TS ts,PetscReal t,Vec u,void *ctx);
911 
912 +   t - current timestep
913 .   u - output vector
914 -   ctx - [optional] user-defined function context
915 
916     Notes:
917     This routine is used for testing accuracy of time integration schemes when you already know the solution.
918     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
919     create closed-form solutions with non-physical forcing terms.
920 
921     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
922 
923     Level: beginner
924 
925 .keywords: TS, timestep, set, right-hand-side, function
926 
927 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
928 @*/
929 PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
930 {
931   PetscErrorCode ierr;
932   DM             dm;
933 
934   PetscFunctionBegin;
935   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
936   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
937   ierr = DMTSSetSolutionFunction(dm,f,ctx);CHKERRQ(ierr);
938   PetscFunctionReturn(0);
939 }
940 
941 #undef __FUNCT__
942 #define __FUNCT__ "TSSetForcingFunction"
943 /*@C
944     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
945 
946     Logically Collective on TS
947 
948     Input Parameters:
949 +   ts - the TS context obtained from TSCreate()
950 .   f - routine for evaluating the forcing function
951 -   ctx - [optional] user-defined context for private data for the
952           function evaluation routine (may be NULL)
953 
954     Calling sequence of func:
955 $     func (TS ts,PetscReal t,Vec u,void *ctx);
956 
957 +   t - current timestep
958 .   u - output vector
959 -   ctx - [optional] user-defined function context
960 
961     Notes:
962     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
963     create closed-form solutions with a non-physical forcing term.
964 
965     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
966 
967     Level: beginner
968 
969 .keywords: TS, timestep, set, right-hand-side, function
970 
971 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
972 @*/
973 PetscErrorCode  TSSetForcingFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
974 {
975   PetscErrorCode ierr;
976   DM             dm;
977 
978   PetscFunctionBegin;
979   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
980   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
981   ierr = DMTSSetForcingFunction(dm,f,ctx);CHKERRQ(ierr);
982   PetscFunctionReturn(0);
983 }
984 
985 #undef __FUNCT__
986 #define __FUNCT__ "TSSetRHSJacobian"
987 /*@C
988    TSSetRHSJacobian - Sets the function to compute the Jacobian of F,
989    where U_t = G(U,t), as well as the location to store the matrix.
990 
991    Logically Collective on TS
992 
993    Input Parameters:
994 +  ts  - the TS context obtained from TSCreate()
995 .  Amat - (approximate) Jacobian matrix
996 .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
997 .  f   - the Jacobian evaluation routine
998 -  ctx - [optional] user-defined context for private data for the
999          Jacobian evaluation routine (may be NULL)
1000 
1001    Calling sequence of func:
1002 $     func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1003 
1004 +  t - current timestep
1005 .  u - input vector
1006 .  Amat - (approximate) Jacobian matrix
1007 .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1008 -  ctx - [optional] user-defined context for matrix evaluation routine
1009 
1010 
1011    Level: beginner
1012 
1013 .keywords: TS, timestep, set, right-hand-side, Jacobian
1014 
1015 .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()
1016 
1017 @*/
1018 PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1019 {
1020   PetscErrorCode ierr;
1021   SNES           snes;
1022   DM             dm;
1023   TSIJacobian    ijacobian;
1024 
1025   PetscFunctionBegin;
1026   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1027   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1028   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1029   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1030   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1031 
1032   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1033   ierr = DMTSSetRHSJacobian(dm,f,ctx);CHKERRQ(ierr);
1034   if (f == TSComputeRHSJacobianConstant) {
1035     /* Handle this case automatically for the user; otherwise user should call themselves. */
1036     ierr = TSRHSJacobianSetReuse(ts,PETSC_TRUE);CHKERRQ(ierr);
1037   }
1038   ierr = DMTSGetIJacobian(dm,&ijacobian,NULL);CHKERRQ(ierr);
1039   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1040   if (!ijacobian) {
1041     ierr = SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1042   }
1043   if (Amat) {
1044     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
1045     ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
1046 
1047     ts->Arhs = Amat;
1048   }
1049   if (Pmat) {
1050     ierr = PetscObjectReference((PetscObject)Pmat);CHKERRQ(ierr);
1051     ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
1052 
1053     ts->Brhs = Pmat;
1054   }
1055   PetscFunctionReturn(0);
1056 }
1057 
1058 
1059 #undef __FUNCT__
1060 #define __FUNCT__ "TSSetIFunction"
1061 /*@C
1062    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1063 
1064    Logically Collective on TS
1065 
1066    Input Parameters:
1067 +  ts  - the TS context obtained from TSCreate()
1068 .  r   - vector to hold the residual (or NULL to have it created internally)
1069 .  f   - the function evaluation routine
1070 -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1071 
1072    Calling sequence of f:
1073 $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1074 
1075 +  t   - time at step/stage being solved
1076 .  u   - state vector
1077 .  u_t - time derivative of state vector
1078 .  F   - function vector
1079 -  ctx - [optional] user-defined context for matrix evaluation routine
1080 
1081    Important:
1082    The user MUST call either this routine, TSSetRHSFunction().  This routine must be used when not solving an ODE, for example a DAE.
1083 
1084    Level: beginner
1085 
1086 .keywords: TS, timestep, set, DAE, Jacobian
1087 
1088 .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1089 @*/
1090 PetscErrorCode  TSSetIFunction(TS ts,Vec res,TSIFunction f,void *ctx)
1091 {
1092   PetscErrorCode ierr;
1093   SNES           snes;
1094   Vec            resalloc = NULL;
1095   DM             dm;
1096 
1097   PetscFunctionBegin;
1098   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1099   if (res) PetscValidHeaderSpecific(res,VEC_CLASSID,2);
1100 
1101   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1102   ierr = DMTSSetIFunction(dm,f,ctx);CHKERRQ(ierr);
1103 
1104   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1105   if (!res && !ts->dm && ts->vec_sol) {
1106     ierr = VecDuplicate(ts->vec_sol,&resalloc);CHKERRQ(ierr);
1107     res  = resalloc;
1108   }
1109   ierr = SNESSetFunction(snes,res,SNESTSFormFunction,ts);CHKERRQ(ierr);
1110   ierr = VecDestroy(&resalloc);CHKERRQ(ierr);
1111   PetscFunctionReturn(0);
1112 }
1113 
1114 #undef __FUNCT__
1115 #define __FUNCT__ "TSGetIFunction"
1116 /*@C
1117    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1118 
1119    Not Collective
1120 
1121    Input Parameter:
1122 .  ts - the TS context
1123 
1124    Output Parameter:
1125 +  r - vector to hold residual (or NULL)
1126 .  func - the function to compute residual (or NULL)
1127 -  ctx - the function context (or NULL)
1128 
1129    Level: advanced
1130 
1131 .keywords: TS, nonlinear, get, function
1132 
1133 .seealso: TSSetIFunction(), SNESGetFunction()
1134 @*/
1135 PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1136 {
1137   PetscErrorCode ierr;
1138   SNES           snes;
1139   DM             dm;
1140 
1141   PetscFunctionBegin;
1142   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1143   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1144   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1145   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1146   ierr = DMTSGetIFunction(dm,func,ctx);CHKERRQ(ierr);
1147   PetscFunctionReturn(0);
1148 }
1149 
1150 #undef __FUNCT__
1151 #define __FUNCT__ "TSGetRHSFunction"
1152 /*@C
1153    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1154 
1155    Not Collective
1156 
1157    Input Parameter:
1158 .  ts - the TS context
1159 
1160    Output Parameter:
1161 +  r - vector to hold computed right hand side (or NULL)
1162 .  func - the function to compute right hand side (or NULL)
1163 -  ctx - the function context (or NULL)
1164 
1165    Level: advanced
1166 
1167 .keywords: TS, nonlinear, get, function
1168 
1169 .seealso: TSSetRhsfunction(), SNESGetFunction()
1170 @*/
1171 PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1172 {
1173   PetscErrorCode ierr;
1174   SNES           snes;
1175   DM             dm;
1176 
1177   PetscFunctionBegin;
1178   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1179   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1180   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1181   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1182   ierr = DMTSGetRHSFunction(dm,func,ctx);CHKERRQ(ierr);
1183   PetscFunctionReturn(0);
1184 }
1185 
1186 #undef __FUNCT__
1187 #define __FUNCT__ "TSSetIJacobian"
1188 /*@C
1189    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1190         provided with TSSetIFunction().
1191 
1192    Logically Collective on TS
1193 
1194    Input Parameters:
1195 +  ts  - the TS context obtained from TSCreate()
1196 .  Amat - (approximate) Jacobian matrix
1197 .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1198 .  f   - the Jacobian evaluation routine
1199 -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1200 
1201    Calling sequence of f:
1202 $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1203 
1204 +  t    - time at step/stage being solved
1205 .  U    - state vector
1206 .  U_t  - time derivative of state vector
1207 .  a    - shift
1208 .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1209 .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1210 -  ctx  - [optional] user-defined context for matrix evaluation routine
1211 
1212    Notes:
1213    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1214 
1215    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1216    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1217    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1218    a and vector W depend on the integration method, step size, and past states. For example with
1219    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1220    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1221 
1222    Level: beginner
1223 
1224 .keywords: TS, timestep, DAE, Jacobian
1225 
1226 .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()
1227 
1228 @*/
1229 PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1230 {
1231   PetscErrorCode ierr;
1232   SNES           snes;
1233   DM             dm;
1234 
1235   PetscFunctionBegin;
1236   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1237   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1238   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1239   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1240   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1241 
1242   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1243   ierr = DMTSSetIJacobian(dm,f,ctx);CHKERRQ(ierr);
1244 
1245   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1246   ierr = SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1247   PetscFunctionReturn(0);
1248 }
1249 
1250 #undef __FUNCT__
1251 #define __FUNCT__ "TSRHSJacobianSetReuse"
1252 /*@
1253    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1254    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1255    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1256    not been changed by the TS.
1257 
1258    Logically Collective
1259 
1260    Input Arguments:
1261 +  ts - TS context obtained from TSCreate()
1262 -  reuse - PETSC_TRUE if the RHS Jacobian
1263 
1264    Level: intermediate
1265 
1266 .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1267 @*/
1268 PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1269 {
1270   PetscFunctionBegin;
1271   ts->rhsjacobian.reuse = reuse;
1272   PetscFunctionReturn(0);
1273 }
1274 
1275 #undef __FUNCT__
1276 #define __FUNCT__ "TSLoad"
1277 /*@C
1278   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
1279 
1280   Collective on PetscViewer
1281 
1282   Input Parameters:
1283 + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1284            some related function before a call to TSLoad().
1285 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1286 
1287    Level: intermediate
1288 
1289   Notes:
1290    The type is determined by the data in the file, any type set into the TS before this call is ignored.
1291 
1292   Notes for advanced users:
1293   Most users should not need to know the details of the binary storage
1294   format, since TSLoad() and TSView() completely hide these details.
1295   But for anyone who's interested, the standard binary matrix storage
1296   format is
1297 .vb
1298      has not yet been determined
1299 .ve
1300 
1301 .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1302 @*/
1303 PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1304 {
1305   PetscErrorCode ierr;
1306   PetscBool      isbinary;
1307   PetscInt       classid;
1308   char           type[256];
1309   DMTS           sdm;
1310   DM             dm;
1311 
1312   PetscFunctionBegin;
1313   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1314   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1315   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1316   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1317 
1318   ierr = PetscViewerBinaryRead(viewer,&classid,1,PETSC_INT);CHKERRQ(ierr);
1319   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1320   ierr = PetscViewerBinaryRead(viewer,type,256,PETSC_CHAR);CHKERRQ(ierr);
1321   ierr = TSSetType(ts, type);CHKERRQ(ierr);
1322   if (ts->ops->load) {
1323     ierr = (*ts->ops->load)(ts,viewer);CHKERRQ(ierr);
1324   }
1325   ierr = DMCreate(PetscObjectComm((PetscObject)ts),&dm);CHKERRQ(ierr);
1326   ierr = DMLoad(dm,viewer);CHKERRQ(ierr);
1327   ierr = TSSetDM(ts,dm);CHKERRQ(ierr);
1328   ierr = DMCreateGlobalVector(ts->dm,&ts->vec_sol);CHKERRQ(ierr);
1329   ierr = VecLoad(ts->vec_sol,viewer);CHKERRQ(ierr);
1330   ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1331   ierr = DMTSLoad(sdm,viewer);CHKERRQ(ierr);
1332   PetscFunctionReturn(0);
1333 }
1334 
1335 #include <petscdraw.h>
1336 #if defined(PETSC_HAVE_SAWS)
1337 #include <petscviewersaws.h>
1338 #endif
1339 #undef __FUNCT__
1340 #define __FUNCT__ "TSView"
1341 /*@C
1342     TSView - Prints the TS data structure.
1343 
1344     Collective on TS
1345 
1346     Input Parameters:
1347 +   ts - the TS context obtained from TSCreate()
1348 -   viewer - visualization context
1349 
1350     Options Database Key:
1351 .   -ts_view - calls TSView() at end of TSStep()
1352 
1353     Notes:
1354     The available visualization contexts include
1355 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1356 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1357          output where only the first processor opens
1358          the file.  All other processors send their
1359          data to the first processor to print.
1360 
1361     The user can open an alternative visualization context with
1362     PetscViewerASCIIOpen() - output to a specified file.
1363 
1364     Level: beginner
1365 
1366 .keywords: TS, timestep, view
1367 
1368 .seealso: PetscViewerASCIIOpen()
1369 @*/
1370 PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1371 {
1372   PetscErrorCode ierr;
1373   TSType         type;
1374   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1375   DMTS           sdm;
1376 #if defined(PETSC_HAVE_SAWS)
1377   PetscBool      isams;
1378 #endif
1379 
1380   PetscFunctionBegin;
1381   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1382   if (!viewer) {
1383     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);CHKERRQ(ierr);
1384   }
1385   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1386   PetscCheckSameComm(ts,1,viewer,2);
1387 
1388   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1389   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
1390   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1391   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1392 #if defined(PETSC_HAVE_SAWS)
1393   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&isams);CHKERRQ(ierr);
1394 #endif
1395   if (iascii) {
1396     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);CHKERRQ(ierr);
1397     ierr = PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);CHKERRQ(ierr);
1398     ierr = PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);CHKERRQ(ierr);
1399     if (ts->problem_type == TS_NONLINEAR) {
1400       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);CHKERRQ(ierr);
1401       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);CHKERRQ(ierr);
1402     }
1403     ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);CHKERRQ(ierr);
1404     ierr = PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);CHKERRQ(ierr);
1405     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1406     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1407     if (ts->ops->view) {
1408       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1409       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1410       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1411     }
1412   } else if (isstring) {
1413     ierr = TSGetType(ts,&type);CHKERRQ(ierr);
1414     ierr = PetscViewerStringSPrintf(viewer," %-7.7s",type);CHKERRQ(ierr);
1415   } else if (isbinary) {
1416     PetscInt    classid = TS_FILE_CLASSID;
1417     MPI_Comm    comm;
1418     PetscMPIInt rank;
1419     char        type[256];
1420 
1421     ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
1422     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
1423     if (!rank) {
1424       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
1425       ierr = PetscStrncpy(type,((PetscObject)ts)->type_name,256);CHKERRQ(ierr);
1426       ierr = PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
1427     }
1428     if (ts->ops->view) {
1429       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1430     }
1431     ierr = DMView(ts->dm,viewer);CHKERRQ(ierr);
1432     ierr = VecView(ts->vec_sol,viewer);CHKERRQ(ierr);
1433     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1434     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1435   } else if (isdraw) {
1436     PetscDraw draw;
1437     char      str[36];
1438     PetscReal x,y,bottom,h;
1439 
1440     ierr   = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
1441     ierr   = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
1442     ierr   = PetscStrcpy(str,"TS: ");CHKERRQ(ierr);
1443     ierr   = PetscStrcat(str,((PetscObject)ts)->type_name);CHKERRQ(ierr);
1444     ierr   = PetscDrawBoxedString(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
1445     bottom = y - h;
1446     ierr   = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
1447     if (ts->ops->view) {
1448       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1449     }
1450     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
1451 #if defined(PETSC_HAVE_SAWS)
1452   } else if (isams) {
1453     PetscMPIInt rank;
1454     const char  *name;
1455 
1456     ierr = PetscObjectGetName((PetscObject)ts,&name);CHKERRQ(ierr);
1457     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1458     if (!((PetscObject)ts)->amsmem && !rank) {
1459       char       dir[1024];
1460 
1461       ierr = PetscObjectViewSAWs((PetscObject)ts,viewer);CHKERRQ(ierr);
1462       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);CHKERRQ(ierr);
1463       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1464       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);CHKERRQ(ierr);
1465       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1466     }
1467     if (ts->ops->view) {
1468       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1469     }
1470 #endif
1471   }
1472 
1473   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1474   ierr = PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);CHKERRQ(ierr);
1475   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1476   PetscFunctionReturn(0);
1477 }
1478 
1479 
1480 #undef __FUNCT__
1481 #define __FUNCT__ "TSSetApplicationContext"
1482 /*@
1483    TSSetApplicationContext - Sets an optional user-defined context for
1484    the timesteppers.
1485 
1486    Logically Collective on TS
1487 
1488    Input Parameters:
1489 +  ts - the TS context obtained from TSCreate()
1490 -  usrP - optional user context
1491 
1492    Level: intermediate
1493 
1494 .keywords: TS, timestep, set, application, context
1495 
1496 .seealso: TSGetApplicationContext()
1497 @*/
1498 PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
1499 {
1500   PetscFunctionBegin;
1501   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1502   ts->user = usrP;
1503   PetscFunctionReturn(0);
1504 }
1505 
1506 #undef __FUNCT__
1507 #define __FUNCT__ "TSGetApplicationContext"
1508 /*@
1509     TSGetApplicationContext - Gets the user-defined context for the
1510     timestepper.
1511 
1512     Not Collective
1513 
1514     Input Parameter:
1515 .   ts - the TS context obtained from TSCreate()
1516 
1517     Output Parameter:
1518 .   usrP - user context
1519 
1520     Level: intermediate
1521 
1522 .keywords: TS, timestep, get, application, context
1523 
1524 .seealso: TSSetApplicationContext()
1525 @*/
1526 PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
1527 {
1528   PetscFunctionBegin;
1529   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1530   *(void**)usrP = ts->user;
1531   PetscFunctionReturn(0);
1532 }
1533 
1534 #undef __FUNCT__
1535 #define __FUNCT__ "TSGetTimeStepNumber"
1536 /*@
1537    TSGetTimeStepNumber - Gets the number of time steps completed.
1538 
1539    Not Collective
1540 
1541    Input Parameter:
1542 .  ts - the TS context obtained from TSCreate()
1543 
1544    Output Parameter:
1545 .  iter - number of steps completed so far
1546 
1547    Level: intermediate
1548 
1549 .keywords: TS, timestep, get, iteration, number
1550 .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
1551 @*/
1552 PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
1553 {
1554   PetscFunctionBegin;
1555   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1556   PetscValidIntPointer(iter,2);
1557   *iter = ts->steps;
1558   PetscFunctionReturn(0);
1559 }
1560 
1561 #undef __FUNCT__
1562 #define __FUNCT__ "TSSetInitialTimeStep"
1563 /*@
1564    TSSetInitialTimeStep - Sets the initial timestep to be used,
1565    as well as the initial time.
1566 
1567    Logically Collective on TS
1568 
1569    Input Parameters:
1570 +  ts - the TS context obtained from TSCreate()
1571 .  initial_time - the initial time
1572 -  time_step - the size of the timestep
1573 
1574    Level: intermediate
1575 
1576 .seealso: TSSetTimeStep(), TSGetTimeStep()
1577 
1578 .keywords: TS, set, initial, timestep
1579 @*/
1580 PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
1581 {
1582   PetscErrorCode ierr;
1583 
1584   PetscFunctionBegin;
1585   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1586   ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
1587   ierr = TSSetTime(ts,initial_time);CHKERRQ(ierr);
1588   PetscFunctionReturn(0);
1589 }
1590 
1591 #undef __FUNCT__
1592 #define __FUNCT__ "TSSetTimeStep"
1593 /*@
1594    TSSetTimeStep - Allows one to reset the timestep at any time,
1595    useful for simple pseudo-timestepping codes.
1596 
1597    Logically Collective on TS
1598 
1599    Input Parameters:
1600 +  ts - the TS context obtained from TSCreate()
1601 -  time_step - the size of the timestep
1602 
1603    Level: intermediate
1604 
1605 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
1606 
1607 .keywords: TS, set, timestep
1608 @*/
1609 PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
1610 {
1611   PetscFunctionBegin;
1612   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1613   PetscValidLogicalCollectiveReal(ts,time_step,2);
1614   ts->time_step      = time_step;
1615   ts->time_step_orig = time_step;
1616   PetscFunctionReturn(0);
1617 }
1618 
1619 #undef __FUNCT__
1620 #define __FUNCT__ "TSSetExactFinalTime"
1621 /*@
1622    TSSetExactFinalTime - Determines whether to adapt the final time step to
1623      match the exact final time, interpolate solution to the exact final time,
1624      or just return at the final time TS computed.
1625 
1626   Logically Collective on TS
1627 
1628    Input Parameter:
1629 +   ts - the time-step context
1630 -   eftopt - exact final time option
1631 
1632    Level: beginner
1633 
1634 .seealso: TSExactFinalTimeOption
1635 @*/
1636 PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
1637 {
1638   PetscFunctionBegin;
1639   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1640   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
1641   ts->exact_final_time = eftopt;
1642   PetscFunctionReturn(0);
1643 }
1644 
1645 #undef __FUNCT__
1646 #define __FUNCT__ "TSGetTimeStep"
1647 /*@
1648    TSGetTimeStep - Gets the current timestep size.
1649 
1650    Not Collective
1651 
1652    Input Parameter:
1653 .  ts - the TS context obtained from TSCreate()
1654 
1655    Output Parameter:
1656 .  dt - the current timestep size
1657 
1658    Level: intermediate
1659 
1660 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
1661 
1662 .keywords: TS, get, timestep
1663 @*/
1664 PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
1665 {
1666   PetscFunctionBegin;
1667   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1668   PetscValidRealPointer(dt,2);
1669   *dt = ts->time_step;
1670   PetscFunctionReturn(0);
1671 }
1672 
1673 #undef __FUNCT__
1674 #define __FUNCT__ "TSGetSolution"
1675 /*@
1676    TSGetSolution - Returns the solution at the present timestep. It
1677    is valid to call this routine inside the function that you are evaluating
1678    in order to move to the new timestep. This vector not changed until
1679    the solution at the next timestep has been calculated.
1680 
1681    Not Collective, but Vec returned is parallel if TS is parallel
1682 
1683    Input Parameter:
1684 .  ts - the TS context obtained from TSCreate()
1685 
1686    Output Parameter:
1687 .  v - the vector containing the solution
1688 
1689    Level: intermediate
1690 
1691 .seealso: TSGetTimeStep()
1692 
1693 .keywords: TS, timestep, get, solution
1694 @*/
1695 PetscErrorCode  TSGetSolution(TS ts,Vec *v)
1696 {
1697   PetscFunctionBegin;
1698   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1699   PetscValidPointer(v,2);
1700   *v = ts->vec_sol;
1701   PetscFunctionReturn(0);
1702 }
1703 
1704 #undef __FUNCT__
1705 #define __FUNCT__ "TSAdjointGetSensitivity"
1706 /*@
1707    TSAdjointGetSensitivity - Returns the sensitivity in the reverse mode.
1708 
1709    Not Collective, but Vec returned is parallel if TS is parallel
1710 
1711    Input Parameter:
1712 .  ts - the TS context obtained from TSCreate()
1713 
1714    Output Parameter:
1715 .  v - the vector containing the solution
1716 
1717    Level: intermediate
1718 
1719 .seealso: TSGetTimeStep()
1720 
1721 .keywords: TS, timestep, get, sensitivity
1722 @*/
1723 PetscErrorCode  TSAdjointGetSensitivity(TS ts,Vec **v,PetscInt *numberadjs)
1724 {
1725   PetscFunctionBegin;
1726   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1727   PetscValidPointer(v,2);
1728   *v          = ts->vecs_sensi;
1729   if(numberadjs) *numberadjs = ts->numberadjs;
1730   PetscFunctionReturn(0);
1731 }
1732 
1733 /* ----- Routines to initialize and destroy a timestepper ---- */
1734 #undef __FUNCT__
1735 #define __FUNCT__ "TSSetProblemType"
1736 /*@
1737   TSSetProblemType - Sets the type of problem to be solved.
1738 
1739   Not collective
1740 
1741   Input Parameters:
1742 + ts   - The TS
1743 - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1744 .vb
1745          U_t - A U = 0      (linear)
1746          U_t - A(t) U = 0   (linear)
1747          F(t,U,U_t) = 0     (nonlinear)
1748 .ve
1749 
1750    Level: beginner
1751 
1752 .keywords: TS, problem type
1753 .seealso: TSSetUp(), TSProblemType, TS
1754 @*/
1755 PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
1756 {
1757   PetscErrorCode ierr;
1758 
1759   PetscFunctionBegin;
1760   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
1761   ts->problem_type = type;
1762   if (type == TS_LINEAR) {
1763     SNES snes;
1764     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1765     ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);
1766   }
1767   PetscFunctionReturn(0);
1768 }
1769 
1770 #undef __FUNCT__
1771 #define __FUNCT__ "TSGetProblemType"
1772 /*@C
1773   TSGetProblemType - Gets the type of problem to be solved.
1774 
1775   Not collective
1776 
1777   Input Parameter:
1778 . ts   - The TS
1779 
1780   Output Parameter:
1781 . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1782 .vb
1783          M U_t = A U
1784          M(t) U_t = A(t) U
1785          F(t,U,U_t)
1786 .ve
1787 
1788    Level: beginner
1789 
1790 .keywords: TS, problem type
1791 .seealso: TSSetUp(), TSProblemType, TS
1792 @*/
1793 PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
1794 {
1795   PetscFunctionBegin;
1796   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
1797   PetscValidIntPointer(type,2);
1798   *type = ts->problem_type;
1799   PetscFunctionReturn(0);
1800 }
1801 
1802 #undef __FUNCT__
1803 #define __FUNCT__ "TSSetUp"
1804 /*@
1805    TSSetUp - Sets up the internal data structures for the later use
1806    of a timestepper.
1807 
1808    Collective on TS
1809 
1810    Input Parameter:
1811 .  ts - the TS context obtained from TSCreate()
1812 
1813    Notes:
1814    For basic use of the TS solvers the user need not explicitly call
1815    TSSetUp(), since these actions will automatically occur during
1816    the call to TSStep().  However, if one wishes to control this
1817    phase separately, TSSetUp() should be called after TSCreate()
1818    and optional routines of the form TSSetXXX(), but before TSStep().
1819 
1820    Level: advanced
1821 
1822 .keywords: TS, timestep, setup
1823 
1824 .seealso: TSCreate(), TSStep(), TSDestroy()
1825 @*/
1826 PetscErrorCode  TSSetUp(TS ts)
1827 {
1828   PetscErrorCode ierr;
1829   DM             dm;
1830   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
1831   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
1832   TSIJacobian    ijac;
1833   TSRHSJacobian  rhsjac;
1834 
1835   PetscFunctionBegin;
1836   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1837   if (ts->setupcalled) PetscFunctionReturn(0);
1838 
1839   ts->total_steps = 0;
1840   if (!((PetscObject)ts)->type_name) {
1841     ierr = TSSetType(ts,TSEULER);CHKERRQ(ierr);
1842   }
1843 
1844   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
1845 
1846 
1847   ierr = TSGetAdapt(ts,&ts->adapt);CHKERRQ(ierr);
1848 
1849   if (ts->rhsjacobian.reuse) {
1850     Mat Amat,Pmat;
1851     SNES snes;
1852     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1853     ierr = SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);CHKERRQ(ierr);
1854     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
1855      * have displaced the RHS matrix */
1856     if (Amat == ts->Arhs) {
1857       ierr = MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);CHKERRQ(ierr);
1858       ierr = SNESSetJacobian(snes,Amat,NULL,NULL,NULL);CHKERRQ(ierr);
1859       ierr = MatDestroy(&Amat);CHKERRQ(ierr);
1860     }
1861     if (Pmat == ts->Brhs) {
1862       ierr = MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);CHKERRQ(ierr);
1863       ierr = SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);CHKERRQ(ierr);
1864       ierr = MatDestroy(&Pmat);CHKERRQ(ierr);
1865     }
1866   }
1867   if (ts->ops->setup) {
1868     ierr = (*ts->ops->setup)(ts);CHKERRQ(ierr);
1869   }
1870 
1871   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
1872    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
1873    */
1874   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1875   ierr = DMSNESGetFunction(dm,&func,NULL);CHKERRQ(ierr);
1876   if (!func) {
1877     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);CHKERRQ(ierr);
1878   }
1879   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
1880      Otherwise, the SNES will use coloring internally to form the Jacobian.
1881    */
1882   ierr = DMSNESGetJacobian(dm,&jac,NULL);CHKERRQ(ierr);
1883   ierr = DMTSGetIJacobian(dm,&ijac,NULL);CHKERRQ(ierr);
1884   ierr = DMTSGetRHSJacobian(dm,&rhsjac,NULL);CHKERRQ(ierr);
1885   if (!jac && (ijac || rhsjac)) {
1886     ierr = DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1887   }
1888   ts->setupcalled = PETSC_TRUE;
1889   PetscFunctionReturn(0);
1890 }
1891 
1892 #undef __FUNCT__
1893 #define __FUNCT__ "TSAdjointSetUp"
1894 /*@
1895    TSAdjointSetUp - Sets up the internal data structures for the later use
1896    of an adjoint solver
1897 
1898    Collective on TS
1899 
1900    Input Parameter:
1901 .  ts - the TS context obtained from TSCreate()
1902 
1903    Notes:
1904    For basic use of the TS solvers the user need not explicitly call
1905    TSSetUp(), since these actions will automatically occur during
1906    the call to TSStep().  However, if one wishes to control this
1907    phase separately, TSSetUp() should be called after TSCreate()
1908    and optional routines of the form TSSetXXX(), but before TSStep().
1909 
1910    Level: advanced
1911 
1912 .keywords: TS, timestep, setup
1913 
1914 .seealso: TSCreate(), TSStep(), TSDestroy()
1915 @*/
1916 PetscErrorCode  TSAdjointSetUp(TS ts)
1917 {
1918   PetscErrorCode ierr;
1919 
1920   PetscFunctionBegin;
1921   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1922   if (ts->adjointsetupcalled) PetscFunctionReturn(0);
1923   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSAdjointSetSensitivity() first");
1924   if (ts->ops->setupadj) {
1925     ierr = (*ts->ops->setupadj)(ts);CHKERRQ(ierr);
1926   }
1927   ts->adjointsetupcalled = PETSC_TRUE;
1928   PetscFunctionReturn(0);
1929 }
1930 
1931 #undef __FUNCT__
1932 #define __FUNCT__ "TSReset"
1933 /*@
1934    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
1935 
1936    Collective on TS
1937 
1938    Input Parameter:
1939 .  ts - the TS context obtained from TSCreate()
1940 
1941    Level: beginner
1942 
1943 .keywords: TS, timestep, reset
1944 
1945 .seealso: TSCreate(), TSSetup(), TSDestroy()
1946 @*/
1947 PetscErrorCode  TSReset(TS ts)
1948 {
1949   PetscErrorCode ierr;
1950 
1951   PetscFunctionBegin;
1952   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1953 
1954   if (ts->ops->reset) {
1955     ierr = (*ts->ops->reset)(ts);CHKERRQ(ierr);
1956   }
1957   if (ts->snes) {ierr = SNESReset(ts->snes);CHKERRQ(ierr);}
1958 
1959   ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
1960   ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
1961   ierr = VecDestroy(&ts->Frhs);CHKERRQ(ierr);
1962   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
1963   ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
1964   ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
1965   ierr = VecDestroyVecs(ts->nwork,&ts->work);CHKERRQ(ierr);
1966   ts->vecs_sensi = 0;
1967   ts->vecs_sensip = 0;
1968   ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
1969   ierr = VecDestroy(&ts->vec_costquad);CHKERRQ(ierr);
1970   ierr = VecDestroy(&ts->vec_costintegrand);CHKERRQ(ierr);
1971   ts->setupcalled = PETSC_FALSE;
1972   PetscFunctionReturn(0);
1973 }
1974 
1975 #undef __FUNCT__
1976 #define __FUNCT__ "TSDestroy"
1977 /*@
1978    TSDestroy - Destroys the timestepper context that was created
1979    with TSCreate().
1980 
1981    Collective on TS
1982 
1983    Input Parameter:
1984 .  ts - the TS context obtained from TSCreate()
1985 
1986    Level: beginner
1987 
1988 .keywords: TS, timestepper, destroy
1989 
1990 .seealso: TSCreate(), TSSetUp(), TSSolve()
1991 @*/
1992 PetscErrorCode  TSDestroy(TS *ts)
1993 {
1994   PetscErrorCode ierr;
1995 
1996   PetscFunctionBegin;
1997   if (!*ts) PetscFunctionReturn(0);
1998   PetscValidHeaderSpecific((*ts),TS_CLASSID,1);
1999   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; PetscFunctionReturn(0);}
2000 
2001   ierr = TSReset((*ts));CHKERRQ(ierr);
2002 
2003   /* if memory was published with SAWs then destroy it */
2004   ierr = PetscObjectSAWsViewOff((PetscObject)*ts);CHKERRQ(ierr);
2005   if ((*ts)->ops->destroy) {ierr = (*(*ts)->ops->destroy)((*ts));CHKERRQ(ierr);}
2006 
2007   ierr = TSAdaptDestroy(&(*ts)->adapt);CHKERRQ(ierr);
2008   if ((*ts)->event) {
2009     ierr = TSEventMonitorDestroy(&(*ts)->event);CHKERRQ(ierr);
2010   }
2011   ierr = SNESDestroy(&(*ts)->snes);CHKERRQ(ierr);
2012   ierr = DMDestroy(&(*ts)->dm);CHKERRQ(ierr);
2013   ierr = TSMonitorCancel((*ts));CHKERRQ(ierr);
2014 
2015   ierr = PetscHeaderDestroy(ts);CHKERRQ(ierr);
2016   PetscFunctionReturn(0);
2017 }
2018 
2019 #undef __FUNCT__
2020 #define __FUNCT__ "TSGetSNES"
2021 /*@
2022    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2023    a TS (timestepper) context. Valid only for nonlinear problems.
2024 
2025    Not Collective, but SNES is parallel if TS is parallel
2026 
2027    Input Parameter:
2028 .  ts - the TS context obtained from TSCreate()
2029 
2030    Output Parameter:
2031 .  snes - the nonlinear solver context
2032 
2033    Notes:
2034    The user can then directly manipulate the SNES context to set various
2035    options, etc.  Likewise, the user can then extract and manipulate the
2036    KSP, KSP, and PC contexts as well.
2037 
2038    TSGetSNES() does not work for integrators that do not use SNES; in
2039    this case TSGetSNES() returns NULL in snes.
2040 
2041    Level: beginner
2042 
2043 .keywords: timestep, get, SNES
2044 @*/
2045 PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2046 {
2047   PetscErrorCode ierr;
2048 
2049   PetscFunctionBegin;
2050   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2051   PetscValidPointer(snes,2);
2052   if (!ts->snes) {
2053     ierr = SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);CHKERRQ(ierr);
2054     ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2055     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);CHKERRQ(ierr);
2056     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);CHKERRQ(ierr);
2057     if (ts->dm) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
2058     if (ts->problem_type == TS_LINEAR) {
2059       ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);
2060     }
2061   }
2062   *snes = ts->snes;
2063   PetscFunctionReturn(0);
2064 }
2065 
2066 #undef __FUNCT__
2067 #define __FUNCT__ "TSSetSNES"
2068 /*@
2069    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2070 
2071    Collective
2072 
2073    Input Parameter:
2074 +  ts - the TS context obtained from TSCreate()
2075 -  snes - the nonlinear solver context
2076 
2077    Notes:
2078    Most users should have the TS created by calling TSGetSNES()
2079 
2080    Level: developer
2081 
2082 .keywords: timestep, set, SNES
2083 @*/
2084 PetscErrorCode TSSetSNES(TS ts,SNES snes)
2085 {
2086   PetscErrorCode ierr;
2087   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2088 
2089   PetscFunctionBegin;
2090   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2091   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
2092   ierr = PetscObjectReference((PetscObject)snes);CHKERRQ(ierr);
2093   ierr = SNESDestroy(&ts->snes);CHKERRQ(ierr);
2094 
2095   ts->snes = snes;
2096 
2097   ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2098   ierr = SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);CHKERRQ(ierr);
2099   if (func == SNESTSFormJacobian) {
2100     ierr = SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2101   }
2102   PetscFunctionReturn(0);
2103 }
2104 
2105 #undef __FUNCT__
2106 #define __FUNCT__ "TSGetKSP"
2107 /*@
2108    TSGetKSP - Returns the KSP (linear solver) associated with
2109    a TS (timestepper) context.
2110 
2111    Not Collective, but KSP is parallel if TS is parallel
2112 
2113    Input Parameter:
2114 .  ts - the TS context obtained from TSCreate()
2115 
2116    Output Parameter:
2117 .  ksp - the nonlinear solver context
2118 
2119    Notes:
2120    The user can then directly manipulate the KSP context to set various
2121    options, etc.  Likewise, the user can then extract and manipulate the
2122    KSP and PC contexts as well.
2123 
2124    TSGetKSP() does not work for integrators that do not use KSP;
2125    in this case TSGetKSP() returns NULL in ksp.
2126 
2127    Level: beginner
2128 
2129 .keywords: timestep, get, KSP
2130 @*/
2131 PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2132 {
2133   PetscErrorCode ierr;
2134   SNES           snes;
2135 
2136   PetscFunctionBegin;
2137   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2138   PetscValidPointer(ksp,2);
2139   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2140   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2141   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2142   ierr = SNESGetKSP(snes,ksp);CHKERRQ(ierr);
2143   PetscFunctionReturn(0);
2144 }
2145 
2146 /* ----------- Routines to set solver parameters ---------- */
2147 
2148 #undef __FUNCT__
2149 #define __FUNCT__ "TSGetDuration"
2150 /*@
2151    TSGetDuration - Gets the maximum number of timesteps to use and
2152    maximum time for iteration.
2153 
2154    Not Collective
2155 
2156    Input Parameters:
2157 +  ts       - the TS context obtained from TSCreate()
2158 .  maxsteps - maximum number of iterations to use, or NULL
2159 -  maxtime  - final time to iterate to, or NULL
2160 
2161    Level: intermediate
2162 
2163 .keywords: TS, timestep, get, maximum, iterations, time
2164 @*/
2165 PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2166 {
2167   PetscFunctionBegin;
2168   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2169   if (maxsteps) {
2170     PetscValidIntPointer(maxsteps,2);
2171     *maxsteps = ts->max_steps;
2172   }
2173   if (maxtime) {
2174     PetscValidScalarPointer(maxtime,3);
2175     *maxtime = ts->max_time;
2176   }
2177   PetscFunctionReturn(0);
2178 }
2179 
2180 #undef __FUNCT__
2181 #define __FUNCT__ "TSSetDuration"
2182 /*@
2183    TSSetDuration - Sets the maximum number of timesteps to use and
2184    maximum time for iteration.
2185 
2186    Logically Collective on TS
2187 
2188    Input Parameters:
2189 +  ts - the TS context obtained from TSCreate()
2190 .  maxsteps - maximum number of iterations to use
2191 -  maxtime - final time to iterate to
2192 
2193    Options Database Keys:
2194 .  -ts_max_steps <maxsteps> - Sets maxsteps
2195 .  -ts_final_time <maxtime> - Sets maxtime
2196 
2197    Notes:
2198    The default maximum number of iterations is 5000. Default time is 5.0
2199 
2200    Level: intermediate
2201 
2202 .keywords: TS, timestep, set, maximum, iterations
2203 
2204 .seealso: TSSetExactFinalTime()
2205 @*/
2206 PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2207 {
2208   PetscFunctionBegin;
2209   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2210   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
2211   PetscValidLogicalCollectiveReal(ts,maxtime,2);
2212   if (maxsteps >= 0) ts->max_steps = maxsteps;
2213   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2214   PetscFunctionReturn(0);
2215 }
2216 
2217 #undef __FUNCT__
2218 #define __FUNCT__ "TSSetSolution"
2219 /*@
2220    TSSetSolution - Sets the initial solution vector
2221    for use by the TS routines.
2222 
2223    Logically Collective on TS and Vec
2224 
2225    Input Parameters:
2226 +  ts - the TS context obtained from TSCreate()
2227 -  u - the solution vector
2228 
2229    Level: beginner
2230 
2231 .keywords: TS, timestep, set, solution, initial conditions
2232 @*/
2233 PetscErrorCode  TSSetSolution(TS ts,Vec u)
2234 {
2235   PetscErrorCode ierr;
2236   DM             dm;
2237 
2238   PetscFunctionBegin;
2239   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2240   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2241   ierr = PetscObjectReference((PetscObject)u);CHKERRQ(ierr);
2242   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2243 
2244   ts->vec_sol = u;
2245 
2246   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2247   ierr = DMShellSetGlobalVector(dm,u);CHKERRQ(ierr);
2248   PetscFunctionReturn(0);
2249 }
2250 
2251 #undef __FUNCT__
2252 #define __FUNCT__ "TSAdjointSetSensitivity"
2253 /*@
2254    TSAdjointSetSensitivity - Sets the initial value of sensitivity (w.r.t. initial conditions)
2255    for use by the TS routines.
2256 
2257    Logically Collective on TS and Vec
2258 
2259    Input Parameters:
2260 +  ts - the TS context obtained from TSCreate()
2261 -  u - the solution vector
2262 
2263    Level: beginner
2264 
2265 .keywords: TS, timestep, set, sensitivity, initial conditions
2266 @*/
2267 PetscErrorCode  TSAdjointSetSensitivity(TS ts,Vec *u,PetscInt numberadjs)
2268 {
2269   PetscFunctionBegin;
2270   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2271   PetscValidPointer(u,2);
2272   ts->vecs_sensi = u;
2273   if(ts->numberadjs && ts->numberadjs!=numberadjs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of adjoint variables (3rd parameter) is inconsistent with the one set by TSAdjointSetSensitivityP()");
2274   ts->numberadjs = numberadjs;
2275 
2276   PetscFunctionReturn(0);
2277 }
2278 
2279 #undef __FUNCT__
2280 #define __FUNCT__ "TSAdjointSetSensitivityP"
2281 /*@
2282    TSAdjointSetSensitivityP - Sets the initial value of sensitivity (w.r.t. parameters)
2283    for use by the TS routines.
2284 
2285    Logically Collective on TS and Vec
2286 
2287    Input Parameters:
2288 +  ts - the TS context obtained from TSCreate()
2289 -  u - the solution vector
2290 
2291    Level: beginner
2292 
2293 .keywords: TS, timestep, set, sensitivity, initial conditions
2294 @*/
2295 PetscErrorCode  TSAdjointSetSensitivityP(TS ts,Vec *u,PetscInt numberadjs)
2296 {
2297   PetscFunctionBegin;
2298   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2299   PetscValidPointer(u,2);
2300   ts->vecs_sensip = u;
2301   if(ts->numberadjs && ts->numberadjs!=numberadjs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of adjoint variables (3rd parameter) is inconsistent with the one set by TSAdjointSetSensitivity()");
2302   ts->numberadjs = numberadjs;
2303 
2304   PetscFunctionReturn(0);
2305 }
2306 
2307 #undef __FUNCT__
2308 #define __FUNCT__ "TSAdjointSetRHSJacobianP"
2309 /*@C
2310   TSAdjointSetRHSJacobianP - Sets the function that computes the Jacobian w.r.t. parameters.
2311 
2312   Logically Collective on TS
2313 
2314   Input Parameters:
2315 + ts   - The TS context obtained from TSCreate()
2316 - func - The function
2317 
2318   Calling sequence of func:
2319 $ func (TS ts,PetscReal t,Vec u,Mat A,void *ctx);
2320 +   t - current timestep
2321 .   u - input vector
2322 .   A - output matrix
2323 -   ctx - [optional] user-defined function context
2324 
2325   Level: intermediate
2326 
2327 .keywords: TS, sensitivity
2328 .seealso:
2329 @*/
2330 PetscErrorCode  TSAdjointSetRHSJacobianP(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2331 {
2332   PetscErrorCode ierr;
2333 
2334   PetscFunctionBegin;
2335   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2336   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
2337 
2338   ts->rhsjacobianp    = func;
2339   ts->rhsjacobianpctx = ctx;
2340   if(Amat) {
2341     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
2342     ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
2343 
2344     ts->Jacp = Amat;
2345   }
2346   PetscFunctionReturn(0);
2347 }
2348 
2349 #undef __FUNCT__
2350 #define __FUNCT__ "TSAdjointComputeRHSJacobianP"
2351 /*@
2352   TSAdjointComputeRHSJacobianP - Runs the user-defined JacobianP function.
2353 
2354   Collective on TS
2355 
2356   Input Parameters:
2357 . ts   - The TS context obtained from TSCreate()
2358 
2359   Level: developer
2360 
2361 .keywords: TS, sensitivity
2362 .seealso: TSAdjointSetRHSJacobianP()
2363 @*/
2364 PetscErrorCode  TSAdjointComputeRHSJacobianP(TS ts,PetscReal t,Vec X,Mat Amat)
2365 {
2366   PetscErrorCode ierr;
2367 
2368   PetscFunctionBegin;
2369   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2370   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2371   PetscValidPointer(Amat,4);
2372 
2373   PetscStackPush("TS user JacobianP function for sensitivity analysis");
2374   ierr = (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx); CHKERRQ(ierr);
2375   PetscStackPop;
2376 
2377   PetscFunctionReturn(0);
2378 }
2379 
2380 #undef __FUNCT__
2381 #define __FUNCT__ "TSAdjointSetCostIntegrand"
2382 /*@C
2383     TSAdjointSetCostIntegrand - Sets the routine for evaluating the quadrature (or integral) term in a cost function,
2384     where Q_t = r(t,u).
2385 
2386     Logically Collective on TS
2387 
2388     Input Parameters:
2389 +   ts - the TS context obtained from TSCreate()
2390 .   q -  vector to put the computed quadrature term in the cost function (or NULL to have it created)
2391 .   fq - routine for evaluating the right-hand-side function
2392 -   ctx - [optional] user-defined context for private data for the
2393           function evaluation routine (may be NULL)
2394 
2395     Calling sequence of func:
2396 $     TSCostIntegrand(TS ts,PetscReal t,Vec u,PetscReal *f,void *ctx);
2397 
2398 +   t - current timestep
2399 .   u - input vector
2400 .   f - function vector
2401 -   ctx - [optional] user-defined function context
2402 
2403     Level: beginner
2404 
2405 .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
2406 
2407 .seealso: TSAdjointSetRHSJacobianP(),TSAdjointSetSensitivity(),TSAdjointSetSensitivityP()
2408 @*/
2409 PetscErrorCode  TSAdjointSetCostIntegrand(TS ts,PetscInt numberadjs,Vec q,PetscErrorCode (*fq)(TS,PetscReal,Vec,Vec,void*),void *ctx)
2410 {
2411   PetscErrorCode ierr;
2412   PetscInt size;
2413 
2414   PetscFunctionBegin;
2415   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2416   if (q) {
2417     PetscValidHeaderSpecific(q,VEC_CLASSID,2);
2418   } else {
2419     SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"TSAdjointSetCostIntegrand() requires a vector of size numberajds to hold the value of integrals as 3rd input parameter");
2420   }
2421   if (!ts->numberadjs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Call TSAdjointSetSensitivity() or TSAdjointSetSensitivityP() first so that the number of cost functions can be determined.");
2422   if (ts->numberadjs && ts->numberadjs!=numberadjs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSAdjointSetCostIntegrand()) is inconsistent with the one set by TSAdjointSetSensitivity() or TSAdjointSetSensitivityP()");
2423   ierr = VecGetSize(q,&size);CHKERRQ(ierr);
2424   ierr = VecZeroEntries(q);CHKERRQ(ierr);
2425   if (size!=numberadjs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions is inconsistent with the number of integrals (size of the 3rd input vector of TSAdjointSetCostIntegrand()).");
2426 
2427   ierr = PetscObjectReference((PetscObject)q);CHKERRQ(ierr);
2428   ierr = VecDestroy(&ts->vec_costquad);CHKERRQ(ierr);
2429   ts->vec_costquad = q;
2430 
2431   ierr                  = VecDuplicate(ts->vec_costquad,&ts->vec_costintegrand);CHKERRQ(ierr);
2432   ts->costintegrand     = fq;
2433   ts->costintegrandctx  = ctx;
2434 
2435   PetscFunctionReturn(0);
2436 }
2437 
2438 #undef __FUNCT__
2439 #define __FUNCT__ "TSAdjointGetCostQuadrature"
2440 /*@
2441    TSAdjointGetCostQuadrature - Returns the values of the quadrature (or integral) terms in a cost function.
2442    It is valid to call the routine after a backward run.
2443 
2444    Not Collective
2445 
2446    Input Parameter:
2447 .  ts - the TS context obtained from TSCreate()
2448 
2449    Output Parameter:
2450 .  v - the vector containing the solution
2451 
2452    Level: intermediate
2453 
2454 .seealso: TSAdjointSetCostIntegrand()
2455 
2456 .keywords: TS, sensitivity analysis
2457 @*/
2458 PetscErrorCode  TSAdjointGetCostQuadrature(TS ts,Vec *v)
2459 {
2460   PetscFunctionBegin;
2461   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2462   PetscValidPointer(v,2);
2463   *v = ts->vec_costquad;
2464   PetscFunctionReturn(0);
2465 }
2466 
2467 #undef __FUNCT__
2468 #define __FUNCT__ "TSAdjointComputeCostIntegrand"
2469 /*@
2470    TSAdjointComputeCostIntegrand - Evaluates the quadrature function in the cost functions.
2471 
2472    Input Parameters:
2473 +  ts - the TS context
2474 .  t - current time
2475 -  U - state vector
2476 
2477    Output Parameter:
2478 .  q - vector of size numberadjs to hold the outputs
2479 
2480    Note:
2481    Most users should not need to explicitly call this routine, as it
2482    is used internally within the sensitivity analysis context.
2483 
2484    Level: developer
2485 
2486 .keywords: TS, compute
2487 
2488 .seealso: TSAdjointSetCostIntegrand()
2489 @*/
2490 PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec U,Vec q)
2491 {
2492   PetscErrorCode ierr;
2493 
2494   PetscFunctionBegin;
2495   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2496   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
2497   PetscValidHeaderSpecific(q,VEC_CLASSID,4);
2498 
2499   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,q,0);CHKERRQ(ierr);
2500   if (ts->costintegrand) {
2501     PetscStackPush("TS user integrand in the cost function");
2502     ierr = (*ts->costintegrand)(ts,t,U,q,ts->costintegrandctx);CHKERRQ(ierr);
2503     PetscStackPop;
2504   } else {
2505     ierr = VecZeroEntries(q);CHKERRQ(ierr);
2506   }
2507 
2508   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,q,0);CHKERRQ(ierr);
2509   PetscFunctionReturn(0);
2510 }
2511 
2512 #undef __FUNCT__
2513 #define __FUNCT__ "TSAdjointSetDRDYFunction"
2514 /*@C
2515   TSAdjointSetDRDYFunction - Sets the function that computes the gradient of the CostIntegrand function r w.r.t. states y.
2516 
2517   Logically Collective on TS
2518 
2519   Input Parameters:
2520 + ts   - The TS context obtained from TSCreate()
2521 - func - The function
2522 
2523   Calling sequence of func:
2524 . PetscErroCode func(TS ts,PetscReal t,Vec U,Vec *drdy,void *ctx);
2525 
2526   Level: intermediate
2527 
2528 .keywords: TS, sensitivity
2529 .seealso:
2530 @*/
2531 PetscErrorCode  TSAdjointSetDRDYFunction(TS ts,Vec *drdy,PetscErrorCode (*func)(TS,PetscReal,Vec,Vec*,void*),void *ctx)
2532 {
2533   PetscFunctionBegin;
2534   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2535 
2536   ts->drdyfunction    = func;
2537   ts->drdyfunctionctx = ctx;
2538   ts->vecs_drdy       = drdy;
2539   PetscFunctionReturn(0);
2540 }
2541 
2542 #undef __FUNCT__
2543 #define __FUNCT__ "TSAdjointComputeDRDYFunction"
2544 /*@
2545   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
2546 
2547   Collective on TS
2548 
2549   Input Parameters:
2550 . ts   - The TS context obtained from TSCreate()
2551 
2552   Notes:
2553   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
2554   so most users would not generally call this routine themselves.
2555 
2556   Level: developer
2557 
2558 .keywords: TS, sensitivity
2559 .seealso: TSAdjointComputeDRDYFunction()
2560 @*/
2561 PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec X,Vec *drdy)
2562 {
2563   PetscErrorCode ierr;
2564 
2565   PetscFunctionBegin;
2566   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2567   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2568 
2569   PetscStackPush("TS user DRDY function for sensitivity analysis");
2570   ierr = (*ts->drdyfunction)(ts,t,X,drdy,ts->drdyfunctionctx); CHKERRQ(ierr);
2571   PetscStackPop;
2572   PetscFunctionReturn(0);
2573 }
2574 
2575 #undef __FUNCT__
2576 #define __FUNCT__ "TSAdjointSetDRDPFunction"
2577 /*@C
2578   TSAdjointSetDRDPFunction - Sets the function that computes the gradient of the CostIntegrand function w.r.t. parameters.
2579 
2580   Logically Collective on TS
2581 
2582   Input Parameters:
2583 + ts   - The TS context obtained from TSCreate()
2584 - func - The function
2585 
2586   Calling sequence of func:
2587 . func(TS ts,PetscReal t,Vec U,Vec *drdy,void *ctx);
2588 
2589   Level: intermediate
2590 
2591 .keywords: TS, sensitivity
2592 .seealso:
2593 @*/
2594 PetscErrorCode  TSAdjointSetDRDPFunction(TS ts,Vec *drdp,PetscErrorCode (*func)(TS,PetscReal,Vec,Vec*,void*),void *ctx)
2595 {
2596   PetscFunctionBegin;
2597   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2598 
2599   ts->drdpfunction    = func;
2600   ts->drdpfunctionctx = ctx;
2601   ts->vecs_drdp       = drdp;
2602 
2603   PetscFunctionReturn(0);
2604 }
2605 
2606 #undef __FUNCT__
2607 #define __FUNCT__ "TSAdjointComputeDRDPFunction"
2608 /*@
2609   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
2610 
2611   Collective on TS
2612 
2613   Input Parameters:
2614 . ts   - The TS context obtained from TSCreate()
2615 
2616   Notes:
2617   TSDRDPFunction() is typically used for sensitivity implementation,
2618   so most users would not generally call this routine themselves.
2619 
2620   Level: developer
2621 
2622 .keywords: TS, sensitivity
2623 .seealso: TSAdjointSetDRDPFunction()
2624 @*/
2625 PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec X,Vec *drdp)
2626 {
2627   PetscErrorCode ierr;
2628 
2629   PetscFunctionBegin;
2630   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2631   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2632 
2633   PetscStackPush("TS user DRDP function for sensitivity analysis");
2634   ierr = (*ts->drdpfunction)(ts,t,X,drdp,ts->drdpfunctionctx); CHKERRQ(ierr);
2635   PetscStackPop;
2636 
2637   PetscFunctionReturn(0);
2638 }
2639 
2640 #undef __FUNCT__
2641 #define __FUNCT__ "TSSetPreStep"
2642 /*@C
2643   TSSetPreStep - Sets the general-purpose function
2644   called once at the beginning of each time step.
2645 
2646   Logically Collective on TS
2647 
2648   Input Parameters:
2649 + ts   - The TS context obtained from TSCreate()
2650 - func - The function
2651 
2652   Calling sequence of func:
2653 . func (TS ts);
2654 
2655   Level: intermediate
2656 
2657   Note:
2658   If a step is rejected, TSStep() will call this routine again before each attempt.
2659   The last completed time step number can be queried using TSGetTimeStepNumber(), the
2660   size of the step being attempted can be obtained using TSGetTimeStep().
2661 
2662 .keywords: TS, timestep
2663 .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
2664 @*/
2665 PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2666 {
2667   PetscFunctionBegin;
2668   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2669   ts->prestep = func;
2670   PetscFunctionReturn(0);
2671 }
2672 
2673 #undef __FUNCT__
2674 #define __FUNCT__ "TSPreStep"
2675 /*@
2676   TSPreStep - Runs the user-defined pre-step function.
2677 
2678   Collective on TS
2679 
2680   Input Parameters:
2681 . ts   - The TS context obtained from TSCreate()
2682 
2683   Notes:
2684   TSPreStep() is typically used within time stepping implementations,
2685   so most users would not generally call this routine themselves.
2686 
2687   Level: developer
2688 
2689 .keywords: TS, timestep
2690 .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
2691 @*/
2692 PetscErrorCode  TSPreStep(TS ts)
2693 {
2694   PetscErrorCode ierr;
2695 
2696   PetscFunctionBegin;
2697   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2698   if (ts->prestep) {
2699     PetscStackCallStandard((*ts->prestep),(ts));
2700   }
2701   PetscFunctionReturn(0);
2702 }
2703 
2704 #undef __FUNCT__
2705 #define __FUNCT__ "TSSetPreStage"
2706 /*@C
2707   TSSetPreStage - Sets the general-purpose function
2708   called once at the beginning of each stage.
2709 
2710   Logically Collective on TS
2711 
2712   Input Parameters:
2713 + ts   - The TS context obtained from TSCreate()
2714 - func - The function
2715 
2716   Calling sequence of func:
2717 . PetscErrorCode func(TS ts, PetscReal stagetime);
2718 
2719   Level: intermediate
2720 
2721   Note:
2722   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2723   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2724   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
2725 
2726 .keywords: TS, timestep
2727 .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2728 @*/
2729 PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2730 {
2731   PetscFunctionBegin;
2732   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2733   ts->prestage = func;
2734   PetscFunctionReturn(0);
2735 }
2736 
2737 #undef __FUNCT__
2738 #define __FUNCT__ "TSSetPostStage"
2739 /*@C
2740   TSSetPostStage - Sets the general-purpose function
2741   called once at the end of each stage.
2742 
2743   Logically Collective on TS
2744 
2745   Input Parameters:
2746 + ts   - The TS context obtained from TSCreate()
2747 - func - The function
2748 
2749   Calling sequence of func:
2750 . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
2751 
2752   Level: intermediate
2753 
2754   Note:
2755   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2756   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2757   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
2758 
2759 .keywords: TS, timestep
2760 .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2761 @*/
2762 PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
2763 {
2764   PetscFunctionBegin;
2765   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2766   ts->poststage = func;
2767   PetscFunctionReturn(0);
2768 }
2769 
2770 #undef __FUNCT__
2771 #define __FUNCT__ "TSPreStage"
2772 /*@
2773   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
2774 
2775   Collective on TS
2776 
2777   Input Parameters:
2778 . ts          - The TS context obtained from TSCreate()
2779   stagetime   - The absolute time of the current stage
2780 
2781   Notes:
2782   TSPreStage() is typically used within time stepping implementations,
2783   most users would not generally call this routine themselves.
2784 
2785   Level: developer
2786 
2787 .keywords: TS, timestep
2788 .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2789 @*/
2790 PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
2791 {
2792   PetscErrorCode ierr;
2793 
2794   PetscFunctionBegin;
2795   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2796   if (ts->prestage) {
2797     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
2798   }
2799   PetscFunctionReturn(0);
2800 }
2801 
2802 #undef __FUNCT__
2803 #define __FUNCT__ "TSPostStage"
2804 /*@
2805   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
2806 
2807   Collective on TS
2808 
2809   Input Parameters:
2810 . ts          - The TS context obtained from TSCreate()
2811   stagetime   - The absolute time of the current stage
2812   stageindex  - Stage number
2813   Y           - Array of vectors (of size = total number
2814                 of stages) with the stage solutions
2815 
2816   Notes:
2817   TSPostStage() is typically used within time stepping implementations,
2818   most users would not generally call this routine themselves.
2819 
2820   Level: developer
2821 
2822 .keywords: TS, timestep
2823 .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2824 @*/
2825 PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
2826 {
2827   PetscErrorCode ierr;
2828 
2829   PetscFunctionBegin;
2830   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2831   if (ts->poststage) {
2832     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
2833   }
2834   PetscFunctionReturn(0);
2835 }
2836 
2837 #undef __FUNCT__
2838 #define __FUNCT__ "TSSetPostStep"
2839 /*@C
2840   TSSetPostStep - Sets the general-purpose function
2841   called once at the end of each time step.
2842 
2843   Logically Collective on TS
2844 
2845   Input Parameters:
2846 + ts   - The TS context obtained from TSCreate()
2847 - func - The function
2848 
2849   Calling sequence of func:
2850 $ func (TS ts);
2851 
2852   Level: intermediate
2853 
2854 .keywords: TS, timestep
2855 .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2856 @*/
2857 PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2858 {
2859   PetscFunctionBegin;
2860   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2861   ts->poststep = func;
2862   PetscFunctionReturn(0);
2863 }
2864 
2865 #undef __FUNCT__
2866 #define __FUNCT__ "TSPostStep"
2867 /*@
2868   TSPostStep - Runs the user-defined post-step function.
2869 
2870   Collective on TS
2871 
2872   Input Parameters:
2873 . ts   - The TS context obtained from TSCreate()
2874 
2875   Notes:
2876   TSPostStep() is typically used within time stepping implementations,
2877   so most users would not generally call this routine themselves.
2878 
2879   Level: developer
2880 
2881 .keywords: TS, timestep
2882 @*/
2883 PetscErrorCode  TSPostStep(TS ts)
2884 {
2885   PetscErrorCode ierr;
2886 
2887   PetscFunctionBegin;
2888   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2889   if (ts->poststep) {
2890     PetscStackCallStandard((*ts->poststep),(ts));
2891   }
2892   PetscFunctionReturn(0);
2893 }
2894 
2895 /* ------------ Routines to set performance monitoring options ----------- */
2896 
2897 #undef __FUNCT__
2898 #define __FUNCT__ "TSMonitorSet"
2899 /*@C
2900    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
2901    timestep to display the iteration's  progress.
2902 
2903    Logically Collective on TS
2904 
2905    Input Parameters:
2906 +  ts - the TS context obtained from TSCreate()
2907 .  monitor - monitoring routine
2908 .  mctx - [optional] user-defined context for private data for the
2909              monitor routine (use NULL if no context is desired)
2910 -  monitordestroy - [optional] routine that frees monitor context
2911           (may be NULL)
2912 
2913    Calling sequence of monitor:
2914 $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
2915 
2916 +    ts - the TS context
2917 .    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
2918                                been interpolated to)
2919 .    time - current time
2920 .    u - current iterate
2921 -    mctx - [optional] monitoring context
2922 
2923    Notes:
2924    This routine adds an additional monitor to the list of monitors that
2925    already has been loaded.
2926 
2927    Fortran notes: Only a single monitor function can be set for each TS object
2928 
2929    Level: intermediate
2930 
2931 .keywords: TS, timestep, set, monitor
2932 
2933 .seealso: TSMonitorDefault(), TSMonitorCancel()
2934 @*/
2935 PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
2936 {
2937   PetscFunctionBegin;
2938   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2939   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
2940   ts->monitor[ts->numbermonitors]          = monitor;
2941   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
2942   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
2943   PetscFunctionReturn(0);
2944 }
2945 
2946 #undef __FUNCT__
2947 #define __FUNCT__ "TSMonitorCancel"
2948 /*@C
2949    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
2950 
2951    Logically Collective on TS
2952 
2953    Input Parameters:
2954 .  ts - the TS context obtained from TSCreate()
2955 
2956    Notes:
2957    There is no way to remove a single, specific monitor.
2958 
2959    Level: intermediate
2960 
2961 .keywords: TS, timestep, set, monitor
2962 
2963 .seealso: TSMonitorDefault(), TSMonitorSet()
2964 @*/
2965 PetscErrorCode  TSMonitorCancel(TS ts)
2966 {
2967   PetscErrorCode ierr;
2968   PetscInt       i;
2969 
2970   PetscFunctionBegin;
2971   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2972   for (i=0; i<ts->numbermonitors; i++) {
2973     if (ts->monitordestroy[i]) {
2974       ierr = (*ts->monitordestroy[i])(&ts->monitorcontext[i]);CHKERRQ(ierr);
2975     }
2976   }
2977   ts->numbermonitors = 0;
2978   PetscFunctionReturn(0);
2979 }
2980 
2981 #undef __FUNCT__
2982 #define __FUNCT__ "TSMonitorDefault"
2983 /*@
2984    TSMonitorDefault - Sets the Default monitor
2985 
2986    Level: intermediate
2987 
2988 .keywords: TS, set, monitor
2989 
2990 .seealso: TSMonitorDefault(), TSMonitorSet()
2991 @*/
2992 PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
2993 {
2994   PetscErrorCode ierr;
2995   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));
2996 
2997   PetscFunctionBegin;
2998   ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
2999   ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g\n",step,(double)ts->time_step,(double)ptime);CHKERRQ(ierr);
3000   ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3001   PetscFunctionReturn(0);
3002 }
3003 
3004 #undef __FUNCT__
3005 #define __FUNCT__ "TSSetRetainStages"
3006 /*@
3007    TSSetRetainStages - Request that all stages in the upcoming step be stored so that interpolation will be available.
3008 
3009    Logically Collective on TS
3010 
3011    Input Argument:
3012 .  ts - time stepping context
3013 
3014    Output Argument:
3015 .  flg - PETSC_TRUE or PETSC_FALSE
3016 
3017    Level: intermediate
3018 
3019 .keywords: TS, set
3020 
3021 .seealso: TSInterpolate(), TSSetPostStep()
3022 @*/
3023 PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
3024 {
3025   PetscFunctionBegin;
3026   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3027   ts->retain_stages = flg;
3028   PetscFunctionReturn(0);
3029 }
3030 
3031 #undef __FUNCT__
3032 #define __FUNCT__ "TSInterpolate"
3033 /*@
3034    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3035 
3036    Collective on TS
3037 
3038    Input Argument:
3039 +  ts - time stepping context
3040 -  t - time to interpolate to
3041 
3042    Output Argument:
3043 .  U - state at given time
3044 
3045    Notes:
3046    The user should call TSSetRetainStages() before taking a step in which interpolation will be requested.
3047 
3048    Level: intermediate
3049 
3050    Developer Notes:
3051    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3052 
3053 .keywords: TS, set
3054 
3055 .seealso: TSSetRetainStages(), TSSetPostStep()
3056 @*/
3057 PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3058 {
3059   PetscErrorCode ierr;
3060 
3061   PetscFunctionBegin;
3062   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3063   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3064   if (t < ts->ptime - ts->time_step_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)(ts->ptime-ts->time_step_prev),(double)ts->ptime);
3065   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3066   ierr = (*ts->ops->interpolate)(ts,t,U);CHKERRQ(ierr);
3067   PetscFunctionReturn(0);
3068 }
3069 
3070 #undef __FUNCT__
3071 #define __FUNCT__ "TSStep"
3072 /*@
3073    TSStep - Steps one time step
3074 
3075    Collective on TS
3076 
3077    Input Parameter:
3078 .  ts - the TS context obtained from TSCreate()
3079 
3080    Level: intermediate
3081 
3082    Notes:
3083    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3084    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3085 
3086    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3087    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3088 
3089 .keywords: TS, timestep, solve
3090 
3091 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3092 @*/
3093 PetscErrorCode  TSStep(TS ts)
3094 {
3095   DM               dm;
3096   PetscErrorCode   ierr;
3097   static PetscBool cite = PETSC_FALSE;
3098 
3099   PetscFunctionBegin;
3100   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3101   ierr = PetscCitationsRegister("@techreport{tspaper,\n"
3102                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3103                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3104                                 "  type        = {Preprint},\n"
3105                                 "  number      = {ANL/MCS-P5061-0114},\n"
3106                                 "  institution = {Argonne National Laboratory},\n"
3107                                 "  year        = {2014}\n}\n",&cite);
3108 
3109   ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
3110   ierr = TSSetUp(ts);CHKERRQ(ierr);
3111 
3112   ts->reason = TS_CONVERGED_ITERATING;
3113   ts->ptime_prev = ts->ptime;
3114   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3115   ierr = VecViewFromOptions(ts->vec_sol, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3116 
3117   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3118   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3119   ierr = (*ts->ops->step)(ts);CHKERRQ(ierr);
3120   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3121 
3122   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3123   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3124 
3125   if (ts->reason < 0) {
3126     if (ts->errorifstepfailed) {
3127       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]);
3128       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3129     }
3130   } else if (!ts->reason) {
3131     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3132     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3133   }
3134   ts->total_steps++;
3135   PetscFunctionReturn(0);
3136 }
3137 
3138 #undef __FUNCT__
3139 #define __FUNCT__ "TSAdjointStep"
3140 /*@
3141    TSAdjointStep - Steps one time step
3142 
3143    Collective on TS
3144 
3145    Input Parameter:
3146 .  ts - the TS context obtained from TSCreate()
3147 
3148    Level: intermediate
3149 
3150    Notes:
3151    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3152    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3153 
3154    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3155    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3156 
3157 .keywords: TS, timestep, solve
3158 
3159 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3160 @*/
3161 PetscErrorCode  TSAdjointStep(TS ts)
3162 {
3163   DM               dm;
3164   PetscErrorCode   ierr;
3165 
3166   PetscFunctionBegin;
3167   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3168   ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
3169   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3170 
3171   ts->reason = TS_CONVERGED_ITERATING;
3172   ts->ptime_prev = ts->ptime;
3173   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3174   ierr = VecViewFromOptions(ts->vec_sol, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3175 
3176   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3177   if (!ts->ops->stepadj) 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);
3178   ierr = (*ts->ops->stepadj)(ts);CHKERRQ(ierr);
3179   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3180 
3181   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3182   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3183 
3184   if (ts->reason < 0) {
3185     if (ts->errorifstepfailed) {
3186       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
3187         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]);
3188       } else if (ts->reason == TS_DIVERGED_STEP_REJECTED) {
3189         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]);
3190       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3191     }
3192   } else if (!ts->reason) {
3193     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3194     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3195   }
3196   ts->total_steps--;
3197   PetscFunctionReturn(0);
3198 }
3199 
3200 #undef __FUNCT__
3201 #define __FUNCT__ "TSEvaluateStep"
3202 /*@
3203    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3204 
3205    Collective on TS
3206 
3207    Input Arguments:
3208 +  ts - time stepping context
3209 .  order - desired order of accuracy
3210 -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3211 
3212    Output Arguments:
3213 .  U - state at the end of the current step
3214 
3215    Level: advanced
3216 
3217    Notes:
3218    This function cannot be called until all stages have been evaluated.
3219    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.
3220 
3221 .seealso: TSStep(), TSAdapt
3222 @*/
3223 PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3224 {
3225   PetscErrorCode ierr;
3226 
3227   PetscFunctionBegin;
3228   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3229   PetscValidType(ts,1);
3230   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3231   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3232   ierr = (*ts->ops->evaluatestep)(ts,order,U,done);CHKERRQ(ierr);
3233   PetscFunctionReturn(0);
3234 }
3235 
3236 #undef __FUNCT__
3237 #define __FUNCT__ "OutputBIN"
3238 static PetscErrorCode OutputBIN(const char *filename, PetscViewer *viewer)
3239 {
3240   PetscErrorCode ierr;
3241 
3242   PetscFunctionBeginUser;
3243   ierr = PetscViewerCreate(PETSC_COMM_WORLD, viewer);CHKERRQ(ierr);
3244   ierr = PetscViewerSetType(*viewer, PETSCVIEWERBINARY);CHKERRQ(ierr);
3245   ierr = PetscViewerFileSetMode(*viewer,FILE_MODE_WRITE);CHKERRQ(ierr);
3246   ierr = PetscViewerFileSetName(*viewer, filename);CHKERRQ(ierr);
3247   PetscFunctionReturn(0);
3248 }
3249 
3250 #undef __FUNCT__
3251 #define __FUNCT__ "TSTrajectorySet"
3252 PetscErrorCode TSTrajectorySet(TS ts,PetscInt stepnum,PetscReal time,Vec X)
3253 {
3254   PetscViewer    viewer;
3255   PetscInt       ns,i;
3256   Vec            *Y;
3257   char           filename[PETSC_MAX_PATH_LEN];
3258   PetscReal      tprev;
3259   PetscErrorCode ierr;
3260 
3261   PetscFunctionBeginUser;
3262   if (stepnum == 0) {
3263 #if defined(PETSC_HAVE_POPEN)
3264     ierr = TSGetTotalSteps(ts,&stepnum);CHKERRQ(ierr);
3265     if (stepnum == 0) {
3266       PetscMPIInt rank;
3267       ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);CHKERRQ(ierr);
3268       if (!rank) {
3269         char command[PETSC_MAX_PATH_LEN];
3270         FILE *fd;
3271         int  err;
3272 
3273         ierr = PetscMemzero(command,sizeof(command));CHKERRQ(ierr);
3274         ierr = PetscSNPrintf(command,PETSC_MAX_PATH_LEN,"rm -fr %s","SA-data");CHKERRQ(ierr);
3275         ierr = PetscPOpen(PETSC_COMM_SELF,NULL,command,"r",&fd);CHKERRQ(ierr);
3276         ierr = PetscPClose(PETSC_COMM_SELF,fd,&err);CHKERRQ(ierr);
3277         ierr = PetscSNPrintf(command,PETSC_MAX_PATH_LEN,"mkdir %s","SA-data");CHKERRQ(ierr);
3278         ierr = PetscPOpen(PETSC_COMM_SELF,NULL,command,"r",&fd);CHKERRQ(ierr);
3279         ierr = PetscPClose(PETSC_COMM_SELF,fd,&err);CHKERRQ(ierr);
3280       }
3281     }
3282 #endif
3283     PetscFunctionReturn(0);
3284   }
3285   ierr = TSGetPrevTime(ts,&tprev);CHKERRQ(ierr);
3286   ierr = TSGetTotalSteps(ts,&stepnum);CHKERRQ(ierr);
3287   ierr = PetscSNPrintf(filename,sizeof(filename),"SA-data/SA-%06d.bin",stepnum);CHKERRQ(ierr);
3288   ierr = OutputBIN(filename,&viewer);CHKERRQ(ierr);
3289   ierr = VecView(X,viewer);CHKERRQ(ierr);
3290   /* ierr = PetscRealView(1,&time,viewer);CHKERRQ(ierr); */
3291   ierr = PetscViewerBinaryWrite(viewer,&tprev,1,PETSC_REAL,PETSC_FALSE);CHKERRQ(ierr);
3292   /* ierr = PetscViewerBinaryWrite(viewer,&h ,1,PETSC_REAL,PETSC_FALSE);CHKERRQ(ierr); */
3293   ierr = TSGetStages(ts,&ns,&Y);CHKERRQ(ierr);
3294 
3295   for (i=0;i<ns;i++) {
3296     ierr = VecView(Y[i],viewer);CHKERRQ(ierr);
3297   }
3298 
3299   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
3300   PetscFunctionReturn(0);
3301 }
3302 
3303 #undef __FUNCT__
3304 #define __FUNCT__ "TSTrajectoryGet"
3305 PetscErrorCode TSTrajectoryGet(TS ts,PetscInt step,PetscReal t,Vec X)
3306 {
3307   PetscReal      ptime;
3308   Vec            Sol,*Y;
3309   PetscInt       Nr,i;
3310   PetscViewer    viewer;
3311   PetscReal      timepre;
3312   char           filename[PETSC_MAX_PATH_LEN];
3313   PetscErrorCode ierr;
3314 
3315   PetscFunctionBeginUser;
3316   ierr = TSGetTotalSteps(ts,&step);CHKERRQ(ierr);
3317   ierr = PetscSNPrintf(filename,sizeof filename,"SA-data/SA-%06d.bin",step);CHKERRQ(ierr);
3318   ierr = PetscViewerBinaryOpen(PETSC_COMM_WORLD,filename,FILE_MODE_READ,&viewer);CHKERRQ(ierr);
3319 
3320   ierr = TSGetSolution(ts,&Sol);CHKERRQ(ierr);
3321   ierr = VecLoad(Sol,viewer);CHKERRQ(ierr);
3322 
3323   Nr   = 1;
3324   /* ierr = PetscRealLoad(Nr,&Nr,&timepre,viewer);CHKERRQ(ierr); */
3325   ierr = PetscViewerBinaryRead(viewer,&timepre,1,PETSC_REAL);CHKERRQ(ierr);
3326 
3327   ierr = TSGetStages(ts,&Nr,&Y);CHKERRQ(ierr);
3328   for (i=0;i<Nr ;i++) {
3329     ierr = VecLoad(Y[i],viewer);CHKERRQ(ierr);
3330   }
3331 
3332   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
3333 
3334   ierr = TSGetTime(ts,&ptime);CHKERRQ(ierr);
3335   ierr = TSSetTimeStep(ts,-ptime+timepre);CHKERRQ(ierr);
3336 
3337   PetscFunctionReturn(0);
3338 }
3339 
3340 #undef __FUNCT__
3341 #define __FUNCT__ "TSSolve"
3342 /*@
3343    TSSolve - Steps the requested number of timesteps.
3344 
3345    Collective on TS
3346 
3347    Input Parameter:
3348 +  ts - the TS context obtained from TSCreate()
3349 -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)
3350 
3351    Level: beginner
3352 
3353    Notes:
3354    The final time returned by this function may be different from the time of the internally
3355    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3356    stepped over the final time.
3357 
3358 .keywords: TS, timestep, solve
3359 
3360 .seealso: TSCreate(), TSSetSolution(), TSStep()
3361 @*/
3362 PetscErrorCode TSSolve(TS ts,Vec u)
3363 {
3364   Vec               solution;
3365   PetscErrorCode    ierr;
3366 
3367   PetscFunctionBegin;
3368   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3369   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3370   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 */
3371     PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3372     if (!ts->vec_sol || u == ts->vec_sol) {
3373       ierr = VecDuplicate(u,&solution);CHKERRQ(ierr);
3374       ierr = TSSetSolution(ts,solution);CHKERRQ(ierr);
3375       ierr = VecDestroy(&solution);CHKERRQ(ierr); /* grant ownership */
3376     }
3377     ierr = VecCopy(u,ts->vec_sol);CHKERRQ(ierr);
3378   } else if (u) {
3379     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
3380   }
3381   ierr = TSSetUp(ts);CHKERRQ(ierr); /*compute adj coefficients if the reverse mode is on*/
3382   /* reset time step and iteration counters */
3383   ts->steps             = 0;
3384   ts->ksp_its           = 0;
3385   ts->snes_its          = 0;
3386   ts->num_snes_failures = 0;
3387   ts->reject            = 0;
3388   ts->reason            = TS_CONVERGED_ITERATING;
3389 
3390   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
3391 
3392   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
3393     ierr = (*ts->ops->solve)(ts);CHKERRQ(ierr);
3394     ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);
3395     ts->solvetime = ts->ptime;
3396   } else {
3397     /* steps the requested number of timesteps. */
3398     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3399     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3400     while (!ts->reason) {
3401       ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3402       ierr = TSTrajectorySet(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3403       ierr = TSStep(ts);CHKERRQ(ierr);
3404       if (ts->event) {
3405 	ierr = TSEventMonitor(ts);CHKERRQ(ierr);
3406 	if (ts->event->status != TSEVENT_PROCESSING) {
3407 	  ierr = TSPostStep(ts);CHKERRQ(ierr);
3408 	}
3409       } else {
3410 	ierr = TSPostStep(ts);CHKERRQ(ierr);
3411       }
3412     }
3413     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3414       ierr = TSInterpolate(ts,ts->max_time,u);CHKERRQ(ierr);
3415       ts->solvetime = ts->max_time;
3416       solution = u;
3417     } else {
3418       if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3419       ts->solvetime = ts->ptime;
3420       solution = ts->vec_sol;
3421     }
3422     ierr = TSTrajectorySet(ts,ts->steps,ts->solvetime,solution);CHKERRQ(ierr);
3423     ierr = TSMonitor(ts,ts->steps,ts->solvetime,solution);CHKERRQ(ierr);
3424     ierr = VecViewFromOptions(u, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3425   }
3426 
3427   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
3428   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
3429   PetscFunctionReturn(0);
3430 }
3431 
3432 #undef __FUNCT__
3433 #define __FUNCT__ "TSAdjointSolve"
3434 /*@
3435    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
3436 
3437    Collective on TS
3438 
3439    Input Parameter:
3440 +  ts - the TS context obtained from TSCreate()
3441 -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)
3442 
3443    Level: intermediate
3444 
3445    Notes:
3446    This must be called after a call to TSSolve() that solves the forward problem
3447 
3448 .keywords: TS, timestep, solve
3449 
3450 .seealso: TSCreate(), TSSetSolution(), TSStep()
3451 @*/
3452 PetscErrorCode TSAdjointSolve(TS ts,Vec u)
3453 {
3454   PetscErrorCode    ierr;
3455 
3456   PetscFunctionBegin;
3457   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3458   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3459   if (u) {
3460     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
3461   }
3462   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3463   /* reset time step and iteration counters */
3464   ts->steps             = 0;
3465   ts->ksp_its           = 0;
3466   ts->snes_its          = 0;
3467   ts->num_snes_failures = 0;
3468   ts->reject            = 0;
3469   ts->reason            = TS_CONVERGED_ITERATING;
3470 
3471   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
3472 
3473   if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3474   while (!ts->reason) {
3475     ierr = TSTrajectoryGet(ts,ts->max_steps-ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3476     ierr = TSMonitor(ts,ts->max_steps-ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3477     ierr = TSAdjointStep(ts);CHKERRQ(ierr);
3478     if (ts->event) {
3479       ierr = TSEventMonitor(ts);CHKERRQ(ierr);
3480       if (ts->event->status != TSEVENT_PROCESSING) {
3481         ierr = TSPostStep(ts);CHKERRQ(ierr);
3482       }
3483     } else {
3484       ierr = TSPostStep(ts);CHKERRQ(ierr);
3485     }
3486   }
3487   if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3488   ts->solvetime = ts->ptime;
3489   ierr = TSMonitor(ts,0,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3490   ierr = VecViewFromOptions(u, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3491 
3492   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
3493   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
3494   PetscFunctionReturn(0);
3495 }
3496 
3497 #undef __FUNCT__
3498 #define __FUNCT__ "TSMonitor"
3499 /*@
3500    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
3501 
3502    Collective on TS
3503 
3504    Input Parameters:
3505 +  ts - time stepping context obtained from TSCreate()
3506 .  step - step number that has just completed
3507 .  ptime - model time of the state
3508 -  u - state at the current model time
3509 
3510    Notes:
3511    TSMonitor() is typically used within the time stepping implementations.
3512    Users might call this function when using the TSStep() interface instead of TSSolve().
3513 
3514    Level: advanced
3515 
3516 .keywords: TS, timestep
3517 @*/
3518 PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
3519 {
3520   PetscErrorCode ierr;
3521   PetscInt       i,n = ts->numbermonitors;
3522 
3523   PetscFunctionBegin;
3524   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3525   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
3526   ierr = VecLockPush(u);CHKERRQ(ierr);
3527   for (i=0; i<n; i++) {
3528     ierr = (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);CHKERRQ(ierr);
3529   }
3530   ierr = VecLockPop(u);CHKERRQ(ierr);
3531   PetscFunctionReturn(0);
3532 }
3533 
3534 /* ------------------------------------------------------------------------*/
3535 #undef __FUNCT__
3536 #define __FUNCT__ "TSMonitorLGCtxCreate"
3537 /*@C
3538    TSMonitorLGCtxCreate - Creates a line graph context for use with
3539    TS to monitor the solution process graphically in various ways
3540 
3541    Collective on TS
3542 
3543    Input Parameters:
3544 +  host - the X display to open, or null for the local machine
3545 .  label - the title to put in the title bar
3546 .  x, y - the screen coordinates of the upper left coordinate of the window
3547 .  m, n - the screen width and height in pixels
3548 -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
3549 
3550    Output Parameter:
3551 .  ctx - the context
3552 
3553    Options Database Key:
3554 +  -ts_monitor_lg_timestep - automatically sets line graph monitor
3555 .  -ts_monitor_lg_solution -
3556 .  -ts_monitor_lg_error -
3557 .  -ts_monitor_lg_ksp_iterations -
3558 .  -ts_monitor_lg_snes_iterations -
3559 -  -lg_indicate_data_points <true,false> - indicate the data points (at each time step) on the plot; default is true
3560 
3561    Notes:
3562    Use TSMonitorLGCtxDestroy() to destroy.
3563 
3564    Level: intermediate
3565 
3566 .keywords: TS, monitor, line graph, residual, seealso
3567 
3568 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
3569 
3570 @*/
3571 PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
3572 {
3573   PetscDraw      win;
3574   PetscErrorCode ierr;
3575 
3576   PetscFunctionBegin;
3577   ierr = PetscNew(ctx);CHKERRQ(ierr);
3578   ierr = PetscDrawCreate(comm,host,label,x,y,m,n,&win);CHKERRQ(ierr);
3579   ierr = PetscDrawSetFromOptions(win);CHKERRQ(ierr);
3580   ierr = PetscDrawLGCreate(win,1,&(*ctx)->lg);CHKERRQ(ierr);
3581   ierr = PetscLogObjectParent((PetscObject)(*ctx)->lg,(PetscObject)win);CHKERRQ(ierr);
3582   ierr = PetscDrawLGIndicateDataPoints((*ctx)->lg,PETSC_TRUE);CHKERRQ(ierr);
3583   ierr = PetscDrawLGSetFromOptions((*ctx)->lg);CHKERRQ(ierr);
3584   (*ctx)->howoften = howoften;
3585   PetscFunctionReturn(0);
3586 }
3587 
3588 #undef __FUNCT__
3589 #define __FUNCT__ "TSMonitorLGTimeStep"
3590 PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
3591 {
3592   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
3593   PetscReal      x   = ptime,y;
3594   PetscErrorCode ierr;
3595 
3596   PetscFunctionBegin;
3597   if (!step) {
3598     PetscDrawAxis axis;
3599     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
3600     ierr = PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");CHKERRQ(ierr);
3601     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
3602     ierr = PetscDrawLGIndicateDataPoints(ctx->lg,PETSC_TRUE);CHKERRQ(ierr);
3603   }
3604   ierr = TSGetTimeStep(ts,&y);CHKERRQ(ierr);
3605   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
3606   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
3607     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
3608   }
3609   PetscFunctionReturn(0);
3610 }
3611 
3612 #undef __FUNCT__
3613 #define __FUNCT__ "TSMonitorLGCtxDestroy"
3614 /*@C
3615    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
3616    with TSMonitorLGCtxCreate().
3617 
3618    Collective on TSMonitorLGCtx
3619 
3620    Input Parameter:
3621 .  ctx - the monitor context
3622 
3623    Level: intermediate
3624 
3625 .keywords: TS, monitor, line graph, destroy
3626 
3627 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
3628 @*/
3629 PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
3630 {
3631   PetscDraw      draw;
3632   PetscErrorCode ierr;
3633 
3634   PetscFunctionBegin;
3635   ierr = PetscDrawLGGetDraw((*ctx)->lg,&draw);CHKERRQ(ierr);
3636   ierr = PetscDrawDestroy(&draw);CHKERRQ(ierr);
3637   ierr = PetscDrawLGDestroy(&(*ctx)->lg);CHKERRQ(ierr);
3638   ierr = PetscFree(*ctx);CHKERRQ(ierr);
3639   PetscFunctionReturn(0);
3640 }
3641 
3642 #undef __FUNCT__
3643 #define __FUNCT__ "TSGetTime"
3644 /*@
3645    TSGetTime - Gets the time of the most recently completed step.
3646 
3647    Not Collective
3648 
3649    Input Parameter:
3650 .  ts - the TS context obtained from TSCreate()
3651 
3652    Output Parameter:
3653 .  t  - the current time
3654 
3655    Level: beginner
3656 
3657    Note:
3658    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
3659    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
3660 
3661 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
3662 
3663 .keywords: TS, get, time
3664 @*/
3665 PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3666 {
3667   PetscFunctionBegin;
3668   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3669   PetscValidRealPointer(t,2);
3670   *t = ts->ptime;
3671   PetscFunctionReturn(0);
3672 }
3673 
3674 #undef __FUNCT__
3675 #define __FUNCT__ "TSGetPrevTime"
3676 /*@
3677    TSGetPrevTime - Gets the starting time of the previously completed step.
3678 
3679    Not Collective
3680 
3681    Input Parameter:
3682 .  ts - the TS context obtained from TSCreate()
3683 
3684    Output Parameter:
3685 .  t  - the previous time
3686 
3687    Level: beginner
3688 
3689 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
3690 
3691 .keywords: TS, get, time
3692 @*/
3693 PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
3694 {
3695   PetscFunctionBegin;
3696   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3697   PetscValidRealPointer(t,2);
3698   *t = ts->ptime_prev;
3699   PetscFunctionReturn(0);
3700 }
3701 
3702 #undef __FUNCT__
3703 #define __FUNCT__ "TSSetTime"
3704 /*@
3705    TSSetTime - Allows one to reset the time.
3706 
3707    Logically Collective on TS
3708 
3709    Input Parameters:
3710 +  ts - the TS context obtained from TSCreate()
3711 -  time - the time
3712 
3713    Level: intermediate
3714 
3715 .seealso: TSGetTime(), TSSetDuration()
3716 
3717 .keywords: TS, set, time
3718 @*/
3719 PetscErrorCode  TSSetTime(TS ts, PetscReal t)
3720 {
3721   PetscFunctionBegin;
3722   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3723   PetscValidLogicalCollectiveReal(ts,t,2);
3724   ts->ptime = t;
3725   PetscFunctionReturn(0);
3726 }
3727 
3728 #undef __FUNCT__
3729 #define __FUNCT__ "TSSetOptionsPrefix"
3730 /*@C
3731    TSSetOptionsPrefix - Sets the prefix used for searching for all
3732    TS options in the database.
3733 
3734    Logically Collective on TS
3735 
3736    Input Parameter:
3737 +  ts     - The TS context
3738 -  prefix - The prefix to prepend to all option names
3739 
3740    Notes:
3741    A hyphen (-) must NOT be given at the beginning of the prefix name.
3742    The first character of all runtime options is AUTOMATICALLY the
3743    hyphen.
3744 
3745    Level: advanced
3746 
3747 .keywords: TS, set, options, prefix, database
3748 
3749 .seealso: TSSetFromOptions()
3750 
3751 @*/
3752 PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
3753 {
3754   PetscErrorCode ierr;
3755   SNES           snes;
3756 
3757   PetscFunctionBegin;
3758   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3759   ierr = PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3760   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3761   ierr = SNESSetOptionsPrefix(snes,prefix);CHKERRQ(ierr);
3762   PetscFunctionReturn(0);
3763 }
3764 
3765 
3766 #undef __FUNCT__
3767 #define __FUNCT__ "TSAppendOptionsPrefix"
3768 /*@C
3769    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3770    TS options in the database.
3771 
3772    Logically Collective on TS
3773 
3774    Input Parameter:
3775 +  ts     - The TS context
3776 -  prefix - The prefix to prepend to all option names
3777 
3778    Notes:
3779    A hyphen (-) must NOT be given at the beginning of the prefix name.
3780    The first character of all runtime options is AUTOMATICALLY the
3781    hyphen.
3782 
3783    Level: advanced
3784 
3785 .keywords: TS, append, options, prefix, database
3786 
3787 .seealso: TSGetOptionsPrefix()
3788 
3789 @*/
3790 PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
3791 {
3792   PetscErrorCode ierr;
3793   SNES           snes;
3794 
3795   PetscFunctionBegin;
3796   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3797   ierr = PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3798   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3799   ierr = SNESAppendOptionsPrefix(snes,prefix);CHKERRQ(ierr);
3800   PetscFunctionReturn(0);
3801 }
3802 
3803 #undef __FUNCT__
3804 #define __FUNCT__ "TSGetOptionsPrefix"
3805 /*@C
3806    TSGetOptionsPrefix - Sets the prefix used for searching for all
3807    TS options in the database.
3808 
3809    Not Collective
3810 
3811    Input Parameter:
3812 .  ts - The TS context
3813 
3814    Output Parameter:
3815 .  prefix - A pointer to the prefix string used
3816 
3817    Notes: On the fortran side, the user should pass in a string 'prifix' of
3818    sufficient length to hold the prefix.
3819 
3820    Level: intermediate
3821 
3822 .keywords: TS, get, options, prefix, database
3823 
3824 .seealso: TSAppendOptionsPrefix()
3825 @*/
3826 PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
3827 {
3828   PetscErrorCode ierr;
3829 
3830   PetscFunctionBegin;
3831   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3832   PetscValidPointer(prefix,2);
3833   ierr = PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3834   PetscFunctionReturn(0);
3835 }
3836 
3837 #undef __FUNCT__
3838 #define __FUNCT__ "TSGetRHSJacobian"
3839 /*@C
3840    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
3841 
3842    Not Collective, but parallel objects are returned if TS is parallel
3843 
3844    Input Parameter:
3845 .  ts  - The TS context obtained from TSCreate()
3846 
3847    Output Parameters:
3848 +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
3849 .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
3850 .  func - Function to compute the Jacobian of the RHS  (or NULL)
3851 -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
3852 
3853    Notes: You can pass in NULL for any return argument you do not need.
3854 
3855    Level: intermediate
3856 
3857 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
3858 
3859 .keywords: TS, timestep, get, matrix, Jacobian
3860 @*/
3861 PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
3862 {
3863   PetscErrorCode ierr;
3864   SNES           snes;
3865   DM             dm;
3866 
3867   PetscFunctionBegin;
3868   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3869   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
3870   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3871   ierr = DMTSGetRHSJacobian(dm,func,ctx);CHKERRQ(ierr);
3872   PetscFunctionReturn(0);
3873 }
3874 
3875 #undef __FUNCT__
3876 #define __FUNCT__ "TSGetIJacobian"
3877 /*@C
3878    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
3879 
3880    Not Collective, but parallel objects are returned if TS is parallel
3881 
3882    Input Parameter:
3883 .  ts  - The TS context obtained from TSCreate()
3884 
3885    Output Parameters:
3886 +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
3887 .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
3888 .  f   - The function to compute the matrices
3889 - ctx - User-defined context for Jacobian evaluation routine
3890 
3891    Notes: You can pass in NULL for any return argument you do not need.
3892 
3893    Level: advanced
3894 
3895 .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
3896 
3897 .keywords: TS, timestep, get, matrix, Jacobian
3898 @*/
3899 PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
3900 {
3901   PetscErrorCode ierr;
3902   SNES           snes;
3903   DM             dm;
3904 
3905   PetscFunctionBegin;
3906   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3907   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
3908   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
3909   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3910   ierr = DMTSGetIJacobian(dm,f,ctx);CHKERRQ(ierr);
3911   PetscFunctionReturn(0);
3912 }
3913 
3914 
3915 #undef __FUNCT__
3916 #define __FUNCT__ "TSMonitorDrawSolution"
3917 /*@C
3918    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
3919    VecView() for the solution at each timestep
3920 
3921    Collective on TS
3922 
3923    Input Parameters:
3924 +  ts - the TS context
3925 .  step - current time-step
3926 .  ptime - current time
3927 -  dummy - either a viewer or NULL
3928 
3929    Options Database:
3930 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
3931 
3932    Notes: the initial solution and current solution are not displayed with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
3933        will look bad
3934 
3935    Level: intermediate
3936 
3937 .keywords: TS,  vector, monitor, view
3938 
3939 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3940 @*/
3941 PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3942 {
3943   PetscErrorCode   ierr;
3944   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
3945   PetscDraw        draw;
3946 
3947   PetscFunctionBegin;
3948   if (!step && ictx->showinitial) {
3949     if (!ictx->initialsolution) {
3950       ierr = VecDuplicate(u,&ictx->initialsolution);CHKERRQ(ierr);
3951     }
3952     ierr = VecCopy(u,ictx->initialsolution);CHKERRQ(ierr);
3953   }
3954   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
3955 
3956   if (ictx->showinitial) {
3957     PetscReal pause;
3958     ierr = PetscViewerDrawGetPause(ictx->viewer,&pause);CHKERRQ(ierr);
3959     ierr = PetscViewerDrawSetPause(ictx->viewer,0.0);CHKERRQ(ierr);
3960     ierr = VecView(ictx->initialsolution,ictx->viewer);CHKERRQ(ierr);
3961     ierr = PetscViewerDrawSetPause(ictx->viewer,pause);CHKERRQ(ierr);
3962     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);CHKERRQ(ierr);
3963   }
3964   ierr = VecView(u,ictx->viewer);CHKERRQ(ierr);
3965   if (ictx->showtimestepandtime) {
3966     PetscReal xl,yl,xr,yr,tw,w,h;
3967     char      time[32];
3968     size_t    len;
3969 
3970     ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
3971     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
3972     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
3973     ierr =  PetscStrlen(time,&len);CHKERRQ(ierr);
3974     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
3975     w    = xl + .5*(xr - xl) - .5*len*tw;
3976     h    = yl + .95*(yr - yl);
3977     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
3978     ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
3979   }
3980 
3981   if (ictx->showinitial) {
3982     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);CHKERRQ(ierr);
3983   }
3984   PetscFunctionReturn(0);
3985 }
3986 
3987 #undef __FUNCT__
3988 #define __FUNCT__ "TSMonitorDrawSolutionPhase"
3989 /*@C
3990    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
3991 
3992    Collective on TS
3993 
3994    Input Parameters:
3995 +  ts - the TS context
3996 .  step - current time-step
3997 .  ptime - current time
3998 -  dummy - either a viewer or NULL
3999 
4000    Level: intermediate
4001 
4002 .keywords: TS,  vector, monitor, view
4003 
4004 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4005 @*/
4006 PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4007 {
4008   PetscErrorCode    ierr;
4009   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4010   PetscDraw         draw;
4011   MPI_Comm          comm;
4012   PetscInt          n;
4013   PetscMPIInt       size;
4014   PetscReal         xl,yl,xr,yr,tw,w,h;
4015   char              time[32];
4016   size_t            len;
4017   const PetscScalar *U;
4018 
4019   PetscFunctionBegin;
4020   ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
4021   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
4022   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
4023   ierr = VecGetSize(u,&n);CHKERRQ(ierr);
4024   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4025 
4026   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4027 
4028   ierr = VecGetArrayRead(u,&U);CHKERRQ(ierr);
4029   ierr = PetscDrawAxisGetLimits(ictx->axis,&xl,&xr,&yl,&yr);CHKERRQ(ierr);
4030   if ((PetscRealPart(U[0]) < xl) || (PetscRealPart(U[1]) < yl) || (PetscRealPart(U[0]) > xr) || (PetscRealPart(U[1]) > yr)) {
4031       ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
4032       PetscFunctionReturn(0);
4033   }
4034   if (!step) ictx->color++;
4035   ierr = PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);CHKERRQ(ierr);
4036   ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
4037 
4038   if (ictx->showtimestepandtime) {
4039     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4040     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
4041     ierr = PetscStrlen(time,&len);CHKERRQ(ierr);
4042     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
4043     w    = xl + .5*(xr - xl) - .5*len*tw;
4044     h    = yl + .95*(yr - yl);
4045     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4046   }
4047   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4048   PetscFunctionReturn(0);
4049 }
4050 
4051 
4052 #undef __FUNCT__
4053 #define __FUNCT__ "TSMonitorDrawCtxDestroy"
4054 /*@C
4055    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4056 
4057    Collective on TS
4058 
4059    Input Parameters:
4060 .    ctx - the monitor context
4061 
4062    Level: intermediate
4063 
4064 .keywords: TS,  vector, monitor, view
4065 
4066 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4067 @*/
4068 PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4069 {
4070   PetscErrorCode ierr;
4071 
4072   PetscFunctionBegin;
4073   ierr = PetscDrawAxisDestroy(&(*ictx)->axis);CHKERRQ(ierr);
4074   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
4075   ierr = VecDestroy(&(*ictx)->initialsolution);CHKERRQ(ierr);
4076   ierr = PetscFree(*ictx);CHKERRQ(ierr);
4077   PetscFunctionReturn(0);
4078 }
4079 
4080 #undef __FUNCT__
4081 #define __FUNCT__ "TSMonitorDrawCtxCreate"
4082 /*@C
4083    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4084 
4085    Collective on TS
4086 
4087    Input Parameter:
4088 .    ts - time-step context
4089 
4090    Output Patameter:
4091 .    ctx - the monitor context
4092 
4093    Options Database:
4094 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4095 
4096    Level: intermediate
4097 
4098 .keywords: TS,  vector, monitor, view
4099 
4100 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4101 @*/
4102 PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4103 {
4104   PetscErrorCode   ierr;
4105 
4106   PetscFunctionBegin;
4107   ierr = PetscNew(ctx);CHKERRQ(ierr);
4108   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
4109   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
4110 
4111   (*ctx)->howoften    = howoften;
4112   (*ctx)->showinitial = PETSC_FALSE;
4113   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);CHKERRQ(ierr);
4114 
4115   (*ctx)->showtimestepandtime = PETSC_FALSE;
4116   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);CHKERRQ(ierr);
4117   (*ctx)->color = PETSC_DRAW_WHITE;
4118   PetscFunctionReturn(0);
4119 }
4120 
4121 #undef __FUNCT__
4122 #define __FUNCT__ "TSMonitorDrawError"
4123 /*@C
4124    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4125    VecView() for the error at each timestep
4126 
4127    Collective on TS
4128 
4129    Input Parameters:
4130 +  ts - the TS context
4131 .  step - current time-step
4132 .  ptime - current time
4133 -  dummy - either a viewer or NULL
4134 
4135    Level: intermediate
4136 
4137 .keywords: TS,  vector, monitor, view
4138 
4139 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4140 @*/
4141 PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4142 {
4143   PetscErrorCode   ierr;
4144   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4145   PetscViewer      viewer = ctx->viewer;
4146   Vec              work;
4147 
4148   PetscFunctionBegin;
4149   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4150   ierr = VecDuplicate(u,&work);CHKERRQ(ierr);
4151   ierr = TSComputeSolutionFunction(ts,ptime,work);CHKERRQ(ierr);
4152   ierr = VecAXPY(work,-1.0,u);CHKERRQ(ierr);
4153   ierr = VecView(work,viewer);CHKERRQ(ierr);
4154   ierr = VecDestroy(&work);CHKERRQ(ierr);
4155   PetscFunctionReturn(0);
4156 }
4157 
4158 #include <petsc-private/dmimpl.h>
4159 #undef __FUNCT__
4160 #define __FUNCT__ "TSSetDM"
4161 /*@
4162    TSSetDM - Sets the DM that may be used by some preconditioners
4163 
4164    Logically Collective on TS and DM
4165 
4166    Input Parameters:
4167 +  ts - the preconditioner context
4168 -  dm - the dm
4169 
4170    Level: intermediate
4171 
4172 
4173 .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4174 @*/
4175 PetscErrorCode  TSSetDM(TS ts,DM dm)
4176 {
4177   PetscErrorCode ierr;
4178   SNES           snes;
4179   DMTS           tsdm;
4180 
4181   PetscFunctionBegin;
4182   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4183   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
4184   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4185     if (ts->dm->dmts && !dm->dmts) {
4186       ierr = DMCopyDMTS(ts->dm,dm);CHKERRQ(ierr);
4187       ierr = DMGetDMTS(ts->dm,&tsdm);CHKERRQ(ierr);
4188       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4189         tsdm->originaldm = dm;
4190       }
4191     }
4192     ierr = DMDestroy(&ts->dm);CHKERRQ(ierr);
4193   }
4194   ts->dm = dm;
4195 
4196   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4197   ierr = SNESSetDM(snes,dm);CHKERRQ(ierr);
4198   PetscFunctionReturn(0);
4199 }
4200 
4201 #undef __FUNCT__
4202 #define __FUNCT__ "TSGetDM"
4203 /*@
4204    TSGetDM - Gets the DM that may be used by some preconditioners
4205 
4206    Not Collective
4207 
4208    Input Parameter:
4209 . ts - the preconditioner context
4210 
4211    Output Parameter:
4212 .  dm - the dm
4213 
4214    Level: intermediate
4215 
4216 
4217 .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4218 @*/
4219 PetscErrorCode  TSGetDM(TS ts,DM *dm)
4220 {
4221   PetscErrorCode ierr;
4222 
4223   PetscFunctionBegin;
4224   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4225   if (!ts->dm) {
4226     ierr = DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);CHKERRQ(ierr);
4227     if (ts->snes) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
4228   }
4229   *dm = ts->dm;
4230   PetscFunctionReturn(0);
4231 }
4232 
4233 #undef __FUNCT__
4234 #define __FUNCT__ "SNESTSFormFunction"
4235 /*@
4236    SNESTSFormFunction - Function to evaluate nonlinear residual
4237 
4238    Logically Collective on SNES
4239 
4240    Input Parameter:
4241 + snes - nonlinear solver
4242 . U - the current state at which to evaluate the residual
4243 - ctx - user context, must be a TS
4244 
4245    Output Parameter:
4246 . F - the nonlinear residual
4247 
4248    Notes:
4249    This function is not normally called by users and is automatically registered with the SNES used by TS.
4250    It is most frequently passed to MatFDColoringSetFunction().
4251 
4252    Level: advanced
4253 
4254 .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4255 @*/
4256 PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4257 {
4258   TS             ts = (TS)ctx;
4259   PetscErrorCode ierr;
4260 
4261   PetscFunctionBegin;
4262   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4263   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4264   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
4265   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
4266   ierr = (ts->ops->snesfunction)(snes,U,F,ts);CHKERRQ(ierr);
4267   PetscFunctionReturn(0);
4268 }
4269 
4270 #undef __FUNCT__
4271 #define __FUNCT__ "SNESTSFormJacobian"
4272 /*@
4273    SNESTSFormJacobian - Function to evaluate the Jacobian
4274 
4275    Collective on SNES
4276 
4277    Input Parameter:
4278 + snes - nonlinear solver
4279 . U - the current state at which to evaluate the residual
4280 - ctx - user context, must be a TS
4281 
4282    Output Parameter:
4283 + A - the Jacobian
4284 . B - the preconditioning matrix (may be the same as A)
4285 - flag - indicates any structure change in the matrix
4286 
4287    Notes:
4288    This function is not normally called by users and is automatically registered with the SNES used by TS.
4289 
4290    Level: developer
4291 
4292 .seealso: SNESSetJacobian()
4293 @*/
4294 PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4295 {
4296   TS             ts = (TS)ctx;
4297   PetscErrorCode ierr;
4298 
4299   PetscFunctionBegin;
4300   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4301   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4302   PetscValidPointer(A,3);
4303   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
4304   PetscValidPointer(B,4);
4305   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
4306   PetscValidHeaderSpecific(ts,TS_CLASSID,6);
4307   ierr = (ts->ops->snesjacobian)(snes,U,A,B,ts);CHKERRQ(ierr);
4308   PetscFunctionReturn(0);
4309 }
4310 
4311 #undef __FUNCT__
4312 #define __FUNCT__ "TSComputeRHSFunctionLinear"
4313 /*@C
4314    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems only
4315 
4316    Collective on TS
4317 
4318    Input Arguments:
4319 +  ts - time stepping context
4320 .  t - time at which to evaluate
4321 .  U - state at which to evaluate
4322 -  ctx - context
4323 
4324    Output Arguments:
4325 .  F - right hand side
4326 
4327    Level: intermediate
4328 
4329    Notes:
4330    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
4331    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
4332 
4333 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
4334 @*/
4335 PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
4336 {
4337   PetscErrorCode ierr;
4338   Mat            Arhs,Brhs;
4339 
4340   PetscFunctionBegin;
4341   ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
4342   ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
4343   ierr = MatMult(Arhs,U,F);CHKERRQ(ierr);
4344   PetscFunctionReturn(0);
4345 }
4346 
4347 #undef __FUNCT__
4348 #define __FUNCT__ "TSComputeRHSJacobianConstant"
4349 /*@C
4350    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
4351 
4352    Collective on TS
4353 
4354    Input Arguments:
4355 +  ts - time stepping context
4356 .  t - time at which to evaluate
4357 .  U - state at which to evaluate
4358 -  ctx - context
4359 
4360    Output Arguments:
4361 +  A - pointer to operator
4362 .  B - pointer to preconditioning matrix
4363 -  flg - matrix structure flag
4364 
4365    Level: intermediate
4366 
4367    Notes:
4368    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
4369 
4370 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
4371 @*/
4372 PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
4373 {
4374   PetscFunctionBegin;
4375   PetscFunctionReturn(0);
4376 }
4377 
4378 #undef __FUNCT__
4379 #define __FUNCT__ "TSComputeIFunctionLinear"
4380 /*@C
4381    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
4382 
4383    Collective on TS
4384 
4385    Input Arguments:
4386 +  ts - time stepping context
4387 .  t - time at which to evaluate
4388 .  U - state at which to evaluate
4389 .  Udot - time derivative of state vector
4390 -  ctx - context
4391 
4392    Output Arguments:
4393 .  F - left hand side
4394 
4395    Level: intermediate
4396 
4397    Notes:
4398    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
4399    user is required to write their own TSComputeIFunction.
4400    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
4401    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
4402 
4403 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
4404 @*/
4405 PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
4406 {
4407   PetscErrorCode ierr;
4408   Mat            A,B;
4409 
4410   PetscFunctionBegin;
4411   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
4412   ierr = TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);CHKERRQ(ierr);
4413   ierr = MatMult(A,Udot,F);CHKERRQ(ierr);
4414   PetscFunctionReturn(0);
4415 }
4416 
4417 #undef __FUNCT__
4418 #define __FUNCT__ "TSComputeIJacobianConstant"
4419 /*@C
4420    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
4421 
4422    Collective on TS
4423 
4424    Input Arguments:
4425 +  ts - time stepping context
4426 .  t - time at which to evaluate
4427 .  U - state at which to evaluate
4428 .  Udot - time derivative of state vector
4429 .  shift - shift to apply
4430 -  ctx - context
4431 
4432    Output Arguments:
4433 +  A - pointer to operator
4434 .  B - pointer to preconditioning matrix
4435 -  flg - matrix structure flag
4436 
4437    Level: advanced
4438 
4439    Notes:
4440    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
4441 
4442    It is only appropriate for problems of the form
4443 
4444 $     M Udot = F(U,t)
4445 
4446   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4447   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4448   an implicit operator of the form
4449 
4450 $    shift*M + J
4451 
4452   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
4453   a copy of M or reassemble it when requested.
4454 
4455 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
4456 @*/
4457 PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
4458 {
4459   PetscErrorCode ierr;
4460 
4461   PetscFunctionBegin;
4462   ierr = MatScale(A, shift / ts->ijacobian.shift);CHKERRQ(ierr);
4463   ts->ijacobian.shift = shift;
4464   PetscFunctionReturn(0);
4465 }
4466 
4467 #undef __FUNCT__
4468 #define __FUNCT__ "TSGetEquationType"
4469 /*@
4470    TSGetEquationType - Gets the type of the equation that TS is solving.
4471 
4472    Not Collective
4473 
4474    Input Parameter:
4475 .  ts - the TS context
4476 
4477    Output Parameter:
4478 .  equation_type - see TSEquationType
4479 
4480    Level: beginner
4481 
4482 .keywords: TS, equation type
4483 
4484 .seealso: TSSetEquationType(), TSEquationType
4485 @*/
4486 PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4487 {
4488   PetscFunctionBegin;
4489   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4490   PetscValidPointer(equation_type,2);
4491   *equation_type = ts->equation_type;
4492   PetscFunctionReturn(0);
4493 }
4494 
4495 #undef __FUNCT__
4496 #define __FUNCT__ "TSSetEquationType"
4497 /*@
4498    TSSetEquationType - Sets the type of the equation that TS is solving.
4499 
4500    Not Collective
4501 
4502    Input Parameter:
4503 +  ts - the TS context
4504 .  equation_type - see TSEquationType
4505 
4506    Level: advanced
4507 
4508 .keywords: TS, equation type
4509 
4510 .seealso: TSGetEquationType(), TSEquationType
4511 @*/
4512 PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4513 {
4514   PetscFunctionBegin;
4515   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4516   ts->equation_type = equation_type;
4517   PetscFunctionReturn(0);
4518 }
4519 
4520 #undef __FUNCT__
4521 #define __FUNCT__ "TSGetConvergedReason"
4522 /*@
4523    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
4524 
4525    Not Collective
4526 
4527    Input Parameter:
4528 .  ts - the TS context
4529 
4530    Output Parameter:
4531 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4532             manual pages for the individual convergence tests for complete lists
4533 
4534    Level: beginner
4535 
4536    Notes:
4537    Can only be called after the call to TSSolve() is complete.
4538 
4539 .keywords: TS, nonlinear, set, convergence, test
4540 
4541 .seealso: TSSetConvergenceTest(), TSConvergedReason
4542 @*/
4543 PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
4544 {
4545   PetscFunctionBegin;
4546   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4547   PetscValidPointer(reason,2);
4548   *reason = ts->reason;
4549   PetscFunctionReturn(0);
4550 }
4551 
4552 #undef __FUNCT__
4553 #define __FUNCT__ "TSSetConvergedReason"
4554 /*@
4555    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
4556 
4557    Not Collective
4558 
4559    Input Parameter:
4560 +  ts - the TS context
4561 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4562             manual pages for the individual convergence tests for complete lists
4563 
4564    Level: advanced
4565 
4566    Notes:
4567    Can only be called during TSSolve() is active.
4568 
4569 .keywords: TS, nonlinear, set, convergence, test
4570 
4571 .seealso: TSConvergedReason
4572 @*/
4573 PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4574 {
4575   PetscFunctionBegin;
4576   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4577   ts->reason = reason;
4578   PetscFunctionReturn(0);
4579 }
4580 
4581 #undef __FUNCT__
4582 #define __FUNCT__ "TSGetSolveTime"
4583 /*@
4584    TSGetSolveTime - Gets the time after a call to TSSolve()
4585 
4586    Not Collective
4587 
4588    Input Parameter:
4589 .  ts - the TS context
4590 
4591    Output Parameter:
4592 .  ftime - the final time. This time should correspond to the final time set with TSSetDuration()
4593 
4594    Level: beginner
4595 
4596    Notes:
4597    Can only be called after the call to TSSolve() is complete.
4598 
4599 .keywords: TS, nonlinear, set, convergence, test
4600 
4601 .seealso: TSSetConvergenceTest(), TSConvergedReason
4602 @*/
4603 PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4604 {
4605   PetscFunctionBegin;
4606   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4607   PetscValidPointer(ftime,2);
4608   *ftime = ts->solvetime;
4609   PetscFunctionReturn(0);
4610 }
4611 
4612 #undef __FUNCT__
4613 #define __FUNCT__ "TSGetTotalSteps"
4614 /*@
4615    TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()
4616 
4617    Not Collective
4618 
4619    Input Parameter:
4620 .  ts - the TS context
4621 
4622    Output Parameter:
4623 .  steps - the number of steps
4624 
4625    Level: beginner
4626 
4627    Notes:
4628    Includes the number of steps for all calls to TSSolve() since TSSetUp() was called
4629 
4630 .keywords: TS, nonlinear, set, convergence, test
4631 
4632 .seealso: TSSetConvergenceTest(), TSConvergedReason
4633 @*/
4634 PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
4635 {
4636   PetscFunctionBegin;
4637   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4638   PetscValidPointer(steps,2);
4639   *steps = ts->total_steps;
4640   PetscFunctionReturn(0);
4641 }
4642 
4643 #undef __FUNCT__
4644 #define __FUNCT__ "TSGetSNESIterations"
4645 /*@
4646    TSGetSNESIterations - Gets the total number of nonlinear iterations
4647    used by the time integrator.
4648 
4649    Not Collective
4650 
4651    Input Parameter:
4652 .  ts - TS context
4653 
4654    Output Parameter:
4655 .  nits - number of nonlinear iterations
4656 
4657    Notes:
4658    This counter is reset to zero for each successive call to TSSolve().
4659 
4660    Level: intermediate
4661 
4662 .keywords: TS, get, number, nonlinear, iterations
4663 
4664 .seealso:  TSGetKSPIterations()
4665 @*/
4666 PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
4667 {
4668   PetscFunctionBegin;
4669   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4670   PetscValidIntPointer(nits,2);
4671   *nits = ts->snes_its;
4672   PetscFunctionReturn(0);
4673 }
4674 
4675 #undef __FUNCT__
4676 #define __FUNCT__ "TSGetKSPIterations"
4677 /*@
4678    TSGetKSPIterations - Gets the total number of linear iterations
4679    used by the time integrator.
4680 
4681    Not Collective
4682 
4683    Input Parameter:
4684 .  ts - TS context
4685 
4686    Output Parameter:
4687 .  lits - number of linear iterations
4688 
4689    Notes:
4690    This counter is reset to zero for each successive call to TSSolve().
4691 
4692    Level: intermediate
4693 
4694 .keywords: TS, get, number, linear, iterations
4695 
4696 .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
4697 @*/
4698 PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
4699 {
4700   PetscFunctionBegin;
4701   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4702   PetscValidIntPointer(lits,2);
4703   *lits = ts->ksp_its;
4704   PetscFunctionReturn(0);
4705 }
4706 
4707 #undef __FUNCT__
4708 #define __FUNCT__ "TSGetStepRejections"
4709 /*@
4710    TSGetStepRejections - Gets the total number of rejected steps.
4711 
4712    Not Collective
4713 
4714    Input Parameter:
4715 .  ts - TS context
4716 
4717    Output Parameter:
4718 .  rejects - number of steps rejected
4719 
4720    Notes:
4721    This counter is reset to zero for each successive call to TSSolve().
4722 
4723    Level: intermediate
4724 
4725 .keywords: TS, get, number
4726 
4727 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
4728 @*/
4729 PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4730 {
4731   PetscFunctionBegin;
4732   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4733   PetscValidIntPointer(rejects,2);
4734   *rejects = ts->reject;
4735   PetscFunctionReturn(0);
4736 }
4737 
4738 #undef __FUNCT__
4739 #define __FUNCT__ "TSGetSNESFailures"
4740 /*@
4741    TSGetSNESFailures - Gets the total number of failed SNES solves
4742 
4743    Not Collective
4744 
4745    Input Parameter:
4746 .  ts - TS context
4747 
4748    Output Parameter:
4749 .  fails - number of failed nonlinear solves
4750 
4751    Notes:
4752    This counter is reset to zero for each successive call to TSSolve().
4753 
4754    Level: intermediate
4755 
4756 .keywords: TS, get, number
4757 
4758 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
4759 @*/
4760 PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4761 {
4762   PetscFunctionBegin;
4763   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4764   PetscValidIntPointer(fails,2);
4765   *fails = ts->num_snes_failures;
4766   PetscFunctionReturn(0);
4767 }
4768 
4769 #undef __FUNCT__
4770 #define __FUNCT__ "TSSetMaxStepRejections"
4771 /*@
4772    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
4773 
4774    Not Collective
4775 
4776    Input Parameter:
4777 +  ts - TS context
4778 -  rejects - maximum number of rejected steps, pass -1 for unlimited
4779 
4780    Notes:
4781    The counter is reset to zero for each step
4782 
4783    Options Database Key:
4784  .  -ts_max_reject - Maximum number of step rejections before a step fails
4785 
4786    Level: intermediate
4787 
4788 .keywords: TS, set, maximum, number
4789 
4790 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4791 @*/
4792 PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4793 {
4794   PetscFunctionBegin;
4795   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4796   ts->max_reject = rejects;
4797   PetscFunctionReturn(0);
4798 }
4799 
4800 #undef __FUNCT__
4801 #define __FUNCT__ "TSSetMaxSNESFailures"
4802 /*@
4803    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
4804 
4805    Not Collective
4806 
4807    Input Parameter:
4808 +  ts - TS context
4809 -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4810 
4811    Notes:
4812    The counter is reset to zero for each successive call to TSSolve().
4813 
4814    Options Database Key:
4815  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4816 
4817    Level: intermediate
4818 
4819 .keywords: TS, set, maximum, number
4820 
4821 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4822 @*/
4823 PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4824 {
4825   PetscFunctionBegin;
4826   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4827   ts->max_snes_failures = fails;
4828   PetscFunctionReturn(0);
4829 }
4830 
4831 #undef __FUNCT__
4832 #define __FUNCT__ "TSSetErrorIfStepFails"
4833 /*@
4834    TSSetErrorIfStepFails - Error if no step succeeds
4835 
4836    Not Collective
4837 
4838    Input Parameter:
4839 +  ts - TS context
4840 -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
4841 
4842    Options Database Key:
4843  .  -ts_error_if_step_fails - Error if no step succeeds
4844 
4845    Level: intermediate
4846 
4847 .keywords: TS, set, error
4848 
4849 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4850 @*/
4851 PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4852 {
4853   PetscFunctionBegin;
4854   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4855   ts->errorifstepfailed = err;
4856   PetscFunctionReturn(0);
4857 }
4858 
4859 #undef __FUNCT__
4860 #define __FUNCT__ "TSMonitorSolutionBinary"
4861 /*@C
4862    TSMonitorSolutionBinary - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file
4863 
4864    Collective on TS
4865 
4866    Input Parameters:
4867 +  ts - the TS context
4868 .  step - current time-step
4869 .  ptime - current time
4870 .  u - current state
4871 -  viewer - binary viewer
4872 
4873    Level: intermediate
4874 
4875 .keywords: TS,  vector, monitor, view
4876 
4877 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4878 @*/
4879 PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
4880 {
4881   PetscErrorCode ierr;
4882   PetscViewer    v = (PetscViewer)viewer;
4883 
4884   PetscFunctionBegin;
4885   ierr = VecView(u,v);CHKERRQ(ierr);
4886   PetscFunctionReturn(0);
4887 }
4888 
4889 #undef __FUNCT__
4890 #define __FUNCT__ "TSMonitorSolutionVTK"
4891 /*@C
4892    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
4893 
4894    Collective on TS
4895 
4896    Input Parameters:
4897 +  ts - the TS context
4898 .  step - current time-step
4899 .  ptime - current time
4900 .  u - current state
4901 -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
4902 
4903    Level: intermediate
4904 
4905    Notes:
4906    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.
4907    These are named according to the file name template.
4908 
4909    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
4910 
4911 .keywords: TS,  vector, monitor, view
4912 
4913 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4914 @*/
4915 PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
4916 {
4917   PetscErrorCode ierr;
4918   char           filename[PETSC_MAX_PATH_LEN];
4919   PetscViewer    viewer;
4920 
4921   PetscFunctionBegin;
4922   ierr = PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);CHKERRQ(ierr);
4923   ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);
4924   ierr = VecView(u,viewer);CHKERRQ(ierr);
4925   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
4926   PetscFunctionReturn(0);
4927 }
4928 
4929 #undef __FUNCT__
4930 #define __FUNCT__ "TSMonitorSolutionVTKDestroy"
4931 /*@C
4932    TSMonitorSolutionVTKDestroy - Destroy context for monitoring
4933 
4934    Collective on TS
4935 
4936    Input Parameters:
4937 .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
4938 
4939    Level: intermediate
4940 
4941    Note:
4942    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
4943 
4944 .keywords: TS,  vector, monitor, view
4945 
4946 .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
4947 @*/
4948 PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
4949 {
4950   PetscErrorCode ierr;
4951 
4952   PetscFunctionBegin;
4953   ierr = PetscFree(*(char**)filenametemplate);CHKERRQ(ierr);
4954   PetscFunctionReturn(0);
4955 }
4956 
4957 #undef __FUNCT__
4958 #define __FUNCT__ "TSGetAdapt"
4959 /*@
4960    TSGetAdapt - Get the adaptive controller context for the current method
4961 
4962    Collective on TS if controller has not been created yet
4963 
4964    Input Arguments:
4965 .  ts - time stepping context
4966 
4967    Output Arguments:
4968 .  adapt - adaptive controller
4969 
4970    Level: intermediate
4971 
4972 .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4973 @*/
4974 PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4975 {
4976   PetscErrorCode ierr;
4977 
4978   PetscFunctionBegin;
4979   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4980   PetscValidPointer(adapt,2);
4981   if (!ts->adapt) {
4982     ierr = TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);CHKERRQ(ierr);
4983     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);CHKERRQ(ierr);
4984     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);CHKERRQ(ierr);
4985   }
4986   *adapt = ts->adapt;
4987   PetscFunctionReturn(0);
4988 }
4989 
4990 #undef __FUNCT__
4991 #define __FUNCT__ "TSSetTolerances"
4992 /*@
4993    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
4994 
4995    Logically Collective
4996 
4997    Input Arguments:
4998 +  ts - time integration context
4999 .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5000 .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5001 .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5002 -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5003 
5004    Options Database keys:
5005 +  -ts_rtol <rtol> - relative tolerance for local truncation error
5006 -  -ts_atol <atol> Absolute tolerance for local truncation error
5007 
5008    Level: beginner
5009 
5010 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5011 @*/
5012 PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5013 {
5014   PetscErrorCode ierr;
5015 
5016   PetscFunctionBegin;
5017   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5018   if (vatol) {
5019     ierr = PetscObjectReference((PetscObject)vatol);CHKERRQ(ierr);
5020     ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
5021 
5022     ts->vatol = vatol;
5023   }
5024   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5025   if (vrtol) {
5026     ierr = PetscObjectReference((PetscObject)vrtol);CHKERRQ(ierr);
5027     ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
5028 
5029     ts->vrtol = vrtol;
5030   }
5031   PetscFunctionReturn(0);
5032 }
5033 
5034 #undef __FUNCT__
5035 #define __FUNCT__ "TSGetTolerances"
5036 /*@
5037    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5038 
5039    Logically Collective
5040 
5041    Input Arguments:
5042 .  ts - time integration context
5043 
5044    Output Arguments:
5045 +  atol - scalar absolute tolerances, NULL to ignore
5046 .  vatol - vector of absolute tolerances, NULL to ignore
5047 .  rtol - scalar relative tolerances, NULL to ignore
5048 -  vrtol - vector of relative tolerances, NULL to ignore
5049 
5050    Level: beginner
5051 
5052 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5053 @*/
5054 PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5055 {
5056   PetscFunctionBegin;
5057   if (atol)  *atol  = ts->atol;
5058   if (vatol) *vatol = ts->vatol;
5059   if (rtol)  *rtol  = ts->rtol;
5060   if (vrtol) *vrtol = ts->vrtol;
5061   PetscFunctionReturn(0);
5062 }
5063 
5064 #undef __FUNCT__
5065 #define __FUNCT__ "TSErrorNormWRMS"
5066 /*@
5067    TSErrorNormWRMS - compute a weighted norm of the difference between a vector and the current state
5068 
5069    Collective on TS
5070 
5071    Input Arguments:
5072 +  ts - time stepping context
5073 -  Y - state vector to be compared to ts->vec_sol
5074 
5075    Output Arguments:
5076 .  norm - weighted norm, a value of 1.0 is considered small
5077 
5078    Level: developer
5079 
5080 .seealso: TSSetTolerances()
5081 @*/
5082 PetscErrorCode TSErrorNormWRMS(TS ts,Vec Y,PetscReal *norm)
5083 {
5084   PetscErrorCode    ierr;
5085   PetscInt          i,n,N;
5086   const PetscScalar *u,*y;
5087   Vec               U;
5088   PetscReal         sum,gsum;
5089 
5090   PetscFunctionBegin;
5091   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5092   PetscValidHeaderSpecific(Y,VEC_CLASSID,2);
5093   PetscValidPointer(norm,3);
5094   U = ts->vec_sol;
5095   PetscCheckSameTypeAndComm(U,1,Y,2);
5096   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"Y cannot be the TS solution vector");
5097 
5098   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
5099   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
5100   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
5101   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
5102   sum  = 0.;
5103   if (ts->vatol && ts->vrtol) {
5104     const PetscScalar *atol,*rtol;
5105     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5106     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5107     for (i=0; i<n; i++) {
5108       PetscReal tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5109       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5110     }
5111     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5112     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5113   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5114     const PetscScalar *atol;
5115     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5116     for (i=0; i<n; i++) {
5117       PetscReal tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5118       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5119     }
5120     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5121   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5122     const PetscScalar *rtol;
5123     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5124     for (i=0; i<n; i++) {
5125       PetscReal tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5126       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5127     }
5128     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5129   } else {                      /* scalar atol, scalar rtol */
5130     for (i=0; i<n; i++) {
5131       PetscReal tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5132       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5133     }
5134   }
5135   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
5136   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
5137 
5138   ierr  = MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
5139   *norm = PetscSqrtReal(gsum / N);
5140   if (PetscIsInfOrNanReal(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5141   PetscFunctionReturn(0);
5142 }
5143 
5144 #undef __FUNCT__
5145 #define __FUNCT__ "TSSetCFLTimeLocal"
5146 /*@
5147    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
5148 
5149    Logically Collective on TS
5150 
5151    Input Arguments:
5152 +  ts - time stepping context
5153 -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
5154 
5155    Note:
5156    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
5157 
5158    Level: intermediate
5159 
5160 .seealso: TSGetCFLTime(), TSADAPTCFL
5161 @*/
5162 PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
5163 {
5164   PetscFunctionBegin;
5165   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5166   ts->cfltime_local = cfltime;
5167   ts->cfltime       = -1.;
5168   PetscFunctionReturn(0);
5169 }
5170 
5171 #undef __FUNCT__
5172 #define __FUNCT__ "TSGetCFLTime"
5173 /*@
5174    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
5175 
5176    Collective on TS
5177 
5178    Input Arguments:
5179 .  ts - time stepping context
5180 
5181    Output Arguments:
5182 .  cfltime - maximum stable time step for forward Euler
5183 
5184    Level: advanced
5185 
5186 .seealso: TSSetCFLTimeLocal()
5187 @*/
5188 PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
5189 {
5190   PetscErrorCode ierr;
5191 
5192   PetscFunctionBegin;
5193   if (ts->cfltime < 0) {
5194     ierr = MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
5195   }
5196   *cfltime = ts->cfltime;
5197   PetscFunctionReturn(0);
5198 }
5199 
5200 #undef __FUNCT__
5201 #define __FUNCT__ "TSVISetVariableBounds"
5202 /*@
5203    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5204 
5205    Input Parameters:
5206 .  ts   - the TS context.
5207 .  xl   - lower bound.
5208 .  xu   - upper bound.
5209 
5210    Notes:
5211    If this routine is not called then the lower and upper bounds are set to
5212    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
5213 
5214    Level: advanced
5215 
5216 @*/
5217 PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5218 {
5219   PetscErrorCode ierr;
5220   SNES           snes;
5221 
5222   PetscFunctionBegin;
5223   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
5224   ierr = SNESVISetVariableBounds(snes,xl,xu);CHKERRQ(ierr);
5225   PetscFunctionReturn(0);
5226 }
5227 
5228 #if defined(PETSC_HAVE_MATLAB_ENGINE)
5229 #include <mex.h>
5230 
5231 typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
5232 
5233 #undef __FUNCT__
5234 #define __FUNCT__ "TSComputeFunction_Matlab"
5235 /*
5236    TSComputeFunction_Matlab - Calls the function that has been set with
5237                          TSSetFunctionMatlab().
5238 
5239    Collective on TS
5240 
5241    Input Parameters:
5242 +  snes - the TS context
5243 -  u - input vector
5244 
5245    Output Parameter:
5246 .  y - function vector, as set by TSSetFunction()
5247 
5248    Notes:
5249    TSComputeFunction() is typically used within nonlinear solvers
5250    implementations, so most users would not generally call this routine
5251    themselves.
5252 
5253    Level: developer
5254 
5255 .keywords: TS, nonlinear, compute, function
5256 
5257 .seealso: TSSetFunction(), TSGetFunction()
5258 */
5259 PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
5260 {
5261   PetscErrorCode  ierr;
5262   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5263   int             nlhs  = 1,nrhs = 7;
5264   mxArray         *plhs[1],*prhs[7];
5265   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;
5266 
5267   PetscFunctionBegin;
5268   PetscValidHeaderSpecific(snes,TS_CLASSID,1);
5269   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
5270   PetscValidHeaderSpecific(udot,VEC_CLASSID,4);
5271   PetscValidHeaderSpecific(y,VEC_CLASSID,5);
5272   PetscCheckSameComm(snes,1,u,3);
5273   PetscCheckSameComm(snes,1,y,5);
5274 
5275   ierr = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
5276   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5277   ierr = PetscMemcpy(&lxdot,&udot,sizeof(udot));CHKERRQ(ierr);
5278   ierr = PetscMemcpy(&ly,&y,sizeof(u));CHKERRQ(ierr);
5279 
5280   prhs[0] =  mxCreateDoubleScalar((double)ls);
5281   prhs[1] =  mxCreateDoubleScalar(time);
5282   prhs[2] =  mxCreateDoubleScalar((double)lx);
5283   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5284   prhs[4] =  mxCreateDoubleScalar((double)ly);
5285   prhs[5] =  mxCreateString(sctx->funcname);
5286   prhs[6] =  sctx->ctx;
5287   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");CHKERRQ(ierr);
5288   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5289   mxDestroyArray(prhs[0]);
5290   mxDestroyArray(prhs[1]);
5291   mxDestroyArray(prhs[2]);
5292   mxDestroyArray(prhs[3]);
5293   mxDestroyArray(prhs[4]);
5294   mxDestroyArray(prhs[5]);
5295   mxDestroyArray(plhs[0]);
5296   PetscFunctionReturn(0);
5297 }
5298 
5299 
5300 #undef __FUNCT__
5301 #define __FUNCT__ "TSSetFunctionMatlab"
5302 /*
5303    TSSetFunctionMatlab - Sets the function evaluation routine and function
5304    vector for use by the TS routines in solving ODEs
5305    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
5306 
5307    Logically Collective on TS
5308 
5309    Input Parameters:
5310 +  ts - the TS context
5311 -  func - function evaluation routine
5312 
5313    Calling sequence of func:
5314 $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
5315 
5316    Level: beginner
5317 
5318 .keywords: TS, nonlinear, set, function
5319 
5320 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5321 */
5322 PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
5323 {
5324   PetscErrorCode  ierr;
5325   TSMatlabContext *sctx;
5326 
5327   PetscFunctionBegin;
5328   /* currently sctx is memory bleed */
5329   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5330   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5331   /*
5332      This should work, but it doesn't
5333   sctx->ctx = ctx;
5334   mexMakeArrayPersistent(sctx->ctx);
5335   */
5336   sctx->ctx = mxDuplicateArray(ctx);
5337 
5338   ierr = TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);CHKERRQ(ierr);
5339   PetscFunctionReturn(0);
5340 }
5341 
5342 #undef __FUNCT__
5343 #define __FUNCT__ "TSComputeJacobian_Matlab"
5344 /*
5345    TSComputeJacobian_Matlab - Calls the function that has been set with
5346                          TSSetJacobianMatlab().
5347 
5348    Collective on TS
5349 
5350    Input Parameters:
5351 +  ts - the TS context
5352 .  u - input vector
5353 .  A, B - the matrices
5354 -  ctx - user context
5355 
5356    Level: developer
5357 
5358 .keywords: TS, nonlinear, compute, function
5359 
5360 .seealso: TSSetFunction(), TSGetFunction()
5361 @*/
5362 PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
5363 {
5364   PetscErrorCode  ierr;
5365   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5366   int             nlhs  = 2,nrhs = 9;
5367   mxArray         *plhs[2],*prhs[9];
5368   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
5369 
5370   PetscFunctionBegin;
5371   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5372   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
5373 
5374   /* call Matlab function in ctx with arguments u and y */
5375 
5376   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
5377   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5378   ierr = PetscMemcpy(&lxdot,&udot,sizeof(u));CHKERRQ(ierr);
5379   ierr = PetscMemcpy(&lA,A,sizeof(u));CHKERRQ(ierr);
5380   ierr = PetscMemcpy(&lB,B,sizeof(u));CHKERRQ(ierr);
5381 
5382   prhs[0] =  mxCreateDoubleScalar((double)ls);
5383   prhs[1] =  mxCreateDoubleScalar((double)time);
5384   prhs[2] =  mxCreateDoubleScalar((double)lx);
5385   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5386   prhs[4] =  mxCreateDoubleScalar((double)shift);
5387   prhs[5] =  mxCreateDoubleScalar((double)lA);
5388   prhs[6] =  mxCreateDoubleScalar((double)lB);
5389   prhs[7] =  mxCreateString(sctx->funcname);
5390   prhs[8] =  sctx->ctx;
5391   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");CHKERRQ(ierr);
5392   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5393   mxDestroyArray(prhs[0]);
5394   mxDestroyArray(prhs[1]);
5395   mxDestroyArray(prhs[2]);
5396   mxDestroyArray(prhs[3]);
5397   mxDestroyArray(prhs[4]);
5398   mxDestroyArray(prhs[5]);
5399   mxDestroyArray(prhs[6]);
5400   mxDestroyArray(prhs[7]);
5401   mxDestroyArray(plhs[0]);
5402   mxDestroyArray(plhs[1]);
5403   PetscFunctionReturn(0);
5404 }
5405 
5406 
5407 #undef __FUNCT__
5408 #define __FUNCT__ "TSSetJacobianMatlab"
5409 /*
5410    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5411    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
5412 
5413    Logically Collective on TS
5414 
5415    Input Parameters:
5416 +  ts - the TS context
5417 .  A,B - Jacobian matrices
5418 .  func - function evaluation routine
5419 -  ctx - user context
5420 
5421    Calling sequence of func:
5422 $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
5423 
5424 
5425    Level: developer
5426 
5427 .keywords: TS, nonlinear, set, function
5428 
5429 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5430 */
5431 PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
5432 {
5433   PetscErrorCode  ierr;
5434   TSMatlabContext *sctx;
5435 
5436   PetscFunctionBegin;
5437   /* currently sctx is memory bleed */
5438   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5439   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5440   /*
5441      This should work, but it doesn't
5442   sctx->ctx = ctx;
5443   mexMakeArrayPersistent(sctx->ctx);
5444   */
5445   sctx->ctx = mxDuplicateArray(ctx);
5446 
5447   ierr = TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
5448   PetscFunctionReturn(0);
5449 }
5450 
5451 #undef __FUNCT__
5452 #define __FUNCT__ "TSMonitor_Matlab"
5453 /*
5454    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
5455 
5456    Collective on TS
5457 
5458 .seealso: TSSetFunction(), TSGetFunction()
5459 @*/
5460 PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
5461 {
5462   PetscErrorCode  ierr;
5463   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5464   int             nlhs  = 1,nrhs = 6;
5465   mxArray         *plhs[1],*prhs[6];
5466   long long int   lx = 0,ls = 0;
5467 
5468   PetscFunctionBegin;
5469   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5470   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
5471 
5472   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
5473   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5474 
5475   prhs[0] =  mxCreateDoubleScalar((double)ls);
5476   prhs[1] =  mxCreateDoubleScalar((double)it);
5477   prhs[2] =  mxCreateDoubleScalar((double)time);
5478   prhs[3] =  mxCreateDoubleScalar((double)lx);
5479   prhs[4] =  mxCreateString(sctx->funcname);
5480   prhs[5] =  sctx->ctx;
5481   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");CHKERRQ(ierr);
5482   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5483   mxDestroyArray(prhs[0]);
5484   mxDestroyArray(prhs[1]);
5485   mxDestroyArray(prhs[2]);
5486   mxDestroyArray(prhs[3]);
5487   mxDestroyArray(prhs[4]);
5488   mxDestroyArray(plhs[0]);
5489   PetscFunctionReturn(0);
5490 }
5491 
5492 
5493 #undef __FUNCT__
5494 #define __FUNCT__ "TSMonitorSetMatlab"
5495 /*
5496    TSMonitorSetMatlab - Sets the monitor function from Matlab
5497 
5498    Level: developer
5499 
5500 .keywords: TS, nonlinear, set, function
5501 
5502 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5503 */
5504 PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
5505 {
5506   PetscErrorCode  ierr;
5507   TSMatlabContext *sctx;
5508 
5509   PetscFunctionBegin;
5510   /* currently sctx is memory bleed */
5511   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5512   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5513   /*
5514      This should work, but it doesn't
5515   sctx->ctx = ctx;
5516   mexMakeArrayPersistent(sctx->ctx);
5517   */
5518   sctx->ctx = mxDuplicateArray(ctx);
5519 
5520   ierr = TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
5521   PetscFunctionReturn(0);
5522 }
5523 #endif
5524 
5525 
5526 
5527 #undef __FUNCT__
5528 #define __FUNCT__ "TSMonitorLGSolution"
5529 /*@C
5530    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
5531        in a time based line graph
5532 
5533    Collective on TS
5534 
5535    Input Parameters:
5536 +  ts - the TS context
5537 .  step - current time-step
5538 .  ptime - current time
5539 -  lg - a line graph object
5540 
5541    Level: intermediate
5542 
5543     Notes: each process in a parallel run displays its component solutions in a separate window
5544 
5545 .keywords: TS,  vector, monitor, view
5546 
5547 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5548 @*/
5549 PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5550 {
5551   PetscErrorCode    ierr;
5552   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5553   const PetscScalar *yy;
5554   PetscInt          dim;
5555 
5556   PetscFunctionBegin;
5557   if (!step) {
5558     PetscDrawAxis axis;
5559     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5560     ierr = PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");CHKERRQ(ierr);
5561     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
5562     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
5563     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5564   }
5565   ierr = VecGetArrayRead(u,&yy);CHKERRQ(ierr);
5566 #if defined(PETSC_USE_COMPLEX)
5567   {
5568     PetscReal *yreal;
5569     PetscInt  i,n;
5570     ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr);
5571     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
5572     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5573     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
5574     ierr = PetscFree(yreal);CHKERRQ(ierr);
5575   }
5576 #else
5577   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
5578 #endif
5579   ierr = VecRestoreArrayRead(u,&yy);CHKERRQ(ierr);
5580   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5581     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5582   }
5583   PetscFunctionReturn(0);
5584 }
5585 
5586 #undef __FUNCT__
5587 #define __FUNCT__ "TSMonitorLGError"
5588 /*@C
5589    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
5590        in a time based line graph
5591 
5592    Collective on TS
5593 
5594    Input Parameters:
5595 +  ts - the TS context
5596 .  step - current time-step
5597 .  ptime - current time
5598 -  lg - a line graph object
5599 
5600    Level: intermediate
5601 
5602    Notes:
5603    Only for sequential solves.
5604 
5605    The user must provide the solution using TSSetSolutionFunction() to use this monitor.
5606 
5607    Options Database Keys:
5608 .  -ts_monitor_lg_error - create a graphical monitor of error history
5609 
5610 .keywords: TS,  vector, monitor, view
5611 
5612 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
5613 @*/
5614 PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5615 {
5616   PetscErrorCode    ierr;
5617   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5618   const PetscScalar *yy;
5619   Vec               y;
5620   PetscInt          dim;
5621 
5622   PetscFunctionBegin;
5623   if (!step) {
5624     PetscDrawAxis axis;
5625     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5626     ierr = PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");CHKERRQ(ierr);
5627     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
5628     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
5629     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5630   }
5631   ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
5632   ierr = TSComputeSolutionFunction(ts,ptime,y);CHKERRQ(ierr);
5633   ierr = VecAXPY(y,-1.0,u);CHKERRQ(ierr);
5634   ierr = VecGetArrayRead(y,&yy);CHKERRQ(ierr);
5635 #if defined(PETSC_USE_COMPLEX)
5636   {
5637     PetscReal *yreal;
5638     PetscInt  i,n;
5639     ierr = VecGetLocalSize(y,&n);CHKERRQ(ierr);
5640     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
5641     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5642     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
5643     ierr = PetscFree(yreal);CHKERRQ(ierr);
5644   }
5645 #else
5646   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
5647 #endif
5648   ierr = VecRestoreArrayRead(y,&yy);CHKERRQ(ierr);
5649   ierr = VecDestroy(&y);CHKERRQ(ierr);
5650   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5651     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5652   }
5653   PetscFunctionReturn(0);
5654 }
5655 
5656 #undef __FUNCT__
5657 #define __FUNCT__ "TSMonitorLGSNESIterations"
5658 PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5659 {
5660   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5661   PetscReal      x   = ptime,y;
5662   PetscErrorCode ierr;
5663   PetscInt       its;
5664 
5665   PetscFunctionBegin;
5666   if (!n) {
5667     PetscDrawAxis axis;
5668 
5669     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5670     ierr = PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");CHKERRQ(ierr);
5671     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5672 
5673     ctx->snes_its = 0;
5674   }
5675   ierr = TSGetSNESIterations(ts,&its);CHKERRQ(ierr);
5676   y    = its - ctx->snes_its;
5677   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
5678   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5679     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5680   }
5681   ctx->snes_its = its;
5682   PetscFunctionReturn(0);
5683 }
5684 
5685 #undef __FUNCT__
5686 #define __FUNCT__ "TSMonitorLGKSPIterations"
5687 PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5688 {
5689   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5690   PetscReal      x   = ptime,y;
5691   PetscErrorCode ierr;
5692   PetscInt       its;
5693 
5694   PetscFunctionBegin;
5695   if (!n) {
5696     PetscDrawAxis axis;
5697 
5698     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5699     ierr = PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");CHKERRQ(ierr);
5700     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5701 
5702     ctx->ksp_its = 0;
5703   }
5704   ierr = TSGetKSPIterations(ts,&its);CHKERRQ(ierr);
5705   y    = its - ctx->ksp_its;
5706   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
5707   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5708     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5709   }
5710   ctx->ksp_its = its;
5711   PetscFunctionReturn(0);
5712 }
5713 
5714 #undef __FUNCT__
5715 #define __FUNCT__ "TSComputeLinearStability"
5716 /*@
5717    TSComputeLinearStability - computes the linear stability function at a point
5718 
5719    Collective on TS and Vec
5720 
5721    Input Parameters:
5722 +  ts - the TS context
5723 -  xr,xi - real and imaginary part of input arguments
5724 
5725    Output Parameters:
5726 .  yr,yi - real and imaginary part of function value
5727 
5728    Level: developer
5729 
5730 .keywords: TS, compute
5731 
5732 .seealso: TSSetRHSFunction(), TSComputeIFunction()
5733 @*/
5734 PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
5735 {
5736   PetscErrorCode ierr;
5737 
5738   PetscFunctionBegin;
5739   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5740   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
5741   ierr = (*ts->ops->linearstability)(ts,xr,xi,yr,yi);CHKERRQ(ierr);
5742   PetscFunctionReturn(0);
5743 }
5744 
5745 #undef __FUNCT__
5746 #define __FUNCT__ "TSRollBack"
5747 /*@
5748    TSRollBack - Rolls back one time step
5749 
5750    Collective on TS
5751 
5752    Input Parameter:
5753 .  ts - the TS context obtained from TSCreate()
5754 
5755    Level: advanced
5756 
5757 .keywords: TS, timestep, rollback
5758 
5759 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
5760 @*/
5761 PetscErrorCode  TSRollBack(TS ts)
5762 {
5763   PetscErrorCode ierr;
5764 
5765   PetscFunctionBegin;
5766   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5767 
5768   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
5769   ierr = (*ts->ops->rollback)(ts);CHKERRQ(ierr);
5770   ts->time_step = ts->ptime - ts->ptime_prev;
5771   ts->ptime = ts->ptime_prev;
5772   PetscFunctionReturn(0);
5773 }
5774 
5775 #undef __FUNCT__
5776 #define __FUNCT__ "TSGetStages"
5777 /*@
5778    TSGetStages - Get the number of stages and stage values
5779 
5780    Input Parameter:
5781 .  ts - the TS context obtained from TSCreate()
5782 
5783    Level: advanced
5784 
5785 .keywords: TS, getstages
5786 
5787 .seealso: TSCreate()
5788 @*/
5789 PetscErrorCode  TSGetStages(TS ts,PetscInt *ns, Vec **Y)
5790 {
5791   PetscErrorCode ierr;
5792 
5793   PetscFunctionBegin;
5794   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5795   PetscValidPointer(ns,2);
5796 
5797   if (!ts->ops->getstages) *ns=0;
5798   else {
5799     ierr = (*ts->ops->getstages)(ts,ns,Y);CHKERRQ(ierr);
5800   }
5801   PetscFunctionReturn(0);
5802 }
5803 
5804