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