Actual source code: ts.c

petsc-3.6.0 2015-06-09
Report Typos and Errors
  2: #include <petsc/private/tsimpl.h>        /*I "petscts.h"  I*/
  3: #include <petscdmshell.h>
  4: #include <petscdmda.h>
  5: #include <petscviewer.h>
  6: #include <petscdraw.h>

  8: /* Logging support */
  9: PetscClassId  TS_CLASSID, DMTS_CLASSID;
 10: PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;

 12: const char *const TSExactFinalTimeOptions[] = {"STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",0};

 14: struct _n_TSMonitorDrawCtx {
 15:   PetscViewer   viewer;
 16:   PetscDrawAxis axis;
 17:   Vec           initialsolution;
 18:   PetscBool     showinitial;
 19:   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
 20:   PetscBool     showtimestepandtime;
 21:   int           color;
 22: };

 26: /*@
 27:    TSSetFromOptions - Sets various TS parameters from user options.

 29:    Collective on TS

 31:    Input Parameter:
 32: .  ts - the TS context obtained from TSCreate()

 34:    Options Database Keys:
 35: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSGL, TSSSP
 36: .  -ts_save_trajectory - checkpoint the solution at each time-step
 37: .  -ts_max_steps <maxsteps> - maximum number of time-steps to take
 38: .  -ts_final_time <time> - maximum time to compute to
 39: .  -ts_dt <dt> - initial time step
 40: .  -ts_exact_final_time <stepover,interpolate,matchstep> whether to stop at the exact given final time and how to compute the solution at that ti,e
 41: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
 42: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
 43: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
 44: .  -ts_rtol <rtol> - relative tolerance for local truncation error
 45: .  -ts_atol <atol> Absolute tolerance for local truncation error
 46: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
 47: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
 48: .  -ts_monitor - print information at each timestep
 49: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
 50: .  -ts_monitor_lg_solution - Monitor solution graphically
 51: .  -ts_monitor_lg_error - Monitor error graphically
 52: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
 53: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
 54: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
 55: .  -ts_monitor_draw_solution - Monitor solution graphically
 56: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
 57: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
 58: .  -ts_monitor_solution_binary <filename> - Save each solution to a binary file
 59: .  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts
 60: -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time

 62:    Developer Note: We should unify all the -ts_monitor options in the way that -xxx_view has been unified

 64:    Level: beginner

 66: .keywords: TS, timestep, set, options, database

 68: .seealso: TSGetType()
 69: @*/
 70: PetscErrorCode  TSSetFromOptions(TS ts)
 71: {
 72:   PetscBool              opt,flg,tflg;
 73:   PetscErrorCode         ierr;
 74:   PetscViewer            monviewer;
 75:   char                   monfilename[PETSC_MAX_PATH_LEN];
 76:   SNES                   snes;
 77:   TSAdapt                adapt;
 78:   PetscReal              time_step;
 79:   TSExactFinalTimeOption eftopt;
 80:   char                   dir[16];
 81:   const char             *defaultType;
 82:   char                   typeName[256];

 86:   PetscObjectOptionsBegin((PetscObject)ts);
 87:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
 88:   else defaultType = TSEULER;

 90:   TSRegisterAll();
 91:   PetscOptionsFList("-ts_type", "TS method"," TSSetType", TSList, defaultType, typeName, 256, &opt);
 92:   if (opt) {
 93:     TSSetType(ts, typeName);
 94:   } else {
 95:     TSSetType(ts, defaultType);
 96:   }

 98:   /* Handle generic TS options */
 99:   if (ts->trajectory) tflg = PETSC_TRUE;
100:   else tflg = PETSC_FALSE;
101:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
102:   if (tflg) {TSSetSaveTrajectory(ts);}
103:   if (ts->adjoint_solve) tflg = PETSC_TRUE;
104:   else tflg = PETSC_FALSE;
105:   PetscOptionsBool("-ts_adjoint_solve","Solve the adjoint problem immediately after solving the forward problem","",tflg,&tflg,&flg);
106:   if (flg) {
107:     TSSetSaveTrajectory(ts);
108:     ts->adjoint_solve = tflg;
109:   }
110:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);
111:   PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);
112:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
113:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
114:   if (flg) {
115:     TSSetTimeStep(ts,time_step);
116:   }
117:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
118:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
119:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
120:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
121:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
122:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
123:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

125: #if defined(PETSC_HAVE_SAWS)
126:   {
127:   PetscBool set;
128:   flg  = PETSC_FALSE;
129:   PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
130:   if (set) {
131:     PetscObjectSAWsSetBlock((PetscObject)ts,flg);
132:   }
133:   }
134: #endif

136:   /* Monitor options */
137:   PetscOptionsString("-ts_monitor","Monitor timestep size","TSMonitorDefault","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
138:   if (flg) {
139:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)ts),monfilename,&monviewer);
140:     TSMonitorSet(ts,TSMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
141:   }
142:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
143:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

145:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
146:   if (opt) {
147:     TSMonitorLGCtx ctx;
148:     PetscInt       howoften = 1;

150:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
151:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
152:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
153:   }
154:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
155:   if (opt) {
156:     TSMonitorLGCtx ctx;
157:     PetscInt       howoften = 1;

159:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
160:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
161:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
162:   }
163:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
164:   if (opt) {
165:     TSMonitorLGCtx ctx;
166:     PetscInt       howoften = 1;

168:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
169:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
170:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
171:   }
172:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
173:   if (opt) {
174:     TSMonitorLGCtx ctx;
175:     PetscInt       howoften = 1;

177:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
178:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
179:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
180:   }
181:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
182:   if (opt) {
183:     TSMonitorLGCtx ctx;
184:     PetscInt       howoften = 1;

186:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
187:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
188:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
189:   }
190:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
191:   if (opt) {
192:     TSMonitorSPEigCtx ctx;
193:     PetscInt          howoften = 1;

195:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
196:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
197:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
198:   }
199:   opt  = PETSC_FALSE;
200:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
201:   if (opt) {
202:     TSMonitorDrawCtx ctx;
203:     PetscInt         howoften = 1;

205:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
206:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
207:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
208:   }
209:   opt  = PETSC_FALSE;
210:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
211:   if (opt) {
212:     TSMonitorDrawCtx ctx;
213:     PetscReal        bounds[4];
214:     PetscInt         n = 4;
215:     PetscDraw        draw;

217:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
218:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
219:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,1,&ctx);
220:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
221:     PetscDrawClear(draw);
222:     PetscDrawAxisCreate(draw,&ctx->axis);
223:     PetscDrawAxisSetLimits(ctx->axis,bounds[0],bounds[2],bounds[1],bounds[3]);
224:     PetscDrawAxisSetLabels(ctx->axis,"Phase Diagram","Variable 1","Variable 2");
225:     PetscDrawAxisDraw(ctx->axis);
226:     /* PetscDrawSetCoordinates(draw,bounds[0],bounds[1],bounds[2],bounds[3]); */
227:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
228:   }
229:   opt  = PETSC_FALSE;
230:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
231:   if (opt) {
232:     TSMonitorDrawCtx ctx;
233:     PetscInt         howoften = 1;

235:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
236:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
237:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
238:   }
239:   opt  = PETSC_FALSE;
240:   PetscOptionsString("-ts_monitor_solution_binary","Save each solution to a binary file","TSMonitorSolutionBinary",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
241:   if (flg) {
242:     PetscViewer ctx;
243:     if (monfilename[0]) {
244:       PetscViewerBinaryOpen(PetscObjectComm((PetscObject)ts),monfilename,FILE_MODE_WRITE,&ctx);
245:       TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))PetscViewerDestroy);
246:     } else {
247:       ctx = PETSC_VIEWER_BINARY_(PetscObjectComm((PetscObject)ts));
248:       TSMonitorSet(ts,TSMonitorSolutionBinary,ctx,(PetscErrorCode (*)(void**))NULL);
249:     }
250:   }
251:   opt  = PETSC_FALSE;
252:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
253:   if (flg) {
254:     const char *ptr,*ptr2;
255:     char       *filetemplate;
256:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
257:     /* Do some cursory validation of the input. */
258:     PetscStrstr(monfilename,"%",(char**)&ptr);
259:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
260:     for (ptr++; ptr && *ptr; ptr++) {
261:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
262:       if (!ptr2 && (*ptr < '0' || '9' < *ptr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03D.vts");
263:       if (ptr2) break;
264:     }
265:     PetscStrallocpy(monfilename,&filetemplate);
266:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
267:   }

269:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
270:   if (flg) {
271:     TSMonitorDMDARayCtx *rayctx;
272:     int                  ray = 0;
273:     DMDADirection        ddir;
274:     DM                   da;
275:     PetscMPIInt          rank;

277:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
278:     if (dir[0] == 'x') ddir = DMDA_X;
279:     else if (dir[0] == 'y') ddir = DMDA_Y;
280:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
281:     sscanf(dir+2,"%d",&ray);

283:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
284:     PetscNew(&rayctx);
285:     TSGetDM(ts,&da);
286:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
287:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
288:     if (!rank) {
289:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
290:     }
291:     rayctx->lgctx = NULL;
292:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
293:   }
294:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,16,&flg);
295:   if (flg) {
296:     TSMonitorDMDARayCtx *rayctx;
297:     int                 ray = 0;
298:     DMDADirection       ddir;
299:     DM                  da;
300:     PetscInt            howoften = 1;

302:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
303:     if      (dir[0] == 'x') ddir = DMDA_X;
304:     else if (dir[0] == 'y') ddir = DMDA_Y;
305:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
306:     sscanf(dir+2, "%d", &ray);

308:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %D\n", dir[0], ray);
309:     PetscNew(&rayctx);
310:     TSGetDM(ts, &da);
311:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
312:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
313:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
314:   }

316:   PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt);
317:   if (opt) {
318:     TSMonitorEnvelopeCtx ctx;

320:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
321:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
322:   }

324:   flg  = PETSC_FALSE;
325:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
326:   if (flg) {
327:     DM   dm;
328:     DMTS tdm;

330:     TSGetDM(ts, &dm);
331:     DMGetDMTS(dm, &tdm);
332:     tdm->ijacobianctx = NULL;
333:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, 0);
334:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
335:   }

337:   /*
338:      This code is all wrong. One is creating objects inside the TSSetFromOptions() so if run with the options gui
339:      will bleed memory. Also one is using a PetscOptionsBegin() inside a PetscOptionsBegin()
340:   */
341:   TSGetAdapt(ts,&adapt);
342:   TSAdaptSetFromOptions(PetscOptionsObject,adapt);

344:     /* Handle specific TS options */
345:   if (ts->ops->setfromoptions) {
346:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
347:   }
348:   PetscOptionsEnd();

350:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
351:   PetscObjectProcessOptionsHandlers((PetscObject)ts);

353:   if (ts->trajectory) {
354:     TSTrajectorySetFromOptions(ts->trajectory);
355:   }

357:   TSGetSNES(ts,&snes);
358:   if (snes) {
359:     if (ts->problem_type == TS_LINEAR) {SNESSetType(snes,SNESKSPONLY);}
360:     SNESSetFromOptions(ts->snes);
361:   }
362:   return(0);
363: }

367: /*@
368:    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object

370:    Collective on TS

372:    Input Parameters:
373: .  ts - the TS context obtained from TSCreate()


376:    Level: intermediate

378: .seealso: TSGetTrajectory(), TSAdjointSolve()

380: .keywords: TS, set, checkpoint,
381: @*/
382: PetscErrorCode  TSSetSaveTrajectory(TS ts)
383: {

388:   if (!ts->trajectory) {
389:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
390:     TSTrajectorySetType(ts->trajectory,TSTRAJECTORYBASIC);
391:   }
392:   return(0);
393: }

397: /*@
398:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
399:       set with TSSetRHSJacobian().

401:    Collective on TS and Vec

403:    Input Parameters:
404: +  ts - the TS context
405: .  t - current timestep
406: -  U - input vector

408:    Output Parameters:
409: +  A - Jacobian matrix
410: .  B - optional preconditioning matrix
411: -  flag - flag indicating matrix structure

413:    Notes:
414:    Most users should not need to explicitly call this routine, as it
415:    is used internally within the nonlinear solvers.

417:    See KSPSetOperators() for important information about setting the
418:    flag parameter.

420:    Level: developer

422: .keywords: SNES, compute, Jacobian, matrix

424: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
425: @*/
426: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
427: {
429:   PetscObjectState Ustate;
430:   DM             dm;
431:   DMTS           tsdm;
432:   TSRHSJacobian  rhsjacobianfunc;
433:   void           *ctx;
434:   TSIJacobian    ijacobianfunc;
435:   TSRHSFunction  rhsfunction;

441:   TSGetDM(ts,&dm);
442:   DMGetDMTS(dm,&tsdm);
443:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
444:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
445:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
446:   PetscObjectStateGet((PetscObject)U,&Ustate);
447:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) {
448:     return(0);
449:   }

451:   if (!rhsjacobianfunc && !ijacobianfunc) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

453:   if (ts->rhsjacobian.reuse) {
454:     MatShift(A,-ts->rhsjacobian.shift);
455:     MatScale(A,1./ts->rhsjacobian.scale);
456:     if (A != B) {
457:       MatShift(B,-ts->rhsjacobian.shift);
458:       MatScale(B,1./ts->rhsjacobian.scale);
459:     }
460:     ts->rhsjacobian.shift = 0;
461:     ts->rhsjacobian.scale = 1.;
462:   }

464:   if (rhsjacobianfunc) {
465:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
466:     PetscStackPush("TS user Jacobian function");
467:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
468:     PetscStackPop;
469:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
470:     /* make sure user returned a correct Jacobian and preconditioner */
473:   } else {
474:     MatZeroEntries(A);
475:     if (A != B) {MatZeroEntries(B);}
476:   }
477:   ts->rhsjacobian.time       = t;
478:   ts->rhsjacobian.X          = U;
479:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
480:   return(0);
481: }

485: /*@
486:    TSComputeRHSFunction - Evaluates the right-hand-side function.

488:    Collective on TS and Vec

490:    Input Parameters:
491: +  ts - the TS context
492: .  t - current time
493: -  U - state vector

495:    Output Parameter:
496: .  y - right hand side

498:    Note:
499:    Most users should not need to explicitly call this routine, as it
500:    is used internally within the nonlinear solvers.

502:    Level: developer

504: .keywords: TS, compute

506: .seealso: TSSetRHSFunction(), TSComputeIFunction()
507: @*/
508: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
509: {
511:   TSRHSFunction  rhsfunction;
512:   TSIFunction    ifunction;
513:   void           *ctx;
514:   DM             dm;

520:   TSGetDM(ts,&dm);
521:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
522:   DMTSGetIFunction(dm,&ifunction,NULL);

524:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

526:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
527:   if (rhsfunction) {
528:     PetscStackPush("TS user right-hand-side function");
529:     (*rhsfunction)(ts,t,U,y,ctx);
530:     PetscStackPop;
531:   } else {
532:     VecZeroEntries(y);
533:   }

535:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
536:   return(0);
537: }

541: /*@
542:    TSComputeSolutionFunction - Evaluates the solution function.

544:    Collective on TS and Vec

546:    Input Parameters:
547: +  ts - the TS context
548: -  t - current time

550:    Output Parameter:
551: .  U - the solution

553:    Note:
554:    Most users should not need to explicitly call this routine, as it
555:    is used internally within the nonlinear solvers.

557:    Level: developer

559: .keywords: TS, compute

561: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
562: @*/
563: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
564: {
565:   PetscErrorCode     ierr;
566:   TSSolutionFunction solutionfunction;
567:   void               *ctx;
568:   DM                 dm;

573:   TSGetDM(ts,&dm);
574:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

576:   if (solutionfunction) {
577:     PetscStackPush("TS user solution function");
578:     (*solutionfunction)(ts,t,U,ctx);
579:     PetscStackPop;
580:   }
581:   return(0);
582: }
585: /*@
586:    TSComputeForcingFunction - Evaluates the forcing function.

588:    Collective on TS and Vec

590:    Input Parameters:
591: +  ts - the TS context
592: -  t - current time

594:    Output Parameter:
595: .  U - the function value

597:    Note:
598:    Most users should not need to explicitly call this routine, as it
599:    is used internally within the nonlinear solvers.

601:    Level: developer

603: .keywords: TS, compute

605: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
606: @*/
607: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
608: {
609:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
610:   void               *ctx;
611:   DM                 dm;

616:   TSGetDM(ts,&dm);
617:   DMTSGetForcingFunction(dm,&forcing,&ctx);

619:   if (forcing) {
620:     PetscStackPush("TS user forcing function");
621:     (*forcing)(ts,t,U,ctx);
622:     PetscStackPop;
623:   }
624:   return(0);
625: }

629: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
630: {
631:   Vec            F;

635:   *Frhs = NULL;
636:   TSGetIFunction(ts,&F,NULL,NULL);
637:   if (!ts->Frhs) {
638:     VecDuplicate(F,&ts->Frhs);
639:   }
640:   *Frhs = ts->Frhs;
641:   return(0);
642: }

646: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
647: {
648:   Mat            A,B;

652:   if (Arhs) *Arhs = NULL;
653:   if (Brhs) *Brhs = NULL;
654:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
655:   if (Arhs) {
656:     if (!ts->Arhs) {
657:       MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
658:     }
659:     *Arhs = ts->Arhs;
660:   }
661:   if (Brhs) {
662:     if (!ts->Brhs) {
663:       if (A != B) {
664:         MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
665:       } else {
666:         ts->Brhs = ts->Arhs;
667:         PetscObjectReference((PetscObject)ts->Arhs);
668:       }
669:     }
670:     *Brhs = ts->Brhs;
671:   }
672:   return(0);
673: }

677: /*@
678:    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0

680:    Collective on TS and Vec

682:    Input Parameters:
683: +  ts - the TS context
684: .  t - current time
685: .  U - state vector
686: .  Udot - time derivative of state vector
687: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

689:    Output Parameter:
690: .  Y - right hand side

692:    Note:
693:    Most users should not need to explicitly call this routine, as it
694:    is used internally within the nonlinear solvers.

696:    If the user did did not write their equations in implicit form, this
697:    function recasts them in implicit form.

699:    Level: developer

701: .keywords: TS, compute

703: .seealso: TSSetIFunction(), TSComputeRHSFunction()
704: @*/
705: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
706: {
708:   TSIFunction    ifunction;
709:   TSRHSFunction  rhsfunction;
710:   void           *ctx;
711:   DM             dm;


719:   TSGetDM(ts,&dm);
720:   DMTSGetIFunction(dm,&ifunction,&ctx);
721:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

723:   if (!rhsfunction && !ifunction) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");

725:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
726:   if (ifunction) {
727:     PetscStackPush("TS user implicit function");
728:     (*ifunction)(ts,t,U,Udot,Y,ctx);
729:     PetscStackPop;
730:   }
731:   if (imex) {
732:     if (!ifunction) {
733:       VecCopy(Udot,Y);
734:     }
735:   } else if (rhsfunction) {
736:     if (ifunction) {
737:       Vec Frhs;
738:       TSGetRHSVec_Private(ts,&Frhs);
739:       TSComputeRHSFunction(ts,t,U,Frhs);
740:       VecAXPY(Y,-1,Frhs);
741:     } else {
742:       TSComputeRHSFunction(ts,t,U,Y);
743:       VecAYPX(Y,-1,Udot);
744:     }
745:   }
746:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
747:   return(0);
748: }

