Actual source code: ts.c

petsc-3.6.1 2015-08-06
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:    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1239:    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

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

1248:    Level: beginner

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

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

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


1268:   TSGetDM(ts,&dm);
1269:   DMTSSetIJacobian(dm,f,ctx);

1271:   TSGetSNES(ts,&snes);
1272:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
1273:   return(0);
1274: }

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

1284:    Logically Collective

1286:    Input Arguments:
1287: +  ts - TS context obtained from TSCreate()
1288: -  reuse - PETSC_TRUE if the RHS Jacobian

1290:    Level: intermediate

1292: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
1293: @*/
1294: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1295: {
1297:   ts->rhsjacobian.reuse = reuse;
1298:   return(0);
1299: }

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

1306:   Collective on PetscViewer

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

1313:    Level: intermediate

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

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

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

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

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

1361: #include <petscdraw.h>
1362: #if defined(PETSC_HAVE_SAWS)
1363: #include <petscviewersaws.h>
1364: #endif
1367: /*@C
1368:     TSView - Prints the TS data structure.

1370:     Collective on TS

1372:     Input Parameters:
1373: +   ts - the TS context obtained from TSCreate()
1374: -   viewer - visualization context

1376:     Options Database Key:
1377: .   -ts_view - calls TSView() at end of TSStep()

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

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

1390:     Level: beginner

1392: .keywords: TS, timestep, view

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

1408:   if (!viewer) {
1409:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
1410:   }

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

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

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

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

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

1499:   PetscViewerASCIIPushTab(viewer);
1500:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
1501:   PetscViewerASCIIPopTab(viewer);
1502:   return(0);
1503: }


1508: /*@
1509:    TSSetApplicationContext - Sets an optional user-defined context for
1510:    the timesteppers.

1512:    Logically Collective on TS

1514:    Input Parameters:
1515: +  ts - the TS context obtained from TSCreate()
1516: -  usrP - optional user context

1518:    Level: intermediate

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

1522: .seealso: TSGetApplicationContext()
1523: @*/
1524: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
1525: {
1528:   ts->user = usrP;
1529:   return(0);
1530: }

1534: /*@
1535:     TSGetApplicationContext - Gets the user-defined context for the
1536:     timestepper.

1538:     Not Collective

1540:     Input Parameter:
1541: .   ts - the TS context obtained from TSCreate()

1543:     Output Parameter:
1544: .   usrP - user context

1546:     Level: intermediate

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

1550: .seealso: TSSetApplicationContext()
1551: @*/
1552: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
1553: {
1556:   *(void**)usrP = ts->user;
1557:   return(0);
1558: }

1562: /*@
1563:    TSGetTimeStepNumber - Gets the number of time steps completed.

1565:    Not Collective

1567:    Input Parameter:
1568: .  ts - the TS context obtained from TSCreate()

1570:    Output Parameter:
1571: .  iter - number of steps completed so far

1573:    Level: intermediate

1575: .keywords: TS, timestep, get, iteration, number
1576: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
1577: @*/
1578: PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
1579: {
1583:   *iter = ts->steps;
1584:   return(0);
1585: }

1589: /*@
1590:    TSSetInitialTimeStep - Sets the initial timestep to be used,
1591:    as well as the initial time.

1593:    Logically Collective on TS

1595:    Input Parameters:
1596: +  ts - the TS context obtained from TSCreate()
1597: .  initial_time - the initial time
1598: -  time_step - the size of the timestep

1600:    Level: intermediate

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

1604: .keywords: TS, set, initial, timestep
1605: @*/
1606: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
1607: {

1612:   TSSetTimeStep(ts,time_step);
1613:   TSSetTime(ts,initial_time);
1614:   return(0);
1615: }

1619: /*@
1620:    TSSetTimeStep - Allows one to reset the timestep at any time,
1621:    useful for simple pseudo-timestepping codes.

1623:    Logically Collective on TS

1625:    Input Parameters:
1626: +  ts - the TS context obtained from TSCreate()
1627: -  time_step - the size of the timestep

1629:    Level: intermediate

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

1633: .keywords: TS, set, timestep
1634: @*/
1635: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
1636: {
1640:   ts->time_step      = time_step;
1641:   ts->time_step_orig = time_step;
1642:   return(0);
1643: }

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

1652:   Logically Collective on TS

1654:    Input Parameter:
1655: +   ts - the time-step context
1656: -   eftopt - exact final time option

1658:    Level: beginner

1660: .seealso: TSExactFinalTimeOption
1661: @*/
1662: PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
1663: {
1667:   ts->exact_final_time = eftopt;
1668:   return(0);
1669: }

1673: /*@
1674:    TSGetTimeStep - Gets the current timestep size.

1676:    Not Collective

1678:    Input Parameter:
1679: .  ts - the TS context obtained from TSCreate()

1681:    Output Parameter:
1682: .  dt - the current timestep size

1684:    Level: intermediate

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

1688: .keywords: TS, get, timestep
1689: @*/
1690: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
1691: {
1695:   *dt = ts->time_step;
1696:   return(0);
1697: }

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

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

1709:    Input Parameter:
1710: .  ts - the TS context obtained from TSCreate()

1712:    Output Parameter:
1713: .  v - the vector containing the solution

1715:    Level: intermediate

1717: .seealso: TSGetTimeStep()

1719: .keywords: TS, timestep, get, solution
1720: @*/
1721: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
1722: {
1726:   *v = ts->vec_sol;
1727:   return(0);
1728: }

1732: /*@
1733:    TSGetCostGradients - Returns the gradients from the TSAdjointSolve()

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

1737:    Input Parameter:
1738: .  ts - the TS context obtained from TSCreate()

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

1744:    Level: intermediate

1746: .seealso: TSGetTimeStep()

1748: .keywords: TS, timestep, get, sensitivity
1749: @*/
1750: PetscErrorCode  TSGetCostGradients(TS ts,PetscInt *numcost,Vec **lambda,Vec **mu)
1751: {
1754:   if (numcost) *numcost = ts->numcost;
1755:   if (lambda)  *lambda  = ts->vecs_sensi;
1756:   if (mu)      *mu      = ts->vecs_sensip;
1757:   return(0);
1758: }

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

1766:   Not collective

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

1777:    Level: beginner

