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