xref: /petsc/src/ts/interface/ts.c (revision 966be33a19c9230d4aa438248a644248d45cc287)
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__ "TSSetI2Function"
1411 /*@C
1412    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1413 
1414    Logically Collective on TS
1415 
1416    Input Parameters:
1417 +  ts  - the TS context obtained from TSCreate()
1418 .  F   - vector to hold the residual (or NULL to have it created internally)
1419 .  fun - the function evaluation routine
1420 -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1421 
1422    Calling sequence of fun:
1423 $  fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1424 
1425 +  t    - time at step/stage being solved
1426 .  U    - state vector
1427 .  U_t  - time derivative of state vector
1428 .  U_tt - second time derivative of state vector
1429 .  F    - function vector
1430 -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1431 
1432    Level: beginner
1433 
1434 .keywords: TS, timestep, set, ODE, DAE, Function
1435 
1436 .seealso: TSSetI2Jacobian()
1437 @*/
1438 PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1439 {
1440   DM             dm;
1441   PetscErrorCode ierr;
1442 
1443   PetscFunctionBegin;
1444   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1445   if (F) PetscValidHeaderSpecific(F,VEC_CLASSID,2);
1446   ierr = TSSetIFunction(ts,F,NULL,NULL);CHKERRQ(ierr);
1447   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1448   ierr = DMTSSetI2Function(dm,fun,ctx);CHKERRQ(ierr);
1449   PetscFunctionReturn(0);
1450 }
1451 
1452 #undef __FUNCT__
1453 #define __FUNCT__ "TSGetI2Function"
1454 /*@C
1455   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1456 
1457   Not Collective
1458 
1459   Input Parameter:
1460 . ts - the TS context
1461 
1462   Output Parameter:
1463 + r - vector to hold residual (or NULL)
1464 . fun - the function to compute residual (or NULL)
1465 - ctx - the function context (or NULL)
1466 
1467   Level: advanced
1468 
1469 .keywords: TS, nonlinear, get, function
1470 
1471 .seealso: TSSetI2Function(), SNESGetFunction()
1472 @*/
1473 PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1474 {
1475   PetscErrorCode ierr;
1476   SNES           snes;
1477   DM             dm;
1478 
1479   PetscFunctionBegin;
1480   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1481   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1482   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1483   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1484   ierr = DMTSGetI2Function(dm,fun,ctx);CHKERRQ(ierr);
1485   PetscFunctionReturn(0);
1486 }
1487 
1488 #undef __FUNCT__
1489 #define __FUNCT__ "TSSetI2Jacobian"
1490 /*@C
1491    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1492         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1493 
1494    Logically Collective on TS
1495 
1496    Input Parameters:
1497 +  ts  - the TS context obtained from TSCreate()
1498 .  J   - Jacobian matrix
1499 .  P   - preconditioning matrix for J (may be same as J)
1500 .  jac - the Jacobian evaluation routine
1501 -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1502 
1503    Calling sequence of jac:
1504 $  jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1505 
1506 +  t    - time at step/stage being solved
1507 .  U    - state vector
1508 .  U_t  - time derivative of state vector
1509 .  U_tt - second time derivative of state vector
1510 .  v    - shift for U_t
1511 .  a    - shift for U_tt
1512 .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1513 .  P    - preconditioning matrix for J, may be same as J
1514 -  ctx  - [optional] user-defined context for matrix evaluation routine
1515 
1516    Notes:
1517    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1518 
1519    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1520    the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
1521    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1522    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1523 
1524    Level: beginner
1525 
1526 .keywords: TS, timestep, set, ODE, DAE, Jacobian
1527 
1528 .seealso: TSSetI2Function()
1529 @*/
1530 PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1531 {
1532   DM             dm;
1533   PetscErrorCode ierr;
1534 
1535   PetscFunctionBegin;
1536   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1537   if (J) PetscValidHeaderSpecific(J,MAT_CLASSID,2);
1538   if (P) PetscValidHeaderSpecific(P,MAT_CLASSID,3);
1539   ierr = TSSetIJacobian(ts,J,P,NULL,NULL);CHKERRQ(ierr);
1540   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1541   ierr = DMTSSetI2Jacobian(dm,jac,ctx);CHKERRQ(ierr);
1542   PetscFunctionReturn(0);
1543 }
1544 
1545 #undef __FUNCT__
1546 #define __FUNCT__ "TSGetI2Jacobian"
1547 /*@C
1548   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1549 
1550   Not Collective, but parallel objects are returned if TS is parallel
1551 
1552   Input Parameter:
1553 . ts  - The TS context obtained from TSCreate()
1554 
1555   Output Parameters:
1556 + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1557 . P - The matrix from which the preconditioner is constructed, often the same as J
1558 . jac - The function to compute the Jacobian matrices
1559 - ctx - User-defined context for Jacobian evaluation routine
1560 
1561   Notes: You can pass in NULL for any return argument you do not need.
1562 
1563   Level: advanced
1564 
1565 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
1566 
1567 .keywords: TS, timestep, get, matrix, Jacobian
1568 @*/
1569 PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1570 {
1571   PetscErrorCode ierr;
1572   SNES           snes;
1573   DM             dm;
1574 
1575   PetscFunctionBegin;
1576   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1577   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
1578   ierr = SNESGetJacobian(snes,J,P,NULL,NULL);CHKERRQ(ierr);
1579   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1580   ierr = DMTSGetI2Jacobian(dm,jac,ctx);CHKERRQ(ierr);
1581   PetscFunctionReturn(0);
1582 }
1583 
1584 #undef __FUNCT__
1585 #define __FUNCT__ "TSComputeI2Function"
1586 /*@
1587   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1588 
1589   Collective on TS and Vec
1590 
1591   Input Parameters:
1592 + ts - the TS context
1593 . t - current time
1594 . U - state vector
1595 . V - time derivative of state vector (U_t)
1596 - A - second time derivative of state vector (U_tt)
1597 
1598   Output Parameter:
1599 . F - the residual vector
1600 
1601   Note:
1602   Most users should not need to explicitly call this routine, as it
1603   is used internally within the nonlinear solvers.
1604 
1605   Level: developer
1606 
1607 .keywords: TS, compute, function, vector
1608 
1609 .seealso: TSSetI2Function()
1610 @*/
1611 PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1612 {
1613   DM             dm;
1614   TSI2Function   I2Function;
1615   void           *ctx;
1616   TSRHSFunction  rhsfunction;
1617   PetscErrorCode ierr;
1618 
1619   PetscFunctionBegin;
1620   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1621   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1622   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1623   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1624   PetscValidHeaderSpecific(F,VEC_CLASSID,6);
1625 
1626   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1627   ierr = DMTSGetI2Function(dm,&I2Function,&ctx);CHKERRQ(ierr);
1628   ierr = DMTSGetRHSFunction(dm,&rhsfunction,NULL);CHKERRQ(ierr);
1629 
1630   if (!I2Function) {
1631     ierr = TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);CHKERRQ(ierr);
1632     PetscFunctionReturn(0);
1633   }
1634 
1635   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);CHKERRQ(ierr);
1636 
1637   PetscStackPush("TS user implicit function");
1638   ierr = I2Function(ts,t,U,V,A,F,ctx);CHKERRQ(ierr);
1639   PetscStackPop;
1640 
1641   if (rhsfunction) {
1642     Vec Frhs;
1643     ierr = TSGetRHSVec_Private(ts,&Frhs);CHKERRQ(ierr);
1644     ierr = TSComputeRHSFunction(ts,t,U,Frhs);CHKERRQ(ierr);
1645     ierr = VecAXPY(F,-1,Frhs);CHKERRQ(ierr);
1646   }
1647 
1648   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);CHKERRQ(ierr);
1649   PetscFunctionReturn(0);
1650 }
1651 
1652 #undef __FUNCT__
1653 #define __FUNCT__ "TSComputeI2Jacobian"
1654 /*@
1655   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1656 
1657   Collective on TS and Vec
1658 
1659   Input Parameters:
1660 + ts - the TS context
1661 . t - current timestep
1662 . U - state vector
1663 . V - time derivative of state vector
1664 . A - second time derivative of state vector
1665 . shiftV - shift to apply, see note below
1666 - shiftA - shift to apply, see note below
1667 
1668   Output Parameters:
1669 + J - Jacobian matrix
1670 - P - optional preconditioning matrix
1671 
1672   Notes:
1673   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1674 
1675   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1676 
1677   Most users should not need to explicitly call this routine, as it
1678   is used internally within the nonlinear solvers.
1679 
1680   Level: developer
1681 
1682 .keywords: TS, compute, Jacobian, matrix
1683 
1684 .seealso:  TSSetI2Jacobian()
1685 @*/
1686 PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1687 {
1688   DM             dm;
1689   TSI2Jacobian   I2Jacobian;
1690   void           *ctx;
1691   TSRHSJacobian  rhsjacobian;
1692   PetscErrorCode ierr;
1693 
1694   PetscFunctionBegin;
1695   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1696   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1697   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1698   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1699   PetscValidHeaderSpecific(J,MAT_CLASSID,8);
1700   PetscValidHeaderSpecific(P,MAT_CLASSID,9);
1701 
1702   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1703   ierr = DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);CHKERRQ(ierr);
1704   ierr = DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);CHKERRQ(ierr);
1705 
1706   if (!I2Jacobian) {
1707     ierr = TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);CHKERRQ(ierr);
1708     PetscFunctionReturn(0);
1709   }
1710 
1711   ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);CHKERRQ(ierr);
1712 
1713   PetscStackPush("TS user implicit Jacobian");
1714   ierr = I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);CHKERRQ(ierr);
1715   PetscStackPop;
1716 
1717   if (rhsjacobian) {
1718     Mat Jrhs,Prhs; MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
1719     ierr = TSGetRHSMats_Private(ts,&Jrhs,&Prhs);CHKERRQ(ierr);
1720     ierr = TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);CHKERRQ(ierr);
1721     ierr = MatAXPY(J,-1,Jrhs,axpy);CHKERRQ(ierr);
1722     if (P != J) {ierr = MatAXPY(P,-1,Prhs,axpy);CHKERRQ(ierr);}
1723   }
1724 
1725   ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);CHKERRQ(ierr);
1726   PetscFunctionReturn(0);
1727 }
1728 
1729 #undef __FUNCT__
1730 #define __FUNCT__ "TS2SetSolution"
1731 /*@
1732    TS2SetSolution - Sets the initial solution and time derivative vectors
1733    for use by the TS routines handling second order equations.
1734 
1735    Logically Collective on TS and Vec
1736 
1737    Input Parameters:
1738 +  ts - the TS context obtained from TSCreate()
1739 .  u - the solution vector
1740 -  v - the time derivative vector
1741 
1742    Level: beginner
1743 
1744 .keywords: TS, timestep, set, solution, initial conditions
1745 @*/
1746 PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1747 {
1748   PetscErrorCode ierr;
1749 
1750   PetscFunctionBegin;
1751   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1752   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
1753   PetscValidHeaderSpecific(v,VEC_CLASSID,3);
1754   ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
1755   ierr = PetscObjectReference((PetscObject)v);CHKERRQ(ierr);
1756   ierr = VecDestroy(&ts->vec_dot);CHKERRQ(ierr);
1757   ts->vec_dot = v;
1758   PetscFunctionReturn(0);
1759 }
1760 
1761 #undef __FUNCT__
1762 #define __FUNCT__ "TS2GetSolution"
1763 /*@
1764    TS2GetSolution - Returns the solution and time derivative at the present timestep
1765    for second order equations. It is valid to call this routine inside the function
1766    that you are evaluating in order to move to the new timestep. This vector not
1767    changed until the solution at the next timestep has been calculated.
1768 
1769    Not Collective, but Vec returned is parallel if TS is parallel
1770 
1771    Input Parameter:
1772 .  ts - the TS context obtained from TSCreate()
1773 
1774    Output Parameter:
1775 +  u - the vector containing the solution
1776 -  v - the vector containing the time derivative
1777 
1778    Level: intermediate
1779 
1780 .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()
1781 
1782 .keywords: TS, timestep, get, solution
1783 @*/
1784 PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1785 {
1786   PetscFunctionBegin;
1787   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1788   if (u) PetscValidPointer(u,2);
1789   if (v) PetscValidPointer(v,3);
1790   if (u) *u = ts->vec_sol;
1791   if (v) *v = ts->vec_dot;
1792   PetscFunctionReturn(0);
1793 }
1794 
1795 #undef __FUNCT__
1796 #define __FUNCT__ "TSLoad"
1797 /*@C
1798   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
1799 
1800   Collective on PetscViewer
1801 
1802   Input Parameters:
1803 + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1804            some related function before a call to TSLoad().
1805 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1806 
1807    Level: intermediate
1808 
1809   Notes:
1810    The type is determined by the data in the file, any type set into the TS before this call is ignored.
1811 
1812   Notes for advanced users:
1813   Most users should not need to know the details of the binary storage
1814   format, since TSLoad() and TSView() completely hide these details.
1815   But for anyone who's interested, the standard binary matrix storage
1816   format is
1817 .vb
1818      has not yet been determined
1819 .ve
1820 
1821 .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1822 @*/
1823 PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1824 {
1825   PetscErrorCode ierr;
1826   PetscBool      isbinary;
1827   PetscInt       classid;
1828   char           type[256];
1829   DMTS           sdm;
1830   DM             dm;
1831 
1832   PetscFunctionBegin;
1833   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1834   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1835   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1836   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1837 
1838   ierr = PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);CHKERRQ(ierr);
1839   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1840   ierr = PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);CHKERRQ(ierr);
1841   ierr = TSSetType(ts, type);CHKERRQ(ierr);
1842   if (ts->ops->load) {
1843     ierr = (*ts->ops->load)(ts,viewer);CHKERRQ(ierr);
1844   }
1845   ierr = DMCreate(PetscObjectComm((PetscObject)ts),&dm);CHKERRQ(ierr);
1846   ierr = DMLoad(dm,viewer);CHKERRQ(ierr);
1847   ierr = TSSetDM(ts,dm);CHKERRQ(ierr);
1848   ierr = DMCreateGlobalVector(ts->dm,&ts->vec_sol);CHKERRQ(ierr);
1849   ierr = VecLoad(ts->vec_sol,viewer);CHKERRQ(ierr);
1850   ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1851   ierr = DMTSLoad(sdm,viewer);CHKERRQ(ierr);
1852   PetscFunctionReturn(0);
1853 }
1854 
1855 #include <petscdraw.h>
1856 #if defined(PETSC_HAVE_SAWS)
1857 #include <petscviewersaws.h>
1858 #endif
1859 #undef __FUNCT__
1860 #define __FUNCT__ "TSView"
1861 /*@C
1862     TSView - Prints the TS data structure.
1863 
1864     Collective on TS
1865 
1866     Input Parameters:
1867 +   ts - the TS context obtained from TSCreate()
1868 -   viewer - visualization context
1869 
1870     Options Database Key:
1871 .   -ts_view - calls TSView() at end of TSStep()
1872 
1873     Notes:
1874     The available visualization contexts include
1875 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1876 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1877          output where only the first processor opens
1878          the file.  All other processors send their
1879          data to the first processor to print.
1880 
1881     The user can open an alternative visualization context with
1882     PetscViewerASCIIOpen() - output to a specified file.
1883 
1884     Level: beginner
1885 
1886 .keywords: TS, timestep, view
1887 
1888 .seealso: PetscViewerASCIIOpen()
1889 @*/
1890 PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1891 {
1892   PetscErrorCode ierr;
1893   TSType         type;
1894   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1895   DMTS           sdm;
1896 #if defined(PETSC_HAVE_SAWS)
1897   PetscBool      issaws;
1898 #endif
1899 
1900   PetscFunctionBegin;
1901   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1902   if (!viewer) {
1903     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);CHKERRQ(ierr);
1904   }
1905   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1906   PetscCheckSameComm(ts,1,viewer,2);
1907 
1908   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1909   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
1910   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1911   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1912 #if defined(PETSC_HAVE_SAWS)
1913   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);CHKERRQ(ierr);
1914 #endif
1915   if (iascii) {
1916     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);CHKERRQ(ierr);
1917     ierr = PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);CHKERRQ(ierr);
1918     ierr = PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);CHKERRQ(ierr);
1919     if (ts->problem_type == TS_NONLINEAR) {
1920       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);CHKERRQ(ierr);
1921       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);CHKERRQ(ierr);
1922     }
1923     ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);CHKERRQ(ierr);
1924     ierr = PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);CHKERRQ(ierr);
1925     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1926     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1927     if (ts->ops->view) {
1928       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1929       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1930       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1931     }
1932   } else if (isstring) {
1933     ierr = TSGetType(ts,&type);CHKERRQ(ierr);
1934     ierr = PetscViewerStringSPrintf(viewer," %-7.7s",type);CHKERRQ(ierr);
1935   } else if (isbinary) {
1936     PetscInt    classid = TS_FILE_CLASSID;
1937     MPI_Comm    comm;
1938     PetscMPIInt rank;
1939     char        type[256];
1940 
1941     ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
1942     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
1943     if (!rank) {
1944       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
1945       ierr = PetscStrncpy(type,((PetscObject)ts)->type_name,256);CHKERRQ(ierr);
1946       ierr = PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
1947     }
1948     if (ts->ops->view) {
1949       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1950     }
1951     ierr = DMView(ts->dm,viewer);CHKERRQ(ierr);
1952     ierr = VecView(ts->vec_sol,viewer);CHKERRQ(ierr);
1953     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1954     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1955   } else if (isdraw) {
1956     PetscDraw draw;
1957     char      str[36];
1958     PetscReal x,y,bottom,h;
1959 
1960     ierr   = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
1961     ierr   = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
1962     ierr   = PetscStrcpy(str,"TS: ");CHKERRQ(ierr);
1963     ierr   = PetscStrcat(str,((PetscObject)ts)->type_name);CHKERRQ(ierr);
1964     ierr   = PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
1965     bottom = y - h;
1966     ierr   = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
1967     if (ts->ops->view) {
1968       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1969     }
1970     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
1971 #if defined(PETSC_HAVE_SAWS)
1972   } else if (issaws) {
1973     PetscMPIInt rank;
1974     const char  *name;
1975 
1976     ierr = PetscObjectGetName((PetscObject)ts,&name);CHKERRQ(ierr);
1977     ierr = MPI_Comm_rank(PETSC_COMM_WORLD,&rank);CHKERRQ(ierr);
1978     if (!((PetscObject)ts)->amsmem && !rank) {
1979       char       dir[1024];
1980 
1981       ierr = PetscObjectViewSAWs((PetscObject)ts,viewer);CHKERRQ(ierr);
1982       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);CHKERRQ(ierr);
1983       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1984       ierr = PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);CHKERRQ(ierr);
1985       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1986     }
1987     if (ts->ops->view) {
1988       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1989     }
1990 #endif
1991   }
1992 
1993   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1994   ierr = PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);CHKERRQ(ierr);
1995   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1996   PetscFunctionReturn(0);
1997 }
1998 
1999 
2000 #undef __FUNCT__
2001 #define __FUNCT__ "TSSetApplicationContext"
2002 /*@
2003    TSSetApplicationContext - Sets an optional user-defined context for
2004    the timesteppers.
2005 
2006    Logically Collective on TS
2007 
2008    Input Parameters:
2009 +  ts - the TS context obtained from TSCreate()
2010 -  usrP - optional user context
2011 
2012    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2013     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2014 
2015    Level: intermediate
2016 
2017 .keywords: TS, timestep, set, application, context
2018 
2019 .seealso: TSGetApplicationContext()
2020 @*/
2021 PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2022 {
2023   PetscFunctionBegin;
2024   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2025   ts->user = usrP;
2026   PetscFunctionReturn(0);
2027 }
2028 
2029 #undef __FUNCT__
2030 #define __FUNCT__ "TSGetApplicationContext"
2031 /*@
2032     TSGetApplicationContext - Gets the user-defined context for the
2033     timestepper.
2034 
2035     Not Collective
2036 
2037     Input Parameter:
2038 .   ts - the TS context obtained from TSCreate()
2039 
2040     Output Parameter:
2041 .   usrP - user context
2042 
2043    Fortran Notes: To use this from Fortran you must write a Fortran interface definition for this
2044     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2045 
2046     Level: intermediate
2047 
2048 .keywords: TS, timestep, get, application, context
2049 
2050 .seealso: TSSetApplicationContext()
2051 @*/
2052 PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2053 {
2054   PetscFunctionBegin;
2055   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2056   *(void**)usrP = ts->user;
2057   PetscFunctionReturn(0);
2058 }
2059 
2060 #undef __FUNCT__
2061 #define __FUNCT__ "TSGetTimeStepNumber"
2062 /*@
2063    TSGetTimeStepNumber - Gets the number of time steps completed.
2064 
2065    Not Collective
2066 
2067    Input Parameter:
2068 .  ts - the TS context obtained from TSCreate()
2069 
2070    Output Parameter:
2071 .  iter - number of steps completed so far
2072 
2073    Level: intermediate
2074 
2075 .keywords: TS, timestep, get, iteration, number
2076 .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
2077 @*/
2078 PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
2079 {
2080   PetscFunctionBegin;
2081   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2082   PetscValidIntPointer(iter,2);
2083   *iter = ts->steps;
2084   PetscFunctionReturn(0);
2085 }
2086 
2087 #undef __FUNCT__
2088 #define __FUNCT__ "TSSetInitialTimeStep"
2089 /*@
2090    TSSetInitialTimeStep - Sets the initial timestep to be used,
2091    as well as the initial time.
2092 
2093    Logically Collective on TS
2094 
2095    Input Parameters:
2096 +  ts - the TS context obtained from TSCreate()
2097 .  initial_time - the initial time
2098 -  time_step - the size of the timestep
2099 
2100    Level: intermediate
2101 
2102 .seealso: TSSetTimeStep(), TSGetTimeStep()
2103 
2104 .keywords: TS, set, initial, timestep
2105 @*/
2106 PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2107 {
2108   PetscErrorCode ierr;
2109 
2110   PetscFunctionBegin;
2111   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2112   ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
2113   ierr = TSSetTime(ts,initial_time);CHKERRQ(ierr);
2114   PetscFunctionReturn(0);
2115 }
2116 
2117 #undef __FUNCT__
2118 #define __FUNCT__ "TSSetTimeStep"
2119 /*@
2120    TSSetTimeStep - Allows one to reset the timestep at any time,
2121    useful for simple pseudo-timestepping codes.
2122 
2123    Logically Collective on TS
2124 
2125    Input Parameters:
2126 +  ts - the TS context obtained from TSCreate()
2127 -  time_step - the size of the timestep
2128 
2129    Level: intermediate
2130 
2131 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2132 
2133 .keywords: TS, set, timestep
2134 @*/
2135 PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2136 {
2137   PetscFunctionBegin;
2138   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2139   PetscValidLogicalCollectiveReal(ts,time_step,2);
2140   ts->time_step = time_step;
2141   PetscFunctionReturn(0);
2142 }
2143 
2144 #undef __FUNCT__
2145 #define __FUNCT__ "TSSetExactFinalTime"
2146 /*@
2147    TSSetExactFinalTime - Determines whether to adapt the final time step to
2148      match the exact final time, interpolate solution to the exact final time,
2149      or just return at the final time TS computed.
2150 
2151   Logically Collective on TS
2152 
2153    Input Parameter:
2154 +   ts - the time-step context
2155 -   eftopt - exact final time option
2156 
2157 $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2158 $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2159 $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2160 
2161    Options Database:
2162 .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2163 
2164    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2165     then the final time you selected.
2166 
2167    Level: beginner
2168 
2169 .seealso: TSExactFinalTimeOption
2170 @*/
2171 PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2172 {
2173   PetscFunctionBegin;
2174   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2175   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
2176   ts->exact_final_time = eftopt;
2177   PetscFunctionReturn(0);
2178 }
2179 
2180 #undef __FUNCT__
2181 #define __FUNCT__ "TSGetTimeStep"
2182 /*@
2183    TSGetTimeStep - Gets the current timestep size.
2184 
2185    Not Collective
2186 
2187    Input Parameter:
2188 .  ts - the TS context obtained from TSCreate()
2189 
2190    Output Parameter:
2191 .  dt - the current timestep size
2192 
2193    Level: intermediate
2194 
2195 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2196 
2197 .keywords: TS, get, timestep
2198 @*/
2199 PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2200 {
2201   PetscFunctionBegin;
2202   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2203   PetscValidRealPointer(dt,2);
2204   *dt = ts->time_step;
2205   PetscFunctionReturn(0);
2206 }
2207 
2208 #undef __FUNCT__
2209 #define __FUNCT__ "TSGetSolution"
2210 /*@
2211    TSGetSolution - Returns the solution at the present timestep. It
2212    is valid to call this routine inside the function that you are evaluating
2213    in order to move to the new timestep. This vector not changed until
2214    the solution at the next timestep has been calculated.
2215 
2216    Not Collective, but Vec returned is parallel if TS is parallel
2217 
2218    Input Parameter:
2219 .  ts - the TS context obtained from TSCreate()
2220 
2221    Output Parameter:
2222 .  v - the vector containing the solution
2223 
2224    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
2225    final time. It returns the solution at the next timestep.
2226 
2227    Level: intermediate
2228 
2229 .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime()
2230 
2231 .keywords: TS, timestep, get, solution
2232 @*/
2233 PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2234 {
2235   PetscFunctionBegin;
2236   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2237   PetscValidPointer(v,2);
2238   *v = ts->vec_sol;
2239   PetscFunctionReturn(0);
2240 }
2241 
2242 #undef __FUNCT__
2243 #define __FUNCT__ "TSGetCostGradients"
2244 /*@
2245    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()
2246 
2247    Not Collective, but Vec returned is parallel if TS is parallel
2248 
2249    Input Parameter:
2250 .  ts - the TS context obtained from TSCreate()
2251 
2252    Output Parameter:
2253 +  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
2254 -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters
2255 
2256    Level: intermediate
2257 
2258 .seealso: TSGetTimeStep()
2259 
2260 .keywords: TS, timestep, get, sensitivity
2261 @*/
2262 PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
2263 {
2264   PetscFunctionBegin;
2265   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2266   if (numcost) *numcost = ts->numcost;
2267   if (lambda)  *lambda  = ts->vecs_sensi;
2268   if (mu)      *mu      = ts->vecs_sensip;
2269   PetscFunctionReturn(0);
2270 }
2271 
2272 /* ----- Routines to initialize and destroy a timestepper ---- */
2273 #undef __FUNCT__
2274 #define __FUNCT__ "TSSetProblemType"
2275 /*@
2276   TSSetProblemType - Sets the type of problem to be solved.
2277 
2278   Not collective
2279 
2280   Input Parameters:
2281 + ts   - The TS
2282 - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2283 .vb
2284          U_t - A U = 0      (linear)
2285          U_t - A(t) U = 0   (linear)
2286          F(t,U,U_t) = 0     (nonlinear)
2287 .ve
2288 
2289    Level: beginner
2290 
2291 .keywords: TS, problem type
2292 .seealso: TSSetUp(), TSProblemType, TS
2293 @*/
2294 PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2295 {
2296   PetscErrorCode ierr;
2297 
2298   PetscFunctionBegin;
2299   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2300   ts->problem_type = type;
2301   if (type == TS_LINEAR) {
2302     SNES snes;
2303     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2304     ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);
2305   }
2306   PetscFunctionReturn(0);
2307 }
2308 
2309 #undef __FUNCT__
2310 #define __FUNCT__ "TSGetProblemType"
2311 /*@C
2312   TSGetProblemType - Gets the type of problem to be solved.
2313 
2314   Not collective
2315 
2316   Input Parameter:
2317 . ts   - The TS
2318 
2319   Output Parameter:
2320 . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2321 .vb
2322          M U_t = A U
2323          M(t) U_t = A(t) U
2324          F(t,U,U_t)
2325 .ve
2326 
2327    Level: beginner
2328 
2329 .keywords: TS, problem type
2330 .seealso: TSSetUp(), TSProblemType, TS
2331 @*/
2332 PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2333 {
2334   PetscFunctionBegin;
2335   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2336   PetscValidIntPointer(type,2);
2337   *type = ts->problem_type;
2338   PetscFunctionReturn(0);
2339 }
2340 
2341 #undef __FUNCT__
2342 #define __FUNCT__ "TSSetUp"
2343 /*@
2344    TSSetUp - Sets up the internal data structures for the later use
2345    of a timestepper.
2346 
2347    Collective on TS
2348 
2349    Input Parameter:
2350 .  ts - the TS context obtained from TSCreate()
2351 
2352    Notes:
2353    For basic use of the TS solvers the user need not explicitly call
2354    TSSetUp(), since these actions will automatically occur during
2355    the call to TSStep().  However, if one wishes to control this
2356    phase separately, TSSetUp() should be called after TSCreate()
2357    and optional routines of the form TSSetXXX(), but before TSStep().
2358 
2359    Level: advanced
2360 
2361 .keywords: TS, timestep, setup
2362 
2363 .seealso: TSCreate(), TSStep(), TSDestroy()
2364 @*/
2365 PetscErrorCode  TSSetUp(TS ts)
2366 {
2367   PetscErrorCode ierr;
2368   DM             dm;
2369   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2370   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2371   TSIFunction    ifun;
2372   TSIJacobian    ijac;
2373   TSI2Jacobian   i2jac;
2374   TSRHSJacobian  rhsjac;
2375 
2376   PetscFunctionBegin;
2377   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2378   if (ts->setupcalled) PetscFunctionReturn(0);
2379 
2380   ts->total_steps = 0;
2381   if (!((PetscObject)ts)->type_name) {
2382     ierr = TSGetIFunction(ts,NULL,&ifun,NULL);CHKERRQ(ierr);
2383     ierr = TSSetType(ts,ifun ? TSBEULER : TSEULER);CHKERRQ(ierr);
2384   }
2385 
2386   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
2387 
2388   if (ts->rhsjacobian.reuse) {
2389     Mat Amat,Pmat;
2390     SNES snes;
2391     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2392     ierr = SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);CHKERRQ(ierr);
2393     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2394      * have displaced the RHS matrix */
2395     if (Amat == ts->Arhs) {
2396       ierr = MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);CHKERRQ(ierr);
2397       ierr = SNESSetJacobian(snes,Amat,NULL,NULL,NULL);CHKERRQ(ierr);
2398       ierr = MatDestroy(&Amat);CHKERRQ(ierr);
2399     }
2400     if (Pmat == ts->Brhs) {
2401       ierr = MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);CHKERRQ(ierr);
2402       ierr = SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);CHKERRQ(ierr);
2403       ierr = MatDestroy(&Pmat);CHKERRQ(ierr);
2404     }
2405   }
2406   if (ts->ops->setup) {
2407     ierr = (*ts->ops->setup)(ts);CHKERRQ(ierr);
2408   }
2409 
2410   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
2411      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
2412    */
2413   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2414   ierr = DMSNESGetFunction(dm,&func,NULL);CHKERRQ(ierr);
2415   if (!func) {
2416     ierr = DMSNESSetFunction(dm,SNESTSFormFunction,ts);CHKERRQ(ierr);
2417   }
2418   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
2419      Otherwise, the SNES will use coloring internally to form the Jacobian.
2420    */
2421   ierr = DMSNESGetJacobian(dm,&jac,NULL);CHKERRQ(ierr);
2422   ierr = DMTSGetIJacobian(dm,&ijac,NULL);CHKERRQ(ierr);
2423   ierr = DMTSGetI2Jacobian(dm,&i2jac,NULL);CHKERRQ(ierr);
2424   ierr = DMTSGetRHSJacobian(dm,&rhsjac,NULL);CHKERRQ(ierr);
2425   if (!jac && (ijac || i2jac || rhsjac)) {
2426     ierr = DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2427   }
2428   ts->setupcalled = PETSC_TRUE;
2429   PetscFunctionReturn(0);
2430 }
2431 
2432 #undef __FUNCT__
2433 #define __FUNCT__ "TSAdjointSetUp"
2434 /*@
2435    TSAdjointSetUp - Sets up the internal data structures for the later use
2436    of an adjoint solver
2437 
2438    Collective on TS
2439 
2440    Input Parameter:
2441 .  ts - the TS context obtained from TSCreate()
2442 
2443    Level: advanced
2444 
2445 .keywords: TS, timestep, setup
2446 
2447 .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
2448 @*/
2449 PetscErrorCode  TSAdjointSetUp(TS ts)
2450 {
2451   PetscErrorCode ierr;
2452 
2453   PetscFunctionBegin;
2454   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2455   if (ts->adjointsetupcalled) PetscFunctionReturn(0);
2456   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");
2457 
2458   if (ts->vec_costintegral) { /* if there is integral in the cost function*/
2459     ierr = VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);CHKERRQ(ierr);
2460     if (ts->vecs_sensip){
2461       ierr = VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);CHKERRQ(ierr);
2462     }
2463   }
2464 
2465   if (ts->ops->adjointsetup) {
2466     ierr = (*ts->ops->adjointsetup)(ts);CHKERRQ(ierr);
2467   }
2468   ts->adjointsetupcalled = PETSC_TRUE;
2469   PetscFunctionReturn(0);
2470 }
2471 
2472 #undef __FUNCT__
2473 #define __FUNCT__ "TSReset"
2474 /*@
2475    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2476 
2477    Collective on TS
2478 
2479    Input Parameter:
2480 .  ts - the TS context obtained from TSCreate()
2481 
2482    Level: beginner
2483 
2484 .keywords: TS, timestep, reset
2485 
2486 .seealso: TSCreate(), TSSetup(), TSDestroy()
2487 @*/
2488 PetscErrorCode  TSReset(TS ts)
2489 {
2490   PetscErrorCode ierr;
2491 
2492   PetscFunctionBegin;
2493   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2494 
2495   if (ts->ops->reset) {
2496     ierr = (*ts->ops->reset)(ts);CHKERRQ(ierr);
2497   }
2498   if (ts->snes) {ierr = SNESReset(ts->snes);CHKERRQ(ierr);}
2499   if (ts->adapt) {ierr = TSAdaptReset(ts->adapt);CHKERRQ(ierr);}
2500 
2501   ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
2502   ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
2503   ierr = VecDestroy(&ts->Frhs);CHKERRQ(ierr);
2504   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2505   ierr = VecDestroy(&ts->vec_dot);CHKERRQ(ierr);
2506   ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
2507   ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
2508   ierr = VecDestroyVecs(ts->nwork,&ts->work);CHKERRQ(ierr);
2509 
2510  if (ts->vec_costintegral) {
2511     ierr = VecDestroyVecs(ts->numcost,&ts->vecs_drdy);CHKERRQ(ierr);
2512     if (ts->vecs_drdp){
2513       ierr = VecDestroyVecs(ts->numcost,&ts->vecs_drdp);CHKERRQ(ierr);
2514     }
2515   }
2516   ts->vecs_sensi  = NULL;
2517   ts->vecs_sensip = NULL;
2518   ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
2519   ierr = VecDestroy(&ts->vec_costintegral);CHKERRQ(ierr);
2520   ierr = VecDestroy(&ts->vec_costintegrand);CHKERRQ(ierr);
2521   ts->setupcalled = PETSC_FALSE;
2522   PetscFunctionReturn(0);
2523 }
2524 
2525 #undef __FUNCT__
2526 #define __FUNCT__ "TSDestroy"
2527 /*@
2528    TSDestroy - Destroys the timestepper context that was created
2529    with TSCreate().
2530 
2531    Collective on TS
2532 
2533    Input Parameter:
2534 .  ts - the TS context obtained from TSCreate()
2535 
2536    Level: beginner
2537 
2538 .keywords: TS, timestepper, destroy
2539 
2540 .seealso: TSCreate(), TSSetUp(), TSSolve()
2541 @*/
2542 PetscErrorCode  TSDestroy(TS *ts)
2543 {
2544   PetscErrorCode ierr;
2545 
2546   PetscFunctionBegin;
2547   if (!*ts) PetscFunctionReturn(0);
2548   PetscValidHeaderSpecific((*ts),TS_CLASSID,1);
2549   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; PetscFunctionReturn(0);}
2550 
2551   ierr = TSReset((*ts));CHKERRQ(ierr);
2552 
2553   /* if memory was published with SAWs then destroy it */
2554   ierr = PetscObjectSAWsViewOff((PetscObject)*ts);CHKERRQ(ierr);
2555   if ((*ts)->ops->destroy) {ierr = (*(*ts)->ops->destroy)((*ts));CHKERRQ(ierr);}
2556 
2557   ierr = TSTrajectoryDestroy(&(*ts)->trajectory);CHKERRQ(ierr);
2558 
2559   ierr = TSAdaptDestroy(&(*ts)->adapt);CHKERRQ(ierr);
2560   ierr = TSEventDestroy(&(*ts)->event);CHKERRQ(ierr);
2561 
2562   ierr = SNESDestroy(&(*ts)->snes);CHKERRQ(ierr);
2563   ierr = DMDestroy(&(*ts)->dm);CHKERRQ(ierr);
2564   ierr = TSMonitorCancel((*ts));CHKERRQ(ierr);
2565   ierr = TSAdjointMonitorCancel((*ts));CHKERRQ(ierr);
2566 
2567   ierr = PetscHeaderDestroy(ts);CHKERRQ(ierr);
2568   PetscFunctionReturn(0);
2569 }
2570 
2571 #undef __FUNCT__
2572 #define __FUNCT__ "TSGetSNES"
2573 /*@
2574    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2575    a TS (timestepper) context. Valid only for nonlinear problems.
2576 
2577    Not Collective, but SNES is parallel if TS is parallel
2578 
2579    Input Parameter:
2580 .  ts - the TS context obtained from TSCreate()
2581 
2582    Output Parameter:
2583 .  snes - the nonlinear solver context
2584 
2585    Notes:
2586    The user can then directly manipulate the SNES context to set various
2587    options, etc.  Likewise, the user can then extract and manipulate the
2588    KSP, KSP, and PC contexts as well.
2589 
2590    TSGetSNES() does not work for integrators that do not use SNES; in
2591    this case TSGetSNES() returns NULL in snes.
2592 
2593    Level: beginner
2594 
2595 .keywords: timestep, get, SNES
2596 @*/
2597 PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2598 {
2599   PetscErrorCode ierr;
2600 
2601   PetscFunctionBegin;
2602   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2603   PetscValidPointer(snes,2);
2604   if (!ts->snes) {
2605     ierr = SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);CHKERRQ(ierr);
2606     ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2607     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);CHKERRQ(ierr);
2608     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);CHKERRQ(ierr);
2609     if (ts->dm) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
2610     if (ts->problem_type == TS_LINEAR) {
2611       ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);
2612     }
2613   }
2614   *snes = ts->snes;
2615   PetscFunctionReturn(0);
2616 }
2617 
2618 #undef __FUNCT__
2619 #define __FUNCT__ "TSSetSNES"
2620 /*@
2621    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2622 
2623    Collective
2624 
2625    Input Parameter:
2626 +  ts - the TS context obtained from TSCreate()
2627 -  snes - the nonlinear solver context
2628 
2629    Notes:
2630    Most users should have the TS created by calling TSGetSNES()
2631 
2632    Level: developer
2633 
2634 .keywords: timestep, set, SNES
2635 @*/
2636 PetscErrorCode TSSetSNES(TS ts,SNES snes)
2637 {
2638   PetscErrorCode ierr;
2639   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2640 
2641   PetscFunctionBegin;
2642   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2643   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
2644   ierr = PetscObjectReference((PetscObject)snes);CHKERRQ(ierr);
2645   ierr = SNESDestroy(&ts->snes);CHKERRQ(ierr);
2646 
2647   ts->snes = snes;
2648 
2649   ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
2650   ierr = SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);CHKERRQ(ierr);
2651   if (func == SNESTSFormJacobian) {
2652     ierr = SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);CHKERRQ(ierr);
2653   }
2654   PetscFunctionReturn(0);
2655 }
2656 
2657 #undef __FUNCT__
2658 #define __FUNCT__ "TSGetKSP"
2659 /*@
2660    TSGetKSP - Returns the KSP (linear solver) associated with
2661    a TS (timestepper) context.
2662 
2663    Not Collective, but KSP is parallel if TS is parallel
2664 
2665    Input Parameter:
2666 .  ts - the TS context obtained from TSCreate()
2667 
2668    Output Parameter:
2669 .  ksp - the nonlinear solver context
2670 
2671    Notes:
2672    The user can then directly manipulate the KSP context to set various
2673    options, etc.  Likewise, the user can then extract and manipulate the
2674    KSP and PC contexts as well.
2675 
2676    TSGetKSP() does not work for integrators that do not use KSP;
2677    in this case TSGetKSP() returns NULL in ksp.
2678 
2679    Level: beginner
2680 
2681 .keywords: timestep, get, KSP
2682 @*/
2683 PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2684 {
2685   PetscErrorCode ierr;
2686   SNES           snes;
2687 
2688   PetscFunctionBegin;
2689   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2690   PetscValidPointer(ksp,2);
2691   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2692   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2693   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2694   ierr = SNESGetKSP(snes,ksp);CHKERRQ(ierr);
2695   PetscFunctionReturn(0);
2696 }
2697 
2698 /* ----------- Routines to set solver parameters ---------- */
2699 
2700 #undef __FUNCT__
2701 #define __FUNCT__ "TSGetDuration"
2702 /*@
2703    TSGetDuration - Gets the maximum number of timesteps to use and
2704    maximum time for iteration.
2705 
2706    Not Collective
2707 
2708    Input Parameters:
2709 +  ts       - the TS context obtained from TSCreate()
2710 .  maxsteps - maximum number of iterations to use, or NULL
2711 -  maxtime  - final time to iterate to, or NULL
2712 
2713    Level: intermediate
2714 
2715 .keywords: TS, timestep, get, maximum, iterations, time
2716 @*/
2717 PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2718 {
2719   PetscFunctionBegin;
2720   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2721   if (maxsteps) {
2722     PetscValidIntPointer(maxsteps,2);
2723     *maxsteps = ts->max_steps;
2724   }
2725   if (maxtime) {
2726     PetscValidScalarPointer(maxtime,3);
2727     *maxtime = ts->max_time;
2728   }
2729   PetscFunctionReturn(0);
2730 }
2731 
2732 #undef __FUNCT__
2733 #define __FUNCT__ "TSSetDuration"
2734 /*@
2735    TSSetDuration - Sets the maximum number of timesteps to use and
2736    maximum time for iteration.
2737 
2738    Logically Collective on TS
2739 
2740    Input Parameters:
2741 +  ts - the TS context obtained from TSCreate()
2742 .  maxsteps - maximum number of iterations to use
2743 -  maxtime - final time to iterate to
2744 
2745    Options Database Keys:
2746 .  -ts_max_steps <maxsteps> - Sets maxsteps
2747 .  -ts_final_time <maxtime> - Sets maxtime
2748 
2749    Notes:
2750    The default maximum number of iterations is 5000. Default time is 5.0
2751 
2752    Level: intermediate
2753 
2754 .keywords: TS, timestep, set, maximum, iterations
2755 
2756 .seealso: TSSetExactFinalTime()
2757 @*/
2758 PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2759 {
2760   PetscFunctionBegin;
2761   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2762   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
2763   PetscValidLogicalCollectiveReal(ts,maxtime,2);
2764   if (maxsteps >= 0) ts->max_steps = maxsteps;
2765   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2766   PetscFunctionReturn(0);
2767 }
2768 
2769 #undef __FUNCT__
2770 #define __FUNCT__ "TSSetSolution"
2771 /*@
2772    TSSetSolution - Sets the initial solution vector
2773    for use by the TS routines.
2774 
2775    Logically Collective on TS and Vec
2776 
2777    Input Parameters:
2778 +  ts - the TS context obtained from TSCreate()
2779 -  u - the solution vector
2780 
2781    Level: beginner
2782 
2783 .keywords: TS, timestep, set, solution, initial conditions
2784 @*/
2785 PetscErrorCode  TSSetSolution(TS ts,Vec u)
2786 {
2787   PetscErrorCode ierr;
2788   DM             dm;
2789 
2790   PetscFunctionBegin;
2791   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2792   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2793   ierr = PetscObjectReference((PetscObject)u);CHKERRQ(ierr);
2794   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2795   ts->vec_sol = u;
2796 
2797   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2798   ierr = DMShellSetGlobalVector(dm,u);CHKERRQ(ierr);
2799   PetscFunctionReturn(0);
2800 }
2801 
2802 #undef __FUNCT__
2803 #define __FUNCT__ "TSAdjointSetSteps"
2804 /*@
2805    TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time
2806 
2807    Logically Collective on TS
2808 
2809    Input Parameters:
2810 +  ts - the TS context obtained from TSCreate()
2811 .  steps - number of steps to use
2812 
2813    Level: intermediate
2814 
2815    Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2816           so as to integrate back to less than the original timestep
2817 
2818 .keywords: TS, timestep, set, maximum, iterations
2819 
2820 .seealso: TSSetExactFinalTime()
2821 @*/
2822 PetscErrorCode  TSAdjointSetSteps(TS ts,PetscInt steps)
2823 {
2824   PetscFunctionBegin;
2825   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2826   PetscValidLogicalCollectiveInt(ts,steps,2);
2827   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2828   if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2829   ts->adjoint_max_steps = steps;
2830   PetscFunctionReturn(0);
2831 }
2832 
2833 #undef __FUNCT__
2834 #define __FUNCT__ "TSSetCostGradients"
2835 /*@
2836    TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters
2837       for use by the TSAdjoint routines.
2838 
2839    Logically Collective on TS and Vec
2840 
2841    Input Parameters:
2842 +  ts - the TS context obtained from TSCreate()
2843 .  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
2844 -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters
2845 
2846    Level: beginner
2847 
2848    Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime  mu_i = df/dp|finaltime
2849 
2850 .keywords: TS, timestep, set, sensitivity, initial conditions
2851 @*/
2852 PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2853 {
2854   PetscFunctionBegin;
2855   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2856   PetscValidPointer(lambda,2);
2857   ts->vecs_sensi  = lambda;
2858   ts->vecs_sensip = mu;
2859   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");
2860   ts->numcost  = numcost;
2861   PetscFunctionReturn(0);
2862 }
2863 
2864 #undef __FUNCT__
2865 #define __FUNCT__ "TSAdjointSetRHSJacobian"
2866 /*@C
2867   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.
2868 
2869   Logically Collective on TS
2870 
2871   Input Parameters:
2872 + ts   - The TS context obtained from TSCreate()
2873 - func - The function
2874 
2875   Calling sequence of func:
2876 $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
2877 +   t - current timestep
2878 .   y - input vector (current ODE solution)
2879 .   A - output matrix
2880 -   ctx - [optional] user-defined function context
2881 
2882   Level: intermediate
2883 
2884   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
2885 
2886 .keywords: TS, sensitivity
2887 .seealso:
2888 @*/
2889 PetscErrorCode  TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2890 {
2891   PetscErrorCode ierr;
2892 
2893   PetscFunctionBegin;
2894   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2895   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
2896 
2897   ts->rhsjacobianp    = func;
2898   ts->rhsjacobianpctx = ctx;
2899   if(Amat) {
2900     ierr = PetscObjectReference((PetscObject)Amat);CHKERRQ(ierr);
2901     ierr = MatDestroy(&ts->Jacp);CHKERRQ(ierr);
2902     ts->Jacp = Amat;
2903   }
2904   PetscFunctionReturn(0);
2905 }
2906 
2907 #undef __FUNCT__
2908 #define __FUNCT__ "TSAdjointComputeRHSJacobian"
2909 /*@C
2910   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.
2911 
2912   Collective on TS
2913 
2914   Input Parameters:
2915 . ts   - The TS context obtained from TSCreate()
2916 
2917   Level: developer
2918 
2919 .keywords: TS, sensitivity
2920 .seealso: TSAdjointSetRHSJacobian()
2921 @*/
2922 PetscErrorCode  TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
2923 {
2924   PetscErrorCode ierr;
2925 
2926   PetscFunctionBegin;
2927   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2928   PetscValidHeaderSpecific(X,VEC_CLASSID,3);
2929   PetscValidPointer(Amat,4);
2930 
2931   PetscStackPush("TS user JacobianP function for sensitivity analysis");
2932   ierr = (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx); CHKERRQ(ierr);
2933   PetscStackPop;
2934   PetscFunctionReturn(0);
2935 }
2936 
2937 #undef __FUNCT__
2938 #define __FUNCT__ "TSSetCostIntegrand"
2939 /*@C
2940     TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions
2941 
2942     Logically Collective on TS
2943 
2944     Input Parameters:
2945 +   ts - the TS context obtained from TSCreate()
2946 .   numcost - number of gradients to be computed, this is the number of cost functions
2947 .   rf - routine for evaluating the integrand function
2948 .   drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
2949 .   drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
2950 .   fwd - flag indicating whether to evaluate cost integral in the forward run or the adjoint run
2951 -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)
2952 
2953     Calling sequence of rf:
2954 $     rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);
2955 
2956 +   t - current timestep
2957 .   y - input vector
2958 .   f - function result; one vector entry for each cost function
2959 -   ctx - [optional] user-defined function context
2960 
2961    Calling sequence of drdyf:
2962 $    PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);
2963 
2964    Calling sequence of drdpf:
2965 $    PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);
2966 
2967     Level: intermediate
2968 
2969     Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions
2970 
2971 .keywords: TS, sensitivity analysis, timestep, set, quadrature, function
2972 
2973 .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
2974 @*/
2975 PetscErrorCode  TSSetCostIntegrand(TS ts,PetscInt numcost,PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
2976                                                           PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
2977                                                           PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),
2978                                                           PetscBool fwd,void *ctx)
2979 {
2980   PetscErrorCode ierr;
2981 
2982   PetscFunctionBegin;
2983   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2984   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()");
2985   if (!ts->numcost) ts->numcost=numcost;
2986 
2987   ts->costintegralfwd  = fwd; /* Evaluate the cost integral in forward run if fwd is true */
2988   ierr                 = VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);CHKERRQ(ierr);
2989   ierr                 = VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);CHKERRQ(ierr);
2990   ts->costintegrand    = rf;
2991   ts->costintegrandctx = ctx;
2992   ts->drdyfunction     = drdyf;
2993   ts->drdpfunction     = drdpf;
2994   PetscFunctionReturn(0);
2995 }
2996 
2997 #undef __FUNCT__
2998 #define __FUNCT__ "TSGetCostIntegral"
2999 /*@
3000    TSGetCostIntegral - Returns the values of the integral term in the cost functions.
3001    It is valid to call the routine after a backward run.
3002 
3003    Not Collective
3004 
3005    Input Parameter:
3006 .  ts - the TS context obtained from TSCreate()
3007 
3008    Output Parameter:
3009 .  v - the vector containing the integrals for each cost function
3010 
3011    Level: intermediate
3012 
3013 .seealso: TSSetCostIntegrand()
3014 
3015 .keywords: TS, sensitivity analysis
3016 @*/
3017 PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
3018 {
3019   PetscFunctionBegin;
3020   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3021   PetscValidPointer(v,2);
3022   *v = ts->vec_costintegral;
3023   PetscFunctionReturn(0);
3024 }
3025 
3026 #undef __FUNCT__
3027 #define __FUNCT__ "TSAdjointComputeCostIntegrand"
3028 /*@
3029    TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.
3030 
3031    Input Parameters:
3032 +  ts - the TS context
3033 .  t - current time
3034 -  y - state vector, i.e. current solution
3035 
3036    Output Parameter:
3037 .  q - vector of size numcost to hold the outputs
3038 
3039    Note:
3040    Most users should not need to explicitly call this routine, as it
3041    is used internally within the sensitivity analysis context.
3042 
3043    Level: developer
3044 
3045 .keywords: TS, compute
3046 
3047 .seealso: TSSetCostIntegrand()
3048 @*/
3049 PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
3050 {
3051   PetscErrorCode ierr;
3052 
3053   PetscFunctionBegin;
3054   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3055   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3056   PetscValidHeaderSpecific(q,VEC_CLASSID,4);
3057 
3058   ierr = PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);CHKERRQ(ierr);
3059   if (ts->costintegrand) {
3060     PetscStackPush("TS user integrand in the cost function");
3061     ierr = (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);CHKERRQ(ierr);
3062     PetscStackPop;
3063   } else {
3064     ierr = VecZeroEntries(q);CHKERRQ(ierr);
3065   }
3066 
3067   ierr = PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);CHKERRQ(ierr);
3068   PetscFunctionReturn(0);
3069 }
3070 
3071 #undef __FUNCT__
3072 #define __FUNCT__ "TSAdjointComputeDRDYFunction"
3073 /*@
3074   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.
3075 
3076   Collective on TS
3077 
3078   Input Parameters:
3079 . ts   - The TS context obtained from TSCreate()
3080 
3081   Notes:
3082   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
3083   so most users would not generally call this routine themselves.
3084 
3085   Level: developer
3086 
3087 .keywords: TS, sensitivity
3088 .seealso: TSAdjointComputeDRDYFunction()
3089 @*/
3090 PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
3091 {
3092   PetscErrorCode ierr;
3093 
3094   PetscFunctionBegin;
3095   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3096   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3097 
3098   PetscStackPush("TS user DRDY function for sensitivity analysis");
3099   ierr = (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx); CHKERRQ(ierr);
3100   PetscStackPop;
3101   PetscFunctionReturn(0);
3102 }
3103 
3104 #undef __FUNCT__
3105 #define __FUNCT__ "TSAdjointComputeDRDPFunction"
3106 /*@
3107   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.
3108 
3109   Collective on TS
3110 
3111   Input Parameters:
3112 . ts   - The TS context obtained from TSCreate()
3113 
3114   Notes:
3115   TSDRDPFunction() is typically used for sensitivity implementation,
3116   so most users would not generally call this routine themselves.
3117 
3118   Level: developer
3119 
3120 .keywords: TS, sensitivity
3121 .seealso: TSAdjointSetDRDPFunction()
3122 @*/
3123 PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
3124 {
3125   PetscErrorCode ierr;
3126 
3127   PetscFunctionBegin;
3128   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3129   PetscValidHeaderSpecific(y,VEC_CLASSID,3);
3130 
3131   PetscStackPush("TS user DRDP function for sensitivity analysis");
3132   ierr = (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx); CHKERRQ(ierr);
3133   PetscStackPop;
3134   PetscFunctionReturn(0);
3135 }
3136 
3137 #undef __FUNCT__
3138 #define __FUNCT__ "TSSetPreStep"
3139 /*@C
3140   TSSetPreStep - Sets the general-purpose function
3141   called once at the beginning of each time step.
3142 
3143   Logically Collective on TS
3144 
3145   Input Parameters:
3146 + ts   - The TS context obtained from TSCreate()
3147 - func - The function
3148 
3149   Calling sequence of func:
3150 . func (TS ts);
3151 
3152   Level: intermediate
3153 
3154   Note:
3155   If a step is rejected, TSStep() will call this routine again before each attempt.
3156   The last completed time step number can be queried using TSGetTimeStepNumber(), the
3157   size of the step being attempted can be obtained using TSGetTimeStep().
3158 
3159 .keywords: TS, timestep
3160 .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
3161 @*/
3162 PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3163 {
3164   PetscFunctionBegin;
3165   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3166   ts->prestep = func;
3167   PetscFunctionReturn(0);
3168 }
3169 
3170 #undef __FUNCT__
3171 #define __FUNCT__ "TSPreStep"
3172 /*@
3173   TSPreStep - Runs the user-defined pre-step function.
3174 
3175   Collective on TS
3176 
3177   Input Parameters:
3178 . ts   - The TS context obtained from TSCreate()
3179 
3180   Notes:
3181   TSPreStep() is typically used within time stepping implementations,
3182   so most users would not generally call this routine themselves.
3183 
3184   Level: developer
3185 
3186 .keywords: TS, timestep
3187 .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
3188 @*/
3189 PetscErrorCode  TSPreStep(TS ts)
3190 {
3191   PetscErrorCode ierr;
3192 
3193   PetscFunctionBegin;
3194   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3195   if (ts->prestep) {
3196     PetscStackCallStandard((*ts->prestep),(ts));
3197   }
3198   PetscFunctionReturn(0);
3199 }
3200 
3201 #undef __FUNCT__
3202 #define __FUNCT__ "TSSetPreStage"
3203 /*@C
3204   TSSetPreStage - Sets the general-purpose function
3205   called once at the beginning of each stage.
3206 
3207   Logically Collective on TS
3208 
3209   Input Parameters:
3210 + ts   - The TS context obtained from TSCreate()
3211 - func - The function
3212 
3213   Calling sequence of func:
3214 . PetscErrorCode func(TS ts, PetscReal stagetime);
3215 
3216   Level: intermediate
3217 
3218   Note:
3219   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3220   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3221   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3222 
3223 .keywords: TS, timestep
3224 .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3225 @*/
3226 PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3227 {
3228   PetscFunctionBegin;
3229   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3230   ts->prestage = func;
3231   PetscFunctionReturn(0);
3232 }
3233 
3234 #undef __FUNCT__
3235 #define __FUNCT__ "TSSetPostStage"
3236 /*@C
3237   TSSetPostStage - Sets the general-purpose function
3238   called once at the end of each stage.
3239 
3240   Logically Collective on TS
3241 
3242   Input Parameters:
3243 + ts   - The TS context obtained from TSCreate()
3244 - func - The function
3245 
3246   Calling sequence of func:
3247 . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
3248 
3249   Level: intermediate
3250 
3251   Note:
3252   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3253   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
3254   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3255 
3256 .keywords: TS, timestep
3257 .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
3258 @*/
3259 PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
3260 {
3261   PetscFunctionBegin;
3262   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3263   ts->poststage = func;
3264   PetscFunctionReturn(0);
3265 }
3266 
3267 #undef __FUNCT__
3268 #define __FUNCT__ "TSPreStage"
3269 /*@
3270   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3271 
3272   Collective on TS
3273 
3274   Input Parameters:
3275 . ts          - The TS context obtained from TSCreate()
3276   stagetime   - The absolute time of the current stage
3277 
3278   Notes:
3279   TSPreStage() is typically used within time stepping implementations,
3280   most users would not generally call this routine themselves.
3281 
3282   Level: developer
3283 
3284 .keywords: TS, timestep
3285 .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3286 @*/
3287 PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3288 {
3289   PetscErrorCode ierr;
3290 
3291   PetscFunctionBegin;
3292   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3293   if (ts->prestage) {
3294     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
3295   }
3296   PetscFunctionReturn(0);
3297 }
3298 
3299 #undef __FUNCT__
3300 #define __FUNCT__ "TSPostStage"
3301 /*@
3302   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
3303 
3304   Collective on TS
3305 
3306   Input Parameters:
3307 . ts          - The TS context obtained from TSCreate()
3308   stagetime   - The absolute time of the current stage
3309   stageindex  - Stage number
3310   Y           - Array of vectors (of size = total number
3311                 of stages) with the stage solutions
3312 
3313   Notes:
3314   TSPostStage() is typically used within time stepping implementations,
3315   most users would not generally call this routine themselves.
3316 
3317   Level: developer
3318 
3319 .keywords: TS, timestep
3320 .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
3321 @*/
3322 PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3323 {
3324   PetscErrorCode ierr;
3325 
3326   PetscFunctionBegin;
3327   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3328   if (ts->poststage) {
3329     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
3330   }
3331   PetscFunctionReturn(0);
3332 }
3333 
3334 #undef __FUNCT__
3335 #define __FUNCT__ "TSSetPostStep"
3336 /*@C
3337   TSSetPostStep - Sets the general-purpose function
3338   called once at the end of each time step.
3339 
3340   Logically Collective on TS
3341 
3342   Input Parameters:
3343 + ts   - The TS context obtained from TSCreate()
3344 - func - The function
3345 
3346   Calling sequence of func:
3347 $ func (TS ts);
3348 
3349   Level: intermediate
3350 
3351 .keywords: TS, timestep
3352 .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
3353 @*/
3354 PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3355 {
3356   PetscFunctionBegin;
3357   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3358   ts->poststep = func;
3359   PetscFunctionReturn(0);
3360 }
3361 
3362 #undef __FUNCT__
3363 #define __FUNCT__ "TSPostStep"
3364 /*@
3365   TSPostStep - Runs the user-defined post-step function.
3366 
3367   Collective on TS
3368 
3369   Input Parameters:
3370 . ts   - The TS context obtained from TSCreate()
3371 
3372   Notes:
3373   TSPostStep() is typically used within time stepping implementations,
3374   so most users would not generally call this routine themselves.
3375 
3376   Level: developer
3377 
3378 .keywords: TS, timestep
3379 @*/
3380 PetscErrorCode  TSPostStep(TS ts)
3381 {
3382   PetscErrorCode ierr;
3383 
3384   PetscFunctionBegin;
3385   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3386   if (ts->poststep) {
3387     PetscStackCallStandard((*ts->poststep),(ts));
3388   }
3389   PetscFunctionReturn(0);
3390 }
3391 
3392 /* ------------ Routines to set performance monitoring options ----------- */
3393 
3394 #undef __FUNCT__
3395 #define __FUNCT__ "TSMonitorSet"
3396 /*@C
3397    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
3398    timestep to display the iteration's  progress.
3399 
3400    Logically Collective on TS
3401 
3402    Input Parameters:
3403 +  ts - the TS context obtained from TSCreate()
3404 .  monitor - monitoring routine
3405 .  mctx - [optional] user-defined context for private data for the
3406              monitor routine (use NULL if no context is desired)
3407 -  monitordestroy - [optional] routine that frees monitor context
3408           (may be NULL)
3409 
3410    Calling sequence of monitor:
3411 $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
3412 
3413 +    ts - the TS context
3414 .    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)
3415 .    time - current time
3416 .    u - current iterate
3417 -    mctx - [optional] monitoring context
3418 
3419    Notes:
3420    This routine adds an additional monitor to the list of monitors that
3421    already has been loaded.
3422 
3423    Fortran notes: Only a single monitor function can be set for each TS object
3424 
3425    Level: intermediate
3426 
3427 .keywords: TS, timestep, set, monitor
3428 
3429 .seealso: TSMonitorDefault(), TSMonitorCancel()
3430 @*/
3431 PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
3432 {
3433   PetscFunctionBegin;
3434   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3435   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
3436   ts->monitor[ts->numbermonitors]          = monitor;
3437   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
3438   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
3439   PetscFunctionReturn(0);
3440 }
3441 
3442 #undef __FUNCT__
3443 #define __FUNCT__ "TSMonitorCancel"
3444 /*@C
3445    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
3446 
3447    Logically Collective on TS
3448 
3449    Input Parameters:
3450 .  ts - the TS context obtained from TSCreate()
3451 
3452    Notes:
3453    There is no way to remove a single, specific monitor.
3454 
3455    Level: intermediate
3456 
3457 .keywords: TS, timestep, set, monitor
3458 
3459 .seealso: TSMonitorDefault(), TSMonitorSet()
3460 @*/
3461 PetscErrorCode  TSMonitorCancel(TS ts)
3462 {
3463   PetscErrorCode ierr;
3464   PetscInt       i;
3465 
3466   PetscFunctionBegin;
3467   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3468   for (i=0; i<ts->numbermonitors; i++) {
3469     if (ts->monitordestroy[i]) {
3470       ierr = (*ts->monitordestroy[i])(&ts->monitorcontext[i]);CHKERRQ(ierr);
3471     }
3472   }
3473   ts->numbermonitors = 0;
3474   PetscFunctionReturn(0);
3475 }
3476 
3477 #undef __FUNCT__
3478 #define __FUNCT__ "TSMonitorDefault"
3479 /*@C
3480    TSMonitorDefault - The Default monitor, prints the timestep and time for each step
3481 
3482    Level: intermediate
3483 
3484 .keywords: TS, set, monitor
3485 
3486 .seealso:  TSMonitorSet()
3487 @*/
3488 PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
3489 {
3490   PetscErrorCode ierr;
3491   PetscViewer    viewer =  vf->viewer;
3492   PetscBool      iascii,ibinary;
3493 
3494   PetscFunctionBegin;
3495   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
3496   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
3497   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);CHKERRQ(ierr);
3498   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
3499   if (iascii) {
3500     ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3501     if (step == -1){ /* this indicates it is an interpolated solution */
3502       ierr = PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);CHKERRQ(ierr);
3503     } else {
3504       ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");CHKERRQ(ierr);
3505     }
3506     ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3507   } else if (ibinary) {
3508     PetscMPIInt rank;
3509     ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);CHKERRQ(ierr);
3510     if (!rank) {
3511       ierr = PetscRealView(1,&ptime,viewer);CHKERRQ(ierr);
3512     } else {
3513       ierr = PetscRealView(0,&ptime,viewer);CHKERRQ(ierr);
3514     }
3515   }
3516   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
3517   PetscFunctionReturn(0);
3518 }
3519 
3520 #undef __FUNCT__
3521 #define __FUNCT__ "TSAdjointMonitorSet"
3522 /*@C
3523    TSAdjointMonitorSet - Sets an ADDITIONAL function that is to be used at every
3524    timestep to display the iteration's  progress.
3525 
3526    Logically Collective on TS
3527 
3528    Input Parameters:
3529 +  ts - the TS context obtained from TSCreate()
3530 .  adjointmonitor - monitoring routine
3531 .  adjointmctx - [optional] user-defined context for private data for the
3532              monitor routine (use NULL if no context is desired)
3533 -  adjointmonitordestroy - [optional] routine that frees monitor context
3534           (may be NULL)
3535 
3536    Calling sequence of monitor:
3537 $    int adjointmonitor(TS ts,PetscInt steps,PetscReal time,Vec u,PetscInt numcost,Vec *lambda, Vec *mu,void *adjointmctx)
3538 
3539 +    ts - the TS context
3540 .    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
3541                                been interpolated to)
3542 .    time - current time
3543 .    u - current iterate
3544 .    numcost - number of cost functionos
3545 .    lambda - sensitivities to initial conditions
3546 .    mu - sensitivities to parameters
3547 -    adjointmctx - [optional] adjoint monitoring context
3548 
3549    Notes:
3550    This routine adds an additional monitor to the list of monitors that
3551    already has been loaded.
3552 
3553    Fortran notes: Only a single monitor function can be set for each TS object
3554 
3555    Level: intermediate
3556 
3557 .keywords: TS, timestep, set, adjoint, monitor
3558 
3559 .seealso: TSAdjointMonitorCancel()
3560 @*/
3561 PetscErrorCode  TSAdjointMonitorSet(TS ts,PetscErrorCode (*adjointmonitor)(TS,PetscInt,PetscReal,Vec,PetscInt,Vec*,Vec*,void*),void *adjointmctx,PetscErrorCode (*adjointmdestroy)(void**))
3562 {
3563   PetscFunctionBegin;
3564   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3565   if (ts->numberadjointmonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many adjoint monitors set");
3566   ts->adjointmonitor[ts->numberadjointmonitors]          = adjointmonitor;
3567   ts->adjointmonitordestroy[ts->numberadjointmonitors]   = adjointmdestroy;
3568   ts->adjointmonitorcontext[ts->numberadjointmonitors++] = (void*)adjointmctx;
3569   PetscFunctionReturn(0);
3570 }
3571 
3572 #undef __FUNCT__
3573 #define __FUNCT__ "TSAdjointMonitorCancel"
3574 /*@C
3575    TSAdjointMonitorCancel - Clears all the adjoint monitors that have been set on a time-step object.
3576 
3577    Logically Collective on TS
3578 
3579    Input Parameters:
3580 .  ts - the TS context obtained from TSCreate()
3581 
3582    Notes:
3583    There is no way to remove a single, specific monitor.
3584 
3585    Level: intermediate
3586 
3587 .keywords: TS, timestep, set, adjoint, monitor
3588 
3589 .seealso: TSAdjointMonitorSet()
3590 @*/
3591 PetscErrorCode  TSAdjointMonitorCancel(TS ts)
3592 {
3593   PetscErrorCode ierr;
3594   PetscInt       i;
3595 
3596   PetscFunctionBegin;
3597   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3598   for (i=0; i<ts->numberadjointmonitors; i++) {
3599     if (ts->adjointmonitordestroy[i]) {
3600       ierr = (*ts->adjointmonitordestroy[i])(&ts->adjointmonitorcontext[i]);CHKERRQ(ierr);
3601     }
3602   }
3603   ts->numberadjointmonitors = 0;
3604   PetscFunctionReturn(0);
3605 }
3606 
3607 #undef __FUNCT__
3608 #define __FUNCT__ "TSAdjointMonitorDefault"
3609 /*@C
3610    TSAdjointMonitorDefault - the default monitor of adjoint computations
3611 
3612    Level: intermediate
3613 
3614 .keywords: TS, set, monitor
3615 
3616 .seealso: TSAdjointMonitorSet()
3617 @*/
3618 PetscErrorCode TSAdjointMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscInt numcost,Vec *lambda,Vec *mu,PetscViewerAndFormat *vf)
3619 {
3620   PetscErrorCode ierr;
3621   PetscViewer    viewer = vf->viewer;
3622 
3623   PetscFunctionBegin;
3624   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,4);
3625   ierr = PetscViewerPushFormat(viewer,vf->format);CHKERRQ(ierr);
3626   ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3627   ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");CHKERRQ(ierr);
3628   ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
3629   ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
3630   PetscFunctionReturn(0);
3631 }
3632 
3633 #undef __FUNCT__
3634 #define __FUNCT__ "TSInterpolate"
3635 /*@
3636    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3637 
3638    Collective on TS
3639 
3640    Input Argument:
3641 +  ts - time stepping context
3642 -  t - time to interpolate to
3643 
3644    Output Argument:
3645 .  U - state at given time
3646 
3647    Level: intermediate
3648 
3649    Developer Notes:
3650    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3651 
3652 .keywords: TS, set
3653 
3654 .seealso: TSSetExactFinalTime(), TSSolve()
3655 @*/
3656 PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3657 {
3658   PetscErrorCode ierr;
3659 
3660   PetscFunctionBegin;
3661   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3662   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3663   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);
3664   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3665   ierr = (*ts->ops->interpolate)(ts,t,U);CHKERRQ(ierr);
3666   PetscFunctionReturn(0);
3667 }
3668 
3669 #undef __FUNCT__
3670 #define __FUNCT__ "TSStep"
3671 /*@
3672    TSStep - Steps one time step
3673 
3674    Collective on TS
3675 
3676    Input Parameter:
3677 .  ts - the TS context obtained from TSCreate()
3678 
3679    Level: developer
3680 
3681    Notes:
3682    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
3683 
3684    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3685    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3686 
3687    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3688    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
3689 
3690 .keywords: TS, timestep, solve
3691 
3692 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3693 @*/
3694 PetscErrorCode  TSStep(TS ts)
3695 {
3696   PetscErrorCode   ierr;
3697   static PetscBool cite = PETSC_FALSE;
3698   PetscReal        ptime;
3699 
3700   PetscFunctionBegin;
3701   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3702   ierr = PetscCitationsRegister("@techreport{tspaper,\n"
3703                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3704                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3705                                 "  type        = {Preprint},\n"
3706                                 "  number      = {ANL/MCS-P5061-0114},\n"
3707                                 "  institution = {Argonne National Laboratory},\n"
3708                                 "  year        = {2014}\n}\n",&cite);CHKERRQ(ierr);
3709 
3710   ierr = TSSetUp(ts);CHKERRQ(ierr);
3711   ierr = TSTrajectorySetUp(ts->trajectory,ts);CHKERRQ(ierr);
3712 
3713   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()");
3714   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");
3715 
3716   if (!ts->steps) ts->ptime_prev = ts->ptime;
3717   ts->reason = TS_CONVERGED_ITERATING;
3718   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
3719   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3720   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3721   ierr = (*ts->ops->step)(ts);CHKERRQ(ierr);
3722   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
3723   ts->ptime_prev = ptime;
3724   ts->steps++; ts->total_steps++;
3725   ts->steprollback = PETSC_FALSE;
3726   ts->steprestart  = PETSC_FALSE;
3727 
3728   if (ts->reason < 0) {
3729     if (ts->errorifstepfailed) {
3730       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]);
3731       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3732     }
3733   } else if (!ts->reason) {
3734     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3735     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3736   }
3737   PetscFunctionReturn(0);
3738 }
3739 
3740 #undef __FUNCT__
3741 #define __FUNCT__ "TSAdjointStep"
3742 /*@
3743    TSAdjointStep - Steps one time step backward in the adjoint run
3744 
3745    Collective on TS
3746 
3747    Input Parameter:
3748 .  ts - the TS context obtained from TSCreate()
3749 
3750    Level: intermediate
3751 
3752 .keywords: TS, adjoint, step
3753 
3754 .seealso: TSAdjointSetUp(), TSAdjointSolve()
3755 @*/
3756 PetscErrorCode  TSAdjointStep(TS ts)
3757 {
3758   DM               dm;
3759   PetscErrorCode   ierr;
3760 
3761   PetscFunctionBegin;
3762   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3763   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
3764   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
3765 
3766   ierr = VecViewFromOptions(ts->vec_sol,(PetscObject)ts,"-ts_view_solution");CHKERRQ(ierr);
3767 
3768   ts->reason = TS_CONVERGED_ITERATING;
3769   ts->ptime_prev = ts->ptime;
3770   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);
3771   ierr = PetscLogEventBegin(TS_AdjointStep,ts,0,0,0);CHKERRQ(ierr);
3772   ierr = (*ts->ops->adjointstep)(ts);CHKERRQ(ierr);
3773   ierr = PetscLogEventEnd(TS_AdjointStep,ts,0,0,0);CHKERRQ(ierr);
3774   ts->steps++; ts->total_steps--;
3775 
3776   if (ts->reason < 0) {
3777     if (ts->errorifstepfailed) {
3778       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]);
3779       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]);
3780       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3781     }
3782   } else if (!ts->reason) {
3783     if (ts->steps >= ts->adjoint_max_steps) ts->reason = TS_CONVERGED_ITS;
3784   }
3785   PetscFunctionReturn(0);
3786 }
3787 
3788 #undef __FUNCT__
3789 #define __FUNCT__ "TSEvaluateWLTE"
3790 /*@
3791    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
3792    at the end of a time step with a given order of accuracy.
3793 
3794    Collective on TS
3795 
3796    Input Arguments:
3797 +  ts - time stepping context
3798 .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
3799 -  order - optional, desired order for the error evaluation or PETSC_DECIDE
3800 
3801    Output Arguments:
3802 +  order - optional, the actual order of the error evaluation
3803 -  wlte - the weighted local truncation error norm
3804 
3805    Level: advanced
3806 
3807    Notes:
3808    If the timestepper cannot evaluate the error in a particular step
3809    (eg. in the first step or restart steps after event handling),
3810    this routine returns wlte=-1.0 .
3811 
3812 .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
3813 @*/
3814 PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
3815 {
3816   PetscErrorCode ierr;
3817 
3818   PetscFunctionBegin;
3819   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3820   PetscValidType(ts,1);
3821   PetscValidLogicalCollectiveEnum(ts,wnormtype,4);
3822   if (order) PetscValidIntPointer(order,3);
3823   if (order) PetscValidLogicalCollectiveInt(ts,*order,3);
3824   PetscValidRealPointer(wlte,4);
3825   if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
3826   if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
3827   ierr = (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);CHKERRQ(ierr);
3828   PetscFunctionReturn(0);
3829 }
3830 
3831 #undef __FUNCT__
3832 #define __FUNCT__ "TSEvaluateStep"
3833 /*@
3834    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
3835 
3836    Collective on TS
3837 
3838    Input Arguments:
3839 +  ts - time stepping context
3840 .  order - desired order of accuracy
3841 -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
3842 
3843    Output Arguments:
3844 .  U - state at the end of the current step
3845 
3846    Level: advanced
3847 
3848    Notes:
3849    This function cannot be called until all stages have been evaluated.
3850    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.
3851 
3852 .seealso: TSStep(), TSAdapt
3853 @*/
3854 PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3855 {
3856   PetscErrorCode ierr;
3857 
3858   PetscFunctionBegin;
3859   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3860   PetscValidType(ts,1);
3861   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
3862   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3863   ierr = (*ts->ops->evaluatestep)(ts,order,U,done);CHKERRQ(ierr);
3864   PetscFunctionReturn(0);
3865 }
3866 
3867 #undef __FUNCT__
3868 #define __FUNCT__ "TSForwardCostIntegral"
3869 /*@
3870  TSForwardCostIntegral - Evaluate the cost integral in the forward run.
3871 
3872  Collective on TS
3873 
3874  Input Arguments:
3875  .  ts - time stepping context
3876 
3877  Level: advanced
3878 
3879  Notes:
3880  This function cannot be called until TSStep() has been completed.
3881 
3882  .seealso: TSSolve(), TSAdjointCostIntegral()
3883  @*/
3884 PetscErrorCode TSForwardCostIntegral(TS ts)
3885 {
3886     PetscErrorCode ierr;
3887     PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3888     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);
3889     ierr = (*ts->ops->forwardintegral)(ts);CHKERRQ(ierr);
3890     PetscFunctionReturn(0);
3891 }
3892 
3893 #undef __FUNCT__
3894 #define __FUNCT__ "TSSolve"
3895 /*@
3896    TSSolve - Steps the requested number of timesteps.
3897 
3898    Collective on TS
3899 
3900    Input Parameter:
3901 +  ts - the TS context obtained from TSCreate()
3902 -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
3903                              otherwise must contain the initial conditions and will contain the solution at the final requested time
3904 
3905    Level: beginner
3906 
3907    Notes:
3908    The final time returned by this function may be different from the time of the internally
3909    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3910    stepped over the final time.
3911 
3912 .keywords: TS, timestep, solve
3913 
3914 .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
3915 @*/
3916 PetscErrorCode TSSolve(TS ts,Vec u)
3917 {
3918   Vec               solution;
3919   PetscErrorCode    ierr;
3920 
3921   PetscFunctionBegin;
3922   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3923   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3924 
3925   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 */
3926     PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3927     if (!ts->vec_sol || u == ts->vec_sol) {
3928       ierr = VecDuplicate(u,&solution);CHKERRQ(ierr);
3929       ierr = TSSetSolution(ts,solution);CHKERRQ(ierr);
3930       ierr = VecDestroy(&solution);CHKERRQ(ierr); /* grant ownership */
3931     }
3932     ierr = VecCopy(u,ts->vec_sol);CHKERRQ(ierr);
3933   } else if (u) {
3934     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
3935   }
3936   ierr = TSSetUp(ts);CHKERRQ(ierr);
3937   ierr = TSTrajectorySetUp(ts->trajectory,ts);CHKERRQ(ierr);
3938 
3939   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()");
3940   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");
3941 
3942   /* reset time step and iteration counters */
3943   ts->steps             = 0;
3944   ts->ksp_its           = 0;
3945   ts->snes_its          = 0;
3946   ts->num_snes_failures = 0;
3947   ts->reject            = 0;
3948   ts->reason            = TS_CONVERGED_ITERATING;
3949 
3950   ierr = TSViewFromOptions(ts,NULL,"-ts_view_pre");CHKERRQ(ierr);
3951 
3952   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3953     ierr = (*ts->ops->solve)(ts);CHKERRQ(ierr);
3954     if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3955     ts->solvetime = ts->ptime;
3956     solution = ts->vec_sol;
3957   } else { /* Step the requested number of timesteps. */
3958     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3959     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3960     ierr = TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3961     ierr = TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3962     ts->steprollback = PETSC_FALSE;
3963     ts->steprestart  = PETSC_TRUE;
3964 
3965     while (!ts->reason) {
3966       ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3967       if (!ts->steprollback) {
3968         ierr = TSPreStep(ts);CHKERRQ(ierr);
3969       }
3970       ierr = TSStep(ts);CHKERRQ(ierr);
3971       ierr = TSEventHandler(ts);CHKERRQ(ierr);
3972       if (!ts->steprollback) {
3973         if (ts->vec_costintegral && ts->costintegralfwd) {
3974           ierr = TSForwardCostIntegral(ts);CHKERRQ(ierr);
3975         }
3976         ierr = TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3977         ierr = TSPostStep(ts);CHKERRQ(ierr);
3978       }
3979     }
3980     ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
3981 
3982     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3983       ierr = TSInterpolate(ts,ts->max_time,u);CHKERRQ(ierr);
3984       ts->solvetime = ts->max_time;
3985       solution = u;
3986       ierr = TSMonitor(ts,-1,ts->solvetime,solution);CHKERRQ(ierr);
3987     } else {
3988       if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
3989       ts->solvetime = ts->ptime;
3990       solution = ts->vec_sol;
3991     }
3992   }
3993 
3994   ierr = TSViewFromOptions(ts,NULL,"-ts_view");CHKERRQ(ierr);
3995   ierr = VecViewFromOptions(solution,NULL,"-ts_view_solution");CHKERRQ(ierr);
3996   ierr = PetscObjectSAWsBlock((PetscObject)ts);CHKERRQ(ierr);
3997   if (ts->adjoint_solve) {
3998     ierr = TSAdjointSolve(ts);CHKERRQ(ierr);
3999   }
4000   PetscFunctionReturn(0);
4001 }
4002 
4003 #undef __FUNCT__
4004 #define __FUNCT__ "TSAdjointCostIntegral"
4005 /*@
4006  TSAdjointCostIntegral - Evaluate the cost integral in the adjoint run.
4007 
4008  Collective on TS
4009 
4010  Input Arguments:
4011  .  ts - time stepping context
4012 
4013  Level: advanced
4014 
4015  Notes:
4016  This function cannot be called until TSAdjointStep() has been completed.
4017 
4018  .seealso: TSAdjointSolve(), TSAdjointStep
4019  @*/
4020 PetscErrorCode TSAdjointCostIntegral(TS ts)
4021 {
4022     PetscErrorCode ierr;
4023     PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4024     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);
4025     ierr = (*ts->ops->adjointintegral)(ts);CHKERRQ(ierr);
4026     PetscFunctionReturn(0);
4027 }
4028 
4029 #undef __FUNCT__
4030 #define __FUNCT__ "TSAdjointSolve"
4031 /*@
4032    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE
4033 
4034    Collective on TS
4035 
4036    Input Parameter:
4037 .  ts - the TS context obtained from TSCreate()
4038 
4039    Options Database:
4040 . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions
4041 
4042    Level: intermediate
4043 
4044    Notes:
4045    This must be called after a call to TSSolve() that solves the forward problem
4046 
4047    By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time
4048 
4049 .keywords: TS, timestep, solve
4050 
4051 .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
4052 @*/
4053 PetscErrorCode TSAdjointSolve(TS ts)
4054 {
4055   PetscErrorCode    ierr;
4056 
4057   PetscFunctionBegin;
4058   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4059   ierr = TSAdjointSetUp(ts);CHKERRQ(ierr);
4060 
4061   /* reset time step and iteration counters */
4062   ts->steps             = 0;
4063   ts->ksp_its           = 0;
4064   ts->snes_its          = 0;
4065   ts->num_snes_failures = 0;
4066   ts->reject            = 0;
4067   ts->reason            = TS_CONVERGED_ITERATING;
4068 
4069   if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;
4070 
4071   if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
4072   while (!ts->reason) {
4073     ierr = TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);CHKERRQ(ierr);
4074     ierr = TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);CHKERRQ(ierr);
4075     ierr = TSAdjointEventHandler(ts);CHKERRQ(ierr);
4076     ierr = TSAdjointStep(ts);CHKERRQ(ierr);
4077     if (ts->vec_costintegral && !ts->costintegralfwd) {
4078       ierr = TSAdjointCostIntegral(ts);CHKERRQ(ierr);
4079     }
4080   }
4081   ierr = TSTrajectoryGet(ts->trajectory,ts,ts->total_steps,&ts->ptime);CHKERRQ(ierr);
4082   ierr = TSAdjointMonitor(ts,ts->total_steps,ts->ptime,ts->vec_sol,ts->numcost,ts->vecs_sensi,ts->vecs_sensip);CHKERRQ(ierr);
4083   ts->solvetime = ts->ptime;
4084   ierr = TSTrajectoryViewFromOptions(ts->trajectory,NULL,"-ts_trajectory_view");CHKERRQ(ierr);
4085   ierr = VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");CHKERRQ(ierr);
4086   PetscFunctionReturn(0);
4087 }
4088 
4089 #undef __FUNCT__
4090 #define __FUNCT__ "TSMonitor"
4091 /*@C
4092    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
4093 
4094    Collective on TS
4095 
4096    Input Parameters:
4097 +  ts - time stepping context obtained from TSCreate()
4098 .  step - step number that has just completed
4099 .  ptime - model time of the state
4100 -  u - state at the current model time
4101 
4102    Notes:
4103    TSMonitor() is typically used automatically within the time stepping implementations.
4104    Users would almost never call this routine directly.
4105 
4106    A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions
4107 
4108    Level: developer
4109 
4110 .keywords: TS, timestep
4111 @*/
4112 PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
4113 {
4114   DM             dm;
4115   PetscInt       i,n = ts->numbermonitors;
4116   PetscErrorCode ierr;
4117 
4118   PetscFunctionBegin;
4119   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4120   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
4121 
4122   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4123   ierr = DMSetOutputSequenceNumber(dm,step,ptime);CHKERRQ(ierr);
4124 
4125   ierr = VecLockPush(u);CHKERRQ(ierr);
4126   for (i=0; i<n; i++) {
4127     ierr = (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);CHKERRQ(ierr);
4128   }
4129   ierr = VecLockPop(u);CHKERRQ(ierr);
4130   PetscFunctionReturn(0);
4131 }
4132 
4133 #undef __FUNCT__
4134 #define __FUNCT__ "TSAdjointMonitor"
4135 /*@C
4136    TSAdjointMonitor - Runs all user-provided adjoint monitor routines set using TSAdjointMonitorSet()
4137 
4138    Collective on TS
4139 
4140    Input Parameters:
4141 +  ts - time stepping context obtained from TSCreate()
4142 .  step - step number that has just completed
4143 .  ptime - model time of the state
4144 .  u - state at the current model time
4145 .  numcost - number of cost functions (dimension of lambda  or mu)
4146 .  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
4147 -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters
4148 
4149    Notes:
4150    TSAdjointMonitor() is typically used automatically within the time stepping implementations.
4151    Users would almost never call this routine directly.
4152 
4153    Level: developer
4154 
4155 .keywords: TS, timestep
4156 @*/
4157 PetscErrorCode TSAdjointMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda, Vec *mu)
4158 {
4159   PetscErrorCode ierr;
4160   PetscInt       i,n = ts->numberadjointmonitors;
4161 
4162   PetscFunctionBegin;
4163   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4164   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
4165   ierr = VecLockPush(u);CHKERRQ(ierr);
4166   for (i=0; i<n; i++) {
4167     ierr = (*ts->adjointmonitor[i])(ts,step,ptime,u,numcost,lambda,mu,ts->adjointmonitorcontext[i]);CHKERRQ(ierr);
4168   }
4169   ierr = VecLockPop(u);CHKERRQ(ierr);
4170   PetscFunctionReturn(0);
4171 }
4172 
4173 /* ------------------------------------------------------------------------*/
4174 #undef __FUNCT__
4175 #define __FUNCT__ "TSMonitorLGCtxCreate"
4176 /*@C
4177    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
4178    TS to monitor the solution process graphically in various ways
4179 
4180    Collective on TS
4181 
4182    Input Parameters:
4183 +  host - the X display to open, or null for the local machine
4184 .  label - the title to put in the title bar
4185 .  x, y - the screen coordinates of the upper left coordinate of the window
4186 .  m, n - the screen width and height in pixels
4187 -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
4188 
4189    Output Parameter:
4190 .  ctx - the context
4191 
4192    Options Database Key:
4193 +  -ts_monitor_lg_timestep - automatically sets line graph monitor
4194 .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
4195 .  -ts_monitor_lg_error -  monitor the error
4196 .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
4197 .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
4198 -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true
4199 
4200    Notes:
4201    Use TSMonitorLGCtxDestroy() to destroy.
4202 
4203    One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()
4204 
4205    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
4206    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
4207    as the first argument.
4208 
4209    One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()
4210 
4211 
4212    Level: intermediate
4213 
4214 .keywords: TS, monitor, line graph, residual
4215 
4216 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
4217            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
4218            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
4219            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
4220            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
4221 
4222 @*/
4223 PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
4224 {
4225   PetscDraw      draw;
4226   PetscErrorCode ierr;
4227 
4228   PetscFunctionBegin;
4229   ierr = PetscNew(ctx);CHKERRQ(ierr);
4230   ierr = PetscDrawCreate(comm,host,label,x,y,m,n,&draw);CHKERRQ(ierr);
4231   ierr = PetscDrawSetFromOptions(draw);CHKERRQ(ierr);
4232   ierr = PetscDrawLGCreate(draw,1,&(*ctx)->lg);CHKERRQ(ierr);
4233   ierr = PetscDrawLGSetFromOptions((*ctx)->lg);CHKERRQ(ierr);
4234   ierr = PetscDrawDestroy(&draw);CHKERRQ(ierr);
4235   (*ctx)->howoften = howoften;
4236   PetscFunctionReturn(0);
4237 }
4238 
4239 #undef __FUNCT__
4240 #define __FUNCT__ "TSMonitorLGTimeStep"
4241 PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
4242 {
4243   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4244   PetscReal      x   = ptime,y;
4245   PetscErrorCode ierr;
4246 
4247   PetscFunctionBegin;
4248   if (step < 0) PetscFunctionReturn(0); /* -1 indicates an interpolated solution */
4249   if (!step) {
4250     PetscDrawAxis axis;
4251     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4252     ierr = PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time Step");CHKERRQ(ierr);
4253     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4254   }
4255   ierr = TSGetTimeStep(ts,&y);CHKERRQ(ierr);
4256   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
4257   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
4258     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4259     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
4260   }
4261   PetscFunctionReturn(0);
4262 }
4263 
4264 #undef __FUNCT__
4265 #define __FUNCT__ "TSMonitorLGCtxDestroy"
4266 /*@C
4267    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
4268    with TSMonitorLGCtxCreate().
4269 
4270    Collective on TSMonitorLGCtx
4271 
4272    Input Parameter:
4273 .  ctx - the monitor context
4274 
4275    Level: intermediate
4276 
4277 .keywords: TS, monitor, line graph, destroy
4278 
4279 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
4280 @*/
4281 PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
4282 {
4283   PetscErrorCode ierr;
4284 
4285   PetscFunctionBegin;
4286   if ((*ctx)->transformdestroy) {
4287     ierr = ((*ctx)->transformdestroy)((*ctx)->transformctx);CHKERRQ(ierr);
4288   }
4289   ierr = PetscDrawLGDestroy(&(*ctx)->lg);CHKERRQ(ierr);
4290   ierr = PetscStrArrayDestroy(&(*ctx)->names);CHKERRQ(ierr);
4291   ierr = PetscStrArrayDestroy(&(*ctx)->displaynames);CHKERRQ(ierr);
4292   ierr = PetscFree((*ctx)->displayvariables);CHKERRQ(ierr);
4293   ierr = PetscFree((*ctx)->displayvalues);CHKERRQ(ierr);
4294   ierr = PetscFree(*ctx);CHKERRQ(ierr);
4295   PetscFunctionReturn(0);
4296 }
4297 
4298 #undef __FUNCT__
4299 #define __FUNCT__ "TSGetTime"
4300 /*@
4301    TSGetTime - Gets the time of the most recently completed step.
4302 
4303    Not Collective
4304 
4305    Input Parameter:
4306 .  ts - the TS context obtained from TSCreate()
4307 
4308    Output Parameter:
4309 .  t  - the current time. This time may not corresponds to the final time set with TSSetDuration(), use TSGetSolveTime().
4310 
4311    Level: beginner
4312 
4313    Note:
4314    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
4315    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
4316 
4317 .seealso: TSSetInitialTimeStep(), TSGetTimeStep(), TSGetSolveTime()
4318 
4319 .keywords: TS, get, time
4320 @*/
4321 PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
4322 {
4323   PetscFunctionBegin;
4324   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4325   PetscValidRealPointer(t,2);
4326   *t = ts->ptime;
4327   PetscFunctionReturn(0);
4328 }
4329 
4330 #undef __FUNCT__
4331 #define __FUNCT__ "TSGetPrevTime"
4332 /*@
4333    TSGetPrevTime - Gets the starting time of the previously completed step.
4334 
4335    Not Collective
4336 
4337    Input Parameter:
4338 .  ts - the TS context obtained from TSCreate()
4339 
4340    Output Parameter:
4341 .  t  - the previous time
4342 
4343    Level: beginner
4344 
4345 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
4346 
4347 .keywords: TS, get, time
4348 @*/
4349 PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4350 {
4351   PetscFunctionBegin;
4352   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4353   PetscValidRealPointer(t,2);
4354   *t = ts->ptime_prev;
4355   PetscFunctionReturn(0);
4356 }
4357 
4358 #undef __FUNCT__
4359 #define __FUNCT__ "TSSetTime"
4360 /*@
4361    TSSetTime - Allows one to reset the time.
4362 
4363    Logically Collective on TS
4364 
4365    Input Parameters:
4366 +  ts - the TS context obtained from TSCreate()
4367 -  time - the time
4368 
4369    Level: intermediate
4370 
4371 .seealso: TSGetTime(), TSSetDuration()
4372 
4373 .keywords: TS, set, time
4374 @*/
4375 PetscErrorCode  TSSetTime(TS ts, PetscReal t)
4376 {
4377   PetscFunctionBegin;
4378   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4379   PetscValidLogicalCollectiveReal(ts,t,2);
4380   ts->ptime = t;
4381   PetscFunctionReturn(0);
4382 }
4383 
4384 #undef __FUNCT__
4385 #define __FUNCT__ "TSSetOptionsPrefix"
4386 /*@C
4387    TSSetOptionsPrefix - Sets the prefix used for searching for all
4388    TS options in the database.
4389 
4390    Logically Collective on TS
4391 
4392    Input Parameter:
4393 +  ts     - The TS context
4394 -  prefix - The prefix to prepend to all option names
4395 
4396    Notes:
4397    A hyphen (-) must NOT be given at the beginning of the prefix name.
4398    The first character of all runtime options is AUTOMATICALLY the
4399    hyphen.
4400 
4401    Level: advanced
4402 
4403 .keywords: TS, set, options, prefix, database
4404 
4405 .seealso: TSSetFromOptions()
4406 
4407 @*/
4408 PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4409 {
4410   PetscErrorCode ierr;
4411   SNES           snes;
4412 
4413   PetscFunctionBegin;
4414   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4415   ierr = PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4416   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4417   ierr = SNESSetOptionsPrefix(snes,prefix);CHKERRQ(ierr);
4418   PetscFunctionReturn(0);
4419 }
4420 
4421 
4422 #undef __FUNCT__
4423 #define __FUNCT__ "TSAppendOptionsPrefix"
4424 /*@C
4425    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4426    TS options in the database.
4427 
4428    Logically Collective on TS
4429 
4430    Input Parameter:
4431 +  ts     - The TS context
4432 -  prefix - The prefix to prepend to all option names
4433 
4434    Notes:
4435    A hyphen (-) must NOT be given at the beginning of the prefix name.
4436    The first character of all runtime options is AUTOMATICALLY the
4437    hyphen.
4438 
4439    Level: advanced
4440 
4441 .keywords: TS, append, options, prefix, database
4442 
4443 .seealso: TSGetOptionsPrefix()
4444 
4445 @*/
4446 PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4447 {
4448   PetscErrorCode ierr;
4449   SNES           snes;
4450 
4451   PetscFunctionBegin;
4452   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4453   ierr = PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4454   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4455   ierr = SNESAppendOptionsPrefix(snes,prefix);CHKERRQ(ierr);
4456   PetscFunctionReturn(0);
4457 }
4458 
4459 #undef __FUNCT__
4460 #define __FUNCT__ "TSGetOptionsPrefix"
4461 /*@C
4462    TSGetOptionsPrefix - Sets the prefix used for searching for all
4463    TS options in the database.
4464 
4465    Not Collective
4466 
4467    Input Parameter:
4468 .  ts - The TS context
4469 
4470    Output Parameter:
4471 .  prefix - A pointer to the prefix string used
4472 
4473    Notes: On the fortran side, the user should pass in a string 'prifix' of
4474    sufficient length to hold the prefix.
4475 
4476    Level: intermediate
4477 
4478 .keywords: TS, get, options, prefix, database
4479 
4480 .seealso: TSAppendOptionsPrefix()
4481 @*/
4482 PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4483 {
4484   PetscErrorCode ierr;
4485 
4486   PetscFunctionBegin;
4487   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4488   PetscValidPointer(prefix,2);
4489   ierr = PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
4490   PetscFunctionReturn(0);
4491 }
4492 
4493 #undef __FUNCT__
4494 #define __FUNCT__ "TSGetRHSJacobian"
4495 /*@C
4496    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4497 
4498    Not Collective, but parallel objects are returned if TS is parallel
4499 
4500    Input Parameter:
4501 .  ts  - The TS context obtained from TSCreate()
4502 
4503    Output Parameters:
4504 +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4505 .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4506 .  func - Function to compute the Jacobian of the RHS  (or NULL)
4507 -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4508 
4509    Notes: You can pass in NULL for any return argument you do not need.
4510 
4511    Level: intermediate
4512 
4513 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4514 
4515 .keywords: TS, timestep, get, matrix, Jacobian
4516 @*/
4517 PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4518 {
4519   PetscErrorCode ierr;
4520   SNES           snes;
4521   DM             dm;
4522 
4523   PetscFunctionBegin;
4524   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4525   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
4526   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4527   ierr = DMTSGetRHSJacobian(dm,func,ctx);CHKERRQ(ierr);
4528   PetscFunctionReturn(0);
4529 }
4530 
4531 #undef __FUNCT__
4532 #define __FUNCT__ "TSGetIJacobian"
4533 /*@C
4534    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
4535 
4536    Not Collective, but parallel objects are returned if TS is parallel
4537 
4538    Input Parameter:
4539 .  ts  - The TS context obtained from TSCreate()
4540 
4541    Output Parameters:
4542 +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4543 .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
4544 .  f   - The function to compute the matrices
4545 - ctx - User-defined context for Jacobian evaluation routine
4546 
4547    Notes: You can pass in NULL for any return argument you do not need.
4548 
4549    Level: advanced
4550 
4551 .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
4552 
4553 .keywords: TS, timestep, get, matrix, Jacobian
4554 @*/
4555 PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
4556 {
4557   PetscErrorCode ierr;
4558   SNES           snes;
4559   DM             dm;
4560 
4561   PetscFunctionBegin;
4562   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4563   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
4564   ierr = SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);CHKERRQ(ierr);
4565   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
4566   ierr = DMTSGetIJacobian(dm,f,ctx);CHKERRQ(ierr);
4567   PetscFunctionReturn(0);
4568 }
4569 
4570 
4571 #undef __FUNCT__
4572 #define __FUNCT__ "TSMonitorDrawSolution"
4573 /*@C
4574    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
4575    VecView() for the solution at each timestep
4576 
4577    Collective on TS
4578 
4579    Input Parameters:
4580 +  ts - the TS context
4581 .  step - current time-step
4582 .  ptime - current time
4583 -  dummy - either a viewer or NULL
4584 
4585    Options Database:
4586 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4587 
4588    Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
4589        will look bad
4590 
4591    Level: intermediate
4592 
4593 .keywords: TS,  vector, monitor, view
4594 
4595 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4596 @*/
4597 PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4598 {
4599   PetscErrorCode   ierr;
4600   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4601   PetscDraw        draw;
4602 
4603   PetscFunctionBegin;
4604   if (!step && ictx->showinitial) {
4605     if (!ictx->initialsolution) {
4606       ierr = VecDuplicate(u,&ictx->initialsolution);CHKERRQ(ierr);
4607     }
4608     ierr = VecCopy(u,ictx->initialsolution);CHKERRQ(ierr);
4609   }
4610   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4611 
4612   if (ictx->showinitial) {
4613     PetscReal pause;
4614     ierr = PetscViewerDrawGetPause(ictx->viewer,&pause);CHKERRQ(ierr);
4615     ierr = PetscViewerDrawSetPause(ictx->viewer,0.0);CHKERRQ(ierr);
4616     ierr = VecView(ictx->initialsolution,ictx->viewer);CHKERRQ(ierr);
4617     ierr = PetscViewerDrawSetPause(ictx->viewer,pause);CHKERRQ(ierr);
4618     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);CHKERRQ(ierr);
4619   }
4620   ierr = VecView(u,ictx->viewer);CHKERRQ(ierr);
4621   if (ictx->showtimestepandtime) {
4622     PetscReal xl,yl,xr,yr,h;
4623     char      time[32];
4624 
4625     ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4626     ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4627     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4628     h    = yl + .95*(yr - yl);
4629     ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4630     ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4631   }
4632 
4633   if (ictx->showinitial) {
4634     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);CHKERRQ(ierr);
4635   }
4636   PetscFunctionReturn(0);
4637 }
4638 
4639 #undef __FUNCT__
4640 #define __FUNCT__ "TSAdjointMonitorDrawSensi"
4641 /*@C
4642    TSAdjointMonitorDrawSensi - Monitors progress of the adjoint TS solvers by calling
4643    VecView() for the sensitivities to initial states at each timestep
4644 
4645    Collective on TS
4646 
4647    Input Parameters:
4648 +  ts - the TS context
4649 .  step - current time-step
4650 .  ptime - current time
4651 .  u - current state
4652 .  numcost - number of cost functions
4653 .  lambda - sensitivities to initial conditions
4654 .  mu - sensitivities to parameters
4655 -  dummy - either a viewer or NULL
4656 
4657    Level: intermediate
4658 
4659 .keywords: TS,  vector, adjoint, monitor, view
4660 
4661 .seealso: TSAdjointMonitorSet(), TSAdjointMonitorDefault(), VecView()
4662 @*/
4663 PetscErrorCode  TSAdjointMonitorDrawSensi(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscInt numcost,Vec *lambda,Vec *mu,void *dummy)
4664 {
4665   PetscErrorCode   ierr;
4666   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
4667   PetscDraw        draw;
4668   PetscReal        xl,yl,xr,yr,h;
4669   char             time[32];
4670 
4671   PetscFunctionBegin;
4672   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4673 
4674   ierr = VecView(lambda[0],ictx->viewer);CHKERRQ(ierr);
4675   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4676   ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4677   ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4678   h    = yl + .95*(yr - yl);
4679   ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4680   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4681   PetscFunctionReturn(0);
4682 }
4683 
4684 #undef __FUNCT__
4685 #define __FUNCT__ "TSMonitorDrawSolutionPhase"
4686 /*@C
4687    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
4688 
4689    Collective on TS
4690 
4691    Input Parameters:
4692 +  ts - the TS context
4693 .  step - current time-step
4694 .  ptime - current time
4695 -  dummy - either a viewer or NULL
4696 
4697    Level: intermediate
4698 
4699 .keywords: TS,  vector, monitor, view
4700 
4701 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4702 @*/
4703 PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4704 {
4705   PetscErrorCode    ierr;
4706   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
4707   PetscDraw         draw;
4708   PetscDrawAxis     axis;
4709   PetscInt          n;
4710   PetscMPIInt       size;
4711   PetscReal         U0,U1,xl,yl,xr,yr,h;
4712   char              time[32];
4713   const PetscScalar *U;
4714 
4715   PetscFunctionBegin;
4716   ierr = MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);CHKERRQ(ierr);
4717   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
4718   ierr = VecGetSize(u,&n);CHKERRQ(ierr);
4719   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");
4720 
4721   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
4722   ierr = PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);CHKERRQ(ierr);
4723   ierr = PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);CHKERRQ(ierr);
4724   if (!step) {
4725     ierr = PetscDrawClear(draw);CHKERRQ(ierr);
4726     ierr = PetscDrawAxisDraw(axis);CHKERRQ(ierr);
4727   }
4728 
4729   ierr = VecGetArrayRead(u,&U);CHKERRQ(ierr);
4730   U0 = PetscRealPart(U[0]);
4731   U1 = PetscRealPart(U[1]);
4732   ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
4733   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) PetscFunctionReturn(0);
4734 
4735   ierr = PetscDrawCollectiveBegin(draw);CHKERRQ(ierr);
4736   ierr = PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);CHKERRQ(ierr);
4737   if (ictx->showtimestepandtime) {
4738     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
4739     ierr = PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);CHKERRQ(ierr);
4740     h    = yl + .95*(yr - yl);
4741     ierr = PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
4742   }
4743   ierr = PetscDrawCollectiveEnd(draw);CHKERRQ(ierr);
4744   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
4745   ierr = PetscDrawSave(draw);CHKERRQ(ierr);
4746   PetscFunctionReturn(0);
4747 }
4748 
4749 
4750 #undef __FUNCT__
4751 #define __FUNCT__ "TSMonitorDrawCtxDestroy"
4752 /*@C
4753    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
4754 
4755    Collective on TS
4756 
4757    Input Parameters:
4758 .    ctx - the monitor context
4759 
4760    Level: intermediate
4761 
4762 .keywords: TS,  vector, monitor, view
4763 
4764 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
4765 @*/
4766 PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
4767 {
4768   PetscErrorCode ierr;
4769 
4770   PetscFunctionBegin;
4771   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
4772   ierr = VecDestroy(&(*ictx)->initialsolution);CHKERRQ(ierr);
4773   ierr = PetscFree(*ictx);CHKERRQ(ierr);
4774   PetscFunctionReturn(0);
4775 }
4776 
4777 #undef __FUNCT__
4778 #define __FUNCT__ "TSMonitorDrawCtxCreate"
4779 /*@C
4780    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
4781 
4782    Collective on TS
4783 
4784    Input Parameter:
4785 .    ts - time-step context
4786 
4787    Output Patameter:
4788 .    ctx - the monitor context
4789 
4790    Options Database:
4791 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
4792 
4793    Level: intermediate
4794 
4795 .keywords: TS,  vector, monitor, view
4796 
4797 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
4798 @*/
4799 PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
4800 {
4801   PetscErrorCode   ierr;
4802 
4803   PetscFunctionBegin;
4804   ierr = PetscNew(ctx);CHKERRQ(ierr);
4805   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
4806   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
4807 
4808   (*ctx)->howoften    = howoften;
4809   (*ctx)->showinitial = PETSC_FALSE;
4810   ierr = PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);CHKERRQ(ierr);
4811 
4812   (*ctx)->showtimestepandtime = PETSC_FALSE;
4813   ierr = PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);CHKERRQ(ierr);
4814   PetscFunctionReturn(0);
4815 }
4816 
4817 #undef __FUNCT__
4818 #define __FUNCT__ "TSMonitorDrawError"
4819 /*@C
4820    TSMonitorDrawError - Monitors progress of the TS solvers by calling
4821    VecView() for the error at each timestep
4822 
4823    Collective on TS
4824 
4825    Input Parameters:
4826 +  ts - the TS context
4827 .  step - current time-step
4828 .  ptime - current time
4829 -  dummy - either a viewer or NULL
4830 
4831    Level: intermediate
4832 
4833 .keywords: TS,  vector, monitor, view
4834 
4835 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4836 @*/
4837 PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4838 {
4839   PetscErrorCode   ierr;
4840   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4841   PetscViewer      viewer = ctx->viewer;
4842   Vec              work;
4843 
4844   PetscFunctionBegin;
4845   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) PetscFunctionReturn(0);
4846   ierr = VecDuplicate(u,&work);CHKERRQ(ierr);
4847   ierr = TSComputeSolutionFunction(ts,ptime,work);CHKERRQ(ierr);
4848   ierr = VecAXPY(work,-1.0,u);CHKERRQ(ierr);
4849   ierr = VecView(work,viewer);CHKERRQ(ierr);
4850   ierr = VecDestroy(&work);CHKERRQ(ierr);
4851   PetscFunctionReturn(0);
4852 }
4853 
4854 #include <petsc/private/dmimpl.h>
4855 #undef __FUNCT__
4856 #define __FUNCT__ "TSSetDM"
4857 /*@
4858    TSSetDM - Sets the DM that may be used by some preconditioners
4859 
4860    Logically Collective on TS and DM
4861 
4862    Input Parameters:
4863 +  ts - the preconditioner context
4864 -  dm - the dm
4865 
4866    Level: intermediate
4867 
4868 
4869 .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4870 @*/
4871 PetscErrorCode  TSSetDM(TS ts,DM dm)
4872 {
4873   PetscErrorCode ierr;
4874   SNES           snes;
4875   DMTS           tsdm;
4876 
4877   PetscFunctionBegin;
4878   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4879   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
4880   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4881     if (ts->dm->dmts && !dm->dmts) {
4882       ierr = DMCopyDMTS(ts->dm,dm);CHKERRQ(ierr);
4883       ierr = DMGetDMTS(ts->dm,&tsdm);CHKERRQ(ierr);
4884       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4885         tsdm->originaldm = dm;
4886       }
4887     }
4888     ierr = DMDestroy(&ts->dm);CHKERRQ(ierr);
4889   }
4890   ts->dm = dm;
4891 
4892   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4893   ierr = SNESSetDM(snes,dm);CHKERRQ(ierr);
4894   PetscFunctionReturn(0);
4895 }
4896 
4897 #undef __FUNCT__
4898 #define __FUNCT__ "TSGetDM"
4899 /*@
4900    TSGetDM - Gets the DM that may be used by some preconditioners
4901 
4902    Not Collective
4903 
4904    Input Parameter:
4905 . ts - the preconditioner context
4906 
4907    Output Parameter:
4908 .  dm - the dm
4909 
4910    Level: intermediate
4911 
4912 
4913 .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4914 @*/
4915 PetscErrorCode  TSGetDM(TS ts,DM *dm)
4916 {
4917   PetscErrorCode ierr;
4918 
4919   PetscFunctionBegin;
4920   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4921   if (!ts->dm) {
4922     ierr = DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);CHKERRQ(ierr);
4923     if (ts->snes) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
4924   }
4925   *dm = ts->dm;
4926   PetscFunctionReturn(0);
4927 }
4928 
4929 #undef __FUNCT__
4930 #define __FUNCT__ "SNESTSFormFunction"
4931 /*@
4932    SNESTSFormFunction - Function to evaluate nonlinear residual
4933 
4934    Logically Collective on SNES
4935 
4936    Input Parameter:
4937 + snes - nonlinear solver
4938 . U - the current state at which to evaluate the residual
4939 - ctx - user context, must be a TS
4940 
4941    Output Parameter:
4942 . F - the nonlinear residual
4943 
4944    Notes:
4945    This function is not normally called by users and is automatically registered with the SNES used by TS.
4946    It is most frequently passed to MatFDColoringSetFunction().
4947 
4948    Level: advanced
4949 
4950 .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4951 @*/
4952 PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4953 {
4954   TS             ts = (TS)ctx;
4955   PetscErrorCode ierr;
4956 
4957   PetscFunctionBegin;
4958   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4959   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4960   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
4961   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
4962   ierr = (ts->ops->snesfunction)(snes,U,F,ts);CHKERRQ(ierr);
4963   PetscFunctionReturn(0);
4964 }
4965 
4966 #undef __FUNCT__
4967 #define __FUNCT__ "SNESTSFormJacobian"
4968 /*@
4969    SNESTSFormJacobian - Function to evaluate the Jacobian
4970 
4971    Collective on SNES
4972 
4973    Input Parameter:
4974 + snes - nonlinear solver
4975 . U - the current state at which to evaluate the residual
4976 - ctx - user context, must be a TS
4977 
4978    Output Parameter:
4979 + A - the Jacobian
4980 . B - the preconditioning matrix (may be the same as A)
4981 - flag - indicates any structure change in the matrix
4982 
4983    Notes:
4984    This function is not normally called by users and is automatically registered with the SNES used by TS.
4985 
4986    Level: developer
4987 
4988 .seealso: SNESSetJacobian()
4989 @*/
4990 PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4991 {
4992   TS             ts = (TS)ctx;
4993   PetscErrorCode ierr;
4994 
4995   PetscFunctionBegin;
4996   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
4997   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4998   PetscValidPointer(A,3);
4999   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
5000   PetscValidPointer(B,4);
5001   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
5002   PetscValidHeaderSpecific(ts,TS_CLASSID,6);
5003   ierr = (ts->ops->snesjacobian)(snes,U,A,B,ts);CHKERRQ(ierr);
5004   PetscFunctionReturn(0);
5005 }
5006 
5007 #undef __FUNCT__
5008 #define __FUNCT__ "TSComputeRHSFunctionLinear"
5009 /*@C
5010    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
5011 
5012    Collective on TS
5013 
5014    Input Arguments:
5015 +  ts - time stepping context
5016 .  t - time at which to evaluate
5017 .  U - state at which to evaluate
5018 -  ctx - context
5019 
5020    Output Arguments:
5021 .  F - right hand side
5022 
5023    Level: intermediate
5024 
5025    Notes:
5026    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
5027    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
5028 
5029 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
5030 @*/
5031 PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
5032 {
5033   PetscErrorCode ierr;
5034   Mat            Arhs,Brhs;
5035 
5036   PetscFunctionBegin;
5037   ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
5038   ierr = TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);CHKERRQ(ierr);
5039   ierr = MatMult(Arhs,U,F);CHKERRQ(ierr);
5040   PetscFunctionReturn(0);
5041 }
5042 
5043 #undef __FUNCT__
5044 #define __FUNCT__ "TSComputeRHSJacobianConstant"
5045 /*@C
5046    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
5047 
5048    Collective on TS
5049 
5050    Input Arguments:
5051 +  ts - time stepping context
5052 .  t - time at which to evaluate
5053 .  U - state at which to evaluate
5054 -  ctx - context
5055 
5056    Output Arguments:
5057 +  A - pointer to operator
5058 .  B - pointer to preconditioning matrix
5059 -  flg - matrix structure flag
5060 
5061    Level: intermediate
5062 
5063    Notes:
5064    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
5065 
5066 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
5067 @*/
5068 PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
5069 {
5070   PetscFunctionBegin;
5071   PetscFunctionReturn(0);
5072 }
5073 
5074 #undef __FUNCT__
5075 #define __FUNCT__ "TSComputeIFunctionLinear"
5076 /*@C
5077    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
5078 
5079    Collective on TS
5080 
5081    Input Arguments:
5082 +  ts - time stepping context
5083 .  t - time at which to evaluate
5084 .  U - state at which to evaluate
5085 .  Udot - time derivative of state vector
5086 -  ctx - context
5087 
5088    Output Arguments:
5089 .  F - left hand side
5090 
5091    Level: intermediate
5092 
5093    Notes:
5094    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
5095    user is required to write their own TSComputeIFunction.
5096    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
5097    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
5098 
5099    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
5100 
5101 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
5102 @*/
5103 PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
5104 {
5105   PetscErrorCode ierr;
5106   Mat            A,B;
5107 
5108   PetscFunctionBegin;
5109   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
5110   ierr = TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);CHKERRQ(ierr);
5111   ierr = MatMult(A,Udot,F);CHKERRQ(ierr);
5112   PetscFunctionReturn(0);
5113 }
5114 
5115 #undef __FUNCT__
5116 #define __FUNCT__ "TSComputeIJacobianConstant"
5117 /*@C
5118    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
5119 
5120    Collective on TS
5121 
5122    Input Arguments:
5123 +  ts - time stepping context
5124 .  t - time at which to evaluate
5125 .  U - state at which to evaluate
5126 .  Udot - time derivative of state vector
5127 .  shift - shift to apply
5128 -  ctx - context
5129 
5130    Output Arguments:
5131 +  A - pointer to operator
5132 .  B - pointer to preconditioning matrix
5133 -  flg - matrix structure flag
5134 
5135    Level: advanced
5136 
5137    Notes:
5138    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
5139 
5140    It is only appropriate for problems of the form
5141 
5142 $     M Udot = F(U,t)
5143 
5144   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
5145   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
5146   an implicit operator of the form
5147 
5148 $    shift*M + J
5149 
5150   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
5151   a copy of M or reassemble it when requested.
5152 
5153 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
5154 @*/
5155 PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
5156 {
5157   PetscErrorCode ierr;
5158 
5159   PetscFunctionBegin;
5160   ierr = MatScale(A, shift / ts->ijacobian.shift);CHKERRQ(ierr);
5161   ts->ijacobian.shift = shift;
5162   PetscFunctionReturn(0);
5163 }
5164 
5165 #undef __FUNCT__
5166 #define __FUNCT__ "TSGetEquationType"
5167 /*@
5168    TSGetEquationType - Gets the type of the equation that TS is solving.
5169 
5170    Not Collective
5171 
5172    Input Parameter:
5173 .  ts - the TS context
5174 
5175    Output Parameter:
5176 .  equation_type - see TSEquationType
5177 
5178    Level: beginner
5179 
5180 .keywords: TS, equation type
5181 
5182 .seealso: TSSetEquationType(), TSEquationType
5183 @*/
5184 PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
5185 {
5186   PetscFunctionBegin;
5187   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5188   PetscValidPointer(equation_type,2);
5189   *equation_type = ts->equation_type;
5190   PetscFunctionReturn(0);
5191 }
5192 
5193 #undef __FUNCT__
5194 #define __FUNCT__ "TSSetEquationType"
5195 /*@
5196    TSSetEquationType - Sets the type of the equation that TS is solving.
5197 
5198    Not Collective
5199 
5200    Input Parameter:
5201 +  ts - the TS context
5202 -  equation_type - see TSEquationType
5203 
5204    Level: advanced
5205 
5206 .keywords: TS, equation type
5207 
5208 .seealso: TSGetEquationType(), TSEquationType
5209 @*/
5210 PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
5211 {
5212   PetscFunctionBegin;
5213   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5214   ts->equation_type = equation_type;
5215   PetscFunctionReturn(0);
5216 }
5217 
5218 #undef __FUNCT__
5219 #define __FUNCT__ "TSGetConvergedReason"
5220 /*@
5221    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
5222 
5223    Not Collective
5224 
5225    Input Parameter:
5226 .  ts - the TS context
5227 
5228    Output Parameter:
5229 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5230             manual pages for the individual convergence tests for complete lists
5231 
5232    Level: beginner
5233 
5234    Notes:
5235    Can only be called after the call to TSSolve() is complete.
5236 
5237 .keywords: TS, nonlinear, set, convergence, test
5238 
5239 .seealso: TSSetConvergenceTest(), TSConvergedReason
5240 @*/
5241 PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
5242 {
5243   PetscFunctionBegin;
5244   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5245   PetscValidPointer(reason,2);
5246   *reason = ts->reason;
5247   PetscFunctionReturn(0);
5248 }
5249 
5250 #undef __FUNCT__
5251 #define __FUNCT__ "TSSetConvergedReason"
5252 /*@
5253    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
5254 
5255    Not Collective
5256 
5257    Input Parameter:
5258 +  ts - the TS context
5259 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
5260             manual pages for the individual convergence tests for complete lists
5261 
5262    Level: advanced
5263 
5264    Notes:
5265    Can only be called during TSSolve() is active.
5266 
5267 .keywords: TS, nonlinear, set, convergence, test
5268 
5269 .seealso: TSConvergedReason
5270 @*/
5271 PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
5272 {
5273   PetscFunctionBegin;
5274   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5275   ts->reason = reason;
5276   PetscFunctionReturn(0);
5277 }
5278 
5279 #undef __FUNCT__
5280 #define __FUNCT__ "TSGetSolveTime"
5281 /*@
5282    TSGetSolveTime - Gets the time after a call to TSSolve()
5283 
5284    Not Collective
5285 
5286    Input Parameter:
5287 .  ts - the TS context
5288 
5289    Output Parameter:
5290 .  ftime - the final time. This time corresponds to the final time set with TSSetDuration()
5291 
5292    Level: beginner
5293 
5294    Notes:
5295    Can only be called after the call to TSSolve() is complete.
5296 
5297 .keywords: TS, nonlinear, set, convergence, test
5298 
5299 .seealso: TSSetConvergenceTest(), TSConvergedReason
5300 @*/
5301 PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
5302 {
5303   PetscFunctionBegin;
5304   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5305   PetscValidPointer(ftime,2);
5306   *ftime = ts->solvetime;
5307   PetscFunctionReturn(0);
5308 }
5309 
5310 #undef __FUNCT__
5311 #define __FUNCT__ "TSGetTotalSteps"
5312 /*@
5313    TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()
5314 
5315    Not Collective
5316 
5317    Input Parameter:
5318 .  ts - the TS context
5319 
5320    Output Parameter:
5321 .  steps - the number of steps
5322 
5323    Level: beginner
5324 
5325    Notes:
5326    Includes the number of steps for all calls to TSSolve() since TSSetUp() was called
5327 
5328 .keywords: TS, nonlinear, set, convergence, test
5329 
5330 .seealso: TSSetConvergenceTest(), TSConvergedReason
5331 @*/
5332 PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
5333 {
5334   PetscFunctionBegin;
5335   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5336   PetscValidPointer(steps,2);
5337   *steps = ts->total_steps;
5338   PetscFunctionReturn(0);
5339 }
5340 
5341 #undef __FUNCT__
5342 #define __FUNCT__ "TSGetSNESIterations"
5343 /*@
5344    TSGetSNESIterations - Gets the total number of nonlinear iterations
5345    used by the time integrator.
5346 
5347    Not Collective
5348 
5349    Input Parameter:
5350 .  ts - TS context
5351 
5352    Output Parameter:
5353 .  nits - number of nonlinear iterations
5354 
5355    Notes:
5356    This counter is reset to zero for each successive call to TSSolve().
5357 
5358    Level: intermediate
5359 
5360 .keywords: TS, get, number, nonlinear, iterations
5361 
5362 .seealso:  TSGetKSPIterations()
5363 @*/
5364 PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
5365 {
5366   PetscFunctionBegin;
5367   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5368   PetscValidIntPointer(nits,2);
5369   *nits = ts->snes_its;
5370   PetscFunctionReturn(0);
5371 }
5372 
5373 #undef __FUNCT__
5374 #define __FUNCT__ "TSGetKSPIterations"
5375 /*@
5376    TSGetKSPIterations - Gets the total number of linear iterations
5377    used by the time integrator.
5378 
5379    Not Collective
5380 
5381    Input Parameter:
5382 .  ts - TS context
5383 
5384    Output Parameter:
5385 .  lits - number of linear iterations
5386 
5387    Notes:
5388    This counter is reset to zero for each successive call to TSSolve().
5389 
5390    Level: intermediate
5391 
5392 .keywords: TS, get, number, linear, iterations
5393 
5394 .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
5395 @*/
5396 PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
5397 {
5398   PetscFunctionBegin;
5399   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5400   PetscValidIntPointer(lits,2);
5401   *lits = ts->ksp_its;
5402   PetscFunctionReturn(0);
5403 }
5404 
5405 #undef __FUNCT__
5406 #define __FUNCT__ "TSGetStepRejections"
5407 /*@
5408    TSGetStepRejections - Gets the total number of rejected steps.
5409 
5410    Not Collective
5411 
5412    Input Parameter:
5413 .  ts - TS context
5414 
5415    Output Parameter:
5416 .  rejects - number of steps rejected
5417 
5418    Notes:
5419    This counter is reset to zero for each successive call to TSSolve().
5420 
5421    Level: intermediate
5422 
5423 .keywords: TS, get, number
5424 
5425 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
5426 @*/
5427 PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
5428 {
5429   PetscFunctionBegin;
5430   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5431   PetscValidIntPointer(rejects,2);
5432   *rejects = ts->reject;
5433   PetscFunctionReturn(0);
5434 }
5435 
5436 #undef __FUNCT__
5437 #define __FUNCT__ "TSGetSNESFailures"
5438 /*@
5439    TSGetSNESFailures - Gets the total number of failed SNES solves
5440 
5441    Not Collective
5442 
5443    Input Parameter:
5444 .  ts - TS context
5445 
5446    Output Parameter:
5447 .  fails - number of failed nonlinear solves
5448 
5449    Notes:
5450    This counter is reset to zero for each successive call to TSSolve().
5451 
5452    Level: intermediate
5453 
5454 .keywords: TS, get, number
5455 
5456 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
5457 @*/
5458 PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
5459 {
5460   PetscFunctionBegin;
5461   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5462   PetscValidIntPointer(fails,2);
5463   *fails = ts->num_snes_failures;
5464   PetscFunctionReturn(0);
5465 }
5466 
5467 #undef __FUNCT__
5468 #define __FUNCT__ "TSSetMaxStepRejections"
5469 /*@
5470    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
5471 
5472    Not Collective
5473 
5474    Input Parameter:
5475 +  ts - TS context
5476 -  rejects - maximum number of rejected steps, pass -1 for unlimited
5477 
5478    Notes:
5479    The counter is reset to zero for each step
5480 
5481    Options Database Key:
5482  .  -ts_max_reject - Maximum number of step rejections before a step fails
5483 
5484    Level: intermediate
5485 
5486 .keywords: TS, set, maximum, number
5487 
5488 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5489 @*/
5490 PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
5491 {
5492   PetscFunctionBegin;
5493   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5494   ts->max_reject = rejects;
5495   PetscFunctionReturn(0);
5496 }
5497 
5498 #undef __FUNCT__
5499 #define __FUNCT__ "TSSetMaxSNESFailures"
5500 /*@
5501    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
5502 
5503    Not Collective
5504 
5505    Input Parameter:
5506 +  ts - TS context
5507 -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
5508 
5509    Notes:
5510    The counter is reset to zero for each successive call to TSSolve().
5511 
5512    Options Database Key:
5513  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
5514 
5515    Level: intermediate
5516 
5517 .keywords: TS, set, maximum, number
5518 
5519 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
5520 @*/
5521 PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
5522 {
5523   PetscFunctionBegin;
5524   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5525   ts->max_snes_failures = fails;
5526   PetscFunctionReturn(0);
5527 }
5528 
5529 #undef __FUNCT__
5530 #define __FUNCT__ "TSSetErrorIfStepFails"
5531 /*@
5532    TSSetErrorIfStepFails - Error if no step succeeds
5533 
5534    Not Collective
5535 
5536    Input Parameter:
5537 +  ts - TS context
5538 -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
5539 
5540    Options Database Key:
5541  .  -ts_error_if_step_fails - Error if no step succeeds
5542 
5543    Level: intermediate
5544 
5545 .keywords: TS, set, error
5546 
5547 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
5548 @*/
5549 PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
5550 {
5551   PetscFunctionBegin;
5552   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5553   ts->errorifstepfailed = err;
5554   PetscFunctionReturn(0);
5555 }
5556 
5557 #undef __FUNCT__
5558 #define __FUNCT__ "TSMonitorSolution"
5559 /*@C
5560    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
5561 
5562    Collective on TS
5563 
5564    Input Parameters:
5565 +  ts - the TS context
5566 .  step - current time-step
5567 .  ptime - current time
5568 .  u - current state
5569 -  vf - viewer and its format
5570 
5571    Level: intermediate
5572 
5573 .keywords: TS,  vector, monitor, view
5574 
5575 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5576 @*/
5577 PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
5578 {
5579   PetscErrorCode ierr;
5580 
5581   PetscFunctionBegin;
5582   ierr = PetscViewerPushFormat(vf->viewer,vf->format);CHKERRQ(ierr);
5583   ierr = VecView(u,vf->viewer);CHKERRQ(ierr);
5584   ierr = PetscViewerPopFormat(vf->viewer);CHKERRQ(ierr);
5585   PetscFunctionReturn(0);
5586 }
5587 
5588 #undef __FUNCT__
5589 #define __FUNCT__ "TSMonitorSolutionVTK"
5590 /*@C
5591    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
5592 
5593    Collective on TS
5594 
5595    Input Parameters:
5596 +  ts - the TS context
5597 .  step - current time-step
5598 .  ptime - current time
5599 .  u - current state
5600 -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5601 
5602    Level: intermediate
5603 
5604    Notes:
5605    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.
5606    These are named according to the file name template.
5607 
5608    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
5609 
5610 .keywords: TS,  vector, monitor, view
5611 
5612 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5613 @*/
5614 PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
5615 {
5616   PetscErrorCode ierr;
5617   char           filename[PETSC_MAX_PATH_LEN];
5618   PetscViewer    viewer;
5619 
5620   PetscFunctionBegin;
5621   if (step < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
5622   ierr = PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);CHKERRQ(ierr);
5623   ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);
5624   ierr = VecView(u,viewer);CHKERRQ(ierr);
5625   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
5626   PetscFunctionReturn(0);
5627 }
5628 
5629 #undef __FUNCT__
5630 #define __FUNCT__ "TSMonitorSolutionVTKDestroy"
5631 /*@C
5632    TSMonitorSolutionVTKDestroy - Destroy context for monitoring
5633 
5634    Collective on TS
5635 
5636    Input Parameters:
5637 .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
5638 
5639    Level: intermediate
5640 
5641    Note:
5642    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
5643 
5644 .keywords: TS,  vector, monitor, view
5645 
5646 .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
5647 @*/
5648 PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
5649 {
5650   PetscErrorCode ierr;
5651 
5652   PetscFunctionBegin;
5653   ierr = PetscFree(*(char**)filenametemplate);CHKERRQ(ierr);
5654   PetscFunctionReturn(0);
5655 }
5656 
5657 #undef __FUNCT__
5658 #define __FUNCT__ "TSGetAdapt"
5659 /*@
5660    TSGetAdapt - Get the adaptive controller context for the current method
5661 
5662    Collective on TS if controller has not been created yet
5663 
5664    Input Arguments:
5665 .  ts - time stepping context
5666 
5667    Output Arguments:
5668 .  adapt - adaptive controller
5669 
5670    Level: intermediate
5671 
5672 .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
5673 @*/
5674 PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
5675 {
5676   PetscErrorCode ierr;
5677 
5678   PetscFunctionBegin;
5679   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5680   PetscValidPointer(adapt,2);
5681   if (!ts->adapt) {
5682     ierr = TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);CHKERRQ(ierr);
5683     ierr = PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);CHKERRQ(ierr);
5684     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);CHKERRQ(ierr);
5685   }
5686   *adapt = ts->adapt;
5687   PetscFunctionReturn(0);
5688 }
5689 
5690 #undef __FUNCT__
5691 #define __FUNCT__ "TSSetTolerances"
5692 /*@
5693    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
5694 
5695    Logically Collective
5696 
5697    Input Arguments:
5698 +  ts - time integration context
5699 .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
5700 .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
5701 .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
5702 -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
5703 
5704    Options Database keys:
5705 +  -ts_rtol <rtol> - relative tolerance for local truncation error
5706 -  -ts_atol <atol> Absolute tolerance for local truncation error
5707 
5708    Notes:
5709    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
5710    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
5711    computed only for the differential or the algebraic part then this can be done using the vector of
5712    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
5713    differential part and infinity for the algebraic part, the LTE calculation will include only the
5714    differential variables.
5715 
5716    Level: beginner
5717 
5718 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
5719 @*/
5720 PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
5721 {
5722   PetscErrorCode ierr;
5723 
5724   PetscFunctionBegin;
5725   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
5726   if (vatol) {
5727     ierr = PetscObjectReference((PetscObject)vatol);CHKERRQ(ierr);
5728     ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
5729     ts->vatol = vatol;
5730   }
5731   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
5732   if (vrtol) {
5733     ierr = PetscObjectReference((PetscObject)vrtol);CHKERRQ(ierr);
5734     ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
5735     ts->vrtol = vrtol;
5736   }
5737   PetscFunctionReturn(0);
5738 }
5739 
5740 #undef __FUNCT__
5741 #define __FUNCT__ "TSGetTolerances"
5742 /*@
5743    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5744 
5745    Logically Collective
5746 
5747    Input Arguments:
5748 .  ts - time integration context
5749 
5750    Output Arguments:
5751 +  atol - scalar absolute tolerances, NULL to ignore
5752 .  vatol - vector of absolute tolerances, NULL to ignore
5753 .  rtol - scalar relative tolerances, NULL to ignore
5754 -  vrtol - vector of relative tolerances, NULL to ignore
5755 
5756    Level: beginner
5757 
5758 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
5759 @*/
5760 PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
5761 {
5762   PetscFunctionBegin;
5763   if (atol)  *atol  = ts->atol;
5764   if (vatol) *vatol = ts->vatol;
5765   if (rtol)  *rtol  = ts->rtol;
5766   if (vrtol) *vrtol = ts->vrtol;
5767   PetscFunctionReturn(0);
5768 }
5769 
5770 #undef __FUNCT__
5771 #define __FUNCT__ "TSErrorWeightedNorm2"
5772 /*@
5773    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
5774 
5775    Collective on TS
5776 
5777    Input Arguments:
5778 +  ts - time stepping context
5779 .  U - state vector, usually ts->vec_sol
5780 -  Y - state vector to be compared to U
5781 
5782    Output Arguments:
5783 .  norm - weighted norm, a value of 1.0 is considered small
5784 
5785    Level: developer
5786 
5787 .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
5788 @*/
5789 PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm)
5790 {
5791   PetscErrorCode    ierr;
5792   PetscInt          i,n,N,rstart;
5793   const PetscScalar *u,*y;
5794   PetscReal         sum,gsum;
5795   PetscReal         tol;
5796 
5797   PetscFunctionBegin;
5798   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5799   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5800   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
5801   PetscValidType(U,2);
5802   PetscValidType(Y,3);
5803   PetscCheckSameComm(U,2,Y,3);
5804   PetscValidPointer(norm,4);
5805   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5806 
5807   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
5808   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
5809   ierr = VecGetOwnershipRange(U,&rstart,NULL);CHKERRQ(ierr);
5810   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
5811   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
5812   sum  = 0.;
5813   if (ts->vatol && ts->vrtol) {
5814     const PetscScalar *atol,*rtol;
5815     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5816     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5817     for (i=0; i<n; i++) {
5818       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5819       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5820     }
5821     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5822     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5823   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5824     const PetscScalar *atol;
5825     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5826     for (i=0; i<n; i++) {
5827       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5828       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5829     }
5830     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5831   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5832     const PetscScalar *rtol;
5833     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5834     for (i=0; i<n; i++) {
5835       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5836       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5837     }
5838     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5839   } else {                      /* scalar atol, scalar rtol */
5840     for (i=0; i<n; i++) {
5841       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5842       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5843     }
5844   }
5845   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
5846   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
5847 
5848   ierr  = MPIU_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
5849   *norm = PetscSqrtReal(gsum / N);
5850 
5851   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5852   PetscFunctionReturn(0);
5853 }
5854 
5855 #undef __FUNCT__
5856 #define __FUNCT__ "TSErrorWeightedNormInfinity"
5857 /*@
5858    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
5859 
5860    Collective on TS
5861 
5862    Input Arguments:
5863 +  ts - time stepping context
5864 .  U - state vector, usually ts->vec_sol
5865 -  Y - state vector to be compared to U
5866 
5867    Output Arguments:
5868 .  norm - weighted norm, a value of 1.0 is considered small
5869 
5870    Level: developer
5871 
5872 .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5873 @*/
5874 PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm)
5875 {
5876   PetscErrorCode    ierr;
5877   PetscInt          i,n,N,rstart,k;
5878   const PetscScalar *u,*y;
5879   PetscReal         max,gmax;
5880   PetscReal         tol;
5881 
5882   PetscFunctionBegin;
5883   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5884   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5885   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
5886   PetscValidType(U,2);
5887   PetscValidType(Y,3);
5888   PetscCheckSameComm(U,2,Y,3);
5889   PetscValidPointer(norm,4);
5890   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
5891 
5892   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
5893   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
5894   ierr = VecGetOwnershipRange(U,&rstart,NULL);CHKERRQ(ierr);
5895   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
5896   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
5897   if (ts->vatol && ts->vrtol) {
5898     const PetscScalar *atol,*rtol;
5899     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5900     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5901     k = 0;
5902     tol = PetscRealPart(atol[k]) + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5903     max = PetscAbsScalar(y[k] - u[k]) / tol;
5904     for (i=1; i<n; i++) {
5905       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5906       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5907     }
5908     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5909     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5910   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5911     const PetscScalar *atol;
5912     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5913     k = 0;
5914     tol = PetscRealPart(atol[k]) + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5915     max = PetscAbsScalar(y[k] - u[k]) / tol;
5916     for (i=1; i<n; i++) {
5917       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5918       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5919     }
5920     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
5921   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5922     const PetscScalar *rtol;
5923     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5924     k = 0;
5925     tol = ts->atol + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5926     max = PetscAbsScalar(y[k] - u[k]) / tol;
5927     for (i=1; i<n; i++) {
5928       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5929       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5930     }
5931     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
5932   } else {                      /* scalar atol, scalar rtol */
5933     k = 0;
5934     tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5935     max = PetscAbsScalar(y[k] - u[k]) / tol;
5936     for (i=1; i<n; i++) {
5937       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5938       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5939     }
5940   }
5941   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
5942   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
5943 
5944   ierr  = MPIU_Allreduce(&max,&gmax,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
5945   *norm = gmax;
5946 
5947   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5948   PetscFunctionReturn(0);
5949 }
5950 
5951 #undef __FUNCT__
5952 #define __FUNCT__ "TSErrorWeightedNorm"
5953 /*@
5954    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors
5955 
5956    Collective on TS
5957 
5958    Input Arguments:
5959 +  ts - time stepping context
5960 .  U - state vector, usually ts->vec_sol
5961 .  Y - state vector to be compared to U
5962 -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
5963 
5964    Output Arguments:
5965 .  norm - weighted norm, a value of 1.0 is considered small
5966 
5967 
5968    Options Database Keys:
5969 .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5970 
5971    Level: developer
5972 
5973 .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
5974 @*/
5975 PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm)
5976 {
5977   PetscErrorCode ierr;
5978 
5979   PetscFunctionBegin;
5980   if (wnormtype == NORM_2) {
5981     ierr = TSErrorWeightedNorm2(ts,U,Y,norm);CHKERRQ(ierr);
5982   } else if(wnormtype == NORM_INFINITY) {
5983     ierr = TSErrorWeightedNormInfinity(ts,U,Y,norm);CHKERRQ(ierr);
5984   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5985   PetscFunctionReturn(0);
5986 }
5987 
5988 #undef __FUNCT__
5989 #define __FUNCT__ "TSSetCFLTimeLocal"
5990 /*@
5991    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
5992 
5993    Logically Collective on TS
5994 
5995    Input Arguments:
5996 +  ts - time stepping context
5997 -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
5998 
5999    Note:
6000    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
6001 
6002    Level: intermediate
6003 
6004 .seealso: TSGetCFLTime(), TSADAPTCFL
6005 @*/
6006 PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
6007 {
6008   PetscFunctionBegin;
6009   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6010   ts->cfltime_local = cfltime;
6011   ts->cfltime       = -1.;
6012   PetscFunctionReturn(0);
6013 }
6014 
6015 #undef __FUNCT__
6016 #define __FUNCT__ "TSGetCFLTime"
6017 /*@
6018    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
6019 
6020    Collective on TS
6021 
6022    Input Arguments:
6023 .  ts - time stepping context
6024 
6025    Output Arguments:
6026 .  cfltime - maximum stable time step for forward Euler
6027 
6028    Level: advanced
6029 
6030 .seealso: TSSetCFLTimeLocal()
6031 @*/
6032 PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
6033 {
6034   PetscErrorCode ierr;
6035 
6036   PetscFunctionBegin;
6037   if (ts->cfltime < 0) {
6038     ierr = MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
6039   }
6040   *cfltime = ts->cfltime;
6041   PetscFunctionReturn(0);
6042 }
6043 
6044 #undef __FUNCT__
6045 #define __FUNCT__ "TSVISetVariableBounds"
6046 /*@
6047    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
6048 
6049    Input Parameters:
6050 .  ts   - the TS context.
6051 .  xl   - lower bound.
6052 .  xu   - upper bound.
6053 
6054    Notes:
6055    If this routine is not called then the lower and upper bounds are set to
6056    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
6057 
6058    Level: advanced
6059 
6060 @*/
6061 PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
6062 {
6063   PetscErrorCode ierr;
6064   SNES           snes;
6065 
6066   PetscFunctionBegin;
6067   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
6068   ierr = SNESVISetVariableBounds(snes,xl,xu);CHKERRQ(ierr);
6069   PetscFunctionReturn(0);
6070 }
6071 
6072 #if defined(PETSC_HAVE_MATLAB_ENGINE)
6073 #include <mex.h>
6074 
6075 typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
6076 
6077 #undef __FUNCT__
6078 #define __FUNCT__ "TSComputeFunction_Matlab"
6079 /*
6080    TSComputeFunction_Matlab - Calls the function that has been set with
6081                          TSSetFunctionMatlab().
6082 
6083    Collective on TS
6084 
6085    Input Parameters:
6086 +  snes - the TS context
6087 -  u - input vector
6088 
6089    Output Parameter:
6090 .  y - function vector, as set by TSSetFunction()
6091 
6092    Notes:
6093    TSComputeFunction() is typically used within nonlinear solvers
6094    implementations, so most users would not generally call this routine
6095    themselves.
6096 
6097    Level: developer
6098 
6099 .keywords: TS, nonlinear, compute, function
6100 
6101 .seealso: TSSetFunction(), TSGetFunction()
6102 */
6103 PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
6104 {
6105   PetscErrorCode  ierr;
6106   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6107   int             nlhs  = 1,nrhs = 7;
6108   mxArray         *plhs[1],*prhs[7];
6109   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;
6110 
6111   PetscFunctionBegin;
6112   PetscValidHeaderSpecific(snes,TS_CLASSID,1);
6113   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
6114   PetscValidHeaderSpecific(udot,VEC_CLASSID,4);
6115   PetscValidHeaderSpecific(y,VEC_CLASSID,5);
6116   PetscCheckSameComm(snes,1,u,3);
6117   PetscCheckSameComm(snes,1,y,5);
6118 
6119   ierr = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
6120   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6121   ierr = PetscMemcpy(&lxdot,&udot,sizeof(udot));CHKERRQ(ierr);
6122   ierr = PetscMemcpy(&ly,&y,sizeof(u));CHKERRQ(ierr);
6123 
6124   prhs[0] =  mxCreateDoubleScalar((double)ls);
6125   prhs[1] =  mxCreateDoubleScalar(time);
6126   prhs[2] =  mxCreateDoubleScalar((double)lx);
6127   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6128   prhs[4] =  mxCreateDoubleScalar((double)ly);
6129   prhs[5] =  mxCreateString(sctx->funcname);
6130   prhs[6] =  sctx->ctx;
6131   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");CHKERRQ(ierr);
6132   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6133   mxDestroyArray(prhs[0]);
6134   mxDestroyArray(prhs[1]);
6135   mxDestroyArray(prhs[2]);
6136   mxDestroyArray(prhs[3]);
6137   mxDestroyArray(prhs[4]);
6138   mxDestroyArray(prhs[5]);
6139   mxDestroyArray(plhs[0]);
6140   PetscFunctionReturn(0);
6141 }
6142 
6143 
6144 #undef __FUNCT__
6145 #define __FUNCT__ "TSSetFunctionMatlab"
6146 /*
6147    TSSetFunctionMatlab - Sets the function evaluation routine and function
6148    vector for use by the TS routines in solving ODEs
6149    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
6150 
6151    Logically Collective on TS
6152 
6153    Input Parameters:
6154 +  ts - the TS context
6155 -  func - function evaluation routine
6156 
6157    Calling sequence of func:
6158 $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
6159 
6160    Level: beginner
6161 
6162 .keywords: TS, nonlinear, set, function
6163 
6164 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6165 */
6166 PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
6167 {
6168   PetscErrorCode  ierr;
6169   TSMatlabContext *sctx;
6170 
6171   PetscFunctionBegin;
6172   /* currently sctx is memory bleed */
6173   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
6174   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6175   /*
6176      This should work, but it doesn't
6177   sctx->ctx = ctx;
6178   mexMakeArrayPersistent(sctx->ctx);
6179   */
6180   sctx->ctx = mxDuplicateArray(ctx);
6181 
6182   ierr = TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);CHKERRQ(ierr);
6183   PetscFunctionReturn(0);
6184 }
6185 
6186 #undef __FUNCT__
6187 #define __FUNCT__ "TSComputeJacobian_Matlab"
6188 /*
6189    TSComputeJacobian_Matlab - Calls the function that has been set with
6190                          TSSetJacobianMatlab().
6191 
6192    Collective on TS
6193 
6194    Input Parameters:
6195 +  ts - the TS context
6196 .  u - input vector
6197 .  A, B - the matrices
6198 -  ctx - user context
6199 
6200    Level: developer
6201 
6202 .keywords: TS, nonlinear, compute, function
6203 
6204 .seealso: TSSetFunction(), TSGetFunction()
6205 @*/
6206 PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
6207 {
6208   PetscErrorCode  ierr;
6209   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6210   int             nlhs  = 2,nrhs = 9;
6211   mxArray         *plhs[2],*prhs[9];
6212   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
6213 
6214   PetscFunctionBegin;
6215   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6216   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
6217 
6218   /* call Matlab function in ctx with arguments u and y */
6219 
6220   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
6221   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6222   ierr = PetscMemcpy(&lxdot,&udot,sizeof(u));CHKERRQ(ierr);
6223   ierr = PetscMemcpy(&lA,A,sizeof(u));CHKERRQ(ierr);
6224   ierr = PetscMemcpy(&lB,B,sizeof(u));CHKERRQ(ierr);
6225 
6226   prhs[0] =  mxCreateDoubleScalar((double)ls);
6227   prhs[1] =  mxCreateDoubleScalar((double)time);
6228   prhs[2] =  mxCreateDoubleScalar((double)lx);
6229   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
6230   prhs[4] =  mxCreateDoubleScalar((double)shift);
6231   prhs[5] =  mxCreateDoubleScalar((double)lA);
6232   prhs[6] =  mxCreateDoubleScalar((double)lB);
6233   prhs[7] =  mxCreateString(sctx->funcname);
6234   prhs[8] =  sctx->ctx;
6235   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");CHKERRQ(ierr);
6236   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6237   mxDestroyArray(prhs[0]);
6238   mxDestroyArray(prhs[1]);
6239   mxDestroyArray(prhs[2]);
6240   mxDestroyArray(prhs[3]);
6241   mxDestroyArray(prhs[4]);
6242   mxDestroyArray(prhs[5]);
6243   mxDestroyArray(prhs[6]);
6244   mxDestroyArray(prhs[7]);
6245   mxDestroyArray(plhs[0]);
6246   mxDestroyArray(plhs[1]);
6247   PetscFunctionReturn(0);
6248 }
6249 
6250 
6251 #undef __FUNCT__
6252 #define __FUNCT__ "TSSetJacobianMatlab"
6253 /*
6254    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
6255    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
6256 
6257    Logically Collective on TS
6258 
6259    Input Parameters:
6260 +  ts - the TS context
6261 .  A,B - Jacobian matrices
6262 .  func - function evaluation routine
6263 -  ctx - user context
6264 
6265    Calling sequence of func:
6266 $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
6267 
6268 
6269    Level: developer
6270 
6271 .keywords: TS, nonlinear, set, function
6272 
6273 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6274 */
6275 PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
6276 {
6277   PetscErrorCode  ierr;
6278   TSMatlabContext *sctx;
6279 
6280   PetscFunctionBegin;
6281   /* currently sctx is memory bleed */
6282   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
6283   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6284   /*
6285      This should work, but it doesn't
6286   sctx->ctx = ctx;
6287   mexMakeArrayPersistent(sctx->ctx);
6288   */
6289   sctx->ctx = mxDuplicateArray(ctx);
6290 
6291   ierr = TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
6292   PetscFunctionReturn(0);
6293 }
6294 
6295 #undef __FUNCT__
6296 #define __FUNCT__ "TSMonitor_Matlab"
6297 /*
6298    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
6299 
6300    Collective on TS
6301 
6302 .seealso: TSSetFunction(), TSGetFunction()
6303 @*/
6304 PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
6305 {
6306   PetscErrorCode  ierr;
6307   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
6308   int             nlhs  = 1,nrhs = 6;
6309   mxArray         *plhs[1],*prhs[6];
6310   long long int   lx = 0,ls = 0;
6311 
6312   PetscFunctionBegin;
6313   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6314   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
6315 
6316   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
6317   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
6318 
6319   prhs[0] =  mxCreateDoubleScalar((double)ls);
6320   prhs[1] =  mxCreateDoubleScalar((double)it);
6321   prhs[2] =  mxCreateDoubleScalar((double)time);
6322   prhs[3] =  mxCreateDoubleScalar((double)lx);
6323   prhs[4] =  mxCreateString(sctx->funcname);
6324   prhs[5] =  sctx->ctx;
6325   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");CHKERRQ(ierr);
6326   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
6327   mxDestroyArray(prhs[0]);
6328   mxDestroyArray(prhs[1]);
6329   mxDestroyArray(prhs[2]);
6330   mxDestroyArray(prhs[3]);
6331   mxDestroyArray(prhs[4]);
6332   mxDestroyArray(plhs[0]);
6333   PetscFunctionReturn(0);
6334 }
6335 
6336 
6337 #undef __FUNCT__
6338 #define __FUNCT__ "TSMonitorSetMatlab"
6339 /*
6340    TSMonitorSetMatlab - Sets the monitor function from Matlab
6341 
6342    Level: developer
6343 
6344 .keywords: TS, nonlinear, set, function
6345 
6346 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
6347 */
6348 PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
6349 {
6350   PetscErrorCode  ierr;
6351   TSMatlabContext *sctx;
6352 
6353   PetscFunctionBegin;
6354   /* currently sctx is memory bleed */
6355   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
6356   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
6357   /*
6358      This should work, but it doesn't
6359   sctx->ctx = ctx;
6360   mexMakeArrayPersistent(sctx->ctx);
6361   */
6362   sctx->ctx = mxDuplicateArray(ctx);
6363 
6364   ierr = TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
6365   PetscFunctionReturn(0);
6366 }
6367 #endif
6368 
6369 #undef __FUNCT__
6370 #define __FUNCT__ "TSMonitorLGSolution"
6371 /*@C
6372    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
6373        in a time based line graph
6374 
6375    Collective on TS
6376 
6377    Input Parameters:
6378 +  ts - the TS context
6379 .  step - current time-step
6380 .  ptime - current time
6381 .  u - current solution
6382 -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()
6383 
6384    Options Database:
6385 .   -ts_monitor_lg_solution_variables
6386 
6387    Level: intermediate
6388 
6389    Notes: Each process in a parallel run displays its component solutions in a separate window
6390 
6391 .keywords: TS,  vector, monitor, view
6392 
6393 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
6394            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
6395            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
6396            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
6397 @*/
6398 PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6399 {
6400   PetscErrorCode    ierr;
6401   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
6402   const PetscScalar *yy;
6403   Vec               v;
6404 
6405   PetscFunctionBegin;
6406   if (step < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
6407   if (!step) {
6408     PetscDrawAxis axis;
6409     PetscInt      dim;
6410     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
6411     ierr = PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");CHKERRQ(ierr);
6412     if (ctx->names && !ctx->displaynames) {
6413       char      **displaynames;
6414       PetscBool flg;
6415       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
6416       ierr = PetscMalloc((dim+1)*sizeof(char*),&displaynames);CHKERRQ(ierr);
6417       ierr = PetscMemzero(displaynames,(dim+1)*sizeof(char*));CHKERRQ(ierr);
6418       ierr = PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);CHKERRQ(ierr);
6419       if (flg) {
6420         ierr = TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);CHKERRQ(ierr);
6421       }
6422       ierr = PetscStrArrayDestroy(&displaynames);CHKERRQ(ierr);
6423     }
6424     if (ctx->displaynames) {
6425       ierr = PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);CHKERRQ(ierr);
6426       ierr = PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);CHKERRQ(ierr);
6427     } else if (ctx->names) {
6428       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
6429       ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
6430       ierr = PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);CHKERRQ(ierr);
6431     } else {
6432       ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
6433       ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
6434     }
6435     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
6436   }
6437 
6438   if (!ctx->transform) v = u;
6439   else {ierr = (*ctx->transform)(ctx->transformctx,u,&v);CHKERRQ(ierr);}
6440   ierr = VecGetArrayRead(v,&yy);CHKERRQ(ierr);
6441   if (ctx->displaynames) {
6442     PetscInt i;
6443     for (i=0; i<ctx->ndisplayvariables; i++)
6444       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
6445     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);CHKERRQ(ierr);
6446   } else {
6447 #if defined(PETSC_USE_COMPLEX)
6448     PetscInt  i,n;
6449     PetscReal *yreal;
6450     ierr = VecGetLocalSize(v,&n);CHKERRQ(ierr);
6451     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
6452     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6453     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
6454     ierr = PetscFree(yreal);CHKERRQ(ierr);
6455 #else
6456     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
6457 #endif
6458   }
6459   ierr = VecRestoreArrayRead(v,&yy);CHKERRQ(ierr);
6460   if (ctx->transform) {ierr = VecDestroy(&v);CHKERRQ(ierr);}
6461 
6462   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6463     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
6464     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
6465   }
6466   PetscFunctionReturn(0);
6467 }
6468 
6469 
6470 #undef __FUNCT__
6471 #define __FUNCT__ "TSMonitorLGSetVariableNames"
6472 /*@C
6473    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6474 
6475    Collective on TS
6476 
6477    Input Parameters:
6478 +  ts - the TS context
6479 -  names - the names of the components, final string must be NULL
6480 
6481    Level: intermediate
6482 
6483    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6484 
6485 .keywords: TS,  vector, monitor, view
6486 
6487 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
6488 @*/
6489 PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
6490 {
6491   PetscErrorCode    ierr;
6492   PetscInt          i;
6493 
6494   PetscFunctionBegin;
6495   for (i=0; i<ts->numbermonitors; i++) {
6496     if (ts->monitor[i] == TSMonitorLGSolution) {
6497       ierr = TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);CHKERRQ(ierr);
6498       break;
6499     }
6500   }
6501   PetscFunctionReturn(0);
6502 }
6503 
6504 #undef __FUNCT__
6505 #define __FUNCT__ "TSMonitorLGCtxSetVariableNames"
6506 /*@C
6507    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot
6508 
6509    Collective on TS
6510 
6511    Input Parameters:
6512 +  ts - the TS context
6513 -  names - the names of the components, final string must be NULL
6514 
6515    Level: intermediate
6516 
6517 .keywords: TS,  vector, monitor, view
6518 
6519 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
6520 @*/
6521 PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
6522 {
6523   PetscErrorCode    ierr;
6524 
6525   PetscFunctionBegin;
6526   ierr = PetscStrArrayDestroy(&ctx->names);CHKERRQ(ierr);
6527   ierr = PetscStrArrayallocpy(names,&ctx->names);CHKERRQ(ierr);
6528   PetscFunctionReturn(0);
6529 }
6530 
6531 #undef __FUNCT__
6532 #define __FUNCT__ "TSMonitorLGGetVariableNames"
6533 /*@C
6534    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot
6535 
6536    Collective on TS
6537 
6538    Input Parameter:
6539 .  ts - the TS context
6540 
6541    Output Parameter:
6542 .  names - the names of the components, final string must be NULL
6543 
6544    Level: intermediate
6545 
6546    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6547 
6548 .keywords: TS,  vector, monitor, view
6549 
6550 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6551 @*/
6552 PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
6553 {
6554   PetscInt       i;
6555 
6556   PetscFunctionBegin;
6557   *names = NULL;
6558   for (i=0; i<ts->numbermonitors; i++) {
6559     if (ts->monitor[i] == TSMonitorLGSolution) {
6560       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
6561       *names = (const char *const *)ctx->names;
6562       break;
6563     }
6564   }
6565   PetscFunctionReturn(0);
6566 }
6567 
6568 #undef __FUNCT__
6569 #define __FUNCT__ "TSMonitorLGCtxSetDisplayVariables"
6570 /*@C
6571    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor
6572 
6573    Collective on TS
6574 
6575    Input Parameters:
6576 +  ctx - the TSMonitorLG context
6577 .  displaynames - the names of the components, final string must be NULL
6578 
6579    Level: intermediate
6580 
6581 .keywords: TS,  vector, monitor, view
6582 
6583 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6584 @*/
6585 PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
6586 {
6587   PetscInt          j = 0,k;
6588   PetscErrorCode    ierr;
6589 
6590   PetscFunctionBegin;
6591   if (!ctx->names) PetscFunctionReturn(0);
6592   ierr = PetscStrArrayDestroy(&ctx->displaynames);CHKERRQ(ierr);
6593   ierr = PetscStrArrayallocpy(displaynames,&ctx->displaynames);CHKERRQ(ierr);
6594   while (displaynames[j]) j++;
6595   ctx->ndisplayvariables = j;
6596   ierr = PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);CHKERRQ(ierr);
6597   ierr = PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);CHKERRQ(ierr);
6598   j = 0;
6599   while (displaynames[j]) {
6600     k = 0;
6601     while (ctx->names[k]) {
6602       PetscBool flg;
6603       ierr = PetscStrcmp(displaynames[j],ctx->names[k],&flg);CHKERRQ(ierr);
6604       if (flg) {
6605         ctx->displayvariables[j] = k;
6606         break;
6607       }
6608       k++;
6609     }
6610     j++;
6611   }
6612   PetscFunctionReturn(0);
6613 }
6614 
6615 
6616 #undef __FUNCT__
6617 #define __FUNCT__ "TSMonitorLGSetDisplayVariables"
6618 /*@C
6619    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor
6620 
6621    Collective on TS
6622 
6623    Input Parameters:
6624 +  ts - the TS context
6625 .  displaynames - the names of the components, final string must be NULL
6626 
6627    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6628 
6629    Level: intermediate
6630 
6631 .keywords: TS,  vector, monitor, view
6632 
6633 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
6634 @*/
6635 PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
6636 {
6637   PetscInt          i;
6638   PetscErrorCode    ierr;
6639 
6640   PetscFunctionBegin;
6641   for (i=0; i<ts->numbermonitors; i++) {
6642     if (ts->monitor[i] == TSMonitorLGSolution) {
6643       ierr = TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);CHKERRQ(ierr);
6644       break;
6645     }
6646   }
6647   PetscFunctionReturn(0);
6648 }
6649 
6650 #undef __FUNCT__
6651 #define __FUNCT__ "TSMonitorLGSetTransform"
6652 /*@C
6653    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed
6654 
6655    Collective on TS
6656 
6657    Input Parameters:
6658 +  ts - the TS context
6659 .  transform - the transform function
6660 .  destroy - function to destroy the optional context
6661 -  ctx - optional context used by transform function
6662 
6663    Notes: If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored
6664 
6665    Level: intermediate
6666 
6667 .keywords: TS,  vector, monitor, view
6668 
6669 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
6670 @*/
6671 PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6672 {
6673   PetscInt          i;
6674   PetscErrorCode    ierr;
6675 
6676   PetscFunctionBegin;
6677   for (i=0; i<ts->numbermonitors; i++) {
6678     if (ts->monitor[i] == TSMonitorLGSolution) {
6679       ierr = TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);CHKERRQ(ierr);
6680     }
6681   }
6682   PetscFunctionReturn(0);
6683 }
6684 
6685 #undef __FUNCT__
6686 #define __FUNCT__ "TSMonitorLGCtxSetTransform"
6687 /*@C
6688    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed
6689 
6690    Collective on TSLGCtx
6691 
6692    Input Parameters:
6693 +  ts - the TS context
6694 .  transform - the transform function
6695 .  destroy - function to destroy the optional context
6696 -  ctx - optional context used by transform function
6697 
6698    Level: intermediate
6699 
6700 .keywords: TS,  vector, monitor, view
6701 
6702 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
6703 @*/
6704 PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
6705 {
6706   PetscFunctionBegin;
6707   ctx->transform    = transform;
6708   ctx->transformdestroy = destroy;
6709   ctx->transformctx = tctx;
6710   PetscFunctionReturn(0);
6711 }
6712 
6713 #undef __FUNCT__
6714 #define __FUNCT__ "TSMonitorLGError"
6715 /*@C
6716    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
6717        in a time based line graph
6718 
6719    Collective on TS
6720 
6721    Input Parameters:
6722 +  ts - the TS context
6723 .  step - current time-step
6724 .  ptime - current time
6725 .  u - current solution
6726 -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()
6727 
6728    Level: intermediate
6729 
6730    Notes: Each process in a parallel run displays its component errors in a separate window
6731 
6732    The user must provide the solution using TSSetSolutionFunction() to use this monitor.
6733 
6734    Options Database Keys:
6735 .  -ts_monitor_lg_error - create a graphical monitor of error history
6736 
6737 .keywords: TS,  vector, monitor, view
6738 
6739 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
6740 @*/
6741 PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6742 {
6743   PetscErrorCode    ierr;
6744   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
6745   const PetscScalar *yy;
6746   Vec               y;
6747 
6748   PetscFunctionBegin;
6749   if (!step) {
6750     PetscDrawAxis axis;
6751     PetscInt      dim;
6752     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
6753     ierr = PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");CHKERRQ(ierr);
6754     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
6755     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
6756     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
6757   }
6758   ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
6759   ierr = TSComputeSolutionFunction(ts,ptime,y);CHKERRQ(ierr);
6760   ierr = VecAXPY(y,-1.0,u);CHKERRQ(ierr);
6761   ierr = VecGetArrayRead(y,&yy);CHKERRQ(ierr);
6762 #if defined(PETSC_USE_COMPLEX)
6763   {
6764     PetscReal *yreal;
6765     PetscInt  i,n;
6766     ierr = VecGetLocalSize(y,&n);CHKERRQ(ierr);
6767     ierr = PetscMalloc1(n,&yreal);CHKERRQ(ierr);
6768     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
6769     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
6770     ierr = PetscFree(yreal);CHKERRQ(ierr);
6771   }
6772 #else
6773   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
6774 #endif
6775   ierr = VecRestoreArrayRead(y,&yy);CHKERRQ(ierr);
6776   ierr = VecDestroy(&y);CHKERRQ(ierr);
6777   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
6778     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
6779     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
6780   }
6781   PetscFunctionReturn(0);
6782 }
6783 
6784 #undef __FUNCT__
6785 #define __FUNCT__ "TSMonitorLGSNESIterations"
6786 PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6787 {
6788   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6789   PetscReal      x   = ptime,y;
6790   PetscErrorCode ierr;
6791   PetscInt       its;
6792 
6793   PetscFunctionBegin;
6794   if (n < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
6795   if (!n) {
6796     PetscDrawAxis axis;
6797     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
6798     ierr = PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");CHKERRQ(ierr);
6799     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
6800     ctx->snes_its = 0;
6801   }
6802   ierr = TSGetSNESIterations(ts,&its);CHKERRQ(ierr);
6803   y    = its - ctx->snes_its;
6804   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
6805   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6806     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
6807     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
6808   }
6809   ctx->snes_its = its;
6810   PetscFunctionReturn(0);
6811 }
6812 
6813 #undef __FUNCT__
6814 #define __FUNCT__ "TSMonitorLGKSPIterations"
6815 PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
6816 {
6817   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
6818   PetscReal      x   = ptime,y;
6819   PetscErrorCode ierr;
6820   PetscInt       its;
6821 
6822   PetscFunctionBegin;
6823   if (n < 0) PetscFunctionReturn(0); /* -1 indicates interpolated solution */
6824   if (!n) {
6825     PetscDrawAxis axis;
6826     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
6827     ierr = PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");CHKERRQ(ierr);
6828     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
6829     ctx->ksp_its = 0;
6830   }
6831   ierr = TSGetKSPIterations(ts,&its);CHKERRQ(ierr);
6832   y    = its - ctx->ksp_its;
6833   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
6834   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
6835     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
6836     ierr = PetscDrawLGSave(ctx->lg);CHKERRQ(ierr);
6837   }
6838   ctx->ksp_its = its;
6839   PetscFunctionReturn(0);
6840 }
6841 
6842 #undef __FUNCT__
6843 #define __FUNCT__ "TSComputeLinearStability"
6844 /*@
6845    TSComputeLinearStability - computes the linear stability function at a point
6846 
6847    Collective on TS and Vec
6848 
6849    Input Parameters:
6850 +  ts - the TS context
6851 -  xr,xi - real and imaginary part of input arguments
6852 
6853    Output Parameters:
6854 .  yr,yi - real and imaginary part of function value
6855 
6856    Level: developer
6857 
6858 .keywords: TS, compute
6859 
6860 .seealso: TSSetRHSFunction(), TSComputeIFunction()
6861 @*/
6862 PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6863 {
6864   PetscErrorCode ierr;
6865 
6866   PetscFunctionBegin;
6867   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6868   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6869   ierr = (*ts->ops->linearstability)(ts,xr,xi,yr,yi);CHKERRQ(ierr);
6870   PetscFunctionReturn(0);
6871 }
6872 
6873 /* ------------------------------------------------------------------------*/
6874 #undef __FUNCT__
6875 #define __FUNCT__ "TSMonitorEnvelopeCtxCreate"
6876 /*@C
6877    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()
6878 
6879    Collective on TS
6880 
6881    Input Parameters:
6882 .  ts  - the ODE solver object
6883 
6884    Output Parameter:
6885 .  ctx - the context
6886 
6887    Level: intermediate
6888 
6889 .keywords: TS, monitor, line graph, residual, seealso
6890 
6891 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
6892 
6893 @*/
6894 PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6895 {
6896   PetscErrorCode ierr;
6897 
6898   PetscFunctionBegin;
6899   ierr = PetscNew(ctx);CHKERRQ(ierr);
6900   PetscFunctionReturn(0);
6901 }
6902 
6903 #undef __FUNCT__
6904 #define __FUNCT__ "TSMonitorEnvelope"
6905 /*@C
6906    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution
6907 
6908    Collective on TS
6909 
6910    Input Parameters:
6911 +  ts - the TS context
6912 .  step - current time-step
6913 .  ptime - current time
6914 .  u  - current solution
6915 -  dctx - the envelope context
6916 
6917    Options Database:
6918 .  -ts_monitor_envelope
6919 
6920    Level: intermediate
6921 
6922    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope
6923 
6924 .keywords: TS,  vector, monitor, view
6925 
6926 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
6927 @*/
6928 PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
6929 {
6930   PetscErrorCode       ierr;
6931   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;
6932 
6933   PetscFunctionBegin;
6934   if (!ctx->max) {
6935     ierr = VecDuplicate(u,&ctx->max);CHKERRQ(ierr);
6936     ierr = VecDuplicate(u,&ctx->min);CHKERRQ(ierr);
6937     ierr = VecCopy(u,ctx->max);CHKERRQ(ierr);
6938     ierr = VecCopy(u,ctx->min);CHKERRQ(ierr);
6939   } else {
6940     ierr = VecPointwiseMax(ctx->max,u,ctx->max);CHKERRQ(ierr);
6941     ierr = VecPointwiseMin(ctx->min,u,ctx->min);CHKERRQ(ierr);
6942   }
6943   PetscFunctionReturn(0);
6944 }
6945 
6946 
6947 #undef __FUNCT__
6948 #define __FUNCT__ "TSMonitorEnvelopeGetBounds"
6949 /*@C
6950    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution
6951 
6952    Collective on TS
6953 
6954    Input Parameter:
6955 .  ts - the TS context
6956 
6957    Output Parameter:
6958 +  max - the maximum values
6959 -  min - the minimum values
6960 
6961    Notes: If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored
6962 
6963    Level: intermediate
6964 
6965 .keywords: TS,  vector, monitor, view
6966 
6967 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6968 @*/
6969 PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
6970 {
6971   PetscInt i;
6972 
6973   PetscFunctionBegin;
6974   if (max) *max = NULL;
6975   if (min) *min = NULL;
6976   for (i=0; i<ts->numbermonitors; i++) {
6977     if (ts->monitor[i] == TSMonitorEnvelope) {
6978       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
6979       if (max) *max = ctx->max;
6980       if (min) *min = ctx->min;
6981       break;
6982     }
6983   }
6984   PetscFunctionReturn(0);
6985 }
6986 
6987 #undef __FUNCT__
6988 #define __FUNCT__ "TSMonitorEnvelopeCtxDestroy"
6989 /*@C
6990    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().
6991 
6992    Collective on TSMonitorEnvelopeCtx
6993 
6994    Input Parameter:
6995 .  ctx - the monitor context
6996 
6997    Level: intermediate
6998 
6999 .keywords: TS, monitor, line graph, destroy
7000 
7001 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
7002 @*/
7003 PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
7004 {
7005   PetscErrorCode ierr;
7006 
7007   PetscFunctionBegin;
7008   ierr = VecDestroy(&(*ctx)->min);CHKERRQ(ierr);
7009   ierr = VecDestroy(&(*ctx)->max);CHKERRQ(ierr);
7010   ierr = PetscFree(*ctx);CHKERRQ(ierr);
7011   PetscFunctionReturn(0);
7012 }
7013 
7014 #undef __FUNCT__
7015 #define __FUNCT__ "TSRollBack"
7016 /*@
7017    TSRollBack - Rolls back one time step
7018 
7019    Collective on TS
7020 
7021    Input Parameter:
7022 .  ts - the TS context obtained from TSCreate()
7023 
7024    Level: advanced
7025 
7026 .keywords: TS, timestep, rollback
7027 
7028 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
7029 @*/
7030 PetscErrorCode  TSRollBack(TS ts)
7031 {
7032   PetscErrorCode ierr;
7033 
7034   PetscFunctionBegin;
7035   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7036   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
7037   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
7038   ierr = (*ts->ops->rollback)(ts);CHKERRQ(ierr);
7039   ts->time_step = ts->ptime - ts->ptime_prev;
7040   ts->ptime = ts->ptime_prev;
7041   ts->ptime_prev = ts->ptime_prev_rollback;
7042   ts->steps--; ts->total_steps--;
7043   ts->steprollback = PETSC_TRUE;
7044   PetscFunctionReturn(0);
7045 }
7046 
7047 #undef __FUNCT__
7048 #define __FUNCT__ "TSGetStages"
7049 /*@
7050    TSGetStages - Get the number of stages and stage values
7051 
7052    Input Parameter:
7053 .  ts - the TS context obtained from TSCreate()
7054 
7055    Level: advanced
7056 
7057 .keywords: TS, getstages
7058 
7059 .seealso: TSCreate()
7060 @*/
7061 PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
7062 {
7063   PetscErrorCode ierr;
7064 
7065   PetscFunctionBegin;
7066   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7067   PetscValidPointer(ns,2);
7068 
7069   if (!ts->ops->getstages) *ns=0;
7070   else {
7071     ierr = (*ts->ops->getstages)(ts,ns,Y);CHKERRQ(ierr);
7072   }
7073   PetscFunctionReturn(0);
7074 }
7075 
7076 #undef __FUNCT__
7077 #define __FUNCT__ "TSComputeIJacobianDefaultColor"
7078 /*@C
7079   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
7080 
7081   Collective on SNES
7082 
7083   Input Parameters:
7084 + ts - the TS context
7085 . t - current timestep
7086 . U - state vector
7087 . Udot - time derivative of state vector
7088 . shift - shift to apply, see note below
7089 - ctx - an optional user context
7090 
7091   Output Parameters:
7092 + J - Jacobian matrix (not altered in this routine)
7093 - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
7094 
7095   Level: intermediate
7096 
7097   Notes:
7098   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
7099 
7100   dF/dU + shift*dF/dUdot
7101 
7102   Most users should not need to explicitly call this routine, as it
7103   is used internally within the nonlinear solvers.
7104 
7105   This will first try to get the coloring from the DM.  If the DM type has no coloring
7106   routine, then it will try to get the coloring from the matrix.  This requires that the
7107   matrix have nonzero entries precomputed.
7108 
7109 .keywords: TS, finite differences, Jacobian, coloring, sparse
7110 .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
7111 @*/
7112 PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
7113 {
7114   SNES           snes;
7115   MatFDColoring  color;
7116   PetscBool      hascolor, matcolor = PETSC_FALSE;
7117   PetscErrorCode ierr;
7118 
7119   PetscFunctionBegin;
7120   ierr = PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);CHKERRQ(ierr);
7121   ierr = PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);CHKERRQ(ierr);
7122   if (!color) {
7123     DM         dm;
7124     ISColoring iscoloring;
7125 
7126     ierr = TSGetDM(ts, &dm);CHKERRQ(ierr);
7127     ierr = DMHasColoring(dm, &hascolor);CHKERRQ(ierr);
7128     if (hascolor && !matcolor) {
7129       ierr = DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);CHKERRQ(ierr);
7130       ierr = MatFDColoringCreate(B, iscoloring, &color);CHKERRQ(ierr);
7131       ierr = MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);CHKERRQ(ierr);
7132       ierr = MatFDColoringSetFromOptions(color);CHKERRQ(ierr);
7133       ierr = MatFDColoringSetUp(B, iscoloring, color);CHKERRQ(ierr);
7134       ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr);
7135     } else {
7136       MatColoring mc;
7137 
7138       ierr = MatColoringCreate(B, &mc);CHKERRQ(ierr);
7139       ierr = MatColoringSetDistance(mc, 2);CHKERRQ(ierr);
7140       ierr = MatColoringSetType(mc, MATCOLORINGSL);CHKERRQ(ierr);
7141       ierr = MatColoringSetFromOptions(mc);CHKERRQ(ierr);
7142       ierr = MatColoringApply(mc, &iscoloring);CHKERRQ(ierr);
7143       ierr = MatColoringDestroy(&mc);CHKERRQ(ierr);
7144       ierr = MatFDColoringCreate(B, iscoloring, &color);CHKERRQ(ierr);
7145       ierr = MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);CHKERRQ(ierr);
7146       ierr = MatFDColoringSetFromOptions(color);CHKERRQ(ierr);
7147       ierr = MatFDColoringSetUp(B, iscoloring, color);CHKERRQ(ierr);
7148       ierr = ISColoringDestroy(&iscoloring);CHKERRQ(ierr);
7149     }
7150     ierr = PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);CHKERRQ(ierr);
7151     ierr = PetscObjectDereference((PetscObject) color);CHKERRQ(ierr);
7152   }
7153   ierr = TSGetSNES(ts, &snes);CHKERRQ(ierr);
7154   ierr = MatFDColoringApply(B, color, U, snes);CHKERRQ(ierr);
7155   if (J != B) {
7156     ierr = MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
7157     ierr = MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);CHKERRQ(ierr);
7158   }
7159   PetscFunctionReturn(0);
7160 }
7161 
7162 #undef __FUNCT__
7163 #define __FUNCT__ "TSSetFunctionDomainError"
7164 /*@
7165     TSSetFunctionDomainError - Set the function testing if the current state vector is valid
7166 
7167     Input Parameters:
7168     ts - the TS context
7169     func - function called within TSFunctionDomainError
7170 
7171     Level: intermediate
7172 
7173 .keywords: TS, state, domain
7174 .seealso: TSAdaptCheckStage(), TSFunctionDomainError()
7175 @*/
7176 
7177 PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
7178 {
7179   PetscFunctionBegin;
7180   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
7181   ts->functiondomainerror = func;
7182   PetscFunctionReturn(0);
7183 }
7184 
7185 #undef __FUNCT__
7186 #define __FUNCT__ "TSFunctionDomainError"
7187 /*@
7188     TSFunctionDomainError - Check if the current state is valid
7189 
7190     Input Parameters:
7191     ts - the TS context
7192     stagetime - time of the simulation
7193     Y - state vector to check.
7194 
7195     Output Parameter:
7196     accept - Set to PETSC_FALSE if the current state vector is valid.
7197 
7198     Note:
7199     This function should be used to ensure the state is in a valid part of the space.
7200     For example, one can ensure here all values are positive.
7201 
7202     Level: advanced
7203 @*/
7204 PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
7205 {
7206   PetscErrorCode ierr;
7207 
7208   PetscFunctionBegin;
7209 
7210   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
7211   *accept = PETSC_TRUE;
7212   if (ts->functiondomainerror) {
7213     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
7214   }
7215   PetscFunctionReturn(0);
7216 }
7217 
7218 #undef  __FUNCT__
7219 #define __FUNCT__ "TSClone"
7220 /*@C
7221   TSClone - This function clones a time step object.
7222 
7223   Collective on MPI_Comm
7224 
7225   Input Parameter:
7226 . tsin    - The input TS
7227 
7228   Output Parameter:
7229 . tsout   - The output TS (cloned)
7230 
7231   Notes:
7232   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.
7233 
7234   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);
7235 
7236   Level: developer
7237 
7238 .keywords: TS, clone
7239 .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
7240 @*/
7241 PetscErrorCode  TSClone(TS tsin, TS *tsout)
7242 {
7243   TS             t;
7244   PetscErrorCode ierr;
7245   SNES           snes_start;
7246   DM             dm;
7247   TSType         type;
7248 
7249   PetscFunctionBegin;
7250   PetscValidPointer(tsin,1);
7251   *tsout = NULL;
7252 
7253   ierr = PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);CHKERRQ(ierr);
7254 
7255   /* General TS description */
7256   t->numbermonitors    = 0;
7257   t->setupcalled       = 0;
7258   t->ksp_its           = 0;
7259   t->snes_its          = 0;
7260   t->nwork             = 0;
7261   t->rhsjacobian.time  = -1e20;
7262   t->rhsjacobian.scale = 1.;
7263   t->ijacobian.shift   = 1.;
7264 
7265   ierr = TSGetSNES(tsin,&snes_start);CHKERRQ(ierr);
7266   ierr = TSSetSNES(t,snes_start);CHKERRQ(ierr);
7267 
7268   ierr = TSGetDM(tsin,&dm);CHKERRQ(ierr);
7269   ierr = TSSetDM(t,dm);CHKERRQ(ierr);
7270 
7271   t->adapt = tsin->adapt;
7272   ierr = PetscObjectReference((PetscObject)t->adapt);CHKERRQ(ierr);
7273 
7274   t->problem_type      = tsin->problem_type;
7275   t->ptime             = tsin->ptime;
7276   t->time_step         = tsin->time_step;
7277   t->max_time          = tsin->max_time;
7278   t->steps             = tsin->steps;
7279   t->max_steps         = tsin->max_steps;
7280   t->equation_type     = tsin->equation_type;
7281   t->atol              = tsin->atol;
7282   t->rtol              = tsin->rtol;
7283   t->max_snes_failures = tsin->max_snes_failures;
7284   t->max_reject        = tsin->max_reject;
7285   t->errorifstepfailed = tsin->errorifstepfailed;
7286 
7287   ierr = TSGetType(tsin,&type);CHKERRQ(ierr);
7288   ierr = TSSetType(t,type);CHKERRQ(ierr);
7289 
7290   t->vec_sol           = NULL;
7291 
7292   t->cfltime          = tsin->cfltime;
7293   t->cfltime_local    = tsin->cfltime_local;
7294   t->exact_final_time = tsin->exact_final_time;
7295 
7296   ierr = PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));CHKERRQ(ierr);
7297 
7298   if (((PetscObject)tsin)->fortran_func_pointers) {
7299     PetscInt i;
7300     ierr = PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);CHKERRQ(ierr);
7301     for (i=0; i<10; i++) {
7302       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
7303     }
7304   }
7305   *tsout = t;
7306   PetscFunctionReturn(0);
7307 }
7308