752: /*@
753:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

755:    Collective on TS and Vec

757:    Input
758:       Input Parameters:
759: +  ts - the TS context
760: .  t - current timestep
761: .  U - state vector
762: .  Udot - time derivative of state vector
763: .  shift - shift to apply, see note below
764: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

766:    Output Parameters:
767: +  A - Jacobian matrix
768: .  B - optional preconditioning matrix
769: -  flag - flag indicating matrix structure

771:    Notes:
772:    If F(t,U,Udot)=0 is the DAE, the required Jacobian is

774:    dF/dU + shift*dF/dUdot

776:    Most users should not need to explicitly call this routine, as it
777:    is used internally within the nonlinear solvers.

779:    Level: developer

781: .keywords: TS, compute, Jacobian, matrix

783: .seealso:  TSSetIJacobian()
784: @*/
785: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
786: {
788:   TSIJacobian    ijacobian;
789:   TSRHSJacobian  rhsjacobian;
790:   DM             dm;
791:   void           *ctx;


802:   TSGetDM(ts,&dm);
803:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
804:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

806:   if (!rhsjacobian && !ijacobian) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");

808:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
809:   if (ijacobian) {
810:     PetscStackPush("TS user implicit Jacobian");
811:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
812:     PetscStackPop;
813:     /* make sure user returned a correct Jacobian and preconditioner */
816:   }
817:   if (imex) {
818:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
819:       MatZeroEntries(A);
820:       MatShift(A,shift);
821:       if (A != B) {
822:         MatZeroEntries(B);
823:         MatShift(B,shift);
824:       }
825:     }
826:   } else {
827:     Mat Arhs = NULL,Brhs = NULL;
828:     if (rhsjacobian) {
829:       if (ijacobian) {
830:         TSGetRHSMats_Private(ts,&Arhs,&Brhs);
831:       } else {
832:         TSGetIJacobian(ts,&Arhs,&Brhs,NULL,NULL);
833:       }
834:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
835:     }
836:     if (Arhs == A) {           /* No IJacobian, so we only have the RHS matrix */
837:       ts->rhsjacobian.scale = -1;
838:       ts->rhsjacobian.shift = shift;
839:       MatScale(A,-1);
840:       MatShift(A,shift);
841:       if (A != B) {
842:         MatScale(B,-1);
843:         MatShift(B,shift);
844:       }
845:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
846:       MatStructure axpy = DIFFERENT_NONZERO_PATTERN;
847:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
848:         MatZeroEntries(A);
849:         MatShift(A,shift);
850:         if (A != B) {
851:           MatZeroEntries(B);
852:           MatShift(B,shift);
853:         }
854:       }
855:       MatAXPY(A,-1,Arhs,axpy);
856:       if (A != B) {
857:         MatAXPY(B,-1,Brhs,axpy);
858:       }
859:     }
860:   }
861:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
862:   return(0);
863: }

867: /*@C
868:     TSSetRHSFunction - Sets the routine for evaluating the function,
869:     where U_t = G(t,u).

871:     Logically Collective on TS

873:     Input Parameters:
874: +   ts - the TS context obtained from TSCreate()
875: .   r - vector to put the computed right hand side (or NULL to have it created)
876: .   f - routine for evaluating the right-hand-side function
877: -   ctx - [optional] user-defined context for private data for the
878:           function evaluation routine (may be NULL)

880:     Calling sequence of func:
881: $     func (TS ts,PetscReal t,Vec u,Vec F,void *ctx);

883: +   t - current timestep
884: .   u - input vector
885: .   F - function vector
886: -   ctx - [optional] user-defined function context

888:     Level: beginner

890:     Notes: You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.

892: .keywords: TS, timestep, set, right-hand-side, function

894: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
895: @*/
896: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
897: {
899:   SNES           snes;
900:   Vec            ralloc = NULL;
901:   DM             dm;


907:   TSGetDM(ts,&dm);
908:   DMTSSetRHSFunction(dm,f,ctx);
909:   TSGetSNES(ts,&snes);
910:   if (!r && !ts->dm && ts->vec_sol) {
911:     VecDuplicate(ts->vec_sol,&ralloc);
912:     r    = ralloc;
913:   }
914:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
915:   VecDestroy(&ralloc);
916:   return(0);
917: }

921: /*@C
922:     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE

924:     Logically Collective on TS

926:     Input Parameters:
927: +   ts - the TS context obtained from TSCreate()
928: .   f - routine for evaluating the solution
929: -   ctx - [optional] user-defined context for private data for the
930:           function evaluation routine (may be NULL)

932:     Calling sequence of func:
933: $     func (TS ts,PetscReal t,Vec u,void *ctx);

935: +   t - current timestep
936: .   u - output vector
937: -   ctx - [optional] user-defined function context

939:     Notes:
940:     This routine is used for testing accuracy of time integration schemes when you already know the solution.
941:     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
942:     create closed-form solutions with non-physical forcing terms.

944:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

946:     Level: beginner

948: .keywords: TS, timestep, set, right-hand-side, function

950: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
951: @*/
952: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
953: {
955:   DM             dm;

959:   TSGetDM(ts,&dm);
960:   DMTSSetSolutionFunction(dm,f,ctx);
961:   return(0);
962: }

966: /*@C
967:     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE

969:     Logically Collective on TS

971:     Input Parameters:
972: +   ts - the TS context obtained from TSCreate()
973: .   f - routine for evaluating the forcing function
974: -   ctx - [optional] user-defined context for private data for the
975:           function evaluation routine (may be NULL)

977:     Calling sequence of func:
978: $     func (TS ts,PetscReal t,Vec u,void *ctx);

980: +   t - current timestep
981: .   u - output vector
982: -   ctx - [optional] user-defined function context

984:     Notes:
985:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
986:     create closed-form solutions with a non-physical forcing term.

988:     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.

990:     Level: beginner

992: .keywords: TS, timestep, set, right-hand-side, function

994: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
995: @*/
996: PetscErrorCode  TSSetForcingFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
997: {
999:   DM             dm;

1003:   TSGetDM(ts,&dm);
1004:   DMTSSetForcingFunction(dm,f,ctx);
1005:   return(0);
1006: }

1010: /*@C
1011:    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1012:    where U_t = G(U,t), as well as the location to store the matrix.

1014:    Logically Collective on TS

1016:    Input Parameters:
1017: +  ts  - the TS context obtained from TSCreate()
1018: .  Amat - (approximate) Jacobian matrix
1019: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1020: .  f   - the Jacobian evaluation routine
1021: -  ctx - [optional] user-defined context for private data for the
1022:          Jacobian evaluation routine (may be NULL)

1024:    Calling sequence of f:
1025: $     func (TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);

1027: +  t - current timestep
1028: .  u - input vector
1029: .  Amat - (approximate) Jacobian matrix
1030: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1031: -  ctx - [optional] user-defined context for matrix evaluation routine


1034:    Level: beginner

1036: .keywords: TS, timestep, set, right-hand-side, Jacobian

1038: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction(), TSRHSJacobianSetReuse(), TSSetIJacobian()

1040: @*/
1041: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1042: {
1044:   SNES           snes;
1045:   DM             dm;
1046:   TSIJacobian    ijacobian;


1055:   TSGetDM(ts,&dm);
1056:   DMTSSetRHSJacobian(dm,f,ctx);
1057:   if (f == TSComputeRHSJacobianConstant) {
1058:     /* Handle this case automatically for the user; otherwise user should call themselves. */
1059:     TSRHSJacobianSetReuse(ts,PETSC_TRUE);
1060:   }
1061:   DMTSGetIJacobian(dm,&ijacobian,NULL);
1062:   TSGetSNES(ts,&snes);
1063:   if (!ijacobian) {
1064:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1065:   }
1066:   if (Amat) {
1067:     PetscObjectReference((PetscObject)Amat);
1068:     MatDestroy(&ts->Arhs);

1070:     ts->Arhs = Amat;
1071:   }
1072:   if (Pmat) {
1073:     PetscObjectReference((PetscObject)Pmat);
1074:     MatDestroy(&ts->Brhs);

1076:     ts->Brhs = Pmat;
1077:   }
1078:   return(0);
1079: }


1084: /*@C
1085:    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.

1087:    Logically Collective on TS

1089:    Input Parameters:
1090: +  ts  - the TS context obtained from TSCreate()
1091: .  r   - vector to hold the residual (or NULL to have it created internally)
1092: .  f   - the function evaluation routine
1093: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

1095:    Calling sequence of f:
1096: $  f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);

1098: +  t   - time at step/stage being solved
1099: .  u   - state vector
1100: .  u_t - time derivative of state vector
1101: .  F   - function vector
1102: -  ctx - [optional] user-defined context for matrix evaluation routine

1104:    Important:
1105:    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.

1107:    Level: beginner

1109: .keywords: TS, timestep, set, DAE, Jacobian

1111: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
1112: @*/
1113: PetscErrorCode  TSSetIFunction(TS ts,Vec res,TSIFunction f,void *ctx)
1114: {
1116:   SNES           snes;
1117:   Vec            resalloc = NULL;
1118:   DM             dm;


1124:   TSGetDM(ts,&dm);
1125:   DMTSSetIFunction(dm,f,ctx);

1127:   TSGetSNES(ts,&snes);
1128:   if (!res && !ts->dm && ts->vec_sol) {
1129:     VecDuplicate(ts->vec_sol,&resalloc);
1130:     res  = resalloc;
1131:   }
1132:   SNESSetFunction(snes,res,SNESTSFormFunction,ts);
1133:   VecDestroy(&resalloc);
1134:   return(0);
1135: }

1139: /*@C
1140:    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/contex to compute it.

1142:    Not Collective

1144:    Input Parameter:
1145: .  ts - the TS context

1147:    Output Parameter:
1148: +  r - vector to hold residual (or NULL)
1149: .  func - the function to compute residual (or NULL)
1150: -  ctx - the function context (or NULL)

1152:    Level: advanced

1154: .keywords: TS, nonlinear, get, function

1156: .seealso: TSSetIFunction(), SNESGetFunction()
1157: @*/
1158: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1159: {
1161:   SNES           snes;
1162:   DM             dm;

1166:   TSGetSNES(ts,&snes);
1167:   SNESGetFunction(snes,r,NULL,NULL);
1168:   TSGetDM(ts,&dm);
1169:   DMTSGetIFunction(dm,func,ctx);
1170:   return(0);
1171: }

1175: /*@C
1176:    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.

1178:    Not Collective

1180:    Input Parameter:
1181: .  ts - the TS context

1183:    Output Parameter:
1184: +  r - vector to hold computed right hand side (or NULL)
1185: .  func - the function to compute right hand side (or NULL)
1186: -  ctx - the function context (or NULL)

1188:    Level: advanced

1190: .keywords: TS, nonlinear, get, function

1192: .seealso: TSSetRHSFunction(), SNESGetFunction()
1193: @*/
1194: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1195: {
1197:   SNES           snes;
1198:   DM             dm;

1202:   TSGetSNES(ts,&snes);
1203:   SNESGetFunction(snes,r,NULL,NULL);
1204:   TSGetDM(ts,&dm);
1205:   DMTSGetRHSFunction(dm,func,ctx);
1206:   return(0);
1207: }

1211: /*@C
1212:    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1213:         provided with TSSetIFunction().

1215:    Logically Collective on TS

1217:    Input Parameters:
1218: +  ts  - the TS context obtained from TSCreate()
1219: .  Amat - (approximate) Jacobian matrix
1220: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1221: .  f   - the Jacobian evaluation routine
1222: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

1224:    Calling sequence of f:
1225: $  f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);

1227: +  t    - time at step/stage being solved
1228: .  U    - state vector
1229: .  U_t  - time derivative of state vector
1230: .  a    - shift
1231: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1232: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1233: -  ctx  - [optional] user-defined context for matrix evaluation routine

1235:    Notes:
1236:    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.

1238:    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1239:    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1240:    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1241:    a and vector W depend on the integration method, step size, and past states. For example with
1242:    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1243:    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt

1245:    Level: beginner

1247: .keywords: TS, timestep, DAE, Jacobian

1249: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault(), TSSetRHSFunction()

1251: @*/
1252: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1253: {
1255:   SNES           snes;
1256:   DM             dm;


1265:   TSGetDM(ts,&dm);
1266:   DMTSSetIJacobian(dm,f,ctx);

1268:   TSGetSNES(ts,&snes);
1269:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1270:   return(0);
1271: }

1275: /*@
1276:    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1277:    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1278:    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1279:    not been changed by the TS.

1281:    Logically Collective

1283:    Input Arguments:
1284: +  ts - TS context obtained from TSCreate()
1285: -  reuse - PETSC_TRUE if the RHS Jacobian

1287:    Level: intermediate

1289: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1290: @*/
1291: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1292: {
1294:   ts->rhsjacobian.reuse = reuse;
1295:   return(0);
1296: }

1300: /*@C
1301:   TSLoad - Loads a KSP that has been stored in binary  with KSPView().

1303:   Collective on PetscViewer

1305:   Input Parameters:
1306: + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
1307:            some related function before a call to TSLoad().
1308: - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()

1310:    Level: intermediate

1312:   Notes:
1313:    The type is determined by the data in the file, any type set into the TS before this call is ignored.

1315:   Notes for advanced users:
1316:   Most users should not need to know the details of the binary storage
1317:   format, since TSLoad() and TSView() completely hide these details.
1318:   But for anyone who's interested, the standard binary matrix storage
1319:   format is
1320: .vb
1321:      has not yet been determined
1322: .ve

1324: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
1325: @*/
1326: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
1327: {
1329:   PetscBool      isbinary;
1330:   PetscInt       classid;
1331:   char           type[256];
1332:   DMTS           sdm;
1333:   DM             dm;

1338:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1339:   if (!isbinary) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");

1341:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
1342:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
1343:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
1344:   TSSetType(ts, type);
1345:   if (ts->ops->load) {
1346:     (*ts->ops->load)(ts,viewer);
1347:   }
1348:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
1349:   DMLoad(dm,viewer);
1350:   TSSetDM(ts,dm);
1351:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
1352:   VecLoad(ts->vec_sol,viewer);
1353:   DMGetDMTS(ts->dm,&sdm);
1354:   DMTSLoad(sdm,viewer);
1355:   return(0);
1356: }

1358: #include <petscdraw.h>
1359: #if defined(PETSC_HAVE_SAWS)
1360: #include <petscviewersaws.h>
1361: #endif
1364: /*@C
1365:     TSView - Prints the TS data structure.

1367:     Collective on TS

1369:     Input Parameters:
1370: +   ts - the TS context obtained from TSCreate()
1371: -   viewer - visualization context

1373:     Options Database Key:
1374: .   -ts_view - calls TSView() at end of TSStep()

1376:     Notes:
1377:     The available visualization contexts include
1378: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1379: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1380:          output where only the first processor opens
1381:          the file.  All other processors send their
1382:          data to the first processor to print.

1384:     The user can open an alternative visualization context with
1385:     PetscViewerASCIIOpen() - output to a specified file.

1387:     Level: beginner

1389: .keywords: TS, timestep, view

1391: .seealso: PetscViewerASCIIOpen()
1392: @*/
1393: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1394: {
1396:   TSType         type;
1397:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
1398:   DMTS           sdm;
1399: #if defined(PETSC_HAVE_SAWS)
1400:   PetscBool      issaws;
1401: #endif

1405:   if (!viewer) {
1406:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1407:   }

1411:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
1412:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
1413:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
1414:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
1415: #if defined(PETSC_HAVE_SAWS)
1416:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
1417: #endif
1418:   if (iascii) {
1419:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
1420:     PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
1421:     PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
1422:     if (ts->problem_type == TS_NONLINEAR) {
1423:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
1424:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
1425:     }
1426:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
1427:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
1428:     DMGetDMTS(ts->dm,&sdm);
1429:     DMTSView(sdm,viewer);
1430:     if (ts->ops->view) {
1431:       PetscViewerASCIIPushTab(viewer);
1432:       (*ts->ops->view)(ts,viewer);
1433:       PetscViewerASCIIPopTab(viewer);
1434:     }
1435:   } else if (isstring) {
1436:     TSGetType(ts,&type);
1437:     PetscViewerStringSPrintf(viewer," %-7.7s",type);
1438:   } else if (isbinary) {
1439:     PetscInt    classid = TS_FILE_CLASSID;
1440:     MPI_Comm    comm;
1441:     PetscMPIInt rank;
1442:     char        type[256];

1444:     PetscObjectGetComm((PetscObject)ts,&comm);
1445:     MPI_Comm_rank(comm,&rank);
1446:     if (!rank) {
1447:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
1448:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
1449:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
1450:     }
1451:     if (ts->ops->view) {
1452:       (*ts->ops->view)(ts,viewer);
1453:     }
1454:     DMView(ts->dm,viewer);
1455:     VecView(ts->vec_sol,viewer);
1456:     DMGetDMTS(ts->dm,&sdm);
1457:     DMTSView(sdm,viewer);
1458:   } else if (isdraw) {
1459:     PetscDraw draw;
1460:     char      str[36];
1461:     PetscReal x,y,bottom,h;

1463:     PetscViewerDrawGetDraw(viewer,0,&draw);
1464:     PetscDrawGetCurrentPoint(draw,&x,&y);
1465:     PetscStrcpy(str,"TS: ");
1466:     PetscStrcat(str,((PetscObject)ts)->type_name);
1467:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
1468:     bottom = y - h;
1469:     PetscDrawPushCurrentPoint(draw,x,bottom);
1470:     if (ts->ops->view) {
1471:       (*ts->ops->view)(ts,viewer);
1472:     }
1473:     PetscDrawPopCurrentPoint(draw);
1474: #if defined(PETSC_HAVE_SAWS)
1475:   } else if (issaws) {
1476:     PetscMPIInt rank;
1477:     const char  *name;

1479:     PetscObjectGetName((PetscObject)ts,&name);
1480:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
1481:     if (!((PetscObject)ts)->amsmem && !rank) {
1482:       char       dir[1024];

1484:       PetscObjectViewSAWs((PetscObject)ts,viewer);
1485:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
1486:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
1487:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
1488:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
1489:     }
1490:     if (ts->ops->view) {
1491:       (*ts->ops->view)(ts,viewer);
1492:     }
1493: #endif
1494:   }

1496:   PetscViewerASCIIPushTab(viewer);
1497:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
1498:   PetscViewerASCIIPopTab(viewer);
1499:   return(0);
1500: }


1505: /*@
1506:    TSSetApplicationContext - Sets an optional user-defined context for
1507:    the timesteppers.

1509:    Logically Collective on TS

1511:    Input Parameters:
1512: +  ts - the TS context obtained from TSCreate()
1513: -  usrP - optional user context

1515:    Level: intermediate

1517: .keywords: TS, timestep, set, application, context

1519: .seealso: TSGetApplicationContext()
1520: @*/
1521: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
1522: {
1525:   ts->user = usrP;
1526:   return(0);
1527: }

