xref: /petsc/src/ts/interface/ts.c (revision 08c7845f0c2a2e52d986918e331abfc731af709e)
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   if (!((PetscObject)ts)->type_name) {
1840     ierr = TSSetType(ts,TSEULER);CHKERRQ(ierr);
1841   }
1842 
1843   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
1844 
1845 
1846   ierr = TSGetAdapt(ts,&ts->adapt);CHKERRQ(ierr);
1847 
1848   if (ts->rhsjacobian.reuse) {
1849     Mat Amat,Pmat;
1850     SNES snes;
1851     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1852     ierr = SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);CHKERRQ(ierr);
1853     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
1854      * have displaced the RHS matrix */
1855     if (Amat == ts->Arhs) {
1856       ierr = MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);CHKERRQ(ierr);
1857       ierr = SNESSetJacobian(snes,Amat,NULL,NULL,NULL);CHKERRQ(ierr);
1858       ierr = MatDestroy(&Amat);CHKERRQ(ierr);
1859     }
1860     if (Pmat == ts->Brhs) {
1861       ierr = MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);CHKERRQ(ierr);
1862       ierr = SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);CHKERRQ(ierr);
1863       ierr = MatDestroy(&Pmat);CHKERRQ(ierr);
1864     }
1865   }
1866   if (ts->ops->setup) {
1867     ierr = (*ts->ops->setup)(ts);CHKERRQ(ierr);
1868   }
1869 
1870   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
1871    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
1872    */
1873   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1874   ierr = DMSNESGetFunction(dm,&func,NULL);CHKERRQ(ierr);
1875   if (!func) {
1876     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);CHKERRQ(ierr);
1877   }
1878   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
1879      Otherwise, the SNES will use coloring internally to form the Jacobian.
1880    */
1881   ierr = DMSNESGetJacobian(dm,&jac,NULL);CHKERRQ(ierr);
1882   ierr = DMTSGetIJacobian(dm,&ijac,NULL);CHKERRQ(ierr);
1883   ierr = DMTSGetRHSJacobian(dm,&rhsjac,NULL);CHKERRQ(ierr);
1884   if (!jac && (ijac || rhsjac)) {
1885     ierr = DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1886   }
1887   ts->setupcalled = PETSC_TRUE;
1888   PetscFunctionReturn(0);
1889 }
1890 
1891 #undef __FUNCT__
1892 #define __FUNCT__ "TSAdjointSetUp"
1893 /*@
1894    TSAdjointSetUp - Sets up the internal data structures for the later use
1895    of an adjoint solver
1896 
1897    Collective on TS
1898 
1899    Input Parameter:
1900 .  ts - the TS context obtained from TSCreate()
1901 
1902    Notes:
1903    For basic use of the TS solvers the user need not explicitly call
1904    TSSetUp(), since these actions will automatically occur during
1905    the call to TSStep().  However, if one wishes to control this
1906    phase separately, TSSetUp() should be called after TSCreate()
1907    and optional routines of the form TSSetXXX(), but before TSStep().
1908 
1909    Level: advanced
1910 
1911 .keywords: TS, timestep, setup
1912 
1913 .seealso: TSCreate(), TSStep(), TSDestroy()
1914 @*/
1915 PetscErrorCode  TSAdjointSetUp(TS ts)
1916 {
1917   PetscErrorCode ierr;
1918 
1919   PetscFunctionBegin;
1920   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1921   if (ts->adjointsetupcalled) PetscFunctionReturn(0);
1922   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSAdjointSetSensitivity() first");
1923   if (ts->ops->setupadj) {
1924     ierr = (*ts->ops->setupadj)(ts);CHKERRQ(ierr);
1925   }
1926   ts->adjointsetupcalled = PETSC_TRUE;
1927   PetscFunctionReturn(0);
1928 }
1929 
1930 #undef __FUNCT__
1931 #define __FUNCT__ "TSReset"
1932 /*@
1933    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
1934 
1935    Collective on TS
1936 
1937    Input Parameter:
1938 .  ts - the TS context obtained from TSCreate()
1939 
1940    Level: beginner
1941 
1942 .keywords: TS, timestep, reset
1943 
1944 .seealso: TSCreate(), TSSetup(), TSDestroy()
1945 @*/
1946 PetscErrorCode  TSReset(TS ts)
1947 {
1948   PetscErrorCode ierr;
1949 
1950   PetscFunctionBegin;
1951   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1952 
1953   if (ts->ops->reset) {
1954     ierr = (*ts->ops->reset)(ts);CHKERRQ(ierr);
1955   }
1956   if (ts->snes) {ierr = SNESReset(ts->snes);CHKERRQ(ierr);}
1957 
1958   ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
1959   ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
1960   ierr = VecDestroy(&ts->Frhs);CHKERRQ(ierr);
1961   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
1962   ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
1963   ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
1964   ierr = VecDestroyVecs(ts->nwork,&ts->work);CHKERRQ(ierr);
1965   ts->vecs_sensi = 0;
1966   ts->vecs_sensip = 0;
1967   ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
1968   ierr = VecDestroy(&ts->vec_costquad);CHKERRQ(ierr);
1969   ierr = VecDestroy(&ts->vec_costintegrand);CHKERRQ(ierr);
1970   ts->setupcalled = PETSC_FALSE;
1971   PetscFunctionReturn(0);
1972 }
1973 
1974 #undef __FUNCT__
1975 #define __FUNCT__ "TSDestroy"
1976 /*@
1977    TSDestroy - Destroys the timestepper context that was created
1978    with TSCreate().
1979 
1980    Collective on TS
1981 
1982    Input Parameter:
1983 .  ts - the TS context obtained from TSCreate()
1984 
1985    Level: beginner
1986 
1987 .keywords: TS, timestepper, destroy
1988 
1989 .seealso: TSCreate(), TSSetUp(), TSSolve()
1990 @*/
1991 PetscErrorCode  TSDestroy(TS *ts)
1992 {
1993   PetscErrorCode ierr;
1994 
1995   PetscFunctionBegin;
1996   if (!*ts) PetscFunctionReturn(0);
1997   PetscValidHeaderSpecific((*ts),TS_CLASSID,1);
1998   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; PetscFunctionReturn(0);}
1999 
2000   ierr = TSReset((*ts));CHKERRQ(ierr);
2001 
2002   /* if memory was published with SAWs then destroy it */
2003   ierr = PetscObjectSAWsViewOff((PetscObject)*ts);CHKERRQ(ierr);
2004   if ((*ts)->ops->destroy) {ierr = (*(*ts)->ops->destroy)((*ts));CHKERRQ(ierr);}
2005 
2006   ierr = TSAdaptDestroy(&(*ts)->adapt);CHKERRQ(ierr);
2007   if ((*ts)->event) {
2008     ierr = TSEventMonitorDestroy(&(*ts)->event);CHKERRQ(ierr);
2009   }
2010   ierr = SNESDestroy(&(*ts)->snes);CHKERRQ(ierr);
2011   ierr = DMDestroy(&(*ts)->dm);CHKERRQ(ierr);
2012   ierr = TSMonitorCancel((*ts));CHKERRQ(ierr);
2013 
2014   ierr = PetscHeaderDestroy(ts);CHKERRQ(ierr);
2015   PetscFunctionReturn(0);
2016 }
2017 
2018 #undef __FUNCT__
2019 #define __FUNCT__ "TSGetSNES"
2020 /*@
2021    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2022    a TS (timestepper) context. Valid only for nonlinear problems.
2023 
2024    Not Collective, but SNES is parallel if TS is parallel
2025 
2026    Input Parameter:
2027 .  ts - the TS context obtained from TSCreate()
2028 
2029    Output Parameter:
2030 .  snes - the nonlinear solver context
2031 
2032    Notes:
2033    The user can then directly manipulate the SNES context to set various
2034    options, etc.  Likewise, the user can then extract and manipulate the
2035    KSP, KSP, and PC contexts as well.
2036 
2037    TSGetSNES() does not work for integrators that do not use SNES; in
2038    this case TSGetSNES() returns NULL in snes.
2039 
2040    Level: beginner
2041 
2042 .keywords: timestep, get, SNES
2043 @*/
2044 PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2045 {
2046   PetscErrorCode ierr;
2047 
2048   PetscFunctionBegin;
2049   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2050   PetscValidPointer(snes,2);
2051   if (!ts->snes) {
2052     ierr = SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);CHKERRQ(ierr);
2053     ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2054     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);CHKERRQ(ierr);
2055     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);CHKERRQ(ierr);
2056     if (ts->dm) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
2057     if (ts->problem_type == TS_LINEAR) {
2058       ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);
2059     }
2060   }
2061   *snes = ts->snes;
2062   PetscFunctionReturn(0);
2063 }
2064 
2065 #undef __FUNCT__
2066 #define __FUNCT__ "TSSetSNES"
2067 /*@
2068    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2069 
2070    Collective
2071 
2072    Input Parameter:
2073 +  ts - the TS context obtained from TSCreate()
2074 -  snes - the nonlinear solver context
2075 
2076    Notes:
2077    Most users should have the TS created by calling TSGetSNES()
2078 
2079    Level: developer
2080 
2081 .keywords: timestep, set, SNES
2082 @*/
2083 PetscErrorCode TSSetSNES(TS ts,SNES snes)
2084 {
2085   PetscErrorCode ierr;
2086   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2087 
2088   PetscFunctionBegin;
2089   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2090   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
2091   ierr = PetscObjectReference((PetscObject)snes);CHKERRQ(ierr);
2092   ierr = SNESDestroy(&ts->snes);CHKERRQ(ierr);
2093 
2094   ts->snes = snes;
2095 
2096   ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2097   ierr = SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);CHKERRQ(ierr);
2098   if (func == SNESTSFormJacobian) {
2099     ierr = SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2100   }
2101   PetscFunctionReturn(0);
2102 }
2103 
2104 #undef __FUNCT__
2105 #define __FUNCT__ "TSGetKSP"
2106 /*@
2107    TSGetKSP - Returns the KSP (linear solver) associated with
2108    a TS (timestepper) context.
2109 
2110    Not Collective, but KSP is parallel if TS is parallel
2111 
2112    Input Parameter:
2113 .  ts - the TS context obtained from TSCreate()
2114 
2115    Output Parameter:
2116 .  ksp - the nonlinear solver context
2117 
2118    Notes:
2119    The user can then directly manipulate the KSP context to set various
2120    options, etc.  Likewise, the user can then extract and manipulate the
2121    KSP and PC contexts as well.
2122 
2123    TSGetKSP() does not work for integrators that do not use KSP;
2124    in this case TSGetKSP() returns NULL in ksp.
2125 
2126    Level: beginner
2127 
2128 .keywords: timestep, get, KSP
2129 @*/
2130 PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2131 {
2132   PetscErrorCode ierr;
2133   SNES           snes;
2134 
2135   PetscFunctionBegin;
2136   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2137   PetscValidPointer(ksp,2);
2138   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2139   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2140   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2141   ierr = SNESGetKSP(snes,ksp);CHKERRQ(ierr);
2142   PetscFunctionReturn(0);
2143 }
2144 
2145 /* ----------- Routines to set solver parameters ---------- */
2146 
2147 #undef __FUNCT__
2148 #define __FUNCT__ "TSGetDuration"
2149 /*@
2150    TSGetDuration - Gets the maximum number of timesteps to use and
2151    maximum time for iteration.
2152 
2153    Not Collective
2154 
2155    Input Parameters:
2156 +  ts       - the TS context obtained from TSCreate()
2157 .  maxsteps - maximum number of iterations to use, or NULL
2158 -  maxtime  - final time to iterate to, or NULL
2159 
2160    Level: intermediate
2161 
2162 .keywords: TS, timestep, get, maximum, iterations, time
2163 @*/
2164 PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2165 {
2166   PetscFunctionBegin;
2167   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2168   if (maxsteps) {
2169     PetscValidIntPointer(maxsteps,2);
2170     *maxsteps = ts->max_steps;
2171   }
2172   if (maxtime) {
2173     PetscValidScalarPointer(maxtime,3);
2174     *maxtime = ts->max_time;
2175   }
2176   PetscFunctionReturn(0);
2177 }
2178 
2179 #undef __FUNCT__
2180 #define __FUNCT__ "TSSetDuration"
2181 /*@
2182    TSSetDuration - Sets the maximum number of timesteps to use and
2183    maximum time for iteration.
2184 
2185    Logically Collective on TS
2186 
2187    Input Parameters:
2188 +  ts - the TS context obtained from TSCreate()
2189 .  maxsteps - maximum number of iterations to use
2190 -  maxtime - final time to iterate to
2191 
2192    Options Database Keys:
2193 .  -ts_max_steps <maxsteps> - Sets maxsteps
2194 .  -ts_final_time <maxtime> - Sets maxtime
2195 
2196    Notes:
2197    The default maximum number of iterations is 5000. Default time is 5.0
2198 
2199    Level: intermediate
2200 
2201 .keywords: TS, timestep, set, maximum, iterations
2202 
2203 .seealso: TSSetExactFinalTime()
2204 @*/
2205 PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2206 {
2207   PetscFunctionBegin;
2208   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2209   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
2210   PetscValidLogicalCollectiveReal(ts,maxtime,2);
2211   if (maxsteps >= 0) ts->max_steps = maxsteps;
2212   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2213   PetscFunctionReturn(0);
2214 }
2215 
2216 #undef __FUNCT__
2217 #define __FUNCT__ "TSSetSolution"
2218 /*@
2219    TSSetSolution - Sets the initial solution vector
2220    for use by the TS routines.
2221 
2222    Logically Collective on TS and Vec
2223 
2224    Input Parameters:
2225 +  ts - the TS context obtained from TSCreate()
2226 -  u - the solution vector
2227 
2228    Level: beginner
2229 
2230 .keywords: TS, timestep, set, solution, initial conditions
2231 @*/
2232 PetscErrorCode  TSSetSolution(TS ts,Vec u)
2233 {
2234   PetscErrorCode ierr;
2235   DM             dm;
2236 
2237   PetscFunctionBegin;
2238   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2239   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2240   ierr = PetscObjectReference((PetscObject)u);CHKERRQ(ierr);
2241   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2242 
2243   ts->vec_sol = u;
2244 
2245   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2246   ierr = DMShellSetGlobalVector(dm,u);CHKERRQ(ierr);
2247   PetscFunctionReturn(0);
2248 }
2249 
2250 #undef __FUNCT__
2251 #define __FUNCT__ "TSAdjointSetSensitivity"
2252 /*@
2253    TSAdjointSetSensitivity - Sets the initial value of sensitivity (w.r.t. initial conditions)
2254    for use by the TS routines.
2255 
2256    Logically Collective on TS and Vec
2257 
2258    Input Parameters:
2259 +  ts - the TS context obtained from TSCreate()
2260 -  u - the solution vector
2261 
2262    Level: beginner
2263 
2264 .keywords: TS, timestep, set, sensitivity, initial conditions
2265 @*/
2266 PetscErrorCode  TSAdjointSetSensitivity(TS ts,Vec *u,PetscInt numberadjs)
2267 {
2268   PetscFunctionBegin;
2269   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2270   PetscValidPointer(u,2);
2271   ts->vecs_sensi = u;
2272   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()");
2273   ts->numberadjs = numberadjs;
2274 
2275   PetscFunctionReturn(0);
2276 }
2277 
2278 #undef __FUNCT__
2279 #define __FUNCT__ "TSAdjointSetSensitivityP"
2280 /*@
2281    TSAdjointSetSensitivityP - Sets the initial value of sensitivity (w.r.t. parameters)
2282    for use by the TS routines.
2283 
2284    Logically Collective on TS and Vec
2285 
2286    Input Parameters:
2287 +  ts - the TS context obtained from TSCreate()
2288 -  u - the solution vector
2289 
2290    Level: beginner
2291 
2292 .keywords: TS, timestep, set, sensitivity, initial conditions
2293 @*/
2294 PetscErrorCode  TSAdjointSetSensitivityP(TS ts,Vec *u,PetscInt numberadjs)
2295 {
2296   PetscFunctionBegin;
2297   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2298   PetscValidPointer(u,2);
2299   ts->vecs_sensip = u;
2300   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()");
2301   ts->numberadjs = numberadjs;
2302 
2303   PetscFunctionReturn(0);
2304 }
2305 
2306 #undef __FUNCT__
2307 #define __FUNCT__ "TSAdjointSetRHSJacobianP"
2308 /*@C
2309   TSAdjointSetRHSJacobianP - Sets the function that computes the Jacobian w.r.t. parameters.
2310 
2311   Logically Collective on TS
2312 
2313   Input Parameters:
2314 + ts   - The TS context obtained from TSCreate()
2315 - func - The function
2316 
2317   Calling sequence of func:
2318 $ func (TS ts,PetscReal t,Vec u,Mat A,void *ctx);
2319 +   t - current timestep
2320 .   u - input vector
2321 .   A - output matrix
2322 -   ctx - [optional] user-defined function context
2323 
2324   Level: intermediate
2325 
2326 .keywords: TS, sensitivity
2327 .seealso:
2328 @*/
2329 PetscErrorCode  TSAdjointSetRHSJacobianP(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2330 {
2331   PetscErrorCode ierr;
2332 
2333   PetscFunctionBegin;
2334   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2335   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
2336 
2337   ts->rhsjacobianp    = func;
2338   ts->rhsjacobianpctx = ctx;
2339   if(Amat) {
2340     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
2341     ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
2342 
2343     ts->Jacp = Amat;
2344   }
2345   PetscFunctionReturn(0);
2346 }
2347 
2348 #undef __FUNCT__
2349 #define __FUNCT__ "TSAdjointComputeRHSJacobianP"
2350 /*@
2351   TSAdjointComputeRHSJacobianP - Runs the user-defined JacobianP function.
2352 
2353   Collective on TS
2354 
2355   Input Parameters:
2356 . ts   - The TS context obtained from TSCreate()
2357 
2358   Level: developer
2359 
2360 .keywords: TS, sensitivity
2361 .seealso: TSAdjointSetRHSJacobianP()
2362 @*/
2363 PetscErrorCode  TSAdjointComputeRHSJacobianP(TS ts,PetscReal t,Vec X,Mat Amat)
2364 {
2365   PetscErrorCode ierr;
2366 
2367   PetscFunctionBegin;
2368   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2369   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2370   PetscValidPointer(Amat,4);
2371 
2372   PetscStackPush("TS user JacobianP function for sensitivity analysis");
2373   ierr = (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx); CHKERRQ(ierr);
2374   PetscStackPop;
2375 
2376   PetscFunctionReturn(0);
2377 }
2378 
2379 #undef __FUNCT__
2380 #define __FUNCT__ "TSAdjointSetCostIntegrand"
2381 /*@C
2382     TSAdjointSetCostIntegrand - Sets the routine for evaluating the quadrature (or integral) term in a cost function,
2383     where Q_t = r(t,u).
2384 
2385     Logically Collective on TS
2386 
2387     Input Parameters:
2388 +   ts - the TS context obtained from TSCreate()
2389 .   q -  vector to put the computed quadrature term in the cost function (or NULL to have it created)
2390 .   fq - routine for evaluating the right-hand-side function
2391 -   ctx - [optional] user-defined context for private data for the
2392           function evaluation routine (may be NULL)
2393 
2394     Calling sequence of func:
2395 $     TSCostIntegrand(TS ts,PetscReal t,Vec u,PetscReal *f,void *ctx);
2396 
2397 +   t - current timestep
2398 .   u - input vector
2399 .   f - function vector
2400 -   ctx - [optional] user-defined function context
2401 
2402     Level: beginner
2403 
2404 .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
2405 
2406 .seealso: TSAdjointSetRHSJacobianP(),TSAdjointSetSensitivity(),TSAdjointSetSensitivityP()
2407 @*/
2408 PetscErrorCode  TSAdjointSetCostIntegrand(TS ts,PetscInt numberadjs,Vec q,PetscErrorCode (*fq)(TS,PetscReal,Vec,Vec,void*),void *ctx)
2409 {
2410   PetscErrorCode ierr;
2411   PetscInt size;
2412 
2413   PetscFunctionBegin;
2414   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2415   if (q) {
2416     PetscValidHeaderSpecific(q,VEC_CLASSID,2);
2417   } else {
2418     SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"TSAdjointSetCostIntegrand() requires a vector of size numberajds to hold the value of integrals as 3rd input parameter");
2419   }
2420   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.");
2421   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()");
2422   ierr = VecGetSize(q,&size);CHKERRQ(ierr);
2423   ierr = VecZeroEntries(q);CHKERRQ(ierr);
2424   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()).");
2425 
2426   ierr = PetscObjectReference((PetscObject)q);CHKERRQ(ierr);
2427   ierr = VecDestroy(&ts->vec_costquad);CHKERRQ(ierr);
2428   ts->vec_costquad = q;
2429 
2430   ierr                  = VecDuplicate(ts->vec_costquad,&ts->vec_costintegrand);CHKERRQ(ierr);
2431   ts->costintegrand     = fq;
2432   ts->costintegrandctx  = ctx;
2433 
2434   PetscFunctionReturn(0);
2435 }
2436 
2437 #undef __FUNCT__
2438 #define __FUNCT__ "TSAdjointGetCostQuadrature"
2439 /*@
2440    TSAdjointGetCostQuadrature - Returns the values of the quadrature (or integral) terms in a cost function.
2441    It is valid to call the routine after a backward run.
2442 
2443    Not Collective
2444 
2445    Input Parameter:
2446 .  ts - the TS context obtained from TSCreate()
2447 
2448    Output Parameter:
2449 .  v - the vector containing the solution
2450 
2451    Level: intermediate
2452 
2453 .seealso: TSAdjointSetCostIntegrand()
2454 
2455 .keywords: TS, sensitivity analysis
2456 @*/
2457 PetscErrorCode  TSAdjointGetCostQuadrature(TS ts,Vec *v)
2458 {
2459   PetscFunctionBegin;
2460   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2461   PetscValidPointer(v,2);
2462   *v = ts->vec_costquad;
2463   PetscFunctionReturn(0);
2464 }
2465 
2466 #undef __FUNCT__
2467 #define __FUNCT__ "TSAdjointComputeCostIntegrand"
2468 /*@
2469    TSAdjointComputeCostIntegrand - Evaluates the quadrature function in the cost functions.
2470 
2471    Input Parameters:
2472 +  ts - the TS context
2473 .  t - current time
2474 -  U - state vector
2475 
2476    Output Parameter:
2477 .  q - vector of size numberadjs to hold the outputs
2478 
2479    Note:
2480    Most users should not need to explicitly call this routine, as it
2481    is used internally within the sensitivity analysis context.
2482 
2483    Level: developer
2484 
2485 .keywords: TS, compute
2486 
2487 .seealso: TSAdjointSetCostIntegrand()
2488 @*/
2489 PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec U,Vec q)
2490 {
2491   PetscErrorCode ierr;
2492 
2493   PetscFunctionBegin;
2494   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2495   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
2496   PetscValidHeaderSpecific(q,VEC_CLASSID,4);
2497 
2498   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,q,0);CHKERRQ(ierr);
2499   if (ts->costintegrand) {
2500     PetscStackPush("TS user integrand in the cost function");
2501     ierr = (*ts->costintegrand)(ts,t,U,q,ts->costintegrandctx);CHKERRQ(ierr);
2502     PetscStackPop;
2503   } else {
2504     ierr = VecZeroEntries(q);CHKERRQ(ierr);
2505   }
2506 
2507   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,q,0);CHKERRQ(ierr);
2508   PetscFunctionReturn(0);
2509 }
2510 
2511 #undef __FUNCT__
2512 #define __FUNCT__ "TSAdjointSetDRDYFunction"
2513 /*@C
2514   TSAdjointSetDRDYFunction - Sets the function that computes the gradient of the CostIntegrand function r w.r.t. states y.
2515 
2516   Logically Collective on TS
2517 
2518   Input Parameters:
2519 + ts   - The TS context obtained from TSCreate()
2520 - func - The function
2521 
2522   Calling sequence of func:
2523 . PetscErroCode func(TS ts,PetscReal t,Vec U,Vec *drdy,void *ctx);
2524 
2525   Level: intermediate
2526 
2527 .keywords: TS, sensitivity
2528 .seealso:
2529 @*/
2530 PetscErrorCode  TSAdjointSetDRDYFunction(TS ts,Vec *drdy,PetscErrorCode (*func)(TS,PetscReal,Vec,Vec*,void*),void *ctx)
2531 {
2532   PetscFunctionBegin;
2533   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2534 
2535   ts->drdyfunction    = func;
2536   ts->drdyfunctionctx = ctx;
2537   ts->vecs_drdy       = drdy;
2538   PetscFunctionReturn(0);
2539 }
2540 
2541 #undef __FUNCT__
2542 #define __FUNCT__ "TSAdjointComputeDRDYFunction"
2543 /*@
2544   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
2545 
2546   Collective on TS
2547 
2548   Input Parameters:
2549 . ts   - The TS context obtained from TSCreate()
2550 
2551   Notes:
2552   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
2553   so most users would not generally call this routine themselves.
2554 
2555   Level: developer
2556 
2557 .keywords: TS, sensitivity
2558 .seealso: TSAdjointComputeDRDYFunction()
2559 @*/
2560 PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec X,Vec *drdy)
2561 {
2562   PetscErrorCode ierr;
2563 
2564   PetscFunctionBegin;
2565   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2566   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2567 
2568   PetscStackPush("TS user DRDY function for sensitivity analysis");
2569   ierr = (*ts->drdyfunction)(ts,t,X,drdy,ts->drdyfunctionctx); CHKERRQ(ierr);
2570   PetscStackPop;
2571   PetscFunctionReturn(0);
2572 }
2573 
2574 #undef __FUNCT__
2575 #define __FUNCT__ "TSAdjointSetDRDPFunction"
2576 /*@C
2577   TSAdjointSetDRDPFunction - Sets the function that computes the gradient of the CostIntegrand function w.r.t. parameters.
2578 
2579   Logically Collective on TS
2580 
2581   Input Parameters:
2582 + ts   - The TS context obtained from TSCreate()
2583 - func - The function
2584 
2585   Calling sequence of func:
2586 . func(TS ts,PetscReal t,Vec U,Vec *drdy,void *ctx);
2587 
2588   Level: intermediate
2589 
2590 .keywords: TS, sensitivity
2591 .seealso:
2592 @*/
2593 PetscErrorCode  TSAdjointSetDRDPFunction(TS ts,Vec *drdp,PetscErrorCode (*func)(TS,PetscReal,Vec,Vec*,void*),void *ctx)
2594 {
2595   PetscFunctionBegin;
2596   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2597 
2598   ts->drdpfunction    = func;
2599   ts->drdpfunctionctx = ctx;
2600   ts->vecs_drdp       = drdp;
2601 
2602   PetscFunctionReturn(0);
2603 }
2604 
2605 #undef __FUNCT__
2606 #define __FUNCT__ "TSAdjointComputeDRDPFunction"
2607 /*@
2608   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
2609 
2610   Collective on TS
2611 
2612   Input Parameters:
2613 . ts   - The TS context obtained from TSCreate()
2614 
2615   Notes:
2616   TSDRDPFunction() is typically used for sensitivity implementation,
2617   so most users would not generally call this routine themselves.
2618 
2619   Level: developer
2620 
2621 .keywords: TS, sensitivity
2622 .seealso: TSAdjointSetDRDPFunction()
2623 @*/
2624 PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec X,Vec *drdp)
2625 {
2626   PetscErrorCode ierr;
2627 
2628   PetscFunctionBegin;
2629   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2630   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2631 
2632   PetscStackPush("TS user DRDP function for sensitivity analysis");
2633   ierr = (*ts->drdpfunction)(ts,t,X,drdp,ts->drdpfunctionctx); CHKERRQ(ierr);
2634   PetscStackPop;
2635 
2636   PetscFunctionReturn(0);
2637 }
2638 
2639 #undef __FUNCT__
2640 #define __FUNCT__ "TSSetPreStep"
2641 /*@C
2642   TSSetPreStep - Sets the general-purpose function
2643   called once at the beginning of each time step.
2644 
2645   Logically Collective on TS
2646 
2647   Input Parameters:
2648 + ts   - The TS context obtained from TSCreate()
2649 - func - The function
2650 
2651   Calling sequence of func:
2652 . func (TS ts);
2653 
2654   Level: intermediate
2655 
2656   Note:
2657   If a step is rejected, TSStep() will call this routine again before each attempt.
2658   The last completed time step number can be queried using TSGetTimeStepNumber(), the
2659   size of the step being attempted can be obtained using TSGetTimeStep().
2660 
2661 .keywords: TS, timestep
2662 .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
2663 @*/
2664 PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2665 {
2666   PetscFunctionBegin;
2667   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2668   ts->prestep = func;
2669   PetscFunctionReturn(0);
2670 }
2671 
2672 #undef __FUNCT__
2673 #define __FUNCT__ "TSPreStep"
2674 /*@
2675   TSPreStep - Runs the user-defined pre-step function.
2676 
2677   Collective on TS
2678 
2679   Input Parameters:
2680 . ts   - The TS context obtained from TSCreate()
2681 
2682   Notes:
2683   TSPreStep() is typically used within time stepping implementations,
2684   so most users would not generally call this routine themselves.
2685 
2686   Level: developer
2687 
2688 .keywords: TS, timestep
2689 .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
2690 @*/
2691 PetscErrorCode  TSPreStep(TS ts)
2692 {
2693   PetscErrorCode ierr;
2694 
2695   PetscFunctionBegin;
2696   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2697   if (ts->prestep) {
2698     PetscStackCallStandard((*ts->prestep),(ts));
2699   }
2700   PetscFunctionReturn(0);
2701 }
2702 
2703 #undef __FUNCT__
2704 #define __FUNCT__ "TSSetPreStage"
2705 /*@C
2706   TSSetPreStage - Sets the general-purpose function
2707   called once at the beginning of each stage.
2708 
2709   Logically Collective on TS
2710 
2711   Input Parameters:
2712 + ts   - The TS context obtained from TSCreate()
2713 - func - The function
2714 
2715   Calling sequence of func:
2716 . PetscErrorCode func(TS ts, PetscReal stagetime);
2717 
2718   Level: intermediate
2719 
2720   Note:
2721   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2722   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2723   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
2724 
2725 .keywords: TS, timestep
2726 .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2727 @*/
2728 PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2729 {
2730   PetscFunctionBegin;
2731   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2732   ts->prestage = func;
2733   PetscFunctionReturn(0);
2734 }
2735 
2736 #undef __FUNCT__
2737 #define __FUNCT__ "TSSetPostStage"
2738 /*@C
2739   TSSetPostStage - Sets the general-purpose function
2740   called once at the end of each stage.
2741 
2742   Logically Collective on TS
2743 
2744   Input Parameters:
2745 + ts   - The TS context obtained from TSCreate()
2746 - func - The function
2747 
2748   Calling sequence of func:
2749 . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
2750 
2751   Level: intermediate
2752 
2753   Note:
2754   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2755   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2756   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
2757 
2758 .keywords: TS, timestep
2759 .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2760 @*/
2761 PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
2762 {
2763   PetscFunctionBegin;
2764   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2765   ts->poststage = func;
2766   PetscFunctionReturn(0);
2767 }
2768 
2769 #undef __FUNCT__
2770 #define __FUNCT__ "TSPreStage"
2771 /*@
2772   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
2773 
2774   Collective on TS
2775 
2776   Input Parameters:
2777 . ts          - The TS context obtained from TSCreate()
2778   stagetime   - The absolute time of the current stage
2779 
2780   Notes:
2781   TSPreStage() is typically used within time stepping implementations,
2782   most users would not generally call this routine themselves.
2783 
2784   Level: developer
2785 
2786 .keywords: TS, timestep
2787 .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2788 @*/
2789 PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
2790 {
2791   PetscErrorCode ierr;
2792 
2793   PetscFunctionBegin;
2794   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2795   if (ts->prestage) {
2796     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
2797   }
2798   PetscFunctionReturn(0);
2799 }
2800 
2801 #undef __FUNCT__
2802 #define __FUNCT__ "TSPostStage"
2803 /*@
2804   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
2805 
2806   Collective on TS
2807 
2808   Input Parameters:
2809 . ts          - The TS context obtained from TSCreate()
2810   stagetime   - The absolute time of the current stage
2811   stageindex  - Stage number
2812   Y           - Array of vectors (of size = total number
2813                 of stages) with the stage solutions
2814 
2815   Notes:
2816   TSPostStage() is typically used within time stepping implementations,
2817   most users would not generally call this routine themselves.
2818 
2819   Level: developer
2820 
2821 .keywords: TS, timestep
2822 .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2823 @*/
2824 PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
2825 {
2826   PetscErrorCode ierr;
2827 
2828   PetscFunctionBegin;
2829   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2830   if (ts->poststage) {
2831     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
2832   }
2833   PetscFunctionReturn(0);
2834 }
2835 
2836 #undef __FUNCT__
2837 #define __FUNCT__ "TSSetPostStep"
2838 /*@C
2839   TSSetPostStep - Sets the general-purpose function
2840   called once at the end of each time step.
2841 
2842   Logically Collective on TS
2843 
2844   Input Parameters:
2845 + ts   - The TS context obtained from TSCreate()
2846 - func - The function
2847 
2848   Calling sequence of func:
2849 $ func (TS ts);
2850 
2851   Level: intermediate
2852 
2853 .keywords: TS, timestep
2854 .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2855 @*/
2856 PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2857 {
2858   PetscFunctionBegin;
2859   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2860   ts->poststep = func;
2861   PetscFunctionReturn(0);
2862 }
2863 
2864 #undef __FUNCT__
2865 #define __FUNCT__ "TSPostStep"
2866 /*@
2867   TSPostStep - Runs the user-defined post-step function.
2868 
2869   Collective on TS
2870 
2871   Input Parameters:
2872 . ts   - The TS context obtained from TSCreate()
2873 
2874   Notes:
2875   TSPostStep() is typically used within time stepping implementations,
2876   so most users would not generally call this routine themselves.
2877 
2878   Level: developer
2879 
2880 .keywords: TS, timestep
2881 @*/
2882 PetscErrorCode  TSPostStep(TS ts)
2883 {
2884   PetscErrorCode ierr;
2885 
2886   PetscFunctionBegin;
2887   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2888   if (ts->poststep) {
2889     PetscStackCallStandard((*ts->poststep),(ts));
2890   }
2891   PetscFunctionReturn(0);
2892 }
2893 
2894 /* ------------ Routines to set performance monitoring options ----------- */
2895 
2896 #undef __FUNCT__
2897 #define __FUNCT__ "TSMonitorSet"
2898 /*@C
2899    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
2900    timestep to display the iteration's  progress.
2901 
2902    Logically Collective on TS
2903 
2904    Input Parameters:
2905 +  ts - the TS context obtained from TSCreate()
2906 .  monitor - monitoring routine
2907 .  mctx - [optional] user-defined context for private data for the
2908              monitor routine (use NULL if no context is desired)
2909 -  monitordestroy - [optional] routine that frees monitor context
2910           (may be NULL)
2911 
2912    Calling sequence of monitor:
2913 $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
2914 
2915 +    ts - the TS context
2916 .    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
2917                                been interpolated to)
2918 .    time - current time
2919 .    u - current iterate
2920 -    mctx - [optional] monitoring context
2921 
2922    Notes:
2923    This routine adds an additional monitor to the list of monitors that
2924    already has been loaded.
2925 
2926    Fortran notes: Only a single monitor function can be set for each TS object
2927 
2928    Level: intermediate
2929 
2930 .keywords: TS, timestep, set, monitor
2931 
2932 .seealso: TSMonitorDefault(), TSMonitorCancel()
2933 @*/
2934 PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
2935 {
2936   PetscFunctionBegin;
2937   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2938   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
2939   ts->monitor[ts->numbermonitors]          = monitor;
2940   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
2941   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
2942   PetscFunctionReturn(0);
2943 }
2944 
2945 #undef __FUNCT__
2946 #define __FUNCT__ "TSMonitorCancel"
2947 /*@C
2948    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
2949 
2950    Logically Collective on TS
2951 
2952    Input Parameters:
2953 .  ts - the TS context obtained from TSCreate()
2954 
2955    Notes:
2956    There is no way to remove a single, specific monitor.
2957 
2958    Level: intermediate
2959 
2960 .keywords: TS, timestep, set, monitor
2961 
2962 .seealso: TSMonitorDefault(), TSMonitorSet()
2963 @*/
2964 PetscErrorCode  TSMonitorCancel(TS ts)
2965 {
2966   PetscErrorCode ierr;
2967   PetscInt       i;
2968 
2969   PetscFunctionBegin;
2970   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2971   for (i=0; i<ts->numbermonitors; i++) {
2972     if (ts->monitordestroy[i]) {
2973       ierr = (*ts->monitordestroy[i])(&ts->monitorcontext[i]);CHKERRQ(ierr);
2974     }
2975   }
2976   ts->numbermonitors = 0;
2977   PetscFunctionReturn(0);
2978 }
2979 
2980 #undef __FUNCT__
2981 #define __FUNCT__ "TSMonitorDefault"
2982 /*@
2983    TSMonitorDefault - Sets the Default monitor
2984 
2985    Level: intermediate
2986 
2987 .keywords: TS, set, monitor
2988 
2989 .seealso: TSMonitorDefault(), TSMonitorSet()
2990 @*/
2991 PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
2992 {
2993   PetscErrorCode ierr;
2994   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));
2995 
2996   PetscFunctionBegin;
2997   ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
2998   ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g\n",step,(double)ts->time_step,(double)ptime);CHKERRQ(ierr);
2999   ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3000   PetscFunctionReturn(0);
3001 }
3002 
3003 #undef __FUNCT__
3004 #define __FUNCT__ "TSSetRetainStages"
3005 /*@
3006    TSSetRetainStages - Request that all stages in the upcoming step be stored so that interpolation will be available.
3007 
3008    Logically Collective on TS
3009 
3010    Input Argument:
3011 .  ts - time stepping context
3012 
3013    Output Argument:
3014 .  flg - PETSC_TRUE or PETSC_FALSE
3015 
3016    Level: intermediate
3017 
3018 .keywords: TS, set
3019 
3020 .seealso: TSInterpolate(), TSSetPostStep()
3021 @*/
3022 PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
3023 {
3024   PetscFunctionBegin;
3025   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3026   ts->retain_stages = flg;
3027   PetscFunctionReturn(0);
3028 }
3029 
3030 #undef __FUNCT__
3031 #define __FUNCT__ "TSInterpolate"
3032 /*@
3033    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3034 
3035    Collective on TS
3036 
3037    Input Argument:
3038 +  ts - time stepping context
3039 -  t - time to interpolate to
3040 
3041    Output Argument:
3042 .  U - state at given time
3043 
3044    Notes:
3045    The user should call TSSetRetainStages() before taking a step in which interpolation will be requested.
3046 
3047    Level: intermediate
3048 
3049    Developer Notes:
3050    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3051 
3052 .keywords: TS, set
3053 
3054 .seealso: TSSetRetainStages(), TSSetPostStep()
3055 @*/
3056 PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3057 {
3058   PetscErrorCode ierr;
3059 
3060   PetscFunctionBegin;
3061   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3062   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3063   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);
3064   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3065   ierr = (*ts->ops->interpolate)(ts,t,U);CHKERRQ(ierr);
3066   PetscFunctionReturn(0);
3067 }
3068 
3069 #undef __FUNCT__
3070 #define __FUNCT__ "TSStep"
3071 /*@
3072    TSStep - Steps one time step
3073 
3074    Collective on TS
3075 
3076    Input Parameter:
3077 .  ts - the TS context obtained from TSCreate()
3078 
3079    Level: intermediate
3080 
3081    Notes:
3082    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3083    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3084 
3085    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3086    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3087 
3088 .keywords: TS, timestep, solve
3089 
3090 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3091 @*/
3092 PetscErrorCode  TSStep(TS ts)
3093 {
3094   DM               dm;
3095   PetscErrorCode   ierr;
3096   static PetscBool cite = PETSC_FALSE;
3097 
3098   PetscFunctionBegin;
3099   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3100   ierr = PetscCitationsRegister("@techreport{tspaper,\n"
3101                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3102                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3103                                 "  type        = {Preprint},\n"
3104                                 "  number      = {ANL/MCS-P5061-0114},\n"
3105                                 "  institution = {Argonne National Laboratory},\n"
3106                                 "  year        = {2014}\n}\n",&cite);
3107 
3108   ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
3109   ierr = TSSetUp(ts);CHKERRQ(ierr);
3110 
3111   ts->reason = TS_CONVERGED_ITERATING;
3112   ts->ptime_prev = ts->ptime;
3113   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3114   ierr = VecViewFromOptions(ts->vec_sol, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3115 
3116   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3117   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3118   ierr = (*ts->ops->step)(ts);CHKERRQ(ierr);
3119   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3120 
3121   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3122   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3123 
3124   if (ts->reason < 0) {
3125     if (ts->errorifstepfailed) {
3126       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]);
3127       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3128     }
3129   } else if (!ts->reason) {
3130     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3131     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3132   }
3133   PetscFunctionReturn(0);
3134 }
3135 
3136 #undef __FUNCT__
3137 #define __FUNCT__ "TSAdjointStep"
3138 /*@
3139    TSAdjointStep - Steps one time step
3140 
3141    Collective on TS
3142 
3143    Input Parameter:
3144 .  ts - the TS context obtained from TSCreate()
3145 
3146    Level: intermediate
3147 
3148    Notes:
3149    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3150    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3151 
3152    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3153    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3154 
3155 .keywords: TS, timestep, solve
3156 
3157 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3158 @*/
3159 PetscErrorCode  TSAdjointStep(TS ts)
3160 {
3161   DM               dm;
3162   PetscErrorCode   ierr;
3163 
3164   PetscFunctionBegin;
3165   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3166   ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
3167   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3168 
3169   ts->reason = TS_CONVERGED_ITERATING;
3170   ts->ptime_prev = ts->ptime;
3171   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3172   ierr = VecViewFromOptions(ts->vec_sol, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3173 
3174   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3175   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);
3176   ierr = (*ts->ops->stepadj)(ts);CHKERRQ(ierr);
3177   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3178 
3179   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3180   ierr = DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);CHKERRQ(ierr);
3181 
3182   if (ts->reason < 0) {
3183     if (ts->errorifstepfailed) {
3184       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
3185         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]);
3186       } else if (ts->reason == TS_DIVERGED_STEP_REJECTED) {
3187         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]);
3188       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3189     }
3190   } else if (!ts->reason) {
3191     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3192     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3193   }
3194   PetscFunctionReturn(0);
3195 }
3196 
3197 #undef __FUNCT__
3198 #define __FUNCT__ "TSEvaluateStep"
3199 /*@
3200    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3201 
3202    Collective on TS
3203 
3204    Input Arguments:
3205 +  ts - time stepping context
3206 .  order - desired order of accuracy
3207 -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3208 
3209    Output Arguments:
3210 .  U - state at the end of the current step
3211 
3212    Level: advanced
3213 
3214    Notes:
3215    This function cannot be called until all stages have been evaluated.
3216    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.
3217 
3218 .seealso: TSStep(), TSAdapt
3219 @*/
3220 PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3221 {
3222   PetscErrorCode ierr;
3223 
3224   PetscFunctionBegin;
3225   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3226   PetscValidType(ts,1);
3227   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3228   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3229   ierr = (*ts->ops->evaluatestep)(ts,order,U,done);CHKERRQ(ierr);
3230   PetscFunctionReturn(0);
3231 }
3232 
3233 #undef __FUNCT__
3234 #define __FUNCT__ "TSSolve"
3235 /*@
3236    TSSolve - Steps the requested number of timesteps.
3237 
3238    Collective on TS
3239 
3240    Input Parameter:
3241 +  ts - the TS context obtained from TSCreate()
3242 -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)
3243 
3244    Level: beginner
3245 
3246    Notes:
3247    The final time returned by this function may be different from the time of the internally
3248    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3249    stepped over the final time.
3250 
3251 .keywords: TS, timestep, solve
3252 
3253 .seealso: TSCreate(), TSSetSolution(), TSStep()
3254 @*/
3255 PetscErrorCode TSSolve(TS ts,Vec u)
3256 {
3257   Vec               solution;
3258   PetscErrorCode    ierr;
3259 
3260   PetscFunctionBegin;
3261   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3262   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3263   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 */
3264     PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3265     if (!ts->vec_sol || u == ts->vec_sol) {
3266       ierr = VecDuplicate(u,&solution);CHKERRQ(ierr);
3267       ierr = TSSetSolution(ts,solution);CHKERRQ(ierr);
3268       ierr = VecDestroy(&solution);CHKERRQ(ierr); /* grant ownership */
3269     }
3270     ierr = VecCopy(u,ts->vec_sol);CHKERRQ(ierr);
3271   } else if (u) {
3272     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
3273   }
3274   ierr = TSSetUp(ts);CHKERRQ(ierr); /*compute adj coefficients if the reverse mode is on*/
3275   /* reset time step and iteration counters */
3276   ts->steps             = 0;
3277   ts->ksp_its           = 0;
3278   ts->snes_its          = 0;
3279   ts->num_snes_failures = 0;
3280   ts->reject            = 0;
3281   ts->reason            = TS_CONVERGED_ITERATING;
3282 
3283   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
3284 
3285   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
3286     ierr = (*ts->ops->solve)(ts);CHKERRQ(ierr);
3287     ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);
3288     ts->solvetime = ts->ptime;
3289   } else {
3290     /* steps the requested number of timesteps. */
3291     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3292     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3293     while (!ts->reason) {
3294       ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3295       ierr = TSStep(ts);CHKERRQ(ierr);
3296       if (ts->event) {
3297 	ierr = TSEventMonitor(ts);CHKERRQ(ierr);
3298 	if (ts->event->status != TSEVENT_PROCESSING) {
3299 	  ierr = TSPostStep(ts);CHKERRQ(ierr);
3300 	}
3301       } else {
3302 	ierr = TSPostStep(ts);CHKERRQ(ierr);
3303       }
3304     }
3305     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3306       ierr = TSInterpolate(ts,ts->max_time,u);CHKERRQ(ierr);
3307       ts->solvetime = ts->max_time;
3308       solution = u;
3309     } else {
3310       if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3311       ts->solvetime = ts->ptime;
3312       solution = ts->vec_sol;
3313     }
3314     ierr = TSMonitor(ts,ts->steps,ts->solvetime,solution);CHKERRQ(ierr);
3315     ierr = VecViewFromOptions(u, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3316   }
3317 
3318   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
3319   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
3320   PetscFunctionReturn(0);
3321 }
3322 
3323 #undef __FUNCT__
3324 #define __FUNCT__ "TSAdjointSolve"
3325 /*@
3326    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
3327 
3328    Collective on TS
3329 
3330    Input Parameter:
3331 +  ts - the TS context obtained from TSCreate()
3332 -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)
3333 
3334    Level: intermediate
3335 
3336    Notes:
3337    This must be called after a call to TSSolve() that solves the forward problem
3338 
3339 .keywords: TS, timestep, solve
3340 
3341 .seealso: TSCreate(), TSSetSolution(), TSStep()
3342 @*/
3343 PetscErrorCode TSAdjointSolve(TS ts,Vec u)
3344 {
3345   Vec               solution;
3346   PetscErrorCode    ierr;
3347 
3348   PetscFunctionBegin;
3349   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3350   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3351   if (u) {
3352     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
3353   }
3354   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3355   /* reset time step and iteration counters */
3356   ts->steps             = 0;
3357   ts->ksp_its           = 0;
3358   ts->snes_its          = 0;
3359   ts->num_snes_failures = 0;
3360   ts->reject            = 0;
3361   ts->reason            = TS_CONVERGED_ITERATING;
3362 
3363   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
3364 
3365   if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3366   while (!ts->reason) {
3367     ierr = TSMonitor(ts,ts->max_steps-ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3368     ierr = TSAdjointStep(ts);CHKERRQ(ierr);
3369     if (ts->event) {
3370       ierr = TSEventMonitor(ts);CHKERRQ(ierr);
3371       if (ts->event->status != TSEVENT_PROCESSING) {
3372         ierr = TSPostStep(ts);CHKERRQ(ierr);
3373       }
3374     } else {
3375       ierr = TSPostStep(ts);CHKERRQ(ierr);
3376     }
3377   }
3378   if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3379   ts->solvetime = ts->ptime;
3380   solution = ts->vec_sol;
3381   ierr = VecViewFromOptions(u, ((PetscObject) ts)->prefix, "-ts_view_solution");CHKERRQ(ierr);
3382 
3383   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
3384   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
3385   PetscFunctionReturn(0);
3386 }
3387 
3388 #undef __FUNCT__
3389 #define __FUNCT__ "TSMonitor"
3390 /*@
3391    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
3392 
3393    Collective on TS
3394 
3395    Input Parameters:
3396 +  ts - time stepping context obtained from TSCreate()
3397 .  step - step number that has just completed
3398 .  ptime - model time of the state
3399 -  u - state at the current model time
3400 
3401    Notes:
3402    TSMonitor() is typically used within the time stepping implementations.
3403    Users might call this function when using the TSStep() interface instead of TSSolve().
3404 
3405    Level: advanced
3406 
3407 .keywords: TS, timestep
3408 @*/
3409 PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
3410 {
3411   PetscErrorCode ierr;
3412   PetscInt       i,n = ts->numbermonitors;
3413 
3414   PetscFunctionBegin;
3415   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3416   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
3417   ierr = VecLockPush(u);CHKERRQ(ierr);
3418   for (i=0; i<n; i++) {
3419     ierr = (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);CHKERRQ(ierr);
3420   }
3421   ierr = VecLockPop(u);CHKERRQ(ierr);
3422   PetscFunctionReturn(0);
3423 }
3424 
3425 /* ------------------------------------------------------------------------*/
3426 #undef __FUNCT__
3427 #define __FUNCT__ "TSMonitorLGCtxCreate"
3428 /*@C
3429    TSMonitorLGCtxCreate - Creates a line graph context for use with
3430    TS to monitor the solution process graphically in various ways
3431 
3432    Collective on TS
3433 
3434    Input Parameters:
3435 +  host - the X display to open, or null for the local machine
3436 .  label - the title to put in the title bar
3437 .  x, y - the screen coordinates of the upper left coordinate of the window
3438 .  m, n - the screen width and height in pixels
3439 -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
3440 
3441    Output Parameter:
3442 .  ctx - the context
3443 
3444    Options Database Key:
3445 +  -ts_monitor_lg_timestep - automatically sets line graph monitor
3446 .  -ts_monitor_lg_solution -
3447 .  -ts_monitor_lg_error -
3448 .  -ts_monitor_lg_ksp_iterations -
3449 .  -ts_monitor_lg_snes_iterations -
3450 -  -lg_indicate_data_points <true,false> - indicate the data points (at each time step) on the plot; default is true
3451 
3452    Notes:
3453    Use TSMonitorLGCtxDestroy() to destroy.
3454 
3455    Level: intermediate
3456 
3457 .keywords: TS, monitor, line graph, residual, seealso
3458 
3459 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
3460 
3461 @*/
3462 PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
3463 {
3464   PetscDraw      win;
3465   PetscErrorCode ierr;
3466 
3467   PetscFunctionBegin;
3468   ierr = PetscNew(ctx);CHKERRQ(ierr);
3469   ierr = PetscDrawCreate(comm,host,label,x,y,m,n,&win);CHKERRQ(ierr);
3470   ierr = PetscDrawSetFromOptions(win);CHKERRQ(ierr);
3471   ierr = PetscDrawLGCreate(win,1,&(*ctx)->lg);CHKERRQ(ierr);
3472   ierr = PetscLogObjectParent((PetscObject)(*ctx)->lg,(PetscObject)win);CHKERRQ(ierr);
3473   ierr = PetscDrawLGIndicateDataPoints((*ctx)->lg,PETSC_TRUE);CHKERRQ(ierr);
3474   ierr = PetscDrawLGSetFromOptions((*ctx)->lg);CHKERRQ(ierr);
3475   (*ctx)->howoften = howoften;
3476   PetscFunctionReturn(0);
3477 }
3478 
3479 #undef __FUNCT__
3480 #define __FUNCT__ "TSMonitorLGTimeStep"
3481 PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
3482 {
3483   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
3484   PetscReal      x   = ptime,y;
3485   PetscErrorCode ierr;
3486 
3487   PetscFunctionBegin;
3488   if (!step) {
3489     PetscDrawAxis axis;
3490     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
3491     ierr = PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");CHKERRQ(ierr);
3492     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
3493     ierr = PetscDrawLGIndicateDataPoints(ctx->lg,PETSC_TRUE);CHKERRQ(ierr);
3494   }
3495   ierr = TSGetTimeStep(ts,&y);CHKERRQ(ierr);
3496   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
3497   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
3498     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
3499   }
3500   PetscFunctionReturn(0);
3501 }
3502 
3503 #undef __FUNCT__
3504 #define __FUNCT__ "TSMonitorLGCtxDestroy"
3505 /*@C
3506    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
3507    with TSMonitorLGCtxCreate().
3508 
3509    Collective on TSMonitorLGCtx
3510 
3511    Input Parameter:
3512 .  ctx - the monitor context
3513 
3514    Level: intermediate
3515 
3516 .keywords: TS, monitor, line graph, destroy
3517 
3518 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
3519 @*/
3520 PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
3521 {
3522   PetscDraw      draw;
3523   PetscErrorCode ierr;
3524 
3525   PetscFunctionBegin;
3526   ierr = PetscDrawLGGetDraw((*ctx)->lg,&draw);CHKERRQ(ierr);
3527   ierr = PetscDrawDestroy(&draw);CHKERRQ(ierr);
3528   ierr = PetscDrawLGDestroy(&(*ctx)->lg);CHKERRQ(ierr);
3529   ierr = PetscFree(*ctx);CHKERRQ(ierr);
3530   PetscFunctionReturn(0);
3531 }
3532 
3533 #undef __FUNCT__
3534 #define __FUNCT__ "TSGetTime"
3535 /*@
3536    TSGetTime - Gets the time of the most recently completed step.
3537 
3538    Not Collective
3539 
3540    Input Parameter:
3541 .  ts - the TS context obtained from TSCreate()
3542 
3543    Output Parameter:
3544 .  t  - the current time
3545 
3546    Level: beginner
3547 
3548    Note:
3549    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
3550    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
3551 
3552 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
3553 
3554 .keywords: TS, get, time
3555 @*/
3556 PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3557 {
3558   PetscFunctionBegin;
3559   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3560   PetscValidRealPointer(t,2);
3561   *t = ts->ptime;
3562   PetscFunctionReturn(0);
3563 }
3564 
3565 #undef __FUNCT__
3566 #define __FUNCT__ "TSGetPrevTime"
3567 /*@
3568    TSGetPrevTime - Gets the starting time of the previously completed step.
3569 
3570    Not Collective
3571 
3572    Input Parameter:
3573 .  ts - the TS context obtained from TSCreate()
3574 
3575    Output Parameter:
3576 .  t  - the previous time
3577 
3578    Level: beginner
3579 
3580 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
3581 
3582 .keywords: TS, get, time
3583 @*/
3584 PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
3585 {
3586   PetscFunctionBegin;
3587   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3588   PetscValidRealPointer(t,2);
3589   *t = ts->ptime_prev;
3590   PetscFunctionReturn(0);
3591 }
3592 
3593 #undef __FUNCT__
3594 #define __FUNCT__ "TSSetTime"
3595 /*@
3596    TSSetTime - Allows one to reset the time.
3597 
3598    Logically Collective on TS
3599 
3600    Input Parameters:
3601 +  ts - the TS context obtained from TSCreate()
3602 -  time - the time
3603 
3604    Level: intermediate
3605 
3606 .seealso: TSGetTime(), TSSetDuration()
3607 
3608 .keywords: TS, set, time
3609 @*/
3610 PetscErrorCode  TSSetTime(TS ts, PetscReal t)
3611 {
3612   PetscFunctionBegin;
3613   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3614   PetscValidLogicalCollectiveReal(ts,t,2);
3615   ts->ptime = t;
3616   PetscFunctionReturn(0);
3617 }
3618 
3619 #undef __FUNCT__
3620 #define __FUNCT__ "TSSetOptionsPrefix"
3621 /*@C
3622    TSSetOptionsPrefix - Sets the prefix used for searching for all
3623    TS options in the database.
3624 
3625    Logically Collective on TS
3626 
3627    Input Parameter:
3628 +  ts     - The TS context
3629 -  prefix - The prefix to prepend to all option names
3630 
3631    Notes:
3632    A hyphen (-) must NOT be given at the beginning of the prefix name.
3633    The first character of all runtime options is AUTOMATICALLY the
3634    hyphen.
3635 
3636    Level: advanced
3637 
3638 .keywords: TS, set, options, prefix, database
3639 
3640 .seealso: TSSetFromOptions()
3641 
3642 @*/
3643 PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
3644 {
3645   PetscErrorCode ierr;
3646   SNES           snes;
3647 
3648   PetscFunctionBegin;
3649   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3650   ierr = PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3651   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3652   ierr = SNESSetOptionsPrefix(snes,prefix);CHKERRQ(ierr);
3653   PetscFunctionReturn(0);
3654 }
3655 
3656 
3657 #undef __FUNCT__
3658 #define __FUNCT__ "TSAppendOptionsPrefix"
3659 /*@C
3660    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3661    TS options in the database.
3662 
3663    Logically Collective on TS
3664 
3665    Input Parameter:
3666 +  ts     - The TS context
3667 -  prefix - The prefix to prepend to all option names
3668 
3669    Notes:
3670    A hyphen (-) must NOT be given at the beginning of the prefix name.
3671    The first character of all runtime options is AUTOMATICALLY the
3672    hyphen.
3673 
3674    Level: advanced
3675 
3676 .keywords: TS, append, options, prefix, database
3677 
3678 .seealso: TSGetOptionsPrefix()
3679 
3680 @*/
3681 PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
3682 {
3683   PetscErrorCode ierr;
3684   SNES           snes;
3685 
3686   PetscFunctionBegin;
3687   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3688   ierr = PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3689   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3690   ierr = SNESAppendOptionsPrefix(snes,prefix);CHKERRQ(ierr);
3691   PetscFunctionReturn(0);
3692 }
3693 
3694 #undef __FUNCT__
3695 #define __FUNCT__ "TSGetOptionsPrefix"
3696 /*@C
3697    TSGetOptionsPrefix - Sets the prefix used for searching for all
3698    TS options in the database.
3699 
3700    Not Collective
3701 
3702    Input Parameter:
3703 .  ts - The TS context
3704 
3705    Output Parameter:
3706 .  prefix - A pointer to the prefix string used
3707 
3708    Notes: On the fortran side, the user should pass in a string 'prifix' of
3709    sufficient length to hold the prefix.
3710 
3711    Level: intermediate
3712 
3713 .keywords: TS, get, options, prefix, database
3714 
3715 .seealso: TSAppendOptionsPrefix()
3716 @*/
3717 PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
3718 {
3719   PetscErrorCode ierr;
3720 
3721   PetscFunctionBegin;
3722   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3723   PetscValidPointer(prefix,2);
3724   ierr = PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
3725   PetscFunctionReturn(0);
3726 }
3727 
3728 #undef __FUNCT__
3729 #define __FUNCT__ "TSGetRHSJacobian"
3730 /*@C
3731    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
3732 
3733    Not Collective, but parallel objects are returned if TS is parallel
3734 
3735    Input Parameter:
3736 .  ts  - The TS context obtained from TSCreate()
3737 
3738    Output Parameters:
3739 +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
3740 .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
3741 .  func - Function to compute the Jacobian of the RHS  (or NULL)
3742 -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
3743 
3744    Notes: You can pass in NULL for any return argument you do not need.
3745 
3746    Level: intermediate
3747 
3748 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
3749 
3750 .keywords: TS, timestep, get, matrix, Jacobian
3751 @*/
3752 PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
3753 {
3754   PetscErrorCode ierr;
3755   SNES           snes;
3756   DM             dm;
3757 
3758   PetscFunctionBegin;
3759   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3760   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
3761   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3762   ierr = DMTSGetRHSJacobian(dm,func,ctx);CHKERRQ(ierr);
3763   PetscFunctionReturn(0);
3764 }
3765 
3766 #undef __FUNCT__
3767 #define __FUNCT__ "TSGetIJacobian"
3768 /*@C
3769    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
3770 
3771    Not Collective, but parallel objects are returned if TS is parallel
3772 
3773    Input Parameter:
3774 .  ts  - The TS context obtained from TSCreate()
3775 
3776    Output Parameters:
3777 +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
3778 .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
3779 .  f   - The function to compute the matrices
3780 - ctx - User-defined context for Jacobian evaluation routine
3781 
3782    Notes: You can pass in NULL for any return argument you do not need.
3783 
3784    Level: advanced
3785 
3786 .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
3787 
3788 .keywords: TS, timestep, get, matrix, Jacobian
3789 @*/
3790 PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
3791 {
3792   PetscErrorCode ierr;
3793   SNES           snes;
3794   DM             dm;
3795 
3796   PetscFunctionBegin;
3797   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3798   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
3799   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
3800   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3801   ierr = DMTSGetIJacobian(dm,f,ctx);CHKERRQ(ierr);
3802   PetscFunctionReturn(0);
3803 }
3804 
3805 
3806 #undef __FUNCT__
3807 #define __FUNCT__ "TSMonitorDrawSolution"
3808 /*@C
3809    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
3810    VecView() for the solution at each timestep
3811 
3812    Collective on TS
3813 
3814    Input Parameters:
3815 +  ts - the TS context
3816 .  step - current time-step
3817 .  ptime - current time
3818 -  dummy - either a viewer or NULL
3819 
3820    Options Database:
3821 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
3822 
3823    Notes: the initial solution and current solution are not displayed with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
3824        will look bad
3825 
3826    Level: intermediate
3827 
3828 .keywords: TS,  vector, monitor, view
3829 
3830 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3831 @*/
3832 PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3833 {
3834   PetscErrorCode   ierr;
3835   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
3836   PetscDraw        draw;
3837 
3838   PetscFunctionBegin;
3839   if (!step && ictx->showinitial) {
3840     if (!ictx->initialsolution) {
3841       ierr = VecDuplicate(u,&ictx->initialsolution);CHKERRQ(ierr);
3842     }
3843     ierr = VecCopy(u,ictx->initialsolution);CHKERRQ(ierr);
3844   }
3845   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
3846 
3847   if (ictx->showinitial) {
3848     PetscReal pause;
3849     ierr = PetscViewerDrawGetPause(ictx->viewer,&pause);CHKERRQ(ierr);
3850     ierr = PetscViewerDrawSetPause(ictx->viewer,0.0);CHKERRQ(ierr);
3851     ierr = VecView(ictx->initialsolution,ictx->viewer);CHKERRQ(ierr);
3852     ierr = PetscViewerDrawSetPause(ictx->viewer,pause);CHKERRQ(ierr);
3853     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);CHKERRQ(ierr);
3854   }
3855   ierr = VecView(u,ictx->viewer);CHKERRQ(ierr);
3856   if (ictx->showtimestepandtime) {
3857     PetscReal xl,yl,xr,yr,tw,w,h;
3858     char      time[32];
3859     size_t    len;
3860 
3861     ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
3862     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
3863     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
3864     ierr =  PetscStrlen(time,&len);CHKERRQ(ierr);
3865     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
3866     w    = xl + .5*(xr - xl) - .5*len*tw;
3867     h    = yl + .95*(yr - yl);
3868     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
3869     ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
3870   }
3871 
3872   if (ictx->showinitial) {
3873     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);CHKERRQ(ierr);
3874   }
3875   PetscFunctionReturn(0);
3876 }
3877 
3878 #undef __FUNCT__
3879 #define __FUNCT__ "TSMonitorDrawSolutionPhase"
3880 /*@C
3881    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
3882 
3883    Collective on TS
3884 
3885    Input Parameters:
3886 +  ts - the TS context
3887 .  step - current time-step
3888 .  ptime - current time
3889 -  dummy - either a viewer or NULL
3890 
3891    Level: intermediate
3892 
3893 .keywords: TS,  vector, monitor, view
3894 
3895 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3896 @*/
3897 PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3898 {
3899   PetscErrorCode    ierr;
3900   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
3901   PetscDraw         draw;
3902   MPI_Comm          comm;
3903   PetscInt          n;
3904   PetscMPIInt       size;
3905   PetscReal         xl,yl,xr,yr,tw,w,h;
3906   char              time[32];
3907   size_t            len;
3908   const PetscScalar *U;
3909 
3910   PetscFunctionBegin;
3911   ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
3912   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
3913   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
3914   ierr = VecGetSize(u,&n);CHKERRQ(ierr);
3915   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");
3916 
3917   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
3918 
3919   ierr = VecGetArrayRead(u,&U);CHKERRQ(ierr);
3920   ierr = PetscDrawAxisGetLimits(ictx->axis,&xl,&xr,&yl,&yr);CHKERRQ(ierr);
3921   if ((PetscRealPart(U[0]) < xl) || (PetscRealPart(U[1]) < yl) || (PetscRealPart(U[0]) > xr) || (PetscRealPart(U[1]) > yr)) {
3922       ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
3923       PetscFunctionReturn(0);
3924   }
3925   if (!step) ictx->color++;
3926   ierr = PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);CHKERRQ(ierr);
3927   ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
3928 
3929   if (ictx->showtimestepandtime) {
3930     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
3931     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
3932     ierr = PetscStrlen(time,&len);CHKERRQ(ierr);
3933     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
3934     w    = xl + .5*(xr - xl) - .5*len*tw;
3935     h    = yl + .95*(yr - yl);
3936     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
3937   }
3938   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
3939   PetscFunctionReturn(0);
3940 }
3941 
3942 
3943 #undef __FUNCT__
3944 #define __FUNCT__ "TSMonitorDrawCtxDestroy"
3945 /*@C
3946    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
3947 
3948    Collective on TS
3949 
3950    Input Parameters:
3951 .    ctx - the monitor context
3952 
3953    Level: intermediate
3954 
3955 .keywords: TS,  vector, monitor, view
3956 
3957 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
3958 @*/
3959 PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
3960 {
3961   PetscErrorCode ierr;
3962 
3963   PetscFunctionBegin;
3964   ierr = PetscDrawAxisDestroy(&(*ictx)->axis);CHKERRQ(ierr);
3965   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
3966   ierr = VecDestroy(&(*ictx)->initialsolution);CHKERRQ(ierr);
3967   ierr = PetscFree(*ictx);CHKERRQ(ierr);
3968   PetscFunctionReturn(0);
3969 }
3970 
3971 #undef __FUNCT__
3972 #define __FUNCT__ "TSMonitorDrawCtxCreate"
3973 /*@C
3974    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
3975 
3976    Collective on TS
3977 
3978    Input Parameter:
3979 .    ts - time-step context
3980 
3981    Output Patameter:
3982 .    ctx - the monitor context
3983 
3984    Options Database:
3985 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
3986 
3987    Level: intermediate
3988 
3989 .keywords: TS,  vector, monitor, view
3990 
3991 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
3992 @*/
3993 PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
3994 {
3995   PetscErrorCode   ierr;
3996 
3997   PetscFunctionBegin;
3998   ierr = PetscNew(ctx);CHKERRQ(ierr);
3999   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
4000   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
4001 
4002   (*ctx)->howoften    = howoften;
4003   (*ctx)->showinitial = PETSC_FALSE;
4004   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);CHKERRQ(ierr);
4005 
4006   (*ctx)->showtimestepandtime = PETSC_FALSE;
4007   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);CHKERRQ(ierr);
4008   (*ctx)->color = PETSC_DRAW_WHITE;
4009   PetscFunctionReturn(0);
4010 }
4011 
4012 #undef __FUNCT__
4013 #define __FUNCT__ "TSMonitorDrawError"
4014 /*@C
4015    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4016    VecView() for the error at each timestep
4017 
4018    Collective on TS
4019 
4020    Input Parameters:
4021 +  ts - the TS context
4022 .  step - current time-step
4023 .  ptime - current time
4024 -  dummy - either a viewer or NULL
4025 
4026    Level: intermediate
4027 
4028 .keywords: TS,  vector, monitor, view
4029 
4030 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4031 @*/
4032 PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4033 {
4034   PetscErrorCode   ierr;
4035   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4036   PetscViewer      viewer = ctx->viewer;
4037   Vec              work;
4038 
4039   PetscFunctionBegin;
4040   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4041   ierr = VecDuplicate(u,&work);CHKERRQ(ierr);
4042   ierr = TSComputeSolutionFunction(ts,ptime,work);CHKERRQ(ierr);
4043   ierr = VecAXPY(work,-1.0,u);CHKERRQ(ierr);
4044   ierr = VecView(work,viewer);CHKERRQ(ierr);
4045   ierr = VecDestroy(&work);CHKERRQ(ierr);
4046   PetscFunctionReturn(0);
4047 }
4048 
4049 #include <petsc-private/dmimpl.h>
4050 #undef __FUNCT__
4051 #define __FUNCT__ "TSSetDM"
4052 /*@
4053    TSSetDM - Sets the DM that may be used by some preconditioners
4054 
4055    Logically Collective on TS and DM
4056 
4057    Input Parameters:
4058 +  ts - the preconditioner context
4059 -  dm - the dm
4060 
4061    Level: intermediate
4062 
4063 
4064 .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4065 @*/
4066 PetscErrorCode  TSSetDM(TS ts,DM dm)
4067 {
4068   PetscErrorCode ierr;
4069   SNES           snes;
4070   DMTS           tsdm;
4071 
4072   PetscFunctionBegin;
4073   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4074   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
4075   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4076     if (ts->dm->dmts && !dm->dmts) {
4077       ierr = DMCopyDMTS(ts->dm,dm);CHKERRQ(ierr);
4078       ierr = DMGetDMTS(ts->dm,&tsdm);CHKERRQ(ierr);
4079       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4080         tsdm->originaldm = dm;
4081       }
4082     }
4083     ierr = DMDestroy(&ts->dm);CHKERRQ(ierr);
4084   }
4085   ts->dm = dm;
4086 
4087   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4088   ierr = SNESSetDM(snes,dm);CHKERRQ(ierr);
4089   PetscFunctionReturn(0);
4090 }
4091 
4092 #undef __FUNCT__
4093 #define __FUNCT__ "TSGetDM"
4094 /*@
4095    TSGetDM - Gets the DM that may be used by some preconditioners
4096 
4097    Not Collective
4098 
4099    Input Parameter:
4100 . ts - the preconditioner context
4101 
4102    Output Parameter:
4103 .  dm - the dm
4104 
4105    Level: intermediate
4106 
4107 
4108 .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4109 @*/
4110 PetscErrorCode  TSGetDM(TS ts,DM *dm)
4111 {
4112   PetscErrorCode ierr;
4113 
4114   PetscFunctionBegin;
4115   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4116   if (!ts->dm) {
4117     ierr = DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);CHKERRQ(ierr);
4118     if (ts->snes) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
4119   }
4120   *dm = ts->dm;
4121   PetscFunctionReturn(0);
4122 }
4123 
4124 #undef __FUNCT__
4125 #define __FUNCT__ "SNESTSFormFunction"
4126 /*@
4127    SNESTSFormFunction - Function to evaluate nonlinear residual
4128 
4129    Logically Collective on SNES
4130 
4131    Input Parameter:
4132 + snes - nonlinear solver
4133 . U - the current state at which to evaluate the residual
4134 - ctx - user context, must be a TS
4135 
4136    Output Parameter:
4137 . F - the nonlinear residual
4138 
4139    Notes:
4140    This function is not normally called by users and is automatically registered with the SNES used by TS.
4141    It is most frequently passed to MatFDColoringSetFunction().
4142 
4143    Level: advanced
4144 
4145 .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4146 @*/
4147 PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4148 {
4149   TS             ts = (TS)ctx;
4150   PetscErrorCode ierr;
4151 
4152   PetscFunctionBegin;
4153   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4154   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4155   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
4156   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
4157   ierr = (ts->ops->snesfunction)(snes,U,F,ts);CHKERRQ(ierr);
4158   PetscFunctionReturn(0);
4159 }
4160 
4161 #undef __FUNCT__
4162 #define __FUNCT__ "SNESTSFormJacobian"
4163 /*@
4164    SNESTSFormJacobian - Function to evaluate the Jacobian
4165 
4166    Collective on SNES
4167 
4168    Input Parameter:
4169 + snes - nonlinear solver
4170 . U - the current state at which to evaluate the residual
4171 - ctx - user context, must be a TS
4172 
4173    Output Parameter:
4174 + A - the Jacobian
4175 . B - the preconditioning matrix (may be the same as A)
4176 - flag - indicates any structure change in the matrix
4177 
4178    Notes:
4179    This function is not normally called by users and is automatically registered with the SNES used by TS.
4180 
4181    Level: developer
4182 
4183 .seealso: SNESSetJacobian()
4184 @*/
4185 PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4186 {
4187   TS             ts = (TS)ctx;
4188   PetscErrorCode ierr;
4189 
4190   PetscFunctionBegin;
4191   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4192   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4193   PetscValidPointer(A,3);
4194   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
4195   PetscValidPointer(B,4);
4196   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
4197   PetscValidHeaderSpecific(ts,TS_CLASSID,6);
4198   ierr = (ts->ops->snesjacobian)(snes,U,A,B,ts);CHKERRQ(ierr);
4199   PetscFunctionReturn(0);
4200 }
4201 
4202 #undef __FUNCT__
4203 #define __FUNCT__ "TSComputeRHSFunctionLinear"
4204 /*@C
4205    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems only
4206 
4207    Collective on TS
4208 
4209    Input Arguments:
4210 +  ts - time stepping context
4211 .  t - time at which to evaluate
4212 .  U - state at which to evaluate
4213 -  ctx - context
4214 
4215    Output Arguments:
4216 .  F - right hand side
4217 
4218    Level: intermediate
4219 
4220    Notes:
4221    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
4222    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
4223 
4224 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
4225 @*/
4226 PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
4227 {
4228   PetscErrorCode ierr;
4229   Mat            Arhs,Brhs;
4230 
4231   PetscFunctionBegin;
4232   ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
4233   ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
4234   ierr = MatMult(Arhs,U,F);CHKERRQ(ierr);
4235   PetscFunctionReturn(0);
4236 }
4237 
4238 #undef __FUNCT__
4239 #define __FUNCT__ "TSComputeRHSJacobianConstant"
4240 /*@C
4241    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
4242 
4243    Collective on TS
4244 
4245    Input Arguments:
4246 +  ts - time stepping context
4247 .  t - time at which to evaluate
4248 .  U - state at which to evaluate
4249 -  ctx - context
4250 
4251    Output Arguments:
4252 +  A - pointer to operator
4253 .  B - pointer to preconditioning matrix
4254 -  flg - matrix structure flag
4255 
4256    Level: intermediate
4257 
4258    Notes:
4259    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
4260 
4261 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
4262 @*/
4263 PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
4264 {
4265   PetscFunctionBegin;
4266   PetscFunctionReturn(0);
4267 }
4268 
4269 #undef __FUNCT__
4270 #define __FUNCT__ "TSComputeIFunctionLinear"
4271 /*@C
4272    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
4273 
4274    Collective on TS
4275 
4276    Input Arguments:
4277 +  ts - time stepping context
4278 .  t - time at which to evaluate
4279 .  U - state at which to evaluate
4280 .  Udot - time derivative of state vector
4281 -  ctx - context
4282 
4283    Output Arguments:
4284 .  F - left hand side
4285 
4286    Level: intermediate
4287 
4288    Notes:
4289    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
4290    user is required to write their own TSComputeIFunction.
4291    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
4292    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
4293 
4294 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
4295 @*/
4296 PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
4297 {
4298   PetscErrorCode ierr;
4299   Mat            A,B;
4300 
4301   PetscFunctionBegin;
4302   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
4303   ierr = TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);CHKERRQ(ierr);
4304   ierr = MatMult(A,Udot,F);CHKERRQ(ierr);
4305   PetscFunctionReturn(0);
4306 }
4307 
4308 #undef __FUNCT__
4309 #define __FUNCT__ "TSComputeIJacobianConstant"
4310 /*@C
4311    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
4312 
4313    Collective on TS
4314 
4315    Input Arguments:
4316 +  ts - time stepping context
4317 .  t - time at which to evaluate
4318 .  U - state at which to evaluate
4319 .  Udot - time derivative of state vector
4320 .  shift - shift to apply
4321 -  ctx - context
4322 
4323    Output Arguments:
4324 +  A - pointer to operator
4325 .  B - pointer to preconditioning matrix
4326 -  flg - matrix structure flag
4327 
4328    Level: advanced
4329 
4330    Notes:
4331    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
4332 
4333    It is only appropriate for problems of the form
4334 
4335 $     M Udot = F(U,t)
4336 
4337   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4338   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4339   an implicit operator of the form
4340 
4341 $    shift*M + J
4342 
4343   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
4344   a copy of M or reassemble it when requested.
4345 
4346 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
4347 @*/
4348 PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
4349 {
4350   PetscErrorCode ierr;
4351 
4352   PetscFunctionBegin;
4353   ierr = MatScale(A, shift / ts->ijacobian.shift);CHKERRQ(ierr);
4354   ts->ijacobian.shift = shift;
4355   PetscFunctionReturn(0);
4356 }
4357 
4358 #undef __FUNCT__
4359 #define __FUNCT__ "TSGetEquationType"
4360 /*@
4361    TSGetEquationType - Gets the type of the equation that TS is solving.
4362 
4363    Not Collective
4364 
4365    Input Parameter:
4366 .  ts - the TS context
4367 
4368    Output Parameter:
4369 .  equation_type - see TSEquationType
4370 
4371    Level: beginner
4372 
4373 .keywords: TS, equation type
4374 
4375 .seealso: TSSetEquationType(), TSEquationType
4376 @*/
4377 PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4378 {
4379   PetscFunctionBegin;
4380   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4381   PetscValidPointer(equation_type,2);
4382   *equation_type = ts->equation_type;
4383   PetscFunctionReturn(0);
4384 }
4385 
4386 #undef __FUNCT__
4387 #define __FUNCT__ "TSSetEquationType"
4388 /*@
4389    TSSetEquationType - Sets the type of the equation that TS is solving.
4390 
4391    Not Collective
4392 
4393    Input Parameter:
4394 +  ts - the TS context
4395 .  equation_type - see TSEquationType
4396 
4397    Level: advanced
4398 
4399 .keywords: TS, equation type
4400 
4401 .seealso: TSGetEquationType(), TSEquationType
4402 @*/
4403 PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4404 {
4405   PetscFunctionBegin;
4406   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4407   ts->equation_type = equation_type;
4408   PetscFunctionReturn(0);
4409 }
4410 
4411 #undef __FUNCT__
4412 #define __FUNCT__ "TSGetConvergedReason"
4413 /*@
4414    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
4415 
4416    Not Collective
4417 
4418    Input Parameter:
4419 .  ts - the TS context
4420 
4421    Output Parameter:
4422 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4423             manual pages for the individual convergence tests for complete lists
4424 
4425    Level: beginner
4426 
4427    Notes:
4428    Can only be called after the call to TSSolve() is complete.
4429 
4430 .keywords: TS, nonlinear, set, convergence, test
4431 
4432 .seealso: TSSetConvergenceTest(), TSConvergedReason
4433 @*/
4434 PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
4435 {
4436   PetscFunctionBegin;
4437   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4438   PetscValidPointer(reason,2);
4439   *reason = ts->reason;
4440   PetscFunctionReturn(0);
4441 }
4442 
4443 #undef __FUNCT__
4444 #define __FUNCT__ "TSSetConvergedReason"
4445 /*@
4446    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
4447 
4448    Not Collective
4449 
4450    Input Parameter:
4451 +  ts - the TS context
4452 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4453             manual pages for the individual convergence tests for complete lists
4454 
4455    Level: advanced
4456 
4457    Notes:
4458    Can only be called during TSSolve() is active.
4459 
4460 .keywords: TS, nonlinear, set, convergence, test
4461 
4462 .seealso: TSConvergedReason
4463 @*/
4464 PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4465 {
4466   PetscFunctionBegin;
4467   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4468   ts->reason = reason;
4469   PetscFunctionReturn(0);
4470 }
4471 
4472 #undef __FUNCT__
4473 #define __FUNCT__ "TSGetSolveTime"
4474 /*@
4475    TSGetSolveTime - Gets the time after a call to TSSolve()
4476 
4477    Not Collective
4478 
4479    Input Parameter:
4480 .  ts - the TS context
4481 
4482    Output Parameter:
4483 .  ftime - the final time. This time should correspond to the final time set with TSSetDuration()
4484 
4485    Level: beginner
4486 
4487    Notes:
4488    Can only be called after the call to TSSolve() is complete.
4489 
4490 .keywords: TS, nonlinear, set, convergence, test
4491 
4492 .seealso: TSSetConvergenceTest(), TSConvergedReason
4493 @*/
4494 PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4495 {
4496   PetscFunctionBegin;
4497   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4498   PetscValidPointer(ftime,2);
4499   *ftime = ts->solvetime;
4500   PetscFunctionReturn(0);
4501 }
4502 
4503 #undef __FUNCT__
4504 #define __FUNCT__ "TSGetSNESIterations"
4505 /*@
4506    TSGetSNESIterations - Gets the total number of nonlinear iterations
4507    used by the time integrator.
4508 
4509    Not Collective
4510 
4511    Input Parameter:
4512 .  ts - TS context
4513 
4514    Output Parameter:
4515 .  nits - number of nonlinear iterations
4516 
4517    Notes:
4518    This counter is reset to zero for each successive call to TSSolve().
4519 
4520    Level: intermediate
4521 
4522 .keywords: TS, get, number, nonlinear, iterations
4523 
4524 .seealso:  TSGetKSPIterations()
4525 @*/
4526 PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
4527 {
4528   PetscFunctionBegin;
4529   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4530   PetscValidIntPointer(nits,2);
4531   *nits = ts->snes_its;
4532   PetscFunctionReturn(0);
4533 }
4534 
4535 #undef __FUNCT__
4536 #define __FUNCT__ "TSGetKSPIterations"
4537 /*@
4538    TSGetKSPIterations - Gets the total number of linear iterations
4539    used by the time integrator.
4540 
4541    Not Collective
4542 
4543    Input Parameter:
4544 .  ts - TS context
4545 
4546    Output Parameter:
4547 .  lits - number of linear iterations
4548 
4549    Notes:
4550    This counter is reset to zero for each successive call to TSSolve().
4551 
4552    Level: intermediate
4553 
4554 .keywords: TS, get, number, linear, iterations
4555 
4556 .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
4557 @*/
4558 PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
4559 {
4560   PetscFunctionBegin;
4561   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4562   PetscValidIntPointer(lits,2);
4563   *lits = ts->ksp_its;
4564   PetscFunctionReturn(0);
4565 }
4566 
4567 #undef __FUNCT__
4568 #define __FUNCT__ "TSGetStepRejections"
4569 /*@
4570    TSGetStepRejections - Gets the total number of rejected steps.
4571 
4572    Not Collective
4573 
4574    Input Parameter:
4575 .  ts - TS context
4576 
4577    Output Parameter:
4578 .  rejects - number of steps rejected
4579 
4580    Notes:
4581    This counter is reset to zero for each successive call to TSSolve().
4582 
4583    Level: intermediate
4584 
4585 .keywords: TS, get, number
4586 
4587 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
4588 @*/
4589 PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4590 {
4591   PetscFunctionBegin;
4592   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4593   PetscValidIntPointer(rejects,2);
4594   *rejects = ts->reject;
4595   PetscFunctionReturn(0);
4596 }
4597 
4598 #undef __FUNCT__
4599 #define __FUNCT__ "TSGetSNESFailures"
4600 /*@
4601    TSGetSNESFailures - Gets the total number of failed SNES solves
4602 
4603    Not Collective
4604 
4605    Input Parameter:
4606 .  ts - TS context
4607 
4608    Output Parameter:
4609 .  fails - number of failed nonlinear solves
4610 
4611    Notes:
4612    This counter is reset to zero for each successive call to TSSolve().
4613 
4614    Level: intermediate
4615 
4616 .keywords: TS, get, number
4617 
4618 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
4619 @*/
4620 PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4621 {
4622   PetscFunctionBegin;
4623   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4624   PetscValidIntPointer(fails,2);
4625   *fails = ts->num_snes_failures;
4626   PetscFunctionReturn(0);
4627 }
4628 
4629 #undef __FUNCT__
4630 #define __FUNCT__ "TSSetMaxStepRejections"
4631 /*@
4632    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
4633 
4634    Not Collective
4635 
4636    Input Parameter:
4637 +  ts - TS context
4638 -  rejects - maximum number of rejected steps, pass -1 for unlimited
4639 
4640    Notes:
4641    The counter is reset to zero for each step
4642 
4643    Options Database Key:
4644  .  -ts_max_reject - Maximum number of step rejections before a step fails
4645 
4646    Level: intermediate
4647 
4648 .keywords: TS, set, maximum, number
4649 
4650 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4651 @*/
4652 PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4653 {
4654   PetscFunctionBegin;
4655   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4656   ts->max_reject = rejects;
4657   PetscFunctionReturn(0);
4658 }
4659 
4660 #undef __FUNCT__
4661 #define __FUNCT__ "TSSetMaxSNESFailures"
4662 /*@
4663    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
4664 
4665    Not Collective
4666 
4667    Input Parameter:
4668 +  ts - TS context
4669 -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4670 
4671    Notes:
4672    The counter is reset to zero for each successive call to TSSolve().
4673 
4674    Options Database Key:
4675  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4676 
4677    Level: intermediate
4678 
4679 .keywords: TS, set, maximum, number
4680 
4681 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4682 @*/
4683 PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4684 {
4685   PetscFunctionBegin;
4686   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4687   ts->max_snes_failures = fails;
4688   PetscFunctionReturn(0);
4689 }
4690 
4691 #undef __FUNCT__
4692 #define __FUNCT__ "TSSetErrorIfStepFails"
4693 /*@
4694    TSSetErrorIfStepFails - Error if no step succeeds
4695 
4696    Not Collective
4697 
4698    Input Parameter:
4699 +  ts - TS context
4700 -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
4701 
4702    Options Database Key:
4703  .  -ts_error_if_step_fails - Error if no step succeeds
4704 
4705    Level: intermediate
4706 
4707 .keywords: TS, set, error
4708 
4709 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4710 @*/
4711 PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4712 {
4713   PetscFunctionBegin;
4714   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4715   ts->errorifstepfailed = err;
4716   PetscFunctionReturn(0);
4717 }
4718 
4719 #undef __FUNCT__
4720 #define __FUNCT__ "TSMonitorSolutionBinary"
4721 /*@C
4722    TSMonitorSolutionBinary - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file
4723 
4724    Collective on TS
4725 
4726    Input Parameters:
4727 +  ts - the TS context
4728 .  step - current time-step
4729 .  ptime - current time
4730 .  u - current state
4731 -  viewer - binary viewer
4732 
4733    Level: intermediate
4734 
4735 .keywords: TS,  vector, monitor, view
4736 
4737 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4738 @*/
4739 PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
4740 {
4741   PetscErrorCode ierr;
4742   PetscViewer    v = (PetscViewer)viewer;
4743 
4744   PetscFunctionBegin;
4745   ierr = VecView(u,v);CHKERRQ(ierr);
4746   PetscFunctionReturn(0);
4747 }
4748 
4749 #undef __FUNCT__
4750 #define __FUNCT__ "TSMonitorSolutionVTK"
4751 /*@C
4752    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
4753 
4754    Collective on TS
4755 
4756    Input Parameters:
4757 +  ts - the TS context
4758 .  step - current time-step
4759 .  ptime - current time
4760 .  u - current state
4761 -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
4762 
4763    Level: intermediate
4764 
4765    Notes:
4766    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.
4767    These are named according to the file name template.
4768 
4769    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
4770 
4771 .keywords: TS,  vector, monitor, view
4772 
4773 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4774 @*/
4775 PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
4776 {
4777   PetscErrorCode ierr;
4778   char           filename[PETSC_MAX_PATH_LEN];
4779   PetscViewer    viewer;
4780 
4781   PetscFunctionBegin;
4782   ierr = PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);CHKERRQ(ierr);
4783   ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);
4784   ierr = VecView(u,viewer);CHKERRQ(ierr);
4785   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
4786   PetscFunctionReturn(0);
4787 }
4788 
4789 #undef __FUNCT__
4790 #define __FUNCT__ "TSMonitorSolutionVTKDestroy"
4791 /*@C
4792    TSMonitorSolutionVTKDestroy - Destroy context for monitoring
4793 
4794    Collective on TS
4795 
4796    Input Parameters:
4797 .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
4798 
4799    Level: intermediate
4800 
4801    Note:
4802    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
4803 
4804 .keywords: TS,  vector, monitor, view
4805 
4806 .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
4807 @*/
4808 PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
4809 {
4810   PetscErrorCode ierr;
4811 
4812   PetscFunctionBegin;
4813   ierr = PetscFree(*(char**)filenametemplate);CHKERRQ(ierr);
4814   PetscFunctionReturn(0);
4815 }
4816 
4817 #undef __FUNCT__
4818 #define __FUNCT__ "TSGetAdapt"
4819 /*@
4820    TSGetAdapt - Get the adaptive controller context for the current method
4821 
4822    Collective on TS if controller has not been created yet
4823 
4824    Input Arguments:
4825 .  ts - time stepping context
4826 
4827    Output Arguments:
4828 .  adapt - adaptive controller
4829 
4830    Level: intermediate
4831 
4832 .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4833 @*/
4834 PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4835 {
4836   PetscErrorCode ierr;
4837 
4838   PetscFunctionBegin;
4839   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4840   PetscValidPointer(adapt,2);
4841   if (!ts->adapt) {
4842     ierr = TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);CHKERRQ(ierr);
4843     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);CHKERRQ(ierr);
4844     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);CHKERRQ(ierr);
4845   }
4846   *adapt = ts->adapt;
4847   PetscFunctionReturn(0);
4848 }
4849 
4850 #undef __FUNCT__
4851 #define __FUNCT__ "TSSetTolerances"
4852 /*@
4853    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
4854 
4855    Logically Collective
4856 
4857    Input Arguments:
4858 +  ts - time integration context
4859 .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
4860 .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4861 .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
4862 -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
4863 
4864    Options Database keys:
4865 +  -ts_rtol <rtol> - relative tolerance for local truncation error
4866 -  -ts_atol <atol> Absolute tolerance for local truncation error
4867 
4868    Level: beginner
4869 
4870 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
4871 @*/
4872 PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
4873 {
4874   PetscErrorCode ierr;
4875 
4876   PetscFunctionBegin;
4877   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4878   if (vatol) {
4879     ierr = PetscObjectReference((PetscObject)vatol);CHKERRQ(ierr);
4880     ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
4881 
4882     ts->vatol = vatol;
4883   }
4884   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
4885   if (vrtol) {
4886     ierr = PetscObjectReference((PetscObject)vrtol);CHKERRQ(ierr);
4887     ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
4888 
4889     ts->vrtol = vrtol;
4890   }
4891   PetscFunctionReturn(0);
4892 }
4893 
4894 #undef __FUNCT__
4895 #define __FUNCT__ "TSGetTolerances"
4896 /*@
4897    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4898 
4899    Logically Collective
4900 
4901    Input Arguments:
4902 .  ts - time integration context
4903 
4904    Output Arguments:
4905 +  atol - scalar absolute tolerances, NULL to ignore
4906 .  vatol - vector of absolute tolerances, NULL to ignore
4907 .  rtol - scalar relative tolerances, NULL to ignore
4908 -  vrtol - vector of relative tolerances, NULL to ignore
4909 
4910    Level: beginner
4911 
4912 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
4913 @*/
4914 PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4915 {
4916   PetscFunctionBegin;
4917   if (atol)  *atol  = ts->atol;
4918   if (vatol) *vatol = ts->vatol;
4919   if (rtol)  *rtol  = ts->rtol;
4920   if (vrtol) *vrtol = ts->vrtol;
4921   PetscFunctionReturn(0);
4922 }
4923 
4924 #undef __FUNCT__
4925 #define __FUNCT__ "TSErrorNormWRMS"
4926 /*@
4927    TSErrorNormWRMS - compute a weighted norm of the difference between a vector and the current state
4928 
4929    Collective on TS
4930 
4931    Input Arguments:
4932 +  ts - time stepping context
4933 -  Y - state vector to be compared to ts->vec_sol
4934 
4935    Output Arguments:
4936 .  norm - weighted norm, a value of 1.0 is considered small
4937 
4938    Level: developer
4939 
4940 .seealso: TSSetTolerances()
4941 @*/
4942 PetscErrorCode TSErrorNormWRMS(TS ts,Vec Y,PetscReal *norm)
4943 {
4944   PetscErrorCode    ierr;
4945   PetscInt          i,n,N;
4946   const PetscScalar *u,*y;
4947   Vec               U;
4948   PetscReal         sum,gsum;
4949 
4950   PetscFunctionBegin;
4951   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4952   PetscValidHeaderSpecific(Y,VEC_CLASSID,2);
4953   PetscValidPointer(norm,3);
4954   U = ts->vec_sol;
4955   PetscCheckSameTypeAndComm(U,1,Y,2);
4956   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"Y cannot be the TS solution vector");
4957 
4958   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
4959   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
4960   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
4961   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
4962   sum  = 0.;
4963   if (ts->vatol && ts->vrtol) {
4964     const PetscScalar *atol,*rtol;
4965     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4966     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4967     for (i=0; i<n; i++) {
4968       PetscReal tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4969       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4970     }
4971     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4972     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4973   } else if (ts->vatol) {       /* vector atol, scalar rtol */
4974     const PetscScalar *atol;
4975     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4976     for (i=0; i<n; i++) {
4977       PetscReal tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4978       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4979     }
4980     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4981   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
4982     const PetscScalar *rtol;
4983     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4984     for (i=0; i<n; i++) {
4985       PetscReal tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4986       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4987     }
4988     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4989   } else {                      /* scalar atol, scalar rtol */
4990     for (i=0; i<n; i++) {
4991       PetscReal tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4992       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4993     }
4994   }
4995   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
4996   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
4997 
4998   ierr  = MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
4999   *norm = PetscSqrtReal(gsum / N);
5000   if (PetscIsInfOrNanReal(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5001   PetscFunctionReturn(0);
5002 }
5003 
5004 #undef __FUNCT__
5005 #define __FUNCT__ "TSSetCFLTimeLocal"
5006 /*@
5007    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
5008 
5009    Logically Collective on TS
5010 
5011    Input Arguments:
5012 +  ts - time stepping context
5013 -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
5014 
5015    Note:
5016    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
5017 
5018    Level: intermediate
5019 
5020 .seealso: TSGetCFLTime(), TSADAPTCFL
5021 @*/
5022 PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
5023 {
5024   PetscFunctionBegin;
5025   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5026   ts->cfltime_local = cfltime;
5027   ts->cfltime       = -1.;
5028   PetscFunctionReturn(0);
5029 }
5030 
5031 #undef __FUNCT__
5032 #define __FUNCT__ "TSGetCFLTime"
5033 /*@
5034    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
5035 
5036    Collective on TS
5037 
5038    Input Arguments:
5039 .  ts - time stepping context
5040 
5041    Output Arguments:
5042 .  cfltime - maximum stable time step for forward Euler
5043 
5044    Level: advanced
5045 
5046 .seealso: TSSetCFLTimeLocal()
5047 @*/
5048 PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
5049 {
5050   PetscErrorCode ierr;
5051 
5052   PetscFunctionBegin;
5053   if (ts->cfltime < 0) {
5054     ierr = MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
5055   }
5056   *cfltime = ts->cfltime;
5057   PetscFunctionReturn(0);
5058 }
5059 
5060 #undef __FUNCT__
5061 #define __FUNCT__ "TSVISetVariableBounds"
5062 /*@
5063    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5064 
5065    Input Parameters:
5066 .  ts   - the TS context.
5067 .  xl   - lower bound.
5068 .  xu   - upper bound.
5069 
5070    Notes:
5071    If this routine is not called then the lower and upper bounds are set to
5072    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
5073 
5074    Level: advanced
5075 
5076 @*/
5077 PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5078 {
5079   PetscErrorCode ierr;
5080   SNES           snes;
5081 
5082   PetscFunctionBegin;
5083   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
5084   ierr = SNESVISetVariableBounds(snes,xl,xu);CHKERRQ(ierr);
5085   PetscFunctionReturn(0);
5086 }
5087 
5088 #if defined(PETSC_HAVE_MATLAB_ENGINE)
5089 #include <mex.h>
5090 
5091 typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
5092 
5093 #undef __FUNCT__
5094 #define __FUNCT__ "TSComputeFunction_Matlab"
5095 /*
5096    TSComputeFunction_Matlab - Calls the function that has been set with
5097                          TSSetFunctionMatlab().
5098 
5099    Collective on TS
5100 
5101    Input Parameters:
5102 +  snes - the TS context
5103 -  u - input vector
5104 
5105    Output Parameter:
5106 .  y - function vector, as set by TSSetFunction()
5107 
5108    Notes:
5109    TSComputeFunction() is typically used within nonlinear solvers
5110    implementations, so most users would not generally call this routine
5111    themselves.
5112 
5113    Level: developer
5114 
5115 .keywords: TS, nonlinear, compute, function
5116 
5117 .seealso: TSSetFunction(), TSGetFunction()
5118 */
5119 PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
5120 {
5121   PetscErrorCode  ierr;
5122   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5123   int             nlhs  = 1,nrhs = 7;
5124   mxArray         *plhs[1],*prhs[7];
5125   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;
5126 
5127   PetscFunctionBegin;
5128   PetscValidHeaderSpecific(snes,TS_CLASSID,1);
5129   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
5130   PetscValidHeaderSpecific(udot,VEC_CLASSID,4);
5131   PetscValidHeaderSpecific(y,VEC_CLASSID,5);
5132   PetscCheckSameComm(snes,1,u,3);
5133   PetscCheckSameComm(snes,1,y,5);
5134 
5135   ierr = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
5136   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5137   ierr = PetscMemcpy(&lxdot,&udot,sizeof(udot));CHKERRQ(ierr);
5138   ierr = PetscMemcpy(&ly,&y,sizeof(u));CHKERRQ(ierr);
5139 
5140   prhs[0] =  mxCreateDoubleScalar((double)ls);
5141   prhs[1] =  mxCreateDoubleScalar(time);
5142   prhs[2] =  mxCreateDoubleScalar((double)lx);
5143   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5144   prhs[4] =  mxCreateDoubleScalar((double)ly);
5145   prhs[5] =  mxCreateString(sctx->funcname);
5146   prhs[6] =  sctx->ctx;
5147   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");CHKERRQ(ierr);
5148   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5149   mxDestroyArray(prhs[0]);
5150   mxDestroyArray(prhs[1]);
5151   mxDestroyArray(prhs[2]);
5152   mxDestroyArray(prhs[3]);
5153   mxDestroyArray(prhs[4]);
5154   mxDestroyArray(prhs[5]);
5155   mxDestroyArray(plhs[0]);
5156   PetscFunctionReturn(0);
5157 }
5158 
5159 
5160 #undef __FUNCT__
5161 #define __FUNCT__ "TSSetFunctionMatlab"
5162 /*
5163    TSSetFunctionMatlab - Sets the function evaluation routine and function
5164    vector for use by the TS routines in solving ODEs
5165    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
5166 
5167    Logically Collective on TS
5168 
5169    Input Parameters:
5170 +  ts - the TS context
5171 -  func - function evaluation routine
5172 
5173    Calling sequence of func:
5174 $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
5175 
5176    Level: beginner
5177 
5178 .keywords: TS, nonlinear, set, function
5179 
5180 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5181 */
5182 PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
5183 {
5184   PetscErrorCode  ierr;
5185   TSMatlabContext *sctx;
5186 
5187   PetscFunctionBegin;
5188   /* currently sctx is memory bleed */
5189   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5190   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5191   /*
5192      This should work, but it doesn't
5193   sctx->ctx = ctx;
5194   mexMakeArrayPersistent(sctx->ctx);
5195   */
5196   sctx->ctx = mxDuplicateArray(ctx);
5197 
5198   ierr = TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);CHKERRQ(ierr);
5199   PetscFunctionReturn(0);
5200 }
5201 
5202 #undef __FUNCT__
5203 #define __FUNCT__ "TSComputeJacobian_Matlab"
5204 /*
5205    TSComputeJacobian_Matlab - Calls the function that has been set with
5206                          TSSetJacobianMatlab().
5207 
5208    Collective on TS
5209 
5210    Input Parameters:
5211 +  ts - the TS context
5212 .  u - input vector
5213 .  A, B - the matrices
5214 -  ctx - user context
5215 
5216    Level: developer
5217 
5218 .keywords: TS, nonlinear, compute, function
5219 
5220 .seealso: TSSetFunction(), TSGetFunction()
5221 @*/
5222 PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
5223 {
5224   PetscErrorCode  ierr;
5225   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5226   int             nlhs  = 2,nrhs = 9;
5227   mxArray         *plhs[2],*prhs[9];
5228   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
5229 
5230   PetscFunctionBegin;
5231   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5232   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
5233 
5234   /* call Matlab function in ctx with arguments u and y */
5235 
5236   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
5237   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5238   ierr = PetscMemcpy(&lxdot,&udot,sizeof(u));CHKERRQ(ierr);
5239   ierr = PetscMemcpy(&lA,A,sizeof(u));CHKERRQ(ierr);
5240   ierr = PetscMemcpy(&lB,B,sizeof(u));CHKERRQ(ierr);
5241 
5242   prhs[0] =  mxCreateDoubleScalar((double)ls);
5243   prhs[1] =  mxCreateDoubleScalar((double)time);
5244   prhs[2] =  mxCreateDoubleScalar((double)lx);
5245   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5246   prhs[4] =  mxCreateDoubleScalar((double)shift);
5247   prhs[5] =  mxCreateDoubleScalar((double)lA);
5248   prhs[6] =  mxCreateDoubleScalar((double)lB);
5249   prhs[7] =  mxCreateString(sctx->funcname);
5250   prhs[8] =  sctx->ctx;
5251   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");CHKERRQ(ierr);
5252   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5253   mxDestroyArray(prhs[0]);
5254   mxDestroyArray(prhs[1]);
5255   mxDestroyArray(prhs[2]);
5256   mxDestroyArray(prhs[3]);
5257   mxDestroyArray(prhs[4]);
5258   mxDestroyArray(prhs[5]);
5259   mxDestroyArray(prhs[6]);
5260   mxDestroyArray(prhs[7]);
5261   mxDestroyArray(plhs[0]);
5262   mxDestroyArray(plhs[1]);
5263   PetscFunctionReturn(0);
5264 }
5265 
5266 
5267 #undef __FUNCT__
5268 #define __FUNCT__ "TSSetJacobianMatlab"
5269 /*
5270    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5271    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
5272 
5273    Logically Collective on TS
5274 
5275    Input Parameters:
5276 +  ts - the TS context
5277 .  A,B - Jacobian matrices
5278 .  func - function evaluation routine
5279 -  ctx - user context
5280 
5281    Calling sequence of func:
5282 $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
5283 
5284 
5285    Level: developer
5286 
5287 .keywords: TS, nonlinear, set, function
5288 
5289 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5290 */
5291 PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
5292 {
5293   PetscErrorCode  ierr;
5294   TSMatlabContext *sctx;
5295 
5296   PetscFunctionBegin;
5297   /* currently sctx is memory bleed */
5298   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5299   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5300   /*
5301      This should work, but it doesn't
5302   sctx->ctx = ctx;
5303   mexMakeArrayPersistent(sctx->ctx);
5304   */
5305   sctx->ctx = mxDuplicateArray(ctx);
5306 
5307   ierr = TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
5308   PetscFunctionReturn(0);
5309 }
5310 
5311 #undef __FUNCT__
5312 #define __FUNCT__ "TSMonitor_Matlab"
5313 /*
5314    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
5315 
5316    Collective on TS
5317 
5318 .seealso: TSSetFunction(), TSGetFunction()
5319 @*/
5320 PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
5321 {
5322   PetscErrorCode  ierr;
5323   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5324   int             nlhs  = 1,nrhs = 6;
5325   mxArray         *plhs[1],*prhs[6];
5326   long long int   lx = 0,ls = 0;
5327 
5328   PetscFunctionBegin;
5329   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5330   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
5331 
5332   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
5333   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
5334 
5335   prhs[0] =  mxCreateDoubleScalar((double)ls);
5336   prhs[1] =  mxCreateDoubleScalar((double)it);
5337   prhs[2] =  mxCreateDoubleScalar((double)time);
5338   prhs[3] =  mxCreateDoubleScalar((double)lx);
5339   prhs[4] =  mxCreateString(sctx->funcname);
5340   prhs[5] =  sctx->ctx;
5341   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");CHKERRQ(ierr);
5342   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
5343   mxDestroyArray(prhs[0]);
5344   mxDestroyArray(prhs[1]);
5345   mxDestroyArray(prhs[2]);
5346   mxDestroyArray(prhs[3]);
5347   mxDestroyArray(prhs[4]);
5348   mxDestroyArray(plhs[0]);
5349   PetscFunctionReturn(0);
5350 }
5351 
5352 
5353 #undef __FUNCT__
5354 #define __FUNCT__ "TSMonitorSetMatlab"
5355 /*
5356    TSMonitorSetMatlab - Sets the monitor function from Matlab
5357 
5358    Level: developer
5359 
5360 .keywords: TS, nonlinear, set, function
5361 
5362 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5363 */
5364 PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
5365 {
5366   PetscErrorCode  ierr;
5367   TSMatlabContext *sctx;
5368 
5369   PetscFunctionBegin;
5370   /* currently sctx is memory bleed */
5371   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
5372   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
5373   /*
5374      This should work, but it doesn't
5375   sctx->ctx = ctx;
5376   mexMakeArrayPersistent(sctx->ctx);
5377   */
5378   sctx->ctx = mxDuplicateArray(ctx);
5379 
5380   ierr = TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
5381   PetscFunctionReturn(0);
5382 }
5383 #endif
5384 
5385 
5386 
5387 #undef __FUNCT__
5388 #define __FUNCT__ "TSMonitorLGSolution"
5389 /*@C
5390    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
5391        in a time based line graph
5392 
5393    Collective on TS
5394 
5395    Input Parameters:
5396 +  ts - the TS context
5397 .  step - current time-step
5398 .  ptime - current time
5399 -  lg - a line graph object
5400 
5401    Level: intermediate
5402 
5403     Notes: each process in a parallel run displays its component solutions in a separate window
5404 
5405 .keywords: TS,  vector, monitor, view
5406 
5407 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5408 @*/
5409 PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5410 {
5411   PetscErrorCode    ierr;
5412   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5413   const PetscScalar *yy;
5414   PetscInt          dim;
5415 
5416   PetscFunctionBegin;
5417   if (!step) {
5418     PetscDrawAxis axis;
5419     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5420     ierr = PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");CHKERRQ(ierr);
5421     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
5422     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
5423     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5424   }
5425   ierr = VecGetArrayRead(u,&yy);CHKERRQ(ierr);
5426 #if defined(PETSC_USE_COMPLEX)
5427   {
5428     PetscReal *yreal;
5429     PetscInt  i,n;
5430     ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr);
5431     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
5432     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5433     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
5434     ierr = PetscFree(yreal);CHKERRQ(ierr);
5435   }
5436 #else
5437   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
5438 #endif
5439   ierr = VecRestoreArrayRead(u,&yy);CHKERRQ(ierr);
5440   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5441     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5442   }
5443   PetscFunctionReturn(0);
5444 }
5445 
5446 #undef __FUNCT__
5447 #define __FUNCT__ "TSMonitorLGError"
5448 /*@C
5449    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
5450        in a time based line graph
5451 
5452    Collective on TS
5453 
5454    Input Parameters:
5455 +  ts - the TS context
5456 .  step - current time-step
5457 .  ptime - current time
5458 -  lg - a line graph object
5459 
5460    Level: intermediate
5461 
5462    Notes:
5463    Only for sequential solves.
5464 
5465    The user must provide the solution using TSSetSolutionFunction() to use this monitor.
5466 
5467    Options Database Keys:
5468 .  -ts_monitor_lg_error - create a graphical monitor of error history
5469 
5470 .keywords: TS,  vector, monitor, view
5471 
5472 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
5473 @*/
5474 PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5475 {
5476   PetscErrorCode    ierr;
5477   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5478   const PetscScalar *yy;
5479   Vec               y;
5480   PetscInt          dim;
5481 
5482   PetscFunctionBegin;
5483   if (!step) {
5484     PetscDrawAxis axis;
5485     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5486     ierr = PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");CHKERRQ(ierr);
5487     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
5488     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
5489     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5490   }
5491   ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
5492   ierr = TSComputeSolutionFunction(ts,ptime,y);CHKERRQ(ierr);
5493   ierr = VecAXPY(y,-1.0,u);CHKERRQ(ierr);
5494   ierr = VecGetArrayRead(y,&yy);CHKERRQ(ierr);
5495 #if defined(PETSC_USE_COMPLEX)
5496   {
5497     PetscReal *yreal;
5498     PetscInt  i,n;
5499     ierr = VecGetLocalSize(y,&n);CHKERRQ(ierr);
5500     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
5501     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5502     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
5503     ierr = PetscFree(yreal);CHKERRQ(ierr);
5504   }
5505 #else
5506   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
5507 #endif
5508   ierr = VecRestoreArrayRead(y,&yy);CHKERRQ(ierr);
5509   ierr = VecDestroy(&y);CHKERRQ(ierr);
5510   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5511     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5512   }
5513   PetscFunctionReturn(0);
5514 }
5515 
5516 #undef __FUNCT__
5517 #define __FUNCT__ "TSMonitorLGSNESIterations"
5518 PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5519 {
5520   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5521   PetscReal      x   = ptime,y;
5522   PetscErrorCode ierr;
5523   PetscInt       its;
5524 
5525   PetscFunctionBegin;
5526   if (!n) {
5527     PetscDrawAxis axis;
5528 
5529     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5530     ierr = PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");CHKERRQ(ierr);
5531     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5532 
5533     ctx->snes_its = 0;
5534   }
5535   ierr = TSGetSNESIterations(ts,&its);CHKERRQ(ierr);
5536   y    = its - ctx->snes_its;
5537   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
5538   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5539     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5540   }
5541   ctx->snes_its = its;
5542   PetscFunctionReturn(0);
5543 }
5544 
5545 #undef __FUNCT__
5546 #define __FUNCT__ "TSMonitorLGKSPIterations"
5547 PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5548 {
5549   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5550   PetscReal      x   = ptime,y;
5551   PetscErrorCode ierr;
5552   PetscInt       its;
5553 
5554   PetscFunctionBegin;
5555   if (!n) {
5556     PetscDrawAxis axis;
5557 
5558     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
5559     ierr = PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");CHKERRQ(ierr);
5560     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
5561 
5562     ctx->ksp_its = 0;
5563   }
5564   ierr = TSGetKSPIterations(ts,&its);CHKERRQ(ierr);
5565   y    = its - ctx->ksp_its;
5566   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
5567   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5568     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
5569   }
5570   ctx->ksp_its = its;
5571   PetscFunctionReturn(0);
5572 }
5573 
5574 #undef __FUNCT__
5575 #define __FUNCT__ "TSComputeLinearStability"
5576 /*@
5577    TSComputeLinearStability - computes the linear stability function at a point
5578 
5579    Collective on TS and Vec
5580 
5581    Input Parameters:
5582 +  ts - the TS context
5583 -  xr,xi - real and imaginary part of input arguments
5584 
5585    Output Parameters:
5586 .  yr,yi - real and imaginary part of function value
5587 
5588    Level: developer
5589 
5590 .keywords: TS, compute
5591 
5592 .seealso: TSSetRHSFunction(), TSComputeIFunction()
5593 @*/
5594 PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
5595 {
5596   PetscErrorCode ierr;
5597 
5598   PetscFunctionBegin;
5599   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5600   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
5601   ierr = (*ts->ops->linearstability)(ts,xr,xi,yr,yi);CHKERRQ(ierr);
5602   PetscFunctionReturn(0);
5603 }
5604 
5605 #undef __FUNCT__
5606 #define __FUNCT__ "TSRollBack"
5607 /*@
5608    TSRollBack - Rolls back one time step
5609 
5610    Collective on TS
5611 
5612    Input Parameter:
5613 .  ts - the TS context obtained from TSCreate()
5614 
5615    Level: advanced
5616 
5617 .keywords: TS, timestep, rollback
5618 
5619 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
5620 @*/
5621 PetscErrorCode  TSRollBack(TS ts)
5622 {
5623   PetscErrorCode ierr;
5624 
5625   PetscFunctionBegin;
5626   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5627 
5628   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
5629   ierr = (*ts->ops->rollback)(ts);CHKERRQ(ierr);
5630   ts->time_step = ts->ptime - ts->ptime_prev;
5631   ts->ptime = ts->ptime_prev;
5632   PetscFunctionReturn(0);
5633 }
5634 
5635 #undef __FUNCT__
5636 #define __FUNCT__ "TSGetStages"
5637 /*@
5638    TSGetStages - Get the number of stages and stage values
5639 
5640    Input Parameter:
5641 .  ts - the TS context obtained from TSCreate()
5642 
5643    Level: advanced
5644 
5645 .keywords: TS, getstages
5646 
5647 .seealso: TSCreate()
5648 @*/
5649 PetscErrorCode  TSGetStages(TS ts,PetscInt *ns, Vec **Y)
5650 {
5651   PetscErrorCode ierr;
5652 
5653   PetscFunctionBegin;
5654   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5655   PetscValidPointer(ns,2);
5656 
5657   if (!ts->ops->getstages) *ns=0;
5658   else {
5659     ierr = (*ts->ops->getstages)(ts,ns,Y);CHKERRQ(ierr);
5660   }
5661   PetscFunctionReturn(0);
5662 }
5663 
5664 
5665 
5666