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