1531: /*@
1532:     TSGetApplicationContext - Gets the user-defined context for the
1533:     timestepper.

1535:     Not Collective

1537:     Input Parameter:
1538: .   ts - the TS context obtained from TSCreate()

1540:     Output Parameter:
1541: .   usrP - user context

1543:     Level: intermediate

1545: .keywords: TS, timestep, get, application, context

1547: .seealso: TSSetApplicationContext()
1548: @*/
1549: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
1550: {
1553:   *(void**)usrP = ts->user;
1554:   return(0);
1555: }

1559: /*@
1560:    TSGetTimeStepNumber - Gets the number of time steps completed.

1562:    Not Collective

1564:    Input Parameter:
1565: .  ts - the TS context obtained from TSCreate()

1567:    Output Parameter:
1568: .  iter - number of steps completed so far

1570:    Level: intermediate

1572: .keywords: TS, timestep, get, iteration, number
1573: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
1574: @*/
1575: PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
1576: {
1580:   *iter = ts->steps;
1581:   return(0);
1582: }

1586: /*@
1587:    TSSetInitialTimeStep - Sets the initial timestep to be used,
1588:    as well as the initial time.

1590:    Logically Collective on TS

1592:    Input Parameters:
1593: +  ts - the TS context obtained from TSCreate()
1594: .  initial_time - the initial time
1595: -  time_step - the size of the timestep

1597:    Level: intermediate

1599: .seealso: TSSetTimeStep(), TSGetTimeStep()

1601: .keywords: TS, set, initial, timestep
1602: @*/
1603: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
1604: {

1609:   TSSetTimeStep(ts,time_step);
1610:   TSSetTime(ts,initial_time);
1611:   return(0);
1612: }

1616: /*@
1617:    TSSetTimeStep - Allows one to reset the timestep at any time,
1618:    useful for simple pseudo-timestepping codes.

1620:    Logically Collective on TS

1622:    Input Parameters:
1623: +  ts - the TS context obtained from TSCreate()
1624: -  time_step - the size of the timestep

1626:    Level: intermediate

1628: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

1630: .keywords: TS, set, timestep
1631: @*/
1632: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
1633: {
1637:   ts->time_step      = time_step;
1638:   ts->time_step_orig = time_step;
1639:   return(0);
1640: }

1644: /*@
1645:    TSSetExactFinalTime - Determines whether to adapt the final time step to
1646:      match the exact final time, interpolate solution to the exact final time,
1647:      or just return at the final time TS computed.

1649:   Logically Collective on TS

1651:    Input Parameter:
1652: +   ts - the time-step context
1653: -   eftopt - exact final time option

1655:    Level: beginner

1657: .seealso: TSExactFinalTimeOption
1658: @*/
1659: PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
1660: {
1664:   ts->exact_final_time = eftopt;
1665:   return(0);
1666: }

1670: /*@
1671:    TSGetTimeStep - Gets the current timestep size.

1673:    Not Collective

1675:    Input Parameter:
1676: .  ts - the TS context obtained from TSCreate()

1678:    Output Parameter:
1679: .  dt - the current timestep size

1681:    Level: intermediate

1683: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

1685: .keywords: TS, get, timestep
1686: @*/
1687: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
1688: {
1692:   *dt = ts->time_step;
1693:   return(0);
1694: }

1698: /*@
1699:    TSGetSolution - Returns the solution at the present timestep. It
1700:    is valid to call this routine inside the function that you are evaluating
1701:    in order to move to the new timestep. This vector not changed until
1702:    the solution at the next timestep has been calculated.

1704:    Not Collective, but Vec returned is parallel if TS is parallel

1706:    Input Parameter:
1707: .  ts - the TS context obtained from TSCreate()

1709:    Output Parameter:
1710: .  v - the vector containing the solution

1712:    Level: intermediate

1714: .seealso: TSGetTimeStep()

1716: .keywords: TS, timestep, get, solution
1717: @*/
1718: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
1719: {
1723:   *v = ts->vec_sol;
1724:   return(0);
1725: }

1729: /*@
1730:    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()

1732:    Not Collective, but Vec returned is parallel if TS is parallel

1734:    Input Parameter:
1735: .  ts - the TS context obtained from TSCreate()

1737:    Output Parameter:
1738: +  lambda - vectors containing the gradients of the cost functions with respect to the ODE/DAE solution variables
1739: -  mu - vectors containing the gradients of the cost functions with respect to the problem parameters

1741:    Level: intermediate

1743: .seealso: TSGetTimeStep()

1745: .keywords: TS, timestep, get, sensitivity
1746: @*/
1747: PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
1748: {
1751:   if (numcost) *numcost = ts->numcost;
1752:   if (lambda)  *lambda  = ts->vecs_sensi;
1753:   if (mu)      *mu      = ts->vecs_sensip;
1754:   return(0);
1755: }

1757: /* ----- Routines to initialize and destroy a timestepper ---- */
1760: /*@
1761:   TSSetProblemType - Sets the type of problem to be solved.

1763:   Not collective

1765:   Input Parameters:
1766: + ts   - The TS
1767: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1768: .vb
1769:          U_t - A U = 0      (linear)
1770:          U_t - A(t) U = 0   (linear)
1771:          F(t,U,U_t) = 0     (nonlinear)
1772: .ve

1774:    Level: beginner

1776: .keywords: TS, problem type
1777: .seealso: TSSetUp(), TSProblemType, TS
1778: @*/
1779: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
1780: {

1785:   ts->problem_type = type;
1786:   if (type == TS_LINEAR) {
1787:     SNES snes;
1788:     TSGetSNES(ts,&snes);
1789:     SNESSetType(snes,SNESKSPONLY);
1790:   }
1791:   return(0);
1792: }

1796: /*@C
1797:   TSGetProblemType - Gets the type of problem to be solved.

1799:   Not collective

1801:   Input Parameter:
1802: . ts   - The TS

1804:   Output Parameter:
1805: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
1806: .vb
1807:          M U_t = A U
1808:          M(t) U_t = A(t) U
1809:          F(t,U,U_t)
1810: .ve

1812:    Level: beginner

1814: .keywords: TS, problem type
1815: .seealso: TSSetUp(), TSProblemType, TS
1816: @*/
1817: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
1818: {
1822:   *type = ts->problem_type;
1823:   return(0);
1824: }

1828: /*@
1829:    TSSetUp - Sets up the internal data structures for the later use
1830:    of a timestepper.

1832:    Collective on TS

1834:    Input Parameter:
1835: .  ts - the TS context obtained from TSCreate()

1837:    Notes:
1838:    For basic use of the TS solvers the user need not explicitly call
1839:    TSSetUp(), since these actions will automatically occur during
1840:    the call to TSStep().  However, if one wishes to control this
1841:    phase separately, TSSetUp() should be called after TSCreate()
1842:    and optional routines of the form TSSetXXX(), but before TSStep().

1844:    Level: advanced

1846: .keywords: TS, timestep, setup

1848: .seealso: TSCreate(), TSStep(), TSDestroy()
1849: @*/
1850: PetscErrorCode  TSSetUp(TS ts)
1851: {
1853:   DM             dm;
1854:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
1855:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
1856:   TSIJacobian    ijac;
1857:   TSRHSJacobian  rhsjac;

1861:   if (ts->setupcalled) return(0);

1863:   ts->total_steps = 0;
1864:   if (!((PetscObject)ts)->type_name) {
1865:     TSSetType(ts,TSEULER);
1866:   }

1868:   if (!ts->vec_sol) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");


1871:   TSGetAdapt(ts,&ts->adapt);

1873:   if (ts->rhsjacobian.reuse) {
1874:     Mat Amat,Pmat;
1875:     SNES snes;
1876:     TSGetSNES(ts,&snes);
1877:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
1878:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
1879:      * have displaced the RHS matrix */
1880:     if (Amat == ts->Arhs) {
1881:       MatDuplicate(ts->Arhs,MAT_DO_NOT_COPY_VALUES,&Amat);
1882:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
1883:       MatDestroy(&Amat);
1884:     }
1885:     if (Pmat == ts->Brhs) {
1886:       MatDuplicate(ts->Brhs,MAT_DO_NOT_COPY_VALUES,&Pmat);
1887:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
1888:       MatDestroy(&Pmat);
1889:     }
1890:   }
1891:   if (ts->ops->setup) {
1892:     (*ts->ops->setup)(ts);
1893:   }

1895:   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
1896:    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
1897:    */
1898:   TSGetDM(ts,&dm);
1899:   DMSNESGetFunction(dm,&func,NULL);
1900:   if (!func) {
1901:     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);
1902:   }
1903:   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
1904:      Otherwise, the SNES will use coloring internally to form the Jacobian.
1905:    */
1906:   DMSNESGetJacobian(dm,&jac,NULL);
1907:   DMTSGetIJacobian(dm,&ijac,NULL);
1908:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
1909:   if (!jac && (ijac || rhsjac)) {
1910:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
1911:   }
1912:   ts->setupcalled = PETSC_TRUE;
1913:   return(0);
1914: }

1918: /*@
1919:    TSAdjointSetUp - Sets up the internal data structures for the later use
1920:    of an adjoint solver

1922:    Collective on TS

1924:    Input Parameter:
1925: .  ts - the TS context obtained from TSCreate()

1927:    Level: advanced

1929: .keywords: TS, timestep, setup

1931: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
1932: @*/
1933: PetscErrorCode  TSAdjointSetUp(TS ts)
1934: {

1939:   if (ts->adjointsetupcalled) return(0);
1940:   if (!ts->vecs_sensi) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetCostGradients() first");

1942:   if (ts->vec_costintegral) { /* if there is integral in the cost function*/
1943:     VecDuplicateVecs(ts->vecs_sensi[0],ts->numcost,&ts->vecs_drdy);
1944:     if (ts->vecs_sensip){
1945:       VecDuplicateVecs(ts->vecs_sensip[0],ts->numcost,&ts->vecs_drdp);
1946:     }
1947:   }

1949:   if (ts->ops->adjointsetup) {
1950:     (*ts->ops->adjointsetup)(ts);
1951:   }
1952:   ts->adjointsetupcalled = PETSC_TRUE;
1953:   return(0);
1954: }

1958: /*@
1959:    TSReset - Resets a TS context and removes any allocated Vecs and Mats.

1961:    Collective on TS

1963:    Input Parameter:
1964: .  ts - the TS context obtained from TSCreate()

1966:    Level: beginner

1968: .keywords: TS, timestep, reset

1970: .seealso: TSCreate(), TSSetup(), TSDestroy()
1971: @*/
1972: PetscErrorCode  TSReset(TS ts)
1973: {


1979:   if (ts->ops->reset) {
1980:     (*ts->ops->reset)(ts);
1981:   }
1982:   if (ts->snes) {SNESReset(ts->snes);}
1983:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

1985:   MatDestroy(&ts->Arhs);
1986:   MatDestroy(&ts->Brhs);
1987:   VecDestroy(&ts->Frhs);
1988:   VecDestroy(&ts->vec_sol);
1989:   VecDestroy(&ts->vatol);
1990:   VecDestroy(&ts->vrtol);
1991:   VecDestroyVecs(ts->nwork,&ts->work);

1993:  if (ts->vec_costintegral) {
1994:     VecDestroyVecs(ts->numcost,&ts->vecs_drdy);
1995:     if (ts->vecs_drdp){
1996:       VecDestroyVecs(ts->numcost,&ts->vecs_drdp);
1997:     }
1998:   }
1999:   ts->vecs_sensi  = NULL;
2000:   ts->vecs_sensip = NULL;
2001:   MatDestroy(&ts->Jacp);
2002:   VecDestroy(&ts->vec_costintegral);
2003:   VecDestroy(&ts->vec_costintegrand);
2004:   ts->setupcalled = PETSC_FALSE;
2005:   return(0);
2006: }

2010: /*@
2011:    TSDestroy - Destroys the timestepper context that was created
2012:    with TSCreate().

2014:    Collective on TS

2016:    Input Parameter:
2017: .  ts - the TS context obtained from TSCreate()

2019:    Level: beginner

2021: .keywords: TS, timestepper, destroy

2023: .seealso: TSCreate(), TSSetUp(), TSSolve()
2024: @*/
2025: PetscErrorCode  TSDestroy(TS *ts)
2026: {

2030:   if (!*ts) return(0);
2032:   if (--((PetscObject)(*ts))->refct > 0) {*ts = 0; return(0);}

2034:   TSReset((*ts));

2036:   /* if memory was published with SAWs then destroy it */
2037:   PetscObjectSAWsViewOff((PetscObject)*ts);
2038:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

2040:   TSTrajectoryDestroy(&(*ts)->trajectory);

2042:   TSAdaptDestroy(&(*ts)->adapt);
2043:   if ((*ts)->event) {
2044:     TSEventMonitorDestroy(&(*ts)->event);
2045:   }
2046:   SNESDestroy(&(*ts)->snes);
2047:   DMDestroy(&(*ts)->dm);
2048:   TSMonitorCancel((*ts));

2050:   PetscHeaderDestroy(ts);
2051:   return(0);
2052: }

2056: /*@
2057:    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2058:    a TS (timestepper) context. Valid only for nonlinear problems.

2060:    Not Collective, but SNES is parallel if TS is parallel

2062:    Input Parameter:
2063: .  ts - the TS context obtained from TSCreate()

2065:    Output Parameter:
2066: .  snes - the nonlinear solver context

2068:    Notes:
2069:    The user can then directly manipulate the SNES context to set various
2070:    options, etc.  Likewise, the user can then extract and manipulate the
2071:    KSP, KSP, and PC contexts as well.

2073:    TSGetSNES() does not work for integrators that do not use SNES; in
2074:    this case TSGetSNES() returns NULL in snes.

2076:    Level: beginner

2078: .keywords: timestep, get, SNES
2079: @*/
2080: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2081: {

2087:   if (!ts->snes) {
2088:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
2089:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2090:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
2091:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
2092:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
2093:     if (ts->problem_type == TS_LINEAR) {
2094:       SNESSetType(ts->snes,SNESKSPONLY);
2095:     }
2096:   }
2097:   *snes = ts->snes;
2098:   return(0);
2099: }

2103: /*@
2104:    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context

2106:    Collective

2108:    Input Parameter:
2109: +  ts - the TS context obtained from TSCreate()
2110: -  snes - the nonlinear solver context

2112:    Notes:
2113:    Most users should have the TS created by calling TSGetSNES()

2115:    Level: developer

2117: .keywords: timestep, set, SNES
2118: @*/
2119: PetscErrorCode TSSetSNES(TS ts,SNES snes)
2120: {
2122:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

2127:   PetscObjectReference((PetscObject)snes);
2128:   SNESDestroy(&ts->snes);

2130:   ts->snes = snes;

2132:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
2133:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
2134:   if (func == SNESTSFormJacobian) {
2135:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
2136:   }
2137:   return(0);
2138: }

2142: /*@
2143:    TSGetKSP - Returns the KSP (linear solver) associated with
2144:    a TS (timestepper) context.

2146:    Not Collective, but KSP is parallel if TS is parallel

2148:    Input Parameter:
2149: .  ts - the TS context obtained from TSCreate()

2151:    Output Parameter:
2152: .  ksp - the nonlinear solver context

2154:    Notes:
2155:    The user can then directly manipulate the KSP context to set various
2156:    options, etc.  Likewise, the user can then extract and manipulate the
2157:    KSP and PC contexts as well.

2159:    TSGetKSP() does not work for integrators that do not use KSP;
2160:    in this case TSGetKSP() returns NULL in ksp.

2162:    Level: beginner

2164: .keywords: timestep, get, KSP
2165: @*/
2166: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2167: {
2169:   SNES           snes;

2174:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
2175:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
2176:   TSGetSNES(ts,&snes);
2177:   SNESGetKSP(snes,ksp);
2178:   return(0);
2179: }

2181: /* ----------- Routines to set solver parameters ---------- */

2185: /*@
2186:    TSGetDuration - Gets the maximum number of timesteps to use and
2187:    maximum time for iteration.

2189:    Not Collective

2191:    Input Parameters:
2192: +  ts       - the TS context obtained from TSCreate()
2193: .  maxsteps - maximum number of iterations to use, or NULL
2194: -  maxtime  - final time to iterate to, or NULL

2196:    Level: intermediate

2198: .keywords: TS, timestep, get, maximum, iterations, time
2199: @*/
2200: PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2201: {
2204:   if (maxsteps) {
2206:     *maxsteps = ts->max_steps;
2207:   }
2208:   if (maxtime) {
2210:     *maxtime = ts->max_time;
2211:   }
2212:   return(0);
2213: }

2217: /*@
2218:    TSSetDuration - Sets the maximum number of timesteps to use and
2219:    maximum time for iteration.

2221:    Logically Collective on TS

2223:    Input Parameters:
2224: +  ts - the TS context obtained from TSCreate()
2225: .  maxsteps - maximum number of iterations to use
2226: -  maxtime - final time to iterate to

2228:    Options Database Keys:
2229: .  -ts_max_steps <maxsteps> - Sets maxsteps
2230: .  -ts_final_time <maxtime> - Sets maxtime

2232:    Notes:
2233:    The default maximum number of iterations is 5000. Default time is 5.0

2235:    Level: intermediate

2237: .keywords: TS, timestep, set, maximum, iterations

2239: .seealso: TSSetExactFinalTime()
2240: @*/
2241: PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2242: {
2247:   if (maxsteps >= 0) ts->max_steps = maxsteps;
2248:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2249:   return(0);
2250: }

2254: /*@
2255:    TSSetSolution - Sets the initial solution vector
2256:    for use by the TS routines.

2258:    Logically Collective on TS and Vec

2260:    Input Parameters:
2261: +  ts - the TS context obtained from TSCreate()
2262: -  u - the solution vector

2264:    Level: beginner

2266: .keywords: TS, timestep, set, solution, initial conditions
2267: @*/
2268: PetscErrorCode  TSSetSolution(TS ts,Vec u)
2269: {
2271:   DM             dm;

2276:   PetscObjectReference((PetscObject)u);
2277:   VecDestroy(&ts->vec_sol);

2279:   ts->vec_sol = u;

2281:   TSGetDM(ts,&dm);
2282:   DMShellSetGlobalVector(dm,u);
2283:   return(0);
2284: }

2288: /*@
2289:    TSAdjointSetSteps - Sets the number of steps the adjoint solver should take backward in time

2291:    Logically Collective on TS

2293:    Input Parameters:
2294: +  ts - the TS context obtained from TSCreate()
2295: .  steps - number of steps to use

2297:    Level: intermediate

2299:    Notes: Normally one does not call this and TSAdjointSolve() integrates back to the original timestep. One can call this
2300:           so as to integrate back to less than the original timestep

2302: .keywords: TS, timestep, set, maximum, iterations

2304: .seealso: TSSetExactFinalTime()
2305: @*/
2306: PetscErrorCode  TSAdjointSetSteps(TS ts,PetscInt steps)
2307: {
2311:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back a negative number of steps");
2312:   if (steps > ts->total_steps) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Cannot step back more than the total number of forward steps");
2313:   ts->adjoint_max_steps = steps;
2314:   return(0);
2315: }

