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