xref: /petsc/src/ts/interface/ts.c (revision 1e66621cd1d96a997273abbd33b5764108d71b04)
1af0996ceSBarry Smith #include <petsc/private/tsimpl.h>        /*I "petscts.h"  I*/
2496e6a7aSJed Brown #include <petscdmshell.h>
31e25c274SJed Brown #include <petscdmda.h>
42d5ee99bSBarry Smith #include <petscviewer.h>
52d5ee99bSBarry Smith #include <petscdraw.h>
6900f6b5bSMatthew G. Knepley #include <petscconvest.h>
7d763cef2SBarry Smith 
81c167fc2SEmil Constantinescu #define SkipSmallValue(a,b,tol) if (PetscAbsScalar(a)< tol || PetscAbsScalar(b)< tol) continue;
91c167fc2SEmil Constantinescu 
10d5ba7fb7SMatthew Knepley /* Logging support */
11d74926cbSBarry Smith PetscClassId  TS_CLASSID, DMTS_CLASSID;
12a05bf03eSHong Zhang PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
13d405a339SMatthew Knepley 
14c793f718SLisandro Dalcin const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED","STEPOVER","INTERPOLATE","MATCHSTEP","TSExactFinalTimeOption","TS_EXACTFINALTIME_",NULL};
1549354f04SShri Abhyankar 
162ffb9264SLisandro Dalcin static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)
172ffb9264SLisandro Dalcin {
182ffb9264SLisandro Dalcin   PetscFunctionBegin;
19b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt,TSADAPT_CLASSID,1);
20b92453a8SLisandro Dalcin   PetscValidCharPointer(default_type,2);
21*1e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt,default_type));
222ffb9264SLisandro Dalcin   PetscFunctionReturn(0);
232ffb9264SLisandro Dalcin }
242ffb9264SLisandro Dalcin 
25bdad233fSMatthew Knepley /*@
26bdad233fSMatthew Knepley    TSSetFromOptions - Sets various TS parameters from user options.
27bdad233fSMatthew Knepley 
28bdad233fSMatthew Knepley    Collective on TS
29bdad233fSMatthew Knepley 
30bdad233fSMatthew Knepley    Input Parameter:
31bdad233fSMatthew Knepley .  ts - the TS context obtained from TSCreate()
32bdad233fSMatthew Knepley 
33bdad233fSMatthew Knepley    Options Database Keys:
34d2567f34SHong Zhang +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP, TSIRK
35ef222394SBarry Smith .  -ts_save_trajectory - checkpoint the solution at each time-step
36ef85077eSLisandro Dalcin .  -ts_max_time <time> - maximum time to compute to
374a658b32SHong Zhang .  -ts_time_span <t0,...tf> - sets the time span, solutions are computed and stored for each indicated time
38ef85077eSLisandro Dalcin .  -ts_max_steps <steps> - maximum number of time-steps to take
39ef85077eSLisandro Dalcin .  -ts_init_time <time> - initial time to start computation
404dc72f7fSBarry Smith .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
413e4cdcaaSBarry Smith .  -ts_dt <dt> - initial time step
421628793fSSatish Balay .  -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
43a3cdaa26SBarry Smith .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
44a3cdaa26SBarry Smith .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
45a3cdaa26SBarry Smith .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
46a3cdaa26SBarry Smith .  -ts_rtol <rtol> - relative tolerance for local truncation error
4767b8a455SSatish Balay .  -ts_atol <atol> - Absolute tolerance for local truncation error
48f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
49f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
5067b8a455SSatish Balay .  -ts_adjoint_solve <yes,no> - After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
51847ff0e1SMatthew G. Knepley .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
52bdad233fSMatthew Knepley .  -ts_monitor - print information at each timestep
53aee7a9fbSMatthew G. Knepley .  -ts_monitor_cancel - Cancel all monitors
54de06c3feSJed Brown .  -ts_monitor_lg_solution - Monitor solution graphically
55de06c3feSJed Brown .  -ts_monitor_lg_error - Monitor error graphically
567cf37e64SBarry Smith .  -ts_monitor_error - Monitors norm of error
576934998bSLisandro Dalcin .  -ts_monitor_lg_timestep - Monitor timestep size graphically
588b668821SLisandro Dalcin .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
59de06c3feSJed Brown .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
60de06c3feSJed Brown .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
61de06c3feSJed Brown .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
62de06c3feSJed Brown .  -ts_monitor_draw_solution - Monitor solution graphically
633e4cdcaaSBarry Smith .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
643e4cdcaaSBarry Smith .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
65fde5950dSBarry Smith .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
6663a3b9bcSJacob Faibussowitsch .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts (filename-%%03" PetscInt_FMT ".vtu)
679e336e28SPatrick Sanan -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
6853ea634cSHong Zhang 
693d5a8a6aSBarry Smith    Notes:
703d5a8a6aSBarry Smith      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.
713d5a8a6aSBarry Smith 
723d5a8a6aSBarry Smith      Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
733d5a8a6aSBarry Smith      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
743d5a8a6aSBarry Smith      -snes_lag_preconditioner_persists true
753d5a8a6aSBarry Smith 
769e336e28SPatrick Sanan    Developer Note:
779e336e28SPatrick Sanan      We should unify all the -ts_monitor options in the way that -xxx_view has been unified
78bdad233fSMatthew Knepley 
79bdad233fSMatthew Knepley    Level: beginner
80bdad233fSMatthew Knepley 
81db781477SPatrick Sanan .seealso: `TSGetType()`
82bdad233fSMatthew Knepley @*/
837087cfbeSBarry Smith PetscErrorCode  TSSetFromOptions(TS ts)
84bdad233fSMatthew Knepley {
85bc952696SBarry Smith   PetscBool              opt,flg,tflg;
86eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
874a658b32SHong Zhang   PetscReal              time_step,tspan[100];
884a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
8949354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
90d1212d36SBarry Smith   char                   dir[16];
91cd11d68dSLisandro Dalcin   TSIFunction            ifun;
926991f827SBarry Smith   const char             *defaultType;
936991f827SBarry Smith   char                   typeName[256];
94bdad233fSMatthew Knepley 
95bdad233fSMatthew Knepley   PetscFunctionBegin;
960700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
976991f827SBarry Smith 
989566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
999566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts,NULL,&ifun,NULL));
100cd11d68dSLisandro Dalcin 
101d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1021ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1031ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1049566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt));
105*1e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts,typeName));
106*1e66621cSBarry Smith   else     PetscCall(TSSetType(ts,defaultType));
107bdad233fSMatthew Knepley 
108bdad233fSMatthew Knepley   /* Handle generic TS options */
1099566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL));
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL));
1114a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span","Time span","TSSetTimeSpan",tspan,&nt,&flg));
1124a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts,nt,tspan));
1139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL));
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg));
1169566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts,time_step));
1179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg));
1189566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts,eftopt));
1199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL));
1209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL));
1219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL));
1229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL));
1239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL));
124bdad233fSMatthew Knepley 
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_rhs_jacobian_test_mult","Test the RHS Jacobian for consistency with RHS at each solve ","None",ts->testjacobian,&ts->testjacobian,NULL));
1269566063dSJacob Faibussowitsch   PetscCall(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));
1279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL));
12856f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
12956f85f32SBarry Smith   {
13056f85f32SBarry Smith     PetscBool set;
13156f85f32SBarry Smith     flg  = PETSC_FALSE;
1329566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set));
1331baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts,flg));
13456f85f32SBarry Smith   }
13556f85f32SBarry Smith #endif
13656f85f32SBarry Smith 
137bdad233fSMatthew Knepley   /* Monitor options */
1389566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1399566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL));
1409566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL));
1419566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL));
1429566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_dmswarm_monitor_moments","Monitor moments of particle distribution","TSDMSwarmMonitorMoments",TSDMSwarmMonitorMoments,NULL));
143fde5950dSBarry Smith 
1449566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",NULL,monfilename,sizeof(monfilename),&flg));
1459566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts,monfilename));
1465180491cSLisandro Dalcin 
1479566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt));
148b3603a34SBarry Smith   if (opt) {
1493923b477SBarry Smith     PetscInt       howoften = 1;
150e669de00SBarry Smith     DM             dm;
151e669de00SBarry Smith     PetscBool      net;
152b3603a34SBarry Smith 
1539566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL));
1549566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts,&dm));
1559566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net));
156e669de00SBarry Smith     if (net) {
157e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1589566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx));
1599566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy));
1609566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL));
161e669de00SBarry Smith     } else {
162e669de00SBarry Smith       TSMonitorLGCtx ctx;
1639566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1649566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
165bdad233fSMatthew Knepley     }
166e669de00SBarry Smith   }
1676ba87a44SLisandro Dalcin 
1689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt));
169ef20d060SBarry Smith   if (opt) {
1700b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1713923b477SBarry Smith     PetscInt       howoften = 1;
172ef20d060SBarry Smith 
1739566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL));
1749566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1759566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
176ef20d060SBarry Smith   }
1779566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL));
1787cf37e64SBarry Smith 
1799566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt));
1806934998bSLisandro Dalcin   if (opt) {
1816934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1826934998bSLisandro Dalcin     PetscInt       howoften = 1;
1836934998bSLisandro Dalcin 
1849566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL));
1859566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1869566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
1876934998bSLisandro Dalcin   }
1889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt));
1898b668821SLisandro Dalcin   if (opt) {
1908b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1918b668821SLisandro Dalcin     PetscInt       howoften = 1;
1928b668821SLisandro Dalcin 
1939566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL));
1949566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1959566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
1968b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
1978b668821SLisandro Dalcin   }
1988b668821SLisandro Dalcin 
1999566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt));
200201da799SBarry Smith   if (opt) {
201201da799SBarry Smith     TSMonitorLGCtx ctx;
202201da799SBarry Smith     PetscInt       howoften = 1;
203201da799SBarry Smith 
2049566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL));
2059566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
2069566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
207201da799SBarry Smith   }
2089566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt));
209201da799SBarry Smith   if (opt) {
210201da799SBarry Smith     TSMonitorLGCtx ctx;
211201da799SBarry Smith     PetscInt       howoften = 1;
212201da799SBarry Smith 
2139566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL));
2149566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
2159566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
216201da799SBarry Smith   }
2179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt));
2188189c53fSBarry Smith   if (opt) {
2198189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2208189c53fSBarry Smith     PetscInt          howoften = 1;
2218189c53fSBarry Smith 
2229566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL));
2239566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2249566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy));
2258189c53fSBarry Smith   }
2269566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt));
2271b575b74SJoseph Pusztay   if (opt) {
2281b575b74SJoseph Pusztay     TSMonitorSPCtx  ctx;
229d7462660SMatthew Knepley     PetscInt        howoften = 1, retain = 0;
2306a5217c0SMatthew G. Knepley     PetscBool       phase = PETSC_TRUE, create = PETSC_TRUE;
231d7462660SMatthew Knepley 
2326a5217c0SMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i) if (ts->monitor[i] == TSMonitorSPSwarmSolution) {create = PETSC_FALSE;break;}
2336a5217c0SMatthew G. Knepley     if (create) {
2349566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2359566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2369566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
2379566063dSJacob Faibussowitsch       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject) ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, &ctx));
2389566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy));
2391b575b74SJoseph Pusztay     }
2406a5217c0SMatthew G. Knepley   }
241ef20d060SBarry Smith   opt  = PETSC_FALSE;
2429566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt));
243a7cc72afSBarry Smith   if (opt) {
24483a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
24583a4ac43SBarry Smith     PetscInt         howoften = 1;
246a80ad3e0SBarry Smith 
2479566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL));
2489566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2499566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
250bdad233fSMatthew Knepley   }
251fb1732b5SBarry Smith   opt  = PETSC_FALSE;
2529566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt));
2532d5ee99bSBarry Smith   if (opt) {
2542d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2552d5ee99bSBarry Smith     PetscReal        bounds[4];
2562d5ee99bSBarry Smith     PetscInt         n = 4;
2572d5ee99bSBarry Smith     PetscDraw        draw;
2586934998bSLisandro Dalcin     PetscDrawAxis    axis;
2592d5ee99bSBarry Smith 
2609566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL));
2613c633725SBarry Smith     PetscCheck(n == 4,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
2629566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx));
2639566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer,0,&draw));
2649566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis));
2659566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]));
2669566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2"));
2679566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2682d5ee99bSBarry Smith   }
2692d5ee99bSBarry Smith   opt  = PETSC_FALSE;
2709566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt));
2713a471f94SBarry Smith   if (opt) {
27283a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
27383a4ac43SBarry Smith     PetscInt         howoften = 1;
2743a471f94SBarry Smith 
2759566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL));
2769566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2779566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2783a471f94SBarry Smith   }
2790ed3bfb6SBarry Smith   opt  = PETSC_FALSE;
2809566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt));
2810ed3bfb6SBarry Smith   if (opt) {
2820ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
2830ed3bfb6SBarry Smith     PetscInt         howoften = 1;
2840ed3bfb6SBarry Smith 
2859566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL));
2869566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2879566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2880ed3bfb6SBarry Smith   }
289fde5950dSBarry Smith 
290ed81e22dSJed Brown   opt  = PETSC_FALSE;
29163a3b9bcSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_solution_vtk","Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts","TSMonitorSolutionVTK",NULL,monfilename,sizeof(monfilename),&flg));
292ed81e22dSJed Brown   if (flg) {
293ed81e22dSJed Brown     const char *ptr,*ptr2;
294ed81e22dSJed Brown     char       *filetemplate;
29563a3b9bcSJacob Faibussowitsch     PetscCheck(monfilename[0],PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
296ed81e22dSJed Brown     /* Do some cursory validation of the input. */
2979566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename,"%",(char**)&ptr));
29863a3b9bcSJacob Faibussowitsch     PetscCheck(ptr,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
299ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3009566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX",*ptr,(char**)&ptr2));
30163a3b9bcSJacob Faibussowitsch       PetscCheck(ptr2 || (*ptr >= '0' && *ptr <= '9'),PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03" PetscInt_FMT ".vts");
302ed81e22dSJed Brown       if (ptr2) break;
303ed81e22dSJed Brown     }
3049566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename,&filetemplate));
3059566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy));
306ed81e22dSJed Brown   }
307bdad233fSMatthew Knepley 
3089566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,sizeof(dir),&flg));
309d1212d36SBarry Smith   if (flg) {
310d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
311d1212d36SBarry Smith     int                  ray = 0;
3123ee9839eSMatthew G. Knepley     DMDirection          ddir;
313d1212d36SBarry Smith     DM                   da;
314d1212d36SBarry Smith     PetscMPIInt          rank;
315d1212d36SBarry Smith 
3163c633725SBarry Smith     PetscCheck(dir[1] == '=',PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
3173ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3183ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
31998921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
320d1212d36SBarry Smith     sscanf(dir+2,"%d",&ray);
321d1212d36SBarry Smith 
3229566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray));
3239566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3249566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts,&da));
3259566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter));
3269566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank));
327*1e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,NULL,0,0,600,300,&rayctx->viewer));
32851b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3299566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy));
330d1212d36SBarry Smith   }
3319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,sizeof(dir),&flg));
33251b4a12fSMatthew G. Knepley   if (flg) {
33351b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
33451b4a12fSMatthew G. Knepley     int                 ray = 0;
3353ee9839eSMatthew G. Knepley     DMDirection         ddir;
33651b4a12fSMatthew G. Knepley     DM                  da;
33751b4a12fSMatthew G. Knepley     PetscInt            howoften = 1;
338d1212d36SBarry Smith 
3393c633725SBarry Smith     PetscCheck(dir[1] == '=',PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3403ee9839eSMatthew G. Knepley     if      (dir[0] == 'x') ddir = DM_X;
3413ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34298921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
34351b4a12fSMatthew G. Knepley     sscanf(dir+2, "%d", &ray);
3441c3436cfSJed Brown 
3459566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3469566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3479566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3489566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3499566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx));
3509566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
35151b4a12fSMatthew G. Knepley   }
352a7a1495cSBarry Smith 
3539566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt));
354b3d3934dSBarry Smith   if (opt) {
355b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
356b3d3934dSBarry Smith 
3579566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts,&ctx));
3589566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy));
359b3d3934dSBarry Smith   }
360aee7a9fbSMatthew G. Knepley   flg  = PETSC_FALSE;
3619566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel","Remove all monitors","TSMonitorCancel",flg,&flg,&opt));
3629566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
363b3d3934dSBarry Smith 
364847ff0e1SMatthew G. Knepley   flg  = PETSC_FALSE;
3659566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL));
366847ff0e1SMatthew G. Knepley   if (flg) {
367847ff0e1SMatthew G. Knepley     DM   dm;
368847ff0e1SMatthew G. Knepley     DMTS tdm;
369847ff0e1SMatthew G. Knepley 
3709566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
3719566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(dm, &tdm));
372847ff0e1SMatthew G. Knepley     tdm->ijacobianctx = NULL;
3739566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
3749566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
375847ff0e1SMatthew G. Knepley   }
376847ff0e1SMatthew G. Knepley 
377d763cef2SBarry Smith   /* Handle specific TS options */
3781baa6e33SBarry Smith   if (ts->ops->setfromoptions) PetscCall((*ts->ops->setfromoptions)(PetscOptionsObject,ts));
379fbc52257SHong Zhang 
380a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
3819566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
3829566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
3839566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt));
384a7bdc993SLisandro Dalcin 
38568bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
3864f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
3879566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL));
3881baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
389a05bf03eSHong Zhang 
3909566063dSJacob Faibussowitsch   PetscCall(TSAdjointSetFromOptions(PetscOptionsObject,ts));
391d763cef2SBarry Smith 
392d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
3939566063dSJacob Faibussowitsch   PetscCall(PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts));
394d0609cedSBarry Smith   PetscOptionsEnd();
395d763cef2SBarry Smith 
3961baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory,ts));
39768bece0bSHong Zhang 
3981ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
3999566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&ts->snes));
4001ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4019566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,""));
4029566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes,SNESKSPONLY));
4031ef27442SStefano Zampini   }
4049566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
405d763cef2SBarry Smith   PetscFunctionReturn(0);
406d763cef2SBarry Smith }
407d763cef2SBarry Smith 
408d2daff3dSHong Zhang /*@
40978fbdcc8SBarry Smith    TSGetTrajectory - Gets the trajectory from a TS if it exists
41078fbdcc8SBarry Smith 
41178fbdcc8SBarry Smith    Collective on TS
41278fbdcc8SBarry Smith 
41378fbdcc8SBarry Smith    Input Parameters:
41478fbdcc8SBarry Smith .  ts - the TS context obtained from TSCreate()
41578fbdcc8SBarry Smith 
4167a7aea1fSJed Brown    Output Parameters:
41778fbdcc8SBarry Smith .  tr - the TSTrajectory object, if it exists
41878fbdcc8SBarry Smith 
41978fbdcc8SBarry Smith    Note: This routine should be called after all TS options have been set
42078fbdcc8SBarry Smith 
42178fbdcc8SBarry Smith    Level: advanced
42278fbdcc8SBarry Smith 
423db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSTrajectory`, `TSTrajectoryCreate()`
42478fbdcc8SBarry Smith 
42578fbdcc8SBarry Smith @*/
42678fbdcc8SBarry Smith PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
42778fbdcc8SBarry Smith {
42878fbdcc8SBarry Smith   PetscFunctionBegin;
42978fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
43078fbdcc8SBarry Smith   *tr = ts->trajectory;
43178fbdcc8SBarry Smith   PetscFunctionReturn(0);
43278fbdcc8SBarry Smith }
43378fbdcc8SBarry Smith 
43478fbdcc8SBarry Smith /*@
435bc952696SBarry Smith    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
436d2daff3dSHong Zhang 
437d2daff3dSHong Zhang    Collective on TS
438d2daff3dSHong Zhang 
439f899ff85SJose E. Roman    Input Parameter:
440bc952696SBarry Smith .  ts - the TS context obtained from TSCreate()
441bc952696SBarry Smith 
44278fbdcc8SBarry Smith    Options Database:
44378fbdcc8SBarry Smith +  -ts_save_trajectory - saves the trajectory to a file
44467b8a455SSatish Balay -  -ts_trajectory_type type - set trajectory type
44578fbdcc8SBarry Smith 
44668bece0bSHong Zhang Note: This routine should be called after all TS options have been set
447d2daff3dSHong Zhang 
448c3a89c15SBarry Smith     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
44978fbdcc8SBarry Smith    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
45078fbdcc8SBarry Smith 
451d2daff3dSHong Zhang    Level: intermediate
452d2daff3dSHong Zhang 
453db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`
454d2daff3dSHong Zhang 
455d2daff3dSHong Zhang @*/
456bc952696SBarry Smith PetscErrorCode  TSSetSaveTrajectory(TS ts)
457d2daff3dSHong Zhang {
458d2daff3dSHong Zhang   PetscFunctionBegin;
459d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
46063a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory));
461d2daff3dSHong Zhang   PetscFunctionReturn(0);
462d2daff3dSHong Zhang }
463d2daff3dSHong Zhang 
464a7a1495cSBarry Smith /*@
4652d29f1f2SStefano Zampini    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object
4662d29f1f2SStefano Zampini 
4672d29f1f2SStefano Zampini    Collective on TS
4682d29f1f2SStefano Zampini 
4692d29f1f2SStefano Zampini    Input Parameters:
4702d29f1f2SStefano Zampini .  ts - the TS context obtained from TSCreate()
4712d29f1f2SStefano Zampini 
4722d29f1f2SStefano Zampini    Level: intermediate
4732d29f1f2SStefano Zampini 
474db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
4752d29f1f2SStefano Zampini 
4762d29f1f2SStefano Zampini @*/
4772d29f1f2SStefano Zampini PetscErrorCode  TSResetTrajectory(TS ts)
4782d29f1f2SStefano Zampini {
4792d29f1f2SStefano Zampini   PetscFunctionBegin;
4802d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4812d29f1f2SStefano Zampini   if (ts->trajectory) {
4829566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
4839566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory));
4842d29f1f2SStefano Zampini   }
4852d29f1f2SStefano Zampini   PetscFunctionReturn(0);
4862d29f1f2SStefano Zampini }
4872d29f1f2SStefano Zampini 
4882d29f1f2SStefano Zampini /*@
48967a3cfb0SHong Zhang    TSRemoveTrajectory - Destroys and removes the internal TSTrajectory object from TS
49067a3cfb0SHong Zhang 
49167a3cfb0SHong Zhang    Collective on TS
49267a3cfb0SHong Zhang 
49367a3cfb0SHong Zhang    Input Parameters:
49467a3cfb0SHong Zhang .  ts - the TS context obtained from TSCreate()
49567a3cfb0SHong Zhang 
49667a3cfb0SHong Zhang    Level: intermediate
49767a3cfb0SHong Zhang 
498db781477SPatrick Sanan .seealso: `TSResetTrajectory()`, `TSAdjointSolve()`
49967a3cfb0SHong Zhang 
50067a3cfb0SHong Zhang @*/
50167a3cfb0SHong Zhang PetscErrorCode TSRemoveTrajectory(TS ts)
50267a3cfb0SHong Zhang {
50367a3cfb0SHong Zhang   PetscFunctionBegin;
50467a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
505*1e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
50667a3cfb0SHong Zhang   PetscFunctionReturn(0);
50767a3cfb0SHong Zhang }
50867a3cfb0SHong Zhang 
50967a3cfb0SHong Zhang /*@
510a7a1495cSBarry Smith    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
511a7a1495cSBarry Smith       set with TSSetRHSJacobian().
512a7a1495cSBarry Smith 
513d083f849SBarry Smith    Collective on TS
514a7a1495cSBarry Smith 
515a7a1495cSBarry Smith    Input Parameters:
516316643e7SJed Brown +  ts - the TS context
517a7a1495cSBarry Smith .  t - current timestep
5180910c330SBarry Smith -  U - input vector
519a7a1495cSBarry Smith 
520a7a1495cSBarry Smith    Output Parameters:
521a7a1495cSBarry Smith +  A - Jacobian matrix
5226b867d5aSJose E. Roman -  B - optional preconditioning matrix
523a7a1495cSBarry Smith 
524a7a1495cSBarry Smith    Notes:
525a7a1495cSBarry Smith    Most users should not need to explicitly call this routine, as it
526a7a1495cSBarry Smith    is used internally within the nonlinear solvers.
527a7a1495cSBarry Smith 
528a7a1495cSBarry Smith    Level: developer
529a7a1495cSBarry Smith 
530db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `KSPSetOperators()`
531a7a1495cSBarry Smith @*/
532d1e9a80fSBarry Smith PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
533a7a1495cSBarry Smith {
534270bf2e7SJed Brown   PetscObjectState Ustate;
5356c1e1eecSBarry Smith   PetscObjectId    Uid;
53624989b8cSPeter Brune   DM               dm;
537942e3340SBarry Smith   DMTS             tsdm;
53824989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
53924989b8cSPeter Brune   void             *ctx;
540b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
541a7a1495cSBarry Smith 
542a7a1495cSBarry Smith   PetscFunctionBegin;
5430700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5440910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
5450910c330SBarry Smith   PetscCheckSameComm(ts,1,U,3);
5469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
5479566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&tsdm));
5489566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
5499566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx));
5509566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U,&Ustate));
5519566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U,&Uid));
552971015bcSStefano Zampini 
5532663174eSHong Zhang   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(0);
554d90be118SSean Farley 
55563a3b9bcSJacob Faibussowitsch   PetscCheck(ts->rhsjacobian.shift == 0.0 || !ts->rhsjacobian.reuse,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Should not call TSComputeRHSJacobian() on a shifted matrix (shift=%lf) when RHSJacobian is reusable.",(double)ts->rhsjacobian.shift);
55624989b8cSPeter Brune   if (rhsjacobianfunc) {
5579566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,A,B));
558792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian",(*rhsjacobianfunc)(ts,t,U,A,B,ctx));
559a6ab3590SBarry Smith     ts->rhsjacs++;
5609566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,A,B));
561ef66eb69SBarry Smith   } else {
5629566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5639566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
564ef66eb69SBarry Smith   }
5650e4ef248SJed Brown   ts->rhsjacobian.time  = t;
566971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
567971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5689566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid));
5699566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate));
570a7a1495cSBarry Smith   PetscFunctionReturn(0);
571a7a1495cSBarry Smith }
572a7a1495cSBarry Smith 
573316643e7SJed Brown /*@
574d763cef2SBarry Smith    TSComputeRHSFunction - Evaluates the right-hand-side function.
575d763cef2SBarry Smith 
576d083f849SBarry Smith    Collective on TS
577316643e7SJed Brown 
578316643e7SJed Brown    Input Parameters:
579316643e7SJed Brown +  ts - the TS context
580316643e7SJed Brown .  t - current time
5810910c330SBarry Smith -  U - state vector
582316643e7SJed Brown 
583316643e7SJed Brown    Output Parameter:
584316643e7SJed Brown .  y - right hand side
585316643e7SJed Brown 
586316643e7SJed Brown    Note:
587316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
588316643e7SJed Brown    is used internally within the nonlinear solvers.
589316643e7SJed Brown 
590316643e7SJed Brown    Level: developer
591316643e7SJed Brown 
592db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
593316643e7SJed Brown @*/
5940910c330SBarry Smith PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
595d763cef2SBarry Smith {
59624989b8cSPeter Brune   TSRHSFunction  rhsfunction;
59724989b8cSPeter Brune   TSIFunction    ifunction;
59824989b8cSPeter Brune   void           *ctx;
59924989b8cSPeter Brune   DM             dm;
60024989b8cSPeter Brune 
601d763cef2SBarry Smith   PetscFunctionBegin;
6020700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6030910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6040700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,4);
6059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
6069566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,&ctx));
6079566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,&ifunction,NULL));
608d763cef2SBarry Smith 
6093c633725SBarry Smith   PetscCheck(rhsfunction || ifunction,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
610d763cef2SBarry Smith 
61124989b8cSPeter Brune   if (rhsfunction) {
6129566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,y,0));
6139566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
614792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side",(*rhsfunction)(ts,t,U,y,ctx));
6159566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
616a6ab3590SBarry Smith     ts->rhsfuncs++;
6179566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,y,0));
618*1e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
619d763cef2SBarry Smith   PetscFunctionReturn(0);
620d763cef2SBarry Smith }
621d763cef2SBarry Smith 
622ef20d060SBarry Smith /*@
623ef20d060SBarry Smith    TSComputeSolutionFunction - Evaluates the solution function.
624ef20d060SBarry Smith 
625d083f849SBarry Smith    Collective on TS
626ef20d060SBarry Smith 
627ef20d060SBarry Smith    Input Parameters:
628ef20d060SBarry Smith +  ts - the TS context
629ef20d060SBarry Smith -  t - current time
630ef20d060SBarry Smith 
631ef20d060SBarry Smith    Output Parameter:
6320910c330SBarry Smith .  U - the solution
633ef20d060SBarry Smith 
634ef20d060SBarry Smith    Note:
635ef20d060SBarry Smith    Most users should not need to explicitly call this routine, as it
636ef20d060SBarry Smith    is used internally within the nonlinear solvers.
637ef20d060SBarry Smith 
638ef20d060SBarry Smith    Level: developer
639ef20d060SBarry Smith 
640db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
641ef20d060SBarry Smith @*/
6420910c330SBarry Smith PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
643ef20d060SBarry Smith {
644ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
645ef20d060SBarry Smith   void               *ctx;
646ef20d060SBarry Smith   DM                 dm;
647ef20d060SBarry Smith 
648ef20d060SBarry Smith   PetscFunctionBegin;
649ef20d060SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6500910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6519566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
6529566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm,&solutionfunction,&ctx));
653ef20d060SBarry Smith 
654792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution",(*solutionfunction)(ts,t,U,ctx));
655ef20d060SBarry Smith   PetscFunctionReturn(0);
656ef20d060SBarry Smith }
6579b7cd975SBarry Smith /*@
6589b7cd975SBarry Smith    TSComputeForcingFunction - Evaluates the forcing function.
6599b7cd975SBarry Smith 
660d083f849SBarry Smith    Collective on TS
6619b7cd975SBarry Smith 
6629b7cd975SBarry Smith    Input Parameters:
6639b7cd975SBarry Smith +  ts - the TS context
6649b7cd975SBarry Smith -  t - current time
6659b7cd975SBarry Smith 
6669b7cd975SBarry Smith    Output Parameter:
6679b7cd975SBarry Smith .  U - the function value
6689b7cd975SBarry Smith 
6699b7cd975SBarry Smith    Note:
6709b7cd975SBarry Smith    Most users should not need to explicitly call this routine, as it
6719b7cd975SBarry Smith    is used internally within the nonlinear solvers.
6729b7cd975SBarry Smith 
6739b7cd975SBarry Smith    Level: developer
6749b7cd975SBarry Smith 
675db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6769b7cd975SBarry Smith @*/
6779b7cd975SBarry Smith PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
6789b7cd975SBarry Smith {
6799b7cd975SBarry Smith   void              *ctx;
6809b7cd975SBarry Smith   DM                 dm;
6815f80ce2aSJacob Faibussowitsch   TSForcingFunction  forcing;
6829b7cd975SBarry Smith 
6839b7cd975SBarry Smith   PetscFunctionBegin;
6849b7cd975SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6859b7cd975SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6869566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
6879566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm,&forcing,&ctx));
6889b7cd975SBarry Smith 
689792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function",(*forcing)(ts,t,U,ctx));
6909b7cd975SBarry Smith   PetscFunctionReturn(0);
6919b7cd975SBarry Smith }
692ef20d060SBarry Smith 
693214bc6a2SJed Brown static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
694214bc6a2SJed Brown {
6952dd45cf8SJed Brown   Vec            F;
696214bc6a2SJed Brown 
697214bc6a2SJed Brown   PetscFunctionBegin;
6980298fd71SBarry Smith   *Frhs = NULL;
6999566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts,&F,NULL,NULL));
700*1e66621cSBarry Smith   if (!ts->Frhs) PetscCall(VecDuplicate(F,&ts->Frhs));
701214bc6a2SJed Brown   *Frhs = ts->Frhs;
702214bc6a2SJed Brown   PetscFunctionReturn(0);
703214bc6a2SJed Brown }
704214bc6a2SJed Brown 
705971015bcSStefano Zampini PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
706214bc6a2SJed Brown {
707214bc6a2SJed Brown   Mat            A,B;
70841a1d4d2SBarry Smith   TSIJacobian    ijacobian;
709214bc6a2SJed Brown 
710214bc6a2SJed Brown   PetscFunctionBegin;
711c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
712c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7139566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts,&A,&B,&ijacobian,NULL));
714214bc6a2SJed Brown   if (Arhs) {
715214bc6a2SJed Brown     if (!ts->Arhs) {
71641a1d4d2SBarry Smith       if (ijacobian) {
7179566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs));
7189566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts,SAME_NONZERO_PATTERN));
71941a1d4d2SBarry Smith       } else {
72041a1d4d2SBarry Smith         ts->Arhs = A;
7219566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
72241a1d4d2SBarry Smith       }
7233565c898SBarry Smith     } else {
7243565c898SBarry Smith       PetscBool flg;
7259566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes,NULL,&flg));
7263565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7273565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7289566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7293565c898SBarry Smith         ts->Arhs = A;
7309566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7313565c898SBarry Smith       }
732214bc6a2SJed Brown     }
733214bc6a2SJed Brown     *Arhs = ts->Arhs;
734214bc6a2SJed Brown   }
735214bc6a2SJed Brown   if (Brhs) {
736214bc6a2SJed Brown     if (!ts->Brhs) {
737bdb70873SJed Brown       if (A != B) {
73841a1d4d2SBarry Smith         if (ijacobian) {
7399566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs));
740bdb70873SJed Brown         } else {
74141a1d4d2SBarry Smith           ts->Brhs = B;
7429566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
74341a1d4d2SBarry Smith         }
74441a1d4d2SBarry Smith       } else {
7459566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
74651699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
747bdb70873SJed Brown       }
748214bc6a2SJed Brown     }
749214bc6a2SJed Brown     *Brhs = ts->Brhs;
750214bc6a2SJed Brown   }
751214bc6a2SJed Brown   PetscFunctionReturn(0);
752214bc6a2SJed Brown }
753214bc6a2SJed Brown 
754316643e7SJed Brown /*@
7550910c330SBarry Smith    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
756316643e7SJed Brown 
757d083f849SBarry Smith    Collective on TS
758316643e7SJed Brown 
759316643e7SJed Brown    Input Parameters:
760316643e7SJed Brown +  ts - the TS context
761316643e7SJed Brown .  t - current time
7620910c330SBarry Smith .  U - state vector
7630910c330SBarry Smith .  Udot - time derivative of state vector
764214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
765316643e7SJed Brown 
766316643e7SJed Brown    Output Parameter:
767316643e7SJed Brown .  Y - right hand side
768316643e7SJed Brown 
769316643e7SJed Brown    Note:
770316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
771316643e7SJed Brown    is used internally within the nonlinear solvers.
772316643e7SJed Brown 
773316643e7SJed Brown    If the user did did not write their equations in implicit form, this
774316643e7SJed Brown    function recasts them in implicit form.
775316643e7SJed Brown 
776316643e7SJed Brown    Level: developer
777316643e7SJed Brown 
778db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSComputeRHSFunction()`
779316643e7SJed Brown @*/
7800910c330SBarry Smith PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
781316643e7SJed Brown {
78224989b8cSPeter Brune   TSIFunction    ifunction;
78324989b8cSPeter Brune   TSRHSFunction  rhsfunction;
78424989b8cSPeter Brune   void           *ctx;
78524989b8cSPeter Brune   DM             dm;
786316643e7SJed Brown 
787316643e7SJed Brown   PetscFunctionBegin;
7880700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
7890910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
7900910c330SBarry Smith   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
7910700a824SBarry Smith   PetscValidHeaderSpecific(Y,VEC_CLASSID,5);
792316643e7SJed Brown 
7939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
7949566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,&ifunction,&ctx));
7959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
79624989b8cSPeter Brune 
7973c633725SBarry Smith   PetscCheck(rhsfunction || ifunction,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
798d90be118SSean Farley 
7999566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y));
80024989b8cSPeter Brune   if (ifunction) {
801792fecdfSBarry Smith     PetscCallBack("TS callback implicit function",(*ifunction)(ts,t,U,Udot,Y,ctx));
802a6ab3590SBarry Smith     ts->ifuncs++;
803214bc6a2SJed Brown   }
804214bc6a2SJed Brown   if (imex) {
805*1e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot,Y));
80624989b8cSPeter Brune   } else if (rhsfunction) {
80724989b8cSPeter Brune     if (ifunction) {
808214bc6a2SJed Brown       Vec Frhs;
8099566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts,&Frhs));
8109566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts,t,U,Frhs));
8119566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y,-1,Frhs));
8122dd45cf8SJed Brown     } else {
8139566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts,t,U,Y));
8149566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y,-1,Udot));
815316643e7SJed Brown     }
8164a6899ffSJed Brown   }
8179566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y));
818316643e7SJed Brown   PetscFunctionReturn(0);
819316643e7SJed Brown }
820316643e7SJed Brown 
821cfa8a9a2SHong Zhang /*
822cfa8a9a2SHong Zhang    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.
823cfa8a9a2SHong Zhang 
824cfa8a9a2SHong Zhang    Note:
825cfa8a9a2SHong Zhang    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().
826cfa8a9a2SHong Zhang 
827cfa8a9a2SHong Zhang */
828cfa8a9a2SHong Zhang static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
829cfa8a9a2SHong Zhang {
830cfa8a9a2SHong Zhang   PetscFunctionBegin;
831cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
8323c633725SBarry Smith   PetscCheck(A == ts->Arhs,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Amat");
8333c633725SBarry Smith   PetscCheck(B == ts->Brhs,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Bmat");
834cfa8a9a2SHong Zhang 
8351baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A,-ts->rhsjacobian.shift));
836cfa8a9a2SHong Zhang   if (ts->rhsjacobian.scale == -1.) {
8379566063dSJacob Faibussowitsch     PetscCall(MatScale(A,-1));
838cfa8a9a2SHong Zhang   }
839cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8401baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B,-ts->rhsjacobian.shift));
841*1e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B,-1));
842cfa8a9a2SHong Zhang   }
843cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
844cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
845cfa8a9a2SHong Zhang   PetscFunctionReturn(0);
846cfa8a9a2SHong Zhang }
847cfa8a9a2SHong Zhang 
848316643e7SJed Brown /*@
849316643e7SJed Brown    TSComputeIJacobian - Evaluates the Jacobian of the DAE
850316643e7SJed Brown 
851d083f849SBarry Smith    Collective on TS
852316643e7SJed Brown 
853316643e7SJed Brown    Input
854316643e7SJed Brown       Input Parameters:
855316643e7SJed Brown +  ts - the TS context
856316643e7SJed Brown .  t - current timestep
8570910c330SBarry Smith .  U - state vector
8580910c330SBarry Smith .  Udot - time derivative of state vector
859214bc6a2SJed Brown .  shift - shift to apply, see note below
860214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
861316643e7SJed Brown 
862316643e7SJed Brown    Output Parameters:
863316643e7SJed Brown +  A - Jacobian matrix
8643565c898SBarry Smith -  B - matrix from which the preconditioner is constructed; often the same as A
865316643e7SJed Brown 
866316643e7SJed Brown    Notes:
8670910c330SBarry Smith    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
868316643e7SJed Brown 
8690910c330SBarry Smith    dF/dU + shift*dF/dUdot
870316643e7SJed Brown 
871316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
872316643e7SJed Brown    is used internally within the nonlinear solvers.
873316643e7SJed Brown 
874316643e7SJed Brown    Level: developer
875316643e7SJed Brown 
876db781477SPatrick Sanan .seealso: `TSSetIJacobian()`
87763495f91SJed Brown @*/
878d1e9a80fSBarry Smith PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
879316643e7SJed Brown {
88024989b8cSPeter Brune   TSIJacobian    ijacobian;
88124989b8cSPeter Brune   TSRHSJacobian  rhsjacobian;
88224989b8cSPeter Brune   DM             dm;
88324989b8cSPeter Brune   void           *ctx;
884316643e7SJed Brown 
885316643e7SJed Brown   PetscFunctionBegin;
8860700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
8870910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
8880910c330SBarry Smith   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
889316643e7SJed Brown   PetscValidPointer(A,6);
89094ab13aaSBarry Smith   PetscValidHeaderSpecific(A,MAT_CLASSID,6);
891316643e7SJed Brown   PetscValidPointer(B,7);
89294ab13aaSBarry Smith   PetscValidHeaderSpecific(B,MAT_CLASSID,7);
89324989b8cSPeter Brune 
8949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
8959566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijacobian,&ctx));
8969566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobian,NULL));
89724989b8cSPeter Brune 
8983c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
899316643e7SJed Brown 
9009566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,A,B));
90124989b8cSPeter Brune   if (ijacobian) {
902792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian",(*ijacobian)(ts,t,U,Udot,shift,A,B,ctx));
903a6ab3590SBarry Smith     ts->ijacs++;
9044a6899ffSJed Brown   }
905214bc6a2SJed Brown   if (imex) {
906b5abc632SBarry Smith     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
9074c26be97Sstefano_zampini       PetscBool assembled;
908971015bcSStefano Zampini       if (rhsjacobian) {
909971015bcSStefano Zampini         Mat Arhs = NULL;
9109566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts,&Arhs,NULL));
911971015bcSStefano Zampini         if (A == Arhs) {
9123c633725SBarry Smith           PetscCheck(rhsjacobian != TSComputeRHSJacobianConstant,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 */
913971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
914971015bcSStefano Zampini         }
915971015bcSStefano Zampini       }
9169566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9179566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A,&assembled));
9184c26be97Sstefano_zampini       if (!assembled) {
9199566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
9209566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
9214c26be97Sstefano_zampini       }
9229566063dSJacob Faibussowitsch       PetscCall(MatShift(A,shift));
92394ab13aaSBarry Smith       if (A != B) {
9249566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9259566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B,&assembled));
9264c26be97Sstefano_zampini         if (!assembled) {
9279566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY));
9289566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY));
9294c26be97Sstefano_zampini         }
9309566063dSJacob Faibussowitsch         PetscCall(MatShift(B,shift));
931214bc6a2SJed Brown       }
932214bc6a2SJed Brown     }
933214bc6a2SJed Brown   } else {
934e1244c69SJed Brown     Mat Arhs = NULL,Brhs = NULL;
935*1e66621cSBarry Smith 
936*1e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
937*1e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts,&Arhs,&Brhs));
938e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
939e8b1e424SHong Zhang       PetscObjectState Ustate;
940e8b1e424SHong Zhang       PetscObjectId    Uid;
941e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
942e8b1e424SHong Zhang 
9439566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
9449566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U,&Ustate));
9459566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U,&Uid));
946097a96a2SHong Zhang       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 */
9479566063dSJacob Faibussowitsch         PetscCall(MatShift(A,shift-ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
948*1e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B,shift-ts->rhsjacobian.shift));
949e8b1e424SHong Zhang       } else {
9503565c898SBarry Smith         PetscBool flg;
951e8b1e424SHong Zhang 
952e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
953e8b1e424SHong Zhang           /* MatScale has a short path for this case.
954e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
955e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9569566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts,A,B));
957e8b1e424SHong Zhang         }
9589566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts,t,U,A,B));
9599566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes,NULL,&flg));
9603565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9613565c898SBarry Smith         if (!flg) {
9629566063dSJacob Faibussowitsch           PetscCall(MatScale(A,-1));
9639566063dSJacob Faibussowitsch           PetscCall(MatShift(A,shift));
9643565c898SBarry Smith         }
96594ab13aaSBarry Smith         if (A != B) {
9669566063dSJacob Faibussowitsch           PetscCall(MatScale(B,-1));
9679566063dSJacob Faibussowitsch           PetscCall(MatShift(B,shift));
968316643e7SJed Brown         }
969e8b1e424SHong Zhang       }
970e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
971e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
972d60b7d5cSBarry Smith     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
973e1244c69SJed Brown       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
9749566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9759566063dSJacob Faibussowitsch         PetscCall(MatShift(A,shift));
97694ab13aaSBarry Smith         if (A != B) {
9779566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9789566063dSJacob Faibussowitsch           PetscCall(MatShift(B,shift));
979214bc6a2SJed Brown         }
980316643e7SJed Brown       }
9819566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts,t,U,Arhs,Brhs));
9829566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A,-1,Arhs,ts->axpy_pattern));
983*1e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B,-1,Brhs,ts->axpy_pattern));
984316643e7SJed Brown     }
985316643e7SJed Brown   }
9869566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,A,B));
987316643e7SJed Brown   PetscFunctionReturn(0);
988316643e7SJed Brown }
989316643e7SJed Brown 
990d763cef2SBarry Smith /*@C
991d763cef2SBarry Smith     TSSetRHSFunction - Sets the routine for evaluating the function,
992b5abc632SBarry Smith     where U_t = G(t,u).
993d763cef2SBarry Smith 
9943f9fe445SBarry Smith     Logically Collective on TS
995d763cef2SBarry Smith 
996d763cef2SBarry Smith     Input Parameters:
997d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
9980298fd71SBarry Smith .   r - vector to put the computed right hand side (or NULL to have it created)
999d763cef2SBarry Smith .   f - routine for evaluating the right-hand-side function
1000d763cef2SBarry Smith -   ctx - [optional] user-defined context for private data for the
10010298fd71SBarry Smith           function evaluation routine (may be NULL)
1002d763cef2SBarry Smith 
1003a96d6ef6SBarry Smith     Calling sequence of f:
1004a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1005d763cef2SBarry Smith 
1006a96d6ef6SBarry Smith +   ts - timestep context
1007a96d6ef6SBarry Smith .   t - current timestep
1008d763cef2SBarry Smith .   u - input vector
1009d763cef2SBarry Smith .   F - function vector
1010d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1011d763cef2SBarry Smith 
1012d763cef2SBarry Smith     Level: beginner
1013d763cef2SBarry Smith 
101495452b02SPatrick Sanan     Notes:
101595452b02SPatrick Sanan     You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
10162bbac0d3SBarry Smith 
1017db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1018d763cef2SBarry Smith @*/
1019089b2837SJed Brown PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1020d763cef2SBarry Smith {
1021089b2837SJed Brown   SNES           snes;
10220298fd71SBarry Smith   Vec            ralloc = NULL;
102324989b8cSPeter Brune   DM             dm;
1024d763cef2SBarry Smith 
1025089b2837SJed Brown   PetscFunctionBegin;
10260700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1027ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
102824989b8cSPeter Brune 
10299566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
10309566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm,f,ctx));
10319566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
1032e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10339566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol,&ralloc));
1034e856ceecSJed Brown     r = ralloc;
1035e856ceecSJed Brown   }
10369566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes,r,SNESTSFormFunction,ts));
10379566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1038d763cef2SBarry Smith   PetscFunctionReturn(0);
1039d763cef2SBarry Smith }
1040d763cef2SBarry Smith 
1041ef20d060SBarry Smith /*@C
1042abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1043ef20d060SBarry Smith 
1044ef20d060SBarry Smith     Logically Collective on TS
1045ef20d060SBarry Smith 
1046ef20d060SBarry Smith     Input Parameters:
1047ef20d060SBarry Smith +   ts - the TS context obtained from TSCreate()
1048ef20d060SBarry Smith .   f - routine for evaluating the solution
1049ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
10500298fd71SBarry Smith           function evaluation routine (may be NULL)
1051ef20d060SBarry Smith 
1052a96d6ef6SBarry Smith     Calling sequence of f:
1053a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1054ef20d060SBarry Smith 
1055ef20d060SBarry Smith +   t - current timestep
1056ef20d060SBarry Smith .   u - output vector
1057ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1058ef20d060SBarry Smith 
10590ed3bfb6SBarry Smith     Options Database:
10600ed3bfb6SBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
10610ed3bfb6SBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
10620ed3bfb6SBarry Smith 
1063abd5a294SJed Brown     Notes:
1064abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1065abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1066abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1067abd5a294SJed Brown 
10684f09c107SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1069abd5a294SJed Brown 
1070ef20d060SBarry Smith     Level: beginner
1071ef20d060SBarry Smith 
1072db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1073ef20d060SBarry Smith @*/
1074ef20d060SBarry Smith PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1075ef20d060SBarry Smith {
1076ef20d060SBarry Smith   DM             dm;
1077ef20d060SBarry Smith 
1078ef20d060SBarry Smith   PetscFunctionBegin;
1079ef20d060SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
10809566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
10819566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm,f,ctx));
1082ef20d060SBarry Smith   PetscFunctionReturn(0);
1083ef20d060SBarry Smith }
1084ef20d060SBarry Smith 
10859b7cd975SBarry Smith /*@C
10869b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10879b7cd975SBarry Smith 
10889b7cd975SBarry Smith     Logically Collective on TS
10899b7cd975SBarry Smith 
10909b7cd975SBarry Smith     Input Parameters:
10919b7cd975SBarry Smith +   ts - the TS context obtained from TSCreate()
1092e162b725SBarry Smith .   func - routine for evaluating the forcing function
10939b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
10940298fd71SBarry Smith           function evaluation routine (may be NULL)
10959b7cd975SBarry Smith 
10969b7cd975SBarry Smith     Calling sequence of func:
10976bc98fa9SBarry Smith $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
10989b7cd975SBarry Smith 
10999b7cd975SBarry Smith +   t - current timestep
1100e162b725SBarry Smith .   f - output vector
11019b7cd975SBarry Smith -   ctx - [optional] user-defined function context
11029b7cd975SBarry Smith 
11039b7cd975SBarry Smith     Notes:
11049b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1105e162b725SBarry Smith     create closed-form solutions with a non-physical forcing term. It allows you to use the Method of Manufactored Solution without directly editing the
1106e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1107e162b725SBarry Smith 
1108e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1109e162b725SBarry Smith 
1110e162b725SBarry Smith     This forcing function does not depend on the solution to the equations, it can only depend on spatial location, time, and possibly parameters, the
1111e162b725SBarry Smith     parameters can be passed in the ctx variable.
11129b7cd975SBarry Smith 
11139b7cd975SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
11149b7cd975SBarry Smith 
11159b7cd975SBarry Smith     Level: beginner
11169b7cd975SBarry Smith 
1117db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11189b7cd975SBarry Smith @*/
1119e162b725SBarry Smith PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
11209b7cd975SBarry Smith {
11219b7cd975SBarry Smith   DM             dm;
11229b7cd975SBarry Smith 
11239b7cd975SBarry Smith   PetscFunctionBegin;
11249b7cd975SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
11259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
11269566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm,func,ctx));
11279b7cd975SBarry Smith   PetscFunctionReturn(0);
11289b7cd975SBarry Smith }
11299b7cd975SBarry Smith 
1130d763cef2SBarry Smith /*@C
1131f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1132b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1133d763cef2SBarry Smith 
11343f9fe445SBarry Smith    Logically Collective on TS
1135d763cef2SBarry Smith 
1136d763cef2SBarry Smith    Input Parameters:
1137d763cef2SBarry Smith +  ts  - the TS context obtained from TSCreate()
1138e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1139e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1140d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1141d763cef2SBarry Smith -  ctx - [optional] user-defined context for private data for the
11420298fd71SBarry Smith          Jacobian evaluation routine (may be NULL)
1143d763cef2SBarry Smith 
1144f7ab8db6SBarry Smith    Calling sequence of f:
1145a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1146d763cef2SBarry Smith 
1147d763cef2SBarry Smith +  t - current timestep
1148d763cef2SBarry Smith .  u - input vector
1149e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1150e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1151d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1152d763cef2SBarry Smith 
11536cd88445SBarry Smith    Notes:
11546cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11556cd88445SBarry Smith 
11566cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1157ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1158d763cef2SBarry Smith 
1159d763cef2SBarry Smith    Level: beginner
1160d763cef2SBarry Smith 
1161db781477SPatrick Sanan .seealso: `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1162d763cef2SBarry Smith 
1163d763cef2SBarry Smith @*/
1164e5d3d808SBarry Smith PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1165d763cef2SBarry Smith {
1166089b2837SJed Brown   SNES           snes;
116724989b8cSPeter Brune   DM             dm;
116824989b8cSPeter Brune   TSIJacobian    ijacobian;
1169277b19d0SLisandro Dalcin 
1170d763cef2SBarry Smith   PetscFunctionBegin;
11710700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1172e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1173e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1174e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1175e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1176d763cef2SBarry Smith 
11779566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
11789566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm,f,ctx));
11799566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijacobian,NULL));
11809566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
1181*1e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts));
1182e5d3d808SBarry Smith   if (Amat) {
11839566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11849566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1185e5d3d808SBarry Smith     ts->Arhs = Amat;
11860e4ef248SJed Brown   }
1187e5d3d808SBarry Smith   if (Pmat) {
11889566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11899566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1190e5d3d808SBarry Smith     ts->Brhs = Pmat;
11910e4ef248SJed Brown   }
1192d763cef2SBarry Smith   PetscFunctionReturn(0);
1193d763cef2SBarry Smith }
1194d763cef2SBarry Smith 
1195316643e7SJed Brown /*@C
1196b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1197316643e7SJed Brown 
11983f9fe445SBarry Smith    Logically Collective on TS
1199316643e7SJed Brown 
1200316643e7SJed Brown    Input Parameters:
1201316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
12020298fd71SBarry Smith .  r   - vector to hold the residual (or NULL to have it created internally)
1203316643e7SJed Brown .  f   - the function evaluation routine
12040298fd71SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1205316643e7SJed Brown 
1206316643e7SJed Brown    Calling sequence of f:
12076bc98fa9SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1208316643e7SJed Brown 
1209316643e7SJed Brown +  t   - time at step/stage being solved
1210316643e7SJed Brown .  u   - state vector
1211316643e7SJed Brown .  u_t - time derivative of state vector
1212316643e7SJed Brown .  F   - function vector
1213316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1214316643e7SJed Brown 
1215316643e7SJed Brown    Important:
12162bbac0d3SBarry Smith    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.
1217316643e7SJed Brown 
1218316643e7SJed Brown    Level: beginner
1219316643e7SJed Brown 
1220db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1221316643e7SJed Brown @*/
122251699248SLisandro Dalcin PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1223316643e7SJed Brown {
1224089b2837SJed Brown   SNES           snes;
122551699248SLisandro Dalcin   Vec            ralloc = NULL;
122624989b8cSPeter Brune   DM             dm;
1227316643e7SJed Brown 
1228316643e7SJed Brown   PetscFunctionBegin;
12290700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
123051699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
123124989b8cSPeter Brune 
12329566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
12339566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm,f,ctx));
123424989b8cSPeter Brune 
12359566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
123651699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12379566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol,&ralloc));
123851699248SLisandro Dalcin     r  = ralloc;
1239e856ceecSJed Brown   }
12409566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes,r,SNESTSFormFunction,ts));
12419566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1242089b2837SJed Brown   PetscFunctionReturn(0);
1243089b2837SJed Brown }
1244089b2837SJed Brown 
1245089b2837SJed Brown /*@C
1246a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1247089b2837SJed Brown 
1248089b2837SJed Brown    Not Collective
1249089b2837SJed Brown 
1250089b2837SJed Brown    Input Parameter:
1251089b2837SJed Brown .  ts - the TS context
1252089b2837SJed Brown 
1253d8d19677SJose E. Roman    Output Parameters:
12540298fd71SBarry Smith +  r - vector to hold residual (or NULL)
12550298fd71SBarry Smith .  func - the function to compute residual (or NULL)
12560298fd71SBarry Smith -  ctx - the function context (or NULL)
1257089b2837SJed Brown 
1258089b2837SJed Brown    Level: advanced
1259089b2837SJed Brown 
1260db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`
1261089b2837SJed Brown @*/
1262089b2837SJed Brown PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1263089b2837SJed Brown {
1264089b2837SJed Brown   SNES           snes;
126524989b8cSPeter Brune   DM             dm;
1266089b2837SJed Brown 
1267089b2837SJed Brown   PetscFunctionBegin;
1268089b2837SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
12699566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
12709566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
12719566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
12729566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,func,ctx));
1273089b2837SJed Brown   PetscFunctionReturn(0);
1274089b2837SJed Brown }
1275089b2837SJed Brown 
1276089b2837SJed Brown /*@C
1277089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1278089b2837SJed Brown 
1279089b2837SJed Brown    Not Collective
1280089b2837SJed Brown 
1281089b2837SJed Brown    Input Parameter:
1282089b2837SJed Brown .  ts - the TS context
1283089b2837SJed Brown 
1284d8d19677SJose E. Roman    Output Parameters:
12850298fd71SBarry Smith +  r - vector to hold computed right hand side (or NULL)
12860298fd71SBarry Smith .  func - the function to compute right hand side (or NULL)
12870298fd71SBarry Smith -  ctx - the function context (or NULL)
1288089b2837SJed Brown 
1289089b2837SJed Brown    Level: advanced
1290089b2837SJed Brown 
1291db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `SNESGetFunction()`
1292089b2837SJed Brown @*/
1293089b2837SJed Brown PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1294089b2837SJed Brown {
1295089b2837SJed Brown   SNES           snes;
129624989b8cSPeter Brune   DM             dm;
1297089b2837SJed Brown 
1298089b2837SJed Brown   PetscFunctionBegin;
1299089b2837SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
13009566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
13019566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
13029566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
13039566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,func,ctx));
1304316643e7SJed Brown   PetscFunctionReturn(0);
1305316643e7SJed Brown }
1306316643e7SJed Brown 
1307316643e7SJed Brown /*@C
1308a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1309ae8867d6SBarry Smith         provided with TSSetIFunction().
1310316643e7SJed Brown 
13113f9fe445SBarry Smith    Logically Collective on TS
1312316643e7SJed Brown 
1313316643e7SJed Brown    Input Parameters:
1314316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
1315e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1316e5d3d808SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1317316643e7SJed Brown .  f   - the Jacobian evaluation routine
13180298fd71SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1319316643e7SJed Brown 
1320316643e7SJed Brown    Calling sequence of f:
13216bc98fa9SBarry Smith $    PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1322316643e7SJed Brown 
1323316643e7SJed Brown +  t    - time at step/stage being solved
13241b4a444bSJed Brown .  U    - state vector
13251b4a444bSJed Brown .  U_t  - time derivative of state vector
1326316643e7SJed Brown .  a    - shift
1327e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1328e5d3d808SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1329316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1330316643e7SJed Brown 
1331316643e7SJed Brown    Notes:
1332e5d3d808SBarry Smith    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1333316643e7SJed Brown 
1334895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1335895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1336895c21f2SBarry Smith 
1337a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1338b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1339a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1340a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1341a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1342a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1343a4f0a591SBarry Smith 
13446cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13456cd88445SBarry Smith 
13466cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1347ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1348ca5f011dSBarry Smith 
1349316643e7SJed Brown    Level: beginner
1350316643e7SJed Brown 
1351db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1352316643e7SJed Brown 
1353316643e7SJed Brown @*/
1354e5d3d808SBarry Smith PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1355316643e7SJed Brown {
1356089b2837SJed Brown   SNES           snes;
135724989b8cSPeter Brune   DM             dm;
1358316643e7SJed Brown 
1359316643e7SJed Brown   PetscFunctionBegin;
13600700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1361e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1362e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1363e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1364e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
136524989b8cSPeter Brune 
13669566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
13679566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm,f,ctx));
136824989b8cSPeter Brune 
13699566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
13709566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts));
1371316643e7SJed Brown   PetscFunctionReturn(0);
1372316643e7SJed Brown }
1373316643e7SJed Brown 
1374e1244c69SJed Brown /*@
1375e1244c69SJed Brown    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1376e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1377e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1378e1244c69SJed Brown    not been changed by the TS.
1379e1244c69SJed Brown 
1380e1244c69SJed Brown    Logically Collective
1381e1244c69SJed Brown 
13824165533cSJose E. Roman    Input Parameters:
1383e1244c69SJed Brown +  ts - TS context obtained from TSCreate()
1384e1244c69SJed Brown -  reuse - PETSC_TRUE if the RHS Jacobian
1385e1244c69SJed Brown 
1386e1244c69SJed Brown    Level: intermediate
1387e1244c69SJed Brown 
1388db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1389e1244c69SJed Brown @*/
1390e1244c69SJed Brown PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1391e1244c69SJed Brown {
1392e1244c69SJed Brown   PetscFunctionBegin;
1393e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
1394e1244c69SJed Brown   PetscFunctionReturn(0);
1395e1244c69SJed Brown }
1396e1244c69SJed Brown 
1397efe9872eSLisandro Dalcin /*@C
1398efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1399efe9872eSLisandro Dalcin 
1400efe9872eSLisandro Dalcin    Logically Collective on TS
1401efe9872eSLisandro Dalcin 
1402efe9872eSLisandro Dalcin    Input Parameters:
1403efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1404efe9872eSLisandro Dalcin .  F   - vector to hold the residual (or NULL to have it created internally)
1405efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1406efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1407efe9872eSLisandro Dalcin 
1408efe9872eSLisandro Dalcin    Calling sequence of fun:
14096bc98fa9SBarry Smith $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1410efe9872eSLisandro Dalcin 
1411efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1412efe9872eSLisandro Dalcin .  U    - state vector
1413efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1414efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1415efe9872eSLisandro Dalcin .  F    - function vector
1416efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1417efe9872eSLisandro Dalcin 
1418efe9872eSLisandro Dalcin    Level: beginner
1419efe9872eSLisandro Dalcin 
1420db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1421efe9872eSLisandro Dalcin @*/
1422efe9872eSLisandro Dalcin PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1423efe9872eSLisandro Dalcin {
1424efe9872eSLisandro Dalcin   DM             dm;
1425efe9872eSLisandro Dalcin 
1426efe9872eSLisandro Dalcin   PetscFunctionBegin;
1427efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1428efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F,VEC_CLASSID,2);
14299566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts,F,NULL,NULL));
14309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
14319566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm,fun,ctx));
1432efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1433efe9872eSLisandro Dalcin }
1434efe9872eSLisandro Dalcin 
1435efe9872eSLisandro Dalcin /*@C
1436a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1437efe9872eSLisandro Dalcin 
1438efe9872eSLisandro Dalcin   Not Collective
1439efe9872eSLisandro Dalcin 
1440efe9872eSLisandro Dalcin   Input Parameter:
1441efe9872eSLisandro Dalcin . ts - the TS context
1442efe9872eSLisandro Dalcin 
1443d8d19677SJose E. Roman   Output Parameters:
1444efe9872eSLisandro Dalcin + r - vector to hold residual (or NULL)
1445efe9872eSLisandro Dalcin . fun - the function to compute residual (or NULL)
1446efe9872eSLisandro Dalcin - ctx - the function context (or NULL)
1447efe9872eSLisandro Dalcin 
1448efe9872eSLisandro Dalcin   Level: advanced
1449efe9872eSLisandro Dalcin 
1450db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1451efe9872eSLisandro Dalcin @*/
1452efe9872eSLisandro Dalcin PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1453efe9872eSLisandro Dalcin {
1454efe9872eSLisandro Dalcin   SNES           snes;
1455efe9872eSLisandro Dalcin   DM             dm;
1456efe9872eSLisandro Dalcin 
1457efe9872eSLisandro Dalcin   PetscFunctionBegin;
1458efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
14599566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
14609566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
14619566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
14629566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm,fun,ctx));
1463efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1464efe9872eSLisandro Dalcin }
1465efe9872eSLisandro Dalcin 
1466efe9872eSLisandro Dalcin /*@C
1467bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1468efe9872eSLisandro Dalcin         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1469efe9872eSLisandro Dalcin 
1470efe9872eSLisandro Dalcin    Logically Collective on TS
1471efe9872eSLisandro Dalcin 
1472efe9872eSLisandro Dalcin    Input Parameters:
1473efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1474efe9872eSLisandro Dalcin .  J   - Jacobian matrix
1475efe9872eSLisandro Dalcin .  P   - preconditioning matrix for J (may be same as J)
1476efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1477efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1478efe9872eSLisandro Dalcin 
1479efe9872eSLisandro Dalcin    Calling sequence of jac:
14806bc98fa9SBarry Smith $    PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1481efe9872eSLisandro Dalcin 
1482efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1483efe9872eSLisandro Dalcin .  U    - state vector
1484efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1485efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1486efe9872eSLisandro Dalcin .  v    - shift for U_t
1487efe9872eSLisandro Dalcin .  a    - shift for U_tt
1488efe9872eSLisandro Dalcin .  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
1489efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1490efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1491efe9872eSLisandro Dalcin 
1492efe9872eSLisandro Dalcin    Notes:
1493efe9872eSLisandro Dalcin    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1494efe9872eSLisandro Dalcin 
1495efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1496efe9872eSLisandro Dalcin    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.
1497efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1498bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1499efe9872eSLisandro Dalcin 
1500efe9872eSLisandro Dalcin    Level: beginner
1501efe9872eSLisandro Dalcin 
1502db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Jacobian()`
1503efe9872eSLisandro Dalcin @*/
1504efe9872eSLisandro Dalcin PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1505efe9872eSLisandro Dalcin {
1506efe9872eSLisandro Dalcin   DM             dm;
1507efe9872eSLisandro Dalcin 
1508efe9872eSLisandro Dalcin   PetscFunctionBegin;
1509efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1510efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J,MAT_CLASSID,2);
1511efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P,MAT_CLASSID,3);
15129566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts,J,P,NULL,NULL));
15139566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15149566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm,jac,ctx));
1515efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1516efe9872eSLisandro Dalcin }
1517efe9872eSLisandro Dalcin 
1518efe9872eSLisandro Dalcin /*@C
1519efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1520efe9872eSLisandro Dalcin 
1521efe9872eSLisandro Dalcin   Not Collective, but parallel objects are returned if TS is parallel
1522efe9872eSLisandro Dalcin 
1523efe9872eSLisandro Dalcin   Input Parameter:
1524efe9872eSLisandro Dalcin . ts  - The TS context obtained from TSCreate()
1525efe9872eSLisandro Dalcin 
1526efe9872eSLisandro Dalcin   Output Parameters:
1527efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1528efe9872eSLisandro Dalcin . P - The matrix from which the preconditioner is constructed, often the same as J
1529efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1530efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1531efe9872eSLisandro Dalcin 
153295452b02SPatrick Sanan   Notes:
153395452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
1534efe9872eSLisandro Dalcin 
1535efe9872eSLisandro Dalcin   Level: advanced
1536efe9872eSLisandro Dalcin 
1537db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1538efe9872eSLisandro Dalcin 
1539efe9872eSLisandro Dalcin @*/
1540efe9872eSLisandro Dalcin PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1541efe9872eSLisandro Dalcin {
1542efe9872eSLisandro Dalcin   SNES           snes;
1543efe9872eSLisandro Dalcin   DM             dm;
1544efe9872eSLisandro Dalcin 
1545efe9872eSLisandro Dalcin   PetscFunctionBegin;
15469566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
15479566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15489566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes,J,P,NULL,NULL));
15499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15509566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,jac,ctx));
1551efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1552efe9872eSLisandro Dalcin }
1553efe9872eSLisandro Dalcin 
1554efe9872eSLisandro Dalcin /*@
1555efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1556efe9872eSLisandro Dalcin 
1557d083f849SBarry Smith   Collective on TS
1558efe9872eSLisandro Dalcin 
1559efe9872eSLisandro Dalcin   Input Parameters:
1560efe9872eSLisandro Dalcin + ts - the TS context
1561efe9872eSLisandro Dalcin . t - current time
1562efe9872eSLisandro Dalcin . U - state vector
1563efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1564efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1565efe9872eSLisandro Dalcin 
1566efe9872eSLisandro Dalcin   Output Parameter:
1567efe9872eSLisandro Dalcin . F - the residual vector
1568efe9872eSLisandro Dalcin 
1569efe9872eSLisandro Dalcin   Note:
1570efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1571efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1572efe9872eSLisandro Dalcin 
1573efe9872eSLisandro Dalcin   Level: developer
1574efe9872eSLisandro Dalcin 
1575db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Function()`
1576efe9872eSLisandro Dalcin @*/
1577efe9872eSLisandro Dalcin PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1578efe9872eSLisandro Dalcin {
1579efe9872eSLisandro Dalcin   DM             dm;
1580efe9872eSLisandro Dalcin   TSI2Function   I2Function;
1581efe9872eSLisandro Dalcin   void           *ctx;
1582efe9872eSLisandro Dalcin   TSRHSFunction  rhsfunction;
1583efe9872eSLisandro Dalcin 
1584efe9872eSLisandro Dalcin   PetscFunctionBegin;
1585efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1586efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1587efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1588efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1589efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F,VEC_CLASSID,6);
1590efe9872eSLisandro Dalcin 
15919566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15929566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm,&I2Function,&ctx));
15939566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
1594efe9872eSLisandro Dalcin 
1595efe9872eSLisandro Dalcin   if (!I2Function) {
15969566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE));
1597efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1598efe9872eSLisandro Dalcin   }
1599efe9872eSLisandro Dalcin 
16009566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,V,F));
1601efe9872eSLisandro Dalcin 
1602792fecdfSBarry Smith   PetscCallBack("TS callback implicit function",I2Function(ts,t,U,V,A,F,ctx));
1603efe9872eSLisandro Dalcin 
1604efe9872eSLisandro Dalcin   if (rhsfunction) {
1605efe9872eSLisandro Dalcin     Vec Frhs;
16069566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts,&Frhs));
16079566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts,t,U,Frhs));
16089566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F,-1,Frhs));
1609efe9872eSLisandro Dalcin   }
1610efe9872eSLisandro Dalcin 
16119566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,V,F));
1612efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1613efe9872eSLisandro Dalcin }
1614efe9872eSLisandro Dalcin 
1615efe9872eSLisandro Dalcin /*@
1616efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1617efe9872eSLisandro Dalcin 
1618d083f849SBarry Smith   Collective on TS
1619efe9872eSLisandro Dalcin 
1620efe9872eSLisandro Dalcin   Input Parameters:
1621efe9872eSLisandro Dalcin + ts - the TS context
1622efe9872eSLisandro Dalcin . t - current timestep
1623efe9872eSLisandro Dalcin . U - state vector
1624efe9872eSLisandro Dalcin . V - time derivative of state vector
1625efe9872eSLisandro Dalcin . A - second time derivative of state vector
1626efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1627efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1628efe9872eSLisandro Dalcin 
1629efe9872eSLisandro Dalcin   Output Parameters:
1630efe9872eSLisandro Dalcin + J - Jacobian matrix
1631efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1632efe9872eSLisandro Dalcin 
1633efe9872eSLisandro Dalcin   Notes:
1634efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1635efe9872eSLisandro Dalcin 
1636efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1637efe9872eSLisandro Dalcin 
1638efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1639efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1640efe9872eSLisandro Dalcin 
1641efe9872eSLisandro Dalcin   Level: developer
1642efe9872eSLisandro Dalcin 
1643db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`
1644efe9872eSLisandro Dalcin @*/
1645efe9872eSLisandro Dalcin PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1646efe9872eSLisandro Dalcin {
1647efe9872eSLisandro Dalcin   DM             dm;
1648efe9872eSLisandro Dalcin   TSI2Jacobian   I2Jacobian;
1649efe9872eSLisandro Dalcin   void           *ctx;
1650efe9872eSLisandro Dalcin   TSRHSJacobian  rhsjacobian;
1651efe9872eSLisandro Dalcin 
1652efe9872eSLisandro Dalcin   PetscFunctionBegin;
1653efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1654efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1655efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1656efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1657efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J,MAT_CLASSID,8);
1658efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P,MAT_CLASSID,9);
1659efe9872eSLisandro Dalcin 
16609566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
16619566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx));
16629566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobian,NULL));
1663efe9872eSLisandro Dalcin 
1664efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16659566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE));
1666efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1667efe9872eSLisandro Dalcin   }
1668efe9872eSLisandro Dalcin 
16699566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,J,P));
1670792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian",I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx));
1671efe9872eSLisandro Dalcin   if (rhsjacobian) {
1672d60b7d5cSBarry Smith     Mat Jrhs,Prhs;
16739566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts,&Jrhs,&Prhs));
16749566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs));
16759566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J,-1,Jrhs,ts->axpy_pattern));
16769566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P,-1,Prhs,ts->axpy_pattern));
1677efe9872eSLisandro Dalcin   }
1678efe9872eSLisandro Dalcin 
16799566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,J,P));
1680efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1681efe9872eSLisandro Dalcin }
1682efe9872eSLisandro Dalcin 
1683438f35afSJed Brown /*@C
1684438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1685438f35afSJed Brown 
1686438f35afSJed Brown    Logically Collective
1687438f35afSJed Brown 
16884165533cSJose E. Roman    Input Parameters:
1689438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1690a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1691438f35afSJed Brown -  ctx - a context for tvar
1692438f35afSJed Brown 
1693a96d6ef6SBarry Smith     Calling sequence of tvar:
1694a96d6ef6SBarry Smith $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1695a96d6ef6SBarry Smith 
1696a96d6ef6SBarry Smith +   ts - timestep context
16976aad120cSJose E. Roman .   p - input vector (primitive form)
1698a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1699a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1700a96d6ef6SBarry Smith 
1701438f35afSJed Brown    Level: advanced
1702438f35afSJed Brown 
1703438f35afSJed Brown    Notes:
1704438f35afSJed Brown    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
1705438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1706438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1707438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1708438f35afSJed Brown    evaluated via the chain rule, as in
1709438f35afSJed Brown 
1710438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1711438f35afSJed Brown 
1712db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1713438f35afSJed Brown @*/
1714438f35afSJed Brown PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1715438f35afSJed Brown {
1716438f35afSJed Brown   DM             dm;
1717438f35afSJed Brown 
1718438f35afSJed Brown   PetscFunctionBegin;
1719438f35afSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
17209566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
17219566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm,tvar,ctx));
1722438f35afSJed Brown   PetscFunctionReturn(0);
1723438f35afSJed Brown }
1724438f35afSJed Brown 
1725efe9872eSLisandro Dalcin /*@
1726e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1727e3c11fc1SJed Brown 
1728e3c11fc1SJed Brown    Logically Collective
1729e3c11fc1SJed Brown 
1730e3c11fc1SJed Brown    Input Parameters:
1731e3c11fc1SJed Brown +  ts - TS on which to compute
1732e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1733e3c11fc1SJed Brown 
1734e3c11fc1SJed Brown    Output Parameters:
1735e3c11fc1SJed Brown .  C - transient (conservative) variable
1736e3c11fc1SJed Brown 
1737e3c11fc1SJed Brown    Developer Notes:
1738e3c11fc1SJed Brown    If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
1739e3c11fc1SJed Brown    This makes it safe to call without a guard.  One can use TSHasTransientVariable() to check if transient variables are
1740e3c11fc1SJed Brown    being used.
1741e3c11fc1SJed Brown 
1742e3c11fc1SJed Brown    Level: developer
1743e3c11fc1SJed Brown 
1744db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1745e3c11fc1SJed Brown @*/
1746e3c11fc1SJed Brown PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1747e3c11fc1SJed Brown {
1748e3c11fc1SJed Brown   DM             dm;
1749e3c11fc1SJed Brown   DMTS           dmts;
1750e3c11fc1SJed Brown 
1751e3c11fc1SJed Brown   PetscFunctionBegin;
1752e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1753e3c11fc1SJed Brown   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
17549566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
17559566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&dmts));
1756e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1757e3c11fc1SJed Brown     PetscValidHeaderSpecific(C,VEC_CLASSID,3);
17589566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx));
1759e3c11fc1SJed Brown   }
1760e3c11fc1SJed Brown   PetscFunctionReturn(0);
1761e3c11fc1SJed Brown }
1762e3c11fc1SJed Brown 
1763e3c11fc1SJed Brown /*@
1764e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1765e3c11fc1SJed Brown 
1766e3c11fc1SJed Brown    Logically Collective
1767e3c11fc1SJed Brown 
1768e3c11fc1SJed Brown    Input Parameters:
1769e3c11fc1SJed Brown .  ts - TS on which to compute
1770e3c11fc1SJed Brown 
1771e3c11fc1SJed Brown    Output Parameters:
1772e3c11fc1SJed Brown .  has - PETSC_TRUE if transient variables have been set
1773e3c11fc1SJed Brown 
1774e3c11fc1SJed Brown    Level: developer
1775e3c11fc1SJed Brown 
1776db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1777e3c11fc1SJed Brown @*/
1778e3c11fc1SJed Brown PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1779e3c11fc1SJed Brown {
1780e3c11fc1SJed Brown   DM             dm;
1781e3c11fc1SJed Brown   DMTS           dmts;
1782e3c11fc1SJed Brown 
1783e3c11fc1SJed Brown   PetscFunctionBegin;
1784e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
17859566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
17869566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&dmts));
1787e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1788e3c11fc1SJed Brown   PetscFunctionReturn(0);
1789e3c11fc1SJed Brown }
1790e3c11fc1SJed Brown 
1791e3c11fc1SJed Brown /*@
1792efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1793efe9872eSLisandro Dalcin    for use by the TS routines handling second order equations.
1794efe9872eSLisandro Dalcin 
1795d083f849SBarry Smith    Logically Collective on TS
1796efe9872eSLisandro Dalcin 
1797efe9872eSLisandro Dalcin    Input Parameters:
1798efe9872eSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
1799efe9872eSLisandro Dalcin .  u - the solution vector
1800efe9872eSLisandro Dalcin -  v - the time derivative vector
1801efe9872eSLisandro Dalcin 
1802efe9872eSLisandro Dalcin    Level: beginner
1803efe9872eSLisandro Dalcin 
1804efe9872eSLisandro Dalcin @*/
1805efe9872eSLisandro Dalcin PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1806efe9872eSLisandro Dalcin {
1807efe9872eSLisandro Dalcin   PetscFunctionBegin;
1808efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1809efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
1810efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v,VEC_CLASSID,3);
18119566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts,u));
18129566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18139566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1814efe9872eSLisandro Dalcin   ts->vec_dot = v;
1815efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1816efe9872eSLisandro Dalcin }
1817efe9872eSLisandro Dalcin 
1818efe9872eSLisandro Dalcin /*@
1819efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1820efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1821efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1822efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1823efe9872eSLisandro Dalcin 
1824efe9872eSLisandro Dalcin    Not Collective, but Vec returned is parallel if TS is parallel
1825efe9872eSLisandro Dalcin 
1826efe9872eSLisandro Dalcin    Input Parameter:
1827efe9872eSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
1828efe9872eSLisandro Dalcin 
1829d8d19677SJose E. Roman    Output Parameters:
1830efe9872eSLisandro Dalcin +  u - the vector containing the solution
1831efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1832efe9872eSLisandro Dalcin 
1833efe9872eSLisandro Dalcin    Level: intermediate
1834efe9872eSLisandro Dalcin 
1835db781477SPatrick Sanan .seealso: `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1836efe9872eSLisandro Dalcin 
1837efe9872eSLisandro Dalcin @*/
1838efe9872eSLisandro Dalcin PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1839efe9872eSLisandro Dalcin {
1840efe9872eSLisandro Dalcin   PetscFunctionBegin;
1841efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1842efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u,2);
1843efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v,3);
1844efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1845efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
1846efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1847efe9872eSLisandro Dalcin }
1848efe9872eSLisandro Dalcin 
184955849f57SBarry Smith /*@C
185055849f57SBarry Smith   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
185155849f57SBarry Smith 
185255849f57SBarry Smith   Collective on PetscViewer
185355849f57SBarry Smith 
185455849f57SBarry Smith   Input Parameters:
185555849f57SBarry Smith + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
185655849f57SBarry Smith            some related function before a call to TSLoad().
185755849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
185855849f57SBarry Smith 
185955849f57SBarry Smith    Level: intermediate
186055849f57SBarry Smith 
186155849f57SBarry Smith   Notes:
186255849f57SBarry Smith    The type is determined by the data in the file, any type set into the TS before this call is ignored.
186355849f57SBarry Smith 
186455849f57SBarry Smith   Notes for advanced users:
186555849f57SBarry Smith   Most users should not need to know the details of the binary storage
186655849f57SBarry Smith   format, since TSLoad() and TSView() completely hide these details.
186755849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
186855849f57SBarry Smith   format is
186955849f57SBarry Smith .vb
187055849f57SBarry Smith      has not yet been determined
187155849f57SBarry Smith .ve
187255849f57SBarry Smith 
1873db781477SPatrick Sanan .seealso: `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
187455849f57SBarry Smith @*/
1875f2c2a1b9SBarry Smith PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
187655849f57SBarry Smith {
187755849f57SBarry Smith   PetscBool      isbinary;
187855849f57SBarry Smith   PetscInt       classid;
187955849f57SBarry Smith   char           type[256];
18802d53ad75SBarry Smith   DMTS           sdm;
1881ad6bc421SBarry Smith   DM             dm;
188255849f57SBarry Smith 
188355849f57SBarry Smith   PetscFunctionBegin;
1884f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
188555849f57SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
18869566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
18873c633725SBarry Smith   PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
188855849f57SBarry Smith 
18899566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT));
18903c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
18919566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR));
18929566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
18931baa6e33SBarry Smith   if (ts->ops->load) PetscCall((*ts->ops->load)(ts,viewer));
18949566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts),&dm));
18959566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm,viewer));
18969566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts,dm));
18979566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm,&ts->vec_sol));
18989566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol,viewer));
18999566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm,&sdm));
19009566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm,viewer));
190155849f57SBarry Smith   PetscFunctionReturn(0);
190255849f57SBarry Smith }
190355849f57SBarry Smith 
19049804daf3SBarry Smith #include <petscdraw.h>
1905e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1906e04113cfSBarry Smith #include <petscviewersaws.h>
1907f05ece33SBarry Smith #endif
1908fe2efc57SMark 
1909fe2efc57SMark /*@C
1910fe2efc57SMark    TSViewFromOptions - View from Options
1911fe2efc57SMark 
1912fe2efc57SMark    Collective on TS
1913fe2efc57SMark 
1914fe2efc57SMark    Input Parameters:
1915fe2efc57SMark +  A - the application ordering context
1916736c3998SJose E. Roman .  obj - Optional object
1917736c3998SJose E. Roman -  name - command line option
1918fe2efc57SMark 
1919fe2efc57SMark    Level: intermediate
1920db781477SPatrick Sanan .seealso: `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1921fe2efc57SMark @*/
1922fe2efc57SMark PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
1923fe2efc57SMark {
1924fe2efc57SMark   PetscFunctionBegin;
1925fe2efc57SMark   PetscValidHeaderSpecific(A,TS_CLASSID,1);
19269566063dSJacob Faibussowitsch   PetscCall(PetscObjectViewFromOptions((PetscObject)A,obj,name));
1927fe2efc57SMark   PetscFunctionReturn(0);
1928fe2efc57SMark }
1929fe2efc57SMark 
19307e2c5f70SBarry Smith /*@C
1931d763cef2SBarry Smith     TSView - Prints the TS data structure.
1932d763cef2SBarry Smith 
19334c49b128SBarry Smith     Collective on TS
1934d763cef2SBarry Smith 
1935d763cef2SBarry Smith     Input Parameters:
1936d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
1937d763cef2SBarry Smith -   viewer - visualization context
1938d763cef2SBarry Smith 
1939d763cef2SBarry Smith     Options Database Key:
1940d763cef2SBarry Smith .   -ts_view - calls TSView() at end of TSStep()
1941d763cef2SBarry Smith 
1942d763cef2SBarry Smith     Notes:
1943d763cef2SBarry Smith     The available visualization contexts include
1944b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1945b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1946d763cef2SBarry Smith          output where only the first processor opens
1947d763cef2SBarry Smith          the file.  All other processors send their
1948d763cef2SBarry Smith          data to the first processor to print.
1949d763cef2SBarry Smith 
1950d763cef2SBarry Smith     The user can open an alternative visualization context with
1951b0a32e0cSBarry Smith     PetscViewerASCIIOpen() - output to a specified file.
1952d763cef2SBarry Smith 
1953595c91d4SBarry Smith     In the debugger you can do "call TSView(ts,0)" to display the TS solver. (The same holds for any PETSc object viewer).
1954595c91d4SBarry Smith 
1955d763cef2SBarry Smith     Level: beginner
1956d763cef2SBarry Smith 
1957db781477SPatrick Sanan .seealso: `PetscViewerASCIIOpen()`
1958d763cef2SBarry Smith @*/
19597087cfbeSBarry Smith PetscErrorCode  TSView(TS ts,PetscViewer viewer)
1960d763cef2SBarry Smith {
196119fd82e9SBarry Smith   TSType         type;
19622b0a91c0SBarry Smith   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
19632d53ad75SBarry Smith   DMTS           sdm;
1964e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1965536b137fSBarry Smith   PetscBool      issaws;
1966f05ece33SBarry Smith #endif
1967d763cef2SBarry Smith 
1968d763cef2SBarry Smith   PetscFunctionBegin;
19690700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1970*1e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer));
19710700a824SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
1972c9780b6fSBarry Smith   PetscCheckSameComm(ts,1,viewer,2);
1973fd16b177SBarry Smith 
19749566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii));
19759566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring));
19769566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
19779566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw));
1978e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19799566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws));
1980f05ece33SBarry Smith #endif
198132077d6dSBarry Smith   if (iascii) {
19829566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer));
1983efd4aadfSBarry Smith     if (ts->ops->view) {
19849566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
19859566063dSJacob Faibussowitsch       PetscCall((*ts->ops->view)(ts,viewer));
19869566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1987efd4aadfSBarry Smith     }
1988*1e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum steps=%" PetscInt_FMT "\n",ts->max_steps));
1989*1e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time));
1990*1e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of I function evaluations=%" PetscInt_FMT "\n",ts->ifuncs));
1991*1e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of I Jacobian evaluations=%" PetscInt_FMT "\n",ts->ijacs));
1992*1e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of RHS function evaluations=%" PetscInt_FMT "\n",ts->rhsfuncs));
1993*1e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n",ts->rhsjacs));
1994efd4aadfSBarry Smith     if (ts->usessnes) {
1995efd4aadfSBarry Smith       PetscBool lin;
1996*1e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%" PetscInt_FMT "\n",ts->snes_its));
199763a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%" PetscInt_FMT "\n",ts->ksp_its));
19989566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,""));
199963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%" PetscInt_FMT "\n",lin ? "" : "non",ts->num_snes_failures));
2000efd4aadfSBarry Smith     }
200163a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%" PetscInt_FMT "\n",ts->reject));
2002*1e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, "));
2003*1e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol));
2004*1e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n"));
2005*1e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol));
20069566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20079566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt,viewer));
20089566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
20090f5bd95cSBarry Smith   } else if (isstring) {
20109566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts,&type));
20119566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type));
20129566063dSJacob Faibussowitsch     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
201355849f57SBarry Smith   } else if (isbinary) {
201455849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
201555849f57SBarry Smith     MPI_Comm    comm;
201655849f57SBarry Smith     PetscMPIInt rank;
201755849f57SBarry Smith     char        type[256];
201855849f57SBarry Smith 
20199566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts,&comm));
20209566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm,&rank));
2021dd400576SPatrick Sanan     if (rank == 0) {
20229566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT));
20239566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type,((PetscObject)ts)->type_name,256));
20249566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR));
202555849f57SBarry Smith     }
20261baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
20279566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt,viewer));
20289566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm,viewer));
20299566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol,viewer));
20309566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm,&sdm));
20319566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm,viewer));
20322b0a91c0SBarry Smith   } else if (isdraw) {
20332b0a91c0SBarry Smith     PetscDraw draw;
20342b0a91c0SBarry Smith     char      str[36];
203589fd9fafSBarry Smith     PetscReal x,y,bottom,h;
20362b0a91c0SBarry Smith 
20379566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
20389566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw,&x,&y));
20399566063dSJacob Faibussowitsch     PetscCall(PetscStrcpy(str,"TS: "));
20409566063dSJacob Faibussowitsch     PetscCall(PetscStrcat(str,((PetscObject)ts)->type_name));
20419566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h));
204289fd9fafSBarry Smith     bottom = y - h;
20439566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw,x,bottom));
20441baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
20459566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt,viewer));
20469566063dSJacob Faibussowitsch     if (ts->snes)  PetscCall(SNESView(ts->snes,viewer));
20479566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2048e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2049536b137fSBarry Smith   } else if (issaws) {
2050d45a07a7SBarry Smith     PetscMPIInt rank;
20512657e9d9SBarry Smith     const char  *name;
20522657e9d9SBarry Smith 
20539566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts,&name));
20549566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
2055dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2056d45a07a7SBarry Smith       char       dir[1024];
2057d45a07a7SBarry Smith 
20589566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts,viewer));
20599566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name));
2060792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
20619566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name));
2062792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2063d763cef2SBarry Smith     }
20641baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
2065f05ece33SBarry Smith #endif
2066f05ece33SBarry Smith   }
206736a9e3b9SBarry Smith   if (ts->snes && ts->usessnes)  {
20689566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20699566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes,viewer));
20709566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
207136a9e3b9SBarry Smith   }
20729566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm,&sdm));
20739566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm,viewer));
2074f05ece33SBarry Smith 
20759566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20769566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials));
20779566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
2078d763cef2SBarry Smith   PetscFunctionReturn(0);
2079d763cef2SBarry Smith }
2080d763cef2SBarry Smith 
2081b07ff414SBarry Smith /*@
2082d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2083d763cef2SBarry Smith    the timesteppers.
2084d763cef2SBarry Smith 
20853f9fe445SBarry Smith    Logically Collective on TS
2086d763cef2SBarry Smith 
2087d763cef2SBarry Smith    Input Parameters:
2088d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2089d763cef2SBarry Smith -  usrP - optional user context
2090d763cef2SBarry Smith 
209195452b02SPatrick Sanan    Fortran Notes:
209295452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2093daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2094daf670e6SBarry Smith 
2095d763cef2SBarry Smith    Level: intermediate
2096d763cef2SBarry Smith 
2097db781477SPatrick Sanan .seealso: `TSGetApplicationContext()`
2098d763cef2SBarry Smith @*/
20997087cfbeSBarry Smith PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2100d763cef2SBarry Smith {
2101d763cef2SBarry Smith   PetscFunctionBegin;
21020700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2103d763cef2SBarry Smith   ts->user = usrP;
2104d763cef2SBarry Smith   PetscFunctionReturn(0);
2105d763cef2SBarry Smith }
2106d763cef2SBarry Smith 
2107b07ff414SBarry Smith /*@
2108d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2109d763cef2SBarry Smith     timestepper.
2110d763cef2SBarry Smith 
2111d763cef2SBarry Smith     Not Collective
2112d763cef2SBarry Smith 
2113d763cef2SBarry Smith     Input Parameter:
2114d763cef2SBarry Smith .   ts - the TS context obtained from TSCreate()
2115d763cef2SBarry Smith 
2116d763cef2SBarry Smith     Output Parameter:
2117d763cef2SBarry Smith .   usrP - user context
2118d763cef2SBarry Smith 
211995452b02SPatrick Sanan    Fortran Notes:
212095452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2121daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2122daf670e6SBarry Smith 
2123d763cef2SBarry Smith     Level: intermediate
2124d763cef2SBarry Smith 
2125db781477SPatrick Sanan .seealso: `TSSetApplicationContext()`
2126d763cef2SBarry Smith @*/
2127e71120c6SJed Brown PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2128d763cef2SBarry Smith {
2129d763cef2SBarry Smith   PetscFunctionBegin;
21300700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2131e71120c6SJed Brown   *(void**)usrP = ts->user;
2132d763cef2SBarry Smith   PetscFunctionReturn(0);
2133d763cef2SBarry Smith }
2134d763cef2SBarry Smith 
2135d763cef2SBarry Smith /*@
213680275a0aSLisandro Dalcin    TSGetStepNumber - Gets the number of steps completed.
2137d763cef2SBarry Smith 
2138d763cef2SBarry Smith    Not Collective
2139d763cef2SBarry Smith 
2140d763cef2SBarry Smith    Input Parameter:
2141d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2142d763cef2SBarry Smith 
2143d763cef2SBarry Smith    Output Parameter:
214480275a0aSLisandro Dalcin .  steps - number of steps completed so far
2145d763cef2SBarry Smith 
2146d763cef2SBarry Smith    Level: intermediate
2147d763cef2SBarry Smith 
2148db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2149d763cef2SBarry Smith @*/
215080275a0aSLisandro Dalcin PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2151d763cef2SBarry Smith {
2152d763cef2SBarry Smith   PetscFunctionBegin;
21530700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
215480275a0aSLisandro Dalcin   PetscValidIntPointer(steps,2);
215580275a0aSLisandro Dalcin   *steps = ts->steps;
215680275a0aSLisandro Dalcin   PetscFunctionReturn(0);
215780275a0aSLisandro Dalcin }
215880275a0aSLisandro Dalcin 
215980275a0aSLisandro Dalcin /*@
216080275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
216180275a0aSLisandro Dalcin 
216280275a0aSLisandro Dalcin    Logically Collective on TS
216380275a0aSLisandro Dalcin 
216480275a0aSLisandro Dalcin    Input Parameters:
216580275a0aSLisandro Dalcin +  ts - the TS context
216680275a0aSLisandro Dalcin -  steps - number of steps completed so far
216780275a0aSLisandro Dalcin 
216880275a0aSLisandro Dalcin    Notes:
216980275a0aSLisandro Dalcin    For most uses of the TS solvers the user need not explicitly call
217080275a0aSLisandro Dalcin    TSSetStepNumber(), as the step counter is appropriately updated in
217180275a0aSLisandro Dalcin    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
217280275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
217380275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
217480275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
217580275a0aSLisandro Dalcin    timestepping from a previously interrupted run in such a way that TS
217680275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
217780275a0aSLisandro Dalcin 
217880275a0aSLisandro Dalcin    Level: advanced
217980275a0aSLisandro Dalcin 
2180db781477SPatrick Sanan .seealso: `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
218180275a0aSLisandro Dalcin @*/
218280275a0aSLisandro Dalcin PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
218380275a0aSLisandro Dalcin {
218480275a0aSLisandro Dalcin   PetscFunctionBegin;
218580275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
218680275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts,steps,2);
21873c633725SBarry Smith   PetscCheck(steps >= 0,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
218880275a0aSLisandro Dalcin   ts->steps = steps;
2189d763cef2SBarry Smith   PetscFunctionReturn(0);
2190d763cef2SBarry Smith }
2191d763cef2SBarry Smith 
2192d763cef2SBarry Smith /*@
2193d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2194d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2195d763cef2SBarry Smith 
21963f9fe445SBarry Smith    Logically Collective on TS
2197d763cef2SBarry Smith 
2198d763cef2SBarry Smith    Input Parameters:
2199d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2200d763cef2SBarry Smith -  time_step - the size of the timestep
2201d763cef2SBarry Smith 
2202d763cef2SBarry Smith    Level: intermediate
2203d763cef2SBarry Smith 
2204db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSSetTime()`
2205d763cef2SBarry Smith 
2206d763cef2SBarry Smith @*/
22077087cfbeSBarry Smith PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2208d763cef2SBarry Smith {
2209d763cef2SBarry Smith   PetscFunctionBegin;
22100700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2211c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts,time_step,2);
2212d763cef2SBarry Smith   ts->time_step = time_step;
2213d763cef2SBarry Smith   PetscFunctionReturn(0);
2214d763cef2SBarry Smith }
2215d763cef2SBarry Smith 
2216a43b19c4SJed Brown /*@
221749354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
221849354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
221949354f04SShri Abhyankar      or just return at the final time TS computed.
2220a43b19c4SJed Brown 
2221a43b19c4SJed Brown   Logically Collective on TS
2222a43b19c4SJed Brown 
2223d8d19677SJose E. Roman    Input Parameters:
2224a43b19c4SJed Brown +   ts - the time-step context
222549354f04SShri Abhyankar -   eftopt - exact final time option
2226a43b19c4SJed Brown 
2227feed9e9dSBarry Smith $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2228feed9e9dSBarry Smith $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2229feed9e9dSBarry Smith $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2230feed9e9dSBarry Smith 
2231feed9e9dSBarry Smith    Options Database:
2232feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2233feed9e9dSBarry Smith 
2234ee346746SBarry Smith    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2235ee346746SBarry Smith     then the final time you selected.
2236ee346746SBarry Smith 
2237a43b19c4SJed Brown    Level: beginner
2238a43b19c4SJed Brown 
2239db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2240a43b19c4SJed Brown @*/
224149354f04SShri Abhyankar PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2242a43b19c4SJed Brown {
2243a43b19c4SJed Brown   PetscFunctionBegin;
2244a43b19c4SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
224549354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
224649354f04SShri Abhyankar   ts->exact_final_time = eftopt;
2247a43b19c4SJed Brown   PetscFunctionReturn(0);
2248a43b19c4SJed Brown }
2249a43b19c4SJed Brown 
2250d763cef2SBarry Smith /*@
2251f6953c82SLisandro Dalcin    TSGetExactFinalTime - Gets the exact final time option.
2252f6953c82SLisandro Dalcin 
2253f6953c82SLisandro Dalcin    Not Collective
2254f6953c82SLisandro Dalcin 
2255f6953c82SLisandro Dalcin    Input Parameter:
2256f6953c82SLisandro Dalcin .  ts - the TS context
2257f6953c82SLisandro Dalcin 
2258f6953c82SLisandro Dalcin    Output Parameter:
2259f6953c82SLisandro Dalcin .  eftopt - exact final time option
2260f6953c82SLisandro Dalcin 
2261f6953c82SLisandro Dalcin    Level: beginner
2262f6953c82SLisandro Dalcin 
2263db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2264f6953c82SLisandro Dalcin @*/
2265f6953c82SLisandro Dalcin PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2266f6953c82SLisandro Dalcin {
2267f6953c82SLisandro Dalcin   PetscFunctionBegin;
2268f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2269f6953c82SLisandro Dalcin   PetscValidPointer(eftopt,2);
2270f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
2271f6953c82SLisandro Dalcin   PetscFunctionReturn(0);
2272f6953c82SLisandro Dalcin }
2273f6953c82SLisandro Dalcin 
2274f6953c82SLisandro Dalcin /*@
2275d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2276d763cef2SBarry Smith 
2277d763cef2SBarry Smith    Not Collective
2278d763cef2SBarry Smith 
2279d763cef2SBarry Smith    Input Parameter:
2280d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2281d763cef2SBarry Smith 
2282d763cef2SBarry Smith    Output Parameter:
2283d763cef2SBarry Smith .  dt - the current timestep size
2284d763cef2SBarry Smith 
2285d763cef2SBarry Smith    Level: intermediate
2286d763cef2SBarry Smith 
2287db781477SPatrick Sanan .seealso: `TSSetTimeStep()`, `TSGetTime()`
2288d763cef2SBarry Smith 
2289d763cef2SBarry Smith @*/
22907087cfbeSBarry Smith PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2291d763cef2SBarry Smith {
2292d763cef2SBarry Smith   PetscFunctionBegin;
22930700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2294f7cf8827SBarry Smith   PetscValidRealPointer(dt,2);
2295d763cef2SBarry Smith   *dt = ts->time_step;
2296d763cef2SBarry Smith   PetscFunctionReturn(0);
2297d763cef2SBarry Smith }
2298d763cef2SBarry Smith 
2299d8e5e3e6SSatish Balay /*@
2300d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2301d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2302d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2303d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2304d763cef2SBarry Smith 
2305d763cef2SBarry Smith    Not Collective, but Vec returned is parallel if TS is parallel
2306d763cef2SBarry Smith 
2307d763cef2SBarry Smith    Input Parameter:
2308d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2309d763cef2SBarry Smith 
2310d763cef2SBarry Smith    Output Parameter:
2311d763cef2SBarry Smith .  v - the vector containing the solution
2312d763cef2SBarry Smith 
231363e21af5SBarry Smith    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
231463e21af5SBarry Smith    final time. It returns the solution at the next timestep.
231563e21af5SBarry Smith 
2316d763cef2SBarry Smith    Level: intermediate
2317d763cef2SBarry Smith 
2318db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2319d763cef2SBarry Smith 
2320d763cef2SBarry Smith @*/
23217087cfbeSBarry Smith PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2322d763cef2SBarry Smith {
2323d763cef2SBarry Smith   PetscFunctionBegin;
23240700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
23254482741eSBarry Smith   PetscValidPointer(v,2);
23268737fe31SLisandro Dalcin   *v = ts->vec_sol;
2327d763cef2SBarry Smith   PetscFunctionReturn(0);
2328d763cef2SBarry Smith }
2329d763cef2SBarry Smith 
233003fe5f5eSDebojyoti Ghosh /*@
2331b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
233203fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2333b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
233403fe5f5eSDebojyoti Ghosh    structure as the solution vector.
233503fe5f5eSDebojyoti Ghosh 
233603fe5f5eSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
233703fe5f5eSDebojyoti Ghosh 
233803fe5f5eSDebojyoti Ghosh    Parameters :
2339a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2340b2bf4f3aSDebojyoti Ghosh .  n - If v is PETSC_NULL, then the number of solution components is
2341b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
234203fe5f5eSDebojyoti Ghosh        returned in v.
2343a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
234403fe5f5eSDebojyoti Ghosh        (may be PETSC_NULL to use this function to find out
2345b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
234603fe5f5eSDebojyoti Ghosh 
23474cdd57e5SDebojyoti Ghosh    Level: advanced
234803fe5f5eSDebojyoti Ghosh 
2349db781477SPatrick Sanan .seealso: `TSGetSolution()`
235003fe5f5eSDebojyoti Ghosh 
235103fe5f5eSDebojyoti Ghosh @*/
2352b2bf4f3aSDebojyoti Ghosh PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
235303fe5f5eSDebojyoti Ghosh {
235403fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
235503fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2356b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2357*1e66621cSBarry Smith   else PetscCall((*ts->ops->getsolutioncomponents)(ts,n,v));
235803fe5f5eSDebojyoti Ghosh   PetscFunctionReturn(0);
235903fe5f5eSDebojyoti Ghosh }
236003fe5f5eSDebojyoti Ghosh 
23614cdd57e5SDebojyoti Ghosh /*@
23624cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
23634cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
23644cdd57e5SDebojyoti Ghosh 
23654cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
23664cdd57e5SDebojyoti Ghosh 
23674cdd57e5SDebojyoti Ghosh    Parameters :
2368a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2369a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
23704cdd57e5SDebojyoti Ghosh 
23714cdd57e5SDebojyoti Ghosh    Level: intermediate
23724cdd57e5SDebojyoti Ghosh 
2373db781477SPatrick Sanan .seealso: `TSGetSolution()`
23744cdd57e5SDebojyoti Ghosh 
23754cdd57e5SDebojyoti Ghosh @*/
23764cdd57e5SDebojyoti Ghosh PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
23774cdd57e5SDebojyoti Ghosh {
23784cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23794cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2380*1e66621cSBarry Smith   if (ts->ops->getauxsolution) PetscCall((*ts->ops->getauxsolution)(ts,v));
2381*1e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23824cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
23834cdd57e5SDebojyoti Ghosh }
23844cdd57e5SDebojyoti Ghosh 
23854cdd57e5SDebojyoti Ghosh /*@
23864cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
23874cdd57e5SDebojyoti Ghosh    TSType has an error estimation functionality.
23884cdd57e5SDebojyoti Ghosh 
23894cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
23904cdd57e5SDebojyoti Ghosh 
23919657682dSDebojyoti Ghosh    Note: MUST call after TSSetUp()
23929657682dSDebojyoti Ghosh 
23934cdd57e5SDebojyoti Ghosh    Parameters :
2394a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2395657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2396a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
23974cdd57e5SDebojyoti Ghosh 
23984cdd57e5SDebojyoti Ghosh    Level: intermediate
23994cdd57e5SDebojyoti Ghosh 
2400db781477SPatrick Sanan .seealso: `TSGetSolution()`, `TSSetTimeError()`
24014cdd57e5SDebojyoti Ghosh 
24024cdd57e5SDebojyoti Ghosh @*/
24030a01e1b2SEmil Constantinescu PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
24044cdd57e5SDebojyoti Ghosh {
24054cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24064cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2407*1e66621cSBarry Smith   if (ts->ops->gettimeerror) PetscCall((*ts->ops->gettimeerror)(ts,n,v));
2408*1e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
24094cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
24104cdd57e5SDebojyoti Ghosh }
24114cdd57e5SDebojyoti Ghosh 
241257df6a1bSDebojyoti Ghosh /*@
241357df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
241457df6a1bSDebojyoti Ghosh    TSType has an error estimation functionality. This can be used
241557df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
241657df6a1bSDebojyoti Ghosh 
241757df6a1bSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
241857df6a1bSDebojyoti Ghosh 
241957df6a1bSDebojyoti Ghosh    Parameters :
2420a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2421a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
242257df6a1bSDebojyoti Ghosh 
242357df6a1bSDebojyoti Ghosh    Level: intermediate
242457df6a1bSDebojyoti Ghosh 
2425db781477SPatrick Sanan .seealso: `TSSetSolution()`, `TSGetTimeError)`
242657df6a1bSDebojyoti Ghosh 
242757df6a1bSDebojyoti Ghosh @*/
242857df6a1bSDebojyoti Ghosh PetscErrorCode  TSSetTimeError(TS ts,Vec v)
242957df6a1bSDebojyoti Ghosh {
243057df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
243157df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
24323c633725SBarry Smith   PetscCheck(ts->setupcalled,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
24331baa6e33SBarry Smith   if (ts->ops->settimeerror) PetscCall((*ts->ops->settimeerror)(ts,v));
243457df6a1bSDebojyoti Ghosh   PetscFunctionReturn(0);
243557df6a1bSDebojyoti Ghosh }
243657df6a1bSDebojyoti Ghosh 
2437bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2438d8e5e3e6SSatish Balay /*@
2439bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2440d763cef2SBarry Smith 
2441bdad233fSMatthew Knepley   Not collective
2442d763cef2SBarry Smith 
2443bdad233fSMatthew Knepley   Input Parameters:
2444bdad233fSMatthew Knepley + ts   - The TS
2445bdad233fSMatthew Knepley - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2446d763cef2SBarry Smith .vb
24470910c330SBarry Smith          U_t - A U = 0      (linear)
24480910c330SBarry Smith          U_t - A(t) U = 0   (linear)
24490910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2450d763cef2SBarry Smith .ve
2451d763cef2SBarry Smith 
2452d763cef2SBarry Smith    Level: beginner
2453d763cef2SBarry Smith 
2454db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2455d763cef2SBarry Smith @*/
24567087cfbeSBarry Smith PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2457a7cc72afSBarry Smith {
2458d763cef2SBarry Smith   PetscFunctionBegin;
24590700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2460bdad233fSMatthew Knepley   ts->problem_type = type;
24619e2a6581SJed Brown   if (type == TS_LINEAR) {
24629e2a6581SJed Brown     SNES snes;
24639566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
24649566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes,SNESKSPONLY));
24659e2a6581SJed Brown   }
2466d763cef2SBarry Smith   PetscFunctionReturn(0);
2467d763cef2SBarry Smith }
2468d763cef2SBarry Smith 
2469bdad233fSMatthew Knepley /*@C
2470bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2471bdad233fSMatthew Knepley 
2472bdad233fSMatthew Knepley   Not collective
2473bdad233fSMatthew Knepley 
2474bdad233fSMatthew Knepley   Input Parameter:
2475bdad233fSMatthew Knepley . ts   - The TS
2476bdad233fSMatthew Knepley 
2477bdad233fSMatthew Knepley   Output Parameter:
2478bdad233fSMatthew Knepley . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2479bdad233fSMatthew Knepley .vb
2480089b2837SJed Brown          M U_t = A U
2481089b2837SJed Brown          M(t) U_t = A(t) U
2482b5abc632SBarry Smith          F(t,U,U_t)
2483bdad233fSMatthew Knepley .ve
2484bdad233fSMatthew Knepley 
2485bdad233fSMatthew Knepley    Level: beginner
2486bdad233fSMatthew Knepley 
2487db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2488bdad233fSMatthew Knepley @*/
24897087cfbeSBarry Smith PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2490a7cc72afSBarry Smith {
2491bdad233fSMatthew Knepley   PetscFunctionBegin;
24920700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
24934482741eSBarry Smith   PetscValidIntPointer(type,2);
2494bdad233fSMatthew Knepley   *type = ts->problem_type;
2495bdad233fSMatthew Knepley   PetscFunctionReturn(0);
2496bdad233fSMatthew Knepley }
2497d763cef2SBarry Smith 
2498303a5415SBarry Smith /*
2499303a5415SBarry Smith     Attempt to check/preset a default value for the exact final time option. This is needed at the beginning of TSSolve() and in TSSetUp()
2500303a5415SBarry Smith */
2501303a5415SBarry Smith static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2502303a5415SBarry Smith {
2503303a5415SBarry Smith   PetscBool      isnone;
2504303a5415SBarry Smith 
2505303a5415SBarry Smith   PetscFunctionBegin;
25069566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
25079566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
2508303a5415SBarry Smith 
25099566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone));
2510*1e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2511*1e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2512303a5415SBarry Smith   PetscFunctionReturn(0);
2513303a5415SBarry Smith }
2514303a5415SBarry Smith 
2515d763cef2SBarry Smith /*@
2516303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2517d763cef2SBarry Smith 
2518d763cef2SBarry Smith    Collective on TS
2519d763cef2SBarry Smith 
2520d763cef2SBarry Smith    Input Parameter:
2521d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2522d763cef2SBarry Smith 
2523d763cef2SBarry Smith    Notes:
2524d763cef2SBarry Smith    For basic use of the TS solvers the user need not explicitly call
2525d763cef2SBarry Smith    TSSetUp(), since these actions will automatically occur during
2526141bd67dSStefano Zampini    the call to TSStep() or TSSolve().  However, if one wishes to control this
2527d763cef2SBarry Smith    phase separately, TSSetUp() should be called after TSCreate()
2528141bd67dSStefano Zampini    and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().
2529d763cef2SBarry Smith 
2530d763cef2SBarry Smith    Level: advanced
2531d763cef2SBarry Smith 
2532db781477SPatrick Sanan .seealso: `TSCreate()`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2533d763cef2SBarry Smith @*/
25347087cfbeSBarry Smith PetscErrorCode  TSSetUp(TS ts)
2535d763cef2SBarry Smith {
25366c6b9e74SPeter Brune   DM             dm;
25376c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2538d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2539cd11d68dSLisandro Dalcin   TSIFunction    ifun;
25406c6b9e74SPeter Brune   TSIJacobian    ijac;
2541efe9872eSLisandro Dalcin   TSI2Jacobian   i2jac;
25426c6b9e74SPeter Brune   TSRHSJacobian  rhsjac;
2543d763cef2SBarry Smith 
2544d763cef2SBarry Smith   PetscFunctionBegin;
25450700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2546277b19d0SLisandro Dalcin   if (ts->setupcalled) PetscFunctionReturn(0);
2547277b19d0SLisandro Dalcin 
25487adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
25499566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts,NULL,&ifun,NULL));
25509566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts,ifun ? TSBEULER : TSEULER));
2551d763cef2SBarry Smith   }
2552277b19d0SLisandro Dalcin 
25531a638600SStefano Zampini   if (!ts->vec_sol) {
2554*1e66621cSBarry Smith     PetscCheck(ts->dm,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
25559566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm,&ts->vec_sol));
25561a638600SStefano Zampini   }
2557277b19d0SLisandro Dalcin 
25584a658b32SHong Zhang   if (ts->tspan) {
2559*1e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol,ts->tspan->num_span_times,&ts->tspan->vecs_sol));
25604a658b32SHong Zhang   }
2561298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25629566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2563298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2564298bade4SHong Zhang   }
2565298bade4SHong Zhang 
2566cd4cee2dSHong Zhang   if (ts->quadraturets) {
25679566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25689566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25699566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand));
2570cd4cee2dSHong Zhang   }
2571cd4cee2dSHong Zhang 
25729566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL));
2573f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2574e1244c69SJed Brown     Mat Amat,Pmat;
2575e1244c69SJed Brown     SNES snes;
25769566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
25779566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL));
2578e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2579e1244c69SJed Brown      * have displaced the RHS matrix */
2580971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2581abc0d4abSBarry Smith       /* 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 */
25829566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat));
25839566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,Amat,NULL,NULL,NULL));
25849566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2585e1244c69SJed Brown     }
2586971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25879566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat));
25889566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,NULL,Pmat,NULL,NULL));
25899566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2590e1244c69SJed Brown     }
2591e1244c69SJed Brown   }
25922ffb9264SLisandro Dalcin 
25939566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
25949566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
25952ffb9264SLisandro Dalcin 
25961baa6e33SBarry Smith   if (ts->ops->setup) PetscCall((*ts->ops->setup)(ts));
2597277b19d0SLisandro Dalcin 
25989566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25992ffb9264SLisandro Dalcin 
2600a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
26016c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
26026c6b9e74SPeter Brune    */
26039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
26049566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm,&func,NULL));
2605*1e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm,SNESTSFormFunction,ts));
2606*1e66621cSBarry Smith 
2607a6772fa2SLisandro Dalcin   /* If the SNES doesn't have a jacobian set and the TS has an ijacobian or rhsjacobian set, set the SNES to use it.
26086c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
26096c6b9e74SPeter Brune    */
26109566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm,&jac,NULL));
26119566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijac,NULL));
26129566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,&i2jac,NULL));
26139566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjac,NULL));
2614*1e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm,SNESTSFormJacobian,ts));
2615c0517034SDebojyoti Ghosh 
2616c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
26171baa6e33SBarry Smith   if (ts->ops->startingmethod) PetscCall((*ts->ops->startingmethod)(ts));
2618c0517034SDebojyoti Ghosh 
2619277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
2620277b19d0SLisandro Dalcin   PetscFunctionReturn(0);
2621277b19d0SLisandro Dalcin }
2622277b19d0SLisandro Dalcin 
2623f6a906c0SBarry Smith /*@
2624277b19d0SLisandro Dalcin    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2625277b19d0SLisandro Dalcin 
2626277b19d0SLisandro Dalcin    Collective on TS
2627277b19d0SLisandro Dalcin 
2628277b19d0SLisandro Dalcin    Input Parameter:
2629277b19d0SLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2630277b19d0SLisandro Dalcin 
2631277b19d0SLisandro Dalcin    Level: beginner
2632277b19d0SLisandro Dalcin 
2633db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetup()`, `TSDestroy()`
2634277b19d0SLisandro Dalcin @*/
2635277b19d0SLisandro Dalcin PetscErrorCode  TSReset(TS ts)
2636277b19d0SLisandro Dalcin {
26371d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2638277b19d0SLisandro Dalcin 
2639277b19d0SLisandro Dalcin   PetscFunctionBegin;
2640277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2641b18ea86cSHong Zhang 
26421baa6e33SBarry Smith   if (ts->ops->reset) PetscCall((*ts->ops->reset)(ts));
26439566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
26449566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2645bbd56ea5SKarl Rupp 
26469566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26479566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26489566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26499566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
26509566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26519566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26529566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26539566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork,&ts->work));
2654bbd56ea5SKarl Rupp 
26559566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26569566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26571baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2658cd4cee2dSHong Zhang   if (ts->quadraturets) {
26599566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26609566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2661cd4cee2dSHong Zhang   }
26621d06f6b3SHong Zhang   while (ilink) {
26631d06f6b3SHong Zhang     next = ilink->next;
26649566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26659566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26669566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26679566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26681d06f6b3SHong Zhang     ilink = next;
266987f4e208SHong Zhang   }
26706bf673ebSJoe Pusztay   ts->tsrhssplit = NULL;
2671545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26724a658b32SHong Zhang   if (ts->tspan) {
26734a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26744a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times,&ts->tspan->vecs_sol));
26754a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26764a658b32SHong Zhang   }
2677277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
2678d763cef2SBarry Smith   PetscFunctionReturn(0);
2679d763cef2SBarry Smith }
2680d763cef2SBarry Smith 
26811fb7b255SJunchao Zhang /*@C
2682d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2683d763cef2SBarry Smith    with TSCreate().
2684d763cef2SBarry Smith 
2685d763cef2SBarry Smith    Collective on TS
2686d763cef2SBarry Smith 
2687d763cef2SBarry Smith    Input Parameter:
2688d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2689d763cef2SBarry Smith 
2690d763cef2SBarry Smith    Level: beginner
2691d763cef2SBarry Smith 
2692db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSSolve()`
2693d763cef2SBarry Smith @*/
26946bf464f9SBarry Smith PetscErrorCode  TSDestroy(TS *ts)
2695d763cef2SBarry Smith {
2696d763cef2SBarry Smith   PetscFunctionBegin;
26976bf464f9SBarry Smith   if (!*ts) PetscFunctionReturn(0);
2698ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts,TS_CLASSID,1);
2699c793f718SLisandro Dalcin   if (--((PetscObject)(*ts))->refct > 0) {*ts = NULL; PetscFunctionReturn(0);}
2700d763cef2SBarry Smith 
27019566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
27029566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
2703*1e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
2704*1e66621cSBarry Smith 
2705e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
27069566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
27079566063dSJacob Faibussowitsch   if ((*ts)->ops->destroy) PetscCall((*(*ts)->ops->destroy)((*ts)));
27086d4c513bSLisandro Dalcin 
27099566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2710bc952696SBarry Smith 
27119566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
27129566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
27136427ac75SLisandro Dalcin 
27149566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
27159566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
27169566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
27179566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
27186d4c513bSLisandro Dalcin 
27199566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
27209566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
2721d763cef2SBarry Smith   PetscFunctionReturn(0);
2722d763cef2SBarry Smith }
2723d763cef2SBarry Smith 
2724d8e5e3e6SSatish Balay /*@
2725d763cef2SBarry Smith    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2726d763cef2SBarry Smith    a TS (timestepper) context. Valid only for nonlinear problems.
2727d763cef2SBarry Smith 
2728d763cef2SBarry Smith    Not Collective, but SNES is parallel if TS is parallel
2729d763cef2SBarry Smith 
2730d763cef2SBarry Smith    Input Parameter:
2731d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2732d763cef2SBarry Smith 
2733d763cef2SBarry Smith    Output Parameter:
2734d763cef2SBarry Smith .  snes - the nonlinear solver context
2735d763cef2SBarry Smith 
2736d763cef2SBarry Smith    Notes:
2737d763cef2SBarry Smith    The user can then directly manipulate the SNES context to set various
2738d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
273994b7f48cSBarry Smith    KSP, KSP, and PC contexts as well.
2740d763cef2SBarry Smith 
2741d763cef2SBarry Smith    TSGetSNES() does not work for integrators that do not use SNES; in
27420298fd71SBarry Smith    this case TSGetSNES() returns NULL in snes.
2743d763cef2SBarry Smith 
2744d763cef2SBarry Smith    Level: beginner
2745d763cef2SBarry Smith 
2746d763cef2SBarry Smith @*/
27477087cfbeSBarry Smith PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2748d763cef2SBarry Smith {
2749d763cef2SBarry Smith   PetscFunctionBegin;
27500700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
27514482741eSBarry Smith   PetscValidPointer(snes,2);
2752d372ba47SLisandro Dalcin   if (!ts->snes) {
27539566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes));
27549566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options));
27559566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts));
27569566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes));
27579566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1));
27589566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes,ts->dm));
2759*1e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes,SNESKSPONLY));
2760d372ba47SLisandro Dalcin   }
2761d763cef2SBarry Smith   *snes = ts->snes;
2762d763cef2SBarry Smith   PetscFunctionReturn(0);
2763d763cef2SBarry Smith }
2764d763cef2SBarry Smith 
2765deb2cd25SJed Brown /*@
2766deb2cd25SJed Brown    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2767deb2cd25SJed Brown 
2768deb2cd25SJed Brown    Collective
2769deb2cd25SJed Brown 
2770d8d19677SJose E. Roman    Input Parameters:
2771deb2cd25SJed Brown +  ts - the TS context obtained from TSCreate()
2772deb2cd25SJed Brown -  snes - the nonlinear solver context
2773deb2cd25SJed Brown 
2774deb2cd25SJed Brown    Notes:
2775deb2cd25SJed Brown    Most users should have the TS created by calling TSGetSNES()
2776deb2cd25SJed Brown 
2777deb2cd25SJed Brown    Level: developer
2778deb2cd25SJed Brown 
2779deb2cd25SJed Brown @*/
2780deb2cd25SJed Brown PetscErrorCode TSSetSNES(TS ts,SNES snes)
2781deb2cd25SJed Brown {
2782d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2783deb2cd25SJed Brown 
2784deb2cd25SJed Brown   PetscFunctionBegin;
2785deb2cd25SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2786deb2cd25SJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
27879566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27889566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2789bbd56ea5SKarl Rupp 
2790deb2cd25SJed Brown   ts->snes = snes;
2791bbd56ea5SKarl Rupp 
27929566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts));
27939566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL));
2794*1e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts));
2795deb2cd25SJed Brown   PetscFunctionReturn(0);
2796deb2cd25SJed Brown }
2797deb2cd25SJed Brown 
2798d8e5e3e6SSatish Balay /*@
279994b7f48cSBarry Smith    TSGetKSP - Returns the KSP (linear solver) associated with
2800d763cef2SBarry Smith    a TS (timestepper) context.
2801d763cef2SBarry Smith 
280294b7f48cSBarry Smith    Not Collective, but KSP is parallel if TS is parallel
2803d763cef2SBarry Smith 
2804d763cef2SBarry Smith    Input Parameter:
2805d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2806d763cef2SBarry Smith 
2807d763cef2SBarry Smith    Output Parameter:
280894b7f48cSBarry Smith .  ksp - the nonlinear solver context
2809d763cef2SBarry Smith 
2810d763cef2SBarry Smith    Notes:
281194b7f48cSBarry Smith    The user can then directly manipulate the KSP context to set various
2812d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2813d763cef2SBarry Smith    KSP and PC contexts as well.
2814d763cef2SBarry Smith 
281594b7f48cSBarry Smith    TSGetKSP() does not work for integrators that do not use KSP;
28160298fd71SBarry Smith    in this case TSGetKSP() returns NULL in ksp.
2817d763cef2SBarry Smith 
2818d763cef2SBarry Smith    Level: beginner
2819d763cef2SBarry Smith 
2820d763cef2SBarry Smith @*/
28217087cfbeSBarry Smith PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2822d763cef2SBarry Smith {
2823089b2837SJed Brown   SNES           snes;
2824d372ba47SLisandro Dalcin 
2825d763cef2SBarry Smith   PetscFunctionBegin;
28260700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
28274482741eSBarry Smith   PetscValidPointer(ksp,2);
28283c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name,PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
28293c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
28309566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
28319566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,ksp));
2832d763cef2SBarry Smith   PetscFunctionReturn(0);
2833d763cef2SBarry Smith }
2834d763cef2SBarry Smith 
2835d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2836d763cef2SBarry Smith 
2837adb62b0dSMatthew Knepley /*@
2838618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2839618ce8baSLisandro Dalcin 
2840618ce8baSLisandro Dalcin    Logically Collective on TS
2841618ce8baSLisandro Dalcin 
2842618ce8baSLisandro Dalcin    Input Parameters:
2843618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2844618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2845618ce8baSLisandro Dalcin 
2846618ce8baSLisandro Dalcin    Options Database Keys:
2847618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2848618ce8baSLisandro Dalcin 
2849618ce8baSLisandro Dalcin    Notes:
2850618ce8baSLisandro Dalcin    The default maximum number of steps is 5000
2851618ce8baSLisandro Dalcin 
2852618ce8baSLisandro Dalcin    Level: intermediate
2853618ce8baSLisandro Dalcin 
2854db781477SPatrick Sanan .seealso: `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2855618ce8baSLisandro Dalcin @*/
2856618ce8baSLisandro Dalcin PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2857618ce8baSLisandro Dalcin {
2858618ce8baSLisandro Dalcin   PetscFunctionBegin;
2859618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2860618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
28613c633725SBarry Smith   PetscCheck(maxsteps >= 0,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2862618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
2863618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2864618ce8baSLisandro Dalcin }
2865618ce8baSLisandro Dalcin 
2866618ce8baSLisandro Dalcin /*@
2867618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2868618ce8baSLisandro Dalcin 
2869618ce8baSLisandro Dalcin    Not Collective
2870618ce8baSLisandro Dalcin 
2871618ce8baSLisandro Dalcin    Input Parameters:
2872618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2873618ce8baSLisandro Dalcin 
2874618ce8baSLisandro Dalcin    Output Parameter:
2875618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2876618ce8baSLisandro Dalcin 
2877618ce8baSLisandro Dalcin    Level: advanced
2878618ce8baSLisandro Dalcin 
2879db781477SPatrick Sanan .seealso: `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2880618ce8baSLisandro Dalcin @*/
2881618ce8baSLisandro Dalcin PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2882618ce8baSLisandro Dalcin {
2883618ce8baSLisandro Dalcin   PetscFunctionBegin;
2884618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2885618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps,2);
2886618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
2887618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2888618ce8baSLisandro Dalcin }
2889618ce8baSLisandro Dalcin 
2890618ce8baSLisandro Dalcin /*@
2891618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2892618ce8baSLisandro Dalcin 
2893618ce8baSLisandro Dalcin    Logically Collective on TS
2894618ce8baSLisandro Dalcin 
2895618ce8baSLisandro Dalcin    Input Parameters:
2896618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2897618ce8baSLisandro Dalcin -  maxtime - final time to step to
2898618ce8baSLisandro Dalcin 
2899618ce8baSLisandro Dalcin    Options Database Keys:
2900ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2901618ce8baSLisandro Dalcin 
2902618ce8baSLisandro Dalcin    Notes:
2903618ce8baSLisandro Dalcin    The default maximum time is 5.0
2904618ce8baSLisandro Dalcin 
2905618ce8baSLisandro Dalcin    Level: intermediate
2906618ce8baSLisandro Dalcin 
2907db781477SPatrick Sanan .seealso: `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2908618ce8baSLisandro Dalcin @*/
2909618ce8baSLisandro Dalcin PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
2910618ce8baSLisandro Dalcin {
2911618ce8baSLisandro Dalcin   PetscFunctionBegin;
2912618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2913618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts,maxtime,2);
2914618ce8baSLisandro Dalcin   ts->max_time = maxtime;
2915618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2916618ce8baSLisandro Dalcin }
2917618ce8baSLisandro Dalcin 
2918618ce8baSLisandro Dalcin /*@
2919618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2920618ce8baSLisandro Dalcin 
2921618ce8baSLisandro Dalcin    Not Collective
2922618ce8baSLisandro Dalcin 
2923618ce8baSLisandro Dalcin    Input Parameters:
2924618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2925618ce8baSLisandro Dalcin 
2926618ce8baSLisandro Dalcin    Output Parameter:
2927618ce8baSLisandro Dalcin .  maxtime - final time to step to
2928618ce8baSLisandro Dalcin 
2929618ce8baSLisandro Dalcin    Level: advanced
2930618ce8baSLisandro Dalcin 
2931db781477SPatrick Sanan .seealso: `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2932618ce8baSLisandro Dalcin @*/
2933618ce8baSLisandro Dalcin PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
2934618ce8baSLisandro Dalcin {
2935618ce8baSLisandro Dalcin   PetscFunctionBegin;
2936618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2937618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime,2);
2938618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
2939618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2940618ce8baSLisandro Dalcin }
2941618ce8baSLisandro Dalcin 
2942618ce8baSLisandro Dalcin /*@
2943aaa6c58dSLisandro Dalcin    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().
2944edc382c3SSatish Balay 
2945edc382c3SSatish Balay    Level: deprecated
2946edc382c3SSatish Balay 
2947aaa6c58dSLisandro Dalcin @*/
2948aaa6c58dSLisandro Dalcin PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
2949aaa6c58dSLisandro Dalcin {
2950aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2951aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
29529566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts,initial_time));
29539566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts,time_step));
2954aaa6c58dSLisandro Dalcin   PetscFunctionReturn(0);
2955aaa6c58dSLisandro Dalcin }
2956aaa6c58dSLisandro Dalcin 
2957aaa6c58dSLisandro Dalcin /*@
295819eac22cSLisandro Dalcin    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().
2959edc382c3SSatish Balay 
2960edc382c3SSatish Balay    Level: deprecated
2961edc382c3SSatish Balay 
2962adb62b0dSMatthew Knepley @*/
29637087cfbeSBarry Smith PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2964adb62b0dSMatthew Knepley {
2965adb62b0dSMatthew Knepley   PetscFunctionBegin;
29660700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2967abc0a331SBarry Smith   if (maxsteps) {
29684482741eSBarry Smith     PetscValidIntPointer(maxsteps,2);
2969adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2970adb62b0dSMatthew Knepley   }
2971abc0a331SBarry Smith   if (maxtime) {
2972064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime,3);
2973adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2974adb62b0dSMatthew Knepley   }
2975adb62b0dSMatthew Knepley   PetscFunctionReturn(0);
2976adb62b0dSMatthew Knepley }
2977adb62b0dSMatthew Knepley 
2978d763cef2SBarry Smith /*@
297919eac22cSLisandro Dalcin    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().
2980edc382c3SSatish Balay 
2981edc382c3SSatish Balay    Level: deprecated
2982edc382c3SSatish Balay 
2983d763cef2SBarry Smith @*/
29847087cfbeSBarry Smith PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
2985d763cef2SBarry Smith {
2986d763cef2SBarry Smith   PetscFunctionBegin;
29870700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2988c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
2989064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts,maxtime,3);
299039b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
299139b7ec4bSSean Farley   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2992d763cef2SBarry Smith   PetscFunctionReturn(0);
2993d763cef2SBarry Smith }
2994d763cef2SBarry Smith 
2995d763cef2SBarry Smith /*@
29965c5f5948SLisandro Dalcin    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().
2997edc382c3SSatish Balay 
2998edc382c3SSatish Balay    Level: deprecated
2999edc382c3SSatish Balay 
30005c5f5948SLisandro Dalcin @*/
3001e193eaafSLisandro Dalcin PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
30025c5f5948SLisandro Dalcin 
300319eac22cSLisandro Dalcin /*@
30044f4e0956SLisandro Dalcin    TSGetTotalSteps - Deprecated, use TSGetStepNumber().
3005edc382c3SSatish Balay 
3006edc382c3SSatish Balay    Level: deprecated
3007edc382c3SSatish Balay 
30084f4e0956SLisandro Dalcin @*/
30094f4e0956SLisandro Dalcin PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
30104f4e0956SLisandro Dalcin 
30114f4e0956SLisandro Dalcin /*@
3012d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3013d763cef2SBarry Smith    for use by the TS routines.
3014d763cef2SBarry Smith 
3015d083f849SBarry Smith    Logically Collective on TS
3016d763cef2SBarry Smith 
3017d763cef2SBarry Smith    Input Parameters:
3018d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
30190910c330SBarry Smith -  u - the solution vector
3020d763cef2SBarry Smith 
3021d763cef2SBarry Smith    Level: beginner
3022d763cef2SBarry Smith 
3023db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3024d763cef2SBarry Smith @*/
30250910c330SBarry Smith PetscErrorCode  TSSetSolution(TS ts,Vec u)
3026d763cef2SBarry Smith {
3027496e6a7aSJed Brown   DM             dm;
30288737fe31SLisandro Dalcin 
3029d763cef2SBarry Smith   PetscFunctionBegin;
30300700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
30310910c330SBarry Smith   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
30329566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30339566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30340910c330SBarry Smith   ts->vec_sol = u;
3035bbd56ea5SKarl Rupp 
30369566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
30379566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm,u));
3038d763cef2SBarry Smith   PetscFunctionReturn(0);
3039d763cef2SBarry Smith }
3040d763cef2SBarry Smith 
3041ac226902SBarry Smith /*@C
3042000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30433f2090d5SJed Brown   called once at the beginning of each time step.
3044000e7ae3SMatthew Knepley 
30453f9fe445SBarry Smith   Logically Collective on TS
3046000e7ae3SMatthew Knepley 
3047000e7ae3SMatthew Knepley   Input Parameters:
3048000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3049000e7ae3SMatthew Knepley - func - The function
3050000e7ae3SMatthew Knepley 
3051000e7ae3SMatthew Knepley   Calling sequence of func:
305267b8a455SSatish Balay .vb
305367b8a455SSatish Balay   PetscErrorCode func (TS ts);
305467b8a455SSatish Balay .ve
3055000e7ae3SMatthew Knepley 
3056000e7ae3SMatthew Knepley   Level: intermediate
3057000e7ae3SMatthew Knepley 
3058db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3059000e7ae3SMatthew Knepley @*/
30607087cfbeSBarry Smith PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3061000e7ae3SMatthew Knepley {
3062000e7ae3SMatthew Knepley   PetscFunctionBegin;
30630700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3064ae60f76fSBarry Smith   ts->prestep = func;
3065000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3066000e7ae3SMatthew Knepley }
3067000e7ae3SMatthew Knepley 
306809ee8438SJed Brown /*@
30693f2090d5SJed Brown   TSPreStep - Runs the user-defined pre-step function.
30703f2090d5SJed Brown 
30713f2090d5SJed Brown   Collective on TS
30723f2090d5SJed Brown 
30733f2090d5SJed Brown   Input Parameters:
30743f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
30753f2090d5SJed Brown 
30763f2090d5SJed Brown   Notes:
30773f2090d5SJed Brown   TSPreStep() is typically used within time stepping implementations,
30783f2090d5SJed Brown   so most users would not generally call this routine themselves.
30793f2090d5SJed Brown 
30803f2090d5SJed Brown   Level: developer
30813f2090d5SJed Brown 
3082db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30833f2090d5SJed Brown @*/
30847087cfbeSBarry Smith PetscErrorCode  TSPreStep(TS ts)
30853f2090d5SJed Brown {
30863f2090d5SJed Brown   PetscFunctionBegin;
30870700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3088ae60f76fSBarry Smith   if (ts->prestep) {
30895efd42a4SStefano Zampini     Vec              U;
3090ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3091ef8d1ce0SJohann Rudi     PetscBool        sameObject;
30925efd42a4SStefano Zampini     PetscObjectState sprev,spost;
30935efd42a4SStefano Zampini 
30949566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
30959566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U,&idprev));
30969566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
309725e27a38SBarry Smith     PetscCallBack("TS callback preset",(*ts->prestep)(ts));
30989566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
30999566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U,idprev,&sameObject));
31009566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
31019566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3102312ce896SJed Brown   }
31033f2090d5SJed Brown   PetscFunctionReturn(0);
31043f2090d5SJed Brown }
31053f2090d5SJed Brown 
3106b8123daeSJed Brown /*@C
3107b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3108b8123daeSJed Brown   called once at the beginning of each stage.
3109b8123daeSJed Brown 
3110b8123daeSJed Brown   Logically Collective on TS
3111b8123daeSJed Brown 
3112b8123daeSJed Brown   Input Parameters:
3113b8123daeSJed Brown + ts   - The TS context obtained from TSCreate()
3114b8123daeSJed Brown - func - The function
3115b8123daeSJed Brown 
3116b8123daeSJed Brown   Calling sequence of func:
311767b8a455SSatish Balay .vb
311867b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime);
311967b8a455SSatish Balay .ve
3120b8123daeSJed Brown 
3121b8123daeSJed Brown   Level: intermediate
3122b8123daeSJed Brown 
3123b8123daeSJed Brown   Note:
3124b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
312580275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
3126b8123daeSJed Brown   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3127b8123daeSJed Brown 
3128db781477SPatrick Sanan .seealso: `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3129b8123daeSJed Brown @*/
3130b8123daeSJed Brown PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3131b8123daeSJed Brown {
3132b8123daeSJed Brown   PetscFunctionBegin;
3133b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3134ae60f76fSBarry Smith   ts->prestage = func;
3135b8123daeSJed Brown   PetscFunctionReturn(0);
3136b8123daeSJed Brown }
3137b8123daeSJed Brown 
31389be3e283SDebojyoti Ghosh /*@C
31399be3e283SDebojyoti Ghosh   TSSetPostStage - Sets the general-purpose function
31409be3e283SDebojyoti Ghosh   called once at the end of each stage.
31419be3e283SDebojyoti Ghosh 
31429be3e283SDebojyoti Ghosh   Logically Collective on TS
31439be3e283SDebojyoti Ghosh 
31449be3e283SDebojyoti Ghosh   Input Parameters:
31459be3e283SDebojyoti Ghosh + ts   - The TS context obtained from TSCreate()
31469be3e283SDebojyoti Ghosh - func - The function
31479be3e283SDebojyoti Ghosh 
31489be3e283SDebojyoti Ghosh   Calling sequence of func:
314967b8a455SSatish Balay .vb
315067b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
315167b8a455SSatish Balay .ve
31529be3e283SDebojyoti Ghosh 
31539be3e283SDebojyoti Ghosh   Level: intermediate
31549be3e283SDebojyoti Ghosh 
31559be3e283SDebojyoti Ghosh   Note:
31569be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
315780275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
31589be3e283SDebojyoti Ghosh   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
31599be3e283SDebojyoti Ghosh 
3160db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31619be3e283SDebojyoti Ghosh @*/
31629be3e283SDebojyoti Ghosh PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
31639be3e283SDebojyoti Ghosh {
31649be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31659be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
31669be3e283SDebojyoti Ghosh   ts->poststage = func;
31679be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
31689be3e283SDebojyoti Ghosh }
31699be3e283SDebojyoti Ghosh 
3170c688d042SShri Abhyankar /*@C
3171c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3172c688d042SShri Abhyankar   called once at the end of each step evaluation.
3173c688d042SShri Abhyankar 
3174c688d042SShri Abhyankar   Logically Collective on TS
3175c688d042SShri Abhyankar 
3176c688d042SShri Abhyankar   Input Parameters:
3177c688d042SShri Abhyankar + ts   - The TS context obtained from TSCreate()
3178c688d042SShri Abhyankar - func - The function
3179c688d042SShri Abhyankar 
3180c688d042SShri Abhyankar   Calling sequence of func:
318167b8a455SSatish Balay .vb
318267b8a455SSatish Balay   PetscErrorCode func(TS ts);
318367b8a455SSatish Balay .ve
3184c688d042SShri Abhyankar 
3185c688d042SShri Abhyankar   Level: intermediate
3186c688d042SShri Abhyankar 
3187c688d042SShri Abhyankar   Note:
31881785ff2aSShri Abhyankar   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
31891785ff2aSShri Abhyankar   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3190e7e94ed4SShri Abhyankar   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3191e7e94ed4SShri Abhyankar   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3192e7e94ed4SShri Abhyankar   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()
3193c688d042SShri Abhyankar 
3194db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3195c688d042SShri Abhyankar @*/
3196c688d042SShri Abhyankar PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3197c688d042SShri Abhyankar {
3198c688d042SShri Abhyankar   PetscFunctionBegin;
3199c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3200c688d042SShri Abhyankar   ts->postevaluate = func;
3201c688d042SShri Abhyankar   PetscFunctionReturn(0);
3202c688d042SShri Abhyankar }
3203c688d042SShri Abhyankar 
3204b8123daeSJed Brown /*@
3205b8123daeSJed Brown   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3206b8123daeSJed Brown 
3207b8123daeSJed Brown   Collective on TS
3208b8123daeSJed Brown 
3209b8123daeSJed Brown   Input Parameters:
3210b8123daeSJed Brown . ts          - The TS context obtained from TSCreate()
32119be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3212b8123daeSJed Brown 
3213b8123daeSJed Brown   Notes:
3214b8123daeSJed Brown   TSPreStage() is typically used within time stepping implementations,
3215b8123daeSJed Brown   most users would not generally call this routine themselves.
3216b8123daeSJed Brown 
3217b8123daeSJed Brown   Level: developer
3218b8123daeSJed Brown 
3219db781477SPatrick Sanan .seealso: `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3220b8123daeSJed Brown @*/
3221b8123daeSJed Brown PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3222b8123daeSJed Brown {
3223b8123daeSJed Brown   PetscFunctionBegin;
3224b8123daeSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3225*1e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage",(*ts->prestage)(ts,stagetime));
3226b8123daeSJed Brown   PetscFunctionReturn(0);
3227b8123daeSJed Brown }
3228b8123daeSJed Brown 
32299be3e283SDebojyoti Ghosh /*@
32309be3e283SDebojyoti Ghosh   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
32319be3e283SDebojyoti Ghosh 
32329be3e283SDebojyoti Ghosh   Collective on TS
32339be3e283SDebojyoti Ghosh 
32349be3e283SDebojyoti Ghosh   Input Parameters:
32359be3e283SDebojyoti Ghosh . ts          - The TS context obtained from TSCreate()
32369be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
32379be3e283SDebojyoti Ghosh   stageindex  - Stage number
32389be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
32399be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
32409be3e283SDebojyoti Ghosh 
32419be3e283SDebojyoti Ghosh   Notes:
32429be3e283SDebojyoti Ghosh   TSPostStage() is typically used within time stepping implementations,
32439be3e283SDebojyoti Ghosh   most users would not generally call this routine themselves.
32449be3e283SDebojyoti Ghosh 
32459be3e283SDebojyoti Ghosh   Level: developer
32469be3e283SDebojyoti Ghosh 
3247db781477SPatrick Sanan .seealso: `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32489be3e283SDebojyoti Ghosh @*/
32499be3e283SDebojyoti Ghosh PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
32509be3e283SDebojyoti Ghosh {
32519be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32529be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3253*1e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage",(*ts->poststage)(ts,stagetime,stageindex,Y));
32549be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
32559be3e283SDebojyoti Ghosh }
32569be3e283SDebojyoti Ghosh 
3257c688d042SShri Abhyankar /*@
3258c688d042SShri Abhyankar   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()
3259c688d042SShri Abhyankar 
3260c688d042SShri Abhyankar   Collective on TS
3261c688d042SShri Abhyankar 
3262c688d042SShri Abhyankar   Input Parameters:
3263c688d042SShri Abhyankar . ts          - The TS context obtained from TSCreate()
3264c688d042SShri Abhyankar 
3265c688d042SShri Abhyankar   Notes:
3266c688d042SShri Abhyankar   TSPostEvaluate() is typically used within time stepping implementations,
3267c688d042SShri Abhyankar   most users would not generally call this routine themselves.
3268c688d042SShri Abhyankar 
3269c688d042SShri Abhyankar   Level: developer
3270c688d042SShri Abhyankar 
3271db781477SPatrick Sanan .seealso: `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3272c688d042SShri Abhyankar @*/
3273c688d042SShri Abhyankar PetscErrorCode  TSPostEvaluate(TS ts)
3274c688d042SShri Abhyankar {
3275c688d042SShri Abhyankar   PetscFunctionBegin;
3276c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3277c688d042SShri Abhyankar   if (ts->postevaluate) {
3278dcb233daSLisandro Dalcin     Vec              U;
3279dcb233daSLisandro Dalcin     PetscObjectState sprev,spost;
3280dcb233daSLisandro Dalcin 
32819566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
32829566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
328325e27a38SBarry Smith     PetscCallBack("TS callback postevaluate",(*ts->postevaluate)(ts));
32849566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
32859566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3286c688d042SShri Abhyankar   }
3287c688d042SShri Abhyankar   PetscFunctionReturn(0);
3288c688d042SShri Abhyankar }
3289c688d042SShri Abhyankar 
3290ac226902SBarry Smith /*@C
3291000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
32923f2090d5SJed Brown   called once at the end of each time step.
3293000e7ae3SMatthew Knepley 
32943f9fe445SBarry Smith   Logically Collective on TS
3295000e7ae3SMatthew Knepley 
3296000e7ae3SMatthew Knepley   Input Parameters:
3297000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3298000e7ae3SMatthew Knepley - func - The function
3299000e7ae3SMatthew Knepley 
3300000e7ae3SMatthew Knepley   Calling sequence of func:
3301b8123daeSJed Brown $ func (TS ts);
3302000e7ae3SMatthew Knepley 
33031785ff2aSShri Abhyankar   Notes:
33041785ff2aSShri Abhyankar   The function set by TSSetPostStep() is called after each successful step. The solution vector X
33051785ff2aSShri Abhyankar   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
33061785ff2aSShri Abhyankar   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.
33071785ff2aSShri Abhyankar 
3308000e7ae3SMatthew Knepley   Level: intermediate
3309000e7ae3SMatthew Knepley 
3310db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3311000e7ae3SMatthew Knepley @*/
33127087cfbeSBarry Smith PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3313000e7ae3SMatthew Knepley {
3314000e7ae3SMatthew Knepley   PetscFunctionBegin;
33150700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3316ae60f76fSBarry Smith   ts->poststep = func;
3317000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3318000e7ae3SMatthew Knepley }
3319000e7ae3SMatthew Knepley 
332009ee8438SJed Brown /*@
33213f2090d5SJed Brown   TSPostStep - Runs the user-defined post-step function.
33223f2090d5SJed Brown 
33233f2090d5SJed Brown   Collective on TS
33243f2090d5SJed Brown 
33253f2090d5SJed Brown   Input Parameters:
33263f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
33273f2090d5SJed Brown 
33283f2090d5SJed Brown   Notes:
33293f2090d5SJed Brown   TSPostStep() is typically used within time stepping implementations,
33303f2090d5SJed Brown   so most users would not generally call this routine themselves.
33313f2090d5SJed Brown 
33323f2090d5SJed Brown   Level: developer
33333f2090d5SJed Brown 
33343f2090d5SJed Brown @*/
33357087cfbeSBarry Smith PetscErrorCode  TSPostStep(TS ts)
33363f2090d5SJed Brown {
33373f2090d5SJed Brown   PetscFunctionBegin;
33380700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3339ae60f76fSBarry Smith   if (ts->poststep) {
33405efd42a4SStefano Zampini     Vec              U;
3341ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3342ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33435efd42a4SStefano Zampini     PetscObjectState sprev,spost;
33445efd42a4SStefano Zampini 
33459566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
33469566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U,&idprev));
33479566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
334825e27a38SBarry Smith     PetscCallBack("TS callback poststep",(*ts->poststep)(ts));
33499566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
33509566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U,idprev,&sameObject));
33519566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
33529566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
335372ac3e02SJed Brown   }
33543f2090d5SJed Brown   PetscFunctionReturn(0);
33553f2090d5SJed Brown }
33563f2090d5SJed Brown 
3357cd652676SJed Brown /*@
3358cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3359cd652676SJed Brown 
3360cd652676SJed Brown    Collective on TS
3361cd652676SJed Brown 
33624165533cSJose E. Roman    Input Parameters:
3363cd652676SJed Brown +  ts - time stepping context
3364cd652676SJed Brown -  t - time to interpolate to
3365cd652676SJed Brown 
33664165533cSJose E. Roman    Output Parameter:
33670910c330SBarry Smith .  U - state at given time
3368cd652676SJed Brown 
3369cd652676SJed Brown    Level: intermediate
3370cd652676SJed Brown 
3371cd652676SJed Brown    Developer Notes:
3372cd652676SJed Brown    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3373cd652676SJed Brown 
3374db781477SPatrick Sanan .seealso: `TSSetExactFinalTime()`, `TSSolve()`
3375cd652676SJed Brown @*/
33760910c330SBarry Smith PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3377cd652676SJed Brown {
3378cd652676SJed Brown   PetscFunctionBegin;
3379cd652676SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3380b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
338163a3b9bcSJacob Faibussowitsch   PetscCheck(t >= ts->ptime_prev && t <= ts->ptime,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Requested time %g not in last time steps [%g,%g]",(double)t,(double)ts->ptime_prev,(double)ts->ptime);
33823c633725SBarry Smith   PetscCheck(ts->ops->interpolate,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
33839566063dSJacob Faibussowitsch   PetscCall((*ts->ops->interpolate)(ts,t,U));
3384cd652676SJed Brown   PetscFunctionReturn(0);
3385cd652676SJed Brown }
3386cd652676SJed Brown 
3387d763cef2SBarry Smith /*@
33886d9e5789SSean Farley    TSStep - Steps one time step
3389d763cef2SBarry Smith 
3390d763cef2SBarry Smith    Collective on TS
3391d763cef2SBarry Smith 
3392d763cef2SBarry Smith    Input Parameter:
3393d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3394d763cef2SBarry Smith 
339527829d71SBarry Smith    Level: developer
3396d763cef2SBarry Smith 
3397b8123daeSJed Brown    Notes:
339827829d71SBarry Smith    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
339927829d71SBarry Smith 
3400b8123daeSJed Brown    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3401b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3402b8123daeSJed Brown 
340319eac22cSLisandro Dalcin    This may over-step the final time provided in TSSetMaxTime() depending on the time-step used. TSSolve() interpolates to exactly the
340419eac22cSLisandro Dalcin    time provided in TSSetMaxTime(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
340525cb2221SBarry Smith 
3406db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3407d763cef2SBarry Smith @*/
3408193ac0bcSJed Brown PetscErrorCode  TSStep(TS ts)
3409d763cef2SBarry Smith {
3410fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3411be5899b3SLisandro Dalcin   PetscReal        ptime;
3412d763cef2SBarry Smith 
3413d763cef2SBarry Smith   PetscFunctionBegin;
34140700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3415d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3416fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3417f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3418f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3419f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3420f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
3421d0609cedSBarry Smith                                    "  year          = {2018}\n}\n",&cite));
34229566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34239566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory,ts));
3424d405a339SMatthew Knepley 
34253c633725SBarry Smith   PetscCheck(ts->ops->step,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
34263c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
34273c633725SBarry Smith   PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_UNSPECIFIED,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSStep()");
34283c633725SBarry Smith   PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP || ts->adapt,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
3429a6772fa2SLisandro Dalcin 
3430be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
3431be5899b3SLisandro Dalcin   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
34322808aa04SLisandro Dalcin   ts->reason = TS_CONVERGED_ITERATING;
3433fc8dbba5SLisandro Dalcin 
34349566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step,ts,0,0,0));
34359566063dSJacob Faibussowitsch   PetscCall((*ts->ops->step)(ts));
34369566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step,ts,0,0,0));
3437fc8dbba5SLisandro Dalcin 
3438fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3439be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34402808aa04SLisandro Dalcin     ts->steps++;
3441be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
344228d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3443e1db57b0SHong Zhang     if (ts->tspan && PetscIsCloseAtTol(ts->ptime,ts->tspan->span_times[ts->tspan->spanctr],ts->tspan->reltol*ts->time_step+ts->tspan->abstol,0) && ts->tspan->spanctr < ts->tspan->num_span_times) PetscCall(VecCopy(ts->vec_sol,ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3444d2daff3dSHong Zhang   }
3445fc8dbba5SLisandro Dalcin 
3446fc8dbba5SLisandro Dalcin   if (!ts->reason) {
344708c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
344808c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
344908c7845fSBarry Smith   }
3450fc8dbba5SLisandro Dalcin 
34513c633725SBarry Smith   PetscCheck(ts->reason >= 0 || !ts->errorifstepfailed || ts->reason != TS_DIVERGED_NONLINEAR_SOLVE,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]);
34523c633725SBarry Smith   PetscCheck(ts->reason >= 0 || !ts->errorifstepfailed,PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
345308c7845fSBarry Smith   PetscFunctionReturn(0);
345408c7845fSBarry Smith }
345508c7845fSBarry Smith 
345608c7845fSBarry Smith /*@
34577cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34587cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
34597cbde773SLisandro Dalcin 
34607cbde773SLisandro Dalcin    Collective on TS
34617cbde773SLisandro Dalcin 
34624165533cSJose E. Roman    Input Parameters:
34637cbde773SLisandro Dalcin +  ts - time stepping context
346497bb3fdcSJose E. Roman -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
34657cbde773SLisandro Dalcin 
346697bb3fdcSJose E. Roman    Input/Output Parameter:
346797bb3fdcSJose E. Roman .  order - optional, desired order for the error evaluation or PETSC_DECIDE;
346897bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
346997bb3fdcSJose E. Roman 
347097bb3fdcSJose E. Roman    Output Parameter:
347197bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
34727cbde773SLisandro Dalcin 
34737cbde773SLisandro Dalcin    Level: advanced
34747cbde773SLisandro Dalcin 
34757cbde773SLisandro Dalcin    Notes:
34767cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
34777cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
34787cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
34797cbde773SLisandro Dalcin 
3480db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34817cbde773SLisandro Dalcin @*/
34827cbde773SLisandro Dalcin PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
34837cbde773SLisandro Dalcin {
34847cbde773SLisandro Dalcin   PetscFunctionBegin;
34857cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
34867cbde773SLisandro Dalcin   PetscValidType(ts,1);
3487064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts,wnormtype,2);
34887cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order,3);
34897cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts,*order,3);
34907cbde773SLisandro Dalcin   PetscValidRealPointer(wlte,4);
34913c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
34923c633725SBarry Smith   PetscCheck(ts->ops->evaluatewlte,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
34939566063dSJacob Faibussowitsch   PetscCall((*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte));
34947cbde773SLisandro Dalcin   PetscFunctionReturn(0);
34957cbde773SLisandro Dalcin }
34967cbde773SLisandro Dalcin 
349705175c85SJed Brown /*@
349805175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
349905175c85SJed Brown 
35001c3436cfSJed Brown    Collective on TS
350105175c85SJed Brown 
35024165533cSJose E. Roman    Input Parameters:
35031c3436cfSJed Brown +  ts - time stepping context
35041c3436cfSJed Brown .  order - desired order of accuracy
35050298fd71SBarry Smith -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
350605175c85SJed Brown 
35074165533cSJose E. Roman    Output Parameter:
35080910c330SBarry Smith .  U - state at the end of the current step
350905175c85SJed Brown 
351005175c85SJed Brown    Level: advanced
351105175c85SJed Brown 
3512108c343cSJed Brown    Notes:
3513108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3514108c343cSJed Brown    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.
3515108c343cSJed Brown 
3516db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`
351705175c85SJed Brown @*/
35180910c330SBarry Smith PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
351905175c85SJed Brown {
352005175c85SJed Brown   PetscFunctionBegin;
352105175c85SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
352205175c85SJed Brown   PetscValidType(ts,1);
35230910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
35243c633725SBarry Smith   PetscCheck(ts->ops->evaluatestep,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
35259566063dSJacob Faibussowitsch   PetscCall((*ts->ops->evaluatestep)(ts,order,U,done));
352605175c85SJed Brown   PetscFunctionReturn(0);
352705175c85SJed Brown }
352805175c85SJed Brown 
3529aad739acSMatthew G. Knepley /*@C
35302e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3531aad739acSMatthew G. Knepley 
3532aad739acSMatthew G. Knepley   Not collective
3533aad739acSMatthew G. Knepley 
35344165533cSJose E. Roman   Input Parameter:
3535aad739acSMatthew G. Knepley . ts        - time stepping context
3536aad739acSMatthew G. Knepley 
35374165533cSJose E. Roman   Output Parameter:
35382e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3539aad739acSMatthew G. Knepley 
3540aad739acSMatthew G. Knepley    Level: advanced
3541aad739acSMatthew G. Knepley 
3542aad739acSMatthew G. Knepley    Notes:
3543aad739acSMatthew G. Knepley    The calling sequence for the function is
35442e61be88SMatthew G. Knepley $ initCondition(TS ts, Vec u)
3545aad739acSMatthew G. Knepley $ ts - The timestepping context
35462e61be88SMatthew G. Knepley $ u  - The input vector in which the initial condition is stored
3547aad739acSMatthew G. Knepley 
3548db781477SPatrick Sanan .seealso: `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3549aad739acSMatthew G. Knepley @*/
35502e61be88SMatthew G. Knepley PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3551aad739acSMatthew G. Knepley {
3552aad739acSMatthew G. Knepley   PetscFunctionBegin;
3553aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35542e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
35552e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
3556aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3557aad739acSMatthew G. Knepley }
3558aad739acSMatthew G. Knepley 
3559aad739acSMatthew G. Knepley /*@C
35602e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3561aad739acSMatthew G. Knepley 
3562aad739acSMatthew G. Knepley   Logically collective on ts
3563aad739acSMatthew G. Knepley 
35644165533cSJose E. Roman   Input Parameters:
3565aad739acSMatthew G. Knepley + ts        - time stepping context
35662e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3567aad739acSMatthew G. Knepley 
3568aad739acSMatthew G. Knepley   Level: advanced
3569aad739acSMatthew G. Knepley 
3570a96d6ef6SBarry Smith   Calling sequence for initCondition:
3571a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3572a96d6ef6SBarry Smith 
3573a96d6ef6SBarry Smith + ts - The timestepping context
3574a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3575aad739acSMatthew G. Knepley 
3576db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3577aad739acSMatthew G. Knepley @*/
35782e61be88SMatthew G. Knepley PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3579aad739acSMatthew G. Knepley {
3580aad739acSMatthew G. Knepley   PetscFunctionBegin;
3581aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35822e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35832e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
3584aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3585aad739acSMatthew G. Knepley }
3586aad739acSMatthew G. Knepley 
3587aad739acSMatthew G. Knepley /*@
35882e61be88SMatthew G. Knepley   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.
3589aad739acSMatthew G. Knepley 
3590aad739acSMatthew G. Knepley   Collective on ts
3591aad739acSMatthew G. Knepley 
35924165533cSJose E. Roman   Input Parameters:
3593aad739acSMatthew G. Knepley + ts - time stepping context
35942e61be88SMatthew G. Knepley - u  - The Vec to store the condition in which will be used in TSSolve()
3595aad739acSMatthew G. Knepley 
3596aad739acSMatthew G. Knepley   Level: advanced
3597aad739acSMatthew G. Knepley 
3598db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3599aad739acSMatthew G. Knepley @*/
36002e61be88SMatthew G. Knepley PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3601aad739acSMatthew G. Knepley {
3602aad739acSMatthew G. Knepley   PetscFunctionBegin;
3603aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3604aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
36059566063dSJacob Faibussowitsch   if (ts->ops->initcondition) PetscCall((*ts->ops->initcondition)(ts, u));
3606aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3607aad739acSMatthew G. Knepley }
3608aad739acSMatthew G. Knepley 
3609aad739acSMatthew G. Knepley /*@C
3610aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3611aad739acSMatthew G. Knepley 
3612aad739acSMatthew G. Knepley   Not collective
3613aad739acSMatthew G. Knepley 
36144165533cSJose E. Roman   Input Parameter:
3615aad739acSMatthew G. Knepley . ts         - time stepping context
3616aad739acSMatthew G. Knepley 
36174165533cSJose E. Roman   Output Parameter:
3618aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3619aad739acSMatthew G. Knepley 
3620aad739acSMatthew G. Knepley   Level: advanced
3621aad739acSMatthew G. Knepley 
3622a96d6ef6SBarry Smith   Calling sequence for exactError:
3623a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3624a96d6ef6SBarry Smith 
3625a96d6ef6SBarry Smith + ts - The timestepping context
3626a96d6ef6SBarry Smith . u  - The approximate solution vector
3627a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3628aad739acSMatthew G. Knepley 
3629db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3630aad739acSMatthew G. Knepley @*/
3631aad739acSMatthew G. Knepley PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3632aad739acSMatthew G. Knepley {
3633aad739acSMatthew G. Knepley   PetscFunctionBegin;
3634aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3635aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3636aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
3637aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3638aad739acSMatthew G. Knepley }
3639aad739acSMatthew G. Knepley 
3640aad739acSMatthew G. Knepley /*@C
3641aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3642aad739acSMatthew G. Knepley 
3643aad739acSMatthew G. Knepley   Logically collective on ts
3644aad739acSMatthew G. Knepley 
36454165533cSJose E. Roman   Input Parameters:
3646aad739acSMatthew G. Knepley + ts         - time stepping context
3647aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3648aad739acSMatthew G. Knepley 
3649aad739acSMatthew G. Knepley   Level: advanced
3650aad739acSMatthew G. Knepley 
3651a96d6ef6SBarry Smith   Calling sequence for exactError:
3652a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3653a96d6ef6SBarry Smith 
3654a96d6ef6SBarry Smith + ts - The timestepping context
3655a96d6ef6SBarry Smith . u  - The approximate solution vector
3656a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3657aad739acSMatthew G. Knepley 
3658db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3659aad739acSMatthew G. Knepley @*/
3660aad739acSMatthew G. Knepley PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3661aad739acSMatthew G. Knepley {
3662aad739acSMatthew G. Knepley   PetscFunctionBegin;
3663aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3664f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3665aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
3666aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3667aad739acSMatthew G. Knepley }
3668aad739acSMatthew G. Knepley 
3669aad739acSMatthew G. Knepley /*@
3670aad739acSMatthew G. Knepley   TSComputeExactError - Compute the solution error for the timestepping using the function previously set.
3671aad739acSMatthew G. Knepley 
3672aad739acSMatthew G. Knepley   Collective on ts
3673aad739acSMatthew G. Knepley 
36744165533cSJose E. Roman   Input Parameters:
3675aad739acSMatthew G. Knepley + ts - time stepping context
3676aad739acSMatthew G. Knepley . u  - The approximate solution
3677aad739acSMatthew G. Knepley - e  - The Vec used to store the error
3678aad739acSMatthew G. Knepley 
3679aad739acSMatthew G. Knepley   Level: advanced
3680aad739acSMatthew G. Knepley 
3681db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3682aad739acSMatthew G. Knepley @*/
3683aad739acSMatthew G. Knepley PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3684aad739acSMatthew G. Knepley {
3685aad739acSMatthew G. Knepley   PetscFunctionBegin;
3686aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3687aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3688aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
36899566063dSJacob Faibussowitsch   if (ts->ops->exacterror) PetscCall((*ts->ops->exacterror)(ts, u, e));
3690aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3691aad739acSMatthew G. Knepley }
3692aad739acSMatthew G. Knepley 
3693b1cb36f3SHong Zhang /*@
36946a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
36956a4d4014SLisandro Dalcin 
36966a4d4014SLisandro Dalcin    Collective on TS
36976a4d4014SLisandro Dalcin 
3698d8d19677SJose E. Roman    Input Parameters:
36996a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
370063e21af5SBarry Smith -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
370163e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
37025a3a76d0SJed Brown 
37036a4d4014SLisandro Dalcin    Level: beginner
37046a4d4014SLisandro Dalcin 
37055a3a76d0SJed Brown    Notes:
37065a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
37075a3a76d0SJed Brown    held state accessible by TSGetSolution() and TSGetTime() because the method may have
37085a3a76d0SJed Brown    stepped over the final time.
37095a3a76d0SJed Brown 
3710db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
37116a4d4014SLisandro Dalcin @*/
3712cc708dedSBarry Smith PetscErrorCode TSSolve(TS ts,Vec u)
37136a4d4014SLisandro Dalcin {
3714b06615a5SLisandro Dalcin   Vec               solution;
3715f22f69f0SBarry Smith 
37166a4d4014SLisandro Dalcin   PetscFunctionBegin;
37170700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3718f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3719303a5415SBarry Smith 
37209566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3721ee41a567SStefano Zampini   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 */
37220910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
37239566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u,&solution));
37249566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts,solution));
37259566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
37265a3a76d0SJed Brown     }
37279566063dSJacob Faibussowitsch     PetscCall(VecCopy(u,ts->vec_sol));
37283c633725SBarry Smith     PetscCheck(!ts->forward_solve,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
37291baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts,u));
37309566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
37319566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory,ts));
3732a6772fa2SLisandro Dalcin 
37333c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
37343c633725SBarry Smith   PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_UNSPECIFIED,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"You must call TSSetExactFinalTime() or use -ts_exact_final_time <stepover,interpolate,matchstep> before calling TSSolve()");
37353c633725SBarry Smith   PetscCheck(ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP || ts->adapt,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Since TS is not adaptive you cannot use TS_EXACTFINALTIME_MATCHSTEP, suggest TS_EXACTFINALTIME_INTERPOLATE");
37364a658b32SHong Zhang   PetscCheck(!(ts->tspan && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP),PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"You must use TS_EXACTFINALTIME_MATCHSTEP when using time span");
37374a658b32SHong Zhang 
3738e1db57b0SHong Zhang   if (ts->tspan && PetscIsCloseAtTol(ts->ptime,ts->tspan->span_times[0],ts->tspan->reltol*ts->time_step+ts->tspan->abstol,0)) { /* starting point in time span */
37394a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol,ts->tspan->vecs_sol[0]));
37404a658b32SHong Zhang     ts->tspan->spanctr = 1;
37414a658b32SHong Zhang   }
3742a6772fa2SLisandro Dalcin 
37431baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3744715f1b00SHong Zhang 
3745e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3746715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3747e7069c78SShri      TSTrajectory to incorrectly save the output files
3748e7069c78SShri   */
3749715f1b00SHong Zhang   /* reset time step and iteration counters */
37502808aa04SLisandro Dalcin   if (!ts->steps) {
37515ef26d82SJed Brown     ts->ksp_its           = 0;
37525ef26d82SJed Brown     ts->snes_its          = 0;
3753c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3754c610991cSLisandro Dalcin     ts->reject            = 0;
37552808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
37562808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
37577d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
37582808aa04SLisandro Dalcin   }
3759e97c63d7SStefano Zampini 
37604a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3761e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
37624a658b32SHong Zhang     PetscReal maxdt;
3763e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3764e97c63d7SStefano Zampini 
37654a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
37664a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3767e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
3768e97c63d7SStefano Zampini   }
3769193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3770193ac0bcSJed Brown 
3771900f6b5bSMatthew G. Knepley   {
3772900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3773900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3774900f6b5bSMatthew G. Knepley     PetscBool         flg;
3775900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3776900f6b5bSMatthew G. Knepley 
3777900f6b5bSMatthew G. Knepley     if (!incall) {
3778900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
37799566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3780900f6b5bSMatthew G. Knepley       if (flg) {
3781900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3782900f6b5bSMatthew G. Knepley         DM           dm;
3783900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3784900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3785f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3786900f6b5bSMatthew G. Knepley 
3787900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
37889566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
37899566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
37909566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
37919566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
37929566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv));
37939566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
37949566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject) ts));
37959566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
37969566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
37979566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
37989566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
37999566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
38009566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
38019566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
38029566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
38039566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3804900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3805900f6b5bSMatthew G. Knepley       }
3806900f6b5bSMatthew G. Knepley     }
3807900f6b5bSMatthew G. Knepley   }
3808900f6b5bSMatthew G. Knepley 
38099566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts,NULL,"-ts_view_pre"));
3810f05ece33SBarry Smith 
3811193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
38129566063dSJacob Faibussowitsch     PetscCall((*ts->ops->solve)(ts));
38139566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol,u));
3814cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3815a6772fa2SLisandro Dalcin     solution = ts->vec_sol;
3816be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3817db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3818db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3819e7069c78SShri 
38202808aa04SLisandro Dalcin     if (!ts->steps) {
38219566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol));
38229566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol));
38232808aa04SLisandro Dalcin     }
38246427ac75SLisandro Dalcin 
3825e1a7a14fSJed Brown     while (!ts->reason) {
38269566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol));
3827*1e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
38289566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
38291baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts,NULL));
38301baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts,NULL));
3831cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
38327b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38339566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
38347b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3835b1cb36f3SHong Zhang       }
383658818c2dSLisandro Dalcin       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
38377b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38389566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
38397b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3840715f1b00SHong Zhang       }
38419566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
38429566063dSJacob Faibussowitsch       PetscCall(TSEventHandler(ts)); /* The right-hand side may be changed due to event. Be careful with Any computation using the RHS information after this point. */
38431baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3844e783b05fSHong Zhang       if (!ts->steprollback) {
38459566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol));
38469566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3847aeb4809dSShri Abhyankar       }
3848193ac0bcSJed Brown     }
38499566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol));
38506427ac75SLisandro Dalcin 
385149354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
38529566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts,ts->max_time,u));
3853cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3854b06615a5SLisandro Dalcin       solution = u;
38559566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts,-1,ts->solvetime,solution));
38560574a7fbSJed Brown     } else {
38579566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol,u));
3858cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3859b06615a5SLisandro Dalcin       solution = ts->vec_sol;
38600574a7fbSJed Brown     }
3861193ac0bcSJed Brown   }
3862d2daff3dSHong Zhang 
38639566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts,NULL,"-ts_view"));
38649566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution,(PetscObject)ts,"-ts_view_solution"));
38659566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
38661baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
38676a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
38686a4d4014SLisandro Dalcin }
38696a4d4014SLisandro Dalcin 
3870d763cef2SBarry Smith /*@
3871b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3872d763cef2SBarry Smith 
3873d763cef2SBarry Smith    Not Collective
3874d763cef2SBarry Smith 
3875d763cef2SBarry Smith    Input Parameter:
3876d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3877d763cef2SBarry Smith 
3878d763cef2SBarry Smith    Output Parameter:
387919eac22cSLisandro Dalcin .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().
3880d763cef2SBarry Smith 
3881d763cef2SBarry Smith    Level: beginner
3882d763cef2SBarry Smith 
3883b8123daeSJed Brown    Note:
3884b8123daeSJed Brown    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
38859be3e283SDebojyoti Ghosh    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
3886b8123daeSJed Brown 
3887db781477SPatrick Sanan .seealso: `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3888d763cef2SBarry Smith 
3889d763cef2SBarry Smith @*/
38907087cfbeSBarry Smith PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3891d763cef2SBarry Smith {
3892d763cef2SBarry Smith   PetscFunctionBegin;
38930700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3894f7cf8827SBarry Smith   PetscValidRealPointer(t,2);
3895d763cef2SBarry Smith   *t = ts->ptime;
3896d763cef2SBarry Smith   PetscFunctionReturn(0);
3897d763cef2SBarry Smith }
3898d763cef2SBarry Smith 
3899e5e524a1SHong Zhang /*@
3900e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3901e5e524a1SHong Zhang 
3902e5e524a1SHong Zhang    Not Collective
3903e5e524a1SHong Zhang 
3904e5e524a1SHong Zhang    Input Parameter:
3905e5e524a1SHong Zhang .  ts - the TS context obtained from TSCreate()
3906e5e524a1SHong Zhang 
3907e5e524a1SHong Zhang    Output Parameter:
3908e5e524a1SHong Zhang .  t  - the previous time
3909e5e524a1SHong Zhang 
3910e5e524a1SHong Zhang    Level: beginner
3911e5e524a1SHong Zhang 
3912db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
3913e5e524a1SHong Zhang 
3914e5e524a1SHong Zhang @*/
3915e5e524a1SHong Zhang PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
3916e5e524a1SHong Zhang {
3917e5e524a1SHong Zhang   PetscFunctionBegin;
3918e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3919e5e524a1SHong Zhang   PetscValidRealPointer(t,2);
3920e5e524a1SHong Zhang   *t = ts->ptime_prev;
3921e5e524a1SHong Zhang   PetscFunctionReturn(0);
3922e5e524a1SHong Zhang }
3923e5e524a1SHong Zhang 
39246a4d4014SLisandro Dalcin /*@
39256a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
39266a4d4014SLisandro Dalcin 
39273f9fe445SBarry Smith    Logically Collective on TS
39286a4d4014SLisandro Dalcin 
39296a4d4014SLisandro Dalcin    Input Parameters:
39306a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
39316a4d4014SLisandro Dalcin -  time - the time
39326a4d4014SLisandro Dalcin 
39336a4d4014SLisandro Dalcin    Level: intermediate
39346a4d4014SLisandro Dalcin 
3935db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSSetMaxSteps()`
39366a4d4014SLisandro Dalcin 
39376a4d4014SLisandro Dalcin @*/
39387087cfbeSBarry Smith PetscErrorCode  TSSetTime(TS ts, PetscReal t)
39396a4d4014SLisandro Dalcin {
39406a4d4014SLisandro Dalcin   PetscFunctionBegin;
39410700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3942c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts,t,2);
39436a4d4014SLisandro Dalcin   ts->ptime = t;
39446a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
39456a4d4014SLisandro Dalcin }
39466a4d4014SLisandro Dalcin 
3947d763cef2SBarry Smith /*@C
3948d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
3949d763cef2SBarry Smith    TS options in the database.
3950d763cef2SBarry Smith 
39513f9fe445SBarry Smith    Logically Collective on TS
3952d763cef2SBarry Smith 
3953d8d19677SJose E. Roman    Input Parameters:
3954d763cef2SBarry Smith +  ts     - The TS context
3955d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3956d763cef2SBarry Smith 
3957d763cef2SBarry Smith    Notes:
3958d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3959d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3960d763cef2SBarry Smith    hyphen.
3961d763cef2SBarry Smith 
3962d763cef2SBarry Smith    Level: advanced
3963d763cef2SBarry Smith 
3964db781477SPatrick Sanan .seealso: `TSSetFromOptions()`
3965d763cef2SBarry Smith 
3966d763cef2SBarry Smith @*/
39677087cfbeSBarry Smith PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
3968d763cef2SBarry Smith {
3969089b2837SJed Brown   SNES           snes;
3970d763cef2SBarry Smith 
3971d763cef2SBarry Smith   PetscFunctionBegin;
39720700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
39739566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts,prefix));
39749566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
39759566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes,prefix));
3976d763cef2SBarry Smith   PetscFunctionReturn(0);
3977d763cef2SBarry Smith }
3978d763cef2SBarry Smith 
3979d763cef2SBarry Smith /*@C
3980d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3981d763cef2SBarry Smith    TS options in the database.
3982d763cef2SBarry Smith 
39833f9fe445SBarry Smith    Logically Collective on TS
3984d763cef2SBarry Smith 
3985d8d19677SJose E. Roman    Input Parameters:
3986d763cef2SBarry Smith +  ts     - The TS context
3987d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3988d763cef2SBarry Smith 
3989d763cef2SBarry Smith    Notes:
3990d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3991d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3992d763cef2SBarry Smith    hyphen.
3993d763cef2SBarry Smith 
3994d763cef2SBarry Smith    Level: advanced
3995d763cef2SBarry Smith 
3996db781477SPatrick Sanan .seealso: `TSGetOptionsPrefix()`
3997d763cef2SBarry Smith 
3998d763cef2SBarry Smith @*/
39997087cfbeSBarry Smith PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4000d763cef2SBarry Smith {
4001089b2837SJed Brown   SNES           snes;
4002d763cef2SBarry Smith 
4003d763cef2SBarry Smith   PetscFunctionBegin;
40040700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
40059566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix));
40069566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
40079566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes,prefix));
4008d763cef2SBarry Smith   PetscFunctionReturn(0);
4009d763cef2SBarry Smith }
4010d763cef2SBarry Smith 
4011d763cef2SBarry Smith /*@C
4012d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
4013d763cef2SBarry Smith    TS options in the database.
4014d763cef2SBarry Smith 
4015d763cef2SBarry Smith    Not Collective
4016d763cef2SBarry Smith 
4017d763cef2SBarry Smith    Input Parameter:
4018d763cef2SBarry Smith .  ts - The TS context
4019d763cef2SBarry Smith 
4020d763cef2SBarry Smith    Output Parameter:
4021d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4022d763cef2SBarry Smith 
402395452b02SPatrick Sanan    Notes:
402495452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prifix' of
4025d763cef2SBarry Smith    sufficient length to hold the prefix.
4026d763cef2SBarry Smith 
4027d763cef2SBarry Smith    Level: intermediate
4028d763cef2SBarry Smith 
4029db781477SPatrick Sanan .seealso: `TSAppendOptionsPrefix()`
4030d763cef2SBarry Smith @*/
40317087cfbeSBarry Smith PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4032d763cef2SBarry Smith {
4033d763cef2SBarry Smith   PetscFunctionBegin;
40340700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
40354482741eSBarry Smith   PetscValidPointer(prefix,2);
40369566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts,prefix));
4037d763cef2SBarry Smith   PetscFunctionReturn(0);
4038d763cef2SBarry Smith }
4039d763cef2SBarry Smith 
4040d763cef2SBarry Smith /*@C
4041d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4042d763cef2SBarry Smith 
4043d763cef2SBarry Smith    Not Collective, but parallel objects are returned if TS is parallel
4044d763cef2SBarry Smith 
4045d763cef2SBarry Smith    Input Parameter:
4046d763cef2SBarry Smith .  ts  - The TS context obtained from TSCreate()
4047d763cef2SBarry Smith 
4048d763cef2SBarry Smith    Output Parameters:
4049e4357dc4SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4050e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4051e4357dc4SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or NULL)
4052e4357dc4SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4053d763cef2SBarry Smith 
405495452b02SPatrick Sanan    Notes:
405595452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
4056d763cef2SBarry Smith 
4057d763cef2SBarry Smith    Level: intermediate
4058d763cef2SBarry Smith 
4059db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4060d763cef2SBarry Smith 
4061d763cef2SBarry Smith @*/
4062e4357dc4SBarry Smith PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4063d763cef2SBarry Smith {
406424989b8cSPeter Brune   DM             dm;
4065089b2837SJed Brown 
4066d763cef2SBarry Smith   PetscFunctionBegin;
406723a57915SBarry Smith   if (Amat || Pmat) {
406823a57915SBarry Smith     SNES snes;
40699566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
40709566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40719566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
407223a57915SBarry Smith   }
40739566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
40749566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,func,ctx));
4075d763cef2SBarry Smith   PetscFunctionReturn(0);
4076d763cef2SBarry Smith }
4077d763cef2SBarry Smith 
40782eca1d9cSJed Brown /*@C
40792eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
40802eca1d9cSJed Brown 
40812eca1d9cSJed Brown    Not Collective, but parallel objects are returned if TS is parallel
40822eca1d9cSJed Brown 
40832eca1d9cSJed Brown    Input Parameter:
40842eca1d9cSJed Brown .  ts  - The TS context obtained from TSCreate()
40852eca1d9cSJed Brown 
40862eca1d9cSJed Brown    Output Parameters:
4087e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4088e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
40892eca1d9cSJed Brown .  f   - The function to compute the matrices
40902eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
40912eca1d9cSJed Brown 
409295452b02SPatrick Sanan    Notes:
409395452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
40942eca1d9cSJed Brown 
40952eca1d9cSJed Brown    Level: advanced
40962eca1d9cSJed Brown 
4097db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
40982eca1d9cSJed Brown 
40992eca1d9cSJed Brown @*/
4100e4357dc4SBarry Smith PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
41012eca1d9cSJed Brown {
410224989b8cSPeter Brune   DM             dm;
41030910c330SBarry Smith 
41042eca1d9cSJed Brown   PetscFunctionBegin;
4105c0aab802Sstefano_zampini   if (Amat || Pmat) {
4106c0aab802Sstefano_zampini     SNES snes;
41079566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
41089566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
41099566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
4110c0aab802Sstefano_zampini   }
41119566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
41129566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,f,ctx));
41132eca1d9cSJed Brown   PetscFunctionReturn(0);
41142eca1d9cSJed Brown }
41152eca1d9cSJed Brown 
4116af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
41176c699258SBarry Smith /*@
41182a808120SBarry Smith    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS
41196c699258SBarry Smith 
4120d083f849SBarry Smith    Logically Collective on ts
41216c699258SBarry Smith 
41226c699258SBarry Smith    Input Parameters:
41232a808120SBarry Smith +  ts - the ODE integrator object
41242a808120SBarry Smith -  dm - the dm, cannot be NULL
41256c699258SBarry Smith 
4126e03a659cSJed Brown    Notes:
4127e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
4128e03a659cSJed Brown    even when not using interfaces like DMTSSetIFunction().  Use DMClone() to get a distinct DM when solving
4129e03a659cSJed Brown    different problems using the same function space.
4130e03a659cSJed Brown 
41316c699258SBarry Smith    Level: intermediate
41326c699258SBarry Smith 
4133db781477SPatrick Sanan .seealso: `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
41346c699258SBarry Smith @*/
41357087cfbeSBarry Smith PetscErrorCode  TSSetDM(TS ts,DM dm)
41366c699258SBarry Smith {
4137089b2837SJed Brown   SNES           snes;
4138942e3340SBarry Smith   DMTS           tsdm;
41396c699258SBarry Smith 
41406c699258SBarry Smith   PetscFunctionBegin;
41410700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
41422a808120SBarry Smith   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
41439566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4144942e3340SBarry Smith   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
41452a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
41469566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm,dm));
41479566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm,&tsdm));
4148*1e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
4149*1e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
415024989b8cSPeter Brune     }
41519566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
415224989b8cSPeter Brune   }
41536c699258SBarry Smith   ts->dm = dm;
4154bbd56ea5SKarl Rupp 
41559566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
41569566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes,dm));
41576c699258SBarry Smith   PetscFunctionReturn(0);
41586c699258SBarry Smith }
41596c699258SBarry Smith 
41606c699258SBarry Smith /*@
41616c699258SBarry Smith    TSGetDM - Gets the DM that may be used by some preconditioners
41626c699258SBarry Smith 
41633f9fe445SBarry Smith    Not Collective
41646c699258SBarry Smith 
41656c699258SBarry Smith    Input Parameter:
41666c699258SBarry Smith . ts - the preconditioner context
41676c699258SBarry Smith 
41686c699258SBarry Smith    Output Parameter:
41696c699258SBarry Smith .  dm - the dm
41706c699258SBarry Smith 
41716c699258SBarry Smith    Level: intermediate
41726c699258SBarry Smith 
4173db781477SPatrick Sanan .seealso: `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
41746c699258SBarry Smith @*/
41757087cfbeSBarry Smith PetscErrorCode  TSGetDM(TS ts,DM *dm)
41766c699258SBarry Smith {
41776c699258SBarry Smith   PetscFunctionBegin;
41780700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4179496e6a7aSJed Brown   if (!ts->dm) {
41809566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm));
41819566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes,ts->dm));
4182496e6a7aSJed Brown   }
41836c699258SBarry Smith   *dm = ts->dm;
41846c699258SBarry Smith   PetscFunctionReturn(0);
41856c699258SBarry Smith }
41861713a123SBarry Smith 
41870f5c6efeSJed Brown /*@
41880f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
41890f5c6efeSJed Brown 
41903f9fe445SBarry Smith    Logically Collective on SNES
41910f5c6efeSJed Brown 
4192d8d19677SJose E. Roman    Input Parameters:
4193d42a1c89SJed Brown + snes - nonlinear solver
41940910c330SBarry Smith . U - the current state at which to evaluate the residual
4195d42a1c89SJed Brown - ctx - user context, must be a TS
41960f5c6efeSJed Brown 
41970f5c6efeSJed Brown    Output Parameter:
41980f5c6efeSJed Brown . F - the nonlinear residual
41990f5c6efeSJed Brown 
42000f5c6efeSJed Brown    Notes:
42010f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
42020f5c6efeSJed Brown    It is most frequently passed to MatFDColoringSetFunction().
42030f5c6efeSJed Brown 
42040f5c6efeSJed Brown    Level: advanced
42050f5c6efeSJed Brown 
4206db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `MatFDColoringSetFunction()`
42070f5c6efeSJed Brown @*/
42080910c330SBarry Smith PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
42090f5c6efeSJed Brown {
42100f5c6efeSJed Brown   TS             ts = (TS)ctx;
42110f5c6efeSJed Brown 
42120f5c6efeSJed Brown   PetscFunctionBegin;
42130f5c6efeSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
42140910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
42150f5c6efeSJed Brown   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
42160f5c6efeSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
42179566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes,U,F,ts));
42180f5c6efeSJed Brown   PetscFunctionReturn(0);
42190f5c6efeSJed Brown }
42200f5c6efeSJed Brown 
42210f5c6efeSJed Brown /*@
42220f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
42230f5c6efeSJed Brown 
42240f5c6efeSJed Brown    Collective on SNES
42250f5c6efeSJed Brown 
4226d8d19677SJose E. Roman    Input Parameters:
42270f5c6efeSJed Brown + snes - nonlinear solver
42280910c330SBarry Smith . U - the current state at which to evaluate the residual
42290f5c6efeSJed Brown - ctx - user context, must be a TS
42300f5c6efeSJed Brown 
4231d8d19677SJose E. Roman    Output Parameters:
42320f5c6efeSJed Brown + A - the Jacobian
42336b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
42340f5c6efeSJed Brown 
42350f5c6efeSJed Brown    Notes:
42360f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
42370f5c6efeSJed Brown 
42380f5c6efeSJed Brown    Level: developer
42390f5c6efeSJed Brown 
4240db781477SPatrick Sanan .seealso: `SNESSetJacobian()`
42410f5c6efeSJed Brown @*/
4242d1e9a80fSBarry Smith PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
42430f5c6efeSJed Brown {
42440f5c6efeSJed Brown   TS             ts = (TS)ctx;
42450f5c6efeSJed Brown 
42460f5c6efeSJed Brown   PetscFunctionBegin;
42470f5c6efeSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
42480910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
42490f5c6efeSJed Brown   PetscValidPointer(A,3);
425094ab13aaSBarry Smith   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
42510f5c6efeSJed Brown   PetscValidPointer(B,4);
425294ab13aaSBarry Smith   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
4253064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts,TS_CLASSID,5);
42549566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes,U,A,B,ts));
42550f5c6efeSJed Brown   PetscFunctionReturn(0);
42560f5c6efeSJed Brown }
4257325fc9f4SBarry Smith 
42580e4ef248SJed Brown /*@C
42599ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
42600e4ef248SJed Brown 
42610e4ef248SJed Brown    Collective on TS
42620e4ef248SJed Brown 
42634165533cSJose E. Roman    Input Parameters:
42640e4ef248SJed Brown +  ts - time stepping context
42650e4ef248SJed Brown .  t - time at which to evaluate
42660910c330SBarry Smith .  U - state at which to evaluate
42670e4ef248SJed Brown -  ctx - context
42680e4ef248SJed Brown 
42694165533cSJose E. Roman    Output Parameter:
42700e4ef248SJed Brown .  F - right hand side
42710e4ef248SJed Brown 
42720e4ef248SJed Brown    Level: intermediate
42730e4ef248SJed Brown 
42740e4ef248SJed Brown    Notes:
42750e4ef248SJed Brown    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
42760e4ef248SJed Brown    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
42770e4ef248SJed Brown 
4278db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
42790e4ef248SJed Brown @*/
42800910c330SBarry Smith PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
42810e4ef248SJed Brown {
42820e4ef248SJed Brown   Mat            Arhs,Brhs;
42830e4ef248SJed Brown 
42840e4ef248SJed Brown   PetscFunctionBegin;
42859566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts,&Arhs,&Brhs));
42862663174eSHong Zhang   /* undo the damage caused by shifting */
42879566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts,Arhs,Brhs));
42889566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts,t,U,Arhs,Brhs));
42899566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs,U,F));
42900e4ef248SJed Brown   PetscFunctionReturn(0);
42910e4ef248SJed Brown }
42920e4ef248SJed Brown 
42930e4ef248SJed Brown /*@C
42940e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
42950e4ef248SJed Brown 
42960e4ef248SJed Brown    Collective on TS
42970e4ef248SJed Brown 
42984165533cSJose E. Roman    Input Parameters:
42990e4ef248SJed Brown +  ts - time stepping context
43000e4ef248SJed Brown .  t - time at which to evaluate
43010910c330SBarry Smith .  U - state at which to evaluate
43020e4ef248SJed Brown -  ctx - context
43030e4ef248SJed Brown 
43044165533cSJose E. Roman    Output Parameters:
43050e4ef248SJed Brown +  A - pointer to operator
430697bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43070e4ef248SJed Brown 
43080e4ef248SJed Brown    Level: intermediate
43090e4ef248SJed Brown 
43100e4ef248SJed Brown    Notes:
43110e4ef248SJed Brown    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
43120e4ef248SJed Brown 
4313db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
43140e4ef248SJed Brown @*/
4315d1e9a80fSBarry Smith PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
43160e4ef248SJed Brown {
43170e4ef248SJed Brown   PetscFunctionBegin;
43180e4ef248SJed Brown   PetscFunctionReturn(0);
43190e4ef248SJed Brown }
43200e4ef248SJed Brown 
43210026cea9SSean Farley /*@C
43220026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
43230026cea9SSean Farley 
43240026cea9SSean Farley    Collective on TS
43250026cea9SSean Farley 
43264165533cSJose E. Roman    Input Parameters:
43270026cea9SSean Farley +  ts - time stepping context
43280026cea9SSean Farley .  t - time at which to evaluate
43290910c330SBarry Smith .  U - state at which to evaluate
43300910c330SBarry Smith .  Udot - time derivative of state vector
43310026cea9SSean Farley -  ctx - context
43320026cea9SSean Farley 
43334165533cSJose E. Roman    Output Parameter:
43340026cea9SSean Farley .  F - left hand side
43350026cea9SSean Farley 
43360026cea9SSean Farley    Level: intermediate
43370026cea9SSean Farley 
43380026cea9SSean Farley    Notes:
43390910c330SBarry Smith    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
43400026cea9SSean Farley    user is required to write their own TSComputeIFunction.
43410026cea9SSean Farley    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
43420026cea9SSean Farley    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
43430026cea9SSean Farley 
43449ae8fd06SBarry Smith    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
43459ae8fd06SBarry Smith 
4346db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
43470026cea9SSean Farley @*/
43480910c330SBarry Smith PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
43490026cea9SSean Farley {
43500026cea9SSean Farley   Mat            A,B;
43510026cea9SSean Farley 
43520026cea9SSean Farley   PetscFunctionBegin;
43539566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts,&A,&B,NULL,NULL));
43549566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE));
43559566063dSJacob Faibussowitsch   PetscCall(MatMult(A,Udot,F));
43560026cea9SSean Farley   PetscFunctionReturn(0);
43570026cea9SSean Farley }
43580026cea9SSean Farley 
43590026cea9SSean Farley /*@C
4360b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
43610026cea9SSean Farley 
43620026cea9SSean Farley    Collective on TS
43630026cea9SSean Farley 
43644165533cSJose E. Roman    Input Parameters:
43650026cea9SSean Farley +  ts - time stepping context
43660026cea9SSean Farley .  t - time at which to evaluate
43670910c330SBarry Smith .  U - state at which to evaluate
43680910c330SBarry Smith .  Udot - time derivative of state vector
43690026cea9SSean Farley .  shift - shift to apply
43700026cea9SSean Farley -  ctx - context
43710026cea9SSean Farley 
43724165533cSJose E. Roman    Output Parameters:
43730026cea9SSean Farley +  A - pointer to operator
437497bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43750026cea9SSean Farley 
4376b41af12eSJed Brown    Level: advanced
43770026cea9SSean Farley 
43780026cea9SSean Farley    Notes:
43790026cea9SSean Farley    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
43800026cea9SSean Farley 
4381b41af12eSJed Brown    It is only appropriate for problems of the form
4382b41af12eSJed Brown 
4383b41af12eSJed Brown $     M Udot = F(U,t)
4384b41af12eSJed Brown 
4385b41af12eSJed Brown   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4386b41af12eSJed Brown   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4387b41af12eSJed Brown   an implicit operator of the form
4388b41af12eSJed Brown 
4389b41af12eSJed Brown $    shift*M + J
4390b41af12eSJed Brown 
4391b41af12eSJed Brown   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
4392b41af12eSJed Brown   a copy of M or reassemble it when requested.
4393b41af12eSJed Brown 
4394db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
43950026cea9SSean Farley @*/
4396d1e9a80fSBarry Smith PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
43970026cea9SSean Farley {
43980026cea9SSean Farley   PetscFunctionBegin;
43999566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4400b41af12eSJed Brown   ts->ijacobian.shift = shift;
44010026cea9SSean Farley   PetscFunctionReturn(0);
44020026cea9SSean Farley }
4403b41af12eSJed Brown 
4404e817cc15SEmil Constantinescu /*@
4405e817cc15SEmil Constantinescu    TSGetEquationType - Gets the type of the equation that TS is solving.
4406e817cc15SEmil Constantinescu 
4407e817cc15SEmil Constantinescu    Not Collective
4408e817cc15SEmil Constantinescu 
4409e817cc15SEmil Constantinescu    Input Parameter:
4410e817cc15SEmil Constantinescu .  ts - the TS context
4411e817cc15SEmil Constantinescu 
4412e817cc15SEmil Constantinescu    Output Parameter:
44134e6b9ce4SEmil Constantinescu .  equation_type - see TSEquationType
4414e817cc15SEmil Constantinescu 
4415e817cc15SEmil Constantinescu    Level: beginner
4416e817cc15SEmil Constantinescu 
4417db781477SPatrick Sanan .seealso: `TSSetEquationType()`, `TSEquationType`
4418e817cc15SEmil Constantinescu @*/
4419e817cc15SEmil Constantinescu PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4420e817cc15SEmil Constantinescu {
4421e817cc15SEmil Constantinescu   PetscFunctionBegin;
4422e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4423e817cc15SEmil Constantinescu   PetscValidPointer(equation_type,2);
4424e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
4425e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4426e817cc15SEmil Constantinescu }
4427e817cc15SEmil Constantinescu 
4428e817cc15SEmil Constantinescu /*@
4429e817cc15SEmil Constantinescu    TSSetEquationType - Sets the type of the equation that TS is solving.
4430e817cc15SEmil Constantinescu 
4431e817cc15SEmil Constantinescu    Not Collective
4432e817cc15SEmil Constantinescu 
4433d8d19677SJose E. Roman    Input Parameters:
4434e817cc15SEmil Constantinescu +  ts - the TS context
44351297b224SEmil Constantinescu -  equation_type - see TSEquationType
4436e817cc15SEmil Constantinescu 
4437e817cc15SEmil Constantinescu    Level: advanced
4438e817cc15SEmil Constantinescu 
4439db781477SPatrick Sanan .seealso: `TSGetEquationType()`, `TSEquationType`
4440e817cc15SEmil Constantinescu @*/
4441e817cc15SEmil Constantinescu PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4442e817cc15SEmil Constantinescu {
4443e817cc15SEmil Constantinescu   PetscFunctionBegin;
4444e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4445e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
4446e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4447e817cc15SEmil Constantinescu }
44480026cea9SSean Farley 
44494af1b03aSJed Brown /*@
44504af1b03aSJed Brown    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
44514af1b03aSJed Brown 
44524af1b03aSJed Brown    Not Collective
44534af1b03aSJed Brown 
44544af1b03aSJed Brown    Input Parameter:
44554af1b03aSJed Brown .  ts - the TS context
44564af1b03aSJed Brown 
44574af1b03aSJed Brown    Output Parameter:
44584af1b03aSJed Brown .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
44594af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
44604af1b03aSJed Brown 
4461487e0bb9SJed Brown    Level: beginner
44624af1b03aSJed Brown 
4463cd652676SJed Brown    Notes:
4464cd652676SJed Brown    Can only be called after the call to TSSolve() is complete.
44654af1b03aSJed Brown 
4466db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
44674af1b03aSJed Brown @*/
44684af1b03aSJed Brown PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
44694af1b03aSJed Brown {
44704af1b03aSJed Brown   PetscFunctionBegin;
44714af1b03aSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
44724af1b03aSJed Brown   PetscValidPointer(reason,2);
44734af1b03aSJed Brown   *reason = ts->reason;
44744af1b03aSJed Brown   PetscFunctionReturn(0);
44754af1b03aSJed Brown }
44764af1b03aSJed Brown 
4477d6ad946cSShri Abhyankar /*@
4478d6ad946cSShri Abhyankar    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
4479d6ad946cSShri Abhyankar 
44806b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4481d6ad946cSShri Abhyankar 
44826b221cbeSPatrick Sanan    Input Parameters:
4483d6ad946cSShri Abhyankar +  ts - the TS context
44846b221cbeSPatrick Sanan -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4485d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4486d6ad946cSShri Abhyankar 
4487f5abba47SShri Abhyankar    Level: advanced
4488d6ad946cSShri Abhyankar 
4489d6ad946cSShri Abhyankar    Notes:
44906b221cbeSPatrick Sanan    Can only be called while TSSolve() is active.
4491d6ad946cSShri Abhyankar 
4492db781477SPatrick Sanan .seealso: `TSConvergedReason`
4493d6ad946cSShri Abhyankar @*/
4494d6ad946cSShri Abhyankar PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4495d6ad946cSShri Abhyankar {
4496d6ad946cSShri Abhyankar   PetscFunctionBegin;
4497d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4498d6ad946cSShri Abhyankar   ts->reason = reason;
4499d6ad946cSShri Abhyankar   PetscFunctionReturn(0);
4500d6ad946cSShri Abhyankar }
4501d6ad946cSShri Abhyankar 
4502cc708dedSBarry Smith /*@
4503cc708dedSBarry Smith    TSGetSolveTime - Gets the time after a call to TSSolve()
4504cc708dedSBarry Smith 
4505cc708dedSBarry Smith    Not Collective
4506cc708dedSBarry Smith 
4507cc708dedSBarry Smith    Input Parameter:
4508cc708dedSBarry Smith .  ts - the TS context
4509cc708dedSBarry Smith 
4510cc708dedSBarry Smith    Output Parameter:
451119eac22cSLisandro Dalcin .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()
4512cc708dedSBarry Smith 
4513487e0bb9SJed Brown    Level: beginner
4514cc708dedSBarry Smith 
4515cc708dedSBarry Smith    Notes:
4516cc708dedSBarry Smith    Can only be called after the call to TSSolve() is complete.
4517cc708dedSBarry Smith 
4518db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
4519cc708dedSBarry Smith @*/
4520cc708dedSBarry Smith PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4521cc708dedSBarry Smith {
4522cc708dedSBarry Smith   PetscFunctionBegin;
4523cc708dedSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4524dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime,2);
4525cc708dedSBarry Smith   *ftime = ts->solvetime;
4526cc708dedSBarry Smith   PetscFunctionReturn(0);
4527cc708dedSBarry Smith }
4528cc708dedSBarry Smith 
45292c18e0fdSBarry Smith /*@
45305ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
45319f67acb7SJed Brown    used by the time integrator.
45329f67acb7SJed Brown 
45339f67acb7SJed Brown    Not Collective
45349f67acb7SJed Brown 
45359f67acb7SJed Brown    Input Parameter:
45369f67acb7SJed Brown .  ts - TS context
45379f67acb7SJed Brown 
45389f67acb7SJed Brown    Output Parameter:
45399f67acb7SJed Brown .  nits - number of nonlinear iterations
45409f67acb7SJed Brown 
45419f67acb7SJed Brown    Notes:
45429f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
45439f67acb7SJed Brown 
45449f67acb7SJed Brown    Level: intermediate
45459f67acb7SJed Brown 
4546db781477SPatrick Sanan .seealso: `TSGetKSPIterations()`
45479f67acb7SJed Brown @*/
45485ef26d82SJed Brown PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
45499f67acb7SJed Brown {
45509f67acb7SJed Brown   PetscFunctionBegin;
45519f67acb7SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
45529f67acb7SJed Brown   PetscValidIntPointer(nits,2);
45535ef26d82SJed Brown   *nits = ts->snes_its;
45549f67acb7SJed Brown   PetscFunctionReturn(0);
45559f67acb7SJed Brown }
45569f67acb7SJed Brown 
45579f67acb7SJed Brown /*@
45585ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
45599f67acb7SJed Brown    used by the time integrator.
45609f67acb7SJed Brown 
45619f67acb7SJed Brown    Not Collective
45629f67acb7SJed Brown 
45639f67acb7SJed Brown    Input Parameter:
45649f67acb7SJed Brown .  ts - TS context
45659f67acb7SJed Brown 
45669f67acb7SJed Brown    Output Parameter:
45679f67acb7SJed Brown .  lits - number of linear iterations
45689f67acb7SJed Brown 
45699f67acb7SJed Brown    Notes:
45709f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
45719f67acb7SJed Brown 
45729f67acb7SJed Brown    Level: intermediate
45739f67acb7SJed Brown 
4574db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `SNESGetKSPIterations()`
45759f67acb7SJed Brown @*/
45765ef26d82SJed Brown PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
45779f67acb7SJed Brown {
45789f67acb7SJed Brown   PetscFunctionBegin;
45799f67acb7SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
45809f67acb7SJed Brown   PetscValidIntPointer(lits,2);
45815ef26d82SJed Brown   *lits = ts->ksp_its;
45829f67acb7SJed Brown   PetscFunctionReturn(0);
45839f67acb7SJed Brown }
45849f67acb7SJed Brown 
4585cef5090cSJed Brown /*@
4586cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4587cef5090cSJed Brown 
4588cef5090cSJed Brown    Not Collective
4589cef5090cSJed Brown 
4590cef5090cSJed Brown    Input Parameter:
4591cef5090cSJed Brown .  ts - TS context
4592cef5090cSJed Brown 
4593cef5090cSJed Brown    Output Parameter:
4594cef5090cSJed Brown .  rejects - number of steps rejected
4595cef5090cSJed Brown 
4596cef5090cSJed Brown    Notes:
4597cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4598cef5090cSJed Brown 
4599cef5090cSJed Brown    Level: intermediate
4600cef5090cSJed Brown 
4601db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4602cef5090cSJed Brown @*/
4603cef5090cSJed Brown PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4604cef5090cSJed Brown {
4605cef5090cSJed Brown   PetscFunctionBegin;
4606cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4607cef5090cSJed Brown   PetscValidIntPointer(rejects,2);
4608cef5090cSJed Brown   *rejects = ts->reject;
4609cef5090cSJed Brown   PetscFunctionReturn(0);
4610cef5090cSJed Brown }
4611cef5090cSJed Brown 
4612cef5090cSJed Brown /*@
4613cef5090cSJed Brown    TSGetSNESFailures - Gets the total number of failed SNES solves
4614cef5090cSJed Brown 
4615cef5090cSJed Brown    Not Collective
4616cef5090cSJed Brown 
4617cef5090cSJed Brown    Input Parameter:
4618cef5090cSJed Brown .  ts - TS context
4619cef5090cSJed Brown 
4620cef5090cSJed Brown    Output Parameter:
4621cef5090cSJed Brown .  fails - number of failed nonlinear solves
4622cef5090cSJed Brown 
4623cef5090cSJed Brown    Notes:
4624cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4625cef5090cSJed Brown 
4626cef5090cSJed Brown    Level: intermediate
4627cef5090cSJed Brown 
4628db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4629cef5090cSJed Brown @*/
4630cef5090cSJed Brown PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4631cef5090cSJed Brown {
4632cef5090cSJed Brown   PetscFunctionBegin;
4633cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4634cef5090cSJed Brown   PetscValidIntPointer(fails,2);
4635cef5090cSJed Brown   *fails = ts->num_snes_failures;
4636cef5090cSJed Brown   PetscFunctionReturn(0);
4637cef5090cSJed Brown }
4638cef5090cSJed Brown 
4639cef5090cSJed Brown /*@
4640cef5090cSJed Brown    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
4641cef5090cSJed Brown 
4642cef5090cSJed Brown    Not Collective
4643cef5090cSJed Brown 
4644d8d19677SJose E. Roman    Input Parameters:
4645cef5090cSJed Brown +  ts - TS context
4646cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4647cef5090cSJed Brown 
4648cef5090cSJed Brown    Notes:
4649cef5090cSJed Brown    The counter is reset to zero for each step
4650cef5090cSJed Brown 
4651cef5090cSJed Brown    Options Database Key:
4652cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4653cef5090cSJed Brown 
4654cef5090cSJed Brown    Level: intermediate
4655cef5090cSJed Brown 
4656db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4657cef5090cSJed Brown @*/
4658cef5090cSJed Brown PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4659cef5090cSJed Brown {
4660cef5090cSJed Brown   PetscFunctionBegin;
4661cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4662cef5090cSJed Brown   ts->max_reject = rejects;
4663cef5090cSJed Brown   PetscFunctionReturn(0);
4664cef5090cSJed Brown }
4665cef5090cSJed Brown 
4666cef5090cSJed Brown /*@
4667cef5090cSJed Brown    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
4668cef5090cSJed Brown 
4669cef5090cSJed Brown    Not Collective
4670cef5090cSJed Brown 
4671d8d19677SJose E. Roman    Input Parameters:
4672cef5090cSJed Brown +  ts - TS context
4673cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4674cef5090cSJed Brown 
4675cef5090cSJed Brown    Notes:
4676cef5090cSJed Brown    The counter is reset to zero for each successive call to TSSolve().
4677cef5090cSJed Brown 
4678cef5090cSJed Brown    Options Database Key:
4679cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4680cef5090cSJed Brown 
4681cef5090cSJed Brown    Level: intermediate
4682cef5090cSJed Brown 
4683db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4684cef5090cSJed Brown @*/
4685cef5090cSJed Brown PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4686cef5090cSJed Brown {
4687cef5090cSJed Brown   PetscFunctionBegin;
4688cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4689cef5090cSJed Brown   ts->max_snes_failures = fails;
4690cef5090cSJed Brown   PetscFunctionReturn(0);
4691cef5090cSJed Brown }
4692cef5090cSJed Brown 
4693cef5090cSJed Brown /*@
4694cef5090cSJed Brown    TSSetErrorIfStepFails - Error if no step succeeds
4695cef5090cSJed Brown 
4696cef5090cSJed Brown    Not Collective
4697cef5090cSJed Brown 
4698d8d19677SJose E. Roman    Input Parameters:
4699cef5090cSJed Brown +  ts - TS context
4700cef5090cSJed Brown -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
4701cef5090cSJed Brown 
4702cef5090cSJed Brown    Options Database Key:
4703cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4704cef5090cSJed Brown 
4705cef5090cSJed Brown    Level: intermediate
4706cef5090cSJed Brown 
4707db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4708cef5090cSJed Brown @*/
4709cef5090cSJed Brown PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4710cef5090cSJed Brown {
4711cef5090cSJed Brown   PetscFunctionBegin;
4712cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4713cef5090cSJed Brown   ts->errorifstepfailed = err;
4714cef5090cSJed Brown   PetscFunctionReturn(0);
4715cef5090cSJed Brown }
4716cef5090cSJed Brown 
471784df9cb4SJed Brown /*@
4718552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
471984df9cb4SJed Brown 
4720ed81e22dSJed Brown    Collective on TS if controller has not been created yet
472184df9cb4SJed Brown 
47224165533cSJose E. Roman    Input Parameter:
4723ed81e22dSJed Brown .  ts - time stepping context
472484df9cb4SJed Brown 
47254165533cSJose E. Roman    Output Parameter:
4726ed81e22dSJed Brown .  adapt - adaptive controller
472784df9cb4SJed Brown 
472884df9cb4SJed Brown    Level: intermediate
472984df9cb4SJed Brown 
4730db781477SPatrick Sanan .seealso: `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
473184df9cb4SJed Brown @*/
4732552698daSJed Brown PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
473384df9cb4SJed Brown {
473484df9cb4SJed Brown   PetscFunctionBegin;
473584df9cb4SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4736bec58848SLisandro Dalcin   PetscValidPointer(adapt,2);
473784df9cb4SJed Brown   if (!ts->adapt) {
47389566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt));
47399566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt));
47409566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1));
474184df9cb4SJed Brown   }
4742bec58848SLisandro Dalcin   *adapt = ts->adapt;
474384df9cb4SJed Brown   PetscFunctionReturn(0);
474484df9cb4SJed Brown }
4745d6ebe24aSShri Abhyankar 
47461c3436cfSJed Brown /*@
47471c3436cfSJed Brown    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
47481c3436cfSJed Brown 
47491c3436cfSJed Brown    Logically Collective
47501c3436cfSJed Brown 
47514165533cSJose E. Roman    Input Parameters:
47521c3436cfSJed Brown +  ts - time integration context
47531c3436cfSJed Brown .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
47540298fd71SBarry Smith .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
47551c3436cfSJed Brown .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
47560298fd71SBarry Smith -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
47571c3436cfSJed Brown 
4758a3cdaa26SBarry Smith    Options Database keys:
4759a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
476067b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4761a3cdaa26SBarry Smith 
47623ff766beSShri Abhyankar    Notes:
47633ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
47643ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
47653ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
47663ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
47673ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
47683ff766beSShri Abhyankar    differential variables.
47693ff766beSShri Abhyankar 
47701c3436cfSJed Brown    Level: beginner
47711c3436cfSJed Brown 
4772db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
47731c3436cfSJed Brown @*/
47741c3436cfSJed Brown PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
47751c3436cfSJed Brown {
47761c3436cfSJed Brown   PetscFunctionBegin;
4777c5033834SJed Brown   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
47781c3436cfSJed Brown   if (vatol) {
47799566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
47809566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
47811c3436cfSJed Brown     ts->vatol = vatol;
47821c3436cfSJed Brown   }
4783c5033834SJed Brown   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
47841c3436cfSJed Brown   if (vrtol) {
47859566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
47869566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
47871c3436cfSJed Brown     ts->vrtol = vrtol;
47881c3436cfSJed Brown   }
47891c3436cfSJed Brown   PetscFunctionReturn(0);
47901c3436cfSJed Brown }
47911c3436cfSJed Brown 
4792c5033834SJed Brown /*@
4793c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4794c5033834SJed Brown 
4795c5033834SJed Brown    Logically Collective
4796c5033834SJed Brown 
47974165533cSJose E. Roman    Input Parameter:
4798c5033834SJed Brown .  ts - time integration context
4799c5033834SJed Brown 
48004165533cSJose E. Roman    Output Parameters:
48010298fd71SBarry Smith +  atol - scalar absolute tolerances, NULL to ignore
48020298fd71SBarry Smith .  vatol - vector of absolute tolerances, NULL to ignore
48030298fd71SBarry Smith .  rtol - scalar relative tolerances, NULL to ignore
48040298fd71SBarry Smith -  vrtol - vector of relative tolerances, NULL to ignore
4805c5033834SJed Brown 
4806c5033834SJed Brown    Level: beginner
4807c5033834SJed Brown 
4808db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4809c5033834SJed Brown @*/
4810c5033834SJed Brown PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4811c5033834SJed Brown {
4812c5033834SJed Brown   PetscFunctionBegin;
4813c5033834SJed Brown   if (atol)  *atol  = ts->atol;
4814c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4815c5033834SJed Brown   if (rtol)  *rtol  = ts->rtol;
4816c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
4817c5033834SJed Brown   PetscFunctionReturn(0);
4818c5033834SJed Brown }
4819c5033834SJed Brown 
48209c6b16b5SShri Abhyankar /*@
4821a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
48229c6b16b5SShri Abhyankar 
48239c6b16b5SShri Abhyankar    Collective on TS
48249c6b16b5SShri Abhyankar 
48254165533cSJose E. Roman    Input Parameters:
48269c6b16b5SShri Abhyankar +  ts - time stepping context
4827a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4828a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
48299c6b16b5SShri Abhyankar 
48304165533cSJose E. Roman    Output Parameters:
4831a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
48327453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4833a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
48349c6b16b5SShri Abhyankar 
48359c6b16b5SShri Abhyankar    Level: developer
48369c6b16b5SShri Abhyankar 
4837db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
48389c6b16b5SShri Abhyankar @*/
48397453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
48409c6b16b5SShri Abhyankar {
48419c6b16b5SShri Abhyankar   PetscInt          i,n,N,rstart;
48427453f775SEmil Constantinescu   PetscInt          n_loc,na_loc,nr_loc;
48437453f775SEmil Constantinescu   PetscReal         n_glb,na_glb,nr_glb;
48449c6b16b5SShri Abhyankar   const PetscScalar *u,*y;
48457453f775SEmil Constantinescu   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
48467453f775SEmil Constantinescu   PetscReal         tol,tola,tolr;
48477453f775SEmil Constantinescu   PetscReal         err_loc[6],err_glb[6];
48489c6b16b5SShri Abhyankar 
48499c6b16b5SShri Abhyankar   PetscFunctionBegin;
48509c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4851a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4852a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
4853a4868fbcSLisandro Dalcin   PetscValidType(U,2);
4854a4868fbcSLisandro Dalcin   PetscValidType(Y,3);
4855a4868fbcSLisandro Dalcin   PetscCheckSameComm(U,2,Y,3);
4856dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,4);
4857dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,5);
4858dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,6);
48593c633725SBarry Smith   PetscCheck(U != Y,PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
48609c6b16b5SShri Abhyankar 
48619566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U,&N));
48629566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U,&n));
48639566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U,&rstart,NULL));
48649566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
48659566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
48667453f775SEmil Constantinescu   sum  = 0.; n_loc  = 0;
48677453f775SEmil Constantinescu   suma = 0.; na_loc = 0;
48687453f775SEmil Constantinescu   sumr = 0.; nr_loc = 0;
48699c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
48709c6b16b5SShri Abhyankar     const PetscScalar *atol,*rtol;
48719566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
48729566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
48739c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
487476cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
48757453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48767453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48777453f775SEmil Constantinescu       if (tola>0.) {
48787453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
48797453f775SEmil Constantinescu         na_loc++;
48807453f775SEmil Constantinescu       }
48817453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
48827453f775SEmil Constantinescu       if (tolr>0.) {
48837453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
48847453f775SEmil Constantinescu         nr_loc++;
48857453f775SEmil Constantinescu       }
48867453f775SEmil Constantinescu       tol=tola+tolr;
48877453f775SEmil Constantinescu       if (tol>0.) {
48887453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
48897453f775SEmil Constantinescu         n_loc++;
48907453f775SEmil Constantinescu       }
48919c6b16b5SShri Abhyankar     }
48929566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
48939566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
48949c6b16b5SShri Abhyankar   } else if (ts->vatol) {       /* vector atol, scalar rtol */
48959c6b16b5SShri Abhyankar     const PetscScalar *atol;
48969566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
48979c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
489876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
48997453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49007453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49017453f775SEmil Constantinescu       if (tola>0.) {
49027453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
49037453f775SEmil Constantinescu         na_loc++;
49047453f775SEmil Constantinescu       }
49057453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
49067453f775SEmil Constantinescu       if (tolr>0.) {
49077453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
49087453f775SEmil Constantinescu         nr_loc++;
49097453f775SEmil Constantinescu       }
49107453f775SEmil Constantinescu       tol=tola+tolr;
49117453f775SEmil Constantinescu       if (tol>0.) {
49127453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
49137453f775SEmil Constantinescu         n_loc++;
49147453f775SEmil Constantinescu       }
49159c6b16b5SShri Abhyankar     }
49169566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
49179c6b16b5SShri Abhyankar   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
49189c6b16b5SShri Abhyankar     const PetscScalar *rtol;
49199566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
49209c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
492176cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
49227453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49237453f775SEmil Constantinescu       tola = ts->atol;
49247453f775SEmil Constantinescu       if (tola>0.) {
49257453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
49267453f775SEmil Constantinescu         na_loc++;
49277453f775SEmil Constantinescu       }
49287453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
49297453f775SEmil Constantinescu       if (tolr>0.) {
49307453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
49317453f775SEmil Constantinescu         nr_loc++;
49327453f775SEmil Constantinescu       }
49337453f775SEmil Constantinescu       tol=tola+tolr;
49347453f775SEmil Constantinescu       if (tol>0.) {
49357453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
49367453f775SEmil Constantinescu         n_loc++;
49377453f775SEmil Constantinescu       }
49389c6b16b5SShri Abhyankar     }
49399566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
49409c6b16b5SShri Abhyankar   } else {                      /* scalar atol, scalar rtol */
49419c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
494276cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
49437453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49447453f775SEmil Constantinescu       tola = ts->atol;
49457453f775SEmil Constantinescu       if (tola>0.) {
49467453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
49477453f775SEmil Constantinescu         na_loc++;
49487453f775SEmil Constantinescu       }
49497453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
49507453f775SEmil Constantinescu       if (tolr>0.) {
49517453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
49527453f775SEmil Constantinescu         nr_loc++;
49537453f775SEmil Constantinescu       }
49547453f775SEmil Constantinescu       tol=tola+tolr;
49557453f775SEmil Constantinescu       if (tol>0.) {
49567453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
49577453f775SEmil Constantinescu         n_loc++;
49587453f775SEmil Constantinescu       }
49599c6b16b5SShri Abhyankar     }
49609c6b16b5SShri Abhyankar   }
49619566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
49629566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
49639c6b16b5SShri Abhyankar 
49647453f775SEmil Constantinescu   err_loc[0] = sum;
49657453f775SEmil Constantinescu   err_loc[1] = suma;
49667453f775SEmil Constantinescu   err_loc[2] = sumr;
49677453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
49687453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
49697453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
49707453f775SEmil Constantinescu 
49711c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts)));
49727453f775SEmil Constantinescu 
49737453f775SEmil Constantinescu   gsum   = err_glb[0];
49747453f775SEmil Constantinescu   gsuma  = err_glb[1];
49757453f775SEmil Constantinescu   gsumr  = err_glb[2];
49767453f775SEmil Constantinescu   n_glb  = err_glb[3];
49777453f775SEmil Constantinescu   na_glb = err_glb[4];
49787453f775SEmil Constantinescu   nr_glb = err_glb[5];
49797453f775SEmil Constantinescu 
4980b1316ef9SEmil Constantinescu   *norm  = 0.;
4981*1e66621cSBarry Smith   if (n_glb>0.) *norm  = PetscSqrtReal(gsum  / n_glb);
4982b1316ef9SEmil Constantinescu   *norma = 0.;
4983*1e66621cSBarry Smith   if (na_glb>0.) *norma = PetscSqrtReal(gsuma / na_glb);
4984b1316ef9SEmil Constantinescu   *normr = 0.;
4985*1e66621cSBarry Smith   if (nr_glb>0.) *normr = PetscSqrtReal(gsumr / nr_glb);
49869c6b16b5SShri Abhyankar 
49873c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
49883c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
49893c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
49909c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
49919c6b16b5SShri Abhyankar }
49929c6b16b5SShri Abhyankar 
49939c6b16b5SShri Abhyankar /*@
4994a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
49959c6b16b5SShri Abhyankar 
49969c6b16b5SShri Abhyankar    Collective on TS
49979c6b16b5SShri Abhyankar 
49984165533cSJose E. Roman    Input Parameters:
49999c6b16b5SShri Abhyankar +  ts - time stepping context
5000a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5001a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
50029c6b16b5SShri Abhyankar 
50034165533cSJose E. Roman    Output Parameters:
5004a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
50057453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5006a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
50079c6b16b5SShri Abhyankar 
50089c6b16b5SShri Abhyankar    Level: developer
50099c6b16b5SShri Abhyankar 
5010db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
50119c6b16b5SShri Abhyankar @*/
50127453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
50139c6b16b5SShri Abhyankar {
50147453f775SEmil Constantinescu   PetscInt          i,n,N,rstart;
50159c6b16b5SShri Abhyankar   const PetscScalar *u,*y;
50167453f775SEmil Constantinescu   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
50177453f775SEmil Constantinescu   PetscReal         tol,tola,tolr,diff;
50187453f775SEmil Constantinescu   PetscReal         err_loc[3],err_glb[3];
50199c6b16b5SShri Abhyankar 
50209c6b16b5SShri Abhyankar   PetscFunctionBegin;
50219c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5022a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5023a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
5024a4868fbcSLisandro Dalcin   PetscValidType(U,2);
5025a4868fbcSLisandro Dalcin   PetscValidType(Y,3);
5026a4868fbcSLisandro Dalcin   PetscCheckSameComm(U,2,Y,3);
5027dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,4);
5028dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,5);
5029dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,6);
50303c633725SBarry Smith   PetscCheck(U != Y,PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
50319c6b16b5SShri Abhyankar 
50329566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U,&N));
50339566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U,&n));
50349566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U,&rstart,NULL));
50359566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
50369566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
50377453f775SEmil Constantinescu 
50387453f775SEmil Constantinescu   max=0.;
50397453f775SEmil Constantinescu   maxa=0.;
50407453f775SEmil Constantinescu   maxr=0.;
50417453f775SEmil Constantinescu 
50427453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
50439c6b16b5SShri Abhyankar     const PetscScalar *atol,*rtol;
50449566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
50459566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
50467453f775SEmil Constantinescu 
50477453f775SEmil Constantinescu     for (i=0; i<n; i++) {
504876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50497453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50507453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50517453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50527453f775SEmil Constantinescu       tol  = tola+tolr;
5053*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,diff / tola);
5054*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,diff / tolr);
5055*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,diff / tol);
50569c6b16b5SShri Abhyankar     }
50579566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
50589566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
50599c6b16b5SShri Abhyankar   } else if (ts->vatol) {       /* vector atol, scalar rtol */
50609c6b16b5SShri Abhyankar     const PetscScalar *atol;
50619566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
50627453f775SEmil Constantinescu     for (i=0; i<n; i++) {
506376cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50647453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50657453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50667453f775SEmil Constantinescu       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50677453f775SEmil Constantinescu       tol  = tola+tolr;
5068*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,diff / tola);
5069*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,diff / tolr);
5070*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,diff / tol);
50719c6b16b5SShri Abhyankar     }
50729566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
50739c6b16b5SShri Abhyankar   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
50749c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50759566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
50767453f775SEmil Constantinescu 
50777453f775SEmil Constantinescu     for (i=0; i<n; i++) {
507876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50797453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50807453f775SEmil Constantinescu       tola = ts->atol;
50817453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50827453f775SEmil Constantinescu       tol  = tola+tolr;
5083*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,diff / tola);
5084*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,diff / tolr);
5085*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,diff / tol);
50869c6b16b5SShri Abhyankar     }
50879566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
50889c6b16b5SShri Abhyankar   } else {                      /* scalar atol, scalar rtol */
50897453f775SEmil Constantinescu 
50907453f775SEmil Constantinescu     for (i=0; i<n; i++) {
509176cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50927453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50937453f775SEmil Constantinescu       tola = ts->atol;
50947453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50957453f775SEmil Constantinescu       tol  = tola+tolr;
5096*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,diff / tola);
5097*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,diff / tolr);
5098*1e66621cSBarry Smith       if (tol>0.) max = PetscMax(max,diff / tol);
50999c6b16b5SShri Abhyankar     }
51009c6b16b5SShri Abhyankar   }
51019566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
51029566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
51037453f775SEmil Constantinescu   err_loc[0] = max;
51047453f775SEmil Constantinescu   err_loc[1] = maxa;
51057453f775SEmil Constantinescu   err_loc[2] = maxr;
51061c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
51077453f775SEmil Constantinescu   gmax   = err_glb[0];
51087453f775SEmil Constantinescu   gmaxa  = err_glb[1];
51097453f775SEmil Constantinescu   gmaxr  = err_glb[2];
51109c6b16b5SShri Abhyankar 
51119c6b16b5SShri Abhyankar   *norm = gmax;
51127453f775SEmil Constantinescu   *norma = gmaxa;
51137453f775SEmil Constantinescu   *normr = gmaxr;
51143c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
51153c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
51163c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
51179c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
51189c6b16b5SShri Abhyankar }
51199c6b16b5SShri Abhyankar 
51201c3436cfSJed Brown /*@
51218a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51221c3436cfSJed Brown 
51231c3436cfSJed Brown    Collective on TS
51241c3436cfSJed Brown 
51254165533cSJose E. Roman    Input Parameters:
51261c3436cfSJed Brown +  ts - time stepping context
5127a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5128a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5129a4868fbcSLisandro Dalcin -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
51307619abb3SShri 
51314165533cSJose E. Roman    Output Parameters:
5132a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51338a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5134a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5135a4868fbcSLisandro Dalcin 
5136a4868fbcSLisandro Dalcin    Options Database Keys:
5137a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5138a4868fbcSLisandro Dalcin 
51391c3436cfSJed Brown    Level: developer
51401c3436cfSJed Brown 
5141db781477SPatrick Sanan .seealso: `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
51421c3436cfSJed Brown @*/
51437453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
51441c3436cfSJed Brown {
51451c3436cfSJed Brown   PetscFunctionBegin;
5146*1e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr));
5147*1e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr));
5148*1e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
51491c3436cfSJed Brown   PetscFunctionReturn(0);
51501c3436cfSJed Brown }
51511c3436cfSJed Brown 
51528a175baeSEmil Constantinescu /*@
51538a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
51548a175baeSEmil Constantinescu 
51558a175baeSEmil Constantinescu    Collective on TS
51568a175baeSEmil Constantinescu 
51574165533cSJose E. Roman    Input Parameters:
51588a175baeSEmil Constantinescu +  ts - time stepping context
51598a175baeSEmil Constantinescu .  E - error vector
51608a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
51618a175baeSEmil Constantinescu -  Y - state vector, previous time step
51628a175baeSEmil Constantinescu 
51634165533cSJose E. Roman    Output Parameters:
5164a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51658a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5166a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51678a175baeSEmil Constantinescu 
51688a175baeSEmil Constantinescu    Level: developer
51698a175baeSEmil Constantinescu 
5170db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
51718a175baeSEmil Constantinescu @*/
51728a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
51738a175baeSEmil Constantinescu {
51748a175baeSEmil Constantinescu   PetscInt          i,n,N,rstart;
51758a175baeSEmil Constantinescu   PetscInt          n_loc,na_loc,nr_loc;
51768a175baeSEmil Constantinescu   PetscReal         n_glb,na_glb,nr_glb;
51778a175baeSEmil Constantinescu   const PetscScalar *e,*u,*y;
51788a175baeSEmil Constantinescu   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
51798a175baeSEmil Constantinescu   PetscReal         tol,tola,tolr;
51808a175baeSEmil Constantinescu   PetscReal         err_loc[6],err_glb[6];
51818a175baeSEmil Constantinescu 
51828a175baeSEmil Constantinescu   PetscFunctionBegin;
51838a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
51848a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
51858a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
51868a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
51878a175baeSEmil Constantinescu   PetscValidType(E,2);
51888a175baeSEmil Constantinescu   PetscValidType(U,3);
51898a175baeSEmil Constantinescu   PetscValidType(Y,4);
51908a175baeSEmil Constantinescu   PetscCheckSameComm(E,2,U,3);
5191064a246eSJacob Faibussowitsch   PetscCheckSameComm(U,3,Y,4);
5192dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,5);
5193dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,6);
5194dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,7);
51958a175baeSEmil Constantinescu 
51969566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E,&N));
51979566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E,&n));
51989566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E,&rstart,NULL));
51999566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E,&e));
52009566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
52019566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
52028a175baeSEmil Constantinescu   sum  = 0.; n_loc  = 0;
52038a175baeSEmil Constantinescu   suma = 0.; na_loc = 0;
52048a175baeSEmil Constantinescu   sumr = 0.; nr_loc = 0;
52058a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
52068a175baeSEmil Constantinescu     const PetscScalar *atol,*rtol;
52079566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
52089566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
52098a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
521076cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
52118a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
52128a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52138a175baeSEmil Constantinescu       if (tola>0.) {
52148a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
52158a175baeSEmil Constantinescu         na_loc++;
52168a175baeSEmil Constantinescu       }
52178a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
52188a175baeSEmil Constantinescu       if (tolr>0.) {
52198a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
52208a175baeSEmil Constantinescu         nr_loc++;
52218a175baeSEmil Constantinescu       }
52228a175baeSEmil Constantinescu       tol=tola+tolr;
52238a175baeSEmil Constantinescu       if (tol>0.) {
52248a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
52258a175baeSEmil Constantinescu         n_loc++;
52268a175baeSEmil Constantinescu       }
52278a175baeSEmil Constantinescu     }
52289566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
52299566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
52308a175baeSEmil Constantinescu   } else if (ts->vatol) {       /* vector atol, scalar rtol */
52318a175baeSEmil Constantinescu     const PetscScalar *atol;
52329566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
52338a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
523476cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
52358a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
52368a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52378a175baeSEmil Constantinescu       if (tola>0.) {
52388a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
52398a175baeSEmil Constantinescu         na_loc++;
52408a175baeSEmil Constantinescu       }
52418a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
52428a175baeSEmil Constantinescu       if (tolr>0.) {
52438a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
52448a175baeSEmil Constantinescu         nr_loc++;
52458a175baeSEmil Constantinescu       }
52468a175baeSEmil Constantinescu       tol=tola+tolr;
52478a175baeSEmil Constantinescu       if (tol>0.) {
52488a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
52498a175baeSEmil Constantinescu         n_loc++;
52508a175baeSEmil Constantinescu       }
52518a175baeSEmil Constantinescu     }
52529566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
52538a175baeSEmil Constantinescu   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
52548a175baeSEmil Constantinescu     const PetscScalar *rtol;
52559566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
52568a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
525776cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
52588a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
52598a175baeSEmil Constantinescu       tola = ts->atol;
52608a175baeSEmil Constantinescu       if (tola>0.) {
52618a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
52628a175baeSEmil Constantinescu         na_loc++;
52638a175baeSEmil Constantinescu       }
52648a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
52658a175baeSEmil Constantinescu       if (tolr>0.) {
52668a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
52678a175baeSEmil Constantinescu         nr_loc++;
52688a175baeSEmil Constantinescu       }
52698a175baeSEmil Constantinescu       tol=tola+tolr;
52708a175baeSEmil Constantinescu       if (tol>0.) {
52718a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
52728a175baeSEmil Constantinescu         n_loc++;
52738a175baeSEmil Constantinescu       }
52748a175baeSEmil Constantinescu     }
52759566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
52768a175baeSEmil Constantinescu   } else {                      /* scalar atol, scalar rtol */
52778a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
527876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
52798a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
52808a175baeSEmil Constantinescu       tola = ts->atol;
52818a175baeSEmil Constantinescu       if (tola>0.) {
52828a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
52838a175baeSEmil Constantinescu         na_loc++;
52848a175baeSEmil Constantinescu       }
52858a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
52868a175baeSEmil Constantinescu       if (tolr>0.) {
52878a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
52888a175baeSEmil Constantinescu         nr_loc++;
52898a175baeSEmil Constantinescu       }
52908a175baeSEmil Constantinescu       tol=tola+tolr;
52918a175baeSEmil Constantinescu       if (tol>0.) {
52928a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
52938a175baeSEmil Constantinescu         n_loc++;
52948a175baeSEmil Constantinescu       }
52958a175baeSEmil Constantinescu     }
52968a175baeSEmil Constantinescu   }
52979566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E,&e));
52989566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
52999566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
53008a175baeSEmil Constantinescu 
53018a175baeSEmil Constantinescu   err_loc[0] = sum;
53028a175baeSEmil Constantinescu   err_loc[1] = suma;
53038a175baeSEmil Constantinescu   err_loc[2] = sumr;
53048a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
53058a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
53068a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
53078a175baeSEmil Constantinescu 
53081c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts)));
53098a175baeSEmil Constantinescu 
53108a175baeSEmil Constantinescu   gsum   = err_glb[0];
53118a175baeSEmil Constantinescu   gsuma  = err_glb[1];
53128a175baeSEmil Constantinescu   gsumr  = err_glb[2];
53138a175baeSEmil Constantinescu   n_glb  = err_glb[3];
53148a175baeSEmil Constantinescu   na_glb = err_glb[4];
53158a175baeSEmil Constantinescu   nr_glb = err_glb[5];
53168a175baeSEmil Constantinescu 
53178a175baeSEmil Constantinescu   *norm  = 0.;
5318*1e66621cSBarry Smith   if (n_glb>0.) *norm  = PetscSqrtReal(gsum  / n_glb);
53198a175baeSEmil Constantinescu   *norma = 0.;
5320*1e66621cSBarry Smith   if (na_glb>0.) *norma = PetscSqrtReal(gsuma / na_glb);
53218a175baeSEmil Constantinescu   *normr = 0.;
5322*1e66621cSBarry Smith   if (nr_glb>0.) *normr = PetscSqrtReal(gsumr / nr_glb);
53238a175baeSEmil Constantinescu 
53243c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
53253c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
53263c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
53278a175baeSEmil Constantinescu   PetscFunctionReturn(0);
53288a175baeSEmil Constantinescu }
53298a175baeSEmil Constantinescu 
53308a175baeSEmil Constantinescu /*@
53318a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
53328a175baeSEmil Constantinescu    Collective on TS
53338a175baeSEmil Constantinescu 
53344165533cSJose E. Roman    Input Parameters:
53358a175baeSEmil Constantinescu +  ts - time stepping context
53368a175baeSEmil Constantinescu .  E - error vector
53378a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
53388a175baeSEmil Constantinescu -  Y - state vector, previous time step
53398a175baeSEmil Constantinescu 
53404165533cSJose E. Roman    Output Parameters:
5341a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
53428a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5343a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
53448a175baeSEmil Constantinescu 
53458a175baeSEmil Constantinescu    Level: developer
53468a175baeSEmil Constantinescu 
5347db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
53488a175baeSEmil Constantinescu @*/
53498a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
53508a175baeSEmil Constantinescu {
53518a175baeSEmil Constantinescu   PetscInt          i,n,N,rstart;
53528a175baeSEmil Constantinescu   const PetscScalar *e,*u,*y;
53538a175baeSEmil Constantinescu   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
53548a175baeSEmil Constantinescu   PetscReal         tol,tola,tolr;
53558a175baeSEmil Constantinescu   PetscReal         err_loc[3],err_glb[3];
53568a175baeSEmil Constantinescu 
53578a175baeSEmil Constantinescu   PetscFunctionBegin;
53588a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
53598a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
53608a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
53618a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
53628a175baeSEmil Constantinescu   PetscValidType(E,2);
53638a175baeSEmil Constantinescu   PetscValidType(U,3);
53648a175baeSEmil Constantinescu   PetscValidType(Y,4);
53658a175baeSEmil Constantinescu   PetscCheckSameComm(E,2,U,3);
5366064a246eSJacob Faibussowitsch   PetscCheckSameComm(U,3,Y,4);
5367dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,5);
5368dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,6);
5369dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,7);
53708a175baeSEmil Constantinescu 
53719566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E,&N));
53729566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E,&n));
53739566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E,&rstart,NULL));
53749566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E,&e));
53759566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
53769566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
53778a175baeSEmil Constantinescu 
53788a175baeSEmil Constantinescu   max=0.;
53798a175baeSEmil Constantinescu   maxa=0.;
53808a175baeSEmil Constantinescu   maxr=0.;
53818a175baeSEmil Constantinescu 
53828a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
53838a175baeSEmil Constantinescu     const PetscScalar *atol,*rtol;
53849566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
53859566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
53868a175baeSEmil Constantinescu 
53878a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
538876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
53898a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
53908a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
53918a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
53928a175baeSEmil Constantinescu       tol  = tola+tolr;
5393*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,err / tola);
5394*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,err / tolr);
5395*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,err / tol);
53968a175baeSEmil Constantinescu     }
53979566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
53989566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
53998a175baeSEmil Constantinescu   } else if (ts->vatol) {       /* vector atol, scalar rtol */
54008a175baeSEmil Constantinescu     const PetscScalar *atol;
54019566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
54028a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
540376cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
54048a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
54058a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
54068a175baeSEmil Constantinescu       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
54078a175baeSEmil Constantinescu       tol  = tola+tolr;
5408*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,err / tola);
5409*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,err / tolr);
5410*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,err / tol);
54118a175baeSEmil Constantinescu     }
54129566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
54138a175baeSEmil Constantinescu   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
54148a175baeSEmil Constantinescu     const PetscScalar *rtol;
54159566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
54168a175baeSEmil Constantinescu 
54178a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
541876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
54198a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
54208a175baeSEmil Constantinescu       tola = ts->atol;
54218a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
54228a175baeSEmil Constantinescu       tol  = tola+tolr;
5423*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,err / tola);
5424*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,err / tolr);
5425*1e66621cSBarry Smith       if (tol>0.) max = PetscMax(max,err / tol);
54268a175baeSEmil Constantinescu     }
54279566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
54288a175baeSEmil Constantinescu   } else {                      /* scalar atol, scalar rtol */
54298a175baeSEmil Constantinescu 
54308a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
543176cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
54328a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
54338a175baeSEmil Constantinescu       tola = ts->atol;
54348a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
54358a175baeSEmil Constantinescu       tol  = tola+tolr;
5436*1e66621cSBarry Smith       if (tola>0.) maxa = PetscMax(maxa,err / tola);
5437*1e66621cSBarry Smith       if (tolr>0.) maxr = PetscMax(maxr,err / tolr);
5438*1e66621cSBarry Smith       if (tol>0.)  max = PetscMax(max,err / tol);
54398a175baeSEmil Constantinescu     }
54408a175baeSEmil Constantinescu   }
54419566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E,&e));
54429566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
54439566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
54448a175baeSEmil Constantinescu   err_loc[0] = max;
54458a175baeSEmil Constantinescu   err_loc[1] = maxa;
54468a175baeSEmil Constantinescu   err_loc[2] = maxr;
54471c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
54488a175baeSEmil Constantinescu   gmax   = err_glb[0];
54498a175baeSEmil Constantinescu   gmaxa  = err_glb[1];
54508a175baeSEmil Constantinescu   gmaxr  = err_glb[2];
54518a175baeSEmil Constantinescu 
54528a175baeSEmil Constantinescu   *norm = gmax;
54538a175baeSEmil Constantinescu   *norma = gmaxa;
54548a175baeSEmil Constantinescu   *normr = gmaxr;
54553c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
54563c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
54573c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
54588a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54598a175baeSEmil Constantinescu }
54608a175baeSEmil Constantinescu 
54618a175baeSEmil Constantinescu /*@
54628a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
54638a175baeSEmil Constantinescu 
54648a175baeSEmil Constantinescu    Collective on TS
54658a175baeSEmil Constantinescu 
54664165533cSJose E. Roman    Input Parameters:
54678a175baeSEmil Constantinescu +  ts - time stepping context
54688a175baeSEmil Constantinescu .  E - error vector
54698a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54708a175baeSEmil Constantinescu .  Y - state vector, previous time step
54718a175baeSEmil Constantinescu -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
54728a175baeSEmil Constantinescu 
54734165533cSJose E. Roman    Output Parameters:
5474a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
54758a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5476a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
54778a175baeSEmil Constantinescu 
54788a175baeSEmil Constantinescu    Options Database Keys:
54798a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
54808a175baeSEmil Constantinescu 
54818a175baeSEmil Constantinescu    Level: developer
54828a175baeSEmil Constantinescu 
5483db781477SPatrick Sanan .seealso: `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
54848a175baeSEmil Constantinescu @*/
54858a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
54868a175baeSEmil Constantinescu {
54878a175baeSEmil Constantinescu   PetscFunctionBegin;
5488*1e66621cSBarry Smith   if (wnormtype == NORM_2)PetscCall(TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr));
5489*1e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr));
5490*1e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
54918a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54928a175baeSEmil Constantinescu }
54938a175baeSEmil Constantinescu 
54948d59e960SJed Brown /*@
54958d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
54968d59e960SJed Brown 
54978d59e960SJed Brown    Logically Collective on TS
54988d59e960SJed Brown 
54994165533cSJose E. Roman    Input Parameters:
55008d59e960SJed Brown +  ts - time stepping context
55018d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
55028d59e960SJed Brown 
55038d59e960SJed Brown    Note:
55048d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
55058d59e960SJed Brown 
55068d59e960SJed Brown    Level: intermediate
55078d59e960SJed Brown 
5508db781477SPatrick Sanan .seealso: `TSGetCFLTime()`, `TSADAPTCFL`
55098d59e960SJed Brown @*/
55108d59e960SJed Brown PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
55118d59e960SJed Brown {
55128d59e960SJed Brown   PetscFunctionBegin;
55138d59e960SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
55148d59e960SJed Brown   ts->cfltime_local = cfltime;
55158d59e960SJed Brown   ts->cfltime       = -1.;
55168d59e960SJed Brown   PetscFunctionReturn(0);
55178d59e960SJed Brown }
55188d59e960SJed Brown 
55198d59e960SJed Brown /*@
55208d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
55218d59e960SJed Brown 
55228d59e960SJed Brown    Collective on TS
55238d59e960SJed Brown 
55244165533cSJose E. Roman    Input Parameter:
55258d59e960SJed Brown .  ts - time stepping context
55268d59e960SJed Brown 
55274165533cSJose E. Roman    Output Parameter:
55288d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
55298d59e960SJed Brown 
55308d59e960SJed Brown    Level: advanced
55318d59e960SJed Brown 
5532db781477SPatrick Sanan .seealso: `TSSetCFLTimeLocal()`
55338d59e960SJed Brown @*/
55348d59e960SJed Brown PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
55358d59e960SJed Brown {
55368d59e960SJed Brown   PetscFunctionBegin;
5537*1e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts)));
55388d59e960SJed Brown   *cfltime = ts->cfltime;
55398d59e960SJed Brown   PetscFunctionReturn(0);
55408d59e960SJed Brown }
55418d59e960SJed Brown 
5542d6ebe24aSShri Abhyankar /*@
5543d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5544d6ebe24aSShri Abhyankar 
5545d6ebe24aSShri Abhyankar    Input Parameters:
5546a2b725a8SWilliam Gropp +  ts   - the TS context.
5547d6ebe24aSShri Abhyankar .  xl   - lower bound.
5548a2b725a8SWilliam Gropp -  xu   - upper bound.
5549d6ebe24aSShri Abhyankar 
5550d6ebe24aSShri Abhyankar    Notes:
5551d6ebe24aSShri Abhyankar    If this routine is not called then the lower and upper bounds are set to
5552e270355aSBarry Smith    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
5553d6ebe24aSShri Abhyankar 
55542bd2b0e6SSatish Balay    Level: advanced
55552bd2b0e6SSatish Balay 
5556d6ebe24aSShri Abhyankar @*/
5557d6ebe24aSShri Abhyankar PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5558d6ebe24aSShri Abhyankar {
5559d6ebe24aSShri Abhyankar   SNES           snes;
5560d6ebe24aSShri Abhyankar 
5561d6ebe24aSShri Abhyankar   PetscFunctionBegin;
55629566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
55639566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes,xl,xu));
5564d6ebe24aSShri Abhyankar   PetscFunctionReturn(0);
5565d6ebe24aSShri Abhyankar }
5566d6ebe24aSShri Abhyankar 
5567f9c1d6abSBarry Smith /*@
5568f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5569f9c1d6abSBarry Smith 
5570d083f849SBarry Smith    Collective on TS
5571f9c1d6abSBarry Smith 
5572f9c1d6abSBarry Smith    Input Parameters:
5573f9c1d6abSBarry Smith +  ts - the TS context
5574f9c1d6abSBarry Smith -  xr,xi - real and imaginary part of input arguments
5575f9c1d6abSBarry Smith 
5576f9c1d6abSBarry Smith    Output Parameters:
5577f9c1d6abSBarry Smith .  yr,yi - real and imaginary part of function value
5578f9c1d6abSBarry Smith 
5579f9c1d6abSBarry Smith    Level: developer
5580f9c1d6abSBarry Smith 
5581db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
5582f9c1d6abSBarry Smith @*/
5583f9c1d6abSBarry Smith PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
5584f9c1d6abSBarry Smith {
5585f9c1d6abSBarry Smith   PetscFunctionBegin;
5586f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
55873c633725SBarry Smith   PetscCheck(ts->ops->linearstability,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
55889566063dSJacob Faibussowitsch   PetscCall((*ts->ops->linearstability)(ts,xr,xi,yr,yi));
5589f9c1d6abSBarry Smith   PetscFunctionReturn(0);
5590f9c1d6abSBarry Smith }
559124655328SShri 
559224655328SShri /*@
5593dcb233daSLisandro Dalcin    TSRestartStep - Flags the solver to restart the next step
5594dcb233daSLisandro Dalcin 
5595dcb233daSLisandro Dalcin    Collective on TS
5596dcb233daSLisandro Dalcin 
5597dcb233daSLisandro Dalcin    Input Parameter:
5598dcb233daSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
5599dcb233daSLisandro Dalcin 
5600dcb233daSLisandro Dalcin    Level: advanced
5601dcb233daSLisandro Dalcin 
5602dcb233daSLisandro Dalcin    Notes:
5603dcb233daSLisandro Dalcin    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5604dcb233daSLisandro Dalcin    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5605dcb233daSLisandro Dalcin    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5606dcb233daSLisandro Dalcin    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
5607dcb233daSLisandro Dalcin    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5608dcb233daSLisandro Dalcin    discontinuous source terms).
5609dcb233daSLisandro Dalcin 
5610db781477SPatrick Sanan .seealso: `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5611dcb233daSLisandro Dalcin @*/
5612dcb233daSLisandro Dalcin PetscErrorCode TSRestartStep(TS ts)
5613dcb233daSLisandro Dalcin {
5614dcb233daSLisandro Dalcin   PetscFunctionBegin;
5615dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5616dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
5617dcb233daSLisandro Dalcin   PetscFunctionReturn(0);
5618dcb233daSLisandro Dalcin }
5619dcb233daSLisandro Dalcin 
5620dcb233daSLisandro Dalcin /*@
562124655328SShri    TSRollBack - Rolls back one time step
562224655328SShri 
562324655328SShri    Collective on TS
562424655328SShri 
562524655328SShri    Input Parameter:
562624655328SShri .  ts - the TS context obtained from TSCreate()
562724655328SShri 
562824655328SShri    Level: advanced
562924655328SShri 
5630db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
563124655328SShri @*/
563224655328SShri PetscErrorCode  TSRollBack(TS ts)
563324655328SShri {
563424655328SShri   PetscFunctionBegin;
563524655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
56363c633725SBarry Smith   PetscCheck(!ts->steprollback,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
56373c633725SBarry Smith   PetscCheck(ts->ops->rollback,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
56389566063dSJacob Faibussowitsch   PetscCall((*ts->ops->rollback)(ts));
563924655328SShri   ts->time_step = ts->ptime - ts->ptime_prev;
564024655328SShri   ts->ptime = ts->ptime_prev;
5641be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
56422808aa04SLisandro Dalcin   ts->steps--;
5643b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
564424655328SShri   PetscFunctionReturn(0);
564524655328SShri }
5646aeb4809dSShri Abhyankar 
5647ff22ae23SHong Zhang /*@
5648ff22ae23SHong Zhang    TSGetStages - Get the number of stages and stage values
5649ff22ae23SHong Zhang 
5650ff22ae23SHong Zhang    Input Parameter:
5651ff22ae23SHong Zhang .  ts - the TS context obtained from TSCreate()
5652ff22ae23SHong Zhang 
56530429704eSStefano Zampini    Output Parameters:
56540429704eSStefano Zampini +  ns - the number of stages
56550429704eSStefano Zampini -  Y - the current stage vectors
56560429704eSStefano Zampini 
5657ff22ae23SHong Zhang    Level: advanced
5658ff22ae23SHong Zhang 
56590429704eSStefano Zampini    Notes: Both ns and Y can be NULL.
56600429704eSStefano Zampini 
5661db781477SPatrick Sanan .seealso: `TSCreate()`
5662ff22ae23SHong Zhang @*/
5663ff22ae23SHong Zhang PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
5664ff22ae23SHong Zhang {
5665ff22ae23SHong Zhang   PetscFunctionBegin;
5666ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5667dadcf809SJacob Faibussowitsch   if (ns) PetscValidIntPointer(ns,2);
56680429704eSStefano Zampini   if (Y) PetscValidPointer(Y,3);
56690429704eSStefano Zampini   if (!ts->ops->getstages) {
56700429704eSStefano Zampini     if (ns) *ns = 0;
56710429704eSStefano Zampini     if (Y) *Y = NULL;
5672*1e66621cSBarry Smith   } else PetscCall((*ts->ops->getstages)(ts,ns,Y));
5673ff22ae23SHong Zhang   PetscFunctionReturn(0);
5674ff22ae23SHong Zhang }
5675ff22ae23SHong Zhang 
5676847ff0e1SMatthew G. Knepley /*@C
5677847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5678847ff0e1SMatthew G. Knepley 
5679847ff0e1SMatthew G. Knepley   Collective on SNES
5680847ff0e1SMatthew G. Knepley 
5681847ff0e1SMatthew G. Knepley   Input Parameters:
5682847ff0e1SMatthew G. Knepley + ts - the TS context
5683847ff0e1SMatthew G. Knepley . t - current timestep
5684847ff0e1SMatthew G. Knepley . U - state vector
5685847ff0e1SMatthew G. Knepley . Udot - time derivative of state vector
5686847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5687847ff0e1SMatthew G. Knepley - ctx - an optional user context
5688847ff0e1SMatthew G. Knepley 
5689847ff0e1SMatthew G. Knepley   Output Parameters:
5690847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5691847ff0e1SMatthew G. Knepley - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
5692847ff0e1SMatthew G. Knepley 
5693847ff0e1SMatthew G. Knepley   Level: intermediate
5694847ff0e1SMatthew G. Knepley 
5695847ff0e1SMatthew G. Knepley   Notes:
5696847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5697847ff0e1SMatthew G. Knepley 
5698847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5699847ff0e1SMatthew G. Knepley 
5700847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5701847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5702847ff0e1SMatthew G. Knepley 
5703847ff0e1SMatthew G. Knepley   This will first try to get the coloring from the DM.  If the DM type has no coloring
5704847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5705847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5706847ff0e1SMatthew G. Knepley 
5707db781477SPatrick Sanan .seealso: `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5708847ff0e1SMatthew G. Knepley @*/
5709847ff0e1SMatthew G. Knepley PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
5710847ff0e1SMatthew G. Knepley {
5711847ff0e1SMatthew G. Knepley   SNES           snes;
5712847ff0e1SMatthew G. Knepley   MatFDColoring  color;
5713847ff0e1SMatthew G. Knepley   PetscBool      hascolor, matcolor = PETSC_FALSE;
5714847ff0e1SMatthew G. Knepley 
5715847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
57169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
57179566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color));
5718847ff0e1SMatthew G. Knepley   if (!color) {
5719847ff0e1SMatthew G. Knepley     DM         dm;
5720847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5721847ff0e1SMatthew G. Knepley 
57229566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
57239566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5724847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
57259566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
57269566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57279566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts));
57289566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57299566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57309566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5731847ff0e1SMatthew G. Knepley     } else {
5732847ff0e1SMatthew G. Knepley       MatColoring mc;
5733847ff0e1SMatthew G. Knepley 
57349566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
57359566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
57369566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
57379566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
57389566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
57399566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
57409566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57419566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts));
57429566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57439566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57449566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5745847ff0e1SMatthew G. Knepley     }
57469566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color));
57479566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject) color));
5748847ff0e1SMatthew G. Knepley   }
57499566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
57509566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5751847ff0e1SMatthew G. Knepley   if (J != B) {
57529566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
57539566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5754847ff0e1SMatthew G. Knepley   }
5755847ff0e1SMatthew G. Knepley   PetscFunctionReturn(0);
5756847ff0e1SMatthew G. Knepley }
575793b34091SDebojyoti Ghosh 
5758cb9d8021SPierre Barbier de Reuille /*@
57596bc98fa9SBarry Smith     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5760cb9d8021SPierre Barbier de Reuille 
5761cb9d8021SPierre Barbier de Reuille     Input Parameters:
57626bc98fa9SBarry Smith +    ts - the TS context
57636bc98fa9SBarry Smith -    func - function called within TSFunctionDomainError
57646bc98fa9SBarry Smith 
57656bc98fa9SBarry Smith     Calling sequence of func:
57666bc98fa9SBarry Smith $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
57676bc98fa9SBarry Smith 
57686bc98fa9SBarry Smith +   ts - the TS context
57696bc98fa9SBarry Smith .   time - the current time (of the stage)
57706bc98fa9SBarry Smith .   state - the state to check if it is valid
57716bc98fa9SBarry Smith -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
5772cb9d8021SPierre Barbier de Reuille 
5773cb9d8021SPierre Barbier de Reuille     Level: intermediate
5774cb9d8021SPierre Barbier de Reuille 
57756bc98fa9SBarry Smith     Notes:
57766bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
57776bc98fa9SBarry Smith       user's code should call SNESSetFunctionDomainError() when domain errors occur during
57786bc98fa9SBarry Smith       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
57796bc98fa9SBarry Smith       Use TSGetSNES() to obtain the SNES object
57806bc98fa9SBarry Smith 
57816bc98fa9SBarry Smith     Developer Notes:
57826bc98fa9SBarry Smith       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
57836bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
57846bc98fa9SBarry Smith 
5785db781477SPatrick Sanan .seealso: `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5786cb9d8021SPierre Barbier de Reuille @*/
5787cb9d8021SPierre Barbier de Reuille 
5788d183316bSPierre Barbier de Reuille PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
5789cb9d8021SPierre Barbier de Reuille {
5790cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5791cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5792cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
5793cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5794cb9d8021SPierre Barbier de Reuille }
5795cb9d8021SPierre Barbier de Reuille 
5796cb9d8021SPierre Barbier de Reuille /*@
57976bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5798cb9d8021SPierre Barbier de Reuille 
5799cb9d8021SPierre Barbier de Reuille     Input Parameters:
58006bc98fa9SBarry Smith +    ts - the TS context
58016bc98fa9SBarry Smith .    stagetime - time of the simulation
58026bc98fa9SBarry Smith -    Y - state vector to check.
5803cb9d8021SPierre Barbier de Reuille 
5804cb9d8021SPierre Barbier de Reuille     Output Parameter:
58056bc98fa9SBarry Smith .    accept - Set to PETSC_FALSE if the current state vector is valid.
5806cb9d8021SPierre Barbier de Reuille 
5807cb9d8021SPierre Barbier de Reuille     Note:
58086bc98fa9SBarry Smith     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
58096bc98fa9SBarry Smith     to check if the current state is valid.
581096a0c994SBarry Smith 
58116bc98fa9SBarry Smith     Level: developer
58126bc98fa9SBarry Smith 
5813db781477SPatrick Sanan .seealso: `TSSetFunctionDomainError()`
5814cb9d8021SPierre Barbier de Reuille @*/
5815d183316bSPierre Barbier de Reuille PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
5816cb9d8021SPierre Barbier de Reuille {
5817cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5818cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5819cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
5820*1e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts,stagetime,Y,accept));
5821cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5822cb9d8021SPierre Barbier de Reuille }
58231ceb14c0SBarry Smith 
582493b34091SDebojyoti Ghosh /*@C
5825e5168f73SEmil Constantinescu   TSClone - This function clones a time step object.
582693b34091SDebojyoti Ghosh 
5827d083f849SBarry Smith   Collective
582893b34091SDebojyoti Ghosh 
582993b34091SDebojyoti Ghosh   Input Parameter:
583093b34091SDebojyoti Ghosh . tsin    - The input TS
583193b34091SDebojyoti Ghosh 
583293b34091SDebojyoti Ghosh   Output Parameter:
5833e5168f73SEmil Constantinescu . tsout   - The output TS (cloned)
583493b34091SDebojyoti Ghosh 
58355eca1a21SEmil Constantinescu   Notes:
58365eca1a21SEmil Constantinescu   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.
58375eca1a21SEmil Constantinescu 
5838928bb9adSStefano Zampini   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);
58395eca1a21SEmil Constantinescu 
58405eca1a21SEmil Constantinescu   Level: developer
584193b34091SDebojyoti Ghosh 
5842db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
584393b34091SDebojyoti Ghosh @*/
5844baa10174SEmil Constantinescu PetscErrorCode  TSClone(TS tsin, TS *tsout)
584593b34091SDebojyoti Ghosh {
584693b34091SDebojyoti Ghosh   TS             t;
5847dc846ba4SSatish Balay   SNES           snes_start;
5848dc846ba4SSatish Balay   DM             dm;
5849dc846ba4SSatish Balay   TSType         type;
585093b34091SDebojyoti Ghosh 
585193b34091SDebojyoti Ghosh   PetscFunctionBegin;
585293b34091SDebojyoti Ghosh   PetscValidPointer(tsin,1);
585393b34091SDebojyoti Ghosh   *tsout = NULL;
585493b34091SDebojyoti Ghosh 
58559566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
585693b34091SDebojyoti Ghosh 
585793b34091SDebojyoti Ghosh   /* General TS description */
585893b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5859d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
586093b34091SDebojyoti Ghosh   t->setupcalled       = 0;
586193b34091SDebojyoti Ghosh   t->ksp_its           = 0;
586293b34091SDebojyoti Ghosh   t->snes_its          = 0;
586393b34091SDebojyoti Ghosh   t->nwork             = 0;
58647d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
586593b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
586693b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
586793b34091SDebojyoti Ghosh 
58689566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin,&snes_start));
58699566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t,snes_start));
5870d15a3a53SEmil Constantinescu 
58719566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin,&dm));
58729566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t,dm));
587393b34091SDebojyoti Ghosh 
587493b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
58759566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
587693b34091SDebojyoti Ghosh 
5877e7069c78SShri   t->trajectory = tsin->trajectory;
58789566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5879e7069c78SShri 
5880e7069c78SShri   t->event = tsin->event;
58816b10a48eSSatish Balay   if (t->event) t->event->refct++;
5882e7069c78SShri 
588393b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
588493b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5885e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
588693b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
588793b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
588893b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
588993b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
589093b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
589193b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
589293b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
589393b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
589493b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
589593b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
589693b34091SDebojyoti Ghosh 
58979566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin,&type));
58989566063dSJacob Faibussowitsch   PetscCall(TSSetType(t,type));
589993b34091SDebojyoti Ghosh 
590093b34091SDebojyoti Ghosh   t->vec_sol           = NULL;
590193b34091SDebojyoti Ghosh 
590293b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
590393b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
590493b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
590593b34091SDebojyoti Ghosh 
59069566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps)));
590793b34091SDebojyoti Ghosh 
59080d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
59090d4fed19SBarry Smith     PetscInt i;
59109566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers));
59110d4fed19SBarry Smith     for (i=0; i<10; i++) {
59120d4fed19SBarry Smith       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
59130d4fed19SBarry Smith     }
59140d4fed19SBarry Smith   }
591593b34091SDebojyoti Ghosh   *tsout = t;
591693b34091SDebojyoti Ghosh   PetscFunctionReturn(0);
591793b34091SDebojyoti Ghosh }
5918f3b1f45cSBarry Smith 
5919f3b1f45cSBarry Smith static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
5920f3b1f45cSBarry Smith {
5921f3b1f45cSBarry Smith   TS             ts = (TS) ctx;
5922f3b1f45cSBarry Smith 
5923f3b1f45cSBarry Smith   PetscFunctionBegin;
59249566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts,0,x,y));
5925f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5926f3b1f45cSBarry Smith }
5927f3b1f45cSBarry Smith 
5928f3b1f45cSBarry Smith /*@
5929f3b1f45cSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.
5930f3b1f45cSBarry Smith 
5931d083f849SBarry Smith    Logically Collective on TS
5932f3b1f45cSBarry Smith 
5933f3b1f45cSBarry Smith     Input Parameters:
5934f3b1f45cSBarry Smith     TS - the time stepping routine
5935f3b1f45cSBarry Smith 
5936f3b1f45cSBarry Smith    Output Parameter:
5937f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
5938f3b1f45cSBarry Smith 
5939f3b1f45cSBarry Smith    Options Database:
5940f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5941f3b1f45cSBarry Smith 
5942f3b1f45cSBarry Smith    Level: advanced
5943f3b1f45cSBarry Smith 
594495452b02SPatrick Sanan    Notes:
594595452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5946f3b1f45cSBarry Smith 
5947db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5948f3b1f45cSBarry Smith @*/
5949f3b1f45cSBarry Smith PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
5950f3b1f45cSBarry Smith {
5951f3b1f45cSBarry Smith   Mat            J,B;
5952f3b1f45cSBarry Smith   TSRHSJacobian  func;
5953f3b1f45cSBarry Smith   void*          ctx;
5954f3b1f45cSBarry Smith 
5955f3b1f45cSBarry Smith   PetscFunctionBegin;
59569566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,&J,&B,&func,&ctx));
59579566063dSJacob Faibussowitsch   PetscCall((*func)(ts,0.0,ts->vec_sol,J,B,ctx));
59589566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg));
5959f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5960f3b1f45cSBarry Smith }
5961f3b1f45cSBarry Smith 
5962f3b1f45cSBarry Smith /*@C
5963f3b1f45cSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.
5964f3b1f45cSBarry Smith 
5965d083f849SBarry Smith    Logically Collective on TS
5966f3b1f45cSBarry Smith 
5967f3b1f45cSBarry Smith     Input Parameters:
5968f3b1f45cSBarry Smith     TS - the time stepping routine
5969f3b1f45cSBarry Smith 
5970f3b1f45cSBarry Smith    Output Parameter:
5971f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
5972f3b1f45cSBarry Smith 
5973f3b1f45cSBarry Smith    Options Database:
5974f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5975f3b1f45cSBarry Smith 
597695452b02SPatrick Sanan    Notes:
597795452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5978f3b1f45cSBarry Smith 
5979f3b1f45cSBarry Smith    Level: advanced
5980f3b1f45cSBarry Smith 
5981db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5982f3b1f45cSBarry Smith @*/
5983f3b1f45cSBarry Smith PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
5984f3b1f45cSBarry Smith {
5985f3b1f45cSBarry Smith   Mat            J,B;
5986f3b1f45cSBarry Smith   void           *ctx;
5987f3b1f45cSBarry Smith   TSRHSJacobian  func;
5988f3b1f45cSBarry Smith 
5989f3b1f45cSBarry Smith   PetscFunctionBegin;
59909566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,&J,&B,&func,&ctx));
59919566063dSJacob Faibussowitsch   PetscCall((*func)(ts,0.0,ts->vec_sol,J,B,ctx));
59929566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg));
5993f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5994f3b1f45cSBarry Smith }
59950fe4d17eSHong Zhang 
59960fe4d17eSHong Zhang /*@
59970fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
59980fe4d17eSHong Zhang 
59990fe4d17eSHong Zhang   Logically collective
60000fe4d17eSHong Zhang 
6001d8d19677SJose E. Roman   Input Parameters:
60020fe4d17eSHong Zhang +  ts - timestepping context
60030fe4d17eSHong Zhang -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
60040fe4d17eSHong Zhang 
60050fe4d17eSHong Zhang   Options Database:
60060fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
60070fe4d17eSHong Zhang 
60080fe4d17eSHong Zhang   Notes:
60090fe4d17eSHong Zhang     This is only useful for multirate methods
60100fe4d17eSHong Zhang 
60110fe4d17eSHong Zhang   Level: intermediate
60120fe4d17eSHong Zhang 
6013db781477SPatrick Sanan .seealso: `TSGetUseSplitRHSFunction()`
60140fe4d17eSHong Zhang @*/
60150fe4d17eSHong Zhang PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
60160fe4d17eSHong Zhang {
60170fe4d17eSHong Zhang   PetscFunctionBegin;
60180fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
60190fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
60200fe4d17eSHong Zhang   PetscFunctionReturn(0);
60210fe4d17eSHong Zhang }
60220fe4d17eSHong Zhang 
60230fe4d17eSHong Zhang /*@
60240fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
60250fe4d17eSHong Zhang 
60260fe4d17eSHong Zhang   Not collective
60270fe4d17eSHong Zhang 
60280fe4d17eSHong Zhang   Input Parameter:
60290fe4d17eSHong Zhang .  ts - timestepping context
60300fe4d17eSHong Zhang 
60310fe4d17eSHong Zhang   Output Parameter:
60320fe4d17eSHong Zhang .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
60330fe4d17eSHong Zhang 
60340fe4d17eSHong Zhang   Level: intermediate
60350fe4d17eSHong Zhang 
6036db781477SPatrick Sanan .seealso: `TSSetUseSplitRHSFunction()`
60370fe4d17eSHong Zhang @*/
60380fe4d17eSHong Zhang PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
60390fe4d17eSHong Zhang {
60400fe4d17eSHong Zhang   PetscFunctionBegin;
60410fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
60420fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
60430fe4d17eSHong Zhang   PetscFunctionReturn(0);
60440fe4d17eSHong Zhang }
6045d60b7d5cSBarry Smith 
6046d60b7d5cSBarry Smith /*@
6047d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6048d60b7d5cSBarry Smith 
6049d60b7d5cSBarry Smith    Logically  Collective on ts
6050d60b7d5cSBarry Smith 
6051d60b7d5cSBarry Smith    Input Parameters:
6052d60b7d5cSBarry Smith +  ts - the time-stepper
6053d60b7d5cSBarry Smith -  str - the structure (the default is UNKNOWN_NONZERO_PATTERN)
6054d60b7d5cSBarry Smith 
6055d60b7d5cSBarry Smith    Level: intermediate
6056d60b7d5cSBarry Smith 
6057d60b7d5cSBarry Smith    Notes:
6058d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6059d60b7d5cSBarry Smith 
6060db781477SPatrick Sanan .seealso: `MatAXPY()`, `MatStructure`
6061d60b7d5cSBarry Smith  @*/
6062d60b7d5cSBarry Smith PetscErrorCode TSSetMatStructure(TS ts,MatStructure str)
6063d60b7d5cSBarry Smith {
6064d60b7d5cSBarry Smith   PetscFunctionBegin;
6065d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6066d60b7d5cSBarry Smith   ts->axpy_pattern = str;
6067d60b7d5cSBarry Smith   PetscFunctionReturn(0);
6068d60b7d5cSBarry Smith }
60694a658b32SHong Zhang 
60704a658b32SHong Zhang /*@
60714a658b32SHong Zhang   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested.
60724a658b32SHong Zhang 
60734a658b32SHong Zhang   Collective on ts
60744a658b32SHong Zhang 
60754a658b32SHong Zhang   Input Parameters:
60764a658b32SHong Zhang + ts - the time-stepper
60774a658b32SHong Zhang . n - number of the time points (>=2)
60784a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60794a658b32SHong Zhang 
60804a658b32SHong Zhang   Options Database Keys:
60814a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
60824a658b32SHong Zhang 
60834a658b32SHong Zhang   Level: beginner
60844a658b32SHong Zhang 
60854a658b32SHong Zhang   Notes:
60864a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
60874a658b32SHong Zhang   TS_EXACTFINALTIME_MATCHSTEP must be used to make the last time step in each sub-interval match the intermediate points specified.
60884a658b32SHong Zhang   The intermediate solutions are saved in a vector array that can be accessed with TSGetSolutions(). Thus using time span may
60894a658b32SHong Zhang   pressure the memory system when using a large number of span points.
60904a658b32SHong Zhang 
6091c2e3fba1SPatrick Sanan .seealso: `TSGetTimeSpan()`, `TSGetSolutions()`
60924a658b32SHong Zhang  @*/
60934a658b32SHong Zhang PetscErrorCode TSSetTimeSpan(TS ts,PetscInt n,PetscReal *span_times)
60944a658b32SHong Zhang {
60954a658b32SHong Zhang   PetscFunctionBegin;
60964a658b32SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
609763a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Minimum time span size is 2 but %" PetscInt_FMT " is provided",n);
60984a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
60994a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
61004a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times,&ts->tspan->vecs_sol));
61014a658b32SHong Zhang     PetscCall(PetscMalloc1(n,&ts->tspan->span_times));
61024a658b32SHong Zhang   }
61034a658b32SHong Zhang   if (!ts->tspan) {
61044a658b32SHong Zhang     TSTimeSpan tspan;
61054a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
61064a658b32SHong Zhang     PetscCall(PetscMalloc1(n,&tspan->span_times));
6107e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6108e1db57b0SHong Zhang     tspan->abstol = 10*PETSC_MACHINE_EPSILON;
61094a658b32SHong Zhang     ts->tspan = tspan;
61104a658b32SHong Zhang   }
61114a658b32SHong Zhang   ts->tspan->num_span_times = n;
61124a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times,span_times,n));
61134a658b32SHong Zhang   PetscCall(TSSetTime(ts,ts->tspan->span_times[0]));
61144a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts,ts->tspan->span_times[n-1]));
61154a658b32SHong Zhang   PetscFunctionReturn(0);
61164a658b32SHong Zhang }
61174a658b32SHong Zhang 
61184a658b32SHong Zhang /*@C
61194a658b32SHong Zhang   TSGetTimeSpan - gets the time span.
61204a658b32SHong Zhang 
61214a658b32SHong Zhang   Not Collective
61224a658b32SHong Zhang 
61234a658b32SHong Zhang   Input Parameter:
61244a658b32SHong Zhang . ts - the time-stepper
61254a658b32SHong Zhang 
61264a658b32SHong Zhang   Output Parameters:
61274a658b32SHong Zhang + n - number of the time points (>=2)
61284a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively. The values are valid until the TS object is destroyed.
61294a658b32SHong Zhang 
61304a658b32SHong Zhang   Level: beginner
61314a658b32SHong Zhang   Notes: Both n and span_times can be NULL.
61324a658b32SHong Zhang 
6133c2e3fba1SPatrick Sanan .seealso: `TSSetTimeSpan()`, `TSGetSolutions()`
61344a658b32SHong Zhang  @*/
61354a658b32SHong Zhang PetscErrorCode TSGetTimeSpan(TS ts,PetscInt *n,const PetscReal **span_times)
61364a658b32SHong Zhang {
61374a658b32SHong Zhang   PetscFunctionBegin;
61384a658b32SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
61394a658b32SHong Zhang   if (n) PetscValidIntPointer(n,2);
61404a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times,3);
61414a658b32SHong Zhang   if (!ts->tspan) {
61424a658b32SHong Zhang     if (n) *n = 0;
61434a658b32SHong Zhang     if (span_times) *span_times = NULL;
61444a658b32SHong Zhang   } else {
61454a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
61464a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
61474a658b32SHong Zhang   }
61484a658b32SHong Zhang   PetscFunctionReturn(0);
61494a658b32SHong Zhang }
61504a658b32SHong Zhang 
61514a658b32SHong Zhang /*@
61524a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
61534a658b32SHong Zhang 
61544a658b32SHong Zhang    Input Parameter:
61554a658b32SHong Zhang .  ts - the TS context obtained from TSCreate()
61564a658b32SHong Zhang 
61574a658b32SHong Zhang    Output Parameters:
61584a658b32SHong Zhang +  nsol - the number of solutions
61594a658b32SHong Zhang -  Sols - the solution vectors
61604a658b32SHong Zhang 
61614a658b32SHong Zhang    Level: beginner
61624a658b32SHong Zhang 
616340bd4cedSHong Zhang    Notes:
616440bd4cedSHong Zhang     Both nsol and Sols can be NULL.
616540bd4cedSHong Zhang     Some time points in the time span may be skipped by TS so that nsol is less than the number of points specified by TSSetTimeSpan(). For example, manipulating the step size, especially with a reduced precision, may cause TS to step over certain points in the span.
61664a658b32SHong Zhang 
6167db781477SPatrick Sanan .seealso: `TSSetTimeSpan()`
61684a658b32SHong Zhang @*/
61694a658b32SHong Zhang PetscErrorCode TSGetTimeSpanSolutions(TS ts,PetscInt *nsol,Vec **Sols)
61704a658b32SHong Zhang {
61714a658b32SHong Zhang   PetscFunctionBegin;
61724a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
61734a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol,2);
61744a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols,3);
61754a658b32SHong Zhang   if (!ts->tspan) {
61764a658b32SHong Zhang     if (nsol) *nsol = 0;
61774a658b32SHong Zhang     if (Sols) *Sols = NULL;
61784a658b32SHong Zhang   } else {
617940bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
61804a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
61814a658b32SHong Zhang   }
61824a658b32SHong Zhang   PetscFunctionReturn(0);
61834a658b32SHong Zhang }
6184