2319: /*@
2320:    TSSetCostGradients - Sets the initial value of the gradients of the cost function w.r.t. initial conditions and w.r.t. the problem parameters 
2321:       for use by the TSAdjoint routines.

2323:    Logically Collective on TS and Vec

2325:    Input Parameters:
2326: +  ts - the TS context obtained from TSCreate()
2327: .  lambda - gradients with respect to the initial condition variables, the dimension and parallel layout of these vectors is the same as the ODE solution vector
2328: -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters

2330:    Level: beginner

2332:    Notes: the entries in these vectors must be correctly initialized with the values lamda_i = df/dy|finaltime  mu_i = df/dp|finaltime

2334: .keywords: TS, timestep, set, sensitivity, initial conditions
2335: @*/
2336: PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2337: {
2341:   ts->vecs_sensi  = lambda;
2342:   ts->vecs_sensip = mu;
2343:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostIntegrand");
2344:   ts->numcost  = numcost;
2345:   return(0);
2346: }

2350: /*@C
2351:   TSAdjointSetRHSJacobian - Sets the function that computes the Jacobian of G w.r.t. the parameters p where y_t = G(y,p,t), as well as the location to store the matrix.

2353:   Logically Collective on TS

2355:   Input Parameters:
2356: + ts   - The TS context obtained from TSCreate()
2357: - func - The function

2359:   Calling sequence of func:
2360: $ func (TS ts,PetscReal t,Vec y,Mat A,void *ctx);
2361: +   t - current timestep
2362: .   y - input vector (current ODE solution)
2363: .   A - output matrix
2364: -   ctx - [optional] user-defined function context

2366:   Level: intermediate

2368:   Notes: Amat has the same number of rows and the same row parallel layout as u, Amat has the same number of columns and parallel layout as p

2370: .keywords: TS, sensitivity
2371: .seealso:
2372: @*/
2373: PetscErrorCode  TSAdjointSetRHSJacobian(TS ts,Mat Amat,PetscErrorCode (*func)(TS,PetscReal,Vec,Mat,void*),void *ctx)
2374: {


2381:   ts->rhsjacobianp    = func;
2382:   ts->rhsjacobianpctx = ctx;
2383:   if(Amat) {
2384:     PetscObjectReference((PetscObject)Amat);
2385:     MatDestroy(&ts->Jacp);
2386:     ts->Jacp = Amat;
2387:   }
2388:   return(0);
2389: }

2393: /*@C
2394:   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.

2396:   Collective on TS

2398:   Input Parameters:
2399: . ts   - The TS context obtained from TSCreate()

2401:   Level: developer

2403: .keywords: TS, sensitivity
2404: .seealso: TSAdjointSetRHSJacobian()
2405: @*/
2406: PetscErrorCode  TSAdjointComputeRHSJacobian(TS ts,PetscReal t,Vec X,Mat Amat)
2407: {


2415:   PetscStackPush("TS user JacobianP function for sensitivity analysis");
2416:   (*ts->rhsjacobianp)(ts,t,X,Amat,ts->rhsjacobianpctx);
2417:   PetscStackPop;
2418:   return(0);
2419: }

2423: /*@C
2424:     TSSetCostIntegrand - Sets the routine for evaluating the integral term in one or more cost functions

2426:     Logically Collective on TS

2428:     Input Parameters:
2429: +   ts - the TS context obtained from TSCreate()
2430: .   numcost - number of gradients to be computed, this is the number of cost functions
2431: .   rf - routine for evaluating the integrand function
2432: .   drdyf - function that computes the gradients of the r's with respect to y,NULL if not a function y
2433: .   drdpf - function that computes the gradients of the r's with respect to p, NULL if not a function of p
2434: -   ctx - [optional] user-defined context for private data for the function evaluation routine (may be NULL)

2436:     Calling sequence of rf:
2437: $     rf(TS ts,PetscReal t,Vec y,Vec f[],void *ctx);

2439: +   t - current timestep
2440: .   y - input vector
2441: .   f - function result; one vector entry for each cost function
2442: -   ctx - [optional] user-defined function context

2444:    Calling sequence of drdyf:
2445: $    PetscErroCode drdyf(TS ts,PetscReal t,Vec y,Vec *drdy,void *ctx);

2447:    Calling sequence of drdpf:
2448: $    PetscErroCode drdpf(TS ts,PetscReal t,Vec y,Vec *drdp,void *ctx);

2450:     Level: intermediate

2452:     Notes: For optimization there is generally a single cost function, numcost = 1. For sensitivities there may be multiple cost functions

2454: .keywords: TS, sensitivity analysis, timestep, set, quadrature, function

2456: .seealso: TSAdjointSetRHSJacobian(),TSGetCostGradients(), TSSetCostGradients()
2457: @*/
2458: PetscErrorCode  TSSetCostIntegrand(TS ts,PetscInt numcost, PetscErrorCode (*rf)(TS,PetscReal,Vec,Vec,void*),
2459:                                                                   PetscErrorCode (*drdyf)(TS,PetscReal,Vec,Vec*,void*),
2460:                                                                   PetscErrorCode (*drdpf)(TS,PetscReal,Vec,Vec*,void*),void *ctx)
2461: {

2466:   if (ts->numcost && ts->numcost!=numcost) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"The number of cost functions (2rd parameter of TSSetCostIntegrand()) is inconsistent with the one set by TSSetCostGradients()");
2467:   if (!ts->numcost) ts->numcost=numcost;

2469:   VecCreateSeq(PETSC_COMM_SELF,numcost,&ts->vec_costintegral);
2470:   VecDuplicate(ts->vec_costintegral,&ts->vec_costintegrand);
2471:   ts->costintegrand    = rf;
2472:   ts->costintegrandctx = ctx;
2473:   ts->drdyfunction     = drdyf;
2474:   ts->drdpfunction     = drdpf;
2475:   return(0);
2476: }

2480: /*@
2481:    TSGetCostIntegral - Returns the values of the integral term in the cost functions.
2482:    It is valid to call the routine after a backward run.

2484:    Not Collective

2486:    Input Parameter:
2487: .  ts - the TS context obtained from TSCreate()

2489:    Output Parameter:
2490: .  v - the vector containing the integrals for each cost function

2492:    Level: intermediate

2494: .seealso: TSSetCostIntegrand()

2496: .keywords: TS, sensitivity analysis
2497: @*/
2498: PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
2499: {
2503:   *v = ts->vec_costintegral;
2504:   return(0);
2505: }

2509: /*@
2510:    TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.

2512:    Input Parameters:
2513: +  ts - the TS context
2514: .  t - current time
2515: -  y - state vector, i.e. current solution

2517:    Output Parameter:
2518: .  q - vector of size numcost to hold the outputs

2520:    Note:
2521:    Most users should not need to explicitly call this routine, as it
2522:    is used internally within the sensitivity analysis context.

2524:    Level: developer

2526: .keywords: TS, compute

2528: .seealso: TSSetCostIntegrand()
2529: @*/
2530: PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
2531: {


2539:   PetscLogEventBegin(TS_FunctionEval,ts,y,q,0);
2540:   if (ts->costintegrand) {
2541:     PetscStackPush("TS user integrand in the cost function");
2542:     (*ts->costintegrand)(ts,t,y,q,ts->costintegrandctx);
2543:     PetscStackPop;
2544:   } else {
2545:     VecZeroEntries(q);
2546:   }

2548:   PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
2549:   return(0);
2550: }

2554: /*@
2555:   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.

2557:   Collective on TS

2559:   Input Parameters:
2560: . ts   - The TS context obtained from TSCreate()

2562:   Notes:
2563:   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
2564:   so most users would not generally call this routine themselves.

2566:   Level: developer

2568: .keywords: TS, sensitivity
2569: .seealso: TSAdjointComputeDRDYFunction()
2570: @*/
2571: PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
2572: {


2579:   PetscStackPush("TS user DRDY function for sensitivity analysis");
2580:   (*ts->drdyfunction)(ts,t,y,drdy,ts->costintegrandctx);
2581:   PetscStackPop;
2582:   return(0);
2583: }

2587: /*@
2588:   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.

2590:   Collective on TS

2592:   Input Parameters:
2593: . ts   - The TS context obtained from TSCreate()

2595:   Notes:
2596:   TSDRDPFunction() is typically used for sensitivity implementation,
2597:   so most users would not generally call this routine themselves.

2599:   Level: developer

2601: .keywords: TS, sensitivity
2602: .seealso: TSAdjointSetDRDPFunction()
2603: @*/
2604: PetscErrorCode  TSAdjointComputeDRDPFunction(TS ts,PetscReal t,Vec y,Vec *drdp)
2605: {


2612:   PetscStackPush("TS user DRDP function for sensitivity analysis");
2613:   (*ts->drdpfunction)(ts,t,y,drdp,ts->costintegrandctx);
2614:   PetscStackPop;
2615:   return(0);
2616: }

2620: /*@C
2621:   TSSetPreStep - Sets the general-purpose function
2622:   called once at the beginning of each time step.

2624:   Logically Collective on TS

2626:   Input Parameters:
2627: + ts   - The TS context obtained from TSCreate()
2628: - func - The function

2630:   Calling sequence of func:
2631: . func (TS ts);

2633:   Level: intermediate

2635:   Note:
2636:   If a step is rejected, TSStep() will call this routine again before each attempt.
2637:   The last completed time step number can be queried using TSGetTimeStepNumber(), the
2638:   size of the step being attempted can be obtained using TSGetTimeStep().

2640: .keywords: TS, timestep
2641: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
2642: @*/
2643: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2644: {
2647:   ts->prestep = func;
2648:   return(0);
2649: }

2653: /*@
2654:   TSPreStep - Runs the user-defined pre-step function.

2656:   Collective on TS

2658:   Input Parameters:
2659: . ts   - The TS context obtained from TSCreate()

2661:   Notes:
2662:   TSPreStep() is typically used within time stepping implementations,
2663:   so most users would not generally call this routine themselves.

2665:   Level: developer

2667: .keywords: TS, timestep
2668: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
2669: @*/
2670: PetscErrorCode  TSPreStep(TS ts)
2671: {

2676:   if (ts->prestep) {
2677:     PetscStackCallStandard((*ts->prestep),(ts));
2678:   }
2679:   return(0);
2680: }

2684: /*@C
2685:   TSSetPreStage - Sets the general-purpose function
2686:   called once at the beginning of each stage.

2688:   Logically Collective on TS

2690:   Input Parameters:
2691: + ts   - The TS context obtained from TSCreate()
2692: - func - The function

2694:   Calling sequence of func:
2695: . PetscErrorCode func(TS ts, PetscReal stagetime);

2697:   Level: intermediate

2699:   Note:
2700:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2701:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2702:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

2704: .keywords: TS, timestep
2705: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2706: @*/
2707: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2708: {
2711:   ts->prestage = func;
2712:   return(0);
2713: }

2717: /*@C
2718:   TSSetPostStage - Sets the general-purpose function
2719:   called once at the end of each stage.

2721:   Logically Collective on TS

2723:   Input Parameters:
2724: + ts   - The TS context obtained from TSCreate()
2725: - func - The function

2727:   Calling sequence of func:
2728: . PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);

2730:   Level: intermediate

2732:   Note:
2733:   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
2734:   The time step number being computed can be queried using TSGetTimeStepNumber() and the total size of the step being
2735:   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().

2737: .keywords: TS, timestep
2738: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2739: @*/
2740: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
2741: {
2744:   ts->poststage = func;
2745:   return(0);
2746: }

2750: /*@
2751:   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()

2753:   Collective on TS

2755:   Input Parameters:
2756: . ts          - The TS context obtained from TSCreate()
2757:   stagetime   - The absolute time of the current stage

2759:   Notes:
2760:   TSPreStage() is typically used within time stepping implementations,
2761:   most users would not generally call this routine themselves.

2763:   Level: developer

2765: .keywords: TS, timestep
2766: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2767: @*/
2768: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
2769: {

2774:   if (ts->prestage) {
2775:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
2776:   }
2777:   return(0);
2778: }

2782: /*@
2783:   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()

2785:   Collective on TS

2787:   Input Parameters:
2788: . ts          - The TS context obtained from TSCreate()
2789:   stagetime   - The absolute time of the current stage
2790:   stageindex  - Stage number
2791:   Y           - Array of vectors (of size = total number
2792:                 of stages) with the stage solutions

2794:   Notes:
2795:   TSPostStage() is typically used within time stepping implementations,
2796:   most users would not generally call this routine themselves.

2798:   Level: developer

2800: .keywords: TS, timestep
2801: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
2802: @*/
2803: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
2804: {

2809:   if (ts->poststage) {
2810:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
2811:   }
2812:   return(0);
2813: }

2817: /*@C
2818:   TSSetPostStep - Sets the general-purpose function
2819:   called once at the end of each time step.

2821:   Logically Collective on TS

2823:   Input Parameters:
2824: + ts   - The TS context obtained from TSCreate()
2825: - func - The function

2827:   Calling sequence of func:
2828: $ func (TS ts);

2830:   Level: intermediate

2832: .keywords: TS, timestep
2833: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2834: @*/
2835: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2836: {
2839:   ts->poststep = func;
2840:   return(0);
2841: }

2845: /*@
2846:   TSPostStep - Runs the user-defined post-step function.

2848:   Collective on TS

2850:   Input Parameters:
2851: . ts   - The TS context obtained from TSCreate()

2853:   Notes:
2854:   TSPostStep() is typically used within time stepping implementations,
2855:   so most users would not generally call this routine themselves.

2857:   Level: developer

2859: .keywords: TS, timestep
2860: @*/
2861: PetscErrorCode  TSPostStep(TS ts)
2862: {

2867:   if (ts->poststep) {
2868:     PetscStackCallStandard((*ts->poststep),(ts));
2869:   }
2870:   return(0);
2871: }

2873: /* ------------ Routines to set performance monitoring options ----------- */

2877: /*@C
2878:    TSMonitorSet - Sets an ADDITIONAL function that is to be used at every
2879:    timestep to display the iteration's  progress.

2881:    Logically Collective on TS

2883:    Input Parameters:
2884: +  ts - the TS context obtained from TSCreate()
2885: .  monitor - monitoring routine
2886: .  mctx - [optional] user-defined context for private data for the
2887:              monitor routine (use NULL if no context is desired)
2888: -  monitordestroy - [optional] routine that frees monitor context
2889:           (may be NULL)

2891:    Calling sequence of monitor:
2892: $    int monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)

2894: +    ts - the TS context
2895: .    steps - iteration number (after the final time step the monitor routine is called with a step of -1, this is at the final time which may have
2896:                                been interpolated to)
2897: .    time - current time
2898: .    u - current iterate
2899: -    mctx - [optional] monitoring context

2901:    Notes:
2902:    This routine adds an additional monitor to the list of monitors that
2903:    already has been loaded.

2905:    Fortran notes: Only a single monitor function can be set for each TS object

2907:    Level: intermediate

2909: .keywords: TS, timestep, set, monitor

2911: .seealso: TSMonitorDefault(), TSMonitorCancel()
2912: @*/
2913: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
2914: {
2917:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
2918:   ts->monitor[ts->numbermonitors]          = monitor;
2919:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
2920:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
2921:   return(0);
2922: }

2926: /*@C
2927:    TSMonitorCancel - Clears all the monitors that have been set on a time-step object.

2929:    Logically Collective on TS

2931:    Input Parameters:
2932: .  ts - the TS context obtained from TSCreate()

2934:    Notes:
2935:    There is no way to remove a single, specific monitor.

2937:    Level: intermediate

2939: .keywords: TS, timestep, set, monitor

2941: .seealso: TSMonitorDefault(), TSMonitorSet()
2942: @*/
2943: PetscErrorCode  TSMonitorCancel(TS ts)
2944: {
2946:   PetscInt       i;

2950:   for (i=0; i<ts->numbermonitors; i++) {
2951:     if (ts->monitordestroy[i]) {
2952:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
2953:     }
2954:   }
2955:   ts->numbermonitors = 0;
2956:   return(0);
2957: }

2961: /*@
2962:    TSMonitorDefault - Sets the Default monitor

2964:    Level: intermediate

2966: .keywords: TS, set, monitor

2968: .seealso: TSMonitorDefault(), TSMonitorSet()
2969: @*/
2970: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
2971: {
2973:   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));

2976:   PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
2977:   PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
2978:   PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
2979:   return(0);
2980: }

2984: /*@
2985:    TSSetRetainStages - Request that all stages in the upcoming step be stored so that interpolation will be available.

2987:    Logically Collective on TS

2989:    Input Argument:
2990: .  ts - time stepping context

2992:    Output Argument:
2993: .  flg - PETSC_TRUE or PETSC_FALSE

2995:    Level: intermediate

2997: .keywords: TS, set

2999: .seealso: TSInterpolate(), TSSetPostStep()
3000: @*/
3001: PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
3002: {
3005:   ts->retain_stages = flg;
3006:   return(0);
3007: }

3011: /*@
3012:    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval

3014:    Collective on TS

3016:    Input Argument:
3017: +  ts - time stepping context
3018: -  t - time to interpolate to

3020:    Output Argument:
3021: .  U - state at given time

3023:    Notes:
3024:    The user should call TSSetRetainStages() before taking a step in which interpolation will be requested.

3026:    Level: intermediate

3028:    Developer Notes:
3029:    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.

3031: .keywords: TS, set

3033: .seealso: TSSetRetainStages(), TSSetPostStep()
3034: @*/
3035: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3036: {

3042:   if (t < ts->ptime - ts->time_step_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)(ts->ptime-ts->time_step_prev),(double)ts->ptime);
3043:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3044:   (*ts->ops->interpolate)(ts,t,U);
3045:   return(0);
3046: }

3050: /*@
3051:    TSStep - Steps one time step

3053:    Collective on TS

3055:    Input Parameter:
3056: .  ts - the TS context obtained from TSCreate()

3058:    Level: developer

3060:    Notes:
3061:    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.

3063:    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3064:    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.

3066:    This may over-step the final time provided in TSSetDuration() depending on the time-step used. TSSolve() interpolates to exactly the
3067:    time provided in TSSetDuration(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.

3069: .keywords: TS, timestep, solve

3071: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
3072: @*/
3073: PetscErrorCode  TSStep(TS ts)
3074: {
3075:   DM               dm;
3076:   PetscErrorCode   ierr;
3077:   static PetscBool cite = PETSC_FALSE;

3081:   PetscCitationsRegister("@techreport{tspaper,\n"
3082:                                 "  title       = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3083:                                 "  author      = {Shrirang Abhyankar and Jed Brown and Emil Constantinescu and Debojyoti Ghosh and Barry F. Smith},\n"
3084:                                 "  type        = {Preprint},\n"
3085:                                 "  number      = {ANL/MCS-P5061-0114},\n"
3086:                                 "  institution = {Argonne National Laboratory},\n"
3087:                                 "  year        = {2014}\n}\n",&cite);

3089:   TSGetDM(ts, &dm);
3090:   TSSetUp(ts);

3092:   ts->reason = TS_CONVERGED_ITERATING;
3093:   ts->ptime_prev = ts->ptime;
3094:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

3096:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3097:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3098:   (*ts->ops->step)(ts);
3099:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3101:   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3102:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

3104:   if (ts->reason < 0) {
3105:     if (ts->errorifstepfailed) {
3106:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3107:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3108:     }
3109:   } else if (!ts->reason) {
3110:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3111:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3112:   }
3113:   ts->total_steps++;
3114:   ts->steprollback = PETSC_FALSE;
3115:   return(0);
3116: }