1779: .keywords: TS, problem type
1780: .seealso: TSSetUp(), TSProblemType, TS
1781: @*/
1782: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
1783: {

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

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

1802:   Not collective

1804:   Input Parameter:
1805: . ts   - The TS

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

1815:    Level: beginner

1817: .keywords: TS, problem type
1818: .seealso: TSSetUp(), TSProblemType, TS
1819: @*/
1820: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
1821: {
1825:   *type = ts->problem_type;
1826:   return(0);
1827: }

1831: /*@
1832:    TSSetUp - Sets up the internal data structures for the later use
1833:    of a timestepper.

1835:    Collective on TS

1837:    Input Parameter:
1838: .  ts - the TS context obtained from TSCreate()

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

1847:    Level: advanced

1849: .keywords: TS, timestep, setup

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

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

1866:   ts->total_steps = 0;
1867:   if (!((PetscObject)ts)->type_name) {
1868:     TSSetType(ts,TSEULER);
1869:   }

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


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

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

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

1921: /*@
1922:    TSAdjointSetUp - Sets up the internal data structures for the later use
1923:    of an adjoint solver

1925:    Collective on TS

1927:    Input Parameter:
1928: .  ts - the TS context obtained from TSCreate()

1930:    Level: advanced

1932: .keywords: TS, timestep, setup

1934: .seealso: TSCreate(), TSAdjointStep(), TSSetCostGradients()
1935: @*/
1936: PetscErrorCode  TSAdjointSetUp(TS ts)
1937: {

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

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

1952:   if (ts->ops->adjointsetup) {
1953:     (*ts->ops->adjointsetup)(ts);
1954:   }
1955:   ts->adjointsetupcalled = PETSC_TRUE;
1956:   return(0);
1957: }

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

1964:    Collective on TS

1966:    Input Parameter:
1967: .  ts - the TS context obtained from TSCreate()

1969:    Level: beginner

1971: .keywords: TS, timestep, reset

1973: .seealso: TSCreate(), TSSetup(), TSDestroy()
1974: @*/
1975: PetscErrorCode  TSReset(TS ts)
1976: {


1982:   if (ts->ops->reset) {
1983:     (*ts->ops->reset)(ts);
1984:   }
1985:   if (ts->snes) {SNESReset(ts->snes);}
1986:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

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

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

2013: /*@
2014:    TSDestroy - Destroys the timestepper context that was created
2015:    with TSCreate().

2017:    Collective on TS

2019:    Input Parameter:
2020: .  ts - the TS context obtained from TSCreate()

2022:    Level: beginner

2024: .keywords: TS, timestepper, destroy

2026: .seealso: TSCreate(), TSSetUp(), TSSolve()
2027: @*/
2028: PetscErrorCode  TSDestroy(TS *ts)
2029: {

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

2037:   TSReset((*ts));

2039:   /* if memory was published with SAWs then destroy it */
2040:   PetscObjectSAWsViewOff((PetscObject)*ts);
2041:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

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

2053:   PetscHeaderDestroy(ts);
2054:   return(0);
2055: }

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

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

2065:    Input Parameter:
2066: .  ts - the TS context obtained from TSCreate()

2068:    Output Parameter:
2069: .  snes - the nonlinear solver context

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

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

2079:    Level: beginner

2081: .keywords: timestep, get, SNES
2082: @*/
2083: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2084: {

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

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

2109:    Collective

2111:    Input Parameter:
2112: +  ts - the TS context obtained from TSCreate()
2113: -  snes - the nonlinear solver context

2115:    Notes:
2116:    Most users should have the TS created by calling TSGetSNES()

2118:    Level: developer

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

2130:   PetscObjectReference((PetscObject)snes);
2131:   SNESDestroy(&ts->snes);

2133:   ts->snes = snes;

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

2145: /*@
2146:    TSGetKSP - Returns the KSP (linear solver) associated with
2147:    a TS (timestepper) context.

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

2151:    Input Parameter:
2152: .  ts - the TS context obtained from TSCreate()

2154:    Output Parameter:
2155: .  ksp - the nonlinear solver context

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

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

2165:    Level: beginner

2167: .keywords: timestep, get, KSP
2168: @*/
2169: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2170: {
2172:   SNES           snes;

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

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

2188: /*@
2189:    TSGetDuration - Gets the maximum number of timesteps to use and
2190:    maximum time for iteration.

2192:    Not Collective

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

2199:    Level: intermediate

2201: .keywords: TS, timestep, get, maximum, iterations, time
2202: @*/
2203: PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2204: {
2207:   if (maxsteps) {
2209:     *maxsteps = ts->max_steps;
2210:   }
2211:   if (maxtime) {
2213:     *maxtime = ts->max_time;
2214:   }
2215:   return(0);
2216: }

2220: /*@
2221:    TSSetDuration - Sets the maximum number of timesteps to use and
2222:    maximum time for iteration.

2224:    Logically Collective on TS

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

2231:    Options Database Keys:
2232: .  -ts_max_steps <maxsteps> - Sets maxsteps
2233: .  -ts_final_time <maxtime> - Sets maxtime

2235:    Notes:
2236:    The default maximum number of iterations is 5000. Default time is 5.0

2238:    Level: intermediate

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

2242: .seealso: TSSetExactFinalTime()
2243: @*/
2244: PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2245: {
2250:   if (maxsteps >= 0) ts->max_steps = maxsteps;
2251:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2252:   return(0);
2253: }

2257: /*@
2258:    TSSetSolution - Sets the initial solution vector
2259:    for use by the TS routines.

2261:    Logically Collective on TS and Vec

2263:    Input Parameters:
2264: +  ts - the TS context obtained from TSCreate()
2265: -  u - the solution vector

2267:    Level: beginner

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

2279:   PetscObjectReference((PetscObject)u);
2280:   VecDestroy(&ts->vec_sol);

2282:   ts->vec_sol = u;

2284:   TSGetDM(ts,&dm);
2285:   DMShellSetGlobalVector(dm,u);
2286:   return(0);
2287: }

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

2294:    Logically Collective on TS

2296:    Input Parameters:
2297: +  ts - the TS context obtained from TSCreate()
2298: .  steps - number of steps to use

2300:    Level: intermediate

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

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

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

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

2326:    Logically Collective on TS and Vec

2328:    Input Parameters:
2329: +  ts - the TS context obtained from TSCreate()
2330: .  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
2331: -  mu - gradients with respect to the parameters, the number of entries in these vectors is the same as the number of parameters

2333:    Level: beginner

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

2337: .keywords: TS, timestep, set, sensitivity, initial conditions
2338: @*/
2339: PetscErrorCode  TSSetCostGradients(TS ts,PetscInt numcost,Vec *lambda,Vec *mu)
2340: {
2344:   ts->vecs_sensi  = lambda;
2345:   ts->vecs_sensip = mu;
2346:   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");
2347:   ts->numcost  = numcost;
2348:   return(0);
2349: }

2353: /*@C
2354:   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.

2356:   Logically Collective on TS

2358:   Input Parameters:
2359: + ts   - The TS context obtained from TSCreate()
2360: - func - The function

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

2369:   Level: intermediate

2371:   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

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


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

2396: /*@C
2397:   TSAdjointComputeRHSJacobian - Runs the user-defined Jacobian function.

2399:   Collective on TS

2401:   Input Parameters:
2402: . ts   - The TS context obtained from TSCreate()

2404:   Level: developer

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


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

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

2429:     Logically Collective on TS

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

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

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

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

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

2453:     Level: intermediate

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

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

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

2469:   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()");
2470:   if (!ts->numcost) ts->numcost=numcost;

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

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

2487:    Not Collective

2489:    Input Parameter:
2490: .  ts - the TS context obtained from TSCreate()

2492:    Output Parameter:
2493: .  v - the vector containing the integrals for each cost function

2495:    Level: intermediate

2497: .seealso: TSSetCostIntegrand()

2499: .keywords: TS, sensitivity analysis
2500: @*/
2501: PetscErrorCode  TSGetCostIntegral(TS ts,Vec *v)
2502: {
2506:   *v = ts->vec_costintegral;
2507:   return(0);
2508: }

2512: /*@
2513:    TSAdjointComputeCostIntegrand - Evaluates the integral function in the cost functions.

2515:    Input Parameters:
2516: +  ts - the TS context
2517: .  t - current time
2518: -  y - state vector, i.e. current solution

2520:    Output Parameter:
2521: .  q - vector of size numcost to hold the outputs

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

2527:    Level: developer

2529: .keywords: TS, compute

2531: .seealso: TSSetCostIntegrand()
2532: @*/
2533: PetscErrorCode TSAdjointComputeCostIntegrand(TS ts,PetscReal t,Vec y,Vec q)
2534: {


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

2551:   PetscLogEventEnd(TS_FunctionEval,ts,y,q,0);
2552:   return(0);
2553: }

2557: /*@
2558:   TSAdjointComputeDRDYFunction - Runs the user-defined DRDY function.

2560:   Collective on TS

2562:   Input Parameters:
2563: . ts   - The TS context obtained from TSCreate()

2565:   Notes:
2566:   TSAdjointComputeDRDYFunction() is typically used for sensitivity implementation,
2567:   so most users would not generally call this routine themselves.

2569:   Level: developer

2571: .keywords: TS, sensitivity
2572: .seealso: TSAdjointComputeDRDYFunction()
2573: @*/
2574: PetscErrorCode  TSAdjointComputeDRDYFunction(TS ts,PetscReal t,Vec y,Vec *drdy)
2575: {


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

2590: /*@
2591:   TSAdjointComputeDRDPFunction - Runs the user-defined DRDP function.

2593:   Collective on TS

2595:   Input Parameters:
2596: . ts   - The TS context obtained from TSCreate()

2598:   Notes:
2599:   TSDRDPFunction() is typically used for sensitivity implementation,
2600:   so most users would not generally call this routine themselves.

2602:   Level: developer

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


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

2623: /*@C
2624:   TSSetPreStep - Sets the general-purpose function
2625:   called once at the beginning of each time step.

2627:   Logically Collective on TS

2629:   Input Parameters:
2630: + ts   - The TS context obtained from TSCreate()
2631: - func - The function

2633:   Calling sequence of func:
2634: . func (TS ts);

2636:   Level: intermediate

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

2643: .keywords: TS, timestep
2644: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep()
2645: @*/
2646: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
2647: {
2650:   ts->prestep = func;
2651:   return(0);
2652: }

2656: /*@
2657:   TSPreStep - Runs the user-defined pre-step function.

2659:   Collective on TS

2661:   Input Parameters:
2662: . ts   - The TS context obtained from TSCreate()

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

2668:   Level: developer

2670: .keywords: TS, timestep
2671: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
2672: @*/
2673: PetscErrorCode  TSPreStep(TS ts)
2674: {

2679:   if (ts->prestep) {
2680:     PetscStackCallStandard((*ts->prestep),(ts));
2681:   }
2682:   return(0);
2683: }

2687: /*@C
2688:   TSSetPreStage - Sets the general-purpose function
2689:   called once at the beginning of each stage.

2691:   Logically Collective on TS

2693:   Input Parameters:
2694: + ts   - The TS context obtained from TSCreate()
2695: - func - The function

2697:   Calling sequence of func:
2698: . PetscErrorCode func(TS ts, PetscReal stagetime);

2700:   Level: intermediate

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

2707: .keywords: TS, timestep
2708: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2709: @*/
2710: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
2711: {
2714:   ts->prestage = func;
2715:   return(0);
2716: }

2720: /*@C
2721:   TSSetPostStage - Sets the general-purpose function
2722:   called once at the end of each stage.

2724:   Logically Collective on TS

2726:   Input Parameters:
2727: + ts   - The TS context obtained from TSCreate()
2728: - func - The function

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

2733:   Level: intermediate

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

2740: .keywords: TS, timestep
2741: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
2742: @*/
2743: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
2744: {
2747:   ts->poststage = func;
2748:   return(0);
2749: }

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

2756:   Collective on TS

2758:   Input Parameters:
2759: . ts          - The TS context obtained from TSCreate()
2760:   stagetime   - The absolute time of the current stage

2762:   Notes:
2763:   TSPreStage() is typically used within time stepping implementations,
2764:   most users would not generally call this routine themselves.

2766:   Level: developer

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

2777:   if (ts->prestage) {
2778:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
2779:   }
2780:   return(0);
2781: }

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

2788:   Collective on TS

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

2797:   Notes:
2798:   TSPostStage() is typically used within time stepping implementations,
2799:   most users would not generally call this routine themselves.

2801:   Level: developer

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

2812:   if (ts->poststage) {
2813:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
2814:   }
2815:   return(0);
2816: }

2820: /*@C
2821:   TSSetPostStep - Sets the general-purpose function
2822:   called once at the end of each time step.

2824:   Logically Collective on TS

2826:   Input Parameters:
2827: + ts   - The TS context obtained from TSCreate()
2828: - func - The function

2830:   Calling sequence of func:
2831: $ func (TS ts);

2833:   Level: intermediate

2835: .keywords: TS, timestep
2836: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
2837: @*/
2838: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
2839: {
2842:   ts->poststep = func;
2843:   return(0);
2844: }

2848: /*@
2849:   TSPostStep - Runs the user-defined post-step function.

2851:   Collective on TS

2853:   Input Parameters:
2854: . ts   - The TS context obtained from TSCreate()

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

2860:   Level: developer

2862: .keywords: TS, timestep
2863: @*/
2864: PetscErrorCode  TSPostStep(TS ts)
2865: {

2870:   if (ts->poststep) {
2871:     PetscStackCallStandard((*ts->poststep),(ts));
2872:   }
2873:   return(0);
2874: }

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

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

2884:    Logically Collective on TS

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

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

2897: +    ts - the TS context
2898: .    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
2899:                                been interpolated to)
2900: .    time - current time
2901: .    u - current iterate
2902: -    mctx - [optional] monitoring context

2904:    Notes:
2905:    This routine adds an additional monitor to the list of monitors that
2906:    already has been loaded.

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

2910:    Level: intermediate

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

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

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

2932:    Logically Collective on TS

2934:    Input Parameters:
2935: .  ts - the TS context obtained from TSCreate()

2937:    Notes:
2938:    There is no way to remove a single, specific monitor.

2940:    Level: intermediate

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

2944: .seealso: TSMonitorDefault(), TSMonitorSet()
2945: @*/
2946: PetscErrorCode  TSMonitorCancel(TS ts)
2947: {
2949:   PetscInt       i;

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

2964: /*@
2965:    TSMonitorDefault - Sets the Default monitor

2967:    Level: intermediate

2969: .keywords: TS, set, monitor

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

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

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

2990:    Logically Collective on TS

2992:    Input Argument:
2993: .  ts - time stepping context

2995:    Output Argument:
2996: .  flg - PETSC_TRUE or PETSC_FALSE

2998:    Level: intermediate

3000: .keywords: TS, set

3002: .seealso: TSInterpolate(), TSSetPostStep()
3003: @*/
3004: PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
3005: {
3008:   ts->retain_stages = flg;
3009:   return(0);
3010: }

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

3017:    Collective on TS

3019:    Input Argument:
3020: +  ts - time stepping context
3021: -  t - time to interpolate to

3023:    Output Argument:
3024: .  U - state at given time

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

3029:    Level: intermediate

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

3034: .keywords: TS, set

3036: .seealso: TSSetRetainStages(), TSSetPostStep()
3037: @*/
3038: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3039: {

3045:   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);
3046:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
3047:   (*ts->ops->interpolate)(ts,t,U);
3048:   return(0);
3049: }

3053: /*@
3054:    TSStep - Steps one time step

3056:    Collective on TS

3058:    Input Parameter:
3059: .  ts - the TS context obtained from TSCreate()

3061:    Level: developer

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

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

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

3072: .keywords: TS, timestep, solve

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

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

3092:   TSGetDM(ts, &dm);
3093:   TSSetUp(ts);

3095:   ts->reason = TS_CONVERGED_ITERATING;
3096:   ts->ptime_prev = ts->ptime;
3097:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

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

3104:   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3105:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

3107:   if (ts->reason < 0) {
3108:     if (ts->errorifstepfailed) {
3109:       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]);
3110:       else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3111:     }
3112:   } else if (!ts->reason) {
3113:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
3114:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3115:   }
3116:   ts->total_steps++;
3117:   ts->steprollback = PETSC_FALSE;
3118:   return(0);
3119: }

3123: /*@
3124:    TSAdjointStep - Steps one time step backward in the adjoint run

3126:    Collective on TS

3128:    Input Parameter:
3129: .  ts - the TS context obtained from TSCreate()

3131:    Level: intermediate

3133: .keywords: TS, adjoint, step

3135: .seealso: TSAdjointSetUp(), TSAdjointSolve()
3136: @*/
3137: PetscErrorCode  TSAdjointStep(TS ts)
3138: {
3139:   DM               dm;
3140:   PetscErrorCode   ierr;

3144:   TSGetDM(ts, &dm);
3145:   TSAdjointSetUp(ts);

3147:   ts->reason = TS_CONVERGED_ITERATING;
3148:   ts->ptime_prev = ts->ptime;
3149:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);
3150:   VecViewFromOptions(ts->vec_sol,(PetscObject)ts, "-ts_view_solution");

3152:   PetscLogEventBegin(TS_Step,ts,0,0,0);
3153:   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);
3154:   (*ts->ops->adjointstep)(ts);
3155:   PetscLogEventEnd(TS_Step,ts,0,0,0);

3157:   ts->time_step_prev = ts->ptime - ts->ptime_prev;
3158:   DMSetOutputSequenceNumber(dm, ts->steps, ts->ptime);

3160:   if (ts->reason < 0) {
3161:     if (ts->errorifstepfailed) {
3162:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
3163:         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]);
3164:       } else if (ts->reason == TS_DIVERGED_STEP_REJECTED) {
3165:         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]);
3166:       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
3167:     }
3168:   } else if (!ts->reason) {
3169:     if (ts->steps >= ts->adjoint_max_steps)     ts->reason = TS_CONVERGED_ITS;
3170:     else if (ts->ptime >= ts->max_time)         ts->reason = TS_CONVERGED_TIME;
3171:   }
3172:   ts->total_steps--;
3173:   return(0);
3174: }

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

