Actual source code: ts.c

      1: #include <petsc/private/tsimpl.h>
      2: #include <petscdmshell.h>
      3: #include <petscdmda.h>
      4: #include <petscviewer.h>
      5: #include <petscdraw.h>
      6: #include <petscconvest.h>

      8: #define SkipSmallValue(a,b,tol) if (PetscAbsScalar(a)< tol || PetscAbsScalar(b)< tol) continue;

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

     14: const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",NULL};

     17: /*@C
     18:    TSMonitorSetFromOptions - Sets a monitor function and viewer appropriate for the type indicated by the user

     20:    Collective on TS

     22:    Input Parameters:
     23: +  ts - TS object you wish to monitor
     24: .  name - the monitor type one is seeking
     25: .  help - message indicating what monitoring is done
     26: .  manual - manual page for the monitor
     27: .  monitor - the monitor function
     28: -  monitorsetup - a function that is called once ONLY if the user selected this monitor that may set additional features of the TS or PetscViewer objects

     30:    Level: developer

     32: .seealso: PetscOptionsGetViewer(), PetscOptionsGetReal(), PetscOptionsHasName(), PetscOptionsGetString(),
     33:           PetscOptionsGetIntArray(), PetscOptionsGetRealArray(), PetscOptionsBool()
     34:           PetscOptionsInt(), PetscOptionsString(), PetscOptionsReal(), PetscOptionsBool(),
     35:           PetscOptionsName(), PetscOptionsBegin(), PetscOptionsEnd(), PetscOptionsHead(),
     36:           PetscOptionsStringArray(),PetscOptionsRealArray(), PetscOptionsScalar(),
     37:           PetscOptionsBoolGroupBegin(), PetscOptionsBoolGroup(), PetscOptionsBoolGroupEnd(),
     38:           PetscOptionsFList(), PetscOptionsEList()
     39: @*/
     40: PetscErrorCode  TSMonitorSetFromOptions(TS ts,const char name[],const char help[], const char manual[],PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,PetscViewerAndFormat*),PetscErrorCode (*monitorsetup)(TS,PetscViewerAndFormat*))
     41: {
     42:   PetscErrorCode    ierr;
     43:   PetscViewer       viewer;
     44:   PetscViewerFormat format;
     45:   PetscBool         flg;

     48:   PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts),((PetscObject) ts)->options,((PetscObject)ts)->prefix,name,&viewer,&format,&flg);
     49:   if (flg) {
     50:     PetscViewerAndFormat *vf;
     51:     PetscViewerAndFormatCreate(viewer,format,&vf);
     52:     PetscObjectDereference((PetscObject)viewer);
     53:     if (monitorsetup) {
     54:       (*monitorsetup)(ts,vf);
     55:     }
     56:     TSMonitorSet(ts,(PetscErrorCode (*)(TS,PetscInt,PetscReal,Vec,void*))monitor,vf,(PetscErrorCode (*)(void**))PetscViewerAndFormatDestroy);
     57:   }
     58:   return(0);
     59: }

     61: static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
     62: {

     68:   if (!((PetscObject)adapt)->type_name) {
     69:     TSAdaptSetType(adapt,default_type);
     70:   }
     71:   return(0);
     72: }

     74: /*@
     75:    TSSetFromOptions - Sets various TS parameters from user options.

     77:    Collective on TS

     79:    Input Parameter:
     80: .  ts - the TS context obtained from TSCreate()

     82:    Options Database Keys:
     83: +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP
     84: .  -ts_save_trajectory - checkpoint the solution at each time-step
     85: .  -ts_max_time <time> - maximum time to compute to
     86: .  -ts_max_steps <steps> - maximum number of time-steps to take
     87: .  -ts_init_time <time> - initial time to start computation
     88: .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
     89: .  -ts_dt <dt> - initial time step
     90: .  -ts_exact_final_time <stepover,interpolate,matchstep> - whether to stop at the exact given final time and how to compute the solution at that time
     91: .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
     92: .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
     93: .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
     94: .  -ts_rtol <rtol> - relative tolerance for local truncation error
     95: .  -ts_atol <atol> Absolute tolerance for local truncation error
     96: .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
     97: .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
     98: .  -ts_adjoint_solve <yes,no> After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
     99: .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
    100: .  -ts_monitor - print information at each timestep
    101: .  -ts_monitor_cancel - Cancel all monitors
    102: .  -ts_monitor_lg_solution - Monitor solution graphically
    103: .  -ts_monitor_lg_error - Monitor error graphically
    104: .  -ts_monitor_error - Monitors norm of error
    105: .  -ts_monitor_lg_timestep - Monitor timestep size graphically
    106: .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
    107: .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
    108: .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
    109: .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
    110: .  -ts_monitor_draw_solution - Monitor solution graphically
    111: .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
    112: .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
    113: .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
    114: .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03D.vts (filename-%%03D.vtu)
    115: -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time

    117:    Notes:
    118:      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.

    120:      Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
    121:      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
    122:      -snes_lag_preconditioner_persists true

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

    127:    Level: beginner

    129: .seealso: TSGetType()
    130: @*/
    131: PetscErrorCode  TSSetFromOptions(TS ts)
    132: {
    133:   PetscBool              opt,flg,tflg;
    134:   PetscErrorCode         ierr;
    135:   char                   monfilename[PETSC_MAX_PATH_LEN];
    136:   PetscReal              time_step;
    137:   TSExactFinalTimeOption eftopt;
    138:   char                   dir[16];
    139:   TSIFunction            ifun;
    140:   const char             *defaultType;
    141:   char                   typeName[256];

    146:   TSRegisterAll();
    147:   TSGetIFunction(ts,NULL,&ifun,NULL);

    149:   PetscObjectOptionsBegin((PetscObject)ts);
    150:   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
    151:   else defaultType = ifun ? TSBEULER : TSEULER;
    152:   PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt);
    153:   if (opt) {
    154:     TSSetType(ts,typeName);
    155:   } else {
    156:     TSSetType(ts,defaultType);
    157:   }

    159:   /* Handle generic TS options */
    160:   PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL);
    161:   PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL);
    162:   PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL);
    163:   PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL);
    164:   PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg);
    165:   if (flg) {TSSetTimeStep(ts,time_step);}
    166:   PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg);
    167:   if (flg) {TSSetExactFinalTime(ts,eftopt);}
    168:   PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL);
    169:   PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL);
    170:   PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL);
    171:   PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL);
    172:   PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL);

    174:   PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL);
    175:   PetscOptionsBool("-ts_rhs_jacobian_test_mult_transpose","Test the RHS Jacobian transpose for consistency with RHS at each solve ","None",ts->testjacobiantranspose,&ts->testjacobiantranspose,NULL);
    176:   PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL);
    177: #if defined(PETSC_HAVE_SAWS)
    178:   {
    179:     PetscBool set;
    180:     flg  = PETSC_FALSE;
    181:     PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set);
    182:     if (set) {
    183:       PetscObjectSAWsSetBlock((PetscObject)ts,flg);
    184:     }
    185:   }
    186: #endif

    188:   /* Monitor options */
    189:   TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL);
    190:   TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL);
    191:   TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL);

    193:   PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",NULL,monfilename,sizeof(monfilename),&flg);
    194:   if (flg) {PetscPythonMonitorSet((PetscObject)ts,monfilename);}

    196:   PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt);
    197:   if (opt) {
    198:     PetscInt       howoften = 1;
    199:     DM             dm;
    200:     PetscBool      net;

    202:     PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL);
    203:     TSGetDM(ts,&dm);
    204:     PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net);
    205:     if (net) {
    206:       TSMonitorLGCtxNetwork ctx;
    207:       TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx);
    208:       TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy);
    209:       PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL);
    210:     } else {
    211:       TSMonitorLGCtx ctx;
    212:       TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    213:       TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    214:     }
    215:   }

    217:   PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt);
    218:   if (opt) {
    219:     TSMonitorLGCtx ctx;
    220:     PetscInt       howoften = 1;

    222:     PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL);
    223:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    224:     TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    225:   }
    226:   TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL);

    228:   PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt);
    229:   if (opt) {
    230:     TSMonitorLGCtx ctx;
    231:     PetscInt       howoften = 1;

    233:     PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
    234:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    235:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    236:   }
    237:   PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt);
    238:   if (opt) {
    239:     TSMonitorLGCtx ctx;
    240:     PetscInt       howoften = 1;

    242:     PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL);
    243:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    244:     TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    245:     ctx->semilogy = PETSC_TRUE;
    246:   }

    248:   PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt);
    249:   if (opt) {
    250:     TSMonitorLGCtx ctx;
    251:     PetscInt       howoften = 1;

    253:     PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL);
    254:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    255:     TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    256:   }
    257:   PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt);
    258:   if (opt) {
    259:     TSMonitorLGCtx ctx;
    260:     PetscInt       howoften = 1;

    262:     PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL);
    263:     TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx);
    264:     TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy);
    265:   }
    266:   PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt);
    267:   if (opt) {
    268:     TSMonitorSPEigCtx ctx;
    269:     PetscInt          howoften = 1;

    271:     PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL);
    272:     TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    273:     TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy);
    274:   }
    275:   PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt);
    276:   if (opt) {
    277:     TSMonitorSPCtx  ctx;
    278:     PetscInt        howoften = 1;
    279:     PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm","TSMonitorSPSwarm",howoften,&howoften,NULL);
    280:     TSMonitorSPCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx);
    281:     TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy);
    282:   }
    283:   opt  = PETSC_FALSE;
    284:   PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt);
    285:   if (opt) {
    286:     TSMonitorDrawCtx ctx;
    287:     PetscInt         howoften = 1;

    289:     PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL);
    290:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    291:     TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
    292:   }
    293:   opt  = PETSC_FALSE;
    294:   PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt);
    295:   if (opt) {
    296:     TSMonitorDrawCtx ctx;
    297:     PetscReal        bounds[4];
    298:     PetscInt         n = 4;
    299:     PetscDraw        draw;
    300:     PetscDrawAxis    axis;

    302:     PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL);
    303:     if (n != 4) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
    304:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx);
    305:     PetscViewerDrawGetDraw(ctx->viewer,0,&draw);
    306:     PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis);
    307:     PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]);
    308:     PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2");
    309:     TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
    310:   }
    311:   opt  = PETSC_FALSE;
    312:   PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt);
    313:   if (opt) {
    314:     TSMonitorDrawCtx ctx;
    315:     PetscInt         howoften = 1;

    317:     PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL);
    318:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    319:     TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
    320:   }
    321:   opt  = PETSC_FALSE;
    322:   PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt);
    323:   if (opt) {
    324:     TSMonitorDrawCtx ctx;
    325:     PetscInt         howoften = 1;

    327:     PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL);
    328:     TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx);
    329:     TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy);
    330:   }

    332:   opt  = PETSC_FALSE;
    333:   PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03D.vts","TSMonitorSolutionVTK",NULL,monfilename,sizeof(monfilename),&flg);
    334:   if (flg) {
    335:     const char *ptr,*ptr2;
    336:     char       *filetemplate;
    337:     if (!monfilename[0]) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
    338:     /* Do some cursory validation of the input. */
    339:     PetscStrstr(monfilename,"%",(char**)&ptr);
    340:     if (!ptr) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03D.vts");
    341:     for (ptr++; ptr && *ptr; ptr++) {
    342:       PetscStrchr("DdiouxX",*ptr,(char**)&ptr2);
    343:       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");
    344:       if (ptr2) break;
    345:     }
    346:     PetscStrallocpy(monfilename,&filetemplate);
    347:     TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy);
    348:   }

    350:   PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,sizeof(dir),&flg);
    351:   if (flg) {
    352:     TSMonitorDMDARayCtx *rayctx;
    353:     int                  ray = 0;
    354:     DMDirection          ddir;
    355:     DM                   da;
    356:     PetscMPIInt          rank;

    358:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
    359:     if (dir[0] == 'x') ddir = DM_X;
    360:     else if (dir[0] == 'y') ddir = DM_Y;
    361:     else SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
    362:     sscanf(dir+2,"%d",&ray);

    364:     PetscInfo2(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray);
    365:     PetscNew(&rayctx);
    366:     TSGetDM(ts,&da);
    367:     DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter);
    368:     MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank);
    369:     if (!rank) {
    370:       PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,NULL,0,0,600,300,&rayctx->viewer);
    371:     }
    372:     rayctx->lgctx = NULL;
    373:     TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy);
    374:   }
    375:   PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,sizeof(dir),&flg);
    376:   if (flg) {
    377:     TSMonitorDMDARayCtx *rayctx;
    378:     int                 ray = 0;
    379:     DMDirection         ddir;
    380:     DM                  da;
    381:     PetscInt            howoften = 1;

    383:     if (dir[1] != '=') SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
    384:     if      (dir[0] == 'x') ddir = DM_X;
    385:     else if (dir[0] == 'y') ddir = DM_Y;
    386:     else SETERRQ1(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
    387:     sscanf(dir+2, "%d", &ray);

    389:     PetscInfo2(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray);
    390:     PetscNew(&rayctx);
    391:     TSGetDM(ts, &da);
    392:     DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter);
    393:     TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx);
    394:     TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy);
    395:   }

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

    401:     TSMonitorEnvelopeCtxCreate(ts,&ctx);
    402:     TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy);
    403:   }
    404:   flg  = PETSC_FALSE;
    405:   PetscOptionsBool("-ts_monitor_cancel","Remove all monitors","TSMonitorCancel",flg,&flg,&opt);
    406:   if (opt && flg) {TSMonitorCancel(ts);}

    408:   flg  = PETSC_FALSE;
    409:   PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL);
    410:   if (flg) {
    411:     DM   dm;
    412:     DMTS tdm;

    414:     TSGetDM(ts, &dm);
    415:     DMGetDMTS(dm, &tdm);
    416:     tdm->ijacobianctx = NULL;
    417:     TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL);
    418:     PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n");
    419:   }

    421:   /* Handle specific TS options */
    422:   if (ts->ops->setfromoptions) {
    423:     (*ts->ops->setfromoptions)(PetscOptionsObject,ts);
    424:   }

    426:   /* Handle TSAdapt options */
    427:   TSGetAdapt(ts,&ts->adapt);
    428:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);
    429:   TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt);

    431:   /* TS trajectory must be set after TS, since it may use some TS options above */
    432:   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
    433:   PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL);
    434:   if (tflg) {
    435:     TSSetSaveTrajectory(ts);
    436:   }

    438:   TSAdjointSetFromOptions(PetscOptionsObject,ts);

    440:   /* process any options handlers added with PetscObjectAddOptionsHandler() */
    441:   PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts);
    442:   PetscOptionsEnd();

    444:   if (ts->trajectory) {
    445:     TSTrajectorySetFromOptions(ts->trajectory,ts);
    446:   }

    448:   /* why do we have to do this here and not during TSSetUp? */
    449:   TSGetSNES(ts,&ts->snes);
    450:   if (ts->problem_type == TS_LINEAR) {
    451:     PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
    452:     if (!flg) { SNESSetType(ts->snes,SNESKSPONLY); }
    453:   }
    454:   SNESSetFromOptions(ts->snes);
    455:   return(0);
    456: }

    458: /*@
    459:    TSGetTrajectory - Gets the trajectory from a TS if it exists

    461:    Collective on TS

    463:    Input Parameters:
    464: .  ts - the TS context obtained from TSCreate()

    466:    Output Parameters:
    467: .  tr - the TSTrajectory object, if it exists

    469:    Note: This routine should be called after all TS options have been set

    471:    Level: advanced

    473: .seealso: TSGetTrajectory(), TSAdjointSolve(), TSTrajectory, TSTrajectoryCreate()

    475: @*/
    476: PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
    477: {
    480:   *tr = ts->trajectory;
    481:   return(0);
    482: }

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

    487:    Collective on TS

    489:    Input Parameters:
    490: .  ts - the TS context obtained from TSCreate()

    492:    Options Database:
    493: +  -ts_save_trajectory - saves the trajectory to a file
    494: -  -ts_trajectory_type type

    496: Note: This routine should be called after all TS options have been set

    498:     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
    499:    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m

    501:    Level: intermediate

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

    505: @*/
    506: PetscErrorCode  TSSetSaveTrajectory(TS ts)
    507: {

    512:   if (!ts->trajectory) {
    513:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
    514:   }
    515:   return(0);
    516: }

    518: /*@
    519:    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object

    521:    Collective on TS

    523:    Input Parameters:
    524: .  ts - the TS context obtained from TSCreate()

    526:    Level: intermediate

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

    530: @*/
    531: PetscErrorCode  TSResetTrajectory(TS ts)
    532: {

    537:   if (ts->trajectory) {
    538:     TSTrajectoryDestroy(&ts->trajectory);
    539:     TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory);
    540:   }
    541:   return(0);
    542: }

    544: /*@
    545:    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
    546:       set with TSSetRHSJacobian().

    548:    Collective on TS

    550:    Input Parameters:
    551: +  ts - the TS context
    552: .  t - current timestep
    553: -  U - input vector

    555:    Output Parameters:
    556: +  A - Jacobian matrix
    557: .  B - optional preconditioning matrix
    558: -  flag - flag indicating matrix structure

    560:    Notes:
    561:    Most users should not need to explicitly call this routine, as it
    562:    is used internally within the nonlinear solvers.

    564:    See KSPSetOperators() for important information about setting the
    565:    flag parameter.

    567:    Level: developer

    569: .seealso:  TSSetRHSJacobian(), KSPSetOperators()
    570: @*/
    571: PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
    572: {
    573:   PetscErrorCode   ierr;
    574:   PetscObjectState Ustate;
    575:   PetscObjectId    Uid;
    576:   DM               dm;
    577:   DMTS             tsdm;
    578:   TSRHSJacobian    rhsjacobianfunc;
    579:   void             *ctx;
    580:   TSRHSFunction    rhsfunction;

    586:   TSGetDM(ts,&dm);
    587:   DMGetDMTS(dm,&tsdm);
    588:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);
    589:   DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx);
    590:   PetscObjectStateGet((PetscObject)U,&Ustate);
    591:   PetscObjectGetId((PetscObject)U,&Uid);

    593:   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) return(0);

    595:   if (ts->rhsjacobian.shift && ts->rhsjacobian.reuse) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.",ts->rhsjacobian.shift);
    596:   if (rhsjacobianfunc) {
    597:     PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
    598:     PetscStackPush("TS user Jacobian function");
    599:     (*rhsjacobianfunc)(ts,t,U,A,B,ctx);
    600:     PetscStackPop;
    601:     ts->rhsjacs++;
    602:     PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
    603:   } else {
    604:     MatZeroEntries(A);
    605:     if (B && A != B) {MatZeroEntries(B);}
    606:   }
    607:   ts->rhsjacobian.time  = t;
    608:   ts->rhsjacobian.shift = 0;
    609:   ts->rhsjacobian.scale = 1.;
    610:   PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid);
    611:   PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate);
    612:   return(0);
    613: }

    615: /*@
    616:    TSComputeRHSFunction - Evaluates the right-hand-side function.

    618:    Collective on TS

    620:    Input Parameters:
    621: +  ts - the TS context
    622: .  t - current time
    623: -  U - state vector

    625:    Output Parameter:
    626: .  y - right hand side

    628:    Note:
    629:    Most users should not need to explicitly call this routine, as it
    630:    is used internally within the nonlinear solvers.

    632:    Level: developer

    634: .seealso: TSSetRHSFunction(), TSComputeIFunction()
    635: @*/
    636: PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
    637: {
    639:   TSRHSFunction  rhsfunction;
    640:   TSIFunction    ifunction;
    641:   void           *ctx;
    642:   DM             dm;

    648:   TSGetDM(ts,&dm);
    649:   DMTSGetRHSFunction(dm,&rhsfunction,&ctx);
    650:   DMTSGetIFunction(dm,&ifunction,NULL);

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

    654:   if (rhsfunction) {
    655:     PetscLogEventBegin(TS_FunctionEval,ts,U,y,0);
    656:     VecLockReadPush(U);
    657:     PetscStackPush("TS user right-hand-side function");
    658:     (*rhsfunction)(ts,t,U,y,ctx);
    659:     PetscStackPop;
    660:     VecLockReadPop(U);
    661:     ts->rhsfuncs++;
    662:     PetscLogEventEnd(TS_FunctionEval,ts,U,y,0);
    663:   } else {
    664:     VecZeroEntries(y);
    665:   }
    666:   return(0);
    667: }

    669: /*@
    670:    TSComputeSolutionFunction - Evaluates the solution function.

    672:    Collective on TS

    674:    Input Parameters:
    675: +  ts - the TS context
    676: -  t - current time

    678:    Output Parameter:
    679: .  U - the solution

    681:    Note:
    682:    Most users should not need to explicitly call this routine, as it
    683:    is used internally within the nonlinear solvers.

    685:    Level: developer

    687: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
    688: @*/
    689: PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
    690: {
    691:   PetscErrorCode     ierr;
    692:   TSSolutionFunction solutionfunction;
    693:   void               *ctx;
    694:   DM                 dm;

    699:   TSGetDM(ts,&dm);
    700:   DMTSGetSolutionFunction(dm,&solutionfunction,&ctx);

    702:   if (solutionfunction) {
    703:     PetscStackPush("TS user solution function");
    704:     (*solutionfunction)(ts,t,U,ctx);
    705:     PetscStackPop;
    706:   }
    707:   return(0);
    708: }
    709: /*@
    710:    TSComputeForcingFunction - Evaluates the forcing function.

    712:    Collective on TS

    714:    Input Parameters:
    715: +  ts - the TS context
    716: -  t - current time

    718:    Output Parameter:
    719: .  U - the function value

    721:    Note:
    722:    Most users should not need to explicitly call this routine, as it
    723:    is used internally within the nonlinear solvers.

    725:    Level: developer

    727: .seealso: TSSetSolutionFunction(), TSSetRHSFunction(), TSComputeIFunction()
    728: @*/
    729: PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
    730: {
    731:   PetscErrorCode     ierr, (*forcing)(TS,PetscReal,Vec,void*);
    732:   void               *ctx;
    733:   DM                 dm;

    738:   TSGetDM(ts,&dm);
    739:   DMTSGetForcingFunction(dm,&forcing,&ctx);

    741:   if (forcing) {
    742:     PetscStackPush("TS user forcing function");
    743:     (*forcing)(ts,t,U,ctx);
    744:     PetscStackPop;
    745:   }
    746:   return(0);
    747: }

    749: static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
    750: {
    751:   Vec            F;

    755:   *Frhs = NULL;
    756:   TSGetIFunction(ts,&F,NULL,NULL);
    757:   if (!ts->Frhs) {
    758:     VecDuplicate(F,&ts->Frhs);
    759:   }
    760:   *Frhs = ts->Frhs;
    761:   return(0);
    762: }

    764: PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
    765: {
    766:   Mat            A,B;
    768:   TSIJacobian    ijacobian;

    771:   if (Arhs) *Arhs = NULL;
    772:   if (Brhs) *Brhs = NULL;
    773:   TSGetIJacobian(ts,&A,&B,&ijacobian,NULL);
    774:   if (Arhs) {
    775:     if (!ts->Arhs) {
    776:       if (ijacobian) {
    777:         MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs);
    778:         TSSetMatStructure(ts,SAME_NONZERO_PATTERN);
    779:       } else {
    780:         ts->Arhs = A;
    781:         PetscObjectReference((PetscObject)A);
    782:       }
    783:     } else {
    784:       PetscBool flg;
    785:       SNESGetUseMatrixFree(ts->snes,NULL,&flg);
    786:       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
    787:       if (flg && !ijacobian && ts->Arhs == ts->Brhs){
    788:         PetscObjectDereference((PetscObject)ts->Arhs);
    789:         ts->Arhs = A;
    790:         PetscObjectReference((PetscObject)A);
    791:       }
    792:     }
    793:     *Arhs = ts->Arhs;
    794:   }
    795:   if (Brhs) {
    796:     if (!ts->Brhs) {
    797:       if (A != B) {
    798:         if (ijacobian) {
    799:           MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs);
    800:         } else {
    801:           ts->Brhs = B;
    802:           PetscObjectReference((PetscObject)B);
    803:         }
    804:       } else {
    805:         PetscObjectReference((PetscObject)ts->Arhs);
    806:         ts->Brhs = ts->Arhs;
    807:       }
    808:     }
    809:     *Brhs = ts->Brhs;
    810:   }
    811:   return(0);
    812: }

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

    817:    Collective on TS

    819:    Input Parameters:
    820: +  ts - the TS context
    821: .  t - current time
    822: .  U - state vector
    823: .  Udot - time derivative of state vector
    824: -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate

    826:    Output Parameter:
    827: .  Y - right hand side

    829:    Note:
    830:    Most users should not need to explicitly call this routine, as it
    831:    is used internally within the nonlinear solvers.

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

    836:    Level: developer

    838: .seealso: TSSetIFunction(), TSComputeRHSFunction()
    839: @*/
    840: PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
    841: {
    843:   TSIFunction    ifunction;
    844:   TSRHSFunction  rhsfunction;
    845:   void           *ctx;
    846:   DM             dm;

    854:   TSGetDM(ts,&dm);
    855:   DMTSGetIFunction(dm,&ifunction,&ctx);
    856:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

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

    860:   PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y);
    861:   if (ifunction) {
    862:     PetscStackPush("TS user implicit function");
    863:     (*ifunction)(ts,t,U,Udot,Y,ctx);
    864:     PetscStackPop;
    865:     ts->ifuncs++;
    866:   }
    867:   if (imex) {
    868:     if (!ifunction) {
    869:       VecCopy(Udot,Y);
    870:     }
    871:   } else if (rhsfunction) {
    872:     if (ifunction) {
    873:       Vec Frhs;
    874:       TSGetRHSVec_Private(ts,&Frhs);
    875:       TSComputeRHSFunction(ts,t,U,Frhs);
    876:       VecAXPY(Y,-1,Frhs);
    877:     } else {
    878:       TSComputeRHSFunction(ts,t,U,Y);
    879:       VecAYPX(Y,-1,Udot);
    880:     }
    881:   }
    882:   PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y);
    883:   return(0);
    884: }

    886: /*
    887:    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.

    889:    Note:
    890:    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().

    892: */
    893: static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
    894: {
    895:   PetscErrorCode   ierr;

    899:   if (A != ts->Arhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Amat");
    900:   if (B != ts->Brhs) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Bmat");

    902:   if (ts->rhsjacobian.shift) {
    903:     MatShift(A,-ts->rhsjacobian.shift);
    904:   }
    905:   if (ts->rhsjacobian.scale == -1.) {
    906:     MatScale(A,-1);
    907:   }
    908:   if (B && B == ts->Brhs && A != B) {
    909:     if (ts->rhsjacobian.shift) {
    910:       MatShift(B,-ts->rhsjacobian.shift);
    911:     }
    912:     if (ts->rhsjacobian.scale == -1.) {
    913:       MatScale(B,-1);
    914:     }
    915:   }
    916:   ts->rhsjacobian.shift = 0;
    917:   ts->rhsjacobian.scale = 1.;
    918:   return(0);
    919: }

    921: /*@
    922:    TSComputeIJacobian - Evaluates the Jacobian of the DAE

    924:    Collective on TS

    926:    Input
    927:       Input Parameters:
    928: +  ts - the TS context
    929: .  t - current timestep
    930: .  U - state vector
    931: .  Udot - time derivative of state vector
    932: .  shift - shift to apply, see note below
    933: -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate

    935:    Output Parameters:
    936: +  A - Jacobian matrix
    937: -  B - matrix from which the preconditioner is constructed; often the same as A

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

    942:    dF/dU + shift*dF/dUdot

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

    947:    Level: developer

    949: .seealso:  TSSetIJacobian()
    950: @*/
    951: PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
    952: {
    954:   TSIJacobian    ijacobian;
    955:   TSRHSJacobian  rhsjacobian;
    956:   DM             dm;
    957:   void           *ctx;

    968:   TSGetDM(ts,&dm);
    969:   DMTSGetIJacobian(dm,&ijacobian,&ctx);
    970:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

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

    974:   PetscLogEventBegin(TS_JacobianEval,ts,U,A,B);
    975:   if (ijacobian) {
    976:     PetscStackPush("TS user implicit Jacobian");
    977:     (*ijacobian)(ts,t,U,Udot,shift,A,B,ctx);
    978:     ts->ijacs++;
    979:     PetscStackPop;
    980:   }
    981:   if (imex) {
    982:     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
    983:       PetscBool assembled;
    984:       if (rhsjacobian) {
    985:         Mat Arhs = NULL;
    986:         TSGetRHSMats_Private(ts,&Arhs,NULL);
    987:         if (A == Arhs) {
    988:           if (rhsjacobian == TSComputeRHSJacobianConstant) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Unsupported operation! cannot use TSComputeRHSJacobianConstant"); /* there is no way to reconstruct shift*M-J since J cannot be reevaluated */
    989:           ts->rhsjacobian.time = PETSC_MIN_REAL;
    990:         }
    991:       }
    992:       MatZeroEntries(A);
    993:       MatAssembled(A,&assembled);
    994:       if (!assembled) {
    995:         MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY);
    996:         MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY);
    997:       }
    998:       MatShift(A,shift);
    999:       if (A != B) {
    1000:         MatZeroEntries(B);
    1001:         MatAssembled(B,&assembled);
    1002:         if (!assembled) {
    1003:           MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY);
    1004:           MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY);
    1005:         }
    1006:         MatShift(B,shift);
    1007:       }
    1008:     }
    1009:   } else {
    1010:     Mat Arhs = NULL,Brhs = NULL;
    1011:     if (rhsjacobian) { /* RHSJacobian needs to be converted to part of IJacobian if exists */
    1012:       TSGetRHSMats_Private(ts,&Arhs,&Brhs);
    1013:     }
    1014:     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
    1015:       PetscObjectState Ustate;
    1016:       PetscObjectId    Uid;
    1017:       TSRHSFunction    rhsfunction;

    1019:       DMTSGetRHSFunction(dm,&rhsfunction,NULL);
    1020:       PetscObjectStateGet((PetscObject)U,&Ustate);
    1021:       PetscObjectGetId((PetscObject)U,&Uid);
    1022:       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) && ts->rhsjacobian.scale == -1.) { /* No need to recompute RHSJacobian */
    1023:         MatShift(A,shift-ts->rhsjacobian.shift); /* revert the old shift and add the new shift with a single call to MatShift */
    1024:         if (A != B) {
    1025:           MatShift(B,shift-ts->rhsjacobian.shift);
    1026:         }
    1027:       } else {
    1028:         PetscBool flg;

    1030:         if (ts->rhsjacobian.reuse) { /* Undo the damage */
    1031:           /* MatScale has a short path for this case.
    1032:              However, this code path is taken the first time TSComputeRHSJacobian is called
    1033:              and the matrices have not been assembled yet */
    1034:           TSRecoverRHSJacobian(ts,A,B);
    1035:         }
    1036:         TSComputeRHSJacobian(ts,t,U,A,B);
    1037:         SNESGetUseMatrixFree(ts->snes,NULL,&flg);
    1038:         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
    1039:         if (!flg) {
    1040:           MatScale(A,-1);
    1041:           MatShift(A,shift);
    1042:         }
    1043:         if (A != B) {
    1044:           MatScale(B,-1);
    1045:           MatShift(B,shift);
    1046:         }
    1047:       }
    1048:       ts->rhsjacobian.scale = -1;
    1049:       ts->rhsjacobian.shift = shift;
    1050:     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
    1051:       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
    1052:         MatZeroEntries(A);
    1053:         MatShift(A,shift);
    1054:         if (A != B) {
    1055:           MatZeroEntries(B);
    1056:           MatShift(B,shift);
    1057:         }
    1058:       }
    1059:       TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
    1060:       MatAXPY(A,-1,Arhs,ts->axpy_pattern);
    1061:       if (A != B) {
    1062:         MatAXPY(B,-1,Brhs,ts->axpy_pattern);
    1063:       }
    1064:     }
    1065:   }
    1066:   PetscLogEventEnd(TS_JacobianEval,ts,U,A,B);
    1067:   return(0);
    1068: }

    1070: /*@C
    1071:     TSSetRHSFunction - Sets the routine for evaluating the function,
    1072:     where U_t = G(t,u).

    1074:     Logically Collective on TS

    1076:     Input Parameters:
    1077: +   ts - the TS context obtained from TSCreate()
    1078: .   r - vector to put the computed right hand side (or NULL to have it created)
    1079: .   f - routine for evaluating the right-hand-side function
    1080: -   ctx - [optional] user-defined context for private data for the
    1081:           function evaluation routine (may be NULL)

    1083:     Calling sequence of f:
    1084: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);

    1086: +   ts - timestep context
    1087: .   t - current timestep
    1088: .   u - input vector
    1089: .   F - function vector
    1090: -   ctx - [optional] user-defined function context

    1092:     Level: beginner

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

    1097: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSSetIFunction()
    1098: @*/
    1099: PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
    1100: {
    1102:   SNES           snes;
    1103:   Vec            ralloc = NULL;
    1104:   DM             dm;

    1110:   TSGetDM(ts,&dm);
    1111:   DMTSSetRHSFunction(dm,f,ctx);
    1112:   TSGetSNES(ts,&snes);
    1113:   if (!r && !ts->dm && ts->vec_sol) {
    1114:     VecDuplicate(ts->vec_sol,&ralloc);
    1115:     r = ralloc;
    1116:   }
    1117:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
    1118:   VecDestroy(&ralloc);
    1119:   return(0);
    1120: }

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

    1125:     Logically Collective on TS

    1127:     Input Parameters:
    1128: +   ts - the TS context obtained from TSCreate()
    1129: .   f - routine for evaluating the solution
    1130: -   ctx - [optional] user-defined context for private data for the
    1131:           function evaluation routine (may be NULL)

    1133:     Calling sequence of f:
    1134: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);

    1136: +   t - current timestep
    1137: .   u - output vector
    1138: -   ctx - [optional] user-defined function context

    1140:     Options Database:
    1141: +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
    1142: -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

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

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

    1151:     Level: beginner

    1153: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetForcingFunction(), TSSetSolution(), TSGetSolution(), TSMonitorLGError(), TSMonitorDrawError()
    1154: @*/
    1155: PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
    1156: {
    1158:   DM             dm;

    1162:   TSGetDM(ts,&dm);
    1163:   DMTSSetSolutionFunction(dm,f,ctx);
    1164:   return(0);
    1165: }

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

    1170:     Logically Collective on TS

    1172:     Input Parameters:
    1173: +   ts - the TS context obtained from TSCreate()
    1174: .   func - routine for evaluating the forcing function
    1175: -   ctx - [optional] user-defined context for private data for the
    1176:           function evaluation routine (may be NULL)

    1178:     Calling sequence of func:
    1179: $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);

    1181: +   t - current timestep
    1182: .   f - output vector
    1183: -   ctx - [optional] user-defined function context

    1185:     Notes:
    1186:     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
    1187:     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
    1188:     definition of the problem you are solving and hence possibly introducing bugs.

    1190:     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0

    1192:     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
    1193:     parameters can be passed in the ctx variable.

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

    1197:     Level: beginner

    1199: .seealso: TSSetRHSJacobian(), TSSetIJacobian(), TSComputeSolutionFunction(), TSSetSolutionFunction()
    1200: @*/
    1201: PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
    1202: {
    1204:   DM             dm;

    1208:   TSGetDM(ts,&dm);
    1209:   DMTSSetForcingFunction(dm,func,ctx);
    1210:   return(0);
    1211: }

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

    1217:    Logically Collective on TS

    1219:    Input Parameters:
    1220: +  ts  - the TS context obtained from TSCreate()
    1221: .  Amat - (approximate) Jacobian matrix
    1222: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
    1223: .  f   - the Jacobian evaluation routine
    1224: -  ctx - [optional] user-defined context for private data for the
    1225:          Jacobian evaluation routine (may be NULL)

    1227:    Calling sequence of f:
    1228: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);

    1230: +  t - current timestep
    1231: .  u - input vector
    1232: .  Amat - (approximate) Jacobian matrix
    1233: .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
    1234: -  ctx - [optional] user-defined context for matrix evaluation routine

    1236:    Notes:
    1237:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

    1239:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
    1240:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

    1242:    Level: beginner

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

    1246: @*/
    1247: PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
    1248: {
    1250:   SNES           snes;
    1251:   DM             dm;
    1252:   TSIJacobian    ijacobian;

    1261:   TSGetDM(ts,&dm);
    1262:   DMTSSetRHSJacobian(dm,f,ctx);
    1263:   DMTSGetIJacobian(dm,&ijacobian,NULL);
    1264:   TSGetSNES(ts,&snes);
    1265:   if (!ijacobian) {
    1266:     SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
    1267:   }
    1268:   if (Amat) {
    1269:     PetscObjectReference((PetscObject)Amat);
    1270:     MatDestroy(&ts->Arhs);
    1271:     ts->Arhs = Amat;
    1272:   }
    1273:   if (Pmat) {
    1274:     PetscObjectReference((PetscObject)Pmat);
    1275:     MatDestroy(&ts->Brhs);
    1276:     ts->Brhs = Pmat;
    1277:   }
    1278:   return(0);
    1279: }

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

    1284:    Logically Collective on TS

    1286:    Input Parameters:
    1287: +  ts  - the TS context obtained from TSCreate()
    1288: .  r   - vector to hold the residual (or NULL to have it created internally)
    1289: .  f   - the function evaluation routine
    1290: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

    1292:    Calling sequence of f:
    1293: $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);

    1295: +  t   - time at step/stage being solved
    1296: .  u   - state vector
    1297: .  u_t - time derivative of state vector
    1298: .  F   - function vector
    1299: -  ctx - [optional] user-defined context for matrix evaluation routine

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

    1304:    Level: beginner

    1306: .seealso: TSSetRHSJacobian(), TSSetRHSFunction(), TSSetIJacobian()
    1307: @*/
    1308: PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
    1309: {
    1311:   SNES           snes;
    1312:   Vec            ralloc = NULL;
    1313:   DM             dm;

    1319:   TSGetDM(ts,&dm);
    1320:   DMTSSetIFunction(dm,f,ctx);

    1322:   TSGetSNES(ts,&snes);
    1323:   if (!r && !ts->dm && ts->vec_sol) {
    1324:     VecDuplicate(ts->vec_sol,&ralloc);
    1325:     r  = ralloc;
    1326:   }
    1327:   SNESSetFunction(snes,r,SNESTSFormFunction,ts);
    1328:   VecDestroy(&ralloc);
    1329:   return(0);
    1330: }

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

    1335:    Not Collective

    1337:    Input Parameter:
    1338: .  ts - the TS context

    1340:    Output Parameter:
    1341: +  r - vector to hold residual (or NULL)
    1342: .  func - the function to compute residual (or NULL)
    1343: -  ctx - the function context (or NULL)

    1345:    Level: advanced

    1347: .seealso: TSSetIFunction(), SNESGetFunction()
    1348: @*/
    1349: PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
    1350: {
    1352:   SNES           snes;
    1353:   DM             dm;

    1357:   TSGetSNES(ts,&snes);
    1358:   SNESGetFunction(snes,r,NULL,NULL);
    1359:   TSGetDM(ts,&dm);
    1360:   DMTSGetIFunction(dm,func,ctx);
    1361:   return(0);
    1362: }

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

    1367:    Not Collective

    1369:    Input Parameter:
    1370: .  ts - the TS context

    1372:    Output Parameter:
    1373: +  r - vector to hold computed right hand side (or NULL)
    1374: .  func - the function to compute right hand side (or NULL)
    1375: -  ctx - the function context (or NULL)

    1377:    Level: advanced

    1379: .seealso: TSSetRHSFunction(), SNESGetFunction()
    1380: @*/
    1381: PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
    1382: {
    1384:   SNES           snes;
    1385:   DM             dm;

    1389:   TSGetSNES(ts,&snes);
    1390:   SNESGetFunction(snes,r,NULL,NULL);
    1391:   TSGetDM(ts,&dm);
    1392:   DMTSGetRHSFunction(dm,func,ctx);
    1393:   return(0);
    1394: }

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

    1400:    Logically Collective on TS

    1402:    Input Parameters:
    1403: +  ts  - the TS context obtained from TSCreate()
    1404: .  Amat - (approximate) Jacobian matrix
    1405: .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
    1406: .  f   - the Jacobian evaluation routine
    1407: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

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

    1412: +  t    - time at step/stage being solved
    1413: .  U    - state vector
    1414: .  U_t  - time derivative of state vector
    1415: .  a    - shift
    1416: .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
    1417: .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
    1418: -  ctx  - [optional] user-defined context for matrix evaluation routine

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

    1423:    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
    1424:    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.

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

    1433:    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value

    1435:    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
    1436:    You should not assume the values are the same in the next call to f() as you set them in the previous call.

    1438:    Level: beginner

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

    1442: @*/
    1443: PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
    1444: {
    1446:   SNES           snes;
    1447:   DM             dm;

    1456:   TSGetDM(ts,&dm);
    1457:   DMTSSetIJacobian(dm,f,ctx);

    1459:   TSGetSNES(ts,&snes);
    1460:   SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts);
    1461:   return(0);
    1462: }

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

    1470:    Logically Collective

    1472:    Input Arguments:
    1473: +  ts - TS context obtained from TSCreate()
    1474: -  reuse - PETSC_TRUE if the RHS Jacobian

    1476:    Level: intermediate

    1478: .seealso: TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
    1479: @*/
    1480: PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
    1481: {
    1483:   ts->rhsjacobian.reuse = reuse;
    1484:   return(0);
    1485: }

    1487: /*@C
    1488:    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.

    1490:    Logically Collective on TS

    1492:    Input Parameters:
    1493: +  ts  - the TS context obtained from TSCreate()
    1494: .  F   - vector to hold the residual (or NULL to have it created internally)
    1495: .  fun - the function evaluation routine
    1496: -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)

    1498:    Calling sequence of fun:
    1499: $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);

    1501: +  t    - time at step/stage being solved
    1502: .  U    - state vector
    1503: .  U_t  - time derivative of state vector
    1504: .  U_tt - second time derivative of state vector
    1505: .  F    - function vector
    1506: -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)

    1508:    Level: beginner

    1510: .seealso: TSSetI2Jacobian(), TSSetIFunction(), TSCreate(), TSSetRHSFunction()
    1511: @*/
    1512: PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
    1513: {
    1514:   DM             dm;

    1520:   TSSetIFunction(ts,F,NULL,NULL);
    1521:   TSGetDM(ts,&dm);
    1522:   DMTSSetI2Function(dm,fun,ctx);
    1523:   return(0);
    1524: }

    1526: /*@C
    1527:   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/contex to compute it.

    1529:   Not Collective

    1531:   Input Parameter:
    1532: . ts - the TS context

    1534:   Output Parameter:
    1535: + r - vector to hold residual (or NULL)
    1536: . fun - the function to compute residual (or NULL)
    1537: - ctx - the function context (or NULL)

    1539:   Level: advanced

    1541: .seealso: TSSetIFunction(), SNESGetFunction(), TSCreate()
    1542: @*/
    1543: PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
    1544: {
    1546:   SNES           snes;
    1547:   DM             dm;

    1551:   TSGetSNES(ts,&snes);
    1552:   SNESGetFunction(snes,r,NULL,NULL);
    1553:   TSGetDM(ts,&dm);
    1554:   DMTSGetI2Function(dm,fun,ctx);
    1555:   return(0);
    1556: }

    1558: /*@C
    1559:    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
    1560:         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().

    1562:    Logically Collective on TS

    1564:    Input Parameters:
    1565: +  ts  - the TS context obtained from TSCreate()
    1566: .  J   - Jacobian matrix
    1567: .  P   - preconditioning matrix for J (may be same as J)
    1568: .  jac - the Jacobian evaluation routine
    1569: -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)

    1571:    Calling sequence of jac:
    1572: $    PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);

    1574: +  t    - time at step/stage being solved
    1575: .  U    - state vector
    1576: .  U_t  - time derivative of state vector
    1577: .  U_tt - second time derivative of state vector
    1578: .  v    - shift for U_t
    1579: .  a    - shift for U_tt
    1580: .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
    1581: .  P    - preconditioning matrix for J, may be same as J
    1582: -  ctx  - [optional] user-defined context for matrix evaluation routine

    1584:    Notes:
    1585:    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.

    1587:    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
    1588:    the Jacobian of G(U) = F(t,U,W+v*U,W'+a*U) where F(t,U,U_t,U_tt) = 0 is the DAE to be solved.
    1589:    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
    1590:    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.

    1592:    Level: beginner

    1594: .seealso: TSSetI2Function(), TSGetI2Jacobian()
    1595: @*/
    1596: PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
    1597: {
    1598:   DM             dm;

    1605:   TSSetIJacobian(ts,J,P,NULL,NULL);
    1606:   TSGetDM(ts,&dm);
    1607:   DMTSSetI2Jacobian(dm,jac,ctx);
    1608:   return(0);
    1609: }

    1611: /*@C
    1612:   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.

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

    1616:   Input Parameter:
    1617: . ts  - The TS context obtained from TSCreate()

    1619:   Output Parameters:
    1620: + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
    1621: . P - The matrix from which the preconditioner is constructed, often the same as J
    1622: . jac - The function to compute the Jacobian matrices
    1623: - ctx - User-defined context for Jacobian evaluation routine

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

    1628:   Level: advanced

    1630: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber(), TSSetI2Jacobian(), TSGetI2Function(), TSCreate()

    1632: @*/
    1633: PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
    1634: {
    1636:   SNES           snes;
    1637:   DM             dm;

    1640:   TSGetSNES(ts,&snes);
    1641:   SNESSetUpMatrices(snes);
    1642:   SNESGetJacobian(snes,J,P,NULL,NULL);
    1643:   TSGetDM(ts,&dm);
    1644:   DMTSGetI2Jacobian(dm,jac,ctx);
    1645:   return(0);
    1646: }

    1648: /*@
    1649:   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0

    1651:   Collective on TS

    1653:   Input Parameters:
    1654: + ts - the TS context
    1655: . t - current time
    1656: . U - state vector
    1657: . V - time derivative of state vector (U_t)
    1658: - A - second time derivative of state vector (U_tt)

    1660:   Output Parameter:
    1661: . F - the residual vector

    1663:   Note:
    1664:   Most users should not need to explicitly call this routine, as it
    1665:   is used internally within the nonlinear solvers.

    1667:   Level: developer

    1669: .seealso: TSSetI2Function(), TSGetI2Function()
    1670: @*/
    1671: PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
    1672: {
    1673:   DM             dm;
    1674:   TSI2Function   I2Function;
    1675:   void           *ctx;
    1676:   TSRHSFunction  rhsfunction;

    1686:   TSGetDM(ts,&dm);
    1687:   DMTSGetI2Function(dm,&I2Function,&ctx);
    1688:   DMTSGetRHSFunction(dm,&rhsfunction,NULL);

    1690:   if (!I2Function) {
    1691:     TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE);
    1692:     return(0);
    1693:   }

    1695:   PetscLogEventBegin(TS_FunctionEval,ts,U,V,F);

    1697:   PetscStackPush("TS user implicit function");
    1698:   I2Function(ts,t,U,V,A,F,ctx);
    1699:   PetscStackPop;

    1701:   if (rhsfunction) {
    1702:     Vec Frhs;
    1703:     TSGetRHSVec_Private(ts,&Frhs);
    1704:     TSComputeRHSFunction(ts,t,U,Frhs);
    1705:     VecAXPY(F,-1,Frhs);
    1706:   }

    1708:   PetscLogEventEnd(TS_FunctionEval,ts,U,V,F);
    1709:   return(0);
    1710: }

    1712: /*@
    1713:   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE

    1715:   Collective on TS

    1717:   Input Parameters:
    1718: + ts - the TS context
    1719: . t - current timestep
    1720: . U - state vector
    1721: . V - time derivative of state vector
    1722: . A - second time derivative of state vector
    1723: . shiftV - shift to apply, see note below
    1724: - shiftA - shift to apply, see note below

    1726:   Output Parameters:
    1727: + J - Jacobian matrix
    1728: - P - optional preconditioning matrix

    1730:   Notes:
    1731:   If F(t,U,V,A)=0 is the DAE, the required Jacobian is

    1733:   dF/dU + shiftV*dF/dV + shiftA*dF/dA

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

    1738:   Level: developer

    1740: .seealso:  TSSetI2Jacobian()
    1741: @*/
    1742: PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
    1743: {
    1744:   DM             dm;
    1745:   TSI2Jacobian   I2Jacobian;
    1746:   void           *ctx;
    1747:   TSRHSJacobian  rhsjacobian;

    1758:   TSGetDM(ts,&dm);
    1759:   DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx);
    1760:   DMTSGetRHSJacobian(dm,&rhsjacobian,NULL);

    1762:   if (!I2Jacobian) {
    1763:     TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE);
    1764:     return(0);
    1765:   }

    1767:   PetscLogEventBegin(TS_JacobianEval,ts,U,J,P);

    1769:   PetscStackPush("TS user implicit Jacobian");
    1770:   I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx);
    1771:   PetscStackPop;

    1773:   if (rhsjacobian) {
    1774:     Mat Jrhs,Prhs;
    1775:     TSGetRHSMats_Private(ts,&Jrhs,&Prhs);
    1776:     TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs);
    1777:     MatAXPY(J,-1,Jrhs,ts->axpy_pattern);
    1778:     if (P != J) {MatAXPY(P,-1,Prhs,ts->axpy_pattern);}
    1779:   }

    1781:   PetscLogEventEnd(TS_JacobianEval,ts,U,J,P);
    1782:   return(0);
    1783: }

    1785: /*@C
    1786:    TSSetTransientVariable - sets function to transform from state to transient variables

    1788:    Logically Collective

    1790:    Input Arguments:
    1791: +  ts - time stepping context on which to change the transient variable
    1792: .  tvar - a function that transforms to transient variables
    1793: -  ctx - a context for tvar

    1795:     Calling sequence of tvar:
    1796: $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);

    1798: +   ts - timestep context
    1799: .   p - input vector (primative form)
    1800: .   c - output vector, transient variables (conservative form)
    1801: -   ctx - [optional] user-defined function context

    1803:    Level: advanced

    1805:    Notes:
    1806:    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
    1807:    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
    1808:    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
    1809:    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
    1810:    evaluated via the chain rule, as in

    1812:      dF/dP + shift * dF/dCdot dC/dP.

    1814: .seealso: DMTSSetTransientVariable(), DMTSGetTransientVariable(), TSSetIFunction(), TSSetIJacobian()
    1815: @*/
    1816: PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
    1817: {
    1819:   DM             dm;

    1823:   TSGetDM(ts,&dm);
    1824:   DMTSSetTransientVariable(dm,tvar,ctx);
    1825:   return(0);
    1826: }

    1828: /*@
    1829:    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables

    1831:    Logically Collective

    1833:    Input Parameters:
    1834: +  ts - TS on which to compute
    1835: -  U - state vector to be transformed to transient variables

    1837:    Output Parameters:
    1838: .  C - transient (conservative) variable

    1840:    Developer Notes:
    1841:    If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
    1842:    This makes it safe to call without a guard.  One can use TSHasTransientVariable() to check if transient variables are
    1843:    being used.

    1845:    Level: developer

    1847: .seealso: DMTSSetTransientVariable(), TSComputeIFunction(), TSComputeIJacobian()
    1848: @*/
    1849: PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
    1850: {
    1852:   DM             dm;
    1853:   DMTS           dmts;

    1858:   TSGetDM(ts,&dm);
    1859:   DMGetDMTS(dm,&dmts);
    1860:   if (dmts->ops->transientvar) {
    1862:     (*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx);
    1863:   }
    1864:   return(0);
    1865: }

    1867: /*@
    1868:    TSHasTransientVariable - determine whether transient variables have been set

    1870:    Logically Collective

    1872:    Input Parameters:
    1873: .  ts - TS on which to compute

    1875:    Output Parameters:
    1876: .  has - PETSC_TRUE if transient variables have been set

    1878:    Level: developer

    1880: .seealso: DMTSSetTransientVariable(), TSComputeTransientVariable()
    1881: @*/
    1882: PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
    1883: {
    1885:   DM             dm;
    1886:   DMTS           dmts;

    1890:   TSGetDM(ts,&dm);
    1891:   DMGetDMTS(dm,&dmts);
    1892:   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
    1893:   return(0);
    1894: }

    1896: /*@
    1897:    TS2SetSolution - Sets the initial solution and time derivative vectors
    1898:    for use by the TS routines handling second order equations.

    1900:    Logically Collective on TS

    1902:    Input Parameters:
    1903: +  ts - the TS context obtained from TSCreate()
    1904: .  u - the solution vector
    1905: -  v - the time derivative vector

    1907:    Level: beginner

    1909: @*/
    1910: PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
    1911: {

    1918:   TSSetSolution(ts,u);
    1919:   PetscObjectReference((PetscObject)v);
    1920:   VecDestroy(&ts->vec_dot);
    1921:   ts->vec_dot = v;
    1922:   return(0);
    1923: }

    1925: /*@
    1926:    TS2GetSolution - Returns the solution and time derivative at the present timestep
    1927:    for second order equations. It is valid to call this routine inside the function
    1928:    that you are evaluating in order to move to the new timestep. This vector not
    1929:    changed until the solution at the next timestep has been calculated.

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

    1933:    Input Parameter:
    1934: .  ts - the TS context obtained from TSCreate()

    1936:    Output Parameter:
    1937: +  u - the vector containing the solution
    1938: -  v - the vector containing the time derivative

    1940:    Level: intermediate

    1942: .seealso: TS2SetSolution(), TSGetTimeStep(), TSGetTime()

    1944: @*/
    1945: PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
    1946: {
    1951:   if (u) *u = ts->vec_sol;
    1952:   if (v) *v = ts->vec_dot;
    1953:   return(0);
    1954: }

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

    1959:   Collective on PetscViewer

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

    1966:    Level: intermediate

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

    1971:   Notes for advanced users:
    1972:   Most users should not need to know the details of the binary storage
    1973:   format, since TSLoad() and TSView() completely hide these details.
    1974:   But for anyone who's interested, the standard binary matrix storage
    1975:   format is
    1976: .vb
    1977:      has not yet been determined
    1978: .ve

    1980: .seealso: PetscViewerBinaryOpen(), TSView(), MatLoad(), VecLoad()
    1981: @*/
    1982: PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
    1983: {
    1985:   PetscBool      isbinary;
    1986:   PetscInt       classid;
    1987:   char           type[256];
    1988:   DMTS           sdm;
    1989:   DM             dm;

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

    1997:   PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT);
    1998:   if (classid != TS_FILE_CLASSID) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
    1999:   PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR);
    2000:   TSSetType(ts, type);
    2001:   if (ts->ops->load) {
    2002:     (*ts->ops->load)(ts,viewer);
    2003:   }
    2004:   DMCreate(PetscObjectComm((PetscObject)ts),&dm);
    2005:   DMLoad(dm,viewer);
    2006:   TSSetDM(ts,dm);
    2007:   DMCreateGlobalVector(ts->dm,&ts->vec_sol);
    2008:   VecLoad(ts->vec_sol,viewer);
    2009:   DMGetDMTS(ts->dm,&sdm);
    2010:   DMTSLoad(sdm,viewer);
    2011:   return(0);
    2012: }

    2014: #include <petscdraw.h>
    2015: #if defined(PETSC_HAVE_SAWS)
    2016: #include <petscviewersaws.h>
    2017: #endif

    2019: /*@C
    2020:    TSViewFromOptions - View from Options

    2022:    Collective on TS

    2024:    Input Parameters:
    2025: +  A - the application ordering context
    2026: .  obj - Optional object
    2027: -  name - command line option

    2029:    Level: intermediate
    2030: .seealso:  TS, TSView, PetscObjectViewFromOptions(), TSCreate()
    2031: @*/
    2032: PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
    2033: {

    2038:   PetscObjectViewFromOptions((PetscObject)A,obj,name);
    2039:   return(0);
    2040: }

    2042: /*@C
    2043:     TSView - Prints the TS data structure.

    2045:     Collective on TS

    2047:     Input Parameters:
    2048: +   ts - the TS context obtained from TSCreate()
    2049: -   viewer - visualization context

    2051:     Options Database Key:
    2052: .   -ts_view - calls TSView() at end of TSStep()

    2054:     Notes:
    2055:     The available visualization contexts include
    2056: +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
    2057: -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
    2058:          output where only the first processor opens
    2059:          the file.  All other processors send their
    2060:          data to the first processor to print.

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

    2065:     In the debugger you can do "call TSView(ts,0)" to display the TS solver. (The same holds for any PETSc object viewer).

    2067:     Level: beginner

    2069: .seealso: PetscViewerASCIIOpen()
    2070: @*/
    2071: PetscErrorCode  TSView(TS ts,PetscViewer viewer)
    2072: {
    2074:   TSType         type;
    2075:   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
    2076:   DMTS           sdm;
    2077: #if defined(PETSC_HAVE_SAWS)
    2078:   PetscBool      issaws;
    2079: #endif

    2083:   if (!viewer) {
    2084:     PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer);
    2085:   }

    2089:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
    2090:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring);
    2091:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary);
    2092:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw);
    2093: #if defined(PETSC_HAVE_SAWS)
    2094:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws);
    2095: #endif
    2096:   if (iascii) {
    2097:     PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer);
    2098:     if (ts->ops->view) {
    2099:       PetscViewerASCIIPushTab(viewer);
    2100:       (*ts->ops->view)(ts,viewer);
    2101:       PetscViewerASCIIPopTab(viewer);
    2102:     }
    2103:     if (ts->max_steps < PETSC_MAX_INT) {
    2104:       PetscViewerASCIIPrintf(viewer,"  maximum steps=%D\n",ts->max_steps);
    2105:     }
    2106:     if (ts->max_time < PETSC_MAX_REAL) {
    2107:       PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time);
    2108:     }
    2109:     if (ts->ifuncs) {
    2110:       PetscViewerASCIIPrintf(viewer,"  total number of I function evaluations=%D\n",ts->ifuncs);
    2111:     }
    2112:     if (ts->ijacs) {
    2113:       PetscViewerASCIIPrintf(viewer,"  total number of I Jacobian evaluations=%D\n",ts->ijacs);
    2114:     }
    2115:     if (ts->rhsfuncs) {
    2116:       PetscViewerASCIIPrintf(viewer,"  total number of RHS function evaluations=%D\n",ts->rhsfuncs);
    2117:     }
    2118:     if (ts->rhsjacs) {
    2119:       PetscViewerASCIIPrintf(viewer,"  total number of RHS Jacobian evaluations=%D\n",ts->rhsjacs);
    2120:     }
    2121:     if (ts->usessnes) {
    2122:       PetscBool lin;
    2123:       if (ts->problem_type == TS_NONLINEAR) {
    2124:         PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%D\n",ts->snes_its);
    2125:       }
    2126:       PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%D\n",ts->ksp_its);
    2127:       PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,"");
    2128:       PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%D\n",lin ? "" : "non",ts->num_snes_failures);
    2129:     }
    2130:     PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%D\n",ts->reject);
    2131:     if (ts->vrtol) {
    2132:       PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, ");
    2133:     } else {
    2134:       PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol);
    2135:     }
    2136:     if (ts->vatol) {
    2137:       PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n");
    2138:     } else {
    2139:       PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol);
    2140:     }
    2141:     PetscViewerASCIIPushTab(viewer);
    2142:     TSAdaptView(ts->adapt,viewer);
    2143:     PetscViewerASCIIPopTab(viewer);
    2144:   } else if (isstring) {
    2145:     TSGetType(ts,&type);
    2146:     PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type);
    2147:     if (ts->ops->view) {(*ts->ops->view)(ts,viewer);}
    2148:   } else if (isbinary) {
    2149:     PetscInt    classid = TS_FILE_CLASSID;
    2150:     MPI_Comm    comm;
    2151:     PetscMPIInt rank;
    2152:     char        type[256];

    2154:     PetscObjectGetComm((PetscObject)ts,&comm);
    2155:     MPI_Comm_rank(comm,&rank);
    2156:     if (!rank) {
    2157:       PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
    2158:       PetscStrncpy(type,((PetscObject)ts)->type_name,256);
    2159:       PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR);
    2160:     }
    2161:     if (ts->ops->view) {
    2162:       (*ts->ops->view)(ts,viewer);
    2163:     }
    2164:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
    2165:     DMView(ts->dm,viewer);
    2166:     VecView(ts->vec_sol,viewer);
    2167:     DMGetDMTS(ts->dm,&sdm);
    2168:     DMTSView(sdm,viewer);
    2169:   } else if (isdraw) {
    2170:     PetscDraw draw;
    2171:     char      str[36];
    2172:     PetscReal x,y,bottom,h;

    2174:     PetscViewerDrawGetDraw(viewer,0,&draw);
    2175:     PetscDrawGetCurrentPoint(draw,&x,&y);
    2176:     PetscStrcpy(str,"TS: ");
    2177:     PetscStrcat(str,((PetscObject)ts)->type_name);
    2178:     PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h);
    2179:     bottom = y - h;
    2180:     PetscDrawPushCurrentPoint(draw,x,bottom);
    2181:     if (ts->ops->view) {
    2182:       (*ts->ops->view)(ts,viewer);
    2183:     }
    2184:     if (ts->adapt) {TSAdaptView(ts->adapt,viewer);}
    2185:     if (ts->snes)  {SNESView(ts->snes,viewer);}
    2186:     PetscDrawPopCurrentPoint(draw);
    2187: #if defined(PETSC_HAVE_SAWS)
    2188:   } else if (issaws) {
    2189:     PetscMPIInt rank;
    2190:     const char  *name;

    2192:     PetscObjectGetName((PetscObject)ts,&name);
    2193:     MPI_Comm_rank(PETSC_COMM_WORLD,&rank);
    2194:     if (!((PetscObject)ts)->amsmem && !rank) {
    2195:       char       dir[1024];

    2197:       PetscObjectViewSAWs((PetscObject)ts,viewer);
    2198:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name);
    2199:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
    2200:       PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name);
    2201:       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
    2202:     }
    2203:     if (ts->ops->view) {
    2204:       (*ts->ops->view)(ts,viewer);
    2205:     }
    2206: #endif
    2207:   }
    2208:   if (ts->snes && ts->usessnes)  {
    2209:     PetscViewerASCIIPushTab(viewer);
    2210:     SNESView(ts->snes,viewer);
    2211:     PetscViewerASCIIPopTab(viewer);
    2212:   }
    2213:   DMGetDMTS(ts->dm,&sdm);
    2214:   DMTSView(sdm,viewer);

    2216:   PetscViewerASCIIPushTab(viewer);
    2217:   PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials);
    2218:   PetscViewerASCIIPopTab(viewer);
    2219:   return(0);
    2220: }

    2222: /*@
    2223:    TSSetApplicationContext - Sets an optional user-defined context for
    2224:    the timesteppers.

    2226:    Logically Collective on TS

    2228:    Input Parameters:
    2229: +  ts - the TS context obtained from TSCreate()
    2230: -  usrP - optional user context

    2232:    Fortran Notes:
    2233:     To use this from Fortran you must write a Fortran interface definition for this
    2234:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

    2236:    Level: intermediate

    2238: .seealso: TSGetApplicationContext()
    2239: @*/
    2240: PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
    2241: {
    2244:   ts->user = usrP;
    2245:   return(0);
    2246: }

    2248: /*@
    2249:     TSGetApplicationContext - Gets the user-defined context for the
    2250:     timestepper.

    2252:     Not Collective

    2254:     Input Parameter:
    2255: .   ts - the TS context obtained from TSCreate()

    2257:     Output Parameter:
    2258: .   usrP - user context

    2260:    Fortran Notes:
    2261:     To use this from Fortran you must write a Fortran interface definition for this
    2262:     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.

    2264:     Level: intermediate

    2266: .seealso: TSSetApplicationContext()
    2267: @*/
    2268: PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
    2269: {
    2272:   *(void**)usrP = ts->user;
    2273:   return(0);
    2274: }

    2276: /*@
    2277:    TSGetStepNumber - Gets the number of steps completed.

    2279:    Not Collective

    2281:    Input Parameter:
    2282: .  ts - the TS context obtained from TSCreate()

    2284:    Output Parameter:
    2285: .  steps - number of steps completed so far

    2287:    Level: intermediate

    2289: .seealso: TSGetTime(), TSGetTimeStep(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSSetPostStep()
    2290: @*/
    2291: PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
    2292: {
    2296:   *steps = ts->steps;
    2297:   return(0);
    2298: }

    2300: /*@
    2301:    TSSetStepNumber - Sets the number of steps completed.

    2303:    Logically Collective on TS

    2305:    Input Parameters:
    2306: +  ts - the TS context
    2307: -  steps - number of steps completed so far

    2309:    Notes:
    2310:    For most uses of the TS solvers the user need not explicitly call
    2311:    TSSetStepNumber(), as the step counter is appropriately updated in
    2312:    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
    2313:    reinitialize timestepping by setting the step counter to zero (and time
    2314:    to the initial time) to solve a similar problem with different initial
    2315:    conditions or parameters. Other possible use case is to continue
    2316:    timestepping from a previously interrupted run in such a way that TS
    2317:    monitors will be called with a initial nonzero step counter.

    2319:    Level: advanced

    2321: .seealso: TSGetStepNumber(), TSSetTime(), TSSetTimeStep(), TSSetSolution()
    2322: @*/
    2323: PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
    2324: {
    2328:   if (steps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
    2329:   ts->steps = steps;
    2330:   return(0);
    2331: }

    2333: /*@
    2334:    TSSetTimeStep - Allows one to reset the timestep at any time,
    2335:    useful for simple pseudo-timestepping codes.

    2337:    Logically Collective on TS

    2339:    Input Parameters:
    2340: +  ts - the TS context obtained from TSCreate()
    2341: -  time_step - the size of the timestep

    2343:    Level: intermediate

    2345: .seealso: TSGetTimeStep(), TSSetTime()

    2347: @*/
    2348: PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
    2349: {
    2353:   ts->time_step = time_step;
    2354:   return(0);
    2355: }

    2357: /*@
    2358:    TSSetExactFinalTime - Determines whether to adapt the final time step to
    2359:      match the exact final time, interpolate solution to the exact final time,
    2360:      or just return at the final time TS computed.

    2362:   Logically Collective on TS

    2364:    Input Parameter:
    2365: +   ts - the time-step context
    2366: -   eftopt - exact final time option

    2368: $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
    2369: $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
    2370: $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time

    2372:    Options Database:
    2373: .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime

    2375:    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
    2376:     then the final time you selected.

    2378:    Level: beginner

    2380: .seealso: TSExactFinalTimeOption, TSGetExactFinalTime()
    2381: @*/
    2382: PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
    2383: {
    2387:   ts->exact_final_time = eftopt;
    2388:   return(0);
    2389: }

    2391: /*@
    2392:    TSGetExactFinalTime - Gets the exact final time option.

    2394:    Not Collective

    2396:    Input Parameter:
    2397: .  ts - the TS context

    2399:    Output Parameter:
    2400: .  eftopt - exact final time option

    2402:    Level: beginner

    2404: .seealso: TSExactFinalTimeOption, TSSetExactFinalTime()
    2405: @*/
    2406: PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
    2407: {
    2411:   *eftopt = ts->exact_final_time;
    2412:   return(0);
    2413: }

    2415: /*@
    2416:    TSGetTimeStep - Gets the current timestep size.

    2418:    Not Collective

    2420:    Input Parameter:
    2421: .  ts - the TS context obtained from TSCreate()

    2423:    Output Parameter:
    2424: .  dt - the current timestep size

    2426:    Level: intermediate

    2428: .seealso: TSSetTimeStep(), TSGetTime()

    2430: @*/
    2431: PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
    2432: {
    2436:   *dt = ts->time_step;
    2437:   return(0);
    2438: }

    2440: /*@
    2441:    TSGetSolution - Returns the solution at the present timestep. It
    2442:    is valid to call this routine inside the function that you are evaluating
    2443:    in order to move to the new timestep. This vector not changed until
    2444:    the solution at the next timestep has been calculated.

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

    2448:    Input Parameter:
    2449: .  ts - the TS context obtained from TSCreate()

    2451:    Output Parameter:
    2452: .  v - the vector containing the solution

    2454:    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
    2455:    final time. It returns the solution at the next timestep.

    2457:    Level: intermediate

    2459: .seealso: TSGetTimeStep(), TSGetTime(), TSGetSolveTime(), TSGetSolutionComponents(), TSSetSolutionFunction()

    2461: @*/
    2462: PetscErrorCode  TSGetSolution(TS ts,Vec *v)
    2463: {
    2467:   *v = ts->vec_sol;
    2468:   return(0);
    2469: }

    2471: /*@
    2472:    TSGetSolutionComponents - Returns any solution components at the present
    2473:    timestep, if available for the time integration method being used.
    2474:    Solution components are quantities that share the same size and
    2475:    structure as the solution vector.

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

    2479:    Parameters :
    2480: +  ts - the TS context obtained from TSCreate() (input parameter).
    2481: .  n - If v is PETSC_NULL, then the number of solution components is
    2482:        returned through n, else the n-th solution component is
    2483:        returned in v.
    2484: -  v - the vector containing the n-th solution component
    2485:        (may be PETSC_NULL to use this function to find out
    2486:         the number of solutions components).

    2488:    Level: advanced

    2490: .seealso: TSGetSolution()

    2492: @*/
    2493: PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
    2494: {

    2499:   if (!ts->ops->getsolutioncomponents) *n = 0;
    2500:   else {
    2501:     (*ts->ops->getsolutioncomponents)(ts,n,v);
    2502:   }
    2503:   return(0);
    2504: }

    2506: /*@
    2507:    TSGetAuxSolution - Returns an auxiliary solution at the present
    2508:    timestep, if available for the time integration method being used.

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

    2512:    Parameters :
    2513: +  ts - the TS context obtained from TSCreate() (input parameter).
    2514: -  v - the vector containing the auxiliary solution

    2516:    Level: intermediate

    2518: .seealso: TSGetSolution()

    2520: @*/
    2521: PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
    2522: {

    2527:   if (ts->ops->getauxsolution) {
    2528:     (*ts->ops->getauxsolution)(ts,v);
    2529:   } else {
    2530:     VecZeroEntries(*v);
    2531:   }
    2532:   return(0);
    2533: }

    2535: /*@
    2536:    TSGetTimeError - Returns the estimated error vector, if the chosen
    2537:    TSType has an error estimation functionality.

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

    2541:    Note: MUST call after TSSetUp()

    2543:    Parameters :
    2544: +  ts - the TS context obtained from TSCreate() (input parameter).
    2545: .  n - current estimate (n=0) or previous one (n=-1)
    2546: -  v - the vector containing the error (same size as the solution).

    2548:    Level: intermediate

    2550: .seealso: TSGetSolution(), TSSetTimeError()

    2552: @*/
    2553: PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
    2554: {

    2559:   if (ts->ops->gettimeerror) {
    2560:     (*ts->ops->gettimeerror)(ts,n,v);
    2561:   } else {
    2562:     VecZeroEntries(*v);
    2563:   }
    2564:   return(0);
    2565: }

    2567: /*@
    2568:    TSSetTimeError - Sets the estimated error vector, if the chosen
    2569:    TSType has an error estimation functionality. This can be used
    2570:    to restart such a time integrator with a given error vector.

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

    2574:    Parameters :
    2575: +  ts - the TS context obtained from TSCreate() (input parameter).
    2576: -  v - the vector containing the error (same size as the solution).

    2578:    Level: intermediate

    2580: .seealso: TSSetSolution(), TSGetTimeError)

    2582: @*/
    2583: PetscErrorCode  TSSetTimeError(TS ts,Vec v)
    2584: {

    2589:   if (!ts->setupcalled) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
    2590:   if (ts->ops->settimeerror) {
    2591:     (*ts->ops->settimeerror)(ts,v);
    2592:   }
    2593:   return(0);
    2594: }

    2596: /* ----- Routines to initialize and destroy a timestepper ---- */
    2597: /*@
    2598:   TSSetProblemType - Sets the type of problem to be solved.

    2600:   Not collective

    2602:   Input Parameters:
    2603: + ts   - The TS
    2604: - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
    2605: .vb
    2606:          U_t - A U = 0      (linear)
    2607:          U_t - A(t) U = 0   (linear)
    2608:          F(t,U,U_t) = 0     (nonlinear)
    2609: .ve

    2611:    Level: beginner

    2613: .seealso: TSSetUp(), TSProblemType, TS
    2614: @*/
    2615: PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
    2616: {

    2621:   ts->problem_type = type;
    2622:   if (type == TS_LINEAR) {
    2623:     SNES snes;
    2624:     TSGetSNES(ts,&snes);
    2625:     SNESSetType(snes,SNESKSPONLY);
    2626:   }
    2627:   return(0);
    2628: }

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

    2633:   Not collective

    2635:   Input Parameter:
    2636: . ts   - The TS

    2638:   Output Parameter:
    2639: . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
    2640: .vb
    2641:          M U_t = A U
    2642:          M(t) U_t = A(t) U
    2643:          F(t,U,U_t)
    2644: .ve

    2646:    Level: beginner

    2648: .seealso: TSSetUp(), TSProblemType, TS
    2649: @*/
    2650: PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
    2651: {
    2655:   *type = ts->problem_type;
    2656:   return(0);
    2657: }

    2659: /*
    2660:     Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
    2661: */
    2662: static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
    2663: {
    2665:   PetscBool      isnone;

    2668:   TSGetAdapt(ts,&ts->adapt);
    2669:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

    2671:   PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone);
    2672:   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
    2673:     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
    2674:   } else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
    2675:     ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
    2676:   }
    2677:   return(0);
    2678: }

    2681: /*@
    2682:    TSSetUp - Sets up the internal data structures for the later use of a timestepper.

    2684:    Collective on TS

    2686:    Input Parameter:
    2687: .  ts - the TS context obtained from TSCreate()

    2689:    Notes:
    2690:    For basic use of the TS solvers the user need not explicitly call
    2691:    TSSetUp(), since these actions will automatically occur during
    2692:    the call to TSStep() or TSSolve().  However, if one wishes to control this
    2693:    phase separately, TSSetUp() should be called after TSCreate()
    2694:    and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().

    2696:    Level: advanced

    2698: .seealso: TSCreate(), TSStep(), TSDestroy(), TSSolve()
    2699: @*/
    2700: PetscErrorCode  TSSetUp(TS ts)
    2701: {
    2703:   DM             dm;
    2704:   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
    2705:   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
    2706:   TSIFunction    ifun;
    2707:   TSIJacobian    ijac;
    2708:   TSI2Jacobian   i2jac;
    2709:   TSRHSJacobian  rhsjac;

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

    2715:   if (!((PetscObject)ts)->type_name) {
    2716:     TSGetIFunction(ts,NULL,&ifun,NULL);
    2717:     TSSetType(ts,ifun ? TSBEULER : TSEULER);
    2718:   }

    2720:   if (!ts->vec_sol) {
    2721:     if (ts->dm) {
    2722:       DMCreateGlobalVector(ts->dm,&ts->vec_sol);
    2723:     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
    2724:   }

    2726:   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
    2727:     PetscObjectReference((PetscObject)ts->Jacprhs);
    2728:     ts->Jacp = ts->Jacprhs;
    2729:   }

    2731:   if (ts->quadraturets) {
    2732:     TSSetUp(ts->quadraturets);
    2733:     VecDestroy(&ts->vec_costintegrand);
    2734:     VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand);
    2735:   }

    2737:   TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL);
    2738:   if (rhsjac == TSComputeRHSJacobianConstant) {
    2739:     Mat Amat,Pmat;
    2740:     SNES snes;
    2741:     TSGetSNES(ts,&snes);
    2742:     SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL);
    2743:     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
    2744:      * have displaced the RHS matrix */
    2745:     if (Amat && Amat == ts->Arhs) {
    2746:       /* we need to copy the values of the matrix because for the constant Jacobian case the user will never set the numerical values in this new location */
    2747:       MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat);
    2748:       SNESSetJacobian(snes,Amat,NULL,NULL,NULL);
    2749:       MatDestroy(&Amat);
    2750:     }
    2751:     if (Pmat && Pmat == ts->Brhs) {
    2752:       MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat);
    2753:       SNESSetJacobian(snes,NULL,Pmat,NULL,NULL);
    2754:       MatDestroy(&Pmat);
    2755:     }
    2756:   }

    2758:   TSGetAdapt(ts,&ts->adapt);
    2759:   TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type);

    2761:   if (ts->ops->setup) {
    2762:     (*ts->ops->setup)(ts);
    2763:   }

    2765:   TSSetExactFinalTimeDefault(ts);

    2767:   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
    2768:      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
    2769:    */
    2770:   TSGetDM(ts,&dm);
    2771:   DMSNESGetFunction(dm,&func,NULL);
    2772:   if (!func) {
    2773:     DMSNESSetFunction(dm,SNESTSFormFunction,ts);
    2774:   }
    2775:   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
    2776:      Otherwise, the SNES will use coloring internally to form the Jacobian.
    2777:    */
    2778:   DMSNESGetJacobian(dm,&jac,NULL);
    2779:   DMTSGetIJacobian(dm,&ijac,NULL);
    2780:   DMTSGetI2Jacobian(dm,&i2jac,NULL);
    2781:   DMTSGetRHSJacobian(dm,&rhsjac,NULL);
    2782:   if (!jac && (ijac || i2jac || rhsjac)) {
    2783:     DMSNESSetJacobian(dm,SNESTSFormJacobian,ts);
    2784:   }

    2786:   /* if time integration scheme has a starting method, call it */
    2787:   if (ts->ops->startingmethod) {
    2788:     (*ts->ops->startingmethod)(ts);
    2789:   }

    2791:   ts->setupcalled = PETSC_TRUE;
    2792:   return(0);
    2793: }

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

    2798:    Collective on TS

    2800:    Input Parameter:
    2801: .  ts - the TS context obtained from TSCreate()

    2803:    Level: beginner

    2805: .seealso: TSCreate(), TSSetup(), TSDestroy()
    2806: @*/
    2807: PetscErrorCode  TSReset(TS ts)
    2808: {
    2809:   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
    2810:   PetscErrorCode  ierr;

    2815:   if (ts->ops->reset) {
    2816:     (*ts->ops->reset)(ts);
    2817:   }
    2818:   if (ts->snes) {SNESReset(ts->snes);}
    2819:   if (ts->adapt) {TSAdaptReset(ts->adapt);}

    2821:   MatDestroy(&ts->Arhs);
    2822:   MatDestroy(&ts->Brhs);
    2823:   VecDestroy(&ts->Frhs);
    2824:   VecDestroy(&ts->vec_sol);
    2825:   VecDestroy(&ts->vec_dot);
    2826:   VecDestroy(&ts->vatol);
    2827:   VecDestroy(&ts->vrtol);
    2828:   VecDestroyVecs(ts->nwork,&ts->work);

    2830:   MatDestroy(&ts->Jacprhs);
    2831:   MatDestroy(&ts->Jacp);
    2832:   if (ts->forward_solve) {
    2833:     TSForwardReset(ts);
    2834:   }
    2835:   if (ts->quadraturets) {
    2836:     TSReset(ts->quadraturets);
    2837:     VecDestroy(&ts->vec_costintegrand);
    2838:   }
    2839:   while (ilink) {
    2840:     next = ilink->next;
    2841:     TSDestroy(&ilink->ts);
    2842:     PetscFree(ilink->splitname);
    2843:     ISDestroy(&ilink->is);
    2844:     PetscFree(ilink);
    2845:     ilink = next;
    2846:   }
    2847:   ts->num_rhs_splits = 0;
    2848:   ts->setupcalled = PETSC_FALSE;
    2849:   return(0);
    2850: }

    2852: /*@C
    2853:    TSDestroy - Destroys the timestepper context that was created
    2854:    with TSCreate().

    2856:    Collective on TS

    2858:    Input Parameter:
    2859: .  ts - the TS context obtained from TSCreate()

    2861:    Level: beginner

    2863: .seealso: TSCreate(), TSSetUp(), TSSolve()
    2864: @*/
    2865: PetscErrorCode  TSDestroy(TS *ts)
    2866: {

    2870:   if (!*ts) return(0);
    2872:   if (--((PetscObject)(*ts))->refct > 0) {*ts = NULL; return(0);}

    2874:   TSReset(*ts);
    2875:   TSAdjointReset(*ts);
    2876:   if ((*ts)->forward_solve) {
    2877:     TSForwardReset(*ts);
    2878:   }
    2879:   /* if memory was published with SAWs then destroy it */
    2880:   PetscObjectSAWsViewOff((PetscObject)*ts);
    2881:   if ((*ts)->ops->destroy) {(*(*ts)->ops->destroy)((*ts));}

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

    2885:   TSAdaptDestroy(&(*ts)->adapt);
    2886:   TSEventDestroy(&(*ts)->event);

    2888:   SNESDestroy(&(*ts)->snes);
    2889:   DMDestroy(&(*ts)->dm);
    2890:   TSMonitorCancel((*ts));
    2891:   TSAdjointMonitorCancel((*ts));

    2893:   TSDestroy(&(*ts)->quadraturets);
    2894:   PetscHeaderDestroy(ts);
    2895:   return(0);
    2896: }

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

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

    2904:    Input Parameter:
    2905: .  ts - the TS context obtained from TSCreate()

    2907:    Output Parameter:
    2908: .  snes - the nonlinear solver context

    2910:    Notes:
    2911:    The user can then directly manipulate the SNES context to set various
    2912:    options, etc.  Likewise, the user can then extract and manipulate the
    2913:    KSP, KSP, and PC contexts as well.

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

    2918:    Level: beginner

    2920: @*/
    2921: PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
    2922: {

    2928:   if (!ts->snes) {
    2929:     SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes);
    2930:     PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options);
    2931:     SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
    2932:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes);
    2933:     PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1);
    2934:     if (ts->dm) {SNESSetDM(ts->snes,ts->dm);}
    2935:     if (ts->problem_type == TS_LINEAR) {
    2936:       SNESSetType(ts->snes,SNESKSPONLY);
    2937:     }
    2938:   }
    2939:   *snes = ts->snes;
    2940:   return(0);
    2941: }

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

    2946:    Collective

    2948:    Input Parameter:
    2949: +  ts - the TS context obtained from TSCreate()
    2950: -  snes - the nonlinear solver context

    2952:    Notes:
    2953:    Most users should have the TS created by calling TSGetSNES()

    2955:    Level: developer

    2957: @*/
    2958: PetscErrorCode TSSetSNES(TS ts,SNES snes)
    2959: {
    2961:   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);

    2966:   PetscObjectReference((PetscObject)snes);
    2967:   SNESDestroy(&ts->snes);

    2969:   ts->snes = snes;

    2971:   SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts);
    2972:   SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL);
    2973:   if (func == SNESTSFormJacobian) {
    2974:     SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts);
    2975:   }
    2976:   return(0);
    2977: }

    2979: /*@
    2980:    TSGetKSP - Returns the KSP (linear solver) associated with
    2981:    a TS (timestepper) context.

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

    2985:    Input Parameter:
    2986: .  ts - the TS context obtained from TSCreate()

    2988:    Output Parameter:
    2989: .  ksp - the nonlinear solver context

    2991:    Notes:
    2992:    The user can then directly manipulate the KSP context to set various
    2993:    options, etc.  Likewise, the user can then extract and manipulate the
    2994:    KSP and PC contexts as well.

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

    2999:    Level: beginner

    3001: @*/
    3002: PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
    3003: {
    3005:   SNES           snes;

    3010:   if (!((PetscObject)ts)->type_name) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
    3011:   if (ts->problem_type != TS_LINEAR) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
    3012:   TSGetSNES(ts,&snes);
    3013:   SNESGetKSP(snes,ksp);
    3014:   return(0);
    3015: }

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

    3019: /*@
    3020:    TSSetMaxSteps - Sets the maximum number of steps to use.

    3022:    Logically Collective on TS

    3024:    Input Parameters:
    3025: +  ts - the TS context obtained from TSCreate()
    3026: -  maxsteps - maximum number of steps to use

    3028:    Options Database Keys:
    3029: .  -ts_max_steps <maxsteps> - Sets maxsteps

    3031:    Notes:
    3032:    The default maximum number of steps is 5000

    3034:    Level: intermediate

    3036: .seealso: TSGetMaxSteps(), TSSetMaxTime(), TSSetExactFinalTime()
    3037: @*/
    3038: PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
    3039: {
    3043:   if (maxsteps < 0) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
    3044:   ts->max_steps = maxsteps;
    3045:   return(0);
    3046: }

    3048: /*@
    3049:    TSGetMaxSteps - Gets the maximum number of steps to use.

    3051:    Not Collective

    3053:    Input Parameters:
    3054: .  ts - the TS context obtained from TSCreate()

    3056:    Output Parameter:
    3057: .  maxsteps - maximum number of steps to use

    3059:    Level: advanced

    3061: .seealso: TSSetMaxSteps(), TSGetMaxTime(), TSSetMaxTime()
    3062: @*/
    3063: PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
    3064: {
    3068:   *maxsteps = ts->max_steps;
    3069:   return(0);
    3070: }

    3072: /*@
    3073:    TSSetMaxTime - Sets the maximum (or final) time for timestepping.

    3075:    Logically Collective on TS

    3077:    Input Parameters:
    3078: +  ts - the TS context obtained from TSCreate()
    3079: -  maxtime - final time to step to

    3081:    Options Database Keys:
    3082: .  -ts_max_time <maxtime> - Sets maxtime

    3084:    Notes:
    3085:    The default maximum time is 5.0

    3087:    Level: intermediate

    3089: .seealso: TSGetMaxTime(), TSSetMaxSteps(), TSSetExactFinalTime()
    3090: @*/
    3091: PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
    3092: {
    3096:   ts->max_time = maxtime;
    3097:   return(0);
    3098: }

    3100: /*@
    3101:    TSGetMaxTime - Gets the maximum (or final) time for timestepping.

    3103:    Not Collective

    3105:    Input Parameters:
    3106: .  ts - the TS context obtained from TSCreate()

    3108:    Output Parameter:
    3109: .  maxtime - final time to step to

    3111:    Level: advanced

    3113: .seealso: TSSetMaxTime(), TSGetMaxSteps(), TSSetMaxSteps()
    3114: @*/
    3115: PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
    3116: {
    3120:   *maxtime = ts->max_time;
    3121:   return(0);
    3122: }

    3124: /*@
    3125:    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().

    3127:    Level: deprecated

    3129: @*/
    3130: PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
    3131: {
    3135:   TSSetTime(ts,initial_time);
    3136:   TSSetTimeStep(ts,time_step);
    3137:   return(0);
    3138: }

    3140: /*@
    3141:    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().

    3143:    Level: deprecated

    3145: @*/
    3146: PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
    3147: {
    3150:   if (maxsteps) {
    3152:     *maxsteps = ts->max_steps;
    3153:   }
    3154:   if (maxtime) {
    3156:     *maxtime = ts->max_time;
    3157:   }
    3158:   return(0);
    3159: }

    3161: /*@
    3162:    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().

    3164:    Level: deprecated

    3166: @*/
    3167: PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
    3168: {
    3173:   if (maxsteps >= 0) ts->max_steps = maxsteps;
    3174:   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
    3175:   return(0);
    3176: }

    3178: /*@
    3179:    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().

    3181:    Level: deprecated

    3183: @*/
    3184: PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

    3186: /*@
    3187:    TSGetTotalSteps - Deprecated, use TSGetStepNumber().

    3189:    Level: deprecated

    3191: @*/
    3192: PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }

    3194: /*@
    3195:    TSSetSolution - Sets the initial solution vector
    3196:    for use by the TS routines.

    3198:    Logically Collective on TS

    3200:    Input Parameters:
    3201: +  ts - the TS context obtained from TSCreate()
    3202: -  u - the solution vector

    3204:    Level: beginner

    3206: .seealso: TSSetSolutionFunction(), TSGetSolution(), TSCreate()
    3207: @*/
    3208: PetscErrorCode  TSSetSolution(TS ts,Vec u)
    3209: {
    3211:   DM             dm;

    3216:   PetscObjectReference((PetscObject)u);
    3217:   VecDestroy(&ts->vec_sol);
    3218:   ts->vec_sol = u;

    3220:   TSGetDM(ts,&dm);
    3221:   DMShellSetGlobalVector(dm,u);
    3222:   return(0);
    3223: }

    3225: /*@C
    3226:   TSSetPreStep - Sets the general-purpose function
    3227:   called once at the beginning of each time step.

    3229:   Logically Collective on TS

    3231:   Input Parameters:
    3232: + ts   - The TS context obtained from TSCreate()
    3233: - func - The function

    3235:   Calling sequence of func:
    3236: .   PetscErrorCode func (TS ts);

    3238:   Level: intermediate

    3240: .seealso: TSSetPreStage(), TSSetPostStage(), TSSetPostStep(), TSStep(), TSRestartStep()
    3241: @*/
    3242: PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
    3243: {
    3246:   ts->prestep = func;
    3247:   return(0);
    3248: }

    3250: /*@
    3251:   TSPreStep - Runs the user-defined pre-step function.

    3253:   Collective on TS

    3255:   Input Parameters:
    3256: . ts   - The TS context obtained from TSCreate()

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

    3262:   Level: developer

    3264: .seealso: TSSetPreStep(), TSPreStage(), TSPostStage(), TSPostStep()
    3265: @*/
    3266: PetscErrorCode  TSPreStep(TS ts)
    3267: {

    3272:   if (ts->prestep) {
    3273:     Vec              U;
    3274:     PetscObjectState sprev,spost;

    3276:     TSGetSolution(ts,&U);
    3277:     PetscObjectStateGet((PetscObject)U,&sprev);
    3278:     PetscStackCallStandard((*ts->prestep),(ts));
    3279:     PetscObjectStateGet((PetscObject)U,&spost);
    3280:     if (sprev != spost) {TSRestartStep(ts);}
    3281:   }
    3282:   return(0);
    3283: }

    3285: /*@C
    3286:   TSSetPreStage - Sets the general-purpose function
    3287:   called once at the beginning of each stage.

    3289:   Logically Collective on TS

    3291:   Input Parameters:
    3292: + ts   - The TS context obtained from TSCreate()
    3293: - func - The function

    3295:   Calling sequence of func:
    3296: .    PetscErrorCode func(TS ts, PetscReal stagetime);

    3298:   Level: intermediate

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

    3305: .seealso: TSSetPostStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
    3306: @*/
    3307: PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
    3308: {
    3311:   ts->prestage = func;
    3312:   return(0);
    3313: }

    3315: /*@C
    3316:   TSSetPostStage - Sets the general-purpose function
    3317:   called once at the end of each stage.

    3319:   Logically Collective on TS

    3321:   Input Parameters:
    3322: + ts   - The TS context obtained from TSCreate()
    3323: - func - The function

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

    3328:   Level: intermediate

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

    3335: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
    3336: @*/
    3337: PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
    3338: {
    3341:   ts->poststage = func;
    3342:   return(0);
    3343: }

    3345: /*@C
    3346:   TSSetPostEvaluate - Sets the general-purpose function
    3347:   called once at the end of each step evaluation.

    3349:   Logically Collective on TS

    3351:   Input Parameters:
    3352: + ts   - The TS context obtained from TSCreate()
    3353: - func - The function

    3355:   Calling sequence of func:
    3356: . PetscErrorCode func(TS ts);

    3358:   Level: intermediate

    3360:   Note:
    3361:   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
    3362:   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
    3363:   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
    3364:   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
    3365:   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()

    3367: .seealso: TSSetPreStage(), TSSetPreStep(), TSSetPostStep(), TSGetApplicationContext()
    3368: @*/
    3369: PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
    3370: {
    3373:   ts->postevaluate = func;
    3374:   return(0);
    3375: }

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

    3380:   Collective on TS

    3382:   Input Parameters:
    3383: . ts          - The TS context obtained from TSCreate()
    3384:   stagetime   - The absolute time of the current stage

    3386:   Notes:
    3387:   TSPreStage() is typically used within time stepping implementations,
    3388:   most users would not generally call this routine themselves.

    3390:   Level: developer

    3392: .seealso: TSPostStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
    3393: @*/
    3394: PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
    3395: {
    3398:   if (ts->prestage) {
    3399:     PetscStackCallStandard((*ts->prestage),(ts,stagetime));
    3400:   }
    3401:   return(0);
    3402: }

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

    3407:   Collective on TS

    3409:   Input Parameters:
    3410: . ts          - The TS context obtained from TSCreate()
    3411:   stagetime   - The absolute time of the current stage
    3412:   stageindex  - Stage number
    3413:   Y           - Array of vectors (of size = total number
    3414:                 of stages) with the stage solutions

    3416:   Notes:
    3417:   TSPostStage() is typically used within time stepping implementations,
    3418:   most users would not generally call this routine themselves.

    3420:   Level: developer

    3422: .seealso: TSPreStage(), TSSetPreStep(), TSPreStep(), TSPostStep()
    3423: @*/
    3424: PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
    3425: {
    3428:   if (ts->poststage) {
    3429:     PetscStackCallStandard((*ts->poststage),(ts,stagetime,stageindex,Y));
    3430:   }
    3431:   return(0);
    3432: }

    3434: /*@
    3435:   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()

    3437:   Collective on TS

    3439:   Input Parameters:
    3440: . ts          - The TS context obtained from TSCreate()

    3442:   Notes:
    3443:   TSPostEvaluate() is typically used within time stepping implementations,
    3444:   most users would not generally call this routine themselves.

    3446:   Level: developer

    3448: .seealso: TSSetPostEvaluate(), TSSetPreStep(), TSPreStep(), TSPostStep()
    3449: @*/
    3450: PetscErrorCode  TSPostEvaluate(TS ts)
    3451: {

    3456:   if (ts->postevaluate) {
    3457:     Vec              U;
    3458:     PetscObjectState sprev,spost;

    3460:     TSGetSolution(ts,&U);
    3461:     PetscObjectStateGet((PetscObject)U,&sprev);
    3462:     PetscStackCallStandard((*ts->postevaluate),(ts));
    3463:     PetscObjectStateGet((PetscObject)U,&spost);
    3464:     if (sprev != spost) {TSRestartStep(ts);}
    3465:   }
    3466:   return(0);
    3467: }

    3469: /*@C
    3470:   TSSetPostStep - Sets the general-purpose function
    3471:   called once at the end of each time step.

    3473:   Logically Collective on TS

    3475:   Input Parameters:
    3476: + ts   - The TS context obtained from TSCreate()
    3477: - func - The function

    3479:   Calling sequence of func:
    3480: $ func (TS ts);

    3482:   Notes:
    3483:   The function set by TSSetPostStep() is called after each successful step. The solution vector X
    3484:   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
    3485:   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.

    3487:   Level: intermediate

    3489: .seealso: TSSetPreStep(), TSSetPreStage(), TSSetPostEvaluate(), TSGetTimeStep(), TSGetStepNumber(), TSGetTime(), TSRestartStep()
    3490: @*/
    3491: PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
    3492: {
    3495:   ts->poststep = func;
    3496:   return(0);
    3497: }

    3499: /*@
    3500:   TSPostStep - Runs the user-defined post-step function.

    3502:   Collective on TS

    3504:   Input Parameters:
    3505: . ts   - The TS context obtained from TSCreate()

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

    3511:   Level: developer

    3513: @*/
    3514: PetscErrorCode  TSPostStep(TS ts)
    3515: {

    3520:   if (ts->poststep) {
    3521:     Vec              U;
    3522:     PetscObjectState sprev,spost;

    3524:     TSGetSolution(ts,&U);
    3525:     PetscObjectStateGet((PetscObject)U,&sprev);
    3526:     PetscStackCallStandard((*ts->poststep),(ts));
    3527:     PetscObjectStateGet((PetscObject)U,&spost);
    3528:     if (sprev != spost) {TSRestartStep(ts);}
    3529:   }
    3530:   return(0);
    3531: }

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

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

    3539:    Logically Collective on TS

    3541:    Input Parameters:
    3542: +  ts - the TS context obtained from TSCreate()
    3543: .  monitor - monitoring routine
    3544: .  mctx - [optional] user-defined context for private data for the
    3545:              monitor routine (use NULL if no context is desired)
    3546: -  monitordestroy - [optional] routine that frees monitor context
    3547:           (may be NULL)

    3549:    Calling sequence of monitor:
    3550: $    PetscErrorCode monitor(TS ts,PetscInt steps,PetscReal time,Vec u,void *mctx)

    3552: +    ts - the TS context
    3553: .    steps - iteration number (after the final time step the monitor routine may be called with a step of -1, this indicates the solution has been interpolated to this time)
    3554: .    time - current time
    3555: .    u - current iterate
    3556: -    mctx - [optional] monitoring context

    3558:    Notes:
    3559:    This routine adds an additional monitor to the list of monitors that
    3560:    already has been loaded.

    3562:    Fortran Notes:
    3563:     Only a single monitor function can be set for each TS object

    3565:    Level: intermediate

    3567: .seealso: TSMonitorDefault(), TSMonitorCancel()
    3568: @*/
    3569: PetscErrorCode  TSMonitorSet(TS ts,PetscErrorCode (*monitor)(TS,PetscInt,PetscReal,Vec,void*),void *mctx,PetscErrorCode (*mdestroy)(void**))
    3570: {
    3572:   PetscInt       i;
    3573:   PetscBool      identical;

    3577:   for (i=0; i<ts->numbermonitors;i++) {
    3578:     PetscMonitorCompare((PetscErrorCode (*)(void))monitor,mctx,mdestroy,(PetscErrorCode (*)(void))ts->monitor[i],ts->monitorcontext[i],ts->monitordestroy[i],&identical);
    3579:     if (identical) return(0);
    3580:   }
    3581:   if (ts->numbermonitors >= MAXTSMONITORS) SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_OUTOFRANGE,"Too many monitors set");
    3582:   ts->monitor[ts->numbermonitors]          = monitor;
    3583:   ts->monitordestroy[ts->numbermonitors]   = mdestroy;
    3584:   ts->monitorcontext[ts->numbermonitors++] = (void*)mctx;
    3585:   return(0);
    3586: }

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

    3591:    Logically Collective on TS

    3593:    Input Parameters:
    3594: .  ts - the TS context obtained from TSCreate()

    3596:    Notes:
    3597:    There is no way to remove a single, specific monitor.

    3599:    Level: intermediate

    3601: .seealso: TSMonitorDefault(), TSMonitorSet()
    3602: @*/
    3603: PetscErrorCode  TSMonitorCancel(TS ts)
    3604: {
    3606:   PetscInt       i;

    3610:   for (i=0; i<ts->numbermonitors; i++) {
    3611:     if (ts->monitordestroy[i]) {
    3612:       (*ts->monitordestroy[i])(&ts->monitorcontext[i]);
    3613:     }
    3614:   }
    3615:   ts->numbermonitors = 0;
    3616:   return(0);
    3617: }

    3619: /*@C
    3620:    TSMonitorDefault - The Default monitor, prints the timestep and time for each step

    3622:    Level: intermediate

    3624: .seealso:  TSMonitorSet()
    3625: @*/
    3626: PetscErrorCode TSMonitorDefault(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
    3627: {
    3629:   PetscViewer    viewer =  vf->viewer;
    3630:   PetscBool      iascii,ibinary;

    3634:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
    3635:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&ibinary);
    3636:   PetscViewerPushFormat(viewer,vf->format);
    3637:   if (iascii) {
    3638:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
    3639:     if (step == -1){ /* this indicates it is an interpolated solution */
    3640:       PetscViewerASCIIPrintf(viewer,"Interpolated solution at time %g between steps %D and %D\n",(double)ptime,ts->steps-1,ts->steps);
    3641:     } else {
    3642:       PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)\n" : "\n");
    3643:     }
    3644:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
    3645:   } else if (ibinary) {
    3646:     PetscMPIInt rank;
    3647:     MPI_Comm_rank(PetscObjectComm((PetscObject)viewer),&rank);
    3648:     if (!rank) {
    3649:       PetscBool skipHeader;
    3650:       PetscInt  classid = REAL_FILE_CLASSID;

    3652:       PetscViewerBinaryGetSkipHeader(viewer,&skipHeader);
    3653:       if (!skipHeader) {
    3654:          PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT);
    3655:        }
    3656:       PetscRealView(1,&ptime,viewer);
    3657:     } else {
    3658:       PetscRealView(0,&ptime,viewer);
    3659:     }
    3660:   }
    3661:   PetscViewerPopFormat(viewer);
    3662:   return(0);
    3663: }

    3665: /*@C
    3666:    TSMonitorExtreme - Prints the extreme values of the solution at each timestep

    3668:    Level: intermediate

    3670: .seealso:  TSMonitorSet()
    3671: @*/
    3672: PetscErrorCode TSMonitorExtreme(TS ts,PetscInt step,PetscReal ptime,Vec v,PetscViewerAndFormat *vf)
    3673: {
    3675:   PetscViewer    viewer =  vf->viewer;
    3676:   PetscBool      iascii;
    3677:   PetscReal      max,min;

    3682:   PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii);
    3683:   PetscViewerPushFormat(viewer,vf->format);
    3684:   if (iascii) {
    3685:     VecMax(v,NULL,&max);
    3686:     VecMin(v,NULL,&min);
    3687:     PetscViewerASCIIAddTab(viewer,((PetscObject)ts)->tablevel);
    3688:     PetscViewerASCIIPrintf(viewer,"%D TS dt %g time %g%s max %g min %g\n",step,(double)ts->time_step,(double)ptime,ts->steprollback ? " (r)" : "",(double)max,(double)min);
    3689:     PetscViewerASCIISubtractTab(viewer,((PetscObject)ts)->tablevel);
    3690:   }
    3691:   PetscViewerPopFormat(viewer);
    3692:   return(0);
    3693: }

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

    3698:    Collective on TS

    3700:    Input Argument:
    3701: +  ts - time stepping context
    3702: -  t - time to interpolate to

    3704:    Output Argument:
    3705: .  U - state at given time

    3707:    Level: intermediate

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

    3712: .seealso: TSSetExactFinalTime(), TSSolve()
    3713: @*/
    3714: PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
    3715: {

    3721:   if (t < ts->ptime_prev || t > ts->ptime) SETERRQ3(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",t,(double)ts->ptime_prev,(double)ts->ptime);
    3722:   if (!ts->ops->interpolate) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
    3723:   (*ts->ops->interpolate)(ts,t,U);
    3724:   return(0);
    3725: }

    3727: /*@
    3728:    TSStep - Steps one time step

    3730:    Collective on TS

    3732:    Input Parameter:
    3733: .  ts - the TS context obtained from TSCreate()

    3735:    Level: developer

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

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

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

    3746: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSSetPostStage(), TSInterpolate()
    3747: @*/
    3748: PetscErrorCode  TSStep(TS ts)
    3749: {
    3750:   PetscErrorCode   ierr;
    3751:   static PetscBool cite = PETSC_FALSE;
    3752:   PetscReal        ptime;

    3756:   PetscCitationsRegister("@article{tspaper,\n"
    3757:                                 "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
    3758:                                 "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
    3759:                                 "  journal       = {arXiv e-preprints},\n"
    3760:                                 "  eprint        = {1806.01437},\n"
    3761:                                 "  archivePrefix = {arXiv},\n"
    3762:                                 "  year          = {2018}\n}\n",&cite);

    3764:   TSSetUp(ts);
    3765:   TSTrajectorySetUp(ts->trajectory,ts);

    3767:   if (!ts->ops->step) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
    3768:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
    3769:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
    3770:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

    3772:   if (!ts->steps) ts->ptime_prev = ts->ptime;
    3773:   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
    3774:   ts->reason = TS_CONVERGED_ITERATING;

    3776:   PetscLogEventBegin(TS_Step,ts,0,0,0);
    3777:   (*ts->ops->step)(ts);
    3778:   PetscLogEventEnd(TS_Step,ts,0,0,0);

    3780:   if (ts->reason >= 0) {
    3781:     ts->ptime_prev = ptime;
    3782:     ts->steps++;
    3783:     ts->steprollback = PETSC_FALSE;
    3784:     ts->steprestart  = PETSC_FALSE;
    3785:   }

    3787:   if (!ts->reason) {
    3788:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
    3789:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
    3790:   }

    3792:   if (ts->reason < 0 && ts->errorifstepfailed && ts->reason == TS_DIVERGED_NONLINEAR_SOLVE) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s, increase -ts_max_snes_failures or make negative to attempt recovery",TSConvergedReasons[ts->reason]);
    3793:   if (ts->reason < 0 && ts->errorifstepfailed) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
    3794:   return(0);
    3795: }

    3797: /*@
    3798:    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
    3799:    at the end of a time step with a given order of accuracy.

    3801:    Collective on TS

    3803:    Input Arguments:
    3804: +  ts - time stepping context
    3805: .  wnormtype - norm type, either NORM_2 or NORM_INFINITY
    3806: -  order - optional, desired order for the error evaluation or PETSC_DECIDE

    3808:    Output Arguments:
    3809: +  order - optional, the actual order of the error evaluation
    3810: -  wlte - the weighted local truncation error norm

    3812:    Level: advanced

    3814:    Notes:
    3815:    If the timestepper cannot evaluate the error in a particular step
    3816:    (eg. in the first step or restart steps after event handling),
    3817:    this routine returns wlte=-1.0 .

    3819: .seealso: TSStep(), TSAdapt, TSErrorWeightedNorm()
    3820: @*/
    3821: PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
    3822: {

    3832:   if (wnormtype != NORM_2 && wnormtype != NORM_INFINITY) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
    3833:   if (!ts->ops->evaluatewlte) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
    3834:   (*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte);
    3835:   return(0);
    3836: }

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

    3841:    Collective on TS

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

    3848:    Output Arguments:
    3849: .  U - state at the end of the current step

    3851:    Level: advanced

    3853:    Notes:
    3854:    This function cannot be called until all stages have been evaluated.
    3855:    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.

    3857: .seealso: TSStep(), TSAdapt
    3858: @*/
    3859: PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
    3860: {

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

    3872: /*@C
    3873:   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.

    3875:   Not collective

    3877:   Input Argument:
    3878: . ts        - time stepping context

    3880:   Output Argument:
    3881: . initConditions - The function which computes an initial condition

    3883:    Level: advanced

    3885:    Notes:
    3886:    The calling sequence for the function is
    3887: $ initCondition(TS ts, Vec u)
    3888: $ ts - The timestepping context
    3889: $ u  - The input vector in which the initial condition is stored

    3891: .seealso: TSSetComputeInitialCondition(), TSComputeInitialCondition()
    3892: @*/
    3893: PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
    3894: {
    3898:   *initCondition = ts->ops->initcondition;
    3899:   return(0);
    3900: }

    3902: /*@C
    3903:   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.

    3905:   Logically collective on ts

    3907:   Input Arguments:
    3908: + ts        - time stepping context
    3909: - initCondition - The function which computes an initial condition

    3911:   Level: advanced

    3913:   Calling sequence for initCondition:
    3914: $ PetscErrorCode initCondition(TS ts, Vec u)

    3916: + ts - The timestepping context
    3917: - u  - The input vector in which the initial condition is to be stored

    3919: .seealso: TSGetComputeInitialCondition(), TSComputeInitialCondition()
    3920: @*/
    3921: PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
    3922: {
    3926:   ts->ops->initcondition = initCondition;
    3927:   return(0);
    3928: }

    3930: /*@
    3931:   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.

    3933:   Collective on ts

    3935:   Input Arguments:
    3936: + ts - time stepping context
    3937: - u  - The Vec to store the condition in which will be used in TSSolve()

    3939:   Level: advanced

    3941: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
    3942: @*/
    3943: PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
    3944: {

    3950:   if (ts->ops->initcondition) {(*ts->ops->initcondition)(ts, u);}
    3951:   return(0);
    3952: }

    3954: /*@C
    3955:   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.

    3957:   Not collective

    3959:   Input Argument:
    3960: . ts         - time stepping context

    3962:   Output Argument:
    3963: . exactError - The function which computes the solution error

    3965:   Level: advanced

    3967:   Calling sequence for exactError:
    3968: $ PetscErrorCode exactError(TS ts, Vec u)

    3970: + ts - The timestepping context
    3971: . u  - The approximate solution vector
    3972: - e  - The input vector in which the error is stored

    3974: .seealso: TSGetComputeExactError(), TSComputeExactError()
    3975: @*/
    3976: PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
    3977: {
    3981:   *exactError = ts->ops->exacterror;
    3982:   return(0);
    3983: }

    3985: /*@C
    3986:   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.

    3988:   Logically collective on ts

    3990:   Input Arguments:
    3991: + ts         - time stepping context
    3992: - exactError - The function which computes the solution error

    3994:   Level: advanced

    3996:   Calling sequence for exactError:
    3997: $ PetscErrorCode exactError(TS ts, Vec u)

    3999: + ts - The timestepping context
    4000: . u  - The approximate solution vector
    4001: - e  - The input vector in which the error is stored

    4003: .seealso: TSGetComputeExactError(), TSComputeExactError()
    4004: @*/
    4005: PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
    4006: {
    4010:   ts->ops->exacterror = exactError;
    4011:   return(0);
    4012: }

    4014: /*@
    4015:   TSComputeExactError - Compute the solution error for the timestepping using the function previously set.

    4017:   Collective on ts

    4019:   Input Arguments:
    4020: + ts - time stepping context
    4021: . u  - The approximate solution
    4022: - e  - The Vec used to store the error

    4024:   Level: advanced

    4026: .seealso: TSGetComputeInitialCondition(), TSSetComputeInitialCondition(), TSSolve()
    4027: @*/
    4028: PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
    4029: {

    4036:   if (ts->ops->exacterror) {(*ts->ops->exacterror)(ts, u, e);}
    4037:   return(0);
    4038: }

    4040: /*@
    4041:    TSSolve - Steps the requested number of timesteps.

    4043:    Collective on TS

    4045:    Input Parameter:
    4046: +  ts - the TS context obtained from TSCreate()
    4047: -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
    4048:                              otherwise must contain the initial conditions and will contain the solution at the final requested time

    4050:    Level: beginner

    4052:    Notes:
    4053:    The final time returned by this function may be different from the time of the internally
    4054:    held state accessible by TSGetSolution() and TSGetTime() because the method may have
    4055:    stepped over the final time.

    4057: .seealso: TSCreate(), TSSetSolution(), TSStep(), TSGetTime(), TSGetSolveTime()
    4058: @*/
    4059: PetscErrorCode TSSolve(TS ts,Vec u)
    4060: {
    4061:   Vec               solution;
    4062:   PetscErrorCode    ierr;

    4068:   TSSetExactFinalTimeDefault(ts);
    4069:   if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && u) {   /* Need ts->vec_sol to be distinct so it is not overwritten when we interpolate at the end */
    4070:     if (!ts->vec_sol || u == ts->vec_sol) {
    4071:       VecDuplicate(u,&solution);
    4072:       TSSetSolution(ts,solution);
    4073:       VecDestroy(&solution); /* grant ownership */
    4074:     }
    4075:     VecCopy(u,ts->vec_sol);
    4076:     if (ts->forward_solve) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
    4077:   } else if (u) {
    4078:     TSSetSolution(ts,u);
    4079:   }
    4080:   TSSetUp(ts);
    4081:   TSTrajectorySetUp(ts->trajectory,ts);

    4083:   if (ts->max_time >= PETSC_MAX_REAL && ts->max_steps == PETSC_MAX_INT) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
    4084:   if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
    4085:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP && !ts->adapt) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");

    4087:   if (ts->forward_solve) {
    4088:     TSForwardSetUp(ts);
    4089:   }

    4091:   /* reset number of steps only when the step is not restarted. ARKIMEX
    4092:      restarts the step after an event. Resetting these counters in such case causes
    4093:      TSTrajectory to incorrectly save the output files
    4094:   */
    4095:   /* reset time step and iteration counters */
    4096:   if (!ts->steps) {
    4097:     ts->ksp_its           = 0;
    4098:     ts->snes_its          = 0;
    4099:     ts->num_snes_failures = 0;
    4100:     ts->reject            = 0;
    4101:     ts->steprestart       = PETSC_TRUE;
    4102:     ts->steprollback      = PETSC_FALSE;
    4103:     ts->rhsjacobian.time  = PETSC_MIN_REAL;
    4104:   }

    4106:   /* make sure initial time step does not overshoot final time */
    4107:   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
    4108:     PetscReal maxdt = ts->max_time-ts->ptime;
    4109:     PetscReal dt = ts->time_step;

    4111:     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
    4112:   }
    4113:   ts->reason = TS_CONVERGED_ITERATING;

    4115:   {
    4116:     PetscViewer       viewer;
    4117:     PetscViewerFormat format;
    4118:     PetscBool         flg;
    4119:     static PetscBool  incall = PETSC_FALSE;

    4121:     if (!incall) {
    4122:       /* Estimate the convergence rate of the time discretization */
    4123:       PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg);
    4124:       if (flg) {
    4125:         PetscConvEst conv;
    4126:         DM           dm;
    4127:         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
    4128:         PetscInt     Nf;
    4129:         PetscBool    checkTemporal = PETSC_TRUE;

    4131:         incall = PETSC_TRUE;
    4132:         PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg);
    4133:         TSGetDM(ts, &dm);
    4134:         DMGetNumFields(dm, &Nf);
    4135:         PetscCalloc1(PetscMax(Nf, 1), &alpha);
    4136:         PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv);
    4137:         PetscConvEstUseTS(conv, checkTemporal);
    4138:         PetscConvEstSetSolver(conv, (PetscObject) ts);
    4139:         PetscConvEstSetFromOptions(conv);
    4140:         PetscConvEstSetUp(conv);
    4141:         PetscConvEstGetConvRate(conv, alpha);
    4142:         PetscViewerPushFormat(viewer, format);
    4143:         PetscConvEstRateView(conv, alpha, viewer);
    4144:         PetscViewerPopFormat(viewer);
    4145:         PetscViewerDestroy(&viewer);
    4146:         PetscConvEstDestroy(&conv);
    4147:         PetscFree(alpha);
    4148:         incall = PETSC_FALSE;
    4149:       }
    4150:     }
    4151:   }

    4153:   TSViewFromOptions(ts,NULL,"-ts_view_pre");

    4155:   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
    4156:     (*ts->ops->solve)(ts);
    4157:     if (u) {VecCopy(ts->vec_sol,u);}
    4158:     ts->solvetime = ts->ptime;
    4159:     solution = ts->vec_sol;
    4160:   } else { /* Step the requested number of timesteps. */
    4161:     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
    4162:     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;

    4164:     if (!ts->steps) {
    4165:       TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
    4166:       TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol);
    4167:     }

    4169:     while (!ts->reason) {
    4170:       TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);
    4171:       if (!ts->steprollback) {
    4172:         TSPreStep(ts);
    4173:       }
    4174:       TSStep(ts);
    4175:       if (ts->testjacobian) {
    4176:         TSRHSJacobianTest(ts,NULL);
    4177:       }
    4178:       if (ts->testjacobiantranspose) {
    4179:         TSRHSJacobianTestTranspose(ts,NULL);
    4180:       }
    4181:       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
    4182:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
    4183:         TSForwardCostIntegral(ts);
    4184:         if (ts->reason >= 0) ts->steps++;
    4185:       }
    4186:       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
    4187:         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
    4188:         TSForwardStep(ts);
    4189:         if (ts->reason >= 0) ts->steps++;
    4190:       }
    4191:       TSPostEvaluate(ts);
    4192:       TSEventHandler(ts); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
    4193:       if (ts->steprollback) {
    4194:         TSPostEvaluate(ts);
    4195:       }
    4196:       if (!ts->steprollback) {
    4197:         TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol);
    4198:         TSPostStep(ts);
    4199:       }
    4200:     }
    4201:     TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol);

    4203:     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
    4204:       TSInterpolate(ts,ts->max_time,u);
    4205:       ts->solvetime = ts->max_time;
    4206:       solution = u;
    4207:       TSMonitor(ts,-1,ts->solvetime,solution);
    4208:     } else {
    4209:       if (u) {VecCopy(ts->vec_sol,u);}
    4210:       ts->solvetime = ts->ptime;
    4211:       solution = ts->vec_sol;
    4212:     }
    4213:   }

    4215:   TSViewFromOptions(ts,NULL,"-ts_view");
    4216:   VecViewFromOptions(solution,(PetscObject)ts,"-ts_view_solution");
    4217:   PetscObjectSAWsBlock((PetscObject)ts);
    4218:   if (ts->adjoint_solve) {
    4219:     TSAdjointSolve(ts);
    4220:   }
    4221:   return(0);
    4222: }

    4224: /*@C
    4225:    TSMonitor - Runs all user-provided monitor routines set using TSMonitorSet()

    4227:    Collective on TS

    4229:    Input Parameters:
    4230: +  ts - time stepping context obtained from TSCreate()
    4231: .  step - step number that has just completed
    4232: .  ptime - model time of the state
    4233: -  u - state at the current model time

    4235:    Notes:
    4236:    TSMonitor() is typically used automatically within the time stepping implementations.
    4237:    Users would almost never call this routine directly.

    4239:    A step of -1 indicates that the monitor is being called on a solution obtained by interpolating from computed solutions

    4241:    Level: developer

    4243: @*/
    4244: PetscErrorCode TSMonitor(TS ts,PetscInt step,PetscReal ptime,Vec u)
    4245: {
    4246:   DM             dm;
    4247:   PetscInt       i,n = ts->numbermonitors;

    4254:   TSGetDM(ts,&dm);
    4255:   DMSetOutputSequenceNumber(dm,step,ptime);

    4257:   VecLockReadPush(u);
    4258:   for (i=0; i<n; i++) {
    4259:     (*ts->monitor[i])(ts,step,ptime,u,ts->monitorcontext[i]);
    4260:   }
    4261:   VecLockReadPop(u);
    4262:   return(0);
    4263: }

    4265: /* ------------------------------------------------------------------------*/
    4266: /*@C
    4267:    TSMonitorLGCtxCreate - Creates a TSMonitorLGCtx context for use with
    4268:    TS to monitor the solution process graphically in various ways

    4270:    Collective on TS

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

    4279:    Output Parameter:
    4280: .  ctx - the context

    4282:    Options Database Key:
    4283: +  -ts_monitor_lg_timestep - automatically sets line graph monitor
    4284: +  -ts_monitor_lg_timestep_log - automatically sets line graph monitor
    4285: .  -ts_monitor_lg_solution - monitor the solution (or certain values of the solution by calling TSMonitorLGSetDisplayVariables() or TSMonitorLGCtxSetDisplayVariables())
    4286: .  -ts_monitor_lg_error -  monitor the error
    4287: .  -ts_monitor_lg_ksp_iterations - monitor the number of KSP iterations needed for each timestep
    4288: .  -ts_monitor_lg_snes_iterations - monitor the number of SNES iterations needed for each timestep
    4289: -  -lg_use_markers <true,false> - mark the data points (at each time step) on the plot; default is true

    4291:    Notes:
    4292:    Use TSMonitorLGCtxDestroy() to destroy.

    4294:    One can provide a function that transforms the solution before plotting it with TSMonitorLGCtxSetTransform() or TSMonitorLGSetTransform()

    4296:    Many of the functions that control the monitoring have two forms: TSMonitorLGSet/GetXXXX() and TSMonitorLGCtxSet/GetXXXX() the first take a TS object as the
    4297:    first argument (if that TS object does not have a TSMonitorLGCtx associated with it the function call is ignored) and the second takes a TSMonitorLGCtx object
    4298:    as the first argument.

    4300:    One can control the names displayed for each solution or error variable with TSMonitorLGCtxSetVariableNames() or TSMonitorLGSetVariableNames()

    4302:    Level: intermediate

    4304: .seealso: TSMonitorLGTimeStep(), TSMonitorSet(), TSMonitorLGSolution(), TSMonitorLGError(), TSMonitorDefault(), VecView(),
    4305:            TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
    4306:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
    4307:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
    4308:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()

    4310: @*/
    4311: PetscErrorCode  TSMonitorLGCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorLGCtx *ctx)
    4312: {
    4313:   PetscDraw      draw;

    4317:   PetscNew(ctx);
    4318:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
    4319:   PetscDrawSetFromOptions(draw);
    4320:   PetscDrawLGCreate(draw,1,&(*ctx)->lg);
    4321:   PetscDrawLGSetFromOptions((*ctx)->lg);
    4322:   PetscDrawDestroy(&draw);
    4323:   (*ctx)->howoften = howoften;
    4324:   return(0);
    4325: }

    4327: PetscErrorCode TSMonitorLGTimeStep(TS ts,PetscInt step,PetscReal ptime,Vec v,void *monctx)
    4328: {
    4329:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    4330:   PetscReal      x   = ptime,y;

    4334:   if (step < 0) return(0); /* -1 indicates an interpolated solution */
    4335:   if (!step) {
    4336:     PetscDrawAxis axis;
    4337:     const char *ylabel = ctx->semilogy ? "Log Time Step" : "Time Step";
    4338:     PetscDrawLGGetAxis(ctx->lg,&axis);
    4339:     PetscDrawAxisSetLabels(axis,"Timestep as function of time","Time",ylabel);
    4340:     PetscDrawLGReset(ctx->lg);
    4341:   }
    4342:   TSGetTimeStep(ts,&y);
    4343:   if (ctx->semilogy) y = PetscLog10Real(y);
    4344:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    4345:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    4346:     PetscDrawLGDraw(ctx->lg);
    4347:     PetscDrawLGSave(ctx->lg);
    4348:   }
    4349:   return(0);
    4350: }

    4352: /*@C
    4353:    TSMonitorLGCtxDestroy - Destroys a line graph context that was created
    4354:    with TSMonitorLGCtxCreate().

    4356:    Collective on TSMonitorLGCtx

    4358:    Input Parameter:
    4359: .  ctx - the monitor context

    4361:    Level: intermediate

    4363: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep();
    4364: @*/
    4365: PetscErrorCode  TSMonitorLGCtxDestroy(TSMonitorLGCtx *ctx)
    4366: {

    4370:   if ((*ctx)->transformdestroy) {
    4371:     ((*ctx)->transformdestroy)((*ctx)->transformctx);
    4372:   }
    4373:   PetscDrawLGDestroy(&(*ctx)->lg);
    4374:   PetscStrArrayDestroy(&(*ctx)->names);
    4375:   PetscStrArrayDestroy(&(*ctx)->displaynames);
    4376:   PetscFree((*ctx)->displayvariables);
    4377:   PetscFree((*ctx)->displayvalues);
    4378:   PetscFree(*ctx);
    4379:   return(0);
    4380: }

    4382: /*

    4384:   Creates a TS Monitor SPCtx for use with DM Swarm particle visualizations

    4386: */
    4387: PetscErrorCode TSMonitorSPCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorSPCtx *ctx)
    4388: {
    4389:   PetscDraw      draw;

    4393:   PetscNew(ctx);
    4394:   PetscDrawCreate(comm,host,label,x,y,m,n,&draw);
    4395:   PetscDrawSetFromOptions(draw);
    4396:   PetscDrawSPCreate(draw,1,&(*ctx)->sp);
    4397:   PetscDrawDestroy(&draw);
    4398:   (*ctx)->howoften = howoften;
    4399:   return(0);

    4401: }

    4403: /*
    4404:   Destroys a TSMonitorSPCtx that was created with TSMonitorSPCtxCreate
    4405: */
    4406: PetscErrorCode TSMonitorSPCtxDestroy(TSMonitorSPCtx *ctx)
    4407: {

    4412:   PetscDrawSPDestroy(&(*ctx)->sp);
    4413:   PetscFree(*ctx);

    4415:   return(0);

    4417: }

    4419: /*@
    4420:    TSGetTime - Gets the time of the most recently completed step.

    4422:    Not Collective

    4424:    Input Parameter:
    4425: .  ts - the TS context obtained from TSCreate()

    4427:    Output Parameter:
    4428: .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().

    4430:    Level: beginner

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

    4436: .seealso:  TSGetSolveTime(), TSSetTime(), TSGetTimeStep(), TSGetStepNumber()

    4438: @*/
    4439: PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
    4440: {
    4444:   *t = ts->ptime;
    4445:   return(0);
    4446: }

    4448: /*@
    4449:    TSGetPrevTime - Gets the starting time of the previously completed step.

    4451:    Not Collective

    4453:    Input Parameter:
    4454: .  ts - the TS context obtained from TSCreate()

    4456:    Output Parameter:
    4457: .  t  - the previous time

    4459:    Level: beginner

    4461: .seealso: TSGetTime(), TSGetSolveTime(), TSGetTimeStep()

    4463: @*/
    4464: PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
    4465: {
    4469:   *t = ts->ptime_prev;
    4470:   return(0);
    4471: }

    4473: /*@
    4474:    TSSetTime - Allows one to reset the time.

    4476:    Logically Collective on TS

    4478:    Input Parameters:
    4479: +  ts - the TS context obtained from TSCreate()
    4480: -  time - the time

    4482:    Level: intermediate

    4484: .seealso: TSGetTime(), TSSetMaxSteps()

    4486: @*/
    4487: PetscErrorCode  TSSetTime(TS ts, PetscReal t)
    4488: {
    4492:   ts->ptime = t;
    4493:   return(0);
    4494: }

    4496: /*@C
    4497:    TSSetOptionsPrefix - Sets the prefix used for searching for all
    4498:    TS options in the database.

    4500:    Logically Collective on TS

    4502:    Input Parameter:
    4503: +  ts     - The TS context
    4504: -  prefix - The prefix to prepend to all option names

    4506:    Notes:
    4507:    A hyphen (-) must NOT be given at the beginning of the prefix name.
    4508:    The first character of all runtime options is AUTOMATICALLY the
    4509:    hyphen.

    4511:    Level: advanced

    4513: .seealso: TSSetFromOptions()

    4515: @*/
    4516: PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
    4517: {
    4519:   SNES           snes;

    4523:   PetscObjectSetOptionsPrefix((PetscObject)ts,prefix);
    4524:   TSGetSNES(ts,&snes);
    4525:   SNESSetOptionsPrefix(snes,prefix);
    4526:   return(0);
    4527: }

    4529: /*@C
    4530:    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
    4531:    TS options in the database.

    4533:    Logically Collective on TS

    4535:    Input Parameter:
    4536: +  ts     - The TS context
    4537: -  prefix - The prefix to prepend to all option names

    4539:    Notes:
    4540:    A hyphen (-) must NOT be given at the beginning of the prefix name.
    4541:    The first character of all runtime options is AUTOMATICALLY the
    4542:    hyphen.

    4544:    Level: advanced

    4546: .seealso: TSGetOptionsPrefix()

    4548: @*/
    4549: PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
    4550: {
    4552:   SNES           snes;

    4556:   PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix);
    4557:   TSGetSNES(ts,&snes);
    4558:   SNESAppendOptionsPrefix(snes,prefix);
    4559:   return(0);
    4560: }

    4562: /*@C
    4563:    TSGetOptionsPrefix - Sets the prefix used for searching for all
    4564:    TS options in the database.

    4566:    Not Collective

    4568:    Input Parameter:
    4569: .  ts - The TS context

    4571:    Output Parameter:
    4572: .  prefix - A pointer to the prefix string used

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

    4578:    Level: intermediate

    4580: .seealso: TSAppendOptionsPrefix()
    4581: @*/
    4582: PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
    4583: {

    4589:   PetscObjectGetOptionsPrefix((PetscObject)ts,prefix);
    4590:   return(0);
    4591: }

    4593: /*@C
    4594:    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.

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

    4598:    Input Parameter:
    4599: .  ts  - The TS context obtained from TSCreate()

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

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

    4610:    Level: intermediate

    4612: .seealso: TSGetTimeStep(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

    4614: @*/
    4615: PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
    4616: {
    4618:   DM             dm;

    4621:   if (Amat || Pmat) {
    4622:     SNES snes;
    4623:     TSGetSNES(ts,&snes);
    4624:     SNESSetUpMatrices(snes);
    4625:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
    4626:   }
    4627:   TSGetDM(ts,&dm);
    4628:   DMTSGetRHSJacobian(dm,func,ctx);
    4629:   return(0);
    4630: }

    4632: /*@C
    4633:    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.

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

    4637:    Input Parameter:
    4638: .  ts  - The TS context obtained from TSCreate()

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

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

    4649:    Level: advanced

    4651: .seealso: TSGetTimeStep(), TSGetRHSJacobian(), TSGetMatrices(), TSGetTime(), TSGetStepNumber()

    4653: @*/
    4654: PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
    4655: {
    4657:   DM             dm;

    4660:   if (Amat || Pmat) {
    4661:     SNES snes;
    4662:     TSGetSNES(ts,&snes);
    4663:     SNESSetUpMatrices(snes);
    4664:     SNESGetJacobian(snes,Amat,Pmat,NULL,NULL);
    4665:   }
    4666:   TSGetDM(ts,&dm);
    4667:   DMTSGetIJacobian(dm,f,ctx);
    4668:   return(0);
    4669: }

    4671: /*@C
    4672:    TSMonitorDrawSolution - Monitors progress of the TS solvers by calling
    4673:    VecView() for the solution at each timestep

    4675:    Collective on TS

    4677:    Input Parameters:
    4678: +  ts - the TS context
    4679: .  step - current time-step
    4680: .  ptime - current time
    4681: -  dummy - either a viewer or NULL

    4683:    Options Database:
    4684: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

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

    4690:    Level: intermediate

    4692: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    4693: @*/
    4694: PetscErrorCode  TSMonitorDrawSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4695: {
    4696:   PetscErrorCode   ierr;
    4697:   TSMonitorDrawCtx ictx = (TSMonitorDrawCtx)dummy;
    4698:   PetscDraw        draw;

    4701:   if (!step && ictx->showinitial) {
    4702:     if (!ictx->initialsolution) {
    4703:       VecDuplicate(u,&ictx->initialsolution);
    4704:     }
    4705:     VecCopy(u,ictx->initialsolution);
    4706:   }
    4707:   if (!(((ictx->howoften > 0) && (!(step % ictx->howoften))) || ((ictx->howoften == -1) && ts->reason))) return(0);

    4709:   if (ictx->showinitial) {
    4710:     PetscReal pause;
    4711:     PetscViewerDrawGetPause(ictx->viewer,&pause);
    4712:     PetscViewerDrawSetPause(ictx->viewer,0.0);
    4713:     VecView(ictx->initialsolution,ictx->viewer);
    4714:     PetscViewerDrawSetPause(ictx->viewer,pause);
    4715:     PetscViewerDrawSetHold(ictx->viewer,PETSC_TRUE);
    4716:   }
    4717:   VecView(u,ictx->viewer);
    4718:   if (ictx->showtimestepandtime) {
    4719:     PetscReal xl,yl,xr,yr,h;
    4720:     char      time[32];

    4722:     PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
    4723:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
    4724:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
    4725:     h    = yl + .95*(yr - yl);
    4726:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
    4727:     PetscDrawFlush(draw);
    4728:   }

    4730:   if (ictx->showinitial) {
    4731:     PetscViewerDrawSetHold(ictx->viewer,PETSC_FALSE);
    4732:   }
    4733:   return(0);
    4734: }

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

    4739:    Collective on TS

    4741:    Input Parameters:
    4742: +  ts - the TS context
    4743: .  step - current time-step
    4744: .  ptime - current time
    4745: -  dummy - either a viewer or NULL

    4747:    Level: intermediate

    4749: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    4750: @*/
    4751: PetscErrorCode  TSMonitorDrawSolutionPhase(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4752: {
    4753:   PetscErrorCode    ierr;
    4754:   TSMonitorDrawCtx  ictx = (TSMonitorDrawCtx)dummy;
    4755:   PetscDraw         draw;
    4756:   PetscDrawAxis     axis;
    4757:   PetscInt          n;
    4758:   PetscMPIInt       size;
    4759:   PetscReal         U0,U1,xl,yl,xr,yr,h;
    4760:   char              time[32];
    4761:   const PetscScalar *U;

    4764:   MPI_Comm_size(PetscObjectComm((PetscObject)ts),&size);
    4765:   if (size != 1) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only allowed for sequential runs");
    4766:   VecGetSize(u,&n);
    4767:   if (n != 2) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Only for ODEs with two unknowns");

    4769:   PetscViewerDrawGetDraw(ictx->viewer,0,&draw);
    4770:   PetscViewerDrawGetDrawAxis(ictx->viewer,0,&axis);
    4771:   PetscDrawAxisGetLimits(axis,&xl,&xr,&yl,&yr);
    4772:   if (!step) {
    4773:     PetscDrawClear(draw);
    4774:     PetscDrawAxisDraw(axis);
    4775:   }

    4777:   VecGetArrayRead(u,&U);
    4778:   U0 = PetscRealPart(U[0]);
    4779:   U1 = PetscRealPart(U[1]);
    4780:   VecRestoreArrayRead(u,&U);
    4781:   if ((U0 < xl) || (U1 < yl) || (U0 > xr) || (U1 > yr)) return(0);

    4783:   PetscDrawCollectiveBegin(draw);
    4784:   PetscDrawPoint(draw,U0,U1,PETSC_DRAW_BLACK);
    4785:   if (ictx->showtimestepandtime) {
    4786:     PetscDrawGetCoordinates(draw,&xl,&yl,&xr,&yr);
    4787:     PetscSNPrintf(time,32,"Timestep %d Time %g",(int)step,(double)ptime);
    4788:     h    = yl + .95*(yr - yl);
    4789:     PetscDrawStringCentered(draw,.5*(xl+xr),h,PETSC_DRAW_BLACK,time);
    4790:   }
    4791:   PetscDrawCollectiveEnd(draw);
    4792:   PetscDrawFlush(draw);
    4793:   PetscDrawPause(draw);
    4794:   PetscDrawSave(draw);
    4795:   return(0);
    4796: }

    4798: /*@C
    4799:    TSMonitorDrawCtxDestroy - Destroys the monitor context for TSMonitorDrawSolution()

    4801:    Collective on TS

    4803:    Input Parameters:
    4804: .    ctx - the monitor context

    4806:    Level: intermediate

    4808: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawSolution(), TSMonitorDrawError()
    4809: @*/
    4810: PetscErrorCode  TSMonitorDrawCtxDestroy(TSMonitorDrawCtx *ictx)
    4811: {

    4815:   PetscViewerDestroy(&(*ictx)->viewer);
    4816:   VecDestroy(&(*ictx)->initialsolution);
    4817:   PetscFree(*ictx);
    4818:   return(0);
    4819: }

    4821: /*@C
    4822:    TSMonitorDrawCtxCreate - Creates the monitor context for TSMonitorDrawCtx

    4824:    Collective on TS

    4826:    Input Parameter:
    4827: .    ts - time-step context

    4829:    Output Patameter:
    4830: .    ctx - the monitor context

    4832:    Options Database:
    4833: .   -ts_monitor_draw_solution_initial - show initial solution as well as current solution

    4835:    Level: intermediate

    4837: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorDrawCtx()
    4838: @*/
    4839: PetscErrorCode  TSMonitorDrawCtxCreate(MPI_Comm comm,const char host[],const char label[],int x,int y,int m,int n,PetscInt howoften,TSMonitorDrawCtx *ctx)
    4840: {
    4841:   PetscErrorCode   ierr;

    4844:   PetscNew(ctx);
    4845:   PetscViewerDrawOpen(comm,host,label,x,y,m,n,&(*ctx)->viewer);
    4846:   PetscViewerSetFromOptions((*ctx)->viewer);

    4848:   (*ctx)->howoften    = howoften;
    4849:   (*ctx)->showinitial = PETSC_FALSE;
    4850:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_initial",&(*ctx)->showinitial,NULL);

    4852:   (*ctx)->showtimestepandtime = PETSC_FALSE;
    4853:   PetscOptionsGetBool(NULL,NULL,"-ts_monitor_draw_solution_show_time",&(*ctx)->showtimestepandtime,NULL);
    4854:   return(0);
    4855: }

    4857: /*@C
    4858:    TSMonitorDrawSolutionFunction - Monitors progress of the TS solvers by calling
    4859:    VecView() for the solution provided by TSSetSolutionFunction() at each timestep

    4861:    Collective on TS

    4863:    Input Parameters:
    4864: +  ts - the TS context
    4865: .  step - current time-step
    4866: .  ptime - current time
    4867: -  dummy - either a viewer or NULL

    4869:    Options Database:
    4870: .  -ts_monitor_draw_solution_function - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

    4872:    Level: intermediate

    4874: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
    4875: @*/
    4876: PetscErrorCode  TSMonitorDrawSolutionFunction(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4877: {
    4878:   PetscErrorCode   ierr;
    4879:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
    4880:   PetscViewer      viewer = ctx->viewer;
    4881:   Vec              work;

    4884:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
    4885:   VecDuplicate(u,&work);
    4886:   TSComputeSolutionFunction(ts,ptime,work);
    4887:   VecView(work,viewer);
    4888:   VecDestroy(&work);
    4889:   return(0);
    4890: }

    4892: /*@C
    4893:    TSMonitorDrawError - Monitors progress of the TS solvers by calling
    4894:    VecView() for the error at each timestep

    4896:    Collective on TS

    4898:    Input Parameters:
    4899: +  ts - the TS context
    4900: .  step - current time-step
    4901: .  ptime - current time
    4902: -  dummy - either a viewer or NULL

    4904:    Options Database:
    4905: .  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()

    4907:    Level: intermediate

    4909: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
    4910: @*/
    4911: PetscErrorCode  TSMonitorDrawError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    4912: {
    4913:   PetscErrorCode   ierr;
    4914:   TSMonitorDrawCtx ctx    = (TSMonitorDrawCtx)dummy;
    4915:   PetscViewer      viewer = ctx->viewer;
    4916:   Vec              work;

    4919:   if (!(((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason))) return(0);
    4920:   VecDuplicate(u,&work);
    4921:   TSComputeSolutionFunction(ts,ptime,work);
    4922:   VecAXPY(work,-1.0,u);
    4923:   VecView(work,viewer);
    4924:   VecDestroy(&work);
    4925:   return(0);
    4926: }

    4928: #include <petsc/private/dmimpl.h>
    4929: /*@
    4930:    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS

    4932:    Logically Collective on ts

    4934:    Input Parameters:
    4935: +  ts - the ODE integrator object
    4936: -  dm - the dm, cannot be NULL

    4938:    Notes:
    4939:    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
    4940:    even when not using interfaces like DMTSSetIFunction().  Use DMClone() to get a distinct DM when solving
    4941:    different problems using the same function space.

    4943:    Level: intermediate

    4945: .seealso: TSGetDM(), SNESSetDM(), SNESGetDM()
    4946: @*/
    4947: PetscErrorCode  TSSetDM(TS ts,DM dm)
    4948: {
    4950:   SNES           snes;
    4951:   DMTS           tsdm;

    4956:   PetscObjectReference((PetscObject)dm);
    4957:   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
    4958:     if (ts->dm->dmts && !dm->dmts) {
    4959:       DMCopyDMTS(ts->dm,dm);
    4960:       DMGetDMTS(ts->dm,&tsdm);
    4961:       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
    4962:         tsdm->originaldm = dm;
    4963:       }
    4964:     }
    4965:     DMDestroy(&ts->dm);
    4966:   }
    4967:   ts->dm = dm;

    4969:   TSGetSNES(ts,&snes);
    4970:   SNESSetDM(snes,dm);
    4971:   return(0);
    4972: }

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

    4977:    Not Collective

    4979:    Input Parameter:
    4980: . ts - the preconditioner context

    4982:    Output Parameter:
    4983: .  dm - the dm

    4985:    Level: intermediate

    4987: .seealso: TSSetDM(), SNESSetDM(), SNESGetDM()
    4988: @*/
    4989: PetscErrorCode  TSGetDM(TS ts,DM *dm)
    4990: {

    4995:   if (!ts->dm) {
    4996:     DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm);
    4997:     if (ts->snes) {SNESSetDM(ts->snes,ts->dm);}
    4998:   }
    4999:   *dm = ts->dm;
    5000:   return(0);
    5001: }

    5003: /*@
    5004:    SNESTSFormFunction - Function to evaluate nonlinear residual

    5006:    Logically Collective on SNES

    5008:    Input Parameter:
    5009: + snes - nonlinear solver
    5010: . U - the current state at which to evaluate the residual
    5011: - ctx - user context, must be a TS

    5013:    Output Parameter:
    5014: . F - the nonlinear residual

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

    5020:    Level: advanced

    5022: .seealso: SNESSetFunction(), MatFDColoringSetFunction()
    5023: @*/
    5024: PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
    5025: {
    5026:   TS             ts = (TS)ctx;

    5034:   (ts->ops->snesfunction)(snes,U,F,ts);
    5035:   return(0);
    5036: }

    5038: /*@
    5039:    SNESTSFormJacobian - Function to evaluate the Jacobian

    5041:    Collective on SNES

    5043:    Input Parameter:
    5044: + snes - nonlinear solver
    5045: . U - the current state at which to evaluate the residual
    5046: - ctx - user context, must be a TS

    5048:    Output Parameter:
    5049: + A - the Jacobian
    5050: . B - the preconditioning matrix (may be the same as A)
    5051: - flag - indicates any structure change in the matrix

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

    5056:    Level: developer

    5058: .seealso: SNESSetJacobian()
    5059: @*/
    5060: PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
    5061: {
    5062:   TS             ts = (TS)ctx;

    5073:   (ts->ops->snesjacobian)(snes,U,A,B,ts);
    5074:   return(0);
    5075: }

    5077: /*@C
    5078:    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only

    5080:    Collective on TS

    5082:    Input Arguments:
    5083: +  ts - time stepping context
    5084: .  t - time at which to evaluate
    5085: .  U - state at which to evaluate
    5086: -  ctx - context

    5088:    Output Arguments:
    5089: .  F - right hand side

    5091:    Level: intermediate

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

    5097: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSJacobianConstant()
    5098: @*/
    5099: PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
    5100: {
    5102:   Mat            Arhs,Brhs;

    5105:   TSGetRHSMats_Private(ts,&Arhs,&Brhs);
    5106:   /* undo the damage caused by shifting */
    5107:   TSRecoverRHSJacobian(ts,Arhs,Brhs);
    5108:   TSComputeRHSJacobian(ts,t,U,Arhs,Brhs);
    5109:   MatMult(Arhs,U,F);
    5110:   return(0);
    5111: }

    5113: /*@C
    5114:    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.

    5116:    Collective on TS

    5118:    Input Arguments:
    5119: +  ts - time stepping context
    5120: .  t - time at which to evaluate
    5121: .  U - state at which to evaluate
    5122: -  ctx - context

    5124:    Output Arguments:
    5125: +  A - pointer to operator
    5126: .  B - pointer to preconditioning matrix
    5127: -  flg - matrix structure flag

    5129:    Level: intermediate

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

    5134: .seealso: TSSetRHSFunction(), TSSetRHSJacobian(), TSComputeRHSFunctionLinear()
    5135: @*/
    5136: PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
    5137: {
    5139:   return(0);
    5140: }

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

    5145:    Collective on TS

    5147:    Input Arguments:
    5148: +  ts - time stepping context
    5149: .  t - time at which to evaluate
    5150: .  U - state at which to evaluate
    5151: .  Udot - time derivative of state vector
    5152: -  ctx - context

    5154:    Output Arguments:
    5155: .  F - left hand side

    5157:    Level: intermediate

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

    5165:    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U

    5167: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIJacobianConstant(), TSComputeRHSFunctionLinear()
    5168: @*/
    5169: PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
    5170: {
    5172:   Mat            A,B;

    5175:   TSGetIJacobian(ts,&A,&B,NULL,NULL);
    5176:   TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE);
    5177:   MatMult(A,Udot,F);
    5178:   return(0);
    5179: }

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

    5184:    Collective on TS

    5186:    Input Arguments:
    5187: +  ts - time stepping context
    5188: .  t - time at which to evaluate
    5189: .  U - state at which to evaluate
    5190: .  Udot - time derivative of state vector
    5191: .  shift - shift to apply
    5192: -  ctx - context

    5194:    Output Arguments:
    5195: +  A - pointer to operator
    5196: .  B - pointer to preconditioning matrix
    5197: -  flg - matrix structure flag

    5199:    Level: advanced

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

    5204:    It is only appropriate for problems of the form

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

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

    5212: $    shift*M + J

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

    5217: .seealso: TSSetIFunction(), TSSetIJacobian(), TSComputeIFunctionLinear()
    5218: @*/
    5219: PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
    5220: {

    5224:   MatScale(A, shift / ts->ijacobian.shift);
    5225:   ts->ijacobian.shift = shift;
    5226:   return(0);
    5227: }

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

    5232:    Not Collective

    5234:    Input Parameter:
    5235: .  ts - the TS context

    5237:    Output Parameter:
    5238: .  equation_type - see TSEquationType

    5240:    Level: beginner

    5242: .seealso: TSSetEquationType(), TSEquationType
    5243: @*/
    5244: PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
    5245: {
    5249:   *equation_type = ts->equation_type;
    5250:   return(0);
    5251: }

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

    5256:    Not Collective

    5258:    Input Parameter:
    5259: +  ts - the TS context
    5260: -  equation_type - see TSEquationType

    5262:    Level: advanced

    5264: .seealso: TSGetEquationType(), TSEquationType
    5265: @*/
    5266: PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
    5267: {
    5270:   ts->equation_type = equation_type;
    5271:   return(0);
    5272: }

    5274: /*@
    5275:    TSGetConvergedReason - Gets the reason the TS iteration was stopped.

    5277:    Not Collective

    5279:    Input Parameter:
    5280: .  ts - the TS context

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

    5286:    Level: beginner

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

    5291: .seealso: TSSetConvergenceTest(), TSConvergedReason
    5292: @*/
    5293: PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
    5294: {
    5298:   *reason = ts->reason;
    5299:   return(0);
    5300: }

    5302: /*@
    5303:    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.

    5305:    Logically Collective; reason must contain common value

    5307:    Input Parameters:
    5308: +  ts - the TS context
    5309: -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
    5310:             manual pages for the individual convergence tests for complete lists

    5312:    Level: advanced

    5314:    Notes:
    5315:    Can only be called while TSSolve() is active.

    5317: .seealso: TSConvergedReason
    5318: @*/
    5319: PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
    5320: {
    5323:   ts->reason = reason;
    5324:   return(0);
    5325: }

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

    5330:    Not Collective

    5332:    Input Parameter:
    5333: .  ts - the TS context

    5335:    Output Parameter:
    5336: .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()

    5338:    Level: beginner

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

    5343: .seealso: TSSetConvergenceTest(), TSConvergedReason
    5344: @*/
    5345: PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
    5346: {
    5350:   *ftime = ts->solvetime;
    5351:   return(0);
    5352: }

    5354: /*@
    5355:    TSGetSNESIterations - Gets the total number of nonlinear iterations
    5356:    used by the time integrator.

    5358:    Not Collective

    5360:    Input Parameter:
    5361: .  ts - TS context

    5363:    Output Parameter:
    5364: .  nits - number of nonlinear iterations

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

    5369:    Level: intermediate

    5371: .seealso:  TSGetKSPIterations()
    5372: @*/
    5373: PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
    5374: {
    5378:   *nits = ts->snes_its;
    5379:   return(0);
    5380: }

    5382: /*@
    5383:    TSGetKSPIterations - Gets the total number of linear iterations
    5384:    used by the time integrator.

    5386:    Not Collective

    5388:    Input Parameter:
    5389: .  ts - TS context

    5391:    Output Parameter:
    5392: .  lits - number of linear iterations

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

    5397:    Level: intermediate

    5399: .seealso:  TSGetSNESIterations(), SNESGetKSPIterations()
    5400: @*/
    5401: PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
    5402: {
    5406:   *lits = ts->ksp_its;
    5407:   return(0);
    5408: }

    5410: /*@
    5411:    TSGetStepRejections - Gets the total number of rejected steps.

    5413:    Not Collective

    5415:    Input Parameter:
    5416: .  ts - TS context

    5418:    Output Parameter:
    5419: .  rejects - number of steps rejected

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

    5424:    Level: intermediate

    5426: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetSNESFailures(), TSSetMaxSNESFailures(), TSSetErrorIfStepFails()
    5427: @*/
    5428: PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
    5429: {
    5433:   *rejects = ts->reject;
    5434:   return(0);
    5435: }

    5437: /*@
    5438:    TSGetSNESFailures - Gets the total number of failed SNES solves

    5440:    Not Collective

    5442:    Input Parameter:
    5443: .  ts - TS context

    5445:    Output Parameter:
    5446: .  fails - number of failed nonlinear solves

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

    5451:    Level: intermediate

    5453: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSSetMaxSNESFailures()
    5454: @*/
    5455: PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
    5456: {
    5460:   *fails = ts->num_snes_failures;
    5461:   return(0);
    5462: }

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

    5467:    Not Collective

    5469:    Input Parameter:
    5470: +  ts - TS context
    5471: -  rejects - maximum number of rejected steps, pass -1 for unlimited

    5473:    Notes:
    5474:    The counter is reset to zero for each step

    5476:    Options Database Key:
    5477:  .  -ts_max_reject - Maximum number of step rejections before a step fails

    5479:    Level: intermediate

    5481: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxSNESFailures(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
    5482: @*/
    5483: PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
    5484: {
    5487:   ts->max_reject = rejects;
    5488:   return(0);
    5489: }

    5491: /*@
    5492:    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves

    5494:    Not Collective

    5496:    Input Parameter:
    5497: +  ts - TS context
    5498: -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited

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

    5503:    Options Database Key:
    5504:  .  -ts_max_snes_failures - Maximum number of nonlinear solve failures

    5506:    Level: intermediate

    5508: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), SNESGetConvergedReason(), TSGetConvergedReason()
    5509: @*/
    5510: PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
    5511: {
    5514:   ts->max_snes_failures = fails;
    5515:   return(0);
    5516: }

    5518: /*@
    5519:    TSSetErrorIfStepFails - Error if no step succeeds

    5521:    Not Collective

    5523:    Input Parameter:
    5524: +  ts - TS context
    5525: -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure

    5527:    Options Database Key:
    5528:  .  -ts_error_if_step_fails - Error if no step succeeds

    5530:    Level: intermediate

    5532: .seealso:  TSGetSNESIterations(), TSGetKSPIterations(), TSSetMaxStepRejections(), TSGetStepRejections(), TSGetSNESFailures(), TSSetErrorIfStepFails(), TSGetConvergedReason()
    5533: @*/
    5534: PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
    5535: {
    5538:   ts->errorifstepfailed = err;
    5539:   return(0);
    5540: }

    5542: /*@C
    5543:    TSMonitorSolution - Monitors progress of the TS solvers by VecView() for the solution at each timestep. Normally the viewer is a binary file or a PetscDraw object

    5545:    Collective on TS

    5547:    Input Parameters:
    5548: +  ts - the TS context
    5549: .  step - current time-step
    5550: .  ptime - current time
    5551: .  u - current state
    5552: -  vf - viewer and its format

    5554:    Level: intermediate

    5556: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    5557: @*/
    5558: PetscErrorCode  TSMonitorSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
    5559: {

    5563:   PetscViewerPushFormat(vf->viewer,vf->format);
    5564:   VecView(u,vf->viewer);
    5565:   PetscViewerPopFormat(vf->viewer);
    5566:   return(0);
    5567: }

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

    5572:    Collective on TS

    5574:    Input Parameters:
    5575: +  ts - the TS context
    5576: .  step - current time-step
    5577: .  ptime - current time
    5578: .  u - current state
    5579: -  filenametemplate - string containing a format specifier for the integer time step (e.g. %03D)

    5581:    Level: intermediate

    5583:    Notes:
    5584:    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.
    5585:    These are named according to the file name template.

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

    5589: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView()
    5590: @*/
    5591: PetscErrorCode TSMonitorSolutionVTK(TS ts,PetscInt step,PetscReal ptime,Vec u,void *filenametemplate)
    5592: {
    5594:   char           filename[PETSC_MAX_PATH_LEN];
    5595:   PetscViewer    viewer;

    5598:   if (step < 0) return(0); /* -1 indicates interpolated solution */
    5599:   PetscSNPrintf(filename,sizeof(filename),(const char*)filenametemplate,step);
    5600:   PetscViewerVTKOpen(PetscObjectComm((PetscObject)ts),filename,FILE_MODE_WRITE,&viewer);
    5601:   VecView(u,viewer);
    5602:   PetscViewerDestroy(&viewer);
    5603:   return(0);
    5604: }

    5606: /*@C
    5607:    TSMonitorSolutionVTKDestroy - Destroy context for monitoring

    5609:    Collective on TS

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

    5614:    Level: intermediate

    5616:    Note:
    5617:    This function is normally passed to TSMonitorSet() along with TSMonitorSolutionVTK().

    5619: .seealso: TSMonitorSet(), TSMonitorSolutionVTK()
    5620: @*/
    5621: PetscErrorCode TSMonitorSolutionVTKDestroy(void *filenametemplate)
    5622: {

    5626:   PetscFree(*(char**)filenametemplate);
    5627:   return(0);
    5628: }

    5630: /*@
    5631:    TSGetAdapt - Get the adaptive controller context for the current method

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

    5635:    Input Arguments:
    5636: .  ts - time stepping context

    5638:    Output Arguments:
    5639: .  adapt - adaptive controller

    5641:    Level: intermediate

    5643: .seealso: TSAdapt, TSAdaptSetType(), TSAdaptChoose()
    5644: @*/
    5645: PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
    5646: {

    5652:   if (!ts->adapt) {
    5653:     TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt);
    5654:     PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt);
    5655:     PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1);
    5656:   }
    5657:   *adapt = ts->adapt;
    5658:   return(0);
    5659: }

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

    5664:    Logically Collective

    5666:    Input Arguments:
    5667: +  ts - time integration context
    5668: .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
    5669: .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
    5670: .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
    5671: -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present

    5673:    Options Database keys:
    5674: +  -ts_rtol <rtol> - relative tolerance for local truncation error
    5675: -  -ts_atol <atol> Absolute tolerance for local truncation error

    5677:    Notes:
    5678:    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
    5679:    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
    5680:    computed only for the differential or the algebraic part then this can be done using the vector of
    5681:    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
    5682:    differential part and infinity for the algebraic part, the LTE calculation will include only the
    5683:    differential variables.

    5685:    Level: beginner

    5687: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSGetTolerances()
    5688: @*/
    5689: PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
    5690: {

    5694:   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
    5695:   if (vatol) {
    5696:     PetscObjectReference((PetscObject)vatol);
    5697:     VecDestroy(&ts->vatol);
    5698:     ts->vatol = vatol;
    5699:   }
    5700:   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
    5701:   if (vrtol) {
    5702:     PetscObjectReference((PetscObject)vrtol);
    5703:     VecDestroy(&ts->vrtol);
    5704:     ts->vrtol = vrtol;
    5705:   }
    5706:   return(0);
    5707: }

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

    5712:    Logically Collective

    5714:    Input Arguments:
    5715: .  ts - time integration context

    5717:    Output Arguments:
    5718: +  atol - scalar absolute tolerances, NULL to ignore
    5719: .  vatol - vector of absolute tolerances, NULL to ignore
    5720: .  rtol - scalar relative tolerances, NULL to ignore
    5721: -  vrtol - vector of relative tolerances, NULL to ignore

    5723:    Level: beginner

    5725: .seealso: TS, TSAdapt, TSErrorWeightedNorm(), TSSetTolerances()
    5726: @*/
    5727: PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
    5728: {
    5730:   if (atol)  *atol  = ts->atol;
    5731:   if (vatol) *vatol = ts->vatol;
    5732:   if (rtol)  *rtol  = ts->rtol;
    5733:   if (vrtol) *vrtol = ts->vrtol;
    5734:   return(0);
    5735: }

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

    5740:    Collective on TS

    5742:    Input Arguments:
    5743: +  ts - time stepping context
    5744: .  U - state vector, usually ts->vec_sol
    5745: -  Y - state vector to be compared to U

    5747:    Output Arguments:
    5748: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
    5749: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
    5750: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

    5752:    Level: developer

    5754: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNormInfinity()
    5755: @*/
    5756: PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    5757: {
    5758:   PetscErrorCode    ierr;
    5759:   PetscInt          i,n,N,rstart;
    5760:   PetscInt          n_loc,na_loc,nr_loc;
    5761:   PetscReal         n_glb,na_glb,nr_glb;
    5762:   const PetscScalar *u,*y;
    5763:   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
    5764:   PetscReal         tol,tola,tolr;
    5765:   PetscReal         err_loc[6],err_glb[6];

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

    5779:   VecGetSize(U,&N);
    5780:   VecGetLocalSize(U,&n);
    5781:   VecGetOwnershipRange(U,&rstart,NULL);
    5782:   VecGetArrayRead(U,&u);
    5783:   VecGetArrayRead(Y,&y);
    5784:   sum  = 0.; n_loc  = 0;
    5785:   suma = 0.; na_loc = 0;
    5786:   sumr = 0.; nr_loc = 0;
    5787:   if (ts->vatol && ts->vrtol) {
    5788:     const PetscScalar *atol,*rtol;
    5789:     VecGetArrayRead(ts->vatol,&atol);
    5790:     VecGetArrayRead(ts->vrtol,&rtol);
    5791:     for (i=0; i<n; i++) {
    5792:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5793:       diff = PetscAbsScalar(y[i] - u[i]);
    5794:       tola = PetscRealPart(atol[i]);
    5795:       if (tola>0.){
    5796:         suma  += PetscSqr(diff/tola);
    5797:         na_loc++;
    5798:       }
    5799:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5800:       if (tolr>0.){
    5801:         sumr  += PetscSqr(diff/tolr);
    5802:         nr_loc++;
    5803:       }
    5804:       tol=tola+tolr;
    5805:       if (tol>0.){
    5806:         sum  += PetscSqr(diff/tol);
    5807:         n_loc++;
    5808:       }
    5809:     }
    5810:     VecRestoreArrayRead(ts->vatol,&atol);
    5811:     VecRestoreArrayRead(ts->vrtol,&rtol);
    5812:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
    5813:     const PetscScalar *atol;
    5814:     VecGetArrayRead(ts->vatol,&atol);
    5815:     for (i=0; i<n; i++) {
    5816:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5817:       diff = PetscAbsScalar(y[i] - u[i]);
    5818:       tola = PetscRealPart(atol[i]);
    5819:       if (tola>0.){
    5820:         suma  += PetscSqr(diff/tola);
    5821:         na_loc++;
    5822:       }
    5823:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5824:       if (tolr>0.){
    5825:         sumr  += PetscSqr(diff/tolr);
    5826:         nr_loc++;
    5827:       }
    5828:       tol=tola+tolr;
    5829:       if (tol>0.){
    5830:         sum  += PetscSqr(diff/tol);
    5831:         n_loc++;
    5832:       }
    5833:     }
    5834:     VecRestoreArrayRead(ts->vatol,&atol);
    5835:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
    5836:     const PetscScalar *rtol;
    5837:     VecGetArrayRead(ts->vrtol,&rtol);
    5838:     for (i=0; i<n; i++) {
    5839:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5840:       diff = PetscAbsScalar(y[i] - u[i]);
    5841:       tola = ts->atol;
    5842:       if (tola>0.){
    5843:         suma  += PetscSqr(diff/tola);
    5844:         na_loc++;
    5845:       }
    5846:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5847:       if (tolr>0.){
    5848:         sumr  += PetscSqr(diff/tolr);
    5849:         nr_loc++;
    5850:       }
    5851:       tol=tola+tolr;
    5852:       if (tol>0.){
    5853:         sum  += PetscSqr(diff/tol);
    5854:         n_loc++;
    5855:       }
    5856:     }
    5857:     VecRestoreArrayRead(ts->vrtol,&rtol);
    5858:   } else {                      /* scalar atol, scalar rtol */
    5859:     for (i=0; i<n; i++) {
    5860:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5861:       diff = PetscAbsScalar(y[i] - u[i]);
    5862:       tola = ts->atol;
    5863:       if (tola>0.){
    5864:         suma  += PetscSqr(diff/tola);
    5865:         na_loc++;
    5866:       }
    5867:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5868:       if (tolr>0.){
    5869:         sumr  += PetscSqr(diff/tolr);
    5870:         nr_loc++;
    5871:       }
    5872:       tol=tola+tolr;
    5873:       if (tol>0.){
    5874:         sum  += PetscSqr(diff/tol);
    5875:         n_loc++;
    5876:       }
    5877:     }
    5878:   }
    5879:   VecRestoreArrayRead(U,&u);
    5880:   VecRestoreArrayRead(Y,&y);

    5882:   err_loc[0] = sum;
    5883:   err_loc[1] = suma;
    5884:   err_loc[2] = sumr;
    5885:   err_loc[3] = (PetscReal)n_loc;
    5886:   err_loc[4] = (PetscReal)na_loc;
    5887:   err_loc[5] = (PetscReal)nr_loc;

    5889:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

    5891:   gsum   = err_glb[0];
    5892:   gsuma  = err_glb[1];
    5893:   gsumr  = err_glb[2];
    5894:   n_glb  = err_glb[3];
    5895:   na_glb = err_glb[4];
    5896:   nr_glb = err_glb[5];

    5898:   *norm  = 0.;
    5899:   if (n_glb>0.){*norm  = PetscSqrtReal(gsum  / n_glb);}
    5900:   *norma = 0.;
    5901:   if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
    5902:   *normr = 0.;
    5903:   if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

    5905:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
    5906:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
    5907:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
    5908:   return(0);
    5909: }

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

    5914:    Collective on TS

    5916:    Input Arguments:
    5917: +  ts - time stepping context
    5918: .  U - state vector, usually ts->vec_sol
    5919: -  Y - state vector to be compared to U

    5921:    Output Arguments:
    5922: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
    5923: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
    5924: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

    5926:    Level: developer

    5928: .seealso: TSErrorWeightedNorm(), TSErrorWeightedNorm2()
    5929: @*/
    5930: PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    5931: {
    5932:   PetscErrorCode    ierr;
    5933:   PetscInt          i,n,N,rstart;
    5934:   const PetscScalar *u,*y;
    5935:   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
    5936:   PetscReal         tol,tola,tolr,diff;
    5937:   PetscReal         err_loc[3],err_glb[3];

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

    5951:   VecGetSize(U,&N);
    5952:   VecGetLocalSize(U,&n);
    5953:   VecGetOwnershipRange(U,&rstart,NULL);
    5954:   VecGetArrayRead(U,&u);
    5955:   VecGetArrayRead(Y,&y);

    5957:   max=0.;
    5958:   maxa=0.;
    5959:   maxr=0.;

    5961:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
    5962:     const PetscScalar *atol,*rtol;
    5963:     VecGetArrayRead(ts->vatol,&atol);
    5964:     VecGetArrayRead(ts->vrtol,&rtol);

    5966:     for (i=0; i<n; i++) {
    5967:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5968:       diff = PetscAbsScalar(y[i] - u[i]);
    5969:       tola = PetscRealPart(atol[i]);
    5970:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5971:       tol  = tola+tolr;
    5972:       if (tola>0.){
    5973:         maxa = PetscMax(maxa,diff / tola);
    5974:       }
    5975:       if (tolr>0.){
    5976:         maxr = PetscMax(maxr,diff / tolr);
    5977:       }
    5978:       if (tol>0.){
    5979:         max = PetscMax(max,diff / tol);
    5980:       }
    5981:     }
    5982:     VecRestoreArrayRead(ts->vatol,&atol);
    5983:     VecRestoreArrayRead(ts->vrtol,&rtol);
    5984:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
    5985:     const PetscScalar *atol;
    5986:     VecGetArrayRead(ts->vatol,&atol);
    5987:     for (i=0; i<n; i++) {
    5988:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    5989:       diff = PetscAbsScalar(y[i] - u[i]);
    5990:       tola = PetscRealPart(atol[i]);
    5991:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    5992:       tol  = tola+tolr;
    5993:       if (tola>0.){
    5994:         maxa = PetscMax(maxa,diff / tola);
    5995:       }
    5996:       if (tolr>0.){
    5997:         maxr = PetscMax(maxr,diff / tolr);
    5998:       }
    5999:       if (tol>0.){
    6000:         max = PetscMax(max,diff / tol);
    6001:       }
    6002:     }
    6003:     VecRestoreArrayRead(ts->vatol,&atol);
    6004:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
    6005:     const PetscScalar *rtol;
    6006:     VecGetArrayRead(ts->vrtol,&rtol);

    6008:     for (i=0; i<n; i++) {
    6009:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6010:       diff = PetscAbsScalar(y[i] - u[i]);
    6011:       tola = ts->atol;
    6012:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6013:       tol  = tola+tolr;
    6014:       if (tola>0.){
    6015:         maxa = PetscMax(maxa,diff / tola);
    6016:       }
    6017:       if (tolr>0.){
    6018:         maxr = PetscMax(maxr,diff / tolr);
    6019:       }
    6020:       if (tol>0.){
    6021:         max = PetscMax(max,diff / tol);
    6022:       }
    6023:     }
    6024:     VecRestoreArrayRead(ts->vrtol,&rtol);
    6025:   } else {                      /* scalar atol, scalar rtol */

    6027:     for (i=0; i<n; i++) {
    6028:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6029:       diff = PetscAbsScalar(y[i] - u[i]);
    6030:       tola = ts->atol;
    6031:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6032:       tol  = tola+tolr;
    6033:       if (tola>0.){
    6034:         maxa = PetscMax(maxa,diff / tola);
    6035:       }
    6036:       if (tolr>0.){
    6037:         maxr = PetscMax(maxr,diff / tolr);
    6038:       }
    6039:       if (tol>0.){
    6040:         max = PetscMax(max,diff / tol);
    6041:       }
    6042:     }
    6043:   }
    6044:   VecRestoreArrayRead(U,&u);
    6045:   VecRestoreArrayRead(Y,&y);
    6046:   err_loc[0] = max;
    6047:   err_loc[1] = maxa;
    6048:   err_loc[2] = maxr;
    6049:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
    6050:   gmax   = err_glb[0];
    6051:   gmaxa  = err_glb[1];
    6052:   gmaxr  = err_glb[2];

    6054:   *norm = gmax;
    6055:   *norma = gmaxa;
    6056:   *normr = gmaxr;
    6057:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
    6058:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
    6059:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
    6060:   return(0);
    6061: }

    6063: /*@
    6064:    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances

    6066:    Collective on TS

    6068:    Input Arguments:
    6069: +  ts - time stepping context
    6070: .  U - state vector, usually ts->vec_sol
    6071: .  Y - state vector to be compared to U
    6072: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

    6074:    Output Arguments:
    6075: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
    6076: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
    6077: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

    6079:    Options Database Keys:
    6080: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

    6082:    Level: developer

    6084: .seealso: TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2(), TSErrorWeightedENorm
    6085: @*/
    6086: PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    6087: {

    6091:   if (wnormtype == NORM_2) {
    6092:     TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr);
    6093:   } else if (wnormtype == NORM_INFINITY) {
    6094:     TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr);
    6095:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
    6096:   return(0);
    6097: }

    6100: /*@
    6101:    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances

    6103:    Collective on TS

    6105:    Input Arguments:
    6106: +  ts - time stepping context
    6107: .  E - error vector
    6108: .  U - state vector, usually ts->vec_sol
    6109: -  Y - state vector, previous time step

    6111:    Output Arguments:
    6112: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
    6113: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
    6114: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

    6116:    Level: developer

    6118: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENormInfinity()
    6119: @*/
    6120: PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    6121: {
    6122:   PetscErrorCode    ierr;
    6123:   PetscInt          i,n,N,rstart;
    6124:   PetscInt          n_loc,na_loc,nr_loc;
    6125:   PetscReal         n_glb,na_glb,nr_glb;
    6126:   const PetscScalar *e,*u,*y;
    6127:   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
    6128:   PetscReal         tol,tola,tolr;
    6129:   PetscReal         err_loc[6],err_glb[6];

    6145:   VecGetSize(E,&N);
    6146:   VecGetLocalSize(E,&n);
    6147:   VecGetOwnershipRange(E,&rstart,NULL);
    6148:   VecGetArrayRead(E,&e);
    6149:   VecGetArrayRead(U,&u);
    6150:   VecGetArrayRead(Y,&y);
    6151:   sum  = 0.; n_loc  = 0;
    6152:   suma = 0.; na_loc = 0;
    6153:   sumr = 0.; nr_loc = 0;
    6154:   if (ts->vatol && ts->vrtol) {
    6155:     const PetscScalar *atol,*rtol;
    6156:     VecGetArrayRead(ts->vatol,&atol);
    6157:     VecGetArrayRead(ts->vrtol,&rtol);
    6158:     for (i=0; i<n; i++) {
    6159:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6160:       err = PetscAbsScalar(e[i]);
    6161:       tola = PetscRealPart(atol[i]);
    6162:       if (tola>0.){
    6163:         suma  += PetscSqr(err/tola);
    6164:         na_loc++;
    6165:       }
    6166:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6167:       if (tolr>0.){
    6168:         sumr  += PetscSqr(err/tolr);
    6169:         nr_loc++;
    6170:       }
    6171:       tol=tola+tolr;
    6172:       if (tol>0.){
    6173:         sum  += PetscSqr(err/tol);
    6174:         n_loc++;
    6175:       }
    6176:     }
    6177:     VecRestoreArrayRead(ts->vatol,&atol);
    6178:     VecRestoreArrayRead(ts->vrtol,&rtol);
    6179:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
    6180:     const PetscScalar *atol;
    6181:     VecGetArrayRead(ts->vatol,&atol);
    6182:     for (i=0; i<n; i++) {
    6183:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6184:       err = PetscAbsScalar(e[i]);
    6185:       tola = PetscRealPart(atol[i]);
    6186:       if (tola>0.){
    6187:         suma  += PetscSqr(err/tola);
    6188:         na_loc++;
    6189:       }
    6190:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6191:       if (tolr>0.){
    6192:         sumr  += PetscSqr(err/tolr);
    6193:         nr_loc++;
    6194:       }
    6195:       tol=tola+tolr;
    6196:       if (tol>0.){
    6197:         sum  += PetscSqr(err/tol);
    6198:         n_loc++;
    6199:       }
    6200:     }
    6201:     VecRestoreArrayRead(ts->vatol,&atol);
    6202:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
    6203:     const PetscScalar *rtol;
    6204:     VecGetArrayRead(ts->vrtol,&rtol);
    6205:     for (i=0; i<n; i++) {
    6206:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6207:       err = PetscAbsScalar(e[i]);
    6208:       tola = ts->atol;
    6209:       if (tola>0.){
    6210:         suma  += PetscSqr(err/tola);
    6211:         na_loc++;
    6212:       }
    6213:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6214:       if (tolr>0.){
    6215:         sumr  += PetscSqr(err/tolr);
    6216:         nr_loc++;
    6217:       }
    6218:       tol=tola+tolr;
    6219:       if (tol>0.){
    6220:         sum  += PetscSqr(err/tol);
    6221:         n_loc++;
    6222:       }
    6223:     }
    6224:     VecRestoreArrayRead(ts->vrtol,&rtol);
    6225:   } else {                      /* scalar atol, scalar rtol */
    6226:     for (i=0; i<n; i++) {
    6227:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6228:       err = PetscAbsScalar(e[i]);
    6229:       tola = ts->atol;
    6230:       if (tola>0.){
    6231:         suma  += PetscSqr(err/tola);
    6232:         na_loc++;
    6233:       }
    6234:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6235:       if (tolr>0.){
    6236:         sumr  += PetscSqr(err/tolr);
    6237:         nr_loc++;
    6238:       }
    6239:       tol=tola+tolr;
    6240:       if (tol>0.){
    6241:         sum  += PetscSqr(err/tol);
    6242:         n_loc++;
    6243:       }
    6244:     }
    6245:   }
    6246:   VecRestoreArrayRead(E,&e);
    6247:   VecRestoreArrayRead(U,&u);
    6248:   VecRestoreArrayRead(Y,&y);

    6250:   err_loc[0] = sum;
    6251:   err_loc[1] = suma;
    6252:   err_loc[2] = sumr;
    6253:   err_loc[3] = (PetscReal)n_loc;
    6254:   err_loc[4] = (PetscReal)na_loc;
    6255:   err_loc[5] = (PetscReal)nr_loc;

    6257:   MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts));

    6259:   gsum   = err_glb[0];
    6260:   gsuma  = err_glb[1];
    6261:   gsumr  = err_glb[2];
    6262:   n_glb  = err_glb[3];
    6263:   na_glb = err_glb[4];
    6264:   nr_glb = err_glb[5];

    6266:   *norm  = 0.;
    6267:   if (n_glb>0.){*norm  = PetscSqrtReal(gsum  / n_glb);}
    6268:   *norma = 0.;
    6269:   if (na_glb>0.){*norma = PetscSqrtReal(gsuma / na_glb);}
    6270:   *normr = 0.;
    6271:   if (nr_glb>0.){*normr = PetscSqrtReal(gsumr / nr_glb);}

    6273:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
    6274:   if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
    6275:   if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
    6276:   return(0);
    6277: }

    6279: /*@
    6280:    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
    6281:    Collective on TS

    6283:    Input Arguments:
    6284: +  ts - time stepping context
    6285: .  E - error vector
    6286: .  U - state vector, usually ts->vec_sol
    6287: -  Y - state vector, previous time step

    6289:    Output Arguments:
    6290: +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
    6291: .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
    6292: -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances

    6294:    Level: developer

    6296: .seealso: TSErrorWeightedENorm(), TSErrorWeightedENorm2()
    6297: @*/
    6298: PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    6299: {
    6300:   PetscErrorCode    ierr;
    6301:   PetscInt          i,n,N,rstart;
    6302:   const PetscScalar *e,*u,*y;
    6303:   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
    6304:   PetscReal         tol,tola,tolr;
    6305:   PetscReal         err_loc[3],err_glb[3];

    6321:   VecGetSize(E,&N);
    6322:   VecGetLocalSize(E,&n);
    6323:   VecGetOwnershipRange(E,&rstart,NULL);
    6324:   VecGetArrayRead(E,&e);
    6325:   VecGetArrayRead(U,&u);
    6326:   VecGetArrayRead(Y,&y);

    6328:   max=0.;
    6329:   maxa=0.;
    6330:   maxr=0.;

    6332:   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
    6333:     const PetscScalar *atol,*rtol;
    6334:     VecGetArrayRead(ts->vatol,&atol);
    6335:     VecGetArrayRead(ts->vrtol,&rtol);

    6337:     for (i=0; i<n; i++) {
    6338:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6339:       err = PetscAbsScalar(e[i]);
    6340:       tola = PetscRealPart(atol[i]);
    6341:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6342:       tol  = tola+tolr;
    6343:       if (tola>0.){
    6344:         maxa = PetscMax(maxa,err / tola);
    6345:       }
    6346:       if (tolr>0.){
    6347:         maxr = PetscMax(maxr,err / tolr);
    6348:       }
    6349:       if (tol>0.){
    6350:         max = PetscMax(max,err / tol);
    6351:       }
    6352:     }
    6353:     VecRestoreArrayRead(ts->vatol,&atol);
    6354:     VecRestoreArrayRead(ts->vrtol,&rtol);
    6355:   } else if (ts->vatol) {       /* vector atol, scalar rtol */
    6356:     const PetscScalar *atol;
    6357:     VecGetArrayRead(ts->vatol,&atol);
    6358:     for (i=0; i<n; i++) {
    6359:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6360:       err = PetscAbsScalar(e[i]);
    6361:       tola = PetscRealPart(atol[i]);
    6362:       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6363:       tol  = tola+tolr;
    6364:       if (tola>0.){
    6365:         maxa = PetscMax(maxa,err / tola);
    6366:       }
    6367:       if (tolr>0.){
    6368:         maxr = PetscMax(maxr,err / tolr);
    6369:       }
    6370:       if (tol>0.){
    6371:         max = PetscMax(max,err / tol);
    6372:       }
    6373:     }
    6374:     VecRestoreArrayRead(ts->vatol,&atol);
    6375:   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
    6376:     const PetscScalar *rtol;
    6377:     VecGetArrayRead(ts->vrtol,&rtol);

    6379:     for (i=0; i<n; i++) {
    6380:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6381:       err = PetscAbsScalar(e[i]);
    6382:       tola = ts->atol;
    6383:       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6384:       tol  = tola+tolr;
    6385:       if (tola>0.){
    6386:         maxa = PetscMax(maxa,err / tola);
    6387:       }
    6388:       if (tolr>0.){
    6389:         maxr = PetscMax(maxr,err / tolr);
    6390:       }
    6391:       if (tol>0.){
    6392:         max = PetscMax(max,err / tol);
    6393:       }
    6394:     }
    6395:     VecRestoreArrayRead(ts->vrtol,&rtol);
    6396:   } else {                      /* scalar atol, scalar rtol */

    6398:     for (i=0; i<n; i++) {
    6399:       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
    6400:       err = PetscAbsScalar(e[i]);
    6401:       tola = ts->atol;
    6402:       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
    6403:       tol  = tola+tolr;
    6404:       if (tola>0.){
    6405:         maxa = PetscMax(maxa,err / tola);
    6406:       }
    6407:       if (tolr>0.){
    6408:         maxr = PetscMax(maxr,err / tolr);
    6409:       }
    6410:       if (tol>0.){
    6411:         max = PetscMax(max,err / tol);
    6412:       }
    6413:     }
    6414:   }
    6415:   VecRestoreArrayRead(E,&e);
    6416:   VecRestoreArrayRead(U,&u);
    6417:   VecRestoreArrayRead(Y,&y);
    6418:   err_loc[0] = max;
    6419:   err_loc[1] = maxa;
    6420:   err_loc[2] = maxr;
    6421:   MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts));
    6422:   gmax   = err_glb[0];
    6423:   gmaxa  = err_glb[1];
    6424:   gmaxr  = err_glb[2];

    6426:   *norm = gmax;
    6427:   *norma = gmaxa;
    6428:   *normr = gmaxr;
    6429:   if (PetscIsInfOrNanScalar(*norm)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
    6430:     if (PetscIsInfOrNanScalar(*norma)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
    6431:     if (PetscIsInfOrNanScalar(*normr)) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
    6432:   return(0);
    6433: }

    6435: /*@
    6436:    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances

    6438:    Collective on TS

    6440:    Input Arguments:
    6441: +  ts - time stepping context
    6442: .  E - error vector
    6443: .  U - state vector, usually ts->vec_sol
    6444: .  Y - state vector, previous time step
    6445: -  wnormtype - norm type, either NORM_2 or NORM_INFINITY

    6447:    Output Arguments:
    6448: +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
    6449: .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
    6450: -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user

    6452:    Options Database Keys:
    6453: .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY

    6455:    Level: developer

    6457: .seealso: TSErrorWeightedENormInfinity(), TSErrorWeightedENorm2(), TSErrorWeightedNormInfinity(), TSErrorWeightedNorm2()
    6458: @*/
    6459: PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
    6460: {

    6464:   if (wnormtype == NORM_2) {
    6465:     TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr);
    6466:   } else if (wnormtype == NORM_INFINITY) {
    6467:     TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr);
    6468:   } else SETERRQ1(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
    6469:   return(0);
    6470: }

    6473: /*@
    6474:    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler

    6476:    Logically Collective on TS

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

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

    6485:    Level: intermediate

    6487: .seealso: TSGetCFLTime(), TSADAPTCFL
    6488: @*/
    6489: PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
    6490: {
    6493:   ts->cfltime_local = cfltime;
    6494:   ts->cfltime       = -1.;
    6495:   return(0);
    6496: }

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

    6501:    Collective on TS

    6503:    Input Arguments:
    6504: .  ts - time stepping context

    6506:    Output Arguments:
    6507: .  cfltime - maximum stable time step for forward Euler

    6509:    Level: advanced

    6511: .seealso: TSSetCFLTimeLocal()
    6512: @*/
    6513: PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
    6514: {

    6518:   if (ts->cfltime < 0) {
    6519:     MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts));
    6520:   }
    6521:   *cfltime = ts->cfltime;
    6522:   return(0);
    6523: }

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

    6528:    Input Parameters:
    6529: +  ts   - the TS context.
    6530: .  xl   - lower bound.
    6531: -  xu   - upper bound.

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

    6537:    Level: advanced

    6539: @*/
    6540: PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
    6541: {
    6543:   SNES           snes;

    6546:   TSGetSNES(ts,&snes);
    6547:   SNESVISetVariableBounds(snes,xl,xu);
    6548:   return(0);
    6549: }

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

    6555:    Collective on TS

    6557:    Input Parameters:
    6558: +  ts - the TS context
    6559: .  step - current time-step
    6560: .  ptime - current time
    6561: .  u - current solution
    6562: -  dctx - the TSMonitorLGCtx object that contains all the options for the monitoring, this is created with TSMonitorLGCtxCreate()

    6564:    Options Database:
    6565: .   -ts_monitor_lg_solution_variables

    6567:    Level: intermediate

    6569:    Notes:
    6570:     Each process in a parallel run displays its component solutions in a separate window

    6572: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGCtxCreate(), TSMonitorLGCtxSetVariableNames(), TSMonitorLGCtxGetVariableNames(),
    6573:            TSMonitorLGSetVariableNames(), TSMonitorLGGetVariableNames(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetDisplayVariables(),
    6574:            TSMonitorLGCtxSetTransform(), TSMonitorLGSetTransform(), TSMonitorLGError(), TSMonitorLGSNESIterations(), TSMonitorLGKSPIterations(),
    6575:            TSMonitorEnvelopeCtxCreate(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxDestroy(), TSMonitorEnvelop()
    6576: @*/
    6577: PetscErrorCode  TSMonitorLGSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
    6578: {
    6579:   PetscErrorCode    ierr;
    6580:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dctx;
    6581:   const PetscScalar *yy;
    6582:   Vec               v;

    6585:   if (step < 0) return(0); /* -1 indicates interpolated solution */
    6586:   if (!step) {
    6587:     PetscDrawAxis axis;
    6588:     PetscInt      dim;
    6589:     PetscDrawLGGetAxis(ctx->lg,&axis);
    6590:     PetscDrawAxisSetLabels(axis,"Solution as function of time","Time","Solution");
    6591:     if (!ctx->names) {
    6592:       PetscBool flg;
    6593:       /* user provides names of variables to plot but no names has been set so assume names are integer values */
    6594:       PetscOptionsHasName(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",&flg);
    6595:       if (flg) {
    6596:         PetscInt i,n;
    6597:         char     **names;
    6598:         VecGetSize(u,&n);
    6599:         PetscMalloc1(n+1,&names);
    6600:         for (i=0; i<n; i++) {
    6601:           PetscMalloc1(5,&names[i]);
    6602:           PetscSNPrintf(names[i],5,"%D",i);
    6603:         }
    6604:         names[n] = NULL;
    6605:         ctx->names = names;
    6606:       }
    6607:     }
    6608:     if (ctx->names && !ctx->displaynames) {
    6609:       char      **displaynames;
    6610:       PetscBool flg;
    6611:       VecGetLocalSize(u,&dim);
    6612:       PetscCalloc1(dim+1,&displaynames);
    6613:       PetscOptionsGetStringArray(((PetscObject)ts)->options,((PetscObject)ts)->prefix,"-ts_monitor_lg_solution_variables",displaynames,&dim,&flg);
    6614:       if (flg) {
    6615:         TSMonitorLGCtxSetDisplayVariables(ctx,(const char *const *)displaynames);
    6616:       }
    6617:       PetscStrArrayDestroy(&displaynames);
    6618:     }
    6619:     if (ctx->displaynames) {
    6620:       PetscDrawLGSetDimension(ctx->lg,ctx->ndisplayvariables);
    6621:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->displaynames);
    6622:     } else if (ctx->names) {
    6623:       VecGetLocalSize(u,&dim);
    6624:       PetscDrawLGSetDimension(ctx->lg,dim);
    6625:       PetscDrawLGSetLegend(ctx->lg,(const char *const *)ctx->names);
    6626:     } else {
    6627:       VecGetLocalSize(u,&dim);
    6628:       PetscDrawLGSetDimension(ctx->lg,dim);
    6629:     }
    6630:     PetscDrawLGReset(ctx->lg);
    6631:   }

    6633:   if (!ctx->transform) v = u;
    6634:   else {(*ctx->transform)(ctx->transformctx,u,&v);}
    6635:   VecGetArrayRead(v,&yy);
    6636:   if (ctx->displaynames) {
    6637:     PetscInt i;
    6638:     for (i=0; i<ctx->ndisplayvariables; i++)
    6639:       ctx->displayvalues[i] = PetscRealPart(yy[ctx->displayvariables[i]]);
    6640:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,ctx->displayvalues);
    6641:   } else {
    6642: #if defined(PETSC_USE_COMPLEX)
    6643:     PetscInt  i,n;
    6644:     PetscReal *yreal;
    6645:     VecGetLocalSize(v,&n);
    6646:     PetscMalloc1(n,&yreal);
    6647:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
    6648:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
    6649:     PetscFree(yreal);
    6650: #else
    6651:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
    6652: #endif
    6653:   }
    6654:   VecRestoreArrayRead(v,&yy);
    6655:   if (ctx->transform) {VecDestroy(&v);}

    6657:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    6658:     PetscDrawLGDraw(ctx->lg);
    6659:     PetscDrawLGSave(ctx->lg);
    6660:   }
    6661:   return(0);
    6662: }

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

    6667:    Collective on TS

    6669:    Input Parameters:
    6670: +  ts - the TS context
    6671: -  names - the names of the components, final string must be NULL

    6673:    Level: intermediate

    6675:    Notes:
    6676:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

    6678: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGCtxSetVariableNames()
    6679: @*/
    6680: PetscErrorCode  TSMonitorLGSetVariableNames(TS ts,const char * const *names)
    6681: {
    6682:   PetscErrorCode    ierr;
    6683:   PetscInt          i;

    6686:   for (i=0; i<ts->numbermonitors; i++) {
    6687:     if (ts->monitor[i] == TSMonitorLGSolution) {
    6688:       TSMonitorLGCtxSetVariableNames((TSMonitorLGCtx)ts->monitorcontext[i],names);
    6689:       break;
    6690:     }
    6691:   }
    6692:   return(0);
    6693: }

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

    6698:    Collective on TS

    6700:    Input Parameters:
    6701: +  ts - the TS context
    6702: -  names - the names of the components, final string must be NULL

    6704:    Level: intermediate

    6706: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables(), TSMonitorLGSetVariableNames()
    6707: @*/
    6708: PetscErrorCode  TSMonitorLGCtxSetVariableNames(TSMonitorLGCtx ctx,const char * const *names)
    6709: {
    6710:   PetscErrorCode    ierr;

    6713:   PetscStrArrayDestroy(&ctx->names);
    6714:   PetscStrArrayallocpy(names,&ctx->names);
    6715:   return(0);
    6716: }

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

    6721:    Collective on TS

    6723:    Input Parameter:
    6724: .  ts - the TS context

    6726:    Output Parameter:
    6727: .  names - the names of the components, final string must be NULL

    6729:    Level: intermediate

    6731:    Notes:
    6732:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

    6734: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
    6735: @*/
    6736: PetscErrorCode  TSMonitorLGGetVariableNames(TS ts,const char *const **names)
    6737: {
    6738:   PetscInt       i;

    6741:   *names = NULL;
    6742:   for (i=0; i<ts->numbermonitors; i++) {
    6743:     if (ts->monitor[i] == TSMonitorLGSolution) {
    6744:       TSMonitorLGCtx  ctx = (TSMonitorLGCtx) ts->monitorcontext[i];
    6745:       *names = (const char *const *)ctx->names;
    6746:       break;
    6747:     }
    6748:   }
    6749:   return(0);
    6750: }

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

    6755:    Collective on TS

    6757:    Input Parameters:
    6758: +  ctx - the TSMonitorLG context
    6759: -  displaynames - the names of the components, final string must be NULL

    6761:    Level: intermediate

    6763: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
    6764: @*/
    6765: PetscErrorCode  TSMonitorLGCtxSetDisplayVariables(TSMonitorLGCtx ctx,const char * const *displaynames)
    6766: {
    6767:   PetscInt          j = 0,k;
    6768:   PetscErrorCode    ierr;

    6771:   if (!ctx->names) return(0);
    6772:   PetscStrArrayDestroy(&ctx->displaynames);
    6773:   PetscStrArrayallocpy(displaynames,&ctx->displaynames);
    6774:   while (displaynames[j]) j++;
    6775:   ctx->ndisplayvariables = j;
    6776:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvariables);
    6777:   PetscMalloc1(ctx->ndisplayvariables,&ctx->displayvalues);
    6778:   j = 0;
    6779:   while (displaynames[j]) {
    6780:     k = 0;
    6781:     while (ctx->names[k]) {
    6782:       PetscBool flg;
    6783:       PetscStrcmp(displaynames[j],ctx->names[k],&flg);
    6784:       if (flg) {
    6785:         ctx->displayvariables[j] = k;
    6786:         break;
    6787:       }
    6788:       k++;
    6789:     }
    6790:     j++;
    6791:   }
    6792:   return(0);
    6793: }

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

    6798:    Collective on TS

    6800:    Input Parameters:
    6801: +  ts - the TS context
    6802: -  displaynames - the names of the components, final string must be NULL

    6804:    Notes:
    6805:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

    6807:    Level: intermediate

    6809: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames()
    6810: @*/
    6811: PetscErrorCode  TSMonitorLGSetDisplayVariables(TS ts,const char * const *displaynames)
    6812: {
    6813:   PetscInt          i;
    6814:   PetscErrorCode    ierr;

    6817:   for (i=0; i<ts->numbermonitors; i++) {
    6818:     if (ts->monitor[i] == TSMonitorLGSolution) {
    6819:       TSMonitorLGCtxSetDisplayVariables((TSMonitorLGCtx)ts->monitorcontext[i],displaynames);
    6820:       break;
    6821:     }
    6822:   }
    6823:   return(0);
    6824: }

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

    6829:    Collective on TS

    6831:    Input Parameters:
    6832: +  ts - the TS context
    6833: .  transform - the transform function
    6834: .  destroy - function to destroy the optional context
    6835: -  ctx - optional context used by transform function

    6837:    Notes:
    6838:     If the TS object does not have a TSMonitorLGCtx associated with it then this function is ignored

    6840:    Level: intermediate

    6842: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGCtxSetTransform()
    6843: @*/
    6844: PetscErrorCode  TSMonitorLGSetTransform(TS ts,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
    6845: {
    6846:   PetscInt          i;
    6847:   PetscErrorCode    ierr;

    6850:   for (i=0; i<ts->numbermonitors; i++) {
    6851:     if (ts->monitor[i] == TSMonitorLGSolution) {
    6852:       TSMonitorLGCtxSetTransform((TSMonitorLGCtx)ts->monitorcontext[i],transform,destroy,tctx);
    6853:     }
    6854:   }
    6855:   return(0);
    6856: }

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

    6861:    Collective on TSLGCtx

    6863:    Input Parameters:
    6864: +  ts - the TS context
    6865: .  transform - the transform function
    6866: .  destroy - function to destroy the optional context
    6867: -  ctx - optional context used by transform function

    6869:    Level: intermediate

    6871: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetVariableNames(), TSMonitorLGSetTransform()
    6872: @*/
    6873: PetscErrorCode  TSMonitorLGCtxSetTransform(TSMonitorLGCtx ctx,PetscErrorCode (*transform)(void*,Vec,Vec*),PetscErrorCode (*destroy)(void*),void *tctx)
    6874: {
    6876:   ctx->transform    = transform;
    6877:   ctx->transformdestroy = destroy;
    6878:   ctx->transformctx = tctx;
    6879:   return(0);
    6880: }

    6882: /*@C
    6883:    TSMonitorLGError - Monitors progress of the TS solvers by plotting each component of the error
    6884:        in a time based line graph

    6886:    Collective on TS

    6888:    Input Parameters:
    6889: +  ts - the TS context
    6890: .  step - current time-step
    6891: .  ptime - current time
    6892: .  u - current solution
    6893: -  dctx - TSMonitorLGCtx object created with TSMonitorLGCtxCreate()

    6895:    Level: intermediate

    6897:    Notes:
    6898:     Each process in a parallel run displays its component errors in a separate window

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

    6902:    Options Database Keys:
    6903: .  -ts_monitor_lg_error - create a graphical monitor of error history

    6905: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
    6906: @*/
    6907: PetscErrorCode  TSMonitorLGError(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dummy)
    6908: {
    6909:   PetscErrorCode    ierr;
    6910:   TSMonitorLGCtx    ctx = (TSMonitorLGCtx)dummy;
    6911:   const PetscScalar *yy;
    6912:   Vec               y;

    6915:   if (!step) {
    6916:     PetscDrawAxis axis;
    6917:     PetscInt      dim;
    6918:     PetscDrawLGGetAxis(ctx->lg,&axis);
    6919:     PetscDrawAxisSetLabels(axis,"Error in solution as function of time","Time","Error");
    6920:     VecGetLocalSize(u,&dim);
    6921:     PetscDrawLGSetDimension(ctx->lg,dim);
    6922:     PetscDrawLGReset(ctx->lg);
    6923:   }
    6924:   VecDuplicate(u,&y);
    6925:   TSComputeSolutionFunction(ts,ptime,y);
    6926:   VecAXPY(y,-1.0,u);
    6927:   VecGetArrayRead(y,&yy);
    6928: #if defined(PETSC_USE_COMPLEX)
    6929:   {
    6930:     PetscReal *yreal;
    6931:     PetscInt  i,n;
    6932:     VecGetLocalSize(y,&n);
    6933:     PetscMalloc1(n,&yreal);
    6934:     for (i=0; i<n; i++) yreal[i] = PetscRealPart(yy[i]);
    6935:     PetscDrawLGAddCommonPoint(ctx->lg,ptime,yreal);
    6936:     PetscFree(yreal);
    6937:   }
    6938: #else
    6939:   PetscDrawLGAddCommonPoint(ctx->lg,ptime,yy);
    6940: #endif
    6941:   VecRestoreArrayRead(y,&yy);
    6942:   VecDestroy(&y);
    6943:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    6944:     PetscDrawLGDraw(ctx->lg);
    6945:     PetscDrawLGSave(ctx->lg);
    6946:   }
    6947:   return(0);
    6948: }

    6950: /*@C
    6951:    TSMonitorSPSwarmSolution - Graphically displays phase plots of DMSwarm particles on a scatter plot

    6953:    Input Parameters:
    6954: +  ts - the TS context
    6955: .  step - current time-step
    6956: .  ptime - current time
    6957: .  u - current solution
    6958: -  dctx - the TSMonitorSPCtx object that contains all the options for the monitoring, this is created with TSMonitorSPCtxCreate()

    6960:    Options Database:
    6961: .   -ts_monitor_sp_swarm

    6963:    Level: intermediate

    6965: @*/
    6966: PetscErrorCode TSMonitorSPSwarmSolution(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
    6967: {
    6968:   PetscErrorCode    ierr;
    6969:   TSMonitorSPCtx    ctx = (TSMonitorSPCtx)dctx;
    6970:   const PetscScalar *yy;
    6971:   PetscReal       *y,*x;
    6972:   PetscInt          Np, p, dim=2;
    6973:   DM                dm;

    6977:   if (step < 0) return(0); /* -1 indicates interpolated solution */
    6978:   if (!step) {
    6979:     PetscDrawAxis axis;
    6980:     PetscDrawSPGetAxis(ctx->sp,&axis);
    6981:     PetscDrawAxisSetLabels(axis,"Particles","X","Y");
    6982:     PetscDrawAxisSetLimits(axis, -5, 5, -5, 5);
    6983:     PetscDrawAxisSetHoldLimits(axis, PETSC_TRUE);
    6984:     TSGetDM(ts, &dm);
    6985:     DMGetDimension(dm, &dim);
    6986:     if (dim!=2) SETERRQ(PETSC_COMM_SELF, ierr, "Dimensions improper for monitor arguments! Current support: two dimensions.");
    6987:     VecGetLocalSize(u, &Np);
    6988:     Np /= 2*dim;
    6989:     PetscDrawSPSetDimension(ctx->sp, Np);
    6990:     PetscDrawSPReset(ctx->sp);
    6991:   }

    6993:   VecGetLocalSize(u, &Np);
    6994:   Np /= 2*dim;
    6995:   VecGetArrayRead(u,&yy);
    6996:   PetscMalloc2(Np, &x, Np, &y);
    6997:   /* get points from solution vector */
    6998:   for (p=0; p<Np; ++p){
    6999:     x[p] = PetscRealPart(yy[2*dim*p]);
    7000:     y[p] = PetscRealPart(yy[2*dim*p+1]);
    7001:   }
    7002:   VecRestoreArrayRead(u,&yy);

    7004:   if (((ctx->howoften > 0) && (!(step % ctx->howoften))) || ((ctx->howoften == -1) && ts->reason)) {
    7005:     PetscDrawSPAddPoint(ctx->sp,x,y);
    7006:     PetscDrawSPDraw(ctx->sp,PETSC_FALSE);
    7007:     PetscDrawSPSave(ctx->sp);
    7008:   }

    7010:   PetscFree2(x, y);

    7012:   return(0);
    7013: }

    7017: /*@C
    7018:    TSMonitorError - Monitors progress of the TS solvers by printing the 2 norm of the error at each timestep

    7020:    Collective on TS

    7022:    Input Parameters:
    7023: +  ts - the TS context
    7024: .  step - current time-step
    7025: .  ptime - current time
    7026: .  u - current solution
    7027: -  dctx - unused context

    7029:    Level: intermediate

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

    7033:    Options Database Keys:
    7034: .  -ts_monitor_error - create a graphical monitor of error history

    7036: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSSetSolutionFunction()
    7037: @*/
    7038: PetscErrorCode  TSMonitorError(TS ts,PetscInt step,PetscReal ptime,Vec u,PetscViewerAndFormat *vf)
    7039: {
    7040:   PetscErrorCode    ierr;
    7041:   Vec               y;
    7042:   PetscReal         nrm;
    7043:   PetscBool         flg;

    7046:   VecDuplicate(u,&y);
    7047:   TSComputeSolutionFunction(ts,ptime,y);
    7048:   VecAXPY(y,-1.0,u);
    7049:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERASCII,&flg);
    7050:   if (flg) {
    7051:     VecNorm(y,NORM_2,&nrm);
    7052:     PetscViewerASCIIPrintf(vf->viewer,"2-norm of error %g\n",(double)nrm);
    7053:   }
    7054:   PetscObjectTypeCompare((PetscObject)vf->viewer,PETSCVIEWERDRAW,&flg);
    7055:   if (flg) {
    7056:     VecView(y,vf->viewer);
    7057:   }
    7058:   VecDestroy(&y);
    7059:   return(0);
    7060: }

    7062: PetscErrorCode TSMonitorLGSNESIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
    7063: {
    7064:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    7065:   PetscReal      x   = ptime,y;
    7067:   PetscInt       its;

    7070:   if (n < 0) return(0); /* -1 indicates interpolated solution */
    7071:   if (!n) {
    7072:     PetscDrawAxis axis;
    7073:     PetscDrawLGGetAxis(ctx->lg,&axis);
    7074:     PetscDrawAxisSetLabels(axis,"Nonlinear iterations as function of time","Time","SNES Iterations");
    7075:     PetscDrawLGReset(ctx->lg);
    7076:     ctx->snes_its = 0;
    7077:   }
    7078:   TSGetSNESIterations(ts,&its);
    7079:   y    = its - ctx->snes_its;
    7080:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    7081:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
    7082:     PetscDrawLGDraw(ctx->lg);
    7083:     PetscDrawLGSave(ctx->lg);
    7084:   }
    7085:   ctx->snes_its = its;
    7086:   return(0);
    7087: }

    7089: PetscErrorCode TSMonitorLGKSPIterations(TS ts,PetscInt n,PetscReal ptime,Vec v,void *monctx)
    7090: {
    7091:   TSMonitorLGCtx ctx = (TSMonitorLGCtx) monctx;
    7092:   PetscReal      x   = ptime,y;
    7094:   PetscInt       its;

    7097:   if (n < 0) return(0); /* -1 indicates interpolated solution */
    7098:   if (!n) {
    7099:     PetscDrawAxis axis;
    7100:     PetscDrawLGGetAxis(ctx->lg,&axis);
    7101:     PetscDrawAxisSetLabels(axis,"Linear iterations as function of time","Time","KSP Iterations");
    7102:     PetscDrawLGReset(ctx->lg);
    7103:     ctx->ksp_its = 0;
    7104:   }
    7105:   TSGetKSPIterations(ts,&its);
    7106:   y    = its - ctx->ksp_its;
    7107:   PetscDrawLGAddPoint(ctx->lg,&x,&y);
    7108:   if (((ctx->howoften > 0) && (!(n % ctx->howoften)) && (n > -1)) || ((ctx->howoften == -1) && (n == -1))) {
    7109:     PetscDrawLGDraw(ctx->lg);
    7110:     PetscDrawLGSave(ctx->lg);
    7111:   }
    7112:   ctx->ksp_its = its;
    7113:   return(0);
    7114: }

    7116: /*@
    7117:    TSComputeLinearStability - computes the linear stability function at a point

    7119:    Collective on TS

    7121:    Input Parameters:
    7122: +  ts - the TS context
    7123: -  xr,xi - real and imaginary part of input arguments

    7125:    Output Parameters:
    7126: .  yr,yi - real and imaginary part of function value

    7128:    Level: developer

    7130: .seealso: TSSetRHSFunction(), TSComputeIFunction()
    7131: @*/
    7132: PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
    7133: {

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

    7143: /* ------------------------------------------------------------------------*/
    7144: /*@C
    7145:    TSMonitorEnvelopeCtxCreate - Creates a context for use with TSMonitorEnvelope()

    7147:    Collective on TS

    7149:    Input Parameters:
    7150: .  ts  - the ODE solver object

    7152:    Output Parameter:
    7153: .  ctx - the context

    7155:    Level: intermediate

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

    7159: @*/
    7160: PetscErrorCode  TSMonitorEnvelopeCtxCreate(TS ts,TSMonitorEnvelopeCtx *ctx)
    7161: {

    7165:   PetscNew(ctx);
    7166:   return(0);
    7167: }

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

    7172:    Collective on TS

    7174:    Input Parameters:
    7175: +  ts - the TS context
    7176: .  step - current time-step
    7177: .  ptime - current time
    7178: .  u  - current solution
    7179: -  dctx - the envelope context

    7181:    Options Database:
    7182: .  -ts_monitor_envelope

    7184:    Level: intermediate

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

    7189: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorEnvelopeGetBounds(), TSMonitorEnvelopeCtxCreate()
    7190: @*/
    7191: PetscErrorCode  TSMonitorEnvelope(TS ts,PetscInt step,PetscReal ptime,Vec u,void *dctx)
    7192: {
    7193:   PetscErrorCode       ierr;
    7194:   TSMonitorEnvelopeCtx ctx = (TSMonitorEnvelopeCtx)dctx;

    7197:   if (!ctx->max) {
    7198:     VecDuplicate(u,&ctx->max);
    7199:     VecDuplicate(u,&ctx->min);
    7200:     VecCopy(u,ctx->max);
    7201:     VecCopy(u,ctx->min);
    7202:   } else {
    7203:     VecPointwiseMax(ctx->max,u,ctx->max);
    7204:     VecPointwiseMin(ctx->min,u,ctx->min);
    7205:   }
    7206:   return(0);
    7207: }

    7209: /*@C
    7210:    TSMonitorEnvelopeGetBounds - Gets the bounds for the components of the solution

    7212:    Collective on TS

    7214:    Input Parameter:
    7215: .  ts - the TS context

    7217:    Output Parameter:
    7218: +  max - the maximum values
    7219: -  min - the minimum values

    7221:    Notes:
    7222:     If the TS does not have a TSMonitorEnvelopeCtx associated with it then this function is ignored

    7224:    Level: intermediate

    7226: .seealso: TSMonitorSet(), TSMonitorDefault(), VecView(), TSMonitorLGSetDisplayVariables()
    7227: @*/
    7228: PetscErrorCode  TSMonitorEnvelopeGetBounds(TS ts,Vec *max,Vec *min)
    7229: {
    7230:   PetscInt i;

    7233:   if (max) *max = NULL;
    7234:   if (min) *min = NULL;
    7235:   for (i=0; i<ts->numbermonitors; i++) {
    7236:     if (ts->monitor[i] == TSMonitorEnvelope) {
    7237:       TSMonitorEnvelopeCtx  ctx = (TSMonitorEnvelopeCtx) ts->monitorcontext[i];
    7238:       if (max) *max = ctx->max;
    7239:       if (min) *min = ctx->min;
    7240:       break;
    7241:     }
    7242:   }
    7243:   return(0);
    7244: }

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

    7249:    Collective on TSMonitorEnvelopeCtx

    7251:    Input Parameter:
    7252: .  ctx - the monitor context

    7254:    Level: intermediate

    7256: .seealso: TSMonitorLGCtxCreate(),  TSMonitorSet(), TSMonitorLGTimeStep()
    7257: @*/
    7258: PetscErrorCode  TSMonitorEnvelopeCtxDestroy(TSMonitorEnvelopeCtx *ctx)
    7259: {

    7263:   VecDestroy(&(*ctx)->min);
    7264:   VecDestroy(&(*ctx)->max);
    7265:   PetscFree(*ctx);
    7266:   return(0);
    7267: }

    7269: /*@
    7270:    TSRestartStep - Flags the solver to restart the next step

    7272:    Collective on TS

    7274:    Input Parameter:
    7275: .  ts - the TS context obtained from TSCreate()

    7277:    Level: advanced

    7279:    Notes:
    7280:    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
    7281:    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
    7282:    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
    7283:    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
    7284:    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
    7285:    discontinuous source terms).

    7287: .seealso: TSSolve(), TSSetPreStep(), TSSetPostStep()
    7288: @*/
    7289: PetscErrorCode TSRestartStep(TS ts)
    7290: {
    7293:   ts->steprestart = PETSC_TRUE;
    7294:   return(0);
    7295: }

    7297: /*@
    7298:    TSRollBack - Rolls back one time step

    7300:    Collective on TS

    7302:    Input Parameter:
    7303: .  ts - the TS context obtained from TSCreate()

    7305:    Level: advanced

    7307: .seealso: TSCreate(), TSSetUp(), TSDestroy(), TSSolve(), TSSetPreStep(), TSSetPreStage(), TSInterpolate()
    7308: @*/
    7309: PetscErrorCode  TSRollBack(TS ts)
    7310: {

    7315:   if (ts->steprollback) SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
    7316:   if (!ts->ops->rollback) SETERRQ1(PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
    7317:   (*ts->ops->rollback)(ts);
    7318:   ts->time_step = ts->ptime - ts->ptime_prev;
    7319:   ts->ptime = ts->ptime_prev;
    7320:   ts->ptime_prev = ts->ptime_prev_rollback;
    7321:   ts->steps--;
    7322:   ts->steprollback = PETSC_TRUE;
    7323:   return(0);
    7324: }

    7326: /*@
    7327:    TSGetStages - Get the number of stages and stage values

    7329:    Input Parameter:
    7330: .  ts - the TS context obtained from TSCreate()

    7332:    Output Parameters:
    7333: +  ns - the number of stages
    7334: -  Y - the current stage vectors

    7336:    Level: advanced

    7338:    Notes: Both ns and Y can be NULL.

    7340: .seealso: TSCreate()
    7341: @*/
    7342: PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
    7343: {

    7350:   if (!ts->ops->getstages) {
    7351:     if (ns) *ns = 0;
    7352:     if (Y) *Y = NULL;
    7353:   } else {
    7354:     (*ts->ops->getstages)(ts,ns,Y);
    7355:   }
    7356:   return(0);
    7357: }

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

    7362:   Collective on SNES

    7364:   Input Parameters:
    7365: + ts - the TS context
    7366: . t - current timestep
    7367: . U - state vector
    7368: . Udot - time derivative of state vector
    7369: . shift - shift to apply, see note below
    7370: - ctx - an optional user context

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

    7376:   Level: intermediate

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

    7381:   dF/dU + shift*dF/dUdot

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

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

    7390: .seealso: TSSetIJacobian(), MatFDColoringCreate(), MatFDColoringSetFunction()
    7391: @*/
    7392: PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
    7393: {
    7394:   SNES           snes;
    7395:   MatFDColoring  color;
    7396:   PetscBool      hascolor, matcolor = PETSC_FALSE;

    7400:   PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL);
    7401:   PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color);
    7402:   if (!color) {
    7403:     DM         dm;
    7404:     ISColoring iscoloring;

    7406:     TSGetDM(ts, &dm);
    7407:     DMHasColoring(dm, &hascolor);
    7408:     if (hascolor && !matcolor) {
    7409:       DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring);
    7410:       MatFDColoringCreate(B, iscoloring, &color);
    7411:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
    7412:       MatFDColoringSetFromOptions(color);
    7413:       MatFDColoringSetUp(B, iscoloring, color);
    7414:       ISColoringDestroy(&iscoloring);
    7415:     } else {
    7416:       MatColoring mc;

    7418:       MatColoringCreate(B, &mc);
    7419:       MatColoringSetDistance(mc, 2);
    7420:       MatColoringSetType(mc, MATCOLORINGSL);
    7421:       MatColoringSetFromOptions(mc);
    7422:       MatColoringApply(mc, &iscoloring);
    7423:       MatColoringDestroy(&mc);
    7424:       MatFDColoringCreate(B, iscoloring, &color);
    7425:       MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts);
    7426:       MatFDColoringSetFromOptions(color);
    7427:       MatFDColoringSetUp(B, iscoloring, color);
    7428:       ISColoringDestroy(&iscoloring);
    7429:     }
    7430:     PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color);
    7431:     PetscObjectDereference((PetscObject) color);
    7432:   }
    7433:   TSGetSNES(ts, &snes);
    7434:   MatFDColoringApply(B, color, U, snes);
    7435:   if (J != B) {
    7436:     MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY);
    7437:     MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY);
    7438:   }
    7439:   return(0);
    7440: }

    7442: /*@
    7443:     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid

    7445:     Input Parameters:
    7446: +    ts - the TS context
    7447: -    func - function called within TSFunctionDomainError

    7449:     Calling sequence of func:
    7450: $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)

    7452: +   ts - the TS context
    7453: .   time - the current time (of the stage)
    7454: .   state - the state to check if it is valid
    7455: -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable

    7457:     Level: intermediate

    7459:     Notes:
    7460:       If an implicit ODE solver is being used then, in addition to providing this routine, the
    7461:       user's code should call SNESSetFunctionDomainError() when domain errors occur during
    7462:       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
    7463:       Use TSGetSNES() to obtain the SNES object

    7465:     Developer Notes:
    7466:       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
    7467:       since one takes a function pointer and the other does not.

    7469: .seealso: TSAdaptCheckStage(), TSFunctionDomainError(), SNESSetFunctionDomainError(), TSGetSNES()
    7470: @*/

    7472: PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
    7473: {
    7476:   ts->functiondomainerror = func;
    7477:   return(0);
    7478: }

    7480: /*@
    7481:     TSFunctionDomainError - Checks if the current state is valid

    7483:     Input Parameters:
    7484: +    ts - the TS context
    7485: .    stagetime - time of the simulation
    7486: -    Y - state vector to check.

    7488:     Output Parameter:
    7489: .    accept - Set to PETSC_FALSE if the current state vector is valid.

    7491:     Note:
    7492:     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
    7493:     to check if the current state is valid.

    7495:     Level: developer

    7497: .seealso: TSSetFunctionDomainError()
    7498: @*/
    7499: PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
    7500: {
    7503:   *accept = PETSC_TRUE;
    7504:   if (ts->functiondomainerror) {
    7505:     PetscStackCallStandard((*ts->functiondomainerror),(ts,stagetime,Y,accept));
    7506:   }
    7507:   return(0);
    7508: }

    7510: /*@C
    7511:   TSClone - This function clones a time step object.

    7513:   Collective

    7515:   Input Parameter:
    7516: . tsin    - The input TS

    7518:   Output Parameter:
    7519: . tsout   - The output TS (cloned)

    7521:   Notes:
    7522:   This function is used to create a clone of a TS object. It is used in ARKIMEX for initializing the slope for first stage explicit methods. It will likely be replaced in the future with a mechanism of switching methods on the fly.

    7524:   When using TSDestroy() on a clone the user has to first reset the correct TS reference in the embedded SNES object: e.g.: by running SNES snes_dup=NULL; TSGetSNES(ts,&snes_dup); TSSetSNES(ts,snes_dup);

    7526:   Level: developer

    7528: .seealso: TSCreate(), TSSetType(), TSSetUp(), TSDestroy(), TSSetProblemType()
    7529: @*/
    7530: PetscErrorCode  TSClone(TS tsin, TS *tsout)
    7531: {
    7532:   TS             t;
    7534:   SNES           snes_start;
    7535:   DM             dm;
    7536:   TSType         type;

    7540:   *tsout = NULL;

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

    7544:   /* General TS description */
    7545:   t->numbermonitors    = 0;
    7546:   t->setupcalled       = 0;
    7547:   t->ksp_its           = 0;
    7548:   t->snes_its          = 0;
    7549:   t->nwork             = 0;
    7550:   t->rhsjacobian.time  = PETSC_MIN_REAL;
    7551:   t->rhsjacobian.scale = 1.;
    7552:   t->ijacobian.shift   = 1.;

    7554:   TSGetSNES(tsin,&snes_start);
    7555:   TSSetSNES(t,snes_start);

    7557:   TSGetDM(tsin,&dm);
    7558:   TSSetDM(t,dm);

    7560:   t->adapt = tsin->adapt;
    7561:   PetscObjectReference((PetscObject)t->adapt);

    7563:   t->trajectory = tsin->trajectory;
    7564:   PetscObjectReference((PetscObject)t->trajectory);

    7566:   t->event = tsin->event;
    7567:   if (t->event) t->event->refct++;

    7569:   t->problem_type      = tsin->problem_type;
    7570:   t->ptime             = tsin->ptime;
    7571:   t->ptime_prev        = tsin->ptime_prev;
    7572:   t->time_step         = tsin->time_step;
    7573:   t->max_time          = tsin->max_time;
    7574:   t->steps             = tsin->steps;
    7575:   t->max_steps         = tsin->max_steps;
    7576:   t->equation_type     = tsin->equation_type;
    7577:   t->atol              = tsin->atol;
    7578:   t->rtol              = tsin->rtol;
    7579:   t->max_snes_failures = tsin->max_snes_failures;
    7580:   t->max_reject        = tsin->max_reject;
    7581:   t->errorifstepfailed = tsin->errorifstepfailed;

    7583:   TSGetType(tsin,&type);
    7584:   TSSetType(t,type);

    7586:   t->vec_sol           = NULL;

    7588:   t->cfltime          = tsin->cfltime;
    7589:   t->cfltime_local    = tsin->cfltime_local;
    7590:   t->exact_final_time = tsin->exact_final_time;

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

    7594:   if (((PetscObject)tsin)->fortran_func_pointers) {
    7595:     PetscInt i;
    7596:     PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers);
    7597:     for (i=0; i<10; i++) {
    7598:       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
    7599:     }
    7600:   }
    7601:   *tsout = t;
    7602:   return(0);
    7603: }

    7605: static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
    7606: {
    7608:   TS             ts = (TS) ctx;

    7611:   TSComputeRHSFunction(ts,0,x,y);
    7612:   return(0);
    7613: }

    7615: /*@
    7616:     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.

    7618:    Logically Collective on TS

    7620:     Input Parameters:
    7621:     TS - the time stepping routine

    7623:    Output Parameter:
    7624: .   flg - PETSC_TRUE if the multiply is likely correct

    7626:    Options Database:
    7627:  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator

    7629:    Level: advanced

    7631:    Notes:
    7632:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

    7634: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTestTranspose()
    7635: @*/
    7636: PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
    7637: {
    7638:   Mat            J,B;
    7640:   TSRHSJacobian  func;
    7641:   void*          ctx;

    7644:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
    7645:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
    7646:   MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
    7647:   return(0);
    7648: }

    7650: /*@C
    7651:     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.

    7653:    Logically Collective on TS

    7655:     Input Parameters:
    7656:     TS - the time stepping routine

    7658:    Output Parameter:
    7659: .   flg - PETSC_TRUE if the multiply is likely correct

    7661:    Options Database:
    7662: .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator

    7664:    Notes:
    7665:     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian

    7667:    Level: advanced

    7669: .seealso: MatCreateShell(), MatShellGetContext(), MatShellGetOperation(), MatShellTestMultTranspose(), TSRHSJacobianTest()
    7670: @*/
    7671: PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
    7672: {
    7673:   Mat            J,B;
    7675:   void           *ctx;
    7676:   TSRHSJacobian  func;

    7679:   TSGetRHSJacobian(ts,&J,&B,&func,&ctx);
    7680:   (*func)(ts,0.0,ts->vec_sol,J,B,ctx);
    7681:   MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg);
    7682:   return(0);
    7683: }

    7685: /*@
    7686:   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.

    7688:   Logically collective

    7690:   Input Parameter:
    7691: +  ts - timestepping context
    7692: -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

    7694:   Options Database:
    7695: .   -ts_use_splitrhsfunction - <true,false>

    7697:   Notes:
    7698:     This is only useful for multirate methods

    7700:   Level: intermediate

    7702: .seealso: TSGetUseSplitRHSFunction()
    7703: @*/
    7704: PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
    7705: {
    7708:   ts->use_splitrhsfunction = use_splitrhsfunction;
    7709:   return(0);
    7710: }

    7712: /*@
    7713:   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.

    7715:   Not collective

    7717:   Input Parameter:
    7718: .  ts - timestepping context

    7720:   Output Parameter:
    7721: .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used

    7723:   Level: intermediate

    7725: .seealso: TSSetUseSplitRHSFunction()
    7726: @*/
    7727: PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
    7728: {
    7731:   *use_splitrhsfunction = ts->use_splitrhsfunction;
    7732:   return(0);
    7733: }

    7735: /*@
    7736:     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.

    7738:    Logically  Collective on ts

    7740:    Input Parameters:
    7741: +  ts - the time-stepper
    7742: -  str - the structure (the default is UNKNOWN_NONZERO_PATTERN)

    7744:    Level: intermediate

    7746:    Notes:
    7747:      When the relationship between the nonzero structures is known and supplied the solution process can be much faster

    7749: .seealso: MatAXPY(), MatStructure
    7750:  @*/
    7751: PetscErrorCode TSSetMatStructure(TS ts,MatStructure str)
    7752: {
    7755:   ts->axpy_pattern = str;
    7756:   return(0);
    7757: }