xref: /petsc/src/ts/interface/ts.c (revision 49abdd8a111d9c2ef7fc48ade253ef64e07f9b37)
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
66c17ba870SStefano Zampini . -ts_monitor_solution_interval <interval>                           - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
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)
68c17ba870SStefano Zampini . -ts_monitor_solution_vtk_interval <interval>                       - output once every interval (default=1) time steps. Use -1 to only output at the end of the simulation
699e336e28SPatrick Sanan - -ts_monitor_envelope                                               - determine maximum and minimum value of each component of the solution over the solution time
7053ea634cSHong Zhang 
71bcf0153eSBarry Smith   Level: beginner
723d5a8a6aSBarry Smith 
73bcf0153eSBarry Smith   Notes:
74bcf0153eSBarry Smith   See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
75bcf0153eSBarry Smith 
76195e9b02SBarry Smith   Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
770d56bcf9SIlya Fursov   to retain them over the multiple nonlinear solves that `TS` uses you must also provide `-snes_lag_jacobian_persists true` and
78195e9b02SBarry Smith   `-snes_lag_preconditioner_persists true`
793d5a8a6aSBarry Smith 
80b43aa488SJacob Faibussowitsch   Developer Notes:
819e336e28SPatrick Sanan   We should unify all the -ts_monitor options in the way that -xxx_view has been unified
82bdad233fSMatthew Knepley 
831cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetType()`
84bdad233fSMatthew Knepley @*/
85d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
86d71ae5a4SJacob Faibussowitsch {
87bc952696SBarry Smith   PetscBool              opt, flg, tflg;
88eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
894a658b32SHong Zhang   PetscReal              time_step, tspan[100];
904a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9149354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
92d1212d36SBarry Smith   char                   dir[16];
938434afd1SBarry Smith   TSIFunctionFn         *ifun;
946991f827SBarry Smith   const char            *defaultType;
956991f827SBarry Smith   char                   typeName[256];
96bdad233fSMatthew Knepley 
97bdad233fSMatthew Knepley   PetscFunctionBegin;
980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
996991f827SBarry Smith 
1009566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1019566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
102cd11d68dSLisandro Dalcin 
103d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1041ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1051ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1071e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1081e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
109bdad233fSMatthew Knepley 
110bdad233fSMatthew Knepley   /* Handle generic TS options */
1119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1134a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1144a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1189566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1209566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
12109cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, &flg));
12209cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxSNESFailures(ts, ts->max_snes_failures));
12309cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, &flg));
12409cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxStepRejections(ts, ts->max_reject));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
12609cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL, 0));
12709cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL, 0));
128bdad233fSMatthew Knepley 
1299566063dSJacob 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));
1309566063dSJacob 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));
1319566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
13256f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13356f85f32SBarry Smith   {
13456f85f32SBarry Smith     PetscBool set;
13556f85f32SBarry Smith     flg = PETSC_FALSE;
1369566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1371baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13856f85f32SBarry Smith   }
13956f85f32SBarry Smith #endif
14056f85f32SBarry Smith 
141bdad233fSMatthew Knepley   /* Monitor options */
1429566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1449566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1459566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1469566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
147fde5950dSBarry Smith 
1489566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1499566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1505180491cSLisandro Dalcin 
1519566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
152b3603a34SBarry Smith   if (opt) {
1533923b477SBarry Smith     PetscInt  howoften = 1;
154e669de00SBarry Smith     DM        dm;
155e669de00SBarry Smith     PetscBool net;
156b3603a34SBarry Smith 
1579566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1589566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1599566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
160e669de00SBarry Smith     if (net) {
161e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1629566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
163*49abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxNetworkDestroy));
1649566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
165e669de00SBarry Smith     } else {
166e669de00SBarry Smith       TSMonitorLGCtx ctx;
1679566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
168*49abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
169bdad233fSMatthew Knepley     }
170e669de00SBarry Smith   }
1716ba87a44SLisandro Dalcin 
1729566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
173ef20d060SBarry Smith   if (opt) {
1740b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1753923b477SBarry Smith     PetscInt       howoften = 1;
176ef20d060SBarry Smith 
1779566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1789566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
179*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
180ef20d060SBarry Smith   }
1819566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1827cf37e64SBarry Smith 
1839566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1846934998bSLisandro Dalcin   if (opt) {
1856934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1866934998bSLisandro Dalcin     PetscInt       howoften = 1;
1876934998bSLisandro Dalcin 
1889566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1899566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
190*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
1916934998bSLisandro Dalcin   }
1929566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1938b668821SLisandro Dalcin   if (opt) {
1948b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1958b668821SLisandro Dalcin     PetscInt       howoften = 1;
1968b668821SLisandro Dalcin 
1979566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1989566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
199*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
2008b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2018b668821SLisandro Dalcin   }
2028b668821SLisandro Dalcin 
2039566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
204201da799SBarry Smith   if (opt) {
205201da799SBarry Smith     TSMonitorLGCtx ctx;
206201da799SBarry Smith     PetscInt       howoften = 1;
207201da799SBarry Smith 
2089566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2099566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
210*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
211201da799SBarry Smith   }
2129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
213201da799SBarry Smith   if (opt) {
214201da799SBarry Smith     TSMonitorLGCtx ctx;
215201da799SBarry Smith     PetscInt       howoften = 1;
216201da799SBarry Smith 
2179566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2189566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
219*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
220201da799SBarry Smith   }
2219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2228189c53fSBarry Smith   if (opt) {
2238189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2248189c53fSBarry Smith     PetscInt          howoften = 1;
2258189c53fSBarry Smith 
2269566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2279566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
228*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscCtxDestroyFn *)TSMonitorSPEigCtxDestroy));
2298189c53fSBarry Smith   }
23060e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2311b575b74SJoseph Pusztay   if (opt) {
2321b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
233d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
23460e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
235d7462660SMatthew Knepley 
2369371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2379371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2389371c9d4SSatish Balay         create = PETSC_FALSE;
2399371c9d4SSatish Balay         break;
2409371c9d4SSatish Balay       }
2416a5217c0SMatthew G. Knepley     if (create) {
24260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2439566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2449566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
24560e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
24660e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
247*49abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorSPCtxDestroy));
2481b575b74SJoseph Pusztay     }
2496a5217c0SMatthew G. Knepley   }
25060e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
25160e16b1bSMatthew G. Knepley   if (opt) {
25260e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
25360e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
25460e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
25560e16b1bSMatthew G. Knepley 
25660e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
25760e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
25860e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
25960e16b1bSMatthew G. Knepley         break;
26060e16b1bSMatthew G. Knepley       }
26160e16b1bSMatthew G. Knepley     if (create) {
26260e16b1bSMatthew G. Knepley       DM       sw, dm;
26360e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
26460e16b1bSMatthew G. Knepley 
26560e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
26660e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
26760e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
26860e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
26960e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
27060e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
27160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
27260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
27360e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
274*49abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorHGCtxDestroy));
27560e16b1bSMatthew G. Knepley     }
27660e16b1bSMatthew G. Knepley   }
277ef20d060SBarry Smith   opt = PETSC_FALSE;
2789566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
279a7cc72afSBarry Smith   if (opt) {
28083a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
28183a4ac43SBarry Smith     PetscInt         howoften = 1;
282a80ad3e0SBarry Smith 
2839566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2849566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
285*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
286bdad233fSMatthew Knepley   }
287fb1732b5SBarry Smith   opt = PETSC_FALSE;
2889566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2892d5ee99bSBarry Smith   if (opt) {
2902d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2912d5ee99bSBarry Smith     PetscReal        bounds[4];
2922d5ee99bSBarry Smith     PetscInt         n = 4;
2932d5ee99bSBarry Smith     PetscDraw        draw;
2946934998bSLisandro Dalcin     PetscDrawAxis    axis;
2952d5ee99bSBarry Smith 
2969566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2973c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2989566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2999566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
3009566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
3019566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
3029566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
303*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3042d5ee99bSBarry Smith   }
3052d5ee99bSBarry Smith   opt = PETSC_FALSE;
3069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3073a471f94SBarry Smith   if (opt) {
30883a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
30983a4ac43SBarry Smith     PetscInt         howoften = 1;
3103a471f94SBarry Smith 
3119566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3129566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
313*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3143a471f94SBarry Smith   }
3150ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3170ed3bfb6SBarry Smith   if (opt) {
3180ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3190ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3200ed3bfb6SBarry Smith 
3219566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3229566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
323*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3240ed3bfb6SBarry Smith   }
325fde5950dSBarry Smith 
326ed81e22dSJed Brown   opt = PETSC_FALSE;
32763a3b9bcSJacob 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));
328ed81e22dSJed Brown   if (flg) {
3297f27e910SStefano Zampini     TSMonitorVTKCtx ctx;
3307f27e910SStefano Zampini 
3317f27e910SStefano Zampini     PetscCall(TSMonitorSolutionVTKCtxCreate(monfilename, &ctx));
332c17ba870SStefano Zampini     PetscCall(PetscOptionsInt("-ts_monitor_solution_vtk_interval", "Save every interval time step (-1 for last step only)", NULL, ctx->interval, &ctx->interval, NULL));
333*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, (PetscErrorCode (*)(TS, PetscInt, PetscReal, Vec, void *))TSMonitorSolutionVTK, ctx, (PetscCtxDestroyFn *)TSMonitorSolutionVTKDestroy));
334ed81e22dSJed Brown   }
335bdad233fSMatthew Knepley 
3369566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
337d1212d36SBarry Smith   if (flg) {
338d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
339d1212d36SBarry Smith     int                  ray = 0;
3403ee9839eSMatthew G. Knepley     DMDirection          ddir;
341d1212d36SBarry Smith     DM                   da;
342d1212d36SBarry Smith     PetscMPIInt          rank;
343d1212d36SBarry Smith 
3443c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3453ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3463ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34798921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
348d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
349d1212d36SBarry Smith 
35057508eceSPierre Jolivet     PetscCall(PetscInfo((PetscObject)ts, "Displaying DMDA ray %c = %d\n", dir[0], ray));
3519566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3529566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3539566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3549566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3551e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
35651b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3579566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
358d1212d36SBarry Smith   }
3599566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
36051b4a12fSMatthew G. Knepley   if (flg) {
36151b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
36251b4a12fSMatthew G. Knepley     int                  ray = 0;
3633ee9839eSMatthew G. Knepley     DMDirection          ddir;
36451b4a12fSMatthew G. Knepley     DM                   da;
36551b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
366d1212d36SBarry Smith 
3673c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3683ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3693ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
37098921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
37151b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3721c3436cfSJed Brown 
37357508eceSPierre Jolivet     PetscCall(PetscInfo((PetscObject)ts, "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3749566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3759566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3769566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3779566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3789566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
37951b4a12fSMatthew G. Knepley   }
380a7a1495cSBarry Smith 
3819566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
382b3d3934dSBarry Smith   if (opt) {
383b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
384b3d3934dSBarry Smith 
3859566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
386*49abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscCtxDestroyFn *)TSMonitorEnvelopeCtxDestroy));
387b3d3934dSBarry Smith   }
388aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3899566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3909566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
391b3d3934dSBarry Smith 
392847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
393d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
394847ff0e1SMatthew G. Knepley   if (flg) {
395847ff0e1SMatthew G. Knepley     DM dm;
396847ff0e1SMatthew G. Knepley 
3979371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
3989371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
3999566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
4009566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
401847ff0e1SMatthew G. Knepley   }
402847ff0e1SMatthew G. Knepley 
403d763cef2SBarry Smith   /* Handle specific TS options */
404dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
405fbc52257SHong Zhang 
406a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4079566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4089566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
409dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
410a7bdc993SLisandro Dalcin 
41168bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4124f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4139566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4141baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
415a05bf03eSHong Zhang 
416dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
417d763cef2SBarry Smith 
418d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
419dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
420d0609cedSBarry Smith   PetscOptionsEnd();
421d763cef2SBarry Smith 
4221baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
42368bece0bSHong Zhang 
4241ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4259566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4261ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4279566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4289566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4291ef27442SStefano Zampini   }
4309566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
432d763cef2SBarry Smith }
433d763cef2SBarry Smith 
434d2daff3dSHong Zhang /*@
435bcf0153eSBarry Smith   TSGetTrajectory - Gets the trajectory from a `TS` if it exists
43678fbdcc8SBarry Smith 
437c3339decSBarry Smith   Collective
43878fbdcc8SBarry Smith 
4392fe279fdSBarry Smith   Input Parameter:
440bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
44178fbdcc8SBarry Smith 
4422fe279fdSBarry Smith   Output Parameter:
443bcf0153eSBarry Smith . tr - the `TSTrajectory` object, if it exists
44478fbdcc8SBarry Smith 
44578fbdcc8SBarry Smith   Level: advanced
44678fbdcc8SBarry Smith 
447bcf0153eSBarry Smith   Note:
448bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
44978fbdcc8SBarry Smith 
450b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
45178fbdcc8SBarry Smith @*/
452d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
453d71ae5a4SJacob Faibussowitsch {
45478fbdcc8SBarry Smith   PetscFunctionBegin;
45578fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45678fbdcc8SBarry Smith   *tr = ts->trajectory;
4573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45878fbdcc8SBarry Smith }
45978fbdcc8SBarry Smith 
46078fbdcc8SBarry Smith /*@
461bcf0153eSBarry Smith   TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
462d2daff3dSHong Zhang 
463c3339decSBarry Smith   Collective
464d2daff3dSHong Zhang 
465f899ff85SJose E. Roman   Input Parameter:
466bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
467bc952696SBarry Smith 
468bcf0153eSBarry Smith   Options Database Keys:
46978fbdcc8SBarry Smith + -ts_save_trajectory      - saves the trajectory to a file
47067b8a455SSatish Balay - -ts_trajectory_type type - set trajectory type
47178fbdcc8SBarry Smith 
472d2daff3dSHong Zhang   Level: intermediate
473d2daff3dSHong Zhang 
474bcf0153eSBarry Smith   Notes:
475bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
476d2daff3dSHong Zhang 
477bcf0153eSBarry Smith   The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
478bcf0153eSBarry Smith   MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
479bcf0153eSBarry Smith 
4801cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
481d2daff3dSHong Zhang @*/
482d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
483d71ae5a4SJacob Faibussowitsch {
484d2daff3dSHong Zhang   PetscFunctionBegin;
485d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48663a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
488d2daff3dSHong Zhang }
489d2daff3dSHong Zhang 
490a7a1495cSBarry Smith /*@
491bcf0153eSBarry Smith   TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
4922d29f1f2SStefano Zampini 
493c3339decSBarry Smith   Collective
4942d29f1f2SStefano Zampini 
4952fe279fdSBarry Smith   Input Parameter:
496bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4972d29f1f2SStefano Zampini 
4982d29f1f2SStefano Zampini   Level: intermediate
4992d29f1f2SStefano Zampini 
5001cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5012d29f1f2SStefano Zampini @*/
502d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
503d71ae5a4SJacob Faibussowitsch {
5042d29f1f2SStefano Zampini   PetscFunctionBegin;
5052d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5062d29f1f2SStefano Zampini   if (ts->trajectory) {
5079566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5089566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5092d29f1f2SStefano Zampini   }
5103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5112d29f1f2SStefano Zampini }
5122d29f1f2SStefano Zampini 
5132d29f1f2SStefano Zampini /*@
514195e9b02SBarry Smith   TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
51567a3cfb0SHong Zhang 
516c3339decSBarry Smith   Collective
51767a3cfb0SHong Zhang 
5182fe279fdSBarry Smith   Input Parameter:
519bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
52067a3cfb0SHong Zhang 
52167a3cfb0SHong Zhang   Level: intermediate
52267a3cfb0SHong Zhang 
5231cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
52467a3cfb0SHong Zhang @*/
525d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
526d71ae5a4SJacob Faibussowitsch {
52767a3cfb0SHong Zhang   PetscFunctionBegin;
52867a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5291e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53167a3cfb0SHong Zhang }
53267a3cfb0SHong Zhang 
53367a3cfb0SHong Zhang /*@
534a7a1495cSBarry Smith   TSComputeRHSJacobian - Computes the Jacobian matrix that has been
535bcf0153eSBarry Smith   set with `TSSetRHSJacobian()`.
536a7a1495cSBarry Smith 
537c3339decSBarry Smith   Collective
538a7a1495cSBarry Smith 
539a7a1495cSBarry Smith   Input Parameters:
540bcf0153eSBarry Smith + ts - the `TS` context
541a7a1495cSBarry Smith . t  - current timestep
5420910c330SBarry Smith - U  - input vector
543a7a1495cSBarry Smith 
544a7a1495cSBarry Smith   Output Parameters:
545a7a1495cSBarry Smith + A - Jacobian matrix
5466b867d5aSJose E. Roman - B - optional preconditioning matrix
547a7a1495cSBarry Smith 
548bcf0153eSBarry Smith   Level: developer
549bcf0153eSBarry Smith 
550bcf0153eSBarry Smith   Note:
551a7a1495cSBarry Smith   Most users should not need to explicitly call this routine, as it
552a7a1495cSBarry Smith   is used internally within the nonlinear solvers.
553a7a1495cSBarry Smith 
5541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
555a7a1495cSBarry Smith @*/
556d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
557d71ae5a4SJacob Faibussowitsch {
558270bf2e7SJed Brown   PetscObjectState Ustate;
5596c1e1eecSBarry Smith   PetscObjectId    Uid;
56024989b8cSPeter Brune   DM               dm;
561942e3340SBarry Smith   DMTS             tsdm;
5628434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobianfunc;
56324989b8cSPeter Brune   void            *ctx;
5648434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
565a7a1495cSBarry Smith 
566a7a1495cSBarry Smith   PetscFunctionBegin;
5670700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5680910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5690910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5709566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5719566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5729566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5739566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5749566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5759566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
576971015bcSStefano Zampini 
5773ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
578d90be118SSean Farley 
57963a3b9bcSJacob 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);
58024989b8cSPeter Brune   if (rhsjacobianfunc) {
581da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
582792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
583a6ab3590SBarry Smith     ts->rhsjacs++;
584da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
585ef66eb69SBarry Smith   } else {
5869566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5879566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
588ef66eb69SBarry Smith   }
5890e4ef248SJed Brown   ts->rhsjacobian.time  = t;
590971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
591971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5929566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
5939566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
5943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
595a7a1495cSBarry Smith }
596a7a1495cSBarry Smith 
597316643e7SJed Brown /*@
598bcf0153eSBarry Smith   TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
599d763cef2SBarry Smith 
600c3339decSBarry Smith   Collective
601316643e7SJed Brown 
602316643e7SJed Brown   Input Parameters:
603bcf0153eSBarry Smith + ts - the `TS` context
604316643e7SJed Brown . t  - current time
6050910c330SBarry Smith - U  - state vector
606316643e7SJed Brown 
607316643e7SJed Brown   Output Parameter:
608dd8e379bSPierre Jolivet . y - right-hand side
609316643e7SJed Brown 
610bcf0153eSBarry Smith   Level: developer
611bcf0153eSBarry Smith 
612316643e7SJed Brown   Note:
613316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
614316643e7SJed Brown   is used internally within the nonlinear solvers.
615316643e7SJed Brown 
6161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
617316643e7SJed Brown @*/
618d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
619d71ae5a4SJacob Faibussowitsch {
6208434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
6218434afd1SBarry Smith   TSIFunctionFn   *ifunction;
62224989b8cSPeter Brune   void            *ctx;
62324989b8cSPeter Brune   DM               dm;
62424989b8cSPeter Brune 
625d763cef2SBarry Smith   PetscFunctionBegin;
6260700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6270910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6280700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6299566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6309566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6319566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
632d763cef2SBarry Smith 
6333c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
634d763cef2SBarry Smith 
63524989b8cSPeter Brune   if (rhsfunction) {
636da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, y, 0));
6379566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
638792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6399566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
640a6ab3590SBarry Smith     ts->rhsfuncs++;
641da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, y, 0));
6421e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6433ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
644d763cef2SBarry Smith }
645d763cef2SBarry Smith 
646ef20d060SBarry Smith /*@
647ef20d060SBarry Smith   TSComputeSolutionFunction - Evaluates the solution function.
648ef20d060SBarry Smith 
649c3339decSBarry Smith   Collective
650ef20d060SBarry Smith 
651ef20d060SBarry Smith   Input Parameters:
652bcf0153eSBarry Smith + ts - the `TS` context
653ef20d060SBarry Smith - t  - current time
654ef20d060SBarry Smith 
655ef20d060SBarry Smith   Output Parameter:
6560910c330SBarry Smith . U - the solution
657ef20d060SBarry Smith 
658ef20d060SBarry Smith   Level: developer
659ef20d060SBarry Smith 
6601cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
661ef20d060SBarry Smith @*/
662d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
663d71ae5a4SJacob Faibussowitsch {
6648434afd1SBarry Smith   TSSolutionFn *solutionfunction;
665ef20d060SBarry Smith   void         *ctx;
666ef20d060SBarry Smith   DM            dm;
667ef20d060SBarry Smith 
668ef20d060SBarry Smith   PetscFunctionBegin;
669ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6700910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6719566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6729566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
673792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6743ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
675ef20d060SBarry Smith }
6769b7cd975SBarry Smith /*@
6779b7cd975SBarry Smith   TSComputeForcingFunction - Evaluates the forcing function.
6789b7cd975SBarry Smith 
679c3339decSBarry Smith   Collective
6809b7cd975SBarry Smith 
6819b7cd975SBarry Smith   Input Parameters:
682bcf0153eSBarry Smith + ts - the `TS` context
6839b7cd975SBarry Smith - t  - current time
6849b7cd975SBarry Smith 
6859b7cd975SBarry Smith   Output Parameter:
6869b7cd975SBarry Smith . U - the function value
6879b7cd975SBarry Smith 
6889b7cd975SBarry Smith   Level: developer
6899b7cd975SBarry Smith 
6901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6919b7cd975SBarry Smith @*/
692d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
693d71ae5a4SJacob Faibussowitsch {
6949b7cd975SBarry Smith   void        *ctx;
6959b7cd975SBarry Smith   DM           dm;
6968434afd1SBarry Smith   TSForcingFn *forcing;
6979b7cd975SBarry Smith 
6989b7cd975SBarry Smith   PetscFunctionBegin;
6999b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7009b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7019566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7029566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7039b7cd975SBarry Smith 
704792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7069b7cd975SBarry Smith }
707ef20d060SBarry Smith 
708d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
709d71ae5a4SJacob Faibussowitsch {
710214bc6a2SJed Brown   Mat            A, B;
7118434afd1SBarry Smith   TSIJacobianFn *ijacobian;
712214bc6a2SJed Brown 
713214bc6a2SJed Brown   PetscFunctionBegin;
714c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
715c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7169566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
717214bc6a2SJed Brown   if (Arhs) {
718214bc6a2SJed Brown     if (!ts->Arhs) {
71941a1d4d2SBarry Smith       if (ijacobian) {
7209566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7219566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
72241a1d4d2SBarry Smith       } else {
72341a1d4d2SBarry Smith         ts->Arhs = A;
7249566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
72541a1d4d2SBarry Smith       }
7263565c898SBarry Smith     } else {
7273565c898SBarry Smith       PetscBool flg;
7289566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7293565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7303565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7319566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7323565c898SBarry Smith         ts->Arhs = A;
7339566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7343565c898SBarry Smith       }
735214bc6a2SJed Brown     }
736214bc6a2SJed Brown     *Arhs = ts->Arhs;
737214bc6a2SJed Brown   }
738214bc6a2SJed Brown   if (Brhs) {
739214bc6a2SJed Brown     if (!ts->Brhs) {
740bdb70873SJed Brown       if (A != B) {
74141a1d4d2SBarry Smith         if (ijacobian) {
7429566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
743bdb70873SJed Brown         } else {
74441a1d4d2SBarry Smith           ts->Brhs = B;
7459566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
74641a1d4d2SBarry Smith         }
74741a1d4d2SBarry Smith       } else {
7489566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
74951699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
750bdb70873SJed Brown       }
751214bc6a2SJed Brown     }
752214bc6a2SJed Brown     *Brhs = ts->Brhs;
753214bc6a2SJed Brown   }
7543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
755214bc6a2SJed Brown }
756214bc6a2SJed Brown 
757316643e7SJed Brown /*@
758195e9b02SBarry Smith   TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
759316643e7SJed Brown 
760c3339decSBarry Smith   Collective
761316643e7SJed Brown 
762316643e7SJed Brown   Input Parameters:
763bcf0153eSBarry Smith + ts   - the `TS` context
764316643e7SJed Brown . t    - current time
7650910c330SBarry Smith . U    - state vector
7660910c330SBarry Smith . Udot - time derivative of state vector
7673dddbd81SStefano Zampini - imex - flag indicates if the method is `TSARKIMEX` so that the RHSFunction should be kept separate
768316643e7SJed Brown 
769316643e7SJed Brown   Output Parameter:
770dd8e379bSPierre Jolivet . Y - right-hand side
771316643e7SJed Brown 
772bcf0153eSBarry Smith   Level: developer
773bcf0153eSBarry Smith 
774316643e7SJed Brown   Note:
775316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
776316643e7SJed Brown   is used internally within the nonlinear solvers.
777316643e7SJed Brown 
77815229ffcSPierre Jolivet   If the user did not write their equations in implicit form, this
779316643e7SJed Brown   function recasts them in implicit form.
780316643e7SJed Brown 
7811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
782316643e7SJed Brown @*/
783d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
784d71ae5a4SJacob Faibussowitsch {
7858434afd1SBarry Smith   TSIFunctionFn   *ifunction;
7868434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
78724989b8cSPeter Brune   void            *ctx;
78824989b8cSPeter Brune   DM               dm;
789316643e7SJed Brown 
790316643e7SJed Brown   PetscFunctionBegin;
7910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7920910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7930910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
7940700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
795316643e7SJed Brown 
7969566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7979566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
7989566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
79924989b8cSPeter Brune 
8003c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
801d90be118SSean Farley 
802da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, Udot, Y));
80324989b8cSPeter Brune   if (ifunction) {
804792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
805a6ab3590SBarry Smith     ts->ifuncs++;
806214bc6a2SJed Brown   }
807214bc6a2SJed Brown   if (imex) {
8081e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
80924989b8cSPeter Brune   } else if (rhsfunction) {
81024989b8cSPeter Brune     if (ifunction) {
811214bc6a2SJed Brown       Vec Frhs;
8128af0501fSStefano Zampini 
8138af0501fSStefano Zampini       PetscCall(DMGetGlobalVector(dm, &Frhs));
8149566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8159566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8168af0501fSStefano Zampini       PetscCall(DMRestoreGlobalVector(dm, &Frhs));
8172dd45cf8SJed Brown     } else {
8189566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8199566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
820316643e7SJed Brown     }
8214a6899ffSJed Brown   }
822da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, Udot, Y));
8233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
824316643e7SJed Brown }
825316643e7SJed Brown 
826cfa8a9a2SHong Zhang /*
827195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
828cfa8a9a2SHong Zhang 
829cfa8a9a2SHong Zhang    Note:
830195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
831cfa8a9a2SHong Zhang 
832cfa8a9a2SHong Zhang */
833d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
834d71ae5a4SJacob Faibussowitsch {
835cfa8a9a2SHong Zhang   PetscFunctionBegin;
836cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8373c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8383c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
839cfa8a9a2SHong Zhang 
8401baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
84148a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
842cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8431baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8441e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
845cfa8a9a2SHong Zhang   }
846cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
847cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
849cfa8a9a2SHong Zhang }
850cfa8a9a2SHong Zhang 
851316643e7SJed Brown /*@
852316643e7SJed Brown   TSComputeIJacobian - Evaluates the Jacobian of the DAE
853316643e7SJed Brown 
854c3339decSBarry Smith   Collective
855316643e7SJed Brown 
856316643e7SJed Brown   Input Parameters:
857bcf0153eSBarry Smith + ts    - the `TS` context
858316643e7SJed Brown . t     - current timestep
8590910c330SBarry Smith . U     - state vector
8600910c330SBarry Smith . Udot  - time derivative of state vector
861214bc6a2SJed Brown . shift - shift to apply, see note below
8623dddbd81SStefano Zampini - imex  - flag indicates if the method is `TSARKIMEX` so that the RHSJacobian should be kept separate
863316643e7SJed Brown 
864316643e7SJed Brown   Output Parameters:
865316643e7SJed Brown + A - Jacobian matrix
866195e9b02SBarry Smith - B - matrix from which the preconditioner is constructed; often the same as `A`
867316643e7SJed Brown 
868bcf0153eSBarry Smith   Level: developer
869bcf0153eSBarry Smith 
870316643e7SJed Brown   Notes:
8710910c330SBarry Smith   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
872195e9b02SBarry Smith .vb
8730910c330SBarry Smith    dF/dU + shift*dF/dUdot
874195e9b02SBarry Smith .ve
875316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
876316643e7SJed Brown   is used internally within the nonlinear solvers.
877316643e7SJed Brown 
8781cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
87963495f91SJed Brown @*/
880d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
881d71ae5a4SJacob Faibussowitsch {
8828434afd1SBarry Smith   TSIJacobianFn   *ijacobian;
8838434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
88424989b8cSPeter Brune   DM               dm;
88524989b8cSPeter Brune   void            *ctx;
886316643e7SJed Brown 
887316643e7SJed Brown   PetscFunctionBegin;
8880700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8890910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8900910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
89194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
89294ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
89324989b8cSPeter Brune 
8949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8959566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
8969566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
89724989b8cSPeter Brune 
8983c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
899316643e7SJed Brown 
900da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
90124989b8cSPeter Brune   if (ijacobian) {
902792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
903a6ab3590SBarry Smith     ts->ijacs++;
9044a6899ffSJed Brown   }
905214bc6a2SJed Brown   if (imex) {
906b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9074c26be97Sstefano_zampini       PetscBool assembled;
908971015bcSStefano Zampini       if (rhsjacobian) {
909971015bcSStefano Zampini         Mat Arhs = NULL;
9109566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
911971015bcSStefano Zampini         if (A == Arhs) {
9123c633725SBarry Smith           PetscCheck(rhsjacobian != TSComputeRHSJacobianConstant, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Unsupported operation! cannot use TSComputeRHSJacobianConstant"); /* there is no way to reconstruct shift*M-J since J cannot be reevaluated */
913971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
914971015bcSStefano Zampini         }
915971015bcSStefano Zampini       }
9169566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9179566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9184c26be97Sstefano_zampini       if (!assembled) {
9199566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9209566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9214c26be97Sstefano_zampini       }
9229566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
92394ab13aaSBarry Smith       if (A != B) {
9249566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9259566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9264c26be97Sstefano_zampini         if (!assembled) {
9279566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9289566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9294c26be97Sstefano_zampini         }
9309566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
931214bc6a2SJed Brown       }
932214bc6a2SJed Brown     }
933214bc6a2SJed Brown   } else {
934e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9351e66621cSBarry Smith 
9361e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9371e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
938e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
939e8b1e424SHong Zhang       PetscObjectState Ustate;
940e8b1e424SHong Zhang       PetscObjectId    Uid;
9418434afd1SBarry Smith       TSRHSFunctionFn *rhsfunction;
942e8b1e424SHong Zhang 
9439566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9449566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9459566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9469371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9479371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9489566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9491e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
950e8b1e424SHong Zhang       } else {
9513565c898SBarry Smith         PetscBool flg;
952e8b1e424SHong Zhang 
953e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
954e8b1e424SHong Zhang           /* MatScale has a short path for this case.
955e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
956e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9579566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
958e8b1e424SHong Zhang         }
9599566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9609566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9613565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9623565c898SBarry Smith         if (!flg) {
9639566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9649566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9653565c898SBarry Smith         }
96694ab13aaSBarry Smith         if (A != B) {
9679566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9689566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
969316643e7SJed Brown         }
970e8b1e424SHong Zhang       }
971e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
972e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
973d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
974e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9759566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9769566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
97794ab13aaSBarry Smith         if (A != B) {
9789566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9799566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
980214bc6a2SJed Brown         }
981316643e7SJed Brown       }
9829566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9839566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9841e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
985316643e7SJed Brown     }
986316643e7SJed Brown   }
987da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
9883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
989316643e7SJed Brown }
990316643e7SJed Brown 
991d763cef2SBarry Smith /*@C
992d763cef2SBarry Smith   TSSetRHSFunction - Sets the routine for evaluating the function,
993b5abc632SBarry Smith   where U_t = G(t,u).
994d763cef2SBarry Smith 
995c3339decSBarry Smith   Logically Collective
996d763cef2SBarry Smith 
997d763cef2SBarry Smith   Input Parameters:
998bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
999dd8e379bSPierre Jolivet . r   - vector to put the computed right-hand side (or `NULL` to have it created)
1000d763cef2SBarry Smith . f   - routine for evaluating the right-hand-side function
1001195e9b02SBarry Smith - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1002d763cef2SBarry Smith 
1003d763cef2SBarry Smith   Level: beginner
1004d763cef2SBarry Smith 
1005bcf0153eSBarry Smith   Note:
1006bcf0153eSBarry Smith   You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10072bbac0d3SBarry Smith 
10088434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSFunctionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1009d763cef2SBarry Smith @*/
10108434afd1SBarry Smith PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunctionFn *f, void *ctx)
1011d71ae5a4SJacob Faibussowitsch {
1012089b2837SJed Brown   SNES snes;
10130298fd71SBarry Smith   Vec  ralloc = NULL;
101424989b8cSPeter Brune   DM   dm;
1015d763cef2SBarry Smith 
1016089b2837SJed Brown   PetscFunctionBegin;
10170700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1018ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
101924989b8cSPeter Brune 
10209566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10219566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10229566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1023e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10249566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1025e856ceecSJed Brown     r = ralloc;
1026e856ceecSJed Brown   }
10279566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10289566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1030d763cef2SBarry Smith }
1031d763cef2SBarry Smith 
1032ef20d060SBarry Smith /*@C
1033abd5a294SJed Brown   TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1034ef20d060SBarry Smith 
1035c3339decSBarry Smith   Logically Collective
1036ef20d060SBarry Smith 
1037ef20d060SBarry Smith   Input Parameters:
1038bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1039ef20d060SBarry Smith . f   - routine for evaluating the solution
1040ef20d060SBarry Smith - ctx - [optional] user-defined context for private data for the
1041195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1042ef20d060SBarry Smith 
1043bcf0153eSBarry Smith   Options Database Keys:
1044bcf0153eSBarry Smith + -ts_monitor_lg_error   - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1045bcf0153eSBarry Smith - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1046bcf0153eSBarry Smith 
1047bcf0153eSBarry Smith   Level: intermediate
10480ed3bfb6SBarry Smith 
1049abd5a294SJed Brown   Notes:
1050abd5a294SJed Brown   This routine is used for testing accuracy of time integration schemes when you already know the solution.
1051abd5a294SJed Brown   If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1052abd5a294SJed Brown   create closed-form solutions with non-physical forcing terms.
1053abd5a294SJed Brown 
1054bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1055abd5a294SJed Brown 
10568434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolutionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1057ef20d060SBarry Smith @*/
10588434afd1SBarry Smith PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFn *f, void *ctx)
1059d71ae5a4SJacob Faibussowitsch {
1060ef20d060SBarry Smith   DM dm;
1061ef20d060SBarry Smith 
1062ef20d060SBarry Smith   PetscFunctionBegin;
1063ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10649566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10659566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
10663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1067ef20d060SBarry Smith }
1068ef20d060SBarry Smith 
10699b7cd975SBarry Smith /*@C
10709b7cd975SBarry Smith   TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10719b7cd975SBarry Smith 
1072c3339decSBarry Smith   Logically Collective
10739b7cd975SBarry Smith 
10749b7cd975SBarry Smith   Input Parameters:
1075bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1076e162b725SBarry Smith . func - routine for evaluating the forcing function
107714d0ab18SJacob Faibussowitsch - ctx  - [optional] user-defined context for private data for the function evaluation routine
107814d0ab18SJacob Faibussowitsch          (may be `NULL`)
10799b7cd975SBarry Smith 
1080bcf0153eSBarry Smith   Level: intermediate
1081bcf0153eSBarry Smith 
10829b7cd975SBarry Smith   Notes:
10839b7cd975SBarry Smith   This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1084e162b725SBarry 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
1085e162b725SBarry Smith   definition of the problem you are solving and hence possibly introducing bugs.
1086e162b725SBarry Smith 
10878847d985SBarry Smith   This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1088e162b725SBarry Smith 
1089e162b725SBarry 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
1090e162b725SBarry Smith   parameters can be passed in the ctx variable.
10919b7cd975SBarry Smith 
1092bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
10939b7cd975SBarry Smith 
10948434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSForcingFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
109514d0ab18SJacob Faibussowitsch `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
10969b7cd975SBarry Smith @*/
10978434afd1SBarry Smith PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFn *func, void *ctx)
1098d71ae5a4SJacob Faibussowitsch {
10999b7cd975SBarry Smith   DM dm;
11009b7cd975SBarry Smith 
11019b7cd975SBarry Smith   PetscFunctionBegin;
11029b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11049566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11069b7cd975SBarry Smith }
11079b7cd975SBarry Smith 
1108d763cef2SBarry Smith /*@C
1109f7ab8db6SBarry Smith   TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1110b5abc632SBarry Smith   where U_t = G(U,t), as well as the location to store the matrix.
1111d763cef2SBarry Smith 
1112c3339decSBarry Smith   Logically Collective
1113d763cef2SBarry Smith 
1114d763cef2SBarry Smith   Input Parameters:
1115bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1116195e9b02SBarry Smith . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1117195e9b02SBarry Smith . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1118d763cef2SBarry Smith . f    - the Jacobian evaluation routine
1119195e9b02SBarry Smith - ctx  - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1120d763cef2SBarry Smith 
1121bcf0153eSBarry Smith   Level: beginner
1122bcf0153eSBarry Smith 
11236cd88445SBarry Smith   Notes:
11246cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11256cd88445SBarry Smith 
112614d0ab18SJacob Faibussowitsch   The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1127ca5f011dSBarry Smith   You should not assume the values are the same in the next call to f() as you set them in the previous call.
1128d763cef2SBarry Smith 
11298434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSJacobianFn`, `SNESComputeJacobianDefaultColor()`,
11308434afd1SBarry Smith `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunctionFn`, `TSIFunctionFn`
1131d763cef2SBarry Smith @*/
11328434afd1SBarry Smith PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobianFn *f, void *ctx)
1133d71ae5a4SJacob Faibussowitsch {
1134089b2837SJed Brown   SNES           snes;
113524989b8cSPeter Brune   DM             dm;
11368434afd1SBarry Smith   TSIJacobianFn *ijacobian;
1137277b19d0SLisandro Dalcin 
1138d763cef2SBarry Smith   PetscFunctionBegin;
11390700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1140e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1141e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1142e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1143e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1144d763cef2SBarry Smith 
11459566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11469566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11479566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11489566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11491e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1150e5d3d808SBarry Smith   if (Amat) {
11519566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11529566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1153e5d3d808SBarry Smith     ts->Arhs = Amat;
11540e4ef248SJed Brown   }
1155e5d3d808SBarry Smith   if (Pmat) {
11569566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11579566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1158e5d3d808SBarry Smith     ts->Brhs = Pmat;
11590e4ef248SJed Brown   }
11603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1161d763cef2SBarry Smith }
1162d763cef2SBarry Smith 
1163316643e7SJed Brown /*@C
1164b5abc632SBarry Smith   TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1165316643e7SJed Brown 
1166c3339decSBarry Smith   Logically Collective
1167316643e7SJed Brown 
1168316643e7SJed Brown   Input Parameters:
1169bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1170195e9b02SBarry Smith . r   - vector to hold the residual (or `NULL` to have it created internally)
1171316643e7SJed Brown . f   - the function evaluation routine
1172195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1173316643e7SJed Brown 
1174316643e7SJed Brown   Level: beginner
1175316643e7SJed Brown 
1176bcf0153eSBarry Smith   Note:
1177bcf0153eSBarry Smith   The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1178bcf0153eSBarry Smith 
11798434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIFunctionFn`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
118014d0ab18SJacob Faibussowitsch `TSSetIJacobian()`
1181316643e7SJed Brown @*/
11828434afd1SBarry Smith PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunctionFn *f, void *ctx)
1183d71ae5a4SJacob Faibussowitsch {
1184089b2837SJed Brown   SNES snes;
118551699248SLisandro Dalcin   Vec  ralloc = NULL;
118624989b8cSPeter Brune   DM   dm;
1187316643e7SJed Brown 
1188316643e7SJed Brown   PetscFunctionBegin;
11890700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
119051699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
119124989b8cSPeter Brune 
11929566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11939566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
119424989b8cSPeter Brune 
11959566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
119651699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
11979566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
119851699248SLisandro Dalcin     r = ralloc;
1199e856ceecSJed Brown   }
12009566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12019566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1203089b2837SJed Brown }
1204089b2837SJed Brown 
1205089b2837SJed Brown /*@C
1206a5b23f4aSJose E. Roman   TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1207089b2837SJed Brown 
1208089b2837SJed Brown   Not Collective
1209089b2837SJed Brown 
1210089b2837SJed Brown   Input Parameter:
1211bcf0153eSBarry Smith . ts - the `TS` context
1212089b2837SJed Brown 
1213d8d19677SJose E. Roman   Output Parameters:
1214195e9b02SBarry Smith + r    - vector to hold residual (or `NULL`)
1215195e9b02SBarry Smith . func - the function to compute residual (or `NULL`)
1216195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1217089b2837SJed Brown 
1218089b2837SJed Brown   Level: advanced
1219089b2837SJed Brown 
12201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1221089b2837SJed Brown @*/
12228434afd1SBarry Smith PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunctionFn **func, void **ctx)
1223d71ae5a4SJacob Faibussowitsch {
1224089b2837SJed Brown   SNES snes;
122524989b8cSPeter Brune   DM   dm;
1226089b2837SJed Brown 
1227089b2837SJed Brown   PetscFunctionBegin;
1228089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12299566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12309566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12319566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12329566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1234089b2837SJed Brown }
1235089b2837SJed Brown 
1236089b2837SJed Brown /*@C
1237dd8e379bSPierre Jolivet   TSGetRHSFunction - Returns the vector where the right-hand side is stored and the function/context to compute it.
1238089b2837SJed Brown 
1239089b2837SJed Brown   Not Collective
1240089b2837SJed Brown 
1241089b2837SJed Brown   Input Parameter:
1242bcf0153eSBarry Smith . ts - the `TS` context
1243089b2837SJed Brown 
1244d8d19677SJose E. Roman   Output Parameters:
1245dd8e379bSPierre Jolivet + r    - vector to hold computed right-hand side (or `NULL`)
1246dd8e379bSPierre Jolivet . func - the function to compute right-hand side (or `NULL`)
1247195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1248089b2837SJed Brown 
1249089b2837SJed Brown   Level: advanced
1250089b2837SJed Brown 
12511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1252089b2837SJed Brown @*/
12538434afd1SBarry Smith PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunctionFn **func, void **ctx)
1254d71ae5a4SJacob Faibussowitsch {
1255089b2837SJed Brown   SNES snes;
125624989b8cSPeter Brune   DM   dm;
1257089b2837SJed Brown 
1258089b2837SJed Brown   PetscFunctionBegin;
1259089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12609566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12619566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12629566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12639566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
12643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1265316643e7SJed Brown }
1266316643e7SJed Brown 
1267316643e7SJed Brown /*@C
1268a4f0a591SBarry Smith   TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1269bcf0153eSBarry Smith   provided with `TSSetIFunction()`.
1270316643e7SJed Brown 
1271c3339decSBarry Smith   Logically Collective
1272316643e7SJed Brown 
1273316643e7SJed Brown   Input Parameters:
1274bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1275aaa8cc7dSPierre Jolivet . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1276195e9b02SBarry Smith . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1277316643e7SJed Brown . f    - the Jacobian evaluation routine
1278195e9b02SBarry Smith - ctx  - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1279316643e7SJed Brown 
1280bcf0153eSBarry Smith   Level: beginner
1281316643e7SJed Brown 
1282bcf0153eSBarry Smith   Notes:
1283195e9b02SBarry Smith   The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1284bcf0153eSBarry Smith 
1285bcf0153eSBarry Smith   If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1286195e9b02SBarry Smith   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1287895c21f2SBarry Smith 
1288a4f0a591SBarry Smith   The matrix dF/dU + a*dF/dU_t you provide turns out to be
1289b5abc632SBarry Smith   the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1290a4f0a591SBarry Smith   The time integrator internally approximates U_t by W+a*U where the positive "shift"
1291a4f0a591SBarry Smith   a and vector W depend on the integration method, step size, and past states. For example with
1292a4f0a591SBarry Smith   the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1293a4f0a591SBarry Smith   W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1294a4f0a591SBarry Smith 
12956cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
12966cd88445SBarry Smith 
1297195e9b02SBarry Smith   The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1298195e9b02SBarry Smith   You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1299ca5f011dSBarry Smith 
1300bc7fdbb5SPierre Jolivet   In case `TSSetRHSJacobian()` is also used in conjunction with a fully-implicit solver,
1301d469ad21SStefano Zampini   multilevel linear solvers, e.g. `PCMG`, will likely not work due to the way `TS` handles rhs matrices.
1302d469ad21SStefano Zampini 
13038434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIJacobianFn`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
130414d0ab18SJacob Faibussowitsch `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1305316643e7SJed Brown @*/
13068434afd1SBarry Smith PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobianFn *f, void *ctx)
1307d71ae5a4SJacob Faibussowitsch {
1308089b2837SJed Brown   SNES snes;
130924989b8cSPeter Brune   DM   dm;
1310316643e7SJed Brown 
1311316643e7SJed Brown   PetscFunctionBegin;
13120700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1313e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1314e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1315e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1316e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
131724989b8cSPeter Brune 
13189566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13199566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
132024989b8cSPeter Brune 
13219566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13229566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1324316643e7SJed Brown }
1325316643e7SJed Brown 
1326e1244c69SJed Brown /*@
13278434afd1SBarry Smith   TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobianFn` function again
1328e1244c69SJed Brown 
1329e1244c69SJed Brown   Logically Collective
1330e1244c69SJed Brown 
13314165533cSJose E. Roman   Input Parameters:
1332bcf0153eSBarry Smith + ts    - `TS` context obtained from `TSCreate()`
1333bcf0153eSBarry Smith - reuse - `PETSC_TRUE` if the RHS Jacobian
1334e1244c69SJed Brown 
1335e1244c69SJed Brown   Level: intermediate
1336e1244c69SJed Brown 
133714d0ab18SJacob Faibussowitsch   Notes:
133814d0ab18SJacob Faibussowitsch   Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
133914d0ab18SJacob Faibussowitsch   finite-time-step implicit solve, in which case the user function will need to recompute the
134014d0ab18SJacob Faibussowitsch   entire Jacobian.  The `reuse `flag must be set if the evaluation function assumes that the
134114d0ab18SJacob Faibussowitsch   matrix entries have not been changed by the `TS`.
134214d0ab18SJacob Faibussowitsch 
13431cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1344e1244c69SJed Brown @*/
1345d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1346d71ae5a4SJacob Faibussowitsch {
1347e1244c69SJed Brown   PetscFunctionBegin;
1348e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
13493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1350e1244c69SJed Brown }
1351e1244c69SJed Brown 
1352efe9872eSLisandro Dalcin /*@C
1353efe9872eSLisandro Dalcin   TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1354efe9872eSLisandro Dalcin 
1355c3339decSBarry Smith   Logically Collective
1356efe9872eSLisandro Dalcin 
1357efe9872eSLisandro Dalcin   Input Parameters:
1358bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1359195e9b02SBarry Smith . F   - vector to hold the residual (or `NULL` to have it created internally)
1360efe9872eSLisandro Dalcin . fun - the function evaluation routine
1361195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1362efe9872eSLisandro Dalcin 
1363efe9872eSLisandro Dalcin   Level: beginner
1364efe9872eSLisandro Dalcin 
13658434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2FunctionFn`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
136614d0ab18SJacob Faibussowitsch `TSCreate()`, `TSSetRHSFunction()`
1367efe9872eSLisandro Dalcin @*/
13688434afd1SBarry Smith PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2FunctionFn *fun, void *ctx)
1369d71ae5a4SJacob Faibussowitsch {
1370efe9872eSLisandro Dalcin   DM dm;
1371efe9872eSLisandro Dalcin 
1372efe9872eSLisandro Dalcin   PetscFunctionBegin;
1373efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1374efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
13759566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
13769566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13779566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
13783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1379efe9872eSLisandro Dalcin }
1380efe9872eSLisandro Dalcin 
1381efe9872eSLisandro Dalcin /*@C
1382a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1383efe9872eSLisandro Dalcin 
1384efe9872eSLisandro Dalcin   Not Collective
1385efe9872eSLisandro Dalcin 
1386efe9872eSLisandro Dalcin   Input Parameter:
1387bcf0153eSBarry Smith . ts - the `TS` context
1388efe9872eSLisandro Dalcin 
1389d8d19677SJose E. Roman   Output Parameters:
1390195e9b02SBarry Smith + r   - vector to hold residual (or `NULL`)
1391195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1392195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1393efe9872eSLisandro Dalcin 
1394efe9872eSLisandro Dalcin   Level: advanced
1395efe9872eSLisandro Dalcin 
13961cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1397efe9872eSLisandro Dalcin @*/
13988434afd1SBarry Smith PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2FunctionFn **fun, void **ctx)
1399d71ae5a4SJacob Faibussowitsch {
1400efe9872eSLisandro Dalcin   SNES snes;
1401efe9872eSLisandro Dalcin   DM   dm;
1402efe9872eSLisandro Dalcin 
1403efe9872eSLisandro Dalcin   PetscFunctionBegin;
1404efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14059566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14069566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14089566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1410efe9872eSLisandro Dalcin }
1411efe9872eSLisandro Dalcin 
1412efe9872eSLisandro Dalcin /*@C
1413bc77d74cSLisandro Dalcin   TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1414bcf0153eSBarry Smith   where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1415efe9872eSLisandro Dalcin 
1416c3339decSBarry Smith   Logically Collective
1417efe9872eSLisandro Dalcin 
1418efe9872eSLisandro Dalcin   Input Parameters:
1419bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1420195e9b02SBarry Smith . J   - matrix to hold the Jacobian values
1421195e9b02SBarry Smith . P   - matrix for constructing the preconditioner (may be same as `J`)
14228434afd1SBarry Smith . jac - the Jacobian evaluation routine, see `TSI2JacobianFn` for the calling sequence
1423195e9b02SBarry Smith - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1424efe9872eSLisandro Dalcin 
1425bcf0153eSBarry Smith   Level: beginner
1426bcf0153eSBarry Smith 
1427efe9872eSLisandro Dalcin   Notes:
1428195e9b02SBarry Smith   The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1429efe9872eSLisandro Dalcin 
1430efe9872eSLisandro Dalcin   The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1431efe9872eSLisandro 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.
1432efe9872eSLisandro Dalcin   The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1433bc77d74cSLisandro Dalcin   parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1434efe9872eSLisandro Dalcin 
14358434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2JacobianFn`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1436efe9872eSLisandro Dalcin @*/
14378434afd1SBarry Smith PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2JacobianFn *jac, void *ctx)
1438d71ae5a4SJacob Faibussowitsch {
1439efe9872eSLisandro Dalcin   DM dm;
1440efe9872eSLisandro Dalcin 
1441efe9872eSLisandro Dalcin   PetscFunctionBegin;
1442efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1443efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1444efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
14459566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
14469566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14479566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
14483ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1449efe9872eSLisandro Dalcin }
1450efe9872eSLisandro Dalcin 
1451efe9872eSLisandro Dalcin /*@C
1452efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1453efe9872eSLisandro Dalcin 
1454bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1455efe9872eSLisandro Dalcin 
1456efe9872eSLisandro Dalcin   Input Parameter:
1457bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
1458efe9872eSLisandro Dalcin 
1459efe9872eSLisandro Dalcin   Output Parameters:
1460efe9872eSLisandro Dalcin + J   - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1461195e9b02SBarry Smith . P   - The matrix from which the preconditioner is constructed, often the same as `J`
1462efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1463efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1464efe9872eSLisandro Dalcin 
1465bcf0153eSBarry Smith   Level: advanced
1466bcf0153eSBarry Smith 
1467195e9b02SBarry Smith   Note:
1468195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
1469efe9872eSLisandro Dalcin 
14701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1471efe9872eSLisandro Dalcin @*/
14728434afd1SBarry Smith PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2JacobianFn **jac, void **ctx)
1473d71ae5a4SJacob Faibussowitsch {
1474efe9872eSLisandro Dalcin   SNES snes;
1475efe9872eSLisandro Dalcin   DM   dm;
1476efe9872eSLisandro Dalcin 
1477efe9872eSLisandro Dalcin   PetscFunctionBegin;
14789566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14799566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
14809566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
14819566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14829566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
14833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1484efe9872eSLisandro Dalcin }
1485efe9872eSLisandro Dalcin 
1486efe9872eSLisandro Dalcin /*@
1487efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1488efe9872eSLisandro Dalcin 
1489c3339decSBarry Smith   Collective
1490efe9872eSLisandro Dalcin 
1491efe9872eSLisandro Dalcin   Input Parameters:
1492bcf0153eSBarry Smith + ts - the `TS` context
1493efe9872eSLisandro Dalcin . t  - current time
1494efe9872eSLisandro Dalcin . U  - state vector
1495efe9872eSLisandro Dalcin . V  - time derivative of state vector (U_t)
1496efe9872eSLisandro Dalcin - A  - second time derivative of state vector (U_tt)
1497efe9872eSLisandro Dalcin 
1498efe9872eSLisandro Dalcin   Output Parameter:
1499efe9872eSLisandro Dalcin . F - the residual vector
1500efe9872eSLisandro Dalcin 
1501bcf0153eSBarry Smith   Level: developer
1502bcf0153eSBarry Smith 
1503efe9872eSLisandro Dalcin   Note:
1504efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1505efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1506efe9872eSLisandro Dalcin 
15071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1508efe9872eSLisandro Dalcin @*/
1509d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1510d71ae5a4SJacob Faibussowitsch {
1511efe9872eSLisandro Dalcin   DM               dm;
15128434afd1SBarry Smith   TSI2FunctionFn  *I2Function;
1513efe9872eSLisandro Dalcin   void            *ctx;
15148434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
1515efe9872eSLisandro Dalcin 
1516efe9872eSLisandro Dalcin   PetscFunctionBegin;
1517efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1518efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1519efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1520efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1521efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1522efe9872eSLisandro Dalcin 
15239566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15249566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15259566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1526efe9872eSLisandro Dalcin 
1527efe9872eSLisandro Dalcin   if (!I2Function) {
15289566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
15293ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1530efe9872eSLisandro Dalcin   }
1531efe9872eSLisandro Dalcin 
1532da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, V, F));
1533efe9872eSLisandro Dalcin 
1534792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1535efe9872eSLisandro Dalcin 
1536efe9872eSLisandro Dalcin   if (rhsfunction) {
1537efe9872eSLisandro Dalcin     Vec Frhs;
15388af0501fSStefano Zampini 
15398af0501fSStefano Zampini     PetscCall(DMGetGlobalVector(dm, &Frhs));
15409566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15419566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
15428af0501fSStefano Zampini     PetscCall(DMRestoreGlobalVector(dm, &Frhs));
1543efe9872eSLisandro Dalcin   }
1544efe9872eSLisandro Dalcin 
1545da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, V, F));
15463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1547efe9872eSLisandro Dalcin }
1548efe9872eSLisandro Dalcin 
1549efe9872eSLisandro Dalcin /*@
1550efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1551efe9872eSLisandro Dalcin 
1552c3339decSBarry Smith   Collective
1553efe9872eSLisandro Dalcin 
1554efe9872eSLisandro Dalcin   Input Parameters:
1555bcf0153eSBarry Smith + ts     - the `TS` context
1556efe9872eSLisandro Dalcin . t      - current timestep
1557efe9872eSLisandro Dalcin . U      - state vector
1558efe9872eSLisandro Dalcin . V      - time derivative of state vector
1559efe9872eSLisandro Dalcin . A      - second time derivative of state vector
1560efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1561efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1562efe9872eSLisandro Dalcin 
1563efe9872eSLisandro Dalcin   Output Parameters:
1564efe9872eSLisandro Dalcin + J - Jacobian matrix
1565efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1566efe9872eSLisandro Dalcin 
1567bcf0153eSBarry Smith   Level: developer
1568bcf0153eSBarry Smith 
1569efe9872eSLisandro Dalcin   Notes:
1570efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1571efe9872eSLisandro Dalcin 
1572efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1573efe9872eSLisandro Dalcin 
1574efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1575efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1576efe9872eSLisandro Dalcin 
15771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1578efe9872eSLisandro Dalcin @*/
1579d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1580d71ae5a4SJacob Faibussowitsch {
1581efe9872eSLisandro Dalcin   DM               dm;
15828434afd1SBarry Smith   TSI2JacobianFn  *I2Jacobian;
1583efe9872eSLisandro Dalcin   void            *ctx;
15848434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
1585efe9872eSLisandro Dalcin 
1586efe9872eSLisandro Dalcin   PetscFunctionBegin;
1587efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1588efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1589efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1590efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1591efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1592efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1593efe9872eSLisandro Dalcin 
15949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15959566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
15969566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1597efe9872eSLisandro Dalcin 
1598efe9872eSLisandro Dalcin   if (!I2Jacobian) {
15999566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16003ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1601efe9872eSLisandro Dalcin   }
1602efe9872eSLisandro Dalcin 
1603da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, J, P));
1604792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1605efe9872eSLisandro Dalcin   if (rhsjacobian) {
1606d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16079566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16089566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16099566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16109566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1611efe9872eSLisandro Dalcin   }
1612efe9872eSLisandro Dalcin 
1613da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, J, P));
16143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1615efe9872eSLisandro Dalcin }
1616efe9872eSLisandro Dalcin 
1617438f35afSJed Brown /*@C
1618438f35afSJed Brown   TSSetTransientVariable - sets function to transform from state to transient variables
1619438f35afSJed Brown 
1620438f35afSJed Brown   Logically Collective
1621438f35afSJed Brown 
16224165533cSJose E. Roman   Input Parameters:
1623438f35afSJed Brown + ts   - time stepping context on which to change the transient variable
16248434afd1SBarry Smith . tvar - a function that transforms to transient variables, see `TSTransientVariableFn` for the calling sequence
1625438f35afSJed Brown - ctx  - a context for tvar
1626438f35afSJed Brown 
1627438f35afSJed Brown   Level: advanced
1628438f35afSJed Brown 
1629438f35afSJed Brown   Notes:
1630bcf0153eSBarry Smith   This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1631438f35afSJed Brown   can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1632438f35afSJed Brown   well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1633438f35afSJed Brown   C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1634438f35afSJed Brown   evaluated via the chain rule, as in
1635195e9b02SBarry Smith .vb
1636438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1637195e9b02SBarry Smith .ve
1638438f35afSJed Brown 
16398434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariableFn`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1640438f35afSJed Brown @*/
16418434afd1SBarry Smith PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariableFn *tvar, void *ctx)
1642d71ae5a4SJacob Faibussowitsch {
1643438f35afSJed Brown   DM dm;
1644438f35afSJed Brown 
1645438f35afSJed Brown   PetscFunctionBegin;
1646438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
16479566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16489566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
16493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1650438f35afSJed Brown }
1651438f35afSJed Brown 
1652efe9872eSLisandro Dalcin /*@
1653e3c11fc1SJed Brown   TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1654e3c11fc1SJed Brown 
1655e3c11fc1SJed Brown   Logically Collective
1656e3c11fc1SJed Brown 
1657e3c11fc1SJed Brown   Input Parameters:
1658e3c11fc1SJed Brown + ts - TS on which to compute
1659e3c11fc1SJed Brown - U  - state vector to be transformed to transient variables
1660e3c11fc1SJed Brown 
16612fe279fdSBarry Smith   Output Parameter:
1662e3c11fc1SJed Brown . C - transient (conservative) variable
1663e3c11fc1SJed Brown 
1664e3c11fc1SJed Brown   Level: developer
1665e3c11fc1SJed Brown 
1666b43aa488SJacob Faibussowitsch   Developer Notes:
1667195e9b02SBarry Smith   If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1668bcf0153eSBarry Smith   This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1669bcf0153eSBarry Smith   being used.
1670bcf0153eSBarry Smith 
16711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1672e3c11fc1SJed Brown @*/
1673d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1674d71ae5a4SJacob Faibussowitsch {
1675e3c11fc1SJed Brown   DM   dm;
1676e3c11fc1SJed Brown   DMTS dmts;
1677e3c11fc1SJed Brown 
1678e3c11fc1SJed Brown   PetscFunctionBegin;
1679e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1680e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
16819566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16829566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1683e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1684e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
16859566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1686e3c11fc1SJed Brown   }
16873ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1688e3c11fc1SJed Brown }
1689e3c11fc1SJed Brown 
1690e3c11fc1SJed Brown /*@
1691e3c11fc1SJed Brown   TSHasTransientVariable - determine whether transient variables have been set
1692e3c11fc1SJed Brown 
1693e3c11fc1SJed Brown   Logically Collective
1694e3c11fc1SJed Brown 
16952fe279fdSBarry Smith   Input Parameter:
1696195e9b02SBarry Smith . ts - `TS` on which to compute
1697e3c11fc1SJed Brown 
16982fe279fdSBarry Smith   Output Parameter:
1699bcf0153eSBarry Smith . has - `PETSC_TRUE` if transient variables have been set
1700e3c11fc1SJed Brown 
1701e3c11fc1SJed Brown   Level: developer
1702e3c11fc1SJed Brown 
17031cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1704e3c11fc1SJed Brown @*/
1705d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1706d71ae5a4SJacob Faibussowitsch {
1707e3c11fc1SJed Brown   DM   dm;
1708e3c11fc1SJed Brown   DMTS dmts;
1709e3c11fc1SJed Brown 
1710e3c11fc1SJed Brown   PetscFunctionBegin;
1711e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17129566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17139566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1714e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
17153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1716e3c11fc1SJed Brown }
1717e3c11fc1SJed Brown 
1718e3c11fc1SJed Brown /*@
1719efe9872eSLisandro Dalcin   TS2SetSolution - Sets the initial solution and time derivative vectors
1720bcf0153eSBarry Smith   for use by the `TS` routines handling second order equations.
1721efe9872eSLisandro Dalcin 
1722c3339decSBarry Smith   Logically Collective
1723efe9872eSLisandro Dalcin 
1724efe9872eSLisandro Dalcin   Input Parameters:
1725bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
1726efe9872eSLisandro Dalcin . u  - the solution vector
1727efe9872eSLisandro Dalcin - v  - the time derivative vector
1728efe9872eSLisandro Dalcin 
1729efe9872eSLisandro Dalcin   Level: beginner
1730efe9872eSLisandro Dalcin 
17311cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
1732efe9872eSLisandro Dalcin @*/
1733d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1734d71ae5a4SJacob Faibussowitsch {
1735efe9872eSLisandro Dalcin   PetscFunctionBegin;
1736efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1737efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1738efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
17399566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
17409566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
17419566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1742efe9872eSLisandro Dalcin   ts->vec_dot = v;
17433ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1744efe9872eSLisandro Dalcin }
1745efe9872eSLisandro Dalcin 
1746efe9872eSLisandro Dalcin /*@
1747efe9872eSLisandro Dalcin   TS2GetSolution - Returns the solution and time derivative at the present timestep
174814d0ab18SJacob Faibussowitsch   for second order equations.
1749efe9872eSLisandro Dalcin 
175014d0ab18SJacob Faibussowitsch   Not Collective
1751efe9872eSLisandro Dalcin 
1752efe9872eSLisandro Dalcin   Input Parameter:
1753bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
1754efe9872eSLisandro Dalcin 
1755d8d19677SJose E. Roman   Output Parameters:
1756efe9872eSLisandro Dalcin + u - the vector containing the solution
1757efe9872eSLisandro Dalcin - v - the vector containing the time derivative
1758efe9872eSLisandro Dalcin 
1759efe9872eSLisandro Dalcin   Level: intermediate
1760efe9872eSLisandro Dalcin 
176114d0ab18SJacob Faibussowitsch   Notes:
176214d0ab18SJacob Faibussowitsch   It is valid to call this routine inside the function
176314d0ab18SJacob Faibussowitsch   that you are evaluating in order to move to the new timestep. This vector not
176414d0ab18SJacob Faibussowitsch   changed until the solution at the next timestep has been calculated.
176514d0ab18SJacob Faibussowitsch 
17661cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1767efe9872eSLisandro Dalcin @*/
1768d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1769d71ae5a4SJacob Faibussowitsch {
1770efe9872eSLisandro Dalcin   PetscFunctionBegin;
1771efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17724f572ea9SToby Isaac   if (u) PetscAssertPointer(u, 2);
17734f572ea9SToby Isaac   if (v) PetscAssertPointer(v, 3);
1774efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1775efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
17763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1777efe9872eSLisandro Dalcin }
1778efe9872eSLisandro Dalcin 
1779ffeef943SBarry Smith /*@
1780bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
178155849f57SBarry Smith 
1782c3339decSBarry Smith   Collective
178355849f57SBarry Smith 
178455849f57SBarry Smith   Input Parameters:
1785b43aa488SJacob Faibussowitsch + ts     - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1786bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1787bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
178855849f57SBarry Smith 
178955849f57SBarry Smith   Level: intermediate
179055849f57SBarry Smith 
1791bcf0153eSBarry Smith   Note:
1792bcf0153eSBarry Smith   The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
179355849f57SBarry Smith 
17941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
179555849f57SBarry Smith @*/
1796d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1797d71ae5a4SJacob Faibussowitsch {
179855849f57SBarry Smith   PetscBool isbinary;
179955849f57SBarry Smith   PetscInt  classid;
180055849f57SBarry Smith   char      type[256];
18012d53ad75SBarry Smith   DMTS      sdm;
1802ad6bc421SBarry Smith   DM        dm;
180355849f57SBarry Smith 
180455849f57SBarry Smith   PetscFunctionBegin;
1805f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
180655849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18079566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18083c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
180955849f57SBarry Smith 
18109566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18113c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18129566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18139566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1814dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18159566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18169566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18179566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18189566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18199566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18209566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18219566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
18223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
182355849f57SBarry Smith }
182455849f57SBarry Smith 
18259804daf3SBarry Smith #include <petscdraw.h>
1826e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1827e04113cfSBarry Smith   #include <petscviewersaws.h>
1828f05ece33SBarry Smith #endif
1829fe2efc57SMark 
1830ffeef943SBarry Smith /*@
1831bcf0153eSBarry Smith   TSViewFromOptions - View a `TS` based on values in the options database
1832fe2efc57SMark 
1833c3339decSBarry Smith   Collective
1834fe2efc57SMark 
1835fe2efc57SMark   Input Parameters:
1836bcf0153eSBarry Smith + ts   - the `TS` context
1837bcf0153eSBarry Smith . obj  - Optional object that provides the prefix for the options database keys
1838bcf0153eSBarry Smith - name - command line option string to be passed by user
1839fe2efc57SMark 
1840fe2efc57SMark   Level: intermediate
1841bcf0153eSBarry Smith 
18421cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1843fe2efc57SMark @*/
1844bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1845d71ae5a4SJacob Faibussowitsch {
1846fe2efc57SMark   PetscFunctionBegin;
1847bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1848bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
18493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1850fe2efc57SMark }
1851fe2efc57SMark 
1852ffeef943SBarry Smith /*@
1853bcf0153eSBarry Smith   TSView - Prints the `TS` data structure.
1854d763cef2SBarry Smith 
1855c3339decSBarry Smith   Collective
1856d763cef2SBarry Smith 
1857d763cef2SBarry Smith   Input Parameters:
1858bcf0153eSBarry Smith + ts     - the `TS` context obtained from `TSCreate()`
1859d763cef2SBarry Smith - viewer - visualization context
1860d763cef2SBarry Smith 
1861d763cef2SBarry Smith   Options Database Key:
1862bcf0153eSBarry Smith . -ts_view - calls `TSView()` at end of `TSStep()`
1863bcf0153eSBarry Smith 
1864bcf0153eSBarry Smith   Level: beginner
1865d763cef2SBarry Smith 
1866d763cef2SBarry Smith   Notes:
1867d763cef2SBarry Smith   The available visualization contexts include
1868bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1869bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1870d763cef2SBarry Smith   output where only the first processor opens
1871d763cef2SBarry Smith   the file.  All other processors send their
1872d763cef2SBarry Smith   data to the first processor to print.
1873d763cef2SBarry Smith 
1874d763cef2SBarry Smith   The user can open an alternative visualization context with
1875bcf0153eSBarry Smith   `PetscViewerASCIIOpen()` - output to a specified file.
1876d763cef2SBarry Smith 
1877bcf0153eSBarry Smith   In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1878595c91d4SBarry Smith 
18791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1880d763cef2SBarry Smith @*/
1881d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1882d71ae5a4SJacob Faibussowitsch {
188319fd82e9SBarry Smith   TSType    type;
18842b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
18852d53ad75SBarry Smith   DMTS      sdm;
1886e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1887536b137fSBarry Smith   PetscBool issaws;
1888f05ece33SBarry Smith #endif
1889d763cef2SBarry Smith 
1890d763cef2SBarry Smith   PetscFunctionBegin;
18910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
18921e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
18930700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1894c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1895fd16b177SBarry Smith 
18969566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
18979566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
18989566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18999566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1900e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19019566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1902f05ece33SBarry Smith #endif
190332077d6dSBarry Smith   if (iascii) {
19049566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1905efd4aadfSBarry Smith     if (ts->ops->view) {
19069566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1907dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19089566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1909efd4aadfSBarry Smith     }
19101690c2aeSBarry Smith     if (ts->max_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19111e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19121e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19131e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19141e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19151e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1916efd4aadfSBarry Smith     if (ts->usessnes) {
1917efd4aadfSBarry Smith       PetscBool lin;
19181e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
191963a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19209566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
192163a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1922efd4aadfSBarry Smith     }
192363a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19241e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19251e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19261e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
19271e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
19289566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19299566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19309566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19310f5bd95cSBarry Smith   } else if (isstring) {
19329566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19339566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1934dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
193555849f57SBarry Smith   } else if (isbinary) {
193655849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
193755849f57SBarry Smith     MPI_Comm    comm;
193855849f57SBarry Smith     PetscMPIInt rank;
193955849f57SBarry Smith     char        type[256];
194055849f57SBarry Smith 
19419566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19429566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1943dd400576SPatrick Sanan     if (rank == 0) {
19449566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
19459566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
19469566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
194755849f57SBarry Smith     }
1948dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19499566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19509566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
19519566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
19529566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
19539566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
19542b0a91c0SBarry Smith   } else if (isdraw) {
19552b0a91c0SBarry Smith     PetscDraw draw;
19562b0a91c0SBarry Smith     char      str[36];
195789fd9fafSBarry Smith     PetscReal x, y, bottom, h;
19582b0a91c0SBarry Smith 
19599566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
19609566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1961c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
1962c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
19639566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
196489fd9fafSBarry Smith     bottom = y - h;
19659566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1966dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19679566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19689566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
19699566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
1970e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1971536b137fSBarry Smith   } else if (issaws) {
1972d45a07a7SBarry Smith     PetscMPIInt rank;
19732657e9d9SBarry Smith     const char *name;
19742657e9d9SBarry Smith 
19759566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
19769566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1977dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
1978d45a07a7SBarry Smith       char dir[1024];
1979d45a07a7SBarry Smith 
19809566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
19819566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
1982792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
19839566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
1984792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
1985d763cef2SBarry Smith     }
1986dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
1987f05ece33SBarry Smith #endif
1988f05ece33SBarry Smith   }
198936a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
19909566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19919566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
19929566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
199336a9e3b9SBarry Smith   }
19949566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
19959566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
1996f05ece33SBarry Smith 
19979566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
19989566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
19999566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2001d763cef2SBarry Smith }
2002d763cef2SBarry Smith 
2003b07ff414SBarry Smith /*@
2004d763cef2SBarry Smith   TSSetApplicationContext - Sets an optional user-defined context for
2005d763cef2SBarry Smith   the timesteppers.
2006d763cef2SBarry Smith 
2007c3339decSBarry Smith   Logically Collective
2008d763cef2SBarry Smith 
2009d763cef2SBarry Smith   Input Parameters:
2010bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
2011*49abdd8aSBarry Smith - ctx - user context
2012daf670e6SBarry Smith 
2013d763cef2SBarry Smith   Level: intermediate
2014d763cef2SBarry Smith 
2015b43aa488SJacob Faibussowitsch   Fortran Notes:
2016195e9b02SBarry Smith   You must write a Fortran interface definition for this
2017195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2018bcf0153eSBarry Smith 
20191cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2020d763cef2SBarry Smith @*/
2021*49abdd8aSBarry Smith PetscErrorCode TSSetApplicationContext(TS ts, void *ctx)
2022d71ae5a4SJacob Faibussowitsch {
2023d763cef2SBarry Smith   PetscFunctionBegin;
20240700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2025*49abdd8aSBarry Smith   ts->ctx = ctx;
20263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2027d763cef2SBarry Smith }
2028d763cef2SBarry Smith 
2029b07ff414SBarry Smith /*@
2030d763cef2SBarry Smith   TSGetApplicationContext - Gets the user-defined context for the
2031bcf0153eSBarry Smith   timestepper that was set with `TSSetApplicationContext()`
2032d763cef2SBarry Smith 
2033d763cef2SBarry Smith   Not Collective
2034d763cef2SBarry Smith 
2035d763cef2SBarry Smith   Input Parameter:
2036bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2037d763cef2SBarry Smith 
2038d763cef2SBarry Smith   Output Parameter:
2039*49abdd8aSBarry Smith . ctx - user context
2040d763cef2SBarry Smith 
2041bcf0153eSBarry Smith   Level: intermediate
2042bcf0153eSBarry Smith 
2043b43aa488SJacob Faibussowitsch   Fortran Notes:
2044195e9b02SBarry Smith   You must write a Fortran interface definition for this
2045195e9b02SBarry Smith   function that tells Fortran the Fortran derived data type that you are passing in as the `ctx` argument.
2046daf670e6SBarry Smith 
20471cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2048d763cef2SBarry Smith @*/
2049*49abdd8aSBarry Smith PetscErrorCode TSGetApplicationContext(TS ts, void *ctx)
2050d71ae5a4SJacob Faibussowitsch {
2051d763cef2SBarry Smith   PetscFunctionBegin;
20520700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2053*49abdd8aSBarry Smith   *(void **)ctx = ts->ctx;
20543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2055d763cef2SBarry Smith }
2056d763cef2SBarry Smith 
2057d763cef2SBarry Smith /*@
2058bcf0153eSBarry Smith   TSGetStepNumber - Gets the number of time steps completed.
2059d763cef2SBarry Smith 
2060d763cef2SBarry Smith   Not Collective
2061d763cef2SBarry Smith 
2062d763cef2SBarry Smith   Input Parameter:
2063bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2064d763cef2SBarry Smith 
2065d763cef2SBarry Smith   Output Parameter:
206680275a0aSLisandro Dalcin . steps - number of steps completed so far
2067d763cef2SBarry Smith 
2068d763cef2SBarry Smith   Level: intermediate
2069d763cef2SBarry Smith 
20701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2071d763cef2SBarry Smith @*/
2072d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2073d71ae5a4SJacob Faibussowitsch {
2074d763cef2SBarry Smith   PetscFunctionBegin;
20750700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
20764f572ea9SToby Isaac   PetscAssertPointer(steps, 2);
207780275a0aSLisandro Dalcin   *steps = ts->steps;
20783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
207980275a0aSLisandro Dalcin }
208080275a0aSLisandro Dalcin 
208180275a0aSLisandro Dalcin /*@
208280275a0aSLisandro Dalcin   TSSetStepNumber - Sets the number of steps completed.
208380275a0aSLisandro Dalcin 
2084c3339decSBarry Smith   Logically Collective
208580275a0aSLisandro Dalcin 
208680275a0aSLisandro Dalcin   Input Parameters:
2087bcf0153eSBarry Smith + ts    - the `TS` context
208880275a0aSLisandro Dalcin - steps - number of steps completed so far
208980275a0aSLisandro Dalcin 
2090bcf0153eSBarry Smith   Level: developer
2091bcf0153eSBarry Smith 
2092bcf0153eSBarry Smith   Note:
2093bcf0153eSBarry Smith   For most uses of the `TS` solvers the user need not explicitly call
2094bcf0153eSBarry Smith   `TSSetStepNumber()`, as the step counter is appropriately updated in
2095bcf0153eSBarry Smith   `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
209680275a0aSLisandro Dalcin   reinitialize timestepping by setting the step counter to zero (and time
209780275a0aSLisandro Dalcin   to the initial time) to solve a similar problem with different initial
209880275a0aSLisandro Dalcin   conditions or parameters. Other possible use case is to continue
2099195e9b02SBarry Smith   timestepping from a previously interrupted run in such a way that `TS`
210080275a0aSLisandro Dalcin   monitors will be called with a initial nonzero step counter.
210180275a0aSLisandro Dalcin 
21021cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
210380275a0aSLisandro Dalcin @*/
2104d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2105d71ae5a4SJacob Faibussowitsch {
210680275a0aSLisandro Dalcin   PetscFunctionBegin;
210780275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
210880275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21093c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
211080275a0aSLisandro Dalcin   ts->steps = steps;
21113ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2112d763cef2SBarry Smith }
2113d763cef2SBarry Smith 
2114d763cef2SBarry Smith /*@
2115d763cef2SBarry Smith   TSSetTimeStep - Allows one to reset the timestep at any time,
2116d763cef2SBarry Smith   useful for simple pseudo-timestepping codes.
2117d763cef2SBarry Smith 
2118c3339decSBarry Smith   Logically Collective
2119d763cef2SBarry Smith 
2120d763cef2SBarry Smith   Input Parameters:
2121bcf0153eSBarry Smith + ts        - the `TS` context obtained from `TSCreate()`
2122d763cef2SBarry Smith - time_step - the size of the timestep
2123d763cef2SBarry Smith 
2124d763cef2SBarry Smith   Level: intermediate
2125d763cef2SBarry Smith 
21261cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2127d763cef2SBarry Smith @*/
2128d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2129d71ae5a4SJacob Faibussowitsch {
2130d763cef2SBarry Smith   PetscFunctionBegin;
21310700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2132c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2133d763cef2SBarry Smith   ts->time_step = time_step;
21343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2135d763cef2SBarry Smith }
2136d763cef2SBarry Smith 
2137a43b19c4SJed Brown /*@
213849354f04SShri Abhyankar   TSSetExactFinalTime - Determines whether to adapt the final time step to
213949354f04SShri Abhyankar   match the exact final time, interpolate solution to the exact final time,
2140bcf0153eSBarry Smith   or just return at the final time `TS` computed.
2141a43b19c4SJed Brown 
2142c3339decSBarry Smith   Logically Collective
2143a43b19c4SJed Brown 
2144d8d19677SJose E. Roman   Input Parameters:
2145a43b19c4SJed Brown + ts     - the time-step context
214649354f04SShri Abhyankar - eftopt - exact final time option
2147bcf0153eSBarry Smith .vb
2148bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2149bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2150bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2151bcf0153eSBarry Smith .ve
2152a43b19c4SJed Brown 
2153bcf0153eSBarry Smith   Options Database Key:
2154feed9e9dSBarry Smith . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2155feed9e9dSBarry Smith 
2156a43b19c4SJed Brown   Level: beginner
2157a43b19c4SJed Brown 
2158bcf0153eSBarry Smith   Note:
2159bcf0153eSBarry Smith   If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2160bcf0153eSBarry Smith   then the final time you selected.
2161bcf0153eSBarry Smith 
21621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2163a43b19c4SJed Brown @*/
2164d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2165d71ae5a4SJacob Faibussowitsch {
2166a43b19c4SJed Brown   PetscFunctionBegin;
2167a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
216849354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
216949354f04SShri Abhyankar   ts->exact_final_time = eftopt;
21703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2171a43b19c4SJed Brown }
2172a43b19c4SJed Brown 
2173d763cef2SBarry Smith /*@
2174bcf0153eSBarry Smith   TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2175f6953c82SLisandro Dalcin 
2176f6953c82SLisandro Dalcin   Not Collective
2177f6953c82SLisandro Dalcin 
2178f6953c82SLisandro Dalcin   Input Parameter:
2179bcf0153eSBarry Smith . ts - the `TS` context
2180f6953c82SLisandro Dalcin 
2181f6953c82SLisandro Dalcin   Output Parameter:
2182f6953c82SLisandro Dalcin . eftopt - exact final time option
2183f6953c82SLisandro Dalcin 
2184f6953c82SLisandro Dalcin   Level: beginner
2185f6953c82SLisandro Dalcin 
21861cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2187f6953c82SLisandro Dalcin @*/
2188d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2189d71ae5a4SJacob Faibussowitsch {
2190f6953c82SLisandro Dalcin   PetscFunctionBegin;
2191f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
21924f572ea9SToby Isaac   PetscAssertPointer(eftopt, 2);
2193f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
21943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2195f6953c82SLisandro Dalcin }
2196f6953c82SLisandro Dalcin 
2197f6953c82SLisandro Dalcin /*@
2198d763cef2SBarry Smith   TSGetTimeStep - Gets the current timestep size.
2199d763cef2SBarry Smith 
2200d763cef2SBarry Smith   Not Collective
2201d763cef2SBarry Smith 
2202d763cef2SBarry Smith   Input Parameter:
2203bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2204d763cef2SBarry Smith 
2205d763cef2SBarry Smith   Output Parameter:
2206d763cef2SBarry Smith . dt - the current timestep size
2207d763cef2SBarry Smith 
2208d763cef2SBarry Smith   Level: intermediate
2209d763cef2SBarry Smith 
22101cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2211d763cef2SBarry Smith @*/
2212d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2213d71ae5a4SJacob Faibussowitsch {
2214d763cef2SBarry Smith   PetscFunctionBegin;
22150700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22164f572ea9SToby Isaac   PetscAssertPointer(dt, 2);
2217d763cef2SBarry Smith   *dt = ts->time_step;
22183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2219d763cef2SBarry Smith }
2220d763cef2SBarry Smith 
2221d8e5e3e6SSatish Balay /*@
2222d763cef2SBarry Smith   TSGetSolution - Returns the solution at the present timestep. It
2223d763cef2SBarry Smith   is valid to call this routine inside the function that you are evaluating
2224d763cef2SBarry Smith   in order to move to the new timestep. This vector not changed until
2225d763cef2SBarry Smith   the solution at the next timestep has been calculated.
2226d763cef2SBarry Smith 
2227bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
2228d763cef2SBarry Smith 
2229d763cef2SBarry Smith   Input Parameter:
2230bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2231d763cef2SBarry Smith 
2232d763cef2SBarry Smith   Output Parameter:
2233d763cef2SBarry Smith . v - the vector containing the solution
2234d763cef2SBarry Smith 
2235d763cef2SBarry Smith   Level: intermediate
2236d763cef2SBarry Smith 
2237bcf0153eSBarry Smith   Note:
2238bcf0153eSBarry Smith   If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2239bcf0153eSBarry Smith   final time. It returns the solution at the next timestep.
2240d763cef2SBarry Smith 
22411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2242d763cef2SBarry Smith @*/
2243d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2244d71ae5a4SJacob Faibussowitsch {
2245d763cef2SBarry Smith   PetscFunctionBegin;
22460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22474f572ea9SToby Isaac   PetscAssertPointer(v, 2);
22488737fe31SLisandro Dalcin   *v = ts->vec_sol;
22493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2250d763cef2SBarry Smith }
2251d763cef2SBarry Smith 
225203fe5f5eSDebojyoti Ghosh /*@
2253b2bf4f3aSDebojyoti Ghosh   TSGetSolutionComponents - Returns any solution components at the present
225403fe5f5eSDebojyoti Ghosh   timestep, if available for the time integration method being used.
2255b2bf4f3aSDebojyoti Ghosh   Solution components are quantities that share the same size and
225603fe5f5eSDebojyoti Ghosh   structure as the solution vector.
225703fe5f5eSDebojyoti Ghosh 
2258bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
225903fe5f5eSDebojyoti Ghosh 
2260b43aa488SJacob Faibussowitsch   Input Parameters:
2261bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2262195e9b02SBarry Smith . n  - If v is `NULL`, then the number of solution components is
2263b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
226403fe5f5eSDebojyoti Ghosh        returned in v.
2265a2b725a8SWilliam Gropp - v  - the vector containing the n-th solution component
2266195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2267b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
226803fe5f5eSDebojyoti Ghosh 
22694cdd57e5SDebojyoti Ghosh   Level: advanced
227003fe5f5eSDebojyoti Ghosh 
22711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
227203fe5f5eSDebojyoti Ghosh @*/
2273d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2274d71ae5a4SJacob Faibussowitsch {
227503fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
227603fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2277b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2278dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
22793ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
228003fe5f5eSDebojyoti Ghosh }
228103fe5f5eSDebojyoti Ghosh 
22824cdd57e5SDebojyoti Ghosh /*@
22834cdd57e5SDebojyoti Ghosh   TSGetAuxSolution - Returns an auxiliary solution at the present
22844cdd57e5SDebojyoti Ghosh   timestep, if available for the time integration method being used.
22854cdd57e5SDebojyoti Ghosh 
2286bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
22874cdd57e5SDebojyoti Ghosh 
2288b43aa488SJacob Faibussowitsch   Input Parameters:
2289bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2290a2b725a8SWilliam Gropp - v  - the vector containing the auxiliary solution
22914cdd57e5SDebojyoti Ghosh 
22924cdd57e5SDebojyoti Ghosh   Level: intermediate
22934cdd57e5SDebojyoti Ghosh 
22941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
22954cdd57e5SDebojyoti Ghosh @*/
2296d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2297d71ae5a4SJacob Faibussowitsch {
22984cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
22994cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2300dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23011e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23034cdd57e5SDebojyoti Ghosh }
23044cdd57e5SDebojyoti Ghosh 
23054cdd57e5SDebojyoti Ghosh /*@
23064cdd57e5SDebojyoti Ghosh   TSGetTimeError - Returns the estimated error vector, if the chosen
2307bcf0153eSBarry Smith   `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23084cdd57e5SDebojyoti Ghosh 
2309bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23109657682dSDebojyoti Ghosh 
2311b43aa488SJacob Faibussowitsch   Input Parameters:
2312bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2313657c1e31SEmil Constantinescu . n  - current estimate (n=0) or previous one (n=-1)
2314a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
23154cdd57e5SDebojyoti Ghosh 
23164cdd57e5SDebojyoti Ghosh   Level: intermediate
23174cdd57e5SDebojyoti Ghosh 
2318bcf0153eSBarry Smith   Note:
2319bcf0153eSBarry Smith   MUST call after `TSSetUp()`
23204cdd57e5SDebojyoti Ghosh 
23211cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
23224cdd57e5SDebojyoti Ghosh @*/
2323d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2324d71ae5a4SJacob Faibussowitsch {
23254cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23264cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2327dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23281e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23304cdd57e5SDebojyoti Ghosh }
23314cdd57e5SDebojyoti Ghosh 
233257df6a1bSDebojyoti Ghosh /*@
233357df6a1bSDebojyoti Ghosh   TSSetTimeError - Sets the estimated error vector, if the chosen
2334bcf0153eSBarry Smith   `TSType` has an error estimation functionality. This can be used
233557df6a1bSDebojyoti Ghosh   to restart such a time integrator with a given error vector.
233657df6a1bSDebojyoti Ghosh 
2337bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
233857df6a1bSDebojyoti Ghosh 
2339b43aa488SJacob Faibussowitsch   Input Parameters:
2340bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2341a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
234257df6a1bSDebojyoti Ghosh 
234357df6a1bSDebojyoti Ghosh   Level: intermediate
234457df6a1bSDebojyoti Ghosh 
2345b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
234657df6a1bSDebojyoti Ghosh @*/
2347d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2348d71ae5a4SJacob Faibussowitsch {
234957df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
235057df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23513c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2352dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
23533ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
235457df6a1bSDebojyoti Ghosh }
235557df6a1bSDebojyoti Ghosh 
2356bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2357d8e5e3e6SSatish Balay /*@
2358bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2359d763cef2SBarry Smith 
2360bdad233fSMatthew Knepley   Not collective
2361d763cef2SBarry Smith 
2362bdad233fSMatthew Knepley   Input Parameters:
2363bcf0153eSBarry Smith + ts   - The `TS`
2364bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2365d763cef2SBarry Smith .vb
23660910c330SBarry Smith          U_t - A U = 0      (linear)
23670910c330SBarry Smith          U_t - A(t) U = 0   (linear)
23680910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2369d763cef2SBarry Smith .ve
2370d763cef2SBarry Smith 
2371d763cef2SBarry Smith   Level: beginner
2372d763cef2SBarry Smith 
23731cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2374d763cef2SBarry Smith @*/
2375d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2376d71ae5a4SJacob Faibussowitsch {
2377d763cef2SBarry Smith   PetscFunctionBegin;
23780700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2379bdad233fSMatthew Knepley   ts->problem_type = type;
23809e2a6581SJed Brown   if (type == TS_LINEAR) {
23819e2a6581SJed Brown     SNES snes;
23829566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
23839566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
23849e2a6581SJed Brown   }
23853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2386d763cef2SBarry Smith }
2387d763cef2SBarry Smith 
2388cc4c1da9SBarry Smith /*@
2389bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2390bdad233fSMatthew Knepley 
2391bdad233fSMatthew Knepley   Not collective
2392bdad233fSMatthew Knepley 
2393bdad233fSMatthew Knepley   Input Parameter:
2394bcf0153eSBarry Smith . ts - The `TS`
2395bdad233fSMatthew Knepley 
2396bdad233fSMatthew Knepley   Output Parameter:
2397bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2398bdad233fSMatthew Knepley .vb
2399089b2837SJed Brown          M U_t = A U
2400089b2837SJed Brown          M(t) U_t = A(t) U
2401b5abc632SBarry Smith          F(t,U,U_t)
2402bdad233fSMatthew Knepley .ve
2403bdad233fSMatthew Knepley 
2404bdad233fSMatthew Knepley   Level: beginner
2405bdad233fSMatthew Knepley 
24061cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2407bdad233fSMatthew Knepley @*/
2408d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2409d71ae5a4SJacob Faibussowitsch {
2410bdad233fSMatthew Knepley   PetscFunctionBegin;
24110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24124f572ea9SToby Isaac   PetscAssertPointer(type, 2);
2413bdad233fSMatthew Knepley   *type = ts->problem_type;
24143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2415bdad233fSMatthew Knepley }
2416d763cef2SBarry Smith 
2417303a5415SBarry Smith /*
2418303a5415SBarry 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()
2419303a5415SBarry Smith */
2420d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2421d71ae5a4SJacob Faibussowitsch {
2422303a5415SBarry Smith   PetscBool isnone;
2423303a5415SBarry Smith 
2424303a5415SBarry Smith   PetscFunctionBegin;
24259566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24269566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2427303a5415SBarry Smith 
24289566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24291e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24301e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
24313ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2432303a5415SBarry Smith }
2433303a5415SBarry Smith 
2434d763cef2SBarry Smith /*@
2435303a5415SBarry Smith   TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2436d763cef2SBarry Smith 
2437c3339decSBarry Smith   Collective
2438d763cef2SBarry Smith 
2439d763cef2SBarry Smith   Input Parameter:
2440bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2441d763cef2SBarry Smith 
2442d763cef2SBarry Smith   Level: advanced
2443d763cef2SBarry Smith 
2444bcf0153eSBarry Smith   Note:
2445bcf0153eSBarry Smith   For basic use of the `TS` solvers the user need not explicitly call
2446bcf0153eSBarry Smith   `TSSetUp()`, since these actions will automatically occur during
2447bcf0153eSBarry Smith   the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2448bcf0153eSBarry Smith   phase separately, `TSSetUp()` should be called after `TSCreate()`
2449bcf0153eSBarry Smith   and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2450bcf0153eSBarry Smith 
24511cc06b55SBarry Smith .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2452d763cef2SBarry Smith @*/
2453d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2454d71ae5a4SJacob Faibussowitsch {
24556c6b9e74SPeter Brune   DM dm;
24566c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2457d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
24588434afd1SBarry Smith   TSIFunctionFn   *ifun;
24598434afd1SBarry Smith   TSIJacobianFn   *ijac;
24608434afd1SBarry Smith   TSI2JacobianFn  *i2jac;
24618434afd1SBarry Smith   TSRHSJacobianFn *rhsjac;
2462d763cef2SBarry Smith 
2463d763cef2SBarry Smith   PetscFunctionBegin;
24640700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24653ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2466277b19d0SLisandro Dalcin 
24677adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
24689566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
24699566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2470d763cef2SBarry Smith   }
2471277b19d0SLisandro Dalcin 
24721a638600SStefano Zampini   if (!ts->vec_sol) {
24731e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
24749566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
24751a638600SStefano Zampini   }
2476277b19d0SLisandro Dalcin 
24774a658b32SHong Zhang   if (ts->tspan) {
24781e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
24794a658b32SHong Zhang   }
2480298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
24819566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2482298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2483298bade4SHong Zhang   }
2484298bade4SHong Zhang 
2485cd4cee2dSHong Zhang   if (ts->quadraturets) {
24869566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
24879566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
24889566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2489cd4cee2dSHong Zhang   }
2490cd4cee2dSHong Zhang 
24919566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2492f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2493e1244c69SJed Brown     Mat  Amat, Pmat;
2494e1244c69SJed Brown     SNES snes;
24959566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24969566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2497e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2498e1244c69SJed Brown      * have displaced the RHS matrix */
2499971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2500abc0d4abSBarry 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 */
25019566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25029566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25039566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2504e1244c69SJed Brown     }
2505971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25069566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25079566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25089566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2509e1244c69SJed Brown     }
2510e1244c69SJed Brown   }
25112ffb9264SLisandro Dalcin 
25129566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25139566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25142ffb9264SLisandro Dalcin 
2515dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2516277b19d0SLisandro Dalcin 
25179566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25182ffb9264SLisandro Dalcin 
2519a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25206c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25216c6b9e74SPeter Brune    */
25229566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25239566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25241e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25251e66621cSBarry Smith 
2526a6772fa2SLisandro 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.
25276c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25286c6b9e74SPeter Brune    */
25299566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25309566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25319566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25329566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25331e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2534c0517034SDebojyoti Ghosh 
2535c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2536dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2537c0517034SDebojyoti Ghosh 
2538277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25393ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2540277b19d0SLisandro Dalcin }
2541277b19d0SLisandro Dalcin 
2542f6a906c0SBarry Smith /*@
2543bcf0153eSBarry Smith   TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2544277b19d0SLisandro Dalcin 
2545c3339decSBarry Smith   Collective
2546277b19d0SLisandro Dalcin 
2547277b19d0SLisandro Dalcin   Input Parameter:
2548bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2549277b19d0SLisandro Dalcin 
2550277b19d0SLisandro Dalcin   Level: beginner
2551277b19d0SLisandro Dalcin 
25521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2553277b19d0SLisandro Dalcin @*/
2554d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2555d71ae5a4SJacob Faibussowitsch {
25561d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2557277b19d0SLisandro Dalcin 
2558277b19d0SLisandro Dalcin   PetscFunctionBegin;
2559277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2560b18ea86cSHong Zhang 
2561dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25629566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25639566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2564bbd56ea5SKarl Rupp 
25659566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
25669566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
25679566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
25689566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
2569c61711c8SStefano Zampini   PetscCall(VecDestroy(&ts->vec_sol0));
25709566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
25719566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
25729566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
25739566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2574bbd56ea5SKarl Rupp 
25759566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
25769566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
25771baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2578cd4cee2dSHong Zhang   if (ts->quadraturets) {
25799566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
25809566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2581cd4cee2dSHong Zhang   }
25821d06f6b3SHong Zhang   while (ilink) {
25831d06f6b3SHong Zhang     next = ilink->next;
25849566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
25859566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
25869566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
25879566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
25881d06f6b3SHong Zhang     ilink = next;
258987f4e208SHong Zhang   }
25906bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2591545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
25924a658b32SHong Zhang   if (ts->tspan) {
25934a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
25944a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25954a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
25964a658b32SHong Zhang   }
2597b3a72457SStefano Zampini   ts->rhsjacobian.time  = PETSC_MIN_REAL;
2598b3a72457SStefano Zampini   ts->rhsjacobian.scale = 1.0;
2599b3a72457SStefano Zampini   ts->ijacobian.shift   = 1.0;
2600277b19d0SLisandro Dalcin   ts->setupcalled       = PETSC_FALSE;
26013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2602d763cef2SBarry Smith }
2603d763cef2SBarry Smith 
260414d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
260514d0ab18SJacob Faibussowitsch 
26060764c050SBarry Smith /*@
2607d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2608bcf0153eSBarry Smith   with `TSCreate()`.
2609d763cef2SBarry Smith 
2610c3339decSBarry Smith   Collective
2611d763cef2SBarry Smith 
2612d763cef2SBarry Smith   Input Parameter:
2613bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2614d763cef2SBarry Smith 
2615d763cef2SBarry Smith   Level: beginner
2616d763cef2SBarry Smith 
26171cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2618d763cef2SBarry Smith @*/
2619d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2620d71ae5a4SJacob Faibussowitsch {
2621d763cef2SBarry Smith   PetscFunctionBegin;
26223ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2623ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
2624f4f49eeaSPierre Jolivet   if (--((PetscObject)*ts)->refct > 0) {
26259371c9d4SSatish Balay     *ts = NULL;
26263ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26279371c9d4SSatish Balay   }
2628d763cef2SBarry Smith 
26299566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26309566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26311e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26326bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26331e66621cSBarry Smith 
2634e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26359566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2636f4f49eeaSPierre Jolivet   PetscTryTypeMethod(*ts, destroy);
26376d4c513bSLisandro Dalcin 
26389566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2639bc952696SBarry Smith 
26409566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26419566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26426427ac75SLisandro Dalcin 
26439566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26444bd3aaa3SHong Zhang   PetscCall(SNESDestroy(&(*ts)->snesrhssplit));
26459566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
2646f4f49eeaSPierre Jolivet   PetscCall(TSMonitorCancel(*ts));
2647f4f49eeaSPierre Jolivet   PetscCall(TSAdjointMonitorCancel(*ts));
26486d4c513bSLisandro Dalcin 
26499566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26509566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2652d763cef2SBarry Smith }
2653d763cef2SBarry Smith 
2654d8e5e3e6SSatish Balay /*@
2655bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2656bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2657d763cef2SBarry Smith 
2658bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2659d763cef2SBarry Smith 
2660d763cef2SBarry Smith   Input Parameter:
2661bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2662d763cef2SBarry Smith 
2663d763cef2SBarry Smith   Output Parameter:
2664d763cef2SBarry Smith . snes - the nonlinear solver context
2665d763cef2SBarry Smith 
2666d763cef2SBarry Smith   Level: beginner
2667d763cef2SBarry Smith 
2668bcf0153eSBarry Smith   Notes:
2669bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2670bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2671bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2672bcf0153eSBarry Smith 
2673bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2674195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2675bcf0153eSBarry Smith 
26761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2677d763cef2SBarry Smith @*/
2678d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2679d71ae5a4SJacob Faibussowitsch {
2680d763cef2SBarry Smith   PetscFunctionBegin;
26810700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
26824f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2683d372ba47SLisandro Dalcin   if (!ts->snes) {
26849566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
26859566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
26869566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
26879566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
26884bd3aaa3SHong Zhang     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
26891e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2690d372ba47SLisandro Dalcin   }
2691d763cef2SBarry Smith   *snes = ts->snes;
26923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2693d763cef2SBarry Smith }
2694d763cef2SBarry Smith 
2695deb2cd25SJed Brown /*@
2696bcf0153eSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2697deb2cd25SJed Brown 
2698deb2cd25SJed Brown   Collective
2699deb2cd25SJed Brown 
2700d8d19677SJose E. Roman   Input Parameters:
2701bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2702deb2cd25SJed Brown - snes - the nonlinear solver context
2703deb2cd25SJed Brown 
2704deb2cd25SJed Brown   Level: developer
2705deb2cd25SJed Brown 
2706bcf0153eSBarry Smith   Note:
2707bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2708bcf0153eSBarry Smith 
27091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2710deb2cd25SJed Brown @*/
2711d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2712d71ae5a4SJacob Faibussowitsch {
2713d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2714deb2cd25SJed Brown 
2715deb2cd25SJed Brown   PetscFunctionBegin;
2716deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2717deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27189566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27199566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2720bbd56ea5SKarl Rupp 
2721deb2cd25SJed Brown   ts->snes = snes;
2722bbd56ea5SKarl Rupp 
27239566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27249566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27251e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2727deb2cd25SJed Brown }
2728deb2cd25SJed Brown 
2729d8e5e3e6SSatish Balay /*@
2730bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2731bcf0153eSBarry Smith   a `TS` (timestepper) context.
2732d763cef2SBarry Smith 
2733195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2734d763cef2SBarry Smith 
2735d763cef2SBarry Smith   Input Parameter:
2736bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2737d763cef2SBarry Smith 
2738d763cef2SBarry Smith   Output Parameter:
273994b7f48cSBarry Smith . ksp - the nonlinear solver context
2740d763cef2SBarry Smith 
2741d763cef2SBarry Smith   Level: beginner
2742d763cef2SBarry Smith 
2743bcf0153eSBarry Smith   Notes:
2744bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2745bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2746bcf0153eSBarry Smith   `PC` context as well.
2747bcf0153eSBarry Smith 
2748bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2749195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2750bcf0153eSBarry Smith 
27511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2752d763cef2SBarry Smith @*/
2753d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2754d71ae5a4SJacob Faibussowitsch {
2755089b2837SJed Brown   SNES snes;
2756d372ba47SLisandro Dalcin 
2757d763cef2SBarry Smith   PetscFunctionBegin;
27580700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27594f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27603c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27613c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27629566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
27639566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
27643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2765d763cef2SBarry Smith }
2766d763cef2SBarry Smith 
2767d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2768d763cef2SBarry Smith 
2769adb62b0dSMatthew Knepley /*@
2770618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2771618ce8baSLisandro Dalcin 
2772c3339decSBarry Smith   Logically Collective
2773618ce8baSLisandro Dalcin 
2774618ce8baSLisandro Dalcin   Input Parameters:
2775bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2776618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2777618ce8baSLisandro Dalcin 
2778bcf0153eSBarry Smith   Options Database Key:
2779618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2780618ce8baSLisandro Dalcin 
2781618ce8baSLisandro Dalcin   Level: intermediate
2782618ce8baSLisandro Dalcin 
2783bcf0153eSBarry Smith   Note:
278409cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
278509cb0f53SBarry Smith 
278609cb0f53SBarry Smith   The default maximum number of steps is 5,000
278709cb0f53SBarry Smith 
278809cb0f53SBarry Smith   Fortran Note:
278909cb0f53SBarry Smith   Use `PETSC_DETERMINE_INTEGER`
2790bcf0153eSBarry Smith 
27911cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2792618ce8baSLisandro Dalcin @*/
2793d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2794d71ae5a4SJacob Faibussowitsch {
2795618ce8baSLisandro Dalcin   PetscFunctionBegin;
2796618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2797618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
279809cb0f53SBarry Smith   if (maxsteps == PETSC_DETERMINE) {
279909cb0f53SBarry Smith     ts->max_steps = ts->default_max_steps;
280009cb0f53SBarry Smith   } else {
28013c633725SBarry Smith     PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2802618ce8baSLisandro Dalcin     ts->max_steps = maxsteps;
280309cb0f53SBarry Smith   }
28043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2805618ce8baSLisandro Dalcin }
2806618ce8baSLisandro Dalcin 
2807618ce8baSLisandro Dalcin /*@
2808618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2809618ce8baSLisandro Dalcin 
2810618ce8baSLisandro Dalcin   Not Collective
2811618ce8baSLisandro Dalcin 
28122fe279fdSBarry Smith   Input Parameter:
2813bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2814618ce8baSLisandro Dalcin 
2815618ce8baSLisandro Dalcin   Output Parameter:
2816618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2817618ce8baSLisandro Dalcin 
2818618ce8baSLisandro Dalcin   Level: advanced
2819618ce8baSLisandro Dalcin 
28201cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2821618ce8baSLisandro Dalcin @*/
2822d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2823d71ae5a4SJacob Faibussowitsch {
2824618ce8baSLisandro Dalcin   PetscFunctionBegin;
2825618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28264f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2827618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2829618ce8baSLisandro Dalcin }
2830618ce8baSLisandro Dalcin 
2831618ce8baSLisandro Dalcin /*@
2832618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2833618ce8baSLisandro Dalcin 
2834c3339decSBarry Smith   Logically Collective
2835618ce8baSLisandro Dalcin 
2836618ce8baSLisandro Dalcin   Input Parameters:
2837bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2838618ce8baSLisandro Dalcin - maxtime - final time to step to
2839618ce8baSLisandro Dalcin 
2840bcf0153eSBarry Smith   Options Database Key:
2841ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2842618ce8baSLisandro Dalcin 
2843bcf0153eSBarry Smith   Level: intermediate
2844bcf0153eSBarry Smith 
2845618ce8baSLisandro Dalcin   Notes:
284609cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
284709cb0f53SBarry Smith 
2848618ce8baSLisandro Dalcin   The default maximum time is 5.0
2849618ce8baSLisandro Dalcin 
285009cb0f53SBarry Smith   Fortran Note:
285109cb0f53SBarry Smith   Use `PETSC_DETERMINE_REAL`
285209cb0f53SBarry Smith 
28531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2854618ce8baSLisandro Dalcin @*/
2855d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2856d71ae5a4SJacob Faibussowitsch {
2857618ce8baSLisandro Dalcin   PetscFunctionBegin;
2858618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2859618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
286009cb0f53SBarry Smith   if (maxtime == PETSC_DETERMINE) {
286109cb0f53SBarry Smith     ts->max_time = ts->default_max_time;
286209cb0f53SBarry Smith   } else {
2863618ce8baSLisandro Dalcin     ts->max_time = maxtime;
286409cb0f53SBarry Smith   }
28653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2866618ce8baSLisandro Dalcin }
2867618ce8baSLisandro Dalcin 
2868618ce8baSLisandro Dalcin /*@
2869618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2870618ce8baSLisandro Dalcin 
2871618ce8baSLisandro Dalcin   Not Collective
2872618ce8baSLisandro Dalcin 
28732fe279fdSBarry Smith   Input Parameter:
2874bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2875618ce8baSLisandro Dalcin 
2876618ce8baSLisandro Dalcin   Output Parameter:
2877618ce8baSLisandro Dalcin . maxtime - final time to step to
2878618ce8baSLisandro Dalcin 
2879618ce8baSLisandro Dalcin   Level: advanced
2880618ce8baSLisandro Dalcin 
28811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2882618ce8baSLisandro Dalcin @*/
2883d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2884d71ae5a4SJacob Faibussowitsch {
2885618ce8baSLisandro Dalcin   PetscFunctionBegin;
2886618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28874f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2888618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
28893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2890618ce8baSLisandro Dalcin }
2891618ce8baSLisandro Dalcin 
289214d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2893618ce8baSLisandro Dalcin /*@
2894bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2895edc382c3SSatish Balay 
2896edc382c3SSatish Balay   Level: deprecated
2897edc382c3SSatish Balay 
2898aaa6c58dSLisandro Dalcin @*/
2899d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2900d71ae5a4SJacob Faibussowitsch {
2901aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2902aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29039566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29049566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
29053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2906aaa6c58dSLisandro Dalcin }
2907aaa6c58dSLisandro Dalcin 
290814d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2909aaa6c58dSLisandro Dalcin /*@
2910bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2911edc382c3SSatish Balay 
2912edc382c3SSatish Balay   Level: deprecated
2913edc382c3SSatish Balay 
2914adb62b0dSMatthew Knepley @*/
2915d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2916d71ae5a4SJacob Faibussowitsch {
2917adb62b0dSMatthew Knepley   PetscFunctionBegin;
29180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2919abc0a331SBarry Smith   if (maxsteps) {
29204f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
2921adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2922adb62b0dSMatthew Knepley   }
2923abc0a331SBarry Smith   if (maxtime) {
29244f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
2925adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2926adb62b0dSMatthew Knepley   }
29273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2928adb62b0dSMatthew Knepley }
2929adb62b0dSMatthew Knepley 
293014d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2931d763cef2SBarry Smith /*@
2932bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2933edc382c3SSatish Balay 
2934edc382c3SSatish Balay   Level: deprecated
2935edc382c3SSatish Balay 
2936d763cef2SBarry Smith @*/
2937d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2938d71ae5a4SJacob Faibussowitsch {
2939d763cef2SBarry Smith   PetscFunctionBegin;
294009cb0f53SBarry Smith   if (maxsteps != (PetscInt)PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
294109cb0f53SBarry Smith   if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
29423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2943d763cef2SBarry Smith }
2944d763cef2SBarry Smith 
294514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2946d763cef2SBarry Smith /*@
2947bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
2948edc382c3SSatish Balay 
2949edc382c3SSatish Balay   Level: deprecated
2950edc382c3SSatish Balay 
29515c5f5948SLisandro Dalcin @*/
2952d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
2953d71ae5a4SJacob Faibussowitsch {
29549371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29559371c9d4SSatish Balay }
29565c5f5948SLisandro Dalcin 
295714d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
295819eac22cSLisandro Dalcin /*@
2959bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
2960edc382c3SSatish Balay 
2961edc382c3SSatish Balay   Level: deprecated
2962edc382c3SSatish Balay 
29634f4e0956SLisandro Dalcin @*/
2964d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
2965d71ae5a4SJacob Faibussowitsch {
29669371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29679371c9d4SSatish Balay }
29684f4e0956SLisandro Dalcin 
29694f4e0956SLisandro Dalcin /*@
2970d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
2971bcf0153eSBarry Smith   for use by the `TS` routines.
2972d763cef2SBarry Smith 
2973c3339decSBarry Smith   Logically Collective
2974d763cef2SBarry Smith 
2975d763cef2SBarry Smith   Input Parameters:
2976bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
29770910c330SBarry Smith - u  - the solution vector
2978d763cef2SBarry Smith 
2979d763cef2SBarry Smith   Level: beginner
2980d763cef2SBarry Smith 
29811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
2982d763cef2SBarry Smith @*/
2983d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
2984d71ae5a4SJacob Faibussowitsch {
2985496e6a7aSJed Brown   DM dm;
29868737fe31SLisandro Dalcin 
2987d763cef2SBarry Smith   PetscFunctionBegin;
29880700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29890910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
29909566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
29919566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
29920910c330SBarry Smith   ts->vec_sol = u;
2993bbd56ea5SKarl Rupp 
29949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
29959566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
29963ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2997d763cef2SBarry Smith }
2998d763cef2SBarry Smith 
2999ac226902SBarry Smith /*@C
3000000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30013f2090d5SJed Brown   called once at the beginning of each time step.
3002000e7ae3SMatthew Knepley 
3003c3339decSBarry Smith   Logically Collective
3004000e7ae3SMatthew Knepley 
3005000e7ae3SMatthew Knepley   Input Parameters:
3006bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3007000e7ae3SMatthew Knepley - func - The function
3008000e7ae3SMatthew Knepley 
300920f4b53cSBarry Smith   Calling sequence of `func`:
301014d0ab18SJacob Faibussowitsch . ts - the `TS` context
3011000e7ae3SMatthew Knepley 
3012000e7ae3SMatthew Knepley   Level: intermediate
3013000e7ae3SMatthew Knepley 
30141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3015000e7ae3SMatthew Knepley @*/
301614d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3017d71ae5a4SJacob Faibussowitsch {
3018000e7ae3SMatthew Knepley   PetscFunctionBegin;
30190700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3020ae60f76fSBarry Smith   ts->prestep = func;
30213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3022000e7ae3SMatthew Knepley }
3023000e7ae3SMatthew Knepley 
302409ee8438SJed Brown /*@
3025bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30263f2090d5SJed Brown 
3027c3339decSBarry Smith   Collective
30283f2090d5SJed Brown 
30292fe279fdSBarry Smith   Input Parameter:
3030bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
30313f2090d5SJed Brown 
30323f2090d5SJed Brown   Level: developer
30333f2090d5SJed Brown 
3034bcf0153eSBarry Smith   Note:
3035bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3036bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3037bcf0153eSBarry Smith 
30381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30393f2090d5SJed Brown @*/
3040d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3041d71ae5a4SJacob Faibussowitsch {
30423f2090d5SJed Brown   PetscFunctionBegin;
30430700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3044ae60f76fSBarry Smith   if (ts->prestep) {
30455efd42a4SStefano Zampini     Vec              U;
3046ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3047ef8d1ce0SJohann Rudi     PetscBool        sameObject;
30485efd42a4SStefano Zampini     PetscObjectState sprev, spost;
30495efd42a4SStefano Zampini 
30509566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30519566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
30529566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
305325e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
30549566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30559566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
30569566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
30579566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3058312ce896SJed Brown   }
30593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
30603f2090d5SJed Brown }
30613f2090d5SJed Brown 
3062b8123daeSJed Brown /*@C
3063b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3064b8123daeSJed Brown   called once at the beginning of each stage.
3065b8123daeSJed Brown 
3066c3339decSBarry Smith   Logically Collective
3067b8123daeSJed Brown 
3068b8123daeSJed Brown   Input Parameters:
3069bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3070b8123daeSJed Brown - func - The function
3071b8123daeSJed Brown 
307220f4b53cSBarry Smith   Calling sequence of `func`:
307314d0ab18SJacob Faibussowitsch + ts        - the `TS` context
307414d0ab18SJacob Faibussowitsch - stagetime - the stage time
3075b8123daeSJed Brown 
3076b8123daeSJed Brown   Level: intermediate
3077b8123daeSJed Brown 
3078b8123daeSJed Brown   Note:
3079b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3080bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3081bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3082b8123daeSJed Brown 
30831cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3084b8123daeSJed Brown @*/
308514d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3086d71ae5a4SJacob Faibussowitsch {
3087b8123daeSJed Brown   PetscFunctionBegin;
3088b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3089ae60f76fSBarry Smith   ts->prestage = func;
30903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3091b8123daeSJed Brown }
3092b8123daeSJed Brown 
30939be3e283SDebojyoti Ghosh /*@C
30940d56bcf9SIlya Fursov   TSSetPostStage - Sets the general-purpose function
30959be3e283SDebojyoti Ghosh   called once at the end of each stage.
30969be3e283SDebojyoti Ghosh 
3097c3339decSBarry Smith   Logically Collective
30989be3e283SDebojyoti Ghosh 
30999be3e283SDebojyoti Ghosh   Input Parameters:
3100bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31019be3e283SDebojyoti Ghosh - func - The function
31029be3e283SDebojyoti Ghosh 
310320f4b53cSBarry Smith   Calling sequence of `func`:
310414d0ab18SJacob Faibussowitsch + ts         - the `TS` context
310514d0ab18SJacob Faibussowitsch . stagetime  - the stage time
310614d0ab18SJacob Faibussowitsch . stageindex - the stage index
310714d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
31089be3e283SDebojyoti Ghosh 
31099be3e283SDebojyoti Ghosh   Level: intermediate
31109be3e283SDebojyoti Ghosh 
31119be3e283SDebojyoti Ghosh   Note:
31129be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3113bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3114bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31159be3e283SDebojyoti Ghosh 
31161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31179be3e283SDebojyoti Ghosh @*/
311814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3119d71ae5a4SJacob Faibussowitsch {
31209be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31219be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31229be3e283SDebojyoti Ghosh   ts->poststage = func;
31233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31249be3e283SDebojyoti Ghosh }
31259be3e283SDebojyoti Ghosh 
3126c688d042SShri Abhyankar /*@C
3127c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
31280d56bcf9SIlya Fursov   called at the end of each step evaluation.
3129c688d042SShri Abhyankar 
3130c3339decSBarry Smith   Logically Collective
3131c688d042SShri Abhyankar 
3132c688d042SShri Abhyankar   Input Parameters:
3133bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3134c688d042SShri Abhyankar - func - The function
3135c688d042SShri Abhyankar 
313620f4b53cSBarry Smith   Calling sequence of `func`:
313714d0ab18SJacob Faibussowitsch . ts - the `TS` context
3138c688d042SShri Abhyankar 
3139c688d042SShri Abhyankar   Level: intermediate
3140c688d042SShri Abhyankar 
3141c688d042SShri Abhyankar   Note:
31420d56bcf9SIlya Fursov   The function set by `TSSetPostEvaluate()` is called after the solution is evaluated, or after the step rollback.
31430d56bcf9SIlya Fursov   Inside the `func` callback, the solution vector can be obtained with `TSGetSolution()`, and modified, if need be.
31440d56bcf9SIlya Fursov   The time step can be obtained with `TSGetTimeStep()`, and the time at the start of the step - via `TSGetTime()`.
31450d56bcf9SIlya Fursov   The potential changes to the solution vector introduced by event handling (`postevent()`) are not relevant for `TSSetPostEvaluate()`,
31460d56bcf9SIlya Fursov   but are relevant for `TSSetPostStep()`, according to the function call scheme in `TSSolve()`, as shown below
31470d56bcf9SIlya Fursov .vb
31480d56bcf9SIlya Fursov   ...
31490d56bcf9SIlya Fursov   Step()
31500d56bcf9SIlya Fursov   PostEvaluate()
31510d56bcf9SIlya Fursov   EventHandling()
31520d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
31530d56bcf9SIlya Fursov   ...
31540d56bcf9SIlya Fursov .ve
31550d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
31560d56bcf9SIlya Fursov .vb
31570d56bcf9SIlya Fursov   (1) | successful step | solution intact
31580d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
31590d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
31600d56bcf9SIlya Fursov .ve
3161c688d042SShri Abhyankar 
31621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3163c688d042SShri Abhyankar @*/
316414d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3165d71ae5a4SJacob Faibussowitsch {
3166c688d042SShri Abhyankar   PetscFunctionBegin;
3167c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3168c688d042SShri Abhyankar   ts->postevaluate = func;
31693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3170c688d042SShri Abhyankar }
3171c688d042SShri Abhyankar 
3172b8123daeSJed Brown /*@
3173bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3174b8123daeSJed Brown 
3175c3339decSBarry Smith   Collective
3176b8123daeSJed Brown 
3177b8123daeSJed Brown   Input Parameters:
317814d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
317914d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3180b8123daeSJed Brown 
3181b8123daeSJed Brown   Level: developer
3182b8123daeSJed Brown 
3183bcf0153eSBarry Smith   Note:
3184bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3185bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3186bcf0153eSBarry Smith 
31871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3188b8123daeSJed Brown @*/
3189d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3190d71ae5a4SJacob Faibussowitsch {
3191b8123daeSJed Brown   PetscFunctionBegin;
3192b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31931e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
31943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3195b8123daeSJed Brown }
3196b8123daeSJed Brown 
31979be3e283SDebojyoti Ghosh /*@
3198bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
31999be3e283SDebojyoti Ghosh 
3200c3339decSBarry Smith   Collective
32019be3e283SDebojyoti Ghosh 
32029be3e283SDebojyoti Ghosh   Input Parameters:
320314d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
320414d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
320514d0ab18SJacob Faibussowitsch . stageindex - Stage number
320614d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
32079be3e283SDebojyoti Ghosh 
32089be3e283SDebojyoti Ghosh   Level: developer
32099be3e283SDebojyoti Ghosh 
3210bcf0153eSBarry Smith   Note:
3211bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3212bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3213bcf0153eSBarry Smith 
32141cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32159be3e283SDebojyoti Ghosh @*/
3216d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3217d71ae5a4SJacob Faibussowitsch {
32189be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32199be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32201e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32229be3e283SDebojyoti Ghosh }
32239be3e283SDebojyoti Ghosh 
3224c688d042SShri Abhyankar /*@
3225bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3226c688d042SShri Abhyankar 
3227c3339decSBarry Smith   Collective
3228c688d042SShri Abhyankar 
32292fe279fdSBarry Smith   Input Parameter:
3230bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3231c688d042SShri Abhyankar 
3232c688d042SShri Abhyankar   Level: developer
3233c688d042SShri Abhyankar 
3234bcf0153eSBarry Smith   Note:
3235bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3236bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3237bcf0153eSBarry Smith 
32381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3239c688d042SShri Abhyankar @*/
3240d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3241d71ae5a4SJacob Faibussowitsch {
3242c688d042SShri Abhyankar   PetscFunctionBegin;
3243c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3244c688d042SShri Abhyankar   if (ts->postevaluate) {
3245dcb233daSLisandro Dalcin     Vec              U;
3246dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3247dcb233daSLisandro Dalcin 
32489566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32499566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
325025e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
32519566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32529566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3253c688d042SShri Abhyankar   }
32543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3255c688d042SShri Abhyankar }
3256c688d042SShri Abhyankar 
3257ac226902SBarry Smith /*@C
3258000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
32590d56bcf9SIlya Fursov   called once at the end of each successful time step.
3260000e7ae3SMatthew Knepley 
3261c3339decSBarry Smith   Logically Collective
3262000e7ae3SMatthew Knepley 
3263000e7ae3SMatthew Knepley   Input Parameters:
3264bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3265000e7ae3SMatthew Knepley - func - The function
3266000e7ae3SMatthew Knepley 
326720f4b53cSBarry Smith   Calling sequence of `func`:
326814d0ab18SJacob Faibussowitsch . ts - the `TS` context
3269000e7ae3SMatthew Knepley 
3270000e7ae3SMatthew Knepley   Level: intermediate
3271000e7ae3SMatthew Knepley 
3272bcf0153eSBarry Smith   Note:
32730d56bcf9SIlya Fursov   The function set by `TSSetPostStep()` is called after each successful step. If the event handler locates an event at the
32740d56bcf9SIlya Fursov   given step, and `postevent()` modifies the solution vector, the solution vector obtained by `TSGetSolution()` inside `func` will
32750d56bcf9SIlya Fursov   contain the changes. To get the solution without these changes, use `TSSetPostEvaluate()` to set the appropriate callback.
32760d56bcf9SIlya Fursov   The scheme of the relevant function calls in `TSSolve()` is shown below
32770d56bcf9SIlya Fursov .vb
32780d56bcf9SIlya Fursov   ...
32790d56bcf9SIlya Fursov   Step()
32800d56bcf9SIlya Fursov   PostEvaluate()
32810d56bcf9SIlya Fursov   EventHandling()
32820d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
32830d56bcf9SIlya Fursov   ...
32840d56bcf9SIlya Fursov .ve
32850d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
32860d56bcf9SIlya Fursov .vb
32870d56bcf9SIlya Fursov   (1) | successful step | solution intact
32880d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
32890d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
32900d56bcf9SIlya Fursov .ve
3291bcf0153eSBarry Smith 
32921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3293000e7ae3SMatthew Knepley @*/
329414d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3295d71ae5a4SJacob Faibussowitsch {
3296000e7ae3SMatthew Knepley   PetscFunctionBegin;
32970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3298ae60f76fSBarry Smith   ts->poststep = func;
32993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3300000e7ae3SMatthew Knepley }
3301000e7ae3SMatthew Knepley 
330209ee8438SJed Brown /*@
3303195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
33043f2090d5SJed Brown 
3305c3339decSBarry Smith   Collective
33063f2090d5SJed Brown 
33072fe279fdSBarry Smith   Input Parameter:
3308bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
33093f2090d5SJed Brown 
3310bcf0153eSBarry Smith   Note:
3311bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
33123f2090d5SJed Brown   so most users would not generally call this routine themselves.
33133f2090d5SJed Brown 
33143f2090d5SJed Brown   Level: developer
33153f2090d5SJed Brown 
33161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
33173f2090d5SJed Brown @*/
3318d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3319d71ae5a4SJacob Faibussowitsch {
33203f2090d5SJed Brown   PetscFunctionBegin;
33210700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3322ae60f76fSBarry Smith   if (ts->poststep) {
33235efd42a4SStefano Zampini     Vec              U;
3324ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3325ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33265efd42a4SStefano Zampini     PetscObjectState sprev, spost;
33275efd42a4SStefano Zampini 
33289566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33299566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
33309566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
333125e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33329566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33339566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33349566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33359566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
333672ac3e02SJed Brown   }
33373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33383f2090d5SJed Brown }
33393f2090d5SJed Brown 
3340cd652676SJed Brown /*@
3341cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3342cd652676SJed Brown 
3343c3339decSBarry Smith   Collective
3344cd652676SJed Brown 
33454165533cSJose E. Roman   Input Parameters:
3346cd652676SJed Brown + ts - time stepping context
3347cd652676SJed Brown - t  - time to interpolate to
3348cd652676SJed Brown 
33494165533cSJose E. Roman   Output Parameter:
33500910c330SBarry Smith . U - state at given time
3351cd652676SJed Brown 
3352cd652676SJed Brown   Level: intermediate
3353cd652676SJed Brown 
3354b43aa488SJacob Faibussowitsch   Developer Notes:
3355bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3356cd652676SJed Brown 
33571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3358cd652676SJed Brown @*/
3359d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3360d71ae5a4SJacob Faibussowitsch {
3361cd652676SJed Brown   PetscFunctionBegin;
3362cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3363b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
336463a3b9bcSJacob 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);
3365dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
33663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3367cd652676SJed Brown }
3368cd652676SJed Brown 
3369d763cef2SBarry Smith /*@
33706d9e5789SSean Farley   TSStep - Steps one time step
3371d763cef2SBarry Smith 
3372c3339decSBarry Smith   Collective
3373d763cef2SBarry Smith 
3374d763cef2SBarry Smith   Input Parameter:
3375bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3376d763cef2SBarry Smith 
337727829d71SBarry Smith   Level: developer
3378d763cef2SBarry Smith 
3379b8123daeSJed Brown   Notes:
3380bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
338127829d71SBarry Smith 
3382bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3383b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3384b8123daeSJed Brown 
3385bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3386bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
338725cb2221SBarry Smith 
33881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3389d763cef2SBarry Smith @*/
3390d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3391d71ae5a4SJacob Faibussowitsch {
3392fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3393be5899b3SLisandro Dalcin   PetscReal        ptime;
3394d763cef2SBarry Smith 
3395d763cef2SBarry Smith   PetscFunctionBegin;
33960700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3397d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3398fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3399f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3400f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3401f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3402f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34039371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34049371c9d4SSatish Balay                                    &cite));
34059566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34069566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3407ca4445c7SIlya Fursov   if (ts->tspan)
3408ca4445c7SIlya Fursov     ts->tspan->worktol = 0; /* In each step of TSSolve() 'tspan->worktol' will be meaningfully defined (later) only once:
3409ca4445c7SIlya Fursov                                                    in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3410d405a339SMatthew Knepley 
34111690c2aeSBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
34123c633725SBarry 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()");
34133c633725SBarry 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");
3414a6772fa2SLisandro Dalcin 
3415c61711c8SStefano Zampini   if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3416c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3417c61711c8SStefano Zampini   ts->time_step0 = ts->time_step;
3418c61711c8SStefano Zampini 
3419be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
34209371c9d4SSatish Balay   ptime = ts->ptime;
3421c61711c8SStefano Zampini 
34229371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
34232808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3424fc8dbba5SLisandro Dalcin 
34259566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3426dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
34279566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3428fc8dbba5SLisandro Dalcin 
3429fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3430be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34312808aa04SLisandro Dalcin     ts->steps++;
3432be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
343328d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3434c6bf8827SStefano Zampini     ts->stepresize   = PETSC_FALSE;
3435d2daff3dSHong Zhang   }
3436fc8dbba5SLisandro Dalcin 
34375c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
34385c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
343909cb0f53SBarry 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]);
34405c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
34415c9bbc89SJed Brown   }
34423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
344308c7845fSBarry Smith }
344408c7845fSBarry Smith 
344508c7845fSBarry Smith /*@
34467cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34477cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
34487cbde773SLisandro Dalcin 
3449c3339decSBarry Smith   Collective
34507cbde773SLisandro Dalcin 
34514165533cSJose E. Roman   Input Parameters:
34527cbde773SLisandro Dalcin + ts        - time stepping context
3453bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34547cbde773SLisandro Dalcin 
345597bb3fdcSJose E. Roman   Input/Output Parameter:
3456bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
345797bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
345897bb3fdcSJose E. Roman 
345997bb3fdcSJose E. Roman   Output Parameter:
346097bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
34617cbde773SLisandro Dalcin 
34627cbde773SLisandro Dalcin   Level: advanced
34637cbde773SLisandro Dalcin 
3464bcf0153eSBarry Smith   Note:
34657cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
34667cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
34677cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
34687cbde773SLisandro Dalcin 
34691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34707cbde773SLisandro Dalcin @*/
3471d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3472d71ae5a4SJacob Faibussowitsch {
34737cbde773SLisandro Dalcin   PetscFunctionBegin;
34747cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34757cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3476064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
34774f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
34787cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
34794f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
34803c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3481dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
34823ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34837cbde773SLisandro Dalcin }
34847cbde773SLisandro Dalcin 
348505175c85SJed Brown /*@
348605175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
348705175c85SJed Brown 
3488c3339decSBarry Smith   Collective
348905175c85SJed Brown 
34904165533cSJose E. Roman   Input Parameters:
34911c3436cfSJed Brown + ts    - time stepping context
34921c3436cfSJed Brown . order - desired order of accuracy
3493195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
349405175c85SJed Brown 
34954165533cSJose E. Roman   Output Parameter:
34960910c330SBarry Smith . U - state at the end of the current step
349705175c85SJed Brown 
349805175c85SJed Brown   Level: advanced
349905175c85SJed Brown 
3500108c343cSJed Brown   Notes:
3501108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3502108c343cSJed Brown 
3503bcf0153eSBarry 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.
3504bcf0153eSBarry Smith 
35051cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
350605175c85SJed Brown @*/
3507d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3508d71ae5a4SJacob Faibussowitsch {
350905175c85SJed Brown   PetscFunctionBegin;
351005175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
351105175c85SJed Brown   PetscValidType(ts, 1);
35120910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3513dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
35143ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
351505175c85SJed Brown }
351605175c85SJed Brown 
3517aad739acSMatthew G. Knepley /*@C
35182e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3519aad739acSMatthew G. Knepley 
3520aad739acSMatthew G. Knepley   Not collective
3521aad739acSMatthew G. Knepley 
35224165533cSJose E. Roman   Input Parameter:
3523aad739acSMatthew G. Knepley . ts - time stepping context
3524aad739acSMatthew G. Knepley 
35254165533cSJose E. Roman   Output Parameter:
3526b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3527aad739acSMatthew G. Knepley 
352820f4b53cSBarry Smith   Calling sequence of `initCondition`:
352920f4b53cSBarry Smith + ts - The timestepping context
353020f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3531bcf0153eSBarry Smith 
3532aad739acSMatthew G. Knepley   Level: advanced
3533aad739acSMatthew G. Knepley 
35341cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3535aad739acSMatthew G. Knepley @*/
353614d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3537d71ae5a4SJacob Faibussowitsch {
3538aad739acSMatthew G. Knepley   PetscFunctionBegin;
3539aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35404f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
35412e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
35423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3543aad739acSMatthew G. Knepley }
3544aad739acSMatthew G. Knepley 
3545aad739acSMatthew G. Knepley /*@C
35462e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3547aad739acSMatthew G. Knepley 
3548c3339decSBarry Smith   Logically collective
3549aad739acSMatthew G. Knepley 
35504165533cSJose E. Roman   Input Parameters:
3551aad739acSMatthew G. Knepley + ts            - time stepping context
35522e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3553aad739acSMatthew G. Knepley 
355420f4b53cSBarry Smith   Calling sequence of `initCondition`:
3555a96d6ef6SBarry Smith + ts - The timestepping context
355614d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3557aad739acSMatthew G. Knepley 
3558bcf0153eSBarry Smith   Level: advanced
3559bcf0153eSBarry Smith 
35601cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3561aad739acSMatthew G. Knepley @*/
356214d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3563d71ae5a4SJacob Faibussowitsch {
3564aad739acSMatthew G. Knepley   PetscFunctionBegin;
3565aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35662e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35672e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
35683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3569aad739acSMatthew G. Knepley }
3570aad739acSMatthew G. Knepley 
3571aad739acSMatthew G. Knepley /*@
3572bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3573aad739acSMatthew G. Knepley 
3574c3339decSBarry Smith   Collective
3575aad739acSMatthew G. Knepley 
35764165533cSJose E. Roman   Input Parameters:
3577aad739acSMatthew G. Knepley + ts - time stepping context
3578bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3579aad739acSMatthew G. Knepley 
3580aad739acSMatthew G. Knepley   Level: advanced
3581aad739acSMatthew G. Knepley 
35821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3583aad739acSMatthew G. Knepley @*/
3584d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3585d71ae5a4SJacob Faibussowitsch {
3586aad739acSMatthew G. Knepley   PetscFunctionBegin;
3587aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3588aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3589dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
35903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3591aad739acSMatthew G. Knepley }
3592aad739acSMatthew G. Knepley 
3593aad739acSMatthew G. Knepley /*@C
3594aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3595aad739acSMatthew G. Knepley 
3596aad739acSMatthew G. Knepley   Not collective
3597aad739acSMatthew G. Knepley 
35984165533cSJose E. Roman   Input Parameter:
3599aad739acSMatthew G. Knepley . ts - time stepping context
3600aad739acSMatthew G. Knepley 
36014165533cSJose E. Roman   Output Parameter:
3602aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3603aad739acSMatthew G. Knepley 
360420f4b53cSBarry Smith   Calling sequence of `exactError`:
3605a96d6ef6SBarry Smith + ts - The timestepping context
3606a96d6ef6SBarry Smith . u  - The approximate solution vector
360720f4b53cSBarry Smith - e  - The vector in which the error is stored
3608aad739acSMatthew G. Knepley 
3609bcf0153eSBarry Smith   Level: advanced
3610bcf0153eSBarry Smith 
361142747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3612aad739acSMatthew G. Knepley @*/
361314d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3614d71ae5a4SJacob Faibussowitsch {
3615aad739acSMatthew G. Knepley   PetscFunctionBegin;
3616aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36174f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3618aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
36193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3620aad739acSMatthew G. Knepley }
3621aad739acSMatthew G. Knepley 
3622aad739acSMatthew G. Knepley /*@C
3623aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3624aad739acSMatthew G. Knepley 
3625c3339decSBarry Smith   Logically collective
3626aad739acSMatthew G. Knepley 
36274165533cSJose E. Roman   Input Parameters:
3628aad739acSMatthew G. Knepley + ts         - time stepping context
3629aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3630aad739acSMatthew G. Knepley 
363120f4b53cSBarry Smith   Calling sequence of `exactError`:
3632a96d6ef6SBarry Smith + ts - The timestepping context
3633a96d6ef6SBarry Smith . u  - The approximate solution vector
363420f4b53cSBarry Smith - e  - The  vector in which the error is stored
3635aad739acSMatthew G. Knepley 
3636bcf0153eSBarry Smith   Level: advanced
3637bcf0153eSBarry Smith 
36381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3639aad739acSMatthew G. Knepley @*/
364014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3641d71ae5a4SJacob Faibussowitsch {
3642aad739acSMatthew G. Knepley   PetscFunctionBegin;
3643aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3644f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3645aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
36463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3647aad739acSMatthew G. Knepley }
3648aad739acSMatthew G. Knepley 
3649aad739acSMatthew G. Knepley /*@
3650bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3651aad739acSMatthew G. Knepley 
3652c3339decSBarry Smith   Collective
3653aad739acSMatthew G. Knepley 
36544165533cSJose E. Roman   Input Parameters:
3655aad739acSMatthew G. Knepley + ts - time stepping context
3656aad739acSMatthew G. Knepley . u  - The approximate solution
3657bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3658aad739acSMatthew G. Knepley 
3659aad739acSMatthew G. Knepley   Level: advanced
3660aad739acSMatthew G. Knepley 
36611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3662aad739acSMatthew G. Knepley @*/
3663d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3664d71ae5a4SJacob Faibussowitsch {
3665aad739acSMatthew G. Knepley   PetscFunctionBegin;
3666aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3667aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3668aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3669dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
36703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3671aad739acSMatthew G. Knepley }
3672aad739acSMatthew G. Knepley 
36736bd3a4fdSStefano Zampini /*@C
36746bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
36756bd3a4fdSStefano Zampini 
36766bd3a4fdSStefano Zampini   Logically Collective
36776bd3a4fdSStefano Zampini 
36786bd3a4fdSStefano Zampini   Input Parameters:
36796bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
3680ecc87898SStefano Zampini . rollback - Whether a resize will restart the step
36816bd3a4fdSStefano Zampini . setup    - The setup function
368214d0ab18SJacob Faibussowitsch . transfer - The transfer function
368314d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
36846bd3a4fdSStefano Zampini 
36856bd3a4fdSStefano Zampini   Calling sequence of `setup`:
36868847d985SBarry Smith + ts     - the `TS` context
36876bd3a4fdSStefano Zampini . step   - the current step
36886bd3a4fdSStefano Zampini . time   - the current time
36896bd3a4fdSStefano Zampini . state  - the current vector of state
36906bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
36916bd3a4fdSStefano Zampini - ctx    - user defined context
36926bd3a4fdSStefano Zampini 
36936bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
36948847d985SBarry Smith + ts      - the `TS` context
36956bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
36966bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
36976bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
36986bd3a4fdSStefano Zampini - ctx     - user defined context
36996bd3a4fdSStefano Zampini 
37006bd3a4fdSStefano Zampini   Notes:
3701ecc87898SStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
3702ecc87898SStefano Zampini   depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
3703ecc87898SStefano Zampini   and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
3704ecc87898SStefano Zampini   that the size of the discrete problem has changed.
3705ecc87898SStefano Zampini   In both cases, the solver will collect the needed vectors that will be
3706ecc87898SStefano Zampini   transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
3707ecc87898SStefano Zampini   current solution vector, and other vectors needed by the specific solver used.
37086bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
37096bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
37106bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
37116bd3a4fdSStefano Zampini   inside the `transfer` function.
37126bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
37136bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
37146bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
37156bd3a4fdSStefano Zampini 
37166bd3a4fdSStefano Zampini   Level: advanced
37176bd3a4fdSStefano Zampini 
37186bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
37196bd3a4fdSStefano Zampini @*/
3720ecc87898SStefano 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)
37216bd3a4fdSStefano Zampini {
37226bd3a4fdSStefano Zampini   PetscFunctionBegin;
37236bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3724ecc87898SStefano Zampini   ts->resizerollback = rollback;
37256bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
37266bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
37276bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
37286bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37296bd3a4fdSStefano Zampini }
37306bd3a4fdSStefano Zampini 
373114d0ab18SJacob Faibussowitsch /*
37326bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
37336bd3a4fdSStefano Zampini 
37346bd3a4fdSStefano Zampini   Collective
37356bd3a4fdSStefano Zampini 
37366bd3a4fdSStefano Zampini   Input Parameters:
37376bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
37386bd3a4fdSStefano 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.
37396bd3a4fdSStefano Zampini 
37406bd3a4fdSStefano Zampini   Level: developer
37416bd3a4fdSStefano Zampini 
37426bd3a4fdSStefano Zampini   Note:
37436bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
37446bd3a4fdSStefano Zampini    used within time stepping implementations,
37456bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
37466bd3a4fdSStefano Zampini 
37476bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
37486bd3a4fdSStefano Zampini @*/
374914d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
37506bd3a4fdSStefano Zampini {
37516bd3a4fdSStefano Zampini   PetscFunctionBegin;
37526bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37536bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
37546bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
37556bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37566bd3a4fdSStefano Zampini }
37576bd3a4fdSStefano Zampini 
375814d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
37596bd3a4fdSStefano Zampini {
37606bd3a4fdSStefano Zampini   PetscFunctionBegin;
37616bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37626bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
37636bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37646bd3a4fdSStefano Zampini }
37656bd3a4fdSStefano Zampini 
37666bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
37676bd3a4fdSStefano Zampini {
37686bd3a4fdSStefano Zampini   PetscFunctionBegin;
37696bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37706bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
37716bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
37726bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
37736bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
37746bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
37756bd3a4fdSStefano Zampini   }
37766bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
37776bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
37786bd3a4fdSStefano Zampini }
37796bd3a4fdSStefano Zampini 
37806bd3a4fdSStefano Zampini /*@C
37816bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
37826bd3a4fdSStefano Zampini 
37836bd3a4fdSStefano Zampini   Collective
37846bd3a4fdSStefano Zampini 
37856bd3a4fdSStefano Zampini   Input Parameters:
37866bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3787baca6076SPierre Jolivet . name - A string identifying the vector
37886bd3a4fdSStefano Zampini - vec  - The vector
37896bd3a4fdSStefano Zampini 
37906bd3a4fdSStefano Zampini   Level: developer
37916bd3a4fdSStefano Zampini 
37926bd3a4fdSStefano Zampini   Note:
37936bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
37946bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
37956bd3a4fdSStefano Zampini 
37966bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
37976bd3a4fdSStefano Zampini @*/
3798cc4c1da9SBarry Smith PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
37996bd3a4fdSStefano Zampini {
38006bd3a4fdSStefano Zampini   PetscFunctionBegin;
38016bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38024f572ea9SToby Isaac   PetscAssertPointer(name, 2);
38036bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
38046bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
38056bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38066bd3a4fdSStefano Zampini }
38076bd3a4fdSStefano Zampini 
38086bd3a4fdSStefano Zampini /*@C
38096bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
38106bd3a4fdSStefano Zampini 
38116bd3a4fdSStefano Zampini   Collective
38126bd3a4fdSStefano Zampini 
38136bd3a4fdSStefano Zampini   Input Parameters:
38146bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3815baca6076SPierre Jolivet . name - A string identifying the vector
38166bd3a4fdSStefano Zampini - vec  - The vector
38176bd3a4fdSStefano Zampini 
38186bd3a4fdSStefano Zampini   Level: developer
38196bd3a4fdSStefano Zampini 
38206bd3a4fdSStefano Zampini   Note:
38216bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
38226bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38236bd3a4fdSStefano Zampini 
38246bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
38256bd3a4fdSStefano Zampini @*/
3826cc4c1da9SBarry Smith PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
38276bd3a4fdSStefano Zampini {
38286bd3a4fdSStefano Zampini   PetscFunctionBegin;
38296bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38304f572ea9SToby Isaac   PetscAssertPointer(name, 2);
38314f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
38326bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
38336bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38346bd3a4fdSStefano Zampini }
38356bd3a4fdSStefano Zampini 
38366bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
38376bd3a4fdSStefano Zampini {
38386bd3a4fdSStefano Zampini   PetscInt        cnt;
38396bd3a4fdSStefano Zampini   PetscObjectList tmp;
38406bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
38416bd3a4fdSStefano Zampini   const char    **namesin = NULL;
38426bd3a4fdSStefano Zampini 
38436bd3a4fdSStefano Zampini   PetscFunctionBegin;
38446bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
38456bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
384603ba6ac9SBarry Smith   if (names) PetscCall(PetscMalloc1(cnt, &namesin));
384703ba6ac9SBarry Smith   if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
38486bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
38496bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
38506bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
38516bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
38526bd3a4fdSStefano Zampini       cnt++;
38536bd3a4fdSStefano Zampini     }
38546bd3a4fdSStefano Zampini   }
38556bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
38566bd3a4fdSStefano Zampini   if (names) *names = namesin;
38576bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
38586bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38596bd3a4fdSStefano Zampini }
38606bd3a4fdSStefano Zampini 
38616bd3a4fdSStefano Zampini /*@
38626bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
38636bd3a4fdSStefano Zampini 
38646bd3a4fdSStefano Zampini   Collective
38656bd3a4fdSStefano Zampini 
38666bd3a4fdSStefano Zampini   Input Parameter:
38676bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
38686bd3a4fdSStefano Zampini 
38696bd3a4fdSStefano Zampini   Level: developer
38706bd3a4fdSStefano Zampini 
38716bd3a4fdSStefano Zampini   Note:
38726bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
38736bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38746bd3a4fdSStefano Zampini 
38756bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38766bd3a4fdSStefano Zampini @*/
38776bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
38786bd3a4fdSStefano Zampini {
38796bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
38806bd3a4fdSStefano Zampini   const char **names   = NULL;
38816bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
38826bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
38836bd3a4fdSStefano Zampini 
38846bd3a4fdSStefano Zampini   PetscFunctionBegin;
38856bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3886ecc87898SStefano Zampini   if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
38876bd3a4fdSStefano Zampini   if (ts->resizesetup) {
38886bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
3889c6bf8827SStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
38906bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
3891c6bf8827SStefano Zampini     if (ts->stepresize) {
3892ecc87898SStefano Zampini       if (ts->resizerollback) {
3893ecc87898SStefano Zampini         PetscCall(TSRollBack(ts));
3894ecc87898SStefano Zampini         ts->time_step = ts->time_step0;
3895ecc87898SStefano Zampini       }
38966bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
38976bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
38986bd3a4fdSStefano Zampini     }
38996bd3a4fdSStefano Zampini   }
39006bd3a4fdSStefano Zampini 
39016bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
39026bd3a4fdSStefano Zampini   if (nv) {
39036bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
39046bd3a4fdSStefano Zampini 
39056bd3a4fdSStefano Zampini     /* Reset internal objects */
39066bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
39076bd3a4fdSStefano Zampini 
3908ecc87898SStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
39096bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
39106bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
39116bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
3912ecc87898SStefano Zampini       const char *name;
3913ecc87898SStefano Zampini       char       *oname;
3914ecc87898SStefano Zampini 
3915ecc87898SStefano Zampini       PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
3916ecc87898SStefano Zampini       PetscCall(PetscStrallocpy(name, &oname));
39176bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
3918ecc87898SStefano Zampini       if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
3919ecc87898SStefano Zampini       PetscCall(PetscFree(oname));
39206bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
39216bd3a4fdSStefano Zampini     }
39226bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
39236bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
39246bd3a4fdSStefano Zampini 
39256bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
39266bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
39276bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
39286bd3a4fdSStefano Zampini   }
39296bd3a4fdSStefano Zampini 
39306bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
39316bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
39326bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
39336bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39346bd3a4fdSStefano Zampini }
39356bd3a4fdSStefano Zampini 
3936b1cb36f3SHong Zhang /*@
39376a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
39386a4d4014SLisandro Dalcin 
3939c3339decSBarry Smith   Collective
39406a4d4014SLisandro Dalcin 
3941d8d19677SJose E. Roman   Input Parameters:
3942bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
3943bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
394463e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
39455a3a76d0SJed Brown 
39466a4d4014SLisandro Dalcin   Level: beginner
39476a4d4014SLisandro Dalcin 
39485a3a76d0SJed Brown   Notes:
39495a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
3950bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
39515a3a76d0SJed Brown   stepped over the final time.
39525a3a76d0SJed Brown 
39531cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
39546a4d4014SLisandro Dalcin @*/
3955d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3956d71ae5a4SJacob Faibussowitsch {
3957b06615a5SLisandro Dalcin   Vec solution;
3958f22f69f0SBarry Smith 
39596a4d4014SLisandro Dalcin   PetscFunctionBegin;
39600700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3961f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3962303a5415SBarry Smith 
39639566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3964ee41a567SStefano 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 */
39650910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
39669566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
39679566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
39689566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
39695a3a76d0SJed Brown     }
39709566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
39713c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
39721baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
39739566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
39749566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3975a6772fa2SLisandro Dalcin 
39761690c2aeSBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
39773c633725SBarry 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()");
39783c633725SBarry 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");
39794a658b32SHong 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");
39804a658b32SHong Zhang 
3981e1db57b0SHong 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 */
39824a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
39834a658b32SHong Zhang     ts->tspan->spanctr = 1;
39844a658b32SHong Zhang   }
3985a6772fa2SLisandro Dalcin 
39861baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3987715f1b00SHong Zhang 
3988e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3989715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3990e7069c78SShri      TSTrajectory to incorrectly save the output files
3991e7069c78SShri   */
3992715f1b00SHong Zhang   /* reset time step and iteration counters */
39932808aa04SLisandro Dalcin   if (!ts->steps) {
39945ef26d82SJed Brown     ts->ksp_its           = 0;
39955ef26d82SJed Brown     ts->snes_its          = 0;
3996c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3997c610991cSLisandro Dalcin     ts->reject            = 0;
39982808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
39992808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
4000c6bf8827SStefano Zampini     ts->stepresize        = PETSC_FALSE;
40017d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
40022808aa04SLisandro Dalcin   }
4003e97c63d7SStefano Zampini 
40044a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
4005e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
40064a658b32SHong Zhang     PetscReal maxdt;
4007e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
4008e97c63d7SStefano Zampini 
40094a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
40104a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
4011e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
4012e97c63d7SStefano Zampini   }
4013193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
4014193ac0bcSJed Brown 
4015900f6b5bSMatthew G. Knepley   {
4016900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
4017900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
4018900f6b5bSMatthew G. Knepley     PetscBool         flg;
4019900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
4020900f6b5bSMatthew G. Knepley 
4021900f6b5bSMatthew G. Knepley     if (!incall) {
4022900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
4023648c30bcSBarry Smith       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
4024900f6b5bSMatthew G. Knepley       if (flg) {
4025900f6b5bSMatthew G. Knepley         PetscConvEst conv;
4026900f6b5bSMatthew G. Knepley         DM           dm;
4027900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4028900f6b5bSMatthew G. Knepley         PetscInt     Nf;
4029f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
4030900f6b5bSMatthew G. Knepley 
4031900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
40329566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
40339566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
40349566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
40359566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
40369566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
40379566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
40389566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
40399566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
40409566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
40419566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
40429566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
40439566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
40449566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
4045648c30bcSBarry Smith         PetscCall(PetscViewerDestroy(&viewer));
40469566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
40479566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
4048900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
4049900f6b5bSMatthew G. Knepley       }
4050900f6b5bSMatthew G. Knepley     }
4051900f6b5bSMatthew G. Knepley   }
4052900f6b5bSMatthew G. Knepley 
40539566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4054f05ece33SBarry Smith 
4055193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4056dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
40579566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4058cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4059a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4060be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4061db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4062db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4063e7069c78SShri 
40642808aa04SLisandro Dalcin     if (!ts->steps) {
40659566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40669566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
40672808aa04SLisandro Dalcin     }
40686427ac75SLisandro Dalcin 
4069e1a7a14fSJed Brown     while (!ts->reason) {
40709566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4071c6bf8827SStefano Zampini       if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
40729566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
40731baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
40741baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4075cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
40767b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
40779566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
40787b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4079b1cb36f3SHong Zhang       }
408058818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
40817b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
40829566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
40837b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4084715f1b00SHong Zhang       }
40859566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
40869566063dSJacob 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. */
40871baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4088ecc87898SStefano Zampini       if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
408990d719a4SStefano Zampini       /* check convergence */
409090d719a4SStefano Zampini       if (!ts->reason) {
409190d719a4SStefano Zampini         if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
409290d719a4SStefano Zampini         else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
409390d719a4SStefano Zampini       }
4094e783b05fSHong Zhang       if (!ts->steprollback) {
40959566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
40969566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
4097ecc87898SStefano Zampini         if (!ts->resizerollback) PetscCall(TSResize(ts));
4098ca4445c7SIlya Fursov 
4099ca4445c7SIlya Fursov         if (ts->tspan && ts->tspan->spanctr < ts->tspan->num_span_times) {
4100ca4445c7SIlya Fursov           PetscCheck(ts->tspan->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(tspan->worktol > 0) in TSSolve()");
4101ca4445c7SIlya 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++]));
4102ca4445c7SIlya Fursov         }
4103aeb4809dSShri Abhyankar       }
4104193ac0bcSJed Brown     }
41059566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
41066427ac75SLisandro Dalcin 
410749354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
41085dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
41099566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4110cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4111b06615a5SLisandro Dalcin       solution      = u;
41129566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
41130574a7fbSJed Brown     } else {
41149566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4115cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4116b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
41170574a7fbSJed Brown     }
4118193ac0bcSJed Brown   }
4119d2daff3dSHong Zhang 
41209566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
41219566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
41229566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
41231baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
41243ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41256a4d4014SLisandro Dalcin }
41266a4d4014SLisandro Dalcin 
4127d763cef2SBarry Smith /*@
4128b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4129d763cef2SBarry Smith 
4130d763cef2SBarry Smith   Not Collective
4131d763cef2SBarry Smith 
4132d763cef2SBarry Smith   Input Parameter:
4133bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4134d763cef2SBarry Smith 
4135d763cef2SBarry Smith   Output Parameter:
4136bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4137d763cef2SBarry Smith 
4138d763cef2SBarry Smith   Level: beginner
4139d763cef2SBarry Smith 
4140b8123daeSJed Brown   Note:
4141bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4142bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4143b8123daeSJed Brown 
4144a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4145d763cef2SBarry Smith @*/
4146d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4147d71ae5a4SJacob Faibussowitsch {
4148d763cef2SBarry Smith   PetscFunctionBegin;
41490700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41504f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4151d763cef2SBarry Smith   *t = ts->ptime;
41523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4153d763cef2SBarry Smith }
4154d763cef2SBarry Smith 
4155e5e524a1SHong Zhang /*@
4156e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4157e5e524a1SHong Zhang 
4158e5e524a1SHong Zhang   Not Collective
4159e5e524a1SHong Zhang 
4160e5e524a1SHong Zhang   Input Parameter:
4161bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4162e5e524a1SHong Zhang 
4163e5e524a1SHong Zhang   Output Parameter:
4164e5e524a1SHong Zhang . t - the previous time
4165e5e524a1SHong Zhang 
4166e5e524a1SHong Zhang   Level: beginner
4167e5e524a1SHong Zhang 
4168a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4169e5e524a1SHong Zhang @*/
4170d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4171d71ae5a4SJacob Faibussowitsch {
4172e5e524a1SHong Zhang   PetscFunctionBegin;
4173e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41744f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4175e5e524a1SHong Zhang   *t = ts->ptime_prev;
41763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4177e5e524a1SHong Zhang }
4178e5e524a1SHong Zhang 
41796a4d4014SLisandro Dalcin /*@
41806a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
41816a4d4014SLisandro Dalcin 
4182c3339decSBarry Smith   Logically Collective
41836a4d4014SLisandro Dalcin 
41846a4d4014SLisandro Dalcin   Input Parameters:
4185bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4186b43aa488SJacob Faibussowitsch - t  - the time
41876a4d4014SLisandro Dalcin 
41886a4d4014SLisandro Dalcin   Level: intermediate
41896a4d4014SLisandro Dalcin 
41901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
41916a4d4014SLisandro Dalcin @*/
4192d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4193d71ae5a4SJacob Faibussowitsch {
41946a4d4014SLisandro Dalcin   PetscFunctionBegin;
41950700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4196c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
41976a4d4014SLisandro Dalcin   ts->ptime = t;
41983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
41996a4d4014SLisandro Dalcin }
42006a4d4014SLisandro Dalcin 
4201cc4c1da9SBarry Smith /*@
4202d763cef2SBarry Smith   TSSetOptionsPrefix - Sets 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`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4219d763cef2SBarry Smith @*/
4220d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(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(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
42279566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
42289566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
42293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4230d763cef2SBarry Smith }
4231d763cef2SBarry Smith 
4232cc4c1da9SBarry Smith /*@
4233d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4234d763cef2SBarry Smith   TS options in the database.
4235d763cef2SBarry Smith 
4236c3339decSBarry Smith   Logically Collective
4237d763cef2SBarry Smith 
4238d8d19677SJose E. Roman   Input Parameters:
4239bcf0153eSBarry Smith + ts     - The `TS` context
4240d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4241d763cef2SBarry Smith 
4242bcf0153eSBarry Smith   Level: advanced
4243bcf0153eSBarry Smith 
4244bcf0153eSBarry Smith   Note:
4245d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4246d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4247d763cef2SBarry Smith   hyphen.
4248d763cef2SBarry Smith 
42491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4250d763cef2SBarry Smith @*/
4251d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4252d71ae5a4SJacob Faibussowitsch {
4253089b2837SJed Brown   SNES snes;
4254d763cef2SBarry Smith 
4255d763cef2SBarry Smith   PetscFunctionBegin;
42560700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42579566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
42589566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
42599566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
42603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4261d763cef2SBarry Smith }
4262d763cef2SBarry Smith 
4263cc4c1da9SBarry Smith /*@
4264d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4265bcf0153eSBarry Smith   `TS` options in the database.
4266d763cef2SBarry Smith 
4267d763cef2SBarry Smith   Not Collective
4268d763cef2SBarry Smith 
4269d763cef2SBarry Smith   Input Parameter:
4270bcf0153eSBarry Smith . ts - The `TS` context
4271d763cef2SBarry Smith 
4272d763cef2SBarry Smith   Output Parameter:
4273d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4274d763cef2SBarry Smith 
4275d763cef2SBarry Smith   Level: intermediate
4276d763cef2SBarry Smith 
4277b43aa488SJacob Faibussowitsch   Fortran Notes:
4278195e9b02SBarry Smith   The user should pass in a string 'prefix' of
4279bcf0153eSBarry Smith   sufficient length to hold the prefix.
4280bcf0153eSBarry Smith 
42811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4282d763cef2SBarry Smith @*/
4283d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4284d71ae5a4SJacob Faibussowitsch {
4285d763cef2SBarry Smith   PetscFunctionBegin;
42860700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42874f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
42889566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
42893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4290d763cef2SBarry Smith }
4291d763cef2SBarry Smith 
4292d763cef2SBarry Smith /*@C
4293d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4294d763cef2SBarry Smith 
4295bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4296d763cef2SBarry Smith 
4297d763cef2SBarry Smith   Input Parameter:
4298bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4299d763cef2SBarry Smith 
4300d763cef2SBarry Smith   Output Parameters:
4301195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4302195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4303195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4304195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4305d763cef2SBarry Smith 
4306d763cef2SBarry Smith   Level: intermediate
4307d763cef2SBarry Smith 
4308bcf0153eSBarry Smith   Note:
4309195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4310bcf0153eSBarry Smith 
43111cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4312d763cef2SBarry Smith 
4313d763cef2SBarry Smith @*/
43148434afd1SBarry Smith PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, void **ctx)
4315d71ae5a4SJacob Faibussowitsch {
431624989b8cSPeter Brune   DM dm;
4317089b2837SJed Brown 
4318d763cef2SBarry Smith   PetscFunctionBegin;
431923a57915SBarry Smith   if (Amat || Pmat) {
432023a57915SBarry Smith     SNES snes;
43219566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
43229566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
43239566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
432423a57915SBarry Smith   }
43259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
43269566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
43273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4328d763cef2SBarry Smith }
4329d763cef2SBarry Smith 
43302eca1d9cSJed Brown /*@C
43312eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
43322eca1d9cSJed Brown 
4333bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
43342eca1d9cSJed Brown 
43352eca1d9cSJed Brown   Input Parameter:
4336bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
43372eca1d9cSJed Brown 
43382eca1d9cSJed Brown   Output Parameters:
4339e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4340195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
43412eca1d9cSJed Brown . f    - The function to compute the matrices
43422eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
43432eca1d9cSJed Brown 
43442eca1d9cSJed Brown   Level: advanced
43452eca1d9cSJed Brown 
4346bcf0153eSBarry Smith   Note:
4347195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4348bcf0153eSBarry Smith 
43491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
43502eca1d9cSJed Brown @*/
43518434afd1SBarry Smith PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, void **ctx)
4352d71ae5a4SJacob Faibussowitsch {
435324989b8cSPeter Brune   DM dm;
43540910c330SBarry Smith 
43552eca1d9cSJed Brown   PetscFunctionBegin;
4356c0aab802Sstefano_zampini   if (Amat || Pmat) {
4357c0aab802Sstefano_zampini     SNES snes;
43589566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
43599566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
43609566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4361c0aab802Sstefano_zampini   }
43629566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
43639566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
43643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43652eca1d9cSJed Brown }
43662eca1d9cSJed Brown 
4367af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
43686c699258SBarry Smith /*@
4369bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
43706c699258SBarry Smith 
4371c3339decSBarry Smith   Logically Collective
43726c699258SBarry Smith 
43736c699258SBarry Smith   Input Parameters:
4374bcf0153eSBarry Smith + ts - the `TS` integrator object
4375195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
43766c699258SBarry Smith 
43776c699258SBarry Smith   Level: intermediate
43786c699258SBarry Smith 
4379bcf0153eSBarry Smith   Notes:
4380bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4381bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4382bcf0153eSBarry Smith   different problems using the same function space.
4383bcf0153eSBarry Smith 
43841cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
43856c699258SBarry Smith @*/
4386d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4387d71ae5a4SJacob Faibussowitsch {
4388089b2837SJed Brown   SNES snes;
4389942e3340SBarry Smith   DMTS tsdm;
43906c699258SBarry Smith 
43916c699258SBarry Smith   PetscFunctionBegin;
43920700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43932a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
43949566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4395942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
43962a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
43979566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
43989566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
43991e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
44001e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
440124989b8cSPeter Brune     }
44029566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
440324989b8cSPeter Brune   }
44046c699258SBarry Smith   ts->dm = dm;
4405bbd56ea5SKarl Rupp 
44069566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
44079566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
44083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44096c699258SBarry Smith }
44106c699258SBarry Smith 
44116c699258SBarry Smith /*@
4412bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
44136c699258SBarry Smith 
44143f9fe445SBarry Smith   Not Collective
44156c699258SBarry Smith 
44166c699258SBarry Smith   Input Parameter:
4417bcf0153eSBarry Smith . ts - the `TS`
44186c699258SBarry Smith 
44196c699258SBarry Smith   Output Parameter:
4420195e9b02SBarry Smith . dm - the `DM`
44216c699258SBarry Smith 
44226c699258SBarry Smith   Level: intermediate
44236c699258SBarry Smith 
44241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
44256c699258SBarry Smith @*/
4426d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4427d71ae5a4SJacob Faibussowitsch {
44286c699258SBarry Smith   PetscFunctionBegin;
44290700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4430496e6a7aSJed Brown   if (!ts->dm) {
44319566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
44324bd3aaa3SHong Zhang     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4433496e6a7aSJed Brown   }
44346c699258SBarry Smith   *dm = ts->dm;
44353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44366c699258SBarry Smith }
44371713a123SBarry Smith 
44380f5c6efeSJed Brown /*@
44390f5c6efeSJed Brown   SNESTSFormFunction - Function to evaluate nonlinear residual
44400f5c6efeSJed Brown 
4441c3339decSBarry Smith   Logically Collective
44420f5c6efeSJed Brown 
4443d8d19677SJose E. Roman   Input Parameters:
4444d42a1c89SJed Brown + snes - nonlinear solver
44450910c330SBarry Smith . U    - the current state at which to evaluate the residual
4446d42a1c89SJed Brown - ctx  - user context, must be a TS
44470f5c6efeSJed Brown 
44480f5c6efeSJed Brown   Output Parameter:
44490f5c6efeSJed Brown . F - the nonlinear residual
44500f5c6efeSJed Brown 
44510f5c6efeSJed Brown   Level: advanced
44520f5c6efeSJed Brown 
4453bcf0153eSBarry Smith   Note:
4454bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4455bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4456bcf0153eSBarry Smith 
44571cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
44580f5c6efeSJed Brown @*/
4459d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4460d71ae5a4SJacob Faibussowitsch {
44610f5c6efeSJed Brown   TS ts = (TS)ctx;
44620f5c6efeSJed Brown 
44630f5c6efeSJed Brown   PetscFunctionBegin;
44640f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
44650910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
44660f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
44670f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
4468346ce620SStefano Zampini   PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4469346ce620SStefano Zampini   PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
44703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44710f5c6efeSJed Brown }
44720f5c6efeSJed Brown 
44730f5c6efeSJed Brown /*@
44740f5c6efeSJed Brown   SNESTSFormJacobian - Function to evaluate the Jacobian
44750f5c6efeSJed Brown 
4476c3339decSBarry Smith   Collective
44770f5c6efeSJed Brown 
4478d8d19677SJose E. Roman   Input Parameters:
44790f5c6efeSJed Brown + snes - nonlinear solver
44800910c330SBarry Smith . U    - the current state at which to evaluate the residual
4481bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
44820f5c6efeSJed Brown 
4483d8d19677SJose E. Roman   Output Parameters:
44840f5c6efeSJed Brown + A - the Jacobian
44856b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
44860f5c6efeSJed Brown 
44870f5c6efeSJed Brown   Level: developer
44880f5c6efeSJed Brown 
4489bcf0153eSBarry Smith   Note:
4490bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4491bcf0153eSBarry Smith 
44921cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
44930f5c6efeSJed Brown @*/
4494d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4495d71ae5a4SJacob Faibussowitsch {
44960f5c6efeSJed Brown   TS ts = (TS)ctx;
44970f5c6efeSJed Brown 
44980f5c6efeSJed Brown   PetscFunctionBegin;
44990f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
45000910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
450194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
450294ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4503064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
4504346ce620SStefano Zampini   PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4505346ce620SStefano Zampini   PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
45063ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45070f5c6efeSJed Brown }
4508325fc9f4SBarry Smith 
45090e4ef248SJed Brown /*@C
4510dd8e379bSPierre Jolivet   TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
45110e4ef248SJed Brown 
4512c3339decSBarry Smith   Collective
45130e4ef248SJed Brown 
45144165533cSJose E. Roman   Input Parameters:
45150e4ef248SJed Brown + ts  - time stepping context
45160e4ef248SJed Brown . t   - time at which to evaluate
45170910c330SBarry Smith . U   - state at which to evaluate
45180e4ef248SJed Brown - ctx - context
45190e4ef248SJed Brown 
45204165533cSJose E. Roman   Output Parameter:
4521dd8e379bSPierre Jolivet . F - right-hand side
45220e4ef248SJed Brown 
45230e4ef248SJed Brown   Level: intermediate
45240e4ef248SJed Brown 
4525bcf0153eSBarry Smith   Note:
4526dd8e379bSPierre Jolivet   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4527bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
45280e4ef248SJed Brown 
45291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
45300e4ef248SJed Brown @*/
4531d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4532d71ae5a4SJacob Faibussowitsch {
45330e4ef248SJed Brown   Mat Arhs, Brhs;
45340e4ef248SJed Brown 
45350e4ef248SJed Brown   PetscFunctionBegin;
45369566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
45372663174eSHong Zhang   /* undo the damage caused by shifting */
45389566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
45399566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
45409566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
45413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45420e4ef248SJed Brown }
45430e4ef248SJed Brown 
45440e4ef248SJed Brown /*@C
45450e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
45460e4ef248SJed Brown 
4547c3339decSBarry Smith   Collective
45480e4ef248SJed Brown 
45494165533cSJose E. Roman   Input Parameters:
45500e4ef248SJed Brown + ts  - time stepping context
45510e4ef248SJed Brown . t   - time at which to evaluate
45520910c330SBarry Smith . U   - state at which to evaluate
45530e4ef248SJed Brown - ctx - context
45540e4ef248SJed Brown 
45554165533cSJose E. Roman   Output Parameters:
45560e4ef248SJed Brown + A - pointer to operator
455797bb3fdcSJose E. Roman - B - pointer to preconditioning matrix
45580e4ef248SJed Brown 
45590e4ef248SJed Brown   Level: intermediate
45600e4ef248SJed Brown 
4561bcf0153eSBarry Smith   Note:
4562bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
45630e4ef248SJed Brown 
45641cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
45650e4ef248SJed Brown @*/
4566d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4567d71ae5a4SJacob Faibussowitsch {
45680e4ef248SJed Brown   PetscFunctionBegin;
45693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45700e4ef248SJed Brown }
45710e4ef248SJed Brown 
45720026cea9SSean Farley /*@C
45730026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
45740026cea9SSean Farley 
4575c3339decSBarry Smith   Collective
45760026cea9SSean Farley 
45774165533cSJose E. Roman   Input Parameters:
45780026cea9SSean Farley + ts   - time stepping context
45790026cea9SSean Farley . t    - time at which to evaluate
45800910c330SBarry Smith . U    - state at which to evaluate
45810910c330SBarry Smith . Udot - time derivative of state vector
45820026cea9SSean Farley - ctx  - context
45830026cea9SSean Farley 
45844165533cSJose E. Roman   Output Parameter:
45850026cea9SSean Farley . F - left hand side
45860026cea9SSean Farley 
45870026cea9SSean Farley   Level: intermediate
45880026cea9SSean Farley 
45890026cea9SSean Farley   Notes:
45900910c330SBarry 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
4591bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4592bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4593bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
45940026cea9SSean Farley 
4595bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
45969ae8fd06SBarry Smith 
45971cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
45980026cea9SSean Farley @*/
4599d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4600d71ae5a4SJacob Faibussowitsch {
46010026cea9SSean Farley   Mat A, B;
46020026cea9SSean Farley 
46030026cea9SSean Farley   PetscFunctionBegin;
46049566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
46059566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
46069566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
46073ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46080026cea9SSean Farley }
46090026cea9SSean Farley 
46100026cea9SSean Farley /*@C
46118434afd1SBarry Smith   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
46120026cea9SSean Farley 
4613c3339decSBarry Smith   Collective
46140026cea9SSean Farley 
46154165533cSJose E. Roman   Input Parameters:
46160026cea9SSean Farley + ts    - time stepping context
46170026cea9SSean Farley . t     - time at which to evaluate
46180910c330SBarry Smith . U     - state at which to evaluate
46190910c330SBarry Smith . Udot  - time derivative of state vector
46200026cea9SSean Farley . shift - shift to apply
46210026cea9SSean Farley - ctx   - context
46220026cea9SSean Farley 
46234165533cSJose E. Roman   Output Parameters:
46240026cea9SSean Farley + A - pointer to operator
4625d1c5d1fcSBarry Smith - B - pointer to matrix from which the preconditioner is built (often `A`)
46260026cea9SSean Farley 
4627b41af12eSJed Brown   Level: advanced
46280026cea9SSean Farley 
46290026cea9SSean Farley   Notes:
4630bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
46310026cea9SSean Farley 
4632b41af12eSJed Brown   It is only appropriate for problems of the form
4633b41af12eSJed Brown 
4634d1c5d1fcSBarry Smith   $$
4635d1c5d1fcSBarry Smith   M \dot{U} = F(U,t)
4636d1c5d1fcSBarry Smith   $$
4637b41af12eSJed Brown 
4638bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4639bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4640b41af12eSJed Brown   an implicit operator of the form
4641b41af12eSJed Brown 
4642d1c5d1fcSBarry Smith   $$
4643d1c5d1fcSBarry Smith   shift*M + J
4644d1c5d1fcSBarry Smith   $$
4645b41af12eSJed Brown 
4646b41af12eSJed 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
4647b41af12eSJed Brown   a copy of M or reassemble it when requested.
4648b41af12eSJed Brown 
46491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
46500026cea9SSean Farley @*/
4651d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4652d71ae5a4SJacob Faibussowitsch {
46530026cea9SSean Farley   PetscFunctionBegin;
46549566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4655b41af12eSJed Brown   ts->ijacobian.shift = shift;
46563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46570026cea9SSean Farley }
4658b41af12eSJed Brown 
4659e817cc15SEmil Constantinescu /*@
4660bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4661e817cc15SEmil Constantinescu 
4662e817cc15SEmil Constantinescu   Not Collective
4663e817cc15SEmil Constantinescu 
4664e817cc15SEmil Constantinescu   Input Parameter:
4665bcf0153eSBarry Smith . ts - the `TS` context
4666e817cc15SEmil Constantinescu 
4667e817cc15SEmil Constantinescu   Output Parameter:
4668bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4669e817cc15SEmil Constantinescu 
4670e817cc15SEmil Constantinescu   Level: beginner
4671e817cc15SEmil Constantinescu 
46721cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4673e817cc15SEmil Constantinescu @*/
4674d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4675d71ae5a4SJacob Faibussowitsch {
4676e817cc15SEmil Constantinescu   PetscFunctionBegin;
4677e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46784f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4679e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
46803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4681e817cc15SEmil Constantinescu }
4682e817cc15SEmil Constantinescu 
4683e817cc15SEmil Constantinescu /*@
4684bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4685e817cc15SEmil Constantinescu 
4686e817cc15SEmil Constantinescu   Not Collective
4687e817cc15SEmil Constantinescu 
4688d8d19677SJose E. Roman   Input Parameters:
4689bcf0153eSBarry Smith + ts            - the `TS` context
4690bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4691e817cc15SEmil Constantinescu 
4692e817cc15SEmil Constantinescu   Level: advanced
4693e817cc15SEmil Constantinescu 
46941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4695e817cc15SEmil Constantinescu @*/
4696d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4697d71ae5a4SJacob Faibussowitsch {
4698e817cc15SEmil Constantinescu   PetscFunctionBegin;
4699e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4700e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
47013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4702e817cc15SEmil Constantinescu }
47030026cea9SSean Farley 
47044af1b03aSJed Brown /*@
4705bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
47064af1b03aSJed Brown 
47074af1b03aSJed Brown   Not Collective
47084af1b03aSJed Brown 
47094af1b03aSJed Brown   Input Parameter:
4710bcf0153eSBarry Smith . ts - the `TS` context
47114af1b03aSJed Brown 
47124af1b03aSJed Brown   Output Parameter:
4713bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
47144af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
47154af1b03aSJed Brown 
4716487e0bb9SJed Brown   Level: beginner
47174af1b03aSJed Brown 
4718bcf0153eSBarry Smith   Note:
4719bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
47204af1b03aSJed Brown 
47217d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
47224af1b03aSJed Brown @*/
4723d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4724d71ae5a4SJacob Faibussowitsch {
47254af1b03aSJed Brown   PetscFunctionBegin;
47264af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47274f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
47284af1b03aSJed Brown   *reason = ts->reason;
47293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47304af1b03aSJed Brown }
47314af1b03aSJed Brown 
4732d6ad946cSShri Abhyankar /*@
4733bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4734d6ad946cSShri Abhyankar 
47356b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4736d6ad946cSShri Abhyankar 
47376b221cbeSPatrick Sanan   Input Parameters:
4738bcf0153eSBarry Smith + ts     - the `TS` context
4739bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4740d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4741d6ad946cSShri Abhyankar 
4742f5abba47SShri Abhyankar   Level: advanced
4743d6ad946cSShri Abhyankar 
4744bcf0153eSBarry Smith   Note:
4745bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4746d6ad946cSShri Abhyankar 
47471cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4748d6ad946cSShri Abhyankar @*/
4749d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4750d71ae5a4SJacob Faibussowitsch {
4751d6ad946cSShri Abhyankar   PetscFunctionBegin;
4752d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4753d6ad946cSShri Abhyankar   ts->reason = reason;
47543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4755d6ad946cSShri Abhyankar }
4756d6ad946cSShri Abhyankar 
4757cc708dedSBarry Smith /*@
4758bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4759cc708dedSBarry Smith 
4760cc708dedSBarry Smith   Not Collective
4761cc708dedSBarry Smith 
4762cc708dedSBarry Smith   Input Parameter:
4763bcf0153eSBarry Smith . ts - the `TS` context
4764cc708dedSBarry Smith 
4765cc708dedSBarry Smith   Output Parameter:
4766bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4767cc708dedSBarry Smith 
4768487e0bb9SJed Brown   Level: beginner
4769cc708dedSBarry Smith 
4770bcf0153eSBarry Smith   Note:
4771bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4772cc708dedSBarry Smith 
47737d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4774cc708dedSBarry Smith @*/
4775d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4776d71ae5a4SJacob Faibussowitsch {
4777cc708dedSBarry Smith   PetscFunctionBegin;
4778cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47794f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4780cc708dedSBarry Smith   *ftime = ts->solvetime;
47813ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4782cc708dedSBarry Smith }
4783cc708dedSBarry Smith 
47842c18e0fdSBarry Smith /*@
47855ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
47869f67acb7SJed Brown   used by the time integrator.
47879f67acb7SJed Brown 
47889f67acb7SJed Brown   Not Collective
47899f67acb7SJed Brown 
47909f67acb7SJed Brown   Input Parameter:
4791bcf0153eSBarry Smith . ts - `TS` context
47929f67acb7SJed Brown 
47939f67acb7SJed Brown   Output Parameter:
47949f67acb7SJed Brown . nits - number of nonlinear iterations
47959f67acb7SJed Brown 
47969f67acb7SJed Brown   Level: intermediate
47979f67acb7SJed Brown 
4798195e9b02SBarry Smith   Note:
4799bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4800bcf0153eSBarry Smith 
48011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
48029f67acb7SJed Brown @*/
4803d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4804d71ae5a4SJacob Faibussowitsch {
48059f67acb7SJed Brown   PetscFunctionBegin;
48069f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48074f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
48085ef26d82SJed Brown   *nits = ts->snes_its;
48093ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48109f67acb7SJed Brown }
48119f67acb7SJed Brown 
48129f67acb7SJed Brown /*@
48135ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
48149f67acb7SJed Brown   used by the time integrator.
48159f67acb7SJed Brown 
48169f67acb7SJed Brown   Not Collective
48179f67acb7SJed Brown 
48189f67acb7SJed Brown   Input Parameter:
4819bcf0153eSBarry Smith . ts - `TS` context
48209f67acb7SJed Brown 
48219f67acb7SJed Brown   Output Parameter:
48229f67acb7SJed Brown . lits - number of linear iterations
48239f67acb7SJed Brown 
48249f67acb7SJed Brown   Level: intermediate
48259f67acb7SJed Brown 
4826bcf0153eSBarry Smith   Note:
4827bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4828bcf0153eSBarry Smith 
48291cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
48309f67acb7SJed Brown @*/
4831d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4832d71ae5a4SJacob Faibussowitsch {
48339f67acb7SJed Brown   PetscFunctionBegin;
48349f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48354f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
48365ef26d82SJed Brown   *lits = ts->ksp_its;
48373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48389f67acb7SJed Brown }
48399f67acb7SJed Brown 
4840cef5090cSJed Brown /*@
4841cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4842cef5090cSJed Brown 
4843cef5090cSJed Brown   Not Collective
4844cef5090cSJed Brown 
4845cef5090cSJed Brown   Input Parameter:
4846bcf0153eSBarry Smith . ts - `TS` context
4847cef5090cSJed Brown 
4848cef5090cSJed Brown   Output Parameter:
4849cef5090cSJed Brown . rejects - number of steps rejected
4850cef5090cSJed Brown 
4851cef5090cSJed Brown   Level: intermediate
4852cef5090cSJed Brown 
4853bcf0153eSBarry Smith   Note:
4854bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4855bcf0153eSBarry Smith 
48561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4857cef5090cSJed Brown @*/
4858d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4859d71ae5a4SJacob Faibussowitsch {
4860cef5090cSJed Brown   PetscFunctionBegin;
4861cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48624f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4863cef5090cSJed Brown   *rejects = ts->reject;
48643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4865cef5090cSJed Brown }
4866cef5090cSJed Brown 
4867cef5090cSJed Brown /*@
4868bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4869cef5090cSJed Brown 
4870cef5090cSJed Brown   Not Collective
4871cef5090cSJed Brown 
4872cef5090cSJed Brown   Input Parameter:
4873bcf0153eSBarry Smith . ts - `TS` context
4874cef5090cSJed Brown 
4875cef5090cSJed Brown   Output Parameter:
4876cef5090cSJed Brown . fails - number of failed nonlinear solves
4877cef5090cSJed Brown 
4878cef5090cSJed Brown   Level: intermediate
4879cef5090cSJed Brown 
4880bcf0153eSBarry Smith   Note:
4881bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4882bcf0153eSBarry Smith 
48831cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4884cef5090cSJed Brown @*/
4885d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4886d71ae5a4SJacob Faibussowitsch {
4887cef5090cSJed Brown   PetscFunctionBegin;
4888cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48894f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
4890cef5090cSJed Brown   *fails = ts->num_snes_failures;
48913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4892cef5090cSJed Brown }
4893cef5090cSJed Brown 
4894cef5090cSJed Brown /*@
4895bcf0153eSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4896cef5090cSJed Brown 
4897cef5090cSJed Brown   Not Collective
4898cef5090cSJed Brown 
4899d8d19677SJose E. Roman   Input Parameters:
4900bcf0153eSBarry Smith + ts      - `TS` context
490109cb0f53SBarry Smith - rejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
4902cef5090cSJed Brown 
4903cef5090cSJed Brown   Options Database Key:
4904cef5090cSJed Brown . -ts_max_reject - Maximum number of step rejections before a step fails
4905cef5090cSJed Brown 
4906cef5090cSJed Brown   Level: intermediate
4907cef5090cSJed Brown 
490809cb0f53SBarry Smith   Developer Note:
490909cb0f53SBarry Smith   The options database name is incorrect.
491009cb0f53SBarry Smith 
49111cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4912cef5090cSJed Brown @*/
4913d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4914d71ae5a4SJacob Faibussowitsch {
4915cef5090cSJed Brown   PetscFunctionBegin;
4916cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
491709cb0f53SBarry Smith   if (rejects == PETSC_UNLIMITED || rejects == -1) {
491809cb0f53SBarry Smith     ts->max_reject = PETSC_UNLIMITED;
491909cb0f53SBarry Smith   } else {
492009cb0f53SBarry Smith     PetscCheck(rejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
4921cef5090cSJed Brown     ts->max_reject = rejects;
492209cb0f53SBarry Smith   }
49233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4924cef5090cSJed Brown }
4925cef5090cSJed Brown 
4926cef5090cSJed Brown /*@
4927bcf0153eSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4928cef5090cSJed Brown 
4929cef5090cSJed Brown   Not Collective
4930cef5090cSJed Brown 
4931d8d19677SJose E. Roman   Input Parameters:
4932bcf0153eSBarry Smith + ts    - `TS` context
493309cb0f53SBarry Smith - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
4934cef5090cSJed Brown 
4935cef5090cSJed Brown   Options Database Key:
4936cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
4937cef5090cSJed Brown 
4938cef5090cSJed Brown   Level: intermediate
4939cef5090cSJed Brown 
49401cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4941cef5090cSJed Brown @*/
4942d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4943d71ae5a4SJacob Faibussowitsch {
4944cef5090cSJed Brown   PetscFunctionBegin;
4945cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
494609cb0f53SBarry Smith   if (fails == PETSC_UNLIMITED || fails == -1) {
494709cb0f53SBarry Smith     ts->max_snes_failures = PETSC_UNLIMITED;
494809cb0f53SBarry Smith   } else {
494909cb0f53SBarry Smith     PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
4950cef5090cSJed Brown     ts->max_snes_failures = fails;
495109cb0f53SBarry Smith   }
49523ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4953cef5090cSJed Brown }
4954cef5090cSJed Brown 
4955cef5090cSJed Brown /*@
4956195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
4957cef5090cSJed Brown 
4958cef5090cSJed Brown   Not Collective
4959cef5090cSJed Brown 
4960d8d19677SJose E. Roman   Input Parameters:
4961bcf0153eSBarry Smith + ts  - `TS` context
4962bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4963cef5090cSJed Brown 
4964cef5090cSJed Brown   Options Database Key:
4965cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
4966cef5090cSJed Brown 
4967cef5090cSJed Brown   Level: intermediate
4968cef5090cSJed Brown 
496942747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
4970cef5090cSJed Brown @*/
4971d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4972d71ae5a4SJacob Faibussowitsch {
4973cef5090cSJed Brown   PetscFunctionBegin;
4974cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4975cef5090cSJed Brown   ts->errorifstepfailed = err;
49763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4977cef5090cSJed Brown }
4978cef5090cSJed Brown 
497984df9cb4SJed Brown /*@
4980552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
498184df9cb4SJed Brown 
49828f14a041SBarry Smith   Collective if controller has not yet been created
498384df9cb4SJed Brown 
49844165533cSJose E. Roman   Input Parameter:
4985ed81e22dSJed Brown . ts - time stepping context
498684df9cb4SJed Brown 
49874165533cSJose E. Roman   Output Parameter:
4988ed81e22dSJed Brown . adapt - adaptive controller
498984df9cb4SJed Brown 
499084df9cb4SJed Brown   Level: intermediate
499184df9cb4SJed Brown 
49921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
499384df9cb4SJed Brown @*/
4994d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4995d71ae5a4SJacob Faibussowitsch {
499684df9cb4SJed Brown   PetscFunctionBegin;
499784df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49984f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
499984df9cb4SJed Brown   if (!ts->adapt) {
50009566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
50019566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
500284df9cb4SJed Brown   }
5003bec58848SLisandro Dalcin   *adapt = ts->adapt;
50043ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
500584df9cb4SJed Brown }
5006d6ebe24aSShri Abhyankar 
50071c3436cfSJed Brown /*@
5008195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
50091c3436cfSJed Brown 
50101c3436cfSJed Brown   Logically Collective
50111c3436cfSJed Brown 
50124165533cSJose E. Roman   Input Parameters:
50131c3436cfSJed Brown + ts    - time integration context
501409cb0f53SBarry Smith . atol  - scalar absolute tolerances
501509cb0f53SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
501609cb0f53SBarry Smith . rtol  - scalar relative tolerances
501709cb0f53SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
50181c3436cfSJed Brown 
5019195e9b02SBarry Smith   Options Database Keys:
5020a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
502167b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
5022a3cdaa26SBarry Smith 
5023bcf0153eSBarry Smith   Level: beginner
5024bcf0153eSBarry Smith 
50253ff766beSShri Abhyankar   Notes:
502609cb0f53SBarry Smith   `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
502709cb0f53SBarry Smith   or the default value from when the object's type was set.
502809cb0f53SBarry Smith 
50293ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
50303ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
50313ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
50323ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
50333ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
50343ff766beSShri Abhyankar   differential variables.
50353ff766beSShri Abhyankar 
503609cb0f53SBarry Smith   Fortran Note:
503709cb0f53SBarry Smith   Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
503809cb0f53SBarry Smith 
50391cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
50401c3436cfSJed Brown @*/
5041d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5042d71ae5a4SJacob Faibussowitsch {
50431c3436cfSJed Brown   PetscFunctionBegin;
504409cb0f53SBarry Smith   if (atol == (PetscReal)PETSC_DETERMINE) {
5045dd460d27SBarry Smith     ts->atol = ts->default_atol;
504609cb0f53SBarry Smith   } else if (atol != (PetscReal)PETSC_CURRENT) {
504709cb0f53SBarry Smith     PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
504809cb0f53SBarry Smith     ts->atol = atol;
504909cb0f53SBarry Smith   }
505009cb0f53SBarry Smith 
50511c3436cfSJed Brown   if (vatol) {
50529566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
50539566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
50541c3436cfSJed Brown     ts->vatol = vatol;
50551c3436cfSJed Brown   }
505609cb0f53SBarry Smith 
505709cb0f53SBarry Smith   if (rtol == (PetscReal)PETSC_DETERMINE) {
5058dd460d27SBarry Smith     ts->rtol = ts->default_rtol;
505909cb0f53SBarry Smith   } else if (rtol != (PetscReal)PETSC_CURRENT) {
506009cb0f53SBarry Smith     PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
506109cb0f53SBarry Smith     ts->rtol = rtol;
506209cb0f53SBarry Smith   }
506309cb0f53SBarry Smith 
50641c3436cfSJed Brown   if (vrtol) {
50659566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
50669566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
50671c3436cfSJed Brown     ts->vrtol = vrtol;
50681c3436cfSJed Brown   }
50693ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
50701c3436cfSJed Brown }
50711c3436cfSJed Brown 
5072c5033834SJed Brown /*@
5073c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5074c5033834SJed Brown 
5075c5033834SJed Brown   Logically Collective
5076c5033834SJed Brown 
50774165533cSJose E. Roman   Input Parameter:
5078c5033834SJed Brown . ts - time integration context
5079c5033834SJed Brown 
50804165533cSJose E. Roman   Output Parameters:
5081195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
5082195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
5083195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
5084195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
5085c5033834SJed Brown 
5086c5033834SJed Brown   Level: beginner
5087c5033834SJed Brown 
50881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5089c5033834SJed Brown @*/
5090d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5091d71ae5a4SJacob Faibussowitsch {
5092c5033834SJed Brown   PetscFunctionBegin;
5093c5033834SJed Brown   if (atol) *atol = ts->atol;
5094c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
5095c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
5096c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
50973ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5098c5033834SJed Brown }
5099c5033834SJed Brown 
51009c6b16b5SShri Abhyankar /*@
51018a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51021c3436cfSJed Brown 
5103c3339decSBarry Smith   Collective
51041c3436cfSJed Brown 
51054165533cSJose E. Roman   Input Parameters:
51061c3436cfSJed Brown + ts        - time stepping context
5107a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5108a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5109bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51107619abb3SShri 
51114165533cSJose E. Roman   Output Parameters:
5112a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51138a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5114a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5115a4868fbcSLisandro Dalcin 
5116bcf0153eSBarry Smith   Options Database Key:
5117a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5118a4868fbcSLisandro Dalcin 
51191c3436cfSJed Brown   Level: developer
51201c3436cfSJed Brown 
51218c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
51221c3436cfSJed Brown @*/
5123d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5124d71ae5a4SJacob Faibussowitsch {
5125037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
51268a175baeSEmil Constantinescu 
51278a175baeSEmil Constantinescu   PetscFunctionBegin;
51288a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5129037d63e4SStefano 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));
5130037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5131037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5132037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5133037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
51348a175baeSEmil Constantinescu   }
51353c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
51363c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
51373c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51398a175baeSEmil Constantinescu }
51408a175baeSEmil Constantinescu 
51418a175baeSEmil Constantinescu /*@
51428a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
51438a175baeSEmil Constantinescu 
5144c3339decSBarry Smith   Collective
51458a175baeSEmil Constantinescu 
51464165533cSJose E. Roman   Input Parameters:
51478a175baeSEmil Constantinescu + ts        - time stepping context
51488a175baeSEmil Constantinescu . E         - error vector
51498a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
51508a175baeSEmil Constantinescu . Y         - state vector, previous time step
5151bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51528a175baeSEmil Constantinescu 
51534165533cSJose E. Roman   Output Parameters:
5154a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51558a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5156a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
51578a175baeSEmil Constantinescu 
5158bcf0153eSBarry Smith   Options Database Key:
51598a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
51608a175baeSEmil Constantinescu 
51618a175baeSEmil Constantinescu   Level: developer
51628a175baeSEmil Constantinescu 
51638c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
51648a175baeSEmil Constantinescu @*/
5165d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5166d71ae5a4SJacob Faibussowitsch {
5167037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5168037d63e4SStefano Zampini 
51698a175baeSEmil Constantinescu   PetscFunctionBegin;
5170037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5171037d63e4SStefano 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));
5172037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5173037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5174037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5175037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5176037d63e4SStefano Zampini   }
5177037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5178037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5179037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
51803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51818a175baeSEmil Constantinescu }
51828a175baeSEmil Constantinescu 
51838d59e960SJed Brown /*@
51848d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
51858d59e960SJed Brown 
5186c3339decSBarry Smith   Logically Collective
51878d59e960SJed Brown 
51884165533cSJose E. Roman   Input Parameters:
51898d59e960SJed Brown + ts      - time stepping context
51908d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
51918d59e960SJed Brown 
51928d59e960SJed Brown   Note:
51938d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
51948d59e960SJed Brown 
51958d59e960SJed Brown   Level: intermediate
51968d59e960SJed Brown 
51971cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
51988d59e960SJed Brown @*/
5199d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5200d71ae5a4SJacob Faibussowitsch {
52018d59e960SJed Brown   PetscFunctionBegin;
52028d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
52038d59e960SJed Brown   ts->cfltime_local = cfltime;
52048d59e960SJed Brown   ts->cfltime       = -1.;
52053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52068d59e960SJed Brown }
52078d59e960SJed Brown 
52088d59e960SJed Brown /*@
52098d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
52108d59e960SJed Brown 
5211c3339decSBarry Smith   Collective
52128d59e960SJed Brown 
52134165533cSJose E. Roman   Input Parameter:
52148d59e960SJed Brown . ts - time stepping context
52158d59e960SJed Brown 
52164165533cSJose E. Roman   Output Parameter:
52178d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
52188d59e960SJed Brown 
52198d59e960SJed Brown   Level: advanced
52208d59e960SJed Brown 
52211cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
52228d59e960SJed Brown @*/
5223d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5224d71ae5a4SJacob Faibussowitsch {
52258d59e960SJed Brown   PetscFunctionBegin;
5226462c564dSBarry Smith   if (ts->cfltime < 0) PetscCallMPI(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
52278d59e960SJed Brown   *cfltime = ts->cfltime;
52283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52298d59e960SJed Brown }
52308d59e960SJed Brown 
5231d6ebe24aSShri Abhyankar /*@
5232d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5233d6ebe24aSShri Abhyankar 
5234d6ebe24aSShri Abhyankar   Input Parameters:
5235bcf0153eSBarry Smith + ts - the `TS` context.
5236d6ebe24aSShri Abhyankar . xl - lower bound.
5237a2b725a8SWilliam Gropp - xu - upper bound.
5238d6ebe24aSShri Abhyankar 
52392bd2b0e6SSatish Balay   Level: advanced
52402bd2b0e6SSatish Balay 
5241bcf0153eSBarry Smith   Note:
5242bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5243bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5244bcf0153eSBarry Smith 
52451cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5246d6ebe24aSShri Abhyankar @*/
5247d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5248d71ae5a4SJacob Faibussowitsch {
5249d6ebe24aSShri Abhyankar   SNES snes;
5250d6ebe24aSShri Abhyankar 
5251d6ebe24aSShri Abhyankar   PetscFunctionBegin;
52529566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
52539566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
52543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5255d6ebe24aSShri Abhyankar }
5256d6ebe24aSShri Abhyankar 
5257f9c1d6abSBarry Smith /*@
5258f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5259f9c1d6abSBarry Smith 
5260c3339decSBarry Smith   Collective
5261f9c1d6abSBarry Smith 
5262f9c1d6abSBarry Smith   Input Parameters:
5263bcf0153eSBarry Smith + ts - the `TS` context
52642fe279fdSBarry Smith . xr - real part of input argument
52652fe279fdSBarry Smith - xi - imaginary part of input argument
5266f9c1d6abSBarry Smith 
5267f9c1d6abSBarry Smith   Output Parameters:
52682fe279fdSBarry Smith + yr - real part of function value
52692fe279fdSBarry Smith - yi - imaginary part of function value
5270f9c1d6abSBarry Smith 
5271f9c1d6abSBarry Smith   Level: developer
5272f9c1d6abSBarry Smith 
52731cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5274f9c1d6abSBarry Smith @*/
5275d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5276d71ae5a4SJacob Faibussowitsch {
5277f9c1d6abSBarry Smith   PetscFunctionBegin;
5278f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5279dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
52803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5281f9c1d6abSBarry Smith }
528224655328SShri 
528324655328SShri /*@
5284dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5285dcb233daSLisandro Dalcin 
5286c3339decSBarry Smith   Collective
5287dcb233daSLisandro Dalcin 
5288dcb233daSLisandro Dalcin   Input Parameter:
5289bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5290dcb233daSLisandro Dalcin 
5291dcb233daSLisandro Dalcin   Level: advanced
5292dcb233daSLisandro Dalcin 
5293dcb233daSLisandro Dalcin   Notes:
5294bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5295dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5296dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5297bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5298dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5299dcb233daSLisandro Dalcin   discontinuous source terms).
5300dcb233daSLisandro Dalcin 
53011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5302dcb233daSLisandro Dalcin @*/
5303d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5304d71ae5a4SJacob Faibussowitsch {
5305dcb233daSLisandro Dalcin   PetscFunctionBegin;
5306dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5307dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
53083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5309dcb233daSLisandro Dalcin }
5310dcb233daSLisandro Dalcin 
5311dcb233daSLisandro Dalcin /*@
531224655328SShri   TSRollBack - Rolls back one time step
531324655328SShri 
5314c3339decSBarry Smith   Collective
531524655328SShri 
531624655328SShri   Input Parameter:
5317bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
531824655328SShri 
531924655328SShri   Level: advanced
532024655328SShri 
53219dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
532224655328SShri @*/
5323d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5324d71ae5a4SJacob Faibussowitsch {
532524655328SShri   PetscFunctionBegin;
532624655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53273c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5328c61711c8SStefano Zampini   PetscTryTypeMethod(ts, rollback);
5329c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
533024655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
533124655328SShri   ts->ptime      = ts->ptime_prev;
5332be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
53332808aa04SLisandro Dalcin   ts->steps--;
5334b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
53353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
533624655328SShri }
5337aeb4809dSShri Abhyankar 
5338ff22ae23SHong Zhang /*@
53399dc50cb5SStefano Zampini   TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
53409dc50cb5SStefano Zampini 
53419dc50cb5SStefano Zampini   Not collective
53429dc50cb5SStefano Zampini 
53439dc50cb5SStefano Zampini   Input Parameter:
53449dc50cb5SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
53459dc50cb5SStefano Zampini 
53469dc50cb5SStefano Zampini   Output Parameter:
53479dc50cb5SStefano Zampini . flg - the rollback flag
53489dc50cb5SStefano Zampini 
53499dc50cb5SStefano Zampini   Level: advanced
53509dc50cb5SStefano Zampini 
53519dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
53529dc50cb5SStefano Zampini @*/
53539dc50cb5SStefano Zampini PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
53549dc50cb5SStefano Zampini {
53559dc50cb5SStefano Zampini   PetscFunctionBegin;
53569dc50cb5SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53579dc50cb5SStefano Zampini   PetscAssertPointer(flg, 2);
53589dc50cb5SStefano Zampini   *flg = ts->steprollback;
53599dc50cb5SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
53609dc50cb5SStefano Zampini }
53619dc50cb5SStefano Zampini 
53629dc50cb5SStefano Zampini /*@
5363c6bf8827SStefano Zampini   TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5364c6bf8827SStefano Zampini 
5365c6bf8827SStefano Zampini   Not collective
5366c6bf8827SStefano Zampini 
5367c6bf8827SStefano Zampini   Input Parameter:
5368c6bf8827SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
5369c6bf8827SStefano Zampini 
5370c6bf8827SStefano Zampini   Output Parameter:
5371c6bf8827SStefano Zampini . flg - the resize flag
5372c6bf8827SStefano Zampini 
5373c6bf8827SStefano Zampini   Level: advanced
5374c6bf8827SStefano Zampini 
5375c6bf8827SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5376c6bf8827SStefano Zampini @*/
5377c6bf8827SStefano Zampini PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5378c6bf8827SStefano Zampini {
5379c6bf8827SStefano Zampini   PetscFunctionBegin;
5380c6bf8827SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5381c6bf8827SStefano Zampini   PetscAssertPointer(flg, 2);
5382c6bf8827SStefano Zampini   *flg = ts->stepresize;
5383c6bf8827SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
5384c6bf8827SStefano Zampini }
5385c6bf8827SStefano Zampini 
5386c6bf8827SStefano Zampini /*@
5387ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5388ff22ae23SHong Zhang 
5389ff22ae23SHong Zhang   Input Parameter:
5390bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5391ff22ae23SHong Zhang 
53920429704eSStefano Zampini   Output Parameters:
53930429704eSStefano Zampini + ns - the number of stages
53940429704eSStefano Zampini - Y  - the current stage vectors
53950429704eSStefano Zampini 
5396ff22ae23SHong Zhang   Level: advanced
5397ff22ae23SHong Zhang 
5398bcf0153eSBarry Smith   Note:
5399195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
54000429704eSStefano Zampini 
54011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5402ff22ae23SHong Zhang @*/
5403d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5404d71ae5a4SJacob Faibussowitsch {
5405ff22ae23SHong Zhang   PetscFunctionBegin;
5406ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54074f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
54084f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
54090429704eSStefano Zampini   if (!ts->ops->getstages) {
54100429704eSStefano Zampini     if (ns) *ns = 0;
54110429704eSStefano Zampini     if (Y) *Y = NULL;
5412dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
54133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5414ff22ae23SHong Zhang }
5415ff22ae23SHong Zhang 
5416847ff0e1SMatthew G. Knepley /*@C
5417847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5418847ff0e1SMatthew G. Knepley 
5419c3339decSBarry Smith   Collective
5420847ff0e1SMatthew G. Knepley 
5421847ff0e1SMatthew G. Knepley   Input Parameters:
5422bcf0153eSBarry Smith + ts    - the `TS` context
5423847ff0e1SMatthew G. Knepley . t     - current timestep
5424847ff0e1SMatthew G. Knepley . U     - state vector
5425847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5426847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5427847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5428847ff0e1SMatthew G. Knepley 
5429847ff0e1SMatthew G. Knepley   Output Parameters:
5430847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5431195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5432847ff0e1SMatthew G. Knepley 
5433847ff0e1SMatthew G. Knepley   Level: intermediate
5434847ff0e1SMatthew G. Knepley 
5435847ff0e1SMatthew G. Knepley   Notes:
5436847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5437847ff0e1SMatthew G. Knepley 
5438847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5439847ff0e1SMatthew G. Knepley 
5440847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5441847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5442847ff0e1SMatthew G. Knepley 
5443bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5444847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5445847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5446847ff0e1SMatthew G. Knepley 
54471cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5448847ff0e1SMatthew G. Knepley @*/
5449d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5450d71ae5a4SJacob Faibussowitsch {
5451847ff0e1SMatthew G. Knepley   SNES          snes;
5452847ff0e1SMatthew G. Knepley   MatFDColoring color;
5453847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5454847ff0e1SMatthew G. Knepley 
5455847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
54569566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
54579566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5458847ff0e1SMatthew G. Knepley   if (!color) {
5459847ff0e1SMatthew G. Knepley     DM         dm;
5460847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5461847ff0e1SMatthew G. Knepley 
54629566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
54639566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5464847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
54659566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
54669566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
54679566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void))SNESTSFormFunction, (void *)ts));
54689566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
54699566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
54709566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5471847ff0e1SMatthew G. Knepley     } else {
5472847ff0e1SMatthew G. Knepley       MatColoring mc;
5473847ff0e1SMatthew G. Knepley 
54749566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
54759566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
54769566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
54779566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
54789566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
54799566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
54809566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
54819566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode (*)(void))SNESTSFormFunction, (void *)ts));
54829566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
54839566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
54849566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5485847ff0e1SMatthew G. Knepley     }
54869566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
54879566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5488847ff0e1SMatthew G. Knepley   }
54899566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
54909566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5491847ff0e1SMatthew G. Knepley   if (J != B) {
54929566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
54939566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5494847ff0e1SMatthew G. Knepley   }
54953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5496847ff0e1SMatthew G. Knepley }
549793b34091SDebojyoti Ghosh 
5498b43aa488SJacob Faibussowitsch /*@C
54996bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5500cb9d8021SPierre Barbier de Reuille 
5501cb9d8021SPierre Barbier de Reuille   Input Parameters:
5502bcf0153eSBarry Smith + ts   - the `TS` context
5503bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
55046bc98fa9SBarry Smith 
550520f4b53cSBarry Smith   Calling sequence of `func`:
55068847d985SBarry Smith + ts     - the `TS` context
55076bc98fa9SBarry Smith . time   - the current time (of the stage)
55086bc98fa9SBarry Smith . state  - the state to check if it is valid
5509a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5510cb9d8021SPierre Barbier de Reuille 
5511cb9d8021SPierre Barbier de Reuille   Level: intermediate
5512cb9d8021SPierre Barbier de Reuille 
55136bc98fa9SBarry Smith   Notes:
55146bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5515bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5516bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5517bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
55186bc98fa9SBarry Smith 
5519b43aa488SJacob Faibussowitsch   Developer Notes:
5520bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
55216bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
55226bc98fa9SBarry Smith 
55231cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5524cb9d8021SPierre Barbier de Reuille @*/
5525a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5526d71ae5a4SJacob Faibussowitsch {
5527cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5528cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5529cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
55303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5531cb9d8021SPierre Barbier de Reuille }
5532cb9d8021SPierre Barbier de Reuille 
5533cb9d8021SPierre Barbier de Reuille /*@
55346bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5535cb9d8021SPierre Barbier de Reuille 
5536cb9d8021SPierre Barbier de Reuille   Input Parameters:
5537bcf0153eSBarry Smith + ts        - the `TS` context
55386bc98fa9SBarry Smith . stagetime - time of the simulation
55396bc98fa9SBarry Smith - Y         - state vector to check.
5540cb9d8021SPierre Barbier de Reuille 
5541cb9d8021SPierre Barbier de Reuille   Output Parameter:
5542bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
554396a0c994SBarry Smith 
55446bc98fa9SBarry Smith   Level: developer
55456bc98fa9SBarry Smith 
5546bcf0153eSBarry Smith   Note:
5547bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5548bcf0153eSBarry Smith   to check if the current state is valid.
5549bcf0153eSBarry Smith 
55501cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5551cb9d8021SPierre Barbier de Reuille @*/
5552d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5553d71ae5a4SJacob Faibussowitsch {
5554cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5555cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5556cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
55571e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
55583ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5559cb9d8021SPierre Barbier de Reuille }
55601ceb14c0SBarry Smith 
5561cc4c1da9SBarry Smith /*@
5562195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
556393b34091SDebojyoti Ghosh 
5564d083f849SBarry Smith   Collective
556593b34091SDebojyoti Ghosh 
556693b34091SDebojyoti Ghosh   Input Parameter:
5567bcf0153eSBarry Smith . tsin - The input `TS`
556893b34091SDebojyoti Ghosh 
556993b34091SDebojyoti Ghosh   Output Parameter:
5570bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
55715eca1a21SEmil Constantinescu 
55725eca1a21SEmil Constantinescu   Level: developer
557393b34091SDebojyoti Ghosh 
5574bcf0153eSBarry Smith   Notes:
5575bcf0153eSBarry 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.
5576bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5577bcf0153eSBarry Smith 
5578195e9b02SBarry 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
5579195e9b02SBarry Smith .vb
5580195e9b02SBarry Smith  SNES snes_dup = NULL;
5581195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5582195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5583195e9b02SBarry Smith .ve
5584bcf0153eSBarry Smith 
55851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
558693b34091SDebojyoti Ghosh @*/
5587d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5588d71ae5a4SJacob Faibussowitsch {
558993b34091SDebojyoti Ghosh   TS     t;
5590dc846ba4SSatish Balay   SNES   snes_start;
5591dc846ba4SSatish Balay   DM     dm;
5592dc846ba4SSatish Balay   TSType type;
559393b34091SDebojyoti Ghosh 
559493b34091SDebojyoti Ghosh   PetscFunctionBegin;
55954f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
559693b34091SDebojyoti Ghosh   *tsout = NULL;
559793b34091SDebojyoti Ghosh 
55989566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
559993b34091SDebojyoti Ghosh 
560093b34091SDebojyoti Ghosh   /* General TS description */
560193b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5602d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
560393b34091SDebojyoti Ghosh   t->setupcalled       = 0;
560493b34091SDebojyoti Ghosh   t->ksp_its           = 0;
560593b34091SDebojyoti Ghosh   t->snes_its          = 0;
560693b34091SDebojyoti Ghosh   t->nwork             = 0;
56077d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
560893b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
560993b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
561093b34091SDebojyoti Ghosh 
56119566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
56129566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5613d15a3a53SEmil Constantinescu 
56149566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
56159566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
561693b34091SDebojyoti Ghosh 
561793b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
56189566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
561993b34091SDebojyoti Ghosh 
5620e7069c78SShri   t->trajectory = tsin->trajectory;
56219566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5622e7069c78SShri 
5623e7069c78SShri   t->event = tsin->event;
56246b10a48eSSatish Balay   if (t->event) t->event->refct++;
5625e7069c78SShri 
562693b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
562793b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5628e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
562993b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
563093b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
563193b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
563293b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
563393b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
563493b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
563593b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
563693b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
563793b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
563893b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
563993b34091SDebojyoti Ghosh 
56409566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
56419566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
564293b34091SDebojyoti Ghosh 
564393b34091SDebojyoti Ghosh   t->vec_sol = NULL;
564493b34091SDebojyoti Ghosh 
564593b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
564693b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
564793b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
564893b34091SDebojyoti Ghosh 
5649aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
565093b34091SDebojyoti Ghosh 
56510d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
56520d4fed19SBarry Smith     PetscInt i;
56539566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5654ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
56550d4fed19SBarry Smith   }
565693b34091SDebojyoti Ghosh   *tsout = t;
56573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
565893b34091SDebojyoti Ghosh }
5659f3b1f45cSBarry Smith 
5660d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5661d71ae5a4SJacob Faibussowitsch {
5662f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5663f3b1f45cSBarry Smith 
5664f3b1f45cSBarry Smith   PetscFunctionBegin;
56659566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
56663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5667f3b1f45cSBarry Smith }
5668f3b1f45cSBarry Smith 
5669f3b1f45cSBarry Smith /*@
5670bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5671f3b1f45cSBarry Smith 
5672c3339decSBarry Smith   Logically Collective
5673f3b1f45cSBarry Smith 
56742fe279fdSBarry Smith   Input Parameter:
5675b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5676f3b1f45cSBarry Smith 
5677f3b1f45cSBarry Smith   Output Parameter:
5678bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5679f3b1f45cSBarry Smith 
5680bcf0153eSBarry Smith   Options Database Key:
5681f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5682f3b1f45cSBarry Smith 
5683f3b1f45cSBarry Smith   Level: advanced
5684f3b1f45cSBarry Smith 
5685bcf0153eSBarry Smith   Note:
5686195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5687f3b1f45cSBarry Smith 
56881cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5689f3b1f45cSBarry Smith @*/
5690d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5691d71ae5a4SJacob Faibussowitsch {
5692f3b1f45cSBarry Smith   Mat              J, B;
56938434afd1SBarry Smith   TSRHSJacobianFn *func;
5694f3b1f45cSBarry Smith   void            *ctx;
5695f3b1f45cSBarry Smith 
5696f3b1f45cSBarry Smith   PetscFunctionBegin;
56979566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
56989566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
56999566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
57003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5701f3b1f45cSBarry Smith }
5702f3b1f45cSBarry Smith 
5703cc4c1da9SBarry Smith /*@
5704bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5705f3b1f45cSBarry Smith 
5706c3339decSBarry Smith   Logically Collective
5707f3b1f45cSBarry Smith 
57082fe279fdSBarry Smith   Input Parameter:
5709b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5710f3b1f45cSBarry Smith 
5711f3b1f45cSBarry Smith   Output Parameter:
5712bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5713f3b1f45cSBarry Smith 
5714bcf0153eSBarry Smith   Options Database Key:
5715f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5716f3b1f45cSBarry Smith 
5717bcf0153eSBarry Smith   Level: advanced
5718bcf0153eSBarry Smith 
571995452b02SPatrick Sanan   Notes:
5720195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5721f3b1f45cSBarry Smith 
57221cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5723f3b1f45cSBarry Smith @*/
5724d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5725d71ae5a4SJacob Faibussowitsch {
5726f3b1f45cSBarry Smith   Mat              J, B;
5727f3b1f45cSBarry Smith   void            *ctx;
57288434afd1SBarry Smith   TSRHSJacobianFn *func;
5729f3b1f45cSBarry Smith 
5730f3b1f45cSBarry Smith   PetscFunctionBegin;
57319566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
57329566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
57339566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
57343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5735f3b1f45cSBarry Smith }
57360fe4d17eSHong Zhang 
57370fe4d17eSHong Zhang /*@
57380fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
57390fe4d17eSHong Zhang 
574020f4b53cSBarry Smith   Logically Collective
57410fe4d17eSHong Zhang 
5742d8d19677SJose E. Roman   Input Parameters:
57430fe4d17eSHong Zhang + ts                   - timestepping context
5744bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
57450fe4d17eSHong Zhang 
5746bcf0153eSBarry Smith   Options Database Key:
57470fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
57480fe4d17eSHong Zhang 
57490fe4d17eSHong Zhang   Level: intermediate
57500fe4d17eSHong Zhang 
5751bcf0153eSBarry Smith   Note:
5752195e9b02SBarry Smith   This is only for multirate methods
5753bcf0153eSBarry Smith 
57541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
57550fe4d17eSHong Zhang @*/
5756d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5757d71ae5a4SJacob Faibussowitsch {
57580fe4d17eSHong Zhang   PetscFunctionBegin;
57590fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57600fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
57613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57620fe4d17eSHong Zhang }
57630fe4d17eSHong Zhang 
57640fe4d17eSHong Zhang /*@
57650fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
57660fe4d17eSHong Zhang 
576720f4b53cSBarry Smith   Not Collective
57680fe4d17eSHong Zhang 
57690fe4d17eSHong Zhang   Input Parameter:
57700fe4d17eSHong Zhang . ts - timestepping context
57710fe4d17eSHong Zhang 
57720fe4d17eSHong Zhang   Output Parameter:
5773bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
57740fe4d17eSHong Zhang 
57750fe4d17eSHong Zhang   Level: intermediate
57760fe4d17eSHong Zhang 
57771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
57780fe4d17eSHong Zhang @*/
5779d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5780d71ae5a4SJacob Faibussowitsch {
57810fe4d17eSHong Zhang   PetscFunctionBegin;
57820fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
57830fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
57843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
57850fe4d17eSHong Zhang }
5786d60b7d5cSBarry Smith 
5787d60b7d5cSBarry Smith /*@
5788d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5789d60b7d5cSBarry Smith 
5790c3339decSBarry Smith   Logically  Collective
5791d60b7d5cSBarry Smith 
5792d60b7d5cSBarry Smith   Input Parameters:
5793d60b7d5cSBarry Smith + ts  - the time-stepper
5794bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5795d60b7d5cSBarry Smith 
5796d60b7d5cSBarry Smith   Level: intermediate
5797d60b7d5cSBarry Smith 
5798bcf0153eSBarry Smith   Note:
5799d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5800d60b7d5cSBarry Smith 
58011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5802d60b7d5cSBarry Smith  @*/
5803d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5804d71ae5a4SJacob Faibussowitsch {
5805d60b7d5cSBarry Smith   PetscFunctionBegin;
5806d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5807d60b7d5cSBarry Smith   ts->axpy_pattern = str;
58083ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5809d60b7d5cSBarry Smith }
58104a658b32SHong Zhang 
58114a658b32SHong Zhang /*@
5812bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
58134a658b32SHong Zhang 
5814c3339decSBarry Smith   Collective
58154a658b32SHong Zhang 
58164a658b32SHong Zhang   Input Parameters:
58174a658b32SHong Zhang + ts         - the time-stepper
58184a658b32SHong Zhang . n          - number of the time points (>=2)
58194a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
58204a658b32SHong Zhang 
5821bcf0153eSBarry Smith   Options Database Key:
58224a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
58234a658b32SHong Zhang 
5824bcf0153eSBarry Smith   Level: intermediate
58254a658b32SHong Zhang 
58264a658b32SHong Zhang   Notes:
58274a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
5828bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
5829bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
58304a658b32SHong Zhang   pressure the memory system when using a large number of span points.
58314a658b32SHong Zhang 
58321cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
58334a658b32SHong Zhang  @*/
5834d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
5835d71ae5a4SJacob Faibussowitsch {
58364a658b32SHong Zhang   PetscFunctionBegin;
58374a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
583863a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
58394a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
58404a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
58414a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
58424a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
58434a658b32SHong Zhang   }
58444a658b32SHong Zhang   if (!ts->tspan) {
58454a658b32SHong Zhang     TSTimeSpan tspan;
58464a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
58474a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
5848e1db57b0SHong Zhang     tspan->reltol  = 1e-6;
5849e1db57b0SHong Zhang     tspan->abstol  = 10 * PETSC_MACHINE_EPSILON;
5850ca4445c7SIlya Fursov     tspan->worktol = 0;
58514a658b32SHong Zhang     ts->tspan      = tspan;
58524a658b32SHong Zhang   }
58534a658b32SHong Zhang   ts->tspan->num_span_times = n;
58544a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
58554a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
58564a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
58573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58584a658b32SHong Zhang }
58594a658b32SHong Zhang 
58604a658b32SHong Zhang /*@C
5861195e9b02SBarry Smith   TSGetTimeSpan - gets the time span set with `TSSetTimeSpan()`
58624a658b32SHong Zhang 
58634a658b32SHong Zhang   Not Collective
58644a658b32SHong Zhang 
58654a658b32SHong Zhang   Input Parameter:
58664a658b32SHong Zhang . ts - the time-stepper
58674a658b32SHong Zhang 
58684a658b32SHong Zhang   Output Parameters:
58694a658b32SHong Zhang + n          - number of the time points (>=2)
5870bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
58714a658b32SHong Zhang 
58724a658b32SHong Zhang   Level: beginner
58734a658b32SHong Zhang 
5874bcf0153eSBarry Smith   Note:
5875195e9b02SBarry Smith   The values obtained are valid until the `TS` object is destroyed.
5876195e9b02SBarry Smith 
5877195e9b02SBarry Smith   Both `n` and `span_times` can be `NULL`.
5878bcf0153eSBarry Smith 
58791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
58804a658b32SHong Zhang  @*/
5881cc4c1da9SBarry Smith PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal *span_times[])
5882d71ae5a4SJacob Faibussowitsch {
58834a658b32SHong Zhang   PetscFunctionBegin;
58844a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58854f572ea9SToby Isaac   if (n) PetscAssertPointer(n, 2);
58864f572ea9SToby Isaac   if (span_times) PetscAssertPointer(span_times, 3);
58874a658b32SHong Zhang   if (!ts->tspan) {
58884a658b32SHong Zhang     if (n) *n = 0;
58894a658b32SHong Zhang     if (span_times) *span_times = NULL;
58904a658b32SHong Zhang   } else {
58914a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
58924a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
58934a658b32SHong Zhang   }
58943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58954a658b32SHong Zhang }
58964a658b32SHong Zhang 
58974a658b32SHong Zhang /*@
58984a658b32SHong Zhang   TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
58994a658b32SHong Zhang 
59004a658b32SHong Zhang   Input Parameter:
5901bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
59024a658b32SHong Zhang 
59034a658b32SHong Zhang   Output Parameters:
59044a658b32SHong Zhang + nsol - the number of solutions
59054a658b32SHong Zhang - Sols - the solution vectors
59064a658b32SHong Zhang 
5907bcf0153eSBarry Smith   Level: intermediate
59084a658b32SHong Zhang 
590940bd4cedSHong Zhang   Notes:
5910195e9b02SBarry Smith   Both `nsol` and `Sols` can be `NULL`.
59114a658b32SHong Zhang 
5912195e9b02SBarry 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()`.
5913bcf0153eSBarry Smith   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
5914bcf0153eSBarry Smith 
59151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeSpan()`
59164a658b32SHong Zhang @*/
5917d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
5918d71ae5a4SJacob Faibussowitsch {
59194a658b32SHong Zhang   PetscFunctionBegin;
59204a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
59214f572ea9SToby Isaac   if (nsol) PetscAssertPointer(nsol, 2);
59224f572ea9SToby Isaac   if (Sols) PetscAssertPointer(Sols, 3);
59234a658b32SHong Zhang   if (!ts->tspan) {
59244a658b32SHong Zhang     if (nsol) *nsol = 0;
59254a658b32SHong Zhang     if (Sols) *Sols = NULL;
59264a658b32SHong Zhang   } else {
592740bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
59284a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
59294a658b32SHong Zhang   }
59303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
59314a658b32SHong Zhang }
5932d7cfae9bSHong Zhang 
5933cc4c1da9SBarry Smith /*@
59347b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
5935d7cfae9bSHong Zhang 
5936195e9b02SBarry Smith   Collective
5937d7cfae9bSHong Zhang 
5938d7cfae9bSHong Zhang   Input Parameters:
5939195e9b02SBarry Smith + ts - the `TS` context
5940d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
5941195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
5942d7cfae9bSHong Zhang 
5943d7cfae9bSHong Zhang   Level: intermediate
5944d7cfae9bSHong Zhang 
5945d7cfae9bSHong Zhang   Notes:
5946195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
5947195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
5948d7cfae9bSHong Zhang   and multiple fields are involved.
5949d7cfae9bSHong Zhang 
5950d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
5951195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
59527b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
59537b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
5954d7cfae9bSHong Zhang 
59551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5956d7cfae9bSHong Zhang @*/
5957d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
5958d7cfae9bSHong Zhang {
5959d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
5960d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
5961d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
5962d7cfae9bSHong Zhang 
5963d7cfae9bSHong Zhang   PetscFunctionBegin;
5964d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
596558c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
5966d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
5967d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
5968d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
5969d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
5970d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
5971d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
5972d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
5973d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
5974d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode (*)(void))SNESTSFormFunction, (void *)ts));
5975d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
5976d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
5977d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
5978d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
5979d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
59803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5981d7cfae9bSHong Zhang }
5982