xref: /petsc/src/ts/interface/ts.c (revision 7f27e910a47413be358360c96e592d1f474bc2bb)
1af0996ceSBarry Smith #include <petsc/private/tsimpl.h> /*I "petscts.h"  I*/
21e25c274SJed Brown #include <petscdmda.h>
360e16b1bSMatthew G. Knepley #include <petscdmshell.h>
460e16b1bSMatthew G. Knepley #include <petscdmplex.h>  // For TSSetFromOptions()
560e16b1bSMatthew G. Knepley #include <petscdmswarm.h> // For TSSetFromOptions()
62d5ee99bSBarry Smith #include <petscviewer.h>
72d5ee99bSBarry Smith #include <petscdraw.h>
8900f6b5bSMatthew G. Knepley #include <petscconvest.h>
9d763cef2SBarry Smith 
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 
16d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
17d71ae5a4SJacob Faibussowitsch {
182ffb9264SLisandro Dalcin   PetscFunctionBegin;
19b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt, TSADAPT_CLASSID, 1);
204f572ea9SToby Isaac   PetscAssertPointer(default_type, 2);
211e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
232ffb9264SLisandro Dalcin }
242ffb9264SLisandro Dalcin 
25bdad233fSMatthew Knepley /*@
26195e9b02SBarry Smith   TSSetFromOptions - Sets various `TS` parameters from the options database
27bdad233fSMatthew Knepley 
28c3339decSBarry Smith   Collective
29bdad233fSMatthew Knepley 
30bdad233fSMatthew Knepley   Input Parameter:
31bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
32bdad233fSMatthew Knepley 
33bdad233fSMatthew Knepley   Options Database Keys:
34195e9b02SBarry Smith + -ts_type <type>                                                    - EULER, BEULER, SUNDIALS, PSEUDO, CN, RK, THETA, ALPHA, GLLE,  SSP, GLEE, BSYMP, IRK, see `TSType`
35ef222394SBarry Smith . -ts_save_trajectory                                                - checkpoint the solution at each time-step
36ef85077eSLisandro Dalcin . -ts_max_time <time>                                                - maximum time to compute to
374a658b32SHong Zhang . -ts_time_span <t0,...tf>                                           - sets the time span, solutions are computed and stored for each indicated time
38ef85077eSLisandro Dalcin . -ts_max_steps <steps>                                              - maximum number of time-steps to take
39ef85077eSLisandro Dalcin . -ts_init_time <time>                                               - initial time to start computation
40195e9b02SBarry Smith . -ts_final_time <time>                                              - final time to compute to (deprecated: use `-ts_max_time`)
413e4cdcaaSBarry Smith . -ts_dt <dt>                                                        - initial time step
421628793fSSatish Balay . -ts_exact_final_time <stepover,interpolate,matchstep>              - whether to stop at the exact given final time and how to compute the solution at that time
43a3cdaa26SBarry Smith . -ts_max_snes_failures <maxfailures>                                - Maximum number of nonlinear solve failures allowed
44a3cdaa26SBarry Smith . -ts_max_reject <maxrejects>                                        - Maximum number of step rejections before step fails
45a3cdaa26SBarry Smith . -ts_error_if_step_fails <true,false>                               - Error if no step succeeds
46a3cdaa26SBarry Smith . -ts_rtol <rtol>                                                    - relative tolerance for local truncation error
4767b8a455SSatish Balay . -ts_atol <atol>                                                    - Absolute tolerance for local truncation error
48f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view               - test the Jacobian at each iteration against finite difference with RHS function
49b43aa488SJacob Faibussowitsch . -ts_rhs_jacobian_test_mult_transpose                               - test the Jacobian at each iteration against finite difference with RHS function
50195e9b02SBarry Smith . -ts_adjoint_solve <yes,no>                                         - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
51847ff0e1SMatthew G. Knepley . -ts_fd_color                                                       - Use finite differences with coloring to compute IJacobian
52bdad233fSMatthew Knepley . -ts_monitor                                                        - print information at each timestep
53aee7a9fbSMatthew G. Knepley . -ts_monitor_cancel                                                 - Cancel all monitors
54de06c3feSJed Brown . -ts_monitor_lg_solution                                            - Monitor solution graphically
55de06c3feSJed Brown . -ts_monitor_lg_error                                               - Monitor error graphically
567cf37e64SBarry Smith . -ts_monitor_error                                                  - Monitors norm of error
576934998bSLisandro Dalcin . -ts_monitor_lg_timestep                                            - Monitor timestep size graphically
588b668821SLisandro Dalcin . -ts_monitor_lg_timestep_log                                        - Monitor log timestep size graphically
59de06c3feSJed Brown . -ts_monitor_lg_snes_iterations                                     - Monitor number nonlinear iterations for each timestep graphically
60de06c3feSJed Brown . -ts_monitor_lg_ksp_iterations                                      - Monitor number nonlinear iterations for each timestep graphically
61de06c3feSJed Brown . -ts_monitor_sp_eig                                                 - Monitor eigenvalues of linearized operator graphically
62de06c3feSJed Brown . -ts_monitor_draw_solution                                          - Monitor solution graphically
633e4cdcaaSBarry Smith . -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright>       - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
643e4cdcaaSBarry Smith . -ts_monitor_draw_error                                             - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
65fde5950dSBarry Smith . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
66b43aa488SJacob Faibussowitsch . -ts_monitor_solution_interval <interval>                           - output once every interval (default=1) time steps
6763a3b9bcSJacob 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)
689e336e28SPatrick Sanan - -ts_monitor_envelope                                               - determine maximum and minimum value of each component of the solution over the solution time
6953ea634cSHong Zhang 
70bcf0153eSBarry Smith   Level: beginner
713d5a8a6aSBarry Smith 
72bcf0153eSBarry Smith   Notes:
73bcf0153eSBarry Smith   See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
74bcf0153eSBarry Smith 
75195e9b02SBarry Smith   Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
76195e9b02SBarry Smith   to retain them over the multiple nonlinear solves that `TS` uses you mush also provide `-snes_lag_jacobian_persists true` and
77195e9b02SBarry Smith   `-snes_lag_preconditioner_persists true`
783d5a8a6aSBarry Smith 
79b43aa488SJacob Faibussowitsch   Developer Notes:
809e336e28SPatrick Sanan   We should unify all the -ts_monitor options in the way that -xxx_view has been unified
81bdad233fSMatthew Knepley 
821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetType()`
83bdad233fSMatthew Knepley @*/
84d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
85d71ae5a4SJacob Faibussowitsch {
86bc952696SBarry Smith   PetscBool              opt, flg, tflg;
87eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
884a658b32SHong Zhang   PetscReal              time_step, tspan[100];
894a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9049354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
91d1212d36SBarry Smith   char                   dir[16];
928434afd1SBarry Smith   TSIFunctionFn         *ifun;
936991f827SBarry Smith   const char            *defaultType;
946991f827SBarry Smith   char                   typeName[256];
95bdad233fSMatthew Knepley 
96bdad233fSMatthew Knepley   PetscFunctionBegin;
970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
986991f827SBarry Smith 
999566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1009566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
101cd11d68dSLisandro Dalcin 
102d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1031ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1041ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1059566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1061e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1071e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
108bdad233fSMatthew Knepley 
109bdad233fSMatthew Knepley   /* Handle generic TS options */
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1124a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1134a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1179566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1189566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1199566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
12009cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, &flg));
12109cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxSNESFailures(ts, ts->max_snes_failures));
12209cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, &flg));
12309cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxStepRejections(ts, ts->max_reject));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
12509cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL, 0));
12609cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL, 0));
127bdad233fSMatthew Knepley 
1289566063dSJacob 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));
1299566063dSJacob 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));
1309566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
13156f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13256f85f32SBarry Smith   {
13356f85f32SBarry Smith     PetscBool set;
13456f85f32SBarry Smith     flg = PETSC_FALSE;
1359566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1361baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13756f85f32SBarry Smith   }
13856f85f32SBarry Smith #endif
13956f85f32SBarry Smith 
140bdad233fSMatthew Knepley   /* Monitor options */
1419566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1429566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1449566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1459566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
146fde5950dSBarry Smith 
1479566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1489566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1495180491cSLisandro Dalcin 
1509566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
151b3603a34SBarry Smith   if (opt) {
1523923b477SBarry Smith     PetscInt  howoften = 1;
153e669de00SBarry Smith     DM        dm;
154e669de00SBarry Smith     PetscBool net;
155b3603a34SBarry Smith 
1569566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1579566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1589566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
159e669de00SBarry Smith     if (net) {
160e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1619566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
1629566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxNetworkDestroy));
1639566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
164e669de00SBarry Smith     } else {
165e669de00SBarry Smith       TSMonitorLGCtx ctx;
1669566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1679566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
168bdad233fSMatthew Knepley     }
169e669de00SBarry Smith   }
1706ba87a44SLisandro Dalcin 
1719566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
172ef20d060SBarry Smith   if (opt) {
1730b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1743923b477SBarry Smith     PetscInt       howoften = 1;
175ef20d060SBarry Smith 
1769566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1779566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1789566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
179ef20d060SBarry Smith   }
1809566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1817cf37e64SBarry Smith 
1829566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1836934998bSLisandro Dalcin   if (opt) {
1846934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1856934998bSLisandro Dalcin     PetscInt       howoften = 1;
1866934998bSLisandro Dalcin 
1879566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1889566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1899566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1906934998bSLisandro Dalcin   }
1919566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1928b668821SLisandro Dalcin   if (opt) {
1938b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1948b668821SLisandro Dalcin     PetscInt       howoften = 1;
1958b668821SLisandro Dalcin 
1969566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1979566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1989566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1998b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2008b668821SLisandro Dalcin   }
2018b668821SLisandro Dalcin 
2029566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
203201da799SBarry Smith   if (opt) {
204201da799SBarry Smith     TSMonitorLGCtx ctx;
205201da799SBarry Smith     PetscInt       howoften = 1;
206201da799SBarry Smith 
2079566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2089566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2099566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
210201da799SBarry Smith   }
2119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
212201da799SBarry Smith   if (opt) {
213201da799SBarry Smith     TSMonitorLGCtx ctx;
214201da799SBarry Smith     PetscInt       howoften = 1;
215201da799SBarry Smith 
2169566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2179566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2189566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
219201da799SBarry Smith   }
2209566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2218189c53fSBarry Smith   if (opt) {
2228189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2238189c53fSBarry Smith     PetscInt          howoften = 1;
2248189c53fSBarry Smith 
2259566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2269566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2279566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscErrorCode(*)(void **))TSMonitorSPEigCtxDestroy));
2288189c53fSBarry Smith   }
22960e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2301b575b74SJoseph Pusztay   if (opt) {
2311b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
232d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
23360e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
234d7462660SMatthew Knepley 
2359371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2369371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2379371c9d4SSatish Balay         create = PETSC_FALSE;
2389371c9d4SSatish Balay         break;
2399371c9d4SSatish Balay       }
2406a5217c0SMatthew G. Knepley     if (create) {
24160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2429566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2439566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
24460e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
24560e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
2469566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorSPCtxDestroy));
2471b575b74SJoseph Pusztay     }
2486a5217c0SMatthew G. Knepley   }
24960e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
25060e16b1bSMatthew G. Knepley   if (opt) {
25160e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
25260e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
25360e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
25460e16b1bSMatthew G. Knepley 
25560e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
25660e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
25760e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
25860e16b1bSMatthew G. Knepley         break;
25960e16b1bSMatthew G. Knepley       }
26060e16b1bSMatthew G. Knepley     if (create) {
26160e16b1bSMatthew G. Knepley       DM       sw, dm;
26260e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
26360e16b1bSMatthew G. Knepley 
26460e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
26560e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
26660e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
26760e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
26860e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
26960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
27060e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
27160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
27260e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
27360e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorHGCtxDestroy));
27460e16b1bSMatthew G. Knepley     }
27560e16b1bSMatthew G. Knepley   }
276ef20d060SBarry Smith   opt = PETSC_FALSE;
2779566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
278a7cc72afSBarry Smith   if (opt) {
27983a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
28083a4ac43SBarry Smith     PetscInt         howoften = 1;
281a80ad3e0SBarry Smith 
2829566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2839566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2849566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
285bdad233fSMatthew Knepley   }
286fb1732b5SBarry Smith   opt = PETSC_FALSE;
2879566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2882d5ee99bSBarry Smith   if (opt) {
2892d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2902d5ee99bSBarry Smith     PetscReal        bounds[4];
2912d5ee99bSBarry Smith     PetscInt         n = 4;
2922d5ee99bSBarry Smith     PetscDraw        draw;
2936934998bSLisandro Dalcin     PetscDrawAxis    axis;
2942d5ee99bSBarry Smith 
2959566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2963c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2979566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2989566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
2999566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
3009566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
3019566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
3029566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3032d5ee99bSBarry Smith   }
3042d5ee99bSBarry Smith   opt = PETSC_FALSE;
3059566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3063a471f94SBarry Smith   if (opt) {
30783a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
30883a4ac43SBarry Smith     PetscInt         howoften = 1;
3093a471f94SBarry Smith 
3109566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3119566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3129566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3133a471f94SBarry Smith   }
3140ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3160ed3bfb6SBarry Smith   if (opt) {
3170ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3180ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3190ed3bfb6SBarry Smith 
3209566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3219566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
3229566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
3230ed3bfb6SBarry Smith   }
324fde5950dSBarry Smith 
325ed81e22dSJed Brown   opt = PETSC_FALSE;
32663a3b9bcSJacob 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));
327ed81e22dSJed Brown   if (flg) {
328*7f27e910SStefano Zampini     TSMonitorVTKCtx ctx;
329*7f27e910SStefano Zampini 
330*7f27e910SStefano Zampini     PetscCall(TSMonitorSolutionVTKCtxCreate(monfilename, &ctx));
331*7f27e910SStefano Zampini     PetscCall(PetscOptionsInt("-ts_monitor_solution_vtk_interval", "Save every interval time step", NULL, ctx->interval, &ctx->interval, NULL));
332*7f27e910SStefano Zampini     PetscCall(TSMonitorSet(ts, (PetscErrorCode(*)(TS, PetscInt, PetscReal, Vec, void *))TSMonitorSolutionVTK, ctx, (PetscErrorCode(*)(void **))TSMonitorSolutionVTKDestroy));
333ed81e22dSJed Brown   }
334bdad233fSMatthew Knepley 
3359566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
336d1212d36SBarry Smith   if (flg) {
337d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
338d1212d36SBarry Smith     int                  ray = 0;
3393ee9839eSMatthew G. Knepley     DMDirection          ddir;
340d1212d36SBarry Smith     DM                   da;
341d1212d36SBarry Smith     PetscMPIInt          rank;
342d1212d36SBarry Smith 
3433c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3443ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3453ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34698921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
347d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
348d1212d36SBarry Smith 
3499566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying DMDA ray %c = %d\n", dir[0], ray));
3509566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3519566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3529566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3539566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3541e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
35551b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3569566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
357d1212d36SBarry Smith   }
3589566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
35951b4a12fSMatthew G. Knepley   if (flg) {
36051b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
36151b4a12fSMatthew G. Knepley     int                  ray = 0;
3623ee9839eSMatthew G. Knepley     DMDirection          ddir;
36351b4a12fSMatthew G. Knepley     DM                   da;
36451b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
365d1212d36SBarry Smith 
3663c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3673ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3683ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
36998921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
37051b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3711c3436cfSJed Brown 
3729566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3739566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3749566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3759566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3769566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3779566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
37851b4a12fSMatthew G. Knepley   }
379a7a1495cSBarry Smith 
3809566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
381b3d3934dSBarry Smith   if (opt) {
382b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
383b3d3934dSBarry Smith 
3849566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
3859566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscErrorCode(*)(void **))TSMonitorEnvelopeCtxDestroy));
386b3d3934dSBarry Smith   }
387aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3899566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
390b3d3934dSBarry Smith 
391847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
392d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
393847ff0e1SMatthew G. Knepley   if (flg) {
394847ff0e1SMatthew G. Knepley     DM dm;
395847ff0e1SMatthew G. Knepley 
3969371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
3979371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
3989566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
3999566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
400847ff0e1SMatthew G. Knepley   }
401847ff0e1SMatthew G. Knepley 
402d763cef2SBarry Smith   /* Handle specific TS options */
403dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
404fbc52257SHong Zhang 
405a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4069566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4079566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
408dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
409a7bdc993SLisandro Dalcin 
41068bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4114f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4131baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
414a05bf03eSHong Zhang 
415dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
416d763cef2SBarry Smith 
417d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
418dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
419d0609cedSBarry Smith   PetscOptionsEnd();
420d763cef2SBarry Smith 
4211baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
42268bece0bSHong Zhang 
4231ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4249566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4251ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4269566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4279566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4281ef27442SStefano Zampini   }
4299566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
431d763cef2SBarry Smith }
432d763cef2SBarry Smith 
433d2daff3dSHong Zhang /*@
434bcf0153eSBarry Smith   TSGetTrajectory - Gets the trajectory from a `TS` if it exists
43578fbdcc8SBarry Smith 
436c3339decSBarry Smith   Collective
43778fbdcc8SBarry Smith 
4382fe279fdSBarry Smith   Input Parameter:
439bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
44078fbdcc8SBarry Smith 
4412fe279fdSBarry Smith   Output Parameter:
442bcf0153eSBarry Smith . tr - the `TSTrajectory` object, if it exists
44378fbdcc8SBarry Smith 
44478fbdcc8SBarry Smith   Level: advanced
44578fbdcc8SBarry Smith 
446bcf0153eSBarry Smith   Note:
447bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
44878fbdcc8SBarry Smith 
449b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
45078fbdcc8SBarry Smith @*/
451d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
452d71ae5a4SJacob Faibussowitsch {
45378fbdcc8SBarry Smith   PetscFunctionBegin;
45478fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45578fbdcc8SBarry Smith   *tr = ts->trajectory;
4563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45778fbdcc8SBarry Smith }
45878fbdcc8SBarry Smith 
45978fbdcc8SBarry Smith /*@
460bcf0153eSBarry Smith   TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
461d2daff3dSHong Zhang 
462c3339decSBarry Smith   Collective
463d2daff3dSHong Zhang 
464f899ff85SJose E. Roman   Input Parameter:
465bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
466bc952696SBarry Smith 
467bcf0153eSBarry Smith   Options Database Keys:
46878fbdcc8SBarry Smith + -ts_save_trajectory      - saves the trajectory to a file
46967b8a455SSatish Balay - -ts_trajectory_type type - set trajectory type
47078fbdcc8SBarry Smith 
471d2daff3dSHong Zhang   Level: intermediate
472d2daff3dSHong Zhang 
473bcf0153eSBarry Smith   Notes:
474bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
475d2daff3dSHong Zhang 
476bcf0153eSBarry Smith   The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
477bcf0153eSBarry Smith   MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
478bcf0153eSBarry Smith 
4791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
480d2daff3dSHong Zhang @*/
481d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
482d71ae5a4SJacob Faibussowitsch {
483d2daff3dSHong Zhang   PetscFunctionBegin;
484d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48563a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
487d2daff3dSHong Zhang }
488d2daff3dSHong Zhang 
489a7a1495cSBarry Smith /*@
490bcf0153eSBarry Smith   TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
4912d29f1f2SStefano Zampini 
492c3339decSBarry Smith   Collective
4932d29f1f2SStefano Zampini 
4942fe279fdSBarry Smith   Input Parameter:
495bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4962d29f1f2SStefano Zampini 
4972d29f1f2SStefano Zampini   Level: intermediate
4982d29f1f2SStefano Zampini 
4991cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5002d29f1f2SStefano Zampini @*/
501d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
502d71ae5a4SJacob Faibussowitsch {
5032d29f1f2SStefano Zampini   PetscFunctionBegin;
5042d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5052d29f1f2SStefano Zampini   if (ts->trajectory) {
5069566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5079566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5082d29f1f2SStefano Zampini   }
5093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5102d29f1f2SStefano Zampini }
5112d29f1f2SStefano Zampini 
5122d29f1f2SStefano Zampini /*@
513195e9b02SBarry Smith   TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
51467a3cfb0SHong Zhang 
515c3339decSBarry Smith   Collective
51667a3cfb0SHong Zhang 
5172fe279fdSBarry Smith   Input Parameter:
518bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
51967a3cfb0SHong Zhang 
52067a3cfb0SHong Zhang   Level: intermediate
52167a3cfb0SHong Zhang 
5221cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
52367a3cfb0SHong Zhang @*/
524d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
525d71ae5a4SJacob Faibussowitsch {
52667a3cfb0SHong Zhang   PetscFunctionBegin;
52767a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5281e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53067a3cfb0SHong Zhang }
53167a3cfb0SHong Zhang 
53267a3cfb0SHong Zhang /*@
533a7a1495cSBarry Smith   TSComputeRHSJacobian - Computes the Jacobian matrix that has been
534bcf0153eSBarry Smith   set with `TSSetRHSJacobian()`.
535a7a1495cSBarry Smith 
536c3339decSBarry Smith   Collective
537a7a1495cSBarry Smith 
538a7a1495cSBarry Smith   Input Parameters:
539bcf0153eSBarry Smith + ts - the `TS` context
540a7a1495cSBarry Smith . t  - current timestep
5410910c330SBarry Smith - U  - input vector
542a7a1495cSBarry Smith 
543a7a1495cSBarry Smith   Output Parameters:
544a7a1495cSBarry Smith + A - Jacobian matrix
5456b867d5aSJose E. Roman - B - optional preconditioning matrix
546a7a1495cSBarry Smith 
547bcf0153eSBarry Smith   Level: developer
548bcf0153eSBarry Smith 
549bcf0153eSBarry Smith   Note:
550a7a1495cSBarry Smith   Most users should not need to explicitly call this routine, as it
551a7a1495cSBarry Smith   is used internally within the nonlinear solvers.
552a7a1495cSBarry Smith 
5531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
554a7a1495cSBarry Smith @*/
555d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
556d71ae5a4SJacob Faibussowitsch {
557270bf2e7SJed Brown   PetscObjectState Ustate;
5586c1e1eecSBarry Smith   PetscObjectId    Uid;
55924989b8cSPeter Brune   DM               dm;
560942e3340SBarry Smith   DMTS             tsdm;
5618434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobianfunc;
56224989b8cSPeter Brune   void            *ctx;
5638434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
564a7a1495cSBarry Smith 
565a7a1495cSBarry Smith   PetscFunctionBegin;
5660700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5670910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5680910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5699566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5709566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5719566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5729566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5739566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5749566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
575971015bcSStefano Zampini 
5763ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
577d90be118SSean Farley 
57863a3b9bcSJacob 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);
57924989b8cSPeter Brune   if (rhsjacobianfunc) {
580da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
581792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
582a6ab3590SBarry Smith     ts->rhsjacs++;
583da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
584ef66eb69SBarry Smith   } else {
5859566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5869566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
587ef66eb69SBarry Smith   }
5880e4ef248SJed Brown   ts->rhsjacobian.time  = t;
589971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
590971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5919566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
5929566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
5933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
594a7a1495cSBarry Smith }
595a7a1495cSBarry Smith 
596316643e7SJed Brown /*@
597bcf0153eSBarry Smith   TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
598d763cef2SBarry Smith 
599c3339decSBarry Smith   Collective
600316643e7SJed Brown 
601316643e7SJed Brown   Input Parameters:
602bcf0153eSBarry Smith + ts - the `TS` context
603316643e7SJed Brown . t  - current time
6040910c330SBarry Smith - U  - state vector
605316643e7SJed Brown 
606316643e7SJed Brown   Output Parameter:
607dd8e379bSPierre Jolivet . y - right-hand side
608316643e7SJed Brown 
609bcf0153eSBarry Smith   Level: developer
610bcf0153eSBarry Smith 
611316643e7SJed Brown   Note:
612316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
613316643e7SJed Brown   is used internally within the nonlinear solvers.
614316643e7SJed Brown 
6151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
616316643e7SJed Brown @*/
617d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
618d71ae5a4SJacob Faibussowitsch {
6198434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
6208434afd1SBarry Smith   TSIFunctionFn   *ifunction;
62124989b8cSPeter Brune   void            *ctx;
62224989b8cSPeter Brune   DM               dm;
62324989b8cSPeter Brune 
624d763cef2SBarry Smith   PetscFunctionBegin;
6250700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6260910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6270700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6289566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6299566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6309566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
631d763cef2SBarry Smith 
6323c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
633d763cef2SBarry Smith 
63424989b8cSPeter Brune   if (rhsfunction) {
635da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, y, 0));
6369566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
637792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6389566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
639a6ab3590SBarry Smith     ts->rhsfuncs++;
640da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, y, 0));
6411e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
643d763cef2SBarry Smith }
644d763cef2SBarry Smith 
645ef20d060SBarry Smith /*@
646ef20d060SBarry Smith   TSComputeSolutionFunction - Evaluates the solution function.
647ef20d060SBarry Smith 
648c3339decSBarry Smith   Collective
649ef20d060SBarry Smith 
650ef20d060SBarry Smith   Input Parameters:
651bcf0153eSBarry Smith + ts - the `TS` context
652ef20d060SBarry Smith - t  - current time
653ef20d060SBarry Smith 
654ef20d060SBarry Smith   Output Parameter:
6550910c330SBarry Smith . U - the solution
656ef20d060SBarry Smith 
657ef20d060SBarry Smith   Level: developer
658ef20d060SBarry Smith 
6591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
660ef20d060SBarry Smith @*/
661d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
662d71ae5a4SJacob Faibussowitsch {
6638434afd1SBarry Smith   TSSolutionFn *solutionfunction;
664ef20d060SBarry Smith   void         *ctx;
665ef20d060SBarry Smith   DM            dm;
666ef20d060SBarry Smith 
667ef20d060SBarry Smith   PetscFunctionBegin;
668ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6690910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6709566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6719566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
672792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
674ef20d060SBarry Smith }
6759b7cd975SBarry Smith /*@
6769b7cd975SBarry Smith   TSComputeForcingFunction - Evaluates the forcing function.
6779b7cd975SBarry Smith 
678c3339decSBarry Smith   Collective
6799b7cd975SBarry Smith 
6809b7cd975SBarry Smith   Input Parameters:
681bcf0153eSBarry Smith + ts - the `TS` context
6829b7cd975SBarry Smith - t  - current time
6839b7cd975SBarry Smith 
6849b7cd975SBarry Smith   Output Parameter:
6859b7cd975SBarry Smith . U - the function value
6869b7cd975SBarry Smith 
6879b7cd975SBarry Smith   Level: developer
6889b7cd975SBarry Smith 
6891cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6909b7cd975SBarry Smith @*/
691d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
692d71ae5a4SJacob Faibussowitsch {
6939b7cd975SBarry Smith   void        *ctx;
6949b7cd975SBarry Smith   DM           dm;
6958434afd1SBarry Smith   TSForcingFn *forcing;
6969b7cd975SBarry Smith 
6979b7cd975SBarry Smith   PetscFunctionBegin;
6989b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6999b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7009566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7019566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7029b7cd975SBarry Smith 
703792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7059b7cd975SBarry Smith }
706ef20d060SBarry Smith 
707d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
708d71ae5a4SJacob Faibussowitsch {
709214bc6a2SJed Brown   Mat            A, B;
7108434afd1SBarry Smith   TSIJacobianFn *ijacobian;
711214bc6a2SJed Brown 
712214bc6a2SJed Brown   PetscFunctionBegin;
713c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
714c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7159566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
716214bc6a2SJed Brown   if (Arhs) {
717214bc6a2SJed Brown     if (!ts->Arhs) {
71841a1d4d2SBarry Smith       if (ijacobian) {
7199566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7209566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
72141a1d4d2SBarry Smith       } else {
72241a1d4d2SBarry Smith         ts->Arhs = A;
7239566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
72441a1d4d2SBarry Smith       }
7253565c898SBarry Smith     } else {
7263565c898SBarry Smith       PetscBool flg;
7279566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7283565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7293565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7309566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7313565c898SBarry Smith         ts->Arhs = A;
7329566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7333565c898SBarry Smith       }
734214bc6a2SJed Brown     }
735214bc6a2SJed Brown     *Arhs = ts->Arhs;
736214bc6a2SJed Brown   }
737214bc6a2SJed Brown   if (Brhs) {
738214bc6a2SJed Brown     if (!ts->Brhs) {
739bdb70873SJed Brown       if (A != B) {
74041a1d4d2SBarry Smith         if (ijacobian) {
7419566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
742bdb70873SJed Brown         } else {
74341a1d4d2SBarry Smith           ts->Brhs = B;
7449566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
74541a1d4d2SBarry Smith         }
74641a1d4d2SBarry Smith       } else {
7479566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
74851699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
749bdb70873SJed Brown       }
750214bc6a2SJed Brown     }
751214bc6a2SJed Brown     *Brhs = ts->Brhs;
752214bc6a2SJed Brown   }
7533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
754214bc6a2SJed Brown }
755214bc6a2SJed Brown 
756316643e7SJed Brown /*@
757195e9b02SBarry Smith   TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
758316643e7SJed Brown 
759c3339decSBarry Smith   Collective
760316643e7SJed Brown 
761316643e7SJed Brown   Input Parameters:
762bcf0153eSBarry Smith + ts   - the `TS` context
763316643e7SJed Brown . t    - current time
7640910c330SBarry Smith . U    - state vector
7650910c330SBarry Smith . Udot - time derivative of state vector
766bcf0153eSBarry Smith - imex - flag indicates if the method is `TSIMEX` so that the RHSFunction should be kept separate
767316643e7SJed Brown 
768316643e7SJed Brown   Output Parameter:
769dd8e379bSPierre Jolivet . Y - right-hand side
770316643e7SJed Brown 
771bcf0153eSBarry Smith   Level: developer
772bcf0153eSBarry Smith 
773316643e7SJed Brown   Note:
774316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
775316643e7SJed Brown   is used internally within the nonlinear solvers.
776316643e7SJed Brown 
77715229ffcSPierre Jolivet   If the user did not write their equations in implicit form, this
778316643e7SJed Brown   function recasts them in implicit form.
779316643e7SJed Brown 
7801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
781316643e7SJed Brown @*/
782d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
783d71ae5a4SJacob Faibussowitsch {
7848434afd1SBarry Smith   TSIFunctionFn   *ifunction;
7858434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
78624989b8cSPeter Brune   void            *ctx;
78724989b8cSPeter Brune   DM               dm;
788316643e7SJed Brown 
789316643e7SJed Brown   PetscFunctionBegin;
7900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7910910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7920910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
7930700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
794316643e7SJed Brown 
7959566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7969566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
7979566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
79824989b8cSPeter Brune 
7993c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
800d90be118SSean Farley 
801da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, Udot, Y));
80224989b8cSPeter Brune   if (ifunction) {
803792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
804a6ab3590SBarry Smith     ts->ifuncs++;
805214bc6a2SJed Brown   }
806214bc6a2SJed Brown   if (imex) {
8071e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
80824989b8cSPeter Brune   } else if (rhsfunction) {
80924989b8cSPeter Brune     if (ifunction) {
810214bc6a2SJed Brown       Vec Frhs;
8118af0501fSStefano Zampini 
8128af0501fSStefano Zampini       PetscCall(DMGetGlobalVector(dm, &Frhs));
8139566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8149566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8158af0501fSStefano Zampini       PetscCall(DMRestoreGlobalVector(dm, &Frhs));
8162dd45cf8SJed Brown     } else {
8179566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8189566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
819316643e7SJed Brown     }
8204a6899ffSJed Brown   }
821da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, Udot, Y));
8223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
823316643e7SJed Brown }
824316643e7SJed Brown 
825cfa8a9a2SHong Zhang /*
826195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
827cfa8a9a2SHong Zhang 
828cfa8a9a2SHong Zhang    Note:
829195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
830cfa8a9a2SHong Zhang 
831cfa8a9a2SHong Zhang */
832d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
833d71ae5a4SJacob Faibussowitsch {
834cfa8a9a2SHong Zhang   PetscFunctionBegin;
835cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8363c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8373c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
838cfa8a9a2SHong Zhang 
8391baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
84048a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
841cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8421baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8431e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
844cfa8a9a2SHong Zhang   }
845cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
846cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
848cfa8a9a2SHong Zhang }
849cfa8a9a2SHong Zhang 
850316643e7SJed Brown /*@
851316643e7SJed Brown   TSComputeIJacobian - Evaluates the Jacobian of the DAE
852316643e7SJed Brown 
853c3339decSBarry Smith   Collective
854316643e7SJed Brown 
855316643e7SJed Brown   Input Parameters:
856bcf0153eSBarry Smith + ts    - the `TS` context
857316643e7SJed Brown . t     - current timestep
8580910c330SBarry Smith . U     - state vector
8590910c330SBarry Smith . Udot  - time derivative of state vector
860214bc6a2SJed Brown . shift - shift to apply, see note below
861bcf0153eSBarry Smith - imex  - flag indicates if the method is `TSIMEX` so that the RHSJacobian should be kept separate
862316643e7SJed Brown 
863316643e7SJed Brown   Output Parameters:
864316643e7SJed Brown + A - Jacobian matrix
865195e9b02SBarry Smith - B - matrix from which the preconditioner is constructed; often the same as `A`
866316643e7SJed Brown 
867bcf0153eSBarry Smith   Level: developer
868bcf0153eSBarry Smith 
869316643e7SJed Brown   Notes:
8700910c330SBarry Smith   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
871195e9b02SBarry Smith .vb
8720910c330SBarry Smith    dF/dU + shift*dF/dUdot
873195e9b02SBarry Smith .ve
874316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
875316643e7SJed Brown   is used internally within the nonlinear solvers.
876316643e7SJed Brown 
8771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
87863495f91SJed Brown @*/
879d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
880d71ae5a4SJacob Faibussowitsch {
8818434afd1SBarry Smith   TSIJacobianFn   *ijacobian;
8828434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
88324989b8cSPeter Brune   DM               dm;
88424989b8cSPeter Brune   void            *ctx;
885316643e7SJed Brown 
886316643e7SJed Brown   PetscFunctionBegin;
8870700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8880910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8890910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
89094ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
89194ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
89224989b8cSPeter Brune 
8939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8949566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
8959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
89624989b8cSPeter Brune 
8973c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
898316643e7SJed Brown 
899da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
90024989b8cSPeter Brune   if (ijacobian) {
901792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
902a6ab3590SBarry Smith     ts->ijacs++;
9034a6899ffSJed Brown   }
904214bc6a2SJed Brown   if (imex) {
905b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9064c26be97Sstefano_zampini       PetscBool assembled;
907971015bcSStefano Zampini       if (rhsjacobian) {
908971015bcSStefano Zampini         Mat Arhs = NULL;
9099566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
910971015bcSStefano Zampini         if (A == Arhs) {
9113c633725SBarry 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 */
912971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
913971015bcSStefano Zampini         }
914971015bcSStefano Zampini       }
9159566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9169566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9174c26be97Sstefano_zampini       if (!assembled) {
9189566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9199566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9204c26be97Sstefano_zampini       }
9219566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
92294ab13aaSBarry Smith       if (A != B) {
9239566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9249566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9254c26be97Sstefano_zampini         if (!assembled) {
9269566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9279566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9284c26be97Sstefano_zampini         }
9299566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
930214bc6a2SJed Brown       }
931214bc6a2SJed Brown     }
932214bc6a2SJed Brown   } else {
933e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9341e66621cSBarry Smith 
9351e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9361e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
937e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
938e8b1e424SHong Zhang       PetscObjectState Ustate;
939e8b1e424SHong Zhang       PetscObjectId    Uid;
9408434afd1SBarry Smith       TSRHSFunctionFn *rhsfunction;
941e8b1e424SHong Zhang 
9429566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9439566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9449566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9459371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9469371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9479566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9481e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
949e8b1e424SHong Zhang       } else {
9503565c898SBarry Smith         PetscBool flg;
951e8b1e424SHong Zhang 
952e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
953e8b1e424SHong Zhang           /* MatScale has a short path for this case.
954e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
955e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9569566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
957e8b1e424SHong Zhang         }
9589566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9599566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9603565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9613565c898SBarry Smith         if (!flg) {
9629566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9639566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9643565c898SBarry Smith         }
96594ab13aaSBarry Smith         if (A != B) {
9669566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9679566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
968316643e7SJed Brown         }
969e8b1e424SHong Zhang       }
970e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
971e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
972d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
973e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9749566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9759566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
97694ab13aaSBarry Smith         if (A != B) {
9779566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9789566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
979214bc6a2SJed Brown         }
980316643e7SJed Brown       }
9819566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9829566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9831e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
984316643e7SJed Brown     }
985316643e7SJed Brown   }
986da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
9873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
988316643e7SJed Brown }
989316643e7SJed Brown 
990d763cef2SBarry Smith /*@C
991d763cef2SBarry Smith   TSSetRHSFunction - Sets the routine for evaluating the function,
992b5abc632SBarry Smith   where U_t = G(t,u).
993d763cef2SBarry Smith 
994c3339decSBarry Smith   Logically Collective
995d763cef2SBarry Smith 
996d763cef2SBarry Smith   Input Parameters:
997bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
998dd8e379bSPierre Jolivet . r   - vector to put the computed right-hand side (or `NULL` to have it created)
999d763cef2SBarry Smith . f   - routine for evaluating the right-hand-side function
1000195e9b02SBarry Smith - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1001d763cef2SBarry Smith 
1002d763cef2SBarry Smith   Level: beginner
1003d763cef2SBarry Smith 
1004bcf0153eSBarry Smith   Note:
1005bcf0153eSBarry Smith   You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10062bbac0d3SBarry Smith 
10078434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSFunctionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1008d763cef2SBarry Smith @*/
10098434afd1SBarry Smith PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunctionFn *f, void *ctx)
1010d71ae5a4SJacob Faibussowitsch {
1011089b2837SJed Brown   SNES snes;
10120298fd71SBarry Smith   Vec  ralloc = NULL;
101324989b8cSPeter Brune   DM   dm;
1014d763cef2SBarry Smith 
1015089b2837SJed Brown   PetscFunctionBegin;
10160700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1017ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
101824989b8cSPeter Brune 
10199566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10209566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10219566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1022e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10239566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1024e856ceecSJed Brown     r = ralloc;
1025e856ceecSJed Brown   }
10269566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10279566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1029d763cef2SBarry Smith }
1030d763cef2SBarry Smith 
1031ef20d060SBarry Smith /*@C
1032abd5a294SJed Brown   TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1033ef20d060SBarry Smith 
1034c3339decSBarry Smith   Logically Collective
1035ef20d060SBarry Smith 
1036ef20d060SBarry Smith   Input Parameters:
1037bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1038ef20d060SBarry Smith . f   - routine for evaluating the solution
1039ef20d060SBarry Smith - ctx - [optional] user-defined context for private data for the
1040195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1041ef20d060SBarry Smith 
1042bcf0153eSBarry Smith   Options Database Keys:
1043bcf0153eSBarry Smith + -ts_monitor_lg_error   - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1044bcf0153eSBarry Smith - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1045bcf0153eSBarry Smith 
1046bcf0153eSBarry Smith   Level: intermediate
10470ed3bfb6SBarry Smith 
1048abd5a294SJed Brown   Notes:
1049abd5a294SJed Brown   This routine is used for testing accuracy of time integration schemes when you already know the solution.
1050abd5a294SJed Brown   If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1051abd5a294SJed Brown   create closed-form solutions with non-physical forcing terms.
1052abd5a294SJed Brown 
1053bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1054abd5a294SJed Brown 
10558434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolutionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1056ef20d060SBarry Smith @*/
10578434afd1SBarry Smith PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFn *f, void *ctx)
1058d71ae5a4SJacob Faibussowitsch {
1059ef20d060SBarry Smith   DM dm;
1060ef20d060SBarry Smith 
1061ef20d060SBarry Smith   PetscFunctionBegin;
1062ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10639566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10649566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
10653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1066ef20d060SBarry Smith }
1067ef20d060SBarry Smith 
10689b7cd975SBarry Smith /*@C
10699b7cd975SBarry Smith   TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10709b7cd975SBarry Smith 
1071c3339decSBarry Smith   Logically Collective
10729b7cd975SBarry Smith 
10739b7cd975SBarry Smith   Input Parameters:
1074bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1075e162b725SBarry Smith . func - routine for evaluating the forcing function
107614d0ab18SJacob Faibussowitsch - ctx  - [optional] user-defined context for private data for the function evaluation routine
107714d0ab18SJacob Faibussowitsch          (may be `NULL`)
10789b7cd975SBarry Smith 
1079bcf0153eSBarry Smith   Level: intermediate
1080bcf0153eSBarry Smith 
10819b7cd975SBarry Smith   Notes:
10829b7cd975SBarry Smith   This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1083e162b725SBarry 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
1084e162b725SBarry Smith   definition of the problem you are solving and hence possibly introducing bugs.
1085e162b725SBarry Smith 
10868847d985SBarry Smith   This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1087e162b725SBarry Smith 
1088e162b725SBarry 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
1089e162b725SBarry Smith   parameters can be passed in the ctx variable.
10909b7cd975SBarry Smith 
1091bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
10929b7cd975SBarry Smith 
10938434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSForcingFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
109414d0ab18SJacob Faibussowitsch `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
10959b7cd975SBarry Smith @*/
10968434afd1SBarry Smith PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFn *func, void *ctx)
1097d71ae5a4SJacob Faibussowitsch {
10989b7cd975SBarry Smith   DM dm;
10999b7cd975SBarry Smith 
11009b7cd975SBarry Smith   PetscFunctionBegin;
11019b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11029566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11039566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11059b7cd975SBarry Smith }
11069b7cd975SBarry Smith 
1107d763cef2SBarry Smith /*@C
1108f7ab8db6SBarry Smith   TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1109b5abc632SBarry Smith   where U_t = G(U,t), as well as the location to store the matrix.
1110d763cef2SBarry Smith 
1111c3339decSBarry Smith   Logically Collective
1112d763cef2SBarry Smith 
1113d763cef2SBarry Smith   Input Parameters:
1114bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1115195e9b02SBarry Smith . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1116195e9b02SBarry Smith . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1117d763cef2SBarry Smith . f    - the Jacobian evaluation routine
1118195e9b02SBarry Smith - ctx  - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1119d763cef2SBarry Smith 
1120bcf0153eSBarry Smith   Level: beginner
1121bcf0153eSBarry Smith 
11226cd88445SBarry Smith   Notes:
11236cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11246cd88445SBarry Smith 
112514d0ab18SJacob Faibussowitsch   The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1126ca5f011dSBarry Smith   You should not assume the values are the same in the next call to f() as you set them in the previous call.
1127d763cef2SBarry Smith 
11288434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSJacobianFn`, `SNESComputeJacobianDefaultColor()`,
11298434afd1SBarry Smith `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunctionFn`, `TSIFunctionFn`
1130d763cef2SBarry Smith @*/
11318434afd1SBarry Smith PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobianFn *f, void *ctx)
1132d71ae5a4SJacob Faibussowitsch {
1133089b2837SJed Brown   SNES           snes;
113424989b8cSPeter Brune   DM             dm;
11358434afd1SBarry Smith   TSIJacobianFn *ijacobian;
1136277b19d0SLisandro Dalcin 
1137d763cef2SBarry Smith   PetscFunctionBegin;
11380700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1139e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1140e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1141e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1142e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1143d763cef2SBarry Smith 
11449566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11459566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11469566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11479566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11481e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1149e5d3d808SBarry Smith   if (Amat) {
11509566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11519566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1152e5d3d808SBarry Smith     ts->Arhs = Amat;
11530e4ef248SJed Brown   }
1154e5d3d808SBarry Smith   if (Pmat) {
11559566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11569566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1157e5d3d808SBarry Smith     ts->Brhs = Pmat;
11580e4ef248SJed Brown   }
11593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1160d763cef2SBarry Smith }
1161d763cef2SBarry Smith 
1162316643e7SJed Brown /*@C
1163b5abc632SBarry Smith   TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1164316643e7SJed Brown 
1165c3339decSBarry Smith   Logically Collective
1166316643e7SJed Brown 
1167316643e7SJed Brown   Input Parameters:
1168bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1169195e9b02SBarry Smith . r   - vector to hold the residual (or `NULL` to have it created internally)
1170316643e7SJed Brown . f   - the function evaluation routine
1171195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1172316643e7SJed Brown 
1173316643e7SJed Brown   Level: beginner
1174316643e7SJed Brown 
1175bcf0153eSBarry Smith   Note:
1176bcf0153eSBarry Smith   The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1177bcf0153eSBarry Smith 
11788434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIFunctionFn`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
117914d0ab18SJacob Faibussowitsch `TSSetIJacobian()`
1180316643e7SJed Brown @*/
11818434afd1SBarry Smith PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunctionFn *f, void *ctx)
1182d71ae5a4SJacob Faibussowitsch {
1183089b2837SJed Brown   SNES snes;
118451699248SLisandro Dalcin   Vec  ralloc = NULL;
118524989b8cSPeter Brune   DM   dm;
1186316643e7SJed Brown 
1187316643e7SJed Brown   PetscFunctionBegin;
11880700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
118951699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
119024989b8cSPeter Brune 
11919566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11929566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
119324989b8cSPeter Brune 
11949566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
119551699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
11969566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
119751699248SLisandro Dalcin     r = ralloc;
1198e856ceecSJed Brown   }
11999566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12009566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1202089b2837SJed Brown }
1203089b2837SJed Brown 
1204089b2837SJed Brown /*@C
1205a5b23f4aSJose E. Roman   TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1206089b2837SJed Brown 
1207089b2837SJed Brown   Not Collective
1208089b2837SJed Brown 
1209089b2837SJed Brown   Input Parameter:
1210bcf0153eSBarry Smith . ts - the `TS` context
1211089b2837SJed Brown 
1212d8d19677SJose E. Roman   Output Parameters:
1213195e9b02SBarry Smith + r    - vector to hold residual (or `NULL`)
1214195e9b02SBarry Smith . func - the function to compute residual (or `NULL`)
1215195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1216089b2837SJed Brown 
1217089b2837SJed Brown   Level: advanced
1218089b2837SJed Brown 
12191cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1220089b2837SJed Brown @*/
12218434afd1SBarry Smith PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunctionFn **func, void **ctx)
1222d71ae5a4SJacob Faibussowitsch {
1223089b2837SJed Brown   SNES snes;
122424989b8cSPeter Brune   DM   dm;
1225089b2837SJed Brown 
1226089b2837SJed Brown   PetscFunctionBegin;
1227089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12289566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12299566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12309566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12319566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1233089b2837SJed Brown }
1234089b2837SJed Brown 
1235089b2837SJed Brown /*@C
1236dd8e379bSPierre Jolivet   TSGetRHSFunction - Returns the vector where the right-hand side is stored and the function/context to compute it.
1237089b2837SJed Brown 
1238089b2837SJed Brown   Not Collective
1239089b2837SJed Brown 
1240089b2837SJed Brown   Input Parameter:
1241bcf0153eSBarry Smith . ts - the `TS` context
1242089b2837SJed Brown 
1243d8d19677SJose E. Roman   Output Parameters:
1244dd8e379bSPierre Jolivet + r    - vector to hold computed right-hand side (or `NULL`)
1245dd8e379bSPierre Jolivet . func - the function to compute right-hand side (or `NULL`)
1246195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1247089b2837SJed Brown 
1248089b2837SJed Brown   Level: advanced
1249089b2837SJed Brown 
12501cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1251089b2837SJed Brown @*/
12528434afd1SBarry Smith PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunctionFn **func, void **ctx)
1253d71ae5a4SJacob Faibussowitsch {
1254089b2837SJed Brown   SNES snes;
125524989b8cSPeter Brune   DM   dm;
1256089b2837SJed Brown 
1257089b2837SJed Brown   PetscFunctionBegin;
1258089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12599566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12609566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12619566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12629566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
12633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1264316643e7SJed Brown }
1265316643e7SJed Brown 
1266316643e7SJed Brown /*@C
1267a4f0a591SBarry Smith   TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1268bcf0153eSBarry Smith   provided with `TSSetIFunction()`.
1269316643e7SJed Brown 
1270c3339decSBarry Smith   Logically Collective
1271316643e7SJed Brown 
1272316643e7SJed Brown   Input Parameters:
1273bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1274aaa8cc7dSPierre Jolivet . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1275195e9b02SBarry Smith . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1276316643e7SJed Brown . f    - the Jacobian evaluation routine
1277195e9b02SBarry Smith - ctx  - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1278316643e7SJed Brown 
1279bcf0153eSBarry Smith   Level: beginner
1280316643e7SJed Brown 
1281bcf0153eSBarry Smith   Notes:
1282195e9b02SBarry Smith   The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1283bcf0153eSBarry Smith 
1284bcf0153eSBarry Smith   If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1285195e9b02SBarry Smith   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1286895c21f2SBarry Smith 
1287a4f0a591SBarry Smith   The matrix dF/dU + a*dF/dU_t you provide turns out to be
1288b5abc632SBarry Smith   the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1289a4f0a591SBarry Smith   The time integrator internally approximates U_t by W+a*U where the positive "shift"
1290a4f0a591SBarry Smith   a and vector W depend on the integration method, step size, and past states. For example with
1291a4f0a591SBarry Smith   the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1292a4f0a591SBarry Smith   W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1293a4f0a591SBarry Smith 
12946cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
12956cd88445SBarry Smith 
1296195e9b02SBarry Smith   The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1297195e9b02SBarry Smith   You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1298ca5f011dSBarry Smith 
1299bc7fdbb5SPierre Jolivet   In case `TSSetRHSJacobian()` is also used in conjunction with a fully-implicit solver,
1300d469ad21SStefano Zampini   multilevel linear solvers, e.g. `PCMG`, will likely not work due to the way `TS` handles rhs matrices.
1301d469ad21SStefano Zampini 
13028434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIJacobianFn`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
130314d0ab18SJacob Faibussowitsch `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1304316643e7SJed Brown @*/
13058434afd1SBarry Smith PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobianFn *f, void *ctx)
1306d71ae5a4SJacob Faibussowitsch {
1307089b2837SJed Brown   SNES snes;
130824989b8cSPeter Brune   DM   dm;
1309316643e7SJed Brown 
1310316643e7SJed Brown   PetscFunctionBegin;
13110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1312e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1313e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1314e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1315e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
131624989b8cSPeter Brune 
13179566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13189566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
131924989b8cSPeter Brune 
13209566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13219566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1323316643e7SJed Brown }
1324316643e7SJed Brown 
1325e1244c69SJed Brown /*@
13268434afd1SBarry Smith   TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobianFn` function again
1327e1244c69SJed Brown 
1328e1244c69SJed Brown   Logically Collective
1329e1244c69SJed Brown 
13304165533cSJose E. Roman   Input Parameters:
1331bcf0153eSBarry Smith + ts    - `TS` context obtained from `TSCreate()`
1332bcf0153eSBarry Smith - reuse - `PETSC_TRUE` if the RHS Jacobian
1333e1244c69SJed Brown 
1334e1244c69SJed Brown   Level: intermediate
1335e1244c69SJed Brown 
133614d0ab18SJacob Faibussowitsch   Notes:
133714d0ab18SJacob Faibussowitsch   Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
133814d0ab18SJacob Faibussowitsch   finite-time-step implicit solve, in which case the user function will need to recompute the
133914d0ab18SJacob Faibussowitsch   entire Jacobian.  The `reuse `flag must be set if the evaluation function assumes that the
134014d0ab18SJacob Faibussowitsch   matrix entries have not been changed by the `TS`.
134114d0ab18SJacob Faibussowitsch 
13421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1343e1244c69SJed Brown @*/
1344d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1345d71ae5a4SJacob Faibussowitsch {
1346e1244c69SJed Brown   PetscFunctionBegin;
1347e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
13483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1349e1244c69SJed Brown }
1350e1244c69SJed Brown 
1351efe9872eSLisandro Dalcin /*@C
1352efe9872eSLisandro Dalcin   TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1353efe9872eSLisandro Dalcin 
1354c3339decSBarry Smith   Logically Collective
1355efe9872eSLisandro Dalcin 
1356efe9872eSLisandro Dalcin   Input Parameters:
1357bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1358195e9b02SBarry Smith . F   - vector to hold the residual (or `NULL` to have it created internally)
1359efe9872eSLisandro Dalcin . fun - the function evaluation routine
1360195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1361efe9872eSLisandro Dalcin 
1362efe9872eSLisandro Dalcin   Level: beginner
1363efe9872eSLisandro Dalcin 
13648434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2FunctionFn`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
136514d0ab18SJacob Faibussowitsch `TSCreate()`, `TSSetRHSFunction()`
1366efe9872eSLisandro Dalcin @*/
13678434afd1SBarry Smith PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2FunctionFn *fun, void *ctx)
1368d71ae5a4SJacob Faibussowitsch {
1369efe9872eSLisandro Dalcin   DM dm;
1370efe9872eSLisandro Dalcin 
1371efe9872eSLisandro Dalcin   PetscFunctionBegin;
1372efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1373efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
13749566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
13759566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13769566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
13773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1378efe9872eSLisandro Dalcin }
1379efe9872eSLisandro Dalcin 
1380efe9872eSLisandro Dalcin /*@C
1381a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1382efe9872eSLisandro Dalcin 
1383efe9872eSLisandro Dalcin   Not Collective
1384efe9872eSLisandro Dalcin 
1385efe9872eSLisandro Dalcin   Input Parameter:
1386bcf0153eSBarry Smith . ts - the `TS` context
1387efe9872eSLisandro Dalcin 
1388d8d19677SJose E. Roman   Output Parameters:
1389195e9b02SBarry Smith + r   - vector to hold residual (or `NULL`)
1390195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1391195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1392efe9872eSLisandro Dalcin 
1393efe9872eSLisandro Dalcin   Level: advanced
1394efe9872eSLisandro Dalcin 
13951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1396efe9872eSLisandro Dalcin @*/
13978434afd1SBarry Smith PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2FunctionFn **fun, void **ctx)
1398d71ae5a4SJacob Faibussowitsch {
1399efe9872eSLisandro Dalcin   SNES snes;
1400efe9872eSLisandro Dalcin   DM   dm;
1401efe9872eSLisandro Dalcin 
1402efe9872eSLisandro Dalcin   PetscFunctionBegin;
1403efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14049566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14059566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14069566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14079566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1409efe9872eSLisandro Dalcin }
1410efe9872eSLisandro Dalcin 
1411efe9872eSLisandro Dalcin /*@C
1412bc77d74cSLisandro Dalcin   TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1413bcf0153eSBarry Smith   where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1414efe9872eSLisandro Dalcin 
1415c3339decSBarry Smith   Logically Collective
1416efe9872eSLisandro Dalcin 
1417efe9872eSLisandro Dalcin   Input Parameters:
1418bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1419195e9b02SBarry Smith . J   - matrix to hold the Jacobian values
1420195e9b02SBarry Smith . P   - matrix for constructing the preconditioner (may be same as `J`)
14218434afd1SBarry Smith . jac - the Jacobian evaluation routine, see `TSI2JacobianFn` for the calling sequence
1422195e9b02SBarry Smith - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1423efe9872eSLisandro Dalcin 
1424bcf0153eSBarry Smith   Level: beginner
1425bcf0153eSBarry Smith 
1426efe9872eSLisandro Dalcin   Notes:
1427195e9b02SBarry Smith   The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1428efe9872eSLisandro Dalcin 
1429efe9872eSLisandro Dalcin   The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1430efe9872eSLisandro 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.
1431efe9872eSLisandro Dalcin   The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1432bc77d74cSLisandro Dalcin   parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1433efe9872eSLisandro Dalcin 
14348434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2JacobianFn`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1435efe9872eSLisandro Dalcin @*/
14368434afd1SBarry Smith PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2JacobianFn *jac, void *ctx)
1437d71ae5a4SJacob Faibussowitsch {
1438efe9872eSLisandro Dalcin   DM dm;
1439efe9872eSLisandro Dalcin 
1440efe9872eSLisandro Dalcin   PetscFunctionBegin;
1441efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1442efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1443efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
14449566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
14459566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14469566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
14473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1448efe9872eSLisandro Dalcin }
1449efe9872eSLisandro Dalcin 
1450efe9872eSLisandro Dalcin /*@C
1451efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1452efe9872eSLisandro Dalcin 
1453bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1454efe9872eSLisandro Dalcin 
1455efe9872eSLisandro Dalcin   Input Parameter:
1456bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
1457efe9872eSLisandro Dalcin 
1458efe9872eSLisandro Dalcin   Output Parameters:
1459efe9872eSLisandro Dalcin + J   - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1460195e9b02SBarry Smith . P   - The matrix from which the preconditioner is constructed, often the same as `J`
1461efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1462efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1463efe9872eSLisandro Dalcin 
1464bcf0153eSBarry Smith   Level: advanced
1465bcf0153eSBarry Smith 
1466195e9b02SBarry Smith   Note:
1467195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
1468efe9872eSLisandro Dalcin 
14691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1470efe9872eSLisandro Dalcin @*/
14718434afd1SBarry Smith PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2JacobianFn **jac, void **ctx)
1472d71ae5a4SJacob Faibussowitsch {
1473efe9872eSLisandro Dalcin   SNES snes;
1474efe9872eSLisandro Dalcin   DM   dm;
1475efe9872eSLisandro Dalcin 
1476efe9872eSLisandro Dalcin   PetscFunctionBegin;
14779566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14789566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
14799566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
14809566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14819566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
14823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1483efe9872eSLisandro Dalcin }
1484efe9872eSLisandro Dalcin 
1485efe9872eSLisandro Dalcin /*@
1486efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1487efe9872eSLisandro Dalcin 
1488c3339decSBarry Smith   Collective
1489efe9872eSLisandro Dalcin 
1490efe9872eSLisandro Dalcin   Input Parameters:
1491bcf0153eSBarry Smith + ts - the `TS` context
1492efe9872eSLisandro Dalcin . t  - current time
1493efe9872eSLisandro Dalcin . U  - state vector
1494efe9872eSLisandro Dalcin . V  - time derivative of state vector (U_t)
1495efe9872eSLisandro Dalcin - A  - second time derivative of state vector (U_tt)
1496efe9872eSLisandro Dalcin 
1497efe9872eSLisandro Dalcin   Output Parameter:
1498efe9872eSLisandro Dalcin . F - the residual vector
1499efe9872eSLisandro Dalcin 
1500bcf0153eSBarry Smith   Level: developer
1501bcf0153eSBarry Smith 
1502efe9872eSLisandro Dalcin   Note:
1503efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1504efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1505efe9872eSLisandro Dalcin 
15061cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1507efe9872eSLisandro Dalcin @*/
1508d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1509d71ae5a4SJacob Faibussowitsch {
1510efe9872eSLisandro Dalcin   DM               dm;
15118434afd1SBarry Smith   TSI2FunctionFn  *I2Function;
1512efe9872eSLisandro Dalcin   void            *ctx;
15138434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
1514efe9872eSLisandro Dalcin 
1515efe9872eSLisandro Dalcin   PetscFunctionBegin;
1516efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1517efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1518efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1519efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1520efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1521efe9872eSLisandro Dalcin 
15229566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15239566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15249566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1525efe9872eSLisandro Dalcin 
1526efe9872eSLisandro Dalcin   if (!I2Function) {
15279566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
15283ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1529efe9872eSLisandro Dalcin   }
1530efe9872eSLisandro Dalcin 
1531da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, V, F));
1532efe9872eSLisandro Dalcin 
1533792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1534efe9872eSLisandro Dalcin 
1535efe9872eSLisandro Dalcin   if (rhsfunction) {
1536efe9872eSLisandro Dalcin     Vec Frhs;
15378af0501fSStefano Zampini 
15388af0501fSStefano Zampini     PetscCall(DMGetGlobalVector(dm, &Frhs));
15399566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15409566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
15418af0501fSStefano Zampini     PetscCall(DMRestoreGlobalVector(dm, &Frhs));
1542efe9872eSLisandro Dalcin   }
1543efe9872eSLisandro Dalcin 
1544da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, V, F));
15453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1546efe9872eSLisandro Dalcin }
1547efe9872eSLisandro Dalcin 
1548efe9872eSLisandro Dalcin /*@
1549efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1550efe9872eSLisandro Dalcin 
1551c3339decSBarry Smith   Collective
1552efe9872eSLisandro Dalcin 
1553efe9872eSLisandro Dalcin   Input Parameters:
1554bcf0153eSBarry Smith + ts     - the `TS` context
1555efe9872eSLisandro Dalcin . t      - current timestep
1556efe9872eSLisandro Dalcin . U      - state vector
1557efe9872eSLisandro Dalcin . V      - time derivative of state vector
1558efe9872eSLisandro Dalcin . A      - second time derivative of state vector
1559efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1560efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1561efe9872eSLisandro Dalcin 
1562efe9872eSLisandro Dalcin   Output Parameters:
1563efe9872eSLisandro Dalcin + J - Jacobian matrix
1564efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1565efe9872eSLisandro Dalcin 
1566bcf0153eSBarry Smith   Level: developer
1567bcf0153eSBarry Smith 
1568efe9872eSLisandro Dalcin   Notes:
1569efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1570efe9872eSLisandro Dalcin 
1571efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1572efe9872eSLisandro Dalcin 
1573efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1574efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1575efe9872eSLisandro Dalcin 
15761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1577efe9872eSLisandro Dalcin @*/
1578d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1579d71ae5a4SJacob Faibussowitsch {
1580efe9872eSLisandro Dalcin   DM               dm;
15818434afd1SBarry Smith   TSI2JacobianFn  *I2Jacobian;
1582efe9872eSLisandro Dalcin   void            *ctx;
15838434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
1584efe9872eSLisandro Dalcin 
1585efe9872eSLisandro Dalcin   PetscFunctionBegin;
1586efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1587efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1588efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1589efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1590efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1591efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1592efe9872eSLisandro Dalcin 
15939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15949566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
15959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1596efe9872eSLisandro Dalcin 
1597efe9872eSLisandro Dalcin   if (!I2Jacobian) {
15989566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
15993ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1600efe9872eSLisandro Dalcin   }
1601efe9872eSLisandro Dalcin 
1602da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, J, P));
1603792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1604efe9872eSLisandro Dalcin   if (rhsjacobian) {
1605d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16069566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16079566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16089566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16099566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1610efe9872eSLisandro Dalcin   }
1611efe9872eSLisandro Dalcin 
1612da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, J, P));
16133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1614efe9872eSLisandro Dalcin }
1615efe9872eSLisandro Dalcin 
1616438f35afSJed Brown /*@C
1617438f35afSJed Brown   TSSetTransientVariable - sets function to transform from state to transient variables
1618438f35afSJed Brown 
1619438f35afSJed Brown   Logically Collective
1620438f35afSJed Brown 
16214165533cSJose E. Roman   Input Parameters:
1622438f35afSJed Brown + ts   - time stepping context on which to change the transient variable
16238434afd1SBarry Smith . tvar - a function that transforms to transient variables, see `TSTransientVariableFn` for the calling sequence
1624438f35afSJed Brown - ctx  - a context for tvar
1625438f35afSJed Brown 
1626438f35afSJed Brown   Level: advanced
1627438f35afSJed Brown 
1628438f35afSJed Brown   Notes:
1629bcf0153eSBarry Smith   This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1630438f35afSJed Brown   can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1631438f35afSJed Brown   well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1632438f35afSJed Brown   C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1633438f35afSJed Brown   evaluated via the chain rule, as in
1634195e9b02SBarry Smith .vb
1635438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1636195e9b02SBarry Smith .ve
1637438f35afSJed Brown 
16388434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariableFn`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1639438f35afSJed Brown @*/
16408434afd1SBarry Smith PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariableFn *tvar, void *ctx)
1641d71ae5a4SJacob Faibussowitsch {
1642438f35afSJed Brown   DM dm;
1643438f35afSJed Brown 
1644438f35afSJed Brown   PetscFunctionBegin;
1645438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
16469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16479566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
16483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1649438f35afSJed Brown }
1650438f35afSJed Brown 
1651efe9872eSLisandro Dalcin /*@
1652e3c11fc1SJed Brown   TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1653e3c11fc1SJed Brown 
1654e3c11fc1SJed Brown   Logically Collective
1655e3c11fc1SJed Brown 
1656e3c11fc1SJed Brown   Input Parameters:
1657e3c11fc1SJed Brown + ts - TS on which to compute
1658e3c11fc1SJed Brown - U  - state vector to be transformed to transient variables
1659e3c11fc1SJed Brown 
16602fe279fdSBarry Smith   Output Parameter:
1661e3c11fc1SJed Brown . C - transient (conservative) variable
1662e3c11fc1SJed Brown 
1663e3c11fc1SJed Brown   Level: developer
1664e3c11fc1SJed Brown 
1665b43aa488SJacob Faibussowitsch   Developer Notes:
1666195e9b02SBarry Smith   If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1667bcf0153eSBarry Smith   This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1668bcf0153eSBarry Smith   being used.
1669bcf0153eSBarry Smith 
16701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1671e3c11fc1SJed Brown @*/
1672d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1673d71ae5a4SJacob Faibussowitsch {
1674e3c11fc1SJed Brown   DM   dm;
1675e3c11fc1SJed Brown   DMTS dmts;
1676e3c11fc1SJed Brown 
1677e3c11fc1SJed Brown   PetscFunctionBegin;
1678e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1679e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
16809566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16819566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1682e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1683e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
16849566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1685e3c11fc1SJed Brown   }
16863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1687e3c11fc1SJed Brown }
1688e3c11fc1SJed Brown 
1689e3c11fc1SJed Brown /*@
1690e3c11fc1SJed Brown   TSHasTransientVariable - determine whether transient variables have been set
1691e3c11fc1SJed Brown 
1692e3c11fc1SJed Brown   Logically Collective
1693e3c11fc1SJed Brown 
16942fe279fdSBarry Smith   Input Parameter:
1695195e9b02SBarry Smith . ts - `TS` on which to compute
1696e3c11fc1SJed Brown 
16972fe279fdSBarry Smith   Output Parameter:
1698bcf0153eSBarry Smith . has - `PETSC_TRUE` if transient variables have been set
1699e3c11fc1SJed Brown 
1700e3c11fc1SJed Brown   Level: developer
1701e3c11fc1SJed Brown 
17021cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1703e3c11fc1SJed Brown @*/
1704d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1705d71ae5a4SJacob Faibussowitsch {
1706e3c11fc1SJed Brown   DM   dm;
1707e3c11fc1SJed Brown   DMTS dmts;
1708e3c11fc1SJed Brown 
1709e3c11fc1SJed Brown   PetscFunctionBegin;
1710e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17119566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17129566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1713e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
17143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1715e3c11fc1SJed Brown }
1716e3c11fc1SJed Brown 
1717e3c11fc1SJed Brown /*@
1718efe9872eSLisandro Dalcin   TS2SetSolution - Sets the initial solution and time derivative vectors
1719bcf0153eSBarry Smith   for use by the `TS` routines handling second order equations.
1720efe9872eSLisandro Dalcin 
1721c3339decSBarry Smith   Logically Collective
1722efe9872eSLisandro Dalcin 
1723efe9872eSLisandro Dalcin   Input Parameters:
1724bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
1725efe9872eSLisandro Dalcin . u  - the solution vector
1726efe9872eSLisandro Dalcin - v  - the time derivative vector
1727efe9872eSLisandro Dalcin 
1728efe9872eSLisandro Dalcin   Level: beginner
1729efe9872eSLisandro Dalcin 
17301cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
1731efe9872eSLisandro Dalcin @*/
1732d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1733d71ae5a4SJacob Faibussowitsch {
1734efe9872eSLisandro Dalcin   PetscFunctionBegin;
1735efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1736efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1737efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
17389566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
17399566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
17409566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1741efe9872eSLisandro Dalcin   ts->vec_dot = v;
17423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1743efe9872eSLisandro Dalcin }
1744efe9872eSLisandro Dalcin 
1745efe9872eSLisandro Dalcin /*@
1746efe9872eSLisandro Dalcin   TS2GetSolution - Returns the solution and time derivative at the present timestep
174714d0ab18SJacob Faibussowitsch   for second order equations.
1748efe9872eSLisandro Dalcin 
174914d0ab18SJacob Faibussowitsch   Not Collective
1750efe9872eSLisandro Dalcin 
1751efe9872eSLisandro Dalcin   Input Parameter:
1752bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
1753efe9872eSLisandro Dalcin 
1754d8d19677SJose E. Roman   Output Parameters:
1755efe9872eSLisandro Dalcin + u - the vector containing the solution
1756efe9872eSLisandro Dalcin - v - the vector containing the time derivative
1757efe9872eSLisandro Dalcin 
1758efe9872eSLisandro Dalcin   Level: intermediate
1759efe9872eSLisandro Dalcin 
176014d0ab18SJacob Faibussowitsch   Notes:
176114d0ab18SJacob Faibussowitsch   It is valid to call this routine inside the function
176214d0ab18SJacob Faibussowitsch   that you are evaluating in order to move to the new timestep. This vector not
176314d0ab18SJacob Faibussowitsch   changed until the solution at the next timestep has been calculated.
176414d0ab18SJacob Faibussowitsch 
17651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1766efe9872eSLisandro Dalcin @*/
1767d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1768d71ae5a4SJacob Faibussowitsch {
1769efe9872eSLisandro Dalcin   PetscFunctionBegin;
1770efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17714f572ea9SToby Isaac   if (u) PetscAssertPointer(u, 2);
17724f572ea9SToby Isaac   if (v) PetscAssertPointer(v, 3);
1773efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1774efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
17753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1776efe9872eSLisandro Dalcin }
1777efe9872eSLisandro Dalcin 
1778ffeef943SBarry Smith /*@
1779bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
178055849f57SBarry Smith 
1781c3339decSBarry Smith   Collective
178255849f57SBarry Smith 
178355849f57SBarry Smith   Input Parameters:
1784b43aa488SJacob Faibussowitsch + ts     - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1785bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1786bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
178755849f57SBarry Smith 
178855849f57SBarry Smith   Level: intermediate
178955849f57SBarry Smith 
1790bcf0153eSBarry Smith   Note:
1791bcf0153eSBarry Smith   The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
179255849f57SBarry Smith 
17931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
179455849f57SBarry Smith @*/
1795d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1796d71ae5a4SJacob Faibussowitsch {
179755849f57SBarry Smith   PetscBool isbinary;
179855849f57SBarry Smith   PetscInt  classid;
179955849f57SBarry Smith   char      type[256];
18002d53ad75SBarry Smith   DMTS      sdm;
1801ad6bc421SBarry Smith   DM        dm;
180255849f57SBarry Smith 
180355849f57SBarry Smith   PetscFunctionBegin;
1804f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
180555849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18069566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18073c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
180855849f57SBarry Smith 
18099566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18103c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18119566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18129566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1813dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18149566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18159566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18169566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18179566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18189566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18199566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18209566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
18213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
182255849f57SBarry Smith }
182355849f57SBarry Smith 
18249804daf3SBarry Smith #include <petscdraw.h>
1825e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1826e04113cfSBarry Smith   #include <petscviewersaws.h>
1827f05ece33SBarry Smith #endif
1828fe2efc57SMark 
1829ffeef943SBarry Smith /*@
1830bcf0153eSBarry Smith   TSViewFromOptions - View a `TS` based on values in the options database
1831fe2efc57SMark 
1832c3339decSBarry Smith   Collective
1833fe2efc57SMark 
1834fe2efc57SMark   Input Parameters:
1835bcf0153eSBarry Smith + ts   - the `TS` context
1836bcf0153eSBarry Smith . obj  - Optional object that provides the prefix for the options database keys
1837bcf0153eSBarry Smith - name - command line option string to be passed by user
1838fe2efc57SMark 
1839fe2efc57SMark   Level: intermediate
1840bcf0153eSBarry Smith 
18411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1842fe2efc57SMark @*/
1843bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1844d71ae5a4SJacob Faibussowitsch {
1845fe2efc57SMark   PetscFunctionBegin;
1846bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1847bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
18483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1849fe2efc57SMark }
1850fe2efc57SMark 
1851ffeef943SBarry Smith /*@
1852bcf0153eSBarry Smith   TSView - Prints the `TS` data structure.
1853d763cef2SBarry Smith 
1854c3339decSBarry Smith   Collective
1855d763cef2SBarry Smith 
1856d763cef2SBarry Smith   Input Parameters:
1857bcf0153eSBarry Smith + ts     - the `TS` context obtained from `TSCreate()`
1858d763cef2SBarry Smith - viewer - visualization context
1859d763cef2SBarry Smith 
1860d763cef2SBarry Smith   Options Database Key:
1861bcf0153eSBarry Smith . -ts_view - calls `TSView()` at end of `TSStep()`
1862bcf0153eSBarry Smith 
1863bcf0153eSBarry Smith   Level: beginner
1864d763cef2SBarry Smith 
1865d763cef2SBarry Smith   Notes:
1866d763cef2SBarry Smith   The available visualization contexts include
1867bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1868bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1869d763cef2SBarry Smith   output where only the first processor opens
1870d763cef2SBarry Smith   the file.  All other processors send their
1871d763cef2SBarry Smith   data to the first processor to print.
1872d763cef2SBarry Smith 
1873d763cef2SBarry Smith   The user can open an alternative visualization context with
1874bcf0153eSBarry Smith   `PetscViewerASCIIOpen()` - output to a specified file.
1875d763cef2SBarry Smith 
1876bcf0153eSBarry Smith   In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1877595c91d4SBarry Smith 
18781cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1879d763cef2SBarry Smith @*/
1880d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1881d71ae5a4SJacob Faibussowitsch {
188219fd82e9SBarry Smith   TSType    type;
18832b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
18842d53ad75SBarry Smith   DMTS      sdm;
1885e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1886536b137fSBarry Smith   PetscBool issaws;
1887f05ece33SBarry Smith #endif
1888d763cef2SBarry Smith 
1889d763cef2SBarry Smith   PetscFunctionBegin;
18900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
18911e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
18920700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1893c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1894fd16b177SBarry Smith 
18959566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
18969566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
18979566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18989566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1899e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19009566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1901f05ece33SBarry Smith #endif
190232077d6dSBarry Smith   if (iascii) {
19039566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1904efd4aadfSBarry Smith     if (ts->ops->view) {
19059566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1906dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19079566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1908efd4aadfSBarry Smith     }
19091e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19101e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19111e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19121e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19131e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19141e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1915efd4aadfSBarry Smith     if (ts->usessnes) {
1916efd4aadfSBarry Smith       PetscBool lin;
19171e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
191863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19199566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
192063a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1921efd4aadfSBarry Smith     }
192263a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19231e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19241e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19251e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
19261e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
19279566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19289566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19299566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19300f5bd95cSBarry Smith   } else if (isstring) {
19319566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19329566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1933dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
193455849f57SBarry Smith   } else if (isbinary) {
193555849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
193655849f57SBarry Smith     MPI_Comm    comm;
193755849f57SBarry Smith     PetscMPIInt rank;
193855849f57SBarry Smith     char        type[256];
193955849f57SBarry Smith 
19409566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19419566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1942dd400576SPatrick Sanan     if (rank == 0) {
19439566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
19449566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
19459566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
194655849f57SBarry Smith     }
1947dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19489566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19499566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
19509566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
19519566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
19529566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
19532b0a91c0SBarry Smith   } else if (isdraw) {
19542b0a91c0SBarry Smith     PetscDraw draw;
19552b0a91c0SBarry Smith     char      str[36];
195689fd9fafSBarry Smith     PetscReal x, y, bottom, h;
19572b0a91c0SBarry Smith 
19589566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
19599566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1960c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
1961c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
19629566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
196389fd9fafSBarry Smith     bottom = y - h;
19649566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1965dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19669566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19679566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
19689566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
1969e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1970536b137fSBarry Smith   } else if (issaws) {
1971d45a07a7SBarry Smith     PetscMPIInt rank;
19722657e9d9SBarry Smith     const char *name;
19732657e9d9SBarry Smith 
19749566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
19759566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1976dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
1977d45a07a7SBarry Smith       char dir[1024];
1978d45a07a7SBarry Smith 
19799566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
19809566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
1981792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
19829566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
1983792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
1984d763cef2SBarry Smith     }
1985dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
1986f05ece33SBarry Smith #endif
1987f05ece33SBarry Smith   }
198836a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
19899566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19909566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
19919566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
199236a9e3b9SBarry Smith   }
19939566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
19949566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
1995f05ece33SBarry Smith 
19969566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
19979566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
19989566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
19993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2000d763cef2SBarry Smith }
2001d763cef2SBarry Smith 
2002b07ff414SBarry Smith /*@
2003d763cef2SBarry Smith   TSSetApplicationContext - Sets an optional user-defined context for
2004d763cef2SBarry Smith   the timesteppers.
2005d763cef2SBarry Smith 
2006c3339decSBarry Smith   Logically Collective
2007d763cef2SBarry Smith 
2008d763cef2SBarry Smith   Input Parameters:
2009bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2010bcf0153eSBarry Smith - usrP - user context
2011daf670e6SBarry Smith 
2012d763cef2SBarry Smith   Level: intermediate
2013d763cef2SBarry Smith 
2014b43aa488SJacob Faibussowitsch   Fortran Notes:
2015195e9b02SBarry Smith   You must write a Fortran interface definition for this
2016195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2017bcf0153eSBarry Smith 
20181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2019d763cef2SBarry Smith @*/
2020d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2021d71ae5a4SJacob Faibussowitsch {
2022d763cef2SBarry Smith   PetscFunctionBegin;
20230700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2024d763cef2SBarry Smith   ts->user = usrP;
20253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2026d763cef2SBarry Smith }
2027d763cef2SBarry Smith 
2028b07ff414SBarry Smith /*@
2029d763cef2SBarry Smith   TSGetApplicationContext - Gets the user-defined context for the
2030bcf0153eSBarry Smith   timestepper that was set with `TSSetApplicationContext()`
2031d763cef2SBarry Smith 
2032d763cef2SBarry Smith   Not Collective
2033d763cef2SBarry Smith 
2034d763cef2SBarry Smith   Input Parameter:
2035bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2036d763cef2SBarry Smith 
2037d763cef2SBarry Smith   Output Parameter:
2038d763cef2SBarry Smith . usrP - user context
2039d763cef2SBarry Smith 
2040bcf0153eSBarry Smith   Level: intermediate
2041bcf0153eSBarry Smith 
2042b43aa488SJacob Faibussowitsch   Fortran Notes:
2043195e9b02SBarry Smith   You must write a Fortran interface definition for this
2044195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2045daf670e6SBarry Smith 
20461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2047d763cef2SBarry Smith @*/
2048d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2049d71ae5a4SJacob Faibussowitsch {
2050d763cef2SBarry Smith   PetscFunctionBegin;
20510700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2052e71120c6SJed Brown   *(void **)usrP = ts->user;
20533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2054d763cef2SBarry Smith }
2055d763cef2SBarry Smith 
2056d763cef2SBarry Smith /*@
2057bcf0153eSBarry Smith   TSGetStepNumber - Gets the number of time steps completed.
2058d763cef2SBarry Smith 
2059d763cef2SBarry Smith   Not Collective
2060d763cef2SBarry Smith 
2061d763cef2SBarry Smith   Input Parameter:
2062bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2063d763cef2SBarry Smith 
2064d763cef2SBarry Smith   Output Parameter:
206580275a0aSLisandro Dalcin . steps - number of steps completed so far
2066d763cef2SBarry Smith 
2067d763cef2SBarry Smith   Level: intermediate
2068d763cef2SBarry Smith 
20691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2070d763cef2SBarry Smith @*/
2071d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2072d71ae5a4SJacob Faibussowitsch {
2073d763cef2SBarry Smith   PetscFunctionBegin;
20740700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
20754f572ea9SToby Isaac   PetscAssertPointer(steps, 2);
207680275a0aSLisandro Dalcin   *steps = ts->steps;
20773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
207880275a0aSLisandro Dalcin }
207980275a0aSLisandro Dalcin 
208080275a0aSLisandro Dalcin /*@
208180275a0aSLisandro Dalcin   TSSetStepNumber - Sets the number of steps completed.
208280275a0aSLisandro Dalcin 
2083c3339decSBarry Smith   Logically Collective
208480275a0aSLisandro Dalcin 
208580275a0aSLisandro Dalcin   Input Parameters:
2086bcf0153eSBarry Smith + ts    - the `TS` context
208780275a0aSLisandro Dalcin - steps - number of steps completed so far
208880275a0aSLisandro Dalcin 
2089bcf0153eSBarry Smith   Level: developer
2090bcf0153eSBarry Smith 
2091bcf0153eSBarry Smith   Note:
2092bcf0153eSBarry Smith   For most uses of the `TS` solvers the user need not explicitly call
2093bcf0153eSBarry Smith   `TSSetStepNumber()`, as the step counter is appropriately updated in
2094bcf0153eSBarry Smith   `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
209580275a0aSLisandro Dalcin   reinitialize timestepping by setting the step counter to zero (and time
209680275a0aSLisandro Dalcin   to the initial time) to solve a similar problem with different initial
209780275a0aSLisandro Dalcin   conditions or parameters. Other possible use case is to continue
2098195e9b02SBarry Smith   timestepping from a previously interrupted run in such a way that `TS`
209980275a0aSLisandro Dalcin   monitors will be called with a initial nonzero step counter.
210080275a0aSLisandro Dalcin 
21011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
210280275a0aSLisandro Dalcin @*/
2103d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2104d71ae5a4SJacob Faibussowitsch {
210580275a0aSLisandro Dalcin   PetscFunctionBegin;
210680275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
210780275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21083c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
210980275a0aSLisandro Dalcin   ts->steps = steps;
21103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2111d763cef2SBarry Smith }
2112d763cef2SBarry Smith 
2113d763cef2SBarry Smith /*@
2114d763cef2SBarry Smith   TSSetTimeStep - Allows one to reset the timestep at any time,
2115d763cef2SBarry Smith   useful for simple pseudo-timestepping codes.
2116d763cef2SBarry Smith 
2117c3339decSBarry Smith   Logically Collective
2118d763cef2SBarry Smith 
2119d763cef2SBarry Smith   Input Parameters:
2120bcf0153eSBarry Smith + ts        - the `TS` context obtained from `TSCreate()`
2121d763cef2SBarry Smith - time_step - the size of the timestep
2122d763cef2SBarry Smith 
2123d763cef2SBarry Smith   Level: intermediate
2124d763cef2SBarry Smith 
21251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2126d763cef2SBarry Smith @*/
2127d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2128d71ae5a4SJacob Faibussowitsch {
2129d763cef2SBarry Smith   PetscFunctionBegin;
21300700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2131c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2132d763cef2SBarry Smith   ts->time_step = time_step;
21333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2134d763cef2SBarry Smith }
2135d763cef2SBarry Smith 
2136a43b19c4SJed Brown /*@
213749354f04SShri Abhyankar   TSSetExactFinalTime - Determines whether to adapt the final time step to
213849354f04SShri Abhyankar   match the exact final time, interpolate solution to the exact final time,
2139bcf0153eSBarry Smith   or just return at the final time `TS` computed.
2140a43b19c4SJed Brown 
2141c3339decSBarry Smith   Logically Collective
2142a43b19c4SJed Brown 
2143d8d19677SJose E. Roman   Input Parameters:
2144a43b19c4SJed Brown + ts     - the time-step context
214549354f04SShri Abhyankar - eftopt - exact final time option
2146bcf0153eSBarry Smith .vb
2147bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2148bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2149bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2150bcf0153eSBarry Smith .ve
2151a43b19c4SJed Brown 
2152bcf0153eSBarry Smith   Options Database Key:
2153feed9e9dSBarry Smith . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2154feed9e9dSBarry Smith 
2155a43b19c4SJed Brown   Level: beginner
2156a43b19c4SJed Brown 
2157bcf0153eSBarry Smith   Note:
2158bcf0153eSBarry Smith   If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2159bcf0153eSBarry Smith   then the final time you selected.
2160bcf0153eSBarry Smith 
21611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2162a43b19c4SJed Brown @*/
2163d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2164d71ae5a4SJacob Faibussowitsch {
2165a43b19c4SJed Brown   PetscFunctionBegin;
2166a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
216749354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
216849354f04SShri Abhyankar   ts->exact_final_time = eftopt;
21693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2170a43b19c4SJed Brown }
2171a43b19c4SJed Brown 
2172d763cef2SBarry Smith /*@
2173bcf0153eSBarry Smith   TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2174f6953c82SLisandro Dalcin 
2175f6953c82SLisandro Dalcin   Not Collective
2176f6953c82SLisandro Dalcin 
2177f6953c82SLisandro Dalcin   Input Parameter:
2178bcf0153eSBarry Smith . ts - the `TS` context
2179f6953c82SLisandro Dalcin 
2180f6953c82SLisandro Dalcin   Output Parameter:
2181f6953c82SLisandro Dalcin . eftopt - exact final time option
2182f6953c82SLisandro Dalcin 
2183f6953c82SLisandro Dalcin   Level: beginner
2184f6953c82SLisandro Dalcin 
21851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2186f6953c82SLisandro Dalcin @*/
2187d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2188d71ae5a4SJacob Faibussowitsch {
2189f6953c82SLisandro Dalcin   PetscFunctionBegin;
2190f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
21914f572ea9SToby Isaac   PetscAssertPointer(eftopt, 2);
2192f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
21933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2194f6953c82SLisandro Dalcin }
2195f6953c82SLisandro Dalcin 
2196f6953c82SLisandro Dalcin /*@
2197d763cef2SBarry Smith   TSGetTimeStep - Gets the current timestep size.
2198d763cef2SBarry Smith 
2199d763cef2SBarry Smith   Not Collective
2200d763cef2SBarry Smith 
2201d763cef2SBarry Smith   Input Parameter:
2202bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2203d763cef2SBarry Smith 
2204d763cef2SBarry Smith   Output Parameter:
2205d763cef2SBarry Smith . dt - the current timestep size
2206d763cef2SBarry Smith 
2207d763cef2SBarry Smith   Level: intermediate
2208d763cef2SBarry Smith 
22091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2210d763cef2SBarry Smith @*/
2211d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2212d71ae5a4SJacob Faibussowitsch {
2213d763cef2SBarry Smith   PetscFunctionBegin;
22140700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22154f572ea9SToby Isaac   PetscAssertPointer(dt, 2);
2216d763cef2SBarry Smith   *dt = ts->time_step;
22173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2218d763cef2SBarry Smith }
2219d763cef2SBarry Smith 
2220d8e5e3e6SSatish Balay /*@
2221d763cef2SBarry Smith   TSGetSolution - Returns the solution at the present timestep. It
2222d763cef2SBarry Smith   is valid to call this routine inside the function that you are evaluating
2223d763cef2SBarry Smith   in order to move to the new timestep. This vector not changed until
2224d763cef2SBarry Smith   the solution at the next timestep has been calculated.
2225d763cef2SBarry Smith 
2226bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
2227d763cef2SBarry Smith 
2228d763cef2SBarry Smith   Input Parameter:
2229bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2230d763cef2SBarry Smith 
2231d763cef2SBarry Smith   Output Parameter:
2232d763cef2SBarry Smith . v - the vector containing the solution
2233d763cef2SBarry Smith 
2234d763cef2SBarry Smith   Level: intermediate
2235d763cef2SBarry Smith 
2236bcf0153eSBarry Smith   Note:
2237bcf0153eSBarry Smith   If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2238bcf0153eSBarry Smith   final time. It returns the solution at the next timestep.
2239d763cef2SBarry Smith 
22401cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2241d763cef2SBarry Smith @*/
2242d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2243d71ae5a4SJacob Faibussowitsch {
2244d763cef2SBarry Smith   PetscFunctionBegin;
22450700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22464f572ea9SToby Isaac   PetscAssertPointer(v, 2);
22478737fe31SLisandro Dalcin   *v = ts->vec_sol;
22483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2249d763cef2SBarry Smith }
2250d763cef2SBarry Smith 
225103fe5f5eSDebojyoti Ghosh /*@
2252b2bf4f3aSDebojyoti Ghosh   TSGetSolutionComponents - Returns any solution components at the present
225303fe5f5eSDebojyoti Ghosh   timestep, if available for the time integration method being used.
2254b2bf4f3aSDebojyoti Ghosh   Solution components are quantities that share the same size and
225503fe5f5eSDebojyoti Ghosh   structure as the solution vector.
225603fe5f5eSDebojyoti Ghosh 
2257bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
225803fe5f5eSDebojyoti Ghosh 
2259b43aa488SJacob Faibussowitsch   Input Parameters:
2260bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2261195e9b02SBarry Smith . n  - If v is `NULL`, then the number of solution components is
2262b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
226303fe5f5eSDebojyoti Ghosh        returned in v.
2264a2b725a8SWilliam Gropp - v  - the vector containing the n-th solution component
2265195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2266b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
226703fe5f5eSDebojyoti Ghosh 
22684cdd57e5SDebojyoti Ghosh   Level: advanced
226903fe5f5eSDebojyoti Ghosh 
22701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
227103fe5f5eSDebojyoti Ghosh @*/
2272d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2273d71ae5a4SJacob Faibussowitsch {
227403fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
227503fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2276b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2277dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
22783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
227903fe5f5eSDebojyoti Ghosh }
228003fe5f5eSDebojyoti Ghosh 
22814cdd57e5SDebojyoti Ghosh /*@
22824cdd57e5SDebojyoti Ghosh   TSGetAuxSolution - Returns an auxiliary solution at the present
22834cdd57e5SDebojyoti Ghosh   timestep, if available for the time integration method being used.
22844cdd57e5SDebojyoti Ghosh 
2285bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
22864cdd57e5SDebojyoti Ghosh 
2287b43aa488SJacob Faibussowitsch   Input Parameters:
2288bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2289a2b725a8SWilliam Gropp - v  - the vector containing the auxiliary solution
22904cdd57e5SDebojyoti Ghosh 
22914cdd57e5SDebojyoti Ghosh   Level: intermediate
22924cdd57e5SDebojyoti Ghosh 
22931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
22944cdd57e5SDebojyoti Ghosh @*/
2295d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2296d71ae5a4SJacob Faibussowitsch {
22974cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
22984cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2299dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23001e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23024cdd57e5SDebojyoti Ghosh }
23034cdd57e5SDebojyoti Ghosh 
23044cdd57e5SDebojyoti Ghosh /*@
23054cdd57e5SDebojyoti Ghosh   TSGetTimeError - Returns the estimated error vector, if the chosen
2306bcf0153eSBarry Smith   `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23074cdd57e5SDebojyoti Ghosh 
2308bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23099657682dSDebojyoti Ghosh 
2310b43aa488SJacob Faibussowitsch   Input Parameters:
2311bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2312657c1e31SEmil Constantinescu . n  - current estimate (n=0) or previous one (n=-1)
2313a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
23144cdd57e5SDebojyoti Ghosh 
23154cdd57e5SDebojyoti Ghosh   Level: intermediate
23164cdd57e5SDebojyoti Ghosh 
2317bcf0153eSBarry Smith   Note:
2318bcf0153eSBarry Smith   MUST call after `TSSetUp()`
23194cdd57e5SDebojyoti Ghosh 
23201cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
23214cdd57e5SDebojyoti Ghosh @*/
2322d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2323d71ae5a4SJacob Faibussowitsch {
23244cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23254cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2326dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23271e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23294cdd57e5SDebojyoti Ghosh }
23304cdd57e5SDebojyoti Ghosh 
233157df6a1bSDebojyoti Ghosh /*@
233257df6a1bSDebojyoti Ghosh   TSSetTimeError - Sets the estimated error vector, if the chosen
2333bcf0153eSBarry Smith   `TSType` has an error estimation functionality. This can be used
233457df6a1bSDebojyoti Ghosh   to restart such a time integrator with a given error vector.
233557df6a1bSDebojyoti Ghosh 
2336bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
233757df6a1bSDebojyoti Ghosh 
2338b43aa488SJacob Faibussowitsch   Input Parameters:
2339bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2340a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
234157df6a1bSDebojyoti Ghosh 
234257df6a1bSDebojyoti Ghosh   Level: intermediate
234357df6a1bSDebojyoti Ghosh 
2344b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
234557df6a1bSDebojyoti Ghosh @*/
2346d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2347d71ae5a4SJacob Faibussowitsch {
234857df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
234957df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23503c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2351dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
23523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
235357df6a1bSDebojyoti Ghosh }
235457df6a1bSDebojyoti Ghosh 
2355bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2356d8e5e3e6SSatish Balay /*@
2357bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2358d763cef2SBarry Smith 
2359bdad233fSMatthew Knepley   Not collective
2360d763cef2SBarry Smith 
2361bdad233fSMatthew Knepley   Input Parameters:
2362bcf0153eSBarry Smith + ts   - The `TS`
2363bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2364d763cef2SBarry Smith .vb
23650910c330SBarry Smith          U_t - A U = 0      (linear)
23660910c330SBarry Smith          U_t - A(t) U = 0   (linear)
23670910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2368d763cef2SBarry Smith .ve
2369d763cef2SBarry Smith 
2370d763cef2SBarry Smith   Level: beginner
2371d763cef2SBarry Smith 
23721cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2373d763cef2SBarry Smith @*/
2374d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2375d71ae5a4SJacob Faibussowitsch {
2376d763cef2SBarry Smith   PetscFunctionBegin;
23770700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2378bdad233fSMatthew Knepley   ts->problem_type = type;
23799e2a6581SJed Brown   if (type == TS_LINEAR) {
23809e2a6581SJed Brown     SNES snes;
23819566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
23829566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
23839e2a6581SJed Brown   }
23843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2385d763cef2SBarry Smith }
2386d763cef2SBarry Smith 
2387cc4c1da9SBarry Smith /*@
2388bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2389bdad233fSMatthew Knepley 
2390bdad233fSMatthew Knepley   Not collective
2391bdad233fSMatthew Knepley 
2392bdad233fSMatthew Knepley   Input Parameter:
2393bcf0153eSBarry Smith . ts - The `TS`
2394bdad233fSMatthew Knepley 
2395bdad233fSMatthew Knepley   Output Parameter:
2396bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2397bdad233fSMatthew Knepley .vb
2398089b2837SJed Brown          M U_t = A U
2399089b2837SJed Brown          M(t) U_t = A(t) U
2400b5abc632SBarry Smith          F(t,U,U_t)
2401bdad233fSMatthew Knepley .ve
2402bdad233fSMatthew Knepley 
2403bdad233fSMatthew Knepley   Level: beginner
2404bdad233fSMatthew Knepley 
24051cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2406bdad233fSMatthew Knepley @*/
2407d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2408d71ae5a4SJacob Faibussowitsch {
2409bdad233fSMatthew Knepley   PetscFunctionBegin;
24100700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24114f572ea9SToby Isaac   PetscAssertPointer(type, 2);
2412bdad233fSMatthew Knepley   *type = ts->problem_type;
24133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2414bdad233fSMatthew Knepley }
2415d763cef2SBarry Smith 
2416303a5415SBarry Smith /*
2417303a5415SBarry 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()
2418303a5415SBarry Smith */
2419d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2420d71ae5a4SJacob Faibussowitsch {
2421303a5415SBarry Smith   PetscBool isnone;
2422303a5415SBarry Smith 
2423303a5415SBarry Smith   PetscFunctionBegin;
24249566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24259566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2426303a5415SBarry Smith 
24279566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24281e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24291e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
24303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2431303a5415SBarry Smith }
2432303a5415SBarry Smith 
2433d763cef2SBarry Smith /*@
2434303a5415SBarry Smith   TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2435d763cef2SBarry Smith 
2436c3339decSBarry Smith   Collective
2437d763cef2SBarry Smith 
2438d763cef2SBarry Smith   Input Parameter:
2439bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2440d763cef2SBarry Smith 
2441d763cef2SBarry Smith   Level: advanced
2442d763cef2SBarry Smith 
2443bcf0153eSBarry Smith   Note:
2444bcf0153eSBarry Smith   For basic use of the `TS` solvers the user need not explicitly call
2445bcf0153eSBarry Smith   `TSSetUp()`, since these actions will automatically occur during
2446bcf0153eSBarry Smith   the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2447bcf0153eSBarry Smith   phase separately, `TSSetUp()` should be called after `TSCreate()`
2448bcf0153eSBarry Smith   and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2449bcf0153eSBarry Smith 
24501cc06b55SBarry Smith .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2451d763cef2SBarry Smith @*/
2452d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2453d71ae5a4SJacob Faibussowitsch {
24546c6b9e74SPeter Brune   DM dm;
24556c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2456d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
24578434afd1SBarry Smith   TSIFunctionFn   *ifun;
24588434afd1SBarry Smith   TSIJacobianFn   *ijac;
24598434afd1SBarry Smith   TSI2JacobianFn  *i2jac;
24608434afd1SBarry Smith   TSRHSJacobianFn *rhsjac;
2461d763cef2SBarry Smith 
2462d763cef2SBarry Smith   PetscFunctionBegin;
24630700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24643ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2465277b19d0SLisandro Dalcin 
24667adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
24679566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
24689566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2469d763cef2SBarry Smith   }
2470277b19d0SLisandro Dalcin 
24711a638600SStefano Zampini   if (!ts->vec_sol) {
24721e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
24739566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
24741a638600SStefano Zampini   }
2475277b19d0SLisandro Dalcin 
24764a658b32SHong Zhang   if (ts->tspan) {
24771e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
24784a658b32SHong Zhang   }
2479298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
24809566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2481298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2482298bade4SHong Zhang   }
2483298bade4SHong Zhang 
2484cd4cee2dSHong Zhang   if (ts->quadraturets) {
24859566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
24869566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
24879566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2488cd4cee2dSHong Zhang   }
2489cd4cee2dSHong Zhang 
24909566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2491f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2492e1244c69SJed Brown     Mat  Amat, Pmat;
2493e1244c69SJed Brown     SNES snes;
24949566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24959566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2496e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2497e1244c69SJed Brown      * have displaced the RHS matrix */
2498971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2499abc0d4abSBarry 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 */
25009566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25019566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25029566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2503e1244c69SJed Brown     }
2504971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25059566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25069566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25079566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2508e1244c69SJed Brown     }
2509e1244c69SJed Brown   }
25102ffb9264SLisandro Dalcin 
25119566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25129566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25132ffb9264SLisandro Dalcin 
2514dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2515277b19d0SLisandro Dalcin 
25169566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25172ffb9264SLisandro Dalcin 
2518a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25196c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25206c6b9e74SPeter Brune    */
25219566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25229566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25231e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25241e66621cSBarry Smith 
2525a6772fa2SLisandro 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.
25266c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25276c6b9e74SPeter Brune    */
25289566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25299566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25309566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25319566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25321e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2533c0517034SDebojyoti Ghosh 
2534c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2535dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2536c0517034SDebojyoti Ghosh 
2537277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2539277b19d0SLisandro Dalcin }
2540277b19d0SLisandro Dalcin 
2541f6a906c0SBarry Smith /*@
2542bcf0153eSBarry Smith   TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2543277b19d0SLisandro Dalcin 
2544c3339decSBarry Smith   Collective
2545277b19d0SLisandro Dalcin 
2546277b19d0SLisandro Dalcin   Input Parameter:
2547bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2548277b19d0SLisandro Dalcin 
2549277b19d0SLisandro Dalcin   Level: beginner
2550277b19d0SLisandro Dalcin 
25511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2552277b19d0SLisandro Dalcin @*/
2553d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2554d71ae5a4SJacob Faibussowitsch {
25551d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2556277b19d0SLisandro Dalcin 
2557277b19d0SLisandro Dalcin   PetscFunctionBegin;
2558277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2559b18ea86cSHong Zhang 
2560dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25619566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25629566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2563bbd56ea5SKarl Rupp 
25649566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
25659566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
25669566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
25679566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
2568c61711c8SStefano Zampini   PetscCall(VecDestroy(&ts->vec_sol0));
25699566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
25709566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
25719566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
25729566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2573bbd56ea5SKarl Rupp 
25749566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
25759566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
25761baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2577cd4cee2dSHong Zhang   if (ts->quadraturets) {
25789566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
25799566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2580cd4cee2dSHong Zhang   }
25811d06f6b3SHong Zhang   while (ilink) {
25821d06f6b3SHong Zhang     next = ilink->next;
25839566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
25849566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
25859566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
25869566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
25871d06f6b3SHong Zhang     ilink = next;
258887f4e208SHong Zhang   }
25896bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2590545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
25914a658b32SHong Zhang   if (ts->tspan) {
25924a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
25934a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25944a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
25954a658b32SHong Zhang   }
2596b3a72457SStefano Zampini   ts->rhsjacobian.time  = PETSC_MIN_REAL;
2597b3a72457SStefano Zampini   ts->rhsjacobian.scale = 1.0;
2598b3a72457SStefano Zampini   ts->ijacobian.shift   = 1.0;
2599277b19d0SLisandro Dalcin   ts->setupcalled       = PETSC_FALSE;
26003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2601d763cef2SBarry Smith }
2602d763cef2SBarry Smith 
260314d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
260414d0ab18SJacob Faibussowitsch 
26050764c050SBarry Smith /*@
2606d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2607bcf0153eSBarry Smith   with `TSCreate()`.
2608d763cef2SBarry Smith 
2609c3339decSBarry Smith   Collective
2610d763cef2SBarry Smith 
2611d763cef2SBarry Smith   Input Parameter:
2612bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2613d763cef2SBarry Smith 
2614d763cef2SBarry Smith   Level: beginner
2615d763cef2SBarry Smith 
26161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2617d763cef2SBarry Smith @*/
2618d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2619d71ae5a4SJacob Faibussowitsch {
2620d763cef2SBarry Smith   PetscFunctionBegin;
26213ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2622ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
2623f4f49eeaSPierre Jolivet   if (--((PetscObject)*ts)->refct > 0) {
26249371c9d4SSatish Balay     *ts = NULL;
26253ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26269371c9d4SSatish Balay   }
2627d763cef2SBarry Smith 
26289566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26299566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26301e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26316bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26321e66621cSBarry Smith 
2633e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26349566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2635f4f49eeaSPierre Jolivet   PetscTryTypeMethod(*ts, destroy);
26366d4c513bSLisandro Dalcin 
26379566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2638bc952696SBarry Smith 
26399566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26409566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26416427ac75SLisandro Dalcin 
26429566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26439566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
2644f4f49eeaSPierre Jolivet   PetscCall(TSMonitorCancel(*ts));
2645f4f49eeaSPierre Jolivet   PetscCall(TSAdjointMonitorCancel(*ts));
26466d4c513bSLisandro Dalcin 
26479566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26489566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2650d763cef2SBarry Smith }
2651d763cef2SBarry Smith 
2652d8e5e3e6SSatish Balay /*@
2653bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2654bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2655d763cef2SBarry Smith 
2656bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2657d763cef2SBarry Smith 
2658d763cef2SBarry Smith   Input Parameter:
2659bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2660d763cef2SBarry Smith 
2661d763cef2SBarry Smith   Output Parameter:
2662d763cef2SBarry Smith . snes - the nonlinear solver context
2663d763cef2SBarry Smith 
2664d763cef2SBarry Smith   Level: beginner
2665d763cef2SBarry Smith 
2666bcf0153eSBarry Smith   Notes:
2667bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2668bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2669bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2670bcf0153eSBarry Smith 
2671bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2672195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2673bcf0153eSBarry Smith 
26741cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2675d763cef2SBarry Smith @*/
2676d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2677d71ae5a4SJacob Faibussowitsch {
2678d763cef2SBarry Smith   PetscFunctionBegin;
26790700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
26804f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2681d372ba47SLisandro Dalcin   if (!ts->snes) {
26829566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
26839566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
26849566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
26859566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
26869566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
26871e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2688d372ba47SLisandro Dalcin   }
2689d763cef2SBarry Smith   *snes = ts->snes;
26903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2691d763cef2SBarry Smith }
2692d763cef2SBarry Smith 
2693deb2cd25SJed Brown /*@
2694bcf0153eSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2695deb2cd25SJed Brown 
2696deb2cd25SJed Brown   Collective
2697deb2cd25SJed Brown 
2698d8d19677SJose E. Roman   Input Parameters:
2699bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2700deb2cd25SJed Brown - snes - the nonlinear solver context
2701deb2cd25SJed Brown 
2702deb2cd25SJed Brown   Level: developer
2703deb2cd25SJed Brown 
2704bcf0153eSBarry Smith   Note:
2705bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2706bcf0153eSBarry Smith 
27071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2708deb2cd25SJed Brown @*/
2709d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2710d71ae5a4SJacob Faibussowitsch {
2711d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2712deb2cd25SJed Brown 
2713deb2cd25SJed Brown   PetscFunctionBegin;
2714deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2715deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27169566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27179566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2718bbd56ea5SKarl Rupp 
2719deb2cd25SJed Brown   ts->snes = snes;
2720bbd56ea5SKarl Rupp 
27219566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27229566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27231e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2725deb2cd25SJed Brown }
2726deb2cd25SJed Brown 
2727d8e5e3e6SSatish Balay /*@
2728bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2729bcf0153eSBarry Smith   a `TS` (timestepper) context.
2730d763cef2SBarry Smith 
2731195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2732d763cef2SBarry Smith 
2733d763cef2SBarry Smith   Input Parameter:
2734bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2735d763cef2SBarry Smith 
2736d763cef2SBarry Smith   Output Parameter:
273794b7f48cSBarry Smith . ksp - the nonlinear solver context
2738d763cef2SBarry Smith 
2739d763cef2SBarry Smith   Level: beginner
2740d763cef2SBarry Smith 
2741bcf0153eSBarry Smith   Notes:
2742bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2743bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2744bcf0153eSBarry Smith   `PC` context as well.
2745bcf0153eSBarry Smith 
2746bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2747195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2748bcf0153eSBarry Smith 
27491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2750d763cef2SBarry Smith @*/
2751d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2752d71ae5a4SJacob Faibussowitsch {
2753089b2837SJed Brown   SNES snes;
2754d372ba47SLisandro Dalcin 
2755d763cef2SBarry Smith   PetscFunctionBegin;
27560700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27574f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27583c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27593c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27609566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
27619566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
27623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2763d763cef2SBarry Smith }
2764d763cef2SBarry Smith 
2765d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2766d763cef2SBarry Smith 
2767adb62b0dSMatthew Knepley /*@
2768618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2769618ce8baSLisandro Dalcin 
2770c3339decSBarry Smith   Logically Collective
2771618ce8baSLisandro Dalcin 
2772618ce8baSLisandro Dalcin   Input Parameters:
2773bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2774618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2775618ce8baSLisandro Dalcin 
2776bcf0153eSBarry Smith   Options Database Key:
2777618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2778618ce8baSLisandro Dalcin 
2779618ce8baSLisandro Dalcin   Level: intermediate
2780618ce8baSLisandro Dalcin 
2781bcf0153eSBarry Smith   Note:
278209cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
278309cb0f53SBarry Smith 
278409cb0f53SBarry Smith   The default maximum number of steps is 5,000
278509cb0f53SBarry Smith 
278609cb0f53SBarry Smith   Fortran Note:
278709cb0f53SBarry Smith   Use `PETSC_DETERMINE_INTEGER`
2788bcf0153eSBarry Smith 
27891cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2790618ce8baSLisandro Dalcin @*/
2791d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2792d71ae5a4SJacob Faibussowitsch {
2793618ce8baSLisandro Dalcin   PetscFunctionBegin;
2794618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2795618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
279609cb0f53SBarry Smith   if (maxsteps == PETSC_DETERMINE) {
279709cb0f53SBarry Smith     ts->max_steps = ts->default_max_steps;
279809cb0f53SBarry Smith   } else {
27993c633725SBarry Smith     PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2800618ce8baSLisandro Dalcin     ts->max_steps = maxsteps;
280109cb0f53SBarry Smith   }
28023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2803618ce8baSLisandro Dalcin }
2804618ce8baSLisandro Dalcin 
2805618ce8baSLisandro Dalcin /*@
2806618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2807618ce8baSLisandro Dalcin 
2808618ce8baSLisandro Dalcin   Not Collective
2809618ce8baSLisandro Dalcin 
28102fe279fdSBarry Smith   Input Parameter:
2811bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2812618ce8baSLisandro Dalcin 
2813618ce8baSLisandro Dalcin   Output Parameter:
2814618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2815618ce8baSLisandro Dalcin 
2816618ce8baSLisandro Dalcin   Level: advanced
2817618ce8baSLisandro Dalcin 
28181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2819618ce8baSLisandro Dalcin @*/
2820d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2821d71ae5a4SJacob Faibussowitsch {
2822618ce8baSLisandro Dalcin   PetscFunctionBegin;
2823618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28244f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2825618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2827618ce8baSLisandro Dalcin }
2828618ce8baSLisandro Dalcin 
2829618ce8baSLisandro Dalcin /*@
2830618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2831618ce8baSLisandro Dalcin 
2832c3339decSBarry Smith   Logically Collective
2833618ce8baSLisandro Dalcin 
2834618ce8baSLisandro Dalcin   Input Parameters:
2835bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2836618ce8baSLisandro Dalcin - maxtime - final time to step to
2837618ce8baSLisandro Dalcin 
2838bcf0153eSBarry Smith   Options Database Key:
2839ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2840618ce8baSLisandro Dalcin 
2841bcf0153eSBarry Smith   Level: intermediate
2842bcf0153eSBarry Smith 
2843618ce8baSLisandro Dalcin   Notes:
284409cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
284509cb0f53SBarry Smith 
2846618ce8baSLisandro Dalcin   The default maximum time is 5.0
2847618ce8baSLisandro Dalcin 
284809cb0f53SBarry Smith   Fortran Note:
284909cb0f53SBarry Smith   Use `PETSC_DETERMINE_REAL`
285009cb0f53SBarry Smith 
28511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2852618ce8baSLisandro Dalcin @*/
2853d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2854d71ae5a4SJacob Faibussowitsch {
2855618ce8baSLisandro Dalcin   PetscFunctionBegin;
2856618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2857618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
285809cb0f53SBarry Smith   if (maxtime == PETSC_DETERMINE) {
285909cb0f53SBarry Smith     ts->max_time = ts->default_max_time;
286009cb0f53SBarry Smith   } else {
2861618ce8baSLisandro Dalcin     ts->max_time = maxtime;
286209cb0f53SBarry Smith   }
28633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2864618ce8baSLisandro Dalcin }
2865618ce8baSLisandro Dalcin 
2866618ce8baSLisandro Dalcin /*@
2867618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2868618ce8baSLisandro Dalcin 
2869618ce8baSLisandro Dalcin   Not Collective
2870618ce8baSLisandro Dalcin 
28712fe279fdSBarry Smith   Input Parameter:
2872bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2873618ce8baSLisandro Dalcin 
2874618ce8baSLisandro Dalcin   Output Parameter:
2875618ce8baSLisandro Dalcin . maxtime - final time to step to
2876618ce8baSLisandro Dalcin 
2877618ce8baSLisandro Dalcin   Level: advanced
2878618ce8baSLisandro Dalcin 
28791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2880618ce8baSLisandro Dalcin @*/
2881d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2882d71ae5a4SJacob Faibussowitsch {
2883618ce8baSLisandro Dalcin   PetscFunctionBegin;
2884618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28854f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2886618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
28873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2888618ce8baSLisandro Dalcin }
2889618ce8baSLisandro Dalcin 
289014d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2891618ce8baSLisandro Dalcin /*@
2892bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2893edc382c3SSatish Balay 
2894edc382c3SSatish Balay   Level: deprecated
2895edc382c3SSatish Balay 
2896aaa6c58dSLisandro Dalcin @*/
2897d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2898d71ae5a4SJacob Faibussowitsch {
2899aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2900aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29019566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29029566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
29033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2904aaa6c58dSLisandro Dalcin }
2905aaa6c58dSLisandro Dalcin 
290614d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2907aaa6c58dSLisandro Dalcin /*@
2908bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2909edc382c3SSatish Balay 
2910edc382c3SSatish Balay   Level: deprecated
2911edc382c3SSatish Balay 
2912adb62b0dSMatthew Knepley @*/
2913d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2914d71ae5a4SJacob Faibussowitsch {
2915adb62b0dSMatthew Knepley   PetscFunctionBegin;
29160700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2917abc0a331SBarry Smith   if (maxsteps) {
29184f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
2919adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2920adb62b0dSMatthew Knepley   }
2921abc0a331SBarry Smith   if (maxtime) {
29224f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
2923adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2924adb62b0dSMatthew Knepley   }
29253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2926adb62b0dSMatthew Knepley }
2927adb62b0dSMatthew Knepley 
292814d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2929d763cef2SBarry Smith /*@
2930bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2931edc382c3SSatish Balay 
2932edc382c3SSatish Balay   Level: deprecated
2933edc382c3SSatish Balay 
2934d763cef2SBarry Smith @*/
2935d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2936d71ae5a4SJacob Faibussowitsch {
2937d763cef2SBarry Smith   PetscFunctionBegin;
293809cb0f53SBarry Smith   if (maxsteps != (PetscInt)PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
293909cb0f53SBarry Smith   if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
29403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2941d763cef2SBarry Smith }
2942d763cef2SBarry Smith 
294314d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2944d763cef2SBarry Smith /*@
2945bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
2946edc382c3SSatish Balay 
2947edc382c3SSatish Balay   Level: deprecated
2948edc382c3SSatish Balay 
29495c5f5948SLisandro Dalcin @*/
2950d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
2951d71ae5a4SJacob Faibussowitsch {
29529371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29539371c9d4SSatish Balay }
29545c5f5948SLisandro Dalcin 
295514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
295619eac22cSLisandro Dalcin /*@
2957bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
2958edc382c3SSatish Balay 
2959edc382c3SSatish Balay   Level: deprecated
2960edc382c3SSatish Balay 
29614f4e0956SLisandro Dalcin @*/
2962d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
2963d71ae5a4SJacob Faibussowitsch {
29649371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29659371c9d4SSatish Balay }
29664f4e0956SLisandro Dalcin 
29674f4e0956SLisandro Dalcin /*@
2968d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
2969bcf0153eSBarry Smith   for use by the `TS` routines.
2970d763cef2SBarry Smith 
2971c3339decSBarry Smith   Logically Collective
2972d763cef2SBarry Smith 
2973d763cef2SBarry Smith   Input Parameters:
2974bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
29750910c330SBarry Smith - u  - the solution vector
2976d763cef2SBarry Smith 
2977d763cef2SBarry Smith   Level: beginner
2978d763cef2SBarry Smith 
29791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
2980d763cef2SBarry Smith @*/
2981d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
2982d71ae5a4SJacob Faibussowitsch {
2983496e6a7aSJed Brown   DM dm;
29848737fe31SLisandro Dalcin 
2985d763cef2SBarry Smith   PetscFunctionBegin;
29860700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29870910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
29889566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
29899566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
29900910c330SBarry Smith   ts->vec_sol = u;
2991bbd56ea5SKarl Rupp 
29929566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
29939566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
29943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2995d763cef2SBarry Smith }
2996d763cef2SBarry Smith 
2997ac226902SBarry Smith /*@C
2998000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
29993f2090d5SJed Brown   called once at the beginning of each time step.
3000000e7ae3SMatthew Knepley 
3001c3339decSBarry Smith   Logically Collective
3002000e7ae3SMatthew Knepley 
3003000e7ae3SMatthew Knepley   Input Parameters:
3004bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3005000e7ae3SMatthew Knepley - func - The function
3006000e7ae3SMatthew Knepley 
300720f4b53cSBarry Smith   Calling sequence of `func`:
300814d0ab18SJacob Faibussowitsch . ts - the `TS` context
3009000e7ae3SMatthew Knepley 
3010000e7ae3SMatthew Knepley   Level: intermediate
3011000e7ae3SMatthew Knepley 
30121cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3013000e7ae3SMatthew Knepley @*/
301414d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3015d71ae5a4SJacob Faibussowitsch {
3016000e7ae3SMatthew Knepley   PetscFunctionBegin;
30170700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3018ae60f76fSBarry Smith   ts->prestep = func;
30193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3020000e7ae3SMatthew Knepley }
3021000e7ae3SMatthew Knepley 
302209ee8438SJed Brown /*@
3023bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30243f2090d5SJed Brown 
3025c3339decSBarry Smith   Collective
30263f2090d5SJed Brown 
30272fe279fdSBarry Smith   Input Parameter:
3028bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
30293f2090d5SJed Brown 
30303f2090d5SJed Brown   Level: developer
30313f2090d5SJed Brown 
3032bcf0153eSBarry Smith   Note:
3033bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3034bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3035bcf0153eSBarry Smith 
30361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30373f2090d5SJed Brown @*/
3038d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3039d71ae5a4SJacob Faibussowitsch {
30403f2090d5SJed Brown   PetscFunctionBegin;
30410700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3042ae60f76fSBarry Smith   if (ts->prestep) {
30435efd42a4SStefano Zampini     Vec              U;
3044ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3045ef8d1ce0SJohann Rudi     PetscBool        sameObject;
30465efd42a4SStefano Zampini     PetscObjectState sprev, spost;
30475efd42a4SStefano Zampini 
30489566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30499566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
30509566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
305125e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
30529566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30539566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
30549566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
30559566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3056312ce896SJed Brown   }
30573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
30583f2090d5SJed Brown }
30593f2090d5SJed Brown 
3060b8123daeSJed Brown /*@C
3061b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3062b8123daeSJed Brown   called once at the beginning of each stage.
3063b8123daeSJed Brown 
3064c3339decSBarry Smith   Logically Collective
3065b8123daeSJed Brown 
3066b8123daeSJed Brown   Input Parameters:
3067bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3068b8123daeSJed Brown - func - The function
3069b8123daeSJed Brown 
307020f4b53cSBarry Smith   Calling sequence of `func`:
307114d0ab18SJacob Faibussowitsch + ts        - the `TS` context
307214d0ab18SJacob Faibussowitsch - stagetime - the stage time
3073b8123daeSJed Brown 
3074b8123daeSJed Brown   Level: intermediate
3075b8123daeSJed Brown 
3076b8123daeSJed Brown   Note:
3077b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3078bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3079bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3080b8123daeSJed Brown 
30811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3082b8123daeSJed Brown @*/
308314d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3084d71ae5a4SJacob Faibussowitsch {
3085b8123daeSJed Brown   PetscFunctionBegin;
3086b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3087ae60f76fSBarry Smith   ts->prestage = func;
30883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3089b8123daeSJed Brown }
3090b8123daeSJed Brown 
30919be3e283SDebojyoti Ghosh /*@C
3092bcf0153eSBarry Smith   TSSetPostStage - Sets the general-purpose function, provided with `TSSetPostStep()`,
30939be3e283SDebojyoti Ghosh   called once at the end of each stage.
30949be3e283SDebojyoti Ghosh 
3095c3339decSBarry Smith   Logically Collective
30969be3e283SDebojyoti Ghosh 
30979be3e283SDebojyoti Ghosh   Input Parameters:
3098bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
30999be3e283SDebojyoti Ghosh - func - The function
31009be3e283SDebojyoti Ghosh 
310120f4b53cSBarry Smith   Calling sequence of `func`:
310214d0ab18SJacob Faibussowitsch + ts         - the `TS` context
310314d0ab18SJacob Faibussowitsch . stagetime  - the stage time
310414d0ab18SJacob Faibussowitsch . stageindex - the stage index
310514d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
31069be3e283SDebojyoti Ghosh 
31079be3e283SDebojyoti Ghosh   Level: intermediate
31089be3e283SDebojyoti Ghosh 
31099be3e283SDebojyoti Ghosh   Note:
31109be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3111bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3112bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31139be3e283SDebojyoti Ghosh 
31141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31159be3e283SDebojyoti Ghosh @*/
311614d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3117d71ae5a4SJacob Faibussowitsch {
31189be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31199be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31209be3e283SDebojyoti Ghosh   ts->poststage = func;
31213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31229be3e283SDebojyoti Ghosh }
31239be3e283SDebojyoti Ghosh 
3124c688d042SShri Abhyankar /*@C
3125c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3126c688d042SShri Abhyankar   called once at the end of each step evaluation.
3127c688d042SShri Abhyankar 
3128c3339decSBarry Smith   Logically Collective
3129c688d042SShri Abhyankar 
3130c688d042SShri Abhyankar   Input Parameters:
3131bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3132c688d042SShri Abhyankar - func - The function
3133c688d042SShri Abhyankar 
313420f4b53cSBarry Smith   Calling sequence of `func`:
313514d0ab18SJacob Faibussowitsch . ts - the `TS` context
3136c688d042SShri Abhyankar 
3137c688d042SShri Abhyankar   Level: intermediate
3138c688d042SShri Abhyankar 
3139c688d042SShri Abhyankar   Note:
3140bcf0153eSBarry Smith   Semantically, `TSSetPostEvaluate()` differs from `TSSetPostStep()` since the function it sets is called before event-handling
3141bcf0153eSBarry Smith   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, `TSPostStep()`
3142bcf0153eSBarry Smith   may be passed a different solution, possibly changed by the event handler. `TSPostEvaluate()` is called after the next step
3143bcf0153eSBarry Smith   solution is evaluated allowing to modify it, if need be. The solution can be obtained with `TSGetSolution()`, the time step
3144bcf0153eSBarry Smith   with `TSGetTimeStep()`, and the time at the start of the step is available via `TSGetTime()`
3145c688d042SShri Abhyankar 
31461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3147c688d042SShri Abhyankar @*/
314814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3149d71ae5a4SJacob Faibussowitsch {
3150c688d042SShri Abhyankar   PetscFunctionBegin;
3151c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3152c688d042SShri Abhyankar   ts->postevaluate = func;
31533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3154c688d042SShri Abhyankar }
3155c688d042SShri Abhyankar 
3156b8123daeSJed Brown /*@
3157bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3158b8123daeSJed Brown 
3159c3339decSBarry Smith   Collective
3160b8123daeSJed Brown 
3161b8123daeSJed Brown   Input Parameters:
316214d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
316314d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3164b8123daeSJed Brown 
3165b8123daeSJed Brown   Level: developer
3166b8123daeSJed Brown 
3167bcf0153eSBarry Smith   Note:
3168bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3169bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3170bcf0153eSBarry Smith 
31711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3172b8123daeSJed Brown @*/
3173d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3174d71ae5a4SJacob Faibussowitsch {
3175b8123daeSJed Brown   PetscFunctionBegin;
3176b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31771e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
31783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3179b8123daeSJed Brown }
3180b8123daeSJed Brown 
31819be3e283SDebojyoti Ghosh /*@
3182bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
31839be3e283SDebojyoti Ghosh 
3184c3339decSBarry Smith   Collective
31859be3e283SDebojyoti Ghosh 
31869be3e283SDebojyoti Ghosh   Input Parameters:
318714d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
318814d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
318914d0ab18SJacob Faibussowitsch . stageindex - Stage number
319014d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
31919be3e283SDebojyoti Ghosh 
31929be3e283SDebojyoti Ghosh   Level: developer
31939be3e283SDebojyoti Ghosh 
3194bcf0153eSBarry Smith   Note:
3195bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3196bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3197bcf0153eSBarry Smith 
31981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
31999be3e283SDebojyoti Ghosh @*/
3200d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3201d71ae5a4SJacob Faibussowitsch {
32029be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32039be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32041e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32069be3e283SDebojyoti Ghosh }
32079be3e283SDebojyoti Ghosh 
3208c688d042SShri Abhyankar /*@
3209bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3210c688d042SShri Abhyankar 
3211c3339decSBarry Smith   Collective
3212c688d042SShri Abhyankar 
32132fe279fdSBarry Smith   Input Parameter:
3214bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3215c688d042SShri Abhyankar 
3216c688d042SShri Abhyankar   Level: developer
3217c688d042SShri Abhyankar 
3218bcf0153eSBarry Smith   Note:
3219bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3220bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3221bcf0153eSBarry Smith 
32221cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3223c688d042SShri Abhyankar @*/
3224d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3225d71ae5a4SJacob Faibussowitsch {
3226c688d042SShri Abhyankar   PetscFunctionBegin;
3227c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3228c688d042SShri Abhyankar   if (ts->postevaluate) {
3229dcb233daSLisandro Dalcin     Vec              U;
3230dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3231dcb233daSLisandro Dalcin 
32329566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32339566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
323425e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
32359566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32369566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3237c688d042SShri Abhyankar   }
32383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3239c688d042SShri Abhyankar }
3240c688d042SShri Abhyankar 
3241ac226902SBarry Smith /*@C
3242000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
32433f2090d5SJed Brown   called once at the end of each time step.
3244000e7ae3SMatthew Knepley 
3245c3339decSBarry Smith   Logically Collective
3246000e7ae3SMatthew Knepley 
3247000e7ae3SMatthew Knepley   Input Parameters:
3248bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3249000e7ae3SMatthew Knepley - func - The function
3250000e7ae3SMatthew Knepley 
325120f4b53cSBarry Smith   Calling sequence of `func`:
325214d0ab18SJacob Faibussowitsch . ts - the `TS` context
3253000e7ae3SMatthew Knepley 
3254000e7ae3SMatthew Knepley   Level: intermediate
3255000e7ae3SMatthew Knepley 
3256bcf0153eSBarry Smith   Note:
3257195e9b02SBarry Smith   The function set by `TSSetPostStep()` is called after each successful step. The solution vector
3258bcf0153eSBarry Smith   obtained by `TSGetSolution()` may be different than that computed at the step end if the event handler
3259bcf0153eSBarry Smith   locates an event and `TSPostEvent()` modifies it. Use `TSSetPostEvaluate()` if an unmodified solution is needed instead.
3260bcf0153eSBarry Smith 
32611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3262000e7ae3SMatthew Knepley @*/
326314d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3264d71ae5a4SJacob Faibussowitsch {
3265000e7ae3SMatthew Knepley   PetscFunctionBegin;
32660700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3267ae60f76fSBarry Smith   ts->poststep = func;
32683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3269000e7ae3SMatthew Knepley }
3270000e7ae3SMatthew Knepley 
327109ee8438SJed Brown /*@
3272195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
32733f2090d5SJed Brown 
3274c3339decSBarry Smith   Collective
32753f2090d5SJed Brown 
32762fe279fdSBarry Smith   Input Parameter:
3277bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
32783f2090d5SJed Brown 
3279bcf0153eSBarry Smith   Note:
3280bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
32813f2090d5SJed Brown   so most users would not generally call this routine themselves.
32823f2090d5SJed Brown 
32833f2090d5SJed Brown   Level: developer
32843f2090d5SJed Brown 
32851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
32863f2090d5SJed Brown @*/
3287d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3288d71ae5a4SJacob Faibussowitsch {
32893f2090d5SJed Brown   PetscFunctionBegin;
32900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3291ae60f76fSBarry Smith   if (ts->poststep) {
32925efd42a4SStefano Zampini     Vec              U;
3293ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3294ef8d1ce0SJohann Rudi     PetscBool        sameObject;
32955efd42a4SStefano Zampini     PetscObjectState sprev, spost;
32965efd42a4SStefano Zampini 
32979566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32989566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
32999566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
330025e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33019566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33029566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33039566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33049566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
330572ac3e02SJed Brown   }
33063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33073f2090d5SJed Brown }
33083f2090d5SJed Brown 
3309cd652676SJed Brown /*@
3310cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3311cd652676SJed Brown 
3312c3339decSBarry Smith   Collective
3313cd652676SJed Brown 
33144165533cSJose E. Roman   Input Parameters:
3315cd652676SJed Brown + ts - time stepping context
3316cd652676SJed Brown - t  - time to interpolate to
3317cd652676SJed Brown 
33184165533cSJose E. Roman   Output Parameter:
33190910c330SBarry Smith . U - state at given time
3320cd652676SJed Brown 
3321cd652676SJed Brown   Level: intermediate
3322cd652676SJed Brown 
3323b43aa488SJacob Faibussowitsch   Developer Notes:
3324bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3325cd652676SJed Brown 
33261cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3327cd652676SJed Brown @*/
3328d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3329d71ae5a4SJacob Faibussowitsch {
3330cd652676SJed Brown   PetscFunctionBegin;
3331cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3332b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
333363a3b9bcSJacob 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);
3334dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
33353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3336cd652676SJed Brown }
3337cd652676SJed Brown 
3338d763cef2SBarry Smith /*@
33396d9e5789SSean Farley   TSStep - Steps one time step
3340d763cef2SBarry Smith 
3341c3339decSBarry Smith   Collective
3342d763cef2SBarry Smith 
3343d763cef2SBarry Smith   Input Parameter:
3344bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3345d763cef2SBarry Smith 
334627829d71SBarry Smith   Level: developer
3347d763cef2SBarry Smith 
3348b8123daeSJed Brown   Notes:
3349bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
335027829d71SBarry Smith 
3351bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3352b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3353b8123daeSJed Brown 
3354bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3355bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
335625cb2221SBarry Smith 
33571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3358d763cef2SBarry Smith @*/
3359d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3360d71ae5a4SJacob Faibussowitsch {
3361fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3362be5899b3SLisandro Dalcin   PetscReal        ptime;
3363d763cef2SBarry Smith 
3364d763cef2SBarry Smith   PetscFunctionBegin;
33650700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3366d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3367fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3368f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3369f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3370f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3371f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
33729371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
33739371c9d4SSatish Balay                                    &cite));
33749566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
33759566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3376ca4445c7SIlya Fursov   if (ts->tspan)
3377ca4445c7SIlya Fursov     ts->tspan->worktol = 0; /* In each step of TSSolve() 'tspan->worktol' will be meaningfully defined (later) only once:
3378ca4445c7SIlya Fursov                                                    in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3379d405a339SMatthew Knepley 
33803c633725SBarry 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>");
33813c633725SBarry 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()");
33823c633725SBarry 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");
3383a6772fa2SLisandro Dalcin 
3384c61711c8SStefano Zampini   if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3385c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3386c61711c8SStefano Zampini   ts->time_step0 = ts->time_step;
3387c61711c8SStefano Zampini 
3388be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
33899371c9d4SSatish Balay   ptime = ts->ptime;
3390c61711c8SStefano Zampini 
33919371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
33922808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3393fc8dbba5SLisandro Dalcin 
33949566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3395dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
33969566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3397fc8dbba5SLisandro Dalcin 
3398fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3399be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34002808aa04SLisandro Dalcin     ts->steps++;
3401be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
340228d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3403c6bf8827SStefano Zampini     ts->stepresize   = PETSC_FALSE;
3404d2daff3dSHong Zhang   }
3405fc8dbba5SLisandro Dalcin 
34065c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
34075c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
340809cb0f53SBarry Smith     PetscCheck(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 use unlimited to attempt recovery", TSConvergedReasons[ts->reason]);
34095c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
34105c9bbc89SJed Brown   }
34113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
341208c7845fSBarry Smith }
341308c7845fSBarry Smith 
341408c7845fSBarry Smith /*@
34157cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34167cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
34177cbde773SLisandro Dalcin 
3418c3339decSBarry Smith   Collective
34197cbde773SLisandro Dalcin 
34204165533cSJose E. Roman   Input Parameters:
34217cbde773SLisandro Dalcin + ts        - time stepping context
3422bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34237cbde773SLisandro Dalcin 
342497bb3fdcSJose E. Roman   Input/Output Parameter:
3425bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
342697bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
342797bb3fdcSJose E. Roman 
342897bb3fdcSJose E. Roman   Output Parameter:
342997bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
34307cbde773SLisandro Dalcin 
34317cbde773SLisandro Dalcin   Level: advanced
34327cbde773SLisandro Dalcin 
3433bcf0153eSBarry Smith   Note:
34347cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
34357cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
34367cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
34377cbde773SLisandro Dalcin 
34381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34397cbde773SLisandro Dalcin @*/
3440d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3441d71ae5a4SJacob Faibussowitsch {
34427cbde773SLisandro Dalcin   PetscFunctionBegin;
34437cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34447cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3445064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
34464f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
34477cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
34484f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
34493c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3450dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
34513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34527cbde773SLisandro Dalcin }
34537cbde773SLisandro Dalcin 
345405175c85SJed Brown /*@
345505175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
345605175c85SJed Brown 
3457c3339decSBarry Smith   Collective
345805175c85SJed Brown 
34594165533cSJose E. Roman   Input Parameters:
34601c3436cfSJed Brown + ts    - time stepping context
34611c3436cfSJed Brown . order - desired order of accuracy
3462195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
346305175c85SJed Brown 
34644165533cSJose E. Roman   Output Parameter:
34650910c330SBarry Smith . U - state at the end of the current step
346605175c85SJed Brown 
346705175c85SJed Brown   Level: advanced
346805175c85SJed Brown 
3469108c343cSJed Brown   Notes:
3470108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3471108c343cSJed Brown 
3472bcf0153eSBarry Smith   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.
3473bcf0153eSBarry Smith 
34741cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
347505175c85SJed Brown @*/
3476d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3477d71ae5a4SJacob Faibussowitsch {
347805175c85SJed Brown   PetscFunctionBegin;
347905175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
348005175c85SJed Brown   PetscValidType(ts, 1);
34810910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3482dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
34833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
348405175c85SJed Brown }
348505175c85SJed Brown 
3486aad739acSMatthew G. Knepley /*@C
34872e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3488aad739acSMatthew G. Knepley 
3489aad739acSMatthew G. Knepley   Not collective
3490aad739acSMatthew G. Knepley 
34914165533cSJose E. Roman   Input Parameter:
3492aad739acSMatthew G. Knepley . ts - time stepping context
3493aad739acSMatthew G. Knepley 
34944165533cSJose E. Roman   Output Parameter:
3495b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3496aad739acSMatthew G. Knepley 
349720f4b53cSBarry Smith   Calling sequence of `initCondition`:
349820f4b53cSBarry Smith + ts - The timestepping context
349920f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3500bcf0153eSBarry Smith 
3501aad739acSMatthew G. Knepley   Level: advanced
3502aad739acSMatthew G. Knepley 
35031cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3504aad739acSMatthew G. Knepley @*/
350514d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3506d71ae5a4SJacob Faibussowitsch {
3507aad739acSMatthew G. Knepley   PetscFunctionBegin;
3508aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35094f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
35102e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
35113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3512aad739acSMatthew G. Knepley }
3513aad739acSMatthew G. Knepley 
3514aad739acSMatthew G. Knepley /*@C
35152e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3516aad739acSMatthew G. Knepley 
3517c3339decSBarry Smith   Logically collective
3518aad739acSMatthew G. Knepley 
35194165533cSJose E. Roman   Input Parameters:
3520aad739acSMatthew G. Knepley + ts            - time stepping context
35212e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3522aad739acSMatthew G. Knepley 
352320f4b53cSBarry Smith   Calling sequence of `initCondition`:
3524a96d6ef6SBarry Smith + ts - The timestepping context
352514d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3526aad739acSMatthew G. Knepley 
3527bcf0153eSBarry Smith   Level: advanced
3528bcf0153eSBarry Smith 
35291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3530aad739acSMatthew G. Knepley @*/
353114d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3532d71ae5a4SJacob Faibussowitsch {
3533aad739acSMatthew G. Knepley   PetscFunctionBegin;
3534aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35352e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35362e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
35373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3538aad739acSMatthew G. Knepley }
3539aad739acSMatthew G. Knepley 
3540aad739acSMatthew G. Knepley /*@
3541bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3542aad739acSMatthew G. Knepley 
3543c3339decSBarry Smith   Collective
3544aad739acSMatthew G. Knepley 
35454165533cSJose E. Roman   Input Parameters:
3546aad739acSMatthew G. Knepley + ts - time stepping context
3547bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3548aad739acSMatthew G. Knepley 
3549aad739acSMatthew G. Knepley   Level: advanced
3550aad739acSMatthew G. Knepley 
35511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3552aad739acSMatthew G. Knepley @*/
3553d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3554d71ae5a4SJacob Faibussowitsch {
3555aad739acSMatthew G. Knepley   PetscFunctionBegin;
3556aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3557aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3558dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
35593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3560aad739acSMatthew G. Knepley }
3561aad739acSMatthew G. Knepley 
3562aad739acSMatthew G. Knepley /*@C
3563aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3564aad739acSMatthew G. Knepley 
3565aad739acSMatthew G. Knepley   Not collective
3566aad739acSMatthew G. Knepley 
35674165533cSJose E. Roman   Input Parameter:
3568aad739acSMatthew G. Knepley . ts - time stepping context
3569aad739acSMatthew G. Knepley 
35704165533cSJose E. Roman   Output Parameter:
3571aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3572aad739acSMatthew G. Knepley 
357320f4b53cSBarry Smith   Calling sequence of `exactError`:
3574a96d6ef6SBarry Smith + ts - The timestepping context
3575a96d6ef6SBarry Smith . u  - The approximate solution vector
357620f4b53cSBarry Smith - e  - The vector in which the error is stored
3577aad739acSMatthew G. Knepley 
3578bcf0153eSBarry Smith   Level: advanced
3579bcf0153eSBarry Smith 
358042747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3581aad739acSMatthew G. Knepley @*/
358214d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3583d71ae5a4SJacob Faibussowitsch {
3584aad739acSMatthew G. Knepley   PetscFunctionBegin;
3585aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35864f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3587aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
35883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3589aad739acSMatthew G. Knepley }
3590aad739acSMatthew G. Knepley 
3591aad739acSMatthew G. Knepley /*@C
3592aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3593aad739acSMatthew G. Knepley 
3594c3339decSBarry Smith   Logically collective
3595aad739acSMatthew G. Knepley 
35964165533cSJose E. Roman   Input Parameters:
3597aad739acSMatthew G. Knepley + ts         - time stepping context
3598aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3599aad739acSMatthew G. Knepley 
360020f4b53cSBarry Smith   Calling sequence of `exactError`:
3601a96d6ef6SBarry Smith + ts - The timestepping context
3602a96d6ef6SBarry Smith . u  - The approximate solution vector
360320f4b53cSBarry Smith - e  - The  vector in which the error is stored
3604aad739acSMatthew G. Knepley 
3605bcf0153eSBarry Smith   Level: advanced
3606bcf0153eSBarry Smith 
36071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3608aad739acSMatthew G. Knepley @*/
360914d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3610d71ae5a4SJacob Faibussowitsch {
3611aad739acSMatthew G. Knepley   PetscFunctionBegin;
3612aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3613f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3614aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
36153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3616aad739acSMatthew G. Knepley }
3617aad739acSMatthew G. Knepley 
3618aad739acSMatthew G. Knepley /*@
3619bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3620aad739acSMatthew G. Knepley 
3621c3339decSBarry Smith   Collective
3622aad739acSMatthew G. Knepley 
36234165533cSJose E. Roman   Input Parameters:
3624aad739acSMatthew G. Knepley + ts - time stepping context
3625aad739acSMatthew G. Knepley . u  - The approximate solution
3626bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3627aad739acSMatthew G. Knepley 
3628aad739acSMatthew G. Knepley   Level: advanced
3629aad739acSMatthew G. Knepley 
36301cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3631aad739acSMatthew G. Knepley @*/
3632d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3633d71ae5a4SJacob Faibussowitsch {
3634aad739acSMatthew G. Knepley   PetscFunctionBegin;
3635aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3636aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3637aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3638dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
36393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3640aad739acSMatthew G. Knepley }
3641aad739acSMatthew G. Knepley 
36426bd3a4fdSStefano Zampini /*@C
36436bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
36446bd3a4fdSStefano Zampini 
36456bd3a4fdSStefano Zampini   Logically Collective
36466bd3a4fdSStefano Zampini 
36476bd3a4fdSStefano Zampini   Input Parameters:
36486bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
3649ecc87898SStefano Zampini . rollback - Whether a resize will restart the step
36506bd3a4fdSStefano Zampini . setup    - The setup function
365114d0ab18SJacob Faibussowitsch . transfer - The transfer function
365214d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
36536bd3a4fdSStefano Zampini 
36546bd3a4fdSStefano Zampini   Calling sequence of `setup`:
36558847d985SBarry Smith + ts     - the `TS` context
36566bd3a4fdSStefano Zampini . step   - the current step
36576bd3a4fdSStefano Zampini . time   - the current time
36586bd3a4fdSStefano Zampini . state  - the current vector of state
36596bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
36606bd3a4fdSStefano Zampini - ctx    - user defined context
36616bd3a4fdSStefano Zampini 
36626bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
36638847d985SBarry Smith + ts      - the `TS` context
36646bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
36656bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
36666bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
36676bd3a4fdSStefano Zampini - ctx     - user defined context
36686bd3a4fdSStefano Zampini 
36696bd3a4fdSStefano Zampini   Notes:
3670ecc87898SStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
3671ecc87898SStefano Zampini   depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
3672ecc87898SStefano Zampini   and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
3673ecc87898SStefano Zampini   that the size of the discrete problem has changed.
3674ecc87898SStefano Zampini   In both cases, the solver will collect the needed vectors that will be
3675ecc87898SStefano Zampini   transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
3676ecc87898SStefano Zampini   current solution vector, and other vectors needed by the specific solver used.
36776bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
36786bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
36796bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
36806bd3a4fdSStefano Zampini   inside the `transfer` function.
36816bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
36826bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
36836bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
36846bd3a4fdSStefano Zampini 
36856bd3a4fdSStefano Zampini   Level: advanced
36866bd3a4fdSStefano Zampini 
36876bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
36886bd3a4fdSStefano Zampini @*/
3689ecc87898SStefano Zampini PetscErrorCode TSSetResize(TS ts, PetscBool rollback, PetscErrorCode (*setup)(TS ts, PetscInt step, PetscReal time, Vec state, PetscBool *resize, void *ctx), PetscErrorCode (*transfer)(TS ts, PetscInt nv, Vec vecsin[], Vec vecsout[], void *ctx), void *ctx)
36906bd3a4fdSStefano Zampini {
36916bd3a4fdSStefano Zampini   PetscFunctionBegin;
36926bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3693ecc87898SStefano Zampini   ts->resizerollback = rollback;
36946bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
36956bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
36966bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
36976bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
36986bd3a4fdSStefano Zampini }
36996bd3a4fdSStefano Zampini 
370014d0ab18SJacob Faibussowitsch /*
37016bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
37026bd3a4fdSStefano Zampini 
37036bd3a4fdSStefano Zampini   Collective
37046bd3a4fdSStefano Zampini 
37056bd3a4fdSStefano Zampini   Input Parameters:
37066bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
37076bd3a4fdSStefano Zampini - flg - If `PETSC_TRUE` each TS implementation (e.g. `TSBDF`) will register vectors to be transferred, if `PETSC_FALSE` vectors will be imported from transferred vectors.
37086bd3a4fdSStefano Zampini 
37096bd3a4fdSStefano Zampini   Level: developer
37106bd3a4fdSStefano Zampini 
37116bd3a4fdSStefano Zampini   Note:
37126bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
37136bd3a4fdSStefano Zampini    used within time stepping implementations,
37146bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
37156bd3a4fdSStefano Zampini 
37166bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
37176bd3a4fdSStefano Zampini @*/
371814d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
37196bd3a4fdSStefano Zampini {
37206bd3a4fdSStefano Zampini   PetscFunctionBegin;
37216bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37226bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
37236bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
37246bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37256bd3a4fdSStefano Zampini }
37266bd3a4fdSStefano Zampini 
372714d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
37286bd3a4fdSStefano Zampini {
37296bd3a4fdSStefano Zampini   PetscFunctionBegin;
37306bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37316bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
37326bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37336bd3a4fdSStefano Zampini }
37346bd3a4fdSStefano Zampini 
37356bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
37366bd3a4fdSStefano Zampini {
37376bd3a4fdSStefano Zampini   PetscFunctionBegin;
37386bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37396bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
37406bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
37416bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
37426bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
37436bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
37446bd3a4fdSStefano Zampini   }
37456bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
37466bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37476bd3a4fdSStefano Zampini }
37486bd3a4fdSStefano Zampini 
37496bd3a4fdSStefano Zampini /*@C
37506bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
37516bd3a4fdSStefano Zampini 
37526bd3a4fdSStefano Zampini   Collective
37536bd3a4fdSStefano Zampini 
37546bd3a4fdSStefano Zampini   Input Parameters:
37556bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3756baca6076SPierre Jolivet . name - A string identifying the vector
37576bd3a4fdSStefano Zampini - vec  - The vector
37586bd3a4fdSStefano Zampini 
37596bd3a4fdSStefano Zampini   Level: developer
37606bd3a4fdSStefano Zampini 
37616bd3a4fdSStefano Zampini   Note:
37626bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
37636bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
37646bd3a4fdSStefano Zampini 
37656bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
37666bd3a4fdSStefano Zampini @*/
3767cc4c1da9SBarry Smith PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
37686bd3a4fdSStefano Zampini {
37696bd3a4fdSStefano Zampini   PetscFunctionBegin;
37706bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37714f572ea9SToby Isaac   PetscAssertPointer(name, 2);
37726bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
37736bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
37746bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37756bd3a4fdSStefano Zampini }
37766bd3a4fdSStefano Zampini 
37776bd3a4fdSStefano Zampini /*@C
37786bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
37796bd3a4fdSStefano Zampini 
37806bd3a4fdSStefano Zampini   Collective
37816bd3a4fdSStefano Zampini 
37826bd3a4fdSStefano Zampini   Input Parameters:
37836bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3784baca6076SPierre Jolivet . name - A string identifying the vector
37856bd3a4fdSStefano Zampini - vec  - The vector
37866bd3a4fdSStefano Zampini 
37876bd3a4fdSStefano Zampini   Level: developer
37886bd3a4fdSStefano Zampini 
37896bd3a4fdSStefano Zampini   Note:
37906bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
37916bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
37926bd3a4fdSStefano Zampini 
37936bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
37946bd3a4fdSStefano Zampini @*/
3795cc4c1da9SBarry Smith PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
37966bd3a4fdSStefano Zampini {
37976bd3a4fdSStefano Zampini   PetscFunctionBegin;
37986bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37994f572ea9SToby Isaac   PetscAssertPointer(name, 2);
38004f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
38016bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
38026bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38036bd3a4fdSStefano Zampini }
38046bd3a4fdSStefano Zampini 
38056bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
38066bd3a4fdSStefano Zampini {
38076bd3a4fdSStefano Zampini   PetscInt        cnt;
38086bd3a4fdSStefano Zampini   PetscObjectList tmp;
38096bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
38106bd3a4fdSStefano Zampini   const char    **namesin = NULL;
38116bd3a4fdSStefano Zampini 
38126bd3a4fdSStefano Zampini   PetscFunctionBegin;
38136bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
38146bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
381503ba6ac9SBarry Smith   if (names) PetscCall(PetscMalloc1(cnt, &namesin));
381603ba6ac9SBarry Smith   if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
38176bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
38186bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
38196bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
38206bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
38216bd3a4fdSStefano Zampini       cnt++;
38226bd3a4fdSStefano Zampini     }
38236bd3a4fdSStefano Zampini   }
38246bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
38256bd3a4fdSStefano Zampini   if (names) *names = namesin;
38266bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
38276bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38286bd3a4fdSStefano Zampini }
38296bd3a4fdSStefano Zampini 
38306bd3a4fdSStefano Zampini /*@
38316bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
38326bd3a4fdSStefano Zampini 
38336bd3a4fdSStefano Zampini   Collective
38346bd3a4fdSStefano Zampini 
38356bd3a4fdSStefano Zampini   Input Parameter:
38366bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
38376bd3a4fdSStefano Zampini 
38386bd3a4fdSStefano Zampini   Level: developer
38396bd3a4fdSStefano Zampini 
38406bd3a4fdSStefano Zampini   Note:
38416bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
38426bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38436bd3a4fdSStefano Zampini 
38446bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38456bd3a4fdSStefano Zampini @*/
38466bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
38476bd3a4fdSStefano Zampini {
38486bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
38496bd3a4fdSStefano Zampini   const char **names   = NULL;
38506bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
38516bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
38526bd3a4fdSStefano Zampini 
38536bd3a4fdSStefano Zampini   PetscFunctionBegin;
38546bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3855ecc87898SStefano Zampini   if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
38566bd3a4fdSStefano Zampini   if (ts->resizesetup) {
38576bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
3858c6bf8827SStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
38596bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
3860c6bf8827SStefano Zampini     if (ts->stepresize) {
3861ecc87898SStefano Zampini       if (ts->resizerollback) {
3862ecc87898SStefano Zampini         PetscCall(TSRollBack(ts));
3863ecc87898SStefano Zampini         ts->time_step = ts->time_step0;
3864ecc87898SStefano Zampini       }
38656bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
38666bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
38676bd3a4fdSStefano Zampini     }
38686bd3a4fdSStefano Zampini   }
38696bd3a4fdSStefano Zampini 
38706bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
38716bd3a4fdSStefano Zampini   if (nv) {
38726bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
38736bd3a4fdSStefano Zampini 
38746bd3a4fdSStefano Zampini     /* Reset internal objects */
38756bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
38766bd3a4fdSStefano Zampini 
3877ecc87898SStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
38786bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
38796bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
38806bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
3881ecc87898SStefano Zampini       const char *name;
3882ecc87898SStefano Zampini       char       *oname;
3883ecc87898SStefano Zampini 
3884ecc87898SStefano Zampini       PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
3885ecc87898SStefano Zampini       PetscCall(PetscStrallocpy(name, &oname));
38866bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
3887ecc87898SStefano Zampini       if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
3888ecc87898SStefano Zampini       PetscCall(PetscFree(oname));
38896bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
38906bd3a4fdSStefano Zampini     }
38916bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
38926bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
38936bd3a4fdSStefano Zampini 
38946bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
38956bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
38966bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
38976bd3a4fdSStefano Zampini   }
38986bd3a4fdSStefano Zampini 
38996bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
39006bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
39016bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
39026bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39036bd3a4fdSStefano Zampini }
39046bd3a4fdSStefano Zampini 
3905b1cb36f3SHong Zhang /*@
39066a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
39076a4d4014SLisandro Dalcin 
3908c3339decSBarry Smith   Collective
39096a4d4014SLisandro Dalcin 
3910d8d19677SJose E. Roman   Input Parameters:
3911bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
3912bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
391363e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
39145a3a76d0SJed Brown 
39156a4d4014SLisandro Dalcin   Level: beginner
39166a4d4014SLisandro Dalcin 
39175a3a76d0SJed Brown   Notes:
39185a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
3919bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
39205a3a76d0SJed Brown   stepped over the final time.
39215a3a76d0SJed Brown 
39221cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
39236a4d4014SLisandro Dalcin @*/
3924d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3925d71ae5a4SJacob Faibussowitsch {
3926b06615a5SLisandro Dalcin   Vec solution;
3927f22f69f0SBarry Smith 
39286a4d4014SLisandro Dalcin   PetscFunctionBegin;
39290700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3930f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3931303a5415SBarry Smith 
39329566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3933ee41a567SStefano 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 */
39340910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
39359566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
39369566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
39379566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
39385a3a76d0SJed Brown     }
39399566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
39403c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
39411baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
39429566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
39439566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3944a6772fa2SLisandro Dalcin 
39453c633725SBarry 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>");
39463c633725SBarry 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()");
39473c633725SBarry 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");
39484a658b32SHong 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");
39494a658b32SHong Zhang 
3950e1db57b0SHong 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 */
39514a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
39524a658b32SHong Zhang     ts->tspan->spanctr = 1;
39534a658b32SHong Zhang   }
3954a6772fa2SLisandro Dalcin 
39551baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3956715f1b00SHong Zhang 
3957e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3958715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3959e7069c78SShri      TSTrajectory to incorrectly save the output files
3960e7069c78SShri   */
3961715f1b00SHong Zhang   /* reset time step and iteration counters */
39622808aa04SLisandro Dalcin   if (!ts->steps) {
39635ef26d82SJed Brown     ts->ksp_its           = 0;
39645ef26d82SJed Brown     ts->snes_its          = 0;
3965c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3966c610991cSLisandro Dalcin     ts->reject            = 0;
39672808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
39682808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
3969c6bf8827SStefano Zampini     ts->stepresize        = PETSC_FALSE;
39707d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
39712808aa04SLisandro Dalcin   }
3972e97c63d7SStefano Zampini 
39734a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3974e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
39754a658b32SHong Zhang     PetscReal maxdt;
3976e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3977e97c63d7SStefano Zampini 
39784a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
39794a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3980e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3981e97c63d7SStefano Zampini   }
3982193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3983193ac0bcSJed Brown 
3984900f6b5bSMatthew G. Knepley   {
3985900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3986900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3987900f6b5bSMatthew G. Knepley     PetscBool         flg;
3988900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3989900f6b5bSMatthew G. Knepley 
3990900f6b5bSMatthew G. Knepley     if (!incall) {
3991900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
3992648c30bcSBarry Smith       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3993900f6b5bSMatthew G. Knepley       if (flg) {
3994900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3995900f6b5bSMatthew G. Knepley         DM           dm;
3996900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3997900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3998f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3999900f6b5bSMatthew G. Knepley 
4000900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
40019566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
40029566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
40039566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
40049566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
40059566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
40069566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
40079566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
40089566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
40099566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
40109566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
40119566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
40129566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
40139566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
4014648c30bcSBarry Smith         PetscCall(PetscViewerDestroy(&viewer));
40159566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
40169566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
4017900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
4018900f6b5bSMatthew G. Knepley       }
4019900f6b5bSMatthew G. Knepley     }
4020900f6b5bSMatthew G. Knepley   }
4021900f6b5bSMatthew G. Knepley 
40229566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4023f05ece33SBarry Smith 
4024193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4025dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
40269566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4027cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4028a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4029be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4030db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4031db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4032e7069c78SShri 
40332808aa04SLisandro Dalcin     if (!ts->steps) {
40349566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40359566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
40362808aa04SLisandro Dalcin     }
40376427ac75SLisandro Dalcin 
4038e1a7a14fSJed Brown     while (!ts->reason) {
40399566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4040c6bf8827SStefano Zampini       if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
40419566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
40421baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
40431baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4044cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
40457b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
40469566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
40477b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4048b1cb36f3SHong Zhang       }
404958818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
40507b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
40519566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
40527b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4053715f1b00SHong Zhang       }
40549566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
40559566063dSJacob 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. */
40561baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4057ecc87898SStefano Zampini       if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
405890d719a4SStefano Zampini       /* check convergence */
405990d719a4SStefano Zampini       if (!ts->reason) {
406090d719a4SStefano Zampini         if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
406190d719a4SStefano Zampini         else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
406290d719a4SStefano Zampini       }
4063e783b05fSHong Zhang       if (!ts->steprollback) {
40649566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40659566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
4066ecc87898SStefano Zampini         if (!ts->resizerollback) PetscCall(TSResize(ts));
4067ca4445c7SIlya Fursov 
4068ca4445c7SIlya Fursov         if (ts->tspan && ts->tspan->spanctr < ts->tspan->num_span_times) {
4069ca4445c7SIlya Fursov           PetscCheck(ts->tspan->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(tspan->worktol > 0) in TSSolve()");
4070ca4445c7SIlya Fursov           if (PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[ts->tspan->spanctr], ts->tspan->worktol, 0)) PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
4071ca4445c7SIlya Fursov         }
4072aeb4809dSShri Abhyankar       }
4073193ac0bcSJed Brown     }
40749566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
40756427ac75SLisandro Dalcin 
407649354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
40775dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
40789566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4079cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4080b06615a5SLisandro Dalcin       solution      = u;
40819566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
40820574a7fbSJed Brown     } else {
40839566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4084cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4085b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
40860574a7fbSJed Brown     }
4087193ac0bcSJed Brown   }
4088d2daff3dSHong Zhang 
40899566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
40909566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
40919566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
40921baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
40933ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
40946a4d4014SLisandro Dalcin }
40956a4d4014SLisandro Dalcin 
4096d763cef2SBarry Smith /*@
4097b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4098d763cef2SBarry Smith 
4099d763cef2SBarry Smith   Not Collective
4100d763cef2SBarry Smith 
4101d763cef2SBarry Smith   Input Parameter:
4102bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4103d763cef2SBarry Smith 
4104d763cef2SBarry Smith   Output Parameter:
4105bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4106d763cef2SBarry Smith 
4107d763cef2SBarry Smith   Level: beginner
4108d763cef2SBarry Smith 
4109b8123daeSJed Brown   Note:
4110bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4111bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4112b8123daeSJed Brown 
4113a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4114d763cef2SBarry Smith @*/
4115d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4116d71ae5a4SJacob Faibussowitsch {
4117d763cef2SBarry Smith   PetscFunctionBegin;
41180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41194f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4120d763cef2SBarry Smith   *t = ts->ptime;
41213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4122d763cef2SBarry Smith }
4123d763cef2SBarry Smith 
4124e5e524a1SHong Zhang /*@
4125e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4126e5e524a1SHong Zhang 
4127e5e524a1SHong Zhang   Not Collective
4128e5e524a1SHong Zhang 
4129e5e524a1SHong Zhang   Input Parameter:
4130bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4131e5e524a1SHong Zhang 
4132e5e524a1SHong Zhang   Output Parameter:
4133e5e524a1SHong Zhang . t - the previous time
4134e5e524a1SHong Zhang 
4135e5e524a1SHong Zhang   Level: beginner
4136e5e524a1SHong Zhang 
4137a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4138e5e524a1SHong Zhang @*/
4139d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4140d71ae5a4SJacob Faibussowitsch {
4141e5e524a1SHong Zhang   PetscFunctionBegin;
4142e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41434f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4144e5e524a1SHong Zhang   *t = ts->ptime_prev;
41453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4146e5e524a1SHong Zhang }
4147e5e524a1SHong Zhang 
41486a4d4014SLisandro Dalcin /*@
41496a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
41506a4d4014SLisandro Dalcin 
4151c3339decSBarry Smith   Logically Collective
41526a4d4014SLisandro Dalcin 
41536a4d4014SLisandro Dalcin   Input Parameters:
4154bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4155b43aa488SJacob Faibussowitsch - t  - the time
41566a4d4014SLisandro Dalcin 
41576a4d4014SLisandro Dalcin   Level: intermediate
41586a4d4014SLisandro Dalcin 
41591cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
41606a4d4014SLisandro Dalcin @*/
4161d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4162d71ae5a4SJacob Faibussowitsch {
41636a4d4014SLisandro Dalcin   PetscFunctionBegin;
41640700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4165c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
41666a4d4014SLisandro Dalcin   ts->ptime = t;
41673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41686a4d4014SLisandro Dalcin }
41696a4d4014SLisandro Dalcin 
4170cc4c1da9SBarry Smith /*@
4171d763cef2SBarry Smith   TSSetOptionsPrefix - Sets the prefix used for searching for all
4172d763cef2SBarry Smith   TS options in the database.
4173d763cef2SBarry Smith 
4174c3339decSBarry Smith   Logically Collective
4175d763cef2SBarry Smith 
4176d8d19677SJose E. Roman   Input Parameters:
4177bcf0153eSBarry Smith + ts     - The `TS` context
4178d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4179d763cef2SBarry Smith 
4180bcf0153eSBarry Smith   Level: advanced
4181bcf0153eSBarry Smith 
4182bcf0153eSBarry Smith   Note:
4183d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4184d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4185d763cef2SBarry Smith   hyphen.
4186d763cef2SBarry Smith 
41871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4188d763cef2SBarry Smith @*/
4189d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4190d71ae5a4SJacob Faibussowitsch {
4191089b2837SJed Brown   SNES snes;
4192d763cef2SBarry Smith 
4193d763cef2SBarry Smith   PetscFunctionBegin;
41940700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41959566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
41969566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41979566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
41983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4199d763cef2SBarry Smith }
4200d763cef2SBarry Smith 
4201cc4c1da9SBarry Smith /*@
4202d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4203d763cef2SBarry Smith   TS options in the database.
4204d763cef2SBarry Smith 
4205c3339decSBarry Smith   Logically Collective
4206d763cef2SBarry Smith 
4207d8d19677SJose E. Roman   Input Parameters:
4208bcf0153eSBarry Smith + ts     - The `TS` context
4209d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4210d763cef2SBarry Smith 
4211bcf0153eSBarry Smith   Level: advanced
4212bcf0153eSBarry Smith 
4213bcf0153eSBarry Smith   Note:
4214d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4215d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4216d763cef2SBarry Smith   hyphen.
4217d763cef2SBarry Smith 
42181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4219d763cef2SBarry Smith @*/
4220d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4221d71ae5a4SJacob Faibussowitsch {
4222089b2837SJed Brown   SNES snes;
4223d763cef2SBarry Smith 
4224d763cef2SBarry Smith   PetscFunctionBegin;
42250700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42269566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
42279566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
42289566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
42293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4230d763cef2SBarry Smith }
4231d763cef2SBarry Smith 
4232cc4c1da9SBarry Smith /*@
4233d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4234bcf0153eSBarry Smith   `TS` options in the database.
4235d763cef2SBarry Smith 
4236d763cef2SBarry Smith   Not Collective
4237d763cef2SBarry Smith 
4238d763cef2SBarry Smith   Input Parameter:
4239bcf0153eSBarry Smith . ts - The `TS` context
4240d763cef2SBarry Smith 
4241d763cef2SBarry Smith   Output Parameter:
4242d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4243d763cef2SBarry Smith 
4244d763cef2SBarry Smith   Level: intermediate
4245d763cef2SBarry Smith 
4246b43aa488SJacob Faibussowitsch   Fortran Notes:
4247195e9b02SBarry Smith   The user should pass in a string 'prefix' of
4248bcf0153eSBarry Smith   sufficient length to hold the prefix.
4249bcf0153eSBarry Smith 
42501cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4251d763cef2SBarry Smith @*/
4252d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4253d71ae5a4SJacob Faibussowitsch {
4254d763cef2SBarry Smith   PetscFunctionBegin;
42550700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42564f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
42579566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
42583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4259d763cef2SBarry Smith }
4260d763cef2SBarry Smith 
4261d763cef2SBarry Smith /*@C
4262d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4263d763cef2SBarry Smith 
4264bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4265d763cef2SBarry Smith 
4266d763cef2SBarry Smith   Input Parameter:
4267bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4268d763cef2SBarry Smith 
4269d763cef2SBarry Smith   Output Parameters:
4270195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4271195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4272195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4273195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4274d763cef2SBarry Smith 
4275d763cef2SBarry Smith   Level: intermediate
4276d763cef2SBarry Smith 
4277bcf0153eSBarry Smith   Note:
4278195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4279bcf0153eSBarry Smith 
42801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4281d763cef2SBarry Smith 
4282d763cef2SBarry Smith @*/
42838434afd1SBarry Smith PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, void **ctx)
4284d71ae5a4SJacob Faibussowitsch {
428524989b8cSPeter Brune   DM dm;
4286089b2837SJed Brown 
4287d763cef2SBarry Smith   PetscFunctionBegin;
428823a57915SBarry Smith   if (Amat || Pmat) {
428923a57915SBarry Smith     SNES snes;
42909566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
42919566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
42929566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
429323a57915SBarry Smith   }
42949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
42959566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
42963ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4297d763cef2SBarry Smith }
4298d763cef2SBarry Smith 
42992eca1d9cSJed Brown /*@C
43002eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
43012eca1d9cSJed Brown 
4302bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
43032eca1d9cSJed Brown 
43042eca1d9cSJed Brown   Input Parameter:
4305bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
43062eca1d9cSJed Brown 
43072eca1d9cSJed Brown   Output Parameters:
4308e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4309195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
43102eca1d9cSJed Brown . f    - The function to compute the matrices
43112eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
43122eca1d9cSJed Brown 
43132eca1d9cSJed Brown   Level: advanced
43142eca1d9cSJed Brown 
4315bcf0153eSBarry Smith   Note:
4316195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4317bcf0153eSBarry Smith 
43181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
43192eca1d9cSJed Brown @*/
43208434afd1SBarry Smith PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, void **ctx)
4321d71ae5a4SJacob Faibussowitsch {
432224989b8cSPeter Brune   DM dm;
43230910c330SBarry Smith 
43242eca1d9cSJed Brown   PetscFunctionBegin;
4325c0aab802Sstefano_zampini   if (Amat || Pmat) {
4326c0aab802Sstefano_zampini     SNES snes;
43279566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
43289566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
43299566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4330c0aab802Sstefano_zampini   }
43319566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
43329566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
43333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43342eca1d9cSJed Brown }
43352eca1d9cSJed Brown 
4336af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
43376c699258SBarry Smith /*@
4338bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
43396c699258SBarry Smith 
4340c3339decSBarry Smith   Logically Collective
43416c699258SBarry Smith 
43426c699258SBarry Smith   Input Parameters:
4343bcf0153eSBarry Smith + ts - the `TS` integrator object
4344195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
43456c699258SBarry Smith 
43466c699258SBarry Smith   Level: intermediate
43476c699258SBarry Smith 
4348bcf0153eSBarry Smith   Notes:
4349bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4350bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4351bcf0153eSBarry Smith   different problems using the same function space.
4352bcf0153eSBarry Smith 
43531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
43546c699258SBarry Smith @*/
4355d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4356d71ae5a4SJacob Faibussowitsch {
4357089b2837SJed Brown   SNES snes;
4358942e3340SBarry Smith   DMTS tsdm;
43596c699258SBarry Smith 
43606c699258SBarry Smith   PetscFunctionBegin;
43610700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43622a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
43639566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4364942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
43652a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
43669566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
43679566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
43681e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
43691e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
437024989b8cSPeter Brune     }
43719566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
437224989b8cSPeter Brune   }
43736c699258SBarry Smith   ts->dm = dm;
4374bbd56ea5SKarl Rupp 
43759566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43769566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
43773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43786c699258SBarry Smith }
43796c699258SBarry Smith 
43806c699258SBarry Smith /*@
4381bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
43826c699258SBarry Smith 
43833f9fe445SBarry Smith   Not Collective
43846c699258SBarry Smith 
43856c699258SBarry Smith   Input Parameter:
4386bcf0153eSBarry Smith . ts - the `TS`
43876c699258SBarry Smith 
43886c699258SBarry Smith   Output Parameter:
4389195e9b02SBarry Smith . dm - the `DM`
43906c699258SBarry Smith 
43916c699258SBarry Smith   Level: intermediate
43926c699258SBarry Smith 
43931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
43946c699258SBarry Smith @*/
4395d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4396d71ae5a4SJacob Faibussowitsch {
43976c699258SBarry Smith   PetscFunctionBegin;
43980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4399496e6a7aSJed Brown   if (!ts->dm) {
44009566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
44019566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4402496e6a7aSJed Brown   }
44036c699258SBarry Smith   *dm = ts->dm;
44043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44056c699258SBarry Smith }
44061713a123SBarry Smith 
44070f5c6efeSJed Brown /*@
44080f5c6efeSJed Brown   SNESTSFormFunction - Function to evaluate nonlinear residual
44090f5c6efeSJed Brown 
4410c3339decSBarry Smith   Logically Collective
44110f5c6efeSJed Brown 
4412d8d19677SJose E. Roman   Input Parameters:
4413d42a1c89SJed Brown + snes - nonlinear solver
44140910c330SBarry Smith . U    - the current state at which to evaluate the residual
4415d42a1c89SJed Brown - ctx  - user context, must be a TS
44160f5c6efeSJed Brown 
44170f5c6efeSJed Brown   Output Parameter:
44180f5c6efeSJed Brown . F - the nonlinear residual
44190f5c6efeSJed Brown 
44200f5c6efeSJed Brown   Level: advanced
44210f5c6efeSJed Brown 
4422bcf0153eSBarry Smith   Note:
4423bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4424bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4425bcf0153eSBarry Smith 
44261cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
44270f5c6efeSJed Brown @*/
4428d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4429d71ae5a4SJacob Faibussowitsch {
44300f5c6efeSJed Brown   TS ts = (TS)ctx;
44310f5c6efeSJed Brown 
44320f5c6efeSJed Brown   PetscFunctionBegin;
44330f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
44340910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
44350f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
44360f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
4437346ce620SStefano Zampini   PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4438346ce620SStefano Zampini   PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
44393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44400f5c6efeSJed Brown }
44410f5c6efeSJed Brown 
44420f5c6efeSJed Brown /*@
44430f5c6efeSJed Brown   SNESTSFormJacobian - Function to evaluate the Jacobian
44440f5c6efeSJed Brown 
4445c3339decSBarry Smith   Collective
44460f5c6efeSJed Brown 
4447d8d19677SJose E. Roman   Input Parameters:
44480f5c6efeSJed Brown + snes - nonlinear solver
44490910c330SBarry Smith . U    - the current state at which to evaluate the residual
4450bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
44510f5c6efeSJed Brown 
4452d8d19677SJose E. Roman   Output Parameters:
44530f5c6efeSJed Brown + A - the Jacobian
44546b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
44550f5c6efeSJed Brown 
44560f5c6efeSJed Brown   Level: developer
44570f5c6efeSJed Brown 
4458bcf0153eSBarry Smith   Note:
4459bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4460bcf0153eSBarry Smith 
44611cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
44620f5c6efeSJed Brown @*/
4463d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4464d71ae5a4SJacob Faibussowitsch {
44650f5c6efeSJed Brown   TS ts = (TS)ctx;
44660f5c6efeSJed Brown 
44670f5c6efeSJed Brown   PetscFunctionBegin;
44680f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
44690910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
447094ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
447194ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4472064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
4473346ce620SStefano Zampini   PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4474346ce620SStefano Zampini   PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
44753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44760f5c6efeSJed Brown }
4477325fc9f4SBarry Smith 
44780e4ef248SJed Brown /*@C
4479dd8e379bSPierre Jolivet   TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
44800e4ef248SJed Brown 
4481c3339decSBarry Smith   Collective
44820e4ef248SJed Brown 
44834165533cSJose E. Roman   Input Parameters:
44840e4ef248SJed Brown + ts  - time stepping context
44850e4ef248SJed Brown . t   - time at which to evaluate
44860910c330SBarry Smith . U   - state at which to evaluate
44870e4ef248SJed Brown - ctx - context
44880e4ef248SJed Brown 
44894165533cSJose E. Roman   Output Parameter:
4490dd8e379bSPierre Jolivet . F - right-hand side
44910e4ef248SJed Brown 
44920e4ef248SJed Brown   Level: intermediate
44930e4ef248SJed Brown 
4494bcf0153eSBarry Smith   Note:
4495dd8e379bSPierre Jolivet   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4496bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
44970e4ef248SJed Brown 
44981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
44990e4ef248SJed Brown @*/
4500d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4501d71ae5a4SJacob Faibussowitsch {
45020e4ef248SJed Brown   Mat Arhs, Brhs;
45030e4ef248SJed Brown 
45040e4ef248SJed Brown   PetscFunctionBegin;
45059566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
45062663174eSHong Zhang   /* undo the damage caused by shifting */
45079566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
45089566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
45099566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
45103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45110e4ef248SJed Brown }
45120e4ef248SJed Brown 
45130e4ef248SJed Brown /*@C
45140e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
45150e4ef248SJed Brown 
4516c3339decSBarry Smith   Collective
45170e4ef248SJed Brown 
45184165533cSJose E. Roman   Input Parameters:
45190e4ef248SJed Brown + ts  - time stepping context
45200e4ef248SJed Brown . t   - time at which to evaluate
45210910c330SBarry Smith . U   - state at which to evaluate
45220e4ef248SJed Brown - ctx - context
45230e4ef248SJed Brown 
45244165533cSJose E. Roman   Output Parameters:
45250e4ef248SJed Brown + A - pointer to operator
452697bb3fdcSJose E. Roman - B - pointer to preconditioning matrix
45270e4ef248SJed Brown 
45280e4ef248SJed Brown   Level: intermediate
45290e4ef248SJed Brown 
4530bcf0153eSBarry Smith   Note:
4531bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
45320e4ef248SJed Brown 
45331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
45340e4ef248SJed Brown @*/
4535d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4536d71ae5a4SJacob Faibussowitsch {
45370e4ef248SJed Brown   PetscFunctionBegin;
45383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45390e4ef248SJed Brown }
45400e4ef248SJed Brown 
45410026cea9SSean Farley /*@C
45420026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
45430026cea9SSean Farley 
4544c3339decSBarry Smith   Collective
45450026cea9SSean Farley 
45464165533cSJose E. Roman   Input Parameters:
45470026cea9SSean Farley + ts   - time stepping context
45480026cea9SSean Farley . t    - time at which to evaluate
45490910c330SBarry Smith . U    - state at which to evaluate
45500910c330SBarry Smith . Udot - time derivative of state vector
45510026cea9SSean Farley - ctx  - context
45520026cea9SSean Farley 
45534165533cSJose E. Roman   Output Parameter:
45540026cea9SSean Farley . F - left hand side
45550026cea9SSean Farley 
45560026cea9SSean Farley   Level: intermediate
45570026cea9SSean Farley 
45580026cea9SSean Farley   Notes:
45590910c330SBarry 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
4560bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4561bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4562bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
45630026cea9SSean Farley 
4564bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
45659ae8fd06SBarry Smith 
45661cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
45670026cea9SSean Farley @*/
4568d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4569d71ae5a4SJacob Faibussowitsch {
45700026cea9SSean Farley   Mat A, B;
45710026cea9SSean Farley 
45720026cea9SSean Farley   PetscFunctionBegin;
45739566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
45749566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
45759566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
45763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45770026cea9SSean Farley }
45780026cea9SSean Farley 
45790026cea9SSean Farley /*@C
45808434afd1SBarry Smith   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
45810026cea9SSean Farley 
4582c3339decSBarry Smith   Collective
45830026cea9SSean Farley 
45844165533cSJose E. Roman   Input Parameters:
45850026cea9SSean Farley + ts    - time stepping context
45860026cea9SSean Farley . t     - time at which to evaluate
45870910c330SBarry Smith . U     - state at which to evaluate
45880910c330SBarry Smith . Udot  - time derivative of state vector
45890026cea9SSean Farley . shift - shift to apply
45900026cea9SSean Farley - ctx   - context
45910026cea9SSean Farley 
45924165533cSJose E. Roman   Output Parameters:
45930026cea9SSean Farley + A - pointer to operator
4594d1c5d1fcSBarry Smith - B - pointer to matrix from which the preconditioner is built (often `A`)
45950026cea9SSean Farley 
4596b41af12eSJed Brown   Level: advanced
45970026cea9SSean Farley 
45980026cea9SSean Farley   Notes:
4599bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
46000026cea9SSean Farley 
4601b41af12eSJed Brown   It is only appropriate for problems of the form
4602b41af12eSJed Brown 
4603d1c5d1fcSBarry Smith   $$
4604d1c5d1fcSBarry Smith   M \dot{U} = F(U,t)
4605d1c5d1fcSBarry Smith   $$
4606b41af12eSJed Brown 
4607bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4608bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4609b41af12eSJed Brown   an implicit operator of the form
4610b41af12eSJed Brown 
4611d1c5d1fcSBarry Smith   $$
4612d1c5d1fcSBarry Smith   shift*M + J
4613d1c5d1fcSBarry Smith   $$
4614b41af12eSJed Brown 
4615b41af12eSJed 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
4616b41af12eSJed Brown   a copy of M or reassemble it when requested.
4617b41af12eSJed Brown 
46181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
46190026cea9SSean Farley @*/
4620d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4621d71ae5a4SJacob Faibussowitsch {
46220026cea9SSean Farley   PetscFunctionBegin;
46239566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4624b41af12eSJed Brown   ts->ijacobian.shift = shift;
46253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46260026cea9SSean Farley }
4627b41af12eSJed Brown 
4628e817cc15SEmil Constantinescu /*@
4629bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4630e817cc15SEmil Constantinescu 
4631e817cc15SEmil Constantinescu   Not Collective
4632e817cc15SEmil Constantinescu 
4633e817cc15SEmil Constantinescu   Input Parameter:
4634bcf0153eSBarry Smith . ts - the `TS` context
4635e817cc15SEmil Constantinescu 
4636e817cc15SEmil Constantinescu   Output Parameter:
4637bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4638e817cc15SEmil Constantinescu 
4639e817cc15SEmil Constantinescu   Level: beginner
4640e817cc15SEmil Constantinescu 
46411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4642e817cc15SEmil Constantinescu @*/
4643d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4644d71ae5a4SJacob Faibussowitsch {
4645e817cc15SEmil Constantinescu   PetscFunctionBegin;
4646e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46474f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4648e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
46493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4650e817cc15SEmil Constantinescu }
4651e817cc15SEmil Constantinescu 
4652e817cc15SEmil Constantinescu /*@
4653bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4654e817cc15SEmil Constantinescu 
4655e817cc15SEmil Constantinescu   Not Collective
4656e817cc15SEmil Constantinescu 
4657d8d19677SJose E. Roman   Input Parameters:
4658bcf0153eSBarry Smith + ts            - the `TS` context
4659bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4660e817cc15SEmil Constantinescu 
4661e817cc15SEmil Constantinescu   Level: advanced
4662e817cc15SEmil Constantinescu 
46631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4664e817cc15SEmil Constantinescu @*/
4665d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4666d71ae5a4SJacob Faibussowitsch {
4667e817cc15SEmil Constantinescu   PetscFunctionBegin;
4668e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4669e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
46703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4671e817cc15SEmil Constantinescu }
46720026cea9SSean Farley 
46734af1b03aSJed Brown /*@
4674bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
46754af1b03aSJed Brown 
46764af1b03aSJed Brown   Not Collective
46774af1b03aSJed Brown 
46784af1b03aSJed Brown   Input Parameter:
4679bcf0153eSBarry Smith . ts - the `TS` context
46804af1b03aSJed Brown 
46814af1b03aSJed Brown   Output Parameter:
4682bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
46834af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
46844af1b03aSJed Brown 
4685487e0bb9SJed Brown   Level: beginner
46864af1b03aSJed Brown 
4687bcf0153eSBarry Smith   Note:
4688bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
46894af1b03aSJed Brown 
46907d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
46914af1b03aSJed Brown @*/
4692d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4693d71ae5a4SJacob Faibussowitsch {
46944af1b03aSJed Brown   PetscFunctionBegin;
46954af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46964f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
46974af1b03aSJed Brown   *reason = ts->reason;
46983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46994af1b03aSJed Brown }
47004af1b03aSJed Brown 
4701d6ad946cSShri Abhyankar /*@
4702bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4703d6ad946cSShri Abhyankar 
47046b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4705d6ad946cSShri Abhyankar 
47066b221cbeSPatrick Sanan   Input Parameters:
4707bcf0153eSBarry Smith + ts     - the `TS` context
4708bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4709d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4710d6ad946cSShri Abhyankar 
4711f5abba47SShri Abhyankar   Level: advanced
4712d6ad946cSShri Abhyankar 
4713bcf0153eSBarry Smith   Note:
4714bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4715d6ad946cSShri Abhyankar 
47161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4717d6ad946cSShri Abhyankar @*/
4718d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4719d71ae5a4SJacob Faibussowitsch {
4720d6ad946cSShri Abhyankar   PetscFunctionBegin;
4721d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4722d6ad946cSShri Abhyankar   ts->reason = reason;
47233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4724d6ad946cSShri Abhyankar }
4725d6ad946cSShri Abhyankar 
4726cc708dedSBarry Smith /*@
4727bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4728cc708dedSBarry Smith 
4729cc708dedSBarry Smith   Not Collective
4730cc708dedSBarry Smith 
4731cc708dedSBarry Smith   Input Parameter:
4732bcf0153eSBarry Smith . ts - the `TS` context
4733cc708dedSBarry Smith 
4734cc708dedSBarry Smith   Output Parameter:
4735bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4736cc708dedSBarry Smith 
4737487e0bb9SJed Brown   Level: beginner
4738cc708dedSBarry Smith 
4739bcf0153eSBarry Smith   Note:
4740bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4741cc708dedSBarry Smith 
47427d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4743cc708dedSBarry Smith @*/
4744d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4745d71ae5a4SJacob Faibussowitsch {
4746cc708dedSBarry Smith   PetscFunctionBegin;
4747cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47484f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4749cc708dedSBarry Smith   *ftime = ts->solvetime;
47503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4751cc708dedSBarry Smith }
4752cc708dedSBarry Smith 
47532c18e0fdSBarry Smith /*@
47545ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
47559f67acb7SJed Brown   used by the time integrator.
47569f67acb7SJed Brown 
47579f67acb7SJed Brown   Not Collective
47589f67acb7SJed Brown 
47599f67acb7SJed Brown   Input Parameter:
4760bcf0153eSBarry Smith . ts - `TS` context
47619f67acb7SJed Brown 
47629f67acb7SJed Brown   Output Parameter:
47639f67acb7SJed Brown . nits - number of nonlinear iterations
47649f67acb7SJed Brown 
47659f67acb7SJed Brown   Level: intermediate
47669f67acb7SJed Brown 
4767195e9b02SBarry Smith   Note:
4768bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4769bcf0153eSBarry Smith 
47701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
47719f67acb7SJed Brown @*/
4772d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4773d71ae5a4SJacob Faibussowitsch {
47749f67acb7SJed Brown   PetscFunctionBegin;
47759f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47764f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
47775ef26d82SJed Brown   *nits = ts->snes_its;
47783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47799f67acb7SJed Brown }
47809f67acb7SJed Brown 
47819f67acb7SJed Brown /*@
47825ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
47839f67acb7SJed Brown   used by the time integrator.
47849f67acb7SJed Brown 
47859f67acb7SJed Brown   Not Collective
47869f67acb7SJed Brown 
47879f67acb7SJed Brown   Input Parameter:
4788bcf0153eSBarry Smith . ts - `TS` context
47899f67acb7SJed Brown 
47909f67acb7SJed Brown   Output Parameter:
47919f67acb7SJed Brown . lits - number of linear iterations
47929f67acb7SJed Brown 
47939f67acb7SJed Brown   Level: intermediate
47949f67acb7SJed Brown 
4795bcf0153eSBarry Smith   Note:
4796bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4797bcf0153eSBarry Smith 
47981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
47999f67acb7SJed Brown @*/
4800d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4801d71ae5a4SJacob Faibussowitsch {
48029f67acb7SJed Brown   PetscFunctionBegin;
48039f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48044f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
48055ef26d82SJed Brown   *lits = ts->ksp_its;
48063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48079f67acb7SJed Brown }
48089f67acb7SJed Brown 
4809cef5090cSJed Brown /*@
4810cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4811cef5090cSJed Brown 
4812cef5090cSJed Brown   Not Collective
4813cef5090cSJed Brown 
4814cef5090cSJed Brown   Input Parameter:
4815bcf0153eSBarry Smith . ts - `TS` context
4816cef5090cSJed Brown 
4817cef5090cSJed Brown   Output Parameter:
4818cef5090cSJed Brown . rejects - number of steps rejected
4819cef5090cSJed Brown 
4820cef5090cSJed Brown   Level: intermediate
4821cef5090cSJed Brown 
4822bcf0153eSBarry Smith   Note:
4823bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4824bcf0153eSBarry Smith 
48251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4826cef5090cSJed Brown @*/
4827d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4828d71ae5a4SJacob Faibussowitsch {
4829cef5090cSJed Brown   PetscFunctionBegin;
4830cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48314f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4832cef5090cSJed Brown   *rejects = ts->reject;
48333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4834cef5090cSJed Brown }
4835cef5090cSJed Brown 
4836cef5090cSJed Brown /*@
4837bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4838cef5090cSJed Brown 
4839cef5090cSJed Brown   Not Collective
4840cef5090cSJed Brown 
4841cef5090cSJed Brown   Input Parameter:
4842bcf0153eSBarry Smith . ts - `TS` context
4843cef5090cSJed Brown 
4844cef5090cSJed Brown   Output Parameter:
4845cef5090cSJed Brown . fails - number of failed nonlinear solves
4846cef5090cSJed Brown 
4847cef5090cSJed Brown   Level: intermediate
4848cef5090cSJed Brown 
4849bcf0153eSBarry Smith   Note:
4850bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4851bcf0153eSBarry Smith 
48521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4853cef5090cSJed Brown @*/
4854d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4855d71ae5a4SJacob Faibussowitsch {
4856cef5090cSJed Brown   PetscFunctionBegin;
4857cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48584f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
4859cef5090cSJed Brown   *fails = ts->num_snes_failures;
48603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4861cef5090cSJed Brown }
4862cef5090cSJed Brown 
4863cef5090cSJed Brown /*@
4864bcf0153eSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4865cef5090cSJed Brown 
4866cef5090cSJed Brown   Not Collective
4867cef5090cSJed Brown 
4868d8d19677SJose E. Roman   Input Parameters:
4869bcf0153eSBarry Smith + ts      - `TS` context
487009cb0f53SBarry Smith - rejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
4871cef5090cSJed Brown 
4872cef5090cSJed Brown   Options Database Key:
4873cef5090cSJed Brown . -ts_max_reject - Maximum number of step rejections before a step fails
4874cef5090cSJed Brown 
4875cef5090cSJed Brown   Level: intermediate
4876cef5090cSJed Brown 
487709cb0f53SBarry Smith   Developer Note:
487809cb0f53SBarry Smith   The options database name is incorrect.
487909cb0f53SBarry Smith 
48801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4881cef5090cSJed Brown @*/
4882d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4883d71ae5a4SJacob Faibussowitsch {
4884cef5090cSJed Brown   PetscFunctionBegin;
4885cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
488609cb0f53SBarry Smith   if (rejects == PETSC_UNLIMITED || rejects == -1) {
488709cb0f53SBarry Smith     ts->max_reject = PETSC_UNLIMITED;
488809cb0f53SBarry Smith   } else {
488909cb0f53SBarry Smith     PetscCheck(rejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
4890cef5090cSJed Brown     ts->max_reject = rejects;
489109cb0f53SBarry Smith   }
48923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4893cef5090cSJed Brown }
4894cef5090cSJed Brown 
4895cef5090cSJed Brown /*@
4896bcf0153eSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4897cef5090cSJed Brown 
4898cef5090cSJed Brown   Not Collective
4899cef5090cSJed Brown 
4900d8d19677SJose E. Roman   Input Parameters:
4901bcf0153eSBarry Smith + ts    - `TS` context
490209cb0f53SBarry Smith - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
4903cef5090cSJed Brown 
4904cef5090cSJed Brown   Options Database Key:
4905cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
4906cef5090cSJed Brown 
4907cef5090cSJed Brown   Level: intermediate
4908cef5090cSJed Brown 
49091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4910cef5090cSJed Brown @*/
4911d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4912d71ae5a4SJacob Faibussowitsch {
4913cef5090cSJed Brown   PetscFunctionBegin;
4914cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
491509cb0f53SBarry Smith   if (fails == PETSC_UNLIMITED || fails == -1) {
491609cb0f53SBarry Smith     ts->max_snes_failures = PETSC_UNLIMITED;
491709cb0f53SBarry Smith   } else {
491809cb0f53SBarry Smith     PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
4919cef5090cSJed Brown     ts->max_snes_failures = fails;
492009cb0f53SBarry Smith   }
49213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4922cef5090cSJed Brown }
4923cef5090cSJed Brown 
4924cef5090cSJed Brown /*@
4925195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
4926cef5090cSJed Brown 
4927cef5090cSJed Brown   Not Collective
4928cef5090cSJed Brown 
4929d8d19677SJose E. Roman   Input Parameters:
4930bcf0153eSBarry Smith + ts  - `TS` context
4931bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4932cef5090cSJed Brown 
4933cef5090cSJed Brown   Options Database Key:
4934cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
4935cef5090cSJed Brown 
4936cef5090cSJed Brown   Level: intermediate
4937cef5090cSJed Brown 
493842747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
4939cef5090cSJed Brown @*/
4940d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4941d71ae5a4SJacob Faibussowitsch {
4942cef5090cSJed Brown   PetscFunctionBegin;
4943cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4944cef5090cSJed Brown   ts->errorifstepfailed = err;
49453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4946cef5090cSJed Brown }
4947cef5090cSJed Brown 
494884df9cb4SJed Brown /*@
4949552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
495084df9cb4SJed Brown 
49518f14a041SBarry Smith   Collective if controller has not yet been created
495284df9cb4SJed Brown 
49534165533cSJose E. Roman   Input Parameter:
4954ed81e22dSJed Brown . ts - time stepping context
495584df9cb4SJed Brown 
49564165533cSJose E. Roman   Output Parameter:
4957ed81e22dSJed Brown . adapt - adaptive controller
495884df9cb4SJed Brown 
495984df9cb4SJed Brown   Level: intermediate
496084df9cb4SJed Brown 
49611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
496284df9cb4SJed Brown @*/
4963d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4964d71ae5a4SJacob Faibussowitsch {
496584df9cb4SJed Brown   PetscFunctionBegin;
496684df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49674f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
496884df9cb4SJed Brown   if (!ts->adapt) {
49699566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
49709566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
497184df9cb4SJed Brown   }
4972bec58848SLisandro Dalcin   *adapt = ts->adapt;
49733ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
497484df9cb4SJed Brown }
4975d6ebe24aSShri Abhyankar 
49761c3436cfSJed Brown /*@
4977195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
49781c3436cfSJed Brown 
49791c3436cfSJed Brown   Logically Collective
49801c3436cfSJed Brown 
49814165533cSJose E. Roman   Input Parameters:
49821c3436cfSJed Brown + ts    - time integration context
498309cb0f53SBarry Smith . atol  - scalar absolute tolerances
498409cb0f53SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
498509cb0f53SBarry Smith . rtol  - scalar relative tolerances
498609cb0f53SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
49871c3436cfSJed Brown 
4988195e9b02SBarry Smith   Options Database Keys:
4989a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
499067b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
4991a3cdaa26SBarry Smith 
4992bcf0153eSBarry Smith   Level: beginner
4993bcf0153eSBarry Smith 
49943ff766beSShri Abhyankar   Notes:
499509cb0f53SBarry Smith   `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
499609cb0f53SBarry Smith   or the default value from when the object's type was set.
499709cb0f53SBarry Smith 
49983ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
49993ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
50003ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
50013ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
50023ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
50033ff766beSShri Abhyankar   differential variables.
50043ff766beSShri Abhyankar 
500509cb0f53SBarry Smith   Fortran Note:
500609cb0f53SBarry Smith   Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
500709cb0f53SBarry Smith 
50081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
50091c3436cfSJed Brown @*/
5010d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5011d71ae5a4SJacob Faibussowitsch {
50121c3436cfSJed Brown   PetscFunctionBegin;
501309cb0f53SBarry Smith   if (atol == (PetscReal)PETSC_DETERMINE) {
501409cb0f53SBarry Smith     ts->atol = atol = ts->default_atol;
501509cb0f53SBarry Smith   } else if (atol != (PetscReal)PETSC_CURRENT) {
501609cb0f53SBarry Smith     PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
501709cb0f53SBarry Smith     ts->atol = atol;
501809cb0f53SBarry Smith   }
501909cb0f53SBarry Smith 
50201c3436cfSJed Brown   if (vatol) {
50219566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
50229566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
50231c3436cfSJed Brown     ts->vatol = vatol;
50241c3436cfSJed Brown   }
502509cb0f53SBarry Smith 
502609cb0f53SBarry Smith   if (rtol == (PetscReal)PETSC_DETERMINE) {
502709cb0f53SBarry Smith     ts->rtol = atol = ts->default_rtol;
502809cb0f53SBarry Smith   } else if (rtol != (PetscReal)PETSC_CURRENT) {
502909cb0f53SBarry Smith     PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
503009cb0f53SBarry Smith     ts->rtol = rtol;
503109cb0f53SBarry Smith   }
503209cb0f53SBarry Smith 
50331c3436cfSJed Brown   if (vrtol) {
50349566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
50359566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
50361c3436cfSJed Brown     ts->vrtol = vrtol;
50371c3436cfSJed Brown   }
50383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
50391c3436cfSJed Brown }
50401c3436cfSJed Brown 
5041c5033834SJed Brown /*@
5042c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5043c5033834SJed Brown 
5044c5033834SJed Brown   Logically Collective
5045c5033834SJed Brown 
50464165533cSJose E. Roman   Input Parameter:
5047c5033834SJed Brown . ts - time integration context
5048c5033834SJed Brown 
50494165533cSJose E. Roman   Output Parameters:
5050195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
5051195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
5052195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
5053195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
5054c5033834SJed Brown 
5055c5033834SJed Brown   Level: beginner
5056c5033834SJed Brown 
50571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5058c5033834SJed Brown @*/
5059d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5060d71ae5a4SJacob Faibussowitsch {
5061c5033834SJed Brown   PetscFunctionBegin;
5062c5033834SJed Brown   if (atol) *atol = ts->atol;
5063c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
5064c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
5065c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
50663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5067c5033834SJed Brown }
5068c5033834SJed Brown 
50699c6b16b5SShri Abhyankar /*@
50708a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
50711c3436cfSJed Brown 
5072c3339decSBarry Smith   Collective
50731c3436cfSJed Brown 
50744165533cSJose E. Roman   Input Parameters:
50751c3436cfSJed Brown + ts        - time stepping context
5076a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5077a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5078bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
50797619abb3SShri 
50804165533cSJose E. Roman   Output Parameters:
5081a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
50828a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5083a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5084a4868fbcSLisandro Dalcin 
5085bcf0153eSBarry Smith   Options Database Key:
5086a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5087a4868fbcSLisandro Dalcin 
50881c3436cfSJed Brown   Level: developer
50891c3436cfSJed Brown 
50908c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
50911c3436cfSJed Brown @*/
5092d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5093d71ae5a4SJacob Faibussowitsch {
5094037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
50958a175baeSEmil Constantinescu 
50968a175baeSEmil Constantinescu   PetscFunctionBegin;
50978a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5098037d63e4SStefano Zampini   PetscCall(VecErrorWeightedNorms(U, Y, NULL, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5099037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5100037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5101037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5102037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
51038a175baeSEmil Constantinescu   }
51043c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
51053c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
51063c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51088a175baeSEmil Constantinescu }
51098a175baeSEmil Constantinescu 
51108a175baeSEmil Constantinescu /*@
51118a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
51128a175baeSEmil Constantinescu 
5113c3339decSBarry Smith   Collective
51148a175baeSEmil Constantinescu 
51154165533cSJose E. Roman   Input Parameters:
51168a175baeSEmil Constantinescu + ts        - time stepping context
51178a175baeSEmil Constantinescu . E         - error vector
51188a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
51198a175baeSEmil Constantinescu . Y         - state vector, previous time step
5120bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51218a175baeSEmil Constantinescu 
51224165533cSJose E. Roman   Output Parameters:
5123a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51248a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5125a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
51268a175baeSEmil Constantinescu 
5127bcf0153eSBarry Smith   Options Database Key:
51288a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
51298a175baeSEmil Constantinescu 
51308a175baeSEmil Constantinescu   Level: developer
51318a175baeSEmil Constantinescu 
51328c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
51338a175baeSEmil Constantinescu @*/
5134d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5135d71ae5a4SJacob Faibussowitsch {
5136037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5137037d63e4SStefano Zampini 
51388a175baeSEmil Constantinescu   PetscFunctionBegin;
5139037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5140037d63e4SStefano Zampini   PetscCall(VecErrorWeightedNorms(U, Y, E, wnormtype, ts->atol, ts->vatol, ts->rtol, ts->vrtol, ts->adapt->ignore_max, norm, &norm_loc, norma, &norma_loc, normr, &normr_loc));
5141037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5142037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5143037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5144037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5145037d63e4SStefano Zampini   }
5146037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5147037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5148037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51508a175baeSEmil Constantinescu }
51518a175baeSEmil Constantinescu 
51528d59e960SJed Brown /*@
51538d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
51548d59e960SJed Brown 
5155c3339decSBarry Smith   Logically Collective
51568d59e960SJed Brown 
51574165533cSJose E. Roman   Input Parameters:
51588d59e960SJed Brown + ts      - time stepping context
51598d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
51608d59e960SJed Brown 
51618d59e960SJed Brown   Note:
51628d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
51638d59e960SJed Brown 
51648d59e960SJed Brown   Level: intermediate
51658d59e960SJed Brown 
51661cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
51678d59e960SJed Brown @*/
5168d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5169d71ae5a4SJacob Faibussowitsch {
51708d59e960SJed Brown   PetscFunctionBegin;
51718d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51728d59e960SJed Brown   ts->cfltime_local = cfltime;
51738d59e960SJed Brown   ts->cfltime       = -1.;
51743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51758d59e960SJed Brown }
51768d59e960SJed Brown 
51778d59e960SJed Brown /*@
51788d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
51798d59e960SJed Brown 
5180c3339decSBarry Smith   Collective
51818d59e960SJed Brown 
51824165533cSJose E. Roman   Input Parameter:
51838d59e960SJed Brown . ts - time stepping context
51848d59e960SJed Brown 
51854165533cSJose E. Roman   Output Parameter:
51868d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
51878d59e960SJed Brown 
51888d59e960SJed Brown   Level: advanced
51898d59e960SJed Brown 
51901cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
51918d59e960SJed Brown @*/
5192d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5193d71ae5a4SJacob Faibussowitsch {
51948d59e960SJed Brown   PetscFunctionBegin;
51951e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
51968d59e960SJed Brown   *cfltime = ts->cfltime;
51973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51988d59e960SJed Brown }
51998d59e960SJed Brown 
5200d6ebe24aSShri Abhyankar /*@
5201d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5202d6ebe24aSShri Abhyankar 
5203d6ebe24aSShri Abhyankar   Input Parameters:
5204bcf0153eSBarry Smith + ts - the `TS` context.
5205d6ebe24aSShri Abhyankar . xl - lower bound.
5206a2b725a8SWilliam Gropp - xu - upper bound.
5207d6ebe24aSShri Abhyankar 
52082bd2b0e6SSatish Balay   Level: advanced
52092bd2b0e6SSatish Balay 
5210bcf0153eSBarry Smith   Note:
5211bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5212bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5213bcf0153eSBarry Smith 
52141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5215d6ebe24aSShri Abhyankar @*/
5216d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5217d71ae5a4SJacob Faibussowitsch {
5218d6ebe24aSShri Abhyankar   SNES snes;
5219d6ebe24aSShri Abhyankar 
5220d6ebe24aSShri Abhyankar   PetscFunctionBegin;
52219566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
52229566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
52233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5224d6ebe24aSShri Abhyankar }
5225d6ebe24aSShri Abhyankar 
5226f9c1d6abSBarry Smith /*@
5227f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5228f9c1d6abSBarry Smith 
5229c3339decSBarry Smith   Collective
5230f9c1d6abSBarry Smith 
5231f9c1d6abSBarry Smith   Input Parameters:
5232bcf0153eSBarry Smith + ts - the `TS` context
52332fe279fdSBarry Smith . xr - real part of input argument
52342fe279fdSBarry Smith - xi - imaginary part of input argument
5235f9c1d6abSBarry Smith 
5236f9c1d6abSBarry Smith   Output Parameters:
52372fe279fdSBarry Smith + yr - real part of function value
52382fe279fdSBarry Smith - yi - imaginary part of function value
5239f9c1d6abSBarry Smith 
5240f9c1d6abSBarry Smith   Level: developer
5241f9c1d6abSBarry Smith 
52421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5243f9c1d6abSBarry Smith @*/
5244d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5245d71ae5a4SJacob Faibussowitsch {
5246f9c1d6abSBarry Smith   PetscFunctionBegin;
5247f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5248dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
52493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5250f9c1d6abSBarry Smith }
525124655328SShri 
525224655328SShri /*@
5253dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5254dcb233daSLisandro Dalcin 
5255c3339decSBarry Smith   Collective
5256dcb233daSLisandro Dalcin 
5257dcb233daSLisandro Dalcin   Input Parameter:
5258bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5259dcb233daSLisandro Dalcin 
5260dcb233daSLisandro Dalcin   Level: advanced
5261dcb233daSLisandro Dalcin 
5262dcb233daSLisandro Dalcin   Notes:
5263bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5264dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5265dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5266bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5267dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5268dcb233daSLisandro Dalcin   discontinuous source terms).
5269dcb233daSLisandro Dalcin 
52701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5271dcb233daSLisandro Dalcin @*/
5272d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5273d71ae5a4SJacob Faibussowitsch {
5274dcb233daSLisandro Dalcin   PetscFunctionBegin;
5275dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5276dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
52773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5278dcb233daSLisandro Dalcin }
5279dcb233daSLisandro Dalcin 
5280dcb233daSLisandro Dalcin /*@
528124655328SShri   TSRollBack - Rolls back one time step
528224655328SShri 
5283c3339decSBarry Smith   Collective
528424655328SShri 
528524655328SShri   Input Parameter:
5286bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
528724655328SShri 
528824655328SShri   Level: advanced
528924655328SShri 
52909dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
529124655328SShri @*/
5292d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5293d71ae5a4SJacob Faibussowitsch {
529424655328SShri   PetscFunctionBegin;
529524655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
52963c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5297c61711c8SStefano Zampini   PetscTryTypeMethod(ts, rollback);
5298c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
529924655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
530024655328SShri   ts->ptime      = ts->ptime_prev;
5301be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
53022808aa04SLisandro Dalcin   ts->steps--;
5303b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
53043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
530524655328SShri }
5306aeb4809dSShri Abhyankar 
5307ff22ae23SHong Zhang /*@
53089dc50cb5SStefano Zampini   TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
53099dc50cb5SStefano Zampini 
53109dc50cb5SStefano Zampini   Not collective
53119dc50cb5SStefano Zampini 
53129dc50cb5SStefano Zampini   Input Parameter:
53139dc50cb5SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
53149dc50cb5SStefano Zampini 
53159dc50cb5SStefano Zampini   Output Parameter:
53169dc50cb5SStefano Zampini . flg - the rollback flag
53179dc50cb5SStefano Zampini 
53189dc50cb5SStefano Zampini   Level: advanced
53199dc50cb5SStefano Zampini 
53209dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
53219dc50cb5SStefano Zampini @*/
53229dc50cb5SStefano Zampini PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
53239dc50cb5SStefano Zampini {
53249dc50cb5SStefano Zampini   PetscFunctionBegin;
53259dc50cb5SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53269dc50cb5SStefano Zampini   PetscAssertPointer(flg, 2);
53279dc50cb5SStefano Zampini   *flg = ts->steprollback;
53289dc50cb5SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
53299dc50cb5SStefano Zampini }
53309dc50cb5SStefano Zampini 
53319dc50cb5SStefano Zampini /*@
5332c6bf8827SStefano Zampini   TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5333c6bf8827SStefano Zampini 
5334c6bf8827SStefano Zampini   Not collective
5335c6bf8827SStefano Zampini 
5336c6bf8827SStefano Zampini   Input Parameter:
5337c6bf8827SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
5338c6bf8827SStefano Zampini 
5339c6bf8827SStefano Zampini   Output Parameter:
5340c6bf8827SStefano Zampini . flg - the resize flag
5341c6bf8827SStefano Zampini 
5342c6bf8827SStefano Zampini   Level: advanced
5343c6bf8827SStefano Zampini 
5344c6bf8827SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5345c6bf8827SStefano Zampini @*/
5346c6bf8827SStefano Zampini PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5347c6bf8827SStefano Zampini {
5348c6bf8827SStefano Zampini   PetscFunctionBegin;
5349c6bf8827SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5350c6bf8827SStefano Zampini   PetscAssertPointer(flg, 2);
5351c6bf8827SStefano Zampini   *flg = ts->stepresize;
5352c6bf8827SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
5353c6bf8827SStefano Zampini }
5354c6bf8827SStefano Zampini 
5355c6bf8827SStefano Zampini /*@
5356ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5357ff22ae23SHong Zhang 
5358ff22ae23SHong Zhang   Input Parameter:
5359bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5360ff22ae23SHong Zhang 
53610429704eSStefano Zampini   Output Parameters:
53620429704eSStefano Zampini + ns - the number of stages
53630429704eSStefano Zampini - Y  - the current stage vectors
53640429704eSStefano Zampini 
5365ff22ae23SHong Zhang   Level: advanced
5366ff22ae23SHong Zhang 
5367bcf0153eSBarry Smith   Note:
5368195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
53690429704eSStefano Zampini 
53701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5371ff22ae23SHong Zhang @*/
5372d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5373d71ae5a4SJacob Faibussowitsch {
5374ff22ae23SHong Zhang   PetscFunctionBegin;
5375ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53764f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
53774f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
53780429704eSStefano Zampini   if (!ts->ops->getstages) {
53790429704eSStefano Zampini     if (ns) *ns = 0;
53800429704eSStefano Zampini     if (Y) *Y = NULL;
5381dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
53823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5383ff22ae23SHong Zhang }
5384ff22ae23SHong Zhang 
5385847ff0e1SMatthew G. Knepley /*@C
5386847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5387847ff0e1SMatthew G. Knepley 
5388c3339decSBarry Smith   Collective
5389847ff0e1SMatthew G. Knepley 
5390847ff0e1SMatthew G. Knepley   Input Parameters:
5391bcf0153eSBarry Smith + ts    - the `TS` context
5392847ff0e1SMatthew G. Knepley . t     - current timestep
5393847ff0e1SMatthew G. Knepley . U     - state vector
5394847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5395847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5396847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5397847ff0e1SMatthew G. Knepley 
5398847ff0e1SMatthew G. Knepley   Output Parameters:
5399847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5400195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5401847ff0e1SMatthew G. Knepley 
5402847ff0e1SMatthew G. Knepley   Level: intermediate
5403847ff0e1SMatthew G. Knepley 
5404847ff0e1SMatthew G. Knepley   Notes:
5405847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5406847ff0e1SMatthew G. Knepley 
5407847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5408847ff0e1SMatthew G. Knepley 
5409847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5410847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5411847ff0e1SMatthew G. Knepley 
5412bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5413847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5414847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5415847ff0e1SMatthew G. Knepley 
54161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5417847ff0e1SMatthew G. Knepley @*/
5418d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5419d71ae5a4SJacob Faibussowitsch {
5420847ff0e1SMatthew G. Knepley   SNES          snes;
5421847ff0e1SMatthew G. Knepley   MatFDColoring color;
5422847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5423847ff0e1SMatthew G. Knepley 
5424847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
54259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
54269566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5427847ff0e1SMatthew G. Knepley   if (!color) {
5428847ff0e1SMatthew G. Knepley     DM         dm;
5429847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5430847ff0e1SMatthew G. Knepley 
54319566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
54329566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5433847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
54349566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
54359566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
54369566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
54379566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
54389566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
54399566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5440847ff0e1SMatthew G. Knepley     } else {
5441847ff0e1SMatthew G. Knepley       MatColoring mc;
5442847ff0e1SMatthew G. Knepley 
54439566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
54449566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
54459566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
54469566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
54479566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
54489566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
54499566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
54509566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
54519566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
54529566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
54539566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5454847ff0e1SMatthew G. Knepley     }
54559566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
54569566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5457847ff0e1SMatthew G. Knepley   }
54589566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
54599566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5460847ff0e1SMatthew G. Knepley   if (J != B) {
54619566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
54629566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5463847ff0e1SMatthew G. Knepley   }
54643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5465847ff0e1SMatthew G. Knepley }
546693b34091SDebojyoti Ghosh 
5467b43aa488SJacob Faibussowitsch /*@C
54686bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5469cb9d8021SPierre Barbier de Reuille 
5470cb9d8021SPierre Barbier de Reuille   Input Parameters:
5471bcf0153eSBarry Smith + ts   - the `TS` context
5472bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
54736bc98fa9SBarry Smith 
547420f4b53cSBarry Smith   Calling sequence of `func`:
54758847d985SBarry Smith + ts     - the `TS` context
54766bc98fa9SBarry Smith . time   - the current time (of the stage)
54776bc98fa9SBarry Smith . state  - the state to check if it is valid
5478a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5479cb9d8021SPierre Barbier de Reuille 
5480cb9d8021SPierre Barbier de Reuille   Level: intermediate
5481cb9d8021SPierre Barbier de Reuille 
54826bc98fa9SBarry Smith   Notes:
54836bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5484bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5485bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5486bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
54876bc98fa9SBarry Smith 
5488b43aa488SJacob Faibussowitsch   Developer Notes:
5489bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
54906bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
54916bc98fa9SBarry Smith 
54921cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5493cb9d8021SPierre Barbier de Reuille @*/
5494a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5495d71ae5a4SJacob Faibussowitsch {
5496cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5497cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5498cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
54993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5500cb9d8021SPierre Barbier de Reuille }
5501cb9d8021SPierre Barbier de Reuille 
5502cb9d8021SPierre Barbier de Reuille /*@
55036bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5504cb9d8021SPierre Barbier de Reuille 
5505cb9d8021SPierre Barbier de Reuille   Input Parameters:
5506bcf0153eSBarry Smith + ts        - the `TS` context
55076bc98fa9SBarry Smith . stagetime - time of the simulation
55086bc98fa9SBarry Smith - Y         - state vector to check.
5509cb9d8021SPierre Barbier de Reuille 
5510cb9d8021SPierre Barbier de Reuille   Output Parameter:
5511bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
551296a0c994SBarry Smith 
55136bc98fa9SBarry Smith   Level: developer
55146bc98fa9SBarry Smith 
5515bcf0153eSBarry Smith   Note:
5516bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5517bcf0153eSBarry Smith   to check if the current state is valid.
5518bcf0153eSBarry Smith 
55191cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5520cb9d8021SPierre Barbier de Reuille @*/
5521d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5522d71ae5a4SJacob Faibussowitsch {
5523cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5524cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5525cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
55261e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
55273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5528cb9d8021SPierre Barbier de Reuille }
55291ceb14c0SBarry Smith 
5530cc4c1da9SBarry Smith /*@
5531195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
553293b34091SDebojyoti Ghosh 
5533d083f849SBarry Smith   Collective
553493b34091SDebojyoti Ghosh 
553593b34091SDebojyoti Ghosh   Input Parameter:
5536bcf0153eSBarry Smith . tsin - The input `TS`
553793b34091SDebojyoti Ghosh 
553893b34091SDebojyoti Ghosh   Output Parameter:
5539bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
55405eca1a21SEmil Constantinescu 
55415eca1a21SEmil Constantinescu   Level: developer
554293b34091SDebojyoti Ghosh 
5543bcf0153eSBarry Smith   Notes:
5544bcf0153eSBarry Smith   This function is used to create a clone of a `TS` object. It is used in `TSARKIMEX` for initializing the slope for first stage explicit methods.
5545bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5546bcf0153eSBarry Smith 
5547195e9b02SBarry Smith   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
5548195e9b02SBarry Smith .vb
5549195e9b02SBarry Smith  SNES snes_dup = NULL;
5550195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5551195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5552195e9b02SBarry Smith .ve
5553bcf0153eSBarry Smith 
55541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
555593b34091SDebojyoti Ghosh @*/
5556d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5557d71ae5a4SJacob Faibussowitsch {
555893b34091SDebojyoti Ghosh   TS     t;
5559dc846ba4SSatish Balay   SNES   snes_start;
5560dc846ba4SSatish Balay   DM     dm;
5561dc846ba4SSatish Balay   TSType type;
556293b34091SDebojyoti Ghosh 
556393b34091SDebojyoti Ghosh   PetscFunctionBegin;
55644f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
556593b34091SDebojyoti Ghosh   *tsout = NULL;
556693b34091SDebojyoti Ghosh 
55679566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
556893b34091SDebojyoti Ghosh 
556993b34091SDebojyoti Ghosh   /* General TS description */
557093b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5571d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
557293b34091SDebojyoti Ghosh   t->setupcalled       = 0;
557393b34091SDebojyoti Ghosh   t->ksp_its           = 0;
557493b34091SDebojyoti Ghosh   t->snes_its          = 0;
557593b34091SDebojyoti Ghosh   t->nwork             = 0;
55767d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
557793b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
557893b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
557993b34091SDebojyoti Ghosh 
55809566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
55819566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5582d15a3a53SEmil Constantinescu 
55839566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
55849566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
558593b34091SDebojyoti Ghosh 
558693b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
55879566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
558893b34091SDebojyoti Ghosh 
5589e7069c78SShri   t->trajectory = tsin->trajectory;
55909566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5591e7069c78SShri 
5592e7069c78SShri   t->event = tsin->event;
55936b10a48eSSatish Balay   if (t->event) t->event->refct++;
5594e7069c78SShri 
559593b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
559693b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5597e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
559893b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
559993b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
560093b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
560193b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
560293b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
560393b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
560493b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
560593b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
560693b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
560793b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
560893b34091SDebojyoti Ghosh 
56099566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
56109566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
561193b34091SDebojyoti Ghosh 
561293b34091SDebojyoti Ghosh   t->vec_sol = NULL;
561393b34091SDebojyoti Ghosh 
561493b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
561593b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
561693b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
561793b34091SDebojyoti Ghosh 
5618aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
561993b34091SDebojyoti Ghosh 
56200d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
56210d4fed19SBarry Smith     PetscInt i;
56229566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5623ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
56240d4fed19SBarry Smith   }
562593b34091SDebojyoti Ghosh   *tsout = t;
56263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
562793b34091SDebojyoti Ghosh }
5628f3b1f45cSBarry Smith 
5629d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5630d71ae5a4SJacob Faibussowitsch {
5631f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5632f3b1f45cSBarry Smith 
5633f3b1f45cSBarry Smith   PetscFunctionBegin;
56349566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
56353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5636f3b1f45cSBarry Smith }
5637f3b1f45cSBarry Smith 
5638f3b1f45cSBarry Smith /*@
5639bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5640f3b1f45cSBarry Smith 
5641c3339decSBarry Smith   Logically Collective
5642f3b1f45cSBarry Smith 
56432fe279fdSBarry Smith   Input Parameter:
5644b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5645f3b1f45cSBarry Smith 
5646f3b1f45cSBarry Smith   Output Parameter:
5647bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5648f3b1f45cSBarry Smith 
5649bcf0153eSBarry Smith   Options Database Key:
5650f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5651f3b1f45cSBarry Smith 
5652f3b1f45cSBarry Smith   Level: advanced
5653f3b1f45cSBarry Smith 
5654bcf0153eSBarry Smith   Note:
5655195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5656f3b1f45cSBarry Smith 
56571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5658f3b1f45cSBarry Smith @*/
5659d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5660d71ae5a4SJacob Faibussowitsch {
5661f3b1f45cSBarry Smith   Mat              J, B;
56628434afd1SBarry Smith   TSRHSJacobianFn *func;
5663f3b1f45cSBarry Smith   void            *ctx;
5664f3b1f45cSBarry Smith 
5665f3b1f45cSBarry Smith   PetscFunctionBegin;
56669566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
56679566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
56689566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
56693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5670f3b1f45cSBarry Smith }
5671f3b1f45cSBarry Smith 
5672cc4c1da9SBarry Smith /*@
5673bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5674f3b1f45cSBarry Smith 
5675c3339decSBarry Smith   Logically Collective
5676f3b1f45cSBarry Smith 
56772fe279fdSBarry Smith   Input Parameter:
5678b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5679f3b1f45cSBarry Smith 
5680f3b1f45cSBarry Smith   Output Parameter:
5681bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5682f3b1f45cSBarry Smith 
5683bcf0153eSBarry Smith   Options Database Key:
5684f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5685f3b1f45cSBarry Smith 
5686bcf0153eSBarry Smith   Level: advanced
5687bcf0153eSBarry Smith 
568895452b02SPatrick Sanan   Notes:
5689195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5690f3b1f45cSBarry Smith 
56911cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5692f3b1f45cSBarry Smith @*/
5693d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5694d71ae5a4SJacob Faibussowitsch {
5695f3b1f45cSBarry Smith   Mat              J, B;
5696f3b1f45cSBarry Smith   void            *ctx;
56978434afd1SBarry Smith   TSRHSJacobianFn *func;
5698f3b1f45cSBarry Smith 
5699f3b1f45cSBarry Smith   PetscFunctionBegin;
57009566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
57019566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
57029566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
57033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5704f3b1f45cSBarry Smith }
57050fe4d17eSHong Zhang 
57060fe4d17eSHong Zhang /*@
57070fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
57080fe4d17eSHong Zhang 
570920f4b53cSBarry Smith   Logically Collective
57100fe4d17eSHong Zhang 
5711d8d19677SJose E. Roman   Input Parameters:
57120fe4d17eSHong Zhang + ts                   - timestepping context
5713bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
57140fe4d17eSHong Zhang 
5715bcf0153eSBarry Smith   Options Database Key:
57160fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
57170fe4d17eSHong Zhang 
57180fe4d17eSHong Zhang   Level: intermediate
57190fe4d17eSHong Zhang 
5720bcf0153eSBarry Smith   Note:
5721195e9b02SBarry Smith   This is only for multirate methods
5722bcf0153eSBarry Smith 
57231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
57240fe4d17eSHong Zhang @*/
5725d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5726d71ae5a4SJacob Faibussowitsch {
57270fe4d17eSHong Zhang   PetscFunctionBegin;
57280fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57290fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
57303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57310fe4d17eSHong Zhang }
57320fe4d17eSHong Zhang 
57330fe4d17eSHong Zhang /*@
57340fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
57350fe4d17eSHong Zhang 
573620f4b53cSBarry Smith   Not Collective
57370fe4d17eSHong Zhang 
57380fe4d17eSHong Zhang   Input Parameter:
57390fe4d17eSHong Zhang . ts - timestepping context
57400fe4d17eSHong Zhang 
57410fe4d17eSHong Zhang   Output Parameter:
5742bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
57430fe4d17eSHong Zhang 
57440fe4d17eSHong Zhang   Level: intermediate
57450fe4d17eSHong Zhang 
57461cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
57470fe4d17eSHong Zhang @*/
5748d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5749d71ae5a4SJacob Faibussowitsch {
57500fe4d17eSHong Zhang   PetscFunctionBegin;
57510fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57520fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
57533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57540fe4d17eSHong Zhang }
5755d60b7d5cSBarry Smith 
5756d60b7d5cSBarry Smith /*@
5757d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5758d60b7d5cSBarry Smith 
5759c3339decSBarry Smith   Logically  Collective
5760d60b7d5cSBarry Smith 
5761d60b7d5cSBarry Smith   Input Parameters:
5762d60b7d5cSBarry Smith + ts  - the time-stepper
5763bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5764d60b7d5cSBarry Smith 
5765d60b7d5cSBarry Smith   Level: intermediate
5766d60b7d5cSBarry Smith 
5767bcf0153eSBarry Smith   Note:
5768d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5769d60b7d5cSBarry Smith 
57701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5771d60b7d5cSBarry Smith  @*/
5772d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5773d71ae5a4SJacob Faibussowitsch {
5774d60b7d5cSBarry Smith   PetscFunctionBegin;
5775d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5776d60b7d5cSBarry Smith   ts->axpy_pattern = str;
57773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5778d60b7d5cSBarry Smith }
57794a658b32SHong Zhang 
57804a658b32SHong Zhang /*@
5781bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
57824a658b32SHong Zhang 
5783c3339decSBarry Smith   Collective
57844a658b32SHong Zhang 
57854a658b32SHong Zhang   Input Parameters:
57864a658b32SHong Zhang + ts         - the time-stepper
57874a658b32SHong Zhang . n          - number of the time points (>=2)
57884a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
57894a658b32SHong Zhang 
5790bcf0153eSBarry Smith   Options Database Key:
57914a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
57924a658b32SHong Zhang 
5793bcf0153eSBarry Smith   Level: intermediate
57944a658b32SHong Zhang 
57954a658b32SHong Zhang   Notes:
57964a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
5797bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
5798bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
57994a658b32SHong Zhang   pressure the memory system when using a large number of span points.
58004a658b32SHong Zhang 
58011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
58024a658b32SHong Zhang  @*/
5803d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
5804d71ae5a4SJacob Faibussowitsch {
58054a658b32SHong Zhang   PetscFunctionBegin;
58064a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
580763a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
58084a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
58094a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
58104a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
58114a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
58124a658b32SHong Zhang   }
58134a658b32SHong Zhang   if (!ts->tspan) {
58144a658b32SHong Zhang     TSTimeSpan tspan;
58154a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
58164a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
5817e1db57b0SHong Zhang     tspan->reltol  = 1e-6;
5818e1db57b0SHong Zhang     tspan->abstol  = 10 * PETSC_MACHINE_EPSILON;
5819ca4445c7SIlya Fursov     tspan->worktol = 0;
58204a658b32SHong Zhang     ts->tspan      = tspan;
58214a658b32SHong Zhang   }
58224a658b32SHong Zhang   ts->tspan->num_span_times = n;
58234a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
58244a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
58254a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
58263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58274a658b32SHong Zhang }
58284a658b32SHong Zhang 
58294a658b32SHong Zhang /*@C
5830195e9b02SBarry Smith   TSGetTimeSpan - gets the time span set with `TSSetTimeSpan()`
58314a658b32SHong Zhang 
58324a658b32SHong Zhang   Not Collective
58334a658b32SHong Zhang 
58344a658b32SHong Zhang   Input Parameter:
58354a658b32SHong Zhang . ts - the time-stepper
58364a658b32SHong Zhang 
58374a658b32SHong Zhang   Output Parameters:
58384a658b32SHong Zhang + n          - number of the time points (>=2)
5839bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
58404a658b32SHong Zhang 
58414a658b32SHong Zhang   Level: beginner
58424a658b32SHong Zhang 
5843bcf0153eSBarry Smith   Note:
5844195e9b02SBarry Smith   The values obtained are valid until the `TS` object is destroyed.
5845195e9b02SBarry Smith 
5846195e9b02SBarry Smith   Both `n` and `span_times` can be `NULL`.
5847bcf0153eSBarry Smith 
58481cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
58494a658b32SHong Zhang  @*/
5850cc4c1da9SBarry Smith PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal *span_times[])
5851d71ae5a4SJacob Faibussowitsch {
58524a658b32SHong Zhang   PetscFunctionBegin;
58534a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58544f572ea9SToby Isaac   if (n) PetscAssertPointer(n, 2);
58554f572ea9SToby Isaac   if (span_times) PetscAssertPointer(span_times, 3);
58564a658b32SHong Zhang   if (!ts->tspan) {
58574a658b32SHong Zhang     if (n) *n = 0;
58584a658b32SHong Zhang     if (span_times) *span_times = NULL;
58594a658b32SHong Zhang   } else {
58604a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
58614a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
58624a658b32SHong Zhang   }
58633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58644a658b32SHong Zhang }
58654a658b32SHong Zhang 
58664a658b32SHong Zhang /*@
58674a658b32SHong Zhang   TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
58684a658b32SHong Zhang 
58694a658b32SHong Zhang   Input Parameter:
5870bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
58714a658b32SHong Zhang 
58724a658b32SHong Zhang   Output Parameters:
58734a658b32SHong Zhang + nsol - the number of solutions
58744a658b32SHong Zhang - Sols - the solution vectors
58754a658b32SHong Zhang 
5876bcf0153eSBarry Smith   Level: intermediate
58774a658b32SHong Zhang 
587840bd4cedSHong Zhang   Notes:
5879195e9b02SBarry Smith   Both `nsol` and `Sols` can be `NULL`.
58804a658b32SHong Zhang 
5881195e9b02SBarry Smith   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()`.
5882bcf0153eSBarry Smith   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
5883bcf0153eSBarry Smith 
58841cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`
58854a658b32SHong Zhang @*/
5886d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
5887d71ae5a4SJacob Faibussowitsch {
58884a658b32SHong Zhang   PetscFunctionBegin;
58894a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58904f572ea9SToby Isaac   if (nsol) PetscAssertPointer(nsol, 2);
58914f572ea9SToby Isaac   if (Sols) PetscAssertPointer(Sols, 3);
58924a658b32SHong Zhang   if (!ts->tspan) {
58934a658b32SHong Zhang     if (nsol) *nsol = 0;
58944a658b32SHong Zhang     if (Sols) *Sols = NULL;
58954a658b32SHong Zhang   } else {
589640bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
58974a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
58984a658b32SHong Zhang   }
58993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
59004a658b32SHong Zhang }
5901d7cfae9bSHong Zhang 
5902cc4c1da9SBarry Smith /*@
59037b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
5904d7cfae9bSHong Zhang 
5905195e9b02SBarry Smith   Collective
5906d7cfae9bSHong Zhang 
5907d7cfae9bSHong Zhang   Input Parameters:
5908195e9b02SBarry Smith + ts - the `TS` context
5909d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
5910195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
5911d7cfae9bSHong Zhang 
5912d7cfae9bSHong Zhang   Level: intermediate
5913d7cfae9bSHong Zhang 
5914d7cfae9bSHong Zhang   Notes:
5915195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
5916195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
5917d7cfae9bSHong Zhang   and multiple fields are involved.
5918d7cfae9bSHong Zhang 
5919d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
5920195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
59217b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
59227b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
5923d7cfae9bSHong Zhang 
59241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5925d7cfae9bSHong Zhang @*/
5926d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
5927d7cfae9bSHong Zhang {
5928d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
5929d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
5930d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
5931d7cfae9bSHong Zhang 
5932d7cfae9bSHong Zhang   PetscFunctionBegin;
5933d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
593458c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
5935d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
5936d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
5937d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
5938d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
5939d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
5940d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
5941d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
5942d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
5943d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
5944d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
5945d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
5946d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
5947d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
5948d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
59493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5950d7cfae9bSHong Zhang }
5951