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