xref: /petsc/src/ts/interface/ts.c (revision a4494fc1234a766fa0fae5f23a8bf26e5b6ec6e1)
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_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
11 
12 const char *const TSExactFinalTimeOptions[] = {"STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};
13 
14 #undef __FUNCT__
15 #define __FUNCT__ "TSSetTypeFromOptions"
16 /*
17   TSSetTypeFromOptions - Sets the type of ts from user options.
18 
19   Collective on TS
20 
21   Input Parameter:
22 . ts - The ts
23 
24   Level: intermediate
25 
26 .keywords: TS, set, options, database, type
27 .seealso: TSSetFromOptions(), TSSetType()
28 */
29 static PetscErrorCode TSSetTypeFromOptions(TS ts)
30 {
31   PetscBool      opt;
32   const char     *defaultType;
33   char           typeName[256];
34   PetscErrorCode ierr;
35 
36   PetscFunctionBegin;
37   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
38   else defaultType = TSEULER;
39 
40   if (!TSRegisterAllCalled) {ierr = TSRegisterAll(NULL);CHKERRQ(ierr);}
41   ierr = PetscOptionsList("-ts_type", "TS method"," TSSetType", TSList, defaultType, typeName, 256, &opt);CHKERRQ(ierr);
42   if (opt) {
43     ierr = TSSetType(ts, typeName);CHKERRQ(ierr);
44   } else {
45     ierr = TSSetType(ts, defaultType);CHKERRQ(ierr);
46   }
47   PetscFunctionReturn(0);
48 }
49 
50 struct _n_TSMonitorDrawCtx {
51   PetscViewer viewer;
52   Vec         initialsolution;
53   PetscBool   showinitial;
54   PetscInt    howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
55   PetscBool   showtimestepandtime;
56   int         color;
57 };
58 
59 #undef __FUNCT__
60 #define __FUNCT__ "TSSetFromOptions"
61 /*@
62    TSSetFromOptions - Sets various TS parameters from user options.
63 
64    Collective on TS
65 
66    Input Parameter:
67 .  ts - the TS context obtained from TSCreate()
68 
69    Options Database Keys:
70 +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSGL, TSSSP
71 .  -ts_max_steps maxsteps - maximum number of time-steps to take
72 .  -ts_final_time time - maximum time to compute to
73 .  -ts_dt dt - initial time step
74 .  -ts_monitor - print information at each timestep
75 .  -ts_monitor_lg_timestep - Monitor timestep size graphically
76 .  -ts_monitor_lg_solution - Monitor solution graphically
77 .  -ts_monitor_lg_error - Monitor error graphically
78 .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
79 .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
80 .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
81 .  -ts_monitor_draw_solution - Monitor solution graphically
82 .  -ts_monitor_draw_solution_phase - Monitor solution graphically with phase diagram
83 .  -ts_monitor_draw_error - Monitor error graphically
84 .  -ts_monitor_solution_binary <filename> - Save each solution to a binary file
85 -  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts
86 
87    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified
88 
89    Level: beginner
90 
91 .keywords: TS, timestep, set, options, database
92 
93 .seealso: TSGetType()
94 @*/
95 PetscErrorCode  TSSetFromOptions(TS ts)
96 {
97   PetscBool              opt,flg;
98   PetscErrorCode         ierr;
99   PetscViewer            monviewer;
100   char                   monfilename[PETSC_MAX_PATH_LEN];
101   SNES                   snes;
102   TSAdapt                adapt;
103   PetscReal              time_step;
104   TSExactFinalTimeOption eftopt;
105   char                   dir[16];
106 
107   PetscFunctionBegin;
108   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
109   ierr = PetscObjectOptionsBegin((PetscObject)ts);CHKERRQ(ierr);
110   /* Handle TS type options */
111   ierr = TSSetTypeFromOptions(ts);CHKERRQ(ierr);
112 
113   /* Handle generic TS options */
114   ierr = PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);CHKERRQ(ierr);
115   ierr = PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);CHKERRQ(ierr);
116   ierr = PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);CHKERRQ(ierr);
117   ierr = PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);CHKERRQ(ierr);
118   if (flg) {
119     ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
120   }
121   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);
122   if (flg) {ierr = TSSetExactFinalTime(ts,eftopt);CHKERRQ(ierr);}
123   ierr = PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);CHKERRQ(ierr);
124   ierr = PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);CHKERRQ(ierr);
125   ierr = PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);CHKERRQ(ierr);
126   ierr = PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);CHKERRQ(ierr);
127   ierr = PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);CHKERRQ(ierr);
128 
129   /* Monitor options */
130   ierr = PetscOptionsString("-ts_monitor","Monitor timestep size","TSMonitorDefault","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
131   if (flg) {
132     ierr = PetscViewerASCIIOpen(PetscObjectComm((PetscObject)ts),monfilename,&monviewer);CHKERRQ(ierr);
133     ierr = TSMonitorSet(ts,TSMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
134   }
135   ierr = PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
136   if (flg) {ierr = PetscPythonMonitorSet((PetscObject)ts,monfilename);CHKERRQ(ierr);}
137 
138   ierr = PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);CHKERRQ(ierr);
139   if (opt) {
140     TSMonitorLGCtx ctx;
141     PetscInt       howoften = 1;
142 
143     ierr = PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);CHKERRQ(ierr);
144     ierr = TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
145     ierr = TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
146   }
147   ierr = PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);CHKERRQ(ierr);
148   if (opt) {
149     TSMonitorLGCtx ctx;
150     PetscInt       howoften = 1;
151 
152     ierr = PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
153     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
154     ierr = TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
155   }
156   ierr = PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);CHKERRQ(ierr);
157   if (opt) {
158     TSMonitorLGCtx ctx;
159     PetscInt       howoften = 1;
160 
161     ierr = PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);CHKERRQ(ierr);
162     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
163     ierr = TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
164   }
165   ierr = PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);CHKERRQ(ierr);
166   if (opt) {
167     TSMonitorLGCtx ctx;
168     PetscInt       howoften = 1;
169 
170     ierr = PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
171     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
172     ierr = TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
173   }
174   ierr = PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);CHKERRQ(ierr);
175   if (opt) {
176     TSMonitorLGCtx ctx;
177     PetscInt       howoften = 1;
178 
179     ierr = PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);CHKERRQ(ierr);
180     ierr = TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);CHKERRQ(ierr);
181     ierr = TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);CHKERRQ(ierr);
182   }
183   ierr = PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);CHKERRQ(ierr);
184   if (opt) {
185     TSMonitorSPEigCtx ctx;
186     PetscInt          howoften = 1;
187 
188     ierr = PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);CHKERRQ(ierr);
189     ierr = TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
190     ierr = TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);CHKERRQ(ierr);
191   }
192   opt  = PETSC_FALSE;
193   ierr = PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);CHKERRQ(ierr);
194   if (opt) {
195     TSMonitorDrawCtx ctx;
196     PetscInt         howoften = 1;
197 
198     ierr = PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);CHKERRQ(ierr);
199     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
200     ierr = TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
201   }
202   opt  = PETSC_FALSE;
203   ierr = PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);CHKERRQ(ierr);
204   if (opt) {
205     TSMonitorDrawCtx ctx;
206     PetscReal        bounds[4];
207     PetscInt         n = 4;
208     PetscDraw        draw;
209 
210     ierr = PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);CHKERRQ(ierr);
211     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
212     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,1,&ctx);CHKERRQ(ierr);
213     ierr = PetscViewerDrawGetDraw(ctx->viewer,0,&draw);CHKERRQ(ierr);
214     ierr = PetscDrawClear(draw);CHKERRQ(ierr);
215     ierr = PetscDrawSetCoordinates(draw,bounds[0],bounds[1],bounds[2],bounds[3]);CHKERRQ(ierr);
216     ierr = TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
217   }
218   opt  = PETSC_FALSE;
219   ierr = PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);CHKERRQ(ierr);
220   if (opt) {
221     TSMonitorDrawCtx ctx;
222     PetscInt         howoften = 1;
223 
224     ierr = PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);CHKERRQ(ierr);
225     ierr = TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);CHKERRQ(ierr);
226     ierr = TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);CHKERRQ(ierr);
227   }
228   opt  = PETSC_FALSE;
229   ierr = PetscOptionsString("-ts_monitor_solution_binary","Save each solution to a binary file","TSMonitorSolutionBinary",0,monfilename,PETSC_MAX_PATH_LEN,&flg);CHKERRQ(ierr);
230   if (flg) {
231     PetscViewer ctx;
232     if (monfilename[0]) {
233       ierr = PetscViewerBinaryOpen(PetscObjectComm((PetscObject)ts),monfilename,FILE_MODE_WRITE,&ctx);CHKERRQ(ierr);
234       ierr = TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);CHKERRQ(ierr);
235     } else {
236       ctx = PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)ts));
237       ierr = TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))NULL);CHKERRQ(ierr);
238     }
239   }
240   opt  = PETSC_FALSE;
241   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);
242   if (flg) {
243     const char *ptr,*ptr2;
244     char       *filetemplate;
245     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
246     /* Do some cursory validation of the input. */
247     ierr = PetscStrstr(monfilename,"%",(char**)&ptr);CHKERRQ(ierr);
248     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
249     for (ptr++; ptr && *ptr; ptr++) {
250       ierr = PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);CHKERRQ(ierr);
251       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");
252       if (ptr2) break;
253     }
254     ierr = PetscStrallocpy(monfilename,&filetemplate);CHKERRQ(ierr);
255     ierr = TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);CHKERRQ(ierr);
256   }
257 
258   ierr = PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);CHKERRQ(ierr);
259   if (flg) {
260     TSMonitorDMDARayCtx *rayctx;
261     int                 ray = 0;
262     DMDADirection       ddir;
263     DM                  da;
264     PetscMPIInt         rank;
265 
266     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
267     if (dir[0] == 'x') ddir = DMDA_X;
268     else if (dir[0] == 'y') ddir = DMDA_Y;
269     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
270     sscanf(dir+2,"%d",&ray);
271 
272     ierr = PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);CHKERRQ(ierr);
273     ierr = PetscNew(TSMonitorDMDARayCtx,&rayctx);CHKERRQ(ierr);
274     ierr = TSGetDM(ts,&da);CHKERRQ(ierr);
275     ierr = DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);CHKERRQ(ierr);
276     ierr = MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);CHKERRQ(ierr);
277     if (!rank) {
278       ierr = PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);CHKERRQ(ierr);
279     }
280     ierr = TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);CHKERRQ(ierr);
281   }
282 
283   ierr = TSGetTSAdapt(ts,&adapt);CHKERRQ(ierr);
284   ierr = TSAdaptSetFromOptions(adapt);CHKERRQ(ierr);
285 
286   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
287   if (ts->problem_type == TS_LINEAR) {ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);}
288 
289   /* Handle specific TS options */
290   if (ts->ops->setfromoptions) {
291     ierr = (*ts->ops->setfromoptions)(ts);CHKERRQ(ierr);
292   }
293 
294   /* process any options handlers added with PetscObjectAddOptionsHandler() */
295   ierr = PetscObjectProcessOptionsHandlers((PetscObject)ts);CHKERRQ(ierr);
296   ierr = PetscOptionsEnd();CHKERRQ(ierr);
297   PetscFunctionReturn(0);
298 }
299 
300 #undef __FUNCT__
301 #undef __FUNCT__
302 #define __FUNCT__ "TSComputeRHSJacobian"
303 /*@
304    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
305       set with TSSetRHSJacobian().
306 
307    Collective on TS and Vec
308 
309    Input Parameters:
310 +  ts - the TS context
311 .  t - current timestep
312 -  U - input vector
313 
314    Output Parameters:
315 +  A - Jacobian matrix
316 .  B - optional preconditioning matrix
317 -  flag - flag indicating matrix structure
318 
319    Notes:
320    Most users should not need to explicitly call this routine, as it
321    is used internally within the nonlinear solvers.
322 
323    See KSPSetOperators() for important information about setting the
324    flag parameter.
325 
326    Level: developer
327 
328 .keywords: SNES, compute, Jacobian, matrix
329 
330 .seealso:  TSSetRHSJacobian(), KSPSetOperators()
331 @*/
332 PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg)
333 {
334   PetscErrorCode ierr;
335   PetscInt       Ustate;
336   DM             dm;
337   DMTS           tsdm;
338   TSRHSJacobian  rhsjacobianfunc;
339   void           *ctx;
340   TSIJacobian    ijacobianfunc;
341 
342   PetscFunctionBegin;
343   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
344   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
345   PetscCheckSameComm(ts,1,U,3);
346   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
347   ierr = DMGetDMTS(dm,&tsdm);CHKERRQ(ierr);
348   ierr = DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);CHKERRQ(ierr);
349   ierr = DMTSGetIJacobian(dm,&ijacobianfunc,NULL);CHKERRQ(ierr);
350   ierr = PetscObjectStateQuery((PetscObject)U,&Ustate);CHKERRQ(ierr);
351   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate))) {
352     *flg = ts->rhsjacobian.mstructure;
353     PetscFunctionReturn(0);
354   }
355 
356   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
357 
358   if (rhsjacobianfunc) {
359     ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);CHKERRQ(ierr);
360     *flg = DIFFERENT_NONZERO_PATTERN;
361     PetscStackPush("TS user Jacobian function");
362     ierr = (*rhsjacobianfunc)(ts,t,U,A,B,flg,ctx);CHKERRQ(ierr);
363     PetscStackPop;
364     ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);CHKERRQ(ierr);
365     /* make sure user returned a correct Jacobian and preconditioner */
366     PetscValidHeaderSpecific(*A,MAT_CLASSID,4);
367     PetscValidHeaderSpecific(*B,MAT_CLASSID,5);
368   } else {
369     ierr = MatZeroEntries(*A);CHKERRQ(ierr);
370     if (*A != *B) {ierr = MatZeroEntries(*B);CHKERRQ(ierr);}
371     *flg = SAME_NONZERO_PATTERN;
372   }
373   ts->rhsjacobian.time       = t;
374   ts->rhsjacobian.X          = U;
375   ierr                       = PetscObjectStateQuery((PetscObject)U,&ts->rhsjacobian.Xstate);CHKERRQ(ierr);
376   ts->rhsjacobian.mstructure = *flg;
377   PetscFunctionReturn(0);
378 }
379 
380 #undef __FUNCT__
381 #define __FUNCT__ "TSComputeRHSFunction"
382 /*@
383    TSComputeRHSFunction - Evaluates the right-hand-side function.
384 
385    Collective on TS and Vec
386 
387    Input Parameters:
388 +  ts - the TS context
389 .  t - current time
390 -  U - state vector
391 
392    Output Parameter:
393 .  y - right hand side
394 
395    Note:
396    Most users should not need to explicitly call this routine, as it
397    is used internally within the nonlinear solvers.
398 
399    Level: developer
400 
401 .keywords: TS, compute
402 
403 .seealso: TSSetRHSFunction(), TSComputeIFunction()
404 @*/
405 PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
406 {
407   PetscErrorCode ierr;
408   TSRHSFunction  rhsfunction;
409   TSIFunction    ifunction;
410   void           *ctx;
411   DM             dm;
412 
413   PetscFunctionBegin;
414   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
415   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
416   PetscValidHeaderSpecific(y,VEC_CLASSID,4);
417   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
418   ierr = DMTSGetRHSFunction(dm,&rhsfunction,&ctx);CHKERRQ(ierr);
419   ierr = DMTSGetIFunction(dm,&ifunction,NULL);CHKERRQ(ierr);
420 
421   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
422 
423   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
424   if (rhsfunction) {
425     PetscStackPush("TS user right-hand-side function");
426     ierr = (*rhsfunction)(ts,t,U,y,ctx);CHKERRQ(ierr);
427     PetscStackPop;
428   } else {
429     ierr = VecZeroEntries(y);CHKERRQ(ierr);
430   }
431 
432   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);CHKERRQ(ierr);
433   PetscFunctionReturn(0);
434 }
435 
436 #undef __FUNCT__
437 #define __FUNCT__ "TSComputeSolutionFunction"
438 /*@
439    TSComputeSolutionFunction - Evaluates the solution function.
440 
441    Collective on TS and Vec
442 
443    Input Parameters:
444 +  ts - the TS context
445 -  t - current time
446 
447    Output Parameter:
448 .  U - the solution
449 
450    Note:
451    Most users should not need to explicitly call this routine, as it
452    is used internally within the nonlinear solvers.
453 
454    Level: developer
455 
456 .keywords: TS, compute
457 
458 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
459 @*/
460 PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
461 {
462   PetscErrorCode     ierr;
463   TSSolutionFunction solutionfunction;
464   void               *ctx;
465   DM                 dm;
466 
467   PetscFunctionBegin;
468   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
469   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
470   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
471   ierr = DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);CHKERRQ(ierr);
472 
473   if (solutionfunction) {
474     PetscStackPush("TS user solution function");
475     ierr = (*solutionfunction)(ts,t,U,ctx);CHKERRQ(ierr);
476     PetscStackPop;
477   }
478   PetscFunctionReturn(0);
479 }
480 #undef __FUNCT__
481 #define __FUNCT__ "TSComputeForcingFunction"
482 /*@
483    TSComputeForcingFunction - Evaluates the forcing function.
484 
485    Collective on TS and Vec
486 
487    Input Parameters:
488 +  ts - the TS context
489 -  t - current time
490 
491    Output Parameter:
492 .  U - the function value
493 
494    Note:
495    Most users should not need to explicitly call this routine, as it
496    is used internally within the nonlinear solvers.
497 
498    Level: developer
499 
500 .keywords: TS, compute
501 
502 .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
503 @*/
504 PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
505 {
506   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
507   void               *ctx;
508   DM                 dm;
509 
510   PetscFunctionBegin;
511   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
512   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
513   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
514   ierr = DMTSGetForcingFunction(dm,&forcing,&ctx);CHKERRQ(ierr);
515 
516   if (forcing) {
517     PetscStackPush("TS user forcing function");
518     ierr = (*forcing)(ts,t,U,ctx);CHKERRQ(ierr);
519     PetscStackPop;
520   }
521   PetscFunctionReturn(0);
522 }
523 
524 #undef __FUNCT__
525 #define __FUNCT__ "TSGetRHSVec_Private"
526 static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
527 {
528   Vec            F;
529   PetscErrorCode ierr;
530 
531   PetscFunctionBegin;
532   *Frhs = NULL;
533   ierr  = TSGetIFunction(ts,&F,NULL,NULL);CHKERRQ(ierr);
534   if (!ts->Frhs) {
535     ierr = VecDuplicate(F,&ts->Frhs);CHKERRQ(ierr);
536   }
537   *Frhs = ts->Frhs;
538   PetscFunctionReturn(0);
539 }
540 
541 #undef __FUNCT__
542 #define __FUNCT__ "TSGetRHSMats_Private"
543 static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
544 {
545   Mat            A,B;
546   PetscErrorCode ierr;
547 
548   PetscFunctionBegin;
549   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
550   if (Arhs) {
551     if (!ts->Arhs) {
552       ierr = MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);CHKERRQ(ierr);
553     }
554     *Arhs = ts->Arhs;
555   }
556   if (Brhs) {
557     if (!ts->Brhs) {
558       ierr = MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);CHKERRQ(ierr);
559     }
560     *Brhs = ts->Brhs;
561   }
562   PetscFunctionReturn(0);
563 }
564 
565 #undef __FUNCT__
566 #define __FUNCT__ "TSComputeIFunction"
567 /*@
568    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
569 
570    Collective on TS and Vec
571 
572    Input Parameters:
573 +  ts - the TS context
574 .  t - current time
575 .  U - state vector
576 .  Udot - time derivative of state vector
577 -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
578 
579    Output Parameter:
580 .  Y - right hand side
581 
582    Note:
583    Most users should not need to explicitly call this routine, as it
584    is used internally within the nonlinear solvers.
585 
586    If the user did did not write their equations in implicit form, this
587    function recasts them in implicit form.
588 
589    Level: developer
590 
591 .keywords: TS, compute
592 
593 .seealso: TSSetIFunction(), TSComputeRHSFunction()
594 @*/
595 PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
596 {
597   PetscErrorCode ierr;
598   TSIFunction    ifunction;
599   TSRHSFunction  rhsfunction;
600   void           *ctx;
601   DM             dm;
602 
603   PetscFunctionBegin;
604   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
605   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
606   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
607   PetscValidHeaderSpecific(Y,VEC_CLASSID,5);
608 
609   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
610   ierr = DMTSGetIFunction(dm,&ifunction,&ctx);CHKERRQ(ierr);
611   ierr = DMTSGetRHSFunction(dm,&rhsfunction,NULL);CHKERRQ(ierr);
612 
613   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
614 
615   ierr = PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
616   if (ifunction) {
617     PetscStackPush("TS user implicit function");
618     ierr = (*ifunction)(ts,t,U,Udot,Y,ctx);CHKERRQ(ierr);
619     PetscStackPop;
620   }
621   if (imex) {
622     if (!ifunction) {
623       ierr = VecCopy(Udot,Y);CHKERRQ(ierr);
624     }
625   } else if (rhsfunction) {
626     if (ifunction) {
627       Vec Frhs;
628       ierr = TSGetRHSVec_Private(ts,&Frhs);CHKERRQ(ierr);
629       ierr = TSComputeRHSFunction(ts,t,U,Frhs);CHKERRQ(ierr);
630       ierr = VecAXPY(Y,-1,Frhs);CHKERRQ(ierr);
631     } else {
632       ierr = TSComputeRHSFunction(ts,t,U,Y);CHKERRQ(ierr);
633       ierr = VecAYPX(Y,-1,Udot);CHKERRQ(ierr);
634     }
635   }
636   ierr = PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);CHKERRQ(ierr);
637   PetscFunctionReturn(0);
638 }
639 
640 #undef __FUNCT__
641 #define __FUNCT__ "TSComputeIJacobian"
642 /*@
643    TSComputeIJacobian - Evaluates the Jacobian of the DAE
644 
645    Collective on TS and Vec
646 
647    Input
648       Input Parameters:
649 +  ts - the TS context
650 .  t - current timestep
651 .  U - state vector
652 .  Udot - time derivative of state vector
653 .  shift - shift to apply, see note below
654 -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
655 
656    Output Parameters:
657 +  A - Jacobian matrix
658 .  B - optional preconditioning matrix
659 -  flag - flag indicating matrix structure
660 
661    Notes:
662    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
663 
664    dF/dU + shift*dF/dUdot
665 
666    Most users should not need to explicitly call this routine, as it
667    is used internally within the nonlinear solvers.
668 
669    Level: developer
670 
671 .keywords: TS, compute, Jacobian, matrix
672 
673 .seealso:  TSSetIJacobian()
674 @*/
675 PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,PetscBool imex)
676 {
677   PetscInt       Ustate, Udotstate;
678   PetscErrorCode ierr;
679   TSIJacobian    ijacobian;
680   TSRHSJacobian  rhsjacobian;
681   DM             dm;
682   void           *ctx;
683 
684   PetscFunctionBegin;
685   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
686   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
687   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
688   PetscValidPointer(A,6);
689   PetscValidHeaderSpecific(*A,MAT_CLASSID,6);
690   PetscValidPointer(B,7);
691   PetscValidHeaderSpecific(*B,MAT_CLASSID,7);
692   PetscValidPointer(flg,8);
693 
694   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
695   ierr = DMTSGetIJacobian(dm,&ijacobian,&ctx);CHKERRQ(ierr);
696   ierr = DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);CHKERRQ(ierr);
697 
698   ierr = PetscObjectStateQuery((PetscObject)U,&Ustate);CHKERRQ(ierr);
699   ierr = PetscObjectStateQuery((PetscObject)Udot,&Udotstate);CHKERRQ(ierr);
700   if (ts->ijacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->ijacobian.X == U && ts->ijacobian.Xstate == Ustate && ts->ijacobian.Xdot == Udot && ts->ijacobian.Xdotstate == Udotstate && ts->ijacobian.imex == imex))) {
701     *flg = ts->ijacobian.mstructure;
702     ierr = MatScale(*A, shift / ts->ijacobian.shift);CHKERRQ(ierr);
703     PetscFunctionReturn(0);
704   }
705 
706   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
707 
708   *flg = SAME_NONZERO_PATTERN;  /* In case we're solving a linear problem in which case it wouldn't get initialized below. */
709   ierr = PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);CHKERRQ(ierr);
710   if (ijacobian) {
711     *flg = DIFFERENT_NONZERO_PATTERN;
712     PetscStackPush("TS user implicit Jacobian");
713     ierr = (*ijacobian)(ts,t,U,Udot,shift,A,B,flg,ctx);CHKERRQ(ierr);
714     PetscStackPop;
715     /* make sure user returned a correct Jacobian and preconditioner */
716     PetscValidHeaderSpecific(*A,MAT_CLASSID,4);
717     PetscValidHeaderSpecific(*B,MAT_CLASSID,5);
718   }
719   if (imex) {
720     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
721       ierr = MatZeroEntries(*A);CHKERRQ(ierr);
722       ierr = MatShift(*A,shift);CHKERRQ(ierr);
723       if (*A != *B) {
724         ierr = MatZeroEntries(*B);CHKERRQ(ierr);
725         ierr = MatShift(*B,shift);CHKERRQ(ierr);
726       }
727       *flg = SAME_PRECONDITIONER;
728     }
729   } else {
730     if (!ijacobian) {
731       ierr = TSComputeRHSJacobian(ts,t,U,A,B,flg);CHKERRQ(ierr);
732       ierr = MatScale(*A,-1);CHKERRQ(ierr);
733       ierr = MatShift(*A,shift);CHKERRQ(ierr);
734       if (*A != *B) {
735         ierr = MatScale(*B,-1);CHKERRQ(ierr);
736         ierr = MatShift(*B,shift);CHKERRQ(ierr);
737       }
738     } else if (rhsjacobian) {
739       Mat          Arhs,Brhs;
740       MatStructure axpy,flg2 = DIFFERENT_NONZERO_PATTERN;
741       ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
742       ierr = TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);CHKERRQ(ierr);
743       axpy = (*flg == flg2) ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN;
744       ierr = MatAXPY(*A,-1,Arhs,axpy);CHKERRQ(ierr);
745       if (*A != *B) {
746         ierr = MatAXPY(*B,-1,Brhs,axpy);CHKERRQ(ierr);
747       }
748       *flg = PetscMin(*flg,flg2);
749     }
750   }
751 
752   ts->ijacobian.time = t;
753   ts->ijacobian.X    = U;
754   ts->ijacobian.Xdot = Udot;
755 
756   ierr = PetscObjectStateQuery((PetscObject)U,&ts->ijacobian.Xstate);CHKERRQ(ierr);
757   ierr = PetscObjectStateQuery((PetscObject)Udot,&ts->ijacobian.Xdotstate);CHKERRQ(ierr);
758 
759   ts->ijacobian.shift      = shift;
760   ts->ijacobian.imex       = imex;
761   ts->ijacobian.mstructure = *flg;
762 
763   ierr = PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);CHKERRQ(ierr);
764   PetscFunctionReturn(0);
765 }
766 
767 #undef __FUNCT__
768 #define __FUNCT__ "TSSetRHSFunction"
769 /*@C
770     TSSetRHSFunction - Sets the routine for evaluating the function,
771     where U_t = G(t,u).
772 
773     Logically Collective on TS
774 
775     Input Parameters:
776 +   ts - the TS context obtained from TSCreate()
777 .   r - vector to put the computed right hand side (or NULL to have it created)
778 .   f - routine for evaluating the right-hand-side function
779 -   ctx - [optional] user-defined context for private data for the
780           function evaluation routine (may be NULL)
781 
782     Calling sequence of func:
783 $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);
784 
785 +   t - current timestep
786 .   u - input vector
787 .   F - function vector
788 -   ctx - [optional] user-defined function context
789 
790     Level: beginner
791 
792 .keywords: TS, timestep, set, right-hand-side, function
793 
794 .seealso: TSSetRHSJacobian(), TSSetIJacobian()
795 @*/
796 PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
797 {
798   PetscErrorCode ierr;
799   SNES           snes;
800   Vec            ralloc = NULL;
801   DM             dm;
802 
803   PetscFunctionBegin;
804   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
805   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
806 
807   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
808   ierr = DMTSSetRHSFunction(dm,f,ctx);CHKERRQ(ierr);
809   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
810   if (!r && !ts->dm && ts->vec_sol) {
811     ierr = VecDuplicate(ts->vec_sol,&ralloc);CHKERRQ(ierr);
812     r    = ralloc;
813   }
814   ierr = SNESSetFunction(snes,r,SNESTSFormFunction,ts);CHKERRQ(ierr);
815   ierr = VecDestroy(&ralloc);CHKERRQ(ierr);
816   PetscFunctionReturn(0);
817 }
818 
819 #undef __FUNCT__
820 #define __FUNCT__ "TSSetSolutionFunction"
821 /*@C
822     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
823 
824     Logically Collective on TS
825 
826     Input Parameters:
827 +   ts - the TS context obtained from TSCreate()
828 .   f - routine for evaluating the solution
829 -   ctx - [optional] user-defined context for private data for the
830           function evaluation routine (may be NULL)
831 
832     Calling sequence of func:
833 $     func (TS ts,PetscReal t,Vec u,void *ctx);
834 
835 +   t - current timestep
836 .   u - output vector
837 -   ctx - [optional] user-defined function context
838 
839     Notes:
840     This routine is used for testing accuracy of time integration schemes when you already know the solution.
841     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
842     create closed-form solutions with non-physical forcing terms.
843 
844     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
845 
846     Level: beginner
847 
848 .keywords: TS, timestep, set, right-hand-side, function
849 
850 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
851 @*/
852 PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
853 {
854   PetscErrorCode ierr;
855   DM             dm;
856 
857   PetscFunctionBegin;
858   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
859   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
860   ierr = DMTSSetSolutionFunction(dm,f,ctx);CHKERRQ(ierr);
861   PetscFunctionReturn(0);
862 }
863 
864 #undef __FUNCT__
865 #define __FUNCT__ "TSSetForcingFunction"
866 /*@C
867     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
868 
869     Logically Collective on TS
870 
871     Input Parameters:
872 +   ts - the TS context obtained from TSCreate()
873 .   f - routine for evaluating the forcing function
874 -   ctx - [optional] user-defined context for private data for the
875           function evaluation routine (may be NULL)
876 
877     Calling sequence of func:
878 $     func (TS ts,PetscReal t,Vec u,void *ctx);
879 
880 +   t - current timestep
881 .   u - output vector
882 -   ctx - [optional] user-defined function context
883 
884     Notes:
885     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
886     create closed-form solutions with a non-physical forcing term.
887 
888     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
889 
890     Level: beginner
891 
892 .keywords: TS, timestep, set, right-hand-side, function
893 
894 .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
895 @*/
896 PetscErrorCode  TSSetForcingFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
897 {
898   PetscErrorCode ierr;
899   DM             dm;
900 
901   PetscFunctionBegin;
902   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
903   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
904   ierr = DMTSSetForcingFunction(dm,f,ctx);CHKERRQ(ierr);
905   PetscFunctionReturn(0);
906 }
907 
908 #undef __FUNCT__
909 #define __FUNCT__ "TSSetRHSJacobian"
910 /*@C
911    TSSetRHSJacobian - Sets the function to compute the Jacobian of F,
912    where U_t = G(U,t), as well as the location to store the matrix.
913 
914    Logically Collective on TS
915 
916    Input Parameters:
917 +  ts  - the TS context obtained from TSCreate()
918 .  A   - Jacobian matrix
919 .  B   - preconditioner matrix (usually same as A)
920 .  f   - the Jacobian evaluation routine
921 -  ctx - [optional] user-defined context for private data for the
922          Jacobian evaluation routine (may be NULL)
923 
924    Calling sequence of func:
925 $     func (TS ts,PetscReal t,Vec u,Mat *A,Mat *B,MatStructure *flag,void *ctx);
926 
927 +  t - current timestep
928 .  u - input vector
929 .  A - matrix A, where U_t = A(t)u
930 .  B - preconditioner matrix, usually the same as A
931 .  flag - flag indicating information about the preconditioner matrix
932           structure (same as flag in KSPSetOperators())
933 -  ctx - [optional] user-defined context for matrix evaluation routine
934 
935    Notes:
936    See KSPSetOperators() for important information about setting the flag
937    output parameter in the routine func().  Be sure to read this information!
938 
939    The routine func() takes Mat * as the matrix arguments rather than Mat.
940    This allows the matrix evaluation routine to replace A and/or B with a
941    completely new matrix structure (not just different matrix elements)
942    when appropriate, for instance, if the nonzero structure is changing
943    throughout the global iterations.
944 
945    Level: beginner
946 
947 .keywords: TS, timestep, set, right-hand-side, Jacobian
948 
949 .seealso: SNESDefaultComputeJacobianColor(), TSSetRHSFunction()
950 
951 @*/
952 PetscErrorCode  TSSetRHSJacobian(TS ts,Mat A,Mat B,TSRHSJacobian f,void *ctx)
953 {
954   PetscErrorCode ierr;
955   SNES           snes;
956   DM             dm;
957   TSIJacobian    ijacobian;
958 
959   PetscFunctionBegin;
960   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
961   if (A) PetscValidHeaderSpecific(A,MAT_CLASSID,2);
962   if (B) PetscValidHeaderSpecific(B,MAT_CLASSID,3);
963   if (A) PetscCheckSameComm(ts,1,A,2);
964   if (B) PetscCheckSameComm(ts,1,B,3);
965 
966   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
967   ierr = DMTSSetRHSJacobian(dm,f,ctx);CHKERRQ(ierr);
968   ierr = DMTSGetIJacobian(dm,&ijacobian,NULL);CHKERRQ(ierr);
969 
970   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
971   if (!ijacobian) {
972     ierr = SNESSetJacobian(snes,A,B,SNESTSFormJacobian,ts);CHKERRQ(ierr);
973   }
974   if (A) {
975     ierr = PetscObjectReference((PetscObject)A);CHKERRQ(ierr);
976     ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
977 
978     ts->Arhs = A;
979   }
980   if (B) {
981     ierr = PetscObjectReference((PetscObject)B);CHKERRQ(ierr);
982     ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
983 
984     ts->Brhs = B;
985   }
986   PetscFunctionReturn(0);
987 }
988 
989 
990 #undef __FUNCT__
991 #define __FUNCT__ "TSSetIFunction"
992 /*@C
993    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
994 
995    Logically Collective on TS
996 
997    Input Parameters:
998 +  ts  - the TS context obtained from TSCreate()
999 .  r   - vector to hold the residual (or NULL to have it created internally)
1000 .  f   - the function evaluation routine
1001 -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1002 
1003    Calling sequence of f:
1004 $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1005 
1006 +  t   - time at step/stage being solved
1007 .  u   - state vector
1008 .  u_t - time derivative of state vector
1009 .  F   - function vector
1010 -  ctx - [optional] user-defined context for matrix evaluation routine
1011 
1012    Important:
1013    The user MUST call either this routine, TSSetRHSFunction().  This routine must be used when not solving an ODE, for example a DAE.
1014 
1015    Level: beginner
1016 
1017 .keywords: TS, timestep, set, DAE, Jacobian
1018 
1019 .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1020 @*/
1021 PetscErrorCode  TSSetIFunction(TS ts,Vec res,TSIFunction f,void *ctx)
1022 {
1023   PetscErrorCode ierr;
1024   SNES           snes;
1025   Vec            resalloc = NULL;
1026   DM             dm;
1027 
1028   PetscFunctionBegin;
1029   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1030   if (res) PetscValidHeaderSpecific(res,VEC_CLASSID,2);
1031 
1032   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1033   ierr = DMTSSetIFunction(dm,f,ctx);CHKERRQ(ierr);
1034 
1035   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1036   if (!res && !ts->dm && ts->vec_sol) {
1037     ierr = VecDuplicate(ts->vec_sol,&resalloc);CHKERRQ(ierr);
1038     res  = resalloc;
1039   }
1040   ierr = SNESSetFunction(snes,res,SNESTSFormFunction,ts);CHKERRQ(ierr);
1041   ierr = VecDestroy(&resalloc);CHKERRQ(ierr);
1042   PetscFunctionReturn(0);
1043 }
1044 
1045 #undef __FUNCT__
1046 #define __FUNCT__ "TSGetIFunction"
1047 /*@C
1048    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.
1049 
1050    Not Collective
1051 
1052    Input Parameter:
1053 .  ts - the TS context
1054 
1055    Output Parameter:
1056 +  r - vector to hold residual (or NULL)
1057 .  func - the function to compute residual (or NULL)
1058 -  ctx - the function context (or NULL)
1059 
1060    Level: advanced
1061 
1062 .keywords: TS, nonlinear, get, function
1063 
1064 .seealso: TSSetIFunction(), SNESGetFunction()
1065 @*/
1066 PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1067 {
1068   PetscErrorCode ierr;
1069   SNES           snes;
1070   DM             dm;
1071 
1072   PetscFunctionBegin;
1073   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1074   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1075   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1076   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1077   ierr = DMTSGetIFunction(dm,func,ctx);CHKERRQ(ierr);
1078   PetscFunctionReturn(0);
1079 }
1080 
1081 #undef __FUNCT__
1082 #define __FUNCT__ "TSGetRHSFunction"
1083 /*@C
1084    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1085 
1086    Not Collective
1087 
1088    Input Parameter:
1089 .  ts - the TS context
1090 
1091    Output Parameter:
1092 +  r - vector to hold computed right hand side (or NULL)
1093 .  func - the function to compute right hand side (or NULL)
1094 -  ctx - the function context (or NULL)
1095 
1096    Level: advanced
1097 
1098 .keywords: TS, nonlinear, get, function
1099 
1100 .seealso: TSSetRhsfunction(), SNESGetFunction()
1101 @*/
1102 PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1103 {
1104   PetscErrorCode ierr;
1105   SNES           snes;
1106   DM             dm;
1107 
1108   PetscFunctionBegin;
1109   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1110   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1111   ierr = SNESGetFunction(snes,r,NULL,NULL);CHKERRQ(ierr);
1112   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1113   ierr = DMTSGetRHSFunction(dm,func,ctx);CHKERRQ(ierr);
1114   PetscFunctionReturn(0);
1115 }
1116 
1117 #undef __FUNCT__
1118 #define __FUNCT__ "TSSetIJacobian"
1119 /*@C
1120    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1121         you provided with TSSetIFunction().
1122 
1123    Logically Collective on TS
1124 
1125    Input Parameters:
1126 +  ts  - the TS context obtained from TSCreate()
1127 .  A   - Jacobian matrix
1128 .  B   - preconditioning matrix for A (may be same as A)
1129 .  f   - the Jacobian evaluation routine
1130 -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1131 
1132    Calling sequence of f:
1133 $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat *A,Mat *B,MatStructure *flag,void *ctx);
1134 
1135 +  t    - time at step/stage being solved
1136 .  U    - state vector
1137 .  U_t  - time derivative of state vector
1138 .  a    - shift
1139 .  A    - Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1140 .  B    - preconditioning matrix for A, may be same as A
1141 .  flag - flag indicating information about the preconditioner matrix
1142           structure (same as flag in KSPSetOperators())
1143 -  ctx  - [optional] user-defined context for matrix evaluation routine
1144 
1145    Notes:
1146    The matrices A and B are exactly the matrices that are used by SNES for the nonlinear solve.
1147 
1148    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1149    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1150    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1151    a and vector W depend on the integration method, step size, and past states. For example with
1152    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1153    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1154 
1155    Level: beginner
1156 
1157 .keywords: TS, timestep, DAE, Jacobian
1158 
1159 .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESDefaultComputeJacobianColor(), SNESDefaultComputeJacobian()
1160 
1161 @*/
1162 PetscErrorCode  TSSetIJacobian(TS ts,Mat A,Mat B,TSIJacobian f,void *ctx)
1163 {
1164   PetscErrorCode ierr;
1165   SNES           snes;
1166   DM             dm;
1167 
1168   PetscFunctionBegin;
1169   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1170   if (A) PetscValidHeaderSpecific(A,MAT_CLASSID,2);
1171   if (B) PetscValidHeaderSpecific(B,MAT_CLASSID,3);
1172   if (A) PetscCheckSameComm(ts,1,A,2);
1173   if (B) PetscCheckSameComm(ts,1,B,3);
1174 
1175   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1176   ierr = DMTSSetIJacobian(dm,f,ctx);CHKERRQ(ierr);
1177 
1178   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1179   ierr = SNESSetJacobian(snes,A,B,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1180   PetscFunctionReturn(0);
1181 }
1182 
1183 #undef __FUNCT__
1184 #define __FUNCT__ "TSLoad"
1185 /*@C
1186   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
1187 
1188   Collective on PetscViewer
1189 
1190   Input Parameters:
1191 + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1192            some related function before a call to TSLoad().
1193 - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
1194 
1195    Level: intermediate
1196 
1197   Notes:
1198    The type is determined by the data in the file, any type set into the TS before this call is ignored.
1199 
1200   Notes for advanced users:
1201   Most users should not need to know the details of the binary storage
1202   format, since TSLoad() and TSView() completely hide these details.
1203   But for anyone who's interested, the standard binary matrix storage
1204   format is
1205 .vb
1206      has not yet been determined
1207 .ve
1208 
1209 .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1210 @*/
1211 PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1212 {
1213   PetscErrorCode ierr;
1214   PetscBool      isbinary;
1215   PetscInt       classid;
1216   char           type[256];
1217   DMTS           sdm;
1218   DM             dm;
1219 
1220   PetscFunctionBegin;
1221   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1222   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1223   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1224   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
1225 
1226   ierr = PetscViewerBinaryRead(viewer,&classid,1,PETSC_INT);CHKERRQ(ierr);
1227   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1228   ierr = PetscViewerBinaryRead(viewer,type,256,PETSC_CHAR);CHKERRQ(ierr);
1229   ierr = TSSetType(ts, type);CHKERRQ(ierr);
1230   if (ts->ops->load) {
1231     ierr = (*ts->ops->load)(ts,viewer);CHKERRQ(ierr);
1232   }
1233   ierr = DMCreate(PetscObjectComm((PetscObject)ts),&dm);CHKERRQ(ierr);
1234   ierr = DMLoad(dm,viewer);CHKERRQ(ierr);
1235   ierr = TSSetDM(ts,dm);CHKERRQ(ierr);
1236   ierr = DMCreateGlobalVector(ts->dm,&ts->vec_sol);CHKERRQ(ierr);
1237   ierr = VecLoad(ts->vec_sol,viewer);CHKERRQ(ierr);
1238   ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1239   ierr = DMTSLoad(sdm,viewer);CHKERRQ(ierr);
1240   PetscFunctionReturn(0);
1241 }
1242 
1243 #include <petscdraw.h>
1244 #undef __FUNCT__
1245 #define __FUNCT__ "TSView"
1246 /*@C
1247     TSView - Prints the TS data structure.
1248 
1249     Collective on TS
1250 
1251     Input Parameters:
1252 +   ts - the TS context obtained from TSCreate()
1253 -   viewer - visualization context
1254 
1255     Options Database Key:
1256 .   -ts_view - calls TSView() at end of TSStep()
1257 
1258     Notes:
1259     The available visualization contexts include
1260 +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1261 -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1262          output where only the first processor opens
1263          the file.  All other processors send their
1264          data to the first processor to print.
1265 
1266     The user can open an alternative visualization context with
1267     PetscViewerASCIIOpen() - output to a specified file.
1268 
1269     Level: beginner
1270 
1271 .keywords: TS, timestep, view
1272 
1273 .seealso: PetscViewerASCIIOpen()
1274 @*/
1275 PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1276 {
1277   PetscErrorCode ierr;
1278   TSType         type;
1279   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1280   DMTS           sdm;
1281 
1282   PetscFunctionBegin;
1283   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1284   if (!viewer) {
1285     ierr = PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);CHKERRQ(ierr);
1286   }
1287   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1288   PetscCheckSameComm(ts,1,viewer,2);
1289 
1290   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);CHKERRQ(ierr);
1291   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);CHKERRQ(ierr);
1292   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);CHKERRQ(ierr);
1293   ierr = PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);CHKERRQ(ierr);
1294   if (iascii) {
1295     ierr = PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer,"TS Object");CHKERRQ(ierr);
1296     ierr = PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);CHKERRQ(ierr);
1297     ierr = PetscViewerASCIIPrintf(viewer,"  maximum time=%G\n",ts->max_time);CHKERRQ(ierr);
1298     if (ts->problem_type == TS_NONLINEAR) {
1299       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);CHKERRQ(ierr);
1300       ierr = PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);CHKERRQ(ierr);
1301     }
1302     ierr = PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);CHKERRQ(ierr);
1303     ierr = PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);CHKERRQ(ierr);
1304     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1305     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1306     if (ts->ops->view) {
1307       ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1308       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1309       ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1310     }
1311   } else if (isstring) {
1312     ierr = TSGetType(ts,&type);CHKERRQ(ierr);
1313     ierr = PetscViewerStringSPrintf(viewer," %-7.7s",type);CHKERRQ(ierr);
1314   } else if (isbinary) {
1315     PetscInt    classid = TS_FILE_CLASSID;
1316     MPI_Comm    comm;
1317     PetscMPIInt rank;
1318     char        type[256];
1319 
1320     ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
1321     ierr = MPI_Comm_rank(comm,&rank);CHKERRQ(ierr);
1322     if (!rank) {
1323       ierr = PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);CHKERRQ(ierr);
1324       ierr = PetscStrncpy(type,((PetscObject)ts)->type_name,256);CHKERRQ(ierr);
1325       ierr = PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);CHKERRQ(ierr);
1326     }
1327     if (ts->ops->view) {
1328       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1329     }
1330     ierr = DMView(ts->dm,viewer);CHKERRQ(ierr);
1331     ierr = VecView(ts->vec_sol,viewer);CHKERRQ(ierr);
1332     ierr = DMGetDMTS(ts->dm,&sdm);CHKERRQ(ierr);
1333     ierr = DMTSView(sdm,viewer);CHKERRQ(ierr);
1334   } else if (isdraw) {
1335     PetscDraw draw;
1336     char      str[36];
1337     PetscReal x,y,bottom,h;
1338 
1339     ierr   = PetscViewerDrawGetDraw(viewer,0,&draw);CHKERRQ(ierr);
1340     ierr   = PetscDrawGetCurrentPoint(draw,&x,&y);CHKERRQ(ierr);
1341     ierr   = PetscStrcpy(str,"TS: ");CHKERRQ(ierr);
1342     ierr   = PetscStrcat(str,((PetscObject)ts)->type_name);CHKERRQ(ierr);
1343     ierr   = PetscDrawBoxedString(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);CHKERRQ(ierr);
1344     bottom = y - h;
1345     ierr   = PetscDrawPushCurrentPoint(draw,x,bottom);CHKERRQ(ierr);
1346     if (ts->ops->view) {
1347       ierr = (*ts->ops->view)(ts,viewer);CHKERRQ(ierr);
1348     }
1349     ierr = PetscDrawPopCurrentPoint(draw);CHKERRQ(ierr);
1350   }
1351   ierr = PetscViewerASCIIPushTab(viewer);CHKERRQ(ierr);
1352   ierr = PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);CHKERRQ(ierr);
1353   ierr = PetscViewerASCIIPopTab(viewer);CHKERRQ(ierr);
1354   PetscFunctionReturn(0);
1355 }
1356 
1357 
1358 #undef __FUNCT__
1359 #define __FUNCT__ "TSSetApplicationContext"
1360 /*@
1361    TSSetApplicationContext - Sets an optional user-defined context for
1362    the timesteppers.
1363 
1364    Logically Collective on TS
1365 
1366    Input Parameters:
1367 +  ts - the TS context obtained from TSCreate()
1368 -  usrP - optional user context
1369 
1370    Level: intermediate
1371 
1372 .keywords: TS, timestep, set, application, context
1373 
1374 .seealso: TSGetApplicationContext()
1375 @*/
1376 PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
1377 {
1378   PetscFunctionBegin;
1379   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1380   ts->user = usrP;
1381   PetscFunctionReturn(0);
1382 }
1383 
1384 #undef __FUNCT__
1385 #define __FUNCT__ "TSGetApplicationContext"
1386 /*@
1387     TSGetApplicationContext - Gets the user-defined context for the
1388     timestepper.
1389 
1390     Not Collective
1391 
1392     Input Parameter:
1393 .   ts - the TS context obtained from TSCreate()
1394 
1395     Output Parameter:
1396 .   usrP - user context
1397 
1398     Level: intermediate
1399 
1400 .keywords: TS, timestep, get, application, context
1401 
1402 .seealso: TSSetApplicationContext()
1403 @*/
1404 PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
1405 {
1406   PetscFunctionBegin;
1407   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1408   *(void**)usrP = ts->user;
1409   PetscFunctionReturn(0);
1410 }
1411 
1412 #undef __FUNCT__
1413 #define __FUNCT__ "TSGetTimeStepNumber"
1414 /*@
1415    TSGetTimeStepNumber - Gets the number of time steps completed.
1416 
1417    Not Collective
1418 
1419    Input Parameter:
1420 .  ts - the TS context obtained from TSCreate()
1421 
1422    Output Parameter:
1423 .  iter - number of steps completed so far
1424 
1425    Level: intermediate
1426 
1427 .keywords: TS, timestep, get, iteration, number
1428 .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStep()
1429 @*/
1430 PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
1431 {
1432   PetscFunctionBegin;
1433   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1434   PetscValidIntPointer(iter,2);
1435   *iter = ts->steps;
1436   PetscFunctionReturn(0);
1437 }
1438 
1439 #undef __FUNCT__
1440 #define __FUNCT__ "TSSetInitialTimeStep"
1441 /*@
1442    TSSetInitialTimeStep - Sets the initial timestep to be used,
1443    as well as the initial time.
1444 
1445    Logically Collective on TS
1446 
1447    Input Parameters:
1448 +  ts - the TS context obtained from TSCreate()
1449 .  initial_time - the initial time
1450 -  time_step - the size of the timestep
1451 
1452    Level: intermediate
1453 
1454 .seealso: TSSetTimeStep(), TSGetTimeStep()
1455 
1456 .keywords: TS, set, initial, timestep
1457 @*/
1458 PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
1459 {
1460   PetscErrorCode ierr;
1461 
1462   PetscFunctionBegin;
1463   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1464   ierr = TSSetTimeStep(ts,time_step);CHKERRQ(ierr);
1465   ierr = TSSetTime(ts,initial_time);CHKERRQ(ierr);
1466   PetscFunctionReturn(0);
1467 }
1468 
1469 #undef __FUNCT__
1470 #define __FUNCT__ "TSSetTimeStep"
1471 /*@
1472    TSSetTimeStep - Allows one to reset the timestep at any time,
1473    useful for simple pseudo-timestepping codes.
1474 
1475    Logically Collective on TS
1476 
1477    Input Parameters:
1478 +  ts - the TS context obtained from TSCreate()
1479 -  time_step - the size of the timestep
1480 
1481    Level: intermediate
1482 
1483 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
1484 
1485 .keywords: TS, set, timestep
1486 @*/
1487 PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
1488 {
1489   PetscFunctionBegin;
1490   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1491   PetscValidLogicalCollectiveReal(ts,time_step,2);
1492   ts->time_step      = time_step;
1493   ts->time_step_orig = time_step;
1494   PetscFunctionReturn(0);
1495 }
1496 
1497 #undef __FUNCT__
1498 #define __FUNCT__ "TSSetExactFinalTime"
1499 /*@
1500    TSSetExactFinalTime - Determines whether to adapt the final time step to
1501      match the exact final time, interpolate solution to the exact final time,
1502      or just return at the final time TS computed.
1503 
1504   Logically Collective on TS
1505 
1506    Input Parameter:
1507 +   ts - the time-step context
1508 -   eftopt - exact final time option
1509 
1510    Level: beginner
1511 
1512 .seealso: TSExactFinalTimeOption
1513 @*/
1514 PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
1515 {
1516   PetscFunctionBegin;
1517   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1518   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
1519   ts->exact_final_time = eftopt;
1520   PetscFunctionReturn(0);
1521 }
1522 
1523 #undef __FUNCT__
1524 #define __FUNCT__ "TSGetTimeStep"
1525 /*@
1526    TSGetTimeStep - Gets the current timestep size.
1527 
1528    Not Collective
1529 
1530    Input Parameter:
1531 .  ts - the TS context obtained from TSCreate()
1532 
1533    Output Parameter:
1534 .  dt - the current timestep size
1535 
1536    Level: intermediate
1537 
1538 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
1539 
1540 .keywords: TS, get, timestep
1541 @*/
1542 PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
1543 {
1544   PetscFunctionBegin;
1545   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1546   PetscValidRealPointer(dt,2);
1547   *dt = ts->time_step;
1548   PetscFunctionReturn(0);
1549 }
1550 
1551 #undef __FUNCT__
1552 #define __FUNCT__ "TSGetSolution"
1553 /*@
1554    TSGetSolution - Returns the solution at the present timestep. It
1555    is valid to call this routine inside the function that you are evaluating
1556    in order to move to the new timestep. This vector not changed until
1557    the solution at the next timestep has been calculated.
1558 
1559    Not Collective, but Vec returned is parallel if TS is parallel
1560 
1561    Input Parameter:
1562 .  ts - the TS context obtained from TSCreate()
1563 
1564    Output Parameter:
1565 .  v - the vector containing the solution
1566 
1567    Level: intermediate
1568 
1569 .seealso: TSGetTimeStep()
1570 
1571 .keywords: TS, timestep, get, solution
1572 @*/
1573 PetscErrorCode  TSGetSolution(TS ts,Vec *v)
1574 {
1575   PetscFunctionBegin;
1576   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1577   PetscValidPointer(v,2);
1578   *v = ts->vec_sol;
1579   PetscFunctionReturn(0);
1580 }
1581 
1582 /* ----- Routines to initialize and destroy a timestepper ---- */
1583 #undef __FUNCT__
1584 #define __FUNCT__ "TSSetProblemType"
1585 /*@
1586   TSSetProblemType - Sets the type of problem to be solved.
1587 
1588   Not collective
1589 
1590   Input Parameters:
1591 + ts   - The TS
1592 - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1593 .vb
1594          U_t - A U = 0      (linear)
1595          U_t - A(t) U = 0   (linear)
1596          F(t,U,U_t) = 0     (nonlinear)
1597 .ve
1598 
1599    Level: beginner
1600 
1601 .keywords: TS, problem type
1602 .seealso: TSSetUp(), TSProblemType, TS
1603 @*/
1604 PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
1605 {
1606   PetscErrorCode ierr;
1607 
1608   PetscFunctionBegin;
1609   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
1610   ts->problem_type = type;
1611   if (type == TS_LINEAR) {
1612     SNES snes;
1613     ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1614     ierr = SNESSetType(snes,SNESKSPONLY);CHKERRQ(ierr);
1615   }
1616   PetscFunctionReturn(0);
1617 }
1618 
1619 #undef __FUNCT__
1620 #define __FUNCT__ "TSGetProblemType"
1621 /*@C
1622   TSGetProblemType - Gets the type of problem to be solved.
1623 
1624   Not collective
1625 
1626   Input Parameter:
1627 . ts   - The TS
1628 
1629   Output Parameter:
1630 . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1631 .vb
1632          M U_t = A U
1633          M(t) U_t = A(t) U
1634          F(t,U,U_t)
1635 .ve
1636 
1637    Level: beginner
1638 
1639 .keywords: TS, problem type
1640 .seealso: TSSetUp(), TSProblemType, TS
1641 @*/
1642 PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
1643 {
1644   PetscFunctionBegin;
1645   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
1646   PetscValidIntPointer(type,2);
1647   *type = ts->problem_type;
1648   PetscFunctionReturn(0);
1649 }
1650 
1651 #undef __FUNCT__
1652 #define __FUNCT__ "TSSetUp"
1653 /*@
1654    TSSetUp - Sets up the internal data structures for the later use
1655    of a timestepper.
1656 
1657    Collective on TS
1658 
1659    Input Parameter:
1660 .  ts - the TS context obtained from TSCreate()
1661 
1662    Notes:
1663    For basic use of the TS solvers the user need not explicitly call
1664    TSSetUp(), since these actions will automatically occur during
1665    the call to TSStep().  However, if one wishes to control this
1666    phase separately, TSSetUp() should be called after TSCreate()
1667    and optional routines of the form TSSetXXX(), but before TSStep().
1668 
1669    Level: advanced
1670 
1671 .keywords: TS, timestep, setup
1672 
1673 .seealso: TSCreate(), TSStep(), TSDestroy()
1674 @*/
1675 PetscErrorCode  TSSetUp(TS ts)
1676 {
1677   PetscErrorCode ierr;
1678   DM             dm;
1679   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
1680   PetscErrorCode (*jac)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
1681   TSIJacobian    ijac;
1682   TSRHSJacobian  rhsjac;
1683 
1684   PetscFunctionBegin;
1685   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1686   if (ts->setupcalled) PetscFunctionReturn(0);
1687 
1688   if (!((PetscObject)ts)->type_name) {
1689     ierr = TSSetType(ts,TSEULER);CHKERRQ(ierr);
1690   }
1691 
1692   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
1693 
1694   ierr = TSGetTSAdapt(ts,&ts->adapt);CHKERRQ(ierr);
1695 
1696   if (ts->ops->setup) {
1697     ierr = (*ts->ops->setup)(ts);CHKERRQ(ierr);
1698   }
1699 
1700   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
1701    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
1702    */
1703   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
1704   ierr = DMSNESGetFunction(dm,&func,NULL);CHKERRQ(ierr);
1705   if (!func) {
1706     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);CHKERRQ(ierr);
1707   }
1708   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
1709      Otherwise, the SNES will use coloring internally to form the Jacobian.
1710    */
1711   ierr = DMSNESGetJacobian(dm,&jac,NULL);CHKERRQ(ierr);
1712   ierr = DMTSGetIJacobian(dm,&ijac,NULL);CHKERRQ(ierr);
1713   ierr = DMTSGetRHSJacobian(dm,&rhsjac,NULL);CHKERRQ(ierr);
1714   if (!jac && (ijac || rhsjac)) {
1715     ierr = DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1716   }
1717   ts->setupcalled = PETSC_TRUE;
1718   PetscFunctionReturn(0);
1719 }
1720 
1721 #undef __FUNCT__
1722 #define __FUNCT__ "TSReset"
1723 /*@
1724    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
1725 
1726    Collective on TS
1727 
1728    Input Parameter:
1729 .  ts - the TS context obtained from TSCreate()
1730 
1731    Level: beginner
1732 
1733 .keywords: TS, timestep, reset
1734 
1735 .seealso: TSCreate(), TSSetup(), TSDestroy()
1736 @*/
1737 PetscErrorCode  TSReset(TS ts)
1738 {
1739   PetscErrorCode ierr;
1740 
1741   PetscFunctionBegin;
1742   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1743   if (ts->ops->reset) {
1744     ierr = (*ts->ops->reset)(ts);CHKERRQ(ierr);
1745   }
1746   if (ts->snes) {ierr = SNESReset(ts->snes);CHKERRQ(ierr);}
1747 
1748   ierr = MatDestroy(&ts->Arhs);CHKERRQ(ierr);
1749   ierr = MatDestroy(&ts->Brhs);CHKERRQ(ierr);
1750   ierr = VecDestroy(&ts->Frhs);CHKERRQ(ierr);
1751   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
1752   ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
1753   ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
1754   ierr = VecDestroyVecs(ts->nwork,&ts->work);CHKERRQ(ierr);
1755 
1756   ts->setupcalled = PETSC_FALSE;
1757   PetscFunctionReturn(0);
1758 }
1759 
1760 #undef __FUNCT__
1761 #define __FUNCT__ "TSDestroy"
1762 /*@
1763    TSDestroy - Destroys the timestepper context that was created
1764    with TSCreate().
1765 
1766    Collective on TS
1767 
1768    Input Parameter:
1769 .  ts - the TS context obtained from TSCreate()
1770 
1771    Level: beginner
1772 
1773 .keywords: TS, timestepper, destroy
1774 
1775 .seealso: TSCreate(), TSSetUp(), TSSolve()
1776 @*/
1777 PetscErrorCode  TSDestroy(TS *ts)
1778 {
1779   PetscErrorCode ierr;
1780 
1781   PetscFunctionBegin;
1782   if (!*ts) PetscFunctionReturn(0);
1783   PetscValidHeaderSpecific((*ts),TS_CLASSID,1);
1784   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; PetscFunctionReturn(0);}
1785 
1786   ierr = TSReset((*ts));CHKERRQ(ierr);
1787 
1788   /* if memory was published with AMS then destroy it */
1789   ierr = PetscObjectDepublish((*ts));CHKERRQ(ierr);
1790   if ((*ts)->ops->destroy) {ierr = (*(*ts)->ops->destroy)((*ts));CHKERRQ(ierr);}
1791 
1792   ierr = TSAdaptDestroy(&(*ts)->adapt);CHKERRQ(ierr);
1793   ierr = SNESDestroy(&(*ts)->snes);CHKERRQ(ierr);
1794   ierr = DMDestroy(&(*ts)->dm);CHKERRQ(ierr);
1795   ierr = TSMonitorCancel((*ts));CHKERRQ(ierr);
1796 
1797   ierr = PetscHeaderDestroy(ts);CHKERRQ(ierr);
1798   PetscFunctionReturn(0);
1799 }
1800 
1801 #undef __FUNCT__
1802 #define __FUNCT__ "TSGetSNES"
1803 /*@
1804    TSGetSNES - Returns the SNES (nonlinear solver) associated with
1805    a TS (timestepper) context. Valid only for nonlinear problems.
1806 
1807    Not Collective, but SNES is parallel if TS is parallel
1808 
1809    Input Parameter:
1810 .  ts - the TS context obtained from TSCreate()
1811 
1812    Output Parameter:
1813 .  snes - the nonlinear solver context
1814 
1815    Notes:
1816    The user can then directly manipulate the SNES context to set various
1817    options, etc.  Likewise, the user can then extract and manipulate the
1818    KSP, KSP, and PC contexts as well.
1819 
1820    TSGetSNES() does not work for integrators that do not use SNES; in
1821    this case TSGetSNES() returns NULL in snes.
1822 
1823    Level: beginner
1824 
1825 .keywords: timestep, get, SNES
1826 @*/
1827 PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
1828 {
1829   PetscErrorCode ierr;
1830 
1831   PetscFunctionBegin;
1832   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1833   PetscValidPointer(snes,2);
1834   if (!ts->snes) {
1835     ierr = SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);CHKERRQ(ierr);
1836     ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
1837     ierr = PetscLogObjectParent(ts,ts->snes);CHKERRQ(ierr);
1838     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);CHKERRQ(ierr);
1839     if (ts->dm) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
1840     if (ts->problem_type == TS_LINEAR) {
1841       ierr = SNESSetType(ts->snes,SNESKSPONLY);CHKERRQ(ierr);
1842     }
1843   }
1844   *snes = ts->snes;
1845   PetscFunctionReturn(0);
1846 }
1847 
1848 #undef __FUNCT__
1849 #define __FUNCT__ "TSSetSNES"
1850 /*@
1851    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
1852 
1853    Collective
1854 
1855    Input Parameter:
1856 +  ts - the TS context obtained from TSCreate()
1857 -  snes - the nonlinear solver context
1858 
1859    Notes:
1860    Most users should have the TS created by calling TSGetSNES()
1861 
1862    Level: developer
1863 
1864 .keywords: timestep, set, SNES
1865 @*/
1866 PetscErrorCode TSSetSNES(TS ts,SNES snes)
1867 {
1868   PetscErrorCode ierr;
1869   PetscErrorCode (*func)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
1870 
1871   PetscFunctionBegin;
1872   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1873   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
1874   ierr = PetscObjectReference((PetscObject)snes);CHKERRQ(ierr);
1875   ierr = SNESDestroy(&ts->snes);CHKERRQ(ierr);
1876 
1877   ts->snes = snes;
1878 
1879   ierr = SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);CHKERRQ(ierr);
1880   ierr = SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);CHKERRQ(ierr);
1881   if (func == SNESTSFormJacobian) {
1882     ierr = SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);CHKERRQ(ierr);
1883   }
1884   PetscFunctionReturn(0);
1885 }
1886 
1887 #undef __FUNCT__
1888 #define __FUNCT__ "TSGetKSP"
1889 /*@
1890    TSGetKSP - Returns the KSP (linear solver) associated with
1891    a TS (timestepper) context.
1892 
1893    Not Collective, but KSP is parallel if TS is parallel
1894 
1895    Input Parameter:
1896 .  ts - the TS context obtained from TSCreate()
1897 
1898    Output Parameter:
1899 .  ksp - the nonlinear solver context
1900 
1901    Notes:
1902    The user can then directly manipulate the KSP context to set various
1903    options, etc.  Likewise, the user can then extract and manipulate the
1904    KSP and PC contexts as well.
1905 
1906    TSGetKSP() does not work for integrators that do not use KSP;
1907    in this case TSGetKSP() returns NULL in ksp.
1908 
1909    Level: beginner
1910 
1911 .keywords: timestep, get, KSP
1912 @*/
1913 PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
1914 {
1915   PetscErrorCode ierr;
1916   SNES           snes;
1917 
1918   PetscFunctionBegin;
1919   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1920   PetscValidPointer(ksp,2);
1921   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
1922   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
1923   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
1924   ierr = SNESGetKSP(snes,ksp);CHKERRQ(ierr);
1925   PetscFunctionReturn(0);
1926 }
1927 
1928 /* ----------- Routines to set solver parameters ---------- */
1929 
1930 #undef __FUNCT__
1931 #define __FUNCT__ "TSGetDuration"
1932 /*@
1933    TSGetDuration - Gets the maximum number of timesteps to use and
1934    maximum time for iteration.
1935 
1936    Not Collective
1937 
1938    Input Parameters:
1939 +  ts       - the TS context obtained from TSCreate()
1940 .  maxsteps - maximum number of iterations to use, or NULL
1941 -  maxtime  - final time to iterate to, or NULL
1942 
1943    Level: intermediate
1944 
1945 .keywords: TS, timestep, get, maximum, iterations, time
1946 @*/
1947 PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
1948 {
1949   PetscFunctionBegin;
1950   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
1951   if (maxsteps) {
1952     PetscValidIntPointer(maxsteps,2);
1953     *maxsteps = ts->max_steps;
1954   }
1955   if (maxtime) {
1956     PetscValidScalarPointer(maxtime,3);
1957     *maxtime = ts->max_time;
1958   }
1959   PetscFunctionReturn(0);
1960 }
1961 
1962 #undef __FUNCT__
1963 #define __FUNCT__ "TSSetDuration"
1964 /*@
1965    TSSetDuration - Sets the maximum number of timesteps to use and
1966    maximum time for iteration.
1967 
1968    Logically Collective on TS
1969 
1970    Input Parameters:
1971 +  ts - the TS context obtained from TSCreate()
1972 .  maxsteps - maximum number of iterations to use
1973 -  maxtime - final time to iterate to
1974 
1975    Options Database Keys:
1976 .  -ts_max_steps <maxsteps> - Sets maxsteps
1977 .  -ts_final_time <maxtime> - Sets maxtime
1978 
1979    Notes:
1980    The default maximum number of iterations is 5000. Default time is 5.0
1981 
1982    Level: intermediate
1983 
1984 .keywords: TS, timestep, set, maximum, iterations
1985 
1986 .seealso: TSSetExactFinalTime()
1987 @*/
1988 PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
1989 {
1990   PetscFunctionBegin;
1991   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1992   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
1993   PetscValidLogicalCollectiveReal(ts,maxtime,2);
1994   if (maxsteps >= 0) ts->max_steps = maxsteps;
1995   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
1996   PetscFunctionReturn(0);
1997 }
1998 
1999 #undef __FUNCT__
2000 #define __FUNCT__ "TSSetSolution"
2001 /*@
2002    TSSetSolution - Sets the initial solution vector
2003    for use by the TS routines.
2004 
2005    Logically Collective on TS and Vec
2006 
2007    Input Parameters:
2008 +  ts - the TS context obtained from TSCreate()
2009 -  u - the solution vector
2010 
2011    Level: beginner
2012 
2013 .keywords: TS, timestep, set, solution, initial conditions
2014 @*/
2015 PetscErrorCode  TSSetSolution(TS ts,Vec u)
2016 {
2017   PetscErrorCode ierr;
2018   DM             dm;
2019 
2020   PetscFunctionBegin;
2021   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2022   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2023   ierr = PetscObjectReference((PetscObject)u);CHKERRQ(ierr);
2024   ierr = VecDestroy(&ts->vec_sol);CHKERRQ(ierr);
2025 
2026   ts->vec_sol = u;
2027 
2028   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2029   ierr = DMShellSetGlobalVector(dm,u);CHKERRQ(ierr);
2030   PetscFunctionReturn(0);
2031 }
2032 
2033 #undef __FUNCT__
2034 #define __FUNCT__ "TSSetPreStep"
2035 /*@C
2036   TSSetPreStep - Sets the general-purpose function
2037   called once at the beginning of each time step.
2038 
2039   Logically Collective on TS
2040 
2041   Input Parameters:
2042 + ts   - The TS context obtained from TSCreate()
2043 - func - The function
2044 
2045   Calling sequence of func:
2046 . func (TS ts);
2047 
2048   Level: intermediate
2049 
2050   Note:
2051   If a step is rejected, TSStep() will call this routine again before each attempt.
2052   The last completed time step number can be queried using TSGetTimeStepNumber(), the
2053   size of the step being attempted can be obtained using TSGetTimeStep().
2054 
2055 .keywords: TS, timestep
2056 .seealso: TSSetPreStage(), TSSetPostStep(), TSStep()
2057 @*/
2058 PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2059 {
2060   PetscFunctionBegin;
2061   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2062   ts->ops->prestep = func;
2063   PetscFunctionReturn(0);
2064 }
2065 
2066 #undef __FUNCT__
2067 #define __FUNCT__ "TSPreStep"
2068 /*@
2069   TSPreStep - Runs the user-defined pre-step function.
2070 
2071   Collective on TS
2072 
2073   Input Parameters:
2074 . ts   - The TS context obtained from TSCreate()
2075 
2076   Notes:
2077   TSPreStep() is typically used within time stepping implementations,
2078   so most users would not generally call this routine themselves.
2079 
2080   Level: developer
2081 
2082 .keywords: TS, timestep
2083 .seealso: TSSetPreStep(), TSPreStage(), TSPostStep()
2084 @*/
2085 PetscErrorCode  TSPreStep(TS ts)
2086 {
2087   PetscErrorCode ierr;
2088 
2089   PetscFunctionBegin;
2090   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2091   if (ts->ops->prestep) {
2092     PetscStackPush("TS PreStep function");
2093     ierr = (*ts->ops->prestep)(ts);CHKERRQ(ierr);
2094     PetscStackPop;
2095   }
2096   PetscFunctionReturn(0);
2097 }
2098 
2099 #undef __FUNCT__
2100 #define __FUNCT__ "TSSetPreStage"
2101 /*@C
2102   TSSetPreStage - Sets the general-purpose function
2103   called once at the beginning of each stage.
2104 
2105   Logically Collective on TS
2106 
2107   Input Parameters:
2108 + ts   - The TS context obtained from TSCreate()
2109 - func - The function
2110 
2111   Calling sequence of func:
2112 . PetscErrorCode func(TS ts, PetscReal stagetime);
2113 
2114   Level: intermediate
2115 
2116   Note:
2117   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2118   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2119   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
2120 
2121 .keywords: TS, timestep
2122 .seealso: TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2123 @*/
2124 PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2125 {
2126   PetscFunctionBegin;
2127   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2128   ts->ops->prestage = func;
2129   PetscFunctionReturn(0);
2130 }
2131 
2132 #undef __FUNCT__
2133 #define __FUNCT__ "TSPreStage"
2134 /*@
2135   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
2136 
2137   Collective on TS
2138 
2139   Input Parameters:
2140 . ts   - The TS context obtained from TSCreate()
2141 
2142   Notes:
2143   TSPreStage() is typically used within time stepping implementations,
2144   most users would not generally call this routine themselves.
2145 
2146   Level: developer
2147 
2148 .keywords: TS, timestep
2149 .seealso: TSSetPreStep(), TSPreStep(), TSPostStep()
2150 @*/
2151 PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
2152 {
2153   PetscErrorCode ierr;
2154 
2155   PetscFunctionBegin;
2156   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2157   if (ts->ops->prestage) {
2158     PetscStackPush("TS PreStage function");
2159     ierr = (*ts->ops->prestage)(ts,stagetime);CHKERRQ(ierr);
2160     PetscStackPop;
2161   }
2162   PetscFunctionReturn(0);
2163 }
2164 
2165 #undef __FUNCT__
2166 #define __FUNCT__ "TSSetPostStep"
2167 /*@C
2168   TSSetPostStep - Sets the general-purpose function
2169   called once at the end of each time step.
2170 
2171   Logically Collective on TS
2172 
2173   Input Parameters:
2174 + ts   - The TS context obtained from TSCreate()
2175 - func - The function
2176 
2177   Calling sequence of func:
2178 $ func (TS ts);
2179 
2180   Level: intermediate
2181 
2182 .keywords: TS, timestep
2183 .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2184 @*/
2185 PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2186 {
2187   PetscFunctionBegin;
2188   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2189   ts->ops->poststep = func;
2190   PetscFunctionReturn(0);
2191 }
2192 
2193 #undef __FUNCT__
2194 #define __FUNCT__ "TSPostStep"
2195 /*@
2196   TSPostStep - Runs the user-defined post-step function.
2197 
2198   Collective on TS
2199 
2200   Input Parameters:
2201 . ts   - The TS context obtained from TSCreate()
2202 
2203   Notes:
2204   TSPostStep() is typically used within time stepping implementations,
2205   so most users would not generally call this routine themselves.
2206 
2207   Level: developer
2208 
2209 .keywords: TS, timestep
2210 @*/
2211 PetscErrorCode  TSPostStep(TS ts)
2212 {
2213   PetscErrorCode ierr;
2214 
2215   PetscFunctionBegin;
2216   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2217   if (ts->ops->poststep) {
2218     PetscStackPush("TS PostStep function");
2219     ierr = (*ts->ops->poststep)(ts);CHKERRQ(ierr);
2220     PetscStackPop;
2221   }
2222   PetscFunctionReturn(0);
2223 }
2224 
2225 /* ------------ Routines to set performance monitoring options ----------- */
2226 
2227 #undef __FUNCT__
2228 #define __FUNCT__ "TSMonitorSet"
2229 /*@C
2230    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
2231    timestep to display the iteration's  progress.
2232 
2233    Logically Collective on TS
2234 
2235    Input Parameters:
2236 +  ts - the TS context obtained from TSCreate()
2237 .  monitor - monitoring routine
2238 .  mctx - [optional] user-defined context for private data for the
2239              monitor routine (use NULL if no context is desired)
2240 -  monitordestroy - [optional] routine that frees monitor context
2241           (may be NULL)
2242 
2243    Calling sequence of monitor:
2244 $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)
2245 
2246 +    ts - the TS context
2247 .    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
2248                                been interpolated to)
2249 .    time - current time
2250 .    u - current iterate
2251 -    mctx - [optional] monitoring context
2252 
2253    Notes:
2254    This routine adds an additional monitor to the list of monitors that
2255    already has been loaded.
2256 
2257    Fortran notes: Only a single monitor function can be set for each TS object
2258 
2259    Level: intermediate
2260 
2261 .keywords: TS, timestep, set, monitor
2262 
2263 .seealso: TSMonitorDefault(), TSMonitorCancel()
2264 @*/
2265 PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
2266 {
2267   PetscFunctionBegin;
2268   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2269   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
2270   ts->monitor[ts->numbermonitors]          = monitor;
2271   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
2272   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
2273   PetscFunctionReturn(0);
2274 }
2275 
2276 #undef __FUNCT__
2277 #define __FUNCT__ "TSMonitorCancel"
2278 /*@C
2279    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.
2280 
2281    Logically Collective on TS
2282 
2283    Input Parameters:
2284 .  ts - the TS context obtained from TSCreate()
2285 
2286    Notes:
2287    There is no way to remove a single, specific monitor.
2288 
2289    Level: intermediate
2290 
2291 .keywords: TS, timestep, set, monitor
2292 
2293 .seealso: TSMonitorDefault(), TSMonitorSet()
2294 @*/
2295 PetscErrorCode  TSMonitorCancel(TS ts)
2296 {
2297   PetscErrorCode ierr;
2298   PetscInt       i;
2299 
2300   PetscFunctionBegin;
2301   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2302   for (i=0; i<ts->numbermonitors; i++) {
2303     if (ts->monitordestroy[i]) {
2304       ierr = (*ts->monitordestroy[i])(&ts->monitorcontext[i]);CHKERRQ(ierr);
2305     }
2306   }
2307   ts->numbermonitors = 0;
2308   PetscFunctionReturn(0);
2309 }
2310 
2311 #undef __FUNCT__
2312 #define __FUNCT__ "TSMonitorDefault"
2313 /*@
2314    TSMonitorDefault - Sets the Default monitor
2315 
2316    Level: intermediate
2317 
2318 .keywords: TS, set, monitor
2319 
2320 .seealso: TSMonitorDefault(), TSMonitorSet()
2321 @*/
2322 PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
2323 {
2324   PetscErrorCode ierr;
2325   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));
2326 
2327   PetscFunctionBegin;
2328   ierr = PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
2329   ierr = PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g\n",step,(double)ts->time_step,(double)ptime);CHKERRQ(ierr);
2330   ierr = PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);CHKERRQ(ierr);
2331   PetscFunctionReturn(0);
2332 }
2333 
2334 #undef __FUNCT__
2335 #define __FUNCT__ "TSSetRetainStages"
2336 /*@
2337    TSSetRetainStages - Request that all stages in the upcoming step be stored so that interpolation will be available.
2338 
2339    Logically Collective on TS
2340 
2341    Input Argument:
2342 .  ts - time stepping context
2343 
2344    Output Argument:
2345 .  flg - PETSC_TRUE or PETSC_FALSE
2346 
2347    Level: intermediate
2348 
2349 .keywords: TS, set
2350 
2351 .seealso: TSInterpolate(), TSSetPostStep()
2352 @*/
2353 PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
2354 {
2355   PetscFunctionBegin;
2356   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2357   ts->retain_stages = flg;
2358   PetscFunctionReturn(0);
2359 }
2360 
2361 #undef __FUNCT__
2362 #define __FUNCT__ "TSInterpolate"
2363 /*@
2364    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
2365 
2366    Collective on TS
2367 
2368    Input Argument:
2369 +  ts - time stepping context
2370 -  t - time to interpolate to
2371 
2372    Output Argument:
2373 .  U - state at given time
2374 
2375    Notes:
2376    The user should call TSSetRetainStages() before taking a step in which interpolation will be requested.
2377 
2378    Level: intermediate
2379 
2380    Developer Notes:
2381    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
2382 
2383 .keywords: TS, set
2384 
2385 .seealso: TSSetRetainStages(), TSSetPostStep()
2386 @*/
2387 PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
2388 {
2389   PetscErrorCode ierr;
2390 
2391   PetscFunctionBegin;
2392   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2393   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,ts->ptime-ts->time_step_prev,ts->ptime);
2394   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
2395   ierr = (*ts->ops->interpolate)(ts,t,U);CHKERRQ(ierr);
2396   PetscFunctionReturn(0);
2397 }
2398 
2399 #undef __FUNCT__
2400 #define __FUNCT__ "TSStep"
2401 /*@
2402    TSStep - Steps one time step
2403 
2404    Collective on TS
2405 
2406    Input Parameter:
2407 .  ts - the TS context obtained from TSCreate()
2408 
2409    Level: intermediate
2410 
2411    Notes:
2412    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
2413    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
2414 
2415    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
2416    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
2417 
2418 .keywords: TS, timestep, solve
2419 
2420 .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
2421 @*/
2422 PetscErrorCode  TSStep(TS ts)
2423 {
2424   PetscReal      ptime_prev;
2425   PetscErrorCode ierr;
2426 
2427   PetscFunctionBegin;
2428   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2429   ierr = TSSetUp(ts);CHKERRQ(ierr);
2430 
2431   ts->reason = TS_CONVERGED_ITERATING;
2432   ptime_prev = ts->ptime;
2433 
2434   ierr = PetscLogEventBegin(TS_Step,ts,0,0,0);CHKERRQ(ierr);
2435   ierr = (*ts->ops->step)(ts);CHKERRQ(ierr);
2436   ierr = PetscLogEventEnd(TS_Step,ts,0,0,0);CHKERRQ(ierr);
2437 
2438   ts->time_step_prev = ts->ptime - ptime_prev;
2439 
2440   if (ts->reason < 0) {
2441     if (ts->errorifstepfailed) {
2442       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
2443         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]);
2444       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
2445     }
2446   } else if (!ts->reason) {
2447     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
2448     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
2449   }
2450   PetscFunctionReturn(0);
2451 }
2452 
2453 #undef __FUNCT__
2454 #define __FUNCT__ "TSEvaluateStep"
2455 /*@
2456    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
2457 
2458    Collective on TS
2459 
2460    Input Arguments:
2461 +  ts - time stepping context
2462 .  order - desired order of accuracy
2463 -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
2464 
2465    Output Arguments:
2466 .  U - state at the end of the current step
2467 
2468    Level: advanced
2469 
2470    Notes:
2471    This function cannot be called until all stages have been evaluated.
2472    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.
2473 
2474 .seealso: TSStep(), TSAdapt
2475 @*/
2476 PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
2477 {
2478   PetscErrorCode ierr;
2479 
2480   PetscFunctionBegin;
2481   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2482   PetscValidType(ts,1);
2483   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
2484   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
2485   ierr = (*ts->ops->evaluatestep)(ts,order,U,done);CHKERRQ(ierr);
2486   PetscFunctionReturn(0);
2487 }
2488 
2489 #undef __FUNCT__
2490 #define __FUNCT__ "TSSolve"
2491 /*@
2492    TSSolve - Steps the requested number of timesteps.
2493 
2494    Collective on TS
2495 
2496    Input Parameter:
2497 +  ts - the TS context obtained from TSCreate()
2498 -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)
2499 
2500    Level: beginner
2501 
2502    Notes:
2503    The final time returned by this function may be different from the time of the internally
2504    held state accessible by TSGetSolution() and TSGetTime() because the method may have
2505    stepped over the final time.
2506 
2507 .keywords: TS, timestep, solve
2508 
2509 .seealso: TSCreate(), TSSetSolution(), TSStep()
2510 @*/
2511 PetscErrorCode TSSolve(TS ts,Vec u)
2512 {
2513   PetscBool         flg;
2514   PetscViewer       viewer;
2515   PetscErrorCode    ierr;
2516   PetscViewerFormat format;
2517 
2518   PetscFunctionBegin;
2519   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2520   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
2521   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 */
2522     if (!ts->vec_sol || u == ts->vec_sol) {
2523       Vec y;
2524       ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
2525       ierr = TSSetSolution(ts,y);CHKERRQ(ierr);
2526       ierr = VecDestroy(&y);CHKERRQ(ierr); /* grant ownership */
2527     }
2528     if (u) {
2529       ierr = VecCopy(u,ts->vec_sol);CHKERRQ(ierr);
2530     }
2531   } else if (u) {
2532     ierr = TSSetSolution(ts,u);CHKERRQ(ierr);
2533   }
2534   ierr = TSSetUp(ts);CHKERRQ(ierr);
2535   /* reset time step and iteration counters */
2536   ts->steps             = 0;
2537   ts->ksp_its           = 0;
2538   ts->snes_its          = 0;
2539   ts->num_snes_failures = 0;
2540   ts->reject            = 0;
2541   ts->reason            = TS_CONVERGED_ITERATING;
2542 
2543   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
2544     ierr = (*ts->ops->solve)(ts);CHKERRQ(ierr);
2545     ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);
2546 
2547     ts->solvetime = ts->ptime;
2548   } else {
2549     /* steps the requested number of timesteps. */
2550     ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
2551     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
2552     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
2553     while (!ts->reason) {
2554       ierr = TSStep(ts);CHKERRQ(ierr);
2555       ierr = TSPostStep(ts);CHKERRQ(ierr);
2556       ierr = TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
2557     }
2558     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
2559       ierr = TSInterpolate(ts,ts->max_time,u);CHKERRQ(ierr);
2560 
2561       ts->solvetime = ts->max_time;
2562     } else {
2563       if (u) {ierr = VecCopy(ts->vec_sol,u);CHKERRQ(ierr);}
2564       ts->solvetime = ts->ptime;
2565     }
2566   }
2567   ierr = TSMonitor(ts,-1,ts->ptime,ts->vec_sol);CHKERRQ(ierr);
2568   ierr = PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,"-ts_view",&viewer,&format,&flg);CHKERRQ(ierr);
2569   if (flg && !PetscPreLoadingOn) {
2570     ierr = PetscViewerPushFormat(viewer,format);CHKERRQ(ierr);
2571     ierr = TSView(ts,viewer);CHKERRQ(ierr);
2572     ierr = PetscViewerPopFormat(viewer);CHKERRQ(ierr);
2573     ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
2574   }
2575   PetscFunctionReturn(0);
2576 }
2577 
2578 #undef __FUNCT__
2579 #define __FUNCT__ "TSMonitor"
2580 /*@
2581    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()
2582 
2583    Collective on TS
2584 
2585    Input Parameters:
2586 +  ts - time stepping context obtained from TSCreate()
2587 .  step - step number that has just completed
2588 .  ptime - model time of the state
2589 -  u - state at the current model time
2590 
2591    Notes:
2592    TSMonitor() is typically used within the time stepping implementations.
2593    Users might call this function when using the TSStep() interface instead of TSSolve().
2594 
2595    Level: advanced
2596 
2597 .keywords: TS, timestep
2598 @*/
2599 PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
2600 {
2601   PetscErrorCode ierr;
2602   PetscInt       i,n = ts->numbermonitors;
2603 
2604   PetscFunctionBegin;
2605   for (i=0; i<n; i++) {
2606     ierr = (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);CHKERRQ(ierr);
2607   }
2608   PetscFunctionReturn(0);
2609 }
2610 
2611 /* ------------------------------------------------------------------------*/
2612 struct _n_TSMonitorLGCtx {
2613   PetscDrawLG lg;
2614   PetscInt    howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
2615   PetscInt    ksp_its,snes_its;
2616 };
2617 
2618 
2619 #undef __FUNCT__
2620 #define __FUNCT__ "TSMonitorLGCtxCreate"
2621 /*@C
2622    TSMonitorLGCtxCreate - Creates a line graph context for use with
2623    TS to monitor the solution process graphically in various ways
2624 
2625    Collective on TS
2626 
2627    Input Parameters:
2628 +  host - the X display to open, or null for the local machine
2629 .  label - the title to put in the title bar
2630 .  x, y - the screen coordinates of the upper left coordinate of the window
2631 .  m, n - the screen width and height in pixels
2632 -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time
2633 
2634    Output Parameter:
2635 .  ctx - the context
2636 
2637    Options Database Key:
2638 +  -ts_monitor_lg_timestep - automatically sets line graph monitor
2639 .  -ts_monitor_lg_solution -
2640 .  -ts_monitor_lg_error -
2641 .  -ts_monitor_lg_ksp_iterations -
2642 .  -ts_monitor_lg_snes_iterations -
2643 -  -lg_indicate_data_points <true,false> - indicate the data points (at each time step) on the plot; default is true
2644 
2645    Notes:
2646    Use TSMonitorLGCtxDestroy() to destroy.
2647 
2648    Level: intermediate
2649 
2650 .keywords: TS, monitor, line graph, residual, seealso
2651 
2652 .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()
2653 
2654 @*/
2655 PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
2656 {
2657   PetscDraw      win;
2658   PetscErrorCode ierr;
2659   PetscBool      flg = PETSC_TRUE;
2660 
2661   PetscFunctionBegin;
2662   ierr = PetscNew(struct _n_TSMonitorLGCtx,ctx);CHKERRQ(ierr);
2663   ierr = PetscDrawCreate(comm,host,label,x,y,m,n,&win);CHKERRQ(ierr);
2664   ierr = PetscDrawSetFromOptions(win);CHKERRQ(ierr);
2665   ierr = PetscDrawLGCreate(win,1,&(*ctx)->lg);CHKERRQ(ierr);
2666   ierr = PetscOptionsGetBool(NULL,"-lg_indicate_data_points",&flg,NULL);CHKERRQ(ierr);
2667   if (flg) {
2668     ierr = PetscDrawLGIndicateDataPoints((*ctx)->lg);CHKERRQ(ierr);
2669   }
2670   ierr = PetscLogObjectParent((*ctx)->lg,win);CHKERRQ(ierr);
2671   (*ctx)->howoften = howoften;
2672   PetscFunctionReturn(0);
2673 }
2674 
2675 #undef __FUNCT__
2676 #define __FUNCT__ "TSMonitorLGTimeStep"
2677 PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
2678 {
2679   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
2680   PetscReal      x   = ptime,y;
2681   PetscErrorCode ierr;
2682 
2683   PetscFunctionBegin;
2684   if (!n) {
2685     PetscDrawAxis axis;
2686     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
2687     ierr = PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");CHKERRQ(ierr);
2688     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
2689   }
2690   ierr = TSGetTimeStep(ts,&y);CHKERRQ(ierr);
2691   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
2692   if (((ctx->howoften > 0) && (!(n % ctx->howoften))) || ((ctx->howoften == -1) && (n == -1))) {
2693     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
2694   }
2695   PetscFunctionReturn(0);
2696 }
2697 
2698 #undef __FUNCT__
2699 #define __FUNCT__ "TSMonitorLGCtxDestroy"
2700 /*@C
2701    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
2702    with TSMonitorLGCtxCreate().
2703 
2704    Collective on TSMonitorLGCtx
2705 
2706    Input Parameter:
2707 .  ctx - the monitor context
2708 
2709    Level: intermediate
2710 
2711 .keywords: TS, monitor, line graph, destroy
2712 
2713 .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
2714 @*/
2715 PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
2716 {
2717   PetscDraw      draw;
2718   PetscErrorCode ierr;
2719 
2720   PetscFunctionBegin;
2721   ierr = PetscDrawLGGetDraw((*ctx)->lg,&draw);CHKERRQ(ierr);
2722   ierr = PetscDrawDestroy(&draw);CHKERRQ(ierr);
2723   ierr = PetscDrawLGDestroy(&(*ctx)->lg);CHKERRQ(ierr);
2724   ierr = PetscFree(*ctx);CHKERRQ(ierr);
2725   PetscFunctionReturn(0);
2726 }
2727 
2728 #undef __FUNCT__
2729 #define __FUNCT__ "TSGetTime"
2730 /*@
2731    TSGetTime - Gets the time of the most recently completed step.
2732 
2733    Not Collective
2734 
2735    Input Parameter:
2736 .  ts - the TS context obtained from TSCreate()
2737 
2738    Output Parameter:
2739 .  t  - the current time
2740 
2741    Level: beginner
2742 
2743    Note:
2744    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
2745    TSSetPreStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
2746 
2747 .seealso: TSSetInitialTimeStep(), TSGetTimeStep()
2748 
2749 .keywords: TS, get, time
2750 @*/
2751 PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
2752 {
2753   PetscFunctionBegin;
2754   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2755   PetscValidRealPointer(t,2);
2756   *t = ts->ptime;
2757   PetscFunctionReturn(0);
2758 }
2759 
2760 #undef __FUNCT__
2761 #define __FUNCT__ "TSSetTime"
2762 /*@
2763    TSSetTime - Allows one to reset the time.
2764 
2765    Logically Collective on TS
2766 
2767    Input Parameters:
2768 +  ts - the TS context obtained from TSCreate()
2769 -  time - the time
2770 
2771    Level: intermediate
2772 
2773 .seealso: TSGetTime(), TSSetDuration()
2774 
2775 .keywords: TS, set, time
2776 @*/
2777 PetscErrorCode  TSSetTime(TS ts, PetscReal t)
2778 {
2779   PetscFunctionBegin;
2780   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2781   PetscValidLogicalCollectiveReal(ts,t,2);
2782   ts->ptime = t;
2783   PetscFunctionReturn(0);
2784 }
2785 
2786 #undef __FUNCT__
2787 #define __FUNCT__ "TSSetOptionsPrefix"
2788 /*@C
2789    TSSetOptionsPrefix - Sets the prefix used for searching for all
2790    TS options in the database.
2791 
2792    Logically Collective on TS
2793 
2794    Input Parameter:
2795 +  ts     - The TS context
2796 -  prefix - The prefix to prepend to all option names
2797 
2798    Notes:
2799    A hyphen (-) must NOT be given at the beginning of the prefix name.
2800    The first character of all runtime options is AUTOMATICALLY the
2801    hyphen.
2802 
2803    Level: advanced
2804 
2805 .keywords: TS, set, options, prefix, database
2806 
2807 .seealso: TSSetFromOptions()
2808 
2809 @*/
2810 PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
2811 {
2812   PetscErrorCode ierr;
2813   SNES           snes;
2814 
2815   PetscFunctionBegin;
2816   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2817   ierr = PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
2818   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2819   ierr = SNESSetOptionsPrefix(snes,prefix);CHKERRQ(ierr);
2820   PetscFunctionReturn(0);
2821 }
2822 
2823 
2824 #undef __FUNCT__
2825 #define __FUNCT__ "TSAppendOptionsPrefix"
2826 /*@C
2827    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
2828    TS options in the database.
2829 
2830    Logically Collective on TS
2831 
2832    Input Parameter:
2833 +  ts     - The TS context
2834 -  prefix - The prefix to prepend to all option names
2835 
2836    Notes:
2837    A hyphen (-) must NOT be given at the beginning of the prefix name.
2838    The first character of all runtime options is AUTOMATICALLY the
2839    hyphen.
2840 
2841    Level: advanced
2842 
2843 .keywords: TS, append, options, prefix, database
2844 
2845 .seealso: TSGetOptionsPrefix()
2846 
2847 @*/
2848 PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
2849 {
2850   PetscErrorCode ierr;
2851   SNES           snes;
2852 
2853   PetscFunctionBegin;
2854   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2855   ierr = PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
2856   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2857   ierr = SNESAppendOptionsPrefix(snes,prefix);CHKERRQ(ierr);
2858   PetscFunctionReturn(0);
2859 }
2860 
2861 #undef __FUNCT__
2862 #define __FUNCT__ "TSGetOptionsPrefix"
2863 /*@C
2864    TSGetOptionsPrefix - Sets the prefix used for searching for all
2865    TS options in the database.
2866 
2867    Not Collective
2868 
2869    Input Parameter:
2870 .  ts - The TS context
2871 
2872    Output Parameter:
2873 .  prefix - A pointer to the prefix string used
2874 
2875    Notes: On the fortran side, the user should pass in a string 'prifix' of
2876    sufficient length to hold the prefix.
2877 
2878    Level: intermediate
2879 
2880 .keywords: TS, get, options, prefix, database
2881 
2882 .seealso: TSAppendOptionsPrefix()
2883 @*/
2884 PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
2885 {
2886   PetscErrorCode ierr;
2887 
2888   PetscFunctionBegin;
2889   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2890   PetscValidPointer(prefix,2);
2891   ierr = PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);CHKERRQ(ierr);
2892   PetscFunctionReturn(0);
2893 }
2894 
2895 #undef __FUNCT__
2896 #define __FUNCT__ "TSGetRHSJacobian"
2897 /*@C
2898    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
2899 
2900    Not Collective, but parallel objects are returned if TS is parallel
2901 
2902    Input Parameter:
2903 .  ts  - The TS context obtained from TSCreate()
2904 
2905    Output Parameters:
2906 +  J   - The Jacobian J of F, where U_t = G(U,t)
2907 .  M   - The preconditioner matrix, usually the same as J
2908 .  func - Function to compute the Jacobian of the RHS
2909 -  ctx - User-defined context for Jacobian evaluation routine
2910 
2911    Notes: You can pass in NULL for any return argument you do not need.
2912 
2913    Level: intermediate
2914 
2915 .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
2916 
2917 .keywords: TS, timestep, get, matrix, Jacobian
2918 @*/
2919 PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *J,Mat *M,TSRHSJacobian *func,void **ctx)
2920 {
2921   PetscErrorCode ierr;
2922   SNES           snes;
2923   DM             dm;
2924 
2925   PetscFunctionBegin;
2926   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2927   ierr = SNESGetJacobian(snes,J,M,NULL,NULL);CHKERRQ(ierr);
2928   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2929   ierr = DMTSGetRHSJacobian(dm,func,ctx);CHKERRQ(ierr);
2930   PetscFunctionReturn(0);
2931 }
2932 
2933 #undef __FUNCT__
2934 #define __FUNCT__ "TSGetIJacobian"
2935 /*@C
2936    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
2937 
2938    Not Collective, but parallel objects are returned if TS is parallel
2939 
2940    Input Parameter:
2941 .  ts  - The TS context obtained from TSCreate()
2942 
2943    Output Parameters:
2944 +  A   - The Jacobian of F(t,U,U_t)
2945 .  B   - The preconditioner matrix, often the same as A
2946 .  f   - The function to compute the matrices
2947 - ctx - User-defined context for Jacobian evaluation routine
2948 
2949    Notes: You can pass in NULL for any return argument you do not need.
2950 
2951    Level: advanced
2952 
2953 .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()
2954 
2955 .keywords: TS, timestep, get, matrix, Jacobian
2956 @*/
2957 PetscErrorCode  TSGetIJacobian(TS ts,Mat *A,Mat *B,TSIJacobian *f,void **ctx)
2958 {
2959   PetscErrorCode ierr;
2960   SNES           snes;
2961   DM             dm;
2962 
2963   PetscFunctionBegin;
2964   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
2965   ierr = SNESSetUpMatrices(snes);CHKERRQ(ierr);
2966   ierr = SNESGetJacobian(snes,A,B,NULL,NULL);CHKERRQ(ierr);
2967   ierr = TSGetDM(ts,&dm);CHKERRQ(ierr);
2968   ierr = DMTSGetIJacobian(dm,f,ctx);CHKERRQ(ierr);
2969   PetscFunctionReturn(0);
2970 }
2971 
2972 
2973 #undef __FUNCT__
2974 #define __FUNCT__ "TSMonitorDrawSolution"
2975 /*@C
2976    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
2977    VecView() for the solution at each timestep
2978 
2979    Collective on TS
2980 
2981    Input Parameters:
2982 +  ts - the TS context
2983 .  step - current time-step
2984 .  ptime - current time
2985 -  dummy - either a viewer or NULL
2986 
2987    Options Database:
2988 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
2989 
2990    Notes: the initial solution and current solution are not displayed with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
2991        will look bad
2992 
2993    Level: intermediate
2994 
2995 .keywords: TS,  vector, monitor, view
2996 
2997 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
2998 @*/
2999 PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3000 {
3001   PetscErrorCode   ierr;
3002   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
3003   PetscDraw        draw;
3004 
3005   PetscFunctionBegin;
3006   if (!step && ictx->showinitial) {
3007     if (!ictx->initialsolution) {
3008       ierr = VecDuplicate(u,&ictx->initialsolution);CHKERRQ(ierr);
3009     }
3010     ierr = VecCopy(u,ictx->initialsolution);CHKERRQ(ierr);
3011   }
3012   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften)) && (step > -1)) || ((ictx->howoften == -1) && (step == -1)))) PetscFunctionReturn(0);
3013 
3014   if (ictx->showinitial) {
3015     PetscReal pause;
3016     ierr = PetscViewerDrawGetPause(ictx->viewer,&pause);CHKERRQ(ierr);
3017     ierr = PetscViewerDrawSetPause(ictx->viewer,0.0);CHKERRQ(ierr);
3018     ierr = VecView(ictx->initialsolution,ictx->viewer);CHKERRQ(ierr);
3019     ierr = PetscViewerDrawSetPause(ictx->viewer,pause);CHKERRQ(ierr);
3020     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);CHKERRQ(ierr);
3021   }
3022   ierr = VecView(u,ictx->viewer);CHKERRQ(ierr);
3023   if (ictx->showtimestepandtime) {
3024     PetscReal xl,yl,xr,yr,tw,w,h;
3025     char      time[32];
3026     size_t    len;
3027 
3028     ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
3029     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
3030     ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
3031     ierr =  PetscStrlen(time,&len);CHKERRQ(ierr);
3032     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
3033     w    = xl + .5*(xr - xl) - .5*len*tw;
3034     h    = yl + .95*(yr - yl);
3035     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
3036     ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
3037   }
3038 
3039   if (ictx->showinitial) {
3040     ierr = PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);CHKERRQ(ierr);
3041   }
3042   PetscFunctionReturn(0);
3043 }
3044 
3045 #undef __FUNCT__
3046 #define __FUNCT__ "TSMonitorDrawSolutionPhase"
3047 /*@C
3048    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram
3049 
3050    Collective on TS
3051 
3052    Input Parameters:
3053 +  ts - the TS context
3054 .  step - current time-step
3055 .  ptime - current time
3056 -  dummy - either a viewer or NULL
3057 
3058    Level: intermediate
3059 
3060 .keywords: TS,  vector, monitor, view
3061 
3062 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3063 @*/
3064 PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3065 {
3066   PetscErrorCode    ierr;
3067   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
3068   PetscDraw         draw;
3069   MPI_Comm          comm;
3070   PetscInt          n;
3071   PetscMPIInt       size;
3072   PetscReal         xl,yl,xr,yr,tw,w,h;
3073   char              time[32];
3074   size_t            len;
3075   const PetscScalar *U;
3076 
3077   PetscFunctionBegin;
3078   ierr = PetscObjectGetComm((PetscObject)ts,&comm);CHKERRQ(ierr);
3079   ierr = MPI_Comm_size(comm,&size);CHKERRQ(ierr);
3080   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
3081   ierr = VecGetSize(u,&n);CHKERRQ(ierr);
3082   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");
3083 
3084   ierr = PetscViewerDrawGetDraw(ictx->viewer,0,&draw);CHKERRQ(ierr);
3085 
3086   ierr = VecGetArrayRead(u,&U);CHKERRQ(ierr);
3087   ierr = PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);CHKERRQ(ierr);
3088   if ((U[0] < xl) || (U[1] < yl) || (U[0] > xr) || (U[1] > yr)) {
3089       ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
3090       PetscFunctionReturn(0);
3091   }
3092   if (!step) ictx->color++;
3093   ierr = PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);CHKERRQ(ierr);
3094   ierr = VecRestoreArrayRead(u,&U);CHKERRQ(ierr);
3095 
3096   if (ictx->showtimestepandtime) {
3097     ierr = PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);CHKERRQ(ierr);
3098     ierr = PetscStrlen(time,&len);CHKERRQ(ierr);
3099     ierr = PetscDrawStringGetSize(draw,&tw,NULL);CHKERRQ(ierr);
3100     w    = xl + .5*(xr - xl) - .5*len*tw;
3101     h    = yl + .95*(yr - yl);
3102     ierr = PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);CHKERRQ(ierr);
3103   }
3104   ierr = PetscDrawFlush(draw);CHKERRQ(ierr);
3105   PetscFunctionReturn(0);
3106 }
3107 
3108 
3109 #undef __FUNCT__
3110 #define __FUNCT__ "TSMonitorDrawCtxDestroy"
3111 /*@C
3112    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()
3113 
3114    Collective on TS
3115 
3116    Input Parameters:
3117 .    ctx - the monitor context
3118 
3119    Level: intermediate
3120 
3121 .keywords: TS,  vector, monitor, view
3122 
3123 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
3124 @*/
3125 PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
3126 {
3127   PetscErrorCode ierr;
3128 
3129   PetscFunctionBegin;
3130   ierr = PetscViewerDestroy(&(*ictx)->viewer);CHKERRQ(ierr);
3131   ierr = VecDestroy(&(*ictx)->initialsolution);CHKERRQ(ierr);
3132   ierr = PetscFree(*ictx);CHKERRQ(ierr);
3133   PetscFunctionReturn(0);
3134 }
3135 
3136 #undef __FUNCT__
3137 #define __FUNCT__ "TSMonitorDrawCtxCreate"
3138 /*@C
3139    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx
3140 
3141    Collective on TS
3142 
3143    Input Parameter:
3144 .    ts - time-step context
3145 
3146    Output Patameter:
3147 .    ctx - the monitor context
3148 
3149    Options Database:
3150 .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution
3151 
3152    Level: intermediate
3153 
3154 .keywords: TS,  vector, monitor, view
3155 
3156 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
3157 @*/
3158 PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
3159 {
3160   PetscErrorCode   ierr;
3161 
3162   PetscFunctionBegin;
3163   ierr = PetscNew(struct _n_TSMonitorDrawCtx,ctx);CHKERRQ(ierr);
3164   ierr = PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);CHKERRQ(ierr);
3165   ierr = PetscViewerSetFromOptions((*ctx)->viewer);CHKERRQ(ierr);
3166 
3167   (*ctx)->howoften    = howoften;
3168   (*ctx)->showinitial = PETSC_FALSE;
3169   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);CHKERRQ(ierr);
3170 
3171   (*ctx)->showtimestepandtime = PETSC_FALSE;
3172   ierr = PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);CHKERRQ(ierr);
3173   (*ctx)->color = PETSC_DRAW_WHITE;
3174   PetscFunctionReturn(0);
3175 }
3176 
3177 #undef __FUNCT__
3178 #define __FUNCT__ "TSMonitorDrawError"
3179 /*@C
3180    TSMonitorDrawError - Monitors progress of the TS solvers by calling
3181    VecView() for the error at each timestep
3182 
3183    Collective on TS
3184 
3185    Input Parameters:
3186 +  ts - the TS context
3187 .  step - current time-step
3188 .  ptime - current time
3189 -  dummy - either a viewer or NULL
3190 
3191    Level: intermediate
3192 
3193 .keywords: TS,  vector, monitor, view
3194 
3195 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3196 @*/
3197 PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3198 {
3199   PetscErrorCode   ierr;
3200   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
3201   PetscViewer      viewer = ctx->viewer;
3202   Vec              work;
3203 
3204   PetscFunctionBegin;
3205   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften)) && (step > -1)) || ((ctx->howoften == -1) && (step == -1)))) PetscFunctionReturn(0);
3206   ierr = VecDuplicate(u,&work);CHKERRQ(ierr);
3207   ierr = TSComputeSolutionFunction(ts,ptime,work);CHKERRQ(ierr);
3208   ierr = VecAXPY(work,-1.0,u);CHKERRQ(ierr);
3209   ierr = VecView(work,viewer);CHKERRQ(ierr);
3210   ierr = VecDestroy(&work);CHKERRQ(ierr);
3211   PetscFunctionReturn(0);
3212 }
3213 
3214 #include <petsc-private/dmimpl.h>
3215 #undef __FUNCT__
3216 #define __FUNCT__ "TSSetDM"
3217 /*@
3218    TSSetDM - Sets the DM that may be used by some preconditioners
3219 
3220    Logically Collective on TS and DM
3221 
3222    Input Parameters:
3223 +  ts - the preconditioner context
3224 -  dm - the dm
3225 
3226    Level: intermediate
3227 
3228 
3229 .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
3230 @*/
3231 PetscErrorCode  TSSetDM(TS ts,DM dm)
3232 {
3233   PetscErrorCode ierr;
3234   SNES           snes;
3235   DMTS           tsdm;
3236 
3237   PetscFunctionBegin;
3238   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3239   ierr = PetscObjectReference((PetscObject)dm);CHKERRQ(ierr);
3240   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
3241     if (ts->dm->dmts && !dm->dmts) {
3242       ierr = DMCopyDMTS(ts->dm,dm);CHKERRQ(ierr);
3243       ierr = DMGetDMTS(ts->dm,&tsdm);CHKERRQ(ierr);
3244       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
3245         tsdm->originaldm = dm;
3246       }
3247     }
3248     ierr = DMDestroy(&ts->dm);CHKERRQ(ierr);
3249   }
3250   ts->dm = dm;
3251 
3252   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
3253   ierr = SNESSetDM(snes,dm);CHKERRQ(ierr);
3254   PetscFunctionReturn(0);
3255 }
3256 
3257 #undef __FUNCT__
3258 #define __FUNCT__ "TSGetDM"
3259 /*@
3260    TSGetDM - Gets the DM that may be used by some preconditioners
3261 
3262    Not Collective
3263 
3264    Input Parameter:
3265 . ts - the preconditioner context
3266 
3267    Output Parameter:
3268 .  dm - the dm
3269 
3270    Level: intermediate
3271 
3272 
3273 .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
3274 @*/
3275 PetscErrorCode  TSGetDM(TS ts,DM *dm)
3276 {
3277   PetscErrorCode ierr;
3278 
3279   PetscFunctionBegin;
3280   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3281   if (!ts->dm) {
3282     ierr = DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);CHKERRQ(ierr);
3283     if (ts->snes) {ierr = SNESSetDM(ts->snes,ts->dm);CHKERRQ(ierr);}
3284   }
3285   *dm = ts->dm;
3286   PetscFunctionReturn(0);
3287 }
3288 
3289 #undef __FUNCT__
3290 #define __FUNCT__ "SNESTSFormFunction"
3291 /*@
3292    SNESTSFormFunction - Function to evaluate nonlinear residual
3293 
3294    Logically Collective on SNES
3295 
3296    Input Parameter:
3297 + snes - nonlinear solver
3298 . U - the current state at which to evaluate the residual
3299 - ctx - user context, must be a TS
3300 
3301    Output Parameter:
3302 . F - the nonlinear residual
3303 
3304    Notes:
3305    This function is not normally called by users and is automatically registered with the SNES used by TS.
3306    It is most frequently passed to MatFDColoringSetFunction().
3307 
3308    Level: advanced
3309 
3310 .seealso: SNESSetFunction(), MatFDColoringSetFunction()
3311 @*/
3312 PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
3313 {
3314   TS             ts = (TS)ctx;
3315   PetscErrorCode ierr;
3316 
3317   PetscFunctionBegin;
3318   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3319   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
3320   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
3321   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
3322   ierr = (ts->ops->snesfunction)(snes,U,F,ts);CHKERRQ(ierr);
3323   PetscFunctionReturn(0);
3324 }
3325 
3326 #undef __FUNCT__
3327 #define __FUNCT__ "SNESTSFormJacobian"
3328 /*@
3329    SNESTSFormJacobian - Function to evaluate the Jacobian
3330 
3331    Collective on SNES
3332 
3333    Input Parameter:
3334 + snes - nonlinear solver
3335 . U - the current state at which to evaluate the residual
3336 - ctx - user context, must be a TS
3337 
3338    Output Parameter:
3339 + A - the Jacobian
3340 . B - the preconditioning matrix (may be the same as A)
3341 - flag - indicates any structure change in the matrix
3342 
3343    Notes:
3344    This function is not normally called by users and is automatically registered with the SNES used by TS.
3345 
3346    Level: developer
3347 
3348 .seealso: SNESSetJacobian()
3349 @*/
3350 PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat *A,Mat *B,MatStructure *flag,void *ctx)
3351 {
3352   TS             ts = (TS)ctx;
3353   PetscErrorCode ierr;
3354 
3355   PetscFunctionBegin;
3356   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
3357   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
3358   PetscValidPointer(A,3);
3359   PetscValidHeaderSpecific(*A,MAT_CLASSID,3);
3360   PetscValidPointer(B,4);
3361   PetscValidHeaderSpecific(*B,MAT_CLASSID,4);
3362   PetscValidPointer(flag,5);
3363   PetscValidHeaderSpecific(ts,TS_CLASSID,6);
3364   ierr = (ts->ops->snesjacobian)(snes,U,A,B,flag,ts);CHKERRQ(ierr);
3365   PetscFunctionReturn(0);
3366 }
3367 
3368 #undef __FUNCT__
3369 #define __FUNCT__ "TSComputeRHSFunctionLinear"
3370 /*@C
3371    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems only
3372 
3373    Collective on TS
3374 
3375    Input Arguments:
3376 +  ts - time stepping context
3377 .  t - time at which to evaluate
3378 .  U - state at which to evaluate
3379 -  ctx - context
3380 
3381    Output Arguments:
3382 .  F - right hand side
3383 
3384    Level: intermediate
3385 
3386    Notes:
3387    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
3388    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
3389 
3390 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
3391 @*/
3392 PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
3393 {
3394   PetscErrorCode ierr;
3395   Mat            Arhs,Brhs;
3396   MatStructure   flg2;
3397 
3398   PetscFunctionBegin;
3399   ierr = TSGetRHSMats_Private(ts,&Arhs,&Brhs);CHKERRQ(ierr);
3400   ierr = TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);CHKERRQ(ierr);
3401   ierr = MatMult(Arhs,U,F);CHKERRQ(ierr);
3402   PetscFunctionReturn(0);
3403 }
3404 
3405 #undef __FUNCT__
3406 #define __FUNCT__ "TSComputeRHSJacobianConstant"
3407 /*@C
3408    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
3409 
3410    Collective on TS
3411 
3412    Input Arguments:
3413 +  ts - time stepping context
3414 .  t - time at which to evaluate
3415 .  U - state at which to evaluate
3416 -  ctx - context
3417 
3418    Output Arguments:
3419 +  A - pointer to operator
3420 .  B - pointer to preconditioning matrix
3421 -  flg - matrix structure flag
3422 
3423    Level: intermediate
3424 
3425    Notes:
3426    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
3427 
3428 .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
3429 @*/
3430 PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg,void *ctx)
3431 {
3432   PetscFunctionBegin;
3433   *flg = SAME_PRECONDITIONER;
3434   PetscFunctionReturn(0);
3435 }
3436 
3437 #undef __FUNCT__
3438 #define __FUNCT__ "TSComputeIFunctionLinear"
3439 /*@C
3440    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
3441 
3442    Collective on TS
3443 
3444    Input Arguments:
3445 +  ts - time stepping context
3446 .  t - time at which to evaluate
3447 .  U - state at which to evaluate
3448 .  Udot - time derivative of state vector
3449 -  ctx - context
3450 
3451    Output Arguments:
3452 .  F - left hand side
3453 
3454    Level: intermediate
3455 
3456    Notes:
3457    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
3458    user is required to write their own TSComputeIFunction.
3459    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
3460    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
3461 
3462 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
3463 @*/
3464 PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
3465 {
3466   PetscErrorCode ierr;
3467   Mat            A,B;
3468   MatStructure   flg2;
3469 
3470   PetscFunctionBegin;
3471   ierr = TSGetIJacobian(ts,&A,&B,NULL,NULL);CHKERRQ(ierr);
3472   ierr = TSComputeIJacobian(ts,t,U,Udot,1.0,&A,&B,&flg2,PETSC_TRUE);CHKERRQ(ierr);
3473   ierr = MatMult(A,Udot,F);CHKERRQ(ierr);
3474   PetscFunctionReturn(0);
3475 }
3476 
3477 #undef __FUNCT__
3478 #define __FUNCT__ "TSComputeIJacobianConstant"
3479 /*@C
3480    TSComputeIJacobianConstant - Reuses a Jacobian that is time-independent.
3481 
3482    Collective on TS
3483 
3484    Input Arguments:
3485 +  ts - time stepping context
3486 .  t - time at which to evaluate
3487 .  U - state at which to evaluate
3488 .  Udot - time derivative of state vector
3489 .  shift - shift to apply
3490 -  ctx - context
3491 
3492    Output Arguments:
3493 +  A - pointer to operator
3494 .  B - pointer to preconditioning matrix
3495 -  flg - matrix structure flag
3496 
3497    Level: intermediate
3498 
3499    Notes:
3500    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
3501 
3502 .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
3503 @*/
3504 PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,void *ctx)
3505 {
3506   PetscFunctionBegin;
3507   *flg = SAME_PRECONDITIONER;
3508   PetscFunctionReturn(0);
3509 }
3510 #undef __FUNCT__
3511 #define __FUNCT__ "TSGetEquationType"
3512 /*@
3513    TSGetEquationType - Gets the type of the equation that TS is solving.
3514 
3515    Not Collective
3516 
3517    Input Parameter:
3518 .  ts - the TS context
3519 
3520    Output Parameter:
3521 .  equation_type - see TSEquatioType
3522 
3523    Level: beginner
3524 
3525 .keywords: TS, equation type
3526 
3527 .seealso: TSSetEquationType(), TSEquationType
3528 @*/
3529 PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
3530 {
3531   PetscFunctionBegin;
3532   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3533   PetscValidPointer(equation_type,2);
3534   *equation_type = ts->equation_type;
3535   PetscFunctionReturn(0);
3536 }
3537 
3538 #undef __FUNCT__
3539 #define __FUNCT__ "TSSetEquationType"
3540 /*@
3541    TSSetEquationType - Sets the type of the equation that TS is solving.
3542 
3543    Not Collective
3544 
3545    Input Parameter:
3546 +  ts - the TS context
3547 .  equation_type - see TSEquatioType
3548 
3549    Level: advanced
3550 
3551 .keywords: TS, equation type
3552 
3553 .seealso: TSGetEquationType(), TSEquationType
3554 @*/
3555 PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
3556 {
3557   PetscFunctionBegin;
3558   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3559   ts->equation_type = equation_type;
3560   PetscFunctionReturn(0);
3561 }
3562 
3563 #undef __FUNCT__
3564 #define __FUNCT__ "TSGetConvergedReason"
3565 /*@
3566    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
3567 
3568    Not Collective
3569 
3570    Input Parameter:
3571 .  ts - the TS context
3572 
3573    Output Parameter:
3574 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
3575             manual pages for the individual convergence tests for complete lists
3576 
3577    Level: beginner
3578 
3579    Notes:
3580    Can only be called after the call to TSSolve() is complete.
3581 
3582 .keywords: TS, nonlinear, set, convergence, test
3583 
3584 .seealso: TSSetConvergenceTest(), TSConvergedReason
3585 @*/
3586 PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
3587 {
3588   PetscFunctionBegin;
3589   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3590   PetscValidPointer(reason,2);
3591   *reason = ts->reason;
3592   PetscFunctionReturn(0);
3593 }
3594 
3595 #undef __FUNCT__
3596 #define __FUNCT__ "TSSetConvergedReason"
3597 /*@
3598    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
3599 
3600    Not Collective
3601 
3602    Input Parameter:
3603 +  ts - the TS context
3604 .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
3605             manual pages for the individual convergence tests for complete lists
3606 
3607    Level: advanced
3608 
3609    Notes:
3610    Can only be called during TSSolve() is active.
3611 
3612 .keywords: TS, nonlinear, set, convergence, test
3613 
3614 .seealso: TSConvergedReason
3615 @*/
3616 PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
3617 {
3618   PetscFunctionBegin;
3619   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3620   ts->reason = reason;
3621   PetscFunctionReturn(0);
3622 }
3623 
3624 #undef __FUNCT__
3625 #define __FUNCT__ "TSGetSolveTime"
3626 /*@
3627    TSGetSolveTime - Gets the time after a call to TSSolve()
3628 
3629    Not Collective
3630 
3631    Input Parameter:
3632 .  ts - the TS context
3633 
3634    Output Parameter:
3635 .  ftime - the final time. This time should correspond to the final time set with TSSetDuration()
3636 
3637    Level: beginner
3638 
3639    Notes:
3640    Can only be called after the call to TSSolve() is complete.
3641 
3642 .keywords: TS, nonlinear, set, convergence, test
3643 
3644 .seealso: TSSetConvergenceTest(), TSConvergedReason
3645 @*/
3646 PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
3647 {
3648   PetscFunctionBegin;
3649   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3650   PetscValidPointer(ftime,2);
3651   *ftime = ts->solvetime;
3652   PetscFunctionReturn(0);
3653 }
3654 
3655 #undef __FUNCT__
3656 #define __FUNCT__ "TSGetSNESIterations"
3657 /*@
3658    TSGetSNESIterations - Gets the total number of nonlinear iterations
3659    used by the time integrator.
3660 
3661    Not Collective
3662 
3663    Input Parameter:
3664 .  ts - TS context
3665 
3666    Output Parameter:
3667 .  nits - number of nonlinear iterations
3668 
3669    Notes:
3670    This counter is reset to zero for each successive call to TSSolve().
3671 
3672    Level: intermediate
3673 
3674 .keywords: TS, get, number, nonlinear, iterations
3675 
3676 .seealso:  TSGetKSPIterations()
3677 @*/
3678 PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
3679 {
3680   PetscFunctionBegin;
3681   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3682   PetscValidIntPointer(nits,2);
3683   *nits = ts->snes_its;
3684   PetscFunctionReturn(0);
3685 }
3686 
3687 #undef __FUNCT__
3688 #define __FUNCT__ "TSGetKSPIterations"
3689 /*@
3690    TSGetKSPIterations - Gets the total number of linear iterations
3691    used by the time integrator.
3692 
3693    Not Collective
3694 
3695    Input Parameter:
3696 .  ts - TS context
3697 
3698    Output Parameter:
3699 .  lits - number of linear iterations
3700 
3701    Notes:
3702    This counter is reset to zero for each successive call to TSSolve().
3703 
3704    Level: intermediate
3705 
3706 .keywords: TS, get, number, linear, iterations
3707 
3708 .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
3709 @*/
3710 PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
3711 {
3712   PetscFunctionBegin;
3713   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3714   PetscValidIntPointer(lits,2);
3715   *lits = ts->ksp_its;
3716   PetscFunctionReturn(0);
3717 }
3718 
3719 #undef __FUNCT__
3720 #define __FUNCT__ "TSGetStepRejections"
3721 /*@
3722    TSGetStepRejections - Gets the total number of rejected steps.
3723 
3724    Not Collective
3725 
3726    Input Parameter:
3727 .  ts - TS context
3728 
3729    Output Parameter:
3730 .  rejects - number of steps rejected
3731 
3732    Notes:
3733    This counter is reset to zero for each successive call to TSSolve().
3734 
3735    Level: intermediate
3736 
3737 .keywords: TS, get, number
3738 
3739 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
3740 @*/
3741 PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
3742 {
3743   PetscFunctionBegin;
3744   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3745   PetscValidIntPointer(rejects,2);
3746   *rejects = ts->reject;
3747   PetscFunctionReturn(0);
3748 }
3749 
3750 #undef __FUNCT__
3751 #define __FUNCT__ "TSGetSNESFailures"
3752 /*@
3753    TSGetSNESFailures - Gets the total number of failed SNES solves
3754 
3755    Not Collective
3756 
3757    Input Parameter:
3758 .  ts - TS context
3759 
3760    Output Parameter:
3761 .  fails - number of failed nonlinear solves
3762 
3763    Notes:
3764    This counter is reset to zero for each successive call to TSSolve().
3765 
3766    Level: intermediate
3767 
3768 .keywords: TS, get, number
3769 
3770 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
3771 @*/
3772 PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
3773 {
3774   PetscFunctionBegin;
3775   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3776   PetscValidIntPointer(fails,2);
3777   *fails = ts->num_snes_failures;
3778   PetscFunctionReturn(0);
3779 }
3780 
3781 #undef __FUNCT__
3782 #define __FUNCT__ "TSSetMaxStepRejections"
3783 /*@
3784    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
3785 
3786    Not Collective
3787 
3788    Input Parameter:
3789 +  ts - TS context
3790 -  rejects - maximum number of rejected steps, pass -1 for unlimited
3791 
3792    Notes:
3793    The counter is reset to zero for each step
3794 
3795    Options Database Key:
3796  .  -ts_max_reject - Maximum number of step rejections before a step fails
3797 
3798    Level: intermediate
3799 
3800 .keywords: TS, set, maximum, number
3801 
3802 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
3803 @*/
3804 PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
3805 {
3806   PetscFunctionBegin;
3807   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3808   ts->max_reject = rejects;
3809   PetscFunctionReturn(0);
3810 }
3811 
3812 #undef __FUNCT__
3813 #define __FUNCT__ "TSSetMaxSNESFailures"
3814 /*@
3815    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
3816 
3817    Not Collective
3818 
3819    Input Parameter:
3820 +  ts - TS context
3821 -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
3822 
3823    Notes:
3824    The counter is reset to zero for each successive call to TSSolve().
3825 
3826    Options Database Key:
3827  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
3828 
3829    Level: intermediate
3830 
3831 .keywords: TS, set, maximum, number
3832 
3833 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
3834 @*/
3835 PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
3836 {
3837   PetscFunctionBegin;
3838   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3839   ts->max_snes_failures = fails;
3840   PetscFunctionReturn(0);
3841 }
3842 
3843 #undef __FUNCT__
3844 #define __FUNCT__ "TSSetErrorIfStepFails()"
3845 /*@
3846    TSSetErrorIfStepFails - Error if no step succeeds
3847 
3848    Not Collective
3849 
3850    Input Parameter:
3851 +  ts - TS context
3852 -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
3853 
3854    Options Database Key:
3855  .  -ts_error_if_step_fails - Error if no step succeeds
3856 
3857    Level: intermediate
3858 
3859 .keywords: TS, set, error
3860 
3861 .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
3862 @*/
3863 PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
3864 {
3865   PetscFunctionBegin;
3866   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3867   ts->errorifstepfailed = err;
3868   PetscFunctionReturn(0);
3869 }
3870 
3871 #undef __FUNCT__
3872 #define __FUNCT__ "TSMonitorSolutionBinary"
3873 /*@C
3874    TSMonitorSolutionBinary - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file
3875 
3876    Collective on TS
3877 
3878    Input Parameters:
3879 +  ts - the TS context
3880 .  step - current time-step
3881 .  ptime - current time
3882 .  u - current state
3883 -  viewer - binary viewer
3884 
3885    Level: intermediate
3886 
3887 .keywords: TS,  vector, monitor, view
3888 
3889 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3890 @*/
3891 PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
3892 {
3893   PetscErrorCode ierr;
3894   PetscViewer    v = (PetscViewer)viewer;
3895 
3896   PetscFunctionBegin;
3897   ierr = VecView(u,v);CHKERRQ(ierr);
3898   PetscFunctionReturn(0);
3899 }
3900 
3901 #undef __FUNCT__
3902 #define __FUNCT__ "TSMonitorSolutionVTK"
3903 /*@C
3904    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.
3905 
3906    Collective on TS
3907 
3908    Input Parameters:
3909 +  ts - the TS context
3910 .  step - current time-step
3911 .  ptime - current time
3912 .  u - current state
3913 -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
3914 
3915    Level: intermediate
3916 
3917    Notes:
3918    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.
3919    These are named according to the file name template.
3920 
3921    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().
3922 
3923 .keywords: TS,  vector, monitor, view
3924 
3925 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3926 @*/
3927 PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
3928 {
3929   PetscErrorCode ierr;
3930   char           filename[PETSC_MAX_PATH_LEN];
3931   PetscViewer    viewer;
3932 
3933   PetscFunctionBegin;
3934   ierr = PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);CHKERRQ(ierr);
3935   ierr = PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);CHKERRQ(ierr);
3936   ierr = VecView(u,viewer);CHKERRQ(ierr);
3937   ierr = PetscViewerDestroy(&viewer);CHKERRQ(ierr);
3938   PetscFunctionReturn(0);
3939 }
3940 
3941 #undef __FUNCT__
3942 #define __FUNCT__ "TSMonitorSolutionVTKDestroy"
3943 /*@C
3944    TSMonitorSolutionVTKDestroy - Destroy context for monitoring
3945 
3946    Collective on TS
3947 
3948    Input Parameters:
3949 .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)
3950 
3951    Level: intermediate
3952 
3953    Note:
3954    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().
3955 
3956 .keywords: TS,  vector, monitor, view
3957 
3958 .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
3959 @*/
3960 PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
3961 {
3962   PetscErrorCode ierr;
3963 
3964   PetscFunctionBegin;
3965   ierr = PetscFree(*(char**)filenametemplate);CHKERRQ(ierr);
3966   PetscFunctionReturn(0);
3967 }
3968 
3969 #undef __FUNCT__
3970 #define __FUNCT__ "TSGetTSAdapt"
3971 /*@
3972    TSGetTSAdapt - Get the adaptive controller context for the current method
3973 
3974    Collective on TS if controller has not been created yet
3975 
3976    Input Arguments:
3977 .  ts - time stepping context
3978 
3979    Output Arguments:
3980 .  adapt - adaptive controller
3981 
3982    Level: intermediate
3983 
3984 .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
3985 @*/
3986 PetscErrorCode TSGetTSAdapt(TS ts,TSAdapt *adapt)
3987 {
3988   PetscErrorCode ierr;
3989 
3990   PetscFunctionBegin;
3991   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3992   PetscValidPointer(adapt,2);
3993   if (!ts->adapt) {
3994     ierr = TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);CHKERRQ(ierr);
3995     ierr = PetscLogObjectParent(ts,ts->adapt);CHKERRQ(ierr);
3996     ierr = PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);CHKERRQ(ierr);
3997   }
3998   *adapt = ts->adapt;
3999   PetscFunctionReturn(0);
4000 }
4001 
4002 #undef __FUNCT__
4003 #define __FUNCT__ "TSSetTolerances"
4004 /*@
4005    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
4006 
4007    Logically Collective
4008 
4009    Input Arguments:
4010 +  ts - time integration context
4011 .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
4012 .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4013 .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
4014 -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
4015 
4016    Level: beginner
4017 
4018 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
4019 @*/
4020 PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
4021 {
4022   PetscErrorCode ierr;
4023 
4024   PetscFunctionBegin;
4025   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4026   if (vatol) {
4027     ierr = PetscObjectReference((PetscObject)vatol);CHKERRQ(ierr);
4028     ierr = VecDestroy(&ts->vatol);CHKERRQ(ierr);
4029 
4030     ts->vatol = vatol;
4031   }
4032   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
4033   if (vrtol) {
4034     ierr = PetscObjectReference((PetscObject)vrtol);CHKERRQ(ierr);
4035     ierr = VecDestroy(&ts->vrtol);CHKERRQ(ierr);
4036 
4037     ts->vrtol = vrtol;
4038   }
4039   PetscFunctionReturn(0);
4040 }
4041 
4042 #undef __FUNCT__
4043 #define __FUNCT__ "TSGetTolerances"
4044 /*@
4045    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4046 
4047    Logically Collective
4048 
4049    Input Arguments:
4050 .  ts - time integration context
4051 
4052    Output Arguments:
4053 +  atol - scalar absolute tolerances, NULL to ignore
4054 .  vatol - vector of absolute tolerances, NULL to ignore
4055 .  rtol - scalar relative tolerances, NULL to ignore
4056 -  vrtol - vector of relative tolerances, NULL to ignore
4057 
4058    Level: beginner
4059 
4060 .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
4061 @*/
4062 PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4063 {
4064   PetscFunctionBegin;
4065   if (atol)  *atol  = ts->atol;
4066   if (vatol) *vatol = ts->vatol;
4067   if (rtol)  *rtol  = ts->rtol;
4068   if (vrtol) *vrtol = ts->vrtol;
4069   PetscFunctionReturn(0);
4070 }
4071 
4072 #undef __FUNCT__
4073 #define __FUNCT__ "TSErrorNormWRMS"
4074 /*@
4075    TSErrorNormWRMS - compute a weighted norm of the difference between a vector and the current state
4076 
4077    Collective on TS
4078 
4079    Input Arguments:
4080 +  ts - time stepping context
4081 -  Y - state vector to be compared to ts->vec_sol
4082 
4083    Output Arguments:
4084 .  norm - weighted norm, a value of 1.0 is considered small
4085 
4086    Level: developer
4087 
4088 .seealso: TSSetTolerances()
4089 @*/
4090 PetscErrorCode TSErrorNormWRMS(TS ts,Vec Y,PetscReal *norm)
4091 {
4092   PetscErrorCode    ierr;
4093   PetscInt          i,n,N;
4094   const PetscScalar *u,*y;
4095   Vec               U;
4096   PetscReal         sum,gsum;
4097 
4098   PetscFunctionBegin;
4099   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4100   PetscValidHeaderSpecific(Y,VEC_CLASSID,2);
4101   PetscValidPointer(norm,3);
4102   U = ts->vec_sol;
4103   PetscCheckSameTypeAndComm(U,1,Y,2);
4104   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"Y cannot be the TS solution vector");
4105 
4106   ierr = VecGetSize(U,&N);CHKERRQ(ierr);
4107   ierr = VecGetLocalSize(U,&n);CHKERRQ(ierr);
4108   ierr = VecGetArrayRead(U,&u);CHKERRQ(ierr);
4109   ierr = VecGetArrayRead(Y,&y);CHKERRQ(ierr);
4110   sum  = 0.;
4111   if (ts->vatol && ts->vrtol) {
4112     const PetscScalar *atol,*rtol;
4113     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4114     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4115     for (i=0; i<n; i++) {
4116       PetscReal tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4117       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4118     }
4119     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4120     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4121   } else if (ts->vatol) {       /* vector atol, scalar rtol */
4122     const PetscScalar *atol;
4123     ierr = VecGetArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4124     for (i=0; i<n; i++) {
4125       PetscReal tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4126       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4127     }
4128     ierr = VecRestoreArrayRead(ts->vatol,&atol);CHKERRQ(ierr);
4129   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
4130     const PetscScalar *rtol;
4131     ierr = VecGetArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4132     for (i=0; i<n; i++) {
4133       PetscReal tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4134       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4135     }
4136     ierr = VecRestoreArrayRead(ts->vrtol,&rtol);CHKERRQ(ierr);
4137   } else {                      /* scalar atol, scalar rtol */
4138     for (i=0; i<n; i++) {
4139       PetscReal tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4140       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4141     }
4142   }
4143   ierr = VecRestoreArrayRead(U,&u);CHKERRQ(ierr);
4144   ierr = VecRestoreArrayRead(Y,&y);CHKERRQ(ierr);
4145 
4146   ierr  = MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
4147   *norm = PetscSqrtReal(gsum / N);
4148   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
4149   PetscFunctionReturn(0);
4150 }
4151 
4152 #undef __FUNCT__
4153 #define __FUNCT__ "TSSetCFLTimeLocal"
4154 /*@
4155    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
4156 
4157    Logically Collective on TS
4158 
4159    Input Arguments:
4160 +  ts - time stepping context
4161 -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
4162 
4163    Note:
4164    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
4165 
4166    Level: intermediate
4167 
4168 .seealso: TSGetCFLTime(), TSADAPTCFL
4169 @*/
4170 PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
4171 {
4172   PetscFunctionBegin;
4173   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4174   ts->cfltime_local = cfltime;
4175   ts->cfltime       = -1.;
4176   PetscFunctionReturn(0);
4177 }
4178 
4179 #undef __FUNCT__
4180 #define __FUNCT__ "TSGetCFLTime"
4181 /*@
4182    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
4183 
4184    Collective on TS
4185 
4186    Input Arguments:
4187 .  ts - time stepping context
4188 
4189    Output Arguments:
4190 .  cfltime - maximum stable time step for forward Euler
4191 
4192    Level: advanced
4193 
4194 .seealso: TSSetCFLTimeLocal()
4195 @*/
4196 PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
4197 {
4198   PetscErrorCode ierr;
4199 
4200   PetscFunctionBegin;
4201   if (ts->cfltime < 0) {
4202     ierr = MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));CHKERRQ(ierr);
4203   }
4204   *cfltime = ts->cfltime;
4205   PetscFunctionReturn(0);
4206 }
4207 
4208 #undef __FUNCT__
4209 #define __FUNCT__ "TSVISetVariableBounds"
4210 /*@
4211    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
4212 
4213    Input Parameters:
4214 .  ts   - the TS context.
4215 .  xl   - lower bound.
4216 .  xu   - upper bound.
4217 
4218    Notes:
4219    If this routine is not called then the lower and upper bounds are set to
4220    SNES_VI_NINF and SNES_VI_INF respectively during SNESSetUp().
4221 
4222    Level: advanced
4223 
4224 @*/
4225 PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
4226 {
4227   PetscErrorCode ierr;
4228   SNES           snes;
4229 
4230   PetscFunctionBegin;
4231   ierr = TSGetSNES(ts,&snes);CHKERRQ(ierr);
4232   ierr = SNESVISetVariableBounds(snes,xl,xu);CHKERRQ(ierr);
4233   PetscFunctionReturn(0);
4234 }
4235 
4236 #if defined(PETSC_HAVE_MATLAB_ENGINE)
4237 #include <mex.h>
4238 
4239 typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;
4240 
4241 #undef __FUNCT__
4242 #define __FUNCT__ "TSComputeFunction_Matlab"
4243 /*
4244    TSComputeFunction_Matlab - Calls the function that has been set with
4245                          TSSetFunctionMatlab().
4246 
4247    Collective on TS
4248 
4249    Input Parameters:
4250 +  snes - the TS context
4251 -  u - input vector
4252 
4253    Output Parameter:
4254 .  y - function vector, as set by TSSetFunction()
4255 
4256    Notes:
4257    TSComputeFunction() is typically used within nonlinear solvers
4258    implementations, so most users would not generally call this routine
4259    themselves.
4260 
4261    Level: developer
4262 
4263 .keywords: TS, nonlinear, compute, function
4264 
4265 .seealso: TSSetFunction(), TSGetFunction()
4266 */
4267 PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
4268 {
4269   PetscErrorCode  ierr;
4270   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4271   int             nlhs  = 1,nrhs = 7;
4272   mxArray         *plhs[1],*prhs[7];
4273   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;
4274 
4275   PetscFunctionBegin;
4276   PetscValidHeaderSpecific(snes,TS_CLASSID,1);
4277   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
4278   PetscValidHeaderSpecific(udot,VEC_CLASSID,4);
4279   PetscValidHeaderSpecific(y,VEC_CLASSID,5);
4280   PetscCheckSameComm(snes,1,u,3);
4281   PetscCheckSameComm(snes,1,y,5);
4282 
4283   ierr = PetscMemcpy(&ls,&snes,sizeof(snes));CHKERRQ(ierr);
4284   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
4285   ierr = PetscMemcpy(&lxdot,&udot,sizeof(udot));CHKERRQ(ierr);
4286   ierr = PetscMemcpy(&ly,&y,sizeof(u));CHKERRQ(ierr);
4287 
4288   prhs[0] =  mxCreateDoubleScalar((double)ls);
4289   prhs[1] =  mxCreateDoubleScalar(time);
4290   prhs[2] =  mxCreateDoubleScalar((double)lx);
4291   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
4292   prhs[4] =  mxCreateDoubleScalar((double)ly);
4293   prhs[5] =  mxCreateString(sctx->funcname);
4294   prhs[6] =  sctx->ctx;
4295   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");CHKERRQ(ierr);
4296   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
4297   mxDestroyArray(prhs[0]);
4298   mxDestroyArray(prhs[1]);
4299   mxDestroyArray(prhs[2]);
4300   mxDestroyArray(prhs[3]);
4301   mxDestroyArray(prhs[4]);
4302   mxDestroyArray(prhs[5]);
4303   mxDestroyArray(plhs[0]);
4304   PetscFunctionReturn(0);
4305 }
4306 
4307 
4308 #undef __FUNCT__
4309 #define __FUNCT__ "TSSetFunctionMatlab"
4310 /*
4311    TSSetFunctionMatlab - Sets the function evaluation routine and function
4312    vector for use by the TS routines in solving ODEs
4313    equations from MATLAB. Here the function is a string containing the name of a MATLAB function
4314 
4315    Logically Collective on TS
4316 
4317    Input Parameters:
4318 +  ts - the TS context
4319 -  func - function evaluation routine
4320 
4321    Calling sequence of func:
4322 $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);
4323 
4324    Level: beginner
4325 
4326 .keywords: TS, nonlinear, set, function
4327 
4328 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4329 */
4330 PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
4331 {
4332   PetscErrorCode  ierr;
4333   TSMatlabContext *sctx;
4334 
4335   PetscFunctionBegin;
4336   /* currently sctx is memory bleed */
4337   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
4338   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
4339   /*
4340      This should work, but it doesn't
4341   sctx->ctx = ctx;
4342   mexMakeArrayPersistent(sctx->ctx);
4343   */
4344   sctx->ctx = mxDuplicateArray(ctx);
4345 
4346   ierr = TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);CHKERRQ(ierr);
4347   PetscFunctionReturn(0);
4348 }
4349 
4350 #undef __FUNCT__
4351 #define __FUNCT__ "TSComputeJacobian_Matlab"
4352 /*
4353    TSComputeJacobian_Matlab - Calls the function that has been set with
4354                          TSSetJacobianMatlab().
4355 
4356    Collective on TS
4357 
4358    Input Parameters:
4359 +  ts - the TS context
4360 .  u - input vector
4361 .  A, B - the matrices
4362 -  ctx - user context
4363 
4364    Output Parameter:
4365 .  flag - structure of the matrix
4366 
4367    Level: developer
4368 
4369 .keywords: TS, nonlinear, compute, function
4370 
4371 .seealso: TSSetFunction(), TSGetFunction()
4372 @*/
4373 PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flag, void *ctx)
4374 {
4375   PetscErrorCode  ierr;
4376   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4377   int             nlhs  = 2,nrhs = 9;
4378   mxArray         *plhs[2],*prhs[9];
4379   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;
4380 
4381   PetscFunctionBegin;
4382   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4383   PetscValidHeaderSpecific(u,VEC_CLASSID,3);
4384 
4385   /* call Matlab function in ctx with arguments u and y */
4386 
4387   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
4388   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
4389   ierr = PetscMemcpy(&lxdot,&udot,sizeof(u));CHKERRQ(ierr);
4390   ierr = PetscMemcpy(&lA,A,sizeof(u));CHKERRQ(ierr);
4391   ierr = PetscMemcpy(&lB,B,sizeof(u));CHKERRQ(ierr);
4392 
4393   prhs[0] =  mxCreateDoubleScalar((double)ls);
4394   prhs[1] =  mxCreateDoubleScalar((double)time);
4395   prhs[2] =  mxCreateDoubleScalar((double)lx);
4396   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
4397   prhs[4] =  mxCreateDoubleScalar((double)shift);
4398   prhs[5] =  mxCreateDoubleScalar((double)lA);
4399   prhs[6] =  mxCreateDoubleScalar((double)lB);
4400   prhs[7] =  mxCreateString(sctx->funcname);
4401   prhs[8] =  sctx->ctx;
4402   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");CHKERRQ(ierr);
4403   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
4404   *flag   =  (MatStructure) mxGetScalar(plhs[1]);CHKERRQ(ierr);
4405   mxDestroyArray(prhs[0]);
4406   mxDestroyArray(prhs[1]);
4407   mxDestroyArray(prhs[2]);
4408   mxDestroyArray(prhs[3]);
4409   mxDestroyArray(prhs[4]);
4410   mxDestroyArray(prhs[5]);
4411   mxDestroyArray(prhs[6]);
4412   mxDestroyArray(prhs[7]);
4413   mxDestroyArray(plhs[0]);
4414   mxDestroyArray(plhs[1]);
4415   PetscFunctionReturn(0);
4416 }
4417 
4418 
4419 #undef __FUNCT__
4420 #define __FUNCT__ "TSSetJacobianMatlab"
4421 /*
4422    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
4423    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
4424 
4425    Logically Collective on TS
4426 
4427    Input Parameters:
4428 +  ts - the TS context
4429 .  A,B - Jacobian matrices
4430 .  func - function evaluation routine
4431 -  ctx - user context
4432 
4433    Calling sequence of func:
4434 $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);
4435 
4436 
4437    Level: developer
4438 
4439 .keywords: TS, nonlinear, set, function
4440 
4441 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4442 */
4443 PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
4444 {
4445   PetscErrorCode  ierr;
4446   TSMatlabContext *sctx;
4447 
4448   PetscFunctionBegin;
4449   /* currently sctx is memory bleed */
4450   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
4451   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
4452   /*
4453      This should work, but it doesn't
4454   sctx->ctx = ctx;
4455   mexMakeArrayPersistent(sctx->ctx);
4456   */
4457   sctx->ctx = mxDuplicateArray(ctx);
4458 
4459   ierr = TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);CHKERRQ(ierr);
4460   PetscFunctionReturn(0);
4461 }
4462 
4463 #undef __FUNCT__
4464 #define __FUNCT__ "TSMonitor_Matlab"
4465 /*
4466    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().
4467 
4468    Collective on TS
4469 
4470 .seealso: TSSetFunction(), TSGetFunction()
4471 @*/
4472 PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
4473 {
4474   PetscErrorCode  ierr;
4475   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
4476   int             nlhs  = 1,nrhs = 6;
4477   mxArray         *plhs[1],*prhs[6];
4478   long long int   lx = 0,ls = 0;
4479 
4480   PetscFunctionBegin;
4481   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4482   PetscValidHeaderSpecific(u,VEC_CLASSID,4);
4483 
4484   ierr = PetscMemcpy(&ls,&ts,sizeof(ts));CHKERRQ(ierr);
4485   ierr = PetscMemcpy(&lx,&u,sizeof(u));CHKERRQ(ierr);
4486 
4487   prhs[0] =  mxCreateDoubleScalar((double)ls);
4488   prhs[1] =  mxCreateDoubleScalar((double)it);
4489   prhs[2] =  mxCreateDoubleScalar((double)time);
4490   prhs[3] =  mxCreateDoubleScalar((double)lx);
4491   prhs[4] =  mxCreateString(sctx->funcname);
4492   prhs[5] =  sctx->ctx;
4493   ierr    =  mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");CHKERRQ(ierr);
4494   ierr    =  mxGetScalar(plhs[0]);CHKERRQ(ierr);
4495   mxDestroyArray(prhs[0]);
4496   mxDestroyArray(prhs[1]);
4497   mxDestroyArray(prhs[2]);
4498   mxDestroyArray(prhs[3]);
4499   mxDestroyArray(prhs[4]);
4500   mxDestroyArray(plhs[0]);
4501   PetscFunctionReturn(0);
4502 }
4503 
4504 
4505 #undef __FUNCT__
4506 #define __FUNCT__ "TSMonitorSetMatlab"
4507 /*
4508    TSMonitorSetMatlab - Sets the monitor function from Matlab
4509 
4510    Level: developer
4511 
4512 .keywords: TS, nonlinear, set, function
4513 
4514 .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
4515 */
4516 PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
4517 {
4518   PetscErrorCode  ierr;
4519   TSMatlabContext *sctx;
4520 
4521   PetscFunctionBegin;
4522   /* currently sctx is memory bleed */
4523   ierr = PetscMalloc(sizeof(TSMatlabContext),&sctx);CHKERRQ(ierr);
4524   ierr = PetscStrallocpy(func,&sctx->funcname);CHKERRQ(ierr);
4525   /*
4526      This should work, but it doesn't
4527   sctx->ctx = ctx;
4528   mexMakeArrayPersistent(sctx->ctx);
4529   */
4530   sctx->ctx = mxDuplicateArray(ctx);
4531 
4532   ierr = TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);CHKERRQ(ierr);
4533   PetscFunctionReturn(0);
4534 }
4535 #endif
4536 
4537 
4538 
4539 #undef __FUNCT__
4540 #define __FUNCT__ "TSMonitorLGSolution"
4541 /*@C
4542    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
4543        in a time based line graph
4544 
4545    Collective on TS
4546 
4547    Input Parameters:
4548 +  ts - the TS context
4549 .  step - current time-step
4550 .  ptime - current time
4551 -  lg - a line graph object
4552 
4553    Level: intermediate
4554 
4555     Notes: each process in a parallel run displays its component solutions in a separate window
4556 
4557 .keywords: TS,  vector, monitor, view
4558 
4559 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4560 @*/
4561 PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4562 {
4563   PetscErrorCode    ierr;
4564   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
4565   const PetscScalar *yy;
4566   PetscInt          dim;
4567 
4568   PetscFunctionBegin;
4569   if (!step) {
4570     PetscDrawAxis axis;
4571     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4572     ierr = PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");CHKERRQ(ierr);
4573     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
4574     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
4575     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4576   }
4577   ierr = VecGetArrayRead(u,&yy);CHKERRQ(ierr);
4578 #if defined(PETSC_USE_COMPLEX)
4579   {
4580     PetscReal *yreal;
4581     PetscInt  i,n;
4582     ierr = VecGetLocalSize(u,&n);CHKERRQ(ierr);
4583     ierr = PetscMalloc(n*sizeof(PetscReal),&yreal);CHKERRQ(ierr);
4584     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
4585     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
4586     ierr = PetscFree(yreal);CHKERRQ(ierr);
4587   }
4588 #else
4589   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
4590 #endif
4591   ierr = VecRestoreArrayRead(u,&yy);CHKERRQ(ierr);
4592   if (((ctx->howoften > 0) && (!(step % ctx->howoften)) && (step > -1)) || ((ctx->howoften == -1) && (step == -1))) {
4593     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4594   }
4595   PetscFunctionReturn(0);
4596 }
4597 
4598 #undef __FUNCT__
4599 #define __FUNCT__ "TSMonitorLGError"
4600 /*@C
4601    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
4602        in a time based line graph
4603 
4604    Collective on TS
4605 
4606    Input Parameters:
4607 +  ts - the TS context
4608 .  step - current time-step
4609 .  ptime - current time
4610 -  lg - a line graph object
4611 
4612    Level: intermediate
4613 
4614    Notes:
4615    Only for sequential solves.
4616 
4617    The user must provide the solution using TSSetSolutionFunction() to use this monitor.
4618 
4619    Options Database Keys:
4620 .  -ts_monitor_lg_error - create a graphical monitor of error history
4621 
4622 .keywords: TS,  vector, monitor, view
4623 
4624 .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
4625 @*/
4626 PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4627 {
4628   PetscErrorCode    ierr;
4629   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
4630   const PetscScalar *yy;
4631   Vec               y;
4632   PetscInt          dim;
4633 
4634   PetscFunctionBegin;
4635   if (!step) {
4636     PetscDrawAxis axis;
4637     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4638     ierr = PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");CHKERRQ(ierr);
4639     ierr = VecGetLocalSize(u,&dim);CHKERRQ(ierr);
4640     ierr = PetscDrawLGSetDimension(ctx->lg,dim);CHKERRQ(ierr);
4641     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4642   }
4643   ierr = VecDuplicate(u,&y);CHKERRQ(ierr);
4644   ierr = TSComputeSolutionFunction(ts,ptime,y);CHKERRQ(ierr);
4645   ierr = VecAXPY(y,-1.0,u);CHKERRQ(ierr);
4646   ierr = VecGetArrayRead(y,&yy);CHKERRQ(ierr);
4647 #if defined(PETSC_USE_COMPLEX)
4648   {
4649     PetscReal *yreal;
4650     PetscInt  i,n;
4651     ierr = VecGetLocalSize(y,&n);CHKERRQ(ierr);
4652     ierr = PetscMalloc(n*sizeof(PetscReal),&yreal);CHKERRQ(ierr);
4653     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
4654     ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);CHKERRQ(ierr);
4655     ierr = PetscFree(yreal);CHKERRQ(ierr);
4656   }
4657 #else
4658   ierr = PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);CHKERRQ(ierr);
4659 #endif
4660   ierr = VecRestoreArrayRead(y,&yy);CHKERRQ(ierr);
4661   ierr = VecDestroy(&y);CHKERRQ(ierr);
4662   if (((ctx->howoften > 0) && (!(step % ctx->howoften)) && (step > -1)) || ((ctx->howoften == -1) && (step == -1))) {
4663     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4664   }
4665   PetscFunctionReturn(0);
4666 }
4667 
4668 #undef __FUNCT__
4669 #define __FUNCT__ "TSMonitorLGSNESIterations"
4670 PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
4671 {
4672   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4673   PetscReal      x   = ptime,y;
4674   PetscErrorCode ierr;
4675   PetscInt       its;
4676 
4677   PetscFunctionBegin;
4678   if (!n) {
4679     PetscDrawAxis axis;
4680 
4681     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4682     ierr = PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");CHKERRQ(ierr);
4683     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4684 
4685     ctx->snes_its = 0;
4686   }
4687   ierr = TSGetSNESIterations(ts,&its);CHKERRQ(ierr);
4688   y    = its - ctx->snes_its;
4689   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
4690   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
4691     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4692   }
4693   ctx->snes_its = its;
4694   PetscFunctionReturn(0);
4695 }
4696 
4697 #undef __FUNCT__
4698 #define __FUNCT__ "TSMonitorLGKSPIterations"
4699 PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
4700 {
4701   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
4702   PetscReal      x   = ptime,y;
4703   PetscErrorCode ierr;
4704   PetscInt       its;
4705 
4706   PetscFunctionBegin;
4707   if (!n) {
4708     PetscDrawAxis axis;
4709 
4710     ierr = PetscDrawLGGetAxis(ctx->lg,&axis);CHKERRQ(ierr);
4711     ierr = PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");CHKERRQ(ierr);
4712     ierr = PetscDrawLGReset(ctx->lg);CHKERRQ(ierr);
4713 
4714     ctx->ksp_its = 0;
4715   }
4716   ierr = TSGetKSPIterations(ts,&its);CHKERRQ(ierr);
4717   y    = its - ctx->ksp_its;
4718   ierr = PetscDrawLGAddPoint(ctx->lg,&x,&y);CHKERRQ(ierr);
4719   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
4720     ierr = PetscDrawLGDraw(ctx->lg);CHKERRQ(ierr);
4721   }
4722   ctx->ksp_its = its;
4723   PetscFunctionReturn(0);
4724 }
4725 
4726 #undef __FUNCT__
4727 #define __FUNCT__ "TSComputeLinearStability"
4728 /*@
4729    TSComputeLinearStability - computes the linear stability function at a point
4730 
4731    Collective on TS and Vec
4732 
4733    Input Parameters:
4734 +  ts - the TS context
4735 -  xr,xi - real and imaginary part of input arguments
4736 
4737    Output Parameters:
4738 .  yr,yi - real and imaginary part of function value
4739 
4740    Level: developer
4741 
4742 .keywords: TS, compute
4743 
4744 .seealso: TSSetRHSFunction(), TSComputeIFunction()
4745 @*/
4746 PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
4747 {
4748   PetscErrorCode ierr;
4749 
4750   PetscFunctionBegin;
4751   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4752   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
4753   ierr = (*ts->ops->linearstability)(ts,xr,xi,yr,yi);CHKERRQ(ierr);
4754   PetscFunctionReturn(0);
4755 }
4756