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