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