3120: /*@
3121:    TSAdjointStep - Steps one time step backward in the adjoint run

3123:    Collective on TS

3125:    Input Parameter:
3126: .  ts - the TS context obtained from TSCreate()

3128:    Level: intermediate

3130: .keywords: TS, adjoint, step

3132: .seealso: TSAdjointSetUp(), TSAdjointSolve()
3133: @*/
3134: PetscErrorCode  TSAdjointStep(TS ts)
3135: {
3136:   DM               dm;
3137:   PetscErrorCode   ierr;

3141:   TSGetDM(ts, &dm);
3142:   TSAdjointSetUp(ts);

3144:   ts->reason = TS_CONVERGED_ITERATING;
3145:   ts->ptime_prev = ts->ptime;
3146:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);
3147:   VecViewFromOptions(ts->vec_sol,(PetscObject)ts, "-ts_view_solution");

3149:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3150:   if (!ts->ops->adjointstep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed because the adjoint of  %s has not been implemented, try other time stepping methods for adjoint sensitivity analysis",((PetscObject)ts)->type_name);
3151:   (*ts->ops->adjointstep)(ts);
3152:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3154:   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3155:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

3157:   if (ts->reason < 0) {
3158:     if (ts->errorifstepfailed) {
3159:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
3160:         SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3161:       } else if (ts->reason == TS_DIVERGED_STEP_REJECTED) {
3162:         SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_reject or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
3163:       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3164:     }
3165:   } else if (!ts->reason) {
3166:     if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
3167:     else if (ts->ptime >= ts->max_time)         ts->reason = TS_CONVERGED_TIME;
3168:   }
3169:   ts->total_steps--;
3170:   return(0);
3171: }

3175: /*@
3176:    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.

3178:    Collective on TS

3180:    Input Arguments:
3181: +  ts - time stepping context
3182: .  order - desired order of accuracy
3183: -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)

3185:    Output Arguments:
3186: .  U - state at the end of the current step

3188:    Level: advanced

3190:    Notes:
3191:    This function cannot be called until all stages have been evaluated.
3192:    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.

3194: .seealso: TSStep(), TSAdapt
3195: @*/
3196: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3197: {

3204:   if (!ts->ops->evaluatestep) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
3205:   (*ts->ops->evaluatestep)(ts,order,U,done);
3206:   return(0);
3207: }


3212: /*@
3213:    TSSolve - Steps the requested number of timesteps.

3215:    Collective on TS

3217:    Input Parameter:
3218: +  ts - the TS context obtained from TSCreate()
3219: -  u - the solution vector  (can be null if TSSetSolution() was used, otherwise must contain the initial conditions)

3221:    Level: beginner

3223:    Notes:
3224:    The final time returned by this function may be different from the time of the internally
3225:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
3226:    stepped over the final time.

3228: .keywords: TS, timestep, solve

3230: .seealso: TSCreate(), TSSetSolution(), TSStep()
3231: @*/
3232: PetscErrorCode TSSolve(TS ts,Vec u)
3233: {
3234:   Vec               solution;
3235:   PetscErrorCode    ierr;

3240:   if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE) {   /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
3242:     if (!ts->vec_sol || u == ts->vec_sol) {
3243:       VecDuplicate(u,&solution);
3244:       TSSetSolution(ts,solution);
3245:       VecDestroy(&solution); /* grant ownership */
3246:     }
3247:     VecCopy(u,ts->vec_sol);
3248:   } else if (u) {
3249:     TSSetSolution(ts,u);
3250:   }
3251:   TSSetUp(ts);
3252:   /* reset time step and iteration counters */
3253:   ts->steps             = 0;
3254:   ts->ksp_its           = 0;
3255:   ts->snes_its          = 0;
3256:   ts->num_snes_failures = 0;
3257:   ts->reject            = 0;
3258:   ts->reason            = TS_CONVERGED_ITERATING;

3260:   TSViewFromOptions(ts,NULL,"-ts_view_pre");
3261:   {
3262:     DM dm;
3263:     TSGetDM(ts, &dm);
3264:     DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);
3265:   }

3267:   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
3268:     (*ts->ops->solve)(ts);
3269:     VecCopy(ts->vec_sol,u);
3270:     ts->solvetime = ts->ptime;
3271:   } else {
3272:     /* steps the requested number of timesteps. */
3273:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3274:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3275:     TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3276:     if (ts->vec_costintegral) ts->costintegralfwd=PETSC_TRUE;
3277:     if(ts->event) {
3278:       TSEventMonitorInitialize(ts);
3279:     }
3280:     while (!ts->reason) {
3281:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
3282:       TSStep(ts);
3283:       if (ts->event) {
3284:         TSEventMonitor(ts);
3285:       }
3286:       if(!ts->steprollback) {
3287:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
3288:         TSPostStep(ts);
3289:       }
3290:     }
3291:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
3292:       TSInterpolate(ts,ts->max_time,u);
3293:       ts->solvetime = ts->max_time;
3294:       solution = u;
3295:     } else {
3296:       if (u) {VecCopy(ts->vec_sol,u);}
3297:       ts->solvetime = ts->ptime;
3298:       solution = ts->vec_sol;
3299:     }
3300:     TSMonitor(ts,ts->steps,ts->solvetime,solution);
3301:     VecViewFromOptions(solution,(PetscObject) ts,"-ts_view_solution");
3302:   }

3304:   TSViewFromOptions(ts,NULL,"-ts_view");
3305:   VecViewFromOptions(ts->vec_sol,NULL,"-ts_view_solution");
3306:   PetscObjectSAWsBlock((PetscObject)ts);
3307:   if (ts->adjoint_solve) {
3308:     TSAdjointSolve(ts);
3309:   }
3310:   return(0);
3311: }

3315: /*@
3316:    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE

3318:    Collective on TS

3320:    Input Parameter:
3321: .  ts - the TS context obtained from TSCreate()

3323:    Options Database:
3324: . -ts_adjoint_view_solution <viewerinfo> - views the first gradient with respect to the initial conditions

3326:    Level: intermediate

3328:    Notes:
3329:    This must be called after a call to TSSolve() that solves the forward problem

3331:    By default this will integrate back to the initial time, one can use TSAdjointSetSteps() to step back to a later time

3333: .keywords: TS, timestep, solve

3335: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
3336: @*/
3337: PetscErrorCode TSAdjointSolve(TS ts)
3338: {
3339:   PetscErrorCode    ierr;

3343:   TSAdjointSetUp(ts);
3344:   /* reset time step and iteration counters */
3345:   ts->steps             = 0;
3346:   ts->ksp_its           = 0;
3347:   ts->snes_its          = 0;
3348:   ts->num_snes_failures = 0;
3349:   ts->reject            = 0;
3350:   ts->reason            = TS_CONVERGED_ITERATING;

3352:   if (!ts->adjoint_max_steps) ts->adjoint_max_steps = ts->total_steps;

3354:   if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
3355:   while (!ts->reason) {
3356:     TSTrajectoryGet(ts->trajectory,ts,ts->adjoint_max_steps-ts->steps,&ts->ptime);
3357:     TSMonitor(ts,ts->adjoint_max_steps-ts->steps,ts->ptime,ts->vec_sol);
3358:     TSAdjointStep(ts);
3359:     if (ts->event) {
3360:       TSAdjointEventMonitor(ts);
3361:     }
3362:   }
3363:   ts->solvetime = ts->ptime;
3364:   VecViewFromOptions(ts->vecs_sensi[0],(PetscObject) ts, "-ts_adjoint_view_solution");
3365:   return(0);
3366: }

3370: /*@
3371:    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()

3373:    Collective on TS

3375:    Input Parameters:
3376: +  ts - time stepping context obtained from TSCreate()
3377: .  step - step number that has just completed
3378: .  ptime - model time of the state
3379: -  u - state at the current model time

3381:    Notes:
3382:    TSMonitor() is typically used within the time stepping implementations.
3383:    Users might call this function when using the TSStep() interface instead of TSSolve().

3385:    Level: advanced

3387: .keywords: TS, timestep
3388: @*/
3389: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
3390: {
3392:   PetscInt       i,n = ts->numbermonitors;

3397:   VecLockPush(u);
3398:   for (i=0; i<n; i++) {
3399:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
3400:   }
3401:   VecLockPop(u);
3402:   return(0);
3403: }

3405: /* ------------------------------------------------------------------------*/
3408: /*@C
3409:    TSMonitorLGCtxCreate - Creates a line graph context for use with
3410:    TS to monitor the solution process graphically in various ways

3412:    Collective on TS

3414:    Input Parameters:
3415: +  host - the X display to open, or null for the local machine
3416: .  label - the title to put in the title bar
3417: .  x, y - the screen coordinates of the upper left coordinate of the window
3418: .  m, n - the screen width and height in pixels
3419: -  howoften - if positive then determines the frequency of the plotting, if -1 then only at the final time

3421:    Output Parameter:
3422: .  ctx - the context

3424:    Options Database Key:
3425: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
3426: .  -ts_monitor_lg_solution -
3427: .  -ts_monitor_lg_error -
3428: .  -ts_monitor_lg_ksp_iterations -
3429: .  -ts_monitor_lg_snes_iterations -
3430: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

3432:    Notes:
3433:    Use TSMonitorLGCtxDestroy() to destroy.

3435:    Level: intermediate

3437: .keywords: TS, monitor, line graph, residual, seealso

3439: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

3441: @*/
3442: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
3443: {
3444:   PetscDraw      win;

3448:   PetscNew(ctx);
3449:   PetscDrawCreate(comm,host,label,x,y,m,n,&win);
3450:   PetscDrawSetFromOptions(win);
3451:   PetscDrawLGCreate(win,1,&(*ctx)->lg);
3452:   PetscLogObjectParent((PetscObject)(*ctx)->lg,(PetscObject)win);
3453:   PetscDrawLGSetUseMarkers((*ctx)->lg,PETSC_TRUE);
3454:   PetscDrawLGSetFromOptions((*ctx)->lg);
3455:   (*ctx)->howoften = howoften;
3456:   return(0);
3457: }

3461: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
3462: {
3463:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
3464:   PetscReal      x   = ptime,y;

3468:   if (!step) {
3469:     PetscDrawAxis axis;
3470:     PetscDrawLGGetAxis(ctx->lg,&axis);
3471:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");
3472:     PetscDrawLGReset(ctx->lg);
3473:   }
3474:   TSGetTimeStep(ts,&y);
3475:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
3476:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
3477:     PetscDrawLGDraw(ctx->lg);
3478:   }
3479:   return(0);
3480: }

3484: /*@C
3485:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
3486:    with TSMonitorLGCtxCreate().

3488:    Collective on TSMonitorLGCtx

3490:    Input Parameter:
3491: .  ctx - the monitor context

3493:    Level: intermediate

3495: .keywords: TS, monitor, line graph, destroy

3497: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
3498: @*/
3499: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
3500: {
3501:   PetscDraw      draw;

3505:   if ((*ctx)->transformdestroy) {
3506:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
3507:   }
3508:   PetscDrawLGGetDraw((*ctx)->lg,&draw);
3509:   PetscDrawDestroy(&draw);
3510:   PetscDrawLGDestroy(&(*ctx)->lg);
3511:   PetscStrArrayDestroy(&(*ctx)->names);
3512:   PetscStrArrayDestroy(&(*ctx)->displaynames);
3513:   PetscFree((*ctx)->displayvariables);
3514:   PetscFree((*ctx)->displayvalues);
3515:   PetscFree(*ctx);
3516:   return(0);
3517: }

3521: /*@
3522:    TSGetTime - Gets the time of the most recently completed step.

3524:    Not Collective

3526:    Input Parameter:
3527: .  ts - the TS context obtained from TSCreate()

3529:    Output Parameter:
3530: .  t  - the current time

3532:    Level: beginner

3534:    Note:
3535:    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
3536:    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.

3538: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

3540: .keywords: TS, get, time
3541: @*/
3542: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3543: {
3547:   *t = ts->ptime;
3548:   return(0);
3549: }

3553: /*@
3554:    TSGetPrevTime - Gets the starting time of the previously completed step.

3556:    Not Collective

3558:    Input Parameter:
3559: .  ts - the TS context obtained from TSCreate()

3561:    Output Parameter:
3562: .  t  - the previous time

3564:    Level: beginner

3566: .seealso: TSSetInitialTimeStep(), TSGetTimeStep()

3568: .keywords: TS, get, time
3569: @*/
3570: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
3571: {
3575:   *t = ts->ptime_prev;
3576:   return(0);
3577: }

3581: /*@
3582:    TSSetTime - Allows one to reset the time.

3584:    Logically Collective on TS

3586:    Input Parameters:
3587: +  ts - the TS context obtained from TSCreate()
3588: -  time - the time

3590:    Level: intermediate

3592: .seealso: TSGetTime(), TSSetDuration()

3594: .keywords: TS, set, time
3595: @*/
3596: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
3597: {
3601:   ts->ptime = t;
3602:   return(0);
3603: }

3607: /*@C
3608:    TSSetOptionsPrefix - Sets the prefix used for searching for all
3609:    TS options in the database.

3611:    Logically Collective on TS

3613:    Input Parameter:
3614: +  ts     - The TS context
3615: -  prefix - The prefix to prepend to all option names

3617:    Notes:
3618:    A hyphen (-) must NOT be given at the beginning of the prefix name.
3619:    The first character of all runtime options is AUTOMATICALLY the
3620:    hyphen.

3622:    Level: advanced

3624: .keywords: TS, set, options, prefix, database

3626: .seealso: TSSetFromOptions()

3628: @*/
3629: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
3630: {
3632:   SNES           snes;

3636:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
3637:   TSGetSNES(ts,&snes);
3638:   SNESSetOptionsPrefix(snes,prefix);
3639:   return(0);
3640: }


3645: /*@C
3646:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3647:    TS options in the database.

3649:    Logically Collective on TS

3651:    Input Parameter:
3652: +  ts     - The TS context
3653: -  prefix - The prefix to prepend to all option names

3655:    Notes:
3656:    A hyphen (-) must NOT be given at the beginning of the prefix name.
3657:    The first character of all runtime options is AUTOMATICALLY the
3658:    hyphen.

3660:    Level: advanced

3662: .keywords: TS, append, options, prefix, database

3664: .seealso: TSGetOptionsPrefix()

3666: @*/
3667: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
3668: {
3670:   SNES           snes;

3674:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
3675:   TSGetSNES(ts,&snes);
3676:   SNESAppendOptionsPrefix(snes,prefix);
3677:   return(0);
3678: }

3682: /*@C
3683:    TSGetOptionsPrefix - Sets the prefix used for searching for all
3684:    TS options in the database.

3686:    Not Collective

3688:    Input Parameter:
3689: .  ts - The TS context

3691:    Output Parameter:
3692: .  prefix - A pointer to the prefix string used

3694:    Notes: On the fortran side, the user should pass in a string 'prifix' of
3695:    sufficient length to hold the prefix.

3697:    Level: intermediate

3699: .keywords: TS, get, options, prefix, database

3701: .seealso: TSAppendOptionsPrefix()
3702: @*/
3703: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
3704: {

3710:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
3711:   return(0);
3712: }

3716: /*@C
3717:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

3719:    Not Collective, but parallel objects are returned if TS is parallel

3721:    Input Parameter:
3722: .  ts  - The TS context obtained from TSCreate()

3724:    Output Parameters:
3725: +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
3726: .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
3727: .  func - Function to compute the Jacobian of the RHS  (or NULL)
3728: -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)

3730:    Notes: You can pass in NULL for any return argument you do not need.

3732:    Level: intermediate

3734: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

3736: .keywords: TS, timestep, get, matrix, Jacobian
3737: @*/
3738: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
3739: {
3741:   SNES           snes;
3742:   DM             dm;

3745:   TSGetSNES(ts,&snes);
3746:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
3747:   TSGetDM(ts,&dm);
3748:   DMTSGetRHSJacobian(dm,func,ctx);
3749:   return(0);
3750: }

3754: /*@C
3755:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

3757:    Not Collective, but parallel objects are returned if TS is parallel

3759:    Input Parameter:
3760: .  ts  - The TS context obtained from TSCreate()

3762:    Output Parameters:
3763: +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
3764: .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
3765: .  f   - The function to compute the matrices
3766: - ctx - User-defined context for Jacobian evaluation routine

3768:    Notes: You can pass in NULL for any return argument you do not need.

3770:    Level: advanced

3772: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetTimeStepNumber()

3774: .keywords: TS, timestep, get, matrix, Jacobian
3775: @*/
3776: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
3777: {
3779:   SNES           snes;
3780:   DM             dm;

3783:   TSGetSNES(ts,&snes);
3784:   SNESSetUpMatrices(snes);
3785:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
3786:   TSGetDM(ts,&dm);
3787:   DMTSGetIJacobian(dm,f,ctx);
3788:   return(0);
3789: }


3794: /*@C
3795:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
3796:    VecView() for the solution at each timestep

3798:    Collective on TS

3800:    Input Parameters:
3801: +  ts - the TS context
3802: .  step - current time-step
3803: .  ptime - current time
3804: -  dummy - either a viewer or NULL

3806:    Options Database:
3807: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

3809:    Notes: the initial solution and current solution are not display with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
3810:        will look bad

3812:    Level: intermediate

3814: .keywords: TS,  vector, monitor, view

3816: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3817: @*/
3818: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3819: {
3820:   PetscErrorCode   ierr;
3821:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
3822:   PetscDraw        draw;

3825:   if (!step && ictx->showinitial) {
3826:     if (!ictx->initialsolution) {
3827:       VecDuplicate(u,&ictx->initialsolution);
3828:     }
3829:     VecCopy(u,ictx->initialsolution);
3830:   }
3831:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

3833:   if (ictx->showinitial) {
3834:     PetscReal pause;
3835:     PetscViewerDrawGetPause(ictx->viewer,&pause);
3836:     PetscViewerDrawSetPause(ictx->viewer,0.0);
3837:     VecView(ictx->initialsolution,ictx->viewer);
3838:     PetscViewerDrawSetPause(ictx->viewer,pause);
3839:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
3840:   }
3841:   VecView(u,ictx->viewer);
3842:   if (ictx->showtimestepandtime) {
3843:     PetscReal xl,yl,xr,yr,h;
3844:     char      time[32];

3846:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
3847:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
3848:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
3849:     h    = yl + .95*(yr - yl);
3850:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
3851:     PetscDrawFlush(draw);
3852:   }

3854:   if (ictx->showinitial) {
3855:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
3856:   }
3857:   return(0);
3858: }

