xref: /petsc/src/ts/interface/ts.c (revision e1db57b00ec97ce1e7dbc3914c7d12e8c5b5b2ae)
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);
212ffb9264SLisandro Dalcin   if (!((PetscObject)adapt)->type_name) {
229566063dSJacob Faibussowitsch     PetscCall(TSAdaptSetType(adapt,default_type));
232ffb9264SLisandro Dalcin   }
242ffb9264SLisandro Dalcin   PetscFunctionReturn(0);
252ffb9264SLisandro Dalcin }
262ffb9264SLisandro Dalcin 
27bdad233fSMatthew Knepley /*@
28bdad233fSMatthew Knepley    TSSetFromOptions - Sets various TS parameters from user options.
29bdad233fSMatthew Knepley 
30bdad233fSMatthew Knepley    Collective on TS
31bdad233fSMatthew Knepley 
32bdad233fSMatthew Knepley    Input Parameter:
33bdad233fSMatthew Knepley .  ts - the TS context obtained from TSCreate()
34bdad233fSMatthew Knepley 
35bdad233fSMatthew Knepley    Options Database Keys:
36d2567f34SHong Zhang +  -ts_type <type> - TSEULER, TSBEULER, TSSUNDIALS, TSPSEUDO, TSCN, TSRK, TSTHETA, TSALPHA, TSGLLE, TSSSP, TSGLEE, TSBSYMP, TSIRK
37ef222394SBarry Smith .  -ts_save_trajectory - checkpoint the solution at each time-step
38ef85077eSLisandro Dalcin .  -ts_max_time <time> - maximum time to compute to
394a658b32SHong Zhang .  -ts_time_span <t0,...tf> - sets the time span, solutions are computed and stored for each indicated time
40ef85077eSLisandro Dalcin .  -ts_max_steps <steps> - maximum number of time-steps to take
41ef85077eSLisandro Dalcin .  -ts_init_time <time> - initial time to start computation
424dc72f7fSBarry Smith .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
433e4cdcaaSBarry Smith .  -ts_dt <dt> - initial time step
441628793fSSatish 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
45a3cdaa26SBarry Smith .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
46a3cdaa26SBarry Smith .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
47a3cdaa26SBarry Smith .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
48a3cdaa26SBarry Smith .  -ts_rtol <rtol> - relative tolerance for local truncation error
4967b8a455SSatish Balay .  -ts_atol <atol> - Absolute tolerance for local truncation error
50f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
51f3b1f45cSBarry 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
5267b8a455SSatish Balay .  -ts_adjoint_solve <yes,no> - After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
53847ff0e1SMatthew G. Knepley .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
54bdad233fSMatthew Knepley .  -ts_monitor - print information at each timestep
55aee7a9fbSMatthew G. Knepley .  -ts_monitor_cancel - Cancel all monitors
56de06c3feSJed Brown .  -ts_monitor_lg_solution - Monitor solution graphically
57de06c3feSJed Brown .  -ts_monitor_lg_error - Monitor error graphically
587cf37e64SBarry Smith .  -ts_monitor_error - Monitors norm of error
596934998bSLisandro Dalcin .  -ts_monitor_lg_timestep - Monitor timestep size graphically
608b668821SLisandro Dalcin .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
61de06c3feSJed Brown .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
62de06c3feSJed Brown .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
63de06c3feSJed Brown .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
64de06c3feSJed Brown .  -ts_monitor_draw_solution - Monitor solution graphically
653e4cdcaaSBarry Smith .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
663e4cdcaaSBarry Smith .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
67fde5950dSBarry Smith .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
6863a3b9bcSJacob 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)
699e336e28SPatrick Sanan -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
7053ea634cSHong Zhang 
713d5a8a6aSBarry Smith    Notes:
723d5a8a6aSBarry Smith      See SNESSetFromOptions() and KSPSetFromOptions() for how to control the nonlinear and linear solves used by the time-stepper.
733d5a8a6aSBarry Smith 
743d5a8a6aSBarry Smith      Certain SNES options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
753d5a8a6aSBarry Smith      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
763d5a8a6aSBarry Smith      -snes_lag_preconditioner_persists true
773d5a8a6aSBarry Smith 
789e336e28SPatrick Sanan    Developer Note:
799e336e28SPatrick Sanan      We should unify all the -ts_monitor options in the way that -xxx_view has been unified
80bdad233fSMatthew Knepley 
81bdad233fSMatthew Knepley    Level: beginner
82bdad233fSMatthew Knepley 
83db781477SPatrick Sanan .seealso: `TSGetType()`
84bdad233fSMatthew Knepley @*/
857087cfbeSBarry Smith PetscErrorCode  TSSetFromOptions(TS ts)
86bdad233fSMatthew Knepley {
87bc952696SBarry Smith   PetscBool              opt,flg,tflg;
88eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
894a658b32SHong Zhang   PetscReal              time_step,tspan[100];
904a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9149354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
92d1212d36SBarry Smith   char                   dir[16];
93cd11d68dSLisandro Dalcin   TSIFunction            ifun;
946991f827SBarry Smith   const char             *defaultType;
956991f827SBarry Smith   char                   typeName[256];
96bdad233fSMatthew Knepley 
97bdad233fSMatthew Knepley   PetscFunctionBegin;
980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
996991f827SBarry Smith 
1009566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1019566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts,NULL,&ifun,NULL));
102cd11d68dSLisandro Dalcin 
103d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1041ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1051ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type","TS method","TSSetType",TSList,defaultType,typeName,256,&opt));
1076991f827SBarry Smith   if (opt) {
1089566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts,typeName));
1096991f827SBarry Smith   } else {
1109566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts,defaultType));
1116991f827SBarry Smith   }
112bdad233fSMatthew Knepley 
113bdad233fSMatthew Knepley   /* Handle generic TS options */
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time","-ts_max_time","3.10",NULL));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time","Maximum time to run to","TSSetMaxTime",ts->max_time,&ts->max_time,NULL));
1164a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span","Time span","TSSetTimeSpan",tspan,&nt,&flg));
1174a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts,nt,tspan));
1189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps","Maximum number of time steps","TSSetMaxSteps",ts->max_steps,&ts->max_steps,NULL));
1199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time","Initial time","TSSetTime",ts->ptime,&ts->ptime,NULL));
1209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt","Initial time step","TSSetTimeStep",ts->time_step,&time_step,&flg));
1219566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts,time_step));
1229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time","Option for handling of final time step","TSSetExactFinalTime",TSExactFinalTimeOptions,(PetscEnum)ts->exact_final_time,(PetscEnum*)&eftopt,&flg));
1239566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts,eftopt));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures","Maximum number of nonlinear solve failures","TSSetMaxSNESFailures",ts->max_snes_failures,&ts->max_snes_failures,NULL));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject","Maximum number of step rejections before step fails","TSSetMaxStepRejections",ts->max_reject,&ts->max_reject,NULL));
1269566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails","Error if no step succeeds","TSSetErrorIfStepFails",ts->errorifstepfailed,&ts->errorifstepfailed,NULL));
1279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol","Relative tolerance for local truncation error","TSSetTolerances",ts->rtol,&ts->rtol,NULL));
1289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol","Absolute tolerance for local truncation error","TSSetTolerances",ts->atol,&ts->atol,NULL));
129bdad233fSMatthew Knepley 
1309566063dSJacob 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));
1319566063dSJacob 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));
1329566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction","Use the split RHS function for multirate solvers ","TSSetUseSplitRHSFunction",ts->use_splitrhsfunction,&ts->use_splitrhsfunction,NULL));
13356f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13456f85f32SBarry Smith   {
13556f85f32SBarry Smith     PetscBool set;
13656f85f32SBarry Smith     flg  = PETSC_FALSE;
1379566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block","Block for SAWs memory snooper at end of TSSolve","PetscObjectSAWsBlock",((PetscObject)ts)->amspublishblock,&flg,&set));
1381baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts,flg));
13956f85f32SBarry Smith   }
14056f85f32SBarry Smith #endif
14156f85f32SBarry Smith 
142bdad233fSMatthew Knepley   /* Monitor options */
1439566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1449566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor","Monitor time and timestep size","TSMonitorDefault",TSMonitorDefault,NULL));
1459566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_extreme","Monitor extreme values of the solution","TSMonitorExtreme",TSMonitorExtreme,NULL));
1469566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_solution","View the solution at each timestep","TSMonitorSolution",TSMonitorSolution,NULL));
1479566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_dmswarm_monitor_moments","Monitor moments of particle distribution","TSDMSwarmMonitorMoments",TSDMSwarmMonitorMoments,NULL));
148fde5950dSBarry Smith 
1499566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python","Use Python function","TSMonitorSet",NULL,monfilename,sizeof(monfilename),&flg));
1509566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts,monfilename));
1515180491cSLisandro Dalcin 
1529566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",&opt));
153b3603a34SBarry Smith   if (opt) {
1543923b477SBarry Smith     PetscInt       howoften = 1;
155e669de00SBarry Smith     DM             dm;
156e669de00SBarry Smith     PetscBool      net;
157b3603a34SBarry Smith 
1589566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution","Monitor solution graphically","TSMonitorLGSolution",howoften,&howoften,NULL));
1599566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts,&dm));
1609566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm,DMNETWORK,&net));
161e669de00SBarry Smith     if (net) {
162e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1639566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&ctx));
1649566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts,TSMonitorLGCtxNetworkSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxNetworkDestroy));
1659566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy","Plot the solution with a semi-log axis","",ctx->semilogy,&ctx->semilogy,NULL));
166e669de00SBarry Smith     } else {
167e669de00SBarry Smith       TSMonitorLGCtx ctx;
1689566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1699566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts,TSMonitorLGSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
170bdad233fSMatthew Knepley     }
171e669de00SBarry Smith   }
1726ba87a44SLisandro Dalcin 
1739566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",&opt));
174ef20d060SBarry Smith   if (opt) {
1750b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1763923b477SBarry Smith     PetscInt       howoften = 1;
177ef20d060SBarry Smith 
1789566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error","Monitor error graphically","TSMonitorLGError",howoften,&howoften,NULL));
1799566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1809566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGError,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
181ef20d060SBarry Smith   }
1829566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts,"-ts_monitor_error","View the error at each timestep","TSMonitorError",TSMonitorError,NULL));
1837cf37e64SBarry Smith 
1849566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",&opt));
1856934998bSLisandro Dalcin   if (opt) {
1866934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1876934998bSLisandro Dalcin     PetscInt       howoften = 1;
1886934998bSLisandro Dalcin 
1899566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep","Monitor timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL));
1909566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
1919566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
1926934998bSLisandro Dalcin   }
1939566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",&opt));
1948b668821SLisandro Dalcin   if (opt) {
1958b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1968b668821SLisandro Dalcin     PetscInt       howoften = 1;
1978b668821SLisandro Dalcin 
1989566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log","Monitor log timestep size graphically","TSMonitorLGTimeStep",howoften,&howoften,NULL));
1999566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
2009566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGTimeStep,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
2018b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2028b668821SLisandro Dalcin   }
2038b668821SLisandro Dalcin 
2049566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",&opt));
205201da799SBarry Smith   if (opt) {
206201da799SBarry Smith     TSMonitorLGCtx ctx;
207201da799SBarry Smith     PetscInt       howoften = 1;
208201da799SBarry Smith 
2099566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGSNESIterations",howoften,&howoften,NULL));
2109566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
2119566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGSNESIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
212201da799SBarry Smith   }
2139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",&opt));
214201da799SBarry Smith   if (opt) {
215201da799SBarry Smith     TSMonitorLGCtx ctx;
216201da799SBarry Smith     PetscInt       howoften = 1;
217201da799SBarry Smith 
2189566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations","Monitor number nonlinear iterations for each timestep graphically","TSMonitorLGKSPIterations",howoften,&howoften,NULL));
2199566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,400,300,howoften,&ctx));
2209566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorLGKSPIterations,ctx,(PetscErrorCode (*)(void**))TSMonitorLGCtxDestroy));
221201da799SBarry Smith   }
2229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",&opt));
2238189c53fSBarry Smith   if (opt) {
2248189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2258189c53fSBarry Smith     PetscInt          howoften = 1;
2268189c53fSBarry Smith 
2279566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig","Monitor eigenvalues of linearized operator graphically","TSMonitorSPEig",howoften,&howoften,NULL));
2289566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2299566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorSPEig,ctx,(PetscErrorCode (*)(void**))TSMonitorSPEigCtxDestroy));
2308189c53fSBarry Smith   }
2319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm","Display particle phase from the DMSwarm","TSMonitorSPSwarm",&opt));
2321b575b74SJoseph Pusztay   if (opt) {
2331b575b74SJoseph Pusztay     TSMonitorSPCtx  ctx;
234d7462660SMatthew Knepley     PetscInt        howoften = 1, retain = 0;
2356a5217c0SMatthew G. Knepley     PetscBool       phase = PETSC_TRUE, create = PETSC_TRUE;
236d7462660SMatthew Knepley 
2376a5217c0SMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i) if (ts->monitor[i] == TSMonitorSPSwarmSolution) {create = PETSC_FALSE;break;}
2386a5217c0SMatthew G. Knepley     if (create) {
2399566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm","Display particles phase from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2409566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2419566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
2429566063dSJacob Faibussowitsch       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject) ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, &ctx));
2439566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode (*)(void**))TSMonitorSPCtxDestroy));
2441b575b74SJoseph Pusztay     }
2456a5217c0SMatthew G. Knepley   }
246ef20d060SBarry Smith   opt  = PETSC_FALSE;
2479566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",&opt));
248a7cc72afSBarry Smith   if (opt) {
24983a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
25083a4ac43SBarry Smith     PetscInt         howoften = 1;
251a80ad3e0SBarry Smith 
2529566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution","Monitor solution graphically","TSMonitorDrawSolution",howoften,&howoften,NULL));
2539566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Computed Solution",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2549566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolution,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
255bdad233fSMatthew Knepley   }
256fb1732b5SBarry Smith   opt  = PETSC_FALSE;
2579566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",&opt));
2582d5ee99bSBarry Smith   if (opt) {
2592d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2602d5ee99bSBarry Smith     PetscReal        bounds[4];
2612d5ee99bSBarry Smith     PetscInt         n = 4;
2622d5ee99bSBarry Smith     PetscDraw        draw;
2636934998bSLisandro Dalcin     PetscDrawAxis    axis;
2642d5ee99bSBarry Smith 
2659566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase","Monitor solution graphically","TSMonitorDrawSolutionPhase",bounds,&n,NULL));
2663c633725SBarry Smith     PetscCheck(n == 4,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Must provide bounding box of phase field");
2679566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,300,300,1,&ctx));
2689566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer,0,&draw));
2699566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer,0,&axis));
2709566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis,bounds[0],bounds[2],bounds[1],bounds[3]));
2719566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis,"Phase Diagram","Variable 1","Variable 2"));
2729566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolutionPhase,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2732d5ee99bSBarry Smith   }
2742d5ee99bSBarry Smith   opt  = PETSC_FALSE;
2759566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",&opt));
2763a471f94SBarry Smith   if (opt) {
27783a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
27883a4ac43SBarry Smith     PetscInt         howoften = 1;
2793a471f94SBarry Smith 
2809566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error","Monitor error graphically","TSMonitorDrawError",howoften,&howoften,NULL));
2819566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Error",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2829566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawError,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2833a471f94SBarry Smith   }
2840ed3bfb6SBarry Smith   opt  = PETSC_FALSE;
2859566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",&opt));
2860ed3bfb6SBarry Smith   if (opt) {
2870ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
2880ed3bfb6SBarry Smith     PetscInt         howoften = 1;
2890ed3bfb6SBarry Smith 
2909566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function","Monitor solution provided by TSMonitorSetSolutionFunction() graphically","TSMonitorDrawSolutionFunction",howoften,&howoften,NULL));
2919566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts),NULL,"Solution provided by user function",PETSC_DECIDE,PETSC_DECIDE,300,300,howoften,&ctx));
2929566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDrawSolutionFunction,ctx,(PetscErrorCode (*)(void**))TSMonitorDrawCtxDestroy));
2930ed3bfb6SBarry Smith   }
294fde5950dSBarry Smith 
295ed81e22dSJed Brown   opt  = PETSC_FALSE;
29663a3b9bcSJacob 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));
297ed81e22dSJed Brown   if (flg) {
298ed81e22dSJed Brown     const char *ptr,*ptr2;
299ed81e22dSJed Brown     char       *filetemplate;
30063a3b9bcSJacob 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");
301ed81e22dSJed Brown     /* Do some cursory validation of the input. */
3029566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename,"%",(char**)&ptr));
30363a3b9bcSJacob Faibussowitsch     PetscCheck(ptr,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
304ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3059566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX",*ptr,(char**)&ptr2));
30663a3b9bcSJacob 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");
307ed81e22dSJed Brown       if (ptr2) break;
308ed81e22dSJed Brown     }
3099566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename,&filetemplate));
3109566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorSolutionVTK,filetemplate,(PetscErrorCode (*)(void**))TSMonitorSolutionVTKDestroy));
311ed81e22dSJed Brown   }
312bdad233fSMatthew Knepley 
3139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray","Display a ray of the solution","None","y=0",dir,sizeof(dir),&flg));
314d1212d36SBarry Smith   if (flg) {
315d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
316d1212d36SBarry Smith     int                  ray = 0;
3173ee9839eSMatthew G. Knepley     DMDirection          ddir;
318d1212d36SBarry Smith     DM                   da;
319d1212d36SBarry Smith     PetscMPIInt          rank;
320d1212d36SBarry Smith 
3213c633725SBarry Smith     PetscCheck(dir[1] == '=',PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
3223ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3233ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
32498921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Unknown ray %s",dir);
325d1212d36SBarry Smith     sscanf(dir+2,"%d",&ray);
326d1212d36SBarry Smith 
3279566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts),"Displaying DMDA ray %c = %d\n",dir[0],ray));
3289566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3299566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts,&da));
3309566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da,ddir,ray,&rayctx->ray,&rayctx->scatter));
3319566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts),&rank));
332dd400576SPatrick Sanan     if (rank == 0) {
3339566063dSJacob Faibussowitsch       PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF,NULL,NULL,0,0,600,300,&rayctx->viewer));
334d1212d36SBarry Smith     }
33551b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3369566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorDMDARay,rayctx,TSMonitorDMDARayDestroy));
337d1212d36SBarry Smith   }
3389566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray","Display a ray of the solution","None","x=0",dir,sizeof(dir),&flg));
33951b4a12fSMatthew G. Knepley   if (flg) {
34051b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
34151b4a12fSMatthew G. Knepley     int                 ray = 0;
3423ee9839eSMatthew G. Knepley     DMDirection         ddir;
34351b4a12fSMatthew G. Knepley     DM                  da;
34451b4a12fSMatthew G. Knepley     PetscInt            howoften = 1;
345d1212d36SBarry Smith 
3463c633725SBarry Smith     PetscCheck(dir[1] == '=',PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3473ee9839eSMatthew G. Knepley     if      (dir[0] == 'x') ddir = DM_X;
3483ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34998921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject) ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
35051b4a12fSMatthew G. Knepley     sscanf(dir+2, "%d", &ray);
3511c3436cfSJed Brown 
3529566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject) ts),"Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3539566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3549566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3559566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3569566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF,NULL,NULL,PETSC_DECIDE,PETSC_DECIDE,600,400,howoften,&rayctx->lgctx));
3579566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
35851b4a12fSMatthew G. Knepley   }
359a7a1495cSBarry Smith 
3609566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope","Monitor maximum and minimum value of each component of the solution","TSMonitorEnvelope",&opt));
361b3d3934dSBarry Smith   if (opt) {
362b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
363b3d3934dSBarry Smith 
3649566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts,&ctx));
3659566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts,TSMonitorEnvelope,ctx,(PetscErrorCode (*)(void**))TSMonitorEnvelopeCtxDestroy));
366b3d3934dSBarry Smith   }
367aee7a9fbSMatthew G. Knepley   flg  = PETSC_FALSE;
3689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel","Remove all monitors","TSMonitorCancel",flg,&flg,&opt));
3699566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
370b3d3934dSBarry Smith 
371847ff0e1SMatthew G. Knepley   flg  = PETSC_FALSE;
3729566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeJacobianDefaultColor", flg, &flg, NULL));
373847ff0e1SMatthew G. Knepley   if (flg) {
374847ff0e1SMatthew G. Knepley     DM   dm;
375847ff0e1SMatthew G. Knepley     DMTS tdm;
376847ff0e1SMatthew G. Knepley 
3779566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
3789566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(dm, &tdm));
379847ff0e1SMatthew G. Knepley     tdm->ijacobianctx = NULL;
3809566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
3819566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
382847ff0e1SMatthew G. Knepley   }
383847ff0e1SMatthew G. Knepley 
384d763cef2SBarry Smith   /* Handle specific TS options */
3851baa6e33SBarry Smith   if (ts->ops->setfromoptions) PetscCall((*ts->ops->setfromoptions)(PetscOptionsObject,ts));
386fbc52257SHong Zhang 
387a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
3889566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
3899566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
3909566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetFromOptions(PetscOptionsObject,ts->adapt));
391a7bdc993SLisandro Dalcin 
39268bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
3934f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
3949566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory","Save the solution at each timestep","TSSetSaveTrajectory",tflg,&tflg,NULL));
3951baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
396a05bf03eSHong Zhang 
3979566063dSJacob Faibussowitsch   PetscCall(TSAdjointSetFromOptions(PetscOptionsObject,ts));
398d763cef2SBarry Smith 
399d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
4009566063dSJacob Faibussowitsch   PetscCall(PetscObjectProcessOptionsHandlers(PetscOptionsObject,(PetscObject)ts));
401d0609cedSBarry Smith   PetscOptionsEnd();
402d763cef2SBarry Smith 
4031baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory,ts));
40468bece0bSHong Zhang 
4051ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4069566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&ts->snes));
4071ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4089566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes,&flg,SNESKSPONLY,SNESKSPTRANSPOSEONLY,""));
4099566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes,SNESKSPONLY));
4101ef27442SStefano Zampini   }
4119566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
412d763cef2SBarry Smith   PetscFunctionReturn(0);
413d763cef2SBarry Smith }
414d763cef2SBarry Smith 
415d2daff3dSHong Zhang /*@
41678fbdcc8SBarry Smith    TSGetTrajectory - Gets the trajectory from a TS if it exists
41778fbdcc8SBarry Smith 
41878fbdcc8SBarry Smith    Collective on TS
41978fbdcc8SBarry Smith 
42078fbdcc8SBarry Smith    Input Parameters:
42178fbdcc8SBarry Smith .  ts - the TS context obtained from TSCreate()
42278fbdcc8SBarry Smith 
4237a7aea1fSJed Brown    Output Parameters:
42478fbdcc8SBarry Smith .  tr - the TSTrajectory object, if it exists
42578fbdcc8SBarry Smith 
42678fbdcc8SBarry Smith    Note: This routine should be called after all TS options have been set
42778fbdcc8SBarry Smith 
42878fbdcc8SBarry Smith    Level: advanced
42978fbdcc8SBarry Smith 
430db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSTrajectory`, `TSTrajectoryCreate()`
43178fbdcc8SBarry Smith 
43278fbdcc8SBarry Smith @*/
43378fbdcc8SBarry Smith PetscErrorCode  TSGetTrajectory(TS ts,TSTrajectory *tr)
43478fbdcc8SBarry Smith {
43578fbdcc8SBarry Smith   PetscFunctionBegin;
43678fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
43778fbdcc8SBarry Smith   *tr = ts->trajectory;
43878fbdcc8SBarry Smith   PetscFunctionReturn(0);
43978fbdcc8SBarry Smith }
44078fbdcc8SBarry Smith 
44178fbdcc8SBarry Smith /*@
442bc952696SBarry Smith    TSSetSaveTrajectory - Causes the TS to save its solutions as it iterates forward in time in a TSTrajectory object
443d2daff3dSHong Zhang 
444d2daff3dSHong Zhang    Collective on TS
445d2daff3dSHong Zhang 
446f899ff85SJose E. Roman    Input Parameter:
447bc952696SBarry Smith .  ts - the TS context obtained from TSCreate()
448bc952696SBarry Smith 
44978fbdcc8SBarry Smith    Options Database:
45078fbdcc8SBarry Smith +  -ts_save_trajectory - saves the trajectory to a file
45167b8a455SSatish Balay -  -ts_trajectory_type type - set trajectory type
45278fbdcc8SBarry Smith 
45368bece0bSHong Zhang Note: This routine should be called after all TS options have been set
454d2daff3dSHong Zhang 
455c3a89c15SBarry Smith     The TSTRAJECTORYVISUALIZATION files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
45678fbdcc8SBarry Smith    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
45778fbdcc8SBarry Smith 
458d2daff3dSHong Zhang    Level: intermediate
459d2daff3dSHong Zhang 
460db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`
461d2daff3dSHong Zhang 
462d2daff3dSHong Zhang @*/
463bc952696SBarry Smith PetscErrorCode  TSSetSaveTrajectory(TS ts)
464d2daff3dSHong Zhang {
465d2daff3dSHong Zhang   PetscFunctionBegin;
466d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
46763a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory));
468d2daff3dSHong Zhang   PetscFunctionReturn(0);
469d2daff3dSHong Zhang }
470d2daff3dSHong Zhang 
471a7a1495cSBarry Smith /*@
4722d29f1f2SStefano Zampini    TSResetTrajectory - Destroys and recreates the internal TSTrajectory object
4732d29f1f2SStefano Zampini 
4742d29f1f2SStefano Zampini    Collective on TS
4752d29f1f2SStefano Zampini 
4762d29f1f2SStefano Zampini    Input Parameters:
4772d29f1f2SStefano Zampini .  ts - the TS context obtained from TSCreate()
4782d29f1f2SStefano Zampini 
4792d29f1f2SStefano Zampini    Level: intermediate
4802d29f1f2SStefano Zampini 
481db781477SPatrick Sanan .seealso: `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
4822d29f1f2SStefano Zampini 
4832d29f1f2SStefano Zampini @*/
4842d29f1f2SStefano Zampini PetscErrorCode  TSResetTrajectory(TS ts)
4852d29f1f2SStefano Zampini {
4862d29f1f2SStefano Zampini   PetscFunctionBegin;
4872d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4882d29f1f2SStefano Zampini   if (ts->trajectory) {
4899566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
4909566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts),&ts->trajectory));
4912d29f1f2SStefano Zampini   }
4922d29f1f2SStefano Zampini   PetscFunctionReturn(0);
4932d29f1f2SStefano Zampini }
4942d29f1f2SStefano Zampini 
4952d29f1f2SStefano Zampini /*@
49667a3cfb0SHong Zhang    TSRemoveTrajectory - Destroys and removes the internal TSTrajectory object from TS
49767a3cfb0SHong Zhang 
49867a3cfb0SHong Zhang    Collective on TS
49967a3cfb0SHong Zhang 
50067a3cfb0SHong Zhang    Input Parameters:
50167a3cfb0SHong Zhang .  ts - the TS context obtained from TSCreate()
50267a3cfb0SHong Zhang 
50367a3cfb0SHong Zhang    Level: intermediate
50467a3cfb0SHong Zhang 
505db781477SPatrick Sanan .seealso: `TSResetTrajectory()`, `TSAdjointSolve()`
50667a3cfb0SHong Zhang 
50767a3cfb0SHong Zhang @*/
50867a3cfb0SHong Zhang PetscErrorCode TSRemoveTrajectory(TS ts)
50967a3cfb0SHong Zhang {
51067a3cfb0SHong Zhang   PetscFunctionBegin;
51167a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
51267a3cfb0SHong Zhang   if (ts->trajectory) {
5139566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
51467a3cfb0SHong Zhang   }
51567a3cfb0SHong Zhang   PetscFunctionReturn(0);
51667a3cfb0SHong Zhang }
51767a3cfb0SHong Zhang 
51867a3cfb0SHong Zhang /*@
519a7a1495cSBarry Smith    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
520a7a1495cSBarry Smith       set with TSSetRHSJacobian().
521a7a1495cSBarry Smith 
522d083f849SBarry Smith    Collective on TS
523a7a1495cSBarry Smith 
524a7a1495cSBarry Smith    Input Parameters:
525316643e7SJed Brown +  ts - the TS context
526a7a1495cSBarry Smith .  t - current timestep
5270910c330SBarry Smith -  U - input vector
528a7a1495cSBarry Smith 
529a7a1495cSBarry Smith    Output Parameters:
530a7a1495cSBarry Smith +  A - Jacobian matrix
5316b867d5aSJose E. Roman -  B - optional preconditioning matrix
532a7a1495cSBarry Smith 
533a7a1495cSBarry Smith    Notes:
534a7a1495cSBarry Smith    Most users should not need to explicitly call this routine, as it
535a7a1495cSBarry Smith    is used internally within the nonlinear solvers.
536a7a1495cSBarry Smith 
537a7a1495cSBarry Smith    Level: developer
538a7a1495cSBarry Smith 
539db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `KSPSetOperators()`
540a7a1495cSBarry Smith @*/
541d1e9a80fSBarry Smith PetscErrorCode  TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)
542a7a1495cSBarry Smith {
543270bf2e7SJed Brown   PetscObjectState Ustate;
5446c1e1eecSBarry Smith   PetscObjectId    Uid;
54524989b8cSPeter Brune   DM               dm;
546942e3340SBarry Smith   DMTS             tsdm;
54724989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
54824989b8cSPeter Brune   void             *ctx;
549b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
550a7a1495cSBarry Smith 
551a7a1495cSBarry Smith   PetscFunctionBegin;
5520700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5530910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
5540910c330SBarry Smith   PetscCheckSameComm(ts,1,U,3);
5559566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
5569566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&tsdm));
5579566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
5589566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobianfunc,&ctx));
5599566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U,&Ustate));
5609566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U,&Uid));
561971015bcSStefano Zampini 
5622663174eSHong Zhang   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(0);
563d90be118SSean Farley 
56463a3b9bcSJacob 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);
56524989b8cSPeter Brune   if (rhsjacobianfunc) {
5669566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,A,B));
567a7a1495cSBarry Smith     PetscStackPush("TS user Jacobian function");
5689566063dSJacob Faibussowitsch     PetscCall((*rhsjacobianfunc)(ts,t,U,A,B,ctx));
569a7a1495cSBarry Smith     PetscStackPop;
570a6ab3590SBarry Smith     ts->rhsjacs++;
5719566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,A,B));
572ef66eb69SBarry Smith   } else {
5739566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5749566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
575ef66eb69SBarry Smith   }
5760e4ef248SJed Brown   ts->rhsjacobian.time  = t;
577971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
578971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5799566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U,&ts->rhsjacobian.Xid));
5809566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U,&ts->rhsjacobian.Xstate));
581a7a1495cSBarry Smith   PetscFunctionReturn(0);
582a7a1495cSBarry Smith }
583a7a1495cSBarry Smith 
584316643e7SJed Brown /*@
585d763cef2SBarry Smith    TSComputeRHSFunction - Evaluates the right-hand-side function.
586d763cef2SBarry Smith 
587d083f849SBarry Smith    Collective on TS
588316643e7SJed Brown 
589316643e7SJed Brown    Input Parameters:
590316643e7SJed Brown +  ts - the TS context
591316643e7SJed Brown .  t - current time
5920910c330SBarry Smith -  U - state vector
593316643e7SJed Brown 
594316643e7SJed Brown    Output Parameter:
595316643e7SJed Brown .  y - right hand side
596316643e7SJed Brown 
597316643e7SJed Brown    Note:
598316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
599316643e7SJed Brown    is used internally within the nonlinear solvers.
600316643e7SJed Brown 
601316643e7SJed Brown    Level: developer
602316643e7SJed Brown 
603db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
604316643e7SJed Brown @*/
6050910c330SBarry Smith PetscErrorCode TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)
606d763cef2SBarry Smith {
60724989b8cSPeter Brune   TSRHSFunction  rhsfunction;
60824989b8cSPeter Brune   TSIFunction    ifunction;
60924989b8cSPeter Brune   void           *ctx;
61024989b8cSPeter Brune   DM             dm;
61124989b8cSPeter Brune 
612d763cef2SBarry Smith   PetscFunctionBegin;
6130700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6140910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6150700a824SBarry Smith   PetscValidHeaderSpecific(y,VEC_CLASSID,4);
6169566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
6179566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,&ctx));
6189566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,&ifunction,NULL));
619d763cef2SBarry Smith 
6203c633725SBarry Smith   PetscCheck(rhsfunction || ifunction,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
621d763cef2SBarry Smith 
62224989b8cSPeter Brune   if (rhsfunction) {
6239566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,y,0));
6249566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
625d763cef2SBarry Smith     PetscStackPush("TS user right-hand-side function");
6269566063dSJacob Faibussowitsch     PetscCall((*rhsfunction)(ts,t,U,y,ctx));
627d763cef2SBarry Smith     PetscStackPop;
6289566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
629a6ab3590SBarry Smith     ts->rhsfuncs++;
6309566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,y,0));
631214bc6a2SJed Brown   } else {
6329566063dSJacob Faibussowitsch     PetscCall(VecZeroEntries(y));
633b2cd27e8SJed Brown   }
634d763cef2SBarry Smith   PetscFunctionReturn(0);
635d763cef2SBarry Smith }
636d763cef2SBarry Smith 
637ef20d060SBarry Smith /*@
638ef20d060SBarry Smith    TSComputeSolutionFunction - Evaluates the solution function.
639ef20d060SBarry Smith 
640d083f849SBarry Smith    Collective on TS
641ef20d060SBarry Smith 
642ef20d060SBarry Smith    Input Parameters:
643ef20d060SBarry Smith +  ts - the TS context
644ef20d060SBarry Smith -  t - current time
645ef20d060SBarry Smith 
646ef20d060SBarry Smith    Output Parameter:
6470910c330SBarry Smith .  U - the solution
648ef20d060SBarry Smith 
649ef20d060SBarry Smith    Note:
650ef20d060SBarry Smith    Most users should not need to explicitly call this routine, as it
651ef20d060SBarry Smith    is used internally within the nonlinear solvers.
652ef20d060SBarry Smith 
653ef20d060SBarry Smith    Level: developer
654ef20d060SBarry Smith 
655db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
656ef20d060SBarry Smith @*/
6570910c330SBarry Smith PetscErrorCode TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)
658ef20d060SBarry Smith {
659ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
660ef20d060SBarry Smith   void               *ctx;
661ef20d060SBarry Smith   DM                 dm;
662ef20d060SBarry Smith 
663ef20d060SBarry Smith   PetscFunctionBegin;
664ef20d060SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6650910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
6669566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
6679566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm,&solutionfunction,&ctx));
668ef20d060SBarry Smith 
669ef20d060SBarry Smith   if (solutionfunction) {
6709b7cd975SBarry Smith     PetscStackPush("TS user solution function");
6719566063dSJacob Faibussowitsch     PetscCall((*solutionfunction)(ts,t,U,ctx));
672ef20d060SBarry Smith     PetscStackPop;
673ef20d060SBarry Smith   }
674ef20d060SBarry Smith   PetscFunctionReturn(0);
675ef20d060SBarry Smith }
6769b7cd975SBarry Smith /*@
6779b7cd975SBarry Smith    TSComputeForcingFunction - Evaluates the forcing function.
6789b7cd975SBarry Smith 
679d083f849SBarry Smith    Collective on TS
6809b7cd975SBarry Smith 
6819b7cd975SBarry Smith    Input Parameters:
6829b7cd975SBarry Smith +  ts - the TS context
6839b7cd975SBarry Smith -  t - current time
6849b7cd975SBarry Smith 
6859b7cd975SBarry Smith    Output Parameter:
6869b7cd975SBarry Smith .  U - the function value
6879b7cd975SBarry Smith 
6889b7cd975SBarry Smith    Note:
6899b7cd975SBarry Smith    Most users should not need to explicitly call this routine, as it
6909b7cd975SBarry Smith    is used internally within the nonlinear solvers.
6919b7cd975SBarry Smith 
6929b7cd975SBarry Smith    Level: developer
6939b7cd975SBarry Smith 
694db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6959b7cd975SBarry Smith @*/
6969b7cd975SBarry Smith PetscErrorCode TSComputeForcingFunction(TS ts,PetscReal t,Vec U)
6979b7cd975SBarry Smith {
6989b7cd975SBarry Smith   void              *ctx;
6999b7cd975SBarry Smith   DM                 dm;
7005f80ce2aSJacob Faibussowitsch   TSForcingFunction  forcing;
7019b7cd975SBarry Smith 
7029b7cd975SBarry Smith   PetscFunctionBegin;
7039b7cd975SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
7049b7cd975SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
7059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
7069566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm,&forcing,&ctx));
7079b7cd975SBarry Smith 
7089b7cd975SBarry Smith   if (forcing) {
7099b7cd975SBarry Smith     PetscStackPush("TS user forcing function");
7109566063dSJacob Faibussowitsch     PetscCall((*forcing)(ts,t,U,ctx));
7119b7cd975SBarry Smith     PetscStackPop;
7129b7cd975SBarry Smith   }
7139b7cd975SBarry Smith   PetscFunctionReturn(0);
7149b7cd975SBarry Smith }
715ef20d060SBarry Smith 
716214bc6a2SJed Brown static PetscErrorCode TSGetRHSVec_Private(TS ts,Vec *Frhs)
717214bc6a2SJed Brown {
7182dd45cf8SJed Brown   Vec            F;
719214bc6a2SJed Brown 
720214bc6a2SJed Brown   PetscFunctionBegin;
7210298fd71SBarry Smith   *Frhs = NULL;
7229566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts,&F,NULL,NULL));
723214bc6a2SJed Brown   if (!ts->Frhs) {
7249566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(F,&ts->Frhs));
725214bc6a2SJed Brown   }
726214bc6a2SJed Brown   *Frhs = ts->Frhs;
727214bc6a2SJed Brown   PetscFunctionReturn(0);
728214bc6a2SJed Brown }
729214bc6a2SJed Brown 
730971015bcSStefano Zampini PetscErrorCode TSGetRHSMats_Private(TS ts,Mat *Arhs,Mat *Brhs)
731214bc6a2SJed Brown {
732214bc6a2SJed Brown   Mat            A,B;
73341a1d4d2SBarry Smith   TSIJacobian    ijacobian;
734214bc6a2SJed Brown 
735214bc6a2SJed Brown   PetscFunctionBegin;
736c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
737c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7389566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts,&A,&B,&ijacobian,NULL));
739214bc6a2SJed Brown   if (Arhs) {
740214bc6a2SJed Brown     if (!ts->Arhs) {
74141a1d4d2SBarry Smith       if (ijacobian) {
7429566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A,MAT_DO_NOT_COPY_VALUES,&ts->Arhs));
7439566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts,SAME_NONZERO_PATTERN));
74441a1d4d2SBarry Smith       } else {
74541a1d4d2SBarry Smith         ts->Arhs = A;
7469566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
74741a1d4d2SBarry Smith       }
7483565c898SBarry Smith     } else {
7493565c898SBarry Smith       PetscBool flg;
7509566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes,NULL,&flg));
7513565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7523565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7539566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7543565c898SBarry Smith         ts->Arhs = A;
7559566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7563565c898SBarry Smith       }
757214bc6a2SJed Brown     }
758214bc6a2SJed Brown     *Arhs = ts->Arhs;
759214bc6a2SJed Brown   }
760214bc6a2SJed Brown   if (Brhs) {
761214bc6a2SJed Brown     if (!ts->Brhs) {
762bdb70873SJed Brown       if (A != B) {
76341a1d4d2SBarry Smith         if (ijacobian) {
7649566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B,MAT_DO_NOT_COPY_VALUES,&ts->Brhs));
765bdb70873SJed Brown         } else {
76641a1d4d2SBarry Smith           ts->Brhs = B;
7679566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
76841a1d4d2SBarry Smith         }
76941a1d4d2SBarry Smith       } else {
7709566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
77151699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
772bdb70873SJed Brown       }
773214bc6a2SJed Brown     }
774214bc6a2SJed Brown     *Brhs = ts->Brhs;
775214bc6a2SJed Brown   }
776214bc6a2SJed Brown   PetscFunctionReturn(0);
777214bc6a2SJed Brown }
778214bc6a2SJed Brown 
779316643e7SJed Brown /*@
7800910c330SBarry Smith    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
781316643e7SJed Brown 
782d083f849SBarry Smith    Collective on TS
783316643e7SJed Brown 
784316643e7SJed Brown    Input Parameters:
785316643e7SJed Brown +  ts - the TS context
786316643e7SJed Brown .  t - current time
7870910c330SBarry Smith .  U - state vector
7880910c330SBarry Smith .  Udot - time derivative of state vector
789214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSFunction should be kept separate
790316643e7SJed Brown 
791316643e7SJed Brown    Output Parameter:
792316643e7SJed Brown .  Y - right hand side
793316643e7SJed Brown 
794316643e7SJed Brown    Note:
795316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
796316643e7SJed Brown    is used internally within the nonlinear solvers.
797316643e7SJed Brown 
798316643e7SJed Brown    If the user did did not write their equations in implicit form, this
799316643e7SJed Brown    function recasts them in implicit form.
800316643e7SJed Brown 
801316643e7SJed Brown    Level: developer
802316643e7SJed Brown 
803db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSComputeRHSFunction()`
804316643e7SJed Brown @*/
8050910c330SBarry Smith PetscErrorCode TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)
806316643e7SJed Brown {
80724989b8cSPeter Brune   TSIFunction    ifunction;
80824989b8cSPeter Brune   TSRHSFunction  rhsfunction;
80924989b8cSPeter Brune   void           *ctx;
81024989b8cSPeter Brune   DM             dm;
811316643e7SJed Brown 
812316643e7SJed Brown   PetscFunctionBegin;
8130700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
8140910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
8150910c330SBarry Smith   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
8160700a824SBarry Smith   PetscValidHeaderSpecific(Y,VEC_CLASSID,5);
817316643e7SJed Brown 
8189566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
8199566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,&ifunction,&ctx));
8209566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
82124989b8cSPeter Brune 
8223c633725SBarry Smith   PetscCheck(rhsfunction || ifunction,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSFunction() and / or TSSetIFunction()");
823d90be118SSean Farley 
8249566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,Udot,Y));
82524989b8cSPeter Brune   if (ifunction) {
826316643e7SJed Brown     PetscStackPush("TS user implicit function");
8279566063dSJacob Faibussowitsch     PetscCall((*ifunction)(ts,t,U,Udot,Y,ctx));
828316643e7SJed Brown     PetscStackPop;
829a6ab3590SBarry Smith     ts->ifuncs++;
830214bc6a2SJed Brown   }
831214bc6a2SJed Brown   if (imex) {
83224989b8cSPeter Brune     if (!ifunction) {
8339566063dSJacob Faibussowitsch       PetscCall(VecCopy(Udot,Y));
8342dd45cf8SJed Brown     }
83524989b8cSPeter Brune   } else if (rhsfunction) {
83624989b8cSPeter Brune     if (ifunction) {
837214bc6a2SJed Brown       Vec Frhs;
8389566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts,&Frhs));
8399566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts,t,U,Frhs));
8409566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y,-1,Frhs));
8412dd45cf8SJed Brown     } else {
8429566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts,t,U,Y));
8439566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y,-1,Udot));
844316643e7SJed Brown     }
8454a6899ffSJed Brown   }
8469566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,Udot,Y));
847316643e7SJed Brown   PetscFunctionReturn(0);
848316643e7SJed Brown }
849316643e7SJed Brown 
850cfa8a9a2SHong Zhang /*
851cfa8a9a2SHong Zhang    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.
852cfa8a9a2SHong Zhang 
853cfa8a9a2SHong Zhang    Note:
854cfa8a9a2SHong Zhang    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().
855cfa8a9a2SHong Zhang 
856cfa8a9a2SHong Zhang */
857cfa8a9a2SHong Zhang static PetscErrorCode TSRecoverRHSJacobian(TS ts,Mat A,Mat B)
858cfa8a9a2SHong Zhang {
859cfa8a9a2SHong Zhang   PetscFunctionBegin;
860cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
8613c633725SBarry Smith   PetscCheck(A == ts->Arhs,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Amat");
8623c633725SBarry Smith   PetscCheck(B == ts->Brhs,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Invalid Bmat");
863cfa8a9a2SHong Zhang 
8641baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A,-ts->rhsjacobian.shift));
865cfa8a9a2SHong Zhang   if (ts->rhsjacobian.scale == -1.) {
8669566063dSJacob Faibussowitsch     PetscCall(MatScale(A,-1));
867cfa8a9a2SHong Zhang   }
868cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8691baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B,-ts->rhsjacobian.shift));
870cfa8a9a2SHong Zhang     if (ts->rhsjacobian.scale == -1.) {
8719566063dSJacob Faibussowitsch       PetscCall(MatScale(B,-1));
872cfa8a9a2SHong Zhang     }
873cfa8a9a2SHong Zhang   }
874cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
875cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
876cfa8a9a2SHong Zhang   PetscFunctionReturn(0);
877cfa8a9a2SHong Zhang }
878cfa8a9a2SHong Zhang 
879316643e7SJed Brown /*@
880316643e7SJed Brown    TSComputeIJacobian - Evaluates the Jacobian of the DAE
881316643e7SJed Brown 
882d083f849SBarry Smith    Collective on TS
883316643e7SJed Brown 
884316643e7SJed Brown    Input
885316643e7SJed Brown       Input Parameters:
886316643e7SJed Brown +  ts - the TS context
887316643e7SJed Brown .  t - current timestep
8880910c330SBarry Smith .  U - state vector
8890910c330SBarry Smith .  Udot - time derivative of state vector
890214bc6a2SJed Brown .  shift - shift to apply, see note below
891214bc6a2SJed Brown -  imex - flag indicates if the method is IMEX so that the RHSJacobian should be kept separate
892316643e7SJed Brown 
893316643e7SJed Brown    Output Parameters:
894316643e7SJed Brown +  A - Jacobian matrix
8953565c898SBarry Smith -  B - matrix from which the preconditioner is constructed; often the same as A
896316643e7SJed Brown 
897316643e7SJed Brown    Notes:
8980910c330SBarry Smith    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
899316643e7SJed Brown 
9000910c330SBarry Smith    dF/dU + shift*dF/dUdot
901316643e7SJed Brown 
902316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
903316643e7SJed Brown    is used internally within the nonlinear solvers.
904316643e7SJed Brown 
905316643e7SJed Brown    Level: developer
906316643e7SJed Brown 
907db781477SPatrick Sanan .seealso: `TSSetIJacobian()`
90863495f91SJed Brown @*/
909d1e9a80fSBarry Smith PetscErrorCode TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)
910316643e7SJed Brown {
91124989b8cSPeter Brune   TSIJacobian    ijacobian;
91224989b8cSPeter Brune   TSRHSJacobian  rhsjacobian;
91324989b8cSPeter Brune   DM             dm;
91424989b8cSPeter Brune   void           *ctx;
915316643e7SJed Brown 
916316643e7SJed Brown   PetscFunctionBegin;
9170700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
9180910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
9190910c330SBarry Smith   PetscValidHeaderSpecific(Udot,VEC_CLASSID,4);
920316643e7SJed Brown   PetscValidPointer(A,6);
92194ab13aaSBarry Smith   PetscValidHeaderSpecific(A,MAT_CLASSID,6);
922316643e7SJed Brown   PetscValidPointer(B,7);
92394ab13aaSBarry Smith   PetscValidHeaderSpecific(B,MAT_CLASSID,7);
92424989b8cSPeter Brune 
9259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
9269566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijacobian,&ctx));
9279566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobian,NULL));
92824989b8cSPeter Brune 
9293c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian,PetscObjectComm((PetscObject)ts),PETSC_ERR_USER,"Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
930316643e7SJed Brown 
9319566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,A,B));
93224989b8cSPeter Brune   if (ijacobian) {
933316643e7SJed Brown     PetscStackPush("TS user implicit Jacobian");
9349566063dSJacob Faibussowitsch     PetscCall((*ijacobian)(ts,t,U,Udot,shift,A,B,ctx));
935a6ab3590SBarry Smith     ts->ijacs++;
936316643e7SJed Brown     PetscStackPop;
9374a6899ffSJed Brown   }
938214bc6a2SJed Brown   if (imex) {
939b5abc632SBarry Smith     if (!ijacobian) {  /* system was written as Udot = G(t,U) */
9404c26be97Sstefano_zampini       PetscBool assembled;
941971015bcSStefano Zampini       if (rhsjacobian) {
942971015bcSStefano Zampini         Mat Arhs = NULL;
9439566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts,&Arhs,NULL));
944971015bcSStefano Zampini         if (A == Arhs) {
9453c633725SBarry 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 */
946971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
947971015bcSStefano Zampini         }
948971015bcSStefano Zampini       }
9499566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9509566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A,&assembled));
9514c26be97Sstefano_zampini       if (!assembled) {
9529566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A,MAT_FINAL_ASSEMBLY));
9539566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A,MAT_FINAL_ASSEMBLY));
9544c26be97Sstefano_zampini       }
9559566063dSJacob Faibussowitsch       PetscCall(MatShift(A,shift));
95694ab13aaSBarry Smith       if (A != B) {
9579566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9589566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B,&assembled));
9594c26be97Sstefano_zampini         if (!assembled) {
9609566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B,MAT_FINAL_ASSEMBLY));
9619566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B,MAT_FINAL_ASSEMBLY));
9624c26be97Sstefano_zampini         }
9639566063dSJacob Faibussowitsch         PetscCall(MatShift(B,shift));
964214bc6a2SJed Brown       }
965214bc6a2SJed Brown     }
966214bc6a2SJed Brown   } else {
967e1244c69SJed Brown     Mat Arhs = NULL,Brhs = NULL;
968e8b1e424SHong Zhang     if (rhsjacobian) { /* RHSJacobian needs to be converted to part of IJacobian if exists */
9699566063dSJacob Faibussowitsch       PetscCall(TSGetRHSMats_Private(ts,&Arhs,&Brhs));
970e1244c69SJed Brown     }
971e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
972e8b1e424SHong Zhang       PetscObjectState Ustate;
973e8b1e424SHong Zhang       PetscObjectId    Uid;
974e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
975e8b1e424SHong Zhang 
9769566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
9779566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U,&Ustate));
9789566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U,&Uid));
979097a96a2SHong 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 */
9809566063dSJacob Faibussowitsch         PetscCall(MatShift(A,shift-ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
98134d322a1SHong Zhang         if (A != B) {
9829566063dSJacob Faibussowitsch           PetscCall(MatShift(B,shift-ts->rhsjacobian.shift));
98334d322a1SHong Zhang         }
984e8b1e424SHong Zhang       } else {
9853565c898SBarry Smith         PetscBool flg;
986e8b1e424SHong Zhang 
987e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
988e8b1e424SHong Zhang           /* MatScale has a short path for this case.
989e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
990e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9919566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts,A,B));
992e8b1e424SHong Zhang         }
9939566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts,t,U,A,B));
9949566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes,NULL,&flg));
9953565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9963565c898SBarry Smith         if (!flg) {
9979566063dSJacob Faibussowitsch           PetscCall(MatScale(A,-1));
9989566063dSJacob Faibussowitsch           PetscCall(MatShift(A,shift));
9993565c898SBarry Smith         }
100094ab13aaSBarry Smith         if (A != B) {
10019566063dSJacob Faibussowitsch           PetscCall(MatScale(B,-1));
10029566063dSJacob Faibussowitsch           PetscCall(MatShift(B,shift));
1003316643e7SJed Brown         }
1004e8b1e424SHong Zhang       }
1005e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
1006e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
1007d60b7d5cSBarry Smith     } else if (Arhs) {          /* Both IJacobian and RHSJacobian */
1008e1244c69SJed Brown       if (!ijacobian) {         /* No IJacobian provided, but we have a separate RHS matrix */
10099566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
10109566063dSJacob Faibussowitsch         PetscCall(MatShift(A,shift));
101194ab13aaSBarry Smith         if (A != B) {
10129566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
10139566063dSJacob Faibussowitsch           PetscCall(MatShift(B,shift));
1014214bc6a2SJed Brown         }
1015316643e7SJed Brown       }
10169566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts,t,U,Arhs,Brhs));
10179566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A,-1,Arhs,ts->axpy_pattern));
101894ab13aaSBarry Smith       if (A != B) {
10199566063dSJacob Faibussowitsch         PetscCall(MatAXPY(B,-1,Brhs,ts->axpy_pattern));
1020316643e7SJed Brown       }
1021316643e7SJed Brown     }
1022316643e7SJed Brown   }
10239566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,A,B));
1024316643e7SJed Brown   PetscFunctionReturn(0);
1025316643e7SJed Brown }
1026316643e7SJed Brown 
1027d763cef2SBarry Smith /*@C
1028d763cef2SBarry Smith     TSSetRHSFunction - Sets the routine for evaluating the function,
1029b5abc632SBarry Smith     where U_t = G(t,u).
1030d763cef2SBarry Smith 
10313f9fe445SBarry Smith     Logically Collective on TS
1032d763cef2SBarry Smith 
1033d763cef2SBarry Smith     Input Parameters:
1034d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
10350298fd71SBarry Smith .   r - vector to put the computed right hand side (or NULL to have it created)
1036d763cef2SBarry Smith .   f - routine for evaluating the right-hand-side function
1037d763cef2SBarry Smith -   ctx - [optional] user-defined context for private data for the
10380298fd71SBarry Smith           function evaluation routine (may be NULL)
1039d763cef2SBarry Smith 
1040a96d6ef6SBarry Smith     Calling sequence of f:
1041a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
1042d763cef2SBarry Smith 
1043a96d6ef6SBarry Smith +   ts - timestep context
1044a96d6ef6SBarry Smith .   t - current timestep
1045d763cef2SBarry Smith .   u - input vector
1046d763cef2SBarry Smith .   F - function vector
1047d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1048d763cef2SBarry Smith 
1049d763cef2SBarry Smith     Level: beginner
1050d763cef2SBarry Smith 
105195452b02SPatrick Sanan     Notes:
105295452b02SPatrick Sanan     You must call this function or TSSetIFunction() to define your ODE. You cannot use this function when solving a DAE.
10532bbac0d3SBarry Smith 
1054db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1055d763cef2SBarry Smith @*/
1056089b2837SJed Brown PetscErrorCode  TSSetRHSFunction(TS ts,Vec r,PetscErrorCode (*f)(TS,PetscReal,Vec,Vec,void*),void *ctx)
1057d763cef2SBarry Smith {
1058089b2837SJed Brown   SNES           snes;
10590298fd71SBarry Smith   Vec            ralloc = NULL;
106024989b8cSPeter Brune   DM             dm;
1061d763cef2SBarry Smith 
1062089b2837SJed Brown   PetscFunctionBegin;
10630700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1064ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
106524989b8cSPeter Brune 
10669566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
10679566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm,f,ctx));
10689566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
1069e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10709566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol,&ralloc));
1071e856ceecSJed Brown     r = ralloc;
1072e856ceecSJed Brown   }
10739566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes,r,SNESTSFormFunction,ts));
10749566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1075d763cef2SBarry Smith   PetscFunctionReturn(0);
1076d763cef2SBarry Smith }
1077d763cef2SBarry Smith 
1078ef20d060SBarry Smith /*@C
1079abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1080ef20d060SBarry Smith 
1081ef20d060SBarry Smith     Logically Collective on TS
1082ef20d060SBarry Smith 
1083ef20d060SBarry Smith     Input Parameters:
1084ef20d060SBarry Smith +   ts - the TS context obtained from TSCreate()
1085ef20d060SBarry Smith .   f - routine for evaluating the solution
1086ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
10870298fd71SBarry Smith           function evaluation routine (may be NULL)
1088ef20d060SBarry Smith 
1089a96d6ef6SBarry Smith     Calling sequence of f:
1090a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1091ef20d060SBarry Smith 
1092ef20d060SBarry Smith +   t - current timestep
1093ef20d060SBarry Smith .   u - output vector
1094ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1095ef20d060SBarry Smith 
10960ed3bfb6SBarry Smith     Options Database:
10970ed3bfb6SBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided TSSetSolutionFunction()
10980ed3bfb6SBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided TSSetSolutionFunction()
10990ed3bfb6SBarry Smith 
1100abd5a294SJed Brown     Notes:
1101abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1102abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1103abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1104abd5a294SJed Brown 
11054f09c107SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
1106abd5a294SJed Brown 
1107ef20d060SBarry Smith     Level: beginner
1108ef20d060SBarry Smith 
1109db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1110ef20d060SBarry Smith @*/
1111ef20d060SBarry Smith PetscErrorCode  TSSetSolutionFunction(TS ts,PetscErrorCode (*f)(TS,PetscReal,Vec,void*),void *ctx)
1112ef20d060SBarry Smith {
1113ef20d060SBarry Smith   DM             dm;
1114ef20d060SBarry Smith 
1115ef20d060SBarry Smith   PetscFunctionBegin;
1116ef20d060SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
11179566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
11189566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm,f,ctx));
1119ef20d060SBarry Smith   PetscFunctionReturn(0);
1120ef20d060SBarry Smith }
1121ef20d060SBarry Smith 
11229b7cd975SBarry Smith /*@C
11239b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
11249b7cd975SBarry Smith 
11259b7cd975SBarry Smith     Logically Collective on TS
11269b7cd975SBarry Smith 
11279b7cd975SBarry Smith     Input Parameters:
11289b7cd975SBarry Smith +   ts - the TS context obtained from TSCreate()
1129e162b725SBarry Smith .   func - routine for evaluating the forcing function
11309b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
11310298fd71SBarry Smith           function evaluation routine (may be NULL)
11329b7cd975SBarry Smith 
11339b7cd975SBarry Smith     Calling sequence of func:
11346bc98fa9SBarry Smith $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
11359b7cd975SBarry Smith 
11369b7cd975SBarry Smith +   t - current timestep
1137e162b725SBarry Smith .   f - output vector
11389b7cd975SBarry Smith -   ctx - [optional] user-defined function context
11399b7cd975SBarry Smith 
11409b7cd975SBarry Smith     Notes:
11419b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1142e162b725SBarry 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
1143e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1144e162b725SBarry Smith 
1145e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1146e162b725SBarry Smith 
1147e162b725SBarry 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
1148e162b725SBarry Smith     parameters can be passed in the ctx variable.
11499b7cd975SBarry Smith 
11509b7cd975SBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, TSMonitorLGError() can be used to monitor the error history.
11519b7cd975SBarry Smith 
11529b7cd975SBarry Smith     Level: beginner
11539b7cd975SBarry Smith 
1154db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11559b7cd975SBarry Smith @*/
1156e162b725SBarry Smith PetscErrorCode  TSSetForcingFunction(TS ts,TSForcingFunction func,void *ctx)
11579b7cd975SBarry Smith {
11589b7cd975SBarry Smith   DM             dm;
11599b7cd975SBarry Smith 
11609b7cd975SBarry Smith   PetscFunctionBegin;
11619b7cd975SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
11629566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
11639566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm,func,ctx));
11649b7cd975SBarry Smith   PetscFunctionReturn(0);
11659b7cd975SBarry Smith }
11669b7cd975SBarry Smith 
1167d763cef2SBarry Smith /*@C
1168f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1169b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1170d763cef2SBarry Smith 
11713f9fe445SBarry Smith    Logically Collective on TS
1172d763cef2SBarry Smith 
1173d763cef2SBarry Smith    Input Parameters:
1174d763cef2SBarry Smith +  ts  - the TS context obtained from TSCreate()
1175e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1176e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1177d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1178d763cef2SBarry Smith -  ctx - [optional] user-defined context for private data for the
11790298fd71SBarry Smith          Jacobian evaluation routine (may be NULL)
1180d763cef2SBarry Smith 
1181f7ab8db6SBarry Smith    Calling sequence of f:
1182a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1183d763cef2SBarry Smith 
1184d763cef2SBarry Smith +  t - current timestep
1185d763cef2SBarry Smith .  u - input vector
1186e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1187e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1188d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1189d763cef2SBarry Smith 
11906cd88445SBarry Smith    Notes:
11916cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11926cd88445SBarry Smith 
11936cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1194ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1195d763cef2SBarry Smith 
1196d763cef2SBarry Smith    Level: beginner
1197d763cef2SBarry Smith 
1198db781477SPatrick Sanan .seealso: `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1199d763cef2SBarry Smith 
1200d763cef2SBarry Smith @*/
1201e5d3d808SBarry Smith PetscErrorCode  TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobian f,void *ctx)
1202d763cef2SBarry Smith {
1203089b2837SJed Brown   SNES           snes;
120424989b8cSPeter Brune   DM             dm;
120524989b8cSPeter Brune   TSIJacobian    ijacobian;
1206277b19d0SLisandro Dalcin 
1207d763cef2SBarry Smith   PetscFunctionBegin;
12080700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1209e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1210e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1211e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1212e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
1213d763cef2SBarry Smith 
12149566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
12159566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm,f,ctx));
12169566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijacobian,NULL));
12179566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
12185f659677SPeter Brune   if (!ijacobian) {
12199566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts));
12200e4ef248SJed Brown   }
1221e5d3d808SBarry Smith   if (Amat) {
12229566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
12239566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1224e5d3d808SBarry Smith     ts->Arhs = Amat;
12250e4ef248SJed Brown   }
1226e5d3d808SBarry Smith   if (Pmat) {
12279566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
12289566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1229e5d3d808SBarry Smith     ts->Brhs = Pmat;
12300e4ef248SJed Brown   }
1231d763cef2SBarry Smith   PetscFunctionReturn(0);
1232d763cef2SBarry Smith }
1233d763cef2SBarry Smith 
1234316643e7SJed Brown /*@C
1235b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1236316643e7SJed Brown 
12373f9fe445SBarry Smith    Logically Collective on TS
1238316643e7SJed Brown 
1239316643e7SJed Brown    Input Parameters:
1240316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
12410298fd71SBarry Smith .  r   - vector to hold the residual (or NULL to have it created internally)
1242316643e7SJed Brown .  f   - the function evaluation routine
12430298fd71SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1244316643e7SJed Brown 
1245316643e7SJed Brown    Calling sequence of f:
12466bc98fa9SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1247316643e7SJed Brown 
1248316643e7SJed Brown +  t   - time at step/stage being solved
1249316643e7SJed Brown .  u   - state vector
1250316643e7SJed Brown .  u_t - time derivative of state vector
1251316643e7SJed Brown .  F   - function vector
1252316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1253316643e7SJed Brown 
1254316643e7SJed Brown    Important:
12552bbac0d3SBarry Smith    The user MUST call either this routine or TSSetRHSFunction() to define the ODE.  When solving DAEs you must use this function.
1256316643e7SJed Brown 
1257316643e7SJed Brown    Level: beginner
1258316643e7SJed Brown 
1259db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1260316643e7SJed Brown @*/
126151699248SLisandro Dalcin PetscErrorCode  TSSetIFunction(TS ts,Vec r,TSIFunction f,void *ctx)
1262316643e7SJed Brown {
1263089b2837SJed Brown   SNES           snes;
126451699248SLisandro Dalcin   Vec            ralloc = NULL;
126524989b8cSPeter Brune   DM             dm;
1266316643e7SJed Brown 
1267316643e7SJed Brown   PetscFunctionBegin;
12680700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
126951699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r,VEC_CLASSID,2);
127024989b8cSPeter Brune 
12719566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
12729566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm,f,ctx));
127324989b8cSPeter Brune 
12749566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
127551699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12769566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol,&ralloc));
127751699248SLisandro Dalcin     r  = ralloc;
1278e856ceecSJed Brown   }
12799566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes,r,SNESTSFormFunction,ts));
12809566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1281089b2837SJed Brown   PetscFunctionReturn(0);
1282089b2837SJed Brown }
1283089b2837SJed Brown 
1284089b2837SJed Brown /*@C
1285a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1286089b2837SJed Brown 
1287089b2837SJed Brown    Not Collective
1288089b2837SJed Brown 
1289089b2837SJed Brown    Input Parameter:
1290089b2837SJed Brown .  ts - the TS context
1291089b2837SJed Brown 
1292d8d19677SJose E. Roman    Output Parameters:
12930298fd71SBarry Smith +  r - vector to hold residual (or NULL)
12940298fd71SBarry Smith .  func - the function to compute residual (or NULL)
12950298fd71SBarry Smith -  ctx - the function context (or NULL)
1296089b2837SJed Brown 
1297089b2837SJed Brown    Level: advanced
1298089b2837SJed Brown 
1299db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`
1300089b2837SJed Brown @*/
1301089b2837SJed Brown PetscErrorCode TSGetIFunction(TS ts,Vec *r,TSIFunction *func,void **ctx)
1302089b2837SJed Brown {
1303089b2837SJed Brown   SNES           snes;
130424989b8cSPeter Brune   DM             dm;
1305089b2837SJed Brown 
1306089b2837SJed Brown   PetscFunctionBegin;
1307089b2837SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
13089566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
13099566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
13109566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
13119566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm,func,ctx));
1312089b2837SJed Brown   PetscFunctionReturn(0);
1313089b2837SJed Brown }
1314089b2837SJed Brown 
1315089b2837SJed Brown /*@C
1316089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1317089b2837SJed Brown 
1318089b2837SJed Brown    Not Collective
1319089b2837SJed Brown 
1320089b2837SJed Brown    Input Parameter:
1321089b2837SJed Brown .  ts - the TS context
1322089b2837SJed Brown 
1323d8d19677SJose E. Roman    Output Parameters:
13240298fd71SBarry Smith +  r - vector to hold computed right hand side (or NULL)
13250298fd71SBarry Smith .  func - the function to compute right hand side (or NULL)
13260298fd71SBarry Smith -  ctx - the function context (or NULL)
1327089b2837SJed Brown 
1328089b2837SJed Brown    Level: advanced
1329089b2837SJed Brown 
1330db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `SNESGetFunction()`
1331089b2837SJed Brown @*/
1332089b2837SJed Brown PetscErrorCode TSGetRHSFunction(TS ts,Vec *r,TSRHSFunction *func,void **ctx)
1333089b2837SJed Brown {
1334089b2837SJed Brown   SNES           snes;
133524989b8cSPeter Brune   DM             dm;
1336089b2837SJed Brown 
1337089b2837SJed Brown   PetscFunctionBegin;
1338089b2837SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
13399566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
13409566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
13419566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
13429566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,func,ctx));
1343316643e7SJed Brown   PetscFunctionReturn(0);
1344316643e7SJed Brown }
1345316643e7SJed Brown 
1346316643e7SJed Brown /*@C
1347a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1348ae8867d6SBarry Smith         provided with TSSetIFunction().
1349316643e7SJed Brown 
13503f9fe445SBarry Smith    Logically Collective on TS
1351316643e7SJed Brown 
1352316643e7SJed Brown    Input Parameters:
1353316643e7SJed Brown +  ts  - the TS context obtained from TSCreate()
1354e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1355e5d3d808SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1356316643e7SJed Brown .  f   - the Jacobian evaluation routine
13570298fd71SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1358316643e7SJed Brown 
1359316643e7SJed Brown    Calling sequence of f:
13606bc98fa9SBarry Smith $    PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1361316643e7SJed Brown 
1362316643e7SJed Brown +  t    - time at step/stage being solved
13631b4a444bSJed Brown .  U    - state vector
13641b4a444bSJed Brown .  U_t  - time derivative of state vector
1365316643e7SJed Brown .  a    - shift
1366e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1367e5d3d808SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1368316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1369316643e7SJed Brown 
1370316643e7SJed Brown    Notes:
1371e5d3d808SBarry Smith    The matrices Amat and Pmat are exactly the matrices that are used by SNES for the nonlinear solve.
1372316643e7SJed Brown 
1373895c21f2SBarry Smith    If you know the operator Amat has a null space you can use MatSetNullSpace() and MatSetTransposeNullSpace() to supply the null
1374895c21f2SBarry Smith    space to Amat and the KSP solvers will automatically use that null space as needed during the solution process.
1375895c21f2SBarry Smith 
1376a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1377b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1378a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1379a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1380a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1381a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1382a4f0a591SBarry Smith 
13836cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13846cd88445SBarry Smith 
13856cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1386ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1387ca5f011dSBarry Smith 
1388316643e7SJed Brown    Level: beginner
1389316643e7SJed Brown 
1390db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1391316643e7SJed Brown 
1392316643e7SJed Brown @*/
1393e5d3d808SBarry Smith PetscErrorCode  TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobian f,void *ctx)
1394316643e7SJed Brown {
1395089b2837SJed Brown   SNES           snes;
139624989b8cSPeter Brune   DM             dm;
1397316643e7SJed Brown 
1398316643e7SJed Brown   PetscFunctionBegin;
13990700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1400e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat,MAT_CLASSID,2);
1401e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat,MAT_CLASSID,3);
1402e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts,1,Amat,2);
1403e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts,1,Pmat,3);
140424989b8cSPeter Brune 
14059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
14069566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm,f,ctx));
140724989b8cSPeter Brune 
14089566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
14099566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes,Amat,Pmat,SNESTSFormJacobian,ts));
1410316643e7SJed Brown   PetscFunctionReturn(0);
1411316643e7SJed Brown }
1412316643e7SJed Brown 
1413e1244c69SJed Brown /*@
1414e1244c69SJed Brown    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, TS will change the sign and
1415e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1416e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1417e1244c69SJed Brown    not been changed by the TS.
1418e1244c69SJed Brown 
1419e1244c69SJed Brown    Logically Collective
1420e1244c69SJed Brown 
14214165533cSJose E. Roman    Input Parameters:
1422e1244c69SJed Brown +  ts - TS context obtained from TSCreate()
1423e1244c69SJed Brown -  reuse - PETSC_TRUE if the RHS Jacobian
1424e1244c69SJed Brown 
1425e1244c69SJed Brown    Level: intermediate
1426e1244c69SJed Brown 
1427db781477SPatrick Sanan .seealso: `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1428e1244c69SJed Brown @*/
1429e1244c69SJed Brown PetscErrorCode TSRHSJacobianSetReuse(TS ts,PetscBool reuse)
1430e1244c69SJed Brown {
1431e1244c69SJed Brown   PetscFunctionBegin;
1432e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
1433e1244c69SJed Brown   PetscFunctionReturn(0);
1434e1244c69SJed Brown }
1435e1244c69SJed Brown 
1436efe9872eSLisandro Dalcin /*@C
1437efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1438efe9872eSLisandro Dalcin 
1439efe9872eSLisandro Dalcin    Logically Collective on TS
1440efe9872eSLisandro Dalcin 
1441efe9872eSLisandro Dalcin    Input Parameters:
1442efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1443efe9872eSLisandro Dalcin .  F   - vector to hold the residual (or NULL to have it created internally)
1444efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1445efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1446efe9872eSLisandro Dalcin 
1447efe9872eSLisandro Dalcin    Calling sequence of fun:
14486bc98fa9SBarry Smith $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1449efe9872eSLisandro Dalcin 
1450efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1451efe9872eSLisandro Dalcin .  U    - state vector
1452efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1453efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1454efe9872eSLisandro Dalcin .  F    - function vector
1455efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1456efe9872eSLisandro Dalcin 
1457efe9872eSLisandro Dalcin    Level: beginner
1458efe9872eSLisandro Dalcin 
1459db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1460efe9872eSLisandro Dalcin @*/
1461efe9872eSLisandro Dalcin PetscErrorCode TSSetI2Function(TS ts,Vec F,TSI2Function fun,void *ctx)
1462efe9872eSLisandro Dalcin {
1463efe9872eSLisandro Dalcin   DM             dm;
1464efe9872eSLisandro Dalcin 
1465efe9872eSLisandro Dalcin   PetscFunctionBegin;
1466efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1467efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F,VEC_CLASSID,2);
14689566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts,F,NULL,NULL));
14699566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
14709566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm,fun,ctx));
1471efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1472efe9872eSLisandro Dalcin }
1473efe9872eSLisandro Dalcin 
1474efe9872eSLisandro Dalcin /*@C
1475a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1476efe9872eSLisandro Dalcin 
1477efe9872eSLisandro Dalcin   Not Collective
1478efe9872eSLisandro Dalcin 
1479efe9872eSLisandro Dalcin   Input Parameter:
1480efe9872eSLisandro Dalcin . ts - the TS context
1481efe9872eSLisandro Dalcin 
1482d8d19677SJose E. Roman   Output Parameters:
1483efe9872eSLisandro Dalcin + r - vector to hold residual (or NULL)
1484efe9872eSLisandro Dalcin . fun - the function to compute residual (or NULL)
1485efe9872eSLisandro Dalcin - ctx - the function context (or NULL)
1486efe9872eSLisandro Dalcin 
1487efe9872eSLisandro Dalcin   Level: advanced
1488efe9872eSLisandro Dalcin 
1489db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1490efe9872eSLisandro Dalcin @*/
1491efe9872eSLisandro Dalcin PetscErrorCode TSGetI2Function(TS ts,Vec *r,TSI2Function *fun,void **ctx)
1492efe9872eSLisandro Dalcin {
1493efe9872eSLisandro Dalcin   SNES           snes;
1494efe9872eSLisandro Dalcin   DM             dm;
1495efe9872eSLisandro Dalcin 
1496efe9872eSLisandro Dalcin   PetscFunctionBegin;
1497efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
14989566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
14999566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes,r,NULL,NULL));
15009566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15019566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm,fun,ctx));
1502efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1503efe9872eSLisandro Dalcin }
1504efe9872eSLisandro Dalcin 
1505efe9872eSLisandro Dalcin /*@C
1506bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1507efe9872eSLisandro Dalcin         where F(t,U,U_t,U_tt) is the function you provided with TSSetI2Function().
1508efe9872eSLisandro Dalcin 
1509efe9872eSLisandro Dalcin    Logically Collective on TS
1510efe9872eSLisandro Dalcin 
1511efe9872eSLisandro Dalcin    Input Parameters:
1512efe9872eSLisandro Dalcin +  ts  - the TS context obtained from TSCreate()
1513efe9872eSLisandro Dalcin .  J   - Jacobian matrix
1514efe9872eSLisandro Dalcin .  P   - preconditioning matrix for J (may be same as J)
1515efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1516efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1517efe9872eSLisandro Dalcin 
1518efe9872eSLisandro Dalcin    Calling sequence of jac:
15196bc98fa9SBarry 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);
1520efe9872eSLisandro Dalcin 
1521efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1522efe9872eSLisandro Dalcin .  U    - state vector
1523efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1524efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1525efe9872eSLisandro Dalcin .  v    - shift for U_t
1526efe9872eSLisandro Dalcin .  a    - shift for U_tt
1527efe9872eSLisandro 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
1528efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1529efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1530efe9872eSLisandro Dalcin 
1531efe9872eSLisandro Dalcin    Notes:
1532efe9872eSLisandro Dalcin    The matrices J and P are exactly the matrices that are used by SNES for the nonlinear solve.
1533efe9872eSLisandro Dalcin 
1534efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1535efe9872eSLisandro 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.
1536efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1537bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1538efe9872eSLisandro Dalcin 
1539efe9872eSLisandro Dalcin    Level: beginner
1540efe9872eSLisandro Dalcin 
1541db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Jacobian()`
1542efe9872eSLisandro Dalcin @*/
1543efe9872eSLisandro Dalcin PetscErrorCode TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2Jacobian jac,void *ctx)
1544efe9872eSLisandro Dalcin {
1545efe9872eSLisandro Dalcin   DM             dm;
1546efe9872eSLisandro Dalcin 
1547efe9872eSLisandro Dalcin   PetscFunctionBegin;
1548efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1549efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J,MAT_CLASSID,2);
1550efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P,MAT_CLASSID,3);
15519566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts,J,P,NULL,NULL));
15529566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15539566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm,jac,ctx));
1554efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1555efe9872eSLisandro Dalcin }
1556efe9872eSLisandro Dalcin 
1557efe9872eSLisandro Dalcin /*@C
1558efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1559efe9872eSLisandro Dalcin 
1560efe9872eSLisandro Dalcin   Not Collective, but parallel objects are returned if TS is parallel
1561efe9872eSLisandro Dalcin 
1562efe9872eSLisandro Dalcin   Input Parameter:
1563efe9872eSLisandro Dalcin . ts  - The TS context obtained from TSCreate()
1564efe9872eSLisandro Dalcin 
1565efe9872eSLisandro Dalcin   Output Parameters:
1566efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1567efe9872eSLisandro Dalcin . P - The matrix from which the preconditioner is constructed, often the same as J
1568efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1569efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1570efe9872eSLisandro Dalcin 
157195452b02SPatrick Sanan   Notes:
157295452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
1573efe9872eSLisandro Dalcin 
1574efe9872eSLisandro Dalcin   Level: advanced
1575efe9872eSLisandro Dalcin 
1576db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1577efe9872eSLisandro Dalcin 
1578efe9872eSLisandro Dalcin @*/
1579efe9872eSLisandro Dalcin PetscErrorCode  TSGetI2Jacobian(TS ts,Mat *J,Mat *P,TSI2Jacobian *jac,void **ctx)
1580efe9872eSLisandro Dalcin {
1581efe9872eSLisandro Dalcin   SNES           snes;
1582efe9872eSLisandro Dalcin   DM             dm;
1583efe9872eSLisandro Dalcin 
1584efe9872eSLisandro Dalcin   PetscFunctionBegin;
15859566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
15869566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15879566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes,J,P,NULL,NULL));
15889566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
15899566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,jac,ctx));
1590efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1591efe9872eSLisandro Dalcin }
1592efe9872eSLisandro Dalcin 
1593efe9872eSLisandro Dalcin /*@
1594efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1595efe9872eSLisandro Dalcin 
1596d083f849SBarry Smith   Collective on TS
1597efe9872eSLisandro Dalcin 
1598efe9872eSLisandro Dalcin   Input Parameters:
1599efe9872eSLisandro Dalcin + ts - the TS context
1600efe9872eSLisandro Dalcin . t - current time
1601efe9872eSLisandro Dalcin . U - state vector
1602efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1603efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1604efe9872eSLisandro Dalcin 
1605efe9872eSLisandro Dalcin   Output Parameter:
1606efe9872eSLisandro Dalcin . F - the residual vector
1607efe9872eSLisandro Dalcin 
1608efe9872eSLisandro Dalcin   Note:
1609efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1610efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1611efe9872eSLisandro Dalcin 
1612efe9872eSLisandro Dalcin   Level: developer
1613efe9872eSLisandro Dalcin 
1614db781477SPatrick Sanan .seealso: `TSSetI2Function()`, `TSGetI2Function()`
1615efe9872eSLisandro Dalcin @*/
1616efe9872eSLisandro Dalcin PetscErrorCode TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)
1617efe9872eSLisandro Dalcin {
1618efe9872eSLisandro Dalcin   DM             dm;
1619efe9872eSLisandro Dalcin   TSI2Function   I2Function;
1620efe9872eSLisandro Dalcin   void           *ctx;
1621efe9872eSLisandro Dalcin   TSRHSFunction  rhsfunction;
1622efe9872eSLisandro Dalcin 
1623efe9872eSLisandro Dalcin   PetscFunctionBegin;
1624efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1625efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1626efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1627efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1628efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F,VEC_CLASSID,6);
1629efe9872eSLisandro Dalcin 
16309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
16319566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm,&I2Function,&ctx));
16329566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm,&rhsfunction,NULL));
1633efe9872eSLisandro Dalcin 
1634efe9872eSLisandro Dalcin   if (!I2Function) {
16359566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts,t,U,A,F,PETSC_FALSE));
1636efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1637efe9872eSLisandro Dalcin   }
1638efe9872eSLisandro Dalcin 
16399566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval,ts,U,V,F));
1640efe9872eSLisandro Dalcin 
1641efe9872eSLisandro Dalcin   PetscStackPush("TS user implicit function");
16429566063dSJacob Faibussowitsch   PetscCall(I2Function(ts,t,U,V,A,F,ctx));
1643efe9872eSLisandro Dalcin   PetscStackPop;
1644efe9872eSLisandro Dalcin 
1645efe9872eSLisandro Dalcin   if (rhsfunction) {
1646efe9872eSLisandro Dalcin     Vec Frhs;
16479566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts,&Frhs));
16489566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts,t,U,Frhs));
16499566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F,-1,Frhs));
1650efe9872eSLisandro Dalcin   }
1651efe9872eSLisandro Dalcin 
16529566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval,ts,U,V,F));
1653efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1654efe9872eSLisandro Dalcin }
1655efe9872eSLisandro Dalcin 
1656efe9872eSLisandro Dalcin /*@
1657efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1658efe9872eSLisandro Dalcin 
1659d083f849SBarry Smith   Collective on TS
1660efe9872eSLisandro Dalcin 
1661efe9872eSLisandro Dalcin   Input Parameters:
1662efe9872eSLisandro Dalcin + ts - the TS context
1663efe9872eSLisandro Dalcin . t - current timestep
1664efe9872eSLisandro Dalcin . U - state vector
1665efe9872eSLisandro Dalcin . V - time derivative of state vector
1666efe9872eSLisandro Dalcin . A - second time derivative of state vector
1667efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1668efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1669efe9872eSLisandro Dalcin 
1670efe9872eSLisandro Dalcin   Output Parameters:
1671efe9872eSLisandro Dalcin + J - Jacobian matrix
1672efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1673efe9872eSLisandro Dalcin 
1674efe9872eSLisandro Dalcin   Notes:
1675efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1676efe9872eSLisandro Dalcin 
1677efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1678efe9872eSLisandro Dalcin 
1679efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1680efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1681efe9872eSLisandro Dalcin 
1682efe9872eSLisandro Dalcin   Level: developer
1683efe9872eSLisandro Dalcin 
1684db781477SPatrick Sanan .seealso: `TSSetI2Jacobian()`
1685efe9872eSLisandro Dalcin @*/
1686efe9872eSLisandro Dalcin PetscErrorCode TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)
1687efe9872eSLisandro Dalcin {
1688efe9872eSLisandro Dalcin   DM             dm;
1689efe9872eSLisandro Dalcin   TSI2Jacobian   I2Jacobian;
1690efe9872eSLisandro Dalcin   void           *ctx;
1691efe9872eSLisandro Dalcin   TSRHSJacobian  rhsjacobian;
1692efe9872eSLisandro Dalcin 
1693efe9872eSLisandro Dalcin   PetscFunctionBegin;
1694efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1695efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
1696efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V,VEC_CLASSID,4);
1697efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A,VEC_CLASSID,5);
1698efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J,MAT_CLASSID,8);
1699efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P,MAT_CLASSID,9);
1700efe9872eSLisandro Dalcin 
17019566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
17029566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,&I2Jacobian,&ctx));
17039566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjacobian,NULL));
1704efe9872eSLisandro Dalcin 
1705efe9872eSLisandro Dalcin   if (!I2Jacobian) {
17069566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts,t,U,A,shiftA,J,P,PETSC_FALSE));
1707efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1708efe9872eSLisandro Dalcin   }
1709efe9872eSLisandro Dalcin 
17109566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval,ts,U,J,P));
1711efe9872eSLisandro Dalcin 
1712efe9872eSLisandro Dalcin   PetscStackPush("TS user implicit Jacobian");
17139566063dSJacob Faibussowitsch   PetscCall(I2Jacobian(ts,t,U,V,A,shiftV,shiftA,J,P,ctx));
1714efe9872eSLisandro Dalcin   PetscStackPop;
1715efe9872eSLisandro Dalcin 
1716efe9872eSLisandro Dalcin   if (rhsjacobian) {
1717d60b7d5cSBarry Smith     Mat Jrhs,Prhs;
17189566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts,&Jrhs,&Prhs));
17199566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts,t,U,Jrhs,Prhs));
17209566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J,-1,Jrhs,ts->axpy_pattern));
17219566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P,-1,Prhs,ts->axpy_pattern));
1722efe9872eSLisandro Dalcin   }
1723efe9872eSLisandro Dalcin 
17249566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval,ts,U,J,P));
1725efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1726efe9872eSLisandro Dalcin }
1727efe9872eSLisandro Dalcin 
1728438f35afSJed Brown /*@C
1729438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1730438f35afSJed Brown 
1731438f35afSJed Brown    Logically Collective
1732438f35afSJed Brown 
17334165533cSJose E. Roman    Input Parameters:
1734438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1735a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1736438f35afSJed Brown -  ctx - a context for tvar
1737438f35afSJed Brown 
1738a96d6ef6SBarry Smith     Calling sequence of tvar:
1739a96d6ef6SBarry Smith $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1740a96d6ef6SBarry Smith 
1741a96d6ef6SBarry Smith +   ts - timestep context
17426aad120cSJose E. Roman .   p - input vector (primitive form)
1743a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1744a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1745a96d6ef6SBarry Smith 
1746438f35afSJed Brown    Level: advanced
1747438f35afSJed Brown 
1748438f35afSJed Brown    Notes:
1749438f35afSJed Brown    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., TSBDF)
1750438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1751438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1752438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1753438f35afSJed Brown    evaluated via the chain rule, as in
1754438f35afSJed Brown 
1755438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1756438f35afSJed Brown 
1757db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1758438f35afSJed Brown @*/
1759438f35afSJed Brown PetscErrorCode TSSetTransientVariable(TS ts,TSTransientVariable tvar,void *ctx)
1760438f35afSJed Brown {
1761438f35afSJed Brown   DM             dm;
1762438f35afSJed Brown 
1763438f35afSJed Brown   PetscFunctionBegin;
1764438f35afSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
17659566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
17669566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm,tvar,ctx));
1767438f35afSJed Brown   PetscFunctionReturn(0);
1768438f35afSJed Brown }
1769438f35afSJed Brown 
1770efe9872eSLisandro Dalcin /*@
1771e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1772e3c11fc1SJed Brown 
1773e3c11fc1SJed Brown    Logically Collective
1774e3c11fc1SJed Brown 
1775e3c11fc1SJed Brown    Input Parameters:
1776e3c11fc1SJed Brown +  ts - TS on which to compute
1777e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1778e3c11fc1SJed Brown 
1779e3c11fc1SJed Brown    Output Parameters:
1780e3c11fc1SJed Brown .  C - transient (conservative) variable
1781e3c11fc1SJed Brown 
1782e3c11fc1SJed Brown    Developer Notes:
1783e3c11fc1SJed Brown    If DMTSSetTransientVariable() has not been called, then C is not modified in this routine and C=NULL is allowed.
1784e3c11fc1SJed Brown    This makes it safe to call without a guard.  One can use TSHasTransientVariable() to check if transient variables are
1785e3c11fc1SJed Brown    being used.
1786e3c11fc1SJed Brown 
1787e3c11fc1SJed Brown    Level: developer
1788e3c11fc1SJed Brown 
1789db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1790e3c11fc1SJed Brown @*/
1791e3c11fc1SJed Brown PetscErrorCode TSComputeTransientVariable(TS ts,Vec U,Vec C)
1792e3c11fc1SJed Brown {
1793e3c11fc1SJed Brown   DM             dm;
1794e3c11fc1SJed Brown   DMTS           dmts;
1795e3c11fc1SJed Brown 
1796e3c11fc1SJed Brown   PetscFunctionBegin;
1797e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1798e3c11fc1SJed Brown   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
17999566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
18009566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&dmts));
1801e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1802e3c11fc1SJed Brown     PetscValidHeaderSpecific(C,VEC_CLASSID,3);
18039566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts,U,C,dmts->transientvarctx));
1804e3c11fc1SJed Brown   }
1805e3c11fc1SJed Brown   PetscFunctionReturn(0);
1806e3c11fc1SJed Brown }
1807e3c11fc1SJed Brown 
1808e3c11fc1SJed Brown /*@
1809e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1810e3c11fc1SJed Brown 
1811e3c11fc1SJed Brown    Logically Collective
1812e3c11fc1SJed Brown 
1813e3c11fc1SJed Brown    Input Parameters:
1814e3c11fc1SJed Brown .  ts - TS on which to compute
1815e3c11fc1SJed Brown 
1816e3c11fc1SJed Brown    Output Parameters:
1817e3c11fc1SJed Brown .  has - PETSC_TRUE if transient variables have been set
1818e3c11fc1SJed Brown 
1819e3c11fc1SJed Brown    Level: developer
1820e3c11fc1SJed Brown 
1821db781477SPatrick Sanan .seealso: `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1822e3c11fc1SJed Brown @*/
1823e3c11fc1SJed Brown PetscErrorCode TSHasTransientVariable(TS ts,PetscBool *has)
1824e3c11fc1SJed Brown {
1825e3c11fc1SJed Brown   DM             dm;
1826e3c11fc1SJed Brown   DMTS           dmts;
1827e3c11fc1SJed Brown 
1828e3c11fc1SJed Brown   PetscFunctionBegin;
1829e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
18309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
18319566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm,&dmts));
1832e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1833e3c11fc1SJed Brown   PetscFunctionReturn(0);
1834e3c11fc1SJed Brown }
1835e3c11fc1SJed Brown 
1836e3c11fc1SJed Brown /*@
1837efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1838efe9872eSLisandro Dalcin    for use by the TS routines handling second order equations.
1839efe9872eSLisandro Dalcin 
1840d083f849SBarry Smith    Logically Collective on TS
1841efe9872eSLisandro Dalcin 
1842efe9872eSLisandro Dalcin    Input Parameters:
1843efe9872eSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
1844efe9872eSLisandro Dalcin .  u - the solution vector
1845efe9872eSLisandro Dalcin -  v - the time derivative vector
1846efe9872eSLisandro Dalcin 
1847efe9872eSLisandro Dalcin    Level: beginner
1848efe9872eSLisandro Dalcin 
1849efe9872eSLisandro Dalcin @*/
1850efe9872eSLisandro Dalcin PetscErrorCode  TS2SetSolution(TS ts,Vec u,Vec v)
1851efe9872eSLisandro Dalcin {
1852efe9872eSLisandro Dalcin   PetscFunctionBegin;
1853efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1854efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
1855efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v,VEC_CLASSID,3);
18569566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts,u));
18579566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18589566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1859efe9872eSLisandro Dalcin   ts->vec_dot = v;
1860efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1861efe9872eSLisandro Dalcin }
1862efe9872eSLisandro Dalcin 
1863efe9872eSLisandro Dalcin /*@
1864efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1865efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1866efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1867efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1868efe9872eSLisandro Dalcin 
1869efe9872eSLisandro Dalcin    Not Collective, but Vec returned is parallel if TS is parallel
1870efe9872eSLisandro Dalcin 
1871efe9872eSLisandro Dalcin    Input Parameter:
1872efe9872eSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
1873efe9872eSLisandro Dalcin 
1874d8d19677SJose E. Roman    Output Parameters:
1875efe9872eSLisandro Dalcin +  u - the vector containing the solution
1876efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1877efe9872eSLisandro Dalcin 
1878efe9872eSLisandro Dalcin    Level: intermediate
1879efe9872eSLisandro Dalcin 
1880db781477SPatrick Sanan .seealso: `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1881efe9872eSLisandro Dalcin 
1882efe9872eSLisandro Dalcin @*/
1883efe9872eSLisandro Dalcin PetscErrorCode  TS2GetSolution(TS ts,Vec *u,Vec *v)
1884efe9872eSLisandro Dalcin {
1885efe9872eSLisandro Dalcin   PetscFunctionBegin;
1886efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
1887efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u,2);
1888efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v,3);
1889efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1890efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
1891efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1892efe9872eSLisandro Dalcin }
1893efe9872eSLisandro Dalcin 
189455849f57SBarry Smith /*@C
189555849f57SBarry Smith   TSLoad - Loads a KSP that has been stored in binary  with KSPView().
189655849f57SBarry Smith 
189755849f57SBarry Smith   Collective on PetscViewer
189855849f57SBarry Smith 
189955849f57SBarry Smith   Input Parameters:
190055849f57SBarry Smith + newdm - the newly loaded TS, this needs to have been created with TSCreate() or
190155849f57SBarry Smith            some related function before a call to TSLoad().
190255849f57SBarry Smith - viewer - binary file viewer, obtained from PetscViewerBinaryOpen()
190355849f57SBarry Smith 
190455849f57SBarry Smith    Level: intermediate
190555849f57SBarry Smith 
190655849f57SBarry Smith   Notes:
190755849f57SBarry Smith    The type is determined by the data in the file, any type set into the TS before this call is ignored.
190855849f57SBarry Smith 
190955849f57SBarry Smith   Notes for advanced users:
191055849f57SBarry Smith   Most users should not need to know the details of the binary storage
191155849f57SBarry Smith   format, since TSLoad() and TSView() completely hide these details.
191255849f57SBarry Smith   But for anyone who's interested, the standard binary matrix storage
191355849f57SBarry Smith   format is
191455849f57SBarry Smith .vb
191555849f57SBarry Smith      has not yet been determined
191655849f57SBarry Smith .ve
191755849f57SBarry Smith 
1918db781477SPatrick Sanan .seealso: `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
191955849f57SBarry Smith @*/
1920f2c2a1b9SBarry Smith PetscErrorCode  TSLoad(TS ts, PetscViewer viewer)
192155849f57SBarry Smith {
192255849f57SBarry Smith   PetscBool      isbinary;
192355849f57SBarry Smith   PetscInt       classid;
192455849f57SBarry Smith   char           type[256];
19252d53ad75SBarry Smith   DMTS           sdm;
1926ad6bc421SBarry Smith   DM             dm;
192755849f57SBarry Smith 
192855849f57SBarry Smith   PetscFunctionBegin;
1929f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
193055849f57SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
19319566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
19323c633725SBarry Smith   PetscCheck(isbinary,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Invalid viewer; open viewer with PetscViewerBinaryOpen()");
193355849f57SBarry Smith 
19349566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,&classid,1,NULL,PETSC_INT));
19353c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Not TS next in file");
19369566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer,type,256,NULL,PETSC_CHAR));
19379566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
19381baa6e33SBarry Smith   if (ts->ops->load) PetscCall((*ts->ops->load)(ts,viewer));
19399566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts),&dm));
19409566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm,viewer));
19419566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts,dm));
19429566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm,&ts->vec_sol));
19439566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol,viewer));
19449566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm,&sdm));
19459566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm,viewer));
194655849f57SBarry Smith   PetscFunctionReturn(0);
194755849f57SBarry Smith }
194855849f57SBarry Smith 
19499804daf3SBarry Smith #include <petscdraw.h>
1950e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1951e04113cfSBarry Smith #include <petscviewersaws.h>
1952f05ece33SBarry Smith #endif
1953fe2efc57SMark 
1954fe2efc57SMark /*@C
1955fe2efc57SMark    TSViewFromOptions - View from Options
1956fe2efc57SMark 
1957fe2efc57SMark    Collective on TS
1958fe2efc57SMark 
1959fe2efc57SMark    Input Parameters:
1960fe2efc57SMark +  A - the application ordering context
1961736c3998SJose E. Roman .  obj - Optional object
1962736c3998SJose E. Roman -  name - command line option
1963fe2efc57SMark 
1964fe2efc57SMark    Level: intermediate
1965db781477SPatrick Sanan .seealso: `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1966fe2efc57SMark @*/
1967fe2efc57SMark PetscErrorCode  TSViewFromOptions(TS A,PetscObject obj,const char name[])
1968fe2efc57SMark {
1969fe2efc57SMark   PetscFunctionBegin;
1970fe2efc57SMark   PetscValidHeaderSpecific(A,TS_CLASSID,1);
19719566063dSJacob Faibussowitsch   PetscCall(PetscObjectViewFromOptions((PetscObject)A,obj,name));
1972fe2efc57SMark   PetscFunctionReturn(0);
1973fe2efc57SMark }
1974fe2efc57SMark 
19757e2c5f70SBarry Smith /*@C
1976d763cef2SBarry Smith     TSView - Prints the TS data structure.
1977d763cef2SBarry Smith 
19784c49b128SBarry Smith     Collective on TS
1979d763cef2SBarry Smith 
1980d763cef2SBarry Smith     Input Parameters:
1981d763cef2SBarry Smith +   ts - the TS context obtained from TSCreate()
1982d763cef2SBarry Smith -   viewer - visualization context
1983d763cef2SBarry Smith 
1984d763cef2SBarry Smith     Options Database Key:
1985d763cef2SBarry Smith .   -ts_view - calls TSView() at end of TSStep()
1986d763cef2SBarry Smith 
1987d763cef2SBarry Smith     Notes:
1988d763cef2SBarry Smith     The available visualization contexts include
1989b0a32e0cSBarry Smith +     PETSC_VIEWER_STDOUT_SELF - standard output (default)
1990b0a32e0cSBarry Smith -     PETSC_VIEWER_STDOUT_WORLD - synchronized standard
1991d763cef2SBarry Smith          output where only the first processor opens
1992d763cef2SBarry Smith          the file.  All other processors send their
1993d763cef2SBarry Smith          data to the first processor to print.
1994d763cef2SBarry Smith 
1995d763cef2SBarry Smith     The user can open an alternative visualization context with
1996b0a32e0cSBarry Smith     PetscViewerASCIIOpen() - output to a specified file.
1997d763cef2SBarry Smith 
1998595c91d4SBarry Smith     In the debugger you can do "call TSView(ts,0)" to display the TS solver. (The same holds for any PETSc object viewer).
1999595c91d4SBarry Smith 
2000d763cef2SBarry Smith     Level: beginner
2001d763cef2SBarry Smith 
2002db781477SPatrick Sanan .seealso: `PetscViewerASCIIOpen()`
2003d763cef2SBarry Smith @*/
20047087cfbeSBarry Smith PetscErrorCode  TSView(TS ts,PetscViewer viewer)
2005d763cef2SBarry Smith {
200619fd82e9SBarry Smith   TSType         type;
20072b0a91c0SBarry Smith   PetscBool      iascii,isstring,isundials,isbinary,isdraw;
20082d53ad75SBarry Smith   DMTS           sdm;
2009e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2010536b137fSBarry Smith   PetscBool      issaws;
2011f05ece33SBarry Smith #endif
2012d763cef2SBarry Smith 
2013d763cef2SBarry Smith   PetscFunctionBegin;
20140700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
20153050cee2SBarry Smith   if (!viewer) {
20169566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts),&viewer));
20173050cee2SBarry Smith   }
20180700a824SBarry Smith   PetscValidHeaderSpecific(viewer,PETSC_VIEWER_CLASSID,2);
2019c9780b6fSBarry Smith   PetscCheckSameComm(ts,1,viewer,2);
2020fd16b177SBarry Smith 
20219566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERASCII,&iascii));
20229566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSTRING,&isstring));
20239566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERBINARY,&isbinary));
20249566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERDRAW,&isdraw));
2025e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
20269566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer,PETSCVIEWERSAWS,&issaws));
2027f05ece33SBarry Smith #endif
202832077d6dSBarry Smith   if (iascii) {
20299566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts,viewer));
2030efd4aadfSBarry Smith     if (ts->ops->view) {
20319566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
20329566063dSJacob Faibussowitsch       PetscCall((*ts->ops->view)(ts,viewer));
20339566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
2034efd4aadfSBarry Smith     }
2035ef85077eSLisandro Dalcin     if (ts->max_steps < PETSC_MAX_INT) {
203663a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum steps=%" PetscInt_FMT "\n",ts->max_steps));
2037ef85077eSLisandro Dalcin     }
2038ef85077eSLisandro Dalcin     if (ts->max_time < PETSC_MAX_REAL) {
20399566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  maximum time=%g\n",(double)ts->max_time));
2040ef85077eSLisandro Dalcin     }
2041a6ab3590SBarry Smith     if (ts->ifuncs) {
204263a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of I function evaluations=%" PetscInt_FMT "\n",ts->ifuncs));
2043a6ab3590SBarry Smith     }
2044a6ab3590SBarry Smith     if (ts->ijacs) {
204563a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of I Jacobian evaluations=%" PetscInt_FMT "\n",ts->ijacs));
2046a6ab3590SBarry Smith     }
2047a6ab3590SBarry Smith     if (ts->rhsfuncs) {
204863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of RHS function evaluations=%" PetscInt_FMT "\n",ts->rhsfuncs));
2049a6ab3590SBarry Smith     }
2050a6ab3590SBarry Smith     if (ts->rhsjacs) {
205163a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n",ts->rhsjacs));
2052a6ab3590SBarry Smith     }
2053efd4aadfSBarry Smith     if (ts->usessnes) {
2054efd4aadfSBarry Smith       PetscBool lin;
2055d763cef2SBarry Smith       if (ts->problem_type == TS_NONLINEAR) {
205663a3b9bcSJacob Faibussowitsch         PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of nonlinear solver iterations=%" PetscInt_FMT "\n",ts->snes_its));
2057d763cef2SBarry Smith       }
205863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of linear solver iterations=%" PetscInt_FMT "\n",ts->ksp_its));
20599566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes,&lin,SNESKSPONLY,SNESKSPTRANSPOSEONLY,""));
206063a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of %slinear solve failures=%" PetscInt_FMT "\n",lin ? "" : "non",ts->num_snes_failures));
2061efd4aadfSBarry Smith     }
206263a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer,"  total number of rejected steps=%" PetscInt_FMT "\n",ts->reject));
2063a0af407cSBarry Smith     if (ts->vrtol) {
20649566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  using vector of relative error tolerances, "));
2065a0af407cSBarry Smith     } else {
20669566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  using relative error tolerance of %g, ",(double)ts->rtol));
2067a0af407cSBarry Smith     }
2068a0af407cSBarry Smith     if (ts->vatol) {
20699566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  using vector of absolute error tolerances\n"));
2070a0af407cSBarry Smith     } else {
20719566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer,"  using absolute error tolerance of %g\n",(double)ts->atol));
2072a0af407cSBarry Smith     }
20739566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20749566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt,viewer));
20759566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
20760f5bd95cSBarry Smith   } else if (isstring) {
20779566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts,&type));
20789566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer," TSType: %-7.7s",type));
20799566063dSJacob Faibussowitsch     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
208055849f57SBarry Smith   } else if (isbinary) {
208155849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
208255849f57SBarry Smith     MPI_Comm    comm;
208355849f57SBarry Smith     PetscMPIInt rank;
208455849f57SBarry Smith     char        type[256];
208555849f57SBarry Smith 
20869566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts,&comm));
20879566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm,&rank));
2088dd400576SPatrick Sanan     if (rank == 0) {
20899566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,&classid,1,PETSC_INT));
20909566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type,((PetscObject)ts)->type_name,256));
20919566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer,type,256,PETSC_CHAR));
209255849f57SBarry Smith     }
20931baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
20949566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt,viewer));
20959566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm,viewer));
20969566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol,viewer));
20979566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm,&sdm));
20989566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm,viewer));
20992b0a91c0SBarry Smith   } else if (isdraw) {
21002b0a91c0SBarry Smith     PetscDraw draw;
21012b0a91c0SBarry Smith     char      str[36];
210289fd9fafSBarry Smith     PetscReal x,y,bottom,h;
21032b0a91c0SBarry Smith 
21049566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer,0,&draw));
21059566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw,&x,&y));
21069566063dSJacob Faibussowitsch     PetscCall(PetscStrcpy(str,"TS: "));
21079566063dSJacob Faibussowitsch     PetscCall(PetscStrcat(str,((PetscObject)ts)->type_name));
21089566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw,x,y,PETSC_DRAW_BLACK,PETSC_DRAW_BLACK,str,NULL,&h));
210989fd9fafSBarry Smith     bottom = y - h;
21109566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw,x,bottom));
21111baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
21129566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt,viewer));
21139566063dSJacob Faibussowitsch     if (ts->snes)  PetscCall(SNESView(ts->snes,viewer));
21149566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2115e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2116536b137fSBarry Smith   } else if (issaws) {
2117d45a07a7SBarry Smith     PetscMPIInt rank;
21182657e9d9SBarry Smith     const char  *name;
21192657e9d9SBarry Smith 
21209566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts,&name));
21219566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD,&rank));
2122dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2123d45a07a7SBarry Smith       char       dir[1024];
2124d45a07a7SBarry Smith 
21259566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts,viewer));
21269566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time_step",name));
21272657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,&ts->steps,1,SAWs_READ,SAWs_INT));
21289566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir,1024,"/PETSc/Objects/%s/time",name));
21292657e9d9SBarry Smith       PetscStackCallSAWs(SAWs_Register,(dir,&ts->ptime,1,SAWs_READ,SAWs_DOUBLE));
2130d763cef2SBarry Smith     }
21311baa6e33SBarry Smith     if (ts->ops->view) PetscCall((*ts->ops->view)(ts,viewer));
2132f05ece33SBarry Smith #endif
2133f05ece33SBarry Smith   }
213436a9e3b9SBarry Smith   if (ts->snes && ts->usessnes)  {
21359566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
21369566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes,viewer));
21379566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
213836a9e3b9SBarry Smith   }
21399566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm,&sdm));
21409566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm,viewer));
2141f05ece33SBarry Smith 
21429566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
21439566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts,TSSUNDIALS,&isundials));
21449566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
2145d763cef2SBarry Smith   PetscFunctionReturn(0);
2146d763cef2SBarry Smith }
2147d763cef2SBarry Smith 
2148b07ff414SBarry Smith /*@
2149d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2150d763cef2SBarry Smith    the timesteppers.
2151d763cef2SBarry Smith 
21523f9fe445SBarry Smith    Logically Collective on TS
2153d763cef2SBarry Smith 
2154d763cef2SBarry Smith    Input Parameters:
2155d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2156d763cef2SBarry Smith -  usrP - optional user context
2157d763cef2SBarry Smith 
215895452b02SPatrick Sanan    Fortran Notes:
215995452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2160daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2161daf670e6SBarry Smith 
2162d763cef2SBarry Smith    Level: intermediate
2163d763cef2SBarry Smith 
2164db781477SPatrick Sanan .seealso: `TSGetApplicationContext()`
2165d763cef2SBarry Smith @*/
21667087cfbeSBarry Smith PetscErrorCode  TSSetApplicationContext(TS ts,void *usrP)
2167d763cef2SBarry Smith {
2168d763cef2SBarry Smith   PetscFunctionBegin;
21690700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2170d763cef2SBarry Smith   ts->user = usrP;
2171d763cef2SBarry Smith   PetscFunctionReturn(0);
2172d763cef2SBarry Smith }
2173d763cef2SBarry Smith 
2174b07ff414SBarry Smith /*@
2175d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2176d763cef2SBarry Smith     timestepper.
2177d763cef2SBarry Smith 
2178d763cef2SBarry Smith     Not Collective
2179d763cef2SBarry Smith 
2180d763cef2SBarry Smith     Input Parameter:
2181d763cef2SBarry Smith .   ts - the TS context obtained from TSCreate()
2182d763cef2SBarry Smith 
2183d763cef2SBarry Smith     Output Parameter:
2184d763cef2SBarry Smith .   usrP - user context
2185d763cef2SBarry Smith 
218695452b02SPatrick Sanan    Fortran Notes:
218795452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2188daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2189daf670e6SBarry Smith 
2190d763cef2SBarry Smith     Level: intermediate
2191d763cef2SBarry Smith 
2192db781477SPatrick Sanan .seealso: `TSSetApplicationContext()`
2193d763cef2SBarry Smith @*/
2194e71120c6SJed Brown PetscErrorCode  TSGetApplicationContext(TS ts,void *usrP)
2195d763cef2SBarry Smith {
2196d763cef2SBarry Smith   PetscFunctionBegin;
21970700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2198e71120c6SJed Brown   *(void**)usrP = ts->user;
2199d763cef2SBarry Smith   PetscFunctionReturn(0);
2200d763cef2SBarry Smith }
2201d763cef2SBarry Smith 
2202d763cef2SBarry Smith /*@
220380275a0aSLisandro Dalcin    TSGetStepNumber - Gets the number of steps completed.
2204d763cef2SBarry Smith 
2205d763cef2SBarry Smith    Not Collective
2206d763cef2SBarry Smith 
2207d763cef2SBarry Smith    Input Parameter:
2208d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2209d763cef2SBarry Smith 
2210d763cef2SBarry Smith    Output Parameter:
221180275a0aSLisandro Dalcin .  steps - number of steps completed so far
2212d763cef2SBarry Smith 
2213d763cef2SBarry Smith    Level: intermediate
2214d763cef2SBarry Smith 
2215db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2216d763cef2SBarry Smith @*/
221780275a0aSLisandro Dalcin PetscErrorCode TSGetStepNumber(TS ts,PetscInt *steps)
2218d763cef2SBarry Smith {
2219d763cef2SBarry Smith   PetscFunctionBegin;
22200700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
222180275a0aSLisandro Dalcin   PetscValidIntPointer(steps,2);
222280275a0aSLisandro Dalcin   *steps = ts->steps;
222380275a0aSLisandro Dalcin   PetscFunctionReturn(0);
222480275a0aSLisandro Dalcin }
222580275a0aSLisandro Dalcin 
222680275a0aSLisandro Dalcin /*@
222780275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
222880275a0aSLisandro Dalcin 
222980275a0aSLisandro Dalcin    Logically Collective on TS
223080275a0aSLisandro Dalcin 
223180275a0aSLisandro Dalcin    Input Parameters:
223280275a0aSLisandro Dalcin +  ts - the TS context
223380275a0aSLisandro Dalcin -  steps - number of steps completed so far
223480275a0aSLisandro Dalcin 
223580275a0aSLisandro Dalcin    Notes:
223680275a0aSLisandro Dalcin    For most uses of the TS solvers the user need not explicitly call
223780275a0aSLisandro Dalcin    TSSetStepNumber(), as the step counter is appropriately updated in
223880275a0aSLisandro Dalcin    TSSolve()/TSStep()/TSRollBack(). Power users may call this routine to
223980275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
224080275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
224180275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
224280275a0aSLisandro Dalcin    timestepping from a previously interrupted run in such a way that TS
224380275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
224480275a0aSLisandro Dalcin 
224580275a0aSLisandro Dalcin    Level: advanced
224680275a0aSLisandro Dalcin 
2247db781477SPatrick Sanan .seealso: `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
224880275a0aSLisandro Dalcin @*/
224980275a0aSLisandro Dalcin PetscErrorCode TSSetStepNumber(TS ts,PetscInt steps)
225080275a0aSLisandro Dalcin {
225180275a0aSLisandro Dalcin   PetscFunctionBegin;
225280275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
225380275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts,steps,2);
22543c633725SBarry Smith   PetscCheck(steps >= 0,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Step number must be non-negative");
225580275a0aSLisandro Dalcin   ts->steps = steps;
2256d763cef2SBarry Smith   PetscFunctionReturn(0);
2257d763cef2SBarry Smith }
2258d763cef2SBarry Smith 
2259d763cef2SBarry Smith /*@
2260d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2261d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2262d763cef2SBarry Smith 
22633f9fe445SBarry Smith    Logically Collective on TS
2264d763cef2SBarry Smith 
2265d763cef2SBarry Smith    Input Parameters:
2266d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
2267d763cef2SBarry Smith -  time_step - the size of the timestep
2268d763cef2SBarry Smith 
2269d763cef2SBarry Smith    Level: intermediate
2270d763cef2SBarry Smith 
2271db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSSetTime()`
2272d763cef2SBarry Smith 
2273d763cef2SBarry Smith @*/
22747087cfbeSBarry Smith PetscErrorCode  TSSetTimeStep(TS ts,PetscReal time_step)
2275d763cef2SBarry Smith {
2276d763cef2SBarry Smith   PetscFunctionBegin;
22770700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2278c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts,time_step,2);
2279d763cef2SBarry Smith   ts->time_step = time_step;
2280d763cef2SBarry Smith   PetscFunctionReturn(0);
2281d763cef2SBarry Smith }
2282d763cef2SBarry Smith 
2283a43b19c4SJed Brown /*@
228449354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
228549354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
228649354f04SShri Abhyankar      or just return at the final time TS computed.
2287a43b19c4SJed Brown 
2288a43b19c4SJed Brown   Logically Collective on TS
2289a43b19c4SJed Brown 
2290d8d19677SJose E. Roman    Input Parameters:
2291a43b19c4SJed Brown +   ts - the time-step context
229249354f04SShri Abhyankar -   eftopt - exact final time option
2293a43b19c4SJed Brown 
2294feed9e9dSBarry Smith $  TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2295feed9e9dSBarry Smith $  TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2296feed9e9dSBarry Smith $  TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2297feed9e9dSBarry Smith 
2298feed9e9dSBarry Smith    Options Database:
2299feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2300feed9e9dSBarry Smith 
2301ee346746SBarry Smith    Warning: If you use the option TS_EXACTFINALTIME_STEPOVER the solution may be at a very different time
2302ee346746SBarry Smith     then the final time you selected.
2303ee346746SBarry Smith 
2304a43b19c4SJed Brown    Level: beginner
2305a43b19c4SJed Brown 
2306db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2307a43b19c4SJed Brown @*/
230849354f04SShri Abhyankar PetscErrorCode TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)
2309a43b19c4SJed Brown {
2310a43b19c4SJed Brown   PetscFunctionBegin;
2311a43b19c4SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
231249354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts,eftopt,2);
231349354f04SShri Abhyankar   ts->exact_final_time = eftopt;
2314a43b19c4SJed Brown   PetscFunctionReturn(0);
2315a43b19c4SJed Brown }
2316a43b19c4SJed Brown 
2317d763cef2SBarry Smith /*@
2318f6953c82SLisandro Dalcin    TSGetExactFinalTime - Gets the exact final time option.
2319f6953c82SLisandro Dalcin 
2320f6953c82SLisandro Dalcin    Not Collective
2321f6953c82SLisandro Dalcin 
2322f6953c82SLisandro Dalcin    Input Parameter:
2323f6953c82SLisandro Dalcin .  ts - the TS context
2324f6953c82SLisandro Dalcin 
2325f6953c82SLisandro Dalcin    Output Parameter:
2326f6953c82SLisandro Dalcin .  eftopt - exact final time option
2327f6953c82SLisandro Dalcin 
2328f6953c82SLisandro Dalcin    Level: beginner
2329f6953c82SLisandro Dalcin 
2330db781477SPatrick Sanan .seealso: `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2331f6953c82SLisandro Dalcin @*/
2332f6953c82SLisandro Dalcin PetscErrorCode TSGetExactFinalTime(TS ts,TSExactFinalTimeOption *eftopt)
2333f6953c82SLisandro Dalcin {
2334f6953c82SLisandro Dalcin   PetscFunctionBegin;
2335f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2336f6953c82SLisandro Dalcin   PetscValidPointer(eftopt,2);
2337f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
2338f6953c82SLisandro Dalcin   PetscFunctionReturn(0);
2339f6953c82SLisandro Dalcin }
2340f6953c82SLisandro Dalcin 
2341f6953c82SLisandro Dalcin /*@
2342d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2343d763cef2SBarry Smith 
2344d763cef2SBarry Smith    Not Collective
2345d763cef2SBarry Smith 
2346d763cef2SBarry Smith    Input Parameter:
2347d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2348d763cef2SBarry Smith 
2349d763cef2SBarry Smith    Output Parameter:
2350d763cef2SBarry Smith .  dt - the current timestep size
2351d763cef2SBarry Smith 
2352d763cef2SBarry Smith    Level: intermediate
2353d763cef2SBarry Smith 
2354db781477SPatrick Sanan .seealso: `TSSetTimeStep()`, `TSGetTime()`
2355d763cef2SBarry Smith 
2356d763cef2SBarry Smith @*/
23577087cfbeSBarry Smith PetscErrorCode  TSGetTimeStep(TS ts,PetscReal *dt)
2358d763cef2SBarry Smith {
2359d763cef2SBarry Smith   PetscFunctionBegin;
23600700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2361f7cf8827SBarry Smith   PetscValidRealPointer(dt,2);
2362d763cef2SBarry Smith   *dt = ts->time_step;
2363d763cef2SBarry Smith   PetscFunctionReturn(0);
2364d763cef2SBarry Smith }
2365d763cef2SBarry Smith 
2366d8e5e3e6SSatish Balay /*@
2367d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2368d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2369d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2370d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2371d763cef2SBarry Smith 
2372d763cef2SBarry Smith    Not Collective, but Vec returned is parallel if TS is parallel
2373d763cef2SBarry Smith 
2374d763cef2SBarry Smith    Input Parameter:
2375d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2376d763cef2SBarry Smith 
2377d763cef2SBarry Smith    Output Parameter:
2378d763cef2SBarry Smith .  v - the vector containing the solution
2379d763cef2SBarry Smith 
238063e21af5SBarry Smith    Note: If you used TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP); this does not return the solution at the requested
238163e21af5SBarry Smith    final time. It returns the solution at the next timestep.
238263e21af5SBarry Smith 
2383d763cef2SBarry Smith    Level: intermediate
2384d763cef2SBarry Smith 
2385db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2386d763cef2SBarry Smith 
2387d763cef2SBarry Smith @*/
23887087cfbeSBarry Smith PetscErrorCode  TSGetSolution(TS ts,Vec *v)
2389d763cef2SBarry Smith {
2390d763cef2SBarry Smith   PetscFunctionBegin;
23910700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
23924482741eSBarry Smith   PetscValidPointer(v,2);
23938737fe31SLisandro Dalcin   *v = ts->vec_sol;
2394d763cef2SBarry Smith   PetscFunctionReturn(0);
2395d763cef2SBarry Smith }
2396d763cef2SBarry Smith 
239703fe5f5eSDebojyoti Ghosh /*@
2398b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
239903fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2400b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
240103fe5f5eSDebojyoti Ghosh    structure as the solution vector.
240203fe5f5eSDebojyoti Ghosh 
240303fe5f5eSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
240403fe5f5eSDebojyoti Ghosh 
240503fe5f5eSDebojyoti Ghosh    Parameters :
2406a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2407b2bf4f3aSDebojyoti Ghosh .  n - If v is PETSC_NULL, then the number of solution components is
2408b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
240903fe5f5eSDebojyoti Ghosh        returned in v.
2410a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
241103fe5f5eSDebojyoti Ghosh        (may be PETSC_NULL to use this function to find out
2412b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
241303fe5f5eSDebojyoti Ghosh 
24144cdd57e5SDebojyoti Ghosh    Level: advanced
241503fe5f5eSDebojyoti Ghosh 
2416db781477SPatrick Sanan .seealso: `TSGetSolution()`
241703fe5f5eSDebojyoti Ghosh 
241803fe5f5eSDebojyoti Ghosh @*/
2419b2bf4f3aSDebojyoti Ghosh PetscErrorCode  TSGetSolutionComponents(TS ts,PetscInt *n,Vec *v)
242003fe5f5eSDebojyoti Ghosh {
242103fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
242203fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2423b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
242403fe5f5eSDebojyoti Ghosh   else {
24259566063dSJacob Faibussowitsch     PetscCall((*ts->ops->getsolutioncomponents)(ts,n,v));
242603fe5f5eSDebojyoti Ghosh   }
242703fe5f5eSDebojyoti Ghosh   PetscFunctionReturn(0);
242803fe5f5eSDebojyoti Ghosh }
242903fe5f5eSDebojyoti Ghosh 
24304cdd57e5SDebojyoti Ghosh /*@
24314cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
24324cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
24334cdd57e5SDebojyoti Ghosh 
24344cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
24354cdd57e5SDebojyoti Ghosh 
24364cdd57e5SDebojyoti Ghosh    Parameters :
2437a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2438a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
24394cdd57e5SDebojyoti Ghosh 
24404cdd57e5SDebojyoti Ghosh    Level: intermediate
24414cdd57e5SDebojyoti Ghosh 
2442db781477SPatrick Sanan .seealso: `TSGetSolution()`
24434cdd57e5SDebojyoti Ghosh 
24444cdd57e5SDebojyoti Ghosh @*/
24454cdd57e5SDebojyoti Ghosh PetscErrorCode  TSGetAuxSolution(TS ts,Vec *v)
24464cdd57e5SDebojyoti Ghosh {
24474cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24484cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2449f6356ec7SDebojyoti Ghosh   if (ts->ops->getauxsolution) {
24509566063dSJacob Faibussowitsch     PetscCall((*ts->ops->getauxsolution)(ts,v));
2451f6356ec7SDebojyoti Ghosh   } else {
24529566063dSJacob Faibussowitsch     PetscCall(VecZeroEntries(*v));
2453f6356ec7SDebojyoti Ghosh   }
24544cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
24554cdd57e5SDebojyoti Ghosh }
24564cdd57e5SDebojyoti Ghosh 
24574cdd57e5SDebojyoti Ghosh /*@
24584cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
24594cdd57e5SDebojyoti Ghosh    TSType has an error estimation functionality.
24604cdd57e5SDebojyoti Ghosh 
24614cdd57e5SDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
24624cdd57e5SDebojyoti Ghosh 
24639657682dSDebojyoti Ghosh    Note: MUST call after TSSetUp()
24649657682dSDebojyoti Ghosh 
24654cdd57e5SDebojyoti Ghosh    Parameters :
2466a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2467657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2468a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
24694cdd57e5SDebojyoti Ghosh 
24704cdd57e5SDebojyoti Ghosh    Level: intermediate
24714cdd57e5SDebojyoti Ghosh 
2472db781477SPatrick Sanan .seealso: `TSGetSolution()`, `TSSetTimeError()`
24734cdd57e5SDebojyoti Ghosh 
24744cdd57e5SDebojyoti Ghosh @*/
24750a01e1b2SEmil Constantinescu PetscErrorCode  TSGetTimeError(TS ts,PetscInt n,Vec *v)
24764cdd57e5SDebojyoti Ghosh {
24774cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
24784cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2479f6356ec7SDebojyoti Ghosh   if (ts->ops->gettimeerror) {
24809566063dSJacob Faibussowitsch     PetscCall((*ts->ops->gettimeerror)(ts,n,v));
2481f6356ec7SDebojyoti Ghosh   } else {
24829566063dSJacob Faibussowitsch     PetscCall(VecZeroEntries(*v));
2483f6356ec7SDebojyoti Ghosh   }
24844cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
24854cdd57e5SDebojyoti Ghosh }
24864cdd57e5SDebojyoti Ghosh 
248757df6a1bSDebojyoti Ghosh /*@
248857df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
248957df6a1bSDebojyoti Ghosh    TSType has an error estimation functionality. This can be used
249057df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
249157df6a1bSDebojyoti Ghosh 
249257df6a1bSDebojyoti Ghosh    Not Collective, but Vec returned is parallel if TS is parallel
249357df6a1bSDebojyoti Ghosh 
249457df6a1bSDebojyoti Ghosh    Parameters :
2495a2b725a8SWilliam Gropp +  ts - the TS context obtained from TSCreate() (input parameter).
2496a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
249757df6a1bSDebojyoti Ghosh 
249857df6a1bSDebojyoti Ghosh    Level: intermediate
249957df6a1bSDebojyoti Ghosh 
2500db781477SPatrick Sanan .seealso: `TSSetSolution()`, `TSGetTimeError)`
250157df6a1bSDebojyoti Ghosh 
250257df6a1bSDebojyoti Ghosh @*/
250357df6a1bSDebojyoti Ghosh PetscErrorCode  TSSetTimeError(TS ts,Vec v)
250457df6a1bSDebojyoti Ghosh {
250557df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
250657df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
25073c633725SBarry Smith   PetscCheck(ts->setupcalled,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetUp() first");
25081baa6e33SBarry Smith   if (ts->ops->settimeerror) PetscCall((*ts->ops->settimeerror)(ts,v));
250957df6a1bSDebojyoti Ghosh   PetscFunctionReturn(0);
251057df6a1bSDebojyoti Ghosh }
251157df6a1bSDebojyoti Ghosh 
2512bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2513d8e5e3e6SSatish Balay /*@
2514bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2515d763cef2SBarry Smith 
2516bdad233fSMatthew Knepley   Not collective
2517d763cef2SBarry Smith 
2518bdad233fSMatthew Knepley   Input Parameters:
2519bdad233fSMatthew Knepley + ts   - The TS
2520bdad233fSMatthew Knepley - type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2521d763cef2SBarry Smith .vb
25220910c330SBarry Smith          U_t - A U = 0      (linear)
25230910c330SBarry Smith          U_t - A(t) U = 0   (linear)
25240910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2525d763cef2SBarry Smith .ve
2526d763cef2SBarry Smith 
2527d763cef2SBarry Smith    Level: beginner
2528d763cef2SBarry Smith 
2529db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2530d763cef2SBarry Smith @*/
25317087cfbeSBarry Smith PetscErrorCode  TSSetProblemType(TS ts, TSProblemType type)
2532a7cc72afSBarry Smith {
2533d763cef2SBarry Smith   PetscFunctionBegin;
25340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
2535bdad233fSMatthew Knepley   ts->problem_type = type;
25369e2a6581SJed Brown   if (type == TS_LINEAR) {
25379e2a6581SJed Brown     SNES snes;
25389566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
25399566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes,SNESKSPONLY));
25409e2a6581SJed Brown   }
2541d763cef2SBarry Smith   PetscFunctionReturn(0);
2542d763cef2SBarry Smith }
2543d763cef2SBarry Smith 
2544bdad233fSMatthew Knepley /*@C
2545bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2546bdad233fSMatthew Knepley 
2547bdad233fSMatthew Knepley   Not collective
2548bdad233fSMatthew Knepley 
2549bdad233fSMatthew Knepley   Input Parameter:
2550bdad233fSMatthew Knepley . ts   - The TS
2551bdad233fSMatthew Knepley 
2552bdad233fSMatthew Knepley   Output Parameter:
2553bdad233fSMatthew Knepley . type - One of TS_LINEAR, TS_NONLINEAR where these types refer to problems of the forms
2554bdad233fSMatthew Knepley .vb
2555089b2837SJed Brown          M U_t = A U
2556089b2837SJed Brown          M(t) U_t = A(t) U
2557b5abc632SBarry Smith          F(t,U,U_t)
2558bdad233fSMatthew Knepley .ve
2559bdad233fSMatthew Knepley 
2560bdad233fSMatthew Knepley    Level: beginner
2561bdad233fSMatthew Knepley 
2562db781477SPatrick Sanan .seealso: `TSSetUp()`, `TSProblemType`, `TS`
2563bdad233fSMatthew Knepley @*/
25647087cfbeSBarry Smith PetscErrorCode  TSGetProblemType(TS ts, TSProblemType *type)
2565a7cc72afSBarry Smith {
2566bdad233fSMatthew Knepley   PetscFunctionBegin;
25670700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
25684482741eSBarry Smith   PetscValidIntPointer(type,2);
2569bdad233fSMatthew Knepley   *type = ts->problem_type;
2570bdad233fSMatthew Knepley   PetscFunctionReturn(0);
2571bdad233fSMatthew Knepley }
2572d763cef2SBarry Smith 
2573303a5415SBarry Smith /*
2574303a5415SBarry 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()
2575303a5415SBarry Smith */
2576303a5415SBarry Smith static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2577303a5415SBarry Smith {
2578303a5415SBarry Smith   PetscBool      isnone;
2579303a5415SBarry Smith 
2580303a5415SBarry Smith   PetscFunctionBegin;
25819566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
25829566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
2583303a5415SBarry Smith 
25849566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt,TSADAPTNONE,&isnone));
2585303a5415SBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2586303a5415SBarry Smith     ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
2587303a5415SBarry Smith   } else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) {
2588303a5415SBarry Smith     ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2589303a5415SBarry Smith   }
2590303a5415SBarry Smith   PetscFunctionReturn(0);
2591303a5415SBarry Smith }
2592303a5415SBarry Smith 
2593d763cef2SBarry Smith /*@
2594303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2595d763cef2SBarry Smith 
2596d763cef2SBarry Smith    Collective on TS
2597d763cef2SBarry Smith 
2598d763cef2SBarry Smith    Input Parameter:
2599d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2600d763cef2SBarry Smith 
2601d763cef2SBarry Smith    Notes:
2602d763cef2SBarry Smith    For basic use of the TS solvers the user need not explicitly call
2603d763cef2SBarry Smith    TSSetUp(), since these actions will automatically occur during
2604141bd67dSStefano Zampini    the call to TSStep() or TSSolve().  However, if one wishes to control this
2605d763cef2SBarry Smith    phase separately, TSSetUp() should be called after TSCreate()
2606141bd67dSStefano Zampini    and optional routines of the form TSSetXXX(), but before TSStep() and TSSolve().
2607d763cef2SBarry Smith 
2608d763cef2SBarry Smith    Level: advanced
2609d763cef2SBarry Smith 
2610db781477SPatrick Sanan .seealso: `TSCreate()`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2611d763cef2SBarry Smith @*/
26127087cfbeSBarry Smith PetscErrorCode  TSSetUp(TS ts)
2613d763cef2SBarry Smith {
26146c6b9e74SPeter Brune   DM             dm;
26156c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES,Vec,Vec,void*);
2616d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES,Vec,Mat,Mat,void*);
2617cd11d68dSLisandro Dalcin   TSIFunction    ifun;
26186c6b9e74SPeter Brune   TSIJacobian    ijac;
2619efe9872eSLisandro Dalcin   TSI2Jacobian   i2jac;
26206c6b9e74SPeter Brune   TSRHSJacobian  rhsjac;
2621d763cef2SBarry Smith 
2622d763cef2SBarry Smith   PetscFunctionBegin;
26230700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2624277b19d0SLisandro Dalcin   if (ts->setupcalled) PetscFunctionReturn(0);
2625277b19d0SLisandro Dalcin 
26267adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
26279566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts,NULL,&ifun,NULL));
26289566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts,ifun ? TSBEULER : TSEULER));
2629d763cef2SBarry Smith   }
2630277b19d0SLisandro Dalcin 
26311a638600SStefano Zampini   if (!ts->vec_sol) {
26321a638600SStefano Zampini     if (ts->dm) {
26339566063dSJacob Faibussowitsch       PetscCall(DMCreateGlobalVector(ts->dm,&ts->vec_sol));
26341a638600SStefano Zampini     } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_ARG_WRONGSTATE,"Must call TSSetSolution() first");
26351a638600SStefano Zampini   }
2636277b19d0SLisandro Dalcin 
26374a658b32SHong Zhang   if (ts->tspan) {
26384a658b32SHong Zhang     if (!ts->tspan->vecs_sol) {
26394a658b32SHong Zhang       PetscCall(VecDuplicateVecs(ts->vec_sol,ts->tspan->num_span_times,&ts->tspan->vecs_sol));
26404a658b32SHong Zhang     }
26414a658b32SHong Zhang   }
2642298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
26439566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2644298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2645298bade4SHong Zhang   }
2646298bade4SHong Zhang 
2647cd4cee2dSHong Zhang   if (ts->quadraturets) {
26489566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
26499566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
26509566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol,&ts->vec_costintegrand));
2651cd4cee2dSHong Zhang   }
2652cd4cee2dSHong Zhang 
26539566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,NULL,NULL,&rhsjac,NULL));
2654f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2655e1244c69SJed Brown     Mat Amat,Pmat;
2656e1244c69SJed Brown     SNES snes;
26579566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
26589566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,&Amat,&Pmat,NULL,NULL));
2659e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2660e1244c69SJed Brown      * have displaced the RHS matrix */
2661971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2662abc0d4abSBarry 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 */
26639566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs,MAT_COPY_VALUES,&Amat));
26649566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,Amat,NULL,NULL,NULL));
26659566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2666e1244c69SJed Brown     }
2667971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
26689566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs,MAT_COPY_VALUES,&Pmat));
26699566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes,NULL,Pmat,NULL,NULL));
26709566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2671e1244c69SJed Brown     }
2672e1244c69SJed Brown   }
26732ffb9264SLisandro Dalcin 
26749566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts,&ts->adapt));
26759566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt,ts->default_adapt_type));
26762ffb9264SLisandro Dalcin 
26771baa6e33SBarry Smith   if (ts->ops->setup) PetscCall((*ts->ops->setup)(ts));
2678277b19d0SLisandro Dalcin 
26799566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
26802ffb9264SLisandro Dalcin 
2681a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
26826c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
26836c6b9e74SPeter Brune    */
26849566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
26859566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm,&func,NULL));
26866c6b9e74SPeter Brune   if (!func) {
26879566063dSJacob Faibussowitsch     PetscCall(DMSNESSetFunction(dm,SNESTSFormFunction,ts));
26886c6b9e74SPeter Brune   }
2689a6772fa2SLisandro 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.
26906c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
26916c6b9e74SPeter Brune    */
26929566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm,&jac,NULL));
26939566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,&ijac,NULL));
26949566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm,&i2jac,NULL));
26959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,&rhsjac,NULL));
2696efe9872eSLisandro Dalcin   if (!jac && (ijac || i2jac || rhsjac)) {
26979566063dSJacob Faibussowitsch     PetscCall(DMSNESSetJacobian(dm,SNESTSFormJacobian,ts));
26986c6b9e74SPeter Brune   }
2699c0517034SDebojyoti Ghosh 
2700c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
27011baa6e33SBarry Smith   if (ts->ops->startingmethod) PetscCall((*ts->ops->startingmethod)(ts));
2702c0517034SDebojyoti Ghosh 
2703277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
2704277b19d0SLisandro Dalcin   PetscFunctionReturn(0);
2705277b19d0SLisandro Dalcin }
2706277b19d0SLisandro Dalcin 
2707f6a906c0SBarry Smith /*@
2708277b19d0SLisandro Dalcin    TSReset - Resets a TS context and removes any allocated Vecs and Mats.
2709277b19d0SLisandro Dalcin 
2710277b19d0SLisandro Dalcin    Collective on TS
2711277b19d0SLisandro Dalcin 
2712277b19d0SLisandro Dalcin    Input Parameter:
2713277b19d0SLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2714277b19d0SLisandro Dalcin 
2715277b19d0SLisandro Dalcin    Level: beginner
2716277b19d0SLisandro Dalcin 
2717db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetup()`, `TSDestroy()`
2718277b19d0SLisandro Dalcin @*/
2719277b19d0SLisandro Dalcin PetscErrorCode  TSReset(TS ts)
2720277b19d0SLisandro Dalcin {
27211d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit,next;
2722277b19d0SLisandro Dalcin 
2723277b19d0SLisandro Dalcin   PetscFunctionBegin;
2724277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2725b18ea86cSHong Zhang 
27261baa6e33SBarry Smith   if (ts->ops->reset) PetscCall((*ts->ops->reset)(ts));
27279566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
27289566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2729bbd56ea5SKarl Rupp 
27309566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
27319566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
27329566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
27339566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
27349566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
27359566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
27369566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
27379566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork,&ts->work));
2738bbd56ea5SKarl Rupp 
27399566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
27409566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
27411baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2742cd4cee2dSHong Zhang   if (ts->quadraturets) {
27439566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
27449566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2745cd4cee2dSHong Zhang   }
27461d06f6b3SHong Zhang   while (ilink) {
27471d06f6b3SHong Zhang     next = ilink->next;
27489566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
27499566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
27509566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
27519566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
27521d06f6b3SHong Zhang     ilink = next;
275387f4e208SHong Zhang   }
27546bf673ebSJoe Pusztay   ts->tsrhssplit = NULL;
2755545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
27564a658b32SHong Zhang   if (ts->tspan) {
27574a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
27584a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times,&ts->tspan->vecs_sol));
27594a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
27604a658b32SHong Zhang   }
2761277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
2762d763cef2SBarry Smith   PetscFunctionReturn(0);
2763d763cef2SBarry Smith }
2764d763cef2SBarry Smith 
27651fb7b255SJunchao Zhang /*@C
2766d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2767d763cef2SBarry Smith    with TSCreate().
2768d763cef2SBarry Smith 
2769d763cef2SBarry Smith    Collective on TS
2770d763cef2SBarry Smith 
2771d763cef2SBarry Smith    Input Parameter:
2772d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2773d763cef2SBarry Smith 
2774d763cef2SBarry Smith    Level: beginner
2775d763cef2SBarry Smith 
2776db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSSolve()`
2777d763cef2SBarry Smith @*/
27786bf464f9SBarry Smith PetscErrorCode  TSDestroy(TS *ts)
2779d763cef2SBarry Smith {
2780d763cef2SBarry Smith   PetscFunctionBegin;
27816bf464f9SBarry Smith   if (!*ts) PetscFunctionReturn(0);
2782ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts,TS_CLASSID,1);
2783c793f718SLisandro Dalcin   if (--((PetscObject)(*ts))->refct > 0) {*ts = NULL; PetscFunctionReturn(0);}
2784d763cef2SBarry Smith 
27859566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
27869566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
2787ecf68647SHong Zhang   if ((*ts)->forward_solve) {
27889566063dSJacob Faibussowitsch     PetscCall(TSForwardReset(*ts));
2789ecf68647SHong Zhang   }
2790e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
27919566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
27929566063dSJacob Faibussowitsch   if ((*ts)->ops->destroy) PetscCall((*(*ts)->ops->destroy)((*ts)));
27936d4c513bSLisandro Dalcin 
27949566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2795bc952696SBarry Smith 
27969566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
27979566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
27986427ac75SLisandro Dalcin 
27999566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
28009566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
28019566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
28029566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
28036d4c513bSLisandro Dalcin 
28049566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
28059566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
2806d763cef2SBarry Smith   PetscFunctionReturn(0);
2807d763cef2SBarry Smith }
2808d763cef2SBarry Smith 
2809d8e5e3e6SSatish Balay /*@
2810d763cef2SBarry Smith    TSGetSNES - Returns the SNES (nonlinear solver) associated with
2811d763cef2SBarry Smith    a TS (timestepper) context. Valid only for nonlinear problems.
2812d763cef2SBarry Smith 
2813d763cef2SBarry Smith    Not Collective, but SNES is parallel if TS is parallel
2814d763cef2SBarry Smith 
2815d763cef2SBarry Smith    Input Parameter:
2816d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2817d763cef2SBarry Smith 
2818d763cef2SBarry Smith    Output Parameter:
2819d763cef2SBarry Smith .  snes - the nonlinear solver context
2820d763cef2SBarry Smith 
2821d763cef2SBarry Smith    Notes:
2822d763cef2SBarry Smith    The user can then directly manipulate the SNES context to set various
2823d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
282494b7f48cSBarry Smith    KSP, KSP, and PC contexts as well.
2825d763cef2SBarry Smith 
2826d763cef2SBarry Smith    TSGetSNES() does not work for integrators that do not use SNES; in
28270298fd71SBarry Smith    this case TSGetSNES() returns NULL in snes.
2828d763cef2SBarry Smith 
2829d763cef2SBarry Smith    Level: beginner
2830d763cef2SBarry Smith 
2831d763cef2SBarry Smith @*/
28327087cfbeSBarry Smith PetscErrorCode  TSGetSNES(TS ts,SNES *snes)
2833d763cef2SBarry Smith {
2834d763cef2SBarry Smith   PetscFunctionBegin;
28350700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
28364482741eSBarry Smith   PetscValidPointer(snes,2);
2837d372ba47SLisandro Dalcin   if (!ts->snes) {
28389566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts),&ts->snes));
28399566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes,((PetscObject)ts)->options));
28409566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts));
28419566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->snes));
28429566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes,(PetscObject)ts,1));
28439566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes,ts->dm));
28449e2a6581SJed Brown     if (ts->problem_type == TS_LINEAR) {
28459566063dSJacob Faibussowitsch       PetscCall(SNESSetType(ts->snes,SNESKSPONLY));
28469e2a6581SJed Brown     }
2847d372ba47SLisandro Dalcin   }
2848d763cef2SBarry Smith   *snes = ts->snes;
2849d763cef2SBarry Smith   PetscFunctionReturn(0);
2850d763cef2SBarry Smith }
2851d763cef2SBarry Smith 
2852deb2cd25SJed Brown /*@
2853deb2cd25SJed Brown    TSSetSNES - Set the SNES (nonlinear solver) to be used by the timestepping context
2854deb2cd25SJed Brown 
2855deb2cd25SJed Brown    Collective
2856deb2cd25SJed Brown 
2857d8d19677SJose E. Roman    Input Parameters:
2858deb2cd25SJed Brown +  ts - the TS context obtained from TSCreate()
2859deb2cd25SJed Brown -  snes - the nonlinear solver context
2860deb2cd25SJed Brown 
2861deb2cd25SJed Brown    Notes:
2862deb2cd25SJed Brown    Most users should have the TS created by calling TSGetSNES()
2863deb2cd25SJed Brown 
2864deb2cd25SJed Brown    Level: developer
2865deb2cd25SJed Brown 
2866deb2cd25SJed Brown @*/
2867deb2cd25SJed Brown PetscErrorCode TSSetSNES(TS ts,SNES snes)
2868deb2cd25SJed Brown {
2869d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES,Vec,Mat,Mat,void*);
2870deb2cd25SJed Brown 
2871deb2cd25SJed Brown   PetscFunctionBegin;
2872deb2cd25SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2873deb2cd25SJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,2);
28749566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
28759566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2876bbd56ea5SKarl Rupp 
2877deb2cd25SJed Brown   ts->snes = snes;
2878bbd56ea5SKarl Rupp 
28799566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes,NULL,SNESTSFormFunction,ts));
28809566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes,NULL,NULL,&func,NULL));
2881740132f1SEmil Constantinescu   if (func == SNESTSFormJacobian) {
28829566063dSJacob Faibussowitsch     PetscCall(SNESSetJacobian(ts->snes,NULL,NULL,SNESTSFormJacobian,ts));
2883740132f1SEmil Constantinescu   }
2884deb2cd25SJed Brown   PetscFunctionReturn(0);
2885deb2cd25SJed Brown }
2886deb2cd25SJed Brown 
2887d8e5e3e6SSatish Balay /*@
288894b7f48cSBarry Smith    TSGetKSP - Returns the KSP (linear solver) associated with
2889d763cef2SBarry Smith    a TS (timestepper) context.
2890d763cef2SBarry Smith 
289194b7f48cSBarry Smith    Not Collective, but KSP is parallel if TS is parallel
2892d763cef2SBarry Smith 
2893d763cef2SBarry Smith    Input Parameter:
2894d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
2895d763cef2SBarry Smith 
2896d763cef2SBarry Smith    Output Parameter:
289794b7f48cSBarry Smith .  ksp - the nonlinear solver context
2898d763cef2SBarry Smith 
2899d763cef2SBarry Smith    Notes:
290094b7f48cSBarry Smith    The user can then directly manipulate the KSP context to set various
2901d763cef2SBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2902d763cef2SBarry Smith    KSP and PC contexts as well.
2903d763cef2SBarry Smith 
290494b7f48cSBarry Smith    TSGetKSP() does not work for integrators that do not use KSP;
29050298fd71SBarry Smith    in this case TSGetKSP() returns NULL in ksp.
2906d763cef2SBarry Smith 
2907d763cef2SBarry Smith    Level: beginner
2908d763cef2SBarry Smith 
2909d763cef2SBarry Smith @*/
29107087cfbeSBarry Smith PetscErrorCode  TSGetKSP(TS ts,KSP *ksp)
2911d763cef2SBarry Smith {
2912089b2837SJed Brown   SNES           snes;
2913d372ba47SLisandro Dalcin 
2914d763cef2SBarry Smith   PetscFunctionBegin;
29150700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
29164482741eSBarry Smith   PetscValidPointer(ksp,2);
29173c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name,PETSC_COMM_SELF,PETSC_ERR_ARG_NULL,"KSP is not created yet. Call TSSetType() first");
29183c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR,PETSC_COMM_SELF,PETSC_ERR_ARG_WRONG,"Linear only; use TSGetSNES()");
29199566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
29209566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes,ksp));
2921d763cef2SBarry Smith   PetscFunctionReturn(0);
2922d763cef2SBarry Smith }
2923d763cef2SBarry Smith 
2924d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2925d763cef2SBarry Smith 
2926adb62b0dSMatthew Knepley /*@
2927618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2928618ce8baSLisandro Dalcin 
2929618ce8baSLisandro Dalcin    Logically Collective on TS
2930618ce8baSLisandro Dalcin 
2931618ce8baSLisandro Dalcin    Input Parameters:
2932618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2933618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2934618ce8baSLisandro Dalcin 
2935618ce8baSLisandro Dalcin    Options Database Keys:
2936618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2937618ce8baSLisandro Dalcin 
2938618ce8baSLisandro Dalcin    Notes:
2939618ce8baSLisandro Dalcin    The default maximum number of steps is 5000
2940618ce8baSLisandro Dalcin 
2941618ce8baSLisandro Dalcin    Level: intermediate
2942618ce8baSLisandro Dalcin 
2943db781477SPatrick Sanan .seealso: `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2944618ce8baSLisandro Dalcin @*/
2945618ce8baSLisandro Dalcin PetscErrorCode TSSetMaxSteps(TS ts,PetscInt maxsteps)
2946618ce8baSLisandro Dalcin {
2947618ce8baSLisandro Dalcin   PetscFunctionBegin;
2948618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2949618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
29503c633725SBarry Smith   PetscCheck(maxsteps >= 0,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_OUTOFRANGE,"Maximum number of steps must be non-negative");
2951618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
2952618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2953618ce8baSLisandro Dalcin }
2954618ce8baSLisandro Dalcin 
2955618ce8baSLisandro Dalcin /*@
2956618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2957618ce8baSLisandro Dalcin 
2958618ce8baSLisandro Dalcin    Not Collective
2959618ce8baSLisandro Dalcin 
2960618ce8baSLisandro Dalcin    Input Parameters:
2961618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
2962618ce8baSLisandro Dalcin 
2963618ce8baSLisandro Dalcin    Output Parameter:
2964618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2965618ce8baSLisandro Dalcin 
2966618ce8baSLisandro Dalcin    Level: advanced
2967618ce8baSLisandro Dalcin 
2968db781477SPatrick Sanan .seealso: `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2969618ce8baSLisandro Dalcin @*/
2970618ce8baSLisandro Dalcin PetscErrorCode TSGetMaxSteps(TS ts,PetscInt *maxsteps)
2971618ce8baSLisandro Dalcin {
2972618ce8baSLisandro Dalcin   PetscFunctionBegin;
2973618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
2974618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps,2);
2975618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
2976618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2977618ce8baSLisandro Dalcin }
2978618ce8baSLisandro Dalcin 
2979618ce8baSLisandro Dalcin /*@
2980618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2981618ce8baSLisandro Dalcin 
2982618ce8baSLisandro Dalcin    Logically Collective on TS
2983618ce8baSLisandro Dalcin 
2984618ce8baSLisandro Dalcin    Input Parameters:
2985618ce8baSLisandro Dalcin +  ts - the TS context obtained from TSCreate()
2986618ce8baSLisandro Dalcin -  maxtime - final time to step to
2987618ce8baSLisandro Dalcin 
2988618ce8baSLisandro Dalcin    Options Database Keys:
2989ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2990618ce8baSLisandro Dalcin 
2991618ce8baSLisandro Dalcin    Notes:
2992618ce8baSLisandro Dalcin    The default maximum time is 5.0
2993618ce8baSLisandro Dalcin 
2994618ce8baSLisandro Dalcin    Level: intermediate
2995618ce8baSLisandro Dalcin 
2996db781477SPatrick Sanan .seealso: `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2997618ce8baSLisandro Dalcin @*/
2998618ce8baSLisandro Dalcin PetscErrorCode TSSetMaxTime(TS ts,PetscReal maxtime)
2999618ce8baSLisandro Dalcin {
3000618ce8baSLisandro Dalcin   PetscFunctionBegin;
3001618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3002618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts,maxtime,2);
3003618ce8baSLisandro Dalcin   ts->max_time = maxtime;
3004618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
3005618ce8baSLisandro Dalcin }
3006618ce8baSLisandro Dalcin 
3007618ce8baSLisandro Dalcin /*@
3008618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
3009618ce8baSLisandro Dalcin 
3010618ce8baSLisandro Dalcin    Not Collective
3011618ce8baSLisandro Dalcin 
3012618ce8baSLisandro Dalcin    Input Parameters:
3013618ce8baSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
3014618ce8baSLisandro Dalcin 
3015618ce8baSLisandro Dalcin    Output Parameter:
3016618ce8baSLisandro Dalcin .  maxtime - final time to step to
3017618ce8baSLisandro Dalcin 
3018618ce8baSLisandro Dalcin    Level: advanced
3019618ce8baSLisandro Dalcin 
3020db781477SPatrick Sanan .seealso: `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
3021618ce8baSLisandro Dalcin @*/
3022618ce8baSLisandro Dalcin PetscErrorCode TSGetMaxTime(TS ts,PetscReal *maxtime)
3023618ce8baSLisandro Dalcin {
3024618ce8baSLisandro Dalcin   PetscFunctionBegin;
3025618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3026618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime,2);
3027618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
3028618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
3029618ce8baSLisandro Dalcin }
3030618ce8baSLisandro Dalcin 
3031618ce8baSLisandro Dalcin /*@
3032aaa6c58dSLisandro Dalcin    TSSetInitialTimeStep - Deprecated, use TSSetTime() and TSSetTimeStep().
3033edc382c3SSatish Balay 
3034edc382c3SSatish Balay    Level: deprecated
3035edc382c3SSatish Balay 
3036aaa6c58dSLisandro Dalcin @*/
3037aaa6c58dSLisandro Dalcin PetscErrorCode  TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)
3038aaa6c58dSLisandro Dalcin {
3039aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
3040aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
30419566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts,initial_time));
30429566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts,time_step));
3043aaa6c58dSLisandro Dalcin   PetscFunctionReturn(0);
3044aaa6c58dSLisandro Dalcin }
3045aaa6c58dSLisandro Dalcin 
3046aaa6c58dSLisandro Dalcin /*@
304719eac22cSLisandro Dalcin    TSGetDuration - Deprecated, use TSGetMaxSteps() and TSGetMaxTime().
3048edc382c3SSatish Balay 
3049edc382c3SSatish Balay    Level: deprecated
3050edc382c3SSatish Balay 
3051adb62b0dSMatthew Knepley @*/
30527087cfbeSBarry Smith PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3053adb62b0dSMatthew Knepley {
3054adb62b0dSMatthew Knepley   PetscFunctionBegin;
30550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3056abc0a331SBarry Smith   if (maxsteps) {
30574482741eSBarry Smith     PetscValidIntPointer(maxsteps,2);
3058adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
3059adb62b0dSMatthew Knepley   }
3060abc0a331SBarry Smith   if (maxtime) {
3061064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime,3);
3062adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
3063adb62b0dSMatthew Knepley   }
3064adb62b0dSMatthew Knepley   PetscFunctionReturn(0);
3065adb62b0dSMatthew Knepley }
3066adb62b0dSMatthew Knepley 
3067d763cef2SBarry Smith /*@
306819eac22cSLisandro Dalcin    TSSetDuration - Deprecated, use TSSetMaxSteps() and TSSetMaxTime().
3069edc382c3SSatish Balay 
3070edc382c3SSatish Balay    Level: deprecated
3071edc382c3SSatish Balay 
3072d763cef2SBarry Smith @*/
30737087cfbeSBarry Smith PetscErrorCode TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)
3074d763cef2SBarry Smith {
3075d763cef2SBarry Smith   PetscFunctionBegin;
30760700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3077c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts,maxsteps,2);
3078064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts,maxtime,3);
307939b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
308039b7ec4bSSean Farley   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
3081d763cef2SBarry Smith   PetscFunctionReturn(0);
3082d763cef2SBarry Smith }
3083d763cef2SBarry Smith 
3084d763cef2SBarry Smith /*@
30855c5f5948SLisandro Dalcin    TSGetTimeStepNumber - Deprecated, use TSGetStepNumber().
3086edc382c3SSatish Balay 
3087edc382c3SSatish Balay    Level: deprecated
3088edc382c3SSatish Balay 
30895c5f5948SLisandro Dalcin @*/
3090e193eaafSLisandro Dalcin PetscErrorCode TSGetTimeStepNumber(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
30915c5f5948SLisandro Dalcin 
309219eac22cSLisandro Dalcin /*@
30934f4e0956SLisandro Dalcin    TSGetTotalSteps - Deprecated, use TSGetStepNumber().
3094edc382c3SSatish Balay 
3095edc382c3SSatish Balay    Level: deprecated
3096edc382c3SSatish Balay 
30974f4e0956SLisandro Dalcin @*/
30984f4e0956SLisandro Dalcin PetscErrorCode TSGetTotalSteps(TS ts,PetscInt *steps) { return TSGetStepNumber(ts,steps); }
30994f4e0956SLisandro Dalcin 
31004f4e0956SLisandro Dalcin /*@
3101d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3102d763cef2SBarry Smith    for use by the TS routines.
3103d763cef2SBarry Smith 
3104d083f849SBarry Smith    Logically Collective on TS
3105d763cef2SBarry Smith 
3106d763cef2SBarry Smith    Input Parameters:
3107d763cef2SBarry Smith +  ts - the TS context obtained from TSCreate()
31080910c330SBarry Smith -  u - the solution vector
3109d763cef2SBarry Smith 
3110d763cef2SBarry Smith    Level: beginner
3111d763cef2SBarry Smith 
3112db781477SPatrick Sanan .seealso: `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3113d763cef2SBarry Smith @*/
31140910c330SBarry Smith PetscErrorCode  TSSetSolution(TS ts,Vec u)
3115d763cef2SBarry Smith {
3116496e6a7aSJed Brown   DM             dm;
31178737fe31SLisandro Dalcin 
3118d763cef2SBarry Smith   PetscFunctionBegin;
31190700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
31200910c330SBarry Smith   PetscValidHeaderSpecific(u,VEC_CLASSID,2);
31219566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
31229566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
31230910c330SBarry Smith   ts->vec_sol = u;
3124bbd56ea5SKarl Rupp 
31259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
31269566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm,u));
3127d763cef2SBarry Smith   PetscFunctionReturn(0);
3128d763cef2SBarry Smith }
3129d763cef2SBarry Smith 
3130ac226902SBarry Smith /*@C
3131000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
31323f2090d5SJed Brown   called once at the beginning of each time step.
3133000e7ae3SMatthew Knepley 
31343f9fe445SBarry Smith   Logically Collective on TS
3135000e7ae3SMatthew Knepley 
3136000e7ae3SMatthew Knepley   Input Parameters:
3137000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3138000e7ae3SMatthew Knepley - func - The function
3139000e7ae3SMatthew Knepley 
3140000e7ae3SMatthew Knepley   Calling sequence of func:
314167b8a455SSatish Balay .vb
314267b8a455SSatish Balay   PetscErrorCode func (TS ts);
314367b8a455SSatish Balay .ve
3144000e7ae3SMatthew Knepley 
3145000e7ae3SMatthew Knepley   Level: intermediate
3146000e7ae3SMatthew Knepley 
3147db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3148000e7ae3SMatthew Knepley @*/
31497087cfbeSBarry Smith PetscErrorCode  TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3150000e7ae3SMatthew Knepley {
3151000e7ae3SMatthew Knepley   PetscFunctionBegin;
31520700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3153ae60f76fSBarry Smith   ts->prestep = func;
3154000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3155000e7ae3SMatthew Knepley }
3156000e7ae3SMatthew Knepley 
315709ee8438SJed Brown /*@
31583f2090d5SJed Brown   TSPreStep - Runs the user-defined pre-step function.
31593f2090d5SJed Brown 
31603f2090d5SJed Brown   Collective on TS
31613f2090d5SJed Brown 
31623f2090d5SJed Brown   Input Parameters:
31633f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
31643f2090d5SJed Brown 
31653f2090d5SJed Brown   Notes:
31663f2090d5SJed Brown   TSPreStep() is typically used within time stepping implementations,
31673f2090d5SJed Brown   so most users would not generally call this routine themselves.
31683f2090d5SJed Brown 
31693f2090d5SJed Brown   Level: developer
31703f2090d5SJed Brown 
3171db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
31723f2090d5SJed Brown @*/
31737087cfbeSBarry Smith PetscErrorCode  TSPreStep(TS ts)
31743f2090d5SJed Brown {
31753f2090d5SJed Brown   PetscFunctionBegin;
31760700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3177ae60f76fSBarry Smith   if (ts->prestep) {
31785efd42a4SStefano Zampini     Vec              U;
3179ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3180ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31815efd42a4SStefano Zampini     PetscObjectState sprev,spost;
31825efd42a4SStefano Zampini 
31839566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
31849566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U,&idprev));
31859566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
3186a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->prestep),ts);
31879566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
31889566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U,idprev,&sameObject));
31899566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
31909566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3191312ce896SJed Brown   }
31923f2090d5SJed Brown   PetscFunctionReturn(0);
31933f2090d5SJed Brown }
31943f2090d5SJed Brown 
3195b8123daeSJed Brown /*@C
3196b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3197b8123daeSJed Brown   called once at the beginning of each stage.
3198b8123daeSJed Brown 
3199b8123daeSJed Brown   Logically Collective on TS
3200b8123daeSJed Brown 
3201b8123daeSJed Brown   Input Parameters:
3202b8123daeSJed Brown + ts   - The TS context obtained from TSCreate()
3203b8123daeSJed Brown - func - The function
3204b8123daeSJed Brown 
3205b8123daeSJed Brown   Calling sequence of func:
320667b8a455SSatish Balay .vb
320767b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime);
320867b8a455SSatish Balay .ve
3209b8123daeSJed Brown 
3210b8123daeSJed Brown   Level: intermediate
3211b8123daeSJed Brown 
3212b8123daeSJed Brown   Note:
3213b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
321480275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
3215b8123daeSJed Brown   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
3216b8123daeSJed Brown 
3217db781477SPatrick Sanan .seealso: `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3218b8123daeSJed Brown @*/
3219b8123daeSJed Brown PetscErrorCode  TSSetPreStage(TS ts, PetscErrorCode (*func)(TS,PetscReal))
3220b8123daeSJed Brown {
3221b8123daeSJed Brown   PetscFunctionBegin;
3222b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3223ae60f76fSBarry Smith   ts->prestage = func;
3224b8123daeSJed Brown   PetscFunctionReturn(0);
3225b8123daeSJed Brown }
3226b8123daeSJed Brown 
32279be3e283SDebojyoti Ghosh /*@C
32289be3e283SDebojyoti Ghosh   TSSetPostStage - Sets the general-purpose function
32299be3e283SDebojyoti Ghosh   called once at the end of each stage.
32309be3e283SDebojyoti Ghosh 
32319be3e283SDebojyoti Ghosh   Logically Collective on TS
32329be3e283SDebojyoti Ghosh 
32339be3e283SDebojyoti Ghosh   Input Parameters:
32349be3e283SDebojyoti Ghosh + ts   - The TS context obtained from TSCreate()
32359be3e283SDebojyoti Ghosh - func - The function
32369be3e283SDebojyoti Ghosh 
32379be3e283SDebojyoti Ghosh   Calling sequence of func:
323867b8a455SSatish Balay .vb
323967b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
324067b8a455SSatish Balay .ve
32419be3e283SDebojyoti Ghosh 
32429be3e283SDebojyoti Ghosh   Level: intermediate
32439be3e283SDebojyoti Ghosh 
32449be3e283SDebojyoti Ghosh   Note:
32459be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
324680275a0aSLisandro Dalcin   The time step number being computed can be queried using TSGetStepNumber() and the total size of the step being
32479be3e283SDebojyoti Ghosh   attempted can be obtained using TSGetTimeStep(). The time at the start of the step is available via TSGetTime().
32489be3e283SDebojyoti Ghosh 
3249db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
32509be3e283SDebojyoti Ghosh @*/
32519be3e283SDebojyoti Ghosh PetscErrorCode  TSSetPostStage(TS ts, PetscErrorCode (*func)(TS,PetscReal,PetscInt,Vec*))
32529be3e283SDebojyoti Ghosh {
32539be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32549be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
32559be3e283SDebojyoti Ghosh   ts->poststage = func;
32569be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
32579be3e283SDebojyoti Ghosh }
32589be3e283SDebojyoti Ghosh 
3259c688d042SShri Abhyankar /*@C
3260c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3261c688d042SShri Abhyankar   called once at the end of each step evaluation.
3262c688d042SShri Abhyankar 
3263c688d042SShri Abhyankar   Logically Collective on TS
3264c688d042SShri Abhyankar 
3265c688d042SShri Abhyankar   Input Parameters:
3266c688d042SShri Abhyankar + ts   - The TS context obtained from TSCreate()
3267c688d042SShri Abhyankar - func - The function
3268c688d042SShri Abhyankar 
3269c688d042SShri Abhyankar   Calling sequence of func:
327067b8a455SSatish Balay .vb
327167b8a455SSatish Balay   PetscErrorCode func(TS ts);
327267b8a455SSatish Balay .ve
3273c688d042SShri Abhyankar 
3274c688d042SShri Abhyankar   Level: intermediate
3275c688d042SShri Abhyankar 
3276c688d042SShri Abhyankar   Note:
32771785ff2aSShri Abhyankar   Semantically, TSSetPostEvaluate() differs from TSSetPostStep() since the function it sets is called before event-handling
32781785ff2aSShri Abhyankar   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, TSPostStep()
3279e7e94ed4SShri Abhyankar   may be passed a different solution, possibly changed by the event handler. TSPostEvaluate() is called after the next step
3280e7e94ed4SShri Abhyankar   solution is evaluated allowing to modify it, if need be. The solution can be obtained with TSGetSolution(), the time step
3281e7e94ed4SShri Abhyankar   with TSGetTimeStep(), and the time at the start of the step is available via TSGetTime()
3282c688d042SShri Abhyankar 
3283db781477SPatrick Sanan .seealso: `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3284c688d042SShri Abhyankar @*/
3285c688d042SShri Abhyankar PetscErrorCode  TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3286c688d042SShri Abhyankar {
3287c688d042SShri Abhyankar   PetscFunctionBegin;
3288c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3289c688d042SShri Abhyankar   ts->postevaluate = func;
3290c688d042SShri Abhyankar   PetscFunctionReturn(0);
3291c688d042SShri Abhyankar }
3292c688d042SShri Abhyankar 
3293b8123daeSJed Brown /*@
3294b8123daeSJed Brown   TSPreStage - Runs the user-defined pre-stage function set using TSSetPreStage()
3295b8123daeSJed Brown 
3296b8123daeSJed Brown   Collective on TS
3297b8123daeSJed Brown 
3298b8123daeSJed Brown   Input Parameters:
3299b8123daeSJed Brown . ts          - The TS context obtained from TSCreate()
33009be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3301b8123daeSJed Brown 
3302b8123daeSJed Brown   Notes:
3303b8123daeSJed Brown   TSPreStage() is typically used within time stepping implementations,
3304b8123daeSJed Brown   most users would not generally call this routine themselves.
3305b8123daeSJed Brown 
3306b8123daeSJed Brown   Level: developer
3307b8123daeSJed Brown 
3308db781477SPatrick Sanan .seealso: `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3309b8123daeSJed Brown @*/
3310b8123daeSJed Brown PetscErrorCode  TSPreStage(TS ts, PetscReal stagetime)
3311b8123daeSJed Brown {
3312b8123daeSJed Brown   PetscFunctionBegin;
3313b8123daeSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3314ae60f76fSBarry Smith   if (ts->prestage) {
3315a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->prestage),ts,stagetime);
3316b8123daeSJed Brown   }
3317b8123daeSJed Brown   PetscFunctionReturn(0);
3318b8123daeSJed Brown }
3319b8123daeSJed Brown 
33209be3e283SDebojyoti Ghosh /*@
33219be3e283SDebojyoti Ghosh   TSPostStage - Runs the user-defined post-stage function set using TSSetPostStage()
33229be3e283SDebojyoti Ghosh 
33239be3e283SDebojyoti Ghosh   Collective on TS
33249be3e283SDebojyoti Ghosh 
33259be3e283SDebojyoti Ghosh   Input Parameters:
33269be3e283SDebojyoti Ghosh . ts          - The TS context obtained from TSCreate()
33279be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
33289be3e283SDebojyoti Ghosh   stageindex  - Stage number
33299be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
33309be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
33319be3e283SDebojyoti Ghosh 
33329be3e283SDebojyoti Ghosh   Notes:
33339be3e283SDebojyoti Ghosh   TSPostStage() is typically used within time stepping implementations,
33349be3e283SDebojyoti Ghosh   most users would not generally call this routine themselves.
33359be3e283SDebojyoti Ghosh 
33369be3e283SDebojyoti Ghosh   Level: developer
33379be3e283SDebojyoti Ghosh 
3338db781477SPatrick Sanan .seealso: `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
33399be3e283SDebojyoti Ghosh @*/
33409be3e283SDebojyoti Ghosh PetscErrorCode  TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
33419be3e283SDebojyoti Ghosh {
33429be3e283SDebojyoti Ghosh   PetscFunctionBegin;
33439be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
33444beae5d8SLisandro Dalcin   if (ts->poststage) {
3345a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->poststage),ts,stagetime,stageindex,Y);
33469be3e283SDebojyoti Ghosh   }
33479be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
33489be3e283SDebojyoti Ghosh }
33499be3e283SDebojyoti Ghosh 
3350c688d042SShri Abhyankar /*@
3351c688d042SShri Abhyankar   TSPostEvaluate - Runs the user-defined post-evaluate function set using TSSetPostEvaluate()
3352c688d042SShri Abhyankar 
3353c688d042SShri Abhyankar   Collective on TS
3354c688d042SShri Abhyankar 
3355c688d042SShri Abhyankar   Input Parameters:
3356c688d042SShri Abhyankar . ts          - The TS context obtained from TSCreate()
3357c688d042SShri Abhyankar 
3358c688d042SShri Abhyankar   Notes:
3359c688d042SShri Abhyankar   TSPostEvaluate() is typically used within time stepping implementations,
3360c688d042SShri Abhyankar   most users would not generally call this routine themselves.
3361c688d042SShri Abhyankar 
3362c688d042SShri Abhyankar   Level: developer
3363c688d042SShri Abhyankar 
3364db781477SPatrick Sanan .seealso: `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3365c688d042SShri Abhyankar @*/
3366c688d042SShri Abhyankar PetscErrorCode  TSPostEvaluate(TS ts)
3367c688d042SShri Abhyankar {
3368c688d042SShri Abhyankar   PetscFunctionBegin;
3369c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3370c688d042SShri Abhyankar   if (ts->postevaluate) {
3371dcb233daSLisandro Dalcin     Vec              U;
3372dcb233daSLisandro Dalcin     PetscObjectState sprev,spost;
3373dcb233daSLisandro Dalcin 
33749566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
33759566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
3376a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->postevaluate),ts);
33779566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
33789566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3379c688d042SShri Abhyankar   }
3380c688d042SShri Abhyankar   PetscFunctionReturn(0);
3381c688d042SShri Abhyankar }
3382c688d042SShri Abhyankar 
3383ac226902SBarry Smith /*@C
3384000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33853f2090d5SJed Brown   called once at the end of each time step.
3386000e7ae3SMatthew Knepley 
33873f9fe445SBarry Smith   Logically Collective on TS
3388000e7ae3SMatthew Knepley 
3389000e7ae3SMatthew Knepley   Input Parameters:
3390000e7ae3SMatthew Knepley + ts   - The TS context obtained from TSCreate()
3391000e7ae3SMatthew Knepley - func - The function
3392000e7ae3SMatthew Knepley 
3393000e7ae3SMatthew Knepley   Calling sequence of func:
3394b8123daeSJed Brown $ func (TS ts);
3395000e7ae3SMatthew Knepley 
33961785ff2aSShri Abhyankar   Notes:
33971785ff2aSShri Abhyankar   The function set by TSSetPostStep() is called after each successful step. The solution vector X
33981785ff2aSShri Abhyankar   obtained by TSGetSolution() may be different than that computed at the step end if the event handler
33991785ff2aSShri Abhyankar   locates an event and TSPostEvent() modifies it. Use TSSetPostEvaluate() if an unmodified solution is needed instead.
34001785ff2aSShri Abhyankar 
3401000e7ae3SMatthew Knepley   Level: intermediate
3402000e7ae3SMatthew Knepley 
3403db781477SPatrick Sanan .seealso: `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3404000e7ae3SMatthew Knepley @*/
34057087cfbeSBarry Smith PetscErrorCode  TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3406000e7ae3SMatthew Knepley {
3407000e7ae3SMatthew Knepley   PetscFunctionBegin;
34080700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
3409ae60f76fSBarry Smith   ts->poststep = func;
3410000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3411000e7ae3SMatthew Knepley }
3412000e7ae3SMatthew Knepley 
341309ee8438SJed Brown /*@
34143f2090d5SJed Brown   TSPostStep - Runs the user-defined post-step function.
34153f2090d5SJed Brown 
34163f2090d5SJed Brown   Collective on TS
34173f2090d5SJed Brown 
34183f2090d5SJed Brown   Input Parameters:
34193f2090d5SJed Brown . ts   - The TS context obtained from TSCreate()
34203f2090d5SJed Brown 
34213f2090d5SJed Brown   Notes:
34223f2090d5SJed Brown   TSPostStep() is typically used within time stepping implementations,
34233f2090d5SJed Brown   so most users would not generally call this routine themselves.
34243f2090d5SJed Brown 
34253f2090d5SJed Brown   Level: developer
34263f2090d5SJed Brown 
34273f2090d5SJed Brown @*/
34287087cfbeSBarry Smith PetscErrorCode  TSPostStep(TS ts)
34293f2090d5SJed Brown {
34303f2090d5SJed Brown   PetscFunctionBegin;
34310700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3432ae60f76fSBarry Smith   if (ts->poststep) {
34335efd42a4SStefano Zampini     Vec              U;
3434ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3435ef8d1ce0SJohann Rudi     PetscBool        sameObject;
34365efd42a4SStefano Zampini     PetscObjectState sprev,spost;
34375efd42a4SStefano Zampini 
34389566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
34399566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U,&idprev));
34409566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&sprev));
3441a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->poststep),ts);
34429566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts,&U));
34439566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U,idprev,&sameObject));
34449566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U,&spost));
34459566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
344672ac3e02SJed Brown   }
34473f2090d5SJed Brown   PetscFunctionReturn(0);
34483f2090d5SJed Brown }
34493f2090d5SJed Brown 
3450cd652676SJed Brown /*@
3451cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3452cd652676SJed Brown 
3453cd652676SJed Brown    Collective on TS
3454cd652676SJed Brown 
34554165533cSJose E. Roman    Input Parameters:
3456cd652676SJed Brown +  ts - time stepping context
3457cd652676SJed Brown -  t - time to interpolate to
3458cd652676SJed Brown 
34594165533cSJose E. Roman    Output Parameter:
34600910c330SBarry Smith .  U - state at given time
3461cd652676SJed Brown 
3462cd652676SJed Brown    Level: intermediate
3463cd652676SJed Brown 
3464cd652676SJed Brown    Developer Notes:
3465cd652676SJed Brown    TSInterpolate() and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3466cd652676SJed Brown 
3467db781477SPatrick Sanan .seealso: `TSSetExactFinalTime()`, `TSSolve()`
3468cd652676SJed Brown @*/
34690910c330SBarry Smith PetscErrorCode TSInterpolate(TS ts,PetscReal t,Vec U)
3470cd652676SJed Brown {
3471cd652676SJed Brown   PetscFunctionBegin;
3472cd652676SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3473b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
347463a3b9bcSJacob 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);
34753c633725SBarry Smith   PetscCheck(ts->ops->interpolate,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"%s does not provide interpolation",((PetscObject)ts)->type_name);
34769566063dSJacob Faibussowitsch   PetscCall((*ts->ops->interpolate)(ts,t,U));
3477cd652676SJed Brown   PetscFunctionReturn(0);
3478cd652676SJed Brown }
3479cd652676SJed Brown 
3480d763cef2SBarry Smith /*@
34816d9e5789SSean Farley    TSStep - Steps one time step
3482d763cef2SBarry Smith 
3483d763cef2SBarry Smith    Collective on TS
3484d763cef2SBarry Smith 
3485d763cef2SBarry Smith    Input Parameter:
3486d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3487d763cef2SBarry Smith 
348827829d71SBarry Smith    Level: developer
3489d763cef2SBarry Smith 
3490b8123daeSJed Brown    Notes:
349127829d71SBarry Smith    The public interface for the ODE/DAE solvers is TSSolve(), you should almost for sure be using that routine and not this routine.
349227829d71SBarry Smith 
3493b8123daeSJed Brown    The hook set using TSSetPreStep() is called before each attempt to take the step. In general, the time step size may
3494b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3495b8123daeSJed Brown 
349619eac22cSLisandro Dalcin    This may over-step the final time provided in TSSetMaxTime() depending on the time-step used. TSSolve() interpolates to exactly the
349719eac22cSLisandro Dalcin    time provided in TSSetMaxTime(). One can use TSInterpolate() to determine an interpolated solution within the final timestep.
349825cb2221SBarry Smith 
3499db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3500d763cef2SBarry Smith @*/
3501193ac0bcSJed Brown PetscErrorCode  TSStep(TS ts)
3502d763cef2SBarry Smith {
3503fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3504be5899b3SLisandro Dalcin   PetscReal        ptime;
3505d763cef2SBarry Smith 
3506d763cef2SBarry Smith   PetscFunctionBegin;
35070700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3508d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3509fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3510f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3511f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3512f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3513f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
3514d0609cedSBarry Smith                                    "  year          = {2018}\n}\n",&cite));
35159566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
35169566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory,ts));
3517d405a339SMatthew Knepley 
35183c633725SBarry Smith   PetscCheck(ts->ops->step,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSStep not implemented for type '%s'",((PetscObject)ts)->type_name);
35193c633725SBarry 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>");
35203c633725SBarry 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()");
35213c633725SBarry 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");
3522a6772fa2SLisandro Dalcin 
3523be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
3524be5899b3SLisandro Dalcin   ptime = ts->ptime; ts->ptime_prev_rollback = ts->ptime_prev;
35252808aa04SLisandro Dalcin   ts->reason = TS_CONVERGED_ITERATING;
3526fc8dbba5SLisandro Dalcin 
35279566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step,ts,0,0,0));
35289566063dSJacob Faibussowitsch   PetscCall((*ts->ops->step)(ts));
35299566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step,ts,0,0,0));
3530fc8dbba5SLisandro Dalcin 
3531fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3532be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
35332808aa04SLisandro Dalcin     ts->steps++;
3534be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
353528d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3536*e1db57b0SHong 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++]));
3537d2daff3dSHong Zhang   }
3538fc8dbba5SLisandro Dalcin 
3539fc8dbba5SLisandro Dalcin   if (!ts->reason) {
354008c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
354108c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
354208c7845fSBarry Smith   }
3543fc8dbba5SLisandro Dalcin 
35443c633725SBarry 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]);
35453c633725SBarry Smith   PetscCheck(ts->reason >= 0 || !ts->errorifstepfailed,PetscObjectComm((PetscObject)ts),PETSC_ERR_NOT_CONVERGED,"TSStep has failed due to %s",TSConvergedReasons[ts->reason]);
354608c7845fSBarry Smith   PetscFunctionReturn(0);
354708c7845fSBarry Smith }
354808c7845fSBarry Smith 
354908c7845fSBarry Smith /*@
35507cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
35517cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
35527cbde773SLisandro Dalcin 
35537cbde773SLisandro Dalcin    Collective on TS
35547cbde773SLisandro Dalcin 
35554165533cSJose E. Roman    Input Parameters:
35567cbde773SLisandro Dalcin +  ts - time stepping context
355797bb3fdcSJose E. Roman -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
35587cbde773SLisandro Dalcin 
355997bb3fdcSJose E. Roman    Input/Output Parameter:
356097bb3fdcSJose E. Roman .  order - optional, desired order for the error evaluation or PETSC_DECIDE;
356197bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
356297bb3fdcSJose E. Roman 
356397bb3fdcSJose E. Roman    Output Parameter:
356497bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
35657cbde773SLisandro Dalcin 
35667cbde773SLisandro Dalcin    Level: advanced
35677cbde773SLisandro Dalcin 
35687cbde773SLisandro Dalcin    Notes:
35697cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
35707cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
35717cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
35727cbde773SLisandro Dalcin 
3573db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35747cbde773SLisandro Dalcin @*/
35757cbde773SLisandro Dalcin PetscErrorCode TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt *order,PetscReal *wlte)
35767cbde773SLisandro Dalcin {
35777cbde773SLisandro Dalcin   PetscFunctionBegin;
35787cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
35797cbde773SLisandro Dalcin   PetscValidType(ts,1);
3580064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts,wnormtype,2);
35817cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order,3);
35827cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts,*order,3);
35837cbde773SLisandro Dalcin   PetscValidRealPointer(wlte,4);
35843c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
35853c633725SBarry Smith   PetscCheck(ts->ops->evaluatewlte,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateWLTE not implemented for type '%s'",((PetscObject)ts)->type_name);
35869566063dSJacob Faibussowitsch   PetscCall((*ts->ops->evaluatewlte)(ts,wnormtype,order,wlte));
35877cbde773SLisandro Dalcin   PetscFunctionReturn(0);
35887cbde773SLisandro Dalcin }
35897cbde773SLisandro Dalcin 
359005175c85SJed Brown /*@
359105175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
359205175c85SJed Brown 
35931c3436cfSJed Brown    Collective on TS
359405175c85SJed Brown 
35954165533cSJose E. Roman    Input Parameters:
35961c3436cfSJed Brown +  ts - time stepping context
35971c3436cfSJed Brown .  order - desired order of accuracy
35980298fd71SBarry Smith -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
359905175c85SJed Brown 
36004165533cSJose E. Roman    Output Parameter:
36010910c330SBarry Smith .  U - state at the end of the current step
360205175c85SJed Brown 
360305175c85SJed Brown    Level: advanced
360405175c85SJed Brown 
3605108c343cSJed Brown    Notes:
3606108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3607108c343cSJed 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.
3608108c343cSJed Brown 
3609db781477SPatrick Sanan .seealso: `TSStep()`, `TSAdapt`
361005175c85SJed Brown @*/
36110910c330SBarry Smith PetscErrorCode TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool *done)
361205175c85SJed Brown {
361305175c85SJed Brown   PetscFunctionBegin;
361405175c85SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
361505175c85SJed Brown   PetscValidType(ts,1);
36160910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
36173c633725SBarry Smith   PetscCheck(ts->ops->evaluatestep,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSEvaluateStep not implemented for type '%s'",((PetscObject)ts)->type_name);
36189566063dSJacob Faibussowitsch   PetscCall((*ts->ops->evaluatestep)(ts,order,U,done));
361905175c85SJed Brown   PetscFunctionReturn(0);
362005175c85SJed Brown }
362105175c85SJed Brown 
3622aad739acSMatthew G. Knepley /*@C
36232e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3624aad739acSMatthew G. Knepley 
3625aad739acSMatthew G. Knepley   Not collective
3626aad739acSMatthew G. Knepley 
36274165533cSJose E. Roman   Input Parameter:
3628aad739acSMatthew G. Knepley . ts        - time stepping context
3629aad739acSMatthew G. Knepley 
36304165533cSJose E. Roman   Output Parameter:
36312e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3632aad739acSMatthew G. Knepley 
3633aad739acSMatthew G. Knepley    Level: advanced
3634aad739acSMatthew G. Knepley 
3635aad739acSMatthew G. Knepley    Notes:
3636aad739acSMatthew G. Knepley    The calling sequence for the function is
36372e61be88SMatthew G. Knepley $ initCondition(TS ts, Vec u)
3638aad739acSMatthew G. Knepley $ ts - The timestepping context
36392e61be88SMatthew G. Knepley $ u  - The input vector in which the initial condition is stored
3640aad739acSMatthew G. Knepley 
3641db781477SPatrick Sanan .seealso: `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3642aad739acSMatthew G. Knepley @*/
36432e61be88SMatthew G. Knepley PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3644aad739acSMatthew G. Knepley {
3645aad739acSMatthew G. Knepley   PetscFunctionBegin;
3646aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36472e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
36482e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
3649aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3650aad739acSMatthew G. Knepley }
3651aad739acSMatthew G. Knepley 
3652aad739acSMatthew G. Knepley /*@C
36532e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3654aad739acSMatthew G. Knepley 
3655aad739acSMatthew G. Knepley   Logically collective on ts
3656aad739acSMatthew G. Knepley 
36574165533cSJose E. Roman   Input Parameters:
3658aad739acSMatthew G. Knepley + ts        - time stepping context
36592e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3660aad739acSMatthew G. Knepley 
3661aad739acSMatthew G. Knepley   Level: advanced
3662aad739acSMatthew G. Knepley 
3663a96d6ef6SBarry Smith   Calling sequence for initCondition:
3664a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3665a96d6ef6SBarry Smith 
3666a96d6ef6SBarry Smith + ts - The timestepping context
3667a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3668aad739acSMatthew G. Knepley 
3669db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3670aad739acSMatthew G. Knepley @*/
36712e61be88SMatthew G. Knepley PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3672aad739acSMatthew G. Knepley {
3673aad739acSMatthew G. Knepley   PetscFunctionBegin;
3674aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36752e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36762e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
3677aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3678aad739acSMatthew G. Knepley }
3679aad739acSMatthew G. Knepley 
3680aad739acSMatthew G. Knepley /*@
36812e61be88SMatthew G. Knepley   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set.
3682aad739acSMatthew G. Knepley 
3683aad739acSMatthew G. Knepley   Collective on ts
3684aad739acSMatthew G. Knepley 
36854165533cSJose E. Roman   Input Parameters:
3686aad739acSMatthew G. Knepley + ts - time stepping context
36872e61be88SMatthew G. Knepley - u  - The Vec to store the condition in which will be used in TSSolve()
3688aad739acSMatthew G. Knepley 
3689aad739acSMatthew G. Knepley   Level: advanced
3690aad739acSMatthew G. Knepley 
3691db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3692aad739acSMatthew G. Knepley @*/
36932e61be88SMatthew G. Knepley PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3694aad739acSMatthew G. Knepley {
3695aad739acSMatthew G. Knepley   PetscFunctionBegin;
3696aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3697aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
36989566063dSJacob Faibussowitsch   if (ts->ops->initcondition) PetscCall((*ts->ops->initcondition)(ts, u));
3699aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3700aad739acSMatthew G. Knepley }
3701aad739acSMatthew G. Knepley 
3702aad739acSMatthew G. Knepley /*@C
3703aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3704aad739acSMatthew G. Knepley 
3705aad739acSMatthew G. Knepley   Not collective
3706aad739acSMatthew G. Knepley 
37074165533cSJose E. Roman   Input Parameter:
3708aad739acSMatthew G. Knepley . ts         - time stepping context
3709aad739acSMatthew G. Knepley 
37104165533cSJose E. Roman   Output Parameter:
3711aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3712aad739acSMatthew G. Knepley 
3713aad739acSMatthew G. Knepley   Level: advanced
3714aad739acSMatthew G. Knepley 
3715a96d6ef6SBarry Smith   Calling sequence for exactError:
3716a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3717a96d6ef6SBarry Smith 
3718a96d6ef6SBarry Smith + ts - The timestepping context
3719a96d6ef6SBarry Smith . u  - The approximate solution vector
3720a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3721aad739acSMatthew G. Knepley 
3722db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3723aad739acSMatthew G. Knepley @*/
3724aad739acSMatthew G. Knepley PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3725aad739acSMatthew G. Knepley {
3726aad739acSMatthew G. Knepley   PetscFunctionBegin;
3727aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3728aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3729aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
3730aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3731aad739acSMatthew G. Knepley }
3732aad739acSMatthew G. Knepley 
3733aad739acSMatthew G. Knepley /*@C
3734aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3735aad739acSMatthew G. Knepley 
3736aad739acSMatthew G. Knepley   Logically collective on ts
3737aad739acSMatthew G. Knepley 
37384165533cSJose E. Roman   Input Parameters:
3739aad739acSMatthew G. Knepley + ts         - time stepping context
3740aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3741aad739acSMatthew G. Knepley 
3742aad739acSMatthew G. Knepley   Level: advanced
3743aad739acSMatthew G. Knepley 
3744a96d6ef6SBarry Smith   Calling sequence for exactError:
3745a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3746a96d6ef6SBarry Smith 
3747a96d6ef6SBarry Smith + ts - The timestepping context
3748a96d6ef6SBarry Smith . u  - The approximate solution vector
3749a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3750aad739acSMatthew G. Knepley 
3751db781477SPatrick Sanan .seealso: `TSGetComputeExactError()`, `TSComputeExactError()`
3752aad739acSMatthew G. Knepley @*/
3753aad739acSMatthew G. Knepley PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3754aad739acSMatthew G. Knepley {
3755aad739acSMatthew G. Knepley   PetscFunctionBegin;
3756aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3757f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3758aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
3759aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3760aad739acSMatthew G. Knepley }
3761aad739acSMatthew G. Knepley 
3762aad739acSMatthew G. Knepley /*@
3763aad739acSMatthew G. Knepley   TSComputeExactError - Compute the solution error for the timestepping using the function previously set.
3764aad739acSMatthew G. Knepley 
3765aad739acSMatthew G. Knepley   Collective on ts
3766aad739acSMatthew G. Knepley 
37674165533cSJose E. Roman   Input Parameters:
3768aad739acSMatthew G. Knepley + ts - time stepping context
3769aad739acSMatthew G. Knepley . u  - The approximate solution
3770aad739acSMatthew G. Knepley - e  - The Vec used to store the error
3771aad739acSMatthew G. Knepley 
3772aad739acSMatthew G. Knepley   Level: advanced
3773aad739acSMatthew G. Knepley 
3774db781477SPatrick Sanan .seealso: `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3775aad739acSMatthew G. Knepley @*/
3776aad739acSMatthew G. Knepley PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3777aad739acSMatthew G. Knepley {
3778aad739acSMatthew G. Knepley   PetscFunctionBegin;
3779aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3780aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3781aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
37829566063dSJacob Faibussowitsch   if (ts->ops->exacterror) PetscCall((*ts->ops->exacterror)(ts, u, e));
3783aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3784aad739acSMatthew G. Knepley }
3785aad739acSMatthew G. Knepley 
3786b1cb36f3SHong Zhang /*@
37876a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
37886a4d4014SLisandro Dalcin 
37896a4d4014SLisandro Dalcin    Collective on TS
37906a4d4014SLisandro Dalcin 
3791d8d19677SJose E. Roman    Input Parameters:
37926a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
379363e21af5SBarry Smith -  u - the solution vector  (can be null if TSSetSolution() was used and TSSetExactFinalTime(ts,TS_EXACTFINALTIME_MATCHSTEP) was not used,
379463e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
37955a3a76d0SJed Brown 
37966a4d4014SLisandro Dalcin    Level: beginner
37976a4d4014SLisandro Dalcin 
37985a3a76d0SJed Brown    Notes:
37995a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
38005a3a76d0SJed Brown    held state accessible by TSGetSolution() and TSGetTime() because the method may have
38015a3a76d0SJed Brown    stepped over the final time.
38025a3a76d0SJed Brown 
3803db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
38046a4d4014SLisandro Dalcin @*/
3805cc708dedSBarry Smith PetscErrorCode TSSolve(TS ts,Vec u)
38066a4d4014SLisandro Dalcin {
3807b06615a5SLisandro Dalcin   Vec               solution;
3808f22f69f0SBarry Smith 
38096a4d4014SLisandro Dalcin   PetscFunctionBegin;
38100700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3811f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u,VEC_CLASSID,2);
3812303a5415SBarry Smith 
38139566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3814ee41a567SStefano 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 */
38150910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
38169566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u,&solution));
38179566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts,solution));
38189566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
38195a3a76d0SJed Brown     }
38209566063dSJacob Faibussowitsch     PetscCall(VecCopy(u,ts->vec_sol));
38213c633725SBarry Smith     PetscCheck(!ts->forward_solve,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
38221baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts,u));
38239566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
38249566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory,ts));
3825a6772fa2SLisandro Dalcin 
38263c633725SBarry 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>");
38273c633725SBarry 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()");
38283c633725SBarry 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");
38294a658b32SHong 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");
38304a658b32SHong Zhang 
3831*e1db57b0SHong 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 */
38324a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol,ts->tspan->vecs_sol[0]));
38334a658b32SHong Zhang     ts->tspan->spanctr = 1;
38344a658b32SHong Zhang   }
3835a6772fa2SLisandro Dalcin 
38361baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3837715f1b00SHong Zhang 
3838e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3839715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3840e7069c78SShri      TSTrajectory to incorrectly save the output files
3841e7069c78SShri   */
3842715f1b00SHong Zhang   /* reset time step and iteration counters */
38432808aa04SLisandro Dalcin   if (!ts->steps) {
38445ef26d82SJed Brown     ts->ksp_its           = 0;
38455ef26d82SJed Brown     ts->snes_its          = 0;
3846c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3847c610991cSLisandro Dalcin     ts->reject            = 0;
38482808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
38492808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
38507d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
38512808aa04SLisandro Dalcin   }
3852e97c63d7SStefano Zampini 
38534a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3854e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
38554a658b32SHong Zhang     PetscReal maxdt;
3856e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3857e97c63d7SStefano Zampini 
38584a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
38594a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3860e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt,maxdt,10*PETSC_MACHINE_EPSILON,0) ? maxdt : dt);
3861e97c63d7SStefano Zampini   }
3862193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3863193ac0bcSJed Brown 
3864900f6b5bSMatthew G. Knepley   {
3865900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3866900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3867900f6b5bSMatthew G. Knepley     PetscBool         flg;
3868900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3869900f6b5bSMatthew G. Knepley 
3870900f6b5bSMatthew G. Knepley     if (!incall) {
3871900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
38729566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject) ts),((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3873900f6b5bSMatthew G. Knepley       if (flg) {
3874900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3875900f6b5bSMatthew G. Knepley         DM           dm;
3876900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3877900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3878f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3879900f6b5bSMatthew G. Knepley 
3880900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
38819566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject) ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
38829566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
38839566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
38849566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
38859566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject) ts), &conv));
38869566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
38879566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject) ts));
38889566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
38899566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
38909566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
38919566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
38929566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
38939566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
38949566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
38959566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
38969566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3897900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3898900f6b5bSMatthew G. Knepley       }
3899900f6b5bSMatthew G. Knepley     }
3900900f6b5bSMatthew G. Knepley   }
3901900f6b5bSMatthew G. Knepley 
39029566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts,NULL,"-ts_view_pre"));
3903f05ece33SBarry Smith 
3904193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
39059566063dSJacob Faibussowitsch     PetscCall((*ts->ops->solve)(ts));
39069566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol,u));
3907cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3908a6772fa2SLisandro Dalcin     solution = ts->vec_sol;
3909be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3910db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3911db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3912e7069c78SShri 
39132808aa04SLisandro Dalcin     if (!ts->steps) {
39149566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol));
39159566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event,ts,ts->ptime,ts->vec_sol));
39162808aa04SLisandro Dalcin     }
39176427ac75SLisandro Dalcin 
3918e1a7a14fSJed Brown     while (!ts->reason) {
39199566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol));
39209687d888SLisandro Dalcin       if (!ts->steprollback) {
39219566063dSJacob Faibussowitsch         PetscCall(TSPreStep(ts));
39229687d888SLisandro Dalcin       }
39239566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
39241baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts,NULL));
39251baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts,NULL));
3926cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
39277b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
39289566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
39297b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3930b1cb36f3SHong Zhang       }
393158818c2dSLisandro Dalcin       if (ts->forward_solve) { /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
39327b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
39339566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
39347b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3935715f1b00SHong Zhang       }
39369566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
39379566063dSJacob 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. */
39381baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3939e783b05fSHong Zhang       if (!ts->steprollback) {
39409566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory,ts,ts->steps,ts->ptime,ts->vec_sol));
39419566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3942aeb4809dSShri Abhyankar       }
3943193ac0bcSJed Brown     }
39449566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts,ts->steps,ts->ptime,ts->vec_sol));
39456427ac75SLisandro Dalcin 
394649354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
39479566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts,ts->max_time,u));
3948cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3949b06615a5SLisandro Dalcin       solution = u;
39509566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts,-1,ts->solvetime,solution));
39510574a7fbSJed Brown     } else {
39529566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol,u));
3953cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3954b06615a5SLisandro Dalcin       solution = ts->vec_sol;
39550574a7fbSJed Brown     }
3956193ac0bcSJed Brown   }
3957d2daff3dSHong Zhang 
39589566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts,NULL,"-ts_view"));
39599566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution,(PetscObject)ts,"-ts_view_solution"));
39609566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
39611baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
39626a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
39636a4d4014SLisandro Dalcin }
39646a4d4014SLisandro Dalcin 
3965d763cef2SBarry Smith /*@
3966b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3967d763cef2SBarry Smith 
3968d763cef2SBarry Smith    Not Collective
3969d763cef2SBarry Smith 
3970d763cef2SBarry Smith    Input Parameter:
3971d763cef2SBarry Smith .  ts - the TS context obtained from TSCreate()
3972d763cef2SBarry Smith 
3973d763cef2SBarry Smith    Output Parameter:
397419eac22cSLisandro Dalcin .  t  - the current time. This time may not corresponds to the final time set with TSSetMaxTime(), use TSGetSolveTime().
3975d763cef2SBarry Smith 
3976d763cef2SBarry Smith    Level: beginner
3977d763cef2SBarry Smith 
3978b8123daeSJed Brown    Note:
3979b8123daeSJed Brown    When called during time step evaluation (e.g. during residual evaluation or via hooks set using TSSetPreStep(),
39809be3e283SDebojyoti Ghosh    TSSetPreStage(), TSSetPostStage(), or TSSetPostStep()), the time is the time at the start of the step being evaluated.
3981b8123daeSJed Brown 
3982db781477SPatrick Sanan .seealso: `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3983d763cef2SBarry Smith 
3984d763cef2SBarry Smith @*/
39857087cfbeSBarry Smith PetscErrorCode  TSGetTime(TS ts,PetscReal *t)
3986d763cef2SBarry Smith {
3987d763cef2SBarry Smith   PetscFunctionBegin;
39880700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
3989f7cf8827SBarry Smith   PetscValidRealPointer(t,2);
3990d763cef2SBarry Smith   *t = ts->ptime;
3991d763cef2SBarry Smith   PetscFunctionReturn(0);
3992d763cef2SBarry Smith }
3993d763cef2SBarry Smith 
3994e5e524a1SHong Zhang /*@
3995e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3996e5e524a1SHong Zhang 
3997e5e524a1SHong Zhang    Not Collective
3998e5e524a1SHong Zhang 
3999e5e524a1SHong Zhang    Input Parameter:
4000e5e524a1SHong Zhang .  ts - the TS context obtained from TSCreate()
4001e5e524a1SHong Zhang 
4002e5e524a1SHong Zhang    Output Parameter:
4003e5e524a1SHong Zhang .  t  - the previous time
4004e5e524a1SHong Zhang 
4005e5e524a1SHong Zhang    Level: beginner
4006e5e524a1SHong Zhang 
4007db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4008e5e524a1SHong Zhang 
4009e5e524a1SHong Zhang @*/
4010e5e524a1SHong Zhang PetscErrorCode  TSGetPrevTime(TS ts,PetscReal *t)
4011e5e524a1SHong Zhang {
4012e5e524a1SHong Zhang   PetscFunctionBegin;
4013e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4014e5e524a1SHong Zhang   PetscValidRealPointer(t,2);
4015e5e524a1SHong Zhang   *t = ts->ptime_prev;
4016e5e524a1SHong Zhang   PetscFunctionReturn(0);
4017e5e524a1SHong Zhang }
4018e5e524a1SHong Zhang 
40196a4d4014SLisandro Dalcin /*@
40206a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
40216a4d4014SLisandro Dalcin 
40223f9fe445SBarry Smith    Logically Collective on TS
40236a4d4014SLisandro Dalcin 
40246a4d4014SLisandro Dalcin    Input Parameters:
40256a4d4014SLisandro Dalcin +  ts - the TS context obtained from TSCreate()
40266a4d4014SLisandro Dalcin -  time - the time
40276a4d4014SLisandro Dalcin 
40286a4d4014SLisandro Dalcin    Level: intermediate
40296a4d4014SLisandro Dalcin 
4030db781477SPatrick Sanan .seealso: `TSGetTime()`, `TSSetMaxSteps()`
40316a4d4014SLisandro Dalcin 
40326a4d4014SLisandro Dalcin @*/
40337087cfbeSBarry Smith PetscErrorCode  TSSetTime(TS ts, PetscReal t)
40346a4d4014SLisandro Dalcin {
40356a4d4014SLisandro Dalcin   PetscFunctionBegin;
40360700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4037c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts,t,2);
40386a4d4014SLisandro Dalcin   ts->ptime = t;
40396a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
40406a4d4014SLisandro Dalcin }
40416a4d4014SLisandro Dalcin 
4042d763cef2SBarry Smith /*@C
4043d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
4044d763cef2SBarry Smith    TS options in the database.
4045d763cef2SBarry Smith 
40463f9fe445SBarry Smith    Logically Collective on TS
4047d763cef2SBarry Smith 
4048d8d19677SJose E. Roman    Input Parameters:
4049d763cef2SBarry Smith +  ts     - The TS context
4050d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
4051d763cef2SBarry Smith 
4052d763cef2SBarry Smith    Notes:
4053d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
4054d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
4055d763cef2SBarry Smith    hyphen.
4056d763cef2SBarry Smith 
4057d763cef2SBarry Smith    Level: advanced
4058d763cef2SBarry Smith 
4059db781477SPatrick Sanan .seealso: `TSSetFromOptions()`
4060d763cef2SBarry Smith 
4061d763cef2SBarry Smith @*/
40627087cfbeSBarry Smith PetscErrorCode  TSSetOptionsPrefix(TS ts,const char prefix[])
4063d763cef2SBarry Smith {
4064089b2837SJed Brown   SNES           snes;
4065d763cef2SBarry Smith 
4066d763cef2SBarry Smith   PetscFunctionBegin;
40670700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
40689566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts,prefix));
40699566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
40709566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes,prefix));
4071d763cef2SBarry Smith   PetscFunctionReturn(0);
4072d763cef2SBarry Smith }
4073d763cef2SBarry Smith 
4074d763cef2SBarry Smith /*@C
4075d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4076d763cef2SBarry Smith    TS options in the database.
4077d763cef2SBarry Smith 
40783f9fe445SBarry Smith    Logically Collective on TS
4079d763cef2SBarry Smith 
4080d8d19677SJose E. Roman    Input Parameters:
4081d763cef2SBarry Smith +  ts     - The TS context
4082d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
4083d763cef2SBarry Smith 
4084d763cef2SBarry Smith    Notes:
4085d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
4086d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
4087d763cef2SBarry Smith    hyphen.
4088d763cef2SBarry Smith 
4089d763cef2SBarry Smith    Level: advanced
4090d763cef2SBarry Smith 
4091db781477SPatrick Sanan .seealso: `TSGetOptionsPrefix()`
4092d763cef2SBarry Smith 
4093d763cef2SBarry Smith @*/
40947087cfbeSBarry Smith PetscErrorCode  TSAppendOptionsPrefix(TS ts,const char prefix[])
4095d763cef2SBarry Smith {
4096089b2837SJed Brown   SNES           snes;
4097d763cef2SBarry Smith 
4098d763cef2SBarry Smith   PetscFunctionBegin;
40990700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
41009566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts,prefix));
41019566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
41029566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes,prefix));
4103d763cef2SBarry Smith   PetscFunctionReturn(0);
4104d763cef2SBarry Smith }
4105d763cef2SBarry Smith 
4106d763cef2SBarry Smith /*@C
4107d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
4108d763cef2SBarry Smith    TS options in the database.
4109d763cef2SBarry Smith 
4110d763cef2SBarry Smith    Not Collective
4111d763cef2SBarry Smith 
4112d763cef2SBarry Smith    Input Parameter:
4113d763cef2SBarry Smith .  ts - The TS context
4114d763cef2SBarry Smith 
4115d763cef2SBarry Smith    Output Parameter:
4116d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4117d763cef2SBarry Smith 
411895452b02SPatrick Sanan    Notes:
411995452b02SPatrick Sanan     On the fortran side, the user should pass in a string 'prifix' of
4120d763cef2SBarry Smith    sufficient length to hold the prefix.
4121d763cef2SBarry Smith 
4122d763cef2SBarry Smith    Level: intermediate
4123d763cef2SBarry Smith 
4124db781477SPatrick Sanan .seealso: `TSAppendOptionsPrefix()`
4125d763cef2SBarry Smith @*/
41267087cfbeSBarry Smith PetscErrorCode  TSGetOptionsPrefix(TS ts,const char *prefix[])
4127d763cef2SBarry Smith {
4128d763cef2SBarry Smith   PetscFunctionBegin;
41290700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
41304482741eSBarry Smith   PetscValidPointer(prefix,2);
41319566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts,prefix));
4132d763cef2SBarry Smith   PetscFunctionReturn(0);
4133d763cef2SBarry Smith }
4134d763cef2SBarry Smith 
4135d763cef2SBarry Smith /*@C
4136d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4137d763cef2SBarry Smith 
4138d763cef2SBarry Smith    Not Collective, but parallel objects are returned if TS is parallel
4139d763cef2SBarry Smith 
4140d763cef2SBarry Smith    Input Parameter:
4141d763cef2SBarry Smith .  ts  - The TS context obtained from TSCreate()
4142d763cef2SBarry Smith 
4143d763cef2SBarry Smith    Output Parameters:
4144e4357dc4SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4145e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4146e4357dc4SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or NULL)
4147e4357dc4SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4148d763cef2SBarry Smith 
414995452b02SPatrick Sanan    Notes:
415095452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
4151d763cef2SBarry Smith 
4152d763cef2SBarry Smith    Level: intermediate
4153d763cef2SBarry Smith 
4154db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4155d763cef2SBarry Smith 
4156d763cef2SBarry Smith @*/
4157e4357dc4SBarry Smith PetscErrorCode  TSGetRHSJacobian(TS ts,Mat *Amat,Mat *Pmat,TSRHSJacobian *func,void **ctx)
4158d763cef2SBarry Smith {
415924989b8cSPeter Brune   DM             dm;
4160089b2837SJed Brown 
4161d763cef2SBarry Smith   PetscFunctionBegin;
416223a57915SBarry Smith   if (Amat || Pmat) {
416323a57915SBarry Smith     SNES snes;
41649566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
41659566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
41669566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
416723a57915SBarry Smith   }
41689566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
41699566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm,func,ctx));
4170d763cef2SBarry Smith   PetscFunctionReturn(0);
4171d763cef2SBarry Smith }
4172d763cef2SBarry Smith 
41732eca1d9cSJed Brown /*@C
41742eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
41752eca1d9cSJed Brown 
41762eca1d9cSJed Brown    Not Collective, but parallel objects are returned if TS is parallel
41772eca1d9cSJed Brown 
41782eca1d9cSJed Brown    Input Parameter:
41792eca1d9cSJed Brown .  ts  - The TS context obtained from TSCreate()
41802eca1d9cSJed Brown 
41812eca1d9cSJed Brown    Output Parameters:
4182e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4183e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
41842eca1d9cSJed Brown .  f   - The function to compute the matrices
41852eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
41862eca1d9cSJed Brown 
418795452b02SPatrick Sanan    Notes:
418895452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
41892eca1d9cSJed Brown 
41902eca1d9cSJed Brown    Level: advanced
41912eca1d9cSJed Brown 
4192db781477SPatrick Sanan .seealso: `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
41932eca1d9cSJed Brown 
41942eca1d9cSJed Brown @*/
4195e4357dc4SBarry Smith PetscErrorCode  TSGetIJacobian(TS ts,Mat *Amat,Mat *Pmat,TSIJacobian *f,void **ctx)
41962eca1d9cSJed Brown {
419724989b8cSPeter Brune   DM             dm;
41980910c330SBarry Smith 
41992eca1d9cSJed Brown   PetscFunctionBegin;
4200c0aab802Sstefano_zampini   if (Amat || Pmat) {
4201c0aab802Sstefano_zampini     SNES snes;
42029566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts,&snes));
42039566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
42049566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes,Amat,Pmat,NULL,NULL));
4205c0aab802Sstefano_zampini   }
42069566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts,&dm));
42079566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm,f,ctx));
42082eca1d9cSJed Brown   PetscFunctionReturn(0);
42092eca1d9cSJed Brown }
42102eca1d9cSJed Brown 
4211af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
42126c699258SBarry Smith /*@
42132a808120SBarry Smith    TSSetDM - Sets the DM that may be used by some nonlinear solvers or preconditioners under the TS
42146c699258SBarry Smith 
4215d083f849SBarry Smith    Logically Collective on ts
42166c699258SBarry Smith 
42176c699258SBarry Smith    Input Parameters:
42182a808120SBarry Smith +  ts - the ODE integrator object
42192a808120SBarry Smith -  dm - the dm, cannot be NULL
42206c699258SBarry Smith 
4221e03a659cSJed Brown    Notes:
4222e03a659cSJed Brown    A DM can only be used for solving one problem at a time because information about the problem is stored on the DM,
4223e03a659cSJed Brown    even when not using interfaces like DMTSSetIFunction().  Use DMClone() to get a distinct DM when solving
4224e03a659cSJed Brown    different problems using the same function space.
4225e03a659cSJed Brown 
42266c699258SBarry Smith    Level: intermediate
42276c699258SBarry Smith 
4228db781477SPatrick Sanan .seealso: `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
42296c699258SBarry Smith @*/
42307087cfbeSBarry Smith PetscErrorCode  TSSetDM(TS ts,DM dm)
42316c699258SBarry Smith {
4232089b2837SJed Brown   SNES           snes;
4233942e3340SBarry Smith   DMTS           tsdm;
42346c699258SBarry Smith 
42356c699258SBarry Smith   PetscFunctionBegin;
42360700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
42372a808120SBarry Smith   PetscValidHeaderSpecific(dm,DM_CLASSID,2);
42389566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4239942e3340SBarry Smith   if (ts->dm) {               /* Move the DMTS context over to the new DM unless the new DM already has one */
42402a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
42419566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm,dm));
42429566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm,&tsdm));
424324989b8cSPeter Brune       if (tsdm->originaldm == ts->dm) { /* Grant write privileges to the replacement DM */
424424989b8cSPeter Brune         tsdm->originaldm = dm;
424524989b8cSPeter Brune       }
424624989b8cSPeter Brune     }
42479566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
424824989b8cSPeter Brune   }
42496c699258SBarry Smith   ts->dm = dm;
4250bbd56ea5SKarl Rupp 
42519566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
42529566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes,dm));
42536c699258SBarry Smith   PetscFunctionReturn(0);
42546c699258SBarry Smith }
42556c699258SBarry Smith 
42566c699258SBarry Smith /*@
42576c699258SBarry Smith    TSGetDM - Gets the DM that may be used by some preconditioners
42586c699258SBarry Smith 
42593f9fe445SBarry Smith    Not Collective
42606c699258SBarry Smith 
42616c699258SBarry Smith    Input Parameter:
42626c699258SBarry Smith . ts - the preconditioner context
42636c699258SBarry Smith 
42646c699258SBarry Smith    Output Parameter:
42656c699258SBarry Smith .  dm - the dm
42666c699258SBarry Smith 
42676c699258SBarry Smith    Level: intermediate
42686c699258SBarry Smith 
4269db781477SPatrick Sanan .seealso: `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
42706c699258SBarry Smith @*/
42717087cfbeSBarry Smith PetscErrorCode  TSGetDM(TS ts,DM *dm)
42726c699258SBarry Smith {
42736c699258SBarry Smith   PetscFunctionBegin;
42740700a824SBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4275496e6a7aSJed Brown   if (!ts->dm) {
42769566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts),&ts->dm));
42779566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes,ts->dm));
4278496e6a7aSJed Brown   }
42796c699258SBarry Smith   *dm = ts->dm;
42806c699258SBarry Smith   PetscFunctionReturn(0);
42816c699258SBarry Smith }
42821713a123SBarry Smith 
42830f5c6efeSJed Brown /*@
42840f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
42850f5c6efeSJed Brown 
42863f9fe445SBarry Smith    Logically Collective on SNES
42870f5c6efeSJed Brown 
4288d8d19677SJose E. Roman    Input Parameters:
4289d42a1c89SJed Brown + snes - nonlinear solver
42900910c330SBarry Smith . U - the current state at which to evaluate the residual
4291d42a1c89SJed Brown - ctx - user context, must be a TS
42920f5c6efeSJed Brown 
42930f5c6efeSJed Brown    Output Parameter:
42940f5c6efeSJed Brown . F - the nonlinear residual
42950f5c6efeSJed Brown 
42960f5c6efeSJed Brown    Notes:
42970f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
42980f5c6efeSJed Brown    It is most frequently passed to MatFDColoringSetFunction().
42990f5c6efeSJed Brown 
43000f5c6efeSJed Brown    Level: advanced
43010f5c6efeSJed Brown 
4302db781477SPatrick Sanan .seealso: `SNESSetFunction()`, `MatFDColoringSetFunction()`
43030f5c6efeSJed Brown @*/
43040910c330SBarry Smith PetscErrorCode  SNESTSFormFunction(SNES snes,Vec U,Vec F,void *ctx)
43050f5c6efeSJed Brown {
43060f5c6efeSJed Brown   TS             ts = (TS)ctx;
43070f5c6efeSJed Brown 
43080f5c6efeSJed Brown   PetscFunctionBegin;
43090f5c6efeSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
43100910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
43110f5c6efeSJed Brown   PetscValidHeaderSpecific(F,VEC_CLASSID,3);
43120f5c6efeSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,4);
43139566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes,U,F,ts));
43140f5c6efeSJed Brown   PetscFunctionReturn(0);
43150f5c6efeSJed Brown }
43160f5c6efeSJed Brown 
43170f5c6efeSJed Brown /*@
43180f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
43190f5c6efeSJed Brown 
43200f5c6efeSJed Brown    Collective on SNES
43210f5c6efeSJed Brown 
4322d8d19677SJose E. Roman    Input Parameters:
43230f5c6efeSJed Brown + snes - nonlinear solver
43240910c330SBarry Smith . U - the current state at which to evaluate the residual
43250f5c6efeSJed Brown - ctx - user context, must be a TS
43260f5c6efeSJed Brown 
4327d8d19677SJose E. Roman    Output Parameters:
43280f5c6efeSJed Brown + A - the Jacobian
43296b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
43300f5c6efeSJed Brown 
43310f5c6efeSJed Brown    Notes:
43320f5c6efeSJed Brown    This function is not normally called by users and is automatically registered with the SNES used by TS.
43330f5c6efeSJed Brown 
43340f5c6efeSJed Brown    Level: developer
43350f5c6efeSJed Brown 
4336db781477SPatrick Sanan .seealso: `SNESSetJacobian()`
43370f5c6efeSJed Brown @*/
4338d1e9a80fSBarry Smith PetscErrorCode  SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,void *ctx)
43390f5c6efeSJed Brown {
43400f5c6efeSJed Brown   TS             ts = (TS)ctx;
43410f5c6efeSJed Brown 
43420f5c6efeSJed Brown   PetscFunctionBegin;
43430f5c6efeSJed Brown   PetscValidHeaderSpecific(snes,SNES_CLASSID,1);
43440910c330SBarry Smith   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
43450f5c6efeSJed Brown   PetscValidPointer(A,3);
434694ab13aaSBarry Smith   PetscValidHeaderSpecific(A,MAT_CLASSID,3);
43470f5c6efeSJed Brown   PetscValidPointer(B,4);
434894ab13aaSBarry Smith   PetscValidHeaderSpecific(B,MAT_CLASSID,4);
4349064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts,TS_CLASSID,5);
43509566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes,U,A,B,ts));
43510f5c6efeSJed Brown   PetscFunctionReturn(0);
43520f5c6efeSJed Brown }
4353325fc9f4SBarry Smith 
43540e4ef248SJed Brown /*@C
43559ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
43560e4ef248SJed Brown 
43570e4ef248SJed Brown    Collective on TS
43580e4ef248SJed Brown 
43594165533cSJose E. Roman    Input Parameters:
43600e4ef248SJed Brown +  ts - time stepping context
43610e4ef248SJed Brown .  t - time at which to evaluate
43620910c330SBarry Smith .  U - state at which to evaluate
43630e4ef248SJed Brown -  ctx - context
43640e4ef248SJed Brown 
43654165533cSJose E. Roman    Output Parameter:
43660e4ef248SJed Brown .  F - right hand side
43670e4ef248SJed Brown 
43680e4ef248SJed Brown    Level: intermediate
43690e4ef248SJed Brown 
43700e4ef248SJed Brown    Notes:
43710e4ef248SJed Brown    This function is intended to be passed to TSSetRHSFunction() to evaluate the right hand side for linear problems.
43720e4ef248SJed Brown    The matrix (and optionally the evaluation context) should be passed to TSSetRHSJacobian().
43730e4ef248SJed Brown 
4374db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
43750e4ef248SJed Brown @*/
43760910c330SBarry Smith PetscErrorCode TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,void *ctx)
43770e4ef248SJed Brown {
43780e4ef248SJed Brown   Mat            Arhs,Brhs;
43790e4ef248SJed Brown 
43800e4ef248SJed Brown   PetscFunctionBegin;
43819566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts,&Arhs,&Brhs));
43822663174eSHong Zhang   /* undo the damage caused by shifting */
43839566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts,Arhs,Brhs));
43849566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts,t,U,Arhs,Brhs));
43859566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs,U,F));
43860e4ef248SJed Brown   PetscFunctionReturn(0);
43870e4ef248SJed Brown }
43880e4ef248SJed Brown 
43890e4ef248SJed Brown /*@C
43900e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
43910e4ef248SJed Brown 
43920e4ef248SJed Brown    Collective on TS
43930e4ef248SJed Brown 
43944165533cSJose E. Roman    Input Parameters:
43950e4ef248SJed Brown +  ts - time stepping context
43960e4ef248SJed Brown .  t - time at which to evaluate
43970910c330SBarry Smith .  U - state at which to evaluate
43980e4ef248SJed Brown -  ctx - context
43990e4ef248SJed Brown 
44004165533cSJose E. Roman    Output Parameters:
44010e4ef248SJed Brown +  A - pointer to operator
440297bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
44030e4ef248SJed Brown 
44040e4ef248SJed Brown    Level: intermediate
44050e4ef248SJed Brown 
44060e4ef248SJed Brown    Notes:
44070e4ef248SJed Brown    This function is intended to be passed to TSSetRHSJacobian() to evaluate the Jacobian for linear time-independent problems.
44080e4ef248SJed Brown 
4409db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
44100e4ef248SJed Brown @*/
4411d1e9a80fSBarry Smith PetscErrorCode TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,void *ctx)
44120e4ef248SJed Brown {
44130e4ef248SJed Brown   PetscFunctionBegin;
44140e4ef248SJed Brown   PetscFunctionReturn(0);
44150e4ef248SJed Brown }
44160e4ef248SJed Brown 
44170026cea9SSean Farley /*@C
44180026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
44190026cea9SSean Farley 
44200026cea9SSean Farley    Collective on TS
44210026cea9SSean Farley 
44224165533cSJose E. Roman    Input Parameters:
44230026cea9SSean Farley +  ts - time stepping context
44240026cea9SSean Farley .  t - time at which to evaluate
44250910c330SBarry Smith .  U - state at which to evaluate
44260910c330SBarry Smith .  Udot - time derivative of state vector
44270026cea9SSean Farley -  ctx - context
44280026cea9SSean Farley 
44294165533cSJose E. Roman    Output Parameter:
44300026cea9SSean Farley .  F - left hand side
44310026cea9SSean Farley 
44320026cea9SSean Farley    Level: intermediate
44330026cea9SSean Farley 
44340026cea9SSean Farley    Notes:
44350910c330SBarry 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
44360026cea9SSean Farley    user is required to write their own TSComputeIFunction.
44370026cea9SSean Farley    This function is intended to be passed to TSSetIFunction() to evaluate the left hand side for linear problems.
44380026cea9SSean Farley    The matrix (and optionally the evaluation context) should be passed to TSSetIJacobian().
44390026cea9SSean Farley 
44409ae8fd06SBarry Smith    Note that using this function is NOT equivalent to using TSComputeRHSFunctionLinear() since that solves Udot = A U
44419ae8fd06SBarry Smith 
4442db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
44430026cea9SSean Farley @*/
44440910c330SBarry Smith PetscErrorCode TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,void *ctx)
44450026cea9SSean Farley {
44460026cea9SSean Farley   Mat            A,B;
44470026cea9SSean Farley 
44480026cea9SSean Farley   PetscFunctionBegin;
44499566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts,&A,&B,NULL,NULL));
44509566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts,t,U,Udot,1.0,A,B,PETSC_TRUE));
44519566063dSJacob Faibussowitsch   PetscCall(MatMult(A,Udot,F));
44520026cea9SSean Farley   PetscFunctionReturn(0);
44530026cea9SSean Farley }
44540026cea9SSean Farley 
44550026cea9SSean Farley /*@C
4456b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
44570026cea9SSean Farley 
44580026cea9SSean Farley    Collective on TS
44590026cea9SSean Farley 
44604165533cSJose E. Roman    Input Parameters:
44610026cea9SSean Farley +  ts - time stepping context
44620026cea9SSean Farley .  t - time at which to evaluate
44630910c330SBarry Smith .  U - state at which to evaluate
44640910c330SBarry Smith .  Udot - time derivative of state vector
44650026cea9SSean Farley .  shift - shift to apply
44660026cea9SSean Farley -  ctx - context
44670026cea9SSean Farley 
44684165533cSJose E. Roman    Output Parameters:
44690026cea9SSean Farley +  A - pointer to operator
447097bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
44710026cea9SSean Farley 
4472b41af12eSJed Brown    Level: advanced
44730026cea9SSean Farley 
44740026cea9SSean Farley    Notes:
44750026cea9SSean Farley    This function is intended to be passed to TSSetIJacobian() to evaluate the Jacobian for linear time-independent problems.
44760026cea9SSean Farley 
4477b41af12eSJed Brown    It is only appropriate for problems of the form
4478b41af12eSJed Brown 
4479b41af12eSJed Brown $     M Udot = F(U,t)
4480b41af12eSJed Brown 
4481b41af12eSJed Brown   where M is constant and F is non-stiff.  The user must pass M to TSSetIJacobian().  The current implementation only
4482b41af12eSJed Brown   works with IMEX time integration methods such as TSROSW and TSARKIMEX, since there is no support for de-constructing
4483b41af12eSJed Brown   an implicit operator of the form
4484b41af12eSJed Brown 
4485b41af12eSJed Brown $    shift*M + J
4486b41af12eSJed Brown 
4487b41af12eSJed 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
4488b41af12eSJed Brown   a copy of M or reassemble it when requested.
4489b41af12eSJed Brown 
4490db781477SPatrick Sanan .seealso: `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
44910026cea9SSean Farley @*/
4492d1e9a80fSBarry Smith PetscErrorCode TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,void *ctx)
44930026cea9SSean Farley {
44940026cea9SSean Farley   PetscFunctionBegin;
44959566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4496b41af12eSJed Brown   ts->ijacobian.shift = shift;
44970026cea9SSean Farley   PetscFunctionReturn(0);
44980026cea9SSean Farley }
4499b41af12eSJed Brown 
4500e817cc15SEmil Constantinescu /*@
4501e817cc15SEmil Constantinescu    TSGetEquationType - Gets the type of the equation that TS is solving.
4502e817cc15SEmil Constantinescu 
4503e817cc15SEmil Constantinescu    Not Collective
4504e817cc15SEmil Constantinescu 
4505e817cc15SEmil Constantinescu    Input Parameter:
4506e817cc15SEmil Constantinescu .  ts - the TS context
4507e817cc15SEmil Constantinescu 
4508e817cc15SEmil Constantinescu    Output Parameter:
45094e6b9ce4SEmil Constantinescu .  equation_type - see TSEquationType
4510e817cc15SEmil Constantinescu 
4511e817cc15SEmil Constantinescu    Level: beginner
4512e817cc15SEmil Constantinescu 
4513db781477SPatrick Sanan .seealso: `TSSetEquationType()`, `TSEquationType`
4514e817cc15SEmil Constantinescu @*/
4515e817cc15SEmil Constantinescu PetscErrorCode  TSGetEquationType(TS ts,TSEquationType *equation_type)
4516e817cc15SEmil Constantinescu {
4517e817cc15SEmil Constantinescu   PetscFunctionBegin;
4518e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4519e817cc15SEmil Constantinescu   PetscValidPointer(equation_type,2);
4520e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
4521e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4522e817cc15SEmil Constantinescu }
4523e817cc15SEmil Constantinescu 
4524e817cc15SEmil Constantinescu /*@
4525e817cc15SEmil Constantinescu    TSSetEquationType - Sets the type of the equation that TS is solving.
4526e817cc15SEmil Constantinescu 
4527e817cc15SEmil Constantinescu    Not Collective
4528e817cc15SEmil Constantinescu 
4529d8d19677SJose E. Roman    Input Parameters:
4530e817cc15SEmil Constantinescu +  ts - the TS context
45311297b224SEmil Constantinescu -  equation_type - see TSEquationType
4532e817cc15SEmil Constantinescu 
4533e817cc15SEmil Constantinescu    Level: advanced
4534e817cc15SEmil Constantinescu 
4535db781477SPatrick Sanan .seealso: `TSGetEquationType()`, `TSEquationType`
4536e817cc15SEmil Constantinescu @*/
4537e817cc15SEmil Constantinescu PetscErrorCode  TSSetEquationType(TS ts,TSEquationType equation_type)
4538e817cc15SEmil Constantinescu {
4539e817cc15SEmil Constantinescu   PetscFunctionBegin;
4540e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4541e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
4542e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4543e817cc15SEmil Constantinescu }
45440026cea9SSean Farley 
45454af1b03aSJed Brown /*@
45464af1b03aSJed Brown    TSGetConvergedReason - Gets the reason the TS iteration was stopped.
45474af1b03aSJed Brown 
45484af1b03aSJed Brown    Not Collective
45494af1b03aSJed Brown 
45504af1b03aSJed Brown    Input Parameter:
45514af1b03aSJed Brown .  ts - the TS context
45524af1b03aSJed Brown 
45534af1b03aSJed Brown    Output Parameter:
45544af1b03aSJed Brown .  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
45554af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
45564af1b03aSJed Brown 
4557487e0bb9SJed Brown    Level: beginner
45584af1b03aSJed Brown 
4559cd652676SJed Brown    Notes:
4560cd652676SJed Brown    Can only be called after the call to TSSolve() is complete.
45614af1b03aSJed Brown 
4562db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
45634af1b03aSJed Brown @*/
45644af1b03aSJed Brown PetscErrorCode  TSGetConvergedReason(TS ts,TSConvergedReason *reason)
45654af1b03aSJed Brown {
45664af1b03aSJed Brown   PetscFunctionBegin;
45674af1b03aSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
45684af1b03aSJed Brown   PetscValidPointer(reason,2);
45694af1b03aSJed Brown   *reason = ts->reason;
45704af1b03aSJed Brown   PetscFunctionReturn(0);
45714af1b03aSJed Brown }
45724af1b03aSJed Brown 
4573d6ad946cSShri Abhyankar /*@
4574d6ad946cSShri Abhyankar    TSSetConvergedReason - Sets the reason for handling the convergence of TSSolve.
4575d6ad946cSShri Abhyankar 
45766b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4577d6ad946cSShri Abhyankar 
45786b221cbeSPatrick Sanan    Input Parameters:
4579d6ad946cSShri Abhyankar +  ts - the TS context
45806b221cbeSPatrick Sanan -  reason - negative value indicates diverged, positive value converged, see TSConvergedReason or the
4581d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4582d6ad946cSShri Abhyankar 
4583f5abba47SShri Abhyankar    Level: advanced
4584d6ad946cSShri Abhyankar 
4585d6ad946cSShri Abhyankar    Notes:
45866b221cbeSPatrick Sanan    Can only be called while TSSolve() is active.
4587d6ad946cSShri Abhyankar 
4588db781477SPatrick Sanan .seealso: `TSConvergedReason`
4589d6ad946cSShri Abhyankar @*/
4590d6ad946cSShri Abhyankar PetscErrorCode  TSSetConvergedReason(TS ts,TSConvergedReason reason)
4591d6ad946cSShri Abhyankar {
4592d6ad946cSShri Abhyankar   PetscFunctionBegin;
4593d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4594d6ad946cSShri Abhyankar   ts->reason = reason;
4595d6ad946cSShri Abhyankar   PetscFunctionReturn(0);
4596d6ad946cSShri Abhyankar }
4597d6ad946cSShri Abhyankar 
4598cc708dedSBarry Smith /*@
4599cc708dedSBarry Smith    TSGetSolveTime - Gets the time after a call to TSSolve()
4600cc708dedSBarry Smith 
4601cc708dedSBarry Smith    Not Collective
4602cc708dedSBarry Smith 
4603cc708dedSBarry Smith    Input Parameter:
4604cc708dedSBarry Smith .  ts - the TS context
4605cc708dedSBarry Smith 
4606cc708dedSBarry Smith    Output Parameter:
460719eac22cSLisandro Dalcin .  ftime - the final time. This time corresponds to the final time set with TSSetMaxTime()
4608cc708dedSBarry Smith 
4609487e0bb9SJed Brown    Level: beginner
4610cc708dedSBarry Smith 
4611cc708dedSBarry Smith    Notes:
4612cc708dedSBarry Smith    Can only be called after the call to TSSolve() is complete.
4613cc708dedSBarry Smith 
4614db781477SPatrick Sanan .seealso: `TSSetConvergenceTest()`, `TSConvergedReason`
4615cc708dedSBarry Smith @*/
4616cc708dedSBarry Smith PetscErrorCode  TSGetSolveTime(TS ts,PetscReal *ftime)
4617cc708dedSBarry Smith {
4618cc708dedSBarry Smith   PetscFunctionBegin;
4619cc708dedSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4620dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime,2);
4621cc708dedSBarry Smith   *ftime = ts->solvetime;
4622cc708dedSBarry Smith   PetscFunctionReturn(0);
4623cc708dedSBarry Smith }
4624cc708dedSBarry Smith 
46252c18e0fdSBarry Smith /*@
46265ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
46279f67acb7SJed Brown    used by the time integrator.
46289f67acb7SJed Brown 
46299f67acb7SJed Brown    Not Collective
46309f67acb7SJed Brown 
46319f67acb7SJed Brown    Input Parameter:
46329f67acb7SJed Brown .  ts - TS context
46339f67acb7SJed Brown 
46349f67acb7SJed Brown    Output Parameter:
46359f67acb7SJed Brown .  nits - number of nonlinear iterations
46369f67acb7SJed Brown 
46379f67acb7SJed Brown    Notes:
46389f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
46399f67acb7SJed Brown 
46409f67acb7SJed Brown    Level: intermediate
46419f67acb7SJed Brown 
4642db781477SPatrick Sanan .seealso: `TSGetKSPIterations()`
46439f67acb7SJed Brown @*/
46445ef26d82SJed Brown PetscErrorCode TSGetSNESIterations(TS ts,PetscInt *nits)
46459f67acb7SJed Brown {
46469f67acb7SJed Brown   PetscFunctionBegin;
46479f67acb7SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
46489f67acb7SJed Brown   PetscValidIntPointer(nits,2);
46495ef26d82SJed Brown   *nits = ts->snes_its;
46509f67acb7SJed Brown   PetscFunctionReturn(0);
46519f67acb7SJed Brown }
46529f67acb7SJed Brown 
46539f67acb7SJed Brown /*@
46545ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
46559f67acb7SJed Brown    used by the time integrator.
46569f67acb7SJed Brown 
46579f67acb7SJed Brown    Not Collective
46589f67acb7SJed Brown 
46599f67acb7SJed Brown    Input Parameter:
46609f67acb7SJed Brown .  ts - TS context
46619f67acb7SJed Brown 
46629f67acb7SJed Brown    Output Parameter:
46639f67acb7SJed Brown .  lits - number of linear iterations
46649f67acb7SJed Brown 
46659f67acb7SJed Brown    Notes:
46669f67acb7SJed Brown    This counter is reset to zero for each successive call to TSSolve().
46679f67acb7SJed Brown 
46689f67acb7SJed Brown    Level: intermediate
46699f67acb7SJed Brown 
4670db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `SNESGetKSPIterations()`
46719f67acb7SJed Brown @*/
46725ef26d82SJed Brown PetscErrorCode TSGetKSPIterations(TS ts,PetscInt *lits)
46739f67acb7SJed Brown {
46749f67acb7SJed Brown   PetscFunctionBegin;
46759f67acb7SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
46769f67acb7SJed Brown   PetscValidIntPointer(lits,2);
46775ef26d82SJed Brown   *lits = ts->ksp_its;
46789f67acb7SJed Brown   PetscFunctionReturn(0);
46799f67acb7SJed Brown }
46809f67acb7SJed Brown 
4681cef5090cSJed Brown /*@
4682cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4683cef5090cSJed Brown 
4684cef5090cSJed Brown    Not Collective
4685cef5090cSJed Brown 
4686cef5090cSJed Brown    Input Parameter:
4687cef5090cSJed Brown .  ts - TS context
4688cef5090cSJed Brown 
4689cef5090cSJed Brown    Output Parameter:
4690cef5090cSJed Brown .  rejects - number of steps rejected
4691cef5090cSJed Brown 
4692cef5090cSJed Brown    Notes:
4693cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4694cef5090cSJed Brown 
4695cef5090cSJed Brown    Level: intermediate
4696cef5090cSJed Brown 
4697db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4698cef5090cSJed Brown @*/
4699cef5090cSJed Brown PetscErrorCode TSGetStepRejections(TS ts,PetscInt *rejects)
4700cef5090cSJed Brown {
4701cef5090cSJed Brown   PetscFunctionBegin;
4702cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4703cef5090cSJed Brown   PetscValidIntPointer(rejects,2);
4704cef5090cSJed Brown   *rejects = ts->reject;
4705cef5090cSJed Brown   PetscFunctionReturn(0);
4706cef5090cSJed Brown }
4707cef5090cSJed Brown 
4708cef5090cSJed Brown /*@
4709cef5090cSJed Brown    TSGetSNESFailures - Gets the total number of failed SNES solves
4710cef5090cSJed Brown 
4711cef5090cSJed Brown    Not Collective
4712cef5090cSJed Brown 
4713cef5090cSJed Brown    Input Parameter:
4714cef5090cSJed Brown .  ts - TS context
4715cef5090cSJed Brown 
4716cef5090cSJed Brown    Output Parameter:
4717cef5090cSJed Brown .  fails - number of failed nonlinear solves
4718cef5090cSJed Brown 
4719cef5090cSJed Brown    Notes:
4720cef5090cSJed Brown    This counter is reset to zero for each successive call to TSSolve().
4721cef5090cSJed Brown 
4722cef5090cSJed Brown    Level: intermediate
4723cef5090cSJed Brown 
4724db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4725cef5090cSJed Brown @*/
4726cef5090cSJed Brown PetscErrorCode TSGetSNESFailures(TS ts,PetscInt *fails)
4727cef5090cSJed Brown {
4728cef5090cSJed Brown   PetscFunctionBegin;
4729cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4730cef5090cSJed Brown   PetscValidIntPointer(fails,2);
4731cef5090cSJed Brown   *fails = ts->num_snes_failures;
4732cef5090cSJed Brown   PetscFunctionReturn(0);
4733cef5090cSJed Brown }
4734cef5090cSJed Brown 
4735cef5090cSJed Brown /*@
4736cef5090cSJed Brown    TSSetMaxStepRejections - Sets the maximum number of step rejections before a step fails
4737cef5090cSJed Brown 
4738cef5090cSJed Brown    Not Collective
4739cef5090cSJed Brown 
4740d8d19677SJose E. Roman    Input Parameters:
4741cef5090cSJed Brown +  ts - TS context
4742cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4743cef5090cSJed Brown 
4744cef5090cSJed Brown    Notes:
4745cef5090cSJed Brown    The counter is reset to zero for each step
4746cef5090cSJed Brown 
4747cef5090cSJed Brown    Options Database Key:
4748cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4749cef5090cSJed Brown 
4750cef5090cSJed Brown    Level: intermediate
4751cef5090cSJed Brown 
4752db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4753cef5090cSJed Brown @*/
4754cef5090cSJed Brown PetscErrorCode TSSetMaxStepRejections(TS ts,PetscInt rejects)
4755cef5090cSJed Brown {
4756cef5090cSJed Brown   PetscFunctionBegin;
4757cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4758cef5090cSJed Brown   ts->max_reject = rejects;
4759cef5090cSJed Brown   PetscFunctionReturn(0);
4760cef5090cSJed Brown }
4761cef5090cSJed Brown 
4762cef5090cSJed Brown /*@
4763cef5090cSJed Brown    TSSetMaxSNESFailures - Sets the maximum number of failed SNES solves
4764cef5090cSJed Brown 
4765cef5090cSJed Brown    Not Collective
4766cef5090cSJed Brown 
4767d8d19677SJose E. Roman    Input Parameters:
4768cef5090cSJed Brown +  ts - TS context
4769cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4770cef5090cSJed Brown 
4771cef5090cSJed Brown    Notes:
4772cef5090cSJed Brown    The counter is reset to zero for each successive call to TSSolve().
4773cef5090cSJed Brown 
4774cef5090cSJed Brown    Options Database Key:
4775cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4776cef5090cSJed Brown 
4777cef5090cSJed Brown    Level: intermediate
4778cef5090cSJed Brown 
4779db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4780cef5090cSJed Brown @*/
4781cef5090cSJed Brown PetscErrorCode TSSetMaxSNESFailures(TS ts,PetscInt fails)
4782cef5090cSJed Brown {
4783cef5090cSJed Brown   PetscFunctionBegin;
4784cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4785cef5090cSJed Brown   ts->max_snes_failures = fails;
4786cef5090cSJed Brown   PetscFunctionReturn(0);
4787cef5090cSJed Brown }
4788cef5090cSJed Brown 
4789cef5090cSJed Brown /*@
4790cef5090cSJed Brown    TSSetErrorIfStepFails - Error if no step succeeds
4791cef5090cSJed Brown 
4792cef5090cSJed Brown    Not Collective
4793cef5090cSJed Brown 
4794d8d19677SJose E. Roman    Input Parameters:
4795cef5090cSJed Brown +  ts - TS context
4796cef5090cSJed Brown -  err - PETSC_TRUE to error if no step succeeds, PETSC_FALSE to return without failure
4797cef5090cSJed Brown 
4798cef5090cSJed Brown    Options Database Key:
4799cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4800cef5090cSJed Brown 
4801cef5090cSJed Brown    Level: intermediate
4802cef5090cSJed Brown 
4803db781477SPatrick Sanan .seealso: `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4804cef5090cSJed Brown @*/
4805cef5090cSJed Brown PetscErrorCode TSSetErrorIfStepFails(TS ts,PetscBool err)
4806cef5090cSJed Brown {
4807cef5090cSJed Brown   PetscFunctionBegin;
4808cef5090cSJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4809cef5090cSJed Brown   ts->errorifstepfailed = err;
4810cef5090cSJed Brown   PetscFunctionReturn(0);
4811cef5090cSJed Brown }
4812cef5090cSJed Brown 
481384df9cb4SJed Brown /*@
4814552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
481584df9cb4SJed Brown 
4816ed81e22dSJed Brown    Collective on TS if controller has not been created yet
481784df9cb4SJed Brown 
48184165533cSJose E. Roman    Input Parameter:
4819ed81e22dSJed Brown .  ts - time stepping context
482084df9cb4SJed Brown 
48214165533cSJose E. Roman    Output Parameter:
4822ed81e22dSJed Brown .  adapt - adaptive controller
482384df9cb4SJed Brown 
482484df9cb4SJed Brown    Level: intermediate
482584df9cb4SJed Brown 
4826db781477SPatrick Sanan .seealso: `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
482784df9cb4SJed Brown @*/
4828552698daSJed Brown PetscErrorCode TSGetAdapt(TS ts,TSAdapt *adapt)
482984df9cb4SJed Brown {
483084df9cb4SJed Brown   PetscFunctionBegin;
483184df9cb4SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4832bec58848SLisandro Dalcin   PetscValidPointer(adapt,2);
483384df9cb4SJed Brown   if (!ts->adapt) {
48349566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts),&ts->adapt));
48359566063dSJacob Faibussowitsch     PetscCall(PetscLogObjectParent((PetscObject)ts,(PetscObject)ts->adapt));
48369566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt,(PetscObject)ts,1));
483784df9cb4SJed Brown   }
4838bec58848SLisandro Dalcin   *adapt = ts->adapt;
483984df9cb4SJed Brown   PetscFunctionReturn(0);
484084df9cb4SJed Brown }
4841d6ebe24aSShri Abhyankar 
48421c3436cfSJed Brown /*@
48431c3436cfSJed Brown    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
48441c3436cfSJed Brown 
48451c3436cfSJed Brown    Logically Collective
48461c3436cfSJed Brown 
48474165533cSJose E. Roman    Input Parameters:
48481c3436cfSJed Brown +  ts - time integration context
48491c3436cfSJed Brown .  atol - scalar absolute tolerances, PETSC_DECIDE to leave current value
48500298fd71SBarry Smith .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
48511c3436cfSJed Brown .  rtol - scalar relative tolerances, PETSC_DECIDE to leave current value
48520298fd71SBarry Smith -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
48531c3436cfSJed Brown 
4854a3cdaa26SBarry Smith    Options Database keys:
4855a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
485667b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4857a3cdaa26SBarry Smith 
48583ff766beSShri Abhyankar    Notes:
48593ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
48603ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
48613ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
48623ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
48633ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
48643ff766beSShri Abhyankar    differential variables.
48653ff766beSShri Abhyankar 
48661c3436cfSJed Brown    Level: beginner
48671c3436cfSJed Brown 
4868db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
48691c3436cfSJed Brown @*/
48701c3436cfSJed Brown PetscErrorCode TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)
48711c3436cfSJed Brown {
48721c3436cfSJed Brown   PetscFunctionBegin;
4873c5033834SJed Brown   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
48741c3436cfSJed Brown   if (vatol) {
48759566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
48769566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
48771c3436cfSJed Brown     ts->vatol = vatol;
48781c3436cfSJed Brown   }
4879c5033834SJed Brown   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
48801c3436cfSJed Brown   if (vrtol) {
48819566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
48829566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
48831c3436cfSJed Brown     ts->vrtol = vrtol;
48841c3436cfSJed Brown   }
48851c3436cfSJed Brown   PetscFunctionReturn(0);
48861c3436cfSJed Brown }
48871c3436cfSJed Brown 
4888c5033834SJed Brown /*@
4889c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4890c5033834SJed Brown 
4891c5033834SJed Brown    Logically Collective
4892c5033834SJed Brown 
48934165533cSJose E. Roman    Input Parameter:
4894c5033834SJed Brown .  ts - time integration context
4895c5033834SJed Brown 
48964165533cSJose E. Roman    Output Parameters:
48970298fd71SBarry Smith +  atol - scalar absolute tolerances, NULL to ignore
48980298fd71SBarry Smith .  vatol - vector of absolute tolerances, NULL to ignore
48990298fd71SBarry Smith .  rtol - scalar relative tolerances, NULL to ignore
49000298fd71SBarry Smith -  vrtol - vector of relative tolerances, NULL to ignore
4901c5033834SJed Brown 
4902c5033834SJed Brown    Level: beginner
4903c5033834SJed Brown 
4904db781477SPatrick Sanan .seealso: `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4905c5033834SJed Brown @*/
4906c5033834SJed Brown PetscErrorCode TSGetTolerances(TS ts,PetscReal *atol,Vec *vatol,PetscReal *rtol,Vec *vrtol)
4907c5033834SJed Brown {
4908c5033834SJed Brown   PetscFunctionBegin;
4909c5033834SJed Brown   if (atol)  *atol  = ts->atol;
4910c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4911c5033834SJed Brown   if (rtol)  *rtol  = ts->rtol;
4912c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
4913c5033834SJed Brown   PetscFunctionReturn(0);
4914c5033834SJed Brown }
4915c5033834SJed Brown 
49169c6b16b5SShri Abhyankar /*@
4917a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
49189c6b16b5SShri Abhyankar 
49199c6b16b5SShri Abhyankar    Collective on TS
49209c6b16b5SShri Abhyankar 
49214165533cSJose E. Roman    Input Parameters:
49229c6b16b5SShri Abhyankar +  ts - time stepping context
4923a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4924a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
49259c6b16b5SShri Abhyankar 
49264165533cSJose E. Roman    Output Parameters:
4927a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
49287453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4929a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
49309c6b16b5SShri Abhyankar 
49319c6b16b5SShri Abhyankar    Level: developer
49329c6b16b5SShri Abhyankar 
4933db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
49349c6b16b5SShri Abhyankar @*/
49357453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNorm2(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
49369c6b16b5SShri Abhyankar {
49379c6b16b5SShri Abhyankar   PetscInt          i,n,N,rstart;
49387453f775SEmil Constantinescu   PetscInt          n_loc,na_loc,nr_loc;
49397453f775SEmil Constantinescu   PetscReal         n_glb,na_glb,nr_glb;
49409c6b16b5SShri Abhyankar   const PetscScalar *u,*y;
49417453f775SEmil Constantinescu   PetscReal         sum,suma,sumr,gsum,gsuma,gsumr,diff;
49427453f775SEmil Constantinescu   PetscReal         tol,tola,tolr;
49437453f775SEmil Constantinescu   PetscReal         err_loc[6],err_glb[6];
49449c6b16b5SShri Abhyankar 
49459c6b16b5SShri Abhyankar   PetscFunctionBegin;
49469c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
4947a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
4948a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
4949a4868fbcSLisandro Dalcin   PetscValidType(U,2);
4950a4868fbcSLisandro Dalcin   PetscValidType(Y,3);
4951a4868fbcSLisandro Dalcin   PetscCheckSameComm(U,2,Y,3);
4952dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,4);
4953dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,5);
4954dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,6);
49553c633725SBarry Smith   PetscCheck(U != Y,PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
49569c6b16b5SShri Abhyankar 
49579566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U,&N));
49589566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U,&n));
49599566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U,&rstart,NULL));
49609566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
49619566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
49627453f775SEmil Constantinescu   sum  = 0.; n_loc  = 0;
49637453f775SEmil Constantinescu   suma = 0.; na_loc = 0;
49647453f775SEmil Constantinescu   sumr = 0.; nr_loc = 0;
49659c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
49669c6b16b5SShri Abhyankar     const PetscScalar *atol,*rtol;
49679566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
49689566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
49699c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
497076cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
49717453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49727453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49737453f775SEmil Constantinescu       if (tola>0.) {
49747453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
49757453f775SEmil Constantinescu         na_loc++;
49767453f775SEmil Constantinescu       }
49777453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
49787453f775SEmil Constantinescu       if (tolr>0.) {
49797453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
49807453f775SEmil Constantinescu         nr_loc++;
49817453f775SEmil Constantinescu       }
49827453f775SEmil Constantinescu       tol=tola+tolr;
49837453f775SEmil Constantinescu       if (tol>0.) {
49847453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
49857453f775SEmil Constantinescu         n_loc++;
49867453f775SEmil Constantinescu       }
49879c6b16b5SShri Abhyankar     }
49889566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
49899566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
49909c6b16b5SShri Abhyankar   } else if (ts->vatol) {       /* vector atol, scalar rtol */
49919c6b16b5SShri Abhyankar     const PetscScalar *atol;
49929566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
49939c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
499476cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
49957453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49967453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
49977453f775SEmil Constantinescu       if (tola>0.) {
49987453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
49997453f775SEmil Constantinescu         na_loc++;
50007453f775SEmil Constantinescu       }
50017453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50027453f775SEmil Constantinescu       if (tolr>0.) {
50037453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
50047453f775SEmil Constantinescu         nr_loc++;
50057453f775SEmil Constantinescu       }
50067453f775SEmil Constantinescu       tol=tola+tolr;
50077453f775SEmil Constantinescu       if (tol>0.) {
50087453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
50097453f775SEmil Constantinescu         n_loc++;
50107453f775SEmil Constantinescu       }
50119c6b16b5SShri Abhyankar     }
50129566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
50139c6b16b5SShri Abhyankar   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
50149c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50159566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
50169c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
501776cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50187453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50197453f775SEmil Constantinescu       tola = ts->atol;
50207453f775SEmil Constantinescu       if (tola>0.) {
50217453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
50227453f775SEmil Constantinescu         na_loc++;
50237453f775SEmil Constantinescu       }
50247453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50257453f775SEmil Constantinescu       if (tolr>0.) {
50267453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
50277453f775SEmil Constantinescu         nr_loc++;
50287453f775SEmil Constantinescu       }
50297453f775SEmil Constantinescu       tol=tola+tolr;
50307453f775SEmil Constantinescu       if (tol>0.) {
50317453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
50327453f775SEmil Constantinescu         n_loc++;
50337453f775SEmil Constantinescu       }
50349c6b16b5SShri Abhyankar     }
50359566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
50369c6b16b5SShri Abhyankar   } else {                      /* scalar atol, scalar rtol */
50379c6b16b5SShri Abhyankar     for (i=0; i<n; i++) {
503876cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
50397453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50407453f775SEmil Constantinescu       tola = ts->atol;
50417453f775SEmil Constantinescu       if (tola>0.) {
50427453f775SEmil Constantinescu         suma  += PetscSqr(diff/tola);
50437453f775SEmil Constantinescu         na_loc++;
50447453f775SEmil Constantinescu       }
50457453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
50467453f775SEmil Constantinescu       if (tolr>0.) {
50477453f775SEmil Constantinescu         sumr  += PetscSqr(diff/tolr);
50487453f775SEmil Constantinescu         nr_loc++;
50497453f775SEmil Constantinescu       }
50507453f775SEmil Constantinescu       tol=tola+tolr;
50517453f775SEmil Constantinescu       if (tol>0.) {
50527453f775SEmil Constantinescu         sum  += PetscSqr(diff/tol);
50537453f775SEmil Constantinescu         n_loc++;
50547453f775SEmil Constantinescu       }
50559c6b16b5SShri Abhyankar     }
50569c6b16b5SShri Abhyankar   }
50579566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
50589566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
50599c6b16b5SShri Abhyankar 
50607453f775SEmil Constantinescu   err_loc[0] = sum;
50617453f775SEmil Constantinescu   err_loc[1] = suma;
50627453f775SEmil Constantinescu   err_loc[2] = sumr;
50637453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
50647453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
50657453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
50667453f775SEmil Constantinescu 
50671c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts)));
50687453f775SEmil Constantinescu 
50697453f775SEmil Constantinescu   gsum   = err_glb[0];
50707453f775SEmil Constantinescu   gsuma  = err_glb[1];
50717453f775SEmil Constantinescu   gsumr  = err_glb[2];
50727453f775SEmil Constantinescu   n_glb  = err_glb[3];
50737453f775SEmil Constantinescu   na_glb = err_glb[4];
50747453f775SEmil Constantinescu   nr_glb = err_glb[5];
50757453f775SEmil Constantinescu 
5076b1316ef9SEmil Constantinescu   *norm  = 0.;
5077b1316ef9SEmil Constantinescu   if (n_glb>0.) {*norm  = PetscSqrtReal(gsum  / n_glb);}
5078b1316ef9SEmil Constantinescu   *norma = 0.;
5079b1316ef9SEmil Constantinescu   if (na_glb>0.) {*norma = PetscSqrtReal(gsuma / na_glb);}
5080b1316ef9SEmil Constantinescu   *normr = 0.;
5081b1316ef9SEmil Constantinescu   if (nr_glb>0.) {*normr = PetscSqrtReal(gsumr / nr_glb);}
50829c6b16b5SShri Abhyankar 
50833c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
50843c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
50853c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
50869c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
50879c6b16b5SShri Abhyankar }
50889c6b16b5SShri Abhyankar 
50899c6b16b5SShri Abhyankar /*@
5090a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
50919c6b16b5SShri Abhyankar 
50929c6b16b5SShri Abhyankar    Collective on TS
50939c6b16b5SShri Abhyankar 
50944165533cSJose E. Roman    Input Parameters:
50959c6b16b5SShri Abhyankar +  ts - time stepping context
5096a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5097a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
50989c6b16b5SShri Abhyankar 
50994165533cSJose E. Roman    Output Parameters:
5100a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51017453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5102a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51039c6b16b5SShri Abhyankar 
51049c6b16b5SShri Abhyankar    Level: developer
51059c6b16b5SShri Abhyankar 
5106db781477SPatrick Sanan .seealso: `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
51079c6b16b5SShri Abhyankar @*/
51087453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNormInfinity(TS ts,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
51099c6b16b5SShri Abhyankar {
51107453f775SEmil Constantinescu   PetscInt          i,n,N,rstart;
51119c6b16b5SShri Abhyankar   const PetscScalar *u,*y;
51127453f775SEmil Constantinescu   PetscReal         max,gmax,maxa,gmaxa,maxr,gmaxr;
51137453f775SEmil Constantinescu   PetscReal         tol,tola,tolr,diff;
51147453f775SEmil Constantinescu   PetscReal         err_loc[3],err_glb[3];
51159c6b16b5SShri Abhyankar 
51169c6b16b5SShri Abhyankar   PetscFunctionBegin;
51179c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5118a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U,VEC_CLASSID,2);
5119a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y,VEC_CLASSID,3);
5120a4868fbcSLisandro Dalcin   PetscValidType(U,2);
5121a4868fbcSLisandro Dalcin   PetscValidType(Y,3);
5122a4868fbcSLisandro Dalcin   PetscCheckSameComm(U,2,Y,3);
5123dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,4);
5124dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,5);
5125dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,6);
51263c633725SBarry Smith   PetscCheck(U != Y,PetscObjectComm((PetscObject)U),PETSC_ERR_ARG_IDN,"U and Y cannot be the same vector");
51279c6b16b5SShri Abhyankar 
51289566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U,&N));
51299566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U,&n));
51309566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U,&rstart,NULL));
51319566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
51329566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
51337453f775SEmil Constantinescu 
51347453f775SEmil Constantinescu   max=0.;
51357453f775SEmil Constantinescu   maxa=0.;
51367453f775SEmil Constantinescu   maxr=0.;
51377453f775SEmil Constantinescu 
51387453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
51399c6b16b5SShri Abhyankar     const PetscScalar *atol,*rtol;
51409566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
51419566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
51427453f775SEmil Constantinescu 
51437453f775SEmil Constantinescu     for (i=0; i<n; i++) {
514476cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
51457453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51467453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
51477453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
51487453f775SEmil Constantinescu       tol  = tola+tolr;
51497453f775SEmil Constantinescu       if (tola>0.) {
51507453f775SEmil Constantinescu         maxa = PetscMax(maxa,diff / tola);
51517453f775SEmil Constantinescu       }
51527453f775SEmil Constantinescu       if (tolr>0.) {
51537453f775SEmil Constantinescu         maxr = PetscMax(maxr,diff / tolr);
51547453f775SEmil Constantinescu       }
51557453f775SEmil Constantinescu       if (tol>0.) {
51567453f775SEmil Constantinescu         max = PetscMax(max,diff / tol);
51577453f775SEmil Constantinescu       }
51589c6b16b5SShri Abhyankar     }
51599566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
51609566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
51619c6b16b5SShri Abhyankar   } else if (ts->vatol) {       /* vector atol, scalar rtol */
51629c6b16b5SShri Abhyankar     const PetscScalar *atol;
51639566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
51647453f775SEmil Constantinescu     for (i=0; i<n; i++) {
516576cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
51667453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51677453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
51687453f775SEmil Constantinescu       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
51697453f775SEmil Constantinescu       tol  = tola+tolr;
51707453f775SEmil Constantinescu       if (tola>0.) {
51717453f775SEmil Constantinescu         maxa = PetscMax(maxa,diff / tola);
51727453f775SEmil Constantinescu       }
51737453f775SEmil Constantinescu       if (tolr>0.) {
51747453f775SEmil Constantinescu         maxr = PetscMax(maxr,diff / tolr);
51757453f775SEmil Constantinescu       }
51767453f775SEmil Constantinescu       if (tol>0.) {
51777453f775SEmil Constantinescu         max = PetscMax(max,diff / tol);
51787453f775SEmil Constantinescu       }
51799c6b16b5SShri Abhyankar     }
51809566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
51819c6b16b5SShri Abhyankar   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
51829c6b16b5SShri Abhyankar     const PetscScalar *rtol;
51839566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
51847453f775SEmil Constantinescu 
51857453f775SEmil Constantinescu     for (i=0; i<n; i++) {
518676cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
51877453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
51887453f775SEmil Constantinescu       tola = ts->atol;
51897453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
51907453f775SEmil Constantinescu       tol  = tola+tolr;
51917453f775SEmil Constantinescu       if (tola>0.) {
51927453f775SEmil Constantinescu         maxa = PetscMax(maxa,diff / tola);
51937453f775SEmil Constantinescu       }
51947453f775SEmil Constantinescu       if (tolr>0.) {
51957453f775SEmil Constantinescu         maxr = PetscMax(maxr,diff / tolr);
51967453f775SEmil Constantinescu       }
51977453f775SEmil Constantinescu       if (tol>0.) {
51987453f775SEmil Constantinescu         max = PetscMax(max,diff / tol);
51997453f775SEmil Constantinescu       }
52009c6b16b5SShri Abhyankar     }
52019566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
52029c6b16b5SShri Abhyankar   } else {                      /* scalar atol, scalar rtol */
52037453f775SEmil Constantinescu 
52047453f775SEmil Constantinescu     for (i=0; i<n; i++) {
520576cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
52067453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
52077453f775SEmil Constantinescu       tola = ts->atol;
52087453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
52097453f775SEmil Constantinescu       tol  = tola+tolr;
52107453f775SEmil Constantinescu       if (tola>0.) {
52117453f775SEmil Constantinescu         maxa = PetscMax(maxa,diff / tola);
52127453f775SEmil Constantinescu       }
52137453f775SEmil Constantinescu       if (tolr>0.) {
52147453f775SEmil Constantinescu         maxr = PetscMax(maxr,diff / tolr);
52157453f775SEmil Constantinescu       }
52167453f775SEmil Constantinescu       if (tol>0.) {
52177453f775SEmil Constantinescu         max = PetscMax(max,diff / tol);
52187453f775SEmil Constantinescu       }
52199c6b16b5SShri Abhyankar     }
52209c6b16b5SShri Abhyankar   }
52219566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
52229566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
52237453f775SEmil Constantinescu   err_loc[0] = max;
52247453f775SEmil Constantinescu   err_loc[1] = maxa;
52257453f775SEmil Constantinescu   err_loc[2] = maxr;
52261c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
52277453f775SEmil Constantinescu   gmax   = err_glb[0];
52287453f775SEmil Constantinescu   gmaxa  = err_glb[1];
52297453f775SEmil Constantinescu   gmaxr  = err_glb[2];
52309c6b16b5SShri Abhyankar 
52319c6b16b5SShri Abhyankar   *norm = gmax;
52327453f775SEmil Constantinescu   *norma = gmaxa;
52337453f775SEmil Constantinescu   *normr = gmaxr;
52343c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
52353c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
52363c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
52379c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
52389c6b16b5SShri Abhyankar }
52399c6b16b5SShri Abhyankar 
52401c3436cfSJed Brown /*@
52418a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
52421c3436cfSJed Brown 
52431c3436cfSJed Brown    Collective on TS
52441c3436cfSJed Brown 
52454165533cSJose E. Roman    Input Parameters:
52461c3436cfSJed Brown +  ts - time stepping context
5247a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5248a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5249a4868fbcSLisandro Dalcin -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
52507619abb3SShri 
52514165533cSJose E. Roman    Output Parameters:
5252a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52538a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5254a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5255a4868fbcSLisandro Dalcin 
5256a4868fbcSLisandro Dalcin    Options Database Keys:
5257a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5258a4868fbcSLisandro Dalcin 
52591c3436cfSJed Brown    Level: developer
52601c3436cfSJed Brown 
5261db781477SPatrick Sanan .seealso: `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
52621c3436cfSJed Brown @*/
52637453f775SEmil Constantinescu PetscErrorCode TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
52641c3436cfSJed Brown {
52651c3436cfSJed Brown   PetscFunctionBegin;
5266a4868fbcSLisandro Dalcin   if (wnormtype == NORM_2) {
52679566063dSJacob Faibussowitsch     PetscCall(TSErrorWeightedNorm2(ts,U,Y,norm,norma,normr));
5268a4868fbcSLisandro Dalcin   } else if (wnormtype == NORM_INFINITY) {
52699566063dSJacob Faibussowitsch     PetscCall(TSErrorWeightedNormInfinity(ts,U,Y,norm,norma,normr));
527098921bdaSJacob Faibussowitsch   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
52711c3436cfSJed Brown   PetscFunctionReturn(0);
52721c3436cfSJed Brown }
52731c3436cfSJed Brown 
52748a175baeSEmil Constantinescu /*@
52758a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
52768a175baeSEmil Constantinescu 
52778a175baeSEmil Constantinescu    Collective on TS
52788a175baeSEmil Constantinescu 
52794165533cSJose E. Roman    Input Parameters:
52808a175baeSEmil Constantinescu +  ts - time stepping context
52818a175baeSEmil Constantinescu .  E - error vector
52828a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
52838a175baeSEmil Constantinescu -  Y - state vector, previous time step
52848a175baeSEmil Constantinescu 
52854165533cSJose E. Roman    Output Parameters:
5286a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
52878a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5288a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
52898a175baeSEmil Constantinescu 
52908a175baeSEmil Constantinescu    Level: developer
52918a175baeSEmil Constantinescu 
5292db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
52938a175baeSEmil Constantinescu @*/
52948a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENorm2(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
52958a175baeSEmil Constantinescu {
52968a175baeSEmil Constantinescu   PetscInt          i,n,N,rstart;
52978a175baeSEmil Constantinescu   PetscInt          n_loc,na_loc,nr_loc;
52988a175baeSEmil Constantinescu   PetscReal         n_glb,na_glb,nr_glb;
52998a175baeSEmil Constantinescu   const PetscScalar *e,*u,*y;
53008a175baeSEmil Constantinescu   PetscReal         err,sum,suma,sumr,gsum,gsuma,gsumr;
53018a175baeSEmil Constantinescu   PetscReal         tol,tola,tolr;
53028a175baeSEmil Constantinescu   PetscReal         err_loc[6],err_glb[6];
53038a175baeSEmil Constantinescu 
53048a175baeSEmil Constantinescu   PetscFunctionBegin;
53058a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
53068a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
53078a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
53088a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
53098a175baeSEmil Constantinescu   PetscValidType(E,2);
53108a175baeSEmil Constantinescu   PetscValidType(U,3);
53118a175baeSEmil Constantinescu   PetscValidType(Y,4);
53128a175baeSEmil Constantinescu   PetscCheckSameComm(E,2,U,3);
5313064a246eSJacob Faibussowitsch   PetscCheckSameComm(U,3,Y,4);
5314dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,5);
5315dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,6);
5316dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,7);
53178a175baeSEmil Constantinescu 
53189566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E,&N));
53199566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E,&n));
53209566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E,&rstart,NULL));
53219566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E,&e));
53229566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
53239566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
53248a175baeSEmil Constantinescu   sum  = 0.; n_loc  = 0;
53258a175baeSEmil Constantinescu   suma = 0.; na_loc = 0;
53268a175baeSEmil Constantinescu   sumr = 0.; nr_loc = 0;
53278a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
53288a175baeSEmil Constantinescu     const PetscScalar *atol,*rtol;
53299566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
53309566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
53318a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
533276cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
53338a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
53348a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
53358a175baeSEmil Constantinescu       if (tola>0.) {
53368a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
53378a175baeSEmil Constantinescu         na_loc++;
53388a175baeSEmil Constantinescu       }
53398a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
53408a175baeSEmil Constantinescu       if (tolr>0.) {
53418a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
53428a175baeSEmil Constantinescu         nr_loc++;
53438a175baeSEmil Constantinescu       }
53448a175baeSEmil Constantinescu       tol=tola+tolr;
53458a175baeSEmil Constantinescu       if (tol>0.) {
53468a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
53478a175baeSEmil Constantinescu         n_loc++;
53488a175baeSEmil Constantinescu       }
53498a175baeSEmil Constantinescu     }
53509566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
53519566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
53528a175baeSEmil Constantinescu   } else if (ts->vatol) {       /* vector atol, scalar rtol */
53538a175baeSEmil Constantinescu     const PetscScalar *atol;
53549566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
53558a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
535676cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
53578a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
53588a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
53598a175baeSEmil Constantinescu       if (tola>0.) {
53608a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
53618a175baeSEmil Constantinescu         na_loc++;
53628a175baeSEmil Constantinescu       }
53638a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
53648a175baeSEmil Constantinescu       if (tolr>0.) {
53658a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
53668a175baeSEmil Constantinescu         nr_loc++;
53678a175baeSEmil Constantinescu       }
53688a175baeSEmil Constantinescu       tol=tola+tolr;
53698a175baeSEmil Constantinescu       if (tol>0.) {
53708a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
53718a175baeSEmil Constantinescu         n_loc++;
53728a175baeSEmil Constantinescu       }
53738a175baeSEmil Constantinescu     }
53749566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
53758a175baeSEmil Constantinescu   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
53768a175baeSEmil Constantinescu     const PetscScalar *rtol;
53779566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
53788a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
537976cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
53808a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
53818a175baeSEmil Constantinescu       tola = ts->atol;
53828a175baeSEmil Constantinescu       if (tola>0.) {
53838a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
53848a175baeSEmil Constantinescu         na_loc++;
53858a175baeSEmil Constantinescu       }
53868a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
53878a175baeSEmil Constantinescu       if (tolr>0.) {
53888a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
53898a175baeSEmil Constantinescu         nr_loc++;
53908a175baeSEmil Constantinescu       }
53918a175baeSEmil Constantinescu       tol=tola+tolr;
53928a175baeSEmil Constantinescu       if (tol>0.) {
53938a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
53948a175baeSEmil Constantinescu         n_loc++;
53958a175baeSEmil Constantinescu       }
53968a175baeSEmil Constantinescu     }
53979566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
53988a175baeSEmil Constantinescu   } else {                      /* scalar atol, scalar rtol */
53998a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
540076cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
54018a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
54028a175baeSEmil Constantinescu       tola = ts->atol;
54038a175baeSEmil Constantinescu       if (tola>0.) {
54048a175baeSEmil Constantinescu         suma  += PetscSqr(err/tola);
54058a175baeSEmil Constantinescu         na_loc++;
54068a175baeSEmil Constantinescu       }
54078a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
54088a175baeSEmil Constantinescu       if (tolr>0.) {
54098a175baeSEmil Constantinescu         sumr  += PetscSqr(err/tolr);
54108a175baeSEmil Constantinescu         nr_loc++;
54118a175baeSEmil Constantinescu       }
54128a175baeSEmil Constantinescu       tol=tola+tolr;
54138a175baeSEmil Constantinescu       if (tol>0.) {
54148a175baeSEmil Constantinescu         sum  += PetscSqr(err/tol);
54158a175baeSEmil Constantinescu         n_loc++;
54168a175baeSEmil Constantinescu       }
54178a175baeSEmil Constantinescu     }
54188a175baeSEmil Constantinescu   }
54199566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E,&e));
54209566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
54219566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
54228a175baeSEmil Constantinescu 
54238a175baeSEmil Constantinescu   err_loc[0] = sum;
54248a175baeSEmil Constantinescu   err_loc[1] = suma;
54258a175baeSEmil Constantinescu   err_loc[2] = sumr;
54268a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
54278a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
54288a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
54298a175baeSEmil Constantinescu 
54301c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,6,MPIU_REAL,MPIU_SUM,PetscObjectComm((PetscObject)ts)));
54318a175baeSEmil Constantinescu 
54328a175baeSEmil Constantinescu   gsum   = err_glb[0];
54338a175baeSEmil Constantinescu   gsuma  = err_glb[1];
54348a175baeSEmil Constantinescu   gsumr  = err_glb[2];
54358a175baeSEmil Constantinescu   n_glb  = err_glb[3];
54368a175baeSEmil Constantinescu   na_glb = err_glb[4];
54378a175baeSEmil Constantinescu   nr_glb = err_glb[5];
54388a175baeSEmil Constantinescu 
54398a175baeSEmil Constantinescu   *norm  = 0.;
54408a175baeSEmil Constantinescu   if (n_glb>0.) {*norm  = PetscSqrtReal(gsum  / n_glb);}
54418a175baeSEmil Constantinescu   *norma = 0.;
54428a175baeSEmil Constantinescu   if (na_glb>0.) {*norma = PetscSqrtReal(gsuma / na_glb);}
54438a175baeSEmil Constantinescu   *normr = 0.;
54448a175baeSEmil Constantinescu   if (nr_glb>0.) {*normr = PetscSqrtReal(gsumr / nr_glb);}
54458a175baeSEmil Constantinescu 
54463c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
54473c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
54483c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
54498a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54508a175baeSEmil Constantinescu }
54518a175baeSEmil Constantinescu 
54528a175baeSEmil Constantinescu /*@
54538a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
54548a175baeSEmil Constantinescu    Collective on TS
54558a175baeSEmil Constantinescu 
54564165533cSJose E. Roman    Input Parameters:
54578a175baeSEmil Constantinescu +  ts - time stepping context
54588a175baeSEmil Constantinescu .  E - error vector
54598a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54608a175baeSEmil Constantinescu -  Y - state vector, previous time step
54618a175baeSEmil Constantinescu 
54624165533cSJose E. Roman    Output Parameters:
5463a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
54648a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5465a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
54668a175baeSEmil Constantinescu 
54678a175baeSEmil Constantinescu    Level: developer
54688a175baeSEmil Constantinescu 
5469db781477SPatrick Sanan .seealso: `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
54708a175baeSEmil Constantinescu @*/
54718a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENormInfinity(TS ts,Vec E,Vec U,Vec Y,PetscReal *norm,PetscReal *norma,PetscReal *normr)
54728a175baeSEmil Constantinescu {
54738a175baeSEmil Constantinescu   PetscInt          i,n,N,rstart;
54748a175baeSEmil Constantinescu   const PetscScalar *e,*u,*y;
54758a175baeSEmil Constantinescu   PetscReal         err,max,gmax,maxa,gmaxa,maxr,gmaxr;
54768a175baeSEmil Constantinescu   PetscReal         tol,tola,tolr;
54778a175baeSEmil Constantinescu   PetscReal         err_loc[3],err_glb[3];
54788a175baeSEmil Constantinescu 
54798a175baeSEmil Constantinescu   PetscFunctionBegin;
54808a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
54818a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E,VEC_CLASSID,2);
54828a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U,VEC_CLASSID,3);
54838a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y,VEC_CLASSID,4);
54848a175baeSEmil Constantinescu   PetscValidType(E,2);
54858a175baeSEmil Constantinescu   PetscValidType(U,3);
54868a175baeSEmil Constantinescu   PetscValidType(Y,4);
54878a175baeSEmil Constantinescu   PetscCheckSameComm(E,2,U,3);
5488064a246eSJacob Faibussowitsch   PetscCheckSameComm(U,3,Y,4);
5489dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm,5);
5490dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma,6);
5491dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr,7);
54928a175baeSEmil Constantinescu 
54939566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E,&N));
54949566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E,&n));
54959566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E,&rstart,NULL));
54969566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E,&e));
54979566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U,&u));
54989566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y,&y));
54998a175baeSEmil Constantinescu 
55008a175baeSEmil Constantinescu   max=0.;
55018a175baeSEmil Constantinescu   maxa=0.;
55028a175baeSEmil Constantinescu   maxr=0.;
55038a175baeSEmil Constantinescu 
55048a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {     /* vector atol, vector rtol */
55058a175baeSEmil Constantinescu     const PetscScalar *atol,*rtol;
55069566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
55079566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
55088a175baeSEmil Constantinescu 
55098a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
551076cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
55118a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
55128a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
55138a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
55148a175baeSEmil Constantinescu       tol  = tola+tolr;
55158a175baeSEmil Constantinescu       if (tola>0.) {
55168a175baeSEmil Constantinescu         maxa = PetscMax(maxa,err / tola);
55178a175baeSEmil Constantinescu       }
55188a175baeSEmil Constantinescu       if (tolr>0.) {
55198a175baeSEmil Constantinescu         maxr = PetscMax(maxr,err / tolr);
55208a175baeSEmil Constantinescu       }
55218a175baeSEmil Constantinescu       if (tol>0.) {
55228a175baeSEmil Constantinescu         max = PetscMax(max,err / tol);
55238a175baeSEmil Constantinescu       }
55248a175baeSEmil Constantinescu     }
55259566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
55269566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
55278a175baeSEmil Constantinescu   } else if (ts->vatol) {       /* vector atol, scalar rtol */
55288a175baeSEmil Constantinescu     const PetscScalar *atol;
55299566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol,&atol));
55308a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
553176cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
55328a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
55338a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
55348a175baeSEmil Constantinescu       tolr = ts->rtol  * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
55358a175baeSEmil Constantinescu       tol  = tola+tolr;
55368a175baeSEmil Constantinescu       if (tola>0.) {
55378a175baeSEmil Constantinescu         maxa = PetscMax(maxa,err / tola);
55388a175baeSEmil Constantinescu       }
55398a175baeSEmil Constantinescu       if (tolr>0.) {
55408a175baeSEmil Constantinescu         maxr = PetscMax(maxr,err / tolr);
55418a175baeSEmil Constantinescu       }
55428a175baeSEmil Constantinescu       if (tol>0.) {
55438a175baeSEmil Constantinescu         max = PetscMax(max,err / tol);
55448a175baeSEmil Constantinescu       }
55458a175baeSEmil Constantinescu     }
55469566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol,&atol));
55478a175baeSEmil Constantinescu   } else if (ts->vrtol) {       /* scalar atol, vector rtol */
55488a175baeSEmil Constantinescu     const PetscScalar *rtol;
55499566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol,&rtol));
55508a175baeSEmil Constantinescu 
55518a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
555276cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
55538a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
55548a175baeSEmil Constantinescu       tola = ts->atol;
55558a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
55568a175baeSEmil Constantinescu       tol  = tola+tolr;
55578a175baeSEmil Constantinescu       if (tola>0.) {
55588a175baeSEmil Constantinescu         maxa = PetscMax(maxa,err / tola);
55598a175baeSEmil Constantinescu       }
55608a175baeSEmil Constantinescu       if (tolr>0.) {
55618a175baeSEmil Constantinescu         maxr = PetscMax(maxr,err / tolr);
55628a175baeSEmil Constantinescu       }
55638a175baeSEmil Constantinescu       if (tol>0.) {
55648a175baeSEmil Constantinescu         max = PetscMax(max,err / tol);
55658a175baeSEmil Constantinescu       }
55668a175baeSEmil Constantinescu     }
55679566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol,&rtol));
55688a175baeSEmil Constantinescu   } else {                      /* scalar atol, scalar rtol */
55698a175baeSEmil Constantinescu 
55708a175baeSEmil Constantinescu     for (i=0; i<n; i++) {
557176cddca1SEmil Constantinescu       SkipSmallValue(y[i],u[i],ts->adapt->ignore_max);
55728a175baeSEmil Constantinescu       err = PetscAbsScalar(e[i]);
55738a175baeSEmil Constantinescu       tola = ts->atol;
55748a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]),PetscAbsScalar(y[i]));
55758a175baeSEmil Constantinescu       tol  = tola+tolr;
55768a175baeSEmil Constantinescu       if (tola>0.) {
55778a175baeSEmil Constantinescu         maxa = PetscMax(maxa,err / tola);
55788a175baeSEmil Constantinescu       }
55798a175baeSEmil Constantinescu       if (tolr>0.) {
55808a175baeSEmil Constantinescu         maxr = PetscMax(maxr,err / tolr);
55818a175baeSEmil Constantinescu       }
55828a175baeSEmil Constantinescu       if (tol>0.) {
55838a175baeSEmil Constantinescu         max = PetscMax(max,err / tol);
55848a175baeSEmil Constantinescu       }
55858a175baeSEmil Constantinescu     }
55868a175baeSEmil Constantinescu   }
55879566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E,&e));
55889566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U,&u));
55899566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y,&y));
55908a175baeSEmil Constantinescu   err_loc[0] = max;
55918a175baeSEmil Constantinescu   err_loc[1] = maxa;
55928a175baeSEmil Constantinescu   err_loc[2] = maxr;
55931c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc,err_glb,3,MPIU_REAL,MPIU_MAX,PetscObjectComm((PetscObject)ts)));
55948a175baeSEmil Constantinescu   gmax   = err_glb[0];
55958a175baeSEmil Constantinescu   gmaxa  = err_glb[1];
55968a175baeSEmil Constantinescu   gmaxr  = err_glb[2];
55978a175baeSEmil Constantinescu 
55988a175baeSEmil Constantinescu   *norm = gmax;
55998a175baeSEmil Constantinescu   *norma = gmaxa;
56008a175baeSEmil Constantinescu   *normr = gmaxr;
56013c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norm");
56023c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in norma");
56033c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr),PetscObjectComm((PetscObject)ts),PETSC_ERR_FP,"Infinite or not-a-number generated in normr");
56048a175baeSEmil Constantinescu   PetscFunctionReturn(0);
56058a175baeSEmil Constantinescu }
56068a175baeSEmil Constantinescu 
56078a175baeSEmil Constantinescu /*@
56088a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
56098a175baeSEmil Constantinescu 
56108a175baeSEmil Constantinescu    Collective on TS
56118a175baeSEmil Constantinescu 
56124165533cSJose E. Roman    Input Parameters:
56138a175baeSEmil Constantinescu +  ts - time stepping context
56148a175baeSEmil Constantinescu .  E - error vector
56158a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
56168a175baeSEmil Constantinescu .  Y - state vector, previous time step
56178a175baeSEmil Constantinescu -  wnormtype - norm type, either NORM_2 or NORM_INFINITY
56188a175baeSEmil Constantinescu 
56194165533cSJose E. Roman    Output Parameters:
5620a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
56218a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5622a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
56238a175baeSEmil Constantinescu 
56248a175baeSEmil Constantinescu    Options Database Keys:
56258a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
56268a175baeSEmil Constantinescu 
56278a175baeSEmil Constantinescu    Level: developer
56288a175baeSEmil Constantinescu 
5629db781477SPatrick Sanan .seealso: `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
56308a175baeSEmil Constantinescu @*/
56318a175baeSEmil Constantinescu PetscErrorCode TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal *norm,PetscReal *norma,PetscReal *normr)
56328a175baeSEmil Constantinescu {
56338a175baeSEmil Constantinescu   PetscFunctionBegin;
56348a175baeSEmil Constantinescu   if (wnormtype == NORM_2) {
56359566063dSJacob Faibussowitsch     PetscCall(TSErrorWeightedENorm2(ts,E,U,Y,norm,norma,normr));
56368a175baeSEmil Constantinescu   } else if (wnormtype == NORM_INFINITY) {
56379566063dSJacob Faibussowitsch     PetscCall(TSErrorWeightedENormInfinity(ts,E,U,Y,norm,norma,normr));
563898921bdaSJacob Faibussowitsch   } else SETERRQ(PETSC_COMM_SELF,PETSC_ERR_SUP,"No support for norm type %s",NormTypes[wnormtype]);
56398a175baeSEmil Constantinescu   PetscFunctionReturn(0);
56408a175baeSEmil Constantinescu }
56418a175baeSEmil Constantinescu 
56428d59e960SJed Brown /*@
56438d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
56448d59e960SJed Brown 
56458d59e960SJed Brown    Logically Collective on TS
56468d59e960SJed Brown 
56474165533cSJose E. Roman    Input Parameters:
56488d59e960SJed Brown +  ts - time stepping context
56498d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
56508d59e960SJed Brown 
56518d59e960SJed Brown    Note:
56528d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
56538d59e960SJed Brown 
56548d59e960SJed Brown    Level: intermediate
56558d59e960SJed Brown 
5656db781477SPatrick Sanan .seealso: `TSGetCFLTime()`, `TSADAPTCFL`
56578d59e960SJed Brown @*/
56588d59e960SJed Brown PetscErrorCode TSSetCFLTimeLocal(TS ts,PetscReal cfltime)
56598d59e960SJed Brown {
56608d59e960SJed Brown   PetscFunctionBegin;
56618d59e960SJed Brown   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
56628d59e960SJed Brown   ts->cfltime_local = cfltime;
56638d59e960SJed Brown   ts->cfltime       = -1.;
56648d59e960SJed Brown   PetscFunctionReturn(0);
56658d59e960SJed Brown }
56668d59e960SJed Brown 
56678d59e960SJed Brown /*@
56688d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
56698d59e960SJed Brown 
56708d59e960SJed Brown    Collective on TS
56718d59e960SJed Brown 
56724165533cSJose E. Roman    Input Parameter:
56738d59e960SJed Brown .  ts - time stepping context
56748d59e960SJed Brown 
56754165533cSJose E. Roman    Output Parameter:
56768d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
56778d59e960SJed Brown 
56788d59e960SJed Brown    Level: advanced
56798d59e960SJed Brown 
5680db781477SPatrick Sanan .seealso: `TSSetCFLTimeLocal()`
56818d59e960SJed Brown @*/
56828d59e960SJed Brown PetscErrorCode TSGetCFLTime(TS ts,PetscReal *cfltime)
56838d59e960SJed Brown {
56848d59e960SJed Brown   PetscFunctionBegin;
56858d59e960SJed Brown   if (ts->cfltime < 0) {
56861c2dc1cbSBarry Smith     PetscCall(MPIU_Allreduce(&ts->cfltime_local,&ts->cfltime,1,MPIU_REAL,MPIU_MIN,PetscObjectComm((PetscObject)ts)));
56878d59e960SJed Brown   }
56888d59e960SJed Brown   *cfltime = ts->cfltime;
56898d59e960SJed Brown   PetscFunctionReturn(0);
56908d59e960SJed Brown }
56918d59e960SJed Brown 
5692d6ebe24aSShri Abhyankar /*@
5693d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5694d6ebe24aSShri Abhyankar 
5695d6ebe24aSShri Abhyankar    Input Parameters:
5696a2b725a8SWilliam Gropp +  ts   - the TS context.
5697d6ebe24aSShri Abhyankar .  xl   - lower bound.
5698a2b725a8SWilliam Gropp -  xu   - upper bound.
5699d6ebe24aSShri Abhyankar 
5700d6ebe24aSShri Abhyankar    Notes:
5701d6ebe24aSShri Abhyankar    If this routine is not called then the lower and upper bounds are set to
5702e270355aSBarry Smith    PETSC_NINFINITY and PETSC_INFINITY respectively during SNESSetUp().
5703d6ebe24aSShri Abhyankar 
57042bd2b0e6SSatish Balay    Level: advanced
57052bd2b0e6SSatish Balay 
5706d6ebe24aSShri Abhyankar @*/
5707d6ebe24aSShri Abhyankar PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5708d6ebe24aSShri Abhyankar {
5709d6ebe24aSShri Abhyankar   SNES           snes;
5710d6ebe24aSShri Abhyankar 
5711d6ebe24aSShri Abhyankar   PetscFunctionBegin;
57129566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts,&snes));
57139566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes,xl,xu));
5714d6ebe24aSShri Abhyankar   PetscFunctionReturn(0);
5715d6ebe24aSShri Abhyankar }
5716d6ebe24aSShri Abhyankar 
5717f9c1d6abSBarry Smith /*@
5718f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5719f9c1d6abSBarry Smith 
5720d083f849SBarry Smith    Collective on TS
5721f9c1d6abSBarry Smith 
5722f9c1d6abSBarry Smith    Input Parameters:
5723f9c1d6abSBarry Smith +  ts - the TS context
5724f9c1d6abSBarry Smith -  xr,xi - real and imaginary part of input arguments
5725f9c1d6abSBarry Smith 
5726f9c1d6abSBarry Smith    Output Parameters:
5727f9c1d6abSBarry Smith .  yr,yi - real and imaginary part of function value
5728f9c1d6abSBarry Smith 
5729f9c1d6abSBarry Smith    Level: developer
5730f9c1d6abSBarry Smith 
5731db781477SPatrick Sanan .seealso: `TSSetRHSFunction()`, `TSComputeIFunction()`
5732f9c1d6abSBarry Smith @*/
5733f9c1d6abSBarry Smith PetscErrorCode TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal *yr,PetscReal *yi)
5734f9c1d6abSBarry Smith {
5735f9c1d6abSBarry Smith   PetscFunctionBegin;
5736f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
57373c633725SBarry Smith   PetscCheck(ts->ops->linearstability,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"Linearized stability function not provided for this method");
57389566063dSJacob Faibussowitsch   PetscCall((*ts->ops->linearstability)(ts,xr,xi,yr,yi));
5739f9c1d6abSBarry Smith   PetscFunctionReturn(0);
5740f9c1d6abSBarry Smith }
574124655328SShri 
574224655328SShri /*@
5743dcb233daSLisandro Dalcin    TSRestartStep - Flags the solver to restart the next step
5744dcb233daSLisandro Dalcin 
5745dcb233daSLisandro Dalcin    Collective on TS
5746dcb233daSLisandro Dalcin 
5747dcb233daSLisandro Dalcin    Input Parameter:
5748dcb233daSLisandro Dalcin .  ts - the TS context obtained from TSCreate()
5749dcb233daSLisandro Dalcin 
5750dcb233daSLisandro Dalcin    Level: advanced
5751dcb233daSLisandro Dalcin 
5752dcb233daSLisandro Dalcin    Notes:
5753dcb233daSLisandro Dalcin    Multistep methods like BDF or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5754dcb233daSLisandro Dalcin    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5755dcb233daSLisandro Dalcin    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5756dcb233daSLisandro Dalcin    the sake of correctness and maximum safety, users are expected to call TSRestart() whenever they introduce
5757dcb233daSLisandro Dalcin    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5758dcb233daSLisandro Dalcin    discontinuous source terms).
5759dcb233daSLisandro Dalcin 
5760db781477SPatrick Sanan .seealso: `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5761dcb233daSLisandro Dalcin @*/
5762dcb233daSLisandro Dalcin PetscErrorCode TSRestartStep(TS ts)
5763dcb233daSLisandro Dalcin {
5764dcb233daSLisandro Dalcin   PetscFunctionBegin;
5765dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5766dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
5767dcb233daSLisandro Dalcin   PetscFunctionReturn(0);
5768dcb233daSLisandro Dalcin }
5769dcb233daSLisandro Dalcin 
5770dcb233daSLisandro Dalcin /*@
577124655328SShri    TSRollBack - Rolls back one time step
577224655328SShri 
577324655328SShri    Collective on TS
577424655328SShri 
577524655328SShri    Input Parameter:
577624655328SShri .  ts - the TS context obtained from TSCreate()
577724655328SShri 
577824655328SShri    Level: advanced
577924655328SShri 
5780db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
578124655328SShri @*/
578224655328SShri PetscErrorCode  TSRollBack(TS ts)
578324655328SShri {
578424655328SShri   PetscFunctionBegin;
578524655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
57863c633725SBarry Smith   PetscCheck(!ts->steprollback,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONGSTATE,"TSRollBack already called");
57873c633725SBarry Smith   PetscCheck(ts->ops->rollback,PetscObjectComm((PetscObject)ts),PETSC_ERR_SUP,"TSRollBack not implemented for type '%s'",((PetscObject)ts)->type_name);
57889566063dSJacob Faibussowitsch   PetscCall((*ts->ops->rollback)(ts));
578924655328SShri   ts->time_step = ts->ptime - ts->ptime_prev;
579024655328SShri   ts->ptime = ts->ptime_prev;
5791be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
57922808aa04SLisandro Dalcin   ts->steps--;
5793b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
579424655328SShri   PetscFunctionReturn(0);
579524655328SShri }
5796aeb4809dSShri Abhyankar 
5797ff22ae23SHong Zhang /*@
5798ff22ae23SHong Zhang    TSGetStages - Get the number of stages and stage values
5799ff22ae23SHong Zhang 
5800ff22ae23SHong Zhang    Input Parameter:
5801ff22ae23SHong Zhang .  ts - the TS context obtained from TSCreate()
5802ff22ae23SHong Zhang 
58030429704eSStefano Zampini    Output Parameters:
58040429704eSStefano Zampini +  ns - the number of stages
58050429704eSStefano Zampini -  Y - the current stage vectors
58060429704eSStefano Zampini 
5807ff22ae23SHong Zhang    Level: advanced
5808ff22ae23SHong Zhang 
58090429704eSStefano Zampini    Notes: Both ns and Y can be NULL.
58100429704eSStefano Zampini 
5811db781477SPatrick Sanan .seealso: `TSCreate()`
5812ff22ae23SHong Zhang @*/
5813ff22ae23SHong Zhang PetscErrorCode  TSGetStages(TS ts,PetscInt *ns,Vec **Y)
5814ff22ae23SHong Zhang {
5815ff22ae23SHong Zhang   PetscFunctionBegin;
5816ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5817dadcf809SJacob Faibussowitsch   if (ns) PetscValidIntPointer(ns,2);
58180429704eSStefano Zampini   if (Y) PetscValidPointer(Y,3);
58190429704eSStefano Zampini   if (!ts->ops->getstages) {
58200429704eSStefano Zampini     if (ns) *ns = 0;
58210429704eSStefano Zampini     if (Y) *Y = NULL;
58220429704eSStefano Zampini   } else {
58239566063dSJacob Faibussowitsch     PetscCall((*ts->ops->getstages)(ts,ns,Y));
5824ff22ae23SHong Zhang   }
5825ff22ae23SHong Zhang   PetscFunctionReturn(0);
5826ff22ae23SHong Zhang }
5827ff22ae23SHong Zhang 
5828847ff0e1SMatthew G. Knepley /*@C
5829847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5830847ff0e1SMatthew G. Knepley 
5831847ff0e1SMatthew G. Knepley   Collective on SNES
5832847ff0e1SMatthew G. Knepley 
5833847ff0e1SMatthew G. Knepley   Input Parameters:
5834847ff0e1SMatthew G. Knepley + ts - the TS context
5835847ff0e1SMatthew G. Knepley . t - current timestep
5836847ff0e1SMatthew G. Knepley . U - state vector
5837847ff0e1SMatthew G. Knepley . Udot - time derivative of state vector
5838847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5839847ff0e1SMatthew G. Knepley - ctx - an optional user context
5840847ff0e1SMatthew G. Knepley 
5841847ff0e1SMatthew G. Knepley   Output Parameters:
5842847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5843847ff0e1SMatthew G. Knepley - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
5844847ff0e1SMatthew G. Knepley 
5845847ff0e1SMatthew G. Knepley   Level: intermediate
5846847ff0e1SMatthew G. Knepley 
5847847ff0e1SMatthew G. Knepley   Notes:
5848847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5849847ff0e1SMatthew G. Knepley 
5850847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5851847ff0e1SMatthew G. Knepley 
5852847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5853847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5854847ff0e1SMatthew G. Knepley 
5855847ff0e1SMatthew G. Knepley   This will first try to get the coloring from the DM.  If the DM type has no coloring
5856847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5857847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5858847ff0e1SMatthew G. Knepley 
5859db781477SPatrick Sanan .seealso: `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5860847ff0e1SMatthew G. Knepley @*/
5861847ff0e1SMatthew G. Knepley PetscErrorCode TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,void *ctx)
5862847ff0e1SMatthew G. Knepley {
5863847ff0e1SMatthew G. Knepley   SNES           snes;
5864847ff0e1SMatthew G. Knepley   MatFDColoring  color;
5865847ff0e1SMatthew G. Knepley   PetscBool      hascolor, matcolor = PETSC_FALSE;
5866847ff0e1SMatthew G. Knepley 
5867847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
58689566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options,((PetscObject) ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
58699566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject) B, "TSMatFDColoring", (PetscObject *) &color));
5870847ff0e1SMatthew G. Knepley   if (!color) {
5871847ff0e1SMatthew G. Knepley     DM         dm;
5872847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5873847ff0e1SMatthew G. Knepley 
58749566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
58759566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5876847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
58779566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
58789566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
58799566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts));
58809566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
58819566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
58829566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5883847ff0e1SMatthew G. Knepley     } else {
5884847ff0e1SMatthew G. Knepley       MatColoring mc;
5885847ff0e1SMatthew G. Knepley 
58869566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
58879566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
58889566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
58899566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
58909566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
58919566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
58929566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
58939566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void)) SNESTSFormFunction, (void *) ts));
58949566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
58959566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
58969566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5897847ff0e1SMatthew G. Knepley     }
58989566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject) B, "TSMatFDColoring", (PetscObject) color));
58999566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject) color));
5900847ff0e1SMatthew G. Knepley   }
59019566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
59029566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5903847ff0e1SMatthew G. Knepley   if (J != B) {
59049566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
59059566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5906847ff0e1SMatthew G. Knepley   }
5907847ff0e1SMatthew G. Knepley   PetscFunctionReturn(0);
5908847ff0e1SMatthew G. Knepley }
590993b34091SDebojyoti Ghosh 
5910cb9d8021SPierre Barbier de Reuille /*@
59116bc98fa9SBarry Smith     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5912cb9d8021SPierre Barbier de Reuille 
5913cb9d8021SPierre Barbier de Reuille     Input Parameters:
59146bc98fa9SBarry Smith +    ts - the TS context
59156bc98fa9SBarry Smith -    func - function called within TSFunctionDomainError
59166bc98fa9SBarry Smith 
59176bc98fa9SBarry Smith     Calling sequence of func:
59186bc98fa9SBarry Smith $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
59196bc98fa9SBarry Smith 
59206bc98fa9SBarry Smith +   ts - the TS context
59216bc98fa9SBarry Smith .   time - the current time (of the stage)
59226bc98fa9SBarry Smith .   state - the state to check if it is valid
59236bc98fa9SBarry Smith -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
5924cb9d8021SPierre Barbier de Reuille 
5925cb9d8021SPierre Barbier de Reuille     Level: intermediate
5926cb9d8021SPierre Barbier de Reuille 
59276bc98fa9SBarry Smith     Notes:
59286bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
59296bc98fa9SBarry Smith       user's code should call SNESSetFunctionDomainError() when domain errors occur during
59306bc98fa9SBarry Smith       function evaluations where the functions are provided by TSSetIFunction() or TSSetRHSFunction().
59316bc98fa9SBarry Smith       Use TSGetSNES() to obtain the SNES object
59326bc98fa9SBarry Smith 
59336bc98fa9SBarry Smith     Developer Notes:
59346bc98fa9SBarry Smith       The naming of this function is inconsistent with the SNESSetFunctionDomainError()
59356bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
59366bc98fa9SBarry Smith 
5937db781477SPatrick Sanan .seealso: `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5938cb9d8021SPierre Barbier de Reuille @*/
5939cb9d8021SPierre Barbier de Reuille 
5940d183316bSPierre Barbier de Reuille PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS,PetscReal,Vec,PetscBool*))
5941cb9d8021SPierre Barbier de Reuille {
5942cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5943cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
5944cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
5945cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5946cb9d8021SPierre Barbier de Reuille }
5947cb9d8021SPierre Barbier de Reuille 
5948cb9d8021SPierre Barbier de Reuille /*@
59496bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5950cb9d8021SPierre Barbier de Reuille 
5951cb9d8021SPierre Barbier de Reuille     Input Parameters:
59526bc98fa9SBarry Smith +    ts - the TS context
59536bc98fa9SBarry Smith .    stagetime - time of the simulation
59546bc98fa9SBarry Smith -    Y - state vector to check.
5955cb9d8021SPierre Barbier de Reuille 
5956cb9d8021SPierre Barbier de Reuille     Output Parameter:
59576bc98fa9SBarry Smith .    accept - Set to PETSC_FALSE if the current state vector is valid.
5958cb9d8021SPierre Barbier de Reuille 
5959cb9d8021SPierre Barbier de Reuille     Note:
59606bc98fa9SBarry Smith     This function is called by the TS integration routines and calls the user provided function (set with TSSetFunctionDomainError())
59616bc98fa9SBarry Smith     to check if the current state is valid.
596296a0c994SBarry Smith 
59636bc98fa9SBarry Smith     Level: developer
59646bc98fa9SBarry Smith 
5965db781477SPatrick Sanan .seealso: `TSSetFunctionDomainError()`
5966cb9d8021SPierre Barbier de Reuille @*/
5967d183316bSPierre Barbier de Reuille PetscErrorCode TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool* accept)
5968cb9d8021SPierre Barbier de Reuille {
5969cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5970cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
5971cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
5972cb9d8021SPierre Barbier de Reuille   if (ts->functiondomainerror) {
5973a74df02fSJacob Faibussowitsch     PetscStackCallStandard((*ts->functiondomainerror),ts,stagetime,Y,accept);
5974cb9d8021SPierre Barbier de Reuille   }
5975cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5976cb9d8021SPierre Barbier de Reuille }
59771ceb14c0SBarry Smith 
597893b34091SDebojyoti Ghosh /*@C
5979e5168f73SEmil Constantinescu   TSClone - This function clones a time step object.
598093b34091SDebojyoti Ghosh 
5981d083f849SBarry Smith   Collective
598293b34091SDebojyoti Ghosh 
598393b34091SDebojyoti Ghosh   Input Parameter:
598493b34091SDebojyoti Ghosh . tsin    - The input TS
598593b34091SDebojyoti Ghosh 
598693b34091SDebojyoti Ghosh   Output Parameter:
5987e5168f73SEmil Constantinescu . tsout   - The output TS (cloned)
598893b34091SDebojyoti Ghosh 
59895eca1a21SEmil Constantinescu   Notes:
59905eca1a21SEmil 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.
59915eca1a21SEmil Constantinescu 
5992928bb9adSStefano 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);
59935eca1a21SEmil Constantinescu 
59945eca1a21SEmil Constantinescu   Level: developer
599593b34091SDebojyoti Ghosh 
5996db781477SPatrick Sanan .seealso: `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
599793b34091SDebojyoti Ghosh @*/
5998baa10174SEmil Constantinescu PetscErrorCode  TSClone(TS tsin, TS *tsout)
599993b34091SDebojyoti Ghosh {
600093b34091SDebojyoti Ghosh   TS             t;
6001dc846ba4SSatish Balay   SNES           snes_start;
6002dc846ba4SSatish Balay   DM             dm;
6003dc846ba4SSatish Balay   TSType         type;
600493b34091SDebojyoti Ghosh 
600593b34091SDebojyoti Ghosh   PetscFunctionBegin;
600693b34091SDebojyoti Ghosh   PetscValidPointer(tsin,1);
600793b34091SDebojyoti Ghosh   *tsout = NULL;
600893b34091SDebojyoti Ghosh 
60099566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
601093b34091SDebojyoti Ghosh 
601193b34091SDebojyoti Ghosh   /* General TS description */
601293b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
6013d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
601493b34091SDebojyoti Ghosh   t->setupcalled       = 0;
601593b34091SDebojyoti Ghosh   t->ksp_its           = 0;
601693b34091SDebojyoti Ghosh   t->snes_its          = 0;
601793b34091SDebojyoti Ghosh   t->nwork             = 0;
60187d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
601993b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
602093b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
602193b34091SDebojyoti Ghosh 
60229566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin,&snes_start));
60239566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t,snes_start));
6024d15a3a53SEmil Constantinescu 
60259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin,&dm));
60269566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t,dm));
602793b34091SDebojyoti Ghosh 
602893b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
60299566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
603093b34091SDebojyoti Ghosh 
6031e7069c78SShri   t->trajectory = tsin->trajectory;
60329566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
6033e7069c78SShri 
6034e7069c78SShri   t->event = tsin->event;
60356b10a48eSSatish Balay   if (t->event) t->event->refct++;
6036e7069c78SShri 
603793b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
603893b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
6039e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
604093b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
604193b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
604293b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
604393b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
604493b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
604593b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
604693b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
604793b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
604893b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
604993b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
605093b34091SDebojyoti Ghosh 
60519566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin,&type));
60529566063dSJacob Faibussowitsch   PetscCall(TSSetType(t,type));
605393b34091SDebojyoti Ghosh 
605493b34091SDebojyoti Ghosh   t->vec_sol           = NULL;
605593b34091SDebojyoti Ghosh 
605693b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
605793b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
605893b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
605993b34091SDebojyoti Ghosh 
60609566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops,tsin->ops,sizeof(struct _TSOps)));
606193b34091SDebojyoti Ghosh 
60620d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
60630d4fed19SBarry Smith     PetscInt i;
60649566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10)*sizeof(void(*)(void)),&((PetscObject)t)->fortran_func_pointers));
60650d4fed19SBarry Smith     for (i=0; i<10; i++) {
60660d4fed19SBarry Smith       ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
60670d4fed19SBarry Smith     }
60680d4fed19SBarry Smith   }
606993b34091SDebojyoti Ghosh   *tsout = t;
607093b34091SDebojyoti Ghosh   PetscFunctionReturn(0);
607193b34091SDebojyoti Ghosh }
6072f3b1f45cSBarry Smith 
6073f3b1f45cSBarry Smith static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void* ctx,Vec x,Vec y)
6074f3b1f45cSBarry Smith {
6075f3b1f45cSBarry Smith   TS             ts = (TS) ctx;
6076f3b1f45cSBarry Smith 
6077f3b1f45cSBarry Smith   PetscFunctionBegin;
60789566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts,0,x,y));
6079f3b1f45cSBarry Smith   PetscFunctionReturn(0);
6080f3b1f45cSBarry Smith }
6081f3b1f45cSBarry Smith 
6082f3b1f45cSBarry Smith /*@
6083f3b1f45cSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the MATSHELL with differencing on the TS given RHS function.
6084f3b1f45cSBarry Smith 
6085d083f849SBarry Smith    Logically Collective on TS
6086f3b1f45cSBarry Smith 
6087f3b1f45cSBarry Smith     Input Parameters:
6088f3b1f45cSBarry Smith     TS - the time stepping routine
6089f3b1f45cSBarry Smith 
6090f3b1f45cSBarry Smith    Output Parameter:
6091f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
6092f3b1f45cSBarry Smith 
6093f3b1f45cSBarry Smith    Options Database:
6094f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
6095f3b1f45cSBarry Smith 
6096f3b1f45cSBarry Smith    Level: advanced
6097f3b1f45cSBarry Smith 
609895452b02SPatrick Sanan    Notes:
609995452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
6100f3b1f45cSBarry Smith 
6101db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
6102f3b1f45cSBarry Smith @*/
6103f3b1f45cSBarry Smith PetscErrorCode  TSRHSJacobianTest(TS ts,PetscBool *flg)
6104f3b1f45cSBarry Smith {
6105f3b1f45cSBarry Smith   Mat            J,B;
6106f3b1f45cSBarry Smith   TSRHSJacobian  func;
6107f3b1f45cSBarry Smith   void*          ctx;
6108f3b1f45cSBarry Smith 
6109f3b1f45cSBarry Smith   PetscFunctionBegin;
61109566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,&J,&B,&func,&ctx));
61119566063dSJacob Faibussowitsch   PetscCall((*func)(ts,0.0,ts->vec_sol,J,B,ctx));
61129566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg));
6113f3b1f45cSBarry Smith   PetscFunctionReturn(0);
6114f3b1f45cSBarry Smith }
6115f3b1f45cSBarry Smith 
6116f3b1f45cSBarry Smith /*@C
6117f3b1f45cSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the MATSHELL with differencing on the TS given RHS function.
6118f3b1f45cSBarry Smith 
6119d083f849SBarry Smith    Logically Collective on TS
6120f3b1f45cSBarry Smith 
6121f3b1f45cSBarry Smith     Input Parameters:
6122f3b1f45cSBarry Smith     TS - the time stepping routine
6123f3b1f45cSBarry Smith 
6124f3b1f45cSBarry Smith    Output Parameter:
6125f3b1f45cSBarry Smith .   flg - PETSC_TRUE if the multiply is likely correct
6126f3b1f45cSBarry Smith 
6127f3b1f45cSBarry Smith    Options Database:
6128f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
6129f3b1f45cSBarry Smith 
613095452b02SPatrick Sanan    Notes:
613195452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
6132f3b1f45cSBarry Smith 
6133f3b1f45cSBarry Smith    Level: advanced
6134f3b1f45cSBarry Smith 
6135db781477SPatrick Sanan .seealso: `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
6136f3b1f45cSBarry Smith @*/
6137f3b1f45cSBarry Smith PetscErrorCode  TSRHSJacobianTestTranspose(TS ts,PetscBool *flg)
6138f3b1f45cSBarry Smith {
6139f3b1f45cSBarry Smith   Mat            J,B;
6140f3b1f45cSBarry Smith   void           *ctx;
6141f3b1f45cSBarry Smith   TSRHSJacobian  func;
6142f3b1f45cSBarry Smith 
6143f3b1f45cSBarry Smith   PetscFunctionBegin;
61449566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts,&J,&B,&func,&ctx));
61459566063dSJacob Faibussowitsch   PetscCall((*func)(ts,0.0,ts->vec_sol,J,B,ctx));
61469566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J,RHSWrapperFunction_TSRHSJacobianTest,ts->vec_sol,ts,flg));
6147f3b1f45cSBarry Smith   PetscFunctionReturn(0);
6148f3b1f45cSBarry Smith }
61490fe4d17eSHong Zhang 
61500fe4d17eSHong Zhang /*@
61510fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
61520fe4d17eSHong Zhang 
61530fe4d17eSHong Zhang   Logically collective
61540fe4d17eSHong Zhang 
6155d8d19677SJose E. Roman   Input Parameters:
61560fe4d17eSHong Zhang +  ts - timestepping context
61570fe4d17eSHong Zhang -  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
61580fe4d17eSHong Zhang 
61590fe4d17eSHong Zhang   Options Database:
61600fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
61610fe4d17eSHong Zhang 
61620fe4d17eSHong Zhang   Notes:
61630fe4d17eSHong Zhang     This is only useful for multirate methods
61640fe4d17eSHong Zhang 
61650fe4d17eSHong Zhang   Level: intermediate
61660fe4d17eSHong Zhang 
6167db781477SPatrick Sanan .seealso: `TSGetUseSplitRHSFunction()`
61680fe4d17eSHong Zhang @*/
61690fe4d17eSHong Zhang PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
61700fe4d17eSHong Zhang {
61710fe4d17eSHong Zhang   PetscFunctionBegin;
61720fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
61730fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
61740fe4d17eSHong Zhang   PetscFunctionReturn(0);
61750fe4d17eSHong Zhang }
61760fe4d17eSHong Zhang 
61770fe4d17eSHong Zhang /*@
61780fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
61790fe4d17eSHong Zhang 
61800fe4d17eSHong Zhang   Not collective
61810fe4d17eSHong Zhang 
61820fe4d17eSHong Zhang   Input Parameter:
61830fe4d17eSHong Zhang .  ts - timestepping context
61840fe4d17eSHong Zhang 
61850fe4d17eSHong Zhang   Output Parameter:
61860fe4d17eSHong Zhang .  use_splitrhsfunction - PETSC_TRUE indicates that the split RHSFunction will be used
61870fe4d17eSHong Zhang 
61880fe4d17eSHong Zhang   Level: intermediate
61890fe4d17eSHong Zhang 
6190db781477SPatrick Sanan .seealso: `TSSetUseSplitRHSFunction()`
61910fe4d17eSHong Zhang @*/
61920fe4d17eSHong Zhang PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
61930fe4d17eSHong Zhang {
61940fe4d17eSHong Zhang   PetscFunctionBegin;
61950fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
61960fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
61970fe4d17eSHong Zhang   PetscFunctionReturn(0);
61980fe4d17eSHong Zhang }
6199d60b7d5cSBarry Smith 
6200d60b7d5cSBarry Smith /*@
6201d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6202d60b7d5cSBarry Smith 
6203d60b7d5cSBarry Smith    Logically  Collective on ts
6204d60b7d5cSBarry Smith 
6205d60b7d5cSBarry Smith    Input Parameters:
6206d60b7d5cSBarry Smith +  ts - the time-stepper
6207d60b7d5cSBarry Smith -  str - the structure (the default is UNKNOWN_NONZERO_PATTERN)
6208d60b7d5cSBarry Smith 
6209d60b7d5cSBarry Smith    Level: intermediate
6210d60b7d5cSBarry Smith 
6211d60b7d5cSBarry Smith    Notes:
6212d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6213d60b7d5cSBarry Smith 
6214db781477SPatrick Sanan .seealso: `MatAXPY()`, `MatStructure`
6215d60b7d5cSBarry Smith  @*/
6216d60b7d5cSBarry Smith PetscErrorCode TSSetMatStructure(TS ts,MatStructure str)
6217d60b7d5cSBarry Smith {
6218d60b7d5cSBarry Smith   PetscFunctionBegin;
6219d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
6220d60b7d5cSBarry Smith   ts->axpy_pattern = str;
6221d60b7d5cSBarry Smith   PetscFunctionReturn(0);
6222d60b7d5cSBarry Smith }
62234a658b32SHong Zhang 
62244a658b32SHong Zhang /*@
62254a658b32SHong Zhang   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested.
62264a658b32SHong Zhang 
62274a658b32SHong Zhang   Collective on ts
62284a658b32SHong Zhang 
62294a658b32SHong Zhang   Input Parameters:
62304a658b32SHong Zhang + ts - the time-stepper
62314a658b32SHong Zhang . n - number of the time points (>=2)
62324a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
62334a658b32SHong Zhang 
62344a658b32SHong Zhang   Options Database Keys:
62354a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
62364a658b32SHong Zhang 
62374a658b32SHong Zhang   Level: beginner
62384a658b32SHong Zhang 
62394a658b32SHong Zhang   Notes:
62404a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
62414a658b32SHong Zhang   TS_EXACTFINALTIME_MATCHSTEP must be used to make the last time step in each sub-interval match the intermediate points specified.
62424a658b32SHong Zhang   The intermediate solutions are saved in a vector array that can be accessed with TSGetSolutions(). Thus using time span may
62434a658b32SHong Zhang   pressure the memory system when using a large number of span points.
62444a658b32SHong Zhang 
6245c2e3fba1SPatrick Sanan .seealso: `TSGetTimeSpan()`, `TSGetSolutions()`
62464a658b32SHong Zhang  @*/
62474a658b32SHong Zhang PetscErrorCode TSSetTimeSpan(TS ts,PetscInt n,PetscReal *span_times)
62484a658b32SHong Zhang {
62494a658b32SHong Zhang   PetscFunctionBegin;
62504a658b32SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
625163a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2,PetscObjectComm((PetscObject)ts),PETSC_ERR_ARG_WRONG,"Minimum time span size is 2 but %" PetscInt_FMT " is provided",n);
62524a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
62534a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
62544a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times,&ts->tspan->vecs_sol));
62554a658b32SHong Zhang     PetscCall(PetscMalloc1(n,&ts->tspan->span_times));
62564a658b32SHong Zhang   }
62574a658b32SHong Zhang   if (!ts->tspan) {
62584a658b32SHong Zhang     TSTimeSpan tspan;
62594a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
62604a658b32SHong Zhang     PetscCall(PetscMalloc1(n,&tspan->span_times));
6261*e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6262*e1db57b0SHong Zhang     tspan->abstol = 10*PETSC_MACHINE_EPSILON;
62634a658b32SHong Zhang     ts->tspan = tspan;
62644a658b32SHong Zhang   }
62654a658b32SHong Zhang   ts->tspan->num_span_times = n;
62664a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times,span_times,n));
62674a658b32SHong Zhang   PetscCall(TSSetTime(ts,ts->tspan->span_times[0]));
62684a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts,ts->tspan->span_times[n-1]));
62694a658b32SHong Zhang   PetscFunctionReturn(0);
62704a658b32SHong Zhang }
62714a658b32SHong Zhang 
62724a658b32SHong Zhang /*@C
62734a658b32SHong Zhang   TSGetTimeSpan - gets the time span.
62744a658b32SHong Zhang 
62754a658b32SHong Zhang   Not Collective
62764a658b32SHong Zhang 
62774a658b32SHong Zhang   Input Parameter:
62784a658b32SHong Zhang . ts - the time-stepper
62794a658b32SHong Zhang 
62804a658b32SHong Zhang   Output Parameters:
62814a658b32SHong Zhang + n - number of the time points (>=2)
62824a658b32SHong 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.
62834a658b32SHong Zhang 
62844a658b32SHong Zhang   Level: beginner
62854a658b32SHong Zhang   Notes: Both n and span_times can be NULL.
62864a658b32SHong Zhang 
6287c2e3fba1SPatrick Sanan .seealso: `TSSetTimeSpan()`, `TSGetSolutions()`
62884a658b32SHong Zhang  @*/
62894a658b32SHong Zhang PetscErrorCode TSGetTimeSpan(TS ts,PetscInt *n,const PetscReal **span_times)
62904a658b32SHong Zhang {
62914a658b32SHong Zhang   PetscFunctionBegin;
62924a658b32SHong Zhang   PetscValidHeaderSpecific(ts,TS_CLASSID,1);
62934a658b32SHong Zhang   if (n) PetscValidIntPointer(n,2);
62944a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times,3);
62954a658b32SHong Zhang   if (!ts->tspan) {
62964a658b32SHong Zhang     if (n) *n = 0;
62974a658b32SHong Zhang     if (span_times) *span_times = NULL;
62984a658b32SHong Zhang   } else {
62994a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
63004a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
63014a658b32SHong Zhang   }
63024a658b32SHong Zhang   PetscFunctionReturn(0);
63034a658b32SHong Zhang }
63044a658b32SHong Zhang 
63054a658b32SHong Zhang /*@
63064a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
63074a658b32SHong Zhang 
63084a658b32SHong Zhang    Input Parameter:
63094a658b32SHong Zhang .  ts - the TS context obtained from TSCreate()
63104a658b32SHong Zhang 
63114a658b32SHong Zhang    Output Parameters:
63124a658b32SHong Zhang +  nsol - the number of solutions
63134a658b32SHong Zhang -  Sols - the solution vectors
63144a658b32SHong Zhang 
63154a658b32SHong Zhang    Level: beginner
63164a658b32SHong Zhang 
631740bd4cedSHong Zhang    Notes:
631840bd4cedSHong Zhang     Both nsol and Sols can be NULL.
631940bd4cedSHong 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.
63204a658b32SHong Zhang 
6321db781477SPatrick Sanan .seealso: `TSSetTimeSpan()`
63224a658b32SHong Zhang @*/
63234a658b32SHong Zhang PetscErrorCode TSGetTimeSpanSolutions(TS ts,PetscInt *nsol,Vec **Sols)
63244a658b32SHong Zhang {
63254a658b32SHong Zhang   PetscFunctionBegin;
63264a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID,1);
63274a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol,2);
63284a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols,3);
63294a658b32SHong Zhang   if (!ts->tspan) {
63304a658b32SHong Zhang     if (nsol) *nsol = 0;
63314a658b32SHong Zhang     if (Sols) *Sols = NULL;
63324a658b32SHong Zhang   } else {
633340bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
63344a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
63354a658b32SHong Zhang   }
63364a658b32SHong Zhang   PetscFunctionReturn(0);
63374a658b32SHong Zhang }
6338