Date: 2013-07-02T14:50:53+00:00

Actual source code: ts.c
petsc-3.4.2 2013-07-02

      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};

     16: /*
     17:   TSSetTypeFromOptions - Sets the type of ts from user options.

     19:   Collective on TS

     21:   Input Parameter:
     22: . ts - The ts

     24:   Level: intermediate

     26: .keywords: TS, set, options, database, type
     27: .seealso: TSSetFromOptions(), TSSetType()
     28: */
     29: static PetscErrorCode TSSetTypeFromOptions(TS ts)
     30: {
     31:   PetscBool      opt;
     32:   const char     *defaultType;
     33:   char           typeName[256];

     37:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
     38:   else defaultType = TSEULER;

     40:   if (!TSRegisterAllCalled) {TSRegisterAll();}
     41:   PetscOptionsList("-ts_type", "TS method"," TSSetType", TSList, defaultType, typeName, 256, &opt);
     42:   if (opt) {
     43:     TSSetType(ts, typeName);
     44:   } else {
     45:     TSSetType(ts, defaultType);
     46:   }
     47:   return(0);
     48: }

     50: struct _n_TSMonitorDrawCtx {
     51:   PetscViewer   viewer;
     52:   PetscDrawAxis axis;
     53:   Vec           initialsolution;
     54:   PetscBool     showinitial;
     55:   PetscInt      howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
     56:   PetscBool     showtimestepandtime;
     57:   int           color;
     58: };

     62: /*@
     63:    TSSetFromOptions - Sets various TS parameters from user options.

     65:    Collective on TS

     67:    Input Parameter:
     68: .  ts - the TS context obtained from TSCreate()

     70:    Options Database Keys:
     71: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSGL, TSSSP
     72: .  -ts_max_steps maxsteps - maximum number of time-steps to take
     73: .  -ts_final_time time - maximum time to compute to
     74: .  -ts_dt dt - initial time step
     75: .  -ts_monitor - print information at each timestep
     76: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
     77: .  -ts_monitor_lg_solution - Monitor solution graphically
     78: .  -ts_monitor_lg_error - Monitor error graphically
     79: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
     80: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
     81: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
     82: .  -ts_monitor_draw_solution - Monitor solution graphically
     83: .  -ts_monitor_draw_solution_phase - Monitor solution graphically with phase diagram
     84: .  -ts_monitor_draw_error - Monitor error graphically
     85: .  -ts_monitor_solution_binary <filename> - Save each solution to a binary file
     86: -  -ts_monitor_solution_vtk <filename.vts> - Save each time step to a binary file, use filename-%%03D.vts

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

     90:    Level: beginner

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

     94: .seealso: TSGetType()
     95: @*/
     96: PetscErrorCode  TSSetFromOptions(TS ts)
     97: {
     98:   PetscBool              opt,flg;
     99:   PetscErrorCode         ierr;
    100:   PetscViewer            monviewer;
    101:   char                   monfilename[PETSC_MAX_PATH_LEN];
    102:   SNES                   snes;
    103:   TSAdapt                adapt;
    104:   PetscReal              time_step;
    105:   TSExactFinalTimeOption eftopt;
    106:   char                   dir[16];

    110:   PetscObjectOptionsBegin((PetscObject)ts);
    111:   /* Handle TS type options */
    112:   TSSetTypeFromOptions(ts);

    114:   /* Handle generic TS options */
    115:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetDuration",ts->max_steps,&ts->max_steps,NULL);
    116:   PetscOptionsReal("-ts_final_time","Time to run to","TSSetDuration",ts->max_time,&ts->max_time,NULL);
    117:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
    118:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
    119:   if (flg) {
    120:     TSSetTimeStep(ts,time_step);
    121:   }
    122:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
    123:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
    124:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
    125:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
    126:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
    127:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
    128:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

    130:   /* Monitor options */
    131:   PetscOptionsString("-ts_monitor","Monitor timestep size","TSMonitorDefault","stdout",monfilename,PETSC_MAX_PATH_LEN,&flg);
    132:   if (flg) {
    133:     PetscViewerASCIIOpen(PetscObjectComm((PetscObject)ts),monfilename,&monviewer);
    134:     TSMonitorSet(ts,TSMonitorDefault,monviewer,(PetscErrorCode (*)(void**))PetscViewerDestroy);
    135:   }
    136:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",0,monfilename,PETSC_MAX_PATH_LEN,&flg);
    137:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

    139:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
    140:   if (opt) {
    141:     TSMonitorLGCtx ctx;
    142:     PetscInt       howoften = 1;

    144:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
    145:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    146:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    147:   }
    148:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
    149:   if (opt) {
    150:     TSMonitorLGCtx ctx;
    151:     PetscInt       howoften = 1;

    153:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
    154:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
    155:     TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    156:   }
    157:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
    158:   if (opt) {
    159:     TSMonitorLGCtx ctx;
    160:     PetscInt       howoften = 1;

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

    171:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
    172:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,0,0,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    173:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    174:   }
    175:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
    176:   if (opt) {
    177:     TSMonitorLGCtx ctx;
    178:     PetscInt       howoften = 1;

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

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

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

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

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

    263:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,16,&flg);
    264:   if (flg) {
    265:     TSMonitorDMDARayCtx *rayctx;
    266:     int                 ray = 0;
    267:     DMDADirection       ddir;
    268:     DM                  da;
    269:     PetscMPIInt         rank;

    271:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
    272:     if (dir[0] == 'x') ddir = DMDA_X;
    273:     else if (dir[0] == 'y') ddir = DMDA_Y;
    274:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
    275:     sscanf(dir+2,"%d",&ray);

    277:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %D\n",dir[0],ray);
    278:     PetscNew(TSMonitorDMDARayCtx,&rayctx);
    279:     TSGetDM(ts,&da);
    280:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
    281:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
    282:     if (!rank) {
    283:       PetscViewerDrawOpen(PETSC_COMM_SELF,0,0,0,0,600,300,&rayctx->viewer);
    284:     }
    285:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
    286:   }

    288:   TSGetAdapt(ts,&adapt);
    289:   TSAdaptSetFromOptions(adapt);

    291:   TSGetSNES(ts,&snes);
    292:   if (ts->problem_type == TS_LINEAR) {SNESSetType(snes,SNESKSPONLY);}

    294:   /* Handle specific TS options */
    295:   if (ts->ops->setfromoptions) {
    296:     (*ts->ops->setfromoptions)(ts);
    297:   }

    299:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
    300:   PetscObjectProcessOptionsHandlers((PetscObject)ts);
    301:   PetscOptionsEnd();
    302:   return(0);
    303: }

    308: /*@
    309:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
    310:       set with TSSetRHSJacobian().

    312:    Collective on TS and Vec

    314:    Input Parameters:
    315: +  ts - the TS context
    316: .  t - current timestep
    317: -  U - input vector

    319:    Output Parameters:
    320: +  A - Jacobian matrix
    321: .  B - optional preconditioning matrix
    322: -  flag - flag indicating matrix structure

    324:    Notes:
    325:    Most users should not need to explicitly call this routine, as it
    326:    is used internally within the nonlinear solvers.

    328:    See KSPSetOperators() for important information about setting the
    329:    flag parameter.

    331:    Level: developer

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

    335: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
    336: @*/
    337: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg)
    338: {
    340:   PetscInt       Ustate;
    341:   DM             dm;
    342:   DMTS           tsdm;
    343:   TSRHSJacobian  rhsjacobianfunc;
    344:   void           *ctx;
    345:   TSIJacobian    ijacobianfunc;

    351:   TSGetDM(ts,&dm);
    352:   DMGetDMTS(dm,&tsdm);
    353:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
    354:   DMTSGetIJacobian(dm,&ijacobianfunc,NULL);
    355:   PetscObjectStateQuery((PetscObject)U,&Ustate);
    356:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.X == U && ts->rhsjacobian.Xstate == Ustate))) {
    357:     *flg = ts->rhsjacobian.mstructure;
    358:     return(0);
    359:   }

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

    363:   if (rhsjacobianfunc) {
    364:     PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);
    365:     *flg = DIFFERENT_NONZERO_PATTERN;
    366:     PetscStackPush("TS user Jacobian function");
    367:     (*rhsjacobianfunc)(ts,t,U,A,B,flg,ctx);
    368:     PetscStackPop;
    369:     PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);
    370:     /* make sure user returned a correct Jacobian and preconditioner */
    373:   } else {
    374:     MatZeroEntries(*A);
    375:     if (*A != *B) {MatZeroEntries(*B);}
    376:     *flg = SAME_NONZERO_PATTERN;
    377:   }
    378:   ts->rhsjacobian.time       = t;
    379:   ts->rhsjacobian.X          = U;
    380:   PetscObjectStateQuery((PetscObject)U,&ts->rhsjacobian.Xstate);
    381:   ts->rhsjacobian.mstructure = *flg;
    382:   return(0);
    383: }

    387: /*@
    388:    TSComputeRHSFunction - Evaluates the right-hand-side function.

    390:    Collective on TS and Vec

    392:    Input Parameters:
    393: +  ts - the TS context
    394: .  t - current time
    395: -  U - state vector

    397:    Output Parameter:
    398: .  y - right hand side

    400:    Note:
    401:    Most users should not need to explicitly call this routine, as it
    402:    is used internally within the nonlinear solvers.

    404:    Level: developer

    406: .keywords: TS, compute

    408: .seealso: TSSetRHSFunction(), TSComputeIFunction()
    409: @*/
    410: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
    411: {
    413:   TSRHSFunction  rhsfunction;
    414:   TSIFunction    ifunction;
    415:   void           *ctx;
    416:   DM             dm;

    422:   TSGetDM(ts,&dm);
    423:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
    424:   DMTSGetIFunction(dm,&ifunction,NULL);

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

    428:   PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
    429:   if (rhsfunction) {
    430:     PetscStackPush("TS user right-hand-side function");
    431:     (*rhsfunction)(ts,t,U,y,ctx);
    432:     PetscStackPop;
    433:   } else {
    434:     VecZeroEntries(y);
    435:   }

    437:   PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
    438:   return(0);
    439: }

    443: /*@
    444:    TSComputeSolutionFunction - Evaluates the solution function.

    446:    Collective on TS and Vec

    448:    Input Parameters:
    449: +  ts - the TS context
    450: -  t - current time

    452:    Output Parameter:
    453: .  U - the solution

    455:    Note:
    456:    Most users should not need to explicitly call this routine, as it
    457:    is used internally within the nonlinear solvers.

    459:    Level: developer

    461: .keywords: TS, compute

    463: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
    464: @*/
    465: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
    466: {
    467:   PetscErrorCode     ierr;
    468:   TSSolutionFunction solutionfunction;
    469:   void               *ctx;
    470:   DM                 dm;

    475:   TSGetDM(ts,&dm);
    476:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

    478:   if (solutionfunction) {
    479:     PetscStackPush("TS user solution function");
    480:     (*solutionfunction)(ts,t,U,ctx);
    481:     PetscStackPop;
    482:   }
    483:   return(0);
    484: }
    487: /*@
    488:    TSComputeForcingFunction - Evaluates the forcing function.

    490:    Collective on TS and Vec

    492:    Input Parameters:
    493: +  ts - the TS context
    494: -  t - current time

    496:    Output Parameter:
    497: .  U - the function value

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

    503:    Level: developer

    505: .keywords: TS, compute

    507: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
    508: @*/
    509: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
    510: {
    511:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
    512:   void               *ctx;
    513:   DM                 dm;

    518:   TSGetDM(ts,&dm);
    519:   DMTSGetForcingFunction(dm,&forcing,&ctx);

    521:   if (forcing) {
    522:     PetscStackPush("TS user forcing function");
    523:     (*forcing)(ts,t,U,ctx);
    524:     PetscStackPop;
    525:   }
    526:   return(0);
    527: }

    531: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
    532: {
    533:   Vec            F;

    537:   *Frhs = NULL;
    538:   TSGetIFunction(ts,&F,NULL,NULL);
    539:   if (!ts->Frhs) {
    540:     VecDuplicate(F,&ts->Frhs);
    541:   }
    542:   *Frhs = ts->Frhs;
    543:   return(0);
    544: }

    548: static PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
    549: {
    550:   Mat            A,B;

    554:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
    555:   if (Arhs) {
    556:     if (!ts->Arhs) {
    557:       MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
    558:     }
    559:     *Arhs = ts->Arhs;
    560:   }
    561:   if (Brhs) {
    562:     if (!ts->Brhs) {
    563:       MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
    564:     }
    565:     *Brhs = ts->Brhs;
    566:   }
    567:   return(0);
    568: }

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

    575:    Collective on TS and Vec

    577:    Input Parameters:
    578: +  ts - the TS context
    579: .  t - current time
    580: .  U - state vector
    581: .  Udot - time derivative of state vector
    582: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

    584:    Output Parameter:
    585: .  Y - right hand side

    587:    Note:
    588:    Most users should not need to explicitly call this routine, as it
    589:    is used internally within the nonlinear solvers.

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

    594:    Level: developer

    596: .keywords: TS, compute

    598: .seealso: TSSetIFunction(), TSComputeRHSFunction()
    599: @*/
    600: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
    601: {
    603:   TSIFunction    ifunction;
    604:   TSRHSFunction  rhsfunction;
    605:   void           *ctx;
    606:   DM             dm;

    614:   TSGetDM(ts,&dm);
    615:   DMTSGetIFunction(dm,&ifunction,&ctx);
    616:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

    620:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
    621:   if (ifunction) {
    622:     PetscStackPush("TS user implicit function");
    623:     (*ifunction)(ts,t,U,Udot,Y,ctx);
    624:     PetscStackPop;
    625:   }
    626:   if (imex) {
    627:     if (!ifunction) {
    628:       VecCopy(Udot,Y);
    629:     }
    630:   } else if (rhsfunction) {
    631:     if (ifunction) {
    632:       Vec Frhs;
    633:       TSGetRHSVec_Private(ts,&Frhs);
    634:       TSComputeRHSFunction(ts,t,U,Frhs);
    635:       VecAXPY(Y,-1,Frhs);
    636:     } else {
    637:       TSComputeRHSFunction(ts,t,U,Y);
    638:       VecAYPX(Y,-1,Udot);
    639:     }
    640:   }
    641:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
    642:   return(0);
    643: }

    647: /*@
    648:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

    650:    Collective on TS and Vec

    652:    Input
    653:       Input Parameters:
    654: +  ts - the TS context
    655: .  t - current timestep
    656: .  U - state vector
    657: .  Udot - time derivative of state vector
    658: .  shift - shift to apply, see note below
    659: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

    661:    Output Parameters:
    662: +  A - Jacobian matrix
    663: .  B - optional preconditioning matrix
    664: -  flag - flag indicating matrix structure

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

    669:    dF/dU + shift*dF/dUdot

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

    674:    Level: developer

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

    678: .seealso:  TSSetIJacobian()
    679: @*/
    680: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,PetscBool imex)
    681: {
    682:   PetscInt       Ustate, Udotstate;
    684:   TSIJacobian    ijacobian;
    685:   TSRHSJacobian  rhsjacobian;
    686:   DM             dm;
    687:   void           *ctx;

    699:   TSGetDM(ts,&dm);
    700:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
    701:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

    703:   PetscObjectStateQuery((PetscObject)U,&Ustate);
    704:   PetscObjectStateQuery((PetscObject)Udot,&Udotstate);
    705:   if (ts->ijacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->ijacobian.X == U && ts->ijacobian.Xstate == Ustate && ts->ijacobian.Xdot == Udot && ts->ijacobian.Xdotstate == Udotstate && ts->ijacobian.imex == imex))) {
    706:     *flg = ts->ijacobian.mstructure;
    707:     MatScale(*A, shift / ts->ijacobian.shift);
    708:     return(0);
    709:   }

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

    713:   *flg = SAME_NONZERO_PATTERN;  /* In case we're solving a linear problem in which case it wouldn't get initialized below. */
    714:   PetscLogEventBegin(TS_JacobianEval,ts,U,*A,*B);
    715:   if (ijacobian) {
    716:     *flg = DIFFERENT_NONZERO_PATTERN;
    717:     PetscStackPush("TS user implicit Jacobian");
    718:     (*ijacobian)(ts,t,U,Udot,shift,A,B,flg,ctx);
    719:     PetscStackPop;
    720:     /* make sure user returned a correct Jacobian and preconditioner */
    723:   }
    724:   if (imex) {
    725:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
    726:       MatZeroEntries(*A);
    727:       MatShift(*A,shift);
    728:       if (*A != *B) {
    729:         MatZeroEntries(*B);
    730:         MatShift(*B,shift);
    731:       }
    732:       *flg = SAME_PRECONDITIONER;
    733:     }
    734:   } else {
    735:     if (!ijacobian) {
    736:       TSComputeRHSJacobian(ts,t,U,A,B,flg);
    737:       MatScale(*A,-1);
    738:       MatShift(*A,shift);
    739:       if (*A != *B) {
    740:         MatScale(*B,-1);
    741:         MatShift(*B,shift);
    742:       }
    743:     } else if (rhsjacobian) {
    744:       Mat          Arhs,Brhs;
    745:       MatStructure axpy,flg2 = DIFFERENT_NONZERO_PATTERN;
    746:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
    747:       TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);
    748:       axpy = (*flg == flg2) ? SAME_NONZERO_PATTERN : DIFFERENT_NONZERO_PATTERN;
    749:       MatAXPY(*A,-1,Arhs,axpy);
    750:       if (*A != *B) {
    751:         MatAXPY(*B,-1,Brhs,axpy);
    752:       }
    753:       *flg = PetscMin(*flg,flg2);
    754:     }
    755:   }

    757:   ts->ijacobian.time = t;
    758:   ts->ijacobian.X    = U;
    759:   ts->ijacobian.Xdot = Udot;

    761:   PetscObjectStateQuery((PetscObject)U,&ts->ijacobian.Xstate);
    762:   PetscObjectStateQuery((PetscObject)Udot,&ts->ijacobian.Xdotstate);

    764:   ts->ijacobian.shift      = shift;
    765:   ts->ijacobian.imex       = imex;
    766:   ts->ijacobian.mstructure = *flg;

    768:   PetscLogEventEnd(TS_JacobianEval,ts,U,*A,*B);
    769:   return(0);
    770: }

    774: /*@C
    775:     TSSetRHSFunction - Sets the routine for evaluating the function,
    776:     where U_t = G(t,u).

    778:     Logically Collective on TS

    780:     Input Parameters:
    781: +   ts - the TS context obtained from TSCreate()
    782: .   r - vector to put the computed right hand side (or NULL to have it created)
    783: .   f - routine for evaluating the right-hand-side function
    784: -   ctx - [optional] user-defined context for private data for the
    785:           function evaluation routine (may be NULL)

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

    790: +   t - current timestep
    791: .   u - input vector
    792: .   F - function vector
    793: -   ctx - [optional] user-defined function context

    795:     Level: beginner

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

    799: .seealso: TSSetRHSJacobian(), TSSetIJacobian()
    800: @*/
    801: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
    802: {
    804:   SNES           snes;
    805:   Vec            ralloc = NULL;
    806:   DM             dm;

    812:   TSGetDM(ts,&dm);
    813:   DMTSSetRHSFunction(dm,f,ctx);
    814:   TSGetSNES(ts,&snes);
    815:   if (!r && !ts->dm && ts->vec_sol) {
    816:     VecDuplicate(ts->vec_sol,&ralloc);
    817:     r    = ralloc;
    818:   }
    819:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
    820:   VecDestroy(&ralloc);
    821:   return(0);
    822: }

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

    829:     Logically Collective on TS

    831:     Input Parameters:
    832: +   ts - the TS context obtained from TSCreate()
    833: .   f - routine for evaluating the solution
    834: -   ctx - [optional] user-defined context for private data for the
    835:           function evaluation routine (may be NULL)

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

    840: +   t - current timestep
    841: .   u - output vector
    842: -   ctx - [optional] user-defined function context

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

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

    851:     Level: beginner

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

    855: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction()
    856: @*/
    857: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
    858: {
    860:   DM             dm;

    864:   TSGetDM(ts,&dm);
    865:   DMTSSetSolutionFunction(dm,f,ctx);
    866:   return(0);
    867: }

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

    874:     Logically Collective on TS

    876:     Input Parameters:
    877: +   ts - the TS context obtained from TSCreate()
    878: .   f - routine for evaluating the forcing function
    879: -   ctx - [optional] user-defined context for private data for the
    880:           function evaluation routine (may be NULL)

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

    885: +   t - current timestep
    886: .   u - output vector
    887: -   ctx - [optional] user-defined function context

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

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

    895:     Level: beginner

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

    899: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
    900: @*/
    901: PetscErrorCode  TSSetForcingFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
    902: {
    904:   DM             dm;

    908:   TSGetDM(ts,&dm);
    909:   DMTSSetForcingFunction(dm,f,ctx);
    910:   return(0);
    911: }

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

    919:    Logically Collective on TS

    921:    Input Parameters:
    922: +  ts  - the TS context obtained from TSCreate()
    923: .  Amat - (approximate) Jacobian matrix
    924: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
    925: .  f   - the Jacobian evaluation routine
    926: -  ctx - [optional] user-defined context for private data for the
    927:          Jacobian evaluation routine (may be NULL)

    929:    Calling sequence of func:
    930: $     func (TS ts,PetscReal t,Vec u,Mat *A,Mat *B,MatStructure *flag,void *ctx);

    932: +  t - current timestep
    933: .  u - input vector
    934: .  Amat - (approximate) Jacobian matrix
    935: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
    936: .  flag - flag indicating information about the preconditioner matrix
    937:           structure (same as flag in KSPSetOperators())
    938: -  ctx - [optional] user-defined context for matrix evaluation routine

    940:    Notes:
    941:    See KSPSetOperators() for important information about setting the flag
    942:    output parameter in the routine func().  Be sure to read this information!

    944:    The routine func() takes Mat * as the matrix arguments rather than Mat.
    945:    This allows the matrix evaluation routine to replace A and/or B with a
    946:    completely new matrix structure (not just different matrix elements)
    947:    when appropriate, for instance, if the nonzero structure is changing
    948:    throughout the global iterations.

    950:    Level: beginner

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

    954: .seealso: SNESComputeJacobianDefaultColor(), TSSetRHSFunction()

    956: @*/
    957: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
    958: {
    960:   SNES           snes;
    961:   DM             dm;
    962:   TSIJacobian    ijacobian;

    971:   TSGetDM(ts,&dm);
    972:   DMTSSetRHSJacobian(dm,f,ctx);
    973:   DMTSGetIJacobian(dm,&ijacobian,NULL);

    975:   TSGetSNES(ts,&snes);
    976:   if (!ijacobian) {
    977:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
    978:   }
    979:   if (Amat) {
    980:     PetscObjectReference((PetscObject)Amat);
    981:     MatDestroy(&ts->Arhs);

    983:     ts->Arhs = Amat;
    984:   }
    985:   if (Pmat) {
    986:     PetscObjectReference((PetscObject)Pmat);
    987:     MatDestroy(&ts->Brhs);

    989:     ts->Brhs = Pmat;
    990:   }
    991:   return(0);
    992: }

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

    1000:    Logically Collective on TS

    1002:    Input Parameters:
    1003: +  ts  - the TS context obtained from TSCreate()
    1004: .  r   - vector to hold the residual (or NULL to have it created internally)
    1005: .  f   - the function evaluation routine
    1006: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

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

    1011: +  t   - time at step/stage being solved
    1012: .  u   - state vector
    1013: .  u_t - time derivative of state vector
    1014: .  F   - function vector
    1015: -  ctx - [optional] user-defined context for matrix evaluation routine

    1017:    Important:
    1018:    The user MUST call either this routine, TSSetRHSFunction().  This routine must be used when not solving an ODE, for example a DAE.

    1020:    Level: beginner

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

    1024: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
    1025: @*/
    1026: PetscErrorCode  TSSetIFunction(TS ts,Vec res,TSIFunction f,void *ctx)
    1027: {
    1029:   SNES           snes;
    1030:   Vec            resalloc = NULL;
    1031:   DM             dm;

    1037:   TSGetDM(ts,&dm);
    1038:   DMTSSetIFunction(dm,f,ctx);

    1040:   TSGetSNES(ts,&snes);
    1041:   if (!res && !ts->dm && ts->vec_sol) {
    1042:     VecDuplicate(ts->vec_sol,&resalloc);
    1043:     res  = resalloc;
    1044:   }
    1045:   SNESSetFunction(snes,res,SNESTSFormFunction,ts);
    1046:   VecDestroy(&resalloc);
    1047:   return(0);
    1048: }

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

    1055:    Not Collective

    1057:    Input Parameter:
    1058: .  ts - the TS context

    1060:    Output Parameter:
    1061: +  r - vector to hold residual (or NULL)
    1062: .  func - the function to compute residual (or NULL)
    1063: -  ctx - the function context (or NULL)

    1065:    Level: advanced

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

    1069: .seealso: TSSetIFunction(), SNESGetFunction()
    1070: @*/
    1071: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
    1072: {
    1074:   SNES           snes;
    1075:   DM             dm;

    1079:   TSGetSNES(ts,&snes);
    1080:   SNESGetFunction(snes,r,NULL,NULL);
    1081:   TSGetDM(ts,&dm);
    1082:   DMTSGetIFunction(dm,func,ctx);
    1083:   return(0);
    1084: }

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

    1091:    Not Collective

    1093:    Input Parameter:
    1094: .  ts - the TS context

    1096:    Output Parameter:
    1097: +  r - vector to hold computed right hand side (or NULL)
    1098: .  func - the function to compute right hand side (or NULL)
    1099: -  ctx - the function context (or NULL)

    1101:    Level: advanced

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

    1105: .seealso: TSSetRhsfunction(), SNESGetFunction()
    1106: @*/
    1107: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
    1108: {
    1110:   SNES           snes;
    1111:   DM             dm;

    1115:   TSGetSNES(ts,&snes);
    1116:   SNESGetFunction(snes,r,NULL,NULL);
    1117:   TSGetDM(ts,&dm);
    1118:   DMTSGetRHSFunction(dm,func,ctx);
    1119:   return(0);
    1120: }

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

    1128:    Logically Collective on TS

    1130:    Input Parameters:
    1131: +  ts  - the TS context obtained from TSCreate()
    1132: .  Amat - (approximate) Jacobian matrix
    1133: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
    1134: .  f   - the Jacobian evaluation routine
    1135: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

    1140: +  t    - time at step/stage being solved
    1141: .  U    - state vector
    1142: .  U_t  - time derivative of state vector
    1143: .  a    - shift
    1144: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
    1145: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
    1146: .  flag - flag indicating information about the preconditioner matrix
    1147:           structure (same as flag in KSPSetOperators())
    1148: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

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

    1160:    Level: beginner

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

    1164: .seealso: TSSetIFunction(), TSSetRHSJacobian(), SNESComputeJacobianDefaultColor(), SNESComputeJacobianDefault()

    1166: @*/
    1167: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
    1168: {
    1170:   SNES           snes;
    1171:   DM             dm;

    1180:   TSGetDM(ts,&dm);
    1181:   DMTSSetIJacobian(dm,f,ctx);

    1183:   TSGetSNES(ts,&snes);
    1184:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
    1185:   return(0);
    1186: }

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

    1193:   Collective on PetscViewer

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

    1200:    Level: intermediate

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

    1205:   Notes for advanced users:
    1206:   Most users should not need to know the details of the binary storage
    1207:   format, since TSLoad() and TSView() completely hide these details.
    1208:   But for anyone who's interested, the standard binary matrix storage
    1209:   format is
    1210: .vb
    1211:      has not yet been determined
    1212: .ve

    1214: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
    1215: @*/
    1216: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
    1217: {
    1219:   PetscBool      isbinary;
    1220:   PetscInt       classid;
    1221:   char           type[256];
    1222:   DMTS           sdm;
    1223:   DM             dm;

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

    1231:   PetscViewerBinaryRead(viewer,&classid,1,PETSC_INT);
    1232:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
    1233:   PetscViewerBinaryRead(viewer,type,256,PETSC_CHAR);
    1234:   TSSetType(ts, type);
    1235:   if (ts->ops->load) {
    1236:     (*ts->ops->load)(ts,viewer);
    1237:   }
    1238:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
    1239:   DMLoad(dm,viewer);
    1240:   TSSetDM(ts,dm);
    1241:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
    1242:   VecLoad(ts->vec_sol,viewer);
    1243:   DMGetDMTS(ts->dm,&sdm);
    1244:   DMTSLoad(sdm,viewer);
    1245:   return(0);
    1246: }

    1248: #include <petscdraw.h>
    1249: #if defined(PETSC_HAVE_AMS)
    1250: #include <petscviewerams.h>
    1251: #endif
    1254: /*@C
    1255:     TSView - Prints the TS data structure.

    1257:     Collective on TS

    1259:     Input Parameters:
    1260: +   ts - the TS context obtained from TSCreate()
    1261: -   viewer - visualization context

    1263:     Options Database Key:
    1264: .   -ts_view - calls TSView() at end of TSStep()

    1266:     Notes:
    1267:     The available visualization contexts include
    1268: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
    1269: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
    1270:          output where only the first processor opens
    1271:          the file.  All other processors send their
    1272:          data to the first processor to print.

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

    1277:     Level: beginner

    1279: .keywords: TS, timestep, view

    1281: .seealso: PetscViewerASCIIOpen()
    1282: @*/
    1283: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
    1284: {
    1286:   TSType         type;
    1287:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
    1288:   DMTS           sdm;
    1289: #if defined(PETSC_HAVE_AMS)
    1290:   PetscBool      isams;
    1291: #endif

    1295:   if (!viewer) {
    1296:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
    1297:   }

    1301:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
    1302:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
    1303:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
    1304:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
    1305: #if defined(PETSC_HAVE_AMS)
    1306:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERAMS,&isams);
    1307: #endif
    1308:   if (iascii) {
    1309:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer,"TS Object");
    1310:     PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
    1311:     PetscViewerASCIIPrintf(viewer,"  maximum time=%G\n",ts->max_time);
    1312:     if (ts->problem_type == TS_NONLINEAR) {
    1313:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
    1314:       PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solve failures=%D\n",ts->num_snes_failures);
    1315:     }
    1316:     PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
    1317:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
    1318:     DMGetDMTS(ts->dm,&sdm);
    1319:     DMTSView(sdm,viewer);
    1320:     if (ts->ops->view) {
    1321:       PetscViewerASCIIPushTab(viewer);
    1322:       (*ts->ops->view)(ts,viewer);
    1323:       PetscViewerASCIIPopTab(viewer);
    1324:     }
    1325:   } else if (isstring) {
    1326:     TSGetType(ts,&type);
    1327:     PetscViewerStringSPrintf(viewer," %-7.7s",type);
    1328:   } else if (isbinary) {
    1329:     PetscInt    classid = TS_FILE_CLASSID;
    1330:     MPI_Comm    comm;
    1331:     PetscMPIInt rank;
    1332:     char        type[256];

    1334:     PetscObjectGetComm((PetscObject)ts,&comm);
    1335:     MPI_Comm_rank(comm,&rank);
    1336:     if (!rank) {
    1337:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT,PETSC_FALSE);
    1338:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
    1339:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR,PETSC_FALSE);
    1340:     }
    1341:     if (ts->ops->view) {
    1342:       (*ts->ops->view)(ts,viewer);
    1343:     }
    1344:     DMView(ts->dm,viewer);
    1345:     VecView(ts->vec_sol,viewer);
    1346:     DMGetDMTS(ts->dm,&sdm);
    1347:     DMTSView(sdm,viewer);
    1348:   } else if (isdraw) {
    1349:     PetscDraw draw;
    1350:     char      str[36];
    1351:     PetscReal x,y,bottom,h;

    1353:     PetscViewerDrawGetDraw(viewer,0,&draw);
    1354:     PetscDrawGetCurrentPoint(draw,&x,&y);
    1355:     PetscStrcpy(str,"TS: ");
    1356:     PetscStrcat(str,((PetscObject)ts)->type_name);
    1357:     PetscDrawBoxedString(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
    1358:     bottom = y - h;
    1359:     PetscDrawPushCurrentPoint(draw,x,bottom);
    1360:     if (ts->ops->view) {
    1361:       (*ts->ops->view)(ts,viewer);
    1362:     }
    1363:     PetscDrawPopCurrentPoint(draw);
    1364: #if defined(PETSC_HAVE_AMS)
    1365:   } else if (isams) {
    1366:     if (((PetscObject)ts)->amsmem == -1) {
    1367:       PetscObjectViewAMS((PetscObject)ts,viewer);
    1368:       PetscStackCallAMS(AMS_Memory_take_access,(((PetscObject)ts)->amsmem));
    1369:       PetscStackCallAMS(AMS_Memory_add_field,(((PetscObject)ts)->amsmem,"time step",&ts->steps,1,AMS_INT,AMS_READ,AMS_COMMON,AMS_REDUCT_UNDEF));
    1370:       PetscStackCallAMS(AMS_Memory_add_field,(((PetscObject)ts)->amsmem,"time",&ts->ptime,1,AMS_DOUBLE,AMS_READ,AMS_COMMON,AMS_REDUCT_UNDEF));
    1371:       PetscStackCallAMS(AMS_Memory_grant_access,(((PetscObject)ts)->amsmem));
    1372:     }
    1373:     if (ts->ops->view) {
    1374:       (*ts->ops->view)(ts,viewer);
    1375:     }
    1376: #endif
    1377:   }

    1379:   PetscViewerASCIIPushTab(viewer);
    1380:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
    1381:   PetscViewerASCIIPopTab(viewer);
    1382:   return(0);
    1383: }

    1388: /*@
    1389:    TSSetApplicationContext - Sets an optional user-defined context for
    1390:    the timesteppers.

    1392:    Logically Collective on TS

    1394:    Input Parameters:
    1395: +  ts - the TS context obtained from TSCreate()
    1396: -  usrP - optional user context

    1398:    Level: intermediate

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

    1402: .seealso: TSGetApplicationContext()
    1403: @*/
    1404: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
    1405: {
    1408:   ts->user = usrP;
    1409:   return(0);
    1410: }

    1414: /*@
    1415:     TSGetApplicationContext - Gets the user-defined context for the
    1416:     timestepper.

    1418:     Not Collective

    1420:     Input Parameter:
    1421: .   ts - the TS context obtained from TSCreate()

    1423:     Output Parameter:
    1424: .   usrP - user context

    1426:     Level: intermediate

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

    1430: .seealso: TSSetApplicationContext()
    1431: @*/
    1432: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
    1433: {
    1436:   *(void**)usrP = ts->user;
    1437:   return(0);
    1438: }

    1442: /*@
    1443:    TSGetTimeStepNumber - Gets the number of time steps completed.

    1445:    Not Collective

    1447:    Input Parameter:
    1448: .  ts - the TS context obtained from TSCreate()

    1450:    Output Parameter:
    1451: .  iter - number of steps completed so far

    1453:    Level: intermediate

    1455: .keywords: TS, timestep, get, iteration, number
    1456: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStep()
    1457: @*/
    1458: PetscErrorCode  TSGetTimeStepNumber(TS ts,PetscInt *iter)
    1459: {
    1463:   *iter = ts->steps;
    1464:   return(0);
    1465: }

    1469: /*@
    1470:    TSSetInitialTimeStep - Sets the initial timestep to be used,
    1471:    as well as the initial time.

    1473:    Logically Collective on TS

    1475:    Input Parameters:
    1476: +  ts - the TS context obtained from TSCreate()
    1477: .  initial_time - the initial time
    1478: -  time_step - the size of the timestep

    1480:    Level: intermediate

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

    1484: .keywords: TS, set, initial, timestep
    1485: @*/
    1486: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
    1487: {

    1492:   TSSetTimeStep(ts,time_step);
    1493:   TSSetTime(ts,initial_time);
    1494:   return(0);
    1495: }

    1499: /*@
    1500:    TSSetTimeStep - Allows one to reset the timestep at any time,
    1501:    useful for simple pseudo-timestepping codes.

    1503:    Logically Collective on TS

    1505:    Input Parameters:
    1506: +  ts - the TS context obtained from TSCreate()
    1507: -  time_step - the size of the timestep

    1509:    Level: intermediate

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

    1513: .keywords: TS, set, timestep
    1514: @*/
    1515: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
    1516: {
    1520:   ts->time_step      = time_step;
    1521:   ts->time_step_orig = time_step;
    1522:   return(0);
    1523: }

    1527: /*@
    1528:    TSSetExactFinalTime - Determines whether to adapt the final time step to
    1529:      match the exact final time, interpolate solution to the exact final time,
    1530:      or just return at the final time TS computed.

    1532:   Logically Collective on TS

    1534:    Input Parameter:
    1535: +   ts - the time-step context
    1536: -   eftopt - exact final time option

    1538:    Level: beginner

    1540: .seealso: TSExactFinalTimeOption
    1541: @*/
    1542: PetscErrorCode  TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
    1543: {
    1547:   ts->exact_final_time = eftopt;
    1548:   return(0);
    1549: }

    1553: /*@
    1554:    TSGetTimeStep - Gets the current timestep size.

    1556:    Not Collective

    1558:    Input Parameter:
    1559: .  ts - the TS context obtained from TSCreate()

    1561:    Output Parameter:
    1562: .  dt - the current timestep size

    1564:    Level: intermediate

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

    1568: .keywords: TS, get, timestep
    1569: @*/
    1570: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
    1571: {
    1575:   *dt = ts->time_step;
    1576:   return(0);
    1577: }

    1581: /*@
    1582:    TSGetSolution - Returns the solution at the present timestep. It
    1583:    is valid to call this routine inside the function that you are evaluating
    1584:    in order to move to the new timestep. This vector not changed until
    1585:    the solution at the next timestep has been calculated.

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

    1589:    Input Parameter:
    1590: .  ts - the TS context obtained from TSCreate()

    1592:    Output Parameter:
    1593: .  v - the vector containing the solution

    1595:    Level: intermediate

    1597: .seealso: TSGetTimeStep()

    1599: .keywords: TS, timestep, get, solution
    1600: @*/
    1601: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
    1602: {
    1606:   *v = ts->vec_sol;
    1607:   return(0);
    1608: }

    1610: /* ----- Routines to initialize and destroy a timestepper ---- */
    1613: /*@
    1614:   TSSetProblemType - Sets the type of problem to be solved.

    1616:   Not collective

    1618:   Input Parameters:
    1619: + ts   - The TS
    1620: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
    1621: .vb
    1622:          U_t - A U = 0      (linear)
    1623:          U_t - A(t) U = 0   (linear)
    1624:          F(t,U,U_t) = 0     (nonlinear)
    1625: .ve

    1627:    Level: beginner

    1629: .keywords: TS, problem type
    1630: .seealso: TSSetUp(), TSProblemType, TS
    1631: @*/
    1632: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
    1633: {

    1638:   ts->problem_type = type;
    1639:   if (type == TS_LINEAR) {
    1640:     SNES snes;
    1641:     TSGetSNES(ts,&snes);
    1642:     SNESSetType(snes,SNESKSPONLY);
    1643:   }
    1644:   return(0);
    1645: }

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

    1652:   Not collective

    1654:   Input Parameter:
    1655: . ts   - The TS

    1657:   Output Parameter:
    1658: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
    1659: .vb
    1660:          M U_t = A U
    1661:          M(t) U_t = A(t) U
    1662:          F(t,U,U_t)
    1663: .ve

    1665:    Level: beginner

    1667: .keywords: TS, problem type
    1668: .seealso: TSSetUp(), TSProblemType, TS
    1669: @*/
    1670: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
    1671: {
    1675:   *type = ts->problem_type;
    1676:   return(0);
    1677: }

    1681: /*@
    1682:    TSSetUp - Sets up the internal data structures for the later use
    1683:    of a timestepper.

    1685:    Collective on TS

    1687:    Input Parameter:
    1688: .  ts - the TS context obtained from TSCreate()

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

    1697:    Level: advanced

    1699: .keywords: TS, timestep, setup

    1701: .seealso: TSCreate(), TSStep(), TSDestroy()
    1702: @*/
    1703: PetscErrorCode  TSSetUp(TS ts)
    1704: {
    1706:   DM             dm;
    1707:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
    1708:   PetscErrorCode (*jac)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);
    1709:   TSIJacobian    ijac;
    1710:   TSRHSJacobian  rhsjac;

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

    1716:   if (!((PetscObject)ts)->type_name) {
    1717:     TSSetType(ts,TSEULER);
    1718:   }

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

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

    1724:   if (ts->ops->setup) {
    1725:     (*ts->ops->setup)(ts);
    1726:   }

    1728:   /* in the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
    1729:    to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
    1730:    */
    1731:   TSGetDM(ts,&dm);
    1732:   DMSNESGetFunction(dm,&func,NULL);
    1733:   if (!func) {
    1734:     ierr =DMSNESSetFunction(dm,SNESTSFormFunction,ts);
    1735:   }
    1736:   /* if the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
    1737:      Otherwise, the SNES will use coloring internally to form the Jacobian.
    1738:    */
    1739:   DMSNESGetJacobian(dm,&jac,NULL);
    1740:   DMTSGetIJacobian(dm,&ijac,NULL);
    1741:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
    1742:   if (!jac && (ijac || rhsjac)) {
    1743:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
    1744:   }
    1745:   ts->setupcalled = PETSC_TRUE;
    1746:   return(0);
    1747: }

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

    1754:    Collective on TS

    1756:    Input Parameter:
    1757: .  ts - the TS context obtained from TSCreate()

    1759:    Level: beginner

    1761: .keywords: TS, timestep, reset

    1763: .seealso: TSCreate(), TSSetup(), TSDestroy()
    1764: @*/
    1765: PetscErrorCode  TSReset(TS ts)
    1766: {

    1771:   if (ts->ops->reset) {
    1772:     (*ts->ops->reset)(ts);
    1773:   }
    1774:   if (ts->snes) {SNESReset(ts->snes);}

    1776:   MatDestroy(&ts->Arhs);
    1777:   MatDestroy(&ts->Brhs);
    1778:   VecDestroy(&ts->Frhs);
    1779:   VecDestroy(&ts->vec_sol);
    1780:   VecDestroy(&ts->vatol);
    1781:   VecDestroy(&ts->vrtol);
    1782:   VecDestroyVecs(ts->nwork,&ts->work);

    1784:   ts->setupcalled = PETSC_FALSE;
    1785:   return(0);
    1786: }

    1790: /*@
    1791:    TSDestroy - Destroys the timestepper context that was created
    1792:    with TSCreate().

    1794:    Collective on TS

    1796:    Input Parameter:
    1797: .  ts - the TS context obtained from TSCreate()

    1799:    Level: beginner

    1801: .keywords: TS, timestepper, destroy

    1803: .seealso: TSCreate(), TSSetUp(), TSSolve()
    1804: @*/
    1805: PetscErrorCode  TSDestroy(TS *ts)
    1806: {

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

    1814:   TSReset((*ts));

    1816:   /* if memory was published with AMS then destroy it */
    1817:   PetscObjectAMSViewOff((PetscObject)*ts);
    1818:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

    1820:   TSAdaptDestroy(&(*ts)->adapt);
    1821:   SNESDestroy(&(*ts)->snes);
    1822:   DMDestroy(&(*ts)->dm);
    1823:   TSMonitorCancel((*ts));

    1825:   PetscHeaderDestroy(ts);
    1826:   return(0);
    1827: }

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

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

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

    1840:    Output Parameter:
    1841: .  snes - the nonlinear solver context

    1843:    Notes:
    1844:    The user can then directly manipulate the SNES context to set various
    1845:    options, etc.  Likewise, the user can then extract and manipulate the
    1846:    KSP, KSP, and PC contexts as well.

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

    1851:    Level: beginner

    1853: .keywords: timestep, get, SNES
    1854: @*/
    1855: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
    1856: {

    1862:   if (!ts->snes) {
    1863:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
    1864:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
    1865:     PetscLogObjectParent(ts,ts->snes);
    1866:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
    1867:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
    1868:     if (ts->problem_type == TS_LINEAR) {
    1869:       SNESSetType(ts->snes,SNESKSPONLY);
    1870:     }
    1871:   }
    1872:   *snes = ts->snes;
    1873:   return(0);
    1874: }

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

    1881:    Collective

    1883:    Input Parameter:
    1884: +  ts - the TS context obtained from TSCreate()
    1885: -  snes - the nonlinear solver context

    1887:    Notes:
    1888:    Most users should have the TS created by calling TSGetSNES()

    1890:    Level: developer

    1892: .keywords: timestep, set, SNES
    1893: @*/
    1894: PetscErrorCode TSSetSNES(TS ts,SNES snes)
    1895: {
    1897:   PetscErrorCode (*func)(SNES,Vec,Mat*,Mat*,MatStructure*,void*);

    1902:   PetscObjectReference((PetscObject)snes);
    1903:   SNESDestroy(&ts->snes);

    1905:   ts->snes = snes;

    1907:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
    1908:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
    1909:   if (func == SNESTSFormJacobian) {
    1910:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
    1911:   }
    1912:   return(0);
    1913: }

    1917: /*@
    1918:    TSGetKSP - Returns the KSP (linear solver) associated with
    1919:    a TS (timestepper) context.

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

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

    1926:    Output Parameter:
    1927: .  ksp - the nonlinear solver context

    1929:    Notes:
    1930:    The user can then directly manipulate the KSP context to set various
    1931:    options, etc.  Likewise, the user can then extract and manipulate the
    1932:    KSP and PC contexts as well.

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

    1937:    Level: beginner

    1939: .keywords: timestep, get, KSP
    1940: @*/
    1941: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
    1942: {
    1944:   SNES           snes;

    1949:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
    1950:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
    1951:   TSGetSNES(ts,&snes);
    1952:   SNESGetKSP(snes,ksp);
    1953:   return(0);
    1954: }

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

    1960: /*@
    1961:    TSGetDuration - Gets the maximum number of timesteps to use and
    1962:    maximum time for iteration.

    1964:    Not Collective

    1966:    Input Parameters:
    1967: +  ts       - the TS context obtained from TSCreate()
    1968: .  maxsteps - maximum number of iterations to use, or NULL
    1969: -  maxtime  - final time to iterate to, or NULL

    1971:    Level: intermediate

    1973: .keywords: TS, timestep, get, maximum, iterations, time
    1974: @*/
    1975: PetscErrorCode  TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
    1976: {
    1979:   if (maxsteps) {
    1981:     *maxsteps = ts->max_steps;
    1982:   }
    1983:   if (maxtime) {
    1985:     *maxtime = ts->max_time;
    1986:   }
    1987:   return(0);
    1988: }

    1992: /*@
    1993:    TSSetDuration - Sets the maximum number of timesteps to use and
    1994:    maximum time for iteration.

    1996:    Logically Collective on TS

    1998:    Input Parameters:
    1999: +  ts - the TS context obtained from TSCreate()
    2000: .  maxsteps - maximum number of iterations to use
    2001: -  maxtime - final time to iterate to

    2003:    Options Database Keys:
    2004: .  -ts_max_steps <maxsteps> - Sets maxsteps
    2005: .  -ts_final_time <maxtime> - Sets maxtime

    2007:    Notes:
    2008:    The default maximum number of iterations is 5000. Default time is 5.0

    2010:    Level: intermediate

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

    2014: .seealso: TSSetExactFinalTime()
    2015: @*/
    2016: PetscErrorCode  TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
    2017: {
    2022:   if (maxsteps >= 0) ts->max_steps = maxsteps;
    2023:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
    2024:   return(0);
    2025: }

    2029: /*@
    2030:    TSSetSolution - Sets the initial solution vector
    2031:    for use by the TS routines.

    2033:    Logically Collective on TS and Vec

    2035:    Input Parameters:
    2036: +  ts - the TS context obtained from TSCreate()
    2037: -  u - the solution vector

    2039:    Level: beginner

    2041: .keywords: TS, timestep, set, solution, initial conditions
    2042: @*/
    2043: PetscErrorCode  TSSetSolution(TS ts,Vec u)
    2044: {
    2046:   DM             dm;

    2051:   PetscObjectReference((PetscObject)u);
    2052:   VecDestroy(&ts->vec_sol);

    2054:   ts->vec_sol = u;

    2056:   TSGetDM(ts,&dm);
    2057:   DMShellSetGlobalVector(dm,u);
    2058:   return(0);
    2059: }

    2063: /*@C
    2064:   TSSetPreStep - Sets the general-purpose function
    2065:   called once at the beginning of each time step.

    2067:   Logically Collective on TS

    2069:   Input Parameters:
    2070: + ts   - The TS context obtained from TSCreate()
    2071: - func - The function

    2073:   Calling sequence of func:
    2074: . func (TS ts);

    2076:   Level: intermediate

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

    2083: .keywords: TS, timestep
    2084: .seealso: TSSetPreStage(), TSSetPostStep(), TSStep()
    2085: @*/
    2086: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
    2087: {
    2090:   ts->prestep = func;
    2091:   return(0);
    2092: }

    2096: /*@
    2097:   TSPreStep - Runs the user-defined pre-step function.

    2099:   Collective on TS

    2101:   Input Parameters:
    2102: . ts   - The TS context obtained from TSCreate()

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

    2108:   Level: developer

    2110: .keywords: TS, timestep
    2111: .seealso: TSSetPreStep(), TSPreStage(), TSPostStep()
    2112: @*/
    2113: PetscErrorCode  TSPreStep(TS ts)
    2114: {

    2119:   if (ts->prestep) {
    2120:     PetscStackCallStandard((*ts->prestep),(ts));
    2121:   }
    2122:   return(0);
    2123: }

    2127: /*@C
    2128:   TSSetPreStage - Sets the general-purpose function
    2129:   called once at the beginning of each stage.

    2131:   Logically Collective on TS

    2133:   Input Parameters:
    2134: + ts   - The TS context obtained from TSCreate()
    2135: - func - The function

    2137:   Calling sequence of func:
    2138: . PetscErrorCode func(TS ts, PetscReal stagetime);

    2140:   Level: intermediate

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

    2147: .keywords: TS, timestep
    2148: .seealso: TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
    2149: @*/
    2150: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
    2151: {
    2154:   ts->prestage = func;
    2155:   return(0);
    2156: }

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

    2163:   Collective on TS

    2165:   Input Parameters:
    2166: . ts   - The TS context obtained from TSCreate()

    2168:   Notes:
    2169:   TSPreStage() is typically used within time stepping implementations,
    2170:   most users would not generally call this routine themselves.

    2172:   Level: developer

    2174: .keywords: TS, timestep
    2175: .seealso: TSSetPreStep(), TSPreStep(), TSPostStep()
    2176: @*/
    2177: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
    2178: {

    2183:   if (ts->prestage) {
    2184:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
    2185:   }
    2186:   return(0);
    2187: }

    2191: /*@C
    2192:   TSSetPostStep - Sets the general-purpose function
    2193:   called once at the end of each time step.

    2195:   Logically Collective on TS

    2197:   Input Parameters:
    2198: + ts   - The TS context obtained from TSCreate()
    2199: - func - The function

    2201:   Calling sequence of func:
    2202: $ func (TS ts);

    2204:   Level: intermediate

    2206: .keywords: TS, timestep
    2207: .seealso: TSSetPreStep(), TSSetPreStage(), TSGetTimeStep(), TSGetTimeStepNumber(), TSGetTime()
    2208: @*/
    2209: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
    2210: {
    2213:   ts->poststep = func;
    2214:   return(0);
    2215: }

    2219: /*@
    2220:   TSPostStep - Runs the user-defined post-step function.

    2222:   Collective on TS

    2224:   Input Parameters:
    2225: . ts   - The TS context obtained from TSCreate()

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

    2231:   Level: developer

    2233: .keywords: TS, timestep
    2234: @*/
    2235: PetscErrorCode  TSPostStep(TS ts)
    2236: {

    2241:   if (ts->poststep) {
    2242:     PetscStackCallStandard((*ts->poststep),(ts));
    2243:   }
    2244:   return(0);
    2245: }

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

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

    2255:    Logically Collective on TS

    2257:    Input Parameters:
    2258: +  ts - the TS context obtained from TSCreate()
    2259: .  monitor - monitoring routine
    2260: .  mctx - [optional] user-defined context for private data for the
    2261:              monitor routine (use NULL if no context is desired)
    2262: -  monitordestroy - [optional] routine that frees monitor context
    2263:           (may be NULL)

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

    2268: +    ts - the TS context
    2269: .    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
    2270:                                been interpolated to)
    2271: .    time - current time
    2272: .    u - current iterate
    2273: -    mctx - [optional] monitoring context

    2275:    Notes:
    2276:    This routine adds an additional monitor to the list of monitors that
    2277:    already has been loaded.

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

    2281:    Level: intermediate

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

    2285: .seealso: TSMonitorDefault(), TSMonitorCancel()
    2286: @*/
    2287: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
    2288: {
    2291:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
    2292:   ts->monitor[ts->numbermonitors]          = monitor;
    2293:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
    2294:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
    2295:   return(0);
    2296: }

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

    2303:    Logically Collective on TS

    2305:    Input Parameters:
    2306: .  ts - the TS context obtained from TSCreate()

    2308:    Notes:
    2309:    There is no way to remove a single, specific monitor.

    2311:    Level: intermediate

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

    2315: .seealso: TSMonitorDefault(), TSMonitorSet()
    2316: @*/
    2317: PetscErrorCode  TSMonitorCancel(TS ts)
    2318: {
    2320:   PetscInt       i;

    2324:   for (i=0; i<ts->numbermonitors; i++) {
    2325:     if (ts->monitordestroy[i]) {
    2326:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
    2327:     }
    2328:   }
    2329:   ts->numbermonitors = 0;
    2330:   return(0);
    2331: }

    2335: /*@
    2336:    TSMonitorDefault - Sets the Default monitor

    2338:    Level: intermediate

    2340: .keywords: TS, set, monitor

    2342: .seealso: TSMonitorDefault(), TSMonitorSet()
    2343: @*/
    2344: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,void *dummy)
    2345: {
    2347:   PetscViewer    viewer = dummy ? (PetscViewer) dummy : PETSC_VIEWER_STDOUT_(PetscObjectComm((PetscObject)ts));

    2350:   PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
    2351:   PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g\n",step,(double)ts->time_step,(double)ptime);
    2352:   PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
    2353:   return(0);
    2354: }

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

    2361:    Logically Collective on TS

    2363:    Input Argument:
    2364: .  ts - time stepping context

    2366:    Output Argument:
    2367: .  flg - PETSC_TRUE or PETSC_FALSE

    2369:    Level: intermediate

    2371: .keywords: TS, set

    2373: .seealso: TSInterpolate(), TSSetPostStep()
    2374: @*/
    2375: PetscErrorCode TSSetRetainStages(TS ts,PetscBool flg)
    2376: {
    2379:   ts->retain_stages = flg;
    2380:   return(0);
    2381: }

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

    2388:    Collective on TS

    2390:    Input Argument:
    2391: +  ts - time stepping context
    2392: -  t - time to interpolate to

    2394:    Output Argument:
    2395: .  U - state at given time

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

    2400:    Level: intermediate

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

    2405: .keywords: TS, set

    2407: .seealso: TSSetRetainStages(), TSSetPostStep()
    2408: @*/
    2409: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
    2410: {

    2416:   if (t < ts->ptime - ts->time_step_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %G not in last time steps [%G,%G]",t,ts->ptime-ts->time_step_prev,ts->ptime);
    2417:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
    2418:   (*ts->ops->interpolate)(ts,t,U);
    2419:   return(0);
    2420: }

    2424: /*@
    2425:    TSStep - Steps one time step

    2427:    Collective on TS

    2429:    Input Parameter:
    2430: .  ts - the TS context obtained from TSCreate()

    2432:    Level: intermediate

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

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

    2441: .keywords: TS, timestep, solve

    2443: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
    2444: @*/
    2445: PetscErrorCode  TSStep(TS ts)
    2446: {
    2447:   PetscReal      ptime_prev;

    2452:   TSSetUp(ts);

    2454:   ts->reason = TS_CONVERGED_ITERATING;
    2455:   ptime_prev = ts->ptime;

    2457:   PetscLogEventBegin(TS_Step,ts,0,0,0);
    2458:   (*ts->ops->step)(ts);
    2459:   PetscLogEventEnd(TS_Step,ts,0,0,0);

    2461:   ts->time_step_prev = ts->ptime - ptime_prev;

    2463:   if (ts->reason < 0) {
    2464:     if (ts->errorifstepfailed) {
    2465:       if (ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) {
    2466:         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]);
    2467:       } else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
    2468:     }
    2469:   } else if (!ts->reason) {
    2470:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
    2471:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
    2472:   }
    2473:   return(0);
    2474: }

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

    2481:    Collective on TS

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

    2488:    Output Arguments:
    2489: .  U - state at the end of the current step

    2491:    Level: advanced

    2493:    Notes:
    2494:    This function cannot be called until all stages have been evaluated.
    2495:    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.

    2497: .seealso: TSStep(), TSAdapt
    2498: @*/
    2499: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
    2500: {

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

    2514: /*@
    2515:    TSSolve - Steps the requested number of timesteps.

    2517:    Collective on TS

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

    2523:    Level: beginner

    2525:    Notes:
    2526:    The final time returned by this function may be different from the time of the internally
    2527:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
    2528:    stepped over the final time.

    2530: .keywords: TS, timestep, solve

    2532: .seealso: TSCreate(), TSSetSolution(), TSStep()
    2533: @*/
    2534: PetscErrorCode TSSolve(TS ts,Vec u)
    2535: {
    2536:   PetscBool         flg;
    2537:   PetscViewer       viewer;
    2538:   Vec               solution;
    2539:   PetscErrorCode    ierr;
    2540:   PetscViewerFormat format;

    2545:   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 */
    2547:     if (!ts->vec_sol || u == ts->vec_sol) {
    2548:       VecDuplicate(u,&solution);
    2549:       TSSetSolution(ts,solution);
    2550:       VecDestroy(&solution); /* grant ownership */
    2551:     }
    2552:     VecCopy(u,ts->vec_sol);
    2553:   } else if (u) {
    2554:     TSSetSolution(ts,u);
    2555:   }
    2556:   TSSetUp(ts);
    2557:   /* reset time step and iteration counters */
    2558:   ts->steps             = 0;
    2559:   ts->ksp_its           = 0;
    2560:   ts->snes_its          = 0;
    2561:   ts->num_snes_failures = 0;
    2562:   ts->reject            = 0;
    2563:   ts->reason            = TS_CONVERGED_ITERATING;

    2565:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,"-ts_view_pre",&viewer,&format,&flg);
    2566:   if (flg && !PetscPreLoadingOn) {
    2567:     PetscViewerPushFormat(viewer,format);
    2568:     TSView(ts,viewer);
    2569:     PetscViewerPopFormat(viewer);
    2570:     PetscViewerDestroy(&viewer);
    2571:   }

    2573:   if (ts->ops->solve) {         /* This private interface is transitional and should be removed when all implementations are updated. */
    2574:     (*ts->ops->solve)(ts);
    2575:     VecCopy(ts->vec_sol,u);
    2576:     ts->solvetime = ts->ptime;
    2577:   } else {
    2578:     /* steps the requested number of timesteps. */
    2579:     if (ts->steps >= ts->max_steps)     ts->reason = TS_CONVERGED_ITS;
    2580:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
    2581:     while (!ts->reason) {
    2582:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
    2583:       TSStep(ts);
    2584:       TSPostStep(ts);
    2585:     }
    2586:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
    2587:       TSInterpolate(ts,ts->max_time,u);
    2588:       ts->solvetime = ts->max_time;
    2589:       solution = u;
    2590:     } else {
    2591:       if (u) {VecCopy(ts->vec_sol,u);}
    2592:       ts->solvetime = ts->ptime;
    2593:       solution = ts->vec_sol;
    2594:     }
    2595:     TSMonitor(ts,ts->steps,ts->solvetime,solution);
    2596:   }
    2597:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject)ts)->prefix,"-ts_view",&viewer,&format,&flg);
    2598:   if (flg && !PetscPreLoadingOn) {
    2599:     PetscViewerPushFormat(viewer,format);
    2600:     TSView(ts,viewer);
    2601:     PetscViewerPopFormat(viewer);
    2602:     PetscViewerDestroy(&viewer);
    2603:   }
    2604:   return(0);
    2605: }

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

    2612:    Collective on TS

    2614:    Input Parameters:
    2615: +  ts - time stepping context obtained from TSCreate()
    2616: .  step - step number that has just completed
    2617: .  ptime - model time of the state
    2618: -  u - state at the current model time

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

    2624:    Level: advanced

    2626: .keywords: TS, timestep
    2627: @*/
    2628: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
    2629: {
    2631:   PetscInt       i,n = ts->numbermonitors;

    2636:   for (i=0; i<n; i++) {
    2637:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
    2638:   }
    2639:   return(0);
    2640: }

    2642: /* ------------------------------------------------------------------------*/
    2643: struct _n_TSMonitorLGCtx {
    2644:   PetscDrawLG lg;
    2645:   PetscInt    howoften;  /* when > 0 uses step % howoften, when negative only final solution plotted */
    2646:   PetscInt    ksp_its,snes_its;
    2647: };

    2652: /*@C
    2653:    TSMonitorLGCtxCreate - Creates a line graph context for use with
    2654:    TS to monitor the solution process graphically in various ways

    2656:    Collective on TS

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

    2665:    Output Parameter:
    2666: .  ctx - the context

    2668:    Options Database Key:
    2669: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
    2670: .  -ts_monitor_lg_solution -
    2671: .  -ts_monitor_lg_error -
    2672: .  -ts_monitor_lg_ksp_iterations -
    2673: .  -ts_monitor_lg_snes_iterations -
    2674: -  -lg_indicate_data_points <true,false> - indicate the data points (at each time step) on the plot; default is true

    2676:    Notes:
    2677:    Use TSMonitorLGCtxDestroy() to destroy.

    2679:    Level: intermediate

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

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

    2685: @*/
    2686: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
    2687: {
    2688:   PetscDraw      win;
    2690:   PetscBool      flg = PETSC_TRUE;

    2693:   PetscNew(struct _n_TSMonitorLGCtx,ctx);
    2694:   PetscDrawCreate(comm,host,label,x,y,m,n,&win);
    2695:   PetscDrawSetFromOptions(win);
    2696:   PetscDrawLGCreate(win,1,&(*ctx)->lg);
    2697:   PetscOptionsGetBool(NULL,"-lg_indicate_data_points",&flg,NULL);
    2698:   if (flg) {
    2699:     PetscDrawLGIndicateDataPoints((*ctx)->lg);
    2700:   }
    2701:   PetscLogObjectParent((*ctx)->lg,win);
    2702:   (*ctx)->howoften = howoften;
    2703:   return(0);
    2704: }

    2708: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
    2709: {
    2710:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    2711:   PetscReal      x   = ptime,y;

    2715:   if (!step) {
    2716:     PetscDrawAxis axis;
    2717:     PetscDrawLGGetAxis(ctx->lg,&axis);
    2718:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time","Time step");
    2719:     PetscDrawLGReset(ctx->lg);
    2720:   }
    2721:   TSGetTimeStep(ts,&y);
    2722:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    2723:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    2724:     PetscDrawLGDraw(ctx->lg);
    2725:   }
    2726:   return(0);
    2727: }

    2731: /*@C
    2732:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
    2733:    with TSMonitorLGCtxCreate().

    2735:    Collective on TSMonitorLGCtx

    2737:    Input Parameter:
    2738: .  ctx - the monitor context

    2740:    Level: intermediate

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

    2744: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
    2745: @*/
    2746: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
    2747: {
    2748:   PetscDraw      draw;

    2752:   PetscDrawLGGetDraw((*ctx)->lg,&draw);
    2753:   PetscDrawDestroy(&draw);
    2754:   PetscDrawLGDestroy(&(*ctx)->lg);
    2755:   PetscFree(*ctx);
    2756:   return(0);
    2757: }

    2761: /*@
    2762:    TSGetTime - Gets the time of the most recently completed step.

    2764:    Not Collective

    2766:    Input Parameter:
    2767: .  ts - the TS context obtained from TSCreate()

    2769:    Output Parameter:
    2770: .  t  - the current time

    2772:    Level: beginner

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

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

    2780: .keywords: TS, get, time
    2781: @*/
    2782: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
    2783: {
    2787:   *t = ts->ptime;
    2788:   return(0);
    2789: }

    2793: /*@
    2794:    TSSetTime - Allows one to reset the time.

    2796:    Logically Collective on TS

    2798:    Input Parameters:
    2799: +  ts - the TS context obtained from TSCreate()
    2800: -  time - the time

    2802:    Level: intermediate

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

    2806: .keywords: TS, set, time
    2807: @*/
    2808: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
    2809: {
    2813:   ts->ptime = t;
    2814:   return(0);
    2815: }

    2819: /*@C
    2820:    TSSetOptionsPrefix - Sets the prefix used for searching for all
    2821:    TS options in the database.

    2823:    Logically Collective on TS

    2825:    Input Parameter:
    2826: +  ts     - The TS context
    2827: -  prefix - The prefix to prepend to all option names

    2829:    Notes:
    2830:    A hyphen (-) must NOT be given at the beginning of the prefix name.
    2831:    The first character of all runtime options is AUTOMATICALLY the
    2832:    hyphen.

    2834:    Level: advanced

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

    2838: .seealso: TSSetFromOptions()

    2840: @*/
    2841: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
    2842: {
    2844:   SNES           snes;

    2848:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
    2849:   TSGetSNES(ts,&snes);
    2850:   SNESSetOptionsPrefix(snes,prefix);
    2851:   return(0);
    2852: }

    2857: /*@C
    2858:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
    2859:    TS options in the database.

    2861:    Logically Collective on TS

    2863:    Input Parameter:
    2864: +  ts     - The TS context
    2865: -  prefix - The prefix to prepend to all option names

    2867:    Notes:
    2868:    A hyphen (-) must NOT be given at the beginning of the prefix name.
    2869:    The first character of all runtime options is AUTOMATICALLY the
    2870:    hyphen.

    2872:    Level: advanced

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

    2876: .seealso: TSGetOptionsPrefix()

    2878: @*/
    2879: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
    2880: {
    2882:   SNES           snes;

    2886:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
    2887:   TSGetSNES(ts,&snes);
    2888:   SNESAppendOptionsPrefix(snes,prefix);
    2889:   return(0);
    2890: }

    2894: /*@C
    2895:    TSGetOptionsPrefix - Sets the prefix used for searching for all
    2896:    TS options in the database.

    2898:    Not Collective

    2900:    Input Parameter:
    2901: .  ts - The TS context

    2903:    Output Parameter:
    2904: .  prefix - A pointer to the prefix string used

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

    2909:    Level: intermediate

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

    2913: .seealso: TSAppendOptionsPrefix()
    2914: @*/
    2915: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
    2916: {

    2922:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
    2923:   return(0);
    2924: }

    2928: /*@C
    2929:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

    2933:    Input Parameter:
    2934: .  ts  - The TS context obtained from TSCreate()

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

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

    2944:    Level: intermediate

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

    2948: .keywords: TS, timestep, get, matrix, Jacobian
    2949: @*/
    2950: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
    2951: {
    2953:   SNES           snes;
    2954:   DM             dm;

    2957:   TSGetSNES(ts,&snes);
    2958:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
    2959:   TSGetDM(ts,&dm);
    2960:   DMTSGetRHSJacobian(dm,func,ctx);
    2961:   return(0);
    2962: }

    2966: /*@C
    2967:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

    2971:    Input Parameter:
    2972: .  ts  - The TS context obtained from TSCreate()

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

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

    2982:    Level: advanced

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

    2986: .keywords: TS, timestep, get, matrix, Jacobian
    2987: @*/
    2988: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
    2989: {
    2991:   SNES           snes;
    2992:   DM             dm;

    2995:   TSGetSNES(ts,&snes);
    2996:   SNESSetUpMatrices(snes);
    2997:   SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
    2998:   TSGetDM(ts,&dm);
    2999:   DMTSGetIJacobian(dm,f,ctx);
    3000:   return(0);
    3001: }

    3006: /*@C
    3007:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
    3008:    VecView() for the solution at each timestep

    3010:    Collective on TS

    3012:    Input Parameters:
    3013: +  ts - the TS context
    3014: .  step - current time-step
    3015: .  ptime - current time
    3016: -  dummy - either a viewer or NULL

    3018:    Options Database:
    3019: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

    3021:    Notes: the initial solution and current solution are not displayed with a common axis scaling so generally the option -ts_monitor_draw_solution_initial
    3022:        will look bad

    3024:    Level: intermediate

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

    3028: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    3029: @*/
    3030: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    3031: {
    3032:   PetscErrorCode   ierr;
    3033:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
    3034:   PetscDraw        draw;

    3037:   if (!step && ictx->showinitial) {
    3038:     if (!ictx->initialsolution) {
    3039:       VecDuplicate(u,&ictx->initialsolution);
    3040:     }
    3041:     VecCopy(u,ictx->initialsolution);
    3042:   }
    3043:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

    3045:   if (ictx->showinitial) {
    3046:     PetscReal pause;
    3047:     PetscViewerDrawGetPause(ictx->viewer,&pause);
    3048:     PetscViewerDrawSetPause(ictx->viewer,0.0);
    3049:     VecView(ictx->initialsolution,ictx->viewer);
    3050:     PetscViewerDrawSetPause(ictx->viewer,pause);
    3051:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
    3052:   }
    3053:   VecView(u,ictx->viewer);
    3054:   if (ictx->showtimestepandtime) {
    3055:     PetscReal xl,yl,xr,yr,tw,w,h;
    3056:     char      time[32];
    3057:     size_t    len;

    3059:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
    3060:     PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);
    3061:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
    3062:      PetscStrlen(time,&len);
    3063:     PetscDrawStringGetSize(draw,&tw,NULL);
    3064:     w    = xl + .5*(xr - xl) - .5*len*tw;
    3065:     h    = yl + .95*(yr - yl);
    3066:     PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);
    3067:     PetscDrawFlush(draw);
    3068:   }

    3070:   if (ictx->showinitial) {
    3071:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
    3072:   }
    3073:   return(0);
    3074: }

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

    3081:    Collective on TS

    3083:    Input Parameters:
    3084: +  ts - the TS context
    3085: .  step - current time-step
    3086: .  ptime - current time
    3087: -  dummy - either a viewer or NULL

    3089:    Level: intermediate

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

    3093: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    3094: @*/
    3095: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    3096: {
    3097:   PetscErrorCode    ierr;
    3098:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
    3099:   PetscDraw         draw;
    3100:   MPI_Comm          comm;
    3101:   PetscInt          n;
    3102:   PetscMPIInt       size;
    3103:   PetscReal         xl,yl,xr,yr,tw,w,h;
    3104:   char              time[32];
    3105:   size_t            len;
    3106:   const PetscScalar *U;

    3109:   PetscObjectGetComm((PetscObject)ts,&comm);
    3110:   MPI_Comm_size(comm,&size);
    3111:   if (size != 1) SETERRQ(comm,PETSC_ERR_SUP,"Only allowed for sequential runs");
    3112:   VecGetSize(u,&n);
    3113:   if (n != 2) SETERRQ(comm,PETSC_ERR_SUP,"Only for ODEs with two unknowns");

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

    3117:   VecGetArrayRead(u,&U);
    3118:   PetscDrawAxisGetLimits(ictx->axis,&xl,&xr,&yl,&yr);
    3119:   if ((PetscRealPart(U[0]) < xl) || (PetscRealPart(U[1]) < yl) || (PetscRealPart(U[0]) > xr) || (PetscRealPart(U[1]) > yr)) {
    3120:       VecRestoreArrayRead(u,&U);
    3121:       return(0);
    3122:   }
    3123:   if (!step) ictx->color++;
    3124:   PetscDrawPoint(draw,PetscRealPart(U[0]),PetscRealPart(U[1]),ictx->color);
    3125:   VecRestoreArrayRead(u,&U);

    3127:   if (ictx->showtimestepandtime) {
    3128:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
    3129:     PetscSNPrintf(time,32,"Timestep %d Time %f",(int)step,(double)ptime);
    3130:     PetscStrlen(time,&len);
    3131:     PetscDrawStringGetSize(draw,&tw,NULL);
    3132:     w    = xl + .5*(xr - xl) - .5*len*tw;
    3133:     h    = yl + .95*(yr - yl);
    3134:     PetscDrawString(draw,w,h,PETSC_DRAW_BLACK,time);
    3135:   }
    3136:   PetscDrawFlush(draw);
    3137:   return(0);
    3138: }

    3143: /*@C
    3144:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

    3146:    Collective on TS

    3148:    Input Parameters:
    3149: .    ctx - the monitor context

    3151:    Level: intermediate

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

    3155: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
    3156: @*/
    3157: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
    3158: {

    3162:   PetscDrawAxisDestroy(&(*ictx)->axis);
    3163:   PetscViewerDestroy(&(*ictx)->viewer);
    3164:   VecDestroy(&(*ictx)->initialsolution);
    3165:   PetscFree(*ictx);
    3166:   return(0);
    3167: }

    3171: /*@C
    3172:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

    3174:    Collective on TS

    3176:    Input Parameter:
    3177: .    ts - time-step context

    3179:    Output Patameter:
    3180: .    ctx - the monitor context

    3182:    Options Database:
    3183: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

    3185:    Level: intermediate

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

    3189: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
    3190: @*/
    3191: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
    3192: {
    3193:   PetscErrorCode   ierr;

    3196:   PetscNew(struct _n_TSMonitorDrawCtx,ctx);
    3197:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
    3198:   PetscViewerSetFromOptions((*ctx)->viewer);

    3200:   (*ctx)->howoften    = howoften;
    3201:   (*ctx)->showinitial = PETSC_FALSE;
    3202:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

    3204:   (*ctx)->showtimestepandtime = PETSC_FALSE;
    3205:   PetscOptionsGetBool(NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
    3206:   (*ctx)->color = PETSC_DRAW_WHITE;
    3207:   return(0);
    3208: }

    3212: /*@C
    3213:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
    3214:    VecView() for the error at each timestep

    3216:    Collective on TS

    3218:    Input Parameters:
    3219: +  ts - the TS context
    3220: .  step - current time-step
    3221: .  ptime - current time
    3222: -  dummy - either a viewer or NULL

    3224:    Level: intermediate

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

    3228: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    3229: @*/
    3230: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    3231: {
    3232:   PetscErrorCode   ierr;
    3233:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
    3234:   PetscViewer      viewer = ctx->viewer;
    3235:   Vec              work;

    3238:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
    3239:   VecDuplicate(u,&work);
    3240:   TSComputeSolutionFunction(ts,ptime,work);
    3241:   VecAXPY(work,-1.0,u);
    3242:   VecView(work,viewer);
    3243:   VecDestroy(&work);
    3244:   return(0);
    3245: }

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

    3253:    Logically Collective on TS and DM

    3255:    Input Parameters:
    3256: +  ts - the preconditioner context
    3257: -  dm - the dm

    3259:    Level: intermediate

    3262: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
    3263: @*/
    3264: PetscErrorCode  TSSetDM(TS ts,DM dm)
    3265: {
    3267:   SNES           snes;
    3268:   DMTS           tsdm;

    3272:   PetscObjectReference((PetscObject)dm);
    3273:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
    3274:     if (ts->dm->dmts && !dm->dmts) {
    3275:       DMCopyDMTS(ts->dm,dm);
    3276:       DMGetDMTS(ts->dm,&tsdm);
    3277:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
    3278:         tsdm->originaldm = dm;
    3279:       }
    3280:     }
    3281:     DMDestroy(&ts->dm);
    3282:   }
    3283:   ts->dm = dm;

    3285:   TSGetSNES(ts,&snes);
    3286:   SNESSetDM(snes,dm);
    3287:   return(0);
    3288: }

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

    3295:    Not Collective

    3297:    Input Parameter:
    3298: . ts - the preconditioner context

    3300:    Output Parameter:
    3301: .  dm - the dm

    3303:    Level: intermediate

    3306: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
    3307: @*/
    3308: PetscErrorCode  TSGetDM(TS ts,DM *dm)
    3309: {

    3314:   if (!ts->dm) {
    3315:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
    3316:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
    3317:   }
    3318:   *dm = ts->dm;
    3319:   return(0);
    3320: }

    3324: /*@
    3325:    SNESTSFormFunction - Function to evaluate nonlinear residual

    3327:    Logically Collective on SNES

    3329:    Input Parameter:
    3330: + snes - nonlinear solver
    3331: . U - the current state at which to evaluate the residual
    3332: - ctx - user context, must be a TS

    3334:    Output Parameter:
    3335: . F - the nonlinear residual

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

    3341:    Level: advanced

    3343: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
    3344: @*/
    3345: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
    3346: {
    3347:   TS             ts = (TS)ctx;

    3355:   (ts->ops->snesfunction)(snes,U,F,ts);
    3356:   return(0);
    3357: }

    3361: /*@
    3362:    SNESTSFormJacobian - Function to evaluate the Jacobian

    3364:    Collective on SNES

    3366:    Input Parameter:
    3367: + snes - nonlinear solver
    3368: . U - the current state at which to evaluate the residual
    3369: - ctx - user context, must be a TS

    3371:    Output Parameter:
    3372: + A - the Jacobian
    3373: . B - the preconditioning matrix (may be the same as A)
    3374: - flag - indicates any structure change in the matrix

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

    3379:    Level: developer

    3381: .seealso: SNESSetJacobian()
    3382: @*/
    3383: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat *A,Mat *B,MatStructure *flag,void *ctx)
    3384: {
    3385:   TS             ts = (TS)ctx;

    3397:   (ts->ops->snesjacobian)(snes,U,A,B,flag,ts);
    3398:   return(0);
    3399: }

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

    3406:    Collective on TS

    3408:    Input Arguments:
    3409: +  ts - time stepping context
    3410: .  t - time at which to evaluate
    3411: .  U - state at which to evaluate
    3412: -  ctx - context

    3414:    Output Arguments:
    3415: .  F - right hand side

    3417:    Level: intermediate

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

    3423: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
    3424: @*/
    3425: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
    3426: {
    3428:   Mat            Arhs,Brhs;
    3429:   MatStructure   flg2;

    3432:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
    3433:   TSComputeRHSJacobian(ts,t,U,&Arhs,&Brhs,&flg2);
    3434:   MatMult(Arhs,U,F);
    3435:   return(0);
    3436: }

    3440: /*@C
    3441:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

    3443:    Collective on TS

    3445:    Input Arguments:
    3446: +  ts - time stepping context
    3447: .  t - time at which to evaluate
    3448: .  U - state at which to evaluate
    3449: -  ctx - context

    3451:    Output Arguments:
    3452: +  A - pointer to operator
    3453: .  B - pointer to preconditioning matrix
    3454: -  flg - matrix structure flag

    3456:    Level: intermediate

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

    3461: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
    3462: @*/
    3463: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat *A,Mat *B,MatStructure *flg,void *ctx)
    3464: {
    3466:   *flg = SAME_PRECONDITIONER;
    3467:   return(0);
    3468: }

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

    3475:    Collective on TS

    3477:    Input Arguments:
    3478: +  ts - time stepping context
    3479: .  t - time at which to evaluate
    3480: .  U - state at which to evaluate
    3481: .  Udot - time derivative of state vector
    3482: -  ctx - context

    3484:    Output Arguments:
    3485: .  F - left hand side

    3487:    Level: intermediate

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

    3495: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant()
    3496: @*/
    3497: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
    3498: {
    3500:   Mat            A,B;
    3501:   MatStructure   flg2;

    3504:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
    3505:   TSComputeIJacobian(ts,t,U,Udot,1.0,&A,&B,&flg2,PETSC_TRUE);
    3506:   MatMult(A,Udot,F);
    3507:   return(0);
    3508: }

    3512: /*@C
    3513:    TSComputeIJacobianConstant - Reuses a Jacobian that is time-independent.

    3515:    Collective on TS

    3517:    Input Arguments:
    3518: +  ts - time stepping context
    3519: .  t - time at which to evaluate
    3520: .  U - state at which to evaluate
    3521: .  Udot - time derivative of state vector
    3522: .  shift - shift to apply
    3523: -  ctx - context

    3525:    Output Arguments:
    3526: +  A - pointer to operator
    3527: .  B - pointer to preconditioning matrix
    3528: -  flg - matrix structure flag

    3530:    Level: intermediate

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

    3535: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
    3536: @*/
    3537: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flg,void *ctx)
    3538: {
    3540:   *flg = SAME_PRECONDITIONER;
    3541:   return(0);
    3542: }
    3545: /*@
    3546:    TSGetEquationType - Gets the type of the equation that TS is solving.

    3548:    Not Collective

    3550:    Input Parameter:
    3551: .  ts - the TS context

    3553:    Output Parameter:
    3554: .  equation_type - see TSEquationType

    3556:    Level: beginner

    3558: .keywords: TS, equation type

    3560: .seealso: TSSetEquationType(), TSEquationType
    3561: @*/
    3562: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
    3563: {
    3567:   *equation_type = ts->equation_type;
    3568:   return(0);
    3569: }

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

    3576:    Not Collective

    3578:    Input Parameter:
    3579: +  ts - the TS context
    3580: .  equation_type - see TSEquationType

    3582:    Level: advanced

    3584: .keywords: TS, equation type

    3586: .seealso: TSGetEquationType(), TSEquationType
    3587: @*/
    3588: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
    3589: {
    3592:   ts->equation_type = equation_type;
    3593:   return(0);
    3594: }

    3598: /*@
    3599:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

    3601:    Not Collective

    3603:    Input Parameter:
    3604: .  ts - the TS context

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

    3610:    Level: beginner

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

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

    3617: .seealso: TSSetConvergenceTest(), TSConvergedReason
    3618: @*/
    3619: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
    3620: {
    3624:   *reason = ts->reason;
    3625:   return(0);
    3626: }

    3630: /*@
    3631:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

    3633:    Not Collective

    3635:    Input Parameter:
    3636: +  ts - the TS context
    3637: .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
    3638:             manual pages for the individual convergence tests for complete lists

    3640:    Level: advanced

    3642:    Notes:
    3643:    Can only be called during TSSolve() is active.

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

    3647: .seealso: TSConvergedReason
    3648: @*/
    3649: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
    3650: {
    3653:   ts->reason = reason;
    3654:   return(0);
    3655: }

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

    3662:    Not Collective

    3664:    Input Parameter:
    3665: .  ts - the TS context

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

    3670:    Level: beginner

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

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

    3677: .seealso: TSSetConvergenceTest(), TSConvergedReason
    3678: @*/
    3679: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
    3680: {
    3684:   *ftime = ts->solvetime;
    3685:   return(0);
    3686: }

    3690: /*@
    3691:    TSGetSNESIterations - Gets the total number of nonlinear iterations
    3692:    used by the time integrator.

    3694:    Not Collective

    3696:    Input Parameter:
    3697: .  ts - TS context

    3699:    Output Parameter:
    3700: .  nits - number of nonlinear iterations

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

    3705:    Level: intermediate

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

    3709: .seealso:  TSGetKSPIterations()
    3710: @*/
    3711: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
    3712: {
    3716:   *nits = ts->snes_its;
    3717:   return(0);
    3718: }

    3722: /*@
    3723:    TSGetKSPIterations - Gets the total number of linear iterations
    3724:    used by the time integrator.

    3726:    Not Collective

    3728:    Input Parameter:
    3729: .  ts - TS context

    3731:    Output Parameter:
    3732: .  lits - number of linear iterations

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

    3737:    Level: intermediate

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

    3741: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
    3742: @*/
    3743: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
    3744: {
    3748:   *lits = ts->ksp_its;
    3749:   return(0);
    3750: }

    3754: /*@
    3755:    TSGetStepRejections - Gets the total number of rejected steps.

    3757:    Not Collective

    3759:    Input Parameter:
    3760: .  ts - TS context

    3762:    Output Parameter:
    3763: .  rejects - number of steps rejected

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

    3768:    Level: intermediate

    3770: .keywords: TS, get, number

    3772: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
    3773: @*/
    3774: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
    3775: {
    3779:   *rejects = ts->reject;
    3780:   return(0);
    3781: }

    3785: /*@
    3786:    TSGetSNESFailures - Gets the total number of failed SNES solves

    3788:    Not Collective

    3790:    Input Parameter:
    3791: .  ts - TS context

    3793:    Output Parameter:
    3794: .  fails - number of failed nonlinear solves

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

    3799:    Level: intermediate

    3801: .keywords: TS, get, number

    3803: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
    3804: @*/
    3805: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
    3806: {
    3810:   *fails = ts->num_snes_failures;
    3811:   return(0);
    3812: }

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

    3819:    Not Collective

    3821:    Input Parameter:
    3822: +  ts - TS context
    3823: -  rejects - maximum number of rejected steps, pass -1 for unlimited

    3825:    Notes:
    3826:    The counter is reset to zero for each step

    3828:    Options Database Key:
    3829:  .  -ts_max_reject - Maximum number of step rejections before a step fails

    3831:    Level: intermediate

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

    3835: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
    3836: @*/
    3837: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
    3838: {
    3841:   ts->max_reject = rejects;
    3842:   return(0);
    3843: }

    3847: /*@
    3848:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

    3850:    Not Collective

    3852:    Input Parameter:
    3853: +  ts - TS context
    3854: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

    3859:    Options Database Key:
    3860:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

    3862:    Level: intermediate

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

    3866: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
    3867: @*/
    3868: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
    3869: {
    3872:   ts->max_snes_failures = fails;
    3873:   return(0);
    3874: }

    3878: /*@
    3879:    TSSetErrorIfStepFails - Error if no step succeeds

    3881:    Not Collective

    3883:    Input Parameter:
    3884: +  ts - TS context
    3885: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

    3887:    Options Database Key:
    3888:  .  -ts_error_if_step_fails - Error if no step succeeds

    3890:    Level: intermediate

    3892: .keywords: TS, set, error

    3894: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
    3895: @*/
    3896: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
    3897: {
    3900:   ts->errorifstepfailed = err;
    3901:   return(0);
    3902: }

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

    3909:    Collective on TS

    3911:    Input Parameters:
    3912: +  ts - the TS context
    3913: .  step - current time-step
    3914: .  ptime - current time
    3915: .  u - current state
    3916: -  viewer - binary viewer

    3918:    Level: intermediate

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

    3922: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    3923: @*/
    3924: PetscErrorCode  TSMonitorSolutionBinary(TS ts,PetscInt step,PetscReal ptime,Vec u,void *viewer)
    3925: {
    3927:   PetscViewer    v = (PetscViewer)viewer;

    3930:   VecView(u,v);
    3931:   return(0);
    3932: }

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

    3939:    Collective on TS

    3941:    Input Parameters:
    3942: +  ts - the TS context
    3943: .  step - current time-step
    3944: .  ptime - current time
    3945: .  u - current state
    3946: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

    3948:    Level: intermediate

    3950:    Notes:
    3951:    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.
    3952:    These are named according to the file name template.

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

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

    3958: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    3959: @*/
    3960: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
    3961: {
    3963:   char           filename[PETSC_MAX_PATH_LEN];
    3964:   PetscViewer    viewer;

    3967:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
    3968:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
    3969:   VecView(u,viewer);
    3970:   PetscViewerDestroy(&viewer);
    3971:   return(0);
    3972: }

    3976: /*@C
    3977:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

    3979:    Collective on TS

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

    3984:    Level: intermediate

    3986:    Note:
    3987:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

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

    3991: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
    3992: @*/
    3993: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
    3994: {

    3998:   PetscFree(*(char**)filenametemplate);
    3999:   return(0);
    4000: }

    4004: /*@
    4005:    TSGetAdapt - Get the adaptive controller context for the current method

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

    4009:    Input Arguments:
    4010: .  ts - time stepping context

    4012:    Output Arguments:
    4013: .  adapt - adaptive controller

    4015:    Level: intermediate

    4017: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
    4018: @*/
    4019: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
    4020: {

    4026:   if (!ts->adapt) {
    4027:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
    4028:     PetscLogObjectParent(ts,ts->adapt);
    4029:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
    4030:   }
    4031:   *adapt = ts->adapt;
    4032:   return(0);
    4033: }

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

    4040:    Logically Collective

    4042:    Input Arguments:
    4043: +  ts - time integration context
    4044: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
    4045: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
    4046: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
    4047: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

    4049:    Level: beginner

    4051: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSGetTolerances()
    4052: @*/
    4053: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
    4054: {

    4058:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
    4059:   if (vatol) {
    4060:     PetscObjectReference((PetscObject)vatol);
    4061:     VecDestroy(&ts->vatol);

    4063:     ts->vatol = vatol;
    4064:   }
    4065:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
    4066:   if (vrtol) {
    4067:     PetscObjectReference((PetscObject)vrtol);
    4068:     VecDestroy(&ts->vrtol);

    4070:     ts->vrtol = vrtol;
    4071:   }
    4072:   return(0);
    4073: }

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

    4080:    Logically Collective

    4082:    Input Arguments:
    4083: .  ts - time integration context

    4085:    Output Arguments:
    4086: +  atol - scalar absolute tolerances, NULL to ignore
    4087: .  vatol - vector of absolute tolerances, NULL to ignore
    4088: .  rtol - scalar relative tolerances, NULL to ignore
    4089: -  vrtol - vector of relative tolerances, NULL to ignore

    4091:    Level: beginner

    4093: .seealso: TS, TSAdapt, TSVecNormWRMS(), TSSetTolerances()
    4094: @*/
    4095: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
    4096: {
    4098:   if (atol)  *atol  = ts->atol;
    4099:   if (vatol) *vatol = ts->vatol;
    4100:   if (rtol)  *rtol  = ts->rtol;
    4101:   if (vrtol) *vrtol = ts->vrtol;
    4102:   return(0);
    4103: }

    4107: /*@
    4108:    TSErrorNormWRMS - compute a weighted norm of the difference between a vector and the current state

    4110:    Collective on TS

    4112:    Input Arguments:
    4113: +  ts - time stepping context
    4114: -  Y - state vector to be compared to ts->vec_sol

    4116:    Output Arguments:
    4117: .  norm - weighted norm, a value of 1.0 is considered small

    4119:    Level: developer

    4121: .seealso: TSSetTolerances()
    4122: @*/
    4123: PetscErrorCode TSErrorNormWRMS(TS ts,Vec Y,PetscReal *norm)
    4124: {
    4125:   PetscErrorCode    ierr;
    4126:   PetscInt          i,n,N;
    4127:   const PetscScalar *u,*y;
    4128:   Vec               U;
    4129:   PetscReal         sum,gsum;

    4135:   U = ts->vec_sol;
    4137:   if (U == Y) SETERRQ(PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"Y cannot be the TS solution vector");

    4139:   VecGetSize(U,&N);
    4140:   VecGetLocalSize(U,&n);
    4141:   VecGetArrayRead(U,&u);
    4142:   VecGetArrayRead(Y,&y);
    4143:   sum  = 0.;
    4144:   if (ts->vatol && ts->vrtol) {
    4145:     const PetscScalar *atol,*rtol;
    4146:     VecGetArrayRead(ts->vatol,&atol);
    4147:     VecGetArrayRead(ts->vrtol,&rtol);
    4148:     for (i=0; i<n; i++) {
    4149:       PetscReal tol = PetscRealPart(atol[i]) + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    4150:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
    4151:     }
    4152:     VecRestoreArrayRead(ts->vatol,&atol);
    4153:     VecRestoreArrayRead(ts->vrtol,&rtol);
    4154:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
    4155:     const PetscScalar *atol;
    4156:     VecGetArrayRead(ts->vatol,&atol);
    4157:     for (i=0; i<n; i++) {
    4158:       PetscReal tol = PetscRealPart(atol[i]) + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    4159:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
    4160:     }
    4161:     VecRestoreArrayRead(ts->vatol,&atol);
    4162:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
    4163:     const PetscScalar *rtol;
    4164:     VecGetArrayRead(ts->vrtol,&rtol);
    4165:     for (i=0; i<n; i++) {
    4166:       PetscReal tol = ts->atol + PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    4167:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
    4168:     }
    4169:     VecRestoreArrayRead(ts->vrtol,&rtol);
    4170:   } else {                      /* scalar atol, scalar rtol */
    4171:     for (i=0; i<n; i++) {
    4172:       PetscReal tol = ts->atol + ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    4173:       sum += PetscSqr(PetscAbsScalar(y[i] - u[i]) / tol);
    4174:     }
    4175:   }
    4176:   VecRestoreArrayRead(U,&u);
    4177:   VecRestoreArrayRead(Y,&y);

    4179:   MPI_Allreduce(&sum,&gsum,1,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));
    4180:   *norm = PetscSqrtReal(gsum / N);
    4181:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
    4182:   return(0);
    4183: }

    4187: /*@
    4188:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

    4190:    Logically Collective on TS

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

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

    4199:    Level: intermediate

    4201: .seealso: TSGetCFLTime(), TSADAPTCFL
    4202: @*/
    4203: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
    4204: {
    4207:   ts->cfltime_local = cfltime;
    4208:   ts->cfltime       = -1.;
    4209:   return(0);
    4210: }

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

    4217:    Collective on TS

    4219:    Input Arguments:
    4220: .  ts - time stepping context

    4222:    Output Arguments:
    4223: .  cfltime - maximum stable time step for forward Euler

    4225:    Level: advanced

    4227: .seealso: TSSetCFLTimeLocal()
    4228: @*/
    4229: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
    4230: {

    4234:   if (ts->cfltime < 0) {
    4235:     MPI_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
    4236:   }
    4237:   *cfltime = ts->cfltime;
    4238:   return(0);
    4239: }

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

    4246:    Input Parameters:
    4247: .  ts   - the TS context.
    4248: .  xl   - lower bound.
    4249: .  xu   - upper bound.

    4251:    Notes:
    4252:    If this routine is not called then the lower and upper bounds are set to
    4253:    SNES_VI_NINF and SNES_VI_INF respectively during SNESSetUp().

    4255:    Level: advanced

    4257: @*/
    4258: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
    4259: {
    4261:   SNES           snes;

    4264:   TSGetSNES(ts,&snes);
    4265:   SNESVISetVariableBounds(snes,xl,xu);
    4266:   return(0);
    4267: }

    4269: #if defined(PETSC_HAVE_MATLAB_ENGINE)
    4270: #include <mex.h>

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

    4276: /*
    4277:    TSComputeFunction_Matlab - Calls the function that has been set with
    4278:                          TSSetFunctionMatlab().

    4280:    Collective on TS

    4282:    Input Parameters:
    4283: +  snes - the TS context
    4284: -  u - input vector

    4286:    Output Parameter:
    4287: .  y - function vector, as set by TSSetFunction()

    4289:    Notes:
    4290:    TSComputeFunction() is typically used within nonlinear solvers
    4291:    implementations, so most users would not generally call this routine
    4292:    themselves.

    4294:    Level: developer

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

    4298: .seealso: TSSetFunction(), TSGetFunction()
    4299: */
    4300: PetscErrorCode  TSComputeFunction_Matlab(TS snes,PetscReal time,Vec u,Vec udot,Vec y, void *ctx)
    4301: {
    4302:   PetscErrorCode  ierr;
    4303:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
    4304:   int             nlhs  = 1,nrhs = 7;
    4305:   mxArray         *plhs[1],*prhs[7];
    4306:   long long int   lx = 0,lxdot = 0,ly = 0,ls = 0;

    4316:   PetscMemcpy(&ls,&snes,sizeof(snes));
    4317:   PetscMemcpy(&lx,&u,sizeof(u));
    4318:   PetscMemcpy(&lxdot,&udot,sizeof(udot));
    4319:   PetscMemcpy(&ly,&y,sizeof(u));

    4321:   prhs[0] =  mxCreateDoubleScalar((double)ls);
    4322:   prhs[1] =  mxCreateDoubleScalar(time);
    4323:   prhs[2] =  mxCreateDoubleScalar((double)lx);
    4324:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
    4325:   prhs[4] =  mxCreateDoubleScalar((double)ly);
    4326:   prhs[5] =  mxCreateString(sctx->funcname);
    4327:   prhs[6] =  sctx->ctx;
    4328:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeFunctionInternal");
    4329:    mxGetScalar(plhs[0]);
    4330:   mxDestroyArray(prhs[0]);
    4331:   mxDestroyArray(prhs[1]);
    4332:   mxDestroyArray(prhs[2]);
    4333:   mxDestroyArray(prhs[3]);
    4334:   mxDestroyArray(prhs[4]);
    4335:   mxDestroyArray(prhs[5]);
    4336:   mxDestroyArray(plhs[0]);
    4337:   return(0);
    4338: }

    4343: /*
    4344:    TSSetFunctionMatlab - Sets the function evaluation routine and function
    4345:    vector for use by the TS routines in solving ODEs
    4346:    equations from MATLAB. Here the function is a string containing the name of a MATLAB function

    4348:    Logically Collective on TS

    4350:    Input Parameters:
    4351: +  ts - the TS context
    4352: -  func - function evaluation routine

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

    4357:    Level: beginner

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

    4361: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
    4362: */
    4363: PetscErrorCode  TSSetFunctionMatlab(TS ts,const char *func,mxArray *ctx)
    4364: {
    4365:   PetscErrorCode  ierr;
    4366:   TSMatlabContext *sctx;

    4369:   /* currently sctx is memory bleed */
    4370:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
    4371:   PetscStrallocpy(func,&sctx->funcname);
    4372:   /*
    4373:      This should work, but it doesn't
    4374:   sctx->ctx = ctx;
    4375:   mexMakeArrayPersistent(sctx->ctx);
    4376:   */
    4377:   sctx->ctx = mxDuplicateArray(ctx);

    4379:   TSSetIFunction(ts,NULL,TSComputeFunction_Matlab,sctx);
    4380:   return(0);
    4381: }

    4385: /*
    4386:    TSComputeJacobian_Matlab - Calls the function that has been set with
    4387:                          TSSetJacobianMatlab().

    4389:    Collective on TS

    4391:    Input Parameters:
    4392: +  ts - the TS context
    4393: .  u - input vector
    4394: .  A, B - the matrices
    4395: -  ctx - user context

    4397:    Output Parameter:
    4398: .  flag - structure of the matrix

    4400:    Level: developer

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

    4404: .seealso: TSSetFunction(), TSGetFunction()
    4405: @*/
    4406: PetscErrorCode  TSComputeJacobian_Matlab(TS ts,PetscReal time,Vec u,Vec udot,PetscReal shift,Mat *A,Mat *B,MatStructure *flag, void *ctx)
    4407: {
    4408:   PetscErrorCode  ierr;
    4409:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
    4410:   int             nlhs  = 2,nrhs = 9;
    4411:   mxArray         *plhs[2],*prhs[9];
    4412:   long long int   lx = 0,lxdot = 0,lA = 0,ls = 0, lB = 0;

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

    4420:   PetscMemcpy(&ls,&ts,sizeof(ts));
    4421:   PetscMemcpy(&lx,&u,sizeof(u));
    4422:   PetscMemcpy(&lxdot,&udot,sizeof(u));
    4423:   PetscMemcpy(&lA,A,sizeof(u));
    4424:   PetscMemcpy(&lB,B,sizeof(u));

    4426:   prhs[0] =  mxCreateDoubleScalar((double)ls);
    4427:   prhs[1] =  mxCreateDoubleScalar((double)time);
    4428:   prhs[2] =  mxCreateDoubleScalar((double)lx);
    4429:   prhs[3] =  mxCreateDoubleScalar((double)lxdot);
    4430:   prhs[4] =  mxCreateDoubleScalar((double)shift);
    4431:   prhs[5] =  mxCreateDoubleScalar((double)lA);
    4432:   prhs[6] =  mxCreateDoubleScalar((double)lB);
    4433:   prhs[7] =  mxCreateString(sctx->funcname);
    4434:   prhs[8] =  sctx->ctx;
    4435:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSComputeJacobianInternal");
    4436:    mxGetScalar(plhs[0]);
    4437:   *flag   =  (MatStructure) mxGetScalar(plhs[1]);
    4438:   mxDestroyArray(prhs[0]);
    4439:   mxDestroyArray(prhs[1]);
    4440:   mxDestroyArray(prhs[2]);
    4441:   mxDestroyArray(prhs[3]);
    4442:   mxDestroyArray(prhs[4]);
    4443:   mxDestroyArray(prhs[5]);
    4444:   mxDestroyArray(prhs[6]);
    4445:   mxDestroyArray(prhs[7]);
    4446:   mxDestroyArray(plhs[0]);
    4447:   mxDestroyArray(plhs[1]);
    4448:   return(0);
    4449: }

    4454: /*
    4455:    TSSetJacobianMatlab - Sets the Jacobian function evaluation routine and two empty Jacobian matrices
    4456:    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

    4458:    Logically Collective on TS

    4460:    Input Parameters:
    4461: +  ts - the TS context
    4462: .  A,B - Jacobian matrices
    4463: .  func - function evaluation routine
    4464: -  ctx - user context

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

    4470:    Level: developer

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

    4474: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
    4475: */
    4476: PetscErrorCode  TSSetJacobianMatlab(TS ts,Mat A,Mat B,const char *func,mxArray *ctx)
    4477: {
    4478:   PetscErrorCode  ierr;
    4479:   TSMatlabContext *sctx;

    4482:   /* currently sctx is memory bleed */
    4483:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
    4484:   PetscStrallocpy(func,&sctx->funcname);
    4485:   /*
    4486:      This should work, but it doesn't
    4487:   sctx->ctx = ctx;
    4488:   mexMakeArrayPersistent(sctx->ctx);
    4489:   */
    4490:   sctx->ctx = mxDuplicateArray(ctx);

    4492:   TSSetIJacobian(ts,A,B,TSComputeJacobian_Matlab,sctx);
    4493:   return(0);
    4494: }

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

    4501:    Collective on TS

    4503: .seealso: TSSetFunction(), TSGetFunction()
    4504: @*/
    4505: PetscErrorCode  TSMonitor_Matlab(TS ts,PetscInt it, PetscReal time,Vec u, void *ctx)
    4506: {
    4507:   PetscErrorCode  ierr;
    4508:   TSMatlabContext *sctx = (TSMatlabContext*)ctx;
    4509:   int             nlhs  = 1,nrhs = 6;
    4510:   mxArray         *plhs[1],*prhs[6];
    4511:   long long int   lx = 0,ls = 0;

    4517:   PetscMemcpy(&ls,&ts,sizeof(ts));
    4518:   PetscMemcpy(&lx,&u,sizeof(u));

    4520:   prhs[0] =  mxCreateDoubleScalar((double)ls);
    4521:   prhs[1] =  mxCreateDoubleScalar((double)it);
    4522:   prhs[2] =  mxCreateDoubleScalar((double)time);
    4523:   prhs[3] =  mxCreateDoubleScalar((double)lx);
    4524:   prhs[4] =  mxCreateString(sctx->funcname);
    4525:   prhs[5] =  sctx->ctx;
    4526:    mexCallMATLAB(nlhs,plhs,nrhs,prhs,"PetscTSMonitorInternal");
    4527:    mxGetScalar(plhs[0]);
    4528:   mxDestroyArray(prhs[0]);
    4529:   mxDestroyArray(prhs[1]);
    4530:   mxDestroyArray(prhs[2]);
    4531:   mxDestroyArray(prhs[3]);
    4532:   mxDestroyArray(prhs[4]);
    4533:   mxDestroyArray(plhs[0]);
    4534:   return(0);
    4535: }

    4540: /*
    4541:    TSMonitorSetMatlab - Sets the monitor function from Matlab

    4543:    Level: developer

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

    4547: .seealso: TSGetFunction(), TSComputeFunction(), TSSetJacobian(), TSSetFunction()
    4548: */
    4549: PetscErrorCode  TSMonitorSetMatlab(TS ts,const char *func,mxArray *ctx)
    4550: {
    4551:   PetscErrorCode  ierr;
    4552:   TSMatlabContext *sctx;

    4555:   /* currently sctx is memory bleed */
    4556:   PetscMalloc(sizeof(TSMatlabContext),&sctx);
    4557:   PetscStrallocpy(func,&sctx->funcname);
    4558:   /*
    4559:      This should work, but it doesn't
    4560:   sctx->ctx = ctx;
    4561:   mexMakeArrayPersistent(sctx->ctx);
    4562:   */
    4563:   sctx->ctx = mxDuplicateArray(ctx);

    4565:   TSMonitorSet(ts,TSMonitor_Matlab,sctx,NULL);
    4566:   return(0);
    4567: }
    4568: #endif

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

    4578:    Collective on TS

    4580:    Input Parameters:
    4581: +  ts - the TS context
    4582: .  step - current time-step
    4583: .  ptime - current time
    4584: -  lg - a line graph object

    4586:    Level: intermediate

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

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

    4592: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    4593: @*/
    4594: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4595: {
    4596:   PetscErrorCode    ierr;
    4597:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
    4598:   const PetscScalar *yy;
    4599:   PetscInt          dim;

    4602:   if (!step) {
    4603:     PetscDrawAxis axis;
    4604:     PetscDrawLGGetAxis(ctx->lg,&axis);
    4605:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
    4606:     VecGetLocalSize(u,&dim);
    4607:     PetscDrawLGSetDimension(ctx->lg,dim);
    4608:     PetscDrawLGReset(ctx->lg);
    4609:   }
    4610:   VecGetArrayRead(u,&yy);
    4611: #if defined(PETSC_USE_COMPLEX)
    4612:   {
    4613:     PetscReal *yreal;
    4614:     PetscInt  i,n;
    4615:     VecGetLocalSize(u,&n);
    4616:     PetscMalloc(n*sizeof(PetscReal),&yreal);
    4617:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
    4618:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
    4619:     PetscFree(yreal);
    4620:   }
    4621: #else
    4622:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
    4623: #endif
    4624:   VecRestoreArrayRead(u,&yy);
    4625:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    4626:     PetscDrawLGDraw(ctx->lg);
    4627:   }
    4628:   return(0);
    4629: }

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

    4637:    Collective on TS

    4639:    Input Parameters:
    4640: +  ts - the TS context
    4641: .  step - current time-step
    4642: .  ptime - current time
    4643: -  lg - a line graph object

    4645:    Level: intermediate

    4647:    Notes:
    4648:    Only for sequential solves.

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

    4652:    Options Database Keys:
    4653: .  -ts_monitor_lg_error - create a graphical monitor of error history

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

    4657: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
    4658: @*/
    4659: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4660: {
    4661:   PetscErrorCode    ierr;
    4662:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
    4663:   const PetscScalar *yy;
    4664:   Vec               y;
    4665:   PetscInt          dim;

    4668:   if (!step) {
    4669:     PetscDrawAxis axis;
    4670:     PetscDrawLGGetAxis(ctx->lg,&axis);
    4671:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Solution");
    4672:     VecGetLocalSize(u,&dim);
    4673:     PetscDrawLGSetDimension(ctx->lg,dim);
    4674:     PetscDrawLGReset(ctx->lg);
    4675:   }
    4676:   VecDuplicate(u,&y);
    4677:   TSComputeSolutionFunction(ts,ptime,y);
    4678:   VecAXPY(y,-1.0,u);
    4679:   VecGetArrayRead(y,&yy);
    4680: #if defined(PETSC_USE_COMPLEX)
    4681:   {
    4682:     PetscReal *yreal;
    4683:     PetscInt  i,n;
    4684:     VecGetLocalSize(y,&n);
    4685:     PetscMalloc(n*sizeof(PetscReal),&yreal);
    4686:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
    4687:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
    4688:     PetscFree(yreal);
    4689:   }
    4690: #else
    4691:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
    4692: #endif
    4693:   VecRestoreArrayRead(y,&yy);
    4694:   VecDestroy(&y);
    4695:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    4696:     PetscDrawLGDraw(ctx->lg);
    4697:   }
    4698:   return(0);
    4699: }

    4703: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
    4704: {
    4705:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    4706:   PetscReal      x   = ptime,y;
    4708:   PetscInt       its;

    4711:   if (!n) {
    4712:     PetscDrawAxis axis;

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

    4718:     ctx->snes_its = 0;
    4719:   }
    4720:   TSGetSNESIterations(ts,&its);
    4721:   y    = its - ctx->snes_its;
    4722:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    4723:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
    4724:     PetscDrawLGDraw(ctx->lg);
    4725:   }
    4726:   ctx->snes_its = its;
    4727:   return(0);
    4728: }

    4732: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
    4733: {
    4734:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    4735:   PetscReal      x   = ptime,y;
    4737:   PetscInt       its;

    4740:   if (!n) {
    4741:     PetscDrawAxis axis;

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

    4747:     ctx->ksp_its = 0;
    4748:   }
    4749:   TSGetKSPIterations(ts,&its);
    4750:   y    = its - ctx->ksp_its;
    4751:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    4752:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
    4753:     PetscDrawLGDraw(ctx->lg);
    4754:   }
    4755:   ctx->ksp_its = its;
    4756:   return(0);
    4757: }

    4761: /*@
    4762:    TSComputeLinearStability - computes the linear stability function at a point

    4764:    Collective on TS and Vec

    4766:    Input Parameters:
    4767: +  ts - the TS context
    4768: -  xr,xi - real and imaginary part of input arguments

    4770:    Output Parameters:
    4771: .  yr,yi - real and imaginary part of function value

    4773:    Level: developer

    4775: .keywords: TS, compute

    4777: .seealso: TSSetRHSFunction(), TSComputeIFunction()
    4778: @*/
    4779: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
    4780: {

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