3862: /*@C
3863:    TSMonitorDrawSolutionPhase - Monitors progress of the TS solvers by plotting the solution as a phase diagram

3865:    Collective on TS

3867:    Input Parameters:
3868: +  ts - the TS context
3869: .  step - current time-step
3870: .  ptime - current time
3871: -  dummy - either a viewer or NULL

3873:    Level: intermediate

3875: .keywords: TS,  vector, monitor, view

3877: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
3878: @*/
3879: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
3880: {
3881:   PetscErrorCode    ierr;
3882:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
3883:   PetscDraw         draw;
3884:   MPI_Comm          comm;
3885:   PetscInt          n;
3886:   PetscMPIInt       size;
3887:   PetscReal         xl,yl,xr,yr,h;
3888:   char              time[32];
3889:   const PetscScalar *U;

3892:   PetscObjectGetComm((PetscObject)ts,&comm);
3893:   MPI_Comm_size(comm,&size);
3894:   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
3895:   VecGetSize(u,&n);
3896:   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");

3898:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);

3900:   VecGetArrayRead(u,&U);
3901:   PetscDrawAxisGetLimits(ictx->axis,&xl,&xr,&yl,&yr);
3902:   if ((PetscRealPart(U[0]) < xl) || (PetscRealPart(U[1]) < yl) || (PetscRealPart(U[0]) > xr) || (PetscRealPart(U[1]) > yr)) {
3903:       VecRestoreArrayRead(u,&U);
3904:       return(0);
3905:   }
3906:   if (!step) ictx->color++;
3907:   PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);
3908:   VecRestoreArrayRead(u,&U);

3910:   if (ictx->showtimestepandtime) {
3911:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
3912:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
3913:     h    = yl + .95*(yr - yl);
3914:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
3915:   }
3916:   PetscDrawFlush(draw);
3917:   return(0);
3918: }


3923: /*@C
3924:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

3926:    Collective on TS

3928:    Input Parameters:
3929: .    ctx - the monitor context

3931:    Level: intermediate

3933: .keywords: TS,  vector, monitor, view

3935: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
3936: @*/
3937: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
3938: {

3942:   PetscDrawAxisDestroy(&(*ictx)->axis);
3943:   PetscViewerDestroy(&(*ictx)->viewer);
3944:   VecDestroy(&(*ictx)->initialsolution);
3945:   PetscFree(*ictx);
3946:   return(0);
3947: }

3951: /*@C
3952:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

3954:    Collective on TS

3956:    Input Parameter:
3957: .    ts - time-step context

3959:    Output Patameter:
3960: .    ctx - the monitor context

3962:    Options Database:
3963: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

3965:    Level: intermediate

3967: .keywords: TS,  vector, monitor, view

3969: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
3970: @*/
3971: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
3972: {
3973:   PetscErrorCode   ierr;

3976:   PetscNew(ctx);
3977:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
3978:   PetscViewerSetFromOptions((*ctx)->viewer);

3980:   (*ctx)->howoften    = howoften;
3981:   (*ctx)->showinitial = PETSC_FALSE;
3982:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

3984:   (*ctx)->showtimestepandtime = PETSC_FALSE;
3985:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
3986:   (*ctx)->color = PETSC_DRAW_WHITE;
3987:   return(0);
3988: }

3992: /*@C
3993:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
3994:    VecView() for the error at each timestep

3996:    Collective on TS

3998:    Input Parameters:
3999: +  ts - the TS context
4000: .  step - current time-step
4001: .  ptime - current time
4002: -  dummy - either a viewer or NULL

4004:    Level: intermediate

4006: .keywords: TS,  vector, monitor, view

4008: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4009: @*/
4010: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
4011: {
4012:   PetscErrorCode   ierr;
4013:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
4014:   PetscViewer      viewer = ctx->viewer;
4015:   Vec              work;

4018:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
4019:   VecDuplicate(u,&work);
4020:   TSComputeSolutionFunction(ts,ptime,work);
4021:   VecAXPY(work,-1.0,u);
4022:   VecView(work,viewer);
4023:   VecDestroy(&work);
4024:   return(0);
4025: }

4027: #include <petsc/private/dmimpl.h>
4030: /*@
4031:    TSSetDM - Sets the DM that may be used by some preconditioners

4033:    Logically Collective on TS and DM

4035:    Input Parameters:
4036: +  ts - the preconditioner context
4037: -  dm - the dm

4039:    Level: intermediate


4042: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
4043: @*/
4044: PetscErrorCode  TSSetDM(TS ts,DM dm)
4045: {
4047:   SNES           snes;
4048:   DMTS           tsdm;

4052:   PetscObjectReference((PetscObject)dm);
4053:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
4054:     if (ts->dm->dmts && !dm->dmts) {
4055:       DMCopyDMTS(ts->dm,dm);
4056:       DMGetDMTS(ts->dm,&tsdm);
4057:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
4058:         tsdm->originaldm = dm;
4059:       }
4060:     }
4061:     DMDestroy(&ts->dm);
4062:   }
4063:   ts->dm = dm;

4065:   TSGetSNES(ts,&snes);
4066:   SNESSetDM(snes,dm);
4067:   return(0);
4068: }

4072: /*@
4073:    TSGetDM - Gets the DM that may be used by some preconditioners

4075:    Not Collective

4077:    Input Parameter:
4078: . ts - the preconditioner context

4080:    Output Parameter:
4081: .  dm - the dm

4083:    Level: intermediate


4086: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4087: @*/
4088: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4089: {

4094:   if (!ts->dm) {
4095:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
4096:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
4097:   }
4098:   *dm = ts->dm;
4099:   return(0);
4100: }

4104: /*@
4105:    SNESTSFormFunction - Function to evaluate nonlinear residual

4107:    Logically Collective on SNES

4109:    Input Parameter:
4110: + snes - nonlinear solver
4111: . U - the current state at which to evaluate the residual
4112: - ctx - user context, must be a TS

4114:    Output Parameter:
4115: . F - the nonlinear residual

4117:    Notes:
4118:    This function is not normally called by users and is automatically registered with the SNES used by TS.
4119:    It is most frequently passed to MatFDColoringSetFunction().

4121:    Level: advanced

4123: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
4124: @*/
4125: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
4126: {
4127:   TS             ts = (TS)ctx;

4135:   (ts->ops->snesfunction)(snes,U,F,ts);
4136:   return(0);
4137: }

4141: /*@
4142:    SNESTSFormJacobian - Function to evaluate the Jacobian

4144:    Collective on SNES

4146:    Input Parameter:
4147: + snes - nonlinear solver
4148: . U - the current state at which to evaluate the residual
4149: - ctx - user context, must be a TS

4151:    Output Parameter:
4152: + A - the Jacobian
4153: . B - the preconditioning matrix (may be the same as A)
4154: - flag - indicates any structure change in the matrix

4156:    Notes:
4157:    This function is not normally called by users and is automatically registered with the SNES used by TS.

4159:    Level: developer

4161: .seealso: SNESSetJacobian()
4162: @*/
4163: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
4164: {
4165:   TS             ts = (TS)ctx;

4176:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
4177:   return(0);
4178: }

4182: /*@C
4183:    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems only

4185:    Collective on TS

4187:    Input Arguments:
4188: +  ts - time stepping context
4189: .  t - time at which to evaluate
4190: .  U - state at which to evaluate
4191: -  ctx - context

4193:    Output Arguments:
4194: .  F - right hand side

4196:    Level: intermediate

4198:    Notes:
4199:    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
4200:    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().

4202: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
4203: @*/
4204: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
4205: {
4207:   Mat            Arhs,Brhs;

4210:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
4211:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
4212:   MatMult(Arhs,U,F);
4213:   return(0);
4214: }

4218: /*@C
4219:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

4221:    Collective on TS

4223:    Input Arguments:
4224: +  ts - time stepping context
4225: .  t - time at which to evaluate
4226: .  U - state at which to evaluate
4227: -  ctx - context

4229:    Output Arguments:
4230: +  A - pointer to operator
4231: .  B - pointer to preconditioning matrix
4232: -  flg - matrix structure flag

4234:    Level: intermediate

4236:    Notes:
4237:    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.

4239: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
4240: @*/
4241: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
4242: {
4244:   return(0);
4245: }

4249: /*@C
4250:    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only

4252:    Collective on TS

4254:    Input Arguments:
4255: +  ts - time stepping context
4256: .  t - time at which to evaluate
4257: .  U - state at which to evaluate
4258: .  Udot - time derivative of state vector
4259: -  ctx - context

4261:    Output Arguments:
4262: .  F - left hand side

4264:    Level: intermediate

4266:    Notes:
4267:    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
4268:    user is required to write their own TSComputeIFunction.
4269:    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
4270:    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().

4272: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
4273: @*/
4274: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
4275: {
4277:   Mat            A,B;

4280:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
4281:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
4282:   MatMult(A,Udot,F);
4283:   return(0);
4284: }

4288: /*@C
4289:    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE

4291:    Collective on TS

4293:    Input Arguments:
4294: +  ts - time stepping context
4295: .  t - time at which to evaluate
4296: .  U - state at which to evaluate
4297: .  Udot - time derivative of state vector
4298: .  shift - shift to apply
4299: -  ctx - context

4301:    Output Arguments:
4302: +  A - pointer to operator
4303: .  B - pointer to preconditioning matrix
4304: -  flg - matrix structure flag

4306:    Level: advanced

4308:    Notes:
4309:    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.

4311:    It is only appropriate for problems of the form

4313: $     M Udot = F(U,t)

4315:   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4316:   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4317:   an implicit operator of the form

4319: $    shift*M + J

4321:   where J is the Jacobian of -F(U).  Support may be added in a future version of PETSc, but for now, the user must store
4322:   a copy of M or reassemble it when requested.

4324: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
4325: @*/
4326: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
4327: {

4331:   MatScale(A, shift / ts->ijacobian.shift);
4332:   ts->ijacobian.shift = shift;
4333:   return(0);
4334: }

4338: /*@
4339:    TSGetEquationType - Gets the type of the equation that TS is solving.

4341:    Not Collective

4343:    Input Parameter:
4344: .  ts - the TS context

4346:    Output Parameter:
4347: .  equation_type - see TSEquationType

4349:    Level: beginner

4351: .keywords: TS, equation type

4353: .seealso: TSSetEquationType(), TSEquationType
4354: @*/
4355: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4356: {
4360:   *equation_type = ts->equation_type;
4361:   return(0);
4362: }

4366: /*@
4367:    TSSetEquationType - Sets the type of the equation that TS is solving.

4369:    Not Collective

4371:    Input Parameter:
4372: +  ts - the TS context
4373: -  equation_type - see TSEquationType

4375:    Level: advanced

4377: .keywords: TS, equation type

4379: .seealso: TSGetEquationType(), TSEquationType
4380: @*/
4381: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4382: {
4385:   ts->equation_type = equation_type;
4386:   return(0);
4387: }

4391: /*@
4392:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

4394:    Not Collective

4396:    Input Parameter:
4397: .  ts - the TS context

4399:    Output Parameter:
4400: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4401:             manual pages for the individual convergence tests for complete lists

4403:    Level: beginner

4405:    Notes:
4406:    Can only be called after the call to TSSolve() is complete.

4408: .keywords: TS, nonlinear, set, convergence, test

4410: .seealso: TSSetConvergenceTest(), TSConvergedReason
4411: @*/
4412: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
4413: {
4417:   *reason = ts->reason;
4418:   return(0);
4419: }

4423: /*@
4424:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

4426:    Not Collective

4428:    Input Parameter:
4429: +  ts - the TS context
4430: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4431:             manual pages for the individual convergence tests for complete lists

4433:    Level: advanced

4435:    Notes:
4436:    Can only be called during TSSolve() is active.

4438: .keywords: TS, nonlinear, set, convergence, test

4440: .seealso: TSConvergedReason
4441: @*/
4442: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4443: {
4446:   ts->reason = reason;
4447:   return(0);
4448: }

4452: /*@
4453:    TSGetSolveTime - Gets the time after a call to TSSolve()

4455:    Not Collective

4457:    Input Parameter:
4458: .  ts - the TS context

4460:    Output Parameter:
4461: .  ftime - the final time. This time should correspond to the final time set with TSSetDuration()

4463:    Level: beginner

4465:    Notes:
4466:    Can only be called after the call to TSSolve() is complete.

4468: .keywords: TS, nonlinear, set, convergence, test

4470: .seealso: TSSetConvergenceTest(), TSConvergedReason
4471: @*/
4472: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4473: {
4477:   *ftime = ts->solvetime;
4478:   return(0);
4479: }

4483: /*@
4484:    TSGetTotalSteps - Gets the total number of steps done since the last call to TSSetUp() or TSCreate()

4486:    Not Collective

4488:    Input Parameter:
4489: .  ts - the TS context

4491:    Output Parameter:
4492: .  steps - the number of steps

4494:    Level: beginner

4496:    Notes:
4497:    Includes the number of steps for all calls to TSSolve() since TSSetUp() was called

4499: .keywords: TS, nonlinear, set, convergence, test

4501: .seealso: TSSetConvergenceTest(), TSConvergedReason
4502: @*/
4503: PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
4504: {
4508:   *steps = ts->total_steps;
4509:   return(0);
4510: }

4514: /*@
4515:    TSGetSNESIterations - Gets the total number of nonlinear iterations
4516:    used by the time integrator.

4518:    Not Collective

4520:    Input Parameter:
4521: .  ts - TS context

4523:    Output Parameter:
4524: .  nits - number of nonlinear iterations

4526:    Notes:
4527:    This counter is reset to zero for each successive call to TSSolve().

4529:    Level: intermediate

4531: .keywords: TS, get, number, nonlinear, iterations

4533: .seealso:  TSGetKSPIterations()
4534: @*/
4535: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
4536: {
4540:   *nits = ts->snes_its;
4541:   return(0);
4542: }

4546: /*@
4547:    TSGetKSPIterations - Gets the total number of linear iterations
4548:    used by the time integrator.

4550:    Not Collective

4552:    Input Parameter:
4553: .  ts - TS context

4555:    Output Parameter:
4556: .  lits - number of linear iterations

4558:    Notes:
4559:    This counter is reset to zero for each successive call to TSSolve().

4561:    Level: intermediate

4563: .keywords: TS, get, number, linear, iterations

4565: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
4566: @*/
4567: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
4568: {
4572:   *lits = ts->ksp_its;
4573:   return(0);
4574: }

4578: /*@
4579:    TSGetStepRejections - Gets the total number of rejected steps.

4581:    Not Collective

4583:    Input Parameter:
4584: .  ts - TS context

4586:    Output Parameter:
4587: .  rejects - number of steps rejected

4589:    Notes:
4590:    This counter is reset to zero for each successive call to TSSolve().

4592:    Level: intermediate

4594: .keywords: TS, get, number

4596: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
4597: @*/
4598: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4599: {
4603:   *rejects = ts->reject;
4604:   return(0);
4605: }

4609: /*@
4610:    TSGetSNESFailures - Gets the total number of failed SNES solves

4612:    Not Collective

4614:    Input Parameter:
4615: .  ts - TS context

4617:    Output Parameter:
4618: .  fails - number of failed nonlinear solves

4620:    Notes:
4621:    This counter is reset to zero for each successive call to TSSolve().

4623:    Level: intermediate

4625: .keywords: TS, get, number

4627: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
4628: @*/
4629: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4630: {
4634:   *fails = ts->num_snes_failures;
4635:   return(0);
4636: }

4640: /*@
4641:    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails

4643:    Not Collective

4645:    Input Parameter:
4646: +  ts - TS context
4647: -  rejects - maximum number of rejected steps, pass -1 for unlimited

4649:    Notes:
4650:    The counter is reset to zero for each step

4652:    Options Database Key:
4653:  .  -ts_max_reject - Maximum number of step rejections before a step fails

4655:    Level: intermediate

4657: .keywords: TS, set, maximum, number

4659: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4660: @*/
4661: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4662: {
4665:   ts->max_reject = rejects;
4666:   return(0);
4667: }

4671: /*@
4672:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

4674:    Not Collective

4676:    Input Parameter:
4677: +  ts - TS context
4678: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

4680:    Notes:
4681:    The counter is reset to zero for each successive call to TSSolve().

4683:    Options Database Key:
4684:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

4686:    Level: intermediate

4688: .keywords: TS, set, maximum, number

4690: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4691: @*/
4692: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4693: {
4696:   ts->max_snes_failures = fails;
4697:   return(0);
4698: }

4702: /*@
4703:    TSSetErrorIfStepFails - Error if no step succeeds

4705:    Not Collective

4707:    Input Parameter:
4708: +  ts - TS context
4709: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

4711:    Options Database Key:
4712:  .  -ts_error_if_step_fails - Error if no step succeeds

4714:    Level: intermediate

4716: .keywords: TS, set, error

4718: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4719: @*/
4720: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4721: {
4724:   ts->errorifstepfailed = err;
4725:   return(0);
4726: }

4730: /*@C
4731:    TSMonitorSolutionBinary - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file

4733:    Collective on TS

4735:    Input Parameters:
4736: +  ts - the TS context
4737: .  step - current time-step
4738: .  ptime - current time
4739: .  u - current state
4740: -  viewer - binary viewer

4742:    Level: intermediate

4744: .keywords: TS,  vector, monitor, view

4746: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4747: @*/
4748: PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
4749: {
4751:   PetscViewer    v = (PetscViewer)viewer;

4754:   VecView(u,v);
4755:   return(0);
4756: }

4760: /*@C
4761:    TSMonitorSolutionVTK - Monitors progress of the TS solvers by VecView() for the solution at each timestep.

4763:    Collective on TS

4765:    Input Parameters:
4766: +  ts - the TS context
4767: .  step - current time-step
4768: .  ptime - current time
4769: .  u - current state
4770: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

4772:    Level: intermediate

4774:    Notes:
4775:    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.
4776:    These are named according to the file name template.

4778:    This function is normally passed as an argument to TSMonitorSet() along with TSMonitorSolutionVTKDestroy().

4780: .keywords: TS,  vector, monitor, view

4782: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
4783: @*/
4784: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
4785: {
4787:   char           filename[PETSC_MAX_PATH_LEN];
4788:   PetscViewer    viewer;

4791:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
4792:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
4793:   VecView(u,viewer);
4794:   PetscViewerDestroy(&viewer);
4795:   return(0);
4796: }

4800: /*@C
4801:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

4803:    Collective on TS

4805:    Input Parameters:
4806: .  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

4808:    Level: intermediate

4810:    Note:
4811:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

4813: .keywords: TS,  vector, monitor, view

4815: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
4816: @*/
4817: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
4818: {

4822:   PetscFree(*(char**)filenametemplate);
4823:   return(0);
4824: }

4828: /*@
4829:    TSGetAdapt - Get the adaptive controller context for the current method

4831:    Collective on TS if controller has not been created yet

4833:    Input Arguments:
4834: .  ts - time stepping context

4836:    Output Arguments:
4837: .  adapt - adaptive controller

4839:    Level: intermediate

4841: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4842: @*/
4843: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4844: {

4850:   if (!ts->adapt) {
4851:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
4852:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
4853:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
4854:   }
4855:   *adapt = ts->adapt;
4856:   return(0);
4857: }