3181:    Collective on TS

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

3188:    Output Arguments:
3189: .  U - state at the end of the current step

3191:    Level: advanced

3193:    Notes:
3194:    This function cannot be called until all stages have been evaluated.
3195:    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.

3197: .seealso: TSStep(), TSAdapt
3198: @*/
3199: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
3200: {

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


3215: /*@
3216:    TSSolve - Steps the requested number of timesteps.

3218:    Collective on TS

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

3224:    Level: beginner

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

3231: .keywords: TS, timestep, solve

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

3243:   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 */
3245:     if (!ts->vec_sol || u == ts->vec_sol) {
3246:       VecDuplicate(u,&solution);
3247:       TSSetSolution(ts,solution);
3248:       VecDestroy(&solution); /* grant ownership */
3249:     }
3250:     VecCopy(u,ts->vec_sol);
3251:   } else if (u) {
3252:     TSSetSolution(ts,u);
3253:   }
3254:   TSSetUp(ts);
3255:   /* reset time step and iteration counters */
3256:   ts->steps             = 0;
3257:   ts->ksp_its           = 0;
3258:   ts->snes_its          = 0;
3259:   ts->num_snes_failures = 0;
3260:   ts->reject            = 0;
3261:   ts->reason            = TS_CONVERGED_ITERATING;

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

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

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

