xref: /petsc/src/ts/interface/ts.c (revision 02699587bc43255da78981f596b61fc497a702ad)
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_AdjointStep, TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
11 
12 const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};
13 
14 struct _n_TSMonitorDrawCtx {
15   PetscViewer   viewer;
16   Vec           initialsolution;
17   PetscBool     showinitial;
18   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
19   PetscBool     showtimestepandtime;
20 };
21 
22 /*@C
23    TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
24 
25    Collective on TS
26 
27    Input Parameters:
28 +  ts - TS object you wish to monitor
29 .  name - the monitor type one is seeking
30 .  help - message indicating what monitoring is done
31 .  manual - manual page for the monitor
32 .  monitor - the monitor function
33 -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects
34 
35    Level: developer
36 
37 .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
38           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
39           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
40           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
41           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
42           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
43           PetscOptionsFList(), PetscOptionsEList()
44 @*/
45 PetscErrorCode  TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
46 {
47   PetscErrorCode    ierr;
48   PetscViewer       viewer;
49   PetscViewerFormat format;
50   PetscBool         flg;
51 
52   PetscFunctionBegin;
53   ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);CHKERRQ(ierr);
54   if (flg) {
55     PetscViewerAndFormat *vf;
56     ierr = PetscViewerAndFormatCreate(viewer,format,&vf);CHKERRQ(ierr);
57     ierr = PetscObjectDereference((PetscObject)viewer);CHKERRQ(ierr);
58     if (monitorsetup) {
59       ierr = (*monitorsetup)(ts,vf);CHKERRQ(ierr);
60     }
61     ierr = TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);CHKERRQ(ierr);
62   }
63   PetscFunctionReturn(0);
64 }
65 
66 /*@C
67    TSAdjointMonitorSensi - monitors the first lambda sensitivity
68 
69    Level: intermediate
70 
71 .keywords: TS, set, monitor
72 
73 .seealso: TSAdjointMonitorSet()
74 @*/
75 PetscErrorCode TSAdjointMonitorSensi(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
76 {
77   PetscErrorCode ierr;
78   PetscViewer    viewer = vf->viewer;
79 
80   PetscFunctionBegin;
81   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
82   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
83   ierr = VecView(lambda[0],viewer);CHKERRQ(ierr);
84   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
85   PetscFunctionReturn(0);
86 }
87 
88 /*@C
89    TSAdjointMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user
90 
91    Collective on TS
92 
93    Input Parameters:
94 +  ts - TS object you wish to monitor
95 .  name - the monitor type one is seeking
96 .  help - message indicating what monitoring is done
97 .  manual - manual page for the monitor
98 .  monitor - the monitor function
99 -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects
100 
101    Level: developer
102 
103 .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
104           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
105           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
106           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
107           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
108           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
109           PetscOptionsFList(), PetscOptionsEList()
110 @*/
111 PetscErrorCode  TSAdjointMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
112 {
113   PetscErrorCode    ierr;
114   PetscViewer       viewer;
115   PetscViewerFormat format;
116   PetscBool         flg;
117 
118   PetscFunctionBegin;
119   ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,name,&viewer,&format,&flg);CHKERRQ(ierr);
120   if (flg) {
121     PetscViewerAndFormat *vf;
122     ierr = PetscViewerAndFormatCreate(viewer,format,&vf);CHKERRQ(ierr);
123     ierr = PetscObjectDereference((PetscObject)viewer);CHKERRQ(ierr);
124     if (monitorsetup) {
125       ierr = (*monitorsetup)(ts,vf);CHKERRQ(ierr);
126     }
127     ierr = TSAdjointMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);CHKERRQ(ierr);
128   }
129   PetscFunctionReturn(0);
130 }
131 
132 static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
133 {
134   PetscErrorCode ierr;
135 
136   PetscFunctionBegin;
137   PetscValidHeaderSpecific(adapt,TSADAPT_CLASSID,1);
138   PetscValidCharPointer(default_type,2);
139   if (!((PetscObject)adapt)->type_name) {
140     ierr = TSAdaptSetType(adapt,default_type);CHKERRQ(ierr);
141   }
142   PetscFunctionReturn(0);
143 }
144 
145 /*@
146    TSSetFromOptions - Sets various TS parameters from user options.
147 
148    Collective on TS
149 
150    Input Parameter:
151 .  ts - the TS context obtained from TSCreate()
152 
153    Options Database Keys:
154 +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE
155 .  -ts_save_trajectory - checkpoint the solution at each time-step
156 .  -ts_max_steps <maxsteps> - maximum number of time-steps to take
157 .  -ts_final_time <time> - maximum time to compute to
158 .  -ts_dt <dt> - initial time step
159 .  -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
160 .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
161 .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
162 .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
163 .  -ts_rtol <rtol> - relative tolerance for local truncation error
164 .  -ts_atol <atol> Absolute tolerance for local truncation error
165 .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
166 .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
167 .  -ts_monitor - print information at each timestep
168 .  -ts_monitor_lg_solution - Monitor solution graphically
169 .  -ts_monitor_lg_error - Monitor error graphically
170 .  -ts_monitor_lg_timestep - Monitor timestep size graphically
171 .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
172 .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
173 .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
174 .  -ts_monitor_draw_solution - Monitor solution graphically
175 .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
176 .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
177 .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
178 .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
179 .  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
180 .  -ts_adjoint_monitor - print information at each adjoint time step
181 -  -ts_adjoint_monitor_draw_sensi - monitor the sensitivity of the first cost function wrt initial conditions (lambda[0]) graphically
182 
183    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
184 
185    Level: beginner
186 
187 .keywords: TS, timestep, set, options, database
188 
189 .seealso: TSGetType()
190 @*/
191 PetscErrorCode  TSSetFromOptions(TS ts)
192 {
193   PetscBool              opt,flg,tflg;
194   PetscErrorCode         ierr;
195   char                   monfilename[PETSC_MAX_PATH_LEN];
196   PetscReal              time_step;
197   TSExactFinalTimeOption eftopt;
198   char                   dir[16];
199   TSIFunction            ifun;
200   const char             *defaultType;
201   char                   typeName[256];
202 
203   PetscFunctionBegin;
204   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
205 
206   ierr = TSRegisterAll();CHKERRQ(ierr);
207   ierr = TSGetIFunction(ts,NULL,&ifun,NULL);CHKERRQ(ierr);
208 
209   ierr = PetscObjectOptionsBegin((PetscObject)ts);CHKERRQ(ierr);
210   if (((PetscObject)ts)->type_name)
211     defaultType = ((PetscObject)ts)->type_name;
212   else
213     defaultType = ifun ? TSBEULER : TSEULER;
214   ierr = PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);CHKERRQ(ierr);
215   if (opt) {
216     ierr = TSSetType(ts,typeName);CHKERRQ(ierr);
217   } else {
218     ierr = TSSetType(ts,defaultType);CHKERRQ(ierr);
219   }
220 
221   /* Handle generic TS options */
222   ierr = PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);CHKERRQ(ierr);
223   ierr = PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);CHKERRQ(ierr);
224   ierr = PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);CHKERRQ(ierr);
225   ierr = PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);CHKERRQ(ierr);
226   if (flg) {ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);}
227   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);
228   if (flg) {ierr = TSSetExactFinalTime(ts,eftopt);CHKERRQ(ierr);}
229   ierr = PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);CHKERRQ(ierr);
230   ierr = PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);CHKERRQ(ierr);
231   ierr = PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);CHKERRQ(ierr);
232   ierr = PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);CHKERRQ(ierr);
233   ierr = PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);CHKERRQ(ierr);
234 
235 #if defined(PETSC_HAVE_SAWS)
236   {
237   PetscBool set;
238   flg  = PETSC_FALSE;
239   ierr = PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);CHKERRQ(ierr);
240   if (set) {
241     ierr = PetscObjectSAWsSetBlock((PetscObject)ts,flg);CHKERRQ(ierr);
242   }
243   }
244 #endif
245 
246   /* Monitor options */
247   ierr = TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);CHKERRQ(ierr);
248   ierr = TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);CHKERRQ(ierr);
249   ierr = TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor","Monitor adjoint timestep size","TSAdjointMonitorDefault",TSAdjointMonitorDefault,NULL);CHKERRQ(ierr);
250   ierr = TSAdjointMonitorSetFromOptions(ts,"-ts_adjoint_monitor_sensi","Monitor sensitivity in the adjoint computation","TSAdjointMonitorSensi",TSAdjointMonitorSensi,NULL);CHKERRQ(ierr);
251 
252   ierr = PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
253   if (flg) {ierr = PetscPythonMonitorSet((PetscObject)ts,monfilename);CHKERRQ(ierr);}
254 
255   ierr = PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);CHKERRQ(ierr);
256   if (opt) {
257     TSMonitorLGCtx ctx;
258     PetscInt       howoften = 1;
259 
260     ierr = PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
261     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);CHKERRQ(ierr);
262     ierr = TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
263   }
264 
265   ierr = PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);CHKERRQ(ierr);
266   if (opt) {
267     TSMonitorLGCtx ctx;
268     PetscInt       howoften = 1;
269 
270     ierr = PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);CHKERRQ(ierr);
271     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);CHKERRQ(ierr);
272     ierr = TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
273   }
274 
275   ierr = PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);CHKERRQ(ierr);
276   if (opt) {
277     TSMonitorLGCtx ctx;
278     PetscInt       howoften = 1;
279 
280     ierr = PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);CHKERRQ(ierr);
281     ierr = TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);CHKERRQ(ierr);
282     ierr = TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
283   }
284   ierr = PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);CHKERRQ(ierr);
285   if (opt) {
286     TSMonitorLGCtx ctx;
287     PetscInt       howoften = 1;
288 
289     ierr = PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
290     ierr = TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);CHKERRQ(ierr);
291     ierr = TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
292   }
293   ierr = PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);CHKERRQ(ierr);
294   if (opt) {
295     TSMonitorLGCtx ctx;
296     PetscInt       howoften = 1;
297 
298     ierr = PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
299     ierr = TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);CHKERRQ(ierr);
300     ierr = TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
301   }
302   ierr = PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);CHKERRQ(ierr);
303   if (opt) {
304     TSMonitorSPEigCtx ctx;
305     PetscInt          howoften = 1;
306 
307     ierr = PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);CHKERRQ(ierr);
308     ierr = TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
309     ierr = TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);CHKERRQ(ierr);
310   }
311   opt  = PETSC_FALSE;
312   ierr = PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);CHKERRQ(ierr);
313   if (opt) {
314     TSMonitorDrawCtx ctx;
315     PetscInt         howoften = 1;
316 
317     ierr = PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
318     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
319     ierr = TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
320   }
321   opt  = PETSC_FALSE;
322   ierr = PetscOptionsName("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",&opt);CHKERRQ(ierr);
323   if (opt) {
324     TSMonitorDrawCtx ctx;
325     PetscInt         howoften = 1;
326 
327     ierr = PetscOptionsInt("-ts_adjoint_monitor_draw_sensi","Monitor adjoint sensitivities (lambda only) graphically","TSAdjointMonitorDrawSensi",howoften,&howoften,NULL);CHKERRQ(ierr);
328     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
329     ierr = TSAdjointMonitorSet(ts,TSAdjointMonitorDrawSensi,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
330   }
331   opt  = PETSC_FALSE;
332   ierr = PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);CHKERRQ(ierr);
333   if (opt) {
334     TSMonitorDrawCtx ctx;
335     PetscReal        bounds[4];
336     PetscInt         n = 4;
337     PetscDraw        draw;
338     PetscDrawAxis    axis;
339 
340     ierr = PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);CHKERRQ(ierr);
341     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
342     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);CHKERRQ(ierr);
343     ierr = PetscViewerDrawGetDraw(ctx->viewer,0,&draw);CHKERRQ(ierr);
344     ierr = PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);CHKERRQ(ierr);
345     ierr = PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);CHKERRQ(ierr);
346     ierr = PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");CHKERRQ(ierr);
347     ierr = TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
348   }
349   opt  = PETSC_FALSE;
350   ierr = PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);CHKERRQ(ierr);
351   if (opt) {
352     TSMonitorDrawCtx ctx;
353     PetscInt         howoften = 1;
354 
355     ierr = PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);CHKERRQ(ierr);
356     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
357     ierr = TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
358   }
359 
360   opt  = PETSC_FALSE;
361   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);
362   if (flg) {
363     const char *ptr,*ptr2;
364     char       *filetemplate;
365     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
366     /* Do some cursory validation of the input. */
367     ierr = PetscStrstr(monfilename,"%",(char**)&ptr);CHKERRQ(ierr);
368     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
369     for (ptr++; ptr && *ptr; ptr++) {
370       ierr = PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);CHKERRQ(ierr);
371       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");
372       if (ptr2) break;
373     }
374     ierr = PetscStrallocpy(monfilename,&filetemplate);CHKERRQ(ierr);
375     ierr = TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);CHKERRQ(ierr);
376   }
377 
378   ierr = PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);CHKERRQ(ierr);
379   if (flg) {
380     TSMonitorDMDARayCtx *rayctx;
381     int                  ray = 0;
382     DMDADirection        ddir;
383     DM                   da;
384     PetscMPIInt          rank;
385 
386     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
387     if (dir[0] == 'x') ddir = DMDA_X;
388     else if (dir[0] == 'y') ddir = DMDA_Y;
389     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
390     sscanf(dir+2,"%d",&ray);
391 
392     ierr = PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);CHKERRQ(ierr);
393     ierr = PetscNew(&rayctx);CHKERRQ(ierr);
394     ierr = TSGetDM(ts,&da);CHKERRQ(ierr);
395     ierr = DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);CHKERRQ(ierr);
396     ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);CHKERRQ(ierr);
397     if (!rank) {
398       ierr = PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);CHKERRQ(ierr);
399     }
400     rayctx->lgctx = NULL;
401     ierr = TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);CHKERRQ(ierr);
402   }
403   ierr = PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);CHKERRQ(ierr);
404   if (flg) {
405     TSMonitorDMDARayCtx *rayctx;
406     int                 ray = 0;
407     DMDADirection       ddir;
408     DM                  da;
409     PetscInt            howoften = 1;
410 
411     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
412     if      (dir[0] == 'x') ddir = DMDA_X;
413     else if (dir[0] == 'y') ddir = DMDA_Y;
414     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
415     sscanf(dir+2, "%d", &ray);
416 
417     ierr = PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);CHKERRQ(ierr);
418     ierr = PetscNew(&rayctx);CHKERRQ(ierr);
419     ierr = TSGetDM(ts, &da);CHKERRQ(ierr);
420     ierr = DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);CHKERRQ(ierr);
421     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);CHKERRQ(ierr);
422     ierr = TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);CHKERRQ(ierr);
423   }
424 
425   ierr = PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);CHKERRQ(ierr);
426   if (opt) {
427     TSMonitorEnvelopeCtx ctx;
428 
429     ierr = TSMonitorEnvelopeCtxCreate(ts,&ctx);CHKERRQ(ierr);
430     ierr = TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);CHKERRQ(ierr);
431   }
432 
433   flg  = PETSC_FALSE;
434   ierr = PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);CHKERRQ(ierr);
435   if (flg) {
436     DM   dm;
437     DMTS tdm;
438 
439     ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
440     ierr = DMGetDMTS(dm, &tdm);CHKERRQ(ierr);
441     tdm->ijacobianctx = NULL;
442     ierr = TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);CHKERRQ(ierr);
443     ierr = PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");CHKERRQ(ierr);
444   }
445 
446   /* Handle specific TS options */
447   if (ts->ops->setfromoptions) {
448     ierr = (*ts->ops->setfromoptions)(PetscOptionsObject,ts);CHKERRQ(ierr);
449   }
450 
451   /* Handle TSAdapt options */
452   ierr = TSGetAdapt(ts,&ts->adapt);CHKERRQ(ierr);
453   ierr = TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);CHKERRQ(ierr);
454   ierr = TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);CHKERRQ(ierr);
455 
456   /* TS trajectory must be set after TS, since it may use some TS options above */
457   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
458   ierr = PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);CHKERRQ(ierr);
459   if (tflg) {
460     ierr = TSSetSaveTrajectory(ts);CHKERRQ(ierr);
461   }
462   tflg = ts->adjoint_solve ? PETSC_TRUE : PETSC_FALSE;
463   ierr = PetscOptionsBool("-ts_adjoint_solve","Solve the adjoint problem immediately after solving the forward problem","",tflg,&tflg,&flg);CHKERRQ(ierr);
464   if (flg) {
465     ierr = TSSetSaveTrajectory(ts);CHKERRQ(ierr);
466     ts->adjoint_solve = tflg;
467   }
468 
469   /* process any options handlers added with PetscObjectAddOptionsHandler() */
470   ierr = PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);CHKERRQ(ierr);
471   ierr = PetscOptionsEnd();CHKERRQ(ierr);
472 
473   if (ts->trajectory) {
474     ierr = TSTrajectorySetFromOptions(ts->trajectory,ts);CHKERRQ(ierr);
475   }
476 
477   ierr = TSGetSNES(ts,&ts->snes);CHKERRQ(ierr);
478   if (ts->problem_type == TS_LINEAR) {ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);}
479   ierr = SNESSetFromOptions(ts->snes);CHKERRQ(ierr);
480   PetscFunctionReturn(0);
481 }
482 
483 /*@
484    TSGetTrajectory - Gets the trajectory from a TS if it exists
485 
486    Collective on TS
487 
488    Input Parameters:
489 .  ts - the TS context obtained from TSCreate()
490 
491    Output Parameters;
492 .  tr - the TSTrajectory object, if it exists
493 
494    Note: This routine should be called after all TS options have been set
495 
496    Level: advanced
497 
498 .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectory, TSTrajectoryCreate()
499 
500 .keywords: TS, set, checkpoint,
501 @*/
502 PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
503 {
504   PetscFunctionBegin;
505   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
506   *tr = ts->trajectory;
507   PetscFunctionReturn(0);
508 }
509 
510 /*@
511    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
512 
513    Collective on TS
514 
515    Input Parameters:
516 .  ts - the TS context obtained from TSCreate()
517 
518    Options Database:
519 +  -ts_save_trajectory - saves the trajectory to a file
520 -  -ts_trajectory_type type
521 
522 Note: This routine should be called after all TS options have been set
523 
524     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/bin/PetscBinaryIOTrajectory.py and
525    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
526 
527    Level: intermediate
528 
529 .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectoryType, TSSetTrajectoryType()
530 
531 .keywords: TS, set, checkpoint,
532 @*/
533 PetscErrorCode  TSSetSaveTrajectory(TS ts)
534 {
535   PetscErrorCode ierr;
536 
537   PetscFunctionBegin;
538   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
539   if (!ts->trajectory) {
540     ierr = TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);CHKERRQ(ierr);
541     ierr = TSTrajectorySetFromOptions(ts->trajectory,ts);CHKERRQ(ierr);
542   }
543   PetscFunctionReturn(0);
544 }
545 
546 /*@
547    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
548       set with TSSetRHSJacobian().
549 
550    Collective on TS and Vec
551 
552    Input Parameters:
553 +  ts - the TS context
554 .  t - current timestep
555 -  U - input vector
556 
557    Output Parameters:
558 +  A - Jacobian matrix
559 .  B - optional preconditioning matrix
560 -  flag - flag indicating matrix structure
561 
562    Notes:
563    Most users should not need to explicitly call this routine, as it
564    is used internally within the nonlinear solvers.
565 
566    See KSPSetOperators() for important information about setting the
567    flag parameter.
568 
569    Level: developer
570 
571 .keywords: SNES, compute, Jacobian, matrix
572 
573 .seealso:  TSSetRHSJacobian(), KSPSetOperators()
574 @*/
575 PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
576 {
577   PetscErrorCode   ierr;
578   PetscObjectState Ustate;
579   PetscObjectId    Uid;
580   DM               dm;
581   DMTS             tsdm;
582   TSRHSJacobian    rhsjacobianfunc;
583   void             *ctx;
584   TSIJacobian      ijacobianfunc;
585   TSRHSFunction    rhsfunction;
586 
587   PetscFunctionBegin;
588   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
589   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
590   PetscCheckSameComm(ts,1,U,3);
591   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
592   ierr = DMGetDMTS(dm,&tsdm);CHKERRQ(ierr);
593   ierr = DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);CHKERRQ(ierr);
594   ierr = DMTSGetIJacobian(dm,&ijacobianfunc,NULL);CHKERRQ(ierr);
595   ierr = DMTSGetRHSFunction(dm,&rhsfunction,&ctx);CHKERRQ(ierr);
596   ierr = PetscObjectStateGet((PetscObject)U,&Ustate);CHKERRQ(ierr);
597   ierr = PetscObjectGetId((PetscObject)U,&Uid);CHKERRQ(ierr);
598   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
599     PetscFunctionReturn(0);
600   }
601 
602   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
603 
604   if (ts->rhsjacobian.reuse) {
605     ierr = MatShift(A,-ts->rhsjacobian.shift);CHKERRQ(ierr);
606     ierr = MatScale(A,1./ts->rhsjacobian.scale);CHKERRQ(ierr);
607     if (A != B) {
608       ierr = MatShift(B,-ts->rhsjacobian.shift);CHKERRQ(ierr);
609       ierr = MatScale(B,1./ts->rhsjacobian.scale);CHKERRQ(ierr);
610     }
611     ts->rhsjacobian.shift = 0;
612     ts->rhsjacobian.scale = 1.;
613   }
614 
615   if (rhsjacobianfunc) {
616     PetscBool missing;
617     ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
618     PetscStackPush("TS user Jacobian function");
619     ierr = (*rhsjacobianfunc)(ts,t,U,A,B,ctx);CHKERRQ(ierr);
620     PetscStackPop;
621     ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
622     if (A) {
623       ierr = MatMissingDiagonal(A,&missing,NULL);CHKERRQ(ierr);
624       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
625     }
626     if (B && B != A) {
627       ierr = MatMissingDiagonal(B,&missing,NULL);CHKERRQ(ierr);
628       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetRHSJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
629     }
630   } else {
631     ierr = MatZeroEntries(A);CHKERRQ(ierr);
632     if (A != B) {ierr = MatZeroEntries(B);CHKERRQ(ierr);}
633   }
634   ts->rhsjacobian.time       = t;
635   ierr                       = PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
636   ierr                       = PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);CHKERRQ(ierr);
637   PetscFunctionReturn(0);
638 }
639 
640 /*@
641    TSComputeRHSFunction - Evaluates the right-hand-side function.
642 
643    Collective on TS and Vec
644 
645    Input Parameters:
646 +  ts - the TS context
647 .  t - current time
648 -  U - state vector
649 
650    Output Parameter:
651 .  y - right hand side
652 
653    Note:
654    Most users should not need to explicitly call this routine, as it
655    is used internally within the nonlinear solvers.
656 
657    Level: developer
658 
659 .keywords: TS, compute
660 
661 .seealso: TSSetRHSFunction(), TSComputeIFunction()
662 @*/
663 PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
664 {
665   PetscErrorCode ierr;
666   TSRHSFunction  rhsfunction;
667   TSIFunction    ifunction;
668   void           *ctx;
669   DM             dm;
670 
671   PetscFunctionBegin;
672   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
673   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
674   PetscValidHeaderSpecific(y,VEC_CLASSID,4);
675   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
676   ierr = DMTSGetRHSFunction(dm,&rhsfunction,&ctx);CHKERRQ(ierr);
677   ierr = DMTSGetIFunction(dm,&ifunction,NULL);CHKERRQ(ierr);
678 
679   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
680 
681   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
682   if (rhsfunction) {
683     PetscStackPush("TS user right-hand-side function");
684     ierr = (*rhsfunction)(ts,t,U,y,ctx);CHKERRQ(ierr);
685     PetscStackPop;
686   } else {
687     ierr = VecZeroEntries(y);CHKERRQ(ierr);
688   }
689 
690   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
691   PetscFunctionReturn(0);
692 }
693 
694 /*@
695    TSComputeSolutionFunction - Evaluates the solution function.
696 
697    Collective on TS and Vec
698 
699    Input Parameters:
700 +  ts - the TS context
701 -  t - current time
702 
703    Output Parameter:
704 .  U - the solution
705 
706    Note:
707    Most users should not need to explicitly call this routine, as it
708    is used internally within the nonlinear solvers.
709 
710    Level: developer
711 
712 .keywords: TS, compute
713 
714 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
715 @*/
716 PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
717 {
718   PetscErrorCode     ierr;
719   TSSolutionFunction solutionfunction;
720   void               *ctx;
721   DM                 dm;
722 
723   PetscFunctionBegin;
724   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
725   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
726   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
727   ierr = DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);CHKERRQ(ierr);
728 
729   if (solutionfunction) {
730     PetscStackPush("TS user solution function");
731     ierr = (*solutionfunction)(ts,t,U,ctx);CHKERRQ(ierr);
732     PetscStackPop;
733   }
734   PetscFunctionReturn(0);
735 }
736 /*@
737    TSComputeForcingFunction - Evaluates the forcing function.
738 
739    Collective on TS and Vec
740 
741    Input Parameters:
742 +  ts - the TS context
743 -  t - current time
744 
745    Output Parameter:
746 .  U - the function value
747 
748    Note:
749    Most users should not need to explicitly call this routine, as it
750    is used internally within the nonlinear solvers.
751 
752    Level: developer
753 
754 .keywords: TS, compute
755 
756 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
757 @*/
758 PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
759 {
760   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
761   void               *ctx;
762   DM                 dm;
763 
764   PetscFunctionBegin;
765   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
766   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
767   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
768   ierr = DMTSGetForcingFunction(dm,&forcing,&ctx);CHKERRQ(ierr);
769 
770   if (forcing) {
771     PetscStackPush("TS user forcing function");
772     ierr = (*forcing)(ts,t,U,ctx);CHKERRQ(ierr);
773     PetscStackPop;
774   }
775   PetscFunctionReturn(0);
776 }
777 
778 static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
779 {
780   Vec            F;
781   PetscErrorCode ierr;
782 
783   PetscFunctionBegin;
784   *Frhs = NULL;
785   ierr  = TSGetIFunction(ts,&F,NULL,NULL);CHKERRQ(ierr);
786   if (!ts->Frhs) {
787     ierr = VecDuplicate(F,&ts->Frhs);CHKERRQ(ierr);
788   }
789   *Frhs = ts->Frhs;
790   PetscFunctionReturn(0);
791 }
792 
793 static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
794 {
795   Mat            A,B;
796   PetscErrorCode ierr;
797   TSIJacobian    ijacobian;
798 
799   PetscFunctionBegin;
800   if (Arhs) *Arhs = NULL;
801   if (Brhs) *Brhs = NULL;
802   ierr = TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);CHKERRQ(ierr);
803   if (Arhs) {
804     if (!ts->Arhs) {
805       if (ijacobian) {
806         ierr = MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);CHKERRQ(ierr);
807       } else {
808         ts->Arhs = A;
809         ierr = PetscObjectReference((PetscObject)A);CHKERRQ(ierr);
810       }
811     } else {
812       PetscBool flg;
813       ierr = SNESGetUseMatrixFree(ts->snes,NULL,&flg);CHKERRQ(ierr);
814       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
815       if (flg && !ijacobian && ts->Arhs == ts->Brhs){
816         ierr = PetscObjectDereference((PetscObject)ts->Arhs);CHKERRQ(ierr);
817         ts->Arhs = A;
818         ierr = PetscObjectReference((PetscObject)A);CHKERRQ(ierr);
819       }
820     }
821     *Arhs = ts->Arhs;
822   }
823   if (Brhs) {
824     if (!ts->Brhs) {
825       if (A != B) {
826         if (ijacobian) {
827           ierr = MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);CHKERRQ(ierr);
828         } else {
829           ts->Brhs = B;
830           ierr = PetscObjectReference((PetscObject)B);CHKERRQ(ierr);
831         }
832       } else {
833         ierr = PetscObjectReference((PetscObject)ts->Arhs);CHKERRQ(ierr);
834         ts->Brhs = ts->Arhs;
835       }
836     }
837     *Brhs = ts->Brhs;
838   }
839   PetscFunctionReturn(0);
840 }
841 
842 /*@
843    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
844 
845    Collective on TS and Vec
846 
847    Input Parameters:
848 +  ts - the TS context
849 .  t - current time
850 .  U - state vector
851 .  Udot - time derivative of state vector
852 -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
853 
854    Output Parameter:
855 .  Y - right hand side
856 
857    Note:
858    Most users should not need to explicitly call this routine, as it
859    is used internally within the nonlinear solvers.
860 
861    If the user did did not write their equations in implicit form, this
862    function recasts them in implicit form.
863 
864    Level: developer
865 
866 .keywords: TS, compute
867 
868 .seealso: TSSetIFunction(), TSComputeRHSFunction()
869 @*/
870 PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
871 {
872   PetscErrorCode ierr;
873   TSIFunction    ifunction;
874   TSRHSFunction  rhsfunction;
875   void           *ctx;
876   DM             dm;
877 
878   PetscFunctionBegin;
879   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
880   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
881   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
882   PetscValidHeaderSpecific(Y,VEC_CLASSID,5);
883 
884   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
885   ierr = DMTSGetIFunction(dm,&ifunction,&ctx);CHKERRQ(ierr);
886   ierr = DMTSGetRHSFunction(dm,&rhsfunction,NULL);CHKERRQ(ierr);
887 
888   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
889 
890   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
891   if (ifunction) {
892     PetscStackPush("TS user implicit function");
893     ierr = (*ifunction)(ts,t,U,Udot,Y,ctx);CHKERRQ(ierr);
894     PetscStackPop;
895   }
896   if (imex) {
897     if (!ifunction) {
898       ierr = VecCopy(Udot,Y);CHKERRQ(ierr);
899     }
900   } else if (rhsfunction) {
901     if (ifunction) {
902       Vec Frhs;
903       ierr = TSGetRHSVec_Private(ts,&Frhs);CHKERRQ(ierr);
904       ierr = TSComputeRHSFunction(ts,t,U,Frhs);CHKERRQ(ierr);
905       ierr = VecAXPY(Y,-1,Frhs);CHKERRQ(ierr);
906     } else {
907       ierr = TSComputeRHSFunction(ts,t,U,Y);CHKERRQ(ierr);
908       ierr = VecAYPX(Y,-1,Udot);CHKERRQ(ierr);
909     }
910   }
911   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
912   PetscFunctionReturn(0);
913 }
914 
915 /*@
916    TSComputeIJacobian - Evaluates the Jacobian of the DAE
917 
918    Collective on TS and Vec
919 
920    Input
921       Input Parameters:
922 +  ts - the TS context
923 .  t - current timestep
924 .  U - state vector
925 .  Udot - time derivative of state vector
926 .  shift - shift to apply, see note below
927 -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
928 
929    Output Parameters:
930 +  A - Jacobian matrix
931 -  B - matrix from which the preconditioner is constructed; often the same as A
932 
933    Notes:
934    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
935 
936    dF/dU + shift*dF/dUdot
937 
938    Most users should not need to explicitly call this routine, as it
939    is used internally within the nonlinear solvers.
940 
941    Level: developer
942 
943 .keywords: TS, compute, Jacobian, matrix
944 
945 .seealso:  TSSetIJacobian()
946 @*/
947 PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
948 {
949   PetscErrorCode ierr;
950   TSIJacobian    ijacobian;
951   TSRHSJacobian  rhsjacobian;
952   DM             dm;
953   void           *ctx;
954 
955   PetscFunctionBegin;
956   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
957   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
958   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
959   PetscValidPointer(A,6);
960   PetscValidHeaderSpecific(A,MAT_CLASSID,6);
961   PetscValidPointer(B,7);
962   PetscValidHeaderSpecific(B,MAT_CLASSID,7);
963 
964   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
965   ierr = DMTSGetIJacobian(dm,&ijacobian,&ctx);CHKERRQ(ierr);
966   ierr = DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);CHKERRQ(ierr);
967 
968   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
969 
970   ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
971   if (ijacobian) {
972     PetscBool missing;
973     PetscStackPush("TS user implicit Jacobian");
974     ierr = (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);CHKERRQ(ierr);
975     PetscStackPop;
976     ierr = MatMissingDiagonal(A,&missing,NULL);CHKERRQ(ierr);
977     if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Amat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
978     if (B != A) {
979       ierr = MatMissingDiagonal(B,&missing,NULL);CHKERRQ(ierr);
980       if (missing) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Bmat passed to TSSetIJacobian() must have all diagonal entries set, if they are zero you must still set them with a zero value");
981     }
982   }
983   if (imex) {
984     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
985       PetscBool assembled;
986       ierr = MatZeroEntries(A);CHKERRQ(ierr);
987       ierr = MatAssembled(A,&assembled);CHKERRQ(ierr);
988       if (!assembled) {
989         ierr = MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
990         ierr = MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
991       }
992       ierr = MatShift(A,shift);CHKERRQ(ierr);
993       if (A != B) {
994         ierr = MatZeroEntries(B);CHKERRQ(ierr);
995         ierr = MatAssembled(B,&assembled);CHKERRQ(ierr);
996         if (!assembled) {
997           ierr = MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
998           ierr = MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
999         }
1000         ierr = MatShift(B,shift);CHKERRQ(ierr);
1001       }
1002     }
1003   } else {
1004     Mat Arhs = NULL,Brhs = NULL;
1005     if (rhsjacobian) {
1006       ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
1007       ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
1008     }
1009     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
1010       PetscBool flg;
1011       ts->rhsjacobian.scale = -1;
1012       ts->rhsjacobian.shift = shift;
1013       ierr = SNESGetUseMatrixFree(ts->snes,NULL,&flg);CHKERRQ(ierr);
1014       /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
1015       if (!flg) {
1016         ierr = MatScale(A,-1);CHKERRQ(ierr);
1017         ierr = MatShift(A,shift);CHKERRQ(ierr);
1018       }
1019       if (A != B) {
1020         ierr = MatScale(B,-1);CHKERRQ(ierr);
1021         ierr = MatShift(B,shift);CHKERRQ(ierr);
1022       }
1023     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
1024       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1025       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
1026         ierr = MatZeroEntries(A);CHKERRQ(ierr);
1027         ierr = MatShift(A,shift);CHKERRQ(ierr);
1028         if (A != B) {
1029           ierr = MatZeroEntries(B);CHKERRQ(ierr);
1030           ierr = MatShift(B,shift);CHKERRQ(ierr);
1031         }
1032       }
1033       ierr = MatAXPY(A,-1,Arhs,axpy);CHKERRQ(ierr);
1034       if (A != B) {
1035         ierr = MatAXPY(B,-1,Brhs,axpy);CHKERRQ(ierr);
1036       }
1037     }
1038   }
1039   ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);CHKERRQ(ierr);
1040   PetscFunctionReturn(0);
1041 }
1042 
1043 /*@C
1044     TSSetRHSFunction - Sets the routine for evaluating the function,
1045     where U_t = G(t,u).
1046 
1047     Logically Collective on TS
1048 
1049     Input Parameters:
1050 +   ts - the TS context obtained from TSCreate()
1051 .   r - vector to put the computed right hand side (or NULL to have it created)
1052 .   f - routine for evaluating the right-hand-side function
1053 -   ctx - [optional] user-defined context for private data for the
1054           function evaluation routine (may be NULL)
1055 
1056     Calling sequence of func:
1057 $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1058 
1059 +   t - current timestep
1060 .   u - input vector
1061 .   F - function vector
1062 -   ctx - [optional] user-defined function context
1063 
1064     Level: beginner
1065 
1066     Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
1067 
1068 .keywords: TS, timestep, set, right-hand-side, function
1069 
1070 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
1071 @*/
1072 PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1073 {
1074   PetscErrorCode ierr;
1075   SNES           snes;
1076   Vec            ralloc = NULL;
1077   DM             dm;
1078 
1079   PetscFunctionBegin;
1080   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1081   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1082 
1083   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1084   ierr = DMTSSetRHSFunction(dm,f,ctx);CHKERRQ(ierr);
1085   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1086   if (!r && !ts->dm && ts->vec_sol) {
1087     ierr = VecDuplicate(ts->vec_sol,&ralloc);CHKERRQ(ierr);
1088     r = ralloc;
1089   }
1090   ierr = SNESSetFunction(snes,r,SNESTSFormFunction,ts);CHKERRQ(ierr);
1091   ierr = VecDestroy(&ralloc);CHKERRQ(ierr);
1092   PetscFunctionReturn(0);
1093 }
1094 
1095 /*@C
1096     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1097 
1098     Logically Collective on TS
1099 
1100     Input Parameters:
1101 +   ts - the TS context obtained from TSCreate()
1102 .   f - routine for evaluating the solution
1103 -   ctx - [optional] user-defined context for private data for the
1104           function evaluation routine (may be NULL)
1105 
1106     Calling sequence of func:
1107 $     func (TS ts,PetscReal t,Vec u,void *ctx);
1108 
1109 +   t - current timestep
1110 .   u - output vector
1111 -   ctx - [optional] user-defined function context
1112 
1113     Notes:
1114     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1115     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1116     create closed-form solutions with non-physical forcing terms.
1117 
1118     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1119 
1120     Level: beginner
1121 
1122 .keywords: TS, timestep, set, right-hand-side, function
1123 
1124 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
1125 @*/
1126 PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1127 {
1128   PetscErrorCode ierr;
1129   DM             dm;
1130 
1131   PetscFunctionBegin;
1132   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1133   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1134   ierr = DMTSSetSolutionFunction(dm,f,ctx);CHKERRQ(ierr);
1135   PetscFunctionReturn(0);
1136 }
1137 
1138 /*@C
1139     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
1140 
1141     Logically Collective on TS
1142 
1143     Input Parameters:
1144 +   ts - the TS context obtained from TSCreate()
1145 .   func - routine for evaluating the forcing function
1146 -   ctx - [optional] user-defined context for private data for the
1147           function evaluation routine (may be NULL)
1148 
1149     Calling sequence of func:
1150 $     func (TS ts,PetscReal t,Vec f,void *ctx);
1151 
1152 +   t - current timestep
1153 .   f - output vector
1154 -   ctx - [optional] user-defined function context
1155 
1156     Notes:
1157     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1158     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1159     definition of the problem you are solving and hence possibly introducing bugs.
1160 
1161     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1162 
1163     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1164     parameters can be passed in the ctx variable.
1165 
1166     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1167 
1168     Level: beginner
1169 
1170 .keywords: TS, timestep, set, right-hand-side, function
1171 
1172 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
1173 @*/
1174 PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
1175 {
1176   PetscErrorCode ierr;
1177   DM             dm;
1178 
1179   PetscFunctionBegin;
1180   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1181   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1182   ierr = DMTSSetForcingFunction(dm,func,ctx);CHKERRQ(ierr);
1183   PetscFunctionReturn(0);
1184 }
1185 
1186 /*@C
1187    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1188    where U_t = G(U,t), as well as the location to store the matrix.
1189 
1190    Logically Collective on TS
1191 
1192    Input Parameters:
1193 +  ts  - the TS context obtained from TSCreate()
1194 .  Amat - (approximate) Jacobian matrix
1195 .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1196 .  f   - the Jacobian evaluation routine
1197 -  ctx - [optional] user-defined context for private data for the
1198          Jacobian evaluation routine (may be NULL)
1199 
1200    Calling sequence of f:
1201 $     func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1202 
1203 +  t - current timestep
1204 .  u - input vector
1205 .  Amat - (approximate) Jacobian matrix
1206 .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1207 -  ctx - [optional] user-defined context for matrix evaluation routine
1208 
1209    Notes:
1210    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1211 
1212    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1213    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1214 
1215    Level: beginner
1216 
1217 .keywords: TS, timestep, set, right-hand-side, Jacobian
1218 
1219 .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()
1220 
1221 @*/
1222 PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1223 {
1224   PetscErrorCode ierr;
1225   SNES           snes;
1226   DM             dm;
1227   TSIJacobian    ijacobian;
1228 
1229   PetscFunctionBegin;
1230   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1231   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1232   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1233   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1234   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1235 
1236   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1237   ierr = DMTSSetRHSJacobian(dm,f,ctx);CHKERRQ(ierr);
1238   if (f == TSComputeRHSJacobianConstant) {
1239     /* Handle this case automatically for the user; otherwise user should call themselves. */
1240     ierr = TSRHSJacobianSetReuse(ts,PETSC_TRUE);CHKERRQ(ierr);
1241   }
1242   ierr = DMTSGetIJacobian(dm,&ijacobian,NULL);CHKERRQ(ierr);
1243   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1244   if (!ijacobian) {
1245     ierr = SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1246   }
1247   if (Amat) {
1248     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
1249     ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
1250     ts->Arhs = Amat;
1251   }
1252   if (Pmat) {
1253     ierr = PetscObjectReference((PetscObject)Pmat);CHKERRQ(ierr);
1254     ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
1255     ts->Brhs = Pmat;
1256   }
1257   PetscFunctionReturn(0);
1258 }
1259 
1260 
1261 /*@C
1262    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1263 
1264    Logically Collective on TS
1265 
1266    Input Parameters:
1267 +  ts  - the TS context obtained from TSCreate()
1268 .  r   - vector to hold the residual (or NULL to have it created internally)
1269 .  f   - the function evaluation routine
1270 -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1271 
1272    Calling sequence of f:
1273 $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1274 
1275 +  t   - time at step/stage being solved
1276 .  u   - state vector
1277 .  u_t - time derivative of state vector
1278 .  F   - function vector
1279 -  ctx - [optional] user-defined context for matrix evaluation routine
1280 
1281    Important:
1282    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.
1283 
1284    Level: beginner
1285 
1286 .keywords: TS, timestep, set, DAE, Jacobian
1287 
1288 .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1289 @*/
1290 PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1291 {
1292   PetscErrorCode ierr;
1293   SNES           snes;
1294   Vec            ralloc = NULL;
1295   DM             dm;
1296 
1297   PetscFunctionBegin;
1298   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1299   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
1300 
1301   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1302   ierr = DMTSSetIFunction(dm,f,ctx);CHKERRQ(ierr);
1303 
1304   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1305   if (!r && !ts->dm && ts->vec_sol) {
1306     ierr = VecDuplicate(ts->vec_sol,&ralloc);CHKERRQ(ierr);
1307     r  = ralloc;
1308   }
1309   ierr = SNESSetFunction(snes,r,SNESTSFormFunction,ts);CHKERRQ(ierr);
1310   ierr = VecDestroy(&ralloc);CHKERRQ(ierr);
1311   PetscFunctionReturn(0);
1312 }
1313 
1314 /*@C
1315    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1316 
1317    Not Collective
1318 
1319    Input Parameter:
1320 .  ts - the TS context
1321 
1322    Output Parameter:
1323 +  r - vector to hold residual (or NULL)
1324 .  func - the function to compute residual (or NULL)
1325 -  ctx - the function context (or NULL)
1326 
1327    Level: advanced
1328 
1329 .keywords: TS, nonlinear, get, function
1330 
1331 .seealso: TSSetIFunction(), SNESGetFunction()
1332 @*/
1333 PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1334 {
1335   PetscErrorCode ierr;
1336   SNES           snes;
1337   DM             dm;
1338 
1339   PetscFunctionBegin;
1340   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1341   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1342   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1343   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1344   ierr = DMTSGetIFunction(dm,func,ctx);CHKERRQ(ierr);
1345   PetscFunctionReturn(0);
1346 }
1347 
1348 /*@C
1349    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1350 
1351    Not Collective
1352 
1353    Input Parameter:
1354 .  ts - the TS context
1355 
1356    Output Parameter:
1357 +  r - vector to hold computed right hand side (or NULL)
1358 .  func - the function to compute right hand side (or NULL)
1359 -  ctx - the function context (or NULL)
1360 
1361    Level: advanced
1362 
1363 .keywords: TS, nonlinear, get, function
1364 
1365 .seealso: TSSetRHSFunction(), SNESGetFunction()
1366 @*/
1367 PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1368 {
1369   PetscErrorCode ierr;
1370   SNES           snes;
1371   DM             dm;
1372 
1373   PetscFunctionBegin;
1374   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1375   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1376   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1377   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1378   ierr = DMTSGetRHSFunction(dm,func,ctx);CHKERRQ(ierr);
1379   PetscFunctionReturn(0);
1380 }
1381 
1382 /*@C
1383    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1384         provided with TSSetIFunction().
1385 
1386    Logically Collective on TS
1387 
1388    Input Parameters:
1389 +  ts  - the TS context obtained from TSCreate()
1390 .  Amat - (approximate) Jacobian matrix
1391 .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1392 .  f   - the Jacobian evaluation routine
1393 -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1394 
1395    Calling sequence of f:
1396 $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1397 
1398 +  t    - time at step/stage being solved
1399 .  U    - state vector
1400 .  U_t  - time derivative of state vector
1401 .  a    - shift
1402 .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1403 .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1404 -  ctx  - [optional] user-defined context for matrix evaluation routine
1405 
1406    Notes:
1407    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1408 
1409    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1410    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1411 
1412    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1413    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1414    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1415    a and vector W depend on the integration method, step size, and past states. For example with
1416    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1417    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1418 
1419    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
1420 
1421    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1422    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1423 
1424    Level: beginner
1425 
1426 .keywords: TS, timestep, DAE, Jacobian
1427 
1428 .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()
1429 
1430 @*/
1431 PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1432 {
1433   PetscErrorCode ierr;
1434   SNES           snes;
1435   DM             dm;
1436 
1437   PetscFunctionBegin;
1438   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1439   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1440   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1441   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1442   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1443 
1444   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1445   ierr = DMTSSetIJacobian(dm,f,ctx);CHKERRQ(ierr);
1446 
1447   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1448   ierr = SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1449   PetscFunctionReturn(0);
1450 }
1451 
1452 /*@
1453    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1454    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1455    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1456    not been changed by the TS.
1457 
1458    Logically Collective
1459 
1460    Input Arguments:
1461 +  ts - TS context obtained from TSCreate()
1462 -  reuse - PETSC_TRUE if the RHS Jacobian
1463 
1464    Level: intermediate
1465 
1466 .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1467 @*/
1468 PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1469 {
1470   PetscFunctionBegin;
1471   ts->rhsjacobian.reuse = reuse;
1472   PetscFunctionReturn(0);
1473 }
1474 
1475 /*@C
1476    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1477 
1478    Logically Collective on TS
1479 
1480    Input Parameters:
1481 +  ts  - the TS context obtained from TSCreate()
1482 .  F   - vector to hold the residual (or NULL to have it created internally)
1483 .  fun - the function evaluation routine
1484 -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1485 
1486    Calling sequence of fun:
1487 $  fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1488 
1489 +  t    - time at step/stage being solved
1490 .  U    - state vector
1491 .  U_t  - time derivative of state vector
1492 .  U_tt - second time derivative of state vector
1493 .  F    - function vector
1494 -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1495 
1496    Level: beginner
1497 
1498 .keywords: TS, timestep, set, ODE, DAE, Function
1499 
1500 .seealso: TSSetI2Jacobian()
1501 @*/
1502 PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1503 {
1504   DM             dm;
1505   PetscErrorCode ierr;
1506 
1507   PetscFunctionBegin;
1508   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1509   if (F) PetscValidHeaderSpecific(F,VEC_CLASSID,2);
1510   ierr = TSSetIFunction(ts,F,NULL,NULL);CHKERRQ(ierr);
1511   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1512   ierr = DMTSSetI2Function(dm,fun,ctx);CHKERRQ(ierr);
1513   PetscFunctionReturn(0);
1514 }
1515 
1516 /*@C
1517   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1518 
1519   Not Collective
1520 
1521   Input Parameter:
1522 . ts - the TS context
1523 
1524   Output Parameter:
1525 + r - vector to hold residual (or NULL)
1526 . fun - the function to compute residual (or NULL)
1527 - ctx - the function context (or NULL)
1528 
1529   Level: advanced
1530 
1531 .keywords: TS, nonlinear, get, function
1532 
1533 .seealso: TSSetI2Function(), SNESGetFunction()
1534 @*/
1535 PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1536 {
1537   PetscErrorCode ierr;
1538   SNES           snes;
1539   DM             dm;
1540 
1541   PetscFunctionBegin;
1542   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1543   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1544   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1545   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1546   ierr = DMTSGetI2Function(dm,fun,ctx);CHKERRQ(ierr);
1547   PetscFunctionReturn(0);
1548 }
1549 
1550 /*@C
1551    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1552         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1553 
1554    Logically Collective on TS
1555 
1556    Input Parameters:
1557 +  ts  - the TS context obtained from TSCreate()
1558 .  J   - Jacobian matrix
1559 .  P   - preconditioning matrix for J (may be same as J)
1560 .  jac - the Jacobian evaluation routine
1561 -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1562 
1563    Calling sequence of jac:
1564 $  jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1565 
1566 +  t    - time at step/stage being solved
1567 .  U    - state vector
1568 .  U_t  - time derivative of state vector
1569 .  U_tt - second time derivative of state vector
1570 .  v    - shift for U_t
1571 .  a    - shift for U_tt
1572 .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1573 .  P    - preconditioning matrix for J, may be same as J
1574 -  ctx  - [optional] user-defined context for matrix evaluation routine
1575 
1576    Notes:
1577    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1578 
1579    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1580    the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
1581    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1582    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1583 
1584    Level: beginner
1585 
1586 .keywords: TS, timestep, set, ODE, DAE, Jacobian
1587 
1588 .seealso: TSSetI2Function()
1589 @*/
1590 PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1591 {
1592   DM             dm;
1593   PetscErrorCode ierr;
1594 
1595   PetscFunctionBegin;
1596   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1597   if (J) PetscValidHeaderSpecific(J,MAT_CLASSID,2);
1598   if (P) PetscValidHeaderSpecific(P,MAT_CLASSID,3);
1599   ierr = TSSetIJacobian(ts,J,P,NULL,NULL);CHKERRQ(ierr);
1600   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1601   ierr = DMTSSetI2Jacobian(dm,jac,ctx);CHKERRQ(ierr);
1602   PetscFunctionReturn(0);
1603 }
1604 
1605 /*@C
1606   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1607 
1608   Not Collective, but parallel objects are returned if TS is parallel
1609 
1610   Input Parameter:
1611 . ts  - The TS context obtained from TSCreate()
1612 
1613   Output Parameters:
1614 + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1615 . P - The matrix from which the preconditioner is constructed, often the same as J
1616 . jac - The function to compute the Jacobian matrices
1617 - ctx - User-defined context for Jacobian evaluation routine
1618 
1619   Notes: You can pass in NULL for any return argument you do not need.
1620 
1621   Level: advanced
1622 
1623 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
1624 
1625 .keywords: TS, timestep, get, matrix, Jacobian
1626 @*/
1627 PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1628 {
1629   PetscErrorCode ierr;
1630   SNES           snes;
1631   DM             dm;
1632 
1633   PetscFunctionBegin;
1634   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1635   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
1636   ierr = SNESGetJacobian(snes,J,P,NULL,NULL);CHKERRQ(ierr);
1637   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1638   ierr = DMTSGetI2Jacobian(dm,jac,ctx);CHKERRQ(ierr);
1639   PetscFunctionReturn(0);
1640 }
1641 
1642 /*@
1643   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1644 
1645   Collective on TS and Vec
1646 
1647   Input Parameters:
1648 + ts - the TS context
1649 . t - current time
1650 . U - state vector
1651 . V - time derivative of state vector (U_t)
1652 - A - second time derivative of state vector (U_tt)
1653 
1654   Output Parameter:
1655 . F - the residual vector
1656 
1657   Note:
1658   Most users should not need to explicitly call this routine, as it
1659   is used internally within the nonlinear solvers.
1660 
1661   Level: developer
1662 
1663 .keywords: TS, compute, function, vector
1664 
1665 .seealso: TSSetI2Function()
1666 @*/
1667 PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1668 {
1669   DM             dm;
1670   TSI2Function   I2Function;
1671   void           *ctx;
1672   TSRHSFunction  rhsfunction;
1673   PetscErrorCode ierr;
1674 
1675   PetscFunctionBegin;
1676   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1677   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1678   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1679   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1680   PetscValidHeaderSpecific(F,VEC_CLASSID,6);
1681 
1682   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1683   ierr = DMTSGetI2Function(dm,&I2Function,&ctx);CHKERRQ(ierr);
1684   ierr = DMTSGetRHSFunction(dm,&rhsfunction,NULL);CHKERRQ(ierr);
1685 
1686   if (!I2Function) {
1687     ierr = TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);CHKERRQ(ierr);
1688     PetscFunctionReturn(0);
1689   }
1690 
1691   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);CHKERRQ(ierr);
1692 
1693   PetscStackPush("TS user implicit function");
1694   ierr = I2Function(ts,t,U,V,A,F,ctx);CHKERRQ(ierr);
1695   PetscStackPop;
1696 
1697   if (rhsfunction) {
1698     Vec Frhs;
1699     ierr = TSGetRHSVec_Private(ts,&Frhs);CHKERRQ(ierr);
1700     ierr = TSComputeRHSFunction(ts,t,U,Frhs);CHKERRQ(ierr);
1701     ierr = VecAXPY(F,-1,Frhs);CHKERRQ(ierr);
1702   }
1703 
1704   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);CHKERRQ(ierr);
1705   PetscFunctionReturn(0);
1706 }
1707 
1708 /*@
1709   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1710 
1711   Collective on TS and Vec
1712 
1713   Input Parameters:
1714 + ts - the TS context
1715 . t - current timestep
1716 . U - state vector
1717 . V - time derivative of state vector
1718 . A - second time derivative of state vector
1719 . shiftV - shift to apply, see note below
1720 - shiftA - shift to apply, see note below
1721 
1722   Output Parameters:
1723 + J - Jacobian matrix
1724 - P - optional preconditioning matrix
1725 
1726   Notes:
1727   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1728 
1729   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1730 
1731   Most users should not need to explicitly call this routine, as it
1732   is used internally within the nonlinear solvers.
1733 
1734   Level: developer
1735 
1736 .keywords: TS, compute, Jacobian, matrix
1737 
1738 .seealso:  TSSetI2Jacobian()
1739 @*/
1740 PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1741 {
1742   DM             dm;
1743   TSI2Jacobian   I2Jacobian;
1744   void           *ctx;
1745   TSRHSJacobian  rhsjacobian;
1746   PetscErrorCode ierr;
1747 
1748   PetscFunctionBegin;
1749   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1750   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1751   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1752   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1753   PetscValidHeaderSpecific(J,MAT_CLASSID,8);
1754   PetscValidHeaderSpecific(P,MAT_CLASSID,9);
1755 
1756   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1757   ierr = DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);CHKERRQ(ierr);
1758   ierr = DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);CHKERRQ(ierr);
1759 
1760   if (!I2Jacobian) {
1761     ierr = TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);CHKERRQ(ierr);
1762     PetscFunctionReturn(0);
1763   }
1764 
1765   ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);CHKERRQ(ierr);
1766 
1767   PetscStackPush("TS user implicit Jacobian");
1768   ierr = I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);CHKERRQ(ierr);
1769   PetscStackPop;
1770 
1771   if (rhsjacobian) {
1772     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1773     ierr = TSGetRHSMats_Private(ts,&Jrhs,&Prhs);CHKERRQ(ierr);
1774     ierr = TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);CHKERRQ(ierr);
1775     ierr = MatAXPY(J,-1,Jrhs,axpy);CHKERRQ(ierr);
1776     if (P != J) {ierr = MatAXPY(P,-1,Prhs,axpy);CHKERRQ(ierr);}
1777   }
1778 
1779   ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);CHKERRQ(ierr);
1780   PetscFunctionReturn(0);
1781 }
1782 
1783 /*@
1784    TS2SetSolution - Sets the initial solution and time derivative vectors
1785    for use by the TS routines handling second order equations.
1786 
1787    Logically Collective on TS and Vec
1788 
1789    Input Parameters:
1790 +  ts - the TS context obtained from TSCreate()
1791 .  u - the solution vector
1792 -  v - the time derivative vector
1793 
1794    Level: beginner
1795 
1796 .keywords: TS, timestep, set, solution, initial conditions
1797 @*/
1798 PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1799 {
1800   PetscErrorCode ierr;
1801 
1802   PetscFunctionBegin;
1803   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1804   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
1805   PetscValidHeaderSpecific(v,VEC_CLASSID,3);
1806   ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
1807   ierr = PetscObjectReference((PetscObject)v);CHKERRQ(ierr);
1808   ierr = VecDestroy(&ts->vec_dot);CHKERRQ(ierr);
1809   ts->vec_dot = v;
1810   PetscFunctionReturn(0);
1811 }
1812 
1813 /*@
1814    TS2GetSolution - Returns the solution and time derivative at the present timestep
1815    for second order equations. It is valid to call this routine inside the function
1816    that you are evaluating in order to move to the new timestep. This vector not
1817    changed until the solution at the next timestep has been calculated.
1818 
1819    Not Collective, but Vec returned is parallel if TS is parallel
1820 
1821    Input Parameter:
1822 .  ts - the TS context obtained from TSCreate()
1823 
1824    Output Parameter:
1825 +  u - the vector containing the solution
1826 -  v - the vector containing the time derivative
1827 
1828    Level: intermediate
1829 
1830 .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()
1831 
1832 .keywords: TS, timestep, get, solution
1833 @*/
1834 PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1835 {
1836   PetscFunctionBegin;
1837   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1838   if (u) PetscValidPointer(u,2);
1839   if (v) PetscValidPointer(v,3);
1840   if (u) *u = ts->vec_sol;
1841   if (v) *v = ts->vec_dot;
1842   PetscFunctionReturn(0);
1843 }
1844 
1845 /*@C
1846   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
1847 
1848   Collective on PetscViewer
1849 
1850   Input Parameters:
1851 + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1852            some related function before a call to TSLoad().
1853 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1854 
1855    Level: intermediate
1856 
1857   Notes:
1858    The type is determined by the data in the file, any type set into the TS before this call is ignored.
1859 
1860   Notes for advanced users:
1861   Most users should not need to know the details of the binary storage
1862   format, since TSLoad() and TSView() completely hide these details.
1863   But for anyone who's interested, the standard binary matrix storage
1864   format is
1865 .vb
1866      has not yet been determined
1867 .ve
1868 
1869 .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1870 @*/
1871 PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1872 {
1873   PetscErrorCode ierr;
1874   PetscBool      isbinary;
1875   PetscInt       classid;
1876   char           type[256];
1877   DMTS           sdm;
1878   DM             dm;
1879 
1880   PetscFunctionBegin;
1881   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1882   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1883   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1884   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1885 
1886   ierr = PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);CHKERRQ(ierr);
1887   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1888   ierr = PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);CHKERRQ(ierr);
1889   ierr = TSSetType(ts, type);CHKERRQ(ierr);
1890   if (ts->ops->load) {
1891     ierr = (*ts->ops->load)(ts,viewer);CHKERRQ(ierr);
1892   }
1893   ierr = DMCreate(PetscObjectComm((PetscObject)ts),&dm);CHKERRQ(ierr);
1894   ierr = DMLoad(dm,viewer);CHKERRQ(ierr);
1895   ierr = TSSetDM(ts,dm);CHKERRQ(ierr);
1896   ierr = DMCreateGlobalVector(ts->dm,&ts->vec_sol);CHKERRQ(ierr);
1897   ierr = VecLoad(ts->vec_sol,viewer);CHKERRQ(ierr);
1898   ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1899   ierr = DMTSLoad(sdm,viewer);CHKERRQ(ierr);
1900   PetscFunctionReturn(0);
1901 }
1902 
1903 #include <petscdraw.h>
1904 #if defined(PETSC_HAVE_SAWS)
1905 #include <petscviewersaws.h>
1906 #endif
1907 /*@C
1908     TSView - Prints the TS data structure.
1909 
1910     Collective on TS
1911 
1912     Input Parameters:
1913 +   ts - the TS context obtained from TSCreate()
1914 -   viewer - visualization context
1915 
1916     Options Database Key:
1917 .   -ts_view - calls TSView() at end of TSStep()
1918 
1919     Notes:
1920     The available visualization contexts include
1921 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1922 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1923          output where only the first processor opens
1924          the file.  All other processors send their
1925          data to the first processor to print.
1926 
1927     The user can open an alternative visualization context with
1928     PetscViewerASCIIOpen() - output to a specified file.
1929 
1930     Level: beginner
1931 
1932 .keywords: TS, timestep, view
1933 
1934 .seealso: PetscViewerASCIIOpen()
1935 @*/
1936 PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1937 {
1938   PetscErrorCode ierr;
1939   TSType         type;
1940   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1941   DMTS           sdm;
1942 #if defined(PETSC_HAVE_SAWS)
1943   PetscBool      issaws;
1944 #endif
1945 
1946   PetscFunctionBegin;
1947   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1948   if (!viewer) {
1949     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);CHKERRQ(ierr);
1950   }
1951   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1952   PetscCheckSameComm(ts,1,viewer,2);
1953 
1954   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1955   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
1956   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1957   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1958 #if defined(PETSC_HAVE_SAWS)
1959   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
1960 #endif
1961   if (iascii) {
1962     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);CHKERRQ(ierr);
1963     if (ts->ops->view) {
1964       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1965       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1966       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1967     }
1968     ierr = PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);CHKERRQ(ierr);
1969     ierr = PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);CHKERRQ(ierr);
1970     if (ts->usessnes) {
1971       PetscBool lin;
1972       if (ts->problem_type == TS_NONLINEAR) {
1973         ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);CHKERRQ(ierr);
1974       }
1975       ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);CHKERRQ(ierr);
1976       ierr = PetscObjectTypeCompare((PetscObject)ts->snes,SNESKSPONLY,&lin);CHKERRQ(ierr);
1977       ierr = PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);CHKERRQ(ierr);
1978     }
1979     ierr = PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);CHKERRQ(ierr);
1980     if (ts->vrtol) {
1981       ierr = PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");CHKERRQ(ierr);
1982     } else {
1983       ierr = PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);CHKERRQ(ierr);
1984     }
1985     if (ts->vatol) {
1986       ierr = PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");CHKERRQ(ierr);
1987     } else {
1988       ierr = PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);CHKERRQ(ierr);
1989     }
1990     ierr = TSAdaptView(ts->adapt,viewer);CHKERRQ(ierr);
1991     if (ts->snes && ts->usessnes)  {ierr = SNESView(ts->snes,viewer);CHKERRQ(ierr);}
1992     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1993     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1994   } else if (isstring) {
1995     ierr = TSGetType(ts,&type);CHKERRQ(ierr);
1996     ierr = PetscViewerStringSPrintf(viewer," %-7.7s",type);CHKERRQ(ierr);
1997   } else if (isbinary) {
1998     PetscInt    classid = TS_FILE_CLASSID;
1999     MPI_Comm    comm;
2000     PetscMPIInt rank;
2001     char        type[256];
2002 
2003     ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
2004     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
2005     if (!rank) {
2006       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
2007       ierr = PetscStrncpy(type,((PetscObject)ts)->type_name,256);CHKERRQ(ierr);
2008       ierr = PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
2009     }
2010     if (ts->ops->view) {
2011       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
2012     }
2013     if (ts->adapt) {ierr = TSAdaptView(ts->adapt,viewer);CHKERRQ(ierr);}
2014     ierr = DMView(ts->dm,viewer);CHKERRQ(ierr);
2015     ierr = VecView(ts->vec_sol,viewer);CHKERRQ(ierr);
2016     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
2017     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
2018   } else if (isdraw) {
2019     PetscDraw draw;
2020     char      str[36];
2021     PetscReal x,y,bottom,h;
2022 
2023     ierr   = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
2024     ierr   = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
2025     ierr   = PetscStrcpy(str,"TS: ");CHKERRQ(ierr);
2026     ierr   = PetscStrcat(str,((PetscObject)ts)->type_name);CHKERRQ(ierr);
2027     ierr   = PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
2028     bottom = y - h;
2029     ierr   = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
2030     if (ts->ops->view) {
2031       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
2032     }
2033     if (ts->adapt) {ierr = TSAdaptView(ts->adapt,viewer);CHKERRQ(ierr);}
2034     if (ts->snes)  {ierr = SNESView(ts->snes,viewer);CHKERRQ(ierr);}
2035     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
2036 #if defined(PETSC_HAVE_SAWS)
2037   } else if (issaws) {
2038     PetscMPIInt rank;
2039     const char  *name;
2040 
2041     ierr = PetscObjectGetName((PetscObject)ts,&name);CHKERRQ(ierr);
2042     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
2043     if (!((PetscObject)ts)->amsmem && !rank) {
2044       char       dir[1024];
2045 
2046       ierr = PetscObjectViewSAWs((PetscObject)ts,viewer);CHKERRQ(ierr);
2047       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);CHKERRQ(ierr);
2048       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
2049       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);CHKERRQ(ierr);
2050       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2051     }
2052     if (ts->ops->view) {
2053       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
2054     }
2055 #endif
2056   }
2057 
2058   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
2059   ierr = PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);CHKERRQ(ierr);
2060   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
2061   PetscFunctionReturn(0);
2062 }
2063 
2064 
2065 /*@
2066    TSSetApplicationContext - Sets an optional user-defined context for
2067    the timesteppers.
2068 
2069    Logically Collective on TS
2070 
2071    Input Parameters:
2072 +  ts - the TS context obtained from TSCreate()
2073 -  usrP - optional user context
2074 
2075    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2076     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2077 
2078    Level: intermediate
2079 
2080 .keywords: TS, timestep, set, application, context
2081 
2082 .seealso: TSGetApplicationContext()
2083 @*/
2084 PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2085 {
2086   PetscFunctionBegin;
2087   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2088   ts->user = usrP;
2089   PetscFunctionReturn(0);
2090 }
2091 
2092 /*@
2093     TSGetApplicationContext - Gets the user-defined context for the
2094     timestepper.
2095 
2096     Not Collective
2097 
2098     Input Parameter:
2099 .   ts - the TS context obtained from TSCreate()
2100 
2101     Output Parameter:
2102 .   usrP - user context
2103 
2104    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2105     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2106 
2107     Level: intermediate
2108 
2109 .keywords: TS, timestep, get, application, context
2110 
2111 .seealso: TSSetApplicationContext()
2112 @*/
2113 PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2114 {
2115   PetscFunctionBegin;
2116   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2117   *(void**)usrP = ts->user;
2118   PetscFunctionReturn(0);
2119 }
2120 
2121 /*@
2122    TSGetTimeStepNumber - Gets the number of time steps completed.
2123 
2124    Not Collective
2125 
2126    Input Parameter:
2127 .  ts - the TS context obtained from TSCreate()
2128 
2129    Output Parameter:
2130 .  iter - number of steps completed so far
2131 
2132    Level: intermediate
2133 
2134 .keywords: TS, timestep, get, iteration, number
2135 .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2136 @*/
2137 PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
2138 {
2139   PetscFunctionBegin;
2140   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2141   PetscValidIntPointer(iter,2);
2142   *iter = ts->steps;
2143   PetscFunctionReturn(0);
2144 }
2145 
2146 /*@
2147    TSSetInitialTimeStep - Sets the initial timestep to be used,
2148    as well as the initial time.
2149 
2150    Logically Collective on TS
2151 
2152    Input Parameters:
2153 +  ts - the TS context obtained from TSCreate()
2154 .  initial_time - the initial time
2155 -  time_step - the size of the timestep
2156 
2157    Level: intermediate
2158 
2159 .seealso: TSSetTimeStep(), TSGetTimeStep()
2160 
2161 .keywords: TS, set, initial, timestep
2162 @*/
2163 PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2164 {
2165   PetscErrorCode ierr;
2166 
2167   PetscFunctionBegin;
2168   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2169   ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
2170   ierr = TSSetTime(ts,initial_time);CHKERRQ(ierr);
2171   PetscFunctionReturn(0);
2172 }
2173 
2174 /*@
2175    TSSetTimeStep - Allows one to reset the timestep at any time,
2176    useful for simple pseudo-timestepping codes.
2177 
2178    Logically Collective on TS
2179 
2180    Input Parameters:
2181 +  ts - the TS context obtained from TSCreate()
2182 -  time_step - the size of the timestep
2183 
2184    Level: intermediate
2185 
2186 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2187 
2188 .keywords: TS, set, timestep
2189 @*/
2190 PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2191 {
2192   PetscFunctionBegin;
2193   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2194   PetscValidLogicalCollectiveReal(ts,time_step,2);
2195   ts->time_step = time_step;
2196   PetscFunctionReturn(0);
2197 }
2198 
2199 /*@
2200    TSSetExactFinalTime - Determines whether to adapt the final time step to
2201      match the exact final time, interpolate solution to the exact final time,
2202      or just return at the final time TS computed.
2203 
2204   Logically Collective on TS
2205 
2206    Input Parameter:
2207 +   ts - the time-step context
2208 -   eftopt - exact final time option
2209 
2210 $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2211 $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2212 $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2213 
2214    Options Database:
2215 .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2216 
2217    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2218     then the final time you selected.
2219 
2220    Level: beginner
2221 
2222 .seealso: TSExactFinalTimeOption
2223 @*/
2224 PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2225 {
2226   PetscFunctionBegin;
2227   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2228   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
2229   ts->exact_final_time = eftopt;
2230   PetscFunctionReturn(0);
2231 }
2232 
2233 /*@
2234    TSGetTimeStep - Gets the current timestep size.
2235 
2236    Not Collective
2237 
2238    Input Parameter:
2239 .  ts - the TS context obtained from TSCreate()
2240 
2241    Output Parameter:
2242 .  dt - the current timestep size
2243 
2244    Level: intermediate
2245 
2246 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2247 
2248 .keywords: TS, get, timestep
2249 @*/
2250 PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2251 {
2252   PetscFunctionBegin;
2253   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2254   PetscValidRealPointer(dt,2);
2255   *dt = ts->time_step;
2256   PetscFunctionReturn(0);
2257 }
2258 
2259 /*@
2260    TSGetSolution - Returns the solution at the present timestep. It
2261    is valid to call this routine inside the function that you are evaluating
2262    in order to move to the new timestep. This vector not changed until
2263    the solution at the next timestep has been calculated.
2264 
2265    Not Collective, but Vec returned is parallel if TS is parallel
2266 
2267    Input Parameter:
2268 .  ts - the TS context obtained from TSCreate()
2269 
2270    Output Parameter:
2271 .  v - the vector containing the solution
2272 
2273    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2274    final time. It returns the solution at the next timestep.
2275 
2276    Level: intermediate
2277 
2278 .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime(), TSGetSolutionComponents()
2279 
2280 .keywords: TS, timestep, get, solution
2281 @*/
2282 PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2283 {
2284   PetscFunctionBegin;
2285   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2286   PetscValidPointer(v,2);
2287   *v = ts->vec_sol;
2288   PetscFunctionReturn(0);
2289 }
2290 
2291 /*@
2292    TSGetSolutionComponents - Returns any solution components at the present
2293    timestep, if available for the time integration method being used.
2294    Solution components are quantities that share the same size and
2295    structure as the solution vector.
2296 
2297    Not Collective, but Vec returned is parallel if TS is parallel
2298 
2299    Parameters :
2300 .  ts - the TS context obtained from TSCreate() (input parameter).
2301 .  n - If v is PETSC_NULL, then the number of solution components is
2302        returned through n, else the n-th solution component is
2303        returned in v.
2304 .  v - the vector containing the n-th solution component
2305        (may be PETSC_NULL to use this function to find out
2306         the number of solutions components).
2307 
2308    Level: advanced
2309 
2310 .seealso: TSGetSolution()
2311 
2312 .keywords: TS, timestep, get, solution
2313 @*/
2314 PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
2315 {
2316   PetscErrorCode ierr;
2317 
2318   PetscFunctionBegin;
2319   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2320   if (!ts->ops->getsolutioncomponents) *n = 0;
2321   else {
2322     ierr = (*ts->ops->getsolutioncomponents)(ts,n,v);CHKERRQ(ierr);
2323   }
2324   PetscFunctionReturn(0);
2325 }
2326 
2327 /*@
2328    TSGetAuxSolution - Returns an auxiliary solution at the present
2329    timestep, if available for the time integration method being used.
2330 
2331    Not Collective, but Vec returned is parallel if TS is parallel
2332 
2333    Parameters :
2334 .  ts - the TS context obtained from TSCreate() (input parameter).
2335 .  v - the vector containing the auxiliary solution
2336 
2337    Level: intermediate
2338 
2339 .seealso: TSGetSolution()
2340 
2341 .keywords: TS, timestep, get, solution
2342 @*/
2343 PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
2344 {
2345   PetscErrorCode ierr;
2346 
2347   PetscFunctionBegin;
2348   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2349   if (ts->ops->getauxsolution) {
2350     ierr = (*ts->ops->getauxsolution)(ts,v);CHKERRQ(ierr);
2351   } else {
2352     ierr = VecZeroEntries(*v); CHKERRQ(ierr);
2353   }
2354   PetscFunctionReturn(0);
2355 }
2356 
2357 /*@
2358    TSGetTimeError - Returns the estimated error vector, if the chosen
2359    TSType has an error estimation functionality.
2360 
2361    Not Collective, but Vec returned is parallel if TS is parallel
2362 
2363    Note: MUST call after TSSetUp()
2364 
2365    Parameters :
2366 .  ts - the TS context obtained from TSCreate() (input parameter).
2367 .  n - current estimate (n=0) or previous one (n=-1)
2368 .  v - the vector containing the error (same size as the solution).
2369 
2370    Level: intermediate
2371 
2372 .seealso: TSGetSolution(), TSSetTimeError()
2373 
2374 .keywords: TS, timestep, get, error
2375 @*/
2376 PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
2377 {
2378   PetscErrorCode ierr;
2379 
2380   PetscFunctionBegin;
2381   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2382   if (ts->ops->gettimeerror) {
2383     ierr = (*ts->ops->gettimeerror)(ts,n,v);CHKERRQ(ierr);
2384   } else {
2385     ierr = VecZeroEntries(*v);CHKERRQ(ierr);
2386   }
2387   PetscFunctionReturn(0);
2388 }
2389 
2390 /*@
2391    TSSetTimeError - Sets the estimated error vector, if the chosen
2392    TSType has an error estimation functionality. This can be used
2393    to restart such a time integrator with a given error vector.
2394 
2395    Not Collective, but Vec returned is parallel if TS is parallel
2396 
2397    Parameters :
2398 .  ts - the TS context obtained from TSCreate() (input parameter).
2399 .  v - the vector containing the error (same size as the solution).
2400 
2401    Level: intermediate
2402 
2403 .seealso: TSSetSolution(), TSGetTimeError)
2404 
2405 .keywords: TS, timestep, get, error
2406 @*/
2407 PetscErrorCode  TSSetTimeError(TS ts,Vec v)
2408 {
2409   PetscErrorCode ierr;
2410 
2411   PetscFunctionBegin;
2412   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2413   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
2414   if (ts->ops->settimeerror) {
2415     ierr = (*ts->ops->settimeerror)(ts,v);CHKERRQ(ierr);
2416   }
2417   PetscFunctionReturn(0);
2418 }
2419 
2420 /*@
2421    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()
2422 
2423    Not Collective, but Vec returned is parallel if TS is parallel
2424 
2425    Input Parameter:
2426 .  ts - the TS context obtained from TSCreate()
2427 
2428    Output Parameter:
2429 +  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2430 -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters
2431 
2432    Level: intermediate
2433 
2434 .seealso: TSGetTimeStep()
2435 
2436 .keywords: TS, timestep, get, sensitivity
2437 @*/
2438 PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2439 {
2440   PetscFunctionBegin;
2441   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2442   if (numcost) *numcost = ts->numcost;
2443   if (lambda)  *lambda  = ts->vecs_sensi;
2444   if (mu)      *mu      = ts->vecs_sensip;
2445   PetscFunctionReturn(0);
2446 }
2447 
2448 /* ----- Routines to initialize and destroy a timestepper ---- */
2449 /*@
2450   TSSetProblemType - Sets the type of problem to be solved.
2451 
2452   Not collective
2453 
2454   Input Parameters:
2455 + ts   - The TS
2456 - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2457 .vb
2458          U_t - A U = 0      (linear)
2459          U_t - A(t) U = 0   (linear)
2460          F(t,U,U_t) = 0     (nonlinear)
2461 .ve
2462 
2463    Level: beginner
2464 
2465 .keywords: TS, problem type
2466 .seealso: TSSetUp(), TSProblemType, TS
2467 @*/
2468 PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2469 {
2470   PetscErrorCode ierr;
2471 
2472   PetscFunctionBegin;
2473   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2474   ts->problem_type = type;
2475   if (type == TS_LINEAR) {
2476     SNES snes;
2477     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2478     ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);
2479   }
2480   PetscFunctionReturn(0);
2481 }
2482 
2483 /*@C
2484   TSGetProblemType - Gets the type of problem to be solved.
2485 
2486   Not collective
2487 
2488   Input Parameter:
2489 . ts   - The TS
2490 
2491   Output Parameter:
2492 . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2493 .vb
2494          M U_t = A U
2495          M(t) U_t = A(t) U
2496          F(t,U,U_t)
2497 .ve
2498 
2499    Level: beginner
2500 
2501 .keywords: TS, problem type
2502 .seealso: TSSetUp(), TSProblemType, TS
2503 @*/
2504 PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2505 {
2506   PetscFunctionBegin;
2507   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2508   PetscValidIntPointer(type,2);
2509   *type = ts->problem_type;
2510   PetscFunctionReturn(0);
2511 }
2512 
2513 /*@
2514    TSSetUp - Sets up the internal data structures for the later use
2515    of a timestepper.
2516 
2517    Collective on TS
2518 
2519    Input Parameter:
2520 .  ts - the TS context obtained from TSCreate()
2521 
2522    Notes:
2523    For basic use of the TS solvers the user need not explicitly call
2524    TSSetUp(), since these actions will automatically occur during
2525    the call to TSStep().  However, if one wishes to control this
2526    phase separately, TSSetUp() should be called after TSCreate()
2527    and optional routines of the form TSSetXXX(), but before TSStep().
2528 
2529    Level: advanced
2530 
2531 .keywords: TS, timestep, setup
2532 
2533 .seealso: TSCreate(), TSStep(), TSDestroy()
2534 @*/
2535 PetscErrorCode  TSSetUp(TS ts)
2536 {
2537   PetscErrorCode ierr;
2538   DM             dm;
2539   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2540   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2541   TSIFunction    ifun;
2542   TSIJacobian    ijac;
2543   TSI2Jacobian   i2jac;
2544   TSRHSJacobian  rhsjac;
2545   PetscBool      isnone;
2546 
2547   PetscFunctionBegin;
2548   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2549   if (ts->setupcalled) PetscFunctionReturn(0);
2550 
2551   if (!((PetscObject)ts)->type_name) {
2552     ierr = TSGetIFunction(ts,NULL,&ifun,NULL);CHKERRQ(ierr);
2553     ierr = TSSetType(ts,ifun ? TSBEULER : TSEULER);CHKERRQ(ierr);
2554   }
2555 
2556   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2557 
2558   if (ts->rhsjacobian.reuse) {
2559     Mat Amat,Pmat;
2560     SNES snes;
2561     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2562     ierr = SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);CHKERRQ(ierr);
2563     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2564      * have displaced the RHS matrix */
2565     if (Amat == ts->Arhs) {
2566       ierr = MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);CHKERRQ(ierr);
2567       ierr = SNESSetJacobian(snes,Amat,NULL,NULL,NULL);CHKERRQ(ierr);
2568       ierr = MatDestroy(&Amat);CHKERRQ(ierr);
2569     }
2570     if (Pmat == ts->Brhs) {
2571       ierr = MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);CHKERRQ(ierr);
2572       ierr = SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);CHKERRQ(ierr);
2573       ierr = MatDestroy(&Pmat);CHKERRQ(ierr);
2574     }
2575   }
2576 
2577   ierr = TSGetAdapt(ts,&ts->adapt);CHKERRQ(ierr);
2578   ierr = TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);CHKERRQ(ierr);
2579 
2580   if (ts->ops->setup) {
2581     ierr = (*ts->ops->setup)(ts);CHKERRQ(ierr);
2582   }
2583 
2584   /* Attempt to check/preset a default value for the exact final time option */
2585   ierr = PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);CHKERRQ(ierr);
2586   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED)
2587     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2588 
2589   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2590      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2591    */
2592   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2593   ierr = DMSNESGetFunction(dm,&func,NULL);CHKERRQ(ierr);
2594   if (!func) {
2595     ierr = DMSNESSetFunction(dm,SNESTSFormFunction,ts);CHKERRQ(ierr);
2596   }
2597   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2598      Otherwise, the SNES will use coloring internally to form the Jacobian.
2599    */
2600   ierr = DMSNESGetJacobian(dm,&jac,NULL);CHKERRQ(ierr);
2601   ierr = DMTSGetIJacobian(dm,&ijac,NULL);CHKERRQ(ierr);
2602   ierr = DMTSGetI2Jacobian(dm,&i2jac,NULL);CHKERRQ(ierr);
2603   ierr = DMTSGetRHSJacobian(dm,&rhsjac,NULL);CHKERRQ(ierr);
2604   if (!jac && (ijac || i2jac || rhsjac)) {
2605     ierr = DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2606   }
2607 
2608   /* if time integration scheme has a starting method, call it */
2609   if (ts->ops->startingmethod) {
2610     ierr = (*ts->ops->startingmethod)(ts);CHKERRQ(ierr);
2611   }
2612 
2613   ts->setupcalled = PETSC_TRUE;
2614   PetscFunctionReturn(0);
2615 }
2616 
2617 /*@
2618    TSAdjointSetUp - Sets up the internal data structures for the later use
2619    of an adjoint solver
2620 
2621    Collective on TS
2622 
2623    Input Parameter:
2624 .  ts - the TS context obtained from TSCreate()
2625 
2626    Level: advanced
2627 
2628 .keywords: TS, timestep, setup
2629 
2630 .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2631 @*/
2632 PetscErrorCode  TSAdjointSetUp(TS ts)
2633 {
2634   PetscErrorCode ierr;
2635 
2636   PetscFunctionBegin;
2637   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2638   if (ts->adjointsetupcalled) PetscFunctionReturn(0);
2639   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");
2640 
2641   if (ts->vec_costintegral) { /* if there is integral in the cost function*/
2642     ierr = VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);CHKERRQ(ierr);
2643     if (ts->vecs_sensip){
2644       ierr = VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);CHKERRQ(ierr);
2645     }
2646   }
2647 
2648   if (ts->ops->adjointsetup) {
2649     ierr = (*ts->ops->adjointsetup)(ts);CHKERRQ(ierr);
2650   }
2651   ts->adjointsetupcalled = PETSC_TRUE;
2652   PetscFunctionReturn(0);
2653 }
2654 
2655 /*@
2656    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2657 
2658    Collective on TS
2659 
2660    Input Parameter:
2661 .  ts - the TS context obtained from TSCreate()
2662 
2663    Level: beginner
2664 
2665 .keywords: TS, timestep, reset
2666 
2667 .seealso: TSCreate(), TSSetup(), TSDestroy()
2668 @*/
2669 PetscErrorCode  TSReset(TS ts)
2670 {
2671   PetscErrorCode ierr;
2672 
2673   PetscFunctionBegin;
2674   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2675 
2676   if (ts->ops->reset) {
2677     ierr = (*ts->ops->reset)(ts);CHKERRQ(ierr);
2678   }
2679   if (ts->snes) {ierr = SNESReset(ts->snes);CHKERRQ(ierr);}
2680   if (ts->adapt) {ierr = TSAdaptReset(ts->adapt);CHKERRQ(ierr);}
2681 
2682   ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
2683   ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
2684   ierr = VecDestroy(&ts->Frhs);CHKERRQ(ierr);
2685   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2686   ierr = VecDestroy(&ts->vec_dot);CHKERRQ(ierr);
2687   ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
2688   ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
2689   ierr = VecDestroyVecs(ts->nwork,&ts->work);CHKERRQ(ierr);
2690 
2691  if (ts->vec_costintegral) {
2692     ierr = VecDestroyVecs(ts->numcost,&ts->vecs_drdy);CHKERRQ(ierr);
2693     if (ts->vecs_drdp){
2694       ierr = VecDestroyVecs(ts->numcost,&ts->vecs_drdp);CHKERRQ(ierr);
2695     }
2696   }
2697   ts->vecs_sensi  = NULL;
2698   ts->vecs_sensip = NULL;
2699   ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
2700   ierr = VecDestroy(&ts->vec_costintegral);CHKERRQ(ierr);
2701   ierr = VecDestroy(&ts->vec_costintegrand);CHKERRQ(ierr);
2702   ts->setupcalled = PETSC_FALSE;
2703   PetscFunctionReturn(0);
2704 }
2705 
2706 /*@
2707    TSDestroy - Destroys the timestepper context that was created
2708    with TSCreate().
2709 
2710    Collective on TS
2711 
2712    Input Parameter:
2713 .  ts - the TS context obtained from TSCreate()
2714 
2715    Level: beginner
2716 
2717 .keywords: TS, timestepper, destroy
2718 
2719 .seealso: TSCreate(), TSSetUp(), TSSolve()
2720 @*/
2721 PetscErrorCode  TSDestroy(TS *ts)
2722 {
2723   PetscErrorCode ierr;
2724 
2725   PetscFunctionBegin;
2726   if (!*ts) PetscFunctionReturn(0);
2727   PetscValidHeaderSpecific((*ts),TS_CLASSID,1);
2728   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; PetscFunctionReturn(0);}
2729 
2730   ierr = TSReset((*ts));CHKERRQ(ierr);
2731 
2732   /* if memory was published with SAWs then destroy it */
2733   ierr = PetscObjectSAWsViewOff((PetscObject)*ts);CHKERRQ(ierr);
2734   if ((*ts)->ops->destroy) {ierr = (*(*ts)->ops->destroy)((*ts));CHKERRQ(ierr);}
2735 
2736   ierr = TSTrajectoryDestroy(&(*ts)->trajectory);CHKERRQ(ierr);
2737 
2738   ierr = TSAdaptDestroy(&(*ts)->adapt);CHKERRQ(ierr);
2739   ierr = TSEventDestroy(&(*ts)->event);CHKERRQ(ierr);
2740 
2741   ierr = SNESDestroy(&(*ts)->snes);CHKERRQ(ierr);
2742   ierr = DMDestroy(&(*ts)->dm);CHKERRQ(ierr);
2743   ierr = TSMonitorCancel((*ts));CHKERRQ(ierr);
2744   ierr = TSAdjointMonitorCancel((*ts));CHKERRQ(ierr);
2745 
2746   ierr = PetscHeaderDestroy(ts);CHKERRQ(ierr);
2747   PetscFunctionReturn(0);
2748 }
2749 
2750 /*@
2751    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2752    a TS (timestepper) context. Valid only for nonlinear problems.
2753 
2754    Not Collective, but SNES is parallel if TS is parallel
2755 
2756    Input Parameter:
2757 .  ts - the TS context obtained from TSCreate()
2758 
2759    Output Parameter:
2760 .  snes - the nonlinear solver context
2761 
2762    Notes:
2763    The user can then directly manipulate the SNES context to set various
2764    options, etc.  Likewise, the user can then extract and manipulate the
2765    KSP, KSP, and PC contexts as well.
2766 
2767    TSGetSNES() does not work for integrators that do not use SNES; in
2768    this case TSGetSNES() returns NULL in snes.
2769 
2770    Level: beginner
2771 
2772 .keywords: timestep, get, SNES
2773 @*/
2774 PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2775 {
2776   PetscErrorCode ierr;
2777 
2778   PetscFunctionBegin;
2779   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2780   PetscValidPointer(snes,2);
2781   if (!ts->snes) {
2782     ierr = SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);CHKERRQ(ierr);
2783     ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2784     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);CHKERRQ(ierr);
2785     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);CHKERRQ(ierr);
2786     if (ts->dm) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
2787     if (ts->problem_type == TS_LINEAR) {
2788       ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);
2789     }
2790   }
2791   *snes = ts->snes;
2792   PetscFunctionReturn(0);
2793 }
2794 
2795 /*@
2796    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2797 
2798    Collective
2799 
2800    Input Parameter:
2801 +  ts - the TS context obtained from TSCreate()
2802 -  snes - the nonlinear solver context
2803 
2804    Notes:
2805    Most users should have the TS created by calling TSGetSNES()
2806 
2807    Level: developer
2808 
2809 .keywords: timestep, set, SNES
2810 @*/
2811 PetscErrorCode TSSetSNES(TS ts,SNES snes)
2812 {
2813   PetscErrorCode ierr;
2814   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2815 
2816   PetscFunctionBegin;
2817   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2818   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
2819   ierr = PetscObjectReference((PetscObject)snes);CHKERRQ(ierr);
2820   ierr = SNESDestroy(&ts->snes);CHKERRQ(ierr);
2821 
2822   ts->snes = snes;
2823 
2824   ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2825   ierr = SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);CHKERRQ(ierr);
2826   if (func == SNESTSFormJacobian) {
2827     ierr = SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2828   }
2829   PetscFunctionReturn(0);
2830 }
2831 
2832 /*@
2833    TSGetKSP - Returns the KSP (linear solver) associated with
2834    a TS (timestepper) context.
2835 
2836    Not Collective, but KSP is parallel if TS is parallel
2837 
2838    Input Parameter:
2839 .  ts - the TS context obtained from TSCreate()
2840 
2841    Output Parameter:
2842 .  ksp - the nonlinear solver context
2843 
2844    Notes:
2845    The user can then directly manipulate the KSP context to set various
2846    options, etc.  Likewise, the user can then extract and manipulate the
2847    KSP and PC contexts as well.
2848 
2849    TSGetKSP() does not work for integrators that do not use KSP;
2850    in this case TSGetKSP() returns NULL in ksp.
2851 
2852    Level: beginner
2853 
2854 .keywords: timestep, get, KSP
2855 @*/
2856 PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2857 {
2858   PetscErrorCode ierr;
2859   SNES           snes;
2860 
2861   PetscFunctionBegin;
2862   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2863   PetscValidPointer(ksp,2);
2864   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2865   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2866   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2867   ierr = SNESGetKSP(snes,ksp);CHKERRQ(ierr);
2868   PetscFunctionReturn(0);
2869 }
2870 
2871 /* ----------- Routines to set solver parameters ---------- */
2872 
2873 /*@
2874    TSGetDuration - Gets the maximum number of timesteps to use and
2875    maximum time for iteration.
2876 
2877    Not Collective
2878 
2879    Input Parameters:
2880 +  ts       - the TS context obtained from TSCreate()
2881 .  maxsteps - maximum number of iterations to use, or NULL
2882 -  maxtime  - final time to iterate to, or NULL
2883 
2884    Level: intermediate
2885 
2886 .keywords: TS, timestep, get, maximum, iterations, time
2887 @*/
2888 PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2889 {
2890   PetscFunctionBegin;
2891   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2892   if (maxsteps) {
2893     PetscValidIntPointer(maxsteps,2);
2894     *maxsteps = ts->max_steps;
2895   }
2896   if (maxtime) {
2897     PetscValidScalarPointer(maxtime,3);
2898     *maxtime = ts->max_time;
2899   }
2900   PetscFunctionReturn(0);
2901 }
2902 
2903 /*@
2904    TSSetDuration - Sets the maximum number of timesteps to use and
2905    maximum time for iteration.
2906 
2907    Logically Collective on TS
2908 
2909    Input Parameters:
2910 +  ts - the TS context obtained from TSCreate()
2911 .  maxsteps - maximum number of iterations to use
2912 -  maxtime - final time to iterate to
2913 
2914    Options Database Keys:
2915 .  -ts_max_steps <maxsteps> - Sets maxsteps
2916 .  -ts_final_time <maxtime> - Sets maxtime
2917 
2918    Notes:
2919    The default maximum number of iterations is 5000. Default time is 5.0
2920 
2921    Level: intermediate
2922 
2923 .keywords: TS, timestep, set, maximum, iterations
2924 
2925 .seealso: TSSetExactFinalTime()
2926 @*/
2927 PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2928 {
2929   PetscFunctionBegin;
2930   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2931   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
2932   PetscValidLogicalCollectiveReal(ts,maxtime,2);
2933   if (maxsteps >= 0) ts->max_steps = maxsteps;
2934   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2935   PetscFunctionReturn(0);
2936 }
2937 
2938 /*@
2939    TSSetSolution - Sets the initial solution vector
2940    for use by the TS routines.
2941 
2942    Logically Collective on TS and Vec
2943 
2944    Input Parameters:
2945 +  ts - the TS context obtained from TSCreate()
2946 -  u - the solution vector
2947 
2948    Level: beginner
2949 
2950 .keywords: TS, timestep, set, solution, initial conditions
2951 @*/
2952 PetscErrorCode  TSSetSolution(TS ts,Vec u)
2953 {
2954   PetscErrorCode ierr;
2955   DM             dm;
2956 
2957   PetscFunctionBegin;
2958   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2959   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2960   ierr = PetscObjectReference((PetscObject)u);CHKERRQ(ierr);
2961   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2962   ts->vec_sol = u;
2963 
2964   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2965   ierr = DMShellSetGlobalVector(dm,u);CHKERRQ(ierr);
2966   PetscFunctionReturn(0);
2967 }
2968 
2969 /*@
2970    TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time
2971 
2972    Logically Collective on TS
2973 
2974    Input Parameters:
2975 +  ts - the TS context obtained from TSCreate()
2976 .  steps - number of steps to use
2977 
2978    Level: intermediate
2979 
2980    Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2981           so as to integrate back to less than the original timestep
2982 
2983 .keywords: TS, timestep, set, maximum, iterations
2984 
2985 .seealso: TSSetExactFinalTime()
2986 @*/
2987 PetscErrorCode  TSAdjointSetSteps(TS ts,PetscInt steps)
2988 {
2989   PetscFunctionBegin;
2990   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2991   PetscValidLogicalCollectiveInt(ts,steps,2);
2992   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2993   if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2994   ts->adjoint_max_steps = steps;
2995   PetscFunctionReturn(0);
2996 }
2997 
2998 /*@
2999    TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters
3000       for use by the TSAdjoint routines.
3001 
3002    Logically Collective on TS and Vec
3003 
3004    Input Parameters:
3005 +  ts - the TS context obtained from TSCreate()
3006 .  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
3007 -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters
3008 
3009    Level: beginner
3010 
3011    Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime  mu_i = df/dp|finaltime
3012 
3013 .keywords: TS, timestep, set, sensitivity, initial conditions
3014 @*/
3015 PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
3016 {
3017   PetscFunctionBegin;
3018   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3019   PetscValidPointer(lambda,2);
3020   ts->vecs_sensi  = lambda;
3021   ts->vecs_sensip = mu;
3022   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostIntegrand");
3023   ts->numcost  = numcost;
3024   PetscFunctionReturn(0);
3025 }
3026 
3027 /*@C
3028   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.
3029 
3030   Logically Collective on TS
3031 
3032   Input Parameters:
3033 + ts   - The TS context obtained from TSCreate()
3034 - func - The function
3035 
3036   Calling sequence of func:
3037 $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
3038 +   t - current timestep
3039 .   y - input vector (current ODE solution)
3040 .   A - output matrix
3041 -   ctx - [optional] user-defined function context
3042 
3043   Level: intermediate
3044 
3045   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
3046 
3047 .keywords: TS, sensitivity
3048 .seealso:
3049 @*/
3050 PetscErrorCode  TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
3051 {
3052   PetscErrorCode ierr;
3053 
3054   PetscFunctionBegin;
3055   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3056   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
3057 
3058   ts->rhsjacobianp    = func;
3059   ts->rhsjacobianpctx = ctx;
3060   if(Amat) {
3061     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
3062     ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
3063     ts->Jacp = Amat;
3064   }
3065   PetscFunctionReturn(0);
3066 }
3067 
3068 /*@C
3069   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.
3070 
3071   Collective on TS
3072 
3073   Input Parameters:
3074 . ts   - The TS context obtained from TSCreate()
3075 
3076   Level: developer
3077 
3078 .keywords: TS, sensitivity
3079 .seealso: TSAdjointSetRHSJacobian()
3080 @*/
3081 PetscErrorCode  TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
3082 {
3083   PetscErrorCode ierr;
3084 
3085   PetscFunctionBegin;
3086   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3087   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
3088   PetscValidPointer(Amat,4);
3089 
3090   PetscStackPush("TS user JacobianP function for sensitivity analysis");
3091   ierr = (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx); CHKERRQ(ierr);
3092   PetscStackPop;
3093   PetscFunctionReturn(0);
3094 }
3095 
3096 /*@C
3097     TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions
3098 
3099     Logically Collective on TS
3100 
3101     Input Parameters:
3102 +   ts - the TS context obtained from TSCreate()
3103 .   numcost - number of gradients to be computed, this is the number of cost functions
3104 .   rf - routine for evaluating the integrand function
3105 .   drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
3106 .   drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
3107 .   fwd - flag indicating whether to evaluate cost integral in the forward run or the adjoint run
3108 -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
3109 
3110     Calling sequence of rf:
3111 $     rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);
3112 
3113 +   t - current timestep
3114 .   y - input vector
3115 .   f - function result; one vector entry for each cost function
3116 -   ctx - [optional] user-defined function context
3117 
3118    Calling sequence of drdyf:
3119 $    PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);
3120 
3121    Calling sequence of drdpf:
3122 $    PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);
3123 
3124     Level: intermediate
3125 
3126     Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions
3127 
3128 .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
3129 
3130 .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
3131 @*/
3132 PetscErrorCode  TSSetCostIntegrand(TS ts,PetscInt numcost,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
3133                                                           PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
3134                                                           PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
3135                                                           PetscBool fwd,void *ctx)
3136 {
3137   PetscErrorCode ierr;
3138 
3139   PetscFunctionBegin;
3140   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3141   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostGradients()");
3142   if (!ts->numcost) ts->numcost=numcost;
3143 
3144   ts->costintegralfwd  = fwd; /* Evaluate the cost integral in forward run if fwd is true */
3145   ierr                 = VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);CHKERRQ(ierr);
3146   ierr                 = VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);CHKERRQ(ierr);
3147   ts->costintegrand    = rf;
3148   ts->costintegrandctx = ctx;
3149   ts->drdyfunction     = drdyf;
3150   ts->drdpfunction     = drdpf;
3151   PetscFunctionReturn(0);
3152 }
3153 
3154 /*@
3155    TSGetCostIntegral - Returns the values of the integral term in the cost functions.
3156    It is valid to call the routine after a backward run.
3157 
3158    Not Collective
3159 
3160    Input Parameter:
3161 .  ts - the TS context obtained from TSCreate()
3162 
3163    Output Parameter:
3164 .  v - the vector containing the integrals for each cost function
3165 
3166    Level: intermediate
3167 
3168 .seealso: TSSetCostIntegrand()
3169 
3170 .keywords: TS, sensitivity analysis
3171 @*/
3172 PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
3173 {
3174   PetscFunctionBegin;
3175   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3176   PetscValidPointer(v,2);
3177   *v = ts->vec_costintegral;
3178   PetscFunctionReturn(0);
3179 }
3180 
3181 /*@
3182    TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.
3183 
3184    Input Parameters:
3185 +  ts - the TS context
3186 .  t - current time
3187 -  y - state vector, i.e. current solution
3188 
3189    Output Parameter:
3190 .  q - vector of size numcost to hold the outputs
3191 
3192    Note:
3193    Most users should not need to explicitly call this routine, as it
3194    is used internally within the sensitivity analysis context.
3195 
3196    Level: developer
3197 
3198 .keywords: TS, compute
3199 
3200 .seealso: TSSetCostIntegrand()
3201 @*/
3202 PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3203 {
3204   PetscErrorCode ierr;
3205 
3206   PetscFunctionBegin;
3207   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3208   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3209   PetscValidHeaderSpecific(q,VEC_CLASSID,4);
3210 
3211   ierr = PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);CHKERRQ(ierr);
3212   if (ts->costintegrand) {
3213     PetscStackPush("TS user integrand in the cost function");
3214     ierr = (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);CHKERRQ(ierr);
3215     PetscStackPop;
3216   } else {
3217     ierr = VecZeroEntries(q);CHKERRQ(ierr);
3218   }
3219 
3220   ierr = PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);CHKERRQ(ierr);
3221   PetscFunctionReturn(0);
3222 }
3223 
3224 /*@
3225   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
3226 
3227   Collective on TS
3228 
3229   Input Parameters:
3230 . ts   - The TS context obtained from TSCreate()
3231 
3232   Notes:
3233   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3234   so most users would not generally call this routine themselves.
3235 
3236   Level: developer
3237 
3238 .keywords: TS, sensitivity
3239 .seealso: TSAdjointComputeDRDYFunction()
3240 @*/
3241 PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3242 {
3243   PetscErrorCode ierr;
3244 
3245   PetscFunctionBegin;
3246   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3247   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3248 
3249   PetscStackPush("TS user DRDY function for sensitivity analysis");
3250   ierr = (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx); CHKERRQ(ierr);
3251   PetscStackPop;
3252   PetscFunctionReturn(0);
3253 }
3254 
3255 /*@
3256   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
3257 
3258   Collective on TS
3259 
3260   Input Parameters:
3261 . ts   - The TS context obtained from TSCreate()
3262 
3263   Notes:
3264   TSDRDPFunction() is typically used for sensitivity implementation,
3265   so most users would not generally call this routine themselves.
3266 
3267   Level: developer
3268 
3269 .keywords: TS, sensitivity
3270 .seealso: TSAdjointSetDRDPFunction()
3271 @*/
3272 PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3273 {
3274   PetscErrorCode ierr;
3275 
3276   PetscFunctionBegin;
3277   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3278   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3279 
3280   PetscStackPush("TS user DRDP function for sensitivity analysis");
3281   ierr = (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx); CHKERRQ(ierr);
3282   PetscStackPop;
3283   PetscFunctionReturn(0);
3284 }
3285 
3286 /*@C
3287   TSSetPreStep - Sets the general-purpose function
3288   called once at the beginning of each time step.
3289 
3290   Logically Collective on TS
3291 
3292   Input Parameters:
3293 + ts   - The TS context obtained from TSCreate()
3294 - func - The function
3295 
3296   Calling sequence of func:
3297 . func (TS ts);
3298 
3299   Level: intermediate
3300 
3301 .keywords: TS, timestep
3302 .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3303 @*/
3304 PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3305 {
3306   PetscFunctionBegin;
3307   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3308   ts->prestep = func;
3309   PetscFunctionReturn(0);
3310 }
3311 
3312 /*@
3313   TSPreStep - Runs the user-defined pre-step function.
3314 
3315   Collective on TS
3316 
3317   Input Parameters:
3318 . ts   - The TS context obtained from TSCreate()
3319 
3320   Notes:
3321   TSPreStep() is typically used within time stepping implementations,
3322   so most users would not generally call this routine themselves.
3323 
3324   Level: developer
3325 
3326 .keywords: TS, timestep
3327 .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3328 @*/
3329 PetscErrorCode  TSPreStep(TS ts)
3330 {
3331   PetscErrorCode ierr;
3332 
3333   PetscFunctionBegin;
3334   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3335   if (ts->prestep) {
3336     PetscStackCallStandard((*ts->prestep),(ts));
3337   }
3338   PetscFunctionReturn(0);
3339 }
3340 
3341 /*@C
3342   TSSetPreStage - Sets the general-purpose function
3343   called once at the beginning of each stage.
3344 
3345   Logically Collective on TS
3346 
3347   Input Parameters:
3348 + ts   - The TS context obtained from TSCreate()
3349 - func - The function
3350 
3351   Calling sequence of func:
3352 . PetscErrorCode func(TS ts, PetscReal stagetime);
3353 
3354   Level: intermediate
3355 
3356   Note:
3357   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3358   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3359   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3360 
3361 .keywords: TS, timestep
3362 .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3363 @*/
3364 PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3365 {
3366   PetscFunctionBegin;
3367   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3368   ts->prestage = func;
3369   PetscFunctionReturn(0);
3370 }
3371 
3372 /*@C
3373   TSSetPostStage - Sets the general-purpose function
3374   called once at the end of each stage.
3375 
3376   Logically Collective on TS
3377 
3378   Input Parameters:
3379 + ts   - The TS context obtained from TSCreate()
3380 - func - The function
3381 
3382   Calling sequence of func:
3383 . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
3384 
3385   Level: intermediate
3386 
3387   Note:
3388   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3389   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3390   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3391 
3392 .keywords: TS, timestep
3393 .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3394 @*/
3395 PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3396 {
3397   PetscFunctionBegin;
3398   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3399   ts->poststage = func;
3400   PetscFunctionReturn(0);
3401 }
3402 
3403 /*@C
3404   TSSetPostEvaluate - Sets the general-purpose function
3405   called once at the end of each step evaluation.
3406 
3407   Logically Collective on TS
3408 
3409   Input Parameters:
3410 + ts   - The TS context obtained from TSCreate()
3411 - func - The function
3412 
3413   Calling sequence of func:
3414 . PetscErrorCode func(TS ts);
3415 
3416   Level: intermediate
3417 
3418   Note:
3419   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
3420   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3421   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3422   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3423   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()
3424 
3425 .keywords: TS, timestep
3426 .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3427 @*/
3428 PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3429 {
3430   PetscFunctionBegin;
3431   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3432   ts->postevaluate = func;
3433   PetscFunctionReturn(0);
3434 }
3435 
3436 /*@
3437   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3438 
3439   Collective on TS
3440 
3441   Input Parameters:
3442 . ts          - The TS context obtained from TSCreate()
3443   stagetime   - The absolute time of the current stage
3444 
3445   Notes:
3446   TSPreStage() is typically used within time stepping implementations,
3447   most users would not generally call this routine themselves.
3448 
3449   Level: developer
3450 
3451 .keywords: TS, timestep
3452 .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3453 @*/
3454 PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3455 {
3456   PetscErrorCode ierr;
3457 
3458   PetscFunctionBegin;
3459   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3460   if (ts->prestage) {
3461     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3462   }
3463   PetscFunctionReturn(0);
3464 }
3465 
3466 /*@
3467   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
3468 
3469   Collective on TS
3470 
3471   Input Parameters:
3472 . ts          - The TS context obtained from TSCreate()
3473   stagetime   - The absolute time of the current stage
3474   stageindex  - Stage number
3475   Y           - Array of vectors (of size = total number
3476                 of stages) with the stage solutions
3477 
3478   Notes:
3479   TSPostStage() is typically used within time stepping implementations,
3480   most users would not generally call this routine themselves.
3481 
3482   Level: developer
3483 
3484 .keywords: TS, timestep
3485 .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3486 @*/
3487 PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3488 {
3489   PetscErrorCode ierr;
3490 
3491   PetscFunctionBegin;
3492   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3493   if (ts->poststage) {
3494     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3495   }
3496   PetscFunctionReturn(0);
3497 }
3498 
3499 /*@
3500   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()
3501 
3502   Collective on TS
3503 
3504   Input Parameters:
3505 . ts          - The TS context obtained from TSCreate()
3506 
3507   Notes:
3508   TSPostEvaluate() is typically used within time stepping implementations,
3509   most users would not generally call this routine themselves.
3510 
3511   Level: developer
3512 
3513 .keywords: TS, timestep
3514 .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
3515 @*/
3516 PetscErrorCode  TSPostEvaluate(TS ts)
3517 {
3518   PetscErrorCode ierr;
3519 
3520   PetscFunctionBegin;
3521   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3522   if (ts->postevaluate) {
3523     PetscStackCallStandard((*ts->postevaluate),(ts));
3524   }
3525   PetscFunctionReturn(0);
3526 }
3527 
3528 /*@C
3529   TSSetPostStep - Sets the general-purpose function
3530   called once at the end of each time step.
3531 
3532   Logically Collective on TS
3533 
3534   Input Parameters:
3535 + ts   - The TS context obtained from TSCreate()
3536 - func - The function
3537 
3538   Calling sequence of func:
3539 $ func (TS ts);
3540 
3541   Notes:
3542   The function set by TSSetPostStep() is called after each successful step. The solution vector X
3543   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
3544   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.
3545 
3546   Level: intermediate
3547 
3548 .keywords: TS, timestep
3549 .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
3550 @*/
3551 PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3552 {
3553   PetscFunctionBegin;
3554   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3555   ts->poststep = func;
3556   PetscFunctionReturn(0);
3557 }
3558 
3559 /*@
3560   TSPostStep - Runs the user-defined post-step function.
3561 
3562   Collective on TS
3563 
3564   Input Parameters:
3565 . ts   - The TS context obtained from TSCreate()
3566 
3567   Notes:
3568   TSPostStep() is typically used within time stepping implementations,
3569   so most users would not generally call this routine themselves.
3570 
3571   Level: developer
3572 
3573 .keywords: TS, timestep
3574 @*/
3575 PetscErrorCode  TSPostStep(TS ts)
3576 {
3577   PetscErrorCode ierr;
3578 
3579   PetscFunctionBegin;
3580   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3581   if (ts->poststep) {
3582     PetscStackCallStandard((*ts->poststep),(ts));
3583   }
3584   PetscFunctionReturn(0);
3585 }
3586 
3587 /* ------------ Routines to set performance monitoring options ----------- */
3588 
3589 /*@C
3590    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3591    timestep to display the iteration's  progress.
3592 
3593    Logically Collective on TS
3594 
3595    Input Parameters:
3596 +  ts - the TS context obtained from TSCreate()
3597 .  monitor - monitoring routine
3598 .  mctx - [optional] user-defined context for private data for the
3599              monitor routine (use NULL if no context is desired)
3600 -  monitordestroy - [optional] routine that frees monitor context
3601           (may be NULL)
3602 
3603    Calling sequence of monitor:
3604 $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
3605 
3606 +    ts - the TS context
3607 .    steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
3608 .    time - current time
3609 .    u - current iterate
3610 -    mctx - [optional] monitoring context
3611 
3612    Notes:
3613    This routine adds an additional monitor to the list of monitors that
3614    already has been loaded.
3615 
3616    Fortran notes: Only a single monitor function can be set for each TS object
3617 
3618    Level: intermediate
3619 
3620 .keywords: TS, timestep, set, monitor
3621 
3622 .seealso: TSMonitorDefault(), TSMonitorCancel()
3623 @*/
3624 PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3625 {
3626   PetscErrorCode ierr;
3627   PetscInt       i;
3628   PetscBool      identical;
3629 
3630   PetscFunctionBegin;
3631   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3632   for (i=0; i<ts->numbermonitors;i++) {
3633     ierr = PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);CHKERRQ(ierr);
3634     if (identical) PetscFunctionReturn(0);
3635   }
3636   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3637   ts->monitor[ts->numbermonitors]          = monitor;
3638   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3639   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3640   PetscFunctionReturn(0);
3641 }
3642 
3643 /*@C
3644    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
3645 
3646    Logically Collective on TS
3647 
3648    Input Parameters:
3649 .  ts - the TS context obtained from TSCreate()
3650 
3651    Notes:
3652    There is no way to remove a single, specific monitor.
3653 
3654    Level: intermediate
3655 
3656 .keywords: TS, timestep, set, monitor
3657 
3658 .seealso: TSMonitorDefault(), TSMonitorSet()
3659 @*/
3660 PetscErrorCode  TSMonitorCancel(TS ts)
3661 {
3662   PetscErrorCode ierr;
3663   PetscInt       i;
3664 
3665   PetscFunctionBegin;
3666   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3667   for (i=0; i<ts->numbermonitors; i++) {
3668     if (ts->monitordestroy[i]) {
3669       ierr = (*ts->monitordestroy[i])(&ts->monitorcontext[i]);CHKERRQ(ierr);
3670     }
3671   }
3672   ts->numbermonitors = 0;
3673   PetscFunctionReturn(0);
3674 }
3675 
3676 /*@C
3677    TSMonitorDefault - The Default monitor, prints the timestep and time for each step
3678 
3679    Level: intermediate
3680 
3681 .keywords: TS, set, monitor
3682 
3683 .seealso:  TSMonitorSet()
3684 @*/
3685 PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3686 {
3687   PetscErrorCode ierr;
3688   PetscViewer    viewer =  vf->viewer;
3689   PetscBool      iascii,ibinary;
3690 
3691   PetscFunctionBegin;
3692   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
3693   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
3694   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);CHKERRQ(ierr);
3695   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
3696   if (iascii) {
3697     ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3698     if (step == -1){ /* this indicates it is an interpolated solution */
3699       ierr = PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);CHKERRQ(ierr);
3700     } else {
3701       ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");CHKERRQ(ierr);
3702     }
3703     ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3704   } else if (ibinary) {
3705     PetscMPIInt rank;
3706     ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
3707     if (!rank) {
3708       PetscBool skipHeader;
3709       PetscInt  classid = REAL_FILE_CLASSID;
3710 
3711       ierr = PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);CHKERRQ(ierr);
3712       if (!skipHeader) {
3713          ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
3714        }
3715       ierr = PetscRealView(1,&ptime,viewer);CHKERRQ(ierr);
3716     } else {
3717       ierr = PetscRealView(0,&ptime,viewer);CHKERRQ(ierr);
3718     }
3719   }
3720   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
3721   PetscFunctionReturn(0);
3722 }
3723 
3724 /*@C
3725    TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3726    timestep to display the iteration's  progress.
3727 
3728    Logically Collective on TS
3729 
3730    Input Parameters:
3731 +  ts - the TS context obtained from TSCreate()
3732 .  adjointmonitor - monitoring routine
3733 .  adjointmctx - [optional] user-defined context for private data for the
3734              monitor routine (use NULL if no context is desired)
3735 -  adjointmonitordestroy - [optional] routine that frees monitor context
3736           (may be NULL)
3737 
3738    Calling sequence of monitor:
3739 $    int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)
3740 
3741 +    ts - the TS context
3742 .    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
3743                                been interpolated to)
3744 .    time - current time
3745 .    u - current iterate
3746 .    numcost - number of cost functionos
3747 .    lambda - sensitivities to initial conditions
3748 .    mu - sensitivities to parameters
3749 -    adjointmctx - [optional] adjoint monitoring context
3750 
3751    Notes:
3752    This routine adds an additional monitor to the list of monitors that
3753    already has been loaded.
3754 
3755    Fortran notes: Only a single monitor function can be set for each TS object
3756 
3757    Level: intermediate
3758 
3759 .keywords: TS, timestep, set, adjoint, monitor
3760 
3761 .seealso: TSAdjointMonitorCancel()
3762 @*/
3763 PetscErrorCode  TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3764 {
3765   PetscErrorCode ierr;
3766   PetscInt       i;
3767   PetscBool      identical;
3768 
3769   PetscFunctionBegin;
3770   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3771   for (i=0; i<ts->numbermonitors;i++) {
3772     ierr = PetscMonitorCompare((PetscErrorCode (*)(void))adjointmonitor,adjointmctx,adjointmdestroy,(PetscErrorCode (*)(void))ts->adjointmonitor[i],ts->adjointmonitorcontext[i],ts->adjointmonitordestroy[i],&identical);CHKERRQ(ierr);
3773     if (identical) PetscFunctionReturn(0);
3774   }
3775   if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3776   ts->adjointmonitor[ts->numberadjointmonitors]          = adjointmonitor;
3777   ts->adjointmonitordestroy[ts->numberadjointmonitors]   = adjointmdestroy;
3778   ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3779   PetscFunctionReturn(0);
3780 }
3781 
3782 /*@C
3783    TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.
3784 
3785    Logically Collective on TS
3786 
3787    Input Parameters:
3788 .  ts - the TS context obtained from TSCreate()
3789 
3790    Notes:
3791    There is no way to remove a single, specific monitor.
3792 
3793    Level: intermediate
3794 
3795 .keywords: TS, timestep, set, adjoint, monitor
3796 
3797 .seealso: TSAdjointMonitorSet()
3798 @*/
3799 PetscErrorCode  TSAdjointMonitorCancel(TS ts)
3800 {
3801   PetscErrorCode ierr;
3802   PetscInt       i;
3803 
3804   PetscFunctionBegin;
3805   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3806   for (i=0; i<ts->numberadjointmonitors; i++) {
3807     if (ts->adjointmonitordestroy[i]) {
3808       ierr = (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);CHKERRQ(ierr);
3809     }
3810   }
3811   ts->numberadjointmonitors = 0;
3812   PetscFunctionReturn(0);
3813 }
3814 
3815 /*@C
3816    TSAdjointMonitorDefault - the default monitor of adjoint computations
3817 
3818    Level: intermediate
3819 
3820 .keywords: TS, set, monitor
3821 
3822 .seealso: TSAdjointMonitorSet()
3823 @*/
3824 PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3825 {
3826   PetscErrorCode ierr;
3827   PetscViewer    viewer = vf->viewer;
3828 
3829   PetscFunctionBegin;
3830   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
3831   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
3832   ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3833   ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");CHKERRQ(ierr);
3834   ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3835   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
3836   PetscFunctionReturn(0);
3837 }
3838 
3839 /*@
3840    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3841 
3842    Collective on TS
3843 
3844    Input Argument:
3845 +  ts - time stepping context
3846 -  t - time to interpolate to
3847 
3848    Output Argument:
3849 .  U - state at given time
3850 
3851    Level: intermediate
3852 
3853    Developer Notes:
3854    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3855 
3856 .keywords: TS, set
3857 
3858 .seealso: TSSetExactFinalTime(), TSSolve()
3859 @*/
3860 PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3861 {
3862   PetscErrorCode ierr;
3863 
3864   PetscFunctionBegin;
3865   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3866   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3867   if (t < ts->ptime_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)ts->ptime_prev,(double)ts->ptime);
3868   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3869   ierr = (*ts->ops->interpolate)(ts,t,U);CHKERRQ(ierr);
3870   PetscFunctionReturn(0);
3871 }
3872 
3873 /*@
3874    TSStep - Steps one time step
3875 
3876    Collective on TS
3877 
3878    Input Parameter:
3879 .  ts - the TS context obtained from TSCreate()
3880 
3881    Level: developer
3882 
3883    Notes:
3884    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
3885 
3886    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3887    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3888 
3889    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3890    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3891 
3892 .keywords: TS, timestep, solve
3893 
3894 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3895 @*/
3896 PetscErrorCode  TSStep(TS ts)
3897 {
3898   PetscErrorCode   ierr;
3899   static PetscBool cite = PETSC_FALSE;
3900   PetscReal        ptime;
3901 
3902   PetscFunctionBegin;
3903   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3904   ierr = PetscCitationsRegister("@techreport{tspaper,\n"
3905                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3906                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3907                                 "  type        = {Preprint},\n"
3908                                 "  number      = {ANL/MCS-P5061-0114},\n"
3909                                 "  institution = {Argonne National Laboratory},\n"
3910                                 "  year        = {2014}\n}\n",&cite);CHKERRQ(ierr);
3911 
3912   ierr = TSSetUp(ts);CHKERRQ(ierr);
3913   ierr = TSTrajectorySetUp(ts->trajectory,ts);CHKERRQ(ierr);
3914 
3915   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
3916   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
3917 
3918   if (!ts->steps) ts->ptime_prev = ts->ptime;
3919   ts->reason = TS_CONVERGED_ITERATING;
3920   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3921   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3922   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3923   ierr = (*ts->ops->step)(ts);CHKERRQ(ierr);
3924   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3925   ts->ptime_prev = ptime;
3926   ts->steps++; ts->total_steps++;
3927   ts->steprollback = PETSC_FALSE;
3928   ts->steprestart  = PETSC_FALSE;
3929 
3930   if (ts->reason < 0) {
3931     if (ts->errorifstepfailed) {
3932       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]);
3933       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3934     }
3935   } else if (!ts->reason) {
3936     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3937     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3938   }
3939   PetscFunctionReturn(0);
3940 }
3941 
3942 /*@
3943    TSAdjointStep - Steps one time step backward in the adjoint run
3944 
3945    Collective on TS
3946 
3947    Input Parameter:
3948 .  ts - the TS context obtained from TSCreate()
3949 
3950    Level: intermediate
3951 
3952 .keywords: TS, adjoint, step
3953 
3954 .seealso: TSAdjointSetUp(), TSAdjointSolve()
3955 @*/
3956 PetscErrorCode  TSAdjointStep(TS ts)
3957 {
3958   DM               dm;
3959   PetscErrorCode   ierr;
3960 
3961   PetscFunctionBegin;
3962   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3963   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3964   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3965 
3966   ierr = VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");CHKERRQ(ierr);
3967 
3968   ts->reason = TS_CONVERGED_ITERATING;
3969   ts->ptime_prev = ts->ptime;
3970   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);
3971   ierr = PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);CHKERRQ(ierr);
3972   ierr = (*ts->ops->adjointstep)(ts);CHKERRQ(ierr);
3973   ierr = PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);CHKERRQ(ierr);
3974   ts->steps++; ts->total_steps--;
3975 
3976   if (ts->reason < 0) {
3977     if (ts->errorifstepfailed) {
3978       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]);
3979       else if (ts->reason == TS_DIVERGED_STEP_REJECTED) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_reject or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3980       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3981     }
3982   } else if (!ts->reason) {
3983     if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
3984   }
3985   PetscFunctionReturn(0);
3986 }
3987 
3988 /*@
3989    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3990    at the end of a time step with a given order of accuracy.
3991 
3992    Collective on TS
3993 
3994    Input Arguments:
3995 +  ts - time stepping context
3996 .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3997 -  order - optional, desired order for the error evaluation or PETSC_DECIDE
3998 
3999    Output Arguments:
4000 +  order - optional, the actual order of the error evaluation
4001 -  wlte - the weighted local truncation error norm
4002 
4003    Level: advanced
4004 
4005    Notes:
4006    If the timestepper cannot evaluate the error in a particular step
4007    (eg. in the first step or restart steps after event handling),
4008    this routine returns wlte=-1.0 .
4009 
4010 .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
4011 @*/
4012 PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
4013 {
4014   PetscErrorCode ierr;
4015 
4016   PetscFunctionBegin;
4017   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4018   PetscValidType(ts,1);
4019   PetscValidLogicalCollectiveEnum(ts,wnormtype,4);
4020   if (order) PetscValidIntPointer(order,3);
4021   if (order) PetscValidLogicalCollectiveInt(ts,*order,3);
4022   PetscValidRealPointer(wlte,4);
4023   if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
4024   if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
4025   ierr = (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);CHKERRQ(ierr);
4026   PetscFunctionReturn(0);
4027 }
4028 
4029 /*@
4030    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
4031 
4032    Collective on TS
4033 
4034    Input Arguments:
4035 +  ts - time stepping context
4036 .  order - desired order of accuracy
4037 -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
4038 
4039    Output Arguments:
4040 .  U - state at the end of the current step
4041 
4042    Level: advanced
4043 
4044    Notes:
4045    This function cannot be called until all stages have been evaluated.
4046    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.
4047 
4048 .seealso: TSStep(), TSAdapt
4049 @*/
4050 PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
4051 {
4052   PetscErrorCode ierr;
4053 
4054   PetscFunctionBegin;
4055   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4056   PetscValidType(ts,1);
4057   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
4058   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
4059   ierr = (*ts->ops->evaluatestep)(ts,order,U,done);CHKERRQ(ierr);
4060   PetscFunctionReturn(0);
4061 }
4062 
4063 /*@
4064  TSForwardCostIntegral - Evaluate the cost integral in the forward run.
4065 
4066  Collective on TS
4067 
4068  Input Arguments:
4069  .  ts - time stepping context
4070 
4071  Level: advanced
4072 
4073  Notes:
4074  This function cannot be called until TSStep() has been completed.
4075 
4076  .seealso: TSSolve(), TSAdjointCostIntegral()
4077  @*/
4078 PetscErrorCode TSForwardCostIntegral(TS ts)
4079 {
4080     PetscErrorCode ierr;
4081     PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4082     if (!ts->ops->forwardintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the forward run",((PetscObject)ts)->type_name);
4083     ierr = (*ts->ops->forwardintegral)(ts);CHKERRQ(ierr);
4084     PetscFunctionReturn(0);
4085 }
4086 
4087 /*@
4088    TSSolve - Steps the requested number of timesteps.
4089 
4090    Collective on TS
4091 
4092    Input Parameter:
4093 +  ts - the TS context obtained from TSCreate()
4094 -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
4095                              otherwise must contain the initial conditions and will contain the solution at the final requested time
4096 
4097    Level: beginner
4098 
4099    Notes:
4100    The final time returned by this function may be different from the time of the internally
4101    held state accessible by TSGetSolution() and TSGetTime() because the method may have
4102    stepped over the final time.
4103 
4104 .keywords: TS, timestep, solve
4105 
4106 .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
4107 @*/
4108 PetscErrorCode TSSolve(TS ts,Vec u)
4109 {
4110   Vec               solution;
4111   PetscErrorCode    ierr;
4112 
4113   PetscFunctionBegin;
4114   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4115   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
4116 
4117   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 */
4118     PetscValidHeaderSpecific(u,VEC_CLASSID,2);
4119     if (!ts->vec_sol || u == ts->vec_sol) {
4120       ierr = VecDuplicate(u,&solution);CHKERRQ(ierr);
4121       ierr = TSSetSolution(ts,solution);CHKERRQ(ierr);
4122       ierr = VecDestroy(&solution);CHKERRQ(ierr); /* grant ownership */
4123     }
4124     ierr = VecCopy(u,ts->vec_sol);CHKERRQ(ierr);
4125   } else if (u) {
4126     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
4127   }
4128   ierr = TSSetUp(ts);CHKERRQ(ierr);
4129   ierr = TSTrajectorySetUp(ts->trajectory,ts);CHKERRQ(ierr);
4130 
4131   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
4132   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
4133 
4134   /* reset number of steps only when the step is not restarted. ARKIMEX
4135      restarts the step after an event. Resetting these counters in such a case causes
4136      TSTrajectory to incorrectly save the output files
4137   */
4138 
4139   ts->steps             = 0;
4140   ts->ksp_its           = 0;
4141   ts->snes_its          = 0;
4142   ts->num_snes_failures = 0;
4143   ts->reject            = 0;
4144   ts->reason            = TS_CONVERGED_ITERATING;
4145 
4146   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
4147 
4148   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4149     ierr = (*ts->ops->solve)(ts);CHKERRQ(ierr);
4150     if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
4151     ts->solvetime = ts->ptime;
4152     solution = ts->vec_sol;
4153   } else { /* Step the requested number of timesteps. */
4154     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
4155     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4156 
4157     ierr = TSTrajectorySet(ts->trajectory,ts,ts->total_steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
4158     ierr = TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
4159 
4160     ts->steprollback = PETSC_FALSE;
4161     ts->steprestart  = PETSC_TRUE;
4162 
4163     while (!ts->reason) {
4164       ierr = TSMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
4165       if (!ts->steprollback) {
4166         ierr = TSPreStep(ts);CHKERRQ(ierr);
4167       }
4168       ierr = TSStep(ts);CHKERRQ(ierr);
4169       if (ts->vec_costintegral && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
4170         ierr = TSForwardCostIntegral(ts);CHKERRQ(ierr);
4171       }
4172       ierr = TSPostEvaluate(ts);CHKERRQ(ierr);
4173       ierr = TSEventHandler(ts);CHKERRQ(ierr); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
4174       if (!ts->steprollback) {
4175         ierr = TSTrajectorySet(ts->trajectory,ts,ts->total_steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
4176         ierr = TSPostStep(ts);CHKERRQ(ierr);
4177       }
4178     }
4179     ierr = TSMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
4180 
4181     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
4182       ierr = TSInterpolate(ts,ts->max_time,u);CHKERRQ(ierr);
4183       ts->solvetime = ts->max_time;
4184       solution = u;
4185       ierr = TSMonitor(ts,-1,ts->solvetime,solution);CHKERRQ(ierr);
4186     } else {
4187       if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
4188       ts->solvetime = ts->ptime;
4189       solution = ts->vec_sol;
4190     }
4191   }
4192 
4193   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
4194   ierr = VecViewFromOptions(solution,NULL,"-ts_view_solution");CHKERRQ(ierr);
4195   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
4196   if (ts->adjoint_solve) {
4197     ierr = TSAdjointSolve(ts);CHKERRQ(ierr);
4198   }
4199   PetscFunctionReturn(0);
4200 }
4201 
4202 /*@
4203  TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4204 
4205  Collective on TS
4206 
4207  Input Arguments:
4208  .  ts - time stepping context
4209 
4210  Level: advanced
4211 
4212  Notes:
4213  This function cannot be called until TSAdjointStep() has been completed.
4214 
4215  .seealso: TSAdjointSolve(), TSAdjointStep
4216  @*/
4217 PetscErrorCode TSAdjointCostIntegral(TS ts)
4218 {
4219     PetscErrorCode ierr;
4220     PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4221     if (!ts->ops->adjointintegral) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide integral evaluation in the adjoint run",((PetscObject)ts)->type_name);
4222     ierr = (*ts->ops->adjointintegral)(ts);CHKERRQ(ierr);
4223     PetscFunctionReturn(0);
4224 }
4225 
4226 /*@
4227    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
4228 
4229    Collective on TS
4230 
4231    Input Parameter:
4232 .  ts - the TS context obtained from TSCreate()
4233 
4234    Options Database:
4235 . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions
4236 
4237    Level: intermediate
4238 
4239    Notes:
4240    This must be called after a call to TSSolve() that solves the forward problem
4241 
4242    By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time
4243 
4244 .keywords: TS, timestep, solve
4245 
4246 .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4247 @*/
4248 PetscErrorCode TSAdjointSolve(TS ts)
4249 {
4250   PetscErrorCode    ierr;
4251 
4252   PetscFunctionBegin;
4253   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4254   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
4255 
4256   /* reset time step and iteration counters */
4257   ts->steps             = 0;
4258   ts->ksp_its           = 0;
4259   ts->snes_its          = 0;
4260   ts->num_snes_failures = 0;
4261   ts->reject            = 0;
4262   ts->reason            = TS_CONVERGED_ITERATING;
4263 
4264   if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;
4265 
4266   if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
4267   while (!ts->reason) {
4268     ierr = TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);CHKERRQ(ierr);
4269     ierr = TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);CHKERRQ(ierr);
4270     ierr = TSAdjointEventHandler(ts);CHKERRQ(ierr);
4271     ierr = TSAdjointStep(ts);CHKERRQ(ierr);
4272     if (ts->vec_costintegral && !ts->costintegralfwd) {
4273       ierr = TSAdjointCostIntegral(ts);CHKERRQ(ierr);
4274     }
4275   }
4276   ierr = TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);CHKERRQ(ierr);
4277   ierr = TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);CHKERRQ(ierr);
4278   ts->solvetime = ts->ptime;
4279   ierr = TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");CHKERRQ(ierr);
4280   ierr = VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");CHKERRQ(ierr);
4281   PetscFunctionReturn(0);
4282 }
4283 
4284 /*@C
4285    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
4286 
4287    Collective on TS
4288 
4289    Input Parameters:
4290 +  ts - time stepping context obtained from TSCreate()
4291 .  step - step number that has just completed
4292 .  ptime - model time of the state
4293 -  u - state at the current model time
4294 
4295    Notes:
4296    TSMonitor() is typically used automatically within the time stepping implementations.
4297    Users would almost never call this routine directly.
4298 
4299    A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions
4300 
4301    Level: developer
4302 
4303 .keywords: TS, timestep
4304 @*/
4305 PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4306 {
4307   DM             dm;
4308   PetscInt       i,n = ts->numbermonitors;
4309   PetscErrorCode ierr;
4310 
4311   PetscFunctionBegin;
4312   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4313   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
4314 
4315   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4316   ierr = DMSetOutputSequenceNumber(dm,step,ptime);CHKERRQ(ierr);
4317 
4318   ierr = VecLockPush(u);CHKERRQ(ierr);
4319   for (i=0; i<n; i++) {
4320     ierr = (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);CHKERRQ(ierr);
4321   }
4322   ierr = VecLockPop(u);CHKERRQ(ierr);
4323   PetscFunctionReturn(0);
4324 }
4325 
4326 /*@C
4327    TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()
4328 
4329    Collective on TS
4330 
4331    Input Parameters:
4332 +  ts - time stepping context obtained from TSCreate()
4333 .  step - step number that has just completed
4334 .  ptime - model time of the state
4335 .  u - state at the current model time
4336 .  numcost - number of cost functions (dimension of lambda  or mu)
4337 .  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4338 -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters
4339 
4340    Notes:
4341    TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4342    Users would almost never call this routine directly.
4343 
4344    Level: developer
4345 
4346 .keywords: TS, timestep
4347 @*/
4348 PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4349 {
4350   PetscErrorCode ierr;
4351   PetscInt       i,n = ts->numberadjointmonitors;
4352 
4353   PetscFunctionBegin;
4354   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4355   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
4356   ierr = VecLockPush(u);CHKERRQ(ierr);
4357   for (i=0; i<n; i++) {
4358     ierr = (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);CHKERRQ(ierr);
4359   }
4360   ierr = VecLockPop(u);CHKERRQ(ierr);
4361   PetscFunctionReturn(0);
4362 }
4363 
4364 /* ------------------------------------------------------------------------*/
4365 /*@C
4366    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4367    TS to monitor the solution process graphically in various ways
4368 
4369    Collective on TS
4370 
4371    Input Parameters:
4372 +  host - the X display to open, or null for the local machine
4373 .  label - the title to put in the title bar
4374 .  x, y - the screen coordinates of the upper left coordinate of the window
4375 .  m, n - the screen width and height in pixels
4376 -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
4377 
4378    Output Parameter:
4379 .  ctx - the context
4380 
4381    Options Database Key:
4382 +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4383 .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4384 .  -ts_monitor_lg_error -  monitor the error
4385 .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4386 .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4387 -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true
4388 
4389    Notes:
4390    Use TSMonitorLGCtxDestroy() to destroy.
4391 
4392    One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()
4393 
4394    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4395    first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
4396    as the first argument.
4397 
4398    One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()
4399 
4400 
4401    Level: intermediate
4402 
4403 .keywords: TS, monitor, line graph, residual
4404 
4405 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4406            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4407            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4408            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4409            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
4410 
4411 @*/
4412 PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4413 {
4414   PetscDraw      draw;
4415   PetscErrorCode ierr;
4416 
4417   PetscFunctionBegin;
4418   ierr = PetscNew(ctx);CHKERRQ(ierr);
4419   ierr = PetscDrawCreate(comm,host,label,x,y,m,n,&draw);CHKERRQ(ierr);
4420   ierr = PetscDrawSetFromOptions(draw);CHKERRQ(ierr);
4421   ierr = PetscDrawLGCreate(draw,1,&(*ctx)->lg);CHKERRQ(ierr);
4422   ierr = PetscDrawLGSetFromOptions((*ctx)->lg);CHKERRQ(ierr);
4423   ierr = PetscDrawDestroy(&draw);CHKERRQ(ierr);
4424   (*ctx)->howoften = howoften;
4425   PetscFunctionReturn(0);
4426 }
4427 
4428 PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4429 {
4430   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4431   PetscReal      x   = ptime,y;
4432   PetscErrorCode ierr;
4433 
4434   PetscFunctionBegin;
4435   if (step < 0) PetscFunctionReturn(0); /* -1 indicates an interpolated solution */
4436   if (!step) {
4437     PetscDrawAxis axis;
4438     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4439     ierr = PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time Step");CHKERRQ(ierr);
4440     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4441   }
4442   ierr = TSGetTimeStep(ts,&y);CHKERRQ(ierr);
4443   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
4444   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4445     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4446     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
4447   }
4448   PetscFunctionReturn(0);
4449 }
4450 
4451 /*@C
4452    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4453    with TSMonitorLGCtxCreate().
4454 
4455    Collective on TSMonitorLGCtx
4456 
4457    Input Parameter:
4458 .  ctx - the monitor context
4459 
4460    Level: intermediate
4461 
4462 .keywords: TS, monitor, line graph, destroy
4463 
4464 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4465 @*/
4466 PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4467 {
4468   PetscErrorCode ierr;
4469 
4470   PetscFunctionBegin;
4471   if ((*ctx)->transformdestroy) {
4472     ierr = ((*ctx)->transformdestroy)((*ctx)->transformctx);CHKERRQ(ierr);
4473   }
4474   ierr = PetscDrawLGDestroy(&(*ctx)->lg);CHKERRQ(ierr);
4475   ierr = PetscStrArrayDestroy(&(*ctx)->names);CHKERRQ(ierr);
4476   ierr = PetscStrArrayDestroy(&(*ctx)->displaynames);CHKERRQ(ierr);
4477   ierr = PetscFree((*ctx)->displayvariables);CHKERRQ(ierr);
4478   ierr = PetscFree((*ctx)->displayvalues);CHKERRQ(ierr);
4479   ierr = PetscFree(*ctx);CHKERRQ(ierr);
4480   PetscFunctionReturn(0);
4481 }
4482 
4483 /*@
4484    TSGetTime - Gets the time of the most recently completed step.
4485 
4486    Not Collective
4487 
4488    Input Parameter:
4489 .  ts - the TS context obtained from TSCreate()
4490 
4491    Output Parameter:
4492 .  t  - the current time. This time may not corresponds to the final time set with TSSetDuration(), use TSGetSolveTime().
4493 
4494    Level: beginner
4495 
4496    Note:
4497    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4498    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
4499 
4500 .seealso: TSSetInitialTimeStep(), TSGetTimeStep(), TSGetSolveTime()
4501 
4502 .keywords: TS, get, time
4503 @*/
4504 PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4505 {
4506   PetscFunctionBegin;
4507   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4508   PetscValidRealPointer(t,2);
4509   *t = ts->ptime;
4510   PetscFunctionReturn(0);
4511 }
4512 
4513 /*@
4514    TSGetPrevTime - Gets the starting time of the previously completed step.
4515 
4516    Not Collective
4517 
4518    Input Parameter:
4519 .  ts - the TS context obtained from TSCreate()
4520 
4521    Output Parameter:
4522 .  t  - the previous time
4523 
4524    Level: beginner
4525 
4526 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
4527 
4528 .keywords: TS, get, time
4529 @*/
4530 PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4531 {
4532   PetscFunctionBegin;
4533   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4534   PetscValidRealPointer(t,2);
4535   *t = ts->ptime_prev;
4536   PetscFunctionReturn(0);
4537 }
4538 
4539 /*@
4540    TSSetTime - Allows one to reset the time.
4541 
4542    Logically Collective on TS
4543 
4544    Input Parameters:
4545 +  ts - the TS context obtained from TSCreate()
4546 -  time - the time
4547 
4548    Level: intermediate
4549 
4550 .seealso: TSGetTime(), TSSetDuration()
4551 
4552 .keywords: TS, set, time
4553 @*/
4554 PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4555 {
4556   PetscFunctionBegin;
4557   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4558   PetscValidLogicalCollectiveReal(ts,t,2);
4559   ts->ptime = t;
4560   PetscFunctionReturn(0);
4561 }
4562 
4563 /*@C
4564    TSSetOptionsPrefix - Sets the prefix used for searching for all
4565    TS options in the database.
4566 
4567    Logically Collective on TS
4568 
4569    Input Parameter:
4570 +  ts     - The TS context
4571 -  prefix - The prefix to prepend to all option names
4572 
4573    Notes:
4574    A hyphen (-) must NOT be given at the beginning of the prefix name.
4575    The first character of all runtime options is AUTOMATICALLY the
4576    hyphen.
4577 
4578    Level: advanced
4579 
4580 .keywords: TS, set, options, prefix, database
4581 
4582 .seealso: TSSetFromOptions()
4583 
4584 @*/
4585 PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4586 {
4587   PetscErrorCode ierr;
4588   SNES           snes;
4589 
4590   PetscFunctionBegin;
4591   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4592   ierr = PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4593   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4594   ierr = SNESSetOptionsPrefix(snes,prefix);CHKERRQ(ierr);
4595   PetscFunctionReturn(0);
4596 }
4597 
4598 
4599 /*@C
4600    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4601    TS options in the database.
4602 
4603    Logically Collective on TS
4604 
4605    Input Parameter:
4606 +  ts     - The TS context
4607 -  prefix - The prefix to prepend to all option names
4608 
4609    Notes:
4610    A hyphen (-) must NOT be given at the beginning of the prefix name.
4611    The first character of all runtime options is AUTOMATICALLY the
4612    hyphen.
4613 
4614    Level: advanced
4615 
4616 .keywords: TS, append, options, prefix, database
4617 
4618 .seealso: TSGetOptionsPrefix()
4619 
4620 @*/
4621 PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4622 {
4623   PetscErrorCode ierr;
4624   SNES           snes;
4625 
4626   PetscFunctionBegin;
4627   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4628   ierr = PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4629   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4630   ierr = SNESAppendOptionsPrefix(snes,prefix);CHKERRQ(ierr);
4631   PetscFunctionReturn(0);
4632 }
4633 
4634 /*@C
4635    TSGetOptionsPrefix - Sets the prefix used for searching for all
4636    TS options in the database.
4637 
4638    Not Collective
4639 
4640    Input Parameter:
4641 .  ts - The TS context
4642 
4643    Output Parameter:
4644 .  prefix - A pointer to the prefix string used
4645 
4646    Notes: On the fortran side, the user should pass in a string 'prifix' of
4647    sufficient length to hold the prefix.
4648 
4649    Level: intermediate
4650 
4651 .keywords: TS, get, options, prefix, database
4652 
4653 .seealso: TSAppendOptionsPrefix()
4654 @*/
4655 PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4656 {
4657   PetscErrorCode ierr;
4658 
4659   PetscFunctionBegin;
4660   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4661   PetscValidPointer(prefix,2);
4662   ierr = PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4663   PetscFunctionReturn(0);
4664 }
4665 
4666 /*@C
4667    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4668 
4669    Not Collective, but parallel objects are returned if TS is parallel
4670 
4671    Input Parameter:
4672 .  ts  - The TS context obtained from TSCreate()
4673 
4674    Output Parameters:
4675 +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4676 .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4677 .  func - Function to compute the Jacobian of the RHS  (or NULL)
4678 -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4679 
4680    Notes: You can pass in NULL for any return argument you do not need.
4681 
4682    Level: intermediate
4683 
4684 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4685 
4686 .keywords: TS, timestep, get, matrix, Jacobian
4687 @*/
4688 PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4689 {
4690   PetscErrorCode ierr;
4691   DM             dm;
4692 
4693   PetscFunctionBegin;
4694   if (Amat || Pmat) {
4695     SNES snes;
4696     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4697     ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
4698     ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
4699   }
4700   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4701   ierr = DMTSGetRHSJacobian(dm,func,ctx);CHKERRQ(ierr);
4702   PetscFunctionReturn(0);
4703 }
4704 
4705 /*@C
4706    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4707 
4708    Not Collective, but parallel objects are returned if TS is parallel
4709 
4710    Input Parameter:
4711 .  ts  - The TS context obtained from TSCreate()
4712 
4713    Output Parameters:
4714 +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4715 .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4716 .  f   - The function to compute the matrices
4717 - ctx - User-defined context for Jacobian evaluation routine
4718 
4719    Notes: You can pass in NULL for any return argument you do not need.
4720 
4721    Level: advanced
4722 
4723 .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4724 
4725 .keywords: TS, timestep, get, matrix, Jacobian
4726 @*/
4727 PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4728 {
4729   PetscErrorCode ierr;
4730   DM             dm;
4731 
4732   PetscFunctionBegin;
4733   if (Amat || Pmat) {
4734     SNES snes;
4735     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4736     ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
4737     ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
4738   }
4739   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4740   ierr = DMTSGetIJacobian(dm,f,ctx);CHKERRQ(ierr);
4741   PetscFunctionReturn(0);
4742 }
4743 
4744 
4745 /*@C
4746    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4747    VecView() for the solution at each timestep
4748 
4749    Collective on TS
4750 
4751    Input Parameters:
4752 +  ts - the TS context
4753 .  step - current time-step
4754 .  ptime - current time
4755 -  dummy - either a viewer or NULL
4756 
4757    Options Database:
4758 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4759 
4760    Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4761        will look bad
4762 
4763    Level: intermediate
4764 
4765 .keywords: TS,  vector, monitor, view
4766 
4767 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4768 @*/
4769 PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4770 {
4771   PetscErrorCode   ierr;
4772   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4773   PetscDraw        draw;
4774 
4775   PetscFunctionBegin;
4776   if (!step && ictx->showinitial) {
4777     if (!ictx->initialsolution) {
4778       ierr = VecDuplicate(u,&ictx->initialsolution);CHKERRQ(ierr);
4779     }
4780     ierr = VecCopy(u,ictx->initialsolution);CHKERRQ(ierr);
4781   }
4782   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4783 
4784   if (ictx->showinitial) {
4785     PetscReal pause;
4786     ierr = PetscViewerDrawGetPause(ictx->viewer,&pause);CHKERRQ(ierr);
4787     ierr = PetscViewerDrawSetPause(ictx->viewer,0.0);CHKERRQ(ierr);
4788     ierr = VecView(ictx->initialsolution,ictx->viewer);CHKERRQ(ierr);
4789     ierr = PetscViewerDrawSetPause(ictx->viewer,pause);CHKERRQ(ierr);
4790     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);CHKERRQ(ierr);
4791   }
4792   ierr = VecView(u,ictx->viewer);CHKERRQ(ierr);
4793   if (ictx->showtimestepandtime) {
4794     PetscReal xl,yl,xr,yr,h;
4795     char      time[32];
4796 
4797     ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4798     ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4799     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4800     h    = yl + .95*(yr - yl);
4801     ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4802     ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4803   }
4804 
4805   if (ictx->showinitial) {
4806     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);CHKERRQ(ierr);
4807   }
4808   PetscFunctionReturn(0);
4809 }
4810 
4811 /*@C
4812    TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
4813    VecView() for the sensitivities to initial states at each timestep
4814 
4815    Collective on TS
4816 
4817    Input Parameters:
4818 +  ts - the TS context
4819 .  step - current time-step
4820 .  ptime - current time
4821 .  u - current state
4822 .  numcost - number of cost functions
4823 .  lambda - sensitivities to initial conditions
4824 .  mu - sensitivities to parameters
4825 -  dummy - either a viewer or NULL
4826 
4827    Level: intermediate
4828 
4829 .keywords: TS,  vector, adjoint, monitor, view
4830 
4831 .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
4832 @*/
4833 PetscErrorCode  TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
4834 {
4835   PetscErrorCode   ierr;
4836   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4837   PetscDraw        draw;
4838   PetscReal        xl,yl,xr,yr,h;
4839   char             time[32];
4840 
4841   PetscFunctionBegin;
4842   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4843 
4844   ierr = VecView(lambda[0],ictx->viewer);CHKERRQ(ierr);
4845   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4846   ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4847   ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4848   h    = yl + .95*(yr - yl);
4849   ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4850   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4851   PetscFunctionReturn(0);
4852 }
4853 
4854 /*@C
4855    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
4856 
4857    Collective on TS
4858 
4859    Input Parameters:
4860 +  ts - the TS context
4861 .  step - current time-step
4862 .  ptime - current time
4863 -  dummy - either a viewer or NULL
4864 
4865    Level: intermediate
4866 
4867 .keywords: TS,  vector, monitor, view
4868 
4869 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4870 @*/
4871 PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4872 {
4873   PetscErrorCode    ierr;
4874   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4875   PetscDraw         draw;
4876   PetscDrawAxis     axis;
4877   PetscInt          n;
4878   PetscMPIInt       size;
4879   PetscReal         U0,U1,xl,yl,xr,yr,h;
4880   char              time[32];
4881   const PetscScalar *U;
4882 
4883   PetscFunctionBegin;
4884   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);CHKERRQ(ierr);
4885   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4886   ierr = VecGetSize(u,&n);CHKERRQ(ierr);
4887   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4888 
4889   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4890   ierr = PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);CHKERRQ(ierr);
4891   ierr = PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);CHKERRQ(ierr);
4892   if (!step) {
4893     ierr = PetscDrawClear(draw);CHKERRQ(ierr);
4894     ierr = PetscDrawAxisDraw(axis);CHKERRQ(ierr);
4895   }
4896 
4897   ierr = VecGetArrayRead(u,&U);CHKERRQ(ierr);
4898   U0 = PetscRealPart(U[0]);
4899   U1 = PetscRealPart(U[1]);
4900   ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
4901   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) PetscFunctionReturn(0);
4902 
4903   ierr = PetscDrawCollectiveBegin(draw);CHKERRQ(ierr);
4904   ierr = PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);CHKERRQ(ierr);
4905   if (ictx->showtimestepandtime) {
4906     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4907     ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4908     h    = yl + .95*(yr - yl);
4909     ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4910   }
4911   ierr = PetscDrawCollectiveEnd(draw);CHKERRQ(ierr);
4912   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4913   ierr = PetscDrawPause(draw);CHKERRQ(ierr);
4914   ierr = PetscDrawSave(draw);CHKERRQ(ierr);
4915   PetscFunctionReturn(0);
4916 }
4917 
4918 
4919 /*@C
4920    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4921 
4922    Collective on TS
4923 
4924    Input Parameters:
4925 .    ctx - the monitor context
4926 
4927    Level: intermediate
4928 
4929 .keywords: TS,  vector, monitor, view
4930 
4931 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4932 @*/
4933 PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4934 {
4935   PetscErrorCode ierr;
4936 
4937   PetscFunctionBegin;
4938   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
4939   ierr = VecDestroy(&(*ictx)->initialsolution);CHKERRQ(ierr);
4940   ierr = PetscFree(*ictx);CHKERRQ(ierr);
4941   PetscFunctionReturn(0);
4942 }
4943 
4944 /*@C
4945    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4946 
4947    Collective on TS
4948 
4949    Input Parameter:
4950 .    ts - time-step context
4951 
4952    Output Patameter:
4953 .    ctx - the monitor context
4954 
4955    Options Database:
4956 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4957 
4958    Level: intermediate
4959 
4960 .keywords: TS,  vector, monitor, view
4961 
4962 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4963 @*/
4964 PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4965 {
4966   PetscErrorCode   ierr;
4967 
4968   PetscFunctionBegin;
4969   ierr = PetscNew(ctx);CHKERRQ(ierr);
4970   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
4971   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
4972 
4973   (*ctx)->howoften    = howoften;
4974   (*ctx)->showinitial = PETSC_FALSE;
4975   ierr = PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);CHKERRQ(ierr);
4976 
4977   (*ctx)->showtimestepandtime = PETSC_FALSE;
4978   ierr = PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);CHKERRQ(ierr);
4979   PetscFunctionReturn(0);
4980 }
4981 
4982 /*@C
4983    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4984    VecView() for the error at each timestep
4985 
4986    Collective on TS
4987 
4988    Input Parameters:
4989 +  ts - the TS context
4990 .  step - current time-step
4991 .  ptime - current time
4992 -  dummy - either a viewer or NULL
4993 
4994    Level: intermediate
4995 
4996 .keywords: TS,  vector, monitor, view
4997 
4998 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4999 @*/
5000 PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5001 {
5002   PetscErrorCode   ierr;
5003   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
5004   PetscViewer      viewer = ctx->viewer;
5005   Vec              work;
5006 
5007   PetscFunctionBegin;
5008   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
5009   ierr = VecDuplicate(u,&work);CHKERRQ(ierr);
5010   ierr = TSComputeSolutionFunction(ts,ptime,work);CHKERRQ(ierr);
5011   ierr = VecAXPY(work,-1.0,u);CHKERRQ(ierr);
5012   ierr = VecView(work,viewer);CHKERRQ(ierr);
5013   ierr = VecDestroy(&work);CHKERRQ(ierr);
5014   PetscFunctionReturn(0);
5015 }
5016 
5017 #include <petsc/private/dmimpl.h>
5018 /*@
5019    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS
5020 
5021    Logically Collective on TS and DM
5022 
5023    Input Parameters:
5024 +  ts - the ODE integrator object
5025 -  dm - the dm, cannot be NULL
5026 
5027    Level: intermediate
5028 
5029 
5030 .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
5031 @*/
5032 PetscErrorCode  TSSetDM(TS ts,DM dm)
5033 {
5034   PetscErrorCode ierr;
5035   SNES           snes;
5036   DMTS           tsdm;
5037 
5038   PetscFunctionBegin;
5039   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5040   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
5041   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
5042   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
5043     if (ts->dm->dmts && !dm->dmts) {
5044       ierr = DMCopyDMTS(ts->dm,dm);CHKERRQ(ierr);
5045       ierr = DMGetDMTS(ts->dm,&tsdm);CHKERRQ(ierr);
5046       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
5047         tsdm->originaldm = dm;
5048       }
5049     }
5050     ierr = DMDestroy(&ts->dm);CHKERRQ(ierr);
5051   }
5052   ts->dm = dm;
5053 
5054   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
5055   ierr = SNESSetDM(snes,dm);CHKERRQ(ierr);
5056   PetscFunctionReturn(0);
5057 }
5058 
5059 /*@
5060    TSGetDM - Gets the DM that may be used by some preconditioners
5061 
5062    Not Collective
5063 
5064    Input Parameter:
5065 . ts - the preconditioner context
5066 
5067    Output Parameter:
5068 .  dm - the dm
5069 
5070    Level: intermediate
5071 
5072 
5073 .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
5074 @*/
5075 PetscErrorCode  TSGetDM(TS ts,DM *dm)
5076 {
5077   PetscErrorCode ierr;
5078 
5079   PetscFunctionBegin;
5080   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5081   if (!ts->dm) {
5082     ierr = DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);CHKERRQ(ierr);
5083     if (ts->snes) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
5084   }
5085   *dm = ts->dm;
5086   PetscFunctionReturn(0);
5087 }
5088 
5089 /*@
5090    SNESTSFormFunction - Function to evaluate nonlinear residual
5091 
5092    Logically Collective on SNES
5093 
5094    Input Parameter:
5095 + snes - nonlinear solver
5096 . U - the current state at which to evaluate the residual
5097 - ctx - user context, must be a TS
5098 
5099    Output Parameter:
5100 . F - the nonlinear residual
5101 
5102    Notes:
5103    This function is not normally called by users and is automatically registered with the SNES used by TS.
5104    It is most frequently passed to MatFDColoringSetFunction().
5105 
5106    Level: advanced
5107 
5108 .seealso: SNESSetFunction(), MatFDColoringSetFunction()
5109 @*/
5110 PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
5111 {
5112   TS             ts = (TS)ctx;
5113   PetscErrorCode ierr;
5114 
5115   PetscFunctionBegin;
5116   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5117   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5118   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
5119   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
5120   ierr = (ts->ops->snesfunction)(snes,U,F,ts);CHKERRQ(ierr);
5121   PetscFunctionReturn(0);
5122 }
5123 
5124 /*@
5125    SNESTSFormJacobian - Function to evaluate the Jacobian
5126 
5127    Collective on SNES
5128 
5129    Input Parameter:
5130 + snes - nonlinear solver
5131 . U - the current state at which to evaluate the residual
5132 - ctx - user context, must be a TS
5133 
5134    Output Parameter:
5135 + A - the Jacobian
5136 . B - the preconditioning matrix (may be the same as A)
5137 - flag - indicates any structure change in the matrix
5138 
5139    Notes:
5140    This function is not normally called by users and is automatically registered with the SNES used by TS.
5141 
5142    Level: developer
5143 
5144 .seealso: SNESSetJacobian()
5145 @*/
5146 PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
5147 {
5148   TS             ts = (TS)ctx;
5149   PetscErrorCode ierr;
5150 
5151   PetscFunctionBegin;
5152   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
5153   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5154   PetscValidPointer(A,3);
5155   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
5156   PetscValidPointer(B,4);
5157   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
5158   PetscValidHeaderSpecific(ts,TS_CLASSID,6);
5159   ierr = (ts->ops->snesjacobian)(snes,U,A,B,ts);CHKERRQ(ierr);
5160   PetscFunctionReturn(0);
5161 }
5162 
5163 /*@C
5164    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
5165 
5166    Collective on TS
5167 
5168    Input Arguments:
5169 +  ts - time stepping context
5170 .  t - time at which to evaluate
5171 .  U - state at which to evaluate
5172 -  ctx - context
5173 
5174    Output Arguments:
5175 .  F - right hand side
5176 
5177    Level: intermediate
5178 
5179    Notes:
5180    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5181    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
5182 
5183 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5184 @*/
5185 PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5186 {
5187   PetscErrorCode ierr;
5188   Mat            Arhs,Brhs;
5189 
5190   PetscFunctionBegin;
5191   ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
5192   ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
5193   ierr = MatMult(Arhs,U,F);CHKERRQ(ierr);
5194   PetscFunctionReturn(0);
5195 }
5196 
5197 /*@C
5198    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
5199 
5200    Collective on TS
5201 
5202    Input Arguments:
5203 +  ts - time stepping context
5204 .  t - time at which to evaluate
5205 .  U - state at which to evaluate
5206 -  ctx - context
5207 
5208    Output Arguments:
5209 +  A - pointer to operator
5210 .  B - pointer to preconditioning matrix
5211 -  flg - matrix structure flag
5212 
5213    Level: intermediate
5214 
5215    Notes:
5216    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
5217 
5218 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5219 @*/
5220 PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5221 {
5222   PetscFunctionBegin;
5223   PetscFunctionReturn(0);
5224 }
5225 
5226 /*@C
5227    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
5228 
5229    Collective on TS
5230 
5231    Input Arguments:
5232 +  ts - time stepping context
5233 .  t - time at which to evaluate
5234 .  U - state at which to evaluate
5235 .  Udot - time derivative of state vector
5236 -  ctx - context
5237 
5238    Output Arguments:
5239 .  F - left hand side
5240 
5241    Level: intermediate
5242 
5243    Notes:
5244    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
5245    user is required to write their own TSComputeIFunction.
5246    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5247    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
5248 
5249    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
5250 
5251 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5252 @*/
5253 PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5254 {
5255   PetscErrorCode ierr;
5256   Mat            A,B;
5257 
5258   PetscFunctionBegin;
5259   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
5260   ierr = TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);CHKERRQ(ierr);
5261   ierr = MatMult(A,Udot,F);CHKERRQ(ierr);
5262   PetscFunctionReturn(0);
5263 }
5264 
5265 /*@C
5266    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
5267 
5268    Collective on TS
5269 
5270    Input Arguments:
5271 +  ts - time stepping context
5272 .  t - time at which to evaluate
5273 .  U - state at which to evaluate
5274 .  Udot - time derivative of state vector
5275 .  shift - shift to apply
5276 -  ctx - context
5277 
5278    Output Arguments:
5279 +  A - pointer to operator
5280 .  B - pointer to preconditioning matrix
5281 -  flg - matrix structure flag
5282 
5283    Level: advanced
5284 
5285    Notes:
5286    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
5287 
5288    It is only appropriate for problems of the form
5289 
5290 $     M Udot = F(U,t)
5291 
5292   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
5293   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5294   an implicit operator of the form
5295 
5296 $    shift*M + J
5297 
5298   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
5299   a copy of M or reassemble it when requested.
5300 
5301 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5302 @*/
5303 PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5304 {
5305   PetscErrorCode ierr;
5306 
5307   PetscFunctionBegin;
5308   ierr = MatScale(A, shift / ts->ijacobian.shift);CHKERRQ(ierr);
5309   ts->ijacobian.shift = shift;
5310   PetscFunctionReturn(0);
5311 }
5312 
5313 /*@
5314    TSGetEquationType - Gets the type of the equation that TS is solving.
5315 
5316    Not Collective
5317 
5318    Input Parameter:
5319 .  ts - the TS context
5320 
5321    Output Parameter:
5322 .  equation_type - see TSEquationType
5323 
5324    Level: beginner
5325 
5326 .keywords: TS, equation type
5327 
5328 .seealso: TSSetEquationType(), TSEquationType
5329 @*/
5330 PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5331 {
5332   PetscFunctionBegin;
5333   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5334   PetscValidPointer(equation_type,2);
5335   *equation_type = ts->equation_type;
5336   PetscFunctionReturn(0);
5337 }
5338 
5339 /*@
5340    TSSetEquationType - Sets the type of the equation that TS is solving.
5341 
5342    Not Collective
5343 
5344    Input Parameter:
5345 +  ts - the TS context
5346 -  equation_type - see TSEquationType
5347 
5348    Level: advanced
5349 
5350 .keywords: TS, equation type
5351 
5352 .seealso: TSGetEquationType(), TSEquationType
5353 @*/
5354 PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5355 {
5356   PetscFunctionBegin;
5357   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5358   ts->equation_type = equation_type;
5359   PetscFunctionReturn(0);
5360 }
5361 
5362 /*@
5363    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
5364 
5365    Not Collective
5366 
5367    Input Parameter:
5368 .  ts - the TS context
5369 
5370    Output Parameter:
5371 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5372             manual pages for the individual convergence tests for complete lists
5373 
5374    Level: beginner
5375 
5376    Notes:
5377    Can only be called after the call to TSSolve() is complete.
5378 
5379 .keywords: TS, nonlinear, set, convergence, test
5380 
5381 .seealso: TSSetConvergenceTest(), TSConvergedReason
5382 @*/
5383 PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5384 {
5385   PetscFunctionBegin;
5386   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5387   PetscValidPointer(reason,2);
5388   *reason = ts->reason;
5389   PetscFunctionReturn(0);
5390 }
5391 
5392 /*@
5393    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
5394 
5395    Not Collective
5396 
5397    Input Parameter:
5398 +  ts - the TS context
5399 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5400             manual pages for the individual convergence tests for complete lists
5401 
5402    Level: advanced
5403 
5404    Notes:
5405    Can only be called during TSSolve() is active.
5406 
5407 .keywords: TS, nonlinear, set, convergence, test
5408 
5409 .seealso: TSConvergedReason
5410 @*/
5411 PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5412 {
5413   PetscFunctionBegin;
5414   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5415   ts->reason = reason;
5416   PetscFunctionReturn(0);
5417 }
5418 
5419 /*@
5420    TSGetSolveTime - Gets the time after a call to TSSolve()
5421 
5422    Not Collective
5423 
5424    Input Parameter:
5425 .  ts - the TS context
5426 
5427    Output Parameter:
5428 .  ftime - the final time. This time corresponds to the final time set with TSSetDuration()
5429 
5430    Level: beginner
5431 
5432    Notes:
5433    Can only be called after the call to TSSolve() is complete.
5434 
5435 .keywords: TS, nonlinear, set, convergence, test
5436 
5437 .seealso: TSSetConvergenceTest(), TSConvergedReason
5438 @*/
5439 PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5440 {
5441   PetscFunctionBegin;
5442   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5443   PetscValidPointer(ftime,2);
5444   *ftime = ts->solvetime;
5445   PetscFunctionReturn(0);
5446 }
5447 
5448 /*@
5449    TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()
5450 
5451    Not Collective
5452 
5453    Input Parameter:
5454 .  ts - the TS context
5455 
5456    Output Parameter:
5457 .  steps - the number of steps
5458 
5459    Level: beginner
5460 
5461    Notes:
5462    Includes the number of steps for all calls to TSSolve() since TSSetUp() was called
5463 
5464 .keywords: TS, nonlinear, set, convergence, test
5465 
5466 .seealso: TSSetConvergenceTest(), TSConvergedReason
5467 @*/
5468 PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
5469 {
5470   PetscFunctionBegin;
5471   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5472   PetscValidPointer(steps,2);
5473   *steps = ts->total_steps;
5474   PetscFunctionReturn(0);
5475 }
5476 
5477 /*@
5478    TSGetSNESIterations - Gets the total number of nonlinear iterations
5479    used by the time integrator.
5480 
5481    Not Collective
5482 
5483    Input Parameter:
5484 .  ts - TS context
5485 
5486    Output Parameter:
5487 .  nits - number of nonlinear iterations
5488 
5489    Notes:
5490    This counter is reset to zero for each successive call to TSSolve().
5491 
5492    Level: intermediate
5493 
5494 .keywords: TS, get, number, nonlinear, iterations
5495 
5496 .seealso:  TSGetKSPIterations()
5497 @*/
5498 PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5499 {
5500   PetscFunctionBegin;
5501   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5502   PetscValidIntPointer(nits,2);
5503   *nits = ts->snes_its;
5504   PetscFunctionReturn(0);
5505 }
5506 
5507 /*@
5508    TSGetKSPIterations - Gets the total number of linear iterations
5509    used by the time integrator.
5510 
5511    Not Collective
5512 
5513    Input Parameter:
5514 .  ts - TS context
5515 
5516    Output Parameter:
5517 .  lits - number of linear iterations
5518 
5519    Notes:
5520    This counter is reset to zero for each successive call to TSSolve().
5521 
5522    Level: intermediate
5523 
5524 .keywords: TS, get, number, linear, iterations
5525 
5526 .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5527 @*/
5528 PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5529 {
5530   PetscFunctionBegin;
5531   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5532   PetscValidIntPointer(lits,2);
5533   *lits = ts->ksp_its;
5534   PetscFunctionReturn(0);
5535 }
5536 
5537 /*@
5538    TSGetStepRejections - Gets the total number of rejected steps.
5539 
5540    Not Collective
5541 
5542    Input Parameter:
5543 .  ts - TS context
5544 
5545    Output Parameter:
5546 .  rejects - number of steps rejected
5547 
5548    Notes:
5549    This counter is reset to zero for each successive call to TSSolve().
5550 
5551    Level: intermediate
5552 
5553 .keywords: TS, get, number
5554 
5555 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5556 @*/
5557 PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5558 {
5559   PetscFunctionBegin;
5560   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5561   PetscValidIntPointer(rejects,2);
5562   *rejects = ts->reject;
5563   PetscFunctionReturn(0);
5564 }
5565 
5566 /*@
5567    TSGetSNESFailures - Gets the total number of failed SNES solves
5568 
5569    Not Collective
5570 
5571    Input Parameter:
5572 .  ts - TS context
5573 
5574    Output Parameter:
5575 .  fails - number of failed nonlinear solves
5576 
5577    Notes:
5578    This counter is reset to zero for each successive call to TSSolve().
5579 
5580    Level: intermediate
5581 
5582 .keywords: TS, get, number
5583 
5584 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5585 @*/
5586 PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5587 {
5588   PetscFunctionBegin;
5589   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5590   PetscValidIntPointer(fails,2);
5591   *fails = ts->num_snes_failures;
5592   PetscFunctionReturn(0);
5593 }
5594 
5595 /*@
5596    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
5597 
5598    Not Collective
5599 
5600    Input Parameter:
5601 +  ts - TS context
5602 -  rejects - maximum number of rejected steps, pass -1 for unlimited
5603 
5604    Notes:
5605    The counter is reset to zero for each step
5606 
5607    Options Database Key:
5608  .  -ts_max_reject - Maximum number of step rejections before a step fails
5609 
5610    Level: intermediate
5611 
5612 .keywords: TS, set, maximum, number
5613 
5614 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5615 @*/
5616 PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5617 {
5618   PetscFunctionBegin;
5619   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5620   ts->max_reject = rejects;
5621   PetscFunctionReturn(0);
5622 }
5623 
5624 /*@
5625    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
5626 
5627    Not Collective
5628 
5629    Input Parameter:
5630 +  ts - TS context
5631 -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
5632 
5633    Notes:
5634    The counter is reset to zero for each successive call to TSSolve().
5635 
5636    Options Database Key:
5637  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
5638 
5639    Level: intermediate
5640 
5641 .keywords: TS, set, maximum, number
5642 
5643 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5644 @*/
5645 PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5646 {
5647   PetscFunctionBegin;
5648   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5649   ts->max_snes_failures = fails;
5650   PetscFunctionReturn(0);
5651 }
5652 
5653 /*@
5654    TSSetErrorIfStepFails - Error if no step succeeds
5655 
5656    Not Collective
5657 
5658    Input Parameter:
5659 +  ts - TS context
5660 -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
5661 
5662    Options Database Key:
5663  .  -ts_error_if_step_fails - Error if no step succeeds
5664 
5665    Level: intermediate
5666 
5667 .keywords: TS, set, error
5668 
5669 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5670 @*/
5671 PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5672 {
5673   PetscFunctionBegin;
5674   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5675   ts->errorifstepfailed = err;
5676   PetscFunctionReturn(0);
5677 }
5678 
5679 /*@C
5680    TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object
5681 
5682    Collective on TS
5683 
5684    Input Parameters:
5685 +  ts - the TS context
5686 .  step - current time-step
5687 .  ptime - current time
5688 .  u - current state
5689 -  vf - viewer and its format
5690 
5691    Level: intermediate
5692 
5693 .keywords: TS,  vector, monitor, view
5694 
5695 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5696 @*/
5697 PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5698 {
5699   PetscErrorCode ierr;
5700 
5701   PetscFunctionBegin;
5702   ierr = PetscViewerPushFormat(vf->viewer,vf->format);CHKERRQ(ierr);
5703   ierr = VecView(u,vf->viewer);CHKERRQ(ierr);
5704   ierr = PetscViewerPopFormat(vf->viewer);CHKERRQ(ierr);
5705   PetscFunctionReturn(0);
5706 }
5707 
5708 /*@C
5709    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
5710 
5711    Collective on TS
5712 
5713    Input Parameters:
5714 +  ts - the TS context
5715 .  step - current time-step
5716 .  ptime - current time
5717 .  u - current state
5718 -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5719 
5720    Level: intermediate
5721 
5722    Notes:
5723    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.
5724    These are named according to the file name template.
5725 
5726    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
5727 
5728 .keywords: TS,  vector, monitor, view
5729 
5730 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5731 @*/
5732 PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5733 {
5734   PetscErrorCode ierr;
5735   char           filename[PETSC_MAX_PATH_LEN];
5736   PetscViewer    viewer;
5737 
5738   PetscFunctionBegin;
5739   if (step < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
5740   ierr = PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);CHKERRQ(ierr);
5741   ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);
5742   ierr = VecView(u,viewer);CHKERRQ(ierr);
5743   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
5744   PetscFunctionReturn(0);
5745 }
5746 
5747 /*@C
5748    TSMonitorSolutionVTKDestroy - Destroy context for monitoring
5749 
5750    Collective on TS
5751 
5752    Input Parameters:
5753 .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5754 
5755    Level: intermediate
5756 
5757    Note:
5758    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
5759 
5760 .keywords: TS,  vector, monitor, view
5761 
5762 .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5763 @*/
5764 PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5765 {
5766   PetscErrorCode ierr;
5767 
5768   PetscFunctionBegin;
5769   ierr = PetscFree(*(char**)filenametemplate);CHKERRQ(ierr);
5770   PetscFunctionReturn(0);
5771 }
5772 
5773 /*@
5774    TSGetAdapt - Get the adaptive controller context for the current method
5775 
5776    Collective on TS if controller has not been created yet
5777 
5778    Input Arguments:
5779 .  ts - time stepping context
5780 
5781    Output Arguments:
5782 .  adapt - adaptive controller
5783 
5784    Level: intermediate
5785 
5786 .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5787 @*/
5788 PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5789 {
5790   PetscErrorCode ierr;
5791 
5792   PetscFunctionBegin;
5793   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5794   PetscValidPointer(adapt,2);
5795   if (!ts->adapt) {
5796     ierr = TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);CHKERRQ(ierr);
5797     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);CHKERRQ(ierr);
5798     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);CHKERRQ(ierr);
5799   }
5800   *adapt = ts->adapt;
5801   PetscFunctionReturn(0);
5802 }
5803 
5804 /*@
5805    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
5806 
5807    Logically Collective
5808 
5809    Input Arguments:
5810 +  ts - time integration context
5811 .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5812 .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5813 .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5814 -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5815 
5816    Options Database keys:
5817 +  -ts_rtol <rtol> - relative tolerance for local truncation error
5818 -  -ts_atol <atol> Absolute tolerance for local truncation error
5819 
5820    Notes:
5821    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5822    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5823    computed only for the differential or the algebraic part then this can be done using the vector of
5824    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5825    differential part and infinity for the algebraic part, the LTE calculation will include only the
5826    differential variables.
5827 
5828    Level: beginner
5829 
5830 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5831 @*/
5832 PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5833 {
5834   PetscErrorCode ierr;
5835 
5836   PetscFunctionBegin;
5837   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5838   if (vatol) {
5839     ierr = PetscObjectReference((PetscObject)vatol);CHKERRQ(ierr);
5840     ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
5841     ts->vatol = vatol;
5842   }
5843   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5844   if (vrtol) {
5845     ierr = PetscObjectReference((PetscObject)vrtol);CHKERRQ(ierr);
5846     ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
5847     ts->vrtol = vrtol;
5848   }
5849   PetscFunctionReturn(0);
5850 }
5851 
5852 /*@
5853    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5854 
5855    Logically Collective
5856 
5857    Input Arguments:
5858 .  ts - time integration context
5859 
5860    Output Arguments:
5861 +  atol - scalar absolute tolerances, NULL to ignore
5862 .  vatol - vector of absolute tolerances, NULL to ignore
5863 .  rtol - scalar relative tolerances, NULL to ignore
5864 -  vrtol - vector of relative tolerances, NULL to ignore
5865 
5866    Level: beginner
5867 
5868 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5869 @*/
5870 PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5871 {
5872   PetscFunctionBegin;
5873   if (atol)  *atol  = ts->atol;
5874   if (vatol) *vatol = ts->vatol;
5875   if (rtol)  *rtol  = ts->rtol;
5876   if (vrtol) *vrtol = ts->vrtol;
5877   PetscFunctionReturn(0);
5878 }
5879 
5880 /*@
5881    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
5882 
5883    Collective on TS
5884 
5885    Input Arguments:
5886 +  ts - time stepping context
5887 .  U - state vector, usually ts->vec_sol
5888 -  Y - state vector to be compared to U
5889 
5890    Output Arguments:
5891 .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
5892 .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5893 .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
5894 
5895    Level: developer
5896 
5897 .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5898 @*/
5899 PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
5900 {
5901   PetscErrorCode    ierr;
5902   PetscInt          i,n,N,rstart;
5903   PetscInt          n_loc,na_loc,nr_loc;
5904   PetscReal         n_glb,na_glb,nr_glb;
5905   const PetscScalar *u,*y;
5906   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
5907   PetscReal         tol,tola,tolr;
5908   PetscReal         err_loc[6],err_glb[6];
5909 
5910   PetscFunctionBegin;
5911   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5912   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5913   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
5914   PetscValidType(U,2);
5915   PetscValidType(Y,3);
5916   PetscCheckSameComm(U,2,Y,3);
5917   PetscValidPointer(norm,4);
5918   PetscValidPointer(norma,5);
5919   PetscValidPointer(normr,6);
5920   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5921 
5922   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
5923   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
5924   ierr = VecGetOwnershipRange(U,&rstart,NULL);CHKERRQ(ierr);
5925   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
5926   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
5927   sum  = 0.; n_loc  = 0;
5928   suma = 0.; na_loc = 0;
5929   sumr = 0.; nr_loc = 0;
5930   if (ts->vatol && ts->vrtol) {
5931     const PetscScalar *atol,*rtol;
5932     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5933     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5934     for (i=0; i<n; i++) {
5935       diff = PetscAbsScalar(y[i] - u[i]);
5936       tola = PetscRealPart(atol[i]);
5937       if(tola>0.){
5938         suma  += PetscSqr(diff/tola);
5939         na_loc++;
5940       }
5941       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5942       if(tolr>0.){
5943         sumr  += PetscSqr(diff/tolr);
5944         nr_loc++;
5945       }
5946       tol=tola+tolr;
5947       if(tol>0.){
5948         sum  += PetscSqr(diff/tol);
5949         n_loc++;
5950       }
5951     }
5952     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5953     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5954   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5955     const PetscScalar *atol;
5956     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5957     for (i=0; i<n; i++) {
5958       diff = PetscAbsScalar(y[i] - u[i]);
5959       tola = PetscRealPart(atol[i]);
5960       if(tola>0.){
5961         suma  += PetscSqr(diff/tola);
5962         na_loc++;
5963       }
5964       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5965       if(tolr>0.){
5966         sumr  += PetscSqr(diff/tolr);
5967         nr_loc++;
5968       }
5969       tol=tola+tolr;
5970       if(tol>0.){
5971         sum  += PetscSqr(diff/tol);
5972         n_loc++;
5973       }
5974     }
5975     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5976   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5977     const PetscScalar *rtol;
5978     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5979     for (i=0; i<n; i++) {
5980       diff = PetscAbsScalar(y[i] - u[i]);
5981       tola = ts->atol;
5982       if(tola>0.){
5983         suma  += PetscSqr(diff/tola);
5984         na_loc++;
5985       }
5986       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5987       if(tolr>0.){
5988         sumr  += PetscSqr(diff/tolr);
5989         nr_loc++;
5990       }
5991       tol=tola+tolr;
5992       if(tol>0.){
5993         sum  += PetscSqr(diff/tol);
5994         n_loc++;
5995       }
5996     }
5997     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5998   } else {                      /* scalar atol, scalar rtol */
5999     for (i=0; i<n; i++) {
6000       diff = PetscAbsScalar(y[i] - u[i]);
6001      tola = ts->atol;
6002       if(tola>0.){
6003         suma  += PetscSqr(diff/tola);
6004         na_loc++;
6005       }
6006       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6007       if(tolr>0.){
6008         sumr  += PetscSqr(diff/tolr);
6009         nr_loc++;
6010       }
6011       tol=tola+tolr;
6012       if(tol>0.){
6013         sum  += PetscSqr(diff/tol);
6014         n_loc++;
6015       }
6016     }
6017   }
6018   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
6019   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
6020 
6021   err_loc[0] = sum;
6022   err_loc[1] = suma;
6023   err_loc[2] = sumr;
6024   err_loc[3] = (PetscReal)n_loc;
6025   err_loc[4] = (PetscReal)na_loc;
6026   err_loc[5] = (PetscReal)nr_loc;
6027 
6028   ierr = MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6029 
6030   gsum   = err_glb[0];
6031   gsuma  = err_glb[1];
6032   gsumr  = err_glb[2];
6033   n_glb  = err_glb[3];
6034   na_glb = err_glb[4];
6035   nr_glb = err_glb[5];
6036 
6037   *norm  = 0.;
6038   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6039   *norma = 0.;
6040   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6041   *normr = 0.;
6042   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}
6043 
6044   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6045   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6046   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6047   PetscFunctionReturn(0);
6048 }
6049 
6050 /*@
6051    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
6052 
6053    Collective on TS
6054 
6055    Input Arguments:
6056 +  ts - time stepping context
6057 .  U - state vector, usually ts->vec_sol
6058 -  Y - state vector to be compared to U
6059 
6060    Output Arguments:
6061 .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6062 .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6063 .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
6064 
6065    Level: developer
6066 
6067 .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
6068 @*/
6069 PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6070 {
6071   PetscErrorCode    ierr;
6072   PetscInt          i,n,N,rstart;
6073   const PetscScalar *u,*y;
6074   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
6075   PetscReal         tol,tola,tolr,diff;
6076   PetscReal         err_loc[3],err_glb[3];
6077 
6078   PetscFunctionBegin;
6079   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6080   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
6081   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
6082   PetscValidType(U,2);
6083   PetscValidType(Y,3);
6084   PetscCheckSameComm(U,2,Y,3);
6085   PetscValidPointer(norm,4);
6086   PetscValidPointer(norma,5);
6087   PetscValidPointer(normr,6);
6088   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
6089 
6090   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
6091   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
6092   ierr = VecGetOwnershipRange(U,&rstart,NULL);CHKERRQ(ierr);
6093   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
6094   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
6095 
6096   max=0.;
6097   maxa=0.;
6098   maxr=0.;
6099 
6100   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6101     const PetscScalar *atol,*rtol;
6102     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6103     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6104 
6105     for (i=0; i<n; i++) {
6106       diff = PetscAbsScalar(y[i] - u[i]);
6107       tola = PetscRealPart(atol[i]);
6108       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6109       tol  = tola+tolr;
6110       if(tola>0.){
6111         maxa = PetscMax(maxa,diff / tola);
6112       }
6113       if(tolr>0.){
6114         maxr = PetscMax(maxr,diff / tolr);
6115       }
6116       if(tol>0.){
6117         max = PetscMax(max,diff / tol);
6118       }
6119     }
6120     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6121     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6122   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6123     const PetscScalar *atol;
6124     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6125     for (i=0; i<n; i++) {
6126       diff = PetscAbsScalar(y[i] - u[i]);
6127       tola = PetscRealPart(atol[i]);
6128       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6129       tol  = tola+tolr;
6130       if(tola>0.){
6131         maxa = PetscMax(maxa,diff / tola);
6132       }
6133       if(tolr>0.){
6134         maxr = PetscMax(maxr,diff / tolr);
6135       }
6136       if(tol>0.){
6137         max = PetscMax(max,diff / tol);
6138       }
6139     }
6140     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6141   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6142     const PetscScalar *rtol;
6143     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6144 
6145     for (i=0; i<n; i++) {
6146       diff = PetscAbsScalar(y[i] - u[i]);
6147       tola = ts->atol;
6148       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6149       tol  = tola+tolr;
6150       if(tola>0.){
6151         maxa = PetscMax(maxa,diff / tola);
6152       }
6153       if(tolr>0.){
6154         maxr = PetscMax(maxr,diff / tolr);
6155       }
6156       if(tol>0.){
6157         max = PetscMax(max,diff / tol);
6158       }
6159     }
6160     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6161   } else {                      /* scalar atol, scalar rtol */
6162 
6163     for (i=0; i<n; i++) {
6164       diff = PetscAbsScalar(y[i] - u[i]);
6165       tola = ts->atol;
6166       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6167       tol  = tola+tolr;
6168       if(tola>0.){
6169         maxa = PetscMax(maxa,diff / tola);
6170       }
6171       if(tolr>0.){
6172         maxr = PetscMax(maxr,diff / tolr);
6173       }
6174       if(tol>0.){
6175         max = PetscMax(max,diff / tol);
6176       }
6177     }
6178   }
6179   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
6180   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
6181   err_loc[0] = max;
6182   err_loc[1] = maxa;
6183   err_loc[2] = maxr;
6184   ierr  = MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6185   gmax   = err_glb[0];
6186   gmaxa  = err_glb[1];
6187   gmaxr  = err_glb[2];
6188 
6189   *norm = gmax;
6190   *norma = gmaxa;
6191   *normr = gmaxr;
6192   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6193     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6194     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6195   PetscFunctionReturn(0);
6196 }
6197 
6198 /*@
6199    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
6200 
6201    Collective on TS
6202 
6203    Input Arguments:
6204 +  ts - time stepping context
6205 .  U - state vector, usually ts->vec_sol
6206 .  Y - state vector to be compared to U
6207 -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
6208 
6209    Output Arguments:
6210 .  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6211 .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6212 .  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
6213 
6214    Options Database Keys:
6215 .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
6216 
6217    Level: developer
6218 
6219 .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
6220 @*/
6221 PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6222 {
6223   PetscErrorCode ierr;
6224 
6225   PetscFunctionBegin;
6226   if (wnormtype == NORM_2) {
6227     ierr = TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);CHKERRQ(ierr);
6228   } else if(wnormtype == NORM_INFINITY) {
6229     ierr = TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);CHKERRQ(ierr);
6230   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6231   PetscFunctionReturn(0);
6232 }
6233 
6234 
6235 /*@
6236    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
6237 
6238    Collective on TS
6239 
6240    Input Arguments:
6241 +  ts - time stepping context
6242 .  E - error vector
6243 .  U - state vector, usually ts->vec_sol
6244 -  Y - state vector, previous time step
6245 
6246    Output Arguments:
6247 .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6248 .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6249 .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
6250 
6251    Level: developer
6252 
6253 .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
6254 @*/
6255 PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6256 {
6257   PetscErrorCode    ierr;
6258   PetscInt          i,n,N,rstart;
6259   PetscInt          n_loc,na_loc,nr_loc;
6260   PetscReal         n_glb,na_glb,nr_glb;
6261   const PetscScalar *e,*u,*y;
6262   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
6263   PetscReal         tol,tola,tolr;
6264   PetscReal         err_loc[6],err_glb[6];
6265 
6266   PetscFunctionBegin;
6267   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6268   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
6269   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6270   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
6271   PetscValidType(E,2);
6272   PetscValidType(U,3);
6273   PetscValidType(Y,4);
6274   PetscCheckSameComm(E,2,U,3);
6275   PetscCheckSameComm(U,2,Y,3);
6276   PetscValidPointer(norm,5);
6277   PetscValidPointer(norma,6);
6278   PetscValidPointer(normr,7);
6279 
6280   ierr = VecGetSize(E,&N);CHKERRQ(ierr);
6281   ierr = VecGetLocalSize(E,&n);CHKERRQ(ierr);
6282   ierr = VecGetOwnershipRange(E,&rstart,NULL);CHKERRQ(ierr);
6283   ierr = VecGetArrayRead(E,&e);CHKERRQ(ierr);
6284   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
6285   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
6286   sum  = 0.; n_loc  = 0;
6287   suma = 0.; na_loc = 0;
6288   sumr = 0.; nr_loc = 0;
6289   if (ts->vatol && ts->vrtol) {
6290     const PetscScalar *atol,*rtol;
6291     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6292     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6293     for (i=0; i<n; i++) {
6294       err = PetscAbsScalar(e[i]);
6295       tola = PetscRealPart(atol[i]);
6296       if(tola>0.){
6297         suma  += PetscSqr(err/tola);
6298         na_loc++;
6299       }
6300       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6301       if(tolr>0.){
6302         sumr  += PetscSqr(err/tolr);
6303         nr_loc++;
6304       }
6305       tol=tola+tolr;
6306       if(tol>0.){
6307         sum  += PetscSqr(err/tol);
6308         n_loc++;
6309       }
6310     }
6311     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6312     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6313   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6314     const PetscScalar *atol;
6315     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6316     for (i=0; i<n; i++) {
6317       err = PetscAbsScalar(e[i]);
6318       tola = PetscRealPart(atol[i]);
6319       if(tola>0.){
6320         suma  += PetscSqr(err/tola);
6321         na_loc++;
6322       }
6323       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6324       if(tolr>0.){
6325         sumr  += PetscSqr(err/tolr);
6326         nr_loc++;
6327       }
6328       tol=tola+tolr;
6329       if(tol>0.){
6330         sum  += PetscSqr(err/tol);
6331         n_loc++;
6332       }
6333     }
6334     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6335   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6336     const PetscScalar *rtol;
6337     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6338     for (i=0; i<n; i++) {
6339       err = PetscAbsScalar(e[i]);
6340       tola = ts->atol;
6341       if(tola>0.){
6342         suma  += PetscSqr(err/tola);
6343         na_loc++;
6344       }
6345       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6346       if(tolr>0.){
6347         sumr  += PetscSqr(err/tolr);
6348         nr_loc++;
6349       }
6350       tol=tola+tolr;
6351       if(tol>0.){
6352         sum  += PetscSqr(err/tol);
6353         n_loc++;
6354       }
6355     }
6356     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6357   } else {                      /* scalar atol, scalar rtol */
6358     for (i=0; i<n; i++) {
6359       err = PetscAbsScalar(e[i]);
6360      tola = ts->atol;
6361       if(tola>0.){
6362         suma  += PetscSqr(err/tola);
6363         na_loc++;
6364       }
6365       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6366       if(tolr>0.){
6367         sumr  += PetscSqr(err/tolr);
6368         nr_loc++;
6369       }
6370       tol=tola+tolr;
6371       if(tol>0.){
6372         sum  += PetscSqr(err/tol);
6373         n_loc++;
6374       }
6375     }
6376   }
6377   ierr = VecRestoreArrayRead(E,&e);CHKERRQ(ierr);
6378   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
6379   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
6380 
6381   err_loc[0] = sum;
6382   err_loc[1] = suma;
6383   err_loc[2] = sumr;
6384   err_loc[3] = (PetscReal)n_loc;
6385   err_loc[4] = (PetscReal)na_loc;
6386   err_loc[5] = (PetscReal)nr_loc;
6387 
6388   ierr = MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6389 
6390   gsum   = err_glb[0];
6391   gsuma  = err_glb[1];
6392   gsumr  = err_glb[2];
6393   n_glb  = err_glb[3];
6394   na_glb = err_glb[4];
6395   nr_glb = err_glb[5];
6396 
6397   *norm  = 0.;
6398   if(n_glb>0. ){*norm  = PetscSqrtReal(gsum  / n_glb );}
6399   *norma = 0.;
6400   if(na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
6401   *normr = 0.;
6402   if(nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}
6403 
6404   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6405   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6406   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6407   PetscFunctionReturn(0);
6408 }
6409 
6410 /*@
6411    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
6412    Collective on TS
6413 
6414    Input Arguments:
6415 +  ts - time stepping context
6416 .  E - error vector
6417 .  U - state vector, usually ts->vec_sol
6418 -  Y - state vector, previous time step
6419 
6420    Output Arguments:
6421 .  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
6422 .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
6423 .  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
6424 
6425    Level: developer
6426 
6427 .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
6428 @*/
6429 PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6430 {
6431   PetscErrorCode    ierr;
6432   PetscInt          i,n,N,rstart;
6433   const PetscScalar *e,*u,*y;
6434   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
6435   PetscReal         tol,tola,tolr;
6436   PetscReal         err_loc[3],err_glb[3];
6437 
6438   PetscFunctionBegin;
6439   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6440   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
6441   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6442   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
6443   PetscValidType(E,2);
6444   PetscValidType(U,3);
6445   PetscValidType(Y,4);
6446   PetscCheckSameComm(E,2,U,3);
6447   PetscCheckSameComm(U,2,Y,3);
6448   PetscValidPointer(norm,5);
6449   PetscValidPointer(norma,6);
6450   PetscValidPointer(normr,7);
6451 
6452   ierr = VecGetSize(E,&N);CHKERRQ(ierr);
6453   ierr = VecGetLocalSize(E,&n);CHKERRQ(ierr);
6454   ierr = VecGetOwnershipRange(E,&rstart,NULL);CHKERRQ(ierr);
6455   ierr = VecGetArrayRead(E,&e);CHKERRQ(ierr);
6456   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
6457   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
6458 
6459   max=0.;
6460   maxa=0.;
6461   maxr=0.;
6462 
6463   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
6464     const PetscScalar *atol,*rtol;
6465     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6466     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6467 
6468     for (i=0; i<n; i++) {
6469       err = PetscAbsScalar(e[i]);
6470       tola = PetscRealPart(atol[i]);
6471       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6472       tol  = tola+tolr;
6473       if(tola>0.){
6474         maxa = PetscMax(maxa,err / tola);
6475       }
6476       if(tolr>0.){
6477         maxr = PetscMax(maxr,err / tolr);
6478       }
6479       if(tol>0.){
6480         max = PetscMax(max,err / tol);
6481       }
6482     }
6483     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6484     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6485   } else if (ts->vatol) {       /* vector atol, scalar rtol */
6486     const PetscScalar *atol;
6487     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6488     for (i=0; i<n; i++) {
6489       err = PetscAbsScalar(e[i]);
6490       tola = PetscRealPart(atol[i]);
6491       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6492       tol  = tola+tolr;
6493       if(tola>0.){
6494         maxa = PetscMax(maxa,err / tola);
6495       }
6496       if(tolr>0.){
6497         maxr = PetscMax(maxr,err / tolr);
6498       }
6499       if(tol>0.){
6500         max = PetscMax(max,err / tol);
6501       }
6502     }
6503     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
6504   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
6505     const PetscScalar *rtol;
6506     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6507 
6508     for (i=0; i<n; i++) {
6509       err = PetscAbsScalar(e[i]);
6510       tola = ts->atol;
6511       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6512       tol  = tola+tolr;
6513       if(tola>0.){
6514         maxa = PetscMax(maxa,err / tola);
6515       }
6516       if(tolr>0.){
6517         maxr = PetscMax(maxr,err / tolr);
6518       }
6519       if(tol>0.){
6520         max = PetscMax(max,err / tol);
6521       }
6522     }
6523     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
6524   } else {                      /* scalar atol, scalar rtol */
6525 
6526     for (i=0; i<n; i++) {
6527       err = PetscAbsScalar(e[i]);
6528       tola = ts->atol;
6529       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
6530       tol  = tola+tolr;
6531       if(tola>0.){
6532         maxa = PetscMax(maxa,err / tola);
6533       }
6534       if(tolr>0.){
6535         maxr = PetscMax(maxr,err / tolr);
6536       }
6537       if(tol>0.){
6538         max = PetscMax(max,err / tol);
6539       }
6540     }
6541   }
6542   ierr = VecRestoreArrayRead(E,&e);CHKERRQ(ierr);
6543   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
6544   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
6545   err_loc[0] = max;
6546   err_loc[1] = maxa;
6547   err_loc[2] = maxr;
6548   ierr  = MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6549   gmax   = err_glb[0];
6550   gmaxa  = err_glb[1];
6551   gmaxr  = err_glb[2];
6552 
6553   *norm = gmax;
6554   *norma = gmaxa;
6555   *normr = gmaxr;
6556   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
6557     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
6558     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
6559   PetscFunctionReturn(0);
6560 }
6561 
6562 /*@
6563    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
6564 
6565    Collective on TS
6566 
6567    Input Arguments:
6568 +  ts - time stepping context
6569 .  E - error vector
6570 .  U - state vector, usually ts->vec_sol
6571 .  Y - state vector, previous time step
6572 -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
6573 
6574    Output Arguments:
6575 .  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
6576 .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
6577 .  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
6578 
6579    Options Database Keys:
6580 .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
6581 
6582    Level: developer
6583 
6584 .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
6585 @*/
6586 PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
6587 {
6588   PetscErrorCode ierr;
6589 
6590   PetscFunctionBegin;
6591   if (wnormtype == NORM_2) {
6592     ierr = TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);CHKERRQ(ierr);
6593   } else if(wnormtype == NORM_INFINITY) {
6594     ierr = TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);CHKERRQ(ierr);
6595   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
6596   PetscFunctionReturn(0);
6597 }
6598 
6599 
6600 /*@
6601    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
6602 
6603    Logically Collective on TS
6604 
6605    Input Arguments:
6606 +  ts - time stepping context
6607 -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
6608 
6609    Note:
6610    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
6611 
6612    Level: intermediate
6613 
6614 .seealso: TSGetCFLTime(), TSADAPTCFL
6615 @*/
6616 PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6617 {
6618   PetscFunctionBegin;
6619   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6620   ts->cfltime_local = cfltime;
6621   ts->cfltime       = -1.;
6622   PetscFunctionReturn(0);
6623 }
6624 
6625 /*@
6626    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
6627 
6628    Collective on TS
6629 
6630    Input Arguments:
6631 .  ts - time stepping context
6632 
6633    Output Arguments:
6634 .  cfltime - maximum stable time step for forward Euler
6635 
6636    Level: advanced
6637 
6638 .seealso: TSSetCFLTimeLocal()
6639 @*/
6640 PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6641 {
6642   PetscErrorCode ierr;
6643 
6644   PetscFunctionBegin;
6645   if (ts->cfltime < 0) {
6646     ierr = MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6647   }
6648   *cfltime = ts->cfltime;
6649   PetscFunctionReturn(0);
6650 }
6651 
6652 /*@
6653    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
6654 
6655    Input Parameters:
6656 .  ts   - the TS context.
6657 .  xl   - lower bound.
6658 .  xu   - upper bound.
6659 
6660    Notes:
6661    If this routine is not called then the lower and upper bounds are set to
6662    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
6663 
6664    Level: advanced
6665 
6666 @*/
6667 PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6668 {
6669   PetscErrorCode ierr;
6670   SNES           snes;
6671 
6672   PetscFunctionBegin;
6673   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
6674   ierr = SNESVISetVariableBounds(snes,xl,xu);CHKERRQ(ierr);
6675   PetscFunctionReturn(0);
6676 }
6677 
6678 #if defined(PETSC_HAVE_MATLAB_ENGINE)
6679 #include <mex.h>
6680 
6681 typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
6682 
6683 /*
6684    TSComputeFunction_Matlab - Calls the function that has been set with
6685                          TSSetFunctionMatlab().
6686 
6687    Collective on TS
6688 
6689    Input Parameters:
6690 +  snes - the TS context
6691 -  u - input vector
6692 
6693    Output Parameter:
6694 .  y - function vector, as set by TSSetFunction()
6695 
6696    Notes:
6697    TSComputeFunction() is typically used within nonlinear solvers
6698    implementations, so most users would not generally call this routine
6699    themselves.
6700 
6701    Level: developer
6702 
6703 .keywords: TS, nonlinear, compute, function
6704 
6705 .seealso: TSSetFunction(), TSGetFunction()
6706 */
6707 PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6708 {
6709   PetscErrorCode  ierr;
6710   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6711   int             nlhs  = 1,nrhs = 7;
6712   mxArray         *plhs[1],*prhs[7];
6713   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;
6714 
6715   PetscFunctionBegin;
6716   PetscValidHeaderSpecific(snes,TS_CLASSID,1);
6717   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
6718   PetscValidHeaderSpecific(udot,VEC_CLASSID,4);
6719   PetscValidHeaderSpecific(y,VEC_CLASSID,5);
6720   PetscCheckSameComm(snes,1,u,3);
6721   PetscCheckSameComm(snes,1,y,5);
6722 
6723   ierr = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
6724   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6725   ierr = PetscMemcpy(&lxdot,&udot,sizeof(udot));CHKERRQ(ierr);
6726   ierr = PetscMemcpy(&ly,&y,sizeof(u));CHKERRQ(ierr);
6727 
6728   prhs[0] =  mxCreateDoubleScalar((double)ls);
6729   prhs[1] =  mxCreateDoubleScalar(time);
6730   prhs[2] =  mxCreateDoubleScalar((double)lx);
6731   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6732   prhs[4] =  mxCreateDoubleScalar((double)ly);
6733   prhs[5] =  mxCreateString(sctx->funcname);
6734   prhs[6] =  sctx->ctx;
6735   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");CHKERRQ(ierr);
6736   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6737   mxDestroyArray(prhs[0]);
6738   mxDestroyArray(prhs[1]);
6739   mxDestroyArray(prhs[2]);
6740   mxDestroyArray(prhs[3]);
6741   mxDestroyArray(prhs[4]);
6742   mxDestroyArray(prhs[5]);
6743   mxDestroyArray(plhs[0]);
6744   PetscFunctionReturn(0);
6745 }
6746 
6747 
6748 /*
6749    TSSetFunctionMatlab - Sets the function evaluation routine and function
6750    vector for use by the TS routines in solving ODEs
6751    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
6752 
6753    Logically Collective on TS
6754 
6755    Input Parameters:
6756 +  ts - the TS context
6757 -  func - function evaluation routine
6758 
6759    Calling sequence of func:
6760 $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
6761 
6762    Level: beginner
6763 
6764 .keywords: TS, nonlinear, set, function
6765 
6766 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6767 */
6768 PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6769 {
6770   PetscErrorCode  ierr;
6771   TSMatlabContext *sctx;
6772 
6773   PetscFunctionBegin;
6774   /* currently sctx is memory bleed */
6775   ierr = PetscNew(&sctx);CHKERRQ(ierr);
6776   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6777   /*
6778      This should work, but it doesn't
6779   sctx->ctx = ctx;
6780   mexMakeArrayPersistent(sctx->ctx);
6781   */
6782   sctx->ctx = mxDuplicateArray(ctx);
6783 
6784   ierr = TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);CHKERRQ(ierr);
6785   PetscFunctionReturn(0);
6786 }
6787 
6788 /*
6789    TSComputeJacobian_Matlab - Calls the function that has been set with
6790                          TSSetJacobianMatlab().
6791 
6792    Collective on TS
6793 
6794    Input Parameters:
6795 +  ts - the TS context
6796 .  u - input vector
6797 .  A, B - the matrices
6798 -  ctx - user context
6799 
6800    Level: developer
6801 
6802 .keywords: TS, nonlinear, compute, function
6803 
6804 .seealso: TSSetFunction(), TSGetFunction()
6805 @*/
6806 PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6807 {
6808   PetscErrorCode  ierr;
6809   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6810   int             nlhs  = 2,nrhs = 9;
6811   mxArray         *plhs[2],*prhs[9];
6812   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
6813 
6814   PetscFunctionBegin;
6815   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6816   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
6817 
6818   /* call Matlab function in ctx with arguments u and y */
6819 
6820   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
6821   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6822   ierr = PetscMemcpy(&lxdot,&udot,sizeof(u));CHKERRQ(ierr);
6823   ierr = PetscMemcpy(&lA,A,sizeof(u));CHKERRQ(ierr);
6824   ierr = PetscMemcpy(&lB,B,sizeof(u));CHKERRQ(ierr);
6825 
6826   prhs[0] =  mxCreateDoubleScalar((double)ls);
6827   prhs[1] =  mxCreateDoubleScalar((double)time);
6828   prhs[2] =  mxCreateDoubleScalar((double)lx);
6829   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6830   prhs[4] =  mxCreateDoubleScalar((double)shift);
6831   prhs[5] =  mxCreateDoubleScalar((double)lA);
6832   prhs[6] =  mxCreateDoubleScalar((double)lB);
6833   prhs[7] =  mxCreateString(sctx->funcname);
6834   prhs[8] =  sctx->ctx;
6835   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");CHKERRQ(ierr);
6836   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6837   mxDestroyArray(prhs[0]);
6838   mxDestroyArray(prhs[1]);
6839   mxDestroyArray(prhs[2]);
6840   mxDestroyArray(prhs[3]);
6841   mxDestroyArray(prhs[4]);
6842   mxDestroyArray(prhs[5]);
6843   mxDestroyArray(prhs[6]);
6844   mxDestroyArray(prhs[7]);
6845   mxDestroyArray(plhs[0]);
6846   mxDestroyArray(plhs[1]);
6847   PetscFunctionReturn(0);
6848 }
6849 
6850 
6851 /*
6852    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
6853    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
6854 
6855    Logically Collective on TS
6856 
6857    Input Parameters:
6858 +  ts - the TS context
6859 .  A,B - Jacobian matrices
6860 .  func - function evaluation routine
6861 -  ctx - user context
6862 
6863    Calling sequence of func:
6864 $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
6865 
6866 
6867    Level: developer
6868 
6869 .keywords: TS, nonlinear, set, function
6870 
6871 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6872 */
6873 PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
6874 {
6875   PetscErrorCode  ierr;
6876   TSMatlabContext *sctx;
6877 
6878   PetscFunctionBegin;
6879   /* currently sctx is memory bleed */
6880   ierr = PetscNew(&sctx);CHKERRQ(ierr);
6881   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6882   /*
6883      This should work, but it doesn't
6884   sctx->ctx = ctx;
6885   mexMakeArrayPersistent(sctx->ctx);
6886   */
6887   sctx->ctx = mxDuplicateArray(ctx);
6888 
6889   ierr = TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
6890   PetscFunctionReturn(0);
6891 }
6892 
6893 /*
6894    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
6895 
6896    Collective on TS
6897 
6898 .seealso: TSSetFunction(), TSGetFunction()
6899 @*/
6900 PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
6901 {
6902   PetscErrorCode  ierr;
6903   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6904   int             nlhs  = 1,nrhs = 6;
6905   mxArray         *plhs[1],*prhs[6];
6906   long long int   lx = 0,ls = 0;
6907 
6908   PetscFunctionBegin;
6909   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6910   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
6911 
6912   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
6913   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6914 
6915   prhs[0] =  mxCreateDoubleScalar((double)ls);
6916   prhs[1] =  mxCreateDoubleScalar((double)it);
6917   prhs[2] =  mxCreateDoubleScalar((double)time);
6918   prhs[3] =  mxCreateDoubleScalar((double)lx);
6919   prhs[4] =  mxCreateString(sctx->funcname);
6920   prhs[5] =  sctx->ctx;
6921   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");CHKERRQ(ierr);
6922   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6923   mxDestroyArray(prhs[0]);
6924   mxDestroyArray(prhs[1]);
6925   mxDestroyArray(prhs[2]);
6926   mxDestroyArray(prhs[3]);
6927   mxDestroyArray(prhs[4]);
6928   mxDestroyArray(plhs[0]);
6929   PetscFunctionReturn(0);
6930 }
6931 
6932 
6933 /*
6934    TSMonitorSetMatlab - Sets the monitor function from Matlab
6935 
6936    Level: developer
6937 
6938 .keywords: TS, nonlinear, set, function
6939 
6940 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6941 */
6942 PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
6943 {
6944   PetscErrorCode  ierr;
6945   TSMatlabContext *sctx;
6946 
6947   PetscFunctionBegin;
6948   /* currently sctx is memory bleed */
6949   ierr = PetscNew(&sctx);CHKERRQ(ierr);
6950   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6951   /*
6952      This should work, but it doesn't
6953   sctx->ctx = ctx;
6954   mexMakeArrayPersistent(sctx->ctx);
6955   */
6956   sctx->ctx = mxDuplicateArray(ctx);
6957 
6958   ierr = TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
6959   PetscFunctionReturn(0);
6960 }
6961 #endif
6962 
6963 /*@C
6964    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6965        in a time based line graph
6966 
6967    Collective on TS
6968 
6969    Input Parameters:
6970 +  ts - the TS context
6971 .  step - current time-step
6972 .  ptime - current time
6973 .  u - current solution
6974 -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()
6975 
6976    Options Database:
6977 .   -ts_monitor_lg_solution_variables
6978 
6979    Level: intermediate
6980 
6981    Notes: Each process in a parallel run displays its component solutions in a separate window
6982 
6983 .keywords: TS,  vector, monitor, view
6984 
6985 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6986            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6987            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6988            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6989 @*/
6990 PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6991 {
6992   PetscErrorCode    ierr;
6993   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6994   const PetscScalar *yy;
6995   Vec               v;
6996 
6997   PetscFunctionBegin;
6998   if (step < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
6999   if (!step) {
7000     PetscDrawAxis axis;
7001     PetscInt      dim;
7002     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
7003     ierr = PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");CHKERRQ(ierr);
7004     if (!ctx->names) {
7005       PetscBool flg;
7006       /* user provides names of variables to plot but no names has been set so assume names are integer values */
7007       ierr = PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);CHKERRQ(ierr);
7008       if (flg) {
7009         PetscInt i,n;
7010         char     **names;
7011         ierr = VecGetSize(u,&n);CHKERRQ(ierr);
7012         ierr = PetscMalloc1(n+1,&names);CHKERRQ(ierr);
7013         for (i=0; i<n; i++) {
7014           ierr = PetscMalloc1(5,&names[i]);CHKERRQ(ierr);
7015           ierr = PetscSNPrintf(names[i],5,"%D",i);CHKERRQ(ierr);
7016         }
7017         names[n] = NULL;
7018         ctx->names = names;
7019       }
7020     }
7021     if (ctx->names && !ctx->displaynames) {
7022       char      **displaynames;
7023       PetscBool flg;
7024       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
7025       ierr = PetscMalloc1(dim+1,&displaynames);CHKERRQ(ierr);
7026       ierr = PetscMemzero(displaynames,(dim+1)*sizeof(char*));CHKERRQ(ierr);
7027       ierr = PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);CHKERRQ(ierr);
7028       if (flg) {
7029         ierr = TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);CHKERRQ(ierr);
7030       }
7031       ierr = PetscStrArrayDestroy(&displaynames);CHKERRQ(ierr);
7032     }
7033     if (ctx->displaynames) {
7034       ierr = PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);CHKERRQ(ierr);
7035       ierr = PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);CHKERRQ(ierr);
7036     } else if (ctx->names) {
7037       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
7038       ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
7039       ierr = PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);CHKERRQ(ierr);
7040     } else {
7041       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
7042       ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
7043     }
7044     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
7045   }
7046 
7047   if (!ctx->transform) v = u;
7048   else {ierr = (*ctx->transform)(ctx->transformctx,u,&v);CHKERRQ(ierr);}
7049   ierr = VecGetArrayRead(v,&yy);CHKERRQ(ierr);
7050   if (ctx->displaynames) {
7051     PetscInt i;
7052     for (i=0; i<ctx->ndisplayvariables; i++)
7053       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
7054     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);CHKERRQ(ierr);
7055   } else {
7056 #if defined(PETSC_USE_COMPLEX)
7057     PetscInt  i,n;
7058     PetscReal *yreal;
7059     ierr = VecGetLocalSize(v,&n);CHKERRQ(ierr);
7060     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
7061     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
7062     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
7063     ierr = PetscFree(yreal);CHKERRQ(ierr);
7064 #else
7065     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
7066 #endif
7067   }
7068   ierr = VecRestoreArrayRead(v,&yy);CHKERRQ(ierr);
7069   if (ctx->transform) {ierr = VecDestroy(&v);CHKERRQ(ierr);}
7070 
7071   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
7072     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
7073     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
7074   }
7075   PetscFunctionReturn(0);
7076 }
7077 
7078 
7079 /*@C
7080    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
7081 
7082    Collective on TS
7083 
7084    Input Parameters:
7085 +  ts - the TS context
7086 -  names - the names of the components, final string must be NULL
7087 
7088    Level: intermediate
7089 
7090    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
7091 
7092 .keywords: TS,  vector, monitor, view
7093 
7094 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
7095 @*/
7096 PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
7097 {
7098   PetscErrorCode    ierr;
7099   PetscInt          i;
7100 
7101   PetscFunctionBegin;
7102   for (i=0; i<ts->numbermonitors; i++) {
7103     if (ts->monitor[i] == TSMonitorLGSolution) {
7104       ierr = TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);CHKERRQ(ierr);
7105       break;
7106     }
7107   }
7108   PetscFunctionReturn(0);
7109 }
7110 
7111 /*@C
7112    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
7113 
7114    Collective on TS
7115 
7116    Input Parameters:
7117 +  ts - the TS context
7118 -  names - the names of the components, final string must be NULL
7119 
7120    Level: intermediate
7121 
7122 .keywords: TS,  vector, monitor, view
7123 
7124 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
7125 @*/
7126 PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
7127 {
7128   PetscErrorCode    ierr;
7129 
7130   PetscFunctionBegin;
7131   ierr = PetscStrArrayDestroy(&ctx->names);CHKERRQ(ierr);
7132   ierr = PetscStrArrayallocpy(names,&ctx->names);CHKERRQ(ierr);
7133   PetscFunctionReturn(0);
7134 }
7135 
7136 /*@C
7137    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot
7138 
7139    Collective on TS
7140 
7141    Input Parameter:
7142 .  ts - the TS context
7143 
7144    Output Parameter:
7145 .  names - the names of the components, final string must be NULL
7146 
7147    Level: intermediate
7148 
7149    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
7150 
7151 .keywords: TS,  vector, monitor, view
7152 
7153 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7154 @*/
7155 PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
7156 {
7157   PetscInt       i;
7158 
7159   PetscFunctionBegin;
7160   *names = NULL;
7161   for (i=0; i<ts->numbermonitors; i++) {
7162     if (ts->monitor[i] == TSMonitorLGSolution) {
7163       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
7164       *names = (const char *const *)ctx->names;
7165       break;
7166     }
7167   }
7168   PetscFunctionReturn(0);
7169 }
7170 
7171 /*@C
7172    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor
7173 
7174    Collective on TS
7175 
7176    Input Parameters:
7177 +  ctx - the TSMonitorLG context
7178 .  displaynames - the names of the components, final string must be NULL
7179 
7180    Level: intermediate
7181 
7182 .keywords: TS,  vector, monitor, view
7183 
7184 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
7185 @*/
7186 PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
7187 {
7188   PetscInt          j = 0,k;
7189   PetscErrorCode    ierr;
7190 
7191   PetscFunctionBegin;
7192   if (!ctx->names) PetscFunctionReturn(0);
7193   ierr = PetscStrArrayDestroy(&ctx->displaynames);CHKERRQ(ierr);
7194   ierr = PetscStrArrayallocpy(displaynames,&ctx->displaynames);CHKERRQ(ierr);
7195   while (displaynames[j]) j++;
7196   ctx->ndisplayvariables = j;
7197   ierr = PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);CHKERRQ(ierr);
7198   ierr = PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);CHKERRQ(ierr);
7199   j = 0;
7200   while (displaynames[j]) {
7201     k = 0;
7202     while (ctx->names[k]) {
7203       PetscBool flg;
7204       ierr = PetscStrcmp(displaynames[j],ctx->names[k],&flg);CHKERRQ(ierr);
7205       if (flg) {
7206         ctx->displayvariables[j] = k;
7207         break;
7208       }
7209       k++;
7210     }
7211     j++;
7212   }
7213   PetscFunctionReturn(0);
7214 }
7215 
7216 
7217 /*@C
7218    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor
7219 
7220    Collective on TS
7221 
7222    Input Parameters:
7223 +  ts - the TS context
7224 .  displaynames - the names of the components, final string must be NULL
7225 
7226    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
7227 
7228    Level: intermediate
7229 
7230 .keywords: TS,  vector, monitor, view
7231 
7232 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
7233 @*/
7234 PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
7235 {
7236   PetscInt          i;
7237   PetscErrorCode    ierr;
7238 
7239   PetscFunctionBegin;
7240   for (i=0; i<ts->numbermonitors; i++) {
7241     if (ts->monitor[i] == TSMonitorLGSolution) {
7242       ierr = TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);CHKERRQ(ierr);
7243       break;
7244     }
7245   }
7246   PetscFunctionReturn(0);
7247 }
7248 
7249 /*@C
7250    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed
7251 
7252    Collective on TS
7253 
7254    Input Parameters:
7255 +  ts - the TS context
7256 .  transform - the transform function
7257 .  destroy - function to destroy the optional context
7258 -  ctx - optional context used by transform function
7259 
7260    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
7261 
7262    Level: intermediate
7263 
7264 .keywords: TS,  vector, monitor, view
7265 
7266 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
7267 @*/
7268 PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
7269 {
7270   PetscInt          i;
7271   PetscErrorCode    ierr;
7272 
7273   PetscFunctionBegin;
7274   for (i=0; i<ts->numbermonitors; i++) {
7275     if (ts->monitor[i] == TSMonitorLGSolution) {
7276       ierr = TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);CHKERRQ(ierr);
7277     }
7278   }
7279   PetscFunctionReturn(0);
7280 }
7281 
7282 /*@C
7283    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed
7284 
7285    Collective on TSLGCtx
7286 
7287    Input Parameters:
7288 +  ts - the TS context
7289 .  transform - the transform function
7290 .  destroy - function to destroy the optional context
7291 -  ctx - optional context used by transform function
7292 
7293    Level: intermediate
7294 
7295 .keywords: TS,  vector, monitor, view
7296 
7297 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
7298 @*/
7299 PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
7300 {
7301   PetscFunctionBegin;
7302   ctx->transform    = transform;
7303   ctx->transformdestroy = destroy;
7304   ctx->transformctx = tctx;
7305   PetscFunctionReturn(0);
7306 }
7307 
7308 /*@C
7309    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
7310        in a time based line graph
7311 
7312    Collective on TS
7313 
7314    Input Parameters:
7315 +  ts - the TS context
7316 .  step - current time-step
7317 .  ptime - current time
7318 .  u - current solution
7319 -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()
7320 
7321    Level: intermediate
7322 
7323    Notes: Each process in a parallel run displays its component errors in a separate window
7324 
7325    The user must provide the solution using TSSetSolutionFunction() to use this monitor.
7326 
7327    Options Database Keys:
7328 .  -ts_monitor_lg_error - create a graphical monitor of error history
7329 
7330 .keywords: TS,  vector, monitor, view
7331 
7332 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
7333 @*/
7334 PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
7335 {
7336   PetscErrorCode    ierr;
7337   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
7338   const PetscScalar *yy;
7339   Vec               y;
7340 
7341   PetscFunctionBegin;
7342   if (!step) {
7343     PetscDrawAxis axis;
7344     PetscInt      dim;
7345     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
7346     ierr = PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");CHKERRQ(ierr);
7347     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
7348     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
7349     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
7350   }
7351   ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
7352   ierr = TSComputeSolutionFunction(ts,ptime,y);CHKERRQ(ierr);
7353   ierr = VecAXPY(y,-1.0,u);CHKERRQ(ierr);
7354   ierr = VecGetArrayRead(y,&yy);CHKERRQ(ierr);
7355 #if defined(PETSC_USE_COMPLEX)
7356   {
7357     PetscReal *yreal;
7358     PetscInt  i,n;
7359     ierr = VecGetLocalSize(y,&n);CHKERRQ(ierr);
7360     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
7361     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
7362     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
7363     ierr = PetscFree(yreal);CHKERRQ(ierr);
7364   }
7365 #else
7366   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
7367 #endif
7368   ierr = VecRestoreArrayRead(y,&yy);CHKERRQ(ierr);
7369   ierr = VecDestroy(&y);CHKERRQ(ierr);
7370   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
7371     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
7372     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
7373   }
7374   PetscFunctionReturn(0);
7375 }
7376 
7377 PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7378 {
7379   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7380   PetscReal      x   = ptime,y;
7381   PetscErrorCode ierr;
7382   PetscInt       its;
7383 
7384   PetscFunctionBegin;
7385   if (n < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
7386   if (!n) {
7387     PetscDrawAxis axis;
7388     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
7389     ierr = PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");CHKERRQ(ierr);
7390     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
7391     ctx->snes_its = 0;
7392   }
7393   ierr = TSGetSNESIterations(ts,&its);CHKERRQ(ierr);
7394   y    = its - ctx->snes_its;
7395   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
7396   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7397     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
7398     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
7399   }
7400   ctx->snes_its = its;
7401   PetscFunctionReturn(0);
7402 }
7403 
7404 PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
7405 {
7406   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
7407   PetscReal      x   = ptime,y;
7408   PetscErrorCode ierr;
7409   PetscInt       its;
7410 
7411   PetscFunctionBegin;
7412   if (n < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
7413   if (!n) {
7414     PetscDrawAxis axis;
7415     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
7416     ierr = PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");CHKERRQ(ierr);
7417     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
7418     ctx->ksp_its = 0;
7419   }
7420   ierr = TSGetKSPIterations(ts,&its);CHKERRQ(ierr);
7421   y    = its - ctx->ksp_its;
7422   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
7423   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
7424     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
7425     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
7426   }
7427   ctx->ksp_its = its;
7428   PetscFunctionReturn(0);
7429 }
7430 
7431 /*@
7432    TSComputeLinearStability - computes the linear stability function at a point
7433 
7434    Collective on TS and Vec
7435 
7436    Input Parameters:
7437 +  ts - the TS context
7438 -  xr,xi - real and imaginary part of input arguments
7439 
7440    Output Parameters:
7441 .  yr,yi - real and imaginary part of function value
7442 
7443    Level: developer
7444 
7445 .keywords: TS, compute
7446 
7447 .seealso: TSSetRHSFunction(), TSComputeIFunction()
7448 @*/
7449 PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
7450 {
7451   PetscErrorCode ierr;
7452 
7453   PetscFunctionBegin;
7454   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
7455   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
7456   ierr = (*ts->ops->linearstability)(ts,xr,xi,yr,yi);CHKERRQ(ierr);
7457   PetscFunctionReturn(0);
7458 }
7459 
7460 /* ------------------------------------------------------------------------*/
7461 /*@C
7462    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()
7463 
7464    Collective on TS
7465 
7466    Input Parameters:
7467 .  ts  - the ODE solver object
7468 
7469    Output Parameter:
7470 .  ctx - the context
7471 
7472    Level: intermediate
7473 
7474 .keywords: TS, monitor, line graph, residual, seealso
7475 
7476 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
7477 
7478 @*/
7479 PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
7480 {
7481   PetscErrorCode ierr;
7482 
7483   PetscFunctionBegin;
7484   ierr = PetscNew(ctx);CHKERRQ(ierr);
7485   PetscFunctionReturn(0);
7486 }
7487 
7488 /*@C
7489    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution
7490 
7491    Collective on TS
7492 
7493    Input Parameters:
7494 +  ts - the TS context
7495 .  step - current time-step
7496 .  ptime - current time
7497 .  u  - current solution
7498 -  dctx - the envelope context
7499 
7500    Options Database:
7501 .  -ts_monitor_envelope
7502 
7503    Level: intermediate
7504 
7505    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope
7506 
7507 .keywords: TS,  vector, monitor, view
7508 
7509 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
7510 @*/
7511 PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
7512 {
7513   PetscErrorCode       ierr;
7514   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;
7515 
7516   PetscFunctionBegin;
7517   if (!ctx->max) {
7518     ierr = VecDuplicate(u,&ctx->max);CHKERRQ(ierr);
7519     ierr = VecDuplicate(u,&ctx->min);CHKERRQ(ierr);
7520     ierr = VecCopy(u,ctx->max);CHKERRQ(ierr);
7521     ierr = VecCopy(u,ctx->min);CHKERRQ(ierr);
7522   } else {
7523     ierr = VecPointwiseMax(ctx->max,u,ctx->max);CHKERRQ(ierr);
7524     ierr = VecPointwiseMin(ctx->min,u,ctx->min);CHKERRQ(ierr);
7525   }
7526   PetscFunctionReturn(0);
7527 }
7528 
7529 
7530 /*@C
7531    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution
7532 
7533    Collective on TS
7534 
7535    Input Parameter:
7536 .  ts - the TS context
7537 
7538    Output Parameter:
7539 +  max - the maximum values
7540 -  min - the minimum values
7541 
7542    Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored
7543 
7544    Level: intermediate
7545 
7546 .keywords: TS,  vector, monitor, view
7547 
7548 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
7549 @*/
7550 PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
7551 {
7552   PetscInt i;
7553 
7554   PetscFunctionBegin;
7555   if (max) *max = NULL;
7556   if (min) *min = NULL;
7557   for (i=0; i<ts->numbermonitors; i++) {
7558     if (ts->monitor[i] == TSMonitorEnvelope) {
7559       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
7560       if (max) *max = ctx->max;
7561       if (min) *min = ctx->min;
7562       break;
7563     }
7564   }
7565   PetscFunctionReturn(0);
7566 }
7567 
7568 /*@C
7569    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().
7570 
7571    Collective on TSMonitorEnvelopeCtx
7572 
7573    Input Parameter:
7574 .  ctx - the monitor context
7575 
7576    Level: intermediate
7577 
7578 .keywords: TS, monitor, line graph, destroy
7579 
7580 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7581 @*/
7582 PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7583 {
7584   PetscErrorCode ierr;
7585 
7586   PetscFunctionBegin;
7587   ierr = VecDestroy(&(*ctx)->min);CHKERRQ(ierr);
7588   ierr = VecDestroy(&(*ctx)->max);CHKERRQ(ierr);
7589   ierr = PetscFree(*ctx);CHKERRQ(ierr);
7590   PetscFunctionReturn(0);
7591 }
7592 
7593 /*@
7594    TSRollBack - Rolls back one time step
7595 
7596    Collective on TS
7597 
7598    Input Parameter:
7599 .  ts - the TS context obtained from TSCreate()
7600 
7601    Level: advanced
7602 
7603 .keywords: TS, timestep, rollback
7604 
7605 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7606 @*/
7607 PetscErrorCode  TSRollBack(TS ts)
7608 {
7609   PetscErrorCode ierr;
7610 
7611   PetscFunctionBegin;
7612   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7613   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7614   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7615   ierr = (*ts->ops->rollback)(ts);CHKERRQ(ierr);
7616   ts->time_step = ts->ptime - ts->ptime_prev;
7617   ts->ptime = ts->ptime_prev;
7618   ts->ptime_prev = ts->ptime_prev_rollback;
7619   ts->steps--; ts->total_steps--;
7620   ierr = TSPostEvaluate(ts);CHKERRQ(ierr);
7621   ts->steprollback = PETSC_TRUE;
7622   PetscFunctionReturn(0);
7623 }
7624 
7625 /*@
7626    TSGetStages - Get the number of stages and stage values
7627 
7628    Input Parameter:
7629 .  ts - the TS context obtained from TSCreate()
7630 
7631    Level: advanced
7632 
7633 .keywords: TS, getstages
7634 
7635 .seealso: TSCreate()
7636 @*/
7637 PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7638 {
7639   PetscErrorCode ierr;
7640 
7641   PetscFunctionBegin;
7642   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7643   PetscValidPointer(ns,2);
7644 
7645   if (!ts->ops->getstages) *ns=0;
7646   else {
7647     ierr = (*ts->ops->getstages)(ts,ns,Y);CHKERRQ(ierr);
7648   }
7649   PetscFunctionReturn(0);
7650 }
7651 
7652 /*@C
7653   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
7654 
7655   Collective on SNES
7656 
7657   Input Parameters:
7658 + ts - the TS context
7659 . t - current timestep
7660 . U - state vector
7661 . Udot - time derivative of state vector
7662 . shift - shift to apply, see note below
7663 - ctx - an optional user context
7664 
7665   Output Parameters:
7666 + J - Jacobian matrix (not altered in this routine)
7667 - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
7668 
7669   Level: intermediate
7670 
7671   Notes:
7672   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
7673 
7674   dF/dU + shift*dF/dUdot
7675 
7676   Most users should not need to explicitly call this routine, as it
7677   is used internally within the nonlinear solvers.
7678 
7679   This will first try to get the coloring from the DM.  If the DM type has no coloring
7680   routine, then it will try to get the coloring from the matrix.  This requires that the
7681   matrix have nonzero entries precomputed.
7682 
7683 .keywords: TS, finite differences, Jacobian, coloring, sparse
7684 .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7685 @*/
7686 PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7687 {
7688   SNES           snes;
7689   MatFDColoring  color;
7690   PetscBool      hascolor, matcolor = PETSC_FALSE;
7691   PetscErrorCode ierr;
7692 
7693   PetscFunctionBegin;
7694   ierr = PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);CHKERRQ(ierr);
7695   ierr = PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);CHKERRQ(ierr);
7696   if (!color) {
7697     DM         dm;
7698     ISColoring iscoloring;
7699 
7700     ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
7701     ierr = DMHasColoring(dm, &hascolor);CHKERRQ(ierr);
7702     if (hascolor && !matcolor) {
7703       ierr = DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);CHKERRQ(ierr);
7704       ierr = MatFDColoringCreate(B, iscoloring, &color);CHKERRQ(ierr);
7705       ierr = MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);CHKERRQ(ierr);
7706       ierr = MatFDColoringSetFromOptions(color);CHKERRQ(ierr);
7707       ierr = MatFDColoringSetUp(B, iscoloring, color);CHKERRQ(ierr);
7708       ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr);
7709     } else {
7710       MatColoring mc;
7711 
7712       ierr = MatColoringCreate(B, &mc);CHKERRQ(ierr);
7713       ierr = MatColoringSetDistance(mc, 2);CHKERRQ(ierr);
7714       ierr = MatColoringSetType(mc, MATCOLORINGSL);CHKERRQ(ierr);
7715       ierr = MatColoringSetFromOptions(mc);CHKERRQ(ierr);
7716       ierr = MatColoringApply(mc, &iscoloring);CHKERRQ(ierr);
7717       ierr = MatColoringDestroy(&mc);CHKERRQ(ierr);
7718       ierr = MatFDColoringCreate(B, iscoloring, &color);CHKERRQ(ierr);
7719       ierr = MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);CHKERRQ(ierr);
7720       ierr = MatFDColoringSetFromOptions(color);CHKERRQ(ierr);
7721       ierr = MatFDColoringSetUp(B, iscoloring, color);CHKERRQ(ierr);
7722       ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr);
7723     }
7724     ierr = PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);CHKERRQ(ierr);
7725     ierr = PetscObjectDereference((PetscObject) color);CHKERRQ(ierr);
7726   }
7727   ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);
7728   ierr = MatFDColoringApply(B, color, U, snes);CHKERRQ(ierr);
7729   if (J != B) {
7730     ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
7731     ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
7732   }
7733   PetscFunctionReturn(0);
7734 }
7735 
7736 /*@
7737     TSSetFunctionDomainError - Set the function testing if the current state vector is valid
7738 
7739     Input Parameters:
7740     ts - the TS context
7741     func - function called within TSFunctionDomainError
7742 
7743     Level: intermediate
7744 
7745 .keywords: TS, state, domain
7746 .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7747 @*/
7748 
7749 PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7750 {
7751   PetscFunctionBegin;
7752   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7753   ts->functiondomainerror = func;
7754   PetscFunctionReturn(0);
7755 }
7756 
7757 /*@
7758     TSFunctionDomainError - Check if the current state is valid
7759 
7760     Input Parameters:
7761     ts - the TS context
7762     stagetime - time of the simulation
7763     Y - state vector to check.
7764 
7765     Output Parameter:
7766     accept - Set to PETSC_FALSE if the current state vector is valid.
7767 
7768     Note:
7769     This function should be used to ensure the state is in a valid part of the space.
7770     For example, one can ensure here all values are positive.
7771 
7772     Level: advanced
7773 @*/
7774 PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7775 {
7776   PetscErrorCode ierr;
7777 
7778   PetscFunctionBegin;
7779 
7780   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
7781   *accept = PETSC_TRUE;
7782   if (ts->functiondomainerror) {
7783     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7784   }
7785   PetscFunctionReturn(0);
7786 }
7787 
7788 /*@C
7789   TSClone - This function clones a time step object.
7790 
7791   Collective on MPI_Comm
7792 
7793   Input Parameter:
7794 . tsin    - The input TS
7795 
7796   Output Parameter:
7797 . tsout   - The output TS (cloned)
7798 
7799   Notes:
7800   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly.
7801 
7802   When using TSDestroy() on a clone the user has to first reset the correct TS reference in the embedded SNES object: e.g.: by running SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); ierr = TSSetSNES(ts,snes_dup);
7803 
7804   Level: developer
7805 
7806 .keywords: TS, clone
7807 .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7808 @*/
7809 PetscErrorCode  TSClone(TS tsin, TS *tsout)
7810 {
7811   TS             t;
7812   PetscErrorCode ierr;
7813   SNES           snes_start;
7814   DM             dm;
7815   TSType         type;
7816 
7817   PetscFunctionBegin;
7818   PetscValidPointer(tsin,1);
7819   *tsout = NULL;
7820 
7821   ierr = PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);CHKERRQ(ierr);
7822 
7823   /* General TS description */
7824   t->numbermonitors    = 0;
7825   t->setupcalled       = 0;
7826   t->ksp_its           = 0;
7827   t->snes_its          = 0;
7828   t->nwork             = 0;
7829   t->rhsjacobian.time  = -1e20;
7830   t->rhsjacobian.scale = 1.;
7831   t->ijacobian.shift   = 1.;
7832 
7833   ierr = TSGetSNES(tsin,&snes_start);CHKERRQ(ierr);
7834   ierr = TSSetSNES(t,snes_start);CHKERRQ(ierr);
7835 
7836   ierr = TSGetDM(tsin,&dm);CHKERRQ(ierr);
7837   ierr = TSSetDM(t,dm);CHKERRQ(ierr);
7838 
7839   t->adapt = tsin->adapt;
7840   ierr = PetscObjectReference((PetscObject)t->adapt);CHKERRQ(ierr);
7841 
7842   t->trajectory = tsin->trajectory;
7843   ierr = PetscObjectReference((PetscObject)t->trajectory);CHKERRQ(ierr);
7844 
7845   t->event = tsin->event;
7846   if (t->event) t->event->refct++;
7847 
7848   t->problem_type      = tsin->problem_type;
7849   t->ptime             = tsin->ptime;
7850   t->ptime_prev        = tsin->ptime_prev;
7851   t->time_step         = tsin->time_step;
7852   t->max_time          = tsin->max_time;
7853   t->steps             = tsin->steps;
7854   t->total_steps       = tsin->total_steps;
7855   t->max_steps         = tsin->max_steps;
7856   t->equation_type     = tsin->equation_type;
7857   t->atol              = tsin->atol;
7858   t->rtol              = tsin->rtol;
7859   t->max_snes_failures = tsin->max_snes_failures;
7860   t->max_reject        = tsin->max_reject;
7861   t->errorifstepfailed = tsin->errorifstepfailed;
7862 
7863   ierr = TSGetType(tsin,&type);CHKERRQ(ierr);
7864   ierr = TSSetType(t,type);CHKERRQ(ierr);
7865 
7866   t->vec_sol           = NULL;
7867 
7868   t->cfltime          = tsin->cfltime;
7869   t->cfltime_local    = tsin->cfltime_local;
7870   t->exact_final_time = tsin->exact_final_time;
7871 
7872   ierr = PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));CHKERRQ(ierr);
7873 
7874   if (((PetscObject)tsin)->fortran_func_pointers) {
7875     PetscInt i;
7876     ierr = PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);CHKERRQ(ierr);
7877     for (i=0; i<10; i++) {
7878       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7879     }
7880   }
7881   *tsout = t;
7882   PetscFunctionReturn(0);
7883 }
7884