4861: /*@
4862:    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller

4864:    Logically Collective

4866:    Input Arguments:
4867: +  ts - time integration context
4868: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
4869: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4870: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
4871: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

4873:    Options Database keys:
4874: +  -ts_rtol <rtol> - relative tolerance for local truncation error
4875: -  -ts_atol <atol> Absolute tolerance for local truncation error

4877:    Notes:
4878:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
4879:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
4880:    computed only for the differential or the algebraic part then this can be done using the vector of
4881:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the 
4882:    differential part and infinity for the algebraic part, the LTE calculation will include only the
4883:    differential variables.

4885:    Level: beginner

4887: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
4888: @*/
4889: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
4890: {

4894:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4895:   if (vatol) {
4896:     PetscObjectReference((PetscObject)vatol);
4897:     VecDestroy(&ts->vatol);

4899:     ts->vatol = vatol;
4900:   }
4901:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
4902:   if (vrtol) {
4903:     PetscObjectReference((PetscObject)vrtol);
4904:     VecDestroy(&ts->vrtol);

4906:     ts->vrtol = vrtol;
4907:   }
4908:   return(0);
4909: }

4913: /*@
4914:    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller

4916:    Logically Collective

4918:    Input Arguments:
4919: .  ts - time integration context

4921:    Output Arguments:
4922: +  atol - scalar absolute tolerances, NULL to ignore
4923: .  vatol - vector of absolute tolerances, NULL to ignore
4924: .  rtol - scalar relative tolerances, NULL to ignore
4925: -  vrtol - vector of relative tolerances, NULL to ignore

4927:    Level: beginner

4929: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
4930: @*/
4931: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4932: {
4934:   if (atol)  *atol  = ts->atol;
4935:   if (vatol) *vatol = ts->vatol;
4936:   if (rtol)  *rtol  = ts->rtol;
4937:   if (vrtol) *vrtol = ts->vrtol;
4938:   return(0);
4939: }

4943: /*@
4944:    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors

4946:    Collective on TS

4948:    Input Arguments:
4949: +  ts - time stepping context
4950: .  U - state vector, usually ts->vec_sol
4951: -  Y - state vector to be compared to U

4953:    Output Arguments:
4954: .  norm - weighted norm, a value of 1.0 is considered small

4956:    Level: developer

4958: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
4959: @*/
4960: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm)
4961: {
4962:   PetscErrorCode    ierr;
4963:   PetscInt          i,n,N,rstart;
4964:   const PetscScalar *u,*y;
4965:   PetscReal         sum,gsum;
4966:   PetscReal         tol;

4976:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

4978:   VecGetSize(U,&N);
4979:   VecGetLocalSize(U,&n);
4980:   VecGetOwnershipRange(U,&rstart,NULL);
4981:   VecGetArrayRead(U,&u);
4982:   VecGetArrayRead(Y,&y);
4983:   sum  = 0.;
4984:   if (ts->vatol && ts->vrtol) {
4985:     const PetscScalar *atol,*rtol;
4986:     VecGetArrayRead(ts->vatol,&atol);
4987:     VecGetArrayRead(ts->vrtol,&rtol);
4988:     for (i=0; i<n; i++) {
4989:       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4990:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
4991:     }
4992:     VecRestoreArrayRead(ts->vatol,&atol);
4993:     VecRestoreArrayRead(ts->vrtol,&rtol);
4994:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
4995:     const PetscScalar *atol;
4996:     VecGetArrayRead(ts->vatol,&atol);
4997:     for (i=0; i<n; i++) {
4998:       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
4999:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5000:     }
5001:     VecRestoreArrayRead(ts->vatol,&atol);
5002:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5003:     const PetscScalar *rtol;
5004:     VecGetArrayRead(ts->vrtol,&rtol);
5005:     for (i=0; i<n; i++) {
5006:       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5007:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5008:     }
5009:     VecRestoreArrayRead(ts->vrtol,&rtol);
5010:   } else {                      /* scalar atol, scalar rtol */
5011:     for (i=0; i<n; i++) {
5012:       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5013:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
5014:     }
5015:   }
5016:   VecRestoreArrayRead(U,&u);
5017:   VecRestoreArrayRead(Y,&y);

5019:   MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
5020:   *norm = PetscSqrtReal(gsum / N);

5022:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5023:   return(0);
5024: }

5028: /*@
5029:    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors

5031:    Collective on TS

5033:    Input Arguments:
5034: +  ts - time stepping context
5035: .  U - state vector, usually ts->vec_sol
5036: -  Y - state vector to be compared to U

5038:    Output Arguments:
5039: .  norm - weighted norm, a value of 1.0 is considered small

5041:    Level: developer

5043: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
5044: @*/
5045: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm)
5046: {
5047:   PetscErrorCode    ierr;
5048:   PetscInt          i,n,N,rstart,k;
5049:   const PetscScalar *u,*y;
5050:   PetscReal         max,gmax;
5051:   PetscReal         tol;

5061:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");

5063:   VecGetSize(U,&N);
5064:   VecGetLocalSize(U,&n);
5065:   VecGetOwnershipRange(U,&rstart,NULL);
5066:   VecGetArrayRead(U,&u);
5067:   VecGetArrayRead(Y,&y);
5068:   if (ts->vatol && ts->vrtol) {
5069:     const PetscScalar *atol,*rtol;
5070:     VecGetArrayRead(ts->vatol,&atol);
5071:     VecGetArrayRead(ts->vrtol,&rtol);
5072:     k = 0;
5073:     tol = PetscRealPart(atol[k]) + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5074:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5075:     for (i=1; i<n; i++) {
5076:       tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5077:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5078:     }
5079:     VecRestoreArrayRead(ts->vatol,&atol);
5080:     VecRestoreArrayRead(ts->vrtol,&rtol);
5081:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
5082:     const PetscScalar *atol;
5083:     VecGetArrayRead(ts->vatol,&atol);
5084:     k = 0;
5085:     tol = PetscRealPart(atol[k]) + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5086:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5087:     for (i=1; i<n; i++) {
5088:       tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5089:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5090:     }
5091:     VecRestoreArrayRead(ts->vatol,&atol);
5092:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
5093:     const PetscScalar *rtol;
5094:     VecGetArrayRead(ts->vrtol,&rtol);
5095:     k = 0;
5096:     tol = ts->atol + PetscRealPart(rtol[k]) * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5097:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5098:     for (i=1; i<n; i++) {
5099:       tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5100:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5101:     }
5102:     VecRestoreArrayRead(ts->vrtol,&rtol);
5103:   } else {                      /* scalar atol, scalar rtol */
5104:     k = 0;
5105:     tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[k]),PetscAbsScalar(y[k]));
5106:     max = PetscAbsScalar(y[k] - u[k]) / tol;
5107:     for (i=1; i<n; i++) {
5108:       tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
5109:       max = PetscMax(max,PetscAbsScalar(y[i] - u[i]) / tol);
5110:     }
5111:   }
5112:   VecRestoreArrayRead(U,&u);
5113:   VecRestoreArrayRead(Y,&y);

5115:   MPI_Allreduce(&max,&gmax,1,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
5116:   *norm = gmax;

5118:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
5119:   return(0);
5120: }

5124: /*@
5125:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors

5127:    Collective on TS

5129:    Input Arguments:
5130: +  ts - time stepping context
5131: .  U - state vector, usually ts->vec_sol
5132: .  Y - state vector to be compared to U
5133: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

5135:    Output Arguments:
5136: .  norm - weighted norm, a value of 1.0 is considered small


5139:    Options Database Keys:
5140: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5142:    Level: developer

5144: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
5145: @*/
5146: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm)
5147: {

5151:   if (wnormtype == NORM_2) {
5152:     TSErrorWeightedNorm2(ts,U,Y,norm);
5153:   } else if(wnormtype == NORM_INFINITY) {
5154:     TSErrorWeightedNormInfinity(ts,U,Y,norm);
5155:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
5156:   return(0);
5157: }

5161: /*@
5162:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

5164:    Logically Collective on TS

5166:    Input Arguments:
5167: +  ts - time stepping context
5168: -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)

5170:    Note:
5171:    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()

5173:    Level: intermediate

5175: .seealso: TSGetCFLTime(), TSADAPTCFL
5176: @*/
5177: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
5178: {
5181:   ts->cfltime_local = cfltime;
5182:   ts->cfltime       = -1.;
5183:   return(0);
5184: }

5188: /*@
5189:    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler

5191:    Collective on TS

5193:    Input Arguments:
5194: .  ts - time stepping context

5196:    Output Arguments:
5197: .  cfltime - maximum stable time step for forward Euler

5199:    Level: advanced

5201: .seealso: TSSetCFLTimeLocal()
5202: @*/
5203: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
5204: {

5208:   if (ts->cfltime < 0) {
5209:     MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
5210:   }
5211:   *cfltime = ts->cfltime;
5212:   return(0);
5213: }

5217: /*@
5218:    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu

5220:    Input Parameters:
5221: .  ts   - the TS context.
5222: .  xl   - lower bound.
5223: .  xu   - upper bound.

5225:    Notes:
5226:    If this routine is not called then the lower and upper bounds are set to
5227:    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().

5229:    Level: advanced

5231: @*/
5232: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5233: {
5235:   SNES           snes;

5238:   TSGetSNES(ts,&snes);
5239:   SNESVISetVariableBounds(snes,xl,xu);
5240:   return(0);
5241: }

5243: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5244: #include <mex.h>

5246: typedef struct {char *funcname; mxArray *ctx;} TSMatlabContext;

5250: /*
5251:    TSComputeFunction_Matlab - Calls the function that has been set with
5252:                          TSSetFunctionMatlab().

5254:    Collective on TS

5256:    Input Parameters:
5257: +  snes - the TS context
5258: -  u - input vector

5260:    Output Parameter:
5261: .  y - function vector, as set by TSSetFunction()

5263:    Notes:
5264:    TSComputeFunction() is typically used within nonlinear solvers
5265:    implementations, so most users would not generally call this routine
5266:    themselves.

5268:    Level: developer

5270: .keywords: TS, nonlinear, compute, function

5272: .seealso: TSSetFunction(), TSGetFunction()
5273: */
5274: PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
5275: {
5276:   PetscErrorCode  ierr;
5277:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5278:   int             nlhs  = 1,nrhs = 7;
5279:   mxArray         *plhs[1],*prhs[7];
5280:   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;


5290:   PetscMemcpy(&ls,&snes,sizeof(snes));
5291:   PetscMemcpy(&lx,&u,sizeof(u));
5292:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
5293:   PetscMemcpy(&ly,&y,sizeof(u));

5295:   prhs[0] =  mxCreateDoubleScalar((double)ls);
5296:   prhs[1] =  mxCreateDoubleScalar(time);
5297:   prhs[2] =  mxCreateDoubleScalar((double)lx);
5298:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5299:   prhs[4] =  mxCreateDoubleScalar((double)ly);
5300:   prhs[5] =  mxCreateString(sctx->funcname);
5301:   prhs[6] =  sctx->ctx;
5302:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
5303:    mxGetScalar(plhs[0]);
5304:   mxDestroyArray(prhs[0]);
5305:   mxDestroyArray(prhs[1]);
5306:   mxDestroyArray(prhs[2]);
5307:   mxDestroyArray(prhs[3]);
5308:   mxDestroyArray(prhs[4]);
5309:   mxDestroyArray(prhs[5]);
5310:   mxDestroyArray(plhs[0]);
5311:   return(0);
5312: }


5317: /*
5318:    TSSetFunctionMatlab - Sets the function evaluation routine and function
5319:    vector for use by the TS routines in solving ODEs
5320:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

5322:    Logically Collective on TS

5324:    Input Parameters:
5325: +  ts - the TS context
5326: -  func - function evaluation routine

5328:    Calling sequence of func:
5329: $    func (TS ts,PetscReal time,Vec u,Vec udot,Vec f,void *ctx);

5331:    Level: beginner

5333: .keywords: TS, nonlinear, set, function

5335: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5336: */
5337: PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
5338: {
5339:   PetscErrorCode  ierr;
5340:   TSMatlabContext *sctx;

5343:   /* currently sctx is memory bleed */
5344:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
5345:   PetscStrallocpy(func,&sctx->funcname);
5346:   /*
5347:      This should work, but it doesn't
5348:   sctx->ctx = ctx;
5349:   mexMakeArrayPersistent(sctx->ctx);
5350:   */
5351:   sctx->ctx = mxDuplicateArray(ctx);

5353:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
5354:   return(0);
5355: }

5359: /*
5360:    TSComputeJacobian_Matlab - Calls the function that has been set with
5361:                          TSSetJacobianMatlab().

5363:    Collective on TS

5365:    Input Parameters:
5366: +  ts - the TS context
5367: .  u - input vector
5368: .  A, B - the matrices
5369: -  ctx - user context

5371:    Level: developer

5373: .keywords: TS, nonlinear, compute, function

5375: .seealso: TSSetFunction(), TSGetFunction()
5376: @*/
5377: PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat A,Mat B,void *ctx)
5378: {
5379:   PetscErrorCode  ierr;
5380:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5381:   int             nlhs  = 2,nrhs = 9;
5382:   mxArray         *plhs[2],*prhs[9];
5383:   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;


5389:   /* call Matlab function in ctx with arguments u and y */

5391:   PetscMemcpy(&ls,&ts,sizeof(ts));
5392:   PetscMemcpy(&lx,&u,sizeof(u));
5393:   PetscMemcpy(&lxdot,&udot,sizeof(u));
5394:   PetscMemcpy(&lA,A,sizeof(u));
5395:   PetscMemcpy(&lB,B,sizeof(u));

5397:   prhs[0] =  mxCreateDoubleScalar((double)ls);
5398:   prhs[1] =  mxCreateDoubleScalar((double)time);
5399:   prhs[2] =  mxCreateDoubleScalar((double)lx);
5400:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
5401:   prhs[4] =  mxCreateDoubleScalar((double)shift);
5402:   prhs[5] =  mxCreateDoubleScalar((double)lA);
5403:   prhs[6] =  mxCreateDoubleScalar((double)lB);
5404:   prhs[7] =  mxCreateString(sctx->funcname);
5405:   prhs[8] =  sctx->ctx;
5406:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
5407:    mxGetScalar(plhs[0]);
5408:   mxDestroyArray(prhs[0]);
5409:   mxDestroyArray(prhs[1]);
5410:   mxDestroyArray(prhs[2]);
5411:   mxDestroyArray(prhs[3]);
5412:   mxDestroyArray(prhs[4]);
5413:   mxDestroyArray(prhs[5]);
5414:   mxDestroyArray(prhs[6]);
5415:   mxDestroyArray(prhs[7]);
5416:   mxDestroyArray(plhs[0]);
5417:   mxDestroyArray(plhs[1]);
5418:   return(0);
5419: }


5424: /*
5425:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5426:    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

5428:    Logically Collective on TS

5430:    Input Parameters:
5431: +  ts - the TS context
5432: .  A,B - Jacobian matrices
5433: .  func - function evaluation routine
5434: -  ctx - user context

5436:    Calling sequence of func:
5437: $    flag = func (TS ts,PetscReal time,Vec u,Vec udot,Mat A,Mat B,void *ctx);


5440:    Level: developer

5442: .keywords: TS, nonlinear, set, function

5444: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5445: */
5446: PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
5447: {
5448:   PetscErrorCode  ierr;
5449:   TSMatlabContext *sctx;

5452:   /* currently sctx is memory bleed */
5453:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
5454:   PetscStrallocpy(func,&sctx->funcname);
5455:   /*
5456:      This should work, but it doesn't
5457:   sctx->ctx = ctx;
5458:   mexMakeArrayPersistent(sctx->ctx);
5459:   */
5460:   sctx->ctx = mxDuplicateArray(ctx);

5462:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
5463:   return(0);
5464: }

5468: /*
5469:    TSMonitor_Matlab - Calls the function that has been set with TSMonitorSetMatlab().

5471:    Collective on TS

5473: .seealso: TSSetFunction(), TSGetFunction()
5474: @*/
5475: PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
5476: {
5477:   PetscErrorCode  ierr;
5478:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
5479:   int             nlhs  = 1,nrhs = 6;
5480:   mxArray         *plhs[1],*prhs[6];
5481:   long long int   lx = 0,ls = 0;


5487:   PetscMemcpy(&ls,&ts,sizeof(ts));
5488:   PetscMemcpy(&lx,&u,sizeof(u));

5490:   prhs[0] =  mxCreateDoubleScalar((double)ls);
5491:   prhs[1] =  mxCreateDoubleScalar((double)it);
5492:   prhs[2] =  mxCreateDoubleScalar((double)time);
5493:   prhs[3] =  mxCreateDoubleScalar((double)lx);
5494:   prhs[4] =  mxCreateString(sctx->funcname);
5495:   prhs[5] =  sctx->ctx;
5496:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
5497:    mxGetScalar(plhs[0]);
5498:   mxDestroyArray(prhs[0]);
5499:   mxDestroyArray(prhs[1]);
5500:   mxDestroyArray(prhs[2]);
5501:   mxDestroyArray(prhs[3]);
5502:   mxDestroyArray(prhs[4]);
5503:   mxDestroyArray(plhs[0]);
5504:   return(0);
5505: }


5510: /*
5511:    TSMonitorSetMatlab - Sets the monitor function from Matlab

5513:    Level: developer

5515: .keywords: TS, nonlinear, set, function

5517: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5518: */
5519: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
5520: {
5521:   PetscErrorCode  ierr;
5522:   TSMatlabContext *sctx;

5525:   /* currently sctx is memory bleed */
5526:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
5527:   PetscStrallocpy(func,&sctx->funcname);
5528:   /*
5529:      This should work, but it doesn't
5530:   sctx->ctx = ctx;
5531:   mexMakeArrayPersistent(sctx->ctx);
5532:   */
5533:   sctx->ctx = mxDuplicateArray(ctx);

5535:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
5536:   return(0);
5537: }
5538: #endif

5542: /*@C
5543:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
5544:        in a time based line graph

5546:    Collective on TS

5548:    Input Parameters:
5549: +  ts - the TS context
5550: .  step - current time-step
5551: .  ptime - current time
5552: -  lg - a line graph object

5554:    Options Database:
5555: .   -ts_monitor_lg_solution_variables

5557:    Level: intermediate

5559:     Notes: each process in a parallel run displays its component solutions in a separate window

5561: .keywords: TS,  vector, monitor, view

5563: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5564: @*/
5565: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5566: {
5567:   PetscErrorCode    ierr;
5568:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5569:   const PetscScalar *yy;
5570:   PetscInt          dim;
5571:   Vec               v;

5574:   if (!step) {
5575:     PetscDrawAxis axis;
5576:     PetscDrawLGGetAxis(ctx->lg,&axis);
5577:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
5578:     if (ctx->names && !ctx->displaynames) {
5579:       char      **displaynames;
5580:       PetscBool flg;

5582:       VecGetLocalSize(u,&dim);
5583:       PetscMalloc((dim+1)*sizeof(char*),&displaynames);
5584:       PetscMemzero(displaynames,(dim+1)*sizeof(char*));
5585:       PetscOptionsGetStringArray(((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
5586:       if (flg) {
5587:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
5588:       }
5589:       PetscStrArrayDestroy(&displaynames);
5590:     }
5591:     if (ctx->displaynames) {
5592:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
5593:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
5594:     } else if (ctx->names) {
5595:       VecGetLocalSize(u,&dim);
5596:       PetscDrawLGSetDimension(ctx->lg,dim);
5597:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
5598:     }
5599:     PetscDrawLGReset(ctx->lg);
5600:   }
5601:   if (ctx->transform) {
5602:     (*ctx->transform)(ctx->transformctx,u,&v);
5603:   } else {
5604:     v = u;
5605:   }
5606:   VecGetArrayRead(v,&yy);
5607: #if defined(PETSC_USE_COMPLEX)
5608:   {
5609:     PetscReal *yreal;
5610:     PetscInt  i,n;
5611:     VecGetLocalSize(v,&n);
5612:     PetscMalloc1(n,&yreal);
5613:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5614:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
5615:     PetscFree(yreal);
5616:   }
5617: #else
5618:   if (ctx->displaynames) {
5619:     PetscInt i;
5620:     for (i=0; i<ctx->ndisplayvariables; i++) {
5621:       ctx->displayvalues[i] = yy[ctx->displayvariables[i]];
5622:     }
5623:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
5624:   } else {
5625:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
5626:   }
5627: #endif
5628:   VecRestoreArrayRead(v,&yy);
5629:   if (ctx->transform) {
5630:     VecDestroy(&v);
5631:   }
5632:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5633:     PetscDrawLGDraw(ctx->lg);
5634:   }
5635:   return(0);
5636: }


5641: /*@C
5642:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

5644:    Collective on TS

5646:    Input Parameters:
5647: +  ts - the TS context
5648: -  names - the names of the components, final string must be NULL

5650:    Level: intermediate

5652: .keywords: TS,  vector, monitor, view

5654: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
5655: @*/
5656: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
5657: {
5658:   PetscErrorCode    ierr;
5659:   PetscInt          i;

5662:   for (i=0; i<ts->numbermonitors; i++) {
5663:     if (ts->monitor[i] == TSMonitorLGSolution) {
5664:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
5665:       break;
5666:     }
5667:   }
5668:   return(0);
5669: }

5673: /*@C
5674:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

5676:    Collective on TS

5678:    Input Parameters:
5679: +  ts - the TS context
5680: -  names - the names of the components, final string must be NULL

5682:    Level: intermediate

5684: .keywords: TS,  vector, monitor, view

5686: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
5687: @*/
5688: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
5689: {
5690:   PetscErrorCode    ierr;

5693:   PetscStrArrayDestroy(&ctx->names);
5694:   PetscStrArrayallocpy(names,&ctx->names);
5695:   return(0);
5696: }

5700: /*@C
5701:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

5703:    Collective on TS

5705:    Input Parameter:
5706: .  ts - the TS context

5708:    Output Parameter:
5709: .  names - the names of the components, final string must be NULL

5711:    Level: intermediate

5713: .keywords: TS,  vector, monitor, view

5715: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
5716: @*/
5717: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
5718: {
5719:   PetscInt       i;

5722:   *names = NULL;
5723:   for (i=0; i<ts->numbermonitors; i++) {
5724:     if (ts->monitor[i] == TSMonitorLGSolution) {
5725:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
5726:       *names = (const char *const *)ctx->names;
5727:       break;
5728:     }
5729:   }
5730:   return(0);
5731: }

5735: /*@C
5736:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

5738:    Collective on TS

5740:    Input Parameters:
5741: +  ctx - the TSMonitorLG context
5742: .  displaynames - the names of the components, final string must be NULL

5744:    Level: intermediate

5746: .keywords: TS,  vector, monitor, view

5748: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
5749: @*/
5750: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
5751: {
5752:   PetscInt          j = 0,k;
5753:   PetscErrorCode    ierr;

5756:   if (!ctx->names) return(0);
5757:   PetscStrArrayDestroy(&ctx->displaynames);
5758:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
5759:   while (displaynames[j]) j++;
5760:   ctx->ndisplayvariables = j;
5761:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
5762:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
5763:   j = 0;
5764:   while (displaynames[j]) {
5765:     k = 0;
5766:     while (ctx->names[k]) {
5767:       PetscBool flg;
5768:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
5769:       if (flg) {
5770:         ctx->displayvariables[j] = k;
5771:         break;
5772:       }
5773:       k++;
5774:     }
5775:     j++;
5776:   }
5777:   return(0);
5778: }


5783: /*@C
5784:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

5786:    Collective on TS

5788:    Input Parameters:
5789: +  ts - the TS context
5790: .  displaynames - the names of the components, final string must be NULL

5792:    Level: intermediate

5794: .keywords: TS,  vector, monitor, view

5796: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
5797: @*/
5798: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
5799: {
5800:   PetscInt          i;
5801:   PetscErrorCode    ierr;

5804:   for (i=0; i<ts->numbermonitors; i++) {
5805:     if (ts->monitor[i] == TSMonitorLGSolution) {
5806:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
5807:       break;
5808:     }
5809:   }
5810:   return(0);
5811: }

5815: /*@C
5816:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

5818:    Collective on TS

5820:    Input Parameters:
5821: +  ts - the TS context
5822: .  transform - the transform function
5823: .  destroy - function to destroy the optional context
5824: -  ctx - optional context used by transform function

5826:    Level: intermediate

5828: .keywords: TS,  vector, monitor, view

5830: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
5831: @*/
5832: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
5833: {
5834:   PetscInt          i;
5835:   PetscErrorCode    ierr;

5838:   for (i=0; i<ts->numbermonitors; i++) {
5839:     if (ts->monitor[i] == TSMonitorLGSolution) {
5840:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
5841:     }
5842:   }
5843:   return(0);
5844: }

5848: /*@C
5849:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

5851:    Collective on TSLGCtx

5853:    Input Parameters:
5854: +  ts - the TS context
5855: .  transform - the transform function
5856: .  destroy - function to destroy the optional context
5857: -  ctx - optional context used by transform function

5859:    Level: intermediate

5861: .keywords: TS,  vector, monitor, view

5863: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
5864: @*/
5865: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
5866: {
5868:   ctx->transform    = transform;
5869:   ctx->transformdestroy = destroy;
5870:   ctx->transformctx = tctx;
5871:   return(0);
5872: }

5876: /*@C
5877:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
5878:        in a time based line graph

5880:    Collective on TS

5882:    Input Parameters:
5883: +  ts - the TS context
5884: .  step - current time-step
5885: .  ptime - current time
5886: -  lg - a line graph object

5888:    Level: intermediate

5890:    Notes:
5891:    Only for sequential solves.

5893:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

5895:    Options Database Keys:
5896: .  -ts_monitor_lg_error - create a graphical monitor of error history

5898: .keywords: TS,  vector, monitor, view

5900: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
5901: @*/
5902: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5903: {
5904:   PetscErrorCode    ierr;
5905:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5906:   const PetscScalar *yy;
5907:   Vec               y;
5908:   PetscInt          dim;

5911:   if (!step) {
5912:     PetscDrawAxis axis;
5913:     PetscDrawLGGetAxis(ctx->lg,&axis);
5914:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
5915:     VecGetLocalSize(u,&dim);
5916:     PetscDrawLGSetDimension(ctx->lg,dim);
5917:     PetscDrawLGReset(ctx->lg);
5918:   }
5919:   VecDuplicate(u,&y);
5920:   TSComputeSolutionFunction(ts,ptime,y);
5921:   VecAXPY(y,-1.0,u);
5922:   VecGetArrayRead(y,&yy);
5923: #if defined(PETSC_USE_COMPLEX)
5924:   {
5925:     PetscReal *yreal;
5926:     PetscInt  i,n;
5927:     VecGetLocalSize(y,&n);
5928:     PetscMalloc1(n,&yreal);
5929:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5930:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
5931:     PetscFree(yreal);
5932:   }
5933: #else
5934:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
5935: #endif
5936:   VecRestoreArrayRead(y,&yy);
5937:   VecDestroy(&y);
5938:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5939:     PetscDrawLGDraw(ctx->lg);
5940:   }
5941:   return(0);
5942: }

5946: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5947: {
5948:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5949:   PetscReal      x   = ptime,y;
5951:   PetscInt       its;

5954:   if (!n) {
5955:     PetscDrawAxis axis;

5957:     PetscDrawLGGetAxis(ctx->lg,&axis);
5958:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
5959:     PetscDrawLGReset(ctx->lg);

5961:     ctx->snes_its = 0;
5962:   }
5963:   TSGetSNESIterations(ts,&its);
5964:   y    = its - ctx->snes_its;
5965:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
5966:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5967:     PetscDrawLGDraw(ctx->lg);
5968:   }
5969:   ctx->snes_its = its;
5970:   return(0);
5971: }

5975: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5976: {
5977:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5978:   PetscReal      x   = ptime,y;
5980:   PetscInt       its;

5983:   if (!n) {
5984:     PetscDrawAxis axis;

5986:     PetscDrawLGGetAxis(ctx->lg,&axis);
5987:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
5988:     PetscDrawLGReset(ctx->lg);

5990:     ctx->ksp_its = 0;
5991:   }
5992:   TSGetKSPIterations(ts,&its);
5993:   y    = its - ctx->ksp_its;
5994:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
5995:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5996:     PetscDrawLGDraw(ctx->lg);
5997:   }
5998:   ctx->ksp_its = its;
5999:   return(0);
6000: }

6004: /*@
6005:    TSComputeLinearStability - computes the linear stability function at a point

6007:    Collective on TS and Vec

6009:    Input Parameters:
6010: +  ts - the TS context
6011: -  xr,xi - real and imaginary part of input arguments

6013:    Output Parameters:
6014: .  yr,yi - real and imaginary part of function value

6016:    Level: developer

6018: .keywords: TS, compute

6020: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6021: @*/
6022: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6023: {

6028:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6029:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6030:   return(0);
6031: }

6033: /* ------------------------------------------------------------------------*/
6036: /*@C
6037:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

6039:    Collective on TS

6041:    Input Parameters:
6042: .  ts  - the ODE solver object

6044:    Output Parameter:
6045: .  ctx - the context

6047:    Level: intermediate

6049: .keywords: TS, monitor, line graph, residual, seealso

6051: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError()

6053: @*/
6054: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6055: {

6059:   PetscNew(ctx);
6060:   return(0);
6061: }

6065: /*@C
6066:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

6068:    Collective on TS

6070:    Input Parameters:
6071: +  ts - the TS context
6072: .  step - current time-step
6073: .  ptime - current time
6074: -  ctx - the envelope context

6076:    Options Database:
6077: .  -ts_monitor_envelope

6079:    Level: intermediate

6081:    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

6083: .keywords: TS,  vector, monitor, view

6085: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds()
6086: @*/
6087: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6088: {
6089:   PetscErrorCode       ierr;
6090:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dummy;

6093:   if (!ctx->max) {
6094:     VecDuplicate(u,&ctx->max);
6095:     VecDuplicate(u,&ctx->min);
6096:     VecCopy(u,ctx->max);
6097:     VecCopy(u,ctx->min);
6098:   } else {
6099:     VecPointwiseMax(ctx->max,u,ctx->max);
6100:     VecPointwiseMin(ctx->min,u,ctx->min);
6101:   }
6102:   return(0);
6103: }


6108: /*@C
6109:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

6111:    Collective on TS

6113:    Input Parameter:
6114: .  ts - the TS context

6116:    Output Parameter:
6117: +  max - the maximum values
6118: -  min - the minimum values

6120:    Level: intermediate

6122: .keywords: TS,  vector, monitor, view

6124: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6125: @*/
6126: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
6127: {
6128:   PetscInt i;

6131:   if (max) *max = NULL;
6132:   if (min) *min = NULL;
6133:   for (i=0; i<ts->numbermonitors; i++) {
6134:     if (ts->monitor[i] == TSMonitorEnvelope) {
6135:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
6136:       if (max) *max = ctx->max;
6137:       if (min) *min = ctx->min;
6138:       break;
6139:     }
6140:   }
6141:   return(0);
6142: }

6146: /*@C
6147:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

6149:    Collective on TSMonitorEnvelopeCtx

6151:    Input Parameter:
6152: .  ctx - the monitor context

6154:    Level: intermediate

6156: .keywords: TS, monitor, line graph, destroy

6158: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
6159: @*/
6160: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
6161: {

6165:   VecDestroy(&(*ctx)->min);
6166:   VecDestroy(&(*ctx)->max);
6167:   PetscFree(*ctx);
6168:   return(0);
6169: }

6173: /*@
6174:    TSRollBack - Rolls back one time step

6176:    Collective on TS

6178:    Input Parameter:
6179: .  ts - the TS context obtained from TSCreate()

6181:    Level: advanced

6183: .keywords: TS, timestep, rollback

6185: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
6186: @*/
6187: PetscErrorCode  TSRollBack(TS ts)
6188: {


6194:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
6195:   (*ts->ops->rollback)(ts);
6196:   ts->time_step = ts->ptime - ts->ptime_prev;
6197:   ts->ptime = ts->ptime_prev;
6198:   ts->steprollback = PETSC_TRUE; /* Flag to indicate that the step is rollbacked */
6199:   return(0);
6200: }

6204: /*@
6205:    TSGetStages - Get the number of stages and stage values 

6207:    Input Parameter:
6208: .  ts - the TS context obtained from TSCreate()

6210:    Level: advanced

6212: .keywords: TS, getstages

6214: .seealso: TSCreate()
6215: @*/
6216: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns, Vec **Y)
6217: {


6224:   if (!ts->ops->getstages) *ns=0;
6225:   else {
6226:     (*ts->ops->getstages)(ts,ns,Y);
6227:   }
6228:   return(0);
6229: }

6233: /*@C
6234:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

6236:   Collective on SNES

6238:   Input Parameters:
6239: + ts - the TS context
6240: . t - current timestep
6241: . U - state vector
6242: . Udot - time derivative of state vector
6243: . shift - shift to apply, see note below
6244: - ctx - an optional user context

6246:   Output Parameters:
6247: + J - Jacobian matrix (not altered in this routine)
6248: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

6250:   Level: intermediate

6252:   Notes:
6253:   If F(t,U,Udot)=0 is the DAE, the required Jacobian is

6255:   dF/dU + shift*dF/dUdot

6257:   Most users should not need to explicitly call this routine, as it
6258:   is used internally within the nonlinear solvers.

6260:   This will first try to get the coloring from the DM.  If the DM type has no coloring
6261:   routine, then it will try to get the coloring from the matrix.  This requires that the
6262:   matrix have nonzero entries precomputed.

6264: .keywords: TS, finite differences, Jacobian, coloring, sparse
6265: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
6266: @*/
6267: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
6268: {
6269:   SNES           snes;
6270:   MatFDColoring  color;
6271:   PetscBool      hascolor, matcolor = PETSC_FALSE;

6275:   PetscOptionsGetBool(((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
6276:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
6277:   if (!color) {
6278:     DM         dm;
6279:     ISColoring iscoloring;

6281:     TSGetDM(ts, &dm);
6282:     DMHasColoring(dm, &hascolor);
6283:     if (hascolor && !matcolor) {
6284:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
6285:       MatFDColoringCreate(B, iscoloring, &color);
6286:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
6287:       MatFDColoringSetFromOptions(color);
6288:       MatFDColoringSetUp(B, iscoloring, color);
6289:       ISColoringDestroy(&iscoloring);
6290:     } else {
6291:       MatColoring mc;

6293:       MatColoringCreate(B, &mc);
6294:       MatColoringSetDistance(mc, 2);
6295:       MatColoringSetType(mc, MATCOLORINGSL);
6296:       MatColoringSetFromOptions(mc);
6297:       MatColoringApply(mc, &iscoloring);
6298:       MatColoringDestroy(&mc);
6299:       MatFDColoringCreate(B, iscoloring, &color);
6300:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
6301:       MatFDColoringSetFromOptions(color);
6302:       MatFDColoringSetUp(B, iscoloring, color);
6303:       ISColoringDestroy(&iscoloring);
6304:     }
6305:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
6306:     PetscObjectDereference((PetscObject) color);
6307:   }
6308:   TSGetSNES(ts, &snes);
6309:   MatFDColoringApply(B, color, U, snes);
6310:   if (J != B) {
6311:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
6312:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
6313:   }
6314:   return(0);
6315: }

6317: #undef  __FUNCT__
6319: /*@C
6320:   TSClone - This function clones a time step object. 

6322:   Collective on MPI_Comm

6324:   Input Parameter:
6325: . tsin    - The input TS

6327:   Output Parameter:
6328: . tsout   - The output TS (cloned)

6330:   Notes:
6331:   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly. 

6333:   When using TSDestroy() on a clone the user has to first reset the correct TS reference in the embedded SNES object: e.g.: by running SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); TSSetSNES(ts,snes_dup);

6335:   Level: developer

6337: .keywords: TS, clone
6338: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
6339: @*/
6340: PetscErrorCode  TSClone(TS tsin, TS *tsout)
6341: {
6342:   TS             t;
6344:   SNES           snes_start;
6345:   DM             dm;
6346:   TSType         type;

6350:   *tsout = NULL;

6352:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

6354:   /* General TS description */
6355:   t->numbermonitors    = 0;
6356:   t->setupcalled       = 0;
6357:   t->ksp_its           = 0;
6358:   t->snes_its          = 0;
6359:   t->nwork             = 0;
6360:   t->rhsjacobian.time  = -1e20;
6361:   t->rhsjacobian.scale = 1.;
6362:   t->ijacobian.shift   = 1.;

6364:   TSGetSNES(tsin,&snes_start);
6365:   TSSetSNES(t,snes_start);

6367:   TSGetDM(tsin,&dm);
6368:   TSSetDM(t,dm);

6370:   t->adapt=tsin->adapt;
6371:   PetscObjectReference((PetscObject)t->adapt);

6373:   t->problem_type      = tsin->problem_type;
6374:   t->ptime             = tsin->ptime;
6375:   t->time_step         = tsin->time_step;
6376:   t->time_step_orig    = tsin->time_step_orig;
6377:   t->max_time          = tsin->max_time;
6378:   t->steps             = tsin->steps;
6379:   t->max_steps         = tsin->max_steps;
6380:   t->equation_type     = tsin->equation_type;
6381:   t->atol              = tsin->atol;
6382:   t->rtol              = tsin->rtol;
6383:   t->max_snes_failures = tsin->max_snes_failures;
6384:   t->max_reject        = tsin->max_reject;
6385:   t->errorifstepfailed = tsin->errorifstepfailed;

6387:   TSGetType(tsin,&type);
6388:   TSSetType(t,type);

6390:   t->vec_sol           = NULL;

6392:   t->cfltime          = tsin->cfltime;
6393:   t->cfltime_local    = tsin->cfltime_local;
6394:   t->exact_final_time = tsin->exact_final_time;

6396:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

6398:   *tsout = t;
6399:   return(0);
6400: }