3318: /*@
3319:    TSAdjointSolve - Solves the discrete ajoint problem for an ODE/DAE

3321:    Collective on TS

3323:    Input Parameter:
3324: .  ts - the TS context obtained from TSCreate()

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

3329:    Level: intermediate

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

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

3336: .keywords: TS, timestep, solve

3338: .seealso: TSCreate(), TSSetCostGradients(), TSSetSolution(), TSAdjointStep()
3339: @*/
3340: PetscErrorCode TSAdjointSolve(TS ts)
3341: {
3342:   PetscErrorCode    ierr;

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

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

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

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

3376:    Collective on TS

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

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

3388:    Level: advanced

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

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

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

3415:    Collective on TS

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

3424:    Output Parameter:
3425: .  ctx - the context

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

3435:    Notes:
3436:    Use TSMonitorLGCtxDestroy() to destroy.

3438:    Level: intermediate

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

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

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

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

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

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

3487: /*@C
3488:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
3489:    with TSMonitorLGCtxCreate().

3491:    Collective on TSMonitorLGCtx

3493:    Input Parameter:
3494: .  ctx - the monitor context

3496:    Level: intermediate

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

3500: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
3501: @*/
3502: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
3503: {
3504:   PetscDraw      draw;

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

3524: /*@
3525:    TSGetTime - Gets the time of the most recently completed step.

3527:    Not Collective

3529:    Input Parameter:
3530: .  ts - the TS context obtained from TSCreate()

3532:    Output Parameter:
3533: .  t  - the current time

3535:    Level: beginner

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

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

3543: .keywords: TS, get, time
3544: @*/
3545: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3546: {
3550:   *t = ts->ptime;
3551:   return(0);
3552: }

3556: /*@
3557:    TSGetPrevTime - Gets the starting time of the previously completed step.

3559:    Not Collective

3561:    Input Parameter:
3562: .  ts - the TS context obtained from TSCreate()

3564:    Output Parameter:
3565: .  t  - the previous time

3567:    Level: beginner

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

3571: .keywords: TS, get, time
3572: @*/
3573: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
3574: {
3578:   *t = ts->ptime_prev;
3579:   return(0);
3580: }

3584: /*@
3585:    TSSetTime - Allows one to reset the time.

3587:    Logically Collective on TS

3589:    Input Parameters:
3590: +  ts - the TS context obtained from TSCreate()
3591: -  time - the time

3593:    Level: intermediate

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

3597: .keywords: TS, set, time
3598: @*/
3599: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
3600: {
3604:   ts->ptime = t;
3605:   return(0);
3606: }

3610: /*@C
3611:    TSSetOptionsPrefix - Sets the prefix used for searching for all
3612:    TS options in the database.

3614:    Logically Collective on TS

3616:    Input Parameter:
3617: +  ts     - The TS context
3618: -  prefix - The prefix to prepend to all option names

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

3625:    Level: advanced

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

3629: .seealso: TSSetFromOptions()

3631: @*/
3632: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
3633: {
3635:   SNES           snes;

3639:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
3640:   TSGetSNES(ts,&snes);
3641:   SNESSetOptionsPrefix(snes,prefix);
3642:   return(0);
3643: }


3648: /*@C
3649:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3650:    TS options in the database.

3652:    Logically Collective on TS

3654:    Input Parameter:
3655: +  ts     - The TS context
3656: -  prefix - The prefix to prepend to all option names

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

3663:    Level: advanced

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

3667: .seealso: TSGetOptionsPrefix()

3669: @*/
3670: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
3671: {
3673:   SNES           snes;

3677:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
3678:   TSGetSNES(ts,&snes);
3679:   SNESAppendOptionsPrefix(snes,prefix);
3680:   return(0);
3681: }

3685: /*@C
3686:    TSGetOptionsPrefix - Sets the prefix used for searching for all
3687:    TS options in the database.

3689:    Not Collective

3691:    Input Parameter:
3692: .  ts - The TS context

3694:    Output Parameter:
3695: .  prefix - A pointer to the prefix string used

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

3700:    Level: intermediate

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

3704: .seealso: TSAppendOptionsPrefix()
3705: @*/
3706: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
3707: {

3713:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
3714:   return(0);
3715: }

3719: /*@C
3720:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

3724:    Input Parameter:
3725: .  ts  - The TS context obtained from TSCreate()

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

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

3735:    Level: intermediate

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

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

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

3757: /*@C
3758:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

3762:    Input Parameter:
3763: .  ts  - The TS context obtained from TSCreate()

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

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

3773:    Level: advanced

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

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

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


3797: /*@C
3798:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
3799:    VecView() for the solution at each timestep

3801:    Collective on TS

3803:    Input Parameters:
3804: +  ts - the TS context
3805: .  step - current time-step
3806: .  ptime - current time
3807: -  dummy - either a viewer or NULL

3809:    Options Database:
3810: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

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

3815:    Level: intermediate

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

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

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

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

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

3857:   if (ictx->showinitial) {
3858:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
3859:   }
3860:   return(0);
3861: }

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

3868:    Collective on TS

3870:    Input Parameters:
3871: +  ts - the TS context
3872: .  step - current time-step
3873: .  ptime - current time
3874: -  dummy - either a viewer or NULL

3876:    Level: intermediate

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

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

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

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

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

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


3926: /*@C
3927:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

3929:    Collective on TS

3931:    Input Parameters:
3932: .    ctx - the monitor context

3934:    Level: intermediate

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

3938: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
3939: @*/
3940: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
3941: {

3945:   PetscDrawAxisDestroy(&(*ictx)->axis);
3946:   PetscViewerDestroy(&(*ictx)->viewer);
3947:   VecDestroy(&(*ictx)->initialsolution);
3948:   PetscFree(*ictx);
3949:   return(0);
3950: }

3954: /*@C
3955:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

3957:    Collective on TS

3959:    Input Parameter:
3960: .    ts - time-step context

3962:    Output Patameter:
3963: .    ctx - the monitor context

3965:    Options Database:
3966: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

3968:    Level: intermediate

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

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

3979:   PetscNew(ctx);
3980:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
3981:   PetscViewerSetFromOptions((*ctx)->viewer);

3983:   (*ctx)->howoften    = howoften;
3984:   (*ctx)->showinitial = PETSC_FALSE;
3985:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

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

3995: /*@C
3996:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
3997:    VecView() for the error at each timestep

3999:    Collective on TS

4001:    Input Parameters:
4002: +  ts - the TS context
4003: .  step - current time-step
4004: .  ptime - current time
4005: -  dummy - either a viewer or NULL

4007:    Level: intermediate

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

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

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

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

4036:    Logically Collective on TS and DM

4038:    Input Parameters:
4039: +  ts - the preconditioner context
4040: -  dm - the dm

4042:    Level: intermediate


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

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

4068:   TSGetSNES(ts,&snes);
4069:   SNESSetDM(snes,dm);
4070:   return(0);
4071: }

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

4078:    Not Collective

4080:    Input Parameter:
4081: . ts - the preconditioner context

4083:    Output Parameter:
4084: .  dm - the dm

4086:    Level: intermediate


4089: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
4090: @*/
4091: PetscErrorCode  TSGetDM(TS ts,DM *dm)
4092: {

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

4107: /*@
4108:    SNESTSFormFunction - Function to evaluate nonlinear residual

4110:    Logically Collective on SNES

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

4117:    Output Parameter:
4118: . F - the nonlinear residual

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

4124:    Level: advanced

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

4138:   (ts->ops->snesfunction)(snes,U,F,ts);
4139:   return(0);
4140: }

4144: /*@
4145:    SNESTSFormJacobian - Function to evaluate the Jacobian

4147:    Collective on SNES

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

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

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

4162:    Level: developer

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

4179:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
4180:   return(0);
4181: }

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

4188:    Collective on TS

4190:    Input Arguments:
4191: +  ts - time stepping context
4192: .  t - time at which to evaluate
4193: .  U - state at which to evaluate
4194: -  ctx - context

4196:    Output Arguments:
4197: .  F - right hand side

4199:    Level: intermediate

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

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

4213:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
4214:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
4215:   MatMult(Arhs,U,F);
4216:   return(0);
4217: }

4221: /*@C
4222:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

4224:    Collective on TS

4226:    Input Arguments:
4227: +  ts - time stepping context
4228: .  t - time at which to evaluate
4229: .  U - state at which to evaluate
4230: -  ctx - context

4232:    Output Arguments:
4233: +  A - pointer to operator
4234: .  B - pointer to preconditioning matrix
4235: -  flg - matrix structure flag

4237:    Level: intermediate

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

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

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

4255:    Collective on TS

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

4264:    Output Arguments:
4265: .  F - left hand side

4267:    Level: intermediate

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

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

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

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

4294:    Collective on TS

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

4304:    Output Arguments:
4305: +  A - pointer to operator
4306: .  B - pointer to preconditioning matrix
4307: -  flg - matrix structure flag

4309:    Level: advanced

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

4314:    It is only appropriate for problems of the form

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

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

4322: $    shift*M + J

4324:   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
4325:   a copy of M or reassemble it when requested.

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

4334:   MatScale(A, shift / ts->ijacobian.shift);
4335:   ts->ijacobian.shift = shift;
4336:   return(0);
4337: }

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

4344:    Not Collective

4346:    Input Parameter:
4347: .  ts - the TS context

4349:    Output Parameter:
4350: .  equation_type - see TSEquationType

4352:    Level: beginner

4354: .keywords: TS, equation type

4356: .seealso: TSSetEquationType(), TSEquationType
4357: @*/
4358: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4359: {
4363:   *equation_type = ts->equation_type;
4364:   return(0);
4365: }

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

4372:    Not Collective

4374:    Input Parameter:
4375: +  ts - the TS context
4376: -  equation_type - see TSEquationType

4378:    Level: advanced

4380: .keywords: TS, equation type

4382: .seealso: TSGetEquationType(), TSEquationType
4383: @*/
4384: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4385: {
4388:   ts->equation_type = equation_type;
4389:   return(0);
4390: }

4394: /*@
4395:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

4397:    Not Collective

4399:    Input Parameter:
4400: .  ts - the TS context

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

4406:    Level: beginner

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

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

4413: .seealso: TSSetConvergenceTest(), TSConvergedReason
4414: @*/
4415: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
4416: {
4420:   *reason = ts->reason;
4421:   return(0);
4422: }

4426: /*@
4427:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

4429:    Not Collective

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

4436:    Level: advanced

4438:    Notes:
4439:    Can only be called during TSSolve() is active.

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

4443: .seealso: TSConvergedReason
4444: @*/
4445: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4446: {
4449:   ts->reason = reason;
4450:   return(0);
4451: }

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

4458:    Not Collective

4460:    Input Parameter:
4461: .  ts - the TS context

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

4466:    Level: beginner

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

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

4473: .seealso: TSSetConvergenceTest(), TSConvergedReason
4474: @*/
4475: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4476: {
4480:   *ftime = ts->solvetime;
4481:   return(0);
4482: }

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

4489:    Not Collective

4491:    Input Parameter:
4492: .  ts - the TS context

4494:    Output Parameter:
4495: .  steps - the number of steps

4497:    Level: beginner

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

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

4504: .seealso: TSSetConvergenceTest(), TSConvergedReason
4505: @*/
4506: PetscErrorCode  TSGetTotalSteps(TS ts,PetscInt *steps)
4507: {
4511:   *steps = ts->total_steps;
4512:   return(0);
4513: }

4517: /*@
4518:    TSGetSNESIterations - Gets the total number of nonlinear iterations
4519:    used by the time integrator.

4521:    Not Collective

4523:    Input Parameter:
4524: .  ts - TS context

4526:    Output Parameter:
4527: .  nits - number of nonlinear iterations

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

4532:    Level: intermediate

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

4536: .seealso:  TSGetKSPIterations()
4537: @*/
4538: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
4539: {
4543:   *nits = ts->snes_its;
4544:   return(0);
4545: }

4549: /*@
4550:    TSGetKSPIterations - Gets the total number of linear iterations
4551:    used by the time integrator.

4553:    Not Collective

4555:    Input Parameter:
4556: .  ts - TS context

4558:    Output Parameter:
4559: .  lits - number of linear iterations

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

4564:    Level: intermediate

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

4568: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
4569: @*/
4570: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
4571: {
4575:   *lits = ts->ksp_its;
4576:   return(0);
4577: }

4581: /*@
4582:    TSGetStepRejections - Gets the total number of rejected steps.

4584:    Not Collective

4586:    Input Parameter:
4587: .  ts - TS context

4589:    Output Parameter:
4590: .  rejects - number of steps rejected

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

4595:    Level: intermediate

4597: .keywords: TS, get, number

4599: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
4600: @*/
4601: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4602: {
4606:   *rejects = ts->reject;
4607:   return(0);
4608: }

4612: /*@
4613:    TSGetSNESFailures - Gets the total number of failed SNES solves

4615:    Not Collective

4617:    Input Parameter:
4618: .  ts - TS context

4620:    Output Parameter:
4621: .  fails - number of failed nonlinear solves

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

4626:    Level: intermediate

4628: .keywords: TS, get, number

4630: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
4631: @*/
4632: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4633: {
4637:   *fails = ts->num_snes_failures;
4638:   return(0);
4639: }

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

4646:    Not Collective

4648:    Input Parameter:
4649: +  ts - TS context
4650: -  rejects - maximum number of rejected steps, pass -1 for unlimited

4652:    Notes:
4653:    The counter is reset to zero for each step

4655:    Options Database Key:
4656:  .  -ts_max_reject - Maximum number of step rejections before a step fails

4658:    Level: intermediate

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

4662: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4663: @*/
4664: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4665: {
4668:   ts->max_reject = rejects;
4669:   return(0);
4670: }

4674: /*@
4675:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

4677:    Not Collective

4679:    Input Parameter:
4680: +  ts - TS context
4681: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

4686:    Options Database Key:
4687:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

4689:    Level: intermediate

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

4693: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
4694: @*/
4695: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4696: {
4699:   ts->max_snes_failures = fails;
4700:   return(0);
4701: }

4705: /*@
4706:    TSSetErrorIfStepFails - Error if no step succeeds

4708:    Not Collective

4710:    Input Parameter:
4711: +  ts - TS context
4712: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

4714:    Options Database Key:
4715:  .  -ts_error_if_step_fails - Error if no step succeeds

4717:    Level: intermediate

4719: .keywords: TS, set, error

4721: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
4722: @*/
4723: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4724: {
4727:   ts->errorifstepfailed = err;
4728:   return(0);
4729: }

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

4736:    Collective on TS

4738:    Input Parameters:
4739: +  ts - the TS context
4740: .  step - current time-step
4741: .  ptime - current time
4742: .  u - current state
4743: -  viewer - binary viewer

4745:    Level: intermediate

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

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

4757:   VecView(u,v);
4758:   return(0);
4759: }

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

4766:    Collective on TS

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

4775:    Level: intermediate

4777:    Notes:
4778:    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.
4779:    These are named according to the file name template.

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

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

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

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

4803: /*@C
4804:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

4806:    Collective on TS

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

4811:    Level: intermediate

4813:    Note:
4814:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

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

4818: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
4819: @*/
4820: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
4821: {

4825:   PetscFree(*(char**)filenametemplate);
4826:   return(0);
4827: }

4831: /*@
4832:    TSGetAdapt - Get the adaptive controller context for the current method

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

4836:    Input Arguments:
4837: .  ts - time stepping context

4839:    Output Arguments:
4840: .  adapt - adaptive controller

4842:    Level: intermediate

4844: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
4845: @*/
4846: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
4847: {

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

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

4867:    Logically Collective

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

4876:    Options Database keys:
4877: +  -ts_rtol <rtol> - relative tolerance for local truncation error
4878: -  -ts_atol <atol> Absolute tolerance for local truncation error

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

4888:    Level: beginner

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

4897:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
4898:   if (vatol) {
4899:     PetscObjectReference((PetscObject)vatol);
4900:     VecDestroy(&ts->vatol);

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

4909:     ts->vrtol = vrtol;
4910:   }
4911:   return(0);
4912: }

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

4919:    Logically Collective

4921:    Input Arguments:
4922: .  ts - time integration context

4924:    Output Arguments:
4925: +  atol - scalar absolute tolerances, NULL to ignore
4926: .  vatol - vector of absolute tolerances, NULL to ignore
4927: .  rtol - scalar relative tolerances, NULL to ignore
4928: -  vrtol - vector of relative tolerances, NULL to ignore

4930:    Level: beginner

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

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

4949:    Collective on TS

4951:    Input Arguments:
4952: +  ts - time stepping context
4953: .  U - state vector, usually ts->vec_sol
4954: -  Y - state vector to be compared to U

4956:    Output Arguments:
4957: .  norm - weighted norm, a value of 1.0 is considered small

4959:    Level: developer

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

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

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

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

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

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

5034:    Collective on TS

5036:    Input Arguments:
5037: +  ts - time stepping context
5038: .  U - state vector, usually ts->vec_sol
5039: -  Y - state vector to be compared to U

5041:    Output Arguments:
5042: .  norm - weighted norm, a value of 1.0 is considered small

5044:    Level: developer

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

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

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

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

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

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

5130:    Collective on TS

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

5138:    Output Arguments:
5139: .  norm - weighted norm, a value of 1.0 is considered small


5142:    Options Database Keys:
5143: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

5145:    Level: developer

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

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

5164: /*@
5165:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

5167:    Logically Collective on TS

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

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

5176:    Level: intermediate

5178: .seealso: TSGetCFLTime(), TSADAPTCFL
5179: @*/
5180: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
5181: {
5184:   ts->cfltime_local = cfltime;
5185:   ts->cfltime       = -1.;
5186:   return(0);
5187: }

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

5194:    Collective on TS

5196:    Input Arguments:
5197: .  ts - time stepping context

5199:    Output Arguments:
5200: .  cfltime - maximum stable time step for forward Euler

5202:    Level: advanced

5204: .seealso: TSSetCFLTimeLocal()
5205: @*/
5206: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
5207: {

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

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

5223:    Input Parameters:
5224: .  ts   - the TS context.
5225: .  xl   - lower bound.
5226: .  xu   - upper bound.

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

5232:    Level: advanced

5234: @*/
5235: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5236: {
5238:   SNES           snes;

5241:   TSGetSNES(ts,&snes);
5242:   SNESVISetVariableBounds(snes,xl,xu);
5243:   return(0);
5244: }

5246: #if defined(PETSC_HAVE_MATLAB_ENGINE)
5247: #include <mex.h>

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

5253: /*
5254:    TSComputeFunction_Matlab - Calls the function that has been set with
5255:                          TSSetFunctionMatlab().

5257:    Collective on TS

5259:    Input Parameters:
5260: +  snes - the TS context
5261: -  u - input vector

5263:    Output Parameter:
5264: .  y - function vector, as set by TSSetFunction()

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

5271:    Level: developer

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

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


5293:   PetscMemcpy(&ls,&snes,sizeof(snes));
5294:   PetscMemcpy(&lx,&u,sizeof(u));
5295:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
5296:   PetscMemcpy(&ly,&y,sizeof(u));

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


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

5325:    Logically Collective on TS

5327:    Input Parameters:
5328: +  ts - the TS context
5329: -  func - function evaluation routine

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

5334:    Level: beginner

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

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

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

5356:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
5357:   return(0);
5358: }

5362: /*
5363:    TSComputeJacobian_Matlab - Calls the function that has been set with
5364:                          TSSetJacobianMatlab().

5366:    Collective on TS

5368:    Input Parameters:
5369: +  ts - the TS context
5370: .  u - input vector
5371: .  A, B - the matrices
5372: -  ctx - user context

5374:    Level: developer

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

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


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

5394:   PetscMemcpy(&ls,&ts,sizeof(ts));
5395:   PetscMemcpy(&lx,&u,sizeof(u));
5396:   PetscMemcpy(&lxdot,&udot,sizeof(u));
5397:   PetscMemcpy(&lA,A,sizeof(u));
5398:   PetscMemcpy(&lB,B,sizeof(u));

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


5427: /*
5428:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
5429:    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

5431:    Logically Collective on TS

5433:    Input Parameters:
5434: +  ts - the TS context
5435: .  A,B - Jacobian matrices
5436: .  func - function evaluation routine
5437: -  ctx - user context

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


5443:    Level: developer

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

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

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

5465:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
5466:   return(0);
5467: }

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

5474:    Collective on TS

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


5490:   PetscMemcpy(&ls,&ts,sizeof(ts));
5491:   PetscMemcpy(&lx,&u,sizeof(u));

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


5513: /*
5514:    TSMonitorSetMatlab - Sets the monitor function from Matlab

5516:    Level: developer

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

5520: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
5521: */
5522: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
5523: {
5524:   PetscErrorCode  ierr;
5525:   TSMatlabContext *sctx;

5528:   /* currently sctx is memory bleed */
5529:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
5530:   PetscStrallocpy(func,&sctx->funcname);
5531:   /*
5532:      This should work, but it doesn't
5533:   sctx->ctx = ctx;
5534:   mexMakeArrayPersistent(sctx->ctx);
5535:   */
5536:   sctx->ctx = mxDuplicateArray(ctx);

5538:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
5539:   return(0);
5540: }
5541: #endif

5545: /*@C
5546:    TSMonitorLGSolution - Monitors progress of the TS solvers by plotting each component of the solution vector
5547:        in a time based line graph

5549:    Collective on TS

5551:    Input Parameters:
5552: +  ts - the TS context
5553: .  step - current time-step
5554: .  ptime - current time
5555: -  lg - a line graph object

5557:    Options Database:
5558: .   -ts_monitor_lg_solution_variables

5560:    Level: intermediate

5562:     Notes: each process in a parallel run displays its component solutions in a separate window

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

5566: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
5567: @*/
5568: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5569: {
5570:   PetscErrorCode    ierr;
5571:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5572:   const PetscScalar *yy;
5573:   PetscInt          dim;
5574:   Vec               v;

5577:   if (!step) {
5578:     PetscDrawAxis axis;
5579:     PetscDrawLGGetAxis(ctx->lg,&axis);
5580:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
5581:     if (ctx->names && !ctx->displaynames) {
5582:       char      **displaynames;
5583:       PetscBool flg;

5585:       VecGetLocalSize(u,&dim);
5586:       PetscMalloc((dim+1)*sizeof(char*),&displaynames);
5587:       PetscMemzero(displaynames,(dim+1)*sizeof(char*));
5588:       PetscOptionsGetStringArray(((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
5589:       if (flg) {
5590:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
5591:       }
5592:       PetscStrArrayDestroy(&displaynames);
5593:     }
5594:     if (ctx->displaynames) {
5595:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
5596:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
5597:     } else if (ctx->names) {
5598:       VecGetLocalSize(u,&dim);
5599:       PetscDrawLGSetDimension(ctx->lg,dim);
5600:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
5601:     }
5602:     PetscDrawLGReset(ctx->lg);
5603:   }
5604:   if (ctx->transform) {
5605:     (*ctx->transform)(ctx->transformctx,u,&v);
5606:   } else {
5607:     v = u;
5608:   }
5609:   VecGetArrayRead(v,&yy);
5610: #if defined(PETSC_USE_COMPLEX)
5611:   {
5612:     PetscReal *yreal;
5613:     PetscInt  i,n;
5614:     VecGetLocalSize(v,&n);
5615:     PetscMalloc1(n,&yreal);
5616:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5617:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
5618:     PetscFree(yreal);
5619:   }
5620: #else
5621:   if (ctx->displaynames) {
5622:     PetscInt i;
5623:     for (i=0; i<ctx->ndisplayvariables; i++) {
5624:       ctx->displayvalues[i] = yy[ctx->displayvariables[i]];
5625:     }
5626:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
5627:   } else {
5628:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
5629:   }
5630: #endif
5631:   VecRestoreArrayRead(v,&yy);
5632:   if (ctx->transform) {
5633:     VecDestroy(&v);
5634:   }
5635:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5636:     PetscDrawLGDraw(ctx->lg);
5637:   }
5638:   return(0);
5639: }


5644: /*@C
5645:    TSMonitorLGSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

5647:    Collective on TS

5649:    Input Parameters:
5650: +  ts - the TS context
5651: -  names - the names of the components, final string must be NULL

5653:    Level: intermediate

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

5657: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
5658: @*/
5659: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
5660: {
5661:   PetscErrorCode    ierr;
5662:   PetscInt          i;

5665:   for (i=0; i<ts->numbermonitors; i++) {
5666:     if (ts->monitor[i] == TSMonitorLGSolution) {
5667:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
5668:       break;
5669:     }
5670:   }
5671:   return(0);
5672: }

5676: /*@C
5677:    TSMonitorLGCtxSetVariableNames - Sets the name of each component in the solution vector so that it may be displayed in the plot

5679:    Collective on TS

5681:    Input Parameters:
5682: +  ts - the TS context
5683: -  names - the names of the components, final string must be NULL

5685:    Level: intermediate

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

5689: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
5690: @*/
5691: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
5692: {
5693:   PetscErrorCode    ierr;

5696:   PetscStrArrayDestroy(&ctx->names);
5697:   PetscStrArrayallocpy(names,&ctx->names);
5698:   return(0);
5699: }

5703: /*@C
5704:    TSMonitorLGGetVariableNames - Gets the name of each component in the solution vector so that it may be displayed in the plot

5706:    Collective on TS

5708:    Input Parameter:
5709: .  ts - the TS context

5711:    Output Parameter:
5712: .  names - the names of the components, final string must be NULL

5714:    Level: intermediate

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

5718: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
5719: @*/
5720: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
5721: {
5722:   PetscInt       i;

5725:   *names = NULL;
5726:   for (i=0; i<ts->numbermonitors; i++) {
5727:     if (ts->monitor[i] == TSMonitorLGSolution) {
5728:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
5729:       *names = (const char *const *)ctx->names;
5730:       break;
5731:     }
5732:   }
5733:   return(0);
5734: }

5738: /*@C
5739:    TSMonitorLGCtxSetDisplayVariables - Sets the variables that are to be display in the monitor

5741:    Collective on TS

5743:    Input Parameters:
5744: +  ctx - the TSMonitorLG context
5745: .  displaynames - the names of the components, final string must be NULL

5747:    Level: intermediate

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

5751: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
5752: @*/
5753: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
5754: {
5755:   PetscInt          j = 0,k;
5756:   PetscErrorCode    ierr;

5759:   if (!ctx->names) return(0);
5760:   PetscStrArrayDestroy(&ctx->displaynames);
5761:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
5762:   while (displaynames[j]) j++;
5763:   ctx->ndisplayvariables = j;
5764:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
5765:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
5766:   j = 0;
5767:   while (displaynames[j]) {
5768:     k = 0;
5769:     while (ctx->names[k]) {
5770:       PetscBool flg;
5771:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
5772:       if (flg) {
5773:         ctx->displayvariables[j] = k;
5774:         break;
5775:       }
5776:       k++;
5777:     }
5778:     j++;
5779:   }
5780:   return(0);
5781: }


5786: /*@C
5787:    TSMonitorLGSetDisplayVariables - Sets the variables that are to be display in the monitor

5789:    Collective on TS

5791:    Input Parameters:
5792: +  ts - the TS context
5793: .  displaynames - the names of the components, final string must be NULL

5795:    Level: intermediate

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

5799: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
5800: @*/
5801: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
5802: {
5803:   PetscInt          i;
5804:   PetscErrorCode    ierr;

5807:   for (i=0; i<ts->numbermonitors; i++) {
5808:     if (ts->monitor[i] == TSMonitorLGSolution) {
5809:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
5810:       break;
5811:     }
5812:   }
5813:   return(0);
5814: }

5818: /*@C
5819:    TSMonitorLGSetTransform - Solution vector will be transformed by provided function before being displayed

5821:    Collective on TS

5823:    Input Parameters:
5824: +  ts - the TS context
5825: .  transform - the transform function
5826: .  destroy - function to destroy the optional context
5827: -  ctx - optional context used by transform function

5829:    Level: intermediate

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

5833: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
5834: @*/
5835: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
5836: {
5837:   PetscInt          i;
5838:   PetscErrorCode    ierr;

5841:   for (i=0; i<ts->numbermonitors; i++) {
5842:     if (ts->monitor[i] == TSMonitorLGSolution) {
5843:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
5844:     }
5845:   }
5846:   return(0);
5847: }

5851: /*@C
5852:    TSMonitorLGCtxSetTransform - Solution vector will be transformed by provided function before being displayed

5854:    Collective on TSLGCtx

5856:    Input Parameters:
5857: +  ts - the TS context
5858: .  transform - the transform function
5859: .  destroy - function to destroy the optional context
5860: -  ctx - optional context used by transform function

5862:    Level: intermediate

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

5866: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
5867: @*/
5868: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
5869: {
5871:   ctx->transform    = transform;
5872:   ctx->transformdestroy = destroy;
5873:   ctx->transformctx = tctx;
5874:   return(0);
5875: }

5879: /*@C
5880:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the solution vector
5881:        in a time based line graph

5883:    Collective on TS

5885:    Input Parameters:
5886: +  ts - the TS context
5887: .  step - current time-step
5888: .  ptime - current time
5889: -  lg - a line graph object

5891:    Level: intermediate

5893:    Notes:
5894:    Only for sequential solves.

5896:    The user must provide the solution using TSSetSolutionFunction() to use this monitor.

5898:    Options Database Keys:
5899: .  -ts_monitor_lg_error - create a graphical monitor of error history

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

5903: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
5904: @*/
5905: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
5906: {
5907:   PetscErrorCode    ierr;
5908:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
5909:   const PetscScalar *yy;
5910:   Vec               y;
5911:   PetscInt          dim;

5914:   if (!step) {
5915:     PetscDrawAxis axis;
5916:     PetscDrawLGGetAxis(ctx->lg,&axis);
5917:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
5918:     VecGetLocalSize(u,&dim);
5919:     PetscDrawLGSetDimension(ctx->lg,dim);
5920:     PetscDrawLGReset(ctx->lg);
5921:   }
5922:   VecDuplicate(u,&y);
5923:   TSComputeSolutionFunction(ts,ptime,y);
5924:   VecAXPY(y,-1.0,u);
5925:   VecGetArrayRead(y,&yy);
5926: #if defined(PETSC_USE_COMPLEX)
5927:   {
5928:     PetscReal *yreal;
5929:     PetscInt  i,n;
5930:     VecGetLocalSize(y,&n);
5931:     PetscMalloc1(n,&yreal);
5932:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
5933:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
5934:     PetscFree(yreal);
5935:   }
5936: #else
5937:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
5938: #endif
5939:   VecRestoreArrayRead(y,&yy);
5940:   VecDestroy(&y);
5941:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
5942:     PetscDrawLGDraw(ctx->lg);
5943:   }
5944:   return(0);
5945: }

5949: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5950: {
5951:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5952:   PetscReal      x   = ptime,y;
5954:   PetscInt       its;

5957:   if (!n) {
5958:     PetscDrawAxis axis;

5960:     PetscDrawLGGetAxis(ctx->lg,&axis);
5961:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
5962:     PetscDrawLGReset(ctx->lg);

5964:     ctx->snes_its = 0;
5965:   }
5966:   TSGetSNESIterations(ts,&its);
5967:   y    = its - ctx->snes_its;
5968:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
5969:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5970:     PetscDrawLGDraw(ctx->lg);
5971:   }
5972:   ctx->snes_its = its;
5973:   return(0);
5974: }

5978: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
5979: {
5980:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
5981:   PetscReal      x   = ptime,y;
5983:   PetscInt       its;

5986:   if (!n) {
5987:     PetscDrawAxis axis;

5989:     PetscDrawLGGetAxis(ctx->lg,&axis);
5990:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
5991:     PetscDrawLGReset(ctx->lg);

5993:     ctx->ksp_its = 0;
5994:   }
5995:   TSGetKSPIterations(ts,&its);
5996:   y    = its - ctx->ksp_its;
5997:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
5998:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
5999:     PetscDrawLGDraw(ctx->lg);
6000:   }
6001:   ctx->ksp_its = its;
6002:   return(0);
6003: }

6007: /*@
6008:    TSComputeLinearStability - computes the linear stability function at a point

6010:    Collective on TS and Vec

6012:    Input Parameters:
6013: +  ts - the TS context
6014: -  xr,xi - real and imaginary part of input arguments

6016:    Output Parameters:
6017: .  yr,yi - real and imaginary part of function value

6019:    Level: developer

6021: .keywords: TS, compute

6023: .seealso: TSSetRHSFunction(), TSComputeIFunction()
6024: @*/
6025: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
6026: {

6031:   if (!ts->ops->linearstability) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
6032:   (*ts->ops->linearstability)(ts,xr,xi,yr,yi);
6033:   return(0);
6034: }

6036: /* ------------------------------------------------------------------------*/
6039: /*@C
6040:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

6042:    Collective on TS

6044:    Input Parameters:
6045: .  ts  - the ODE solver object

6047:    Output Parameter:
6048: .  ctx - the context

6050:    Level: intermediate

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

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

6056: @*/
6057: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
6058: {

6062:   PetscNew(ctx);
6063:   return(0);
6064: }

6068: /*@C
6069:    TSMonitorEnvelope - Monitors the maximum and minimum value of each component of the solution

6071:    Collective on TS

6073:    Input Parameters:
6074: +  ts - the TS context
6075: .  step - current time-step
6076: .  ptime - current time
6077: -  ctx - the envelope context

6079:    Options Database:
6080: .  -ts_monitor_envelope

6082:    Level: intermediate

6084:    Notes: after a solve you can use TSMonitorEnvelopeGetBounds() to access the envelope

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

6088: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds()
6089: @*/
6090: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
6091: {
6092:   PetscErrorCode       ierr;
6093:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dummy;

6096:   if (!ctx->max) {
6097:     VecDuplicate(u,&ctx->max);
6098:     VecDuplicate(u,&ctx->min);
6099:     VecCopy(u,ctx->max);
6100:     VecCopy(u,ctx->min);
6101:   } else {
6102:     VecPointwiseMax(ctx->max,u,ctx->max);
6103:     VecPointwiseMin(ctx->min,u,ctx->min);
6104:   }
6105:   return(0);
6106: }


6111: /*@C
6112:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

6114:    Collective on TS

6116:    Input Parameter:
6117: .  ts - the TS context

6119:    Output Parameter:
6120: +  max - the maximum values
6121: -  min - the minimum values

6123:    Level: intermediate

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

6127: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
6128: @*/
6129: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
6130: {
6131:   PetscInt i;

6134:   if (max) *max = NULL;
6135:   if (min) *min = NULL;
6136:   for (i=0; i<ts->numbermonitors; i++) {
6137:     if (ts->monitor[i] == TSMonitorEnvelope) {
6138:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
6139:       if (max) *max = ctx->max;
6140:       if (min) *min = ctx->min;
6141:       break;
6142:     }
6143:   }
6144:   return(0);
6145: }

6149: /*@C
6150:    TSMonitorEnvelopeCtxDestroy - Destroys a context that was created  with TSMonitorEnvelopeCtxCreate().

6152:    Collective on TSMonitorEnvelopeCtx

6154:    Input Parameter:
6155: .  ctx - the monitor context

6157:    Level: intermediate

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

6161: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
6162: @*/
6163: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
6164: {

6168:   VecDestroy(&(*ctx)->min);
6169:   VecDestroy(&(*ctx)->max);
6170:   PetscFree(*ctx);
6171:   return(0);
6172: }

6176: /*@
6177:    TSRollBack - Rolls back one time step

6179:    Collective on TS

6181:    Input Parameter:
6182: .  ts - the TS context obtained from TSCreate()

6184:    Level: advanced

6186: .keywords: TS, timestep, rollback

6188: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
6189: @*/
6190: PetscErrorCode  TSRollBack(TS ts)
6191: {


6197:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
6198:   (*ts->ops->rollback)(ts);
6199:   ts->time_step = ts->ptime - ts->ptime_prev;
6200:   ts->ptime = ts->ptime_prev;
6201:   ts->steprollback = PETSC_TRUE; /* Flag to indicate that the step is rollbacked */
6202:   return(0);
6203: }

6207: /*@
6208:    TSGetStages - Get the number of stages and stage values 

6210:    Input Parameter:
6211: .  ts - the TS context obtained from TSCreate()

6213:    Level: advanced

6215: .keywords: TS, getstages

6217: .seealso: TSCreate()
6218: @*/
6219: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns, Vec **Y)
6220: {


6227:   if (!ts->ops->getstages) *ns=0;
6228:   else {
6229:     (*ts->ops->getstages)(ts,ns,Y);
6230:   }
6231:   return(0);
6232: }

6236: /*@C
6237:   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.

6239:   Collective on SNES

6241:   Input Parameters:
6242: + ts - the TS context
6243: . t - current timestep
6244: . U - state vector
6245: . Udot - time derivative of state vector
6246: . shift - shift to apply, see note below
6247: - ctx - an optional user context

6249:   Output Parameters:
6250: + J - Jacobian matrix (not altered in this routine)
6251: - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)

6253:   Level: intermediate

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

6258:   dF/dU + shift*dF/dUdot

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

6263:   This will first try to get the coloring from the DM.  If the DM type has no coloring
6264:   routine, then it will try to get the coloring from the matrix.  This requires that the
6265:   matrix have nonzero entries precomputed.

6267: .keywords: TS, finite differences, Jacobian, coloring, sparse
6268: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
6269: @*/
6270: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
6271: {
6272:   SNES           snes;
6273:   MatFDColoring  color;
6274:   PetscBool      hascolor, matcolor = PETSC_FALSE;

6278:   PetscOptionsGetBool(((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
6279:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
6280:   if (!color) {
6281:     DM         dm;
6282:     ISColoring iscoloring;

6284:     TSGetDM(ts, &dm);
6285:     DMHasColoring(dm, &hascolor);
6286:     if (hascolor && !matcolor) {
6287:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
6288:       MatFDColoringCreate(B, iscoloring, &color);
6289:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
6290:       MatFDColoringSetFromOptions(color);
6291:       MatFDColoringSetUp(B, iscoloring, color);
6292:       ISColoringDestroy(&iscoloring);
6293:     } else {
6294:       MatColoring mc;

6296:       MatColoringCreate(B, &mc);
6297:       MatColoringSetDistance(mc, 2);
6298:       MatColoringSetType(mc, MATCOLORINGSL);
6299:       MatColoringSetFromOptions(mc);
6300:       MatColoringApply(mc, &iscoloring);
6301:       MatColoringDestroy(&mc);
6302:       MatFDColoringCreate(B, iscoloring, &color);
6303:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
6304:       MatFDColoringSetFromOptions(color);
6305:       MatFDColoringSetUp(B, iscoloring, color);
6306:       ISColoringDestroy(&iscoloring);
6307:     }
6308:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
6309:     PetscObjectDereference((PetscObject) color);
6310:   }
6311:   TSGetSNES(ts, &snes);
6312:   MatFDColoringApply(B, color, U, snes);
6313:   if (J != B) {
6314:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
6315:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
6316:   }
6317:   return(0);
6318: }

6320: #undef  __FUNCT__
6322: /*@C
6323:   TSClone - This function clones a time step object. 

6325:   Collective on MPI_Comm

6327:   Input Parameter:
6328: . tsin    - The input TS

6330:   Output Parameter:
6331: . tsout   - The output TS (cloned)

6333:   Notes:
6334:   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. 

6336:   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);

6338:   Level: developer

6340: .keywords: TS, clone
6341: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
6342: @*/
6343: PetscErrorCode  TSClone(TS tsin, TS *tsout)
6344: {
6345:   TS             t;
6347:   SNES           snes_start;
6348:   DM             dm;
6349:   TSType         type;

6353:   *tsout = NULL;

6355:   PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView);

6357:   /* General TS description */
6358:   t->numbermonitors    = 0;
6359:   t->setupcalled       = 0;
6360:   t->ksp_its           = 0;
6361:   t->snes_its          = 0;
6362:   t->nwork             = 0;
6363:   t->rhsjacobian.time  = -1e20;
6364:   t->rhsjacobian.scale = 1.;
6365:   t->ijacobian.shift   = 1.;

6367:   TSGetSNES(tsin,&snes_start);
6368:   TSSetSNES(t,snes_start);

6370:   TSGetDM(tsin,&dm);
6371:   TSSetDM(t,dm);

6373:   t->adapt=tsin->adapt;
6374:   PetscObjectReference((PetscObject)t->adapt);

6376:   t->problem_type      = tsin->problem_type;
6377:   t->ptime             = tsin->ptime;
6378:   t->time_step         = tsin->time_step;
6379:   t->time_step_orig    = tsin->time_step_orig;
6380:   t->max_time          = tsin->max_time;
6381:   t->steps             = tsin->steps;
6382:   t->max_steps         = tsin->max_steps;
6383:   t->equation_type     = tsin->equation_type;
6384:   t->atol              = tsin->atol;
6385:   t->rtol              = tsin->rtol;
6386:   t->max_snes_failures = tsin->max_snes_failures;
6387:   t->max_reject        = tsin->max_reject;
6388:   t->errorifstepfailed = tsin->errorifstepfailed;

6390:   TSGetType(tsin,&type);
6391:   TSSetType(t,type);

6393:   t->vec_sol           = NULL;

6395:   t->cfltime          = tsin->cfltime;
6396:   t->cfltime_local    = tsin->cfltime_local;
6397:   t->exact_final_time = tsin->exact_final_time;

6399:   PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps));

6401:   *tsout = t;
6402:   return(0);
6403: }