xref: /petsc/src/ts/interface/ts.c (revision 4e8208cbcbc709572b8abe32f33c78b69c819375)
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 
TSAdaptSetDefaultType(TSAdapt adapt,TSAdaptType default_type)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
378343f784SJames Wright . -ts_time_span <t0,...tf>                                           - sets the time span, solutions are computed and stored for each indicated time, init_time and max_time are set
388343f784SJames Wright . -ts_eval_times <t0,...tn>                                          - time points where solutions are computed and stored for each indicated time
398e562f8dSJames Wright . -ts_max_steps <steps>                                              - maximum time-step number to execute until (possibly with nonzero starting value)
40188af4bfSBarry Smith . -ts_run_steps <steps>                                              - maximum number of time steps for `TSSolve()` to take on each call
41ef85077eSLisandro Dalcin . -ts_init_time <time>                                               - initial time to start computation
42195e9b02SBarry Smith . -ts_final_time <time>                                              - final time to compute to (deprecated: use `-ts_max_time`)
43188af4bfSBarry Smith . -ts_time_step <dt>                                                 - initial time step (only a suggestion, the actual initial time step used differ)
441628793fSSatish Balay . -ts_exact_final_time <stepover,interpolate,matchstep>              - whether to stop at the exact given final time and how to compute the solution at that time
45a3cdaa26SBarry Smith . -ts_max_snes_failures <maxfailures>                                - Maximum number of nonlinear solve failures allowed
46188af4bfSBarry Smith . -ts_max_step_rejections <maxrejects>                               - Maximum number of step rejections before step fails
47a3cdaa26SBarry Smith . -ts_error_if_step_fails <true,false>                               - Error if no step succeeds
48a3cdaa26SBarry Smith . -ts_rtol <rtol>                                                    - relative tolerance for local truncation error
4967b8a455SSatish Balay . -ts_atol <atol>                                                    - Absolute tolerance for local truncation error
50f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view               - test the Jacobian at each iteration against finite difference with RHS function
51b43aa488SJacob Faibussowitsch . -ts_rhs_jacobian_test_mult_transpose                               - test the Jacobian at each iteration against finite difference with RHS function
52195e9b02SBarry Smith . -ts_adjoint_solve <yes,no>                                         - After solving the ODE/DAE solve the adjoint problem (requires `-ts_save_trajectory`)
53847ff0e1SMatthew G. Knepley . -ts_fd_color                                                       - Use finite differences with coloring to compute IJacobian
54bdad233fSMatthew Knepley . -ts_monitor                                                        - print information at each timestep
55aee7a9fbSMatthew G. Knepley . -ts_monitor_cancel                                                 - Cancel all monitors
56340b794cSJed Brown . -ts_monitor_wall_clock_time                                        - Monitor wall-clock time, KSP iterations, and SNES iterations per step
57de06c3feSJed Brown . -ts_monitor_lg_solution                                            - Monitor solution graphically
58de06c3feSJed Brown . -ts_monitor_lg_error                                               - Monitor error graphically
597cf37e64SBarry Smith . -ts_monitor_error                                                  - Monitors norm of error
606934998bSLisandro Dalcin . -ts_monitor_lg_timestep                                            - Monitor timestep size graphically
618b668821SLisandro Dalcin . -ts_monitor_lg_timestep_log                                        - Monitor log timestep size graphically
62de06c3feSJed Brown . -ts_monitor_lg_snes_iterations                                     - Monitor number nonlinear iterations for each timestep graphically
63de06c3feSJed Brown . -ts_monitor_lg_ksp_iterations                                      - Monitor number nonlinear iterations for each timestep graphically
64de06c3feSJed Brown . -ts_monitor_sp_eig                                                 - Monitor eigenvalues of linearized operator graphically
65de06c3feSJed Brown . -ts_monitor_draw_solution                                          - Monitor solution graphically
663e4cdcaaSBarry Smith . -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright>       - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
673e4cdcaaSBarry Smith . -ts_monitor_draw_error                                             - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
68fde5950dSBarry Smith . -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
69c17ba870SStefano 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
708e562f8dSJames Wright . -ts_monitor_solution_skip_initial                                  - skip writing of initial condition
7163a3b9bcSJacob 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)
72c17ba870SStefano 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
739e336e28SPatrick Sanan - -ts_monitor_envelope                                               - determine maximum and minimum value of each component of the solution over the solution time
7453ea634cSHong Zhang 
75bcf0153eSBarry Smith   Level: beginner
763d5a8a6aSBarry Smith 
77bcf0153eSBarry Smith   Notes:
78bcf0153eSBarry Smith   See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
79bcf0153eSBarry Smith 
80195e9b02SBarry Smith   Certain `SNES` options get reset for each new nonlinear solver, for example `-snes_lag_jacobian its` and `-snes_lag_preconditioner its`, in order
810d56bcf9SIlya Fursov   to retain them over the multiple nonlinear solves that `TS` uses you must also provide `-snes_lag_jacobian_persists true` and
82195e9b02SBarry Smith   `-snes_lag_preconditioner_persists true`
833d5a8a6aSBarry Smith 
84b43aa488SJacob Faibussowitsch   Developer Notes:
859e336e28SPatrick Sanan   We should unify all the -ts_monitor options in the way that -xxx_view has been unified
86bdad233fSMatthew Knepley 
871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetType()`
88bdad233fSMatthew Knepley @*/
TSSetFromOptions(TS ts)89d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
90d71ae5a4SJacob Faibussowitsch {
91bc952696SBarry Smith   PetscBool              opt, flg, tflg;
92eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
93acc0c1feSStefano Zampini   PetscReal              time_step, eval_times[100] = {0};
94136cf249SJames Wright   PetscInt               num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
9549354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
96d1212d36SBarry Smith   char                   dir[16];
978434afd1SBarry Smith   TSIFunctionFn         *ifun;
986991f827SBarry Smith   const char            *defaultType;
996991f827SBarry Smith   char                   typeName[256];
100bdad233fSMatthew Knepley 
101bdad233fSMatthew Knepley   PetscFunctionBegin;
1020700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1036991f827SBarry Smith 
1049566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1059566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
106cd11d68dSLisandro Dalcin 
107d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1081ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1091ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1111e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1121e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
113bdad233fSMatthew Knepley 
114bdad233fSMatthew Knepley   /* Handle generic TS options */
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
117136cf249SJames Wright   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", eval_times, &num_eval_times, &flg));
118136cf249SJames Wright   if (flg) PetscCall(TSSetTimeSpan(ts, num_eval_times, eval_times));
119136cf249SJames Wright   num_eval_times = PETSC_STATIC_ARRAY_LENGTH(eval_times);
120136cf249SJames Wright   PetscCall(PetscOptionsRealArray("-ts_eval_times", "Evaluation time points", "TSSetEvaluationTimes", eval_times, &num_eval_times, &opt));
1218343f784SJames Wright   PetscCheck(flg != opt || (!flg && !opt), PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "May not provide -ts_time_span and -ts_eval_times simultaneously");
122136cf249SJames Wright   if (opt) PetscCall(TSSetEvaluationTimes(ts, num_eval_times, eval_times));
1238e562f8dSJames Wright   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum time step number to execute to (possibly with non-zero starting value)", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1248e562f8dSJames Wright   PetscCall(PetscOptionsInt("-ts_run_steps", "Maximum number of time steps to take on each call to TSSolve()", "TSSetRunSteps", ts->run_steps, &ts->run_steps, NULL));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
126188af4bfSBarry Smith   PetscCall(PetscOptionsDeprecated("-ts_dt", "-ts_time_step", "3.25", NULL));
127188af4bfSBarry Smith   PetscCall(PetscOptionsReal("-ts_time_step", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1289566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1299566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1309566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
13109cb0f53SBarry Smith   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, &flg));
13209cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxSNESFailures(ts, ts->max_snes_failures));
133188af4bfSBarry Smith   PetscCall(PetscOptionsDeprecated("-ts_max_reject", "-ts_max_step_rejections", "3.25", NULL));
134188af4bfSBarry Smith   PetscCall(PetscOptionsInt("-ts_max_step_rejections", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, &flg));
13509cb0f53SBarry Smith   if (flg) PetscCall(TSSetMaxStepRejections(ts, ts->max_reject));
1369566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
13709cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL, 0));
13809cb0f53SBarry Smith   PetscCall(PetscOptionsBoundedReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL, 0));
139bdad233fSMatthew Knepley 
1409566063dSJacob 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));
1419566063dSJacob 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));
1429566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
14356f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
14456f85f32SBarry Smith   {
14556f85f32SBarry Smith     PetscBool set;
14656f85f32SBarry Smith     flg = PETSC_FALSE;
1479566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1481baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
14956f85f32SBarry Smith   }
15056f85f32SBarry Smith #endif
15156f85f32SBarry Smith 
152bdad233fSMatthew Knepley   /* Monitor options */
15341d17464SJames Wright   PetscCall(PetscOptionsDeprecated("-ts_monitor_frequency", "-ts_dmswarm_monitor_moments_interval", "3.24", "Retired in favor of monitor-specific intervals (ts_dmswarm_monitor_moments was the only monitor to use ts_monitor_frequency)"));
1549566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
155340b794cSJed Brown   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_wall_clock_time", "Monitor wall-clock time, KSP iterations, and SNES iterations per step", "TSMonitorWallClockTime", TSMonitorWallClockTime, TSMonitorWallClockTimeSetUp));
1569566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1578e562f8dSJames Wright   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, TSMonitorSolutionSetup));
1589566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
1599566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1609566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1615180491cSLisandro Dalcin 
1629566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
163b3603a34SBarry Smith   if (opt) {
1643923b477SBarry Smith     PetscInt  howoften = 1;
165e669de00SBarry Smith     DM        dm;
166e669de00SBarry Smith     PetscBool net;
167b3603a34SBarry Smith 
1689566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1699566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1709566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
171e669de00SBarry Smith     if (net) {
172e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1739566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
17449abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxNetworkDestroy));
1759566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
176e669de00SBarry Smith     } else {
177e669de00SBarry Smith       TSMonitorLGCtx ctx;
1789566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
17949abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
180bdad233fSMatthew Knepley     }
181e669de00SBarry Smith   }
1826ba87a44SLisandro Dalcin 
1839566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
184ef20d060SBarry Smith   if (opt) {
1850b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1863923b477SBarry Smith     PetscInt       howoften = 1;
187ef20d060SBarry Smith 
1889566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1899566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
19049abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
191ef20d060SBarry Smith   }
1929566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1937cf37e64SBarry Smith 
1949566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1956934998bSLisandro Dalcin   if (opt) {
1966934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1976934998bSLisandro Dalcin     PetscInt       howoften = 1;
1986934998bSLisandro Dalcin 
1999566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
2009566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
20149abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
2026934998bSLisandro Dalcin   }
2039566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
2048b668821SLisandro Dalcin   if (opt) {
2058b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
2068b668821SLisandro Dalcin     PetscInt       howoften = 1;
2078b668821SLisandro Dalcin 
2089566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
2099566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
21049abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
2118b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
2128b668821SLisandro Dalcin   }
2138b668821SLisandro Dalcin 
2149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
215201da799SBarry Smith   if (opt) {
216201da799SBarry Smith     TSMonitorLGCtx ctx;
217201da799SBarry Smith     PetscInt       howoften = 1;
218201da799SBarry Smith 
2199566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2209566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
22149abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
222201da799SBarry Smith   }
2239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
224201da799SBarry Smith   if (opt) {
225201da799SBarry Smith     TSMonitorLGCtx ctx;
226201da799SBarry Smith     PetscInt       howoften = 1;
227201da799SBarry Smith 
2289566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2299566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
23049abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscCtxDestroyFn *)TSMonitorLGCtxDestroy));
231201da799SBarry Smith   }
2329566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2338189c53fSBarry Smith   if (opt) {
2348189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2358189c53fSBarry Smith     PetscInt          howoften = 1;
2368189c53fSBarry Smith 
2379566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2389566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
23949abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscCtxDestroyFn *)TSMonitorSPEigCtxDestroy));
2408189c53fSBarry Smith   }
24160e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase space from the DMSwarm", "TSMonitorSPSwarm", &opt));
2421b575b74SJoseph Pusztay   if (opt) {
2431b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
244d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
24560e16b1bSMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE, multispecies = PETSC_FALSE;
246d7462660SMatthew Knepley 
2479371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2489371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2499371c9d4SSatish Balay         create = PETSC_FALSE;
2509371c9d4SSatish Balay         break;
2519371c9d4SSatish Balay       }
2526a5217c0SMatthew G. Knepley     if (create) {
25360e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase space from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2549566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2559566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
25660e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_multi_species", "Color particles by particle species", "TSMonitorSPSwarm", multispecies, &multispecies, NULL));
25760e16b1bSMatthew G. Knepley       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, multispecies, &ctx));
25849abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorSPCtxDestroy));
2591b575b74SJoseph Pusztay     }
2606a5217c0SMatthew G. Knepley   }
26160e16b1bSMatthew G. Knepley   PetscCall(PetscOptionsName("-ts_monitor_hg_swarm", "Display particle histogram from the DMSwarm", "TSMonitorHGSwarm", &opt));
26260e16b1bSMatthew G. Knepley   if (opt) {
26360e16b1bSMatthew G. Knepley     TSMonitorHGCtx ctx;
26460e16b1bSMatthew G. Knepley     PetscInt       howoften = 1, Ns = 1;
26560e16b1bSMatthew G. Knepley     PetscBool      velocity = PETSC_FALSE, create = PETSC_TRUE;
26660e16b1bSMatthew G. Knepley 
26760e16b1bSMatthew G. Knepley     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
26860e16b1bSMatthew G. Knepley       if (ts->monitor[i] == TSMonitorHGSwarmSolution) {
26960e16b1bSMatthew G. Knepley         create = PETSC_FALSE;
27060e16b1bSMatthew G. Knepley         break;
27160e16b1bSMatthew G. Knepley       }
27260e16b1bSMatthew G. Knepley     if (create) {
27360e16b1bSMatthew G. Knepley       DM       sw, dm;
27460e16b1bSMatthew G. Knepley       PetscInt Nc, Nb;
27560e16b1bSMatthew G. Knepley 
27660e16b1bSMatthew G. Knepley       PetscCall(TSGetDM(ts, &sw));
27760e16b1bSMatthew G. Knepley       PetscCall(DMSwarmGetCellDM(sw, &dm));
27860e16b1bSMatthew G. Knepley       PetscCall(DMPlexGetHeightStratum(dm, 0, NULL, &Nc));
27960e16b1bSMatthew G. Knepley       Nb = PetscMin(20, PetscMax(10, Nc));
28060e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm", "Display particles histogram from the DMSwarm", "TSMonitorHGSwarm", howoften, &howoften, NULL));
28160e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsBool("-ts_monitor_hg_swarm_velocity", "Plot in velocity space rather than coordinate space", "TSMonitorHGSwarm", velocity, &velocity, NULL));
28260e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_species", "Number of species to histogram", "TSMonitorHGSwarm", Ns, &Ns, NULL));
28360e16b1bSMatthew G. Knepley       PetscCall(PetscOptionsInt("-ts_monitor_hg_swarm_bins", "Number of histogram bins", "TSMonitorHGSwarm", Nb, &Nb, NULL));
28460e16b1bSMatthew G. Knepley       PetscCall(TSMonitorHGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, Ns, Nb, velocity, &ctx));
28549abdd8aSBarry Smith       PetscCall(TSMonitorSet(ts, TSMonitorHGSwarmSolution, ctx, (PetscCtxDestroyFn *)TSMonitorHGCtxDestroy));
28660e16b1bSMatthew G. Knepley     }
28760e16b1bSMatthew G. Knepley   }
288ef20d060SBarry Smith   opt = PETSC_FALSE;
2899566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
290a7cc72afSBarry Smith   if (opt) {
29183a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
29283a4ac43SBarry Smith     PetscInt         howoften = 1;
293a80ad3e0SBarry Smith 
2949566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2959566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
29649abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
297bdad233fSMatthew Knepley   }
298fb1732b5SBarry Smith   opt = PETSC_FALSE;
2999566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
3002d5ee99bSBarry Smith   if (opt) {
3012d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
3022d5ee99bSBarry Smith     PetscReal        bounds[4];
3032d5ee99bSBarry Smith     PetscInt         n = 4;
3042d5ee99bSBarry Smith     PetscDraw        draw;
3056934998bSLisandro Dalcin     PetscDrawAxis    axis;
3062d5ee99bSBarry Smith 
3079566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
3083c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
3099566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
3109566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
3119566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
3129566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
3139566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
31449abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3152d5ee99bSBarry Smith   }
3162d5ee99bSBarry Smith   opt = PETSC_FALSE;
3179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
3183a471f94SBarry Smith   if (opt) {
31983a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
32083a4ac43SBarry Smith     PetscInt         howoften = 1;
3213a471f94SBarry Smith 
3229566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
3239566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
32449abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3253a471f94SBarry Smith   }
3260ed3bfb6SBarry Smith   opt = PETSC_FALSE;
3279566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
3280ed3bfb6SBarry Smith   if (opt) {
3290ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
3300ed3bfb6SBarry Smith     PetscInt         howoften = 1;
3310ed3bfb6SBarry Smith 
3329566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
3339566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
33449abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscCtxDestroyFn *)TSMonitorDrawCtxDestroy));
3350ed3bfb6SBarry Smith   }
336fde5950dSBarry Smith 
337ed81e22dSJed Brown   opt = PETSC_FALSE;
33863a3b9bcSJacob 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));
339ed81e22dSJed Brown   if (flg) {
3407f27e910SStefano Zampini     TSMonitorVTKCtx ctx;
3417f27e910SStefano Zampini 
3427f27e910SStefano Zampini     PetscCall(TSMonitorSolutionVTKCtxCreate(monfilename, &ctx));
343c17ba870SStefano Zampini     PetscCall(PetscOptionsInt("-ts_monitor_solution_vtk_interval", "Save every interval time step (-1 for last step only)", NULL, ctx->interval, &ctx->interval, NULL));
344*2a8381b2SBarry Smith     PetscCall(TSMonitorSet(ts, (PetscErrorCode (*)(TS, PetscInt, PetscReal, Vec, PetscCtx))TSMonitorSolutionVTK, ctx, (PetscCtxDestroyFn *)TSMonitorSolutionVTKDestroy));
345ed81e22dSJed Brown   }
346bdad233fSMatthew Knepley 
3479566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
348d1212d36SBarry Smith   if (flg) {
349d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
350d1212d36SBarry Smith     int                  ray = 0;
3513ee9839eSMatthew G. Knepley     DMDirection          ddir;
352d1212d36SBarry Smith     DM                   da;
353d1212d36SBarry Smith     PetscMPIInt          rank;
354d1212d36SBarry Smith 
3553c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3563ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3573ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
35898921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
359d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
360d1212d36SBarry Smith 
361835f2295SStefano Zampini     PetscCall(PetscInfo(ts, "Displaying DMDA ray %c = %d\n", dir[0], ray));
3629566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3639566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3649566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3659566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3661e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
36751b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3689566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
369d1212d36SBarry Smith   }
3709566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
37151b4a12fSMatthew G. Knepley   if (flg) {
37251b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
37351b4a12fSMatthew G. Knepley     int                  ray = 0;
3743ee9839eSMatthew G. Knepley     DMDirection          ddir;
37551b4a12fSMatthew G. Knepley     DM                   da;
37651b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
377d1212d36SBarry Smith 
3783c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3793ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3803ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
38198921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
38251b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3831c3436cfSJed Brown 
384835f2295SStefano Zampini     PetscCall(PetscInfo(ts, "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3859566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3869566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3879566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3889566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3899566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
39051b4a12fSMatthew G. Knepley   }
391a7a1495cSBarry Smith 
3929566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
393b3d3934dSBarry Smith   if (opt) {
394b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
395b3d3934dSBarry Smith 
3969566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
39749abdd8aSBarry Smith     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscCtxDestroyFn *)TSMonitorEnvelopeCtxDestroy));
398b3d3934dSBarry Smith   }
399aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
4009566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
4019566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
402b3d3934dSBarry Smith 
403847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
404d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
405847ff0e1SMatthew G. Knepley   if (flg) {
406847ff0e1SMatthew G. Knepley     DM dm;
407847ff0e1SMatthew G. Knepley 
4089371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
4099371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
4109566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
4119566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
412847ff0e1SMatthew G. Knepley   }
413847ff0e1SMatthew G. Knepley 
414d763cef2SBarry Smith   /* Handle specific TS options */
415dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
416fbc52257SHong Zhang 
417a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
4189566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
4199566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
420dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
421a7bdc993SLisandro Dalcin 
42268bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
4234f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
4249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
4251baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
426a05bf03eSHong Zhang 
427dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
428d763cef2SBarry Smith 
429d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
430dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
431d0609cedSBarry Smith   PetscOptionsEnd();
432d763cef2SBarry Smith 
4331baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
43468bece0bSHong Zhang 
4351ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4369566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4371ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4389566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4399566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4401ef27442SStefano Zampini   }
4419566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
4423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
443d763cef2SBarry Smith }
444d763cef2SBarry Smith 
445d2daff3dSHong Zhang /*@
446bcf0153eSBarry Smith   TSGetTrajectory - Gets the trajectory from a `TS` if it exists
44778fbdcc8SBarry Smith 
448c3339decSBarry Smith   Collective
44978fbdcc8SBarry Smith 
4502fe279fdSBarry Smith   Input Parameter:
451bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
45278fbdcc8SBarry Smith 
4532fe279fdSBarry Smith   Output Parameter:
454bcf0153eSBarry Smith . tr - the `TSTrajectory` object, if it exists
45578fbdcc8SBarry Smith 
45678fbdcc8SBarry Smith   Level: advanced
45778fbdcc8SBarry Smith 
458bcf0153eSBarry Smith   Note:
459bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
46078fbdcc8SBarry Smith 
461b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectoryCreate()`
46278fbdcc8SBarry Smith @*/
TSGetTrajectory(TS ts,TSTrajectory * tr)463d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
464d71ae5a4SJacob Faibussowitsch {
46578fbdcc8SBarry Smith   PetscFunctionBegin;
46678fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46778fbdcc8SBarry Smith   *tr = ts->trajectory;
4683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46978fbdcc8SBarry Smith }
47078fbdcc8SBarry Smith 
47178fbdcc8SBarry Smith /*@
472bcf0153eSBarry Smith   TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
473d2daff3dSHong Zhang 
474c3339decSBarry Smith   Collective
475d2daff3dSHong Zhang 
476f899ff85SJose E. Roman   Input Parameter:
477bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
478bc952696SBarry Smith 
479bcf0153eSBarry Smith   Options Database Keys:
48078fbdcc8SBarry Smith + -ts_save_trajectory      - saves the trajectory to a file
48167b8a455SSatish Balay - -ts_trajectory_type type - set trajectory type
48278fbdcc8SBarry Smith 
483d2daff3dSHong Zhang   Level: intermediate
484d2daff3dSHong Zhang 
485bcf0153eSBarry Smith   Notes:
486bcf0153eSBarry Smith   This routine should be called after all `TS` options have been set
487d2daff3dSHong Zhang 
488bcf0153eSBarry Smith   The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
489bcf0153eSBarry Smith   MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
490bcf0153eSBarry Smith 
4911cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
492d2daff3dSHong Zhang @*/
TSSetSaveTrajectory(TS ts)493d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
494d71ae5a4SJacob Faibussowitsch {
495d2daff3dSHong Zhang   PetscFunctionBegin;
496d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49763a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
499d2daff3dSHong Zhang }
500d2daff3dSHong Zhang 
501a7a1495cSBarry Smith /*@
502bcf0153eSBarry Smith   TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
5032d29f1f2SStefano Zampini 
504c3339decSBarry Smith   Collective
5052d29f1f2SStefano Zampini 
5062fe279fdSBarry Smith   Input Parameter:
507bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5082d29f1f2SStefano Zampini 
5092d29f1f2SStefano Zampini   Level: intermediate
5102d29f1f2SStefano Zampini 
5111cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
5122d29f1f2SStefano Zampini @*/
TSResetTrajectory(TS ts)513d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
514d71ae5a4SJacob Faibussowitsch {
5152d29f1f2SStefano Zampini   PetscFunctionBegin;
5162d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5172d29f1f2SStefano Zampini   if (ts->trajectory) {
5189566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5199566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
5202d29f1f2SStefano Zampini   }
5213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5222d29f1f2SStefano Zampini }
5232d29f1f2SStefano Zampini 
5242d29f1f2SStefano Zampini /*@
525195e9b02SBarry Smith   TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from a `TS`
52667a3cfb0SHong Zhang 
527c3339decSBarry Smith   Collective
52867a3cfb0SHong Zhang 
5292fe279fdSBarry Smith   Input Parameter:
530bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
53167a3cfb0SHong Zhang 
53267a3cfb0SHong Zhang   Level: intermediate
53367a3cfb0SHong Zhang 
5341cc06b55SBarry Smith .seealso: [](ch_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
53567a3cfb0SHong Zhang @*/
TSRemoveTrajectory(TS ts)536d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
537d71ae5a4SJacob Faibussowitsch {
53867a3cfb0SHong Zhang   PetscFunctionBegin;
53967a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5401e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
5413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
54267a3cfb0SHong Zhang }
54367a3cfb0SHong Zhang 
54467a3cfb0SHong Zhang /*@
545a7a1495cSBarry Smith   TSComputeRHSJacobian - Computes the Jacobian matrix that has been
546bcf0153eSBarry Smith   set with `TSSetRHSJacobian()`.
547a7a1495cSBarry Smith 
548c3339decSBarry Smith   Collective
549a7a1495cSBarry Smith 
550a7a1495cSBarry Smith   Input Parameters:
551bcf0153eSBarry Smith + ts - the `TS` context
552a7a1495cSBarry Smith . t  - current timestep
5530910c330SBarry Smith - U  - input vector
554a7a1495cSBarry Smith 
555a7a1495cSBarry Smith   Output Parameters:
556a7a1495cSBarry Smith + A - Jacobian matrix
5577addb90fSBarry Smith - B - optional matrix used to compute the preconditioner, often the same as `A`
558a7a1495cSBarry Smith 
559bcf0153eSBarry Smith   Level: developer
560bcf0153eSBarry Smith 
561bcf0153eSBarry Smith   Note:
562a7a1495cSBarry Smith   Most users should not need to explicitly call this routine, as it
5637addb90fSBarry Smith   is used internally within the ODE integrators.
564a7a1495cSBarry Smith 
5651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
566a7a1495cSBarry Smith @*/
TSComputeRHSJacobian(TS ts,PetscReal t,Vec U,Mat A,Mat B)567d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
568d71ae5a4SJacob Faibussowitsch {
569270bf2e7SJed Brown   PetscObjectState Ustate;
5706c1e1eecSBarry Smith   PetscObjectId    Uid;
57124989b8cSPeter Brune   DM               dm;
572942e3340SBarry Smith   DMTS             tsdm;
5738434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobianfunc;
57424989b8cSPeter Brune   void            *ctx;
5758434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
576a7a1495cSBarry Smith 
577a7a1495cSBarry Smith   PetscFunctionBegin;
5780700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5790910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5800910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5819566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5829566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5839566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5849566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5859566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5869566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
587971015bcSStefano Zampini 
5883ba16761SJacob Faibussowitsch   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(PETSC_SUCCESS);
589d90be118SSean Farley 
59063a3b9bcSJacob 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);
59124989b8cSPeter Brune   if (rhsjacobianfunc) {
592da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
593792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
594a6ab3590SBarry Smith     ts->rhsjacs++;
595da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
596ef66eb69SBarry Smith   } else {
5979566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5989566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
599ef66eb69SBarry Smith   }
6000e4ef248SJed Brown   ts->rhsjacobian.time  = t;
601971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
602971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
6039566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
6049566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
6053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
606a7a1495cSBarry Smith }
607a7a1495cSBarry Smith 
608316643e7SJed Brown /*@
609bcf0153eSBarry Smith   TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
610d763cef2SBarry Smith 
611c3339decSBarry Smith   Collective
612316643e7SJed Brown 
613316643e7SJed Brown   Input Parameters:
614bcf0153eSBarry Smith + ts - the `TS` context
615316643e7SJed Brown . t  - current time
6160910c330SBarry Smith - U  - state vector
617316643e7SJed Brown 
618316643e7SJed Brown   Output Parameter:
619dd8e379bSPierre Jolivet . y - right-hand side
620316643e7SJed Brown 
621bcf0153eSBarry Smith   Level: developer
622bcf0153eSBarry Smith 
623316643e7SJed Brown   Note:
624316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
625316643e7SJed Brown   is used internally within the nonlinear solvers.
626316643e7SJed Brown 
6271cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
628316643e7SJed Brown @*/
TSComputeRHSFunction(TS ts,PetscReal t,Vec U,Vec y)629d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
630d71ae5a4SJacob Faibussowitsch {
6318434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
6328434afd1SBarry Smith   TSIFunctionFn   *ifunction;
63324989b8cSPeter Brune   void            *ctx;
63424989b8cSPeter Brune   DM               dm;
63524989b8cSPeter Brune 
636d763cef2SBarry Smith   PetscFunctionBegin;
6370700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6380910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6390700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6409566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6419566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6429566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
643d763cef2SBarry Smith 
6443c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
645d763cef2SBarry Smith 
64624989b8cSPeter Brune   if (rhsfunction) {
647da023ba9SStefano Zampini     PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, y, 0));
6489566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
649792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6509566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
651a6ab3590SBarry Smith     ts->rhsfuncs++;
652da023ba9SStefano Zampini     PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, y, 0));
6531e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
6543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
655d763cef2SBarry Smith }
656d763cef2SBarry Smith 
657ef20d060SBarry Smith /*@
658ef20d060SBarry Smith   TSComputeSolutionFunction - Evaluates the solution function.
659ef20d060SBarry Smith 
660c3339decSBarry Smith   Collective
661ef20d060SBarry Smith 
662ef20d060SBarry Smith   Input Parameters:
663bcf0153eSBarry Smith + ts - the `TS` context
664ef20d060SBarry Smith - t  - current time
665ef20d060SBarry Smith 
666ef20d060SBarry Smith   Output Parameter:
6670910c330SBarry Smith . U - the solution
668ef20d060SBarry Smith 
669ef20d060SBarry Smith   Level: developer
670ef20d060SBarry Smith 
6711cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
672ef20d060SBarry Smith @*/
TSComputeSolutionFunction(TS ts,PetscReal t,Vec U)673d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
674d71ae5a4SJacob Faibussowitsch {
6758434afd1SBarry Smith   TSSolutionFn *solutionfunction;
676ef20d060SBarry Smith   void         *ctx;
677ef20d060SBarry Smith   DM            dm;
678ef20d060SBarry Smith 
679ef20d060SBarry Smith   PetscFunctionBegin;
680ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6810910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6829566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6839566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
684792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
6853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
686ef20d060SBarry Smith }
6879b7cd975SBarry Smith /*@
6889b7cd975SBarry Smith   TSComputeForcingFunction - Evaluates the forcing function.
6899b7cd975SBarry Smith 
690c3339decSBarry Smith   Collective
6919b7cd975SBarry Smith 
6929b7cd975SBarry Smith   Input Parameters:
693bcf0153eSBarry Smith + ts - the `TS` context
6949b7cd975SBarry Smith - t  - current time
6959b7cd975SBarry Smith 
6969b7cd975SBarry Smith   Output Parameter:
6979b7cd975SBarry Smith . U - the function value
6989b7cd975SBarry Smith 
6999b7cd975SBarry Smith   Level: developer
7009b7cd975SBarry Smith 
7011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
7029b7cd975SBarry Smith @*/
TSComputeForcingFunction(TS ts,PetscReal t,Vec U)703d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
704d71ae5a4SJacob Faibussowitsch {
7059b7cd975SBarry Smith   void        *ctx;
7069b7cd975SBarry Smith   DM           dm;
7078434afd1SBarry Smith   TSForcingFn *forcing;
7089b7cd975SBarry Smith 
7099b7cd975SBarry Smith   PetscFunctionBegin;
7109b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7119b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7129566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7139566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
7149b7cd975SBarry Smith 
715792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
7163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
7179b7cd975SBarry Smith }
718ef20d060SBarry Smith 
TSGetRHSMats_Private(TS ts,Mat * Arhs,Mat * Brhs)719d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
720d71ae5a4SJacob Faibussowitsch {
721214bc6a2SJed Brown   Mat            A, B;
7228434afd1SBarry Smith   TSIJacobianFn *ijacobian;
723214bc6a2SJed Brown 
724214bc6a2SJed Brown   PetscFunctionBegin;
725c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
726c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7279566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
728214bc6a2SJed Brown   if (Arhs) {
729214bc6a2SJed Brown     if (!ts->Arhs) {
73041a1d4d2SBarry Smith       if (ijacobian) {
7319566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7329566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
73341a1d4d2SBarry Smith       } else {
73441a1d4d2SBarry Smith         ts->Arhs = A;
7359566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
73641a1d4d2SBarry Smith       }
7373565c898SBarry Smith     } else {
7383565c898SBarry Smith       PetscBool flg;
7399566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7403565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7413565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7429566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7433565c898SBarry Smith         ts->Arhs = A;
7449566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7453565c898SBarry Smith       }
746214bc6a2SJed Brown     }
747214bc6a2SJed Brown     *Arhs = ts->Arhs;
748214bc6a2SJed Brown   }
749214bc6a2SJed Brown   if (Brhs) {
750214bc6a2SJed Brown     if (!ts->Brhs) {
751bdb70873SJed Brown       if (A != B) {
75241a1d4d2SBarry Smith         if (ijacobian) {
7539566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
754bdb70873SJed Brown         } else {
75541a1d4d2SBarry Smith           ts->Brhs = B;
7569566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
75741a1d4d2SBarry Smith         }
75841a1d4d2SBarry Smith       } else {
7599566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
76051699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
761bdb70873SJed Brown       }
762214bc6a2SJed Brown     }
763214bc6a2SJed Brown     *Brhs = ts->Brhs;
764214bc6a2SJed Brown   }
7653ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
766214bc6a2SJed Brown }
767214bc6a2SJed Brown 
768316643e7SJed Brown /*@
769195e9b02SBarry Smith   TSComputeIFunction - Evaluates the DAE residual written in the implicit form F(t,U,Udot)=0
770316643e7SJed Brown 
771c3339decSBarry Smith   Collective
772316643e7SJed Brown 
773316643e7SJed Brown   Input Parameters:
774bcf0153eSBarry Smith + ts   - the `TS` context
775316643e7SJed Brown . t    - current time
7760910c330SBarry Smith . U    - state vector
7770910c330SBarry Smith . Udot - time derivative of state vector
7783dddbd81SStefano Zampini - imex - flag indicates if the method is `TSARKIMEX` so that the RHSFunction should be kept separate
779316643e7SJed Brown 
780316643e7SJed Brown   Output Parameter:
781dd8e379bSPierre Jolivet . Y - right-hand side
782316643e7SJed Brown 
783bcf0153eSBarry Smith   Level: developer
784bcf0153eSBarry Smith 
785316643e7SJed Brown   Note:
786316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
787316643e7SJed Brown   is used internally within the nonlinear solvers.
788316643e7SJed Brown 
78915229ffcSPierre Jolivet   If the user did not write their equations in implicit form, this
790316643e7SJed Brown   function recasts them in implicit form.
791316643e7SJed Brown 
7921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
793316643e7SJed Brown @*/
TSComputeIFunction(TS ts,PetscReal t,Vec U,Vec Udot,Vec Y,PetscBool imex)794d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
795d71ae5a4SJacob Faibussowitsch {
7968434afd1SBarry Smith   TSIFunctionFn   *ifunction;
7978434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
79824989b8cSPeter Brune   void            *ctx;
79924989b8cSPeter Brune   DM               dm;
800316643e7SJed Brown 
801316643e7SJed Brown   PetscFunctionBegin;
8020700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8030910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8040910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
8050700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
806316643e7SJed Brown 
8079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8089566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
8099566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
81024989b8cSPeter Brune 
8113c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
812d90be118SSean Farley 
813da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, Udot, Y));
81424989b8cSPeter Brune   if (ifunction) {
815792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
816a6ab3590SBarry Smith     ts->ifuncs++;
817214bc6a2SJed Brown   }
818214bc6a2SJed Brown   if (imex) {
8191e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
82024989b8cSPeter Brune   } else if (rhsfunction) {
82124989b8cSPeter Brune     if (ifunction) {
822214bc6a2SJed Brown       Vec Frhs;
8238af0501fSStefano Zampini 
8248af0501fSStefano Zampini       PetscCall(DMGetGlobalVector(dm, &Frhs));
8259566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8269566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8278af0501fSStefano Zampini       PetscCall(DMRestoreGlobalVector(dm, &Frhs));
8282dd45cf8SJed Brown     } else {
8299566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8309566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
831316643e7SJed Brown     }
8324a6899ffSJed Brown   }
833da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, Udot, Y));
8343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
835316643e7SJed Brown }
836316643e7SJed Brown 
837cfa8a9a2SHong Zhang /*
838195e9b02SBarry Smith    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call `TSComputeRHSJacobian()` on it.
839cfa8a9a2SHong Zhang 
840cfa8a9a2SHong Zhang    Note:
841195e9b02SBarry Smith    This routine is needed when one switches from `TSComputeIJacobian()` to `TSComputeRHSJacobian()` because the Jacobian matrix may be shifted or scaled in `TSComputeIJacobian()`.
842cfa8a9a2SHong Zhang 
843cfa8a9a2SHong Zhang */
TSRecoverRHSJacobian(TS ts,Mat A,Mat B)844d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
845d71ae5a4SJacob Faibussowitsch {
846cfa8a9a2SHong Zhang   PetscFunctionBegin;
847cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8483c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8493c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
850cfa8a9a2SHong Zhang 
8511baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
85248a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
853cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8541baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8551e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
856cfa8a9a2SHong Zhang   }
857cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
858cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
8593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
860cfa8a9a2SHong Zhang }
861cfa8a9a2SHong Zhang 
862316643e7SJed Brown /*@
863316643e7SJed Brown   TSComputeIJacobian - Evaluates the Jacobian of the DAE
864316643e7SJed Brown 
865c3339decSBarry Smith   Collective
866316643e7SJed Brown 
867316643e7SJed Brown   Input Parameters:
868bcf0153eSBarry Smith + ts    - the `TS` context
869316643e7SJed Brown . t     - current timestep
8700910c330SBarry Smith . U     - state vector
8710910c330SBarry Smith . Udot  - time derivative of state vector
872214bc6a2SJed Brown . shift - shift to apply, see note below
8733dddbd81SStefano Zampini - imex  - flag indicates if the method is `TSARKIMEX` so that the RHSJacobian should be kept separate
874316643e7SJed Brown 
875316643e7SJed Brown   Output Parameters:
876316643e7SJed Brown + A - Jacobian matrix
877195e9b02SBarry Smith - B - matrix from which the preconditioner is constructed; often the same as `A`
878316643e7SJed Brown 
879bcf0153eSBarry Smith   Level: developer
880bcf0153eSBarry Smith 
881316643e7SJed Brown   Notes:
882efa39862SBarry Smith   If $ F(t,U,\dot{U})=0 $ is the DAE, the required Jacobian is
883195e9b02SBarry Smith .vb
8840910c330SBarry Smith    dF/dU + shift*dF/dUdot
885195e9b02SBarry Smith .ve
886316643e7SJed Brown   Most users should not need to explicitly call this routine, as it
887316643e7SJed Brown   is used internally within the nonlinear solvers.
888316643e7SJed Brown 
8891cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`
89063495f91SJed Brown @*/
TSComputeIJacobian(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscBool imex)891d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
892d71ae5a4SJacob Faibussowitsch {
8938434afd1SBarry Smith   TSIJacobianFn   *ijacobian;
8948434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
89524989b8cSPeter Brune   DM               dm;
89624989b8cSPeter Brune   void            *ctx;
897316643e7SJed Brown 
898316643e7SJed Brown   PetscFunctionBegin;
8990700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
9000910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
9010910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
90294ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
90394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
90424989b8cSPeter Brune 
9059566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
9069566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
9079566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
90824989b8cSPeter Brune 
9093c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
910316643e7SJed Brown 
911da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, A, B));
91224989b8cSPeter Brune   if (ijacobian) {
913792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
914a6ab3590SBarry Smith     ts->ijacs++;
9154a6899ffSJed Brown   }
916214bc6a2SJed Brown   if (imex) {
917b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
9184c26be97Sstefano_zampini       PetscBool assembled;
919971015bcSStefano Zampini       if (rhsjacobian) {
920971015bcSStefano Zampini         Mat Arhs = NULL;
9219566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
922971015bcSStefano Zampini         if (A == Arhs) {
9233c633725SBarry 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 */
924971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
925971015bcSStefano Zampini         }
926971015bcSStefano Zampini       }
9279566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9289566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9294c26be97Sstefano_zampini       if (!assembled) {
9309566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9319566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9324c26be97Sstefano_zampini       }
9339566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
93494ab13aaSBarry Smith       if (A != B) {
9359566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9369566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9374c26be97Sstefano_zampini         if (!assembled) {
9389566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9399566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9404c26be97Sstefano_zampini         }
9419566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
942214bc6a2SJed Brown       }
943214bc6a2SJed Brown     }
944214bc6a2SJed Brown   } else {
945e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9461e66621cSBarry Smith 
9471e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9481e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
949e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
950e8b1e424SHong Zhang       PetscObjectState Ustate;
951e8b1e424SHong Zhang       PetscObjectId    Uid;
9528434afd1SBarry Smith       TSRHSFunctionFn *rhsfunction;
953e8b1e424SHong Zhang 
9549566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9559566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9569566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9579371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9589371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9599566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9601e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
961e8b1e424SHong Zhang       } else {
9623565c898SBarry Smith         PetscBool flg;
963e8b1e424SHong Zhang 
964e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
965e8b1e424SHong Zhang           /* MatScale has a short path for this case.
966e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
967e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9689566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
969e8b1e424SHong Zhang         }
9709566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9719566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9723565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9733565c898SBarry Smith         if (!flg) {
9749566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9759566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9763565c898SBarry Smith         }
97794ab13aaSBarry Smith         if (A != B) {
9789566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9799566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
980316643e7SJed Brown         }
981e8b1e424SHong Zhang       }
982e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
983e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
984d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
985e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9869566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9879566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
98894ab13aaSBarry Smith         if (A != B) {
9899566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9909566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
991214bc6a2SJed Brown         }
992316643e7SJed Brown       }
9939566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9949566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9951e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
996316643e7SJed Brown     }
997316643e7SJed Brown   }
998da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, A, B));
9993ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1000316643e7SJed Brown }
1001316643e7SJed Brown 
1002d763cef2SBarry Smith /*@C
1003d763cef2SBarry Smith   TSSetRHSFunction - Sets the routine for evaluating the function,
1004b5abc632SBarry Smith   where U_t = G(t,u).
1005d763cef2SBarry Smith 
1006c3339decSBarry Smith   Logically Collective
1007d763cef2SBarry Smith 
1008d763cef2SBarry Smith   Input Parameters:
1009bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1010dd8e379bSPierre Jolivet . r   - vector to put the computed right-hand side (or `NULL` to have it created)
1011d763cef2SBarry Smith . f   - routine for evaluating the right-hand-side function
1012195e9b02SBarry Smith - ctx - [optional] user-defined context for private data for the function evaluation routine (may be `NULL`)
1013d763cef2SBarry Smith 
1014d763cef2SBarry Smith   Level: beginner
1015d763cef2SBarry Smith 
1016bcf0153eSBarry Smith   Note:
1017bcf0153eSBarry Smith   You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10182bbac0d3SBarry Smith 
10198434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSFunctionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1020d763cef2SBarry Smith @*/
TSSetRHSFunction(TS ts,Vec r,TSRHSFunctionFn * f,PetscCtx ctx)1021*2a8381b2SBarry Smith PetscErrorCode TSSetRHSFunction(TS ts, Vec r, TSRHSFunctionFn *f, PetscCtx ctx)
1022d71ae5a4SJacob Faibussowitsch {
1023089b2837SJed Brown   SNES snes;
10240298fd71SBarry Smith   Vec  ralloc = NULL;
102524989b8cSPeter Brune   DM   dm;
1026d763cef2SBarry Smith 
1027089b2837SJed Brown   PetscFunctionBegin;
10280700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1029ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
103024989b8cSPeter Brune 
10319566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10329566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10339566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1034e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10359566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1036e856ceecSJed Brown     r = ralloc;
1037e856ceecSJed Brown   }
10389566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10399566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
10403ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1041d763cef2SBarry Smith }
1042d763cef2SBarry Smith 
1043ef20d060SBarry Smith /*@C
1044abd5a294SJed Brown   TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1045ef20d060SBarry Smith 
1046c3339decSBarry Smith   Logically Collective
1047ef20d060SBarry Smith 
1048ef20d060SBarry Smith   Input Parameters:
1049bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1050ef20d060SBarry Smith . f   - routine for evaluating the solution
1051ef20d060SBarry Smith - ctx - [optional] user-defined context for private data for the
1052195e9b02SBarry Smith           function evaluation routine (may be `NULL`)
1053ef20d060SBarry Smith 
1054bcf0153eSBarry Smith   Options Database Keys:
1055bcf0153eSBarry Smith + -ts_monitor_lg_error   - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1056bcf0153eSBarry Smith - -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1057bcf0153eSBarry Smith 
1058bcf0153eSBarry Smith   Level: intermediate
10590ed3bfb6SBarry Smith 
1060abd5a294SJed Brown   Notes:
1061abd5a294SJed Brown   This routine is used for testing accuracy of time integration schemes when you already know the solution.
1062abd5a294SJed Brown   If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1063abd5a294SJed Brown   create closed-form solutions with non-physical forcing terms.
1064abd5a294SJed Brown 
1065bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1066abd5a294SJed Brown 
10678434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolutionFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1068ef20d060SBarry Smith @*/
TSSetSolutionFunction(TS ts,TSSolutionFn * f,PetscCtx ctx)1069*2a8381b2SBarry Smith PetscErrorCode TSSetSolutionFunction(TS ts, TSSolutionFn *f, PetscCtx ctx)
1070d71ae5a4SJacob Faibussowitsch {
1071ef20d060SBarry Smith   DM dm;
1072ef20d060SBarry Smith 
1073ef20d060SBarry Smith   PetscFunctionBegin;
1074ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10759566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10769566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
10773ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1078ef20d060SBarry Smith }
1079ef20d060SBarry Smith 
10809b7cd975SBarry Smith /*@C
10819b7cd975SBarry Smith   TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10829b7cd975SBarry Smith 
1083c3339decSBarry Smith   Logically Collective
10849b7cd975SBarry Smith 
10859b7cd975SBarry Smith   Input Parameters:
1086bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1087e162b725SBarry Smith . func - routine for evaluating the forcing function
108814d0ab18SJacob Faibussowitsch - ctx  - [optional] user-defined context for private data for the function evaluation routine
108914d0ab18SJacob Faibussowitsch          (may be `NULL`)
10909b7cd975SBarry Smith 
1091bcf0153eSBarry Smith   Level: intermediate
1092bcf0153eSBarry Smith 
10939b7cd975SBarry Smith   Notes:
10949b7cd975SBarry Smith   This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1095e162b725SBarry 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
1096e162b725SBarry Smith   definition of the problem you are solving and hence possibly introducing bugs.
1097e162b725SBarry Smith 
10988847d985SBarry Smith   This replaces the ODE F(u,u_t,t) = 0 the `TS` is solving with F(u,u_t,t) - func(t) = 0
1099e162b725SBarry Smith 
1100e162b725SBarry 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
1101e162b725SBarry Smith   parameters can be passed in the ctx variable.
11029b7cd975SBarry Smith 
1103bcf0153eSBarry Smith   For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11049b7cd975SBarry Smith 
11058434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSForcingFn`, `TSSetRHSJacobian()`, `TSSetIJacobian()`,
110614d0ab18SJacob Faibussowitsch `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11079b7cd975SBarry Smith @*/
TSSetForcingFunction(TS ts,TSForcingFn * func,PetscCtx ctx)1108*2a8381b2SBarry Smith PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFn *func, PetscCtx ctx)
1109d71ae5a4SJacob Faibussowitsch {
11109b7cd975SBarry Smith   DM dm;
11119b7cd975SBarry Smith 
11129b7cd975SBarry Smith   PetscFunctionBegin;
11139b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11149566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11159566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
11179b7cd975SBarry Smith }
11189b7cd975SBarry Smith 
1119d763cef2SBarry Smith /*@C
1120f7ab8db6SBarry Smith   TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1121b5abc632SBarry Smith   where U_t = G(U,t), as well as the location to store the matrix.
1122d763cef2SBarry Smith 
1123c3339decSBarry Smith   Logically Collective
1124d763cef2SBarry Smith 
1125d763cef2SBarry Smith   Input Parameters:
1126bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1127195e9b02SBarry Smith . Amat - (approximate) location to store Jacobian matrix entries computed by `f`
1128195e9b02SBarry Smith . Pmat - matrix from which preconditioner is to be constructed (usually the same as `Amat`)
1129d763cef2SBarry Smith . f    - the Jacobian evaluation routine
1130195e9b02SBarry Smith - ctx  - [optional] user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1131d763cef2SBarry Smith 
1132bcf0153eSBarry Smith   Level: beginner
1133bcf0153eSBarry Smith 
11346cd88445SBarry Smith   Notes:
11356cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11366cd88445SBarry Smith 
113714d0ab18SJacob Faibussowitsch   The `TS` solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f()`
1138ca5f011dSBarry Smith   You should not assume the values are the same in the next call to f() as you set them in the previous call.
1139d763cef2SBarry Smith 
11408434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSRHSJacobianFn`, `SNESComputeJacobianDefaultColor()`,
11418434afd1SBarry Smith `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`, `TSRHSFunctionFn`, `TSIFunctionFn`
1142d763cef2SBarry Smith @*/
TSSetRHSJacobian(TS ts,Mat Amat,Mat Pmat,TSRHSJacobianFn * f,PetscCtx ctx)1143*2a8381b2SBarry Smith PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobianFn *f, PetscCtx ctx)
1144d71ae5a4SJacob Faibussowitsch {
1145089b2837SJed Brown   SNES           snes;
114624989b8cSPeter Brune   DM             dm;
11478434afd1SBarry Smith   TSIJacobianFn *ijacobian;
1148277b19d0SLisandro Dalcin 
1149d763cef2SBarry Smith   PetscFunctionBegin;
11500700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1151e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1152e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1153e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1154e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1155d763cef2SBarry Smith 
11569566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11579566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11589566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11599566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11601e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1161e5d3d808SBarry Smith   if (Amat) {
11629566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11639566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1164e5d3d808SBarry Smith     ts->Arhs = Amat;
11650e4ef248SJed Brown   }
1166e5d3d808SBarry Smith   if (Pmat) {
11679566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11689566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1169e5d3d808SBarry Smith     ts->Brhs = Pmat;
11700e4ef248SJed Brown   }
11713ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1172d763cef2SBarry Smith }
1173d763cef2SBarry Smith 
1174316643e7SJed Brown /*@C
1175b5abc632SBarry Smith   TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1176316643e7SJed Brown 
1177c3339decSBarry Smith   Logically Collective
1178316643e7SJed Brown 
1179316643e7SJed Brown   Input Parameters:
1180bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1181195e9b02SBarry Smith . r   - vector to hold the residual (or `NULL` to have it created internally)
1182316643e7SJed Brown . f   - the function evaluation routine
1183195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1184316643e7SJed Brown 
1185316643e7SJed Brown   Level: beginner
1186316643e7SJed Brown 
1187bcf0153eSBarry Smith   Note:
1188bcf0153eSBarry Smith   The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1189bcf0153eSBarry Smith 
11908434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIFunctionFn`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`,
119114d0ab18SJacob Faibussowitsch `TSSetIJacobian()`
1192316643e7SJed Brown @*/
TSSetIFunction(TS ts,Vec r,TSIFunctionFn * f,PetscCtx ctx)1193*2a8381b2SBarry Smith PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunctionFn *f, PetscCtx ctx)
1194d71ae5a4SJacob Faibussowitsch {
1195089b2837SJed Brown   SNES snes;
119651699248SLisandro Dalcin   Vec  ralloc = NULL;
119724989b8cSPeter Brune   DM   dm;
1198316643e7SJed Brown 
1199316643e7SJed Brown   PetscFunctionBegin;
12000700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
120151699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
120224989b8cSPeter Brune 
12039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12049566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
120524989b8cSPeter Brune 
12069566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
120751699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12089566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
120951699248SLisandro Dalcin     r = ralloc;
1210e856ceecSJed Brown   }
12119566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12129566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
12133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1214089b2837SJed Brown }
1215089b2837SJed Brown 
1216089b2837SJed Brown /*@C
1217a5b23f4aSJose E. Roman   TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1218089b2837SJed Brown 
1219089b2837SJed Brown   Not Collective
1220089b2837SJed Brown 
1221089b2837SJed Brown   Input Parameter:
1222bcf0153eSBarry Smith . ts - the `TS` context
1223089b2837SJed Brown 
1224d8d19677SJose E. Roman   Output Parameters:
1225195e9b02SBarry Smith + r    - vector to hold residual (or `NULL`)
1226195e9b02SBarry Smith . func - the function to compute residual (or `NULL`)
1227195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1228089b2837SJed Brown 
1229089b2837SJed Brown   Level: advanced
1230089b2837SJed Brown 
12311cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1232089b2837SJed Brown @*/
TSGetIFunction(TS ts,Vec * r,TSIFunctionFn ** func,PetscCtxRt ctx)1233*2a8381b2SBarry Smith PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunctionFn **func, PetscCtxRt ctx)
1234d71ae5a4SJacob Faibussowitsch {
1235089b2837SJed Brown   SNES snes;
123624989b8cSPeter Brune   DM   dm;
1237089b2837SJed Brown 
1238089b2837SJed Brown   PetscFunctionBegin;
1239089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12409566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12419566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12429566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12439566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
12443ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1245089b2837SJed Brown }
1246089b2837SJed Brown 
1247089b2837SJed Brown /*@C
1248dd8e379bSPierre Jolivet   TSGetRHSFunction - Returns the vector where the right-hand side is stored and the function/context to compute it.
1249089b2837SJed Brown 
1250089b2837SJed Brown   Not Collective
1251089b2837SJed Brown 
1252089b2837SJed Brown   Input Parameter:
1253bcf0153eSBarry Smith . ts - the `TS` context
1254089b2837SJed Brown 
1255d8d19677SJose E. Roman   Output Parameters:
1256dd8e379bSPierre Jolivet + r    - vector to hold computed right-hand side (or `NULL`)
1257dd8e379bSPierre Jolivet . func - the function to compute right-hand side (or `NULL`)
1258195e9b02SBarry Smith - ctx  - the function context (or `NULL`)
1259089b2837SJed Brown 
1260089b2837SJed Brown   Level: advanced
1261089b2837SJed Brown 
12621cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1263089b2837SJed Brown @*/
TSGetRHSFunction(TS ts,Vec * r,TSRHSFunctionFn ** func,PetscCtxRt ctx)1264*2a8381b2SBarry Smith PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunctionFn **func, PetscCtxRt ctx)
1265d71ae5a4SJacob Faibussowitsch {
1266089b2837SJed Brown   SNES snes;
126724989b8cSPeter Brune   DM   dm;
1268089b2837SJed Brown 
1269089b2837SJed Brown   PetscFunctionBegin;
1270089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12719566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12729566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12739566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12749566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
12753ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1276316643e7SJed Brown }
1277316643e7SJed Brown 
1278316643e7SJed Brown /*@C
1279a4f0a591SBarry Smith   TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1280bcf0153eSBarry Smith   provided with `TSSetIFunction()`.
1281316643e7SJed Brown 
1282c3339decSBarry Smith   Logically Collective
1283316643e7SJed Brown 
1284316643e7SJed Brown   Input Parameters:
1285bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
1286aaa8cc7dSPierre Jolivet . Amat - (approximate) matrix to store Jacobian entries computed by `f`
1287195e9b02SBarry Smith . Pmat - matrix used to compute preconditioner (usually the same as `Amat`)
1288316643e7SJed Brown . f    - the Jacobian evaluation routine
1289195e9b02SBarry Smith - ctx  - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1290316643e7SJed Brown 
1291bcf0153eSBarry Smith   Level: beginner
1292316643e7SJed Brown 
1293bcf0153eSBarry Smith   Notes:
1294195e9b02SBarry Smith   The matrices `Amat` and `Pmat` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1295bcf0153eSBarry Smith 
1296bcf0153eSBarry Smith   If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1297195e9b02SBarry Smith   space to `Amat` and the `KSP` solvers will automatically use that null space as needed during the solution process.
1298895c21f2SBarry Smith 
1299a4f0a591SBarry Smith   The matrix dF/dU + a*dF/dU_t you provide turns out to be
1300b5abc632SBarry Smith   the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1301a4f0a591SBarry Smith   The time integrator internally approximates U_t by W+a*U where the positive "shift"
1302a4f0a591SBarry Smith   a and vector W depend on the integration method, step size, and past states. For example with
1303a4f0a591SBarry Smith   the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1304a4f0a591SBarry Smith   W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1305a4f0a591SBarry Smith 
13066cd88445SBarry Smith   You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13076cd88445SBarry Smith 
1308195e9b02SBarry Smith   The TS solver may modify the nonzero structure and the entries of the matrices `Amat` and `Pmat` between the calls to `f`
1309195e9b02SBarry Smith   You should not assume the values are the same in the next call to `f` as you set them in the previous call.
1310ca5f011dSBarry Smith 
1311bc7fdbb5SPierre Jolivet   In case `TSSetRHSJacobian()` is also used in conjunction with a fully-implicit solver,
1312d469ad21SStefano Zampini   multilevel linear solvers, e.g. `PCMG`, will likely not work due to the way `TS` handles rhs matrices.
1313d469ad21SStefano Zampini 
13148434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSIJacobianFn`, `TSSetIFunction()`, `TSSetRHSJacobian()`,
131514d0ab18SJacob Faibussowitsch `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1316316643e7SJed Brown @*/
TSSetIJacobian(TS ts,Mat Amat,Mat Pmat,TSIJacobianFn * f,PetscCtx ctx)1317*2a8381b2SBarry Smith PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobianFn *f, PetscCtx ctx)
1318d71ae5a4SJacob Faibussowitsch {
1319089b2837SJed Brown   SNES snes;
132024989b8cSPeter Brune   DM   dm;
1321316643e7SJed Brown 
1322316643e7SJed Brown   PetscFunctionBegin;
13230700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1324e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1325e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1326e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1327e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
132824989b8cSPeter Brune 
13299566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13309566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
133124989b8cSPeter Brune 
13329566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13339566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
13343ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1335316643e7SJed Brown }
1336316643e7SJed Brown 
1337e1244c69SJed Brown /*@
13388434afd1SBarry Smith   TSRHSJacobianSetReuse - restore the RHS Jacobian before calling the user-provided `TSRHSJacobianFn` function again
1339e1244c69SJed Brown 
1340e1244c69SJed Brown   Logically Collective
1341e1244c69SJed Brown 
13424165533cSJose E. Roman   Input Parameters:
1343bcf0153eSBarry Smith + ts    - `TS` context obtained from `TSCreate()`
1344bcf0153eSBarry Smith - reuse - `PETSC_TRUE` if the RHS Jacobian
1345e1244c69SJed Brown 
1346e1244c69SJed Brown   Level: intermediate
1347e1244c69SJed Brown 
134814d0ab18SJacob Faibussowitsch   Notes:
134914d0ab18SJacob Faibussowitsch   Without this flag, `TS` will change the sign and shift the RHS Jacobian for a
135014d0ab18SJacob Faibussowitsch   finite-time-step implicit solve, in which case the user function will need to recompute the
135114d0ab18SJacob Faibussowitsch   entire Jacobian.  The `reuse `flag must be set if the evaluation function assumes that the
135214d0ab18SJacob Faibussowitsch   matrix entries have not been changed by the `TS`.
135314d0ab18SJacob Faibussowitsch 
13541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1355e1244c69SJed Brown @*/
TSRHSJacobianSetReuse(TS ts,PetscBool reuse)1356d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1357d71ae5a4SJacob Faibussowitsch {
1358e1244c69SJed Brown   PetscFunctionBegin;
1359e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
13603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1361e1244c69SJed Brown }
1362e1244c69SJed Brown 
1363efe9872eSLisandro Dalcin /*@C
1364efe9872eSLisandro Dalcin   TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1365efe9872eSLisandro Dalcin 
1366c3339decSBarry Smith   Logically Collective
1367efe9872eSLisandro Dalcin 
1368efe9872eSLisandro Dalcin   Input Parameters:
1369bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1370195e9b02SBarry Smith . F   - vector to hold the residual (or `NULL` to have it created internally)
1371efe9872eSLisandro Dalcin . fun - the function evaluation routine
1372195e9b02SBarry Smith - ctx - user-defined context for private data for the function evaluation routine (may be `NULL`)
1373efe9872eSLisandro Dalcin 
1374efe9872eSLisandro Dalcin   Level: beginner
1375efe9872eSLisandro Dalcin 
13768434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2FunctionFn`, `TSSetI2Jacobian()`, `TSSetIFunction()`,
137714d0ab18SJacob Faibussowitsch `TSCreate()`, `TSSetRHSFunction()`
1378efe9872eSLisandro Dalcin @*/
TSSetI2Function(TS ts,Vec F,TSI2FunctionFn * fun,PetscCtx ctx)1379*2a8381b2SBarry Smith PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2FunctionFn *fun, PetscCtx ctx)
1380d71ae5a4SJacob Faibussowitsch {
1381efe9872eSLisandro Dalcin   DM dm;
1382efe9872eSLisandro Dalcin 
1383efe9872eSLisandro Dalcin   PetscFunctionBegin;
1384efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1385efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
13869566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
13879566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13889566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
13893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1390efe9872eSLisandro Dalcin }
1391efe9872eSLisandro Dalcin 
1392efe9872eSLisandro Dalcin /*@C
1393a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1394efe9872eSLisandro Dalcin 
1395efe9872eSLisandro Dalcin   Not Collective
1396efe9872eSLisandro Dalcin 
1397efe9872eSLisandro Dalcin   Input Parameter:
1398bcf0153eSBarry Smith . ts - the `TS` context
1399efe9872eSLisandro Dalcin 
1400d8d19677SJose E. Roman   Output Parameters:
1401195e9b02SBarry Smith + r   - vector to hold residual (or `NULL`)
1402195e9b02SBarry Smith . fun - the function to compute residual (or `NULL`)
1403195e9b02SBarry Smith - ctx - the function context (or `NULL`)
1404efe9872eSLisandro Dalcin 
1405efe9872eSLisandro Dalcin   Level: advanced
1406efe9872eSLisandro Dalcin 
14071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1408efe9872eSLisandro Dalcin @*/
TSGetI2Function(TS ts,Vec * r,TSI2FunctionFn ** fun,PetscCtxRt ctx)1409*2a8381b2SBarry Smith PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2FunctionFn **fun, PetscCtxRt ctx)
1410d71ae5a4SJacob Faibussowitsch {
1411efe9872eSLisandro Dalcin   SNES snes;
1412efe9872eSLisandro Dalcin   DM   dm;
1413efe9872eSLisandro Dalcin 
1414efe9872eSLisandro Dalcin   PetscFunctionBegin;
1415efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14169566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14179566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14189566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14199566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
14203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1421efe9872eSLisandro Dalcin }
1422efe9872eSLisandro Dalcin 
1423efe9872eSLisandro Dalcin /*@C
1424bc77d74cSLisandro Dalcin   TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1425bcf0153eSBarry Smith   where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1426efe9872eSLisandro Dalcin 
1427c3339decSBarry Smith   Logically Collective
1428efe9872eSLisandro Dalcin 
1429efe9872eSLisandro Dalcin   Input Parameters:
1430bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
1431195e9b02SBarry Smith . J   - matrix to hold the Jacobian values
1432195e9b02SBarry Smith . P   - matrix for constructing the preconditioner (may be same as `J`)
14338434afd1SBarry Smith . jac - the Jacobian evaluation routine, see `TSI2JacobianFn` for the calling sequence
1434195e9b02SBarry Smith - ctx - user-defined context for private data for the Jacobian evaluation routine (may be `NULL`)
1435efe9872eSLisandro Dalcin 
1436bcf0153eSBarry Smith   Level: beginner
1437bcf0153eSBarry Smith 
1438efe9872eSLisandro Dalcin   Notes:
1439195e9b02SBarry Smith   The matrices `J` and `P` are exactly the matrices that are used by `SNES` for the nonlinear solve.
1440efe9872eSLisandro Dalcin 
1441efe9872eSLisandro Dalcin   The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1442efe9872eSLisandro 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.
1443efe9872eSLisandro Dalcin   The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1444bc77d74cSLisandro Dalcin   parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1445efe9872eSLisandro Dalcin 
14468434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSI2JacobianFn`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1447efe9872eSLisandro Dalcin @*/
TSSetI2Jacobian(TS ts,Mat J,Mat P,TSI2JacobianFn * jac,PetscCtx ctx)1448*2a8381b2SBarry Smith PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2JacobianFn *jac, PetscCtx ctx)
1449d71ae5a4SJacob Faibussowitsch {
1450efe9872eSLisandro Dalcin   DM dm;
1451efe9872eSLisandro Dalcin 
1452efe9872eSLisandro Dalcin   PetscFunctionBegin;
1453efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1454efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1455efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
14569566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
14579566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14589566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
14593ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1460efe9872eSLisandro Dalcin }
1461efe9872eSLisandro Dalcin 
1462efe9872eSLisandro Dalcin /*@C
1463efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1464efe9872eSLisandro Dalcin 
1465bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1466efe9872eSLisandro Dalcin 
1467efe9872eSLisandro Dalcin   Input Parameter:
1468bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
1469efe9872eSLisandro Dalcin 
1470efe9872eSLisandro Dalcin   Output Parameters:
1471efe9872eSLisandro Dalcin + J   - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1472195e9b02SBarry Smith . P   - The matrix from which the preconditioner is constructed, often the same as `J`
1473efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1474efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1475efe9872eSLisandro Dalcin 
1476bcf0153eSBarry Smith   Level: advanced
1477bcf0153eSBarry Smith 
1478195e9b02SBarry Smith   Note:
1479195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
1480efe9872eSLisandro Dalcin 
14811cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1482efe9872eSLisandro Dalcin @*/
TSGetI2Jacobian(TS ts,Mat * J,Mat * P,TSI2JacobianFn ** jac,PetscCtxRt ctx)1483*2a8381b2SBarry Smith PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2JacobianFn **jac, PetscCtxRt ctx)
1484d71ae5a4SJacob Faibussowitsch {
1485efe9872eSLisandro Dalcin   SNES snes;
1486efe9872eSLisandro Dalcin   DM   dm;
1487efe9872eSLisandro Dalcin 
1488efe9872eSLisandro Dalcin   PetscFunctionBegin;
14899566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14909566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
14919566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
14929566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14939566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
14943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1495efe9872eSLisandro Dalcin }
1496efe9872eSLisandro Dalcin 
1497efe9872eSLisandro Dalcin /*@
1498efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1499efe9872eSLisandro Dalcin 
1500c3339decSBarry Smith   Collective
1501efe9872eSLisandro Dalcin 
1502efe9872eSLisandro Dalcin   Input Parameters:
1503bcf0153eSBarry Smith + ts - the `TS` context
1504efe9872eSLisandro Dalcin . t  - current time
1505efe9872eSLisandro Dalcin . U  - state vector
1506efe9872eSLisandro Dalcin . V  - time derivative of state vector (U_t)
1507efe9872eSLisandro Dalcin - A  - second time derivative of state vector (U_tt)
1508efe9872eSLisandro Dalcin 
1509efe9872eSLisandro Dalcin   Output Parameter:
1510efe9872eSLisandro Dalcin . F - the residual vector
1511efe9872eSLisandro Dalcin 
1512bcf0153eSBarry Smith   Level: developer
1513bcf0153eSBarry Smith 
1514efe9872eSLisandro Dalcin   Note:
1515efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1516efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1517efe9872eSLisandro Dalcin 
15181cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1519efe9872eSLisandro Dalcin @*/
TSComputeI2Function(TS ts,PetscReal t,Vec U,Vec V,Vec A,Vec F)1520d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1521d71ae5a4SJacob Faibussowitsch {
1522efe9872eSLisandro Dalcin   DM               dm;
15238434afd1SBarry Smith   TSI2FunctionFn  *I2Function;
1524efe9872eSLisandro Dalcin   void            *ctx;
15258434afd1SBarry Smith   TSRHSFunctionFn *rhsfunction;
1526efe9872eSLisandro Dalcin 
1527efe9872eSLisandro Dalcin   PetscFunctionBegin;
1528efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1529efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1530efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1531efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1532efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1533efe9872eSLisandro Dalcin 
15349566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15359566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15369566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1537efe9872eSLisandro Dalcin 
1538efe9872eSLisandro Dalcin   if (!I2Function) {
15399566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
15403ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1541efe9872eSLisandro Dalcin   }
1542efe9872eSLisandro Dalcin 
1543da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_FunctionEval, U, ts, V, F));
1544efe9872eSLisandro Dalcin 
1545792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1546efe9872eSLisandro Dalcin 
1547efe9872eSLisandro Dalcin   if (rhsfunction) {
1548efe9872eSLisandro Dalcin     Vec Frhs;
15498af0501fSStefano Zampini 
15508af0501fSStefano Zampini     PetscCall(DMGetGlobalVector(dm, &Frhs));
15519566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15529566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
15538af0501fSStefano Zampini     PetscCall(DMRestoreGlobalVector(dm, &Frhs));
1554efe9872eSLisandro Dalcin   }
1555efe9872eSLisandro Dalcin 
1556da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_FunctionEval, U, ts, V, F));
15573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1558efe9872eSLisandro Dalcin }
1559efe9872eSLisandro Dalcin 
1560efe9872eSLisandro Dalcin /*@
1561efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1562efe9872eSLisandro Dalcin 
1563c3339decSBarry Smith   Collective
1564efe9872eSLisandro Dalcin 
1565efe9872eSLisandro Dalcin   Input Parameters:
1566bcf0153eSBarry Smith + ts     - the `TS` context
1567efe9872eSLisandro Dalcin . t      - current timestep
1568efe9872eSLisandro Dalcin . U      - state vector
1569efe9872eSLisandro Dalcin . V      - time derivative of state vector
1570efe9872eSLisandro Dalcin . A      - second time derivative of state vector
1571efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1572efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1573efe9872eSLisandro Dalcin 
1574efe9872eSLisandro Dalcin   Output Parameters:
1575efe9872eSLisandro Dalcin + J - Jacobian matrix
15767addb90fSBarry Smith - P - optional matrix used to construct the preconditioner
1577efe9872eSLisandro Dalcin 
1578bcf0153eSBarry Smith   Level: developer
1579bcf0153eSBarry Smith 
1580efe9872eSLisandro Dalcin   Notes:
15817addb90fSBarry Smith   If $F(t,U,V,A) = 0$ is the DAE, the required Jacobian is
1582efe9872eSLisandro Dalcin 
15837addb90fSBarry Smith $$
1584efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
15857addb90fSBarry Smith $$
1586efe9872eSLisandro Dalcin 
1587efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
15887addb90fSBarry Smith   is used internally within the ODE integrators.
1589efe9872eSLisandro Dalcin 
15901cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetI2Jacobian()`
1591efe9872eSLisandro Dalcin @*/
TSComputeI2Jacobian(TS ts,PetscReal t,Vec U,Vec V,Vec A,PetscReal shiftV,PetscReal shiftA,Mat J,Mat P)1592d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1593d71ae5a4SJacob Faibussowitsch {
1594efe9872eSLisandro Dalcin   DM               dm;
15958434afd1SBarry Smith   TSI2JacobianFn  *I2Jacobian;
1596efe9872eSLisandro Dalcin   void            *ctx;
15978434afd1SBarry Smith   TSRHSJacobianFn *rhsjacobian;
1598efe9872eSLisandro Dalcin 
1599efe9872eSLisandro Dalcin   PetscFunctionBegin;
1600efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1601efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1602efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1603efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1604efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1605efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1606efe9872eSLisandro Dalcin 
16079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16089566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16099566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1610efe9872eSLisandro Dalcin 
1611efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16129566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
16133ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
1614efe9872eSLisandro Dalcin   }
1615efe9872eSLisandro Dalcin 
1616da023ba9SStefano Zampini   PetscCall(PetscLogEventBegin(TS_JacobianEval, U, ts, J, P));
1617792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1618efe9872eSLisandro Dalcin   if (rhsjacobian) {
1619d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16209566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16219566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16229566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16239566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1624efe9872eSLisandro Dalcin   }
1625efe9872eSLisandro Dalcin 
1626da023ba9SStefano Zampini   PetscCall(PetscLogEventEnd(TS_JacobianEval, U, ts, J, P));
16273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1628efe9872eSLisandro Dalcin }
1629efe9872eSLisandro Dalcin 
1630438f35afSJed Brown /*@C
1631438f35afSJed Brown   TSSetTransientVariable - sets function to transform from state to transient variables
1632438f35afSJed Brown 
1633438f35afSJed Brown   Logically Collective
1634438f35afSJed Brown 
16354165533cSJose E. Roman   Input Parameters:
1636438f35afSJed Brown + ts   - time stepping context on which to change the transient variable
16378434afd1SBarry Smith . tvar - a function that transforms to transient variables, see `TSTransientVariableFn` for the calling sequence
1638438f35afSJed Brown - ctx  - a context for tvar
1639438f35afSJed Brown 
1640438f35afSJed Brown   Level: advanced
1641438f35afSJed Brown 
1642438f35afSJed Brown   Notes:
1643bcf0153eSBarry Smith   This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1644438f35afSJed Brown   can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1645438f35afSJed Brown   well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1646438f35afSJed Brown   C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1647438f35afSJed Brown   evaluated via the chain rule, as in
1648195e9b02SBarry Smith .vb
1649438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1650195e9b02SBarry Smith .ve
1651438f35afSJed Brown 
16528434afd1SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSTransientVariableFn`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1653438f35afSJed Brown @*/
TSSetTransientVariable(TS ts,TSTransientVariableFn * tvar,PetscCtx ctx)1654*2a8381b2SBarry Smith PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariableFn *tvar, PetscCtx ctx)
1655d71ae5a4SJacob Faibussowitsch {
1656438f35afSJed Brown   DM dm;
1657438f35afSJed Brown 
1658438f35afSJed Brown   PetscFunctionBegin;
1659438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
16609566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16619566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
16623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1663438f35afSJed Brown }
1664438f35afSJed Brown 
1665efe9872eSLisandro Dalcin /*@
1666e3c11fc1SJed Brown   TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1667e3c11fc1SJed Brown 
1668e3c11fc1SJed Brown   Logically Collective
1669e3c11fc1SJed Brown 
1670e3c11fc1SJed Brown   Input Parameters:
1671e3c11fc1SJed Brown + ts - TS on which to compute
1672e3c11fc1SJed Brown - U  - state vector to be transformed to transient variables
1673e3c11fc1SJed Brown 
16742fe279fdSBarry Smith   Output Parameter:
1675e3c11fc1SJed Brown . C - transient (conservative) variable
1676e3c11fc1SJed Brown 
1677e3c11fc1SJed Brown   Level: developer
1678e3c11fc1SJed Brown 
1679b43aa488SJacob Faibussowitsch   Developer Notes:
1680195e9b02SBarry Smith   If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = `NULL` is allowed.
1681bcf0153eSBarry Smith   This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1682bcf0153eSBarry Smith   being used.
1683bcf0153eSBarry Smith 
16841cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1685e3c11fc1SJed Brown @*/
TSComputeTransientVariable(TS ts,Vec U,Vec C)1686d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1687d71ae5a4SJacob Faibussowitsch {
1688e3c11fc1SJed Brown   DM   dm;
1689e3c11fc1SJed Brown   DMTS dmts;
1690e3c11fc1SJed Brown 
1691e3c11fc1SJed Brown   PetscFunctionBegin;
1692e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1693e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
16949566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16959566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1696e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1697e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
16989566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1699e3c11fc1SJed Brown   }
17003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1701e3c11fc1SJed Brown }
1702e3c11fc1SJed Brown 
1703e3c11fc1SJed Brown /*@
1704e3c11fc1SJed Brown   TSHasTransientVariable - determine whether transient variables have been set
1705e3c11fc1SJed Brown 
1706e3c11fc1SJed Brown   Logically Collective
1707e3c11fc1SJed Brown 
17082fe279fdSBarry Smith   Input Parameter:
1709195e9b02SBarry Smith . ts - `TS` on which to compute
1710e3c11fc1SJed Brown 
17112fe279fdSBarry Smith   Output Parameter:
1712bcf0153eSBarry Smith . has - `PETSC_TRUE` if transient variables have been set
1713e3c11fc1SJed Brown 
1714e3c11fc1SJed Brown   Level: developer
1715e3c11fc1SJed Brown 
17161cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1717e3c11fc1SJed Brown @*/
TSHasTransientVariable(TS ts,PetscBool * has)1718d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1719d71ae5a4SJacob Faibussowitsch {
1720e3c11fc1SJed Brown   DM   dm;
1721e3c11fc1SJed Brown   DMTS dmts;
1722e3c11fc1SJed Brown 
1723e3c11fc1SJed Brown   PetscFunctionBegin;
1724e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17269566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1727e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
17283ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1729e3c11fc1SJed Brown }
1730e3c11fc1SJed Brown 
1731e3c11fc1SJed Brown /*@
1732efe9872eSLisandro Dalcin   TS2SetSolution - Sets the initial solution and time derivative vectors
1733bcf0153eSBarry Smith   for use by the `TS` routines handling second order equations.
1734efe9872eSLisandro Dalcin 
1735c3339decSBarry Smith   Logically Collective
1736efe9872eSLisandro Dalcin 
1737efe9872eSLisandro Dalcin   Input Parameters:
1738bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
1739efe9872eSLisandro Dalcin . u  - the solution vector
1740efe9872eSLisandro Dalcin - v  - the time derivative vector
1741efe9872eSLisandro Dalcin 
1742efe9872eSLisandro Dalcin   Level: beginner
1743efe9872eSLisandro Dalcin 
17441cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
1745efe9872eSLisandro Dalcin @*/
TS2SetSolution(TS ts,Vec u,Vec v)1746d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1747d71ae5a4SJacob Faibussowitsch {
1748efe9872eSLisandro Dalcin   PetscFunctionBegin;
1749efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1750efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1751efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
17529566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
17539566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
17549566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1755efe9872eSLisandro Dalcin   ts->vec_dot = v;
17563ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1757efe9872eSLisandro Dalcin }
1758efe9872eSLisandro Dalcin 
1759efe9872eSLisandro Dalcin /*@
1760efe9872eSLisandro Dalcin   TS2GetSolution - Returns the solution and time derivative at the present timestep
176114d0ab18SJacob Faibussowitsch   for second order equations.
1762efe9872eSLisandro Dalcin 
176314d0ab18SJacob Faibussowitsch   Not Collective
1764efe9872eSLisandro Dalcin 
1765efe9872eSLisandro Dalcin   Input Parameter:
1766bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
1767efe9872eSLisandro Dalcin 
1768d8d19677SJose E. Roman   Output Parameters:
1769efe9872eSLisandro Dalcin + u - the vector containing the solution
1770efe9872eSLisandro Dalcin - v - the vector containing the time derivative
1771efe9872eSLisandro Dalcin 
1772efe9872eSLisandro Dalcin   Level: intermediate
1773efe9872eSLisandro Dalcin 
177414d0ab18SJacob Faibussowitsch   Notes:
177514d0ab18SJacob Faibussowitsch   It is valid to call this routine inside the function
177614d0ab18SJacob Faibussowitsch   that you are evaluating in order to move to the new timestep. This vector not
177714d0ab18SJacob Faibussowitsch   changed until the solution at the next timestep has been calculated.
177814d0ab18SJacob Faibussowitsch 
17791cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1780efe9872eSLisandro Dalcin @*/
TS2GetSolution(TS ts,Vec * u,Vec * v)1781d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1782d71ae5a4SJacob Faibussowitsch {
1783efe9872eSLisandro Dalcin   PetscFunctionBegin;
1784efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17854f572ea9SToby Isaac   if (u) PetscAssertPointer(u, 2);
17864f572ea9SToby Isaac   if (v) PetscAssertPointer(v, 3);
1787efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1788efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
17893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1790efe9872eSLisandro Dalcin }
1791efe9872eSLisandro Dalcin 
1792ffeef943SBarry Smith /*@
1793bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
179455849f57SBarry Smith 
1795c3339decSBarry Smith   Collective
179655849f57SBarry Smith 
179755849f57SBarry Smith   Input Parameters:
1798b43aa488SJacob Faibussowitsch + ts     - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1799bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1800bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
180155849f57SBarry Smith 
180255849f57SBarry Smith   Level: intermediate
180355849f57SBarry Smith 
1804bcf0153eSBarry Smith   Note:
1805bcf0153eSBarry Smith   The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
180655849f57SBarry Smith 
18071cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
180855849f57SBarry Smith @*/
TSLoad(TS ts,PetscViewer viewer)1809d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1810d71ae5a4SJacob Faibussowitsch {
181155849f57SBarry Smith   PetscBool isbinary;
181255849f57SBarry Smith   PetscInt  classid;
181355849f57SBarry Smith   char      type[256];
18142d53ad75SBarry Smith   DMTS      sdm;
1815ad6bc421SBarry Smith   DM        dm;
181655849f57SBarry Smith 
181755849f57SBarry Smith   PetscFunctionBegin;
1818f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
181955849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18209566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18213c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
182255849f57SBarry Smith 
18239566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18243c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18259566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18269566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1827dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18289566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18299566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18309566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18319566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18329566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18339566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18349566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
18353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
183655849f57SBarry Smith }
183755849f57SBarry Smith 
18389804daf3SBarry Smith #include <petscdraw.h>
1839e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1840e04113cfSBarry Smith   #include <petscviewersaws.h>
1841f05ece33SBarry Smith #endif
1842fe2efc57SMark 
1843ffeef943SBarry Smith /*@
1844bcf0153eSBarry Smith   TSViewFromOptions - View a `TS` based on values in the options database
1845fe2efc57SMark 
1846c3339decSBarry Smith   Collective
1847fe2efc57SMark 
1848fe2efc57SMark   Input Parameters:
1849bcf0153eSBarry Smith + ts   - the `TS` context
1850bcf0153eSBarry Smith . obj  - Optional object that provides the prefix for the options database keys
1851bcf0153eSBarry Smith - name - command line option string to be passed by user
1852fe2efc57SMark 
1853fe2efc57SMark   Level: intermediate
1854bcf0153eSBarry Smith 
18551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1856fe2efc57SMark @*/
TSViewFromOptions(TS ts,PetscObject obj,const char name[])1857bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1858d71ae5a4SJacob Faibussowitsch {
1859fe2efc57SMark   PetscFunctionBegin;
1860bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1861bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
18623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
1863fe2efc57SMark }
1864fe2efc57SMark 
1865ffeef943SBarry Smith /*@
1866bcf0153eSBarry Smith   TSView - Prints the `TS` data structure.
1867d763cef2SBarry Smith 
1868c3339decSBarry Smith   Collective
1869d763cef2SBarry Smith 
1870d763cef2SBarry Smith   Input Parameters:
1871bcf0153eSBarry Smith + ts     - the `TS` context obtained from `TSCreate()`
1872d763cef2SBarry Smith - viewer - visualization context
1873d763cef2SBarry Smith 
1874d763cef2SBarry Smith   Options Database Key:
1875bcf0153eSBarry Smith . -ts_view - calls `TSView()` at end of `TSStep()`
1876bcf0153eSBarry Smith 
1877bcf0153eSBarry Smith   Level: beginner
1878d763cef2SBarry Smith 
1879d763cef2SBarry Smith   Notes:
1880d763cef2SBarry Smith   The available visualization contexts include
1881bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1882bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1883d763cef2SBarry Smith   output where only the first processor opens
1884d763cef2SBarry Smith   the file.  All other processors send their
1885d763cef2SBarry Smith   data to the first processor to print.
1886d763cef2SBarry Smith 
1887d763cef2SBarry Smith   The user can open an alternative visualization context with
1888bcf0153eSBarry Smith   `PetscViewerASCIIOpen()` - output to a specified file.
1889d763cef2SBarry Smith 
1890bcf0153eSBarry Smith   In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1891595c91d4SBarry Smith 
1892188af4bfSBarry Smith   The "initial time step" displayed is the default time step from `TSCreate()` or that set with `TSSetTimeStep()` or `-ts_time_step`
1893188af4bfSBarry Smith 
18941cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1895d763cef2SBarry Smith @*/
TSView(TS ts,PetscViewer viewer)1896d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1897d71ae5a4SJacob Faibussowitsch {
189819fd82e9SBarry Smith   TSType    type;
18999f196a02SMartin Diehl   PetscBool isascii, isstring, issundials, isbinary, isdraw;
19002d53ad75SBarry Smith   DMTS      sdm;
1901e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1902536b137fSBarry Smith   PetscBool issaws;
1903f05ece33SBarry Smith #endif
1904d763cef2SBarry Smith 
1905d763cef2SBarry Smith   PetscFunctionBegin;
19060700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19071e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19080700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1909c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1910fd16b177SBarry Smith 
19119f196a02SMartin Diehl   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &isascii));
19129566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19139566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19149566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1915e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19169566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1917f05ece33SBarry Smith #endif
19189f196a02SMartin Diehl   if (isascii) {
19199566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1920efd4aadfSBarry Smith     if (ts->ops->view) {
19219566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1922dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19239566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1924efd4aadfSBarry Smith     }
1925188af4bfSBarry Smith     PetscCall(PetscViewerASCIIPrintf(viewer, "  initial time step=%g\n", (double)ts->initial_time_step));
19261690c2aeSBarry Smith     if (ts->max_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19278e562f8dSJames Wright     if (ts->run_steps < PETSC_INT_MAX) PetscCall(PetscViewerASCIIPrintf(viewer, "  run steps=%" PetscInt_FMT "\n", ts->run_steps));
19281e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
1929188af4bfSBarry Smith     if (ts->max_reject != PETSC_UNLIMITED) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum number of step rejections=%" PetscInt_FMT "\n", ts->max_reject));
1930188af4bfSBarry Smith     if (ts->max_snes_failures != PETSC_UNLIMITED) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum number of SNES failures allowed=%" PetscInt_FMT "\n", ts->max_snes_failures));
19311e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19321e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19331e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19341e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1935efd4aadfSBarry Smith     if (ts->usessnes) {
1936efd4aadfSBarry Smith       PetscBool lin;
19371e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
193863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19399566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
194063a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1941efd4aadfSBarry Smith     }
194263a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19431e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19441e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19451e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "using vector of absolute error tolerances\n"));
19461e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "using absolute error tolerance of %g\n", (double)ts->atol));
19479566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19489566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19499566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19500f5bd95cSBarry Smith   } else if (isstring) {
19519566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19529566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1953dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
195455849f57SBarry Smith   } else if (isbinary) {
195555849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
195655849f57SBarry Smith     MPI_Comm    comm;
195755849f57SBarry Smith     PetscMPIInt rank;
195855849f57SBarry Smith     char        type[256];
195955849f57SBarry Smith 
19609566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
19619566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
1962dd400576SPatrick Sanan     if (rank == 0) {
19639566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
19649566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
19659566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
196655849f57SBarry Smith     }
1967dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19689566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19699566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
19709566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
19719566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
19729566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
19732b0a91c0SBarry Smith   } else if (isdraw) {
19742b0a91c0SBarry Smith     PetscDraw draw;
19752b0a91c0SBarry Smith     char      str[36];
197689fd9fafSBarry Smith     PetscReal x, y, bottom, h;
19772b0a91c0SBarry Smith 
19789566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
19799566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
1980c6a7a370SJeremy L Thompson     PetscCall(PetscStrncpy(str, "TS: ", sizeof(str)));
1981c6a7a370SJeremy L Thompson     PetscCall(PetscStrlcat(str, ((PetscObject)ts)->type_name, sizeof(str)));
19829566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
198389fd9fafSBarry Smith     bottom = y - h;
19849566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
1985dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
19869566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
19879566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
19889566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
1989e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1990536b137fSBarry Smith   } else if (issaws) {
1991d45a07a7SBarry Smith     PetscMPIInt rank;
19922657e9d9SBarry Smith     const char *name;
19932657e9d9SBarry Smith 
19949566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
19959566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
1996dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
1997d45a07a7SBarry Smith       char dir[1024];
1998d45a07a7SBarry Smith 
19999566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
20009566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2001792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
20029566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2003792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
2004d763cef2SBarry Smith     }
2005dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
2006f05ece33SBarry Smith #endif
2007f05ece33SBarry Smith   }
200836a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20099566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20109566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20119566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
201236a9e3b9SBarry Smith   }
20139566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20149566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2015f05ece33SBarry Smith 
20169566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20179f196a02SMartin Diehl   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &issundials));
20189566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
20193ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2020d763cef2SBarry Smith }
2021d763cef2SBarry Smith 
2022b07ff414SBarry Smith /*@
2023ce78bad3SBarry Smith   TSSetApplicationContext - Sets an optional user-defined context for the timesteppers that may be accessed, for example inside the user provided
2024ce78bad3SBarry Smith   `TS` callbacks with `TSGetApplicationContext()`
2025d763cef2SBarry Smith 
2026c3339decSBarry Smith   Logically Collective
2027d763cef2SBarry Smith 
2028d763cef2SBarry Smith   Input Parameters:
2029bcf0153eSBarry Smith + ts  - the `TS` context obtained from `TSCreate()`
203049abdd8aSBarry Smith - ctx - user context
2031daf670e6SBarry Smith 
2032d763cef2SBarry Smith   Level: intermediate
2033d763cef2SBarry Smith 
2034ce78bad3SBarry Smith   Fortran Note:
2035ce78bad3SBarry Smith   This only works when `ctx` is a Fortran derived type (it cannot be a `PetscObject`), we recommend writing a Fortran interface definition for this
2036ce78bad3SBarry Smith   function that tells the Fortran compiler the derived data type that is passed in as the `ctx` argument. See `TSGetApplicationContext()` for
2037ce78bad3SBarry Smith   an example.
2038bcf0153eSBarry Smith 
20391cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetApplicationContext()`
2040d763cef2SBarry Smith @*/
TSSetApplicationContext(TS ts,PetscCtx ctx)2041*2a8381b2SBarry Smith PetscErrorCode TSSetApplicationContext(TS ts, PetscCtx ctx)
2042d71ae5a4SJacob Faibussowitsch {
2043d763cef2SBarry Smith   PetscFunctionBegin;
20440700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
204549abdd8aSBarry Smith   ts->ctx = ctx;
20463ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2047d763cef2SBarry Smith }
2048d763cef2SBarry Smith 
2049b07ff414SBarry Smith /*@
2050d763cef2SBarry Smith   TSGetApplicationContext - Gets the user-defined context for the
2051bcf0153eSBarry Smith   timestepper that was set with `TSSetApplicationContext()`
2052d763cef2SBarry Smith 
2053d763cef2SBarry Smith   Not Collective
2054d763cef2SBarry Smith 
2055d763cef2SBarry Smith   Input Parameter:
2056bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2057d763cef2SBarry Smith 
2058d763cef2SBarry Smith   Output Parameter:
2059ce78bad3SBarry Smith . ctx - a pointer to the user context
2060d763cef2SBarry Smith 
2061bcf0153eSBarry Smith   Level: intermediate
2062bcf0153eSBarry Smith 
2063b43aa488SJacob Faibussowitsch   Fortran Notes:
2064*2a8381b2SBarry Smith   This only works when the context is a Fortran derived type or a `PetscObject`. Declare `ctx` with
2065ce78bad3SBarry Smith .vb
2066ce78bad3SBarry Smith   type(tUsertype), pointer :: ctx
2067ce78bad3SBarry Smith .ve
2068daf670e6SBarry Smith 
20691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetApplicationContext()`
2070d763cef2SBarry Smith @*/
TSGetApplicationContext(TS ts,PetscCtxRt ctx)2071*2a8381b2SBarry Smith PetscErrorCode TSGetApplicationContext(TS ts, PetscCtxRt ctx)
2072d71ae5a4SJacob Faibussowitsch {
2073d763cef2SBarry Smith   PetscFunctionBegin;
20740700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
207549abdd8aSBarry Smith   *(void **)ctx = ts->ctx;
20763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2077d763cef2SBarry Smith }
2078d763cef2SBarry Smith 
2079d763cef2SBarry Smith /*@
2080bcf0153eSBarry Smith   TSGetStepNumber - Gets the number of time steps completed.
2081d763cef2SBarry Smith 
2082d763cef2SBarry Smith   Not Collective
2083d763cef2SBarry Smith 
2084d763cef2SBarry Smith   Input Parameter:
2085bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2086d763cef2SBarry Smith 
2087d763cef2SBarry Smith   Output Parameter:
208880275a0aSLisandro Dalcin . steps - number of steps completed so far
2089d763cef2SBarry Smith 
2090d763cef2SBarry Smith   Level: intermediate
2091d763cef2SBarry Smith 
20921cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2093d763cef2SBarry Smith @*/
TSGetStepNumber(TS ts,PetscInt * steps)2094d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2095d71ae5a4SJacob Faibussowitsch {
2096d763cef2SBarry Smith   PetscFunctionBegin;
20970700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
20984f572ea9SToby Isaac   PetscAssertPointer(steps, 2);
209980275a0aSLisandro Dalcin   *steps = ts->steps;
21003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
210180275a0aSLisandro Dalcin }
210280275a0aSLisandro Dalcin 
210380275a0aSLisandro Dalcin /*@
210480275a0aSLisandro Dalcin   TSSetStepNumber - Sets the number of steps completed.
210580275a0aSLisandro Dalcin 
2106c3339decSBarry Smith   Logically Collective
210780275a0aSLisandro Dalcin 
210880275a0aSLisandro Dalcin   Input Parameters:
2109bcf0153eSBarry Smith + ts    - the `TS` context
211080275a0aSLisandro Dalcin - steps - number of steps completed so far
211180275a0aSLisandro Dalcin 
2112bcf0153eSBarry Smith   Level: developer
2113bcf0153eSBarry Smith 
2114bcf0153eSBarry Smith   Note:
2115bcf0153eSBarry Smith   For most uses of the `TS` solvers the user need not explicitly call
2116bcf0153eSBarry Smith   `TSSetStepNumber()`, as the step counter is appropriately updated in
2117bcf0153eSBarry Smith   `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
211880275a0aSLisandro Dalcin   reinitialize timestepping by setting the step counter to zero (and time
211980275a0aSLisandro Dalcin   to the initial time) to solve a similar problem with different initial
212080275a0aSLisandro Dalcin   conditions or parameters. Other possible use case is to continue
2121195e9b02SBarry Smith   timestepping from a previously interrupted run in such a way that `TS`
212280275a0aSLisandro Dalcin   monitors will be called with a initial nonzero step counter.
212380275a0aSLisandro Dalcin 
21241cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
212580275a0aSLisandro Dalcin @*/
TSSetStepNumber(TS ts,PetscInt steps)2126d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2127d71ae5a4SJacob Faibussowitsch {
212880275a0aSLisandro Dalcin   PetscFunctionBegin;
212980275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
213080275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21313c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
213280275a0aSLisandro Dalcin   ts->steps = steps;
21333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2134d763cef2SBarry Smith }
2135d763cef2SBarry Smith 
2136d763cef2SBarry Smith /*@
2137188af4bfSBarry Smith   TSSetTimeStep - Allows one to reset the timestep at any time.
2138d763cef2SBarry Smith 
2139c3339decSBarry Smith   Logically Collective
2140d763cef2SBarry Smith 
2141d763cef2SBarry Smith   Input Parameters:
2142bcf0153eSBarry Smith + ts        - the `TS` context obtained from `TSCreate()`
2143d763cef2SBarry Smith - time_step - the size of the timestep
2144d763cef2SBarry Smith 
2145188af4bfSBarry Smith   Options Database Key:
2146188af4bfSBarry Smith . -ts_time_step <dt> - provide the initial time step
2147188af4bfSBarry Smith 
2148d763cef2SBarry Smith   Level: intermediate
2149d763cef2SBarry Smith 
2150188af4bfSBarry Smith   Notes:
2151188af4bfSBarry Smith   This is only a suggestion, the actual initial time step used may differ
2152188af4bfSBarry Smith 
2153188af4bfSBarry Smith   If this is called after `TSSetUp()`, it will not change the initial time step value printed by `TSView()`
2154188af4bfSBarry Smith 
21551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2156d763cef2SBarry Smith @*/
TSSetTimeStep(TS ts,PetscReal time_step)2157d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2158d71ae5a4SJacob Faibussowitsch {
2159d763cef2SBarry Smith   PetscFunctionBegin;
21600700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2161c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2162d763cef2SBarry Smith   ts->time_step = time_step;
2163188af4bfSBarry Smith   if (ts->setupcalled == PETSC_FALSE) ts->initial_time_step = time_step;
21643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2165d763cef2SBarry Smith }
2166d763cef2SBarry Smith 
2167a43b19c4SJed Brown /*@
216849354f04SShri Abhyankar   TSSetExactFinalTime - Determines whether to adapt the final time step to
21690b4b7b1cSBarry Smith   match the exact final time, to interpolate the solution to the exact final time,
21700b4b7b1cSBarry Smith   or to just return at the final time `TS` computed (which may be slightly larger
21710b4b7b1cSBarry Smith   than the requested final time).
2172a43b19c4SJed Brown 
2173c3339decSBarry Smith   Logically Collective
2174a43b19c4SJed Brown 
2175d8d19677SJose E. Roman   Input Parameters:
2176a43b19c4SJed Brown + ts     - the time-step context
217749354f04SShri Abhyankar - eftopt - exact final time option
2178bcf0153eSBarry Smith .vb
21790b4b7b1cSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded, just use it
21800b4b7b1cSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time if the final time is exceeded
21810b4b7b1cSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP   - Adapt final time step to ensure the computed final time exactly equals the requested final time
2182bcf0153eSBarry Smith .ve
2183a43b19c4SJed Brown 
2184bcf0153eSBarry Smith   Options Database Key:
21850b4b7b1cSBarry Smith . -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step approach at runtime
2186feed9e9dSBarry Smith 
2187a43b19c4SJed Brown   Level: beginner
2188a43b19c4SJed Brown 
2189bcf0153eSBarry Smith   Note:
2190bcf0153eSBarry Smith   If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2191bcf0153eSBarry Smith   then the final time you selected.
2192bcf0153eSBarry Smith 
21931cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2194a43b19c4SJed Brown @*/
TSSetExactFinalTime(TS ts,TSExactFinalTimeOption eftopt)2195d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2196d71ae5a4SJacob Faibussowitsch {
2197a43b19c4SJed Brown   PetscFunctionBegin;
2198a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
219949354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
220049354f04SShri Abhyankar   ts->exact_final_time = eftopt;
22013ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2202a43b19c4SJed Brown }
2203a43b19c4SJed Brown 
2204d763cef2SBarry Smith /*@
2205bcf0153eSBarry Smith   TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2206f6953c82SLisandro Dalcin 
2207f6953c82SLisandro Dalcin   Not Collective
2208f6953c82SLisandro Dalcin 
2209f6953c82SLisandro Dalcin   Input Parameter:
2210bcf0153eSBarry Smith . ts - the `TS` context
2211f6953c82SLisandro Dalcin 
2212f6953c82SLisandro Dalcin   Output Parameter:
2213f6953c82SLisandro Dalcin . eftopt - exact final time option
2214f6953c82SLisandro Dalcin 
2215f6953c82SLisandro Dalcin   Level: beginner
2216f6953c82SLisandro Dalcin 
22171cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2218f6953c82SLisandro Dalcin @*/
TSGetExactFinalTime(TS ts,TSExactFinalTimeOption * eftopt)2219d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2220d71ae5a4SJacob Faibussowitsch {
2221f6953c82SLisandro Dalcin   PetscFunctionBegin;
2222f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22234f572ea9SToby Isaac   PetscAssertPointer(eftopt, 2);
2224f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
22253ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2226f6953c82SLisandro Dalcin }
2227f6953c82SLisandro Dalcin 
2228f6953c82SLisandro Dalcin /*@
2229d763cef2SBarry Smith   TSGetTimeStep - Gets the current timestep size.
2230d763cef2SBarry Smith 
2231d763cef2SBarry Smith   Not Collective
2232d763cef2SBarry Smith 
2233d763cef2SBarry Smith   Input Parameter:
2234bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2235d763cef2SBarry Smith 
2236d763cef2SBarry Smith   Output Parameter:
2237d763cef2SBarry Smith . dt - the current timestep size
2238d763cef2SBarry Smith 
2239d763cef2SBarry Smith   Level: intermediate
2240d763cef2SBarry Smith 
22411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2242d763cef2SBarry Smith @*/
TSGetTimeStep(TS ts,PetscReal * dt)2243d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2244d71ae5a4SJacob Faibussowitsch {
2245d763cef2SBarry Smith   PetscFunctionBegin;
22460700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22474f572ea9SToby Isaac   PetscAssertPointer(dt, 2);
2248d763cef2SBarry Smith   *dt = ts->time_step;
22493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2250d763cef2SBarry Smith }
2251d763cef2SBarry Smith 
2252d8e5e3e6SSatish Balay /*@
2253d763cef2SBarry Smith   TSGetSolution - Returns the solution at the present timestep. It
2254d763cef2SBarry Smith   is valid to call this routine inside the function that you are evaluating
2255d763cef2SBarry Smith   in order to move to the new timestep. This vector not changed until
2256d763cef2SBarry Smith   the solution at the next timestep has been calculated.
2257d763cef2SBarry Smith 
2258bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
2259d763cef2SBarry Smith 
2260d763cef2SBarry Smith   Input Parameter:
2261bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2262d763cef2SBarry Smith 
2263d763cef2SBarry Smith   Output Parameter:
2264d763cef2SBarry Smith . v - the vector containing the solution
2265d763cef2SBarry Smith 
2266d763cef2SBarry Smith   Level: intermediate
2267d763cef2SBarry Smith 
2268bcf0153eSBarry Smith   Note:
2269bcf0153eSBarry Smith   If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2270bcf0153eSBarry Smith   final time. It returns the solution at the next timestep.
2271d763cef2SBarry Smith 
22721cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2273d763cef2SBarry Smith @*/
TSGetSolution(TS ts,Vec * v)2274d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2275d71ae5a4SJacob Faibussowitsch {
2276d763cef2SBarry Smith   PetscFunctionBegin;
22770700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
22784f572ea9SToby Isaac   PetscAssertPointer(v, 2);
22798737fe31SLisandro Dalcin   *v = ts->vec_sol;
22803ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2281d763cef2SBarry Smith }
2282d763cef2SBarry Smith 
228303fe5f5eSDebojyoti Ghosh /*@
2284b2bf4f3aSDebojyoti Ghosh   TSGetSolutionComponents - Returns any solution components at the present
228503fe5f5eSDebojyoti Ghosh   timestep, if available for the time integration method being used.
2286b2bf4f3aSDebojyoti Ghosh   Solution components are quantities that share the same size and
228703fe5f5eSDebojyoti Ghosh   structure as the solution vector.
228803fe5f5eSDebojyoti Ghosh 
2289bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
229003fe5f5eSDebojyoti Ghosh 
2291b43aa488SJacob Faibussowitsch   Input Parameters:
2292bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2293195e9b02SBarry Smith . n  - If v is `NULL`, then the number of solution components is
2294b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
229503fe5f5eSDebojyoti Ghosh        returned in v.
2296a2b725a8SWilliam Gropp - v  - the vector containing the n-th solution component
2297195e9b02SBarry Smith        (may be `NULL` to use this function to find out
2298b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
229903fe5f5eSDebojyoti Ghosh 
23004cdd57e5SDebojyoti Ghosh   Level: advanced
230103fe5f5eSDebojyoti Ghosh 
23021cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
230303fe5f5eSDebojyoti Ghosh @*/
TSGetSolutionComponents(TS ts,PetscInt * n,Vec * v)2304d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2305d71ae5a4SJacob Faibussowitsch {
230603fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
230703fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2308b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2309dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
23103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
231103fe5f5eSDebojyoti Ghosh }
231203fe5f5eSDebojyoti Ghosh 
23134cdd57e5SDebojyoti Ghosh /*@
23144cdd57e5SDebojyoti Ghosh   TSGetAuxSolution - Returns an auxiliary solution at the present
23154cdd57e5SDebojyoti Ghosh   timestep, if available for the time integration method being used.
23164cdd57e5SDebojyoti Ghosh 
2317bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23184cdd57e5SDebojyoti Ghosh 
2319b43aa488SJacob Faibussowitsch   Input Parameters:
2320bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2321a2b725a8SWilliam Gropp - v  - the vector containing the auxiliary solution
23224cdd57e5SDebojyoti Ghosh 
23234cdd57e5SDebojyoti Ghosh   Level: intermediate
23244cdd57e5SDebojyoti Ghosh 
23251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetSolution()`
23264cdd57e5SDebojyoti Ghosh @*/
TSGetAuxSolution(TS ts,Vec * v)2327d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2328d71ae5a4SJacob Faibussowitsch {
23294cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23304cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2331dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23321e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23333ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23344cdd57e5SDebojyoti Ghosh }
23354cdd57e5SDebojyoti Ghosh 
23364cdd57e5SDebojyoti Ghosh /*@
23374cdd57e5SDebojyoti Ghosh   TSGetTimeError - Returns the estimated error vector, if the chosen
2338bcf0153eSBarry Smith   `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23394cdd57e5SDebojyoti Ghosh 
2340bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
23419657682dSDebojyoti Ghosh 
2342b43aa488SJacob Faibussowitsch   Input Parameters:
2343bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2344657c1e31SEmil Constantinescu . n  - current estimate (n=0) or previous one (n=-1)
2345a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
23464cdd57e5SDebojyoti Ghosh 
23474cdd57e5SDebojyoti Ghosh   Level: intermediate
23484cdd57e5SDebojyoti Ghosh 
2349bcf0153eSBarry Smith   Note:
2350bcf0153eSBarry Smith   MUST call after `TSSetUp()`
23514cdd57e5SDebojyoti Ghosh 
23521cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetSolution()`, `TSSetTimeError()`
23534cdd57e5SDebojyoti Ghosh @*/
TSGetTimeError(TS ts,PetscInt n,Vec * v)2354d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2355d71ae5a4SJacob Faibussowitsch {
23564cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23574cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2358dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23591e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
23614cdd57e5SDebojyoti Ghosh }
23624cdd57e5SDebojyoti Ghosh 
236357df6a1bSDebojyoti Ghosh /*@
236457df6a1bSDebojyoti Ghosh   TSSetTimeError - Sets the estimated error vector, if the chosen
2365bcf0153eSBarry Smith   `TSType` has an error estimation functionality. This can be used
236657df6a1bSDebojyoti Ghosh   to restart such a time integrator with a given error vector.
236757df6a1bSDebojyoti Ghosh 
2368bcf0153eSBarry Smith   Not Collective, but v returned is parallel if ts is parallel
236957df6a1bSDebojyoti Ghosh 
2370b43aa488SJacob Faibussowitsch   Input Parameters:
2371bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()` (input parameter).
2372a2b725a8SWilliam Gropp - v  - the vector containing the error (same size as the solution).
237357df6a1bSDebojyoti Ghosh 
237457df6a1bSDebojyoti Ghosh   Level: intermediate
237557df6a1bSDebojyoti Ghosh 
2376b43aa488SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSSetSolution()`, `TSGetTimeError()`
237757df6a1bSDebojyoti Ghosh @*/
TSSetTimeError(TS ts,Vec v)2378d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2379d71ae5a4SJacob Faibussowitsch {
238057df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
238157df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23823c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2383dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
23843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
238557df6a1bSDebojyoti Ghosh }
238657df6a1bSDebojyoti Ghosh 
2387bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2388d8e5e3e6SSatish Balay /*@
2389bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2390d763cef2SBarry Smith 
2391bdad233fSMatthew Knepley   Not collective
2392d763cef2SBarry Smith 
2393bdad233fSMatthew Knepley   Input Parameters:
2394bcf0153eSBarry Smith + ts   - The `TS`
2395bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2396d763cef2SBarry Smith .vb
23970910c330SBarry Smith          U_t - A U = 0      (linear)
23980910c330SBarry Smith          U_t - A(t) U = 0   (linear)
23990910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2400d763cef2SBarry Smith .ve
2401d763cef2SBarry Smith 
2402d763cef2SBarry Smith   Level: beginner
2403d763cef2SBarry Smith 
24041cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2405d763cef2SBarry Smith @*/
TSSetProblemType(TS ts,TSProblemType type)2406d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2407d71ae5a4SJacob Faibussowitsch {
2408d763cef2SBarry Smith   PetscFunctionBegin;
24090700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2410bdad233fSMatthew Knepley   ts->problem_type = type;
24119e2a6581SJed Brown   if (type == TS_LINEAR) {
24129e2a6581SJed Brown     SNES snes;
24139566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24149566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24159e2a6581SJed Brown   }
24163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2417d763cef2SBarry Smith }
2418d763cef2SBarry Smith 
2419cc4c1da9SBarry Smith /*@
2420bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2421bdad233fSMatthew Knepley 
2422bdad233fSMatthew Knepley   Not collective
2423bdad233fSMatthew Knepley 
2424bdad233fSMatthew Knepley   Input Parameter:
2425bcf0153eSBarry Smith . ts - The `TS`
2426bdad233fSMatthew Knepley 
2427bdad233fSMatthew Knepley   Output Parameter:
2428bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2429bdad233fSMatthew Knepley .vb
2430089b2837SJed Brown          M U_t = A U
2431089b2837SJed Brown          M(t) U_t = A(t) U
2432b5abc632SBarry Smith          F(t,U,U_t)
2433bdad233fSMatthew Knepley .ve
2434bdad233fSMatthew Knepley 
2435bdad233fSMatthew Knepley   Level: beginner
2436bdad233fSMatthew Knepley 
24371cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetUp()`, `TSProblemType`, `TS`
2438bdad233fSMatthew Knepley @*/
TSGetProblemType(TS ts,TSProblemType * type)2439d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2440d71ae5a4SJacob Faibussowitsch {
2441bdad233fSMatthew Knepley   PetscFunctionBegin;
24420700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24434f572ea9SToby Isaac   PetscAssertPointer(type, 2);
2444bdad233fSMatthew Knepley   *type = ts->problem_type;
24453ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2446bdad233fSMatthew Knepley }
2447d763cef2SBarry Smith 
2448303a5415SBarry Smith /*
2449303a5415SBarry 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()
2450303a5415SBarry Smith */
TSSetExactFinalTimeDefault(TS ts)2451d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2452d71ae5a4SJacob Faibussowitsch {
2453303a5415SBarry Smith   PetscBool isnone;
2454303a5415SBarry Smith 
2455303a5415SBarry Smith   PetscFunctionBegin;
24569566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24579566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2458303a5415SBarry Smith 
24599566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24601e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24611e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
24623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2463303a5415SBarry Smith }
2464303a5415SBarry Smith 
2465d763cef2SBarry Smith /*@
2466303a5415SBarry Smith   TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2467d763cef2SBarry Smith 
2468c3339decSBarry Smith   Collective
2469d763cef2SBarry Smith 
2470d763cef2SBarry Smith   Input Parameter:
2471bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2472d763cef2SBarry Smith 
2473d763cef2SBarry Smith   Level: advanced
2474d763cef2SBarry Smith 
2475bcf0153eSBarry Smith   Note:
2476bcf0153eSBarry Smith   For basic use of the `TS` solvers the user need not explicitly call
2477bcf0153eSBarry Smith   `TSSetUp()`, since these actions will automatically occur during
2478bcf0153eSBarry Smith   the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2479bcf0153eSBarry Smith   phase separately, `TSSetUp()` should be called after `TSCreate()`
2480bcf0153eSBarry Smith   and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2481bcf0153eSBarry Smith 
24821cc06b55SBarry Smith .seealso: [](ch_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2483d763cef2SBarry Smith @*/
TSSetUp(TS ts)2484d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2485d71ae5a4SJacob Faibussowitsch {
24866c6b9e74SPeter Brune   DM dm;
24876c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2488d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
24898434afd1SBarry Smith   TSIFunctionFn   *ifun;
24908434afd1SBarry Smith   TSIJacobianFn   *ijac;
24918434afd1SBarry Smith   TSI2JacobianFn  *i2jac;
24928434afd1SBarry Smith   TSRHSJacobianFn *rhsjac;
2493d763cef2SBarry Smith 
2494d763cef2SBarry Smith   PetscFunctionBegin;
24950700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24963ba16761SJacob Faibussowitsch   if (ts->setupcalled) PetscFunctionReturn(PETSC_SUCCESS);
2497277b19d0SLisandro Dalcin 
24987adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
24999566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
25009566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2501d763cef2SBarry Smith   }
2502277b19d0SLisandro Dalcin 
25031a638600SStefano Zampini   if (!ts->vec_sol) {
25041e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25059566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25061a638600SStefano Zampini   }
2507277b19d0SLisandro Dalcin 
2508298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25099566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2510298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2511298bade4SHong Zhang   }
2512298bade4SHong Zhang 
2513cd4cee2dSHong Zhang   if (ts->quadraturets) {
25149566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25159566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25169566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2517cd4cee2dSHong Zhang   }
2518cd4cee2dSHong Zhang 
25199566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2520f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2521e1244c69SJed Brown     Mat  Amat, Pmat;
2522e1244c69SJed Brown     SNES snes;
25239566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25249566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2525e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2526e1244c69SJed Brown      * have displaced the RHS matrix */
2527971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2528abc0d4abSBarry 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 */
25299566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25309566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25319566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2532e1244c69SJed Brown     }
2533971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25349566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25359566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25369566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2537e1244c69SJed Brown     }
2538e1244c69SJed Brown   }
25392ffb9264SLisandro Dalcin 
25409566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25419566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25422ffb9264SLisandro Dalcin 
2543dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2544277b19d0SLisandro Dalcin 
25459566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25462ffb9264SLisandro Dalcin 
2547a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25486c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25496c6b9e74SPeter Brune    */
25509566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25519566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25521e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25531e66621cSBarry Smith 
2554a6772fa2SLisandro 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.
25556c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25566c6b9e74SPeter Brune    */
25579566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25589566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25599566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25609566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25611e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2562c0517034SDebojyoti Ghosh 
2563c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2564dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2565c0517034SDebojyoti Ghosh 
2566277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
25673ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2568277b19d0SLisandro Dalcin }
2569277b19d0SLisandro Dalcin 
2570f6a906c0SBarry Smith /*@
25710b4b7b1cSBarry Smith   TSReset - Resets a `TS` context to the state it was in before `TSSetUp()` was called and removes any allocated `Vec` and `Mat` from its data structures
2572277b19d0SLisandro Dalcin 
2573c3339decSBarry Smith   Collective
2574277b19d0SLisandro Dalcin 
2575277b19d0SLisandro Dalcin   Input Parameter:
2576bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2577277b19d0SLisandro Dalcin 
25780b4b7b1cSBarry Smith   Level: developer
2579277b19d0SLisandro Dalcin 
25800b4b7b1cSBarry Smith   Notes:
25810b4b7b1cSBarry Smith   Any options set on the `TS` object, including those set with `TSSetFromOptions()` remain.
25820b4b7b1cSBarry Smith 
25830b4b7b1cSBarry Smith   See also `TSSetResize()` to change the size of the system being integrated (for example by adaptive mesh refinement) during the time integration.
25840b4b7b1cSBarry Smith 
2585bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSetResize()`
2586277b19d0SLisandro Dalcin @*/
TSReset(TS ts)2587d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2588d71ae5a4SJacob Faibussowitsch {
25891d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2590277b19d0SLisandro Dalcin 
2591277b19d0SLisandro Dalcin   PetscFunctionBegin;
2592277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2593b18ea86cSHong Zhang 
2594dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
25959566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
25969566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2597bbd56ea5SKarl Rupp 
25989566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
25999566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26009566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26019566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
2602c61711c8SStefano Zampini   PetscCall(VecDestroy(&ts->vec_sol0));
26039566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26049566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26059566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26069566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2607bbd56ea5SKarl Rupp 
26089566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26099566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26101baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2611cd4cee2dSHong Zhang   if (ts->quadraturets) {
26129566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26139566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2614cd4cee2dSHong Zhang   }
26151d06f6b3SHong Zhang   while (ilink) {
26161d06f6b3SHong Zhang     next = ilink->next;
26179566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26189566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26199566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26209566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26211d06f6b3SHong Zhang     ilink = next;
262287f4e208SHong Zhang   }
26236bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2624545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
2625136cf249SJames Wright   if (ts->eval_times) {
2626136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->time_points));
2627136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times->sol_times));
2628136cf249SJames Wright     PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
2629136cf249SJames Wright     PetscCall(PetscFree(ts->eval_times));
26304a658b32SHong Zhang   }
2631b3a72457SStefano Zampini   ts->rhsjacobian.time  = PETSC_MIN_REAL;
2632b3a72457SStefano Zampini   ts->rhsjacobian.scale = 1.0;
2633b3a72457SStefano Zampini   ts->ijacobian.shift   = 1.0;
2634277b19d0SLisandro Dalcin   ts->setupcalled       = PETSC_FALSE;
26353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2636d763cef2SBarry Smith }
2637d763cef2SBarry Smith 
263814d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS);
263914d0ab18SJacob Faibussowitsch 
26400764c050SBarry Smith /*@
2641d763cef2SBarry Smith   TSDestroy - Destroys the timestepper context that was created
2642bcf0153eSBarry Smith   with `TSCreate()`.
2643d763cef2SBarry Smith 
2644c3339decSBarry Smith   Collective
2645d763cef2SBarry Smith 
2646d763cef2SBarry Smith   Input Parameter:
2647bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2648d763cef2SBarry Smith 
2649d763cef2SBarry Smith   Level: beginner
2650d763cef2SBarry Smith 
26511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2652d763cef2SBarry Smith @*/
TSDestroy(TS * ts)2653d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2654d71ae5a4SJacob Faibussowitsch {
2655d763cef2SBarry Smith   PetscFunctionBegin;
26563ba16761SJacob Faibussowitsch   if (!*ts) PetscFunctionReturn(PETSC_SUCCESS);
2657ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
2658f4f49eeaSPierre Jolivet   if (--((PetscObject)*ts)->refct > 0) {
26599371c9d4SSatish Balay     *ts = NULL;
26603ba16761SJacob Faibussowitsch     PetscFunctionReturn(PETSC_SUCCESS);
26619371c9d4SSatish Balay   }
2662d763cef2SBarry Smith 
26639566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26649566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26651e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26666bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(*ts));
26671e66621cSBarry Smith 
2668e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26699566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2670f4f49eeaSPierre Jolivet   PetscTryTypeMethod(*ts, destroy);
26716d4c513bSLisandro Dalcin 
26729566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2673bc952696SBarry Smith 
26749566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26759566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26766427ac75SLisandro Dalcin 
26779566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26784bd3aaa3SHong Zhang   PetscCall(SNESDestroy(&(*ts)->snesrhssplit));
26799566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
2680f4f49eeaSPierre Jolivet   PetscCall(TSMonitorCancel(*ts));
2681f4f49eeaSPierre Jolivet   PetscCall(TSAdjointMonitorCancel(*ts));
26826d4c513bSLisandro Dalcin 
26839566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
26849566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
26853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2686d763cef2SBarry Smith }
2687d763cef2SBarry Smith 
2688d8e5e3e6SSatish Balay /*@
2689bcf0153eSBarry Smith   TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2690bcf0153eSBarry Smith   a `TS` (timestepper) context. Valid only for nonlinear problems.
2691d763cef2SBarry Smith 
2692bcf0153eSBarry Smith   Not Collective, but snes is parallel if ts is parallel
2693d763cef2SBarry Smith 
2694d763cef2SBarry Smith   Input Parameter:
2695bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2696d763cef2SBarry Smith 
2697d763cef2SBarry Smith   Output Parameter:
2698d763cef2SBarry Smith . snes - the nonlinear solver context
2699d763cef2SBarry Smith 
2700d763cef2SBarry Smith   Level: beginner
2701d763cef2SBarry Smith 
2702bcf0153eSBarry Smith   Notes:
2703bcf0153eSBarry Smith   The user can then directly manipulate the `SNES` context to set various
2704bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2705bcf0153eSBarry Smith   `KSP`, and `PC` contexts as well.
2706bcf0153eSBarry Smith 
2707bcf0153eSBarry Smith   `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2708195e9b02SBarry Smith   this case `TSGetSNES()` returns `NULL` in `snes`.
2709bcf0153eSBarry Smith 
27101cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2711d763cef2SBarry Smith @*/
TSGetSNES(TS ts,SNES * snes)2712d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2713d71ae5a4SJacob Faibussowitsch {
2714d763cef2SBarry Smith   PetscFunctionBegin;
27150700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27164f572ea9SToby Isaac   PetscAssertPointer(snes, 2);
2717d372ba47SLisandro Dalcin   if (!ts->snes) {
27189566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27199566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27209566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27219566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27224bd3aaa3SHong Zhang     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27231e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2724d372ba47SLisandro Dalcin   }
2725d763cef2SBarry Smith   *snes = ts->snes;
27263ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2727d763cef2SBarry Smith }
2728d763cef2SBarry Smith 
2729deb2cd25SJed Brown /*@
27300b4b7b1cSBarry Smith   TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the `TS` timestepping context
2731deb2cd25SJed Brown 
2732deb2cd25SJed Brown   Collective
2733deb2cd25SJed Brown 
2734d8d19677SJose E. Roman   Input Parameters:
2735bcf0153eSBarry Smith + ts   - the `TS` context obtained from `TSCreate()`
2736deb2cd25SJed Brown - snes - the nonlinear solver context
2737deb2cd25SJed Brown 
2738deb2cd25SJed Brown   Level: developer
2739deb2cd25SJed Brown 
2740bcf0153eSBarry Smith   Note:
2741bcf0153eSBarry Smith   Most users should have the `TS` created by calling `TSGetSNES()`
2742bcf0153eSBarry Smith 
27431cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2744deb2cd25SJed Brown @*/
TSSetSNES(TS ts,SNES snes)2745d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2746d71ae5a4SJacob Faibussowitsch {
2747d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2748deb2cd25SJed Brown 
2749deb2cd25SJed Brown   PetscFunctionBegin;
2750deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2751deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27529566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27539566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2754bbd56ea5SKarl Rupp 
2755deb2cd25SJed Brown   ts->snes = snes;
2756bbd56ea5SKarl Rupp 
27579566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27589566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27591e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
27603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2761deb2cd25SJed Brown }
2762deb2cd25SJed Brown 
2763d8e5e3e6SSatish Balay /*@
2764bcf0153eSBarry Smith   TSGetKSP - Returns the `KSP` (linear solver) associated with
2765bcf0153eSBarry Smith   a `TS` (timestepper) context.
2766d763cef2SBarry Smith 
2767195e9b02SBarry Smith   Not Collective, but `ksp` is parallel if `ts` is parallel
2768d763cef2SBarry Smith 
2769d763cef2SBarry Smith   Input Parameter:
2770bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2771d763cef2SBarry Smith 
2772d763cef2SBarry Smith   Output Parameter:
277394b7f48cSBarry Smith . ksp - the nonlinear solver context
2774d763cef2SBarry Smith 
2775d763cef2SBarry Smith   Level: beginner
2776d763cef2SBarry Smith 
2777bcf0153eSBarry Smith   Notes:
2778bcf0153eSBarry Smith   The user can then directly manipulate the `KSP` context to set various
2779bcf0153eSBarry Smith   options, etc.  Likewise, the user can then extract and manipulate the
2780bcf0153eSBarry Smith   `PC` context as well.
2781bcf0153eSBarry Smith 
2782bcf0153eSBarry Smith   `TSGetKSP()` does not work for integrators that do not use `KSP`;
2783195e9b02SBarry Smith   in this case `TSGetKSP()` returns `NULL` in `ksp`.
2784bcf0153eSBarry Smith 
27851cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2786d763cef2SBarry Smith @*/
TSGetKSP(TS ts,KSP * ksp)2787d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2788d71ae5a4SJacob Faibussowitsch {
2789089b2837SJed Brown   SNES snes;
2790d372ba47SLisandro Dalcin 
2791d763cef2SBarry Smith   PetscFunctionBegin;
27920700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27934f572ea9SToby Isaac   PetscAssertPointer(ksp, 2);
27943c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
27953c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
27969566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
27979566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
27983ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2799d763cef2SBarry Smith }
2800d763cef2SBarry Smith 
2801d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2802d763cef2SBarry Smith 
2803adb62b0dSMatthew Knepley /*@
2804618ce8baSLisandro Dalcin   TSSetMaxSteps - Sets the maximum number of steps to use.
2805618ce8baSLisandro Dalcin 
2806c3339decSBarry Smith   Logically Collective
2807618ce8baSLisandro Dalcin 
2808618ce8baSLisandro Dalcin   Input Parameters:
2809bcf0153eSBarry Smith + ts       - the `TS` context obtained from `TSCreate()`
2810618ce8baSLisandro Dalcin - maxsteps - maximum number of steps to use
2811618ce8baSLisandro Dalcin 
2812bcf0153eSBarry Smith   Options Database Key:
2813618ce8baSLisandro Dalcin . -ts_max_steps <maxsteps> - Sets maxsteps
2814618ce8baSLisandro Dalcin 
2815618ce8baSLisandro Dalcin   Level: intermediate
2816618ce8baSLisandro Dalcin 
2817bcf0153eSBarry Smith   Note:
281809cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum number of steps to the default from when the object's type was set
281909cb0f53SBarry Smith 
282009cb0f53SBarry Smith   The default maximum number of steps is 5,000
282109cb0f53SBarry Smith 
282209cb0f53SBarry Smith   Fortran Note:
282309cb0f53SBarry Smith   Use `PETSC_DETERMINE_INTEGER`
2824bcf0153eSBarry Smith 
28251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2826618ce8baSLisandro Dalcin @*/
TSSetMaxSteps(TS ts,PetscInt maxsteps)2827d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2828d71ae5a4SJacob Faibussowitsch {
2829618ce8baSLisandro Dalcin   PetscFunctionBegin;
2830618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2831618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
283209cb0f53SBarry Smith   if (maxsteps == PETSC_DETERMINE) {
283309cb0f53SBarry Smith     ts->max_steps = ts->default_max_steps;
283409cb0f53SBarry Smith   } else {
28353c633725SBarry Smith     PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2836618ce8baSLisandro Dalcin     ts->max_steps = maxsteps;
283709cb0f53SBarry Smith   }
28383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2839618ce8baSLisandro Dalcin }
2840618ce8baSLisandro Dalcin 
2841618ce8baSLisandro Dalcin /*@
2842618ce8baSLisandro Dalcin   TSGetMaxSteps - Gets the maximum number of steps to use.
2843618ce8baSLisandro Dalcin 
2844618ce8baSLisandro Dalcin   Not Collective
2845618ce8baSLisandro Dalcin 
28462fe279fdSBarry Smith   Input Parameter:
2847bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2848618ce8baSLisandro Dalcin 
2849618ce8baSLisandro Dalcin   Output Parameter:
2850618ce8baSLisandro Dalcin . maxsteps - maximum number of steps to use
2851618ce8baSLisandro Dalcin 
2852618ce8baSLisandro Dalcin   Level: advanced
2853618ce8baSLisandro Dalcin 
28541cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2855618ce8baSLisandro Dalcin @*/
TSGetMaxSteps(TS ts,PetscInt * maxsteps)2856d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2857d71ae5a4SJacob Faibussowitsch {
2858618ce8baSLisandro Dalcin   PetscFunctionBegin;
2859618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28604f572ea9SToby Isaac   PetscAssertPointer(maxsteps, 2);
2861618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
28623ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2863618ce8baSLisandro Dalcin }
2864618ce8baSLisandro Dalcin 
2865618ce8baSLisandro Dalcin /*@
28668e562f8dSJames Wright   TSSetRunSteps - Sets the maximum number of steps to take in each call to `TSSolve()`.
28678e562f8dSJames Wright 
28688e562f8dSJames Wright   If the step count when `TSSolve()` is `start_step`, this will stop the simulation once `current_step - start_step >= run_steps`.
28698e562f8dSJames Wright   Comparatively, `TSSetMaxSteps()` will stop if `current_step >= max_steps`.
28708e562f8dSJames Wright   The simulation will stop when either condition is reached.
28718e562f8dSJames Wright 
28728e562f8dSJames Wright   Logically Collective
28738e562f8dSJames Wright 
28748e562f8dSJames Wright   Input Parameters:
28758e562f8dSJames Wright + ts       - the `TS` context obtained from `TSCreate()`
28768e562f8dSJames Wright - runsteps - maximum number of steps to take in each call to `TSSolve()`;
28778e562f8dSJames Wright 
28788e562f8dSJames Wright   Options Database Key:
28798e562f8dSJames Wright . -ts_run_steps <runsteps> - Sets runsteps
28808e562f8dSJames Wright 
28818e562f8dSJames Wright   Level: intermediate
28828e562f8dSJames Wright 
28838e562f8dSJames Wright   Note:
28848e562f8dSJames Wright   The default is `PETSC_UNLIMITED`
28858e562f8dSJames Wright 
28868e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSGetRunSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`, `TSSetMaxSteps()`
28878e562f8dSJames Wright @*/
TSSetRunSteps(TS ts,PetscInt runsteps)28888e562f8dSJames Wright PetscErrorCode TSSetRunSteps(TS ts, PetscInt runsteps)
28898e562f8dSJames Wright {
28908e562f8dSJames Wright   PetscFunctionBegin;
28918e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28928e562f8dSJames Wright   PetscValidLogicalCollectiveInt(ts, runsteps, 2);
28938e562f8dSJames Wright   if (runsteps == PETSC_DETERMINE) {
28948e562f8dSJames Wright     ts->run_steps = PETSC_UNLIMITED;
28958e562f8dSJames Wright   } else {
28968e562f8dSJames Wright     PetscCheck(runsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Max number of steps to take in each call to TSSolve must be non-negative");
28978e562f8dSJames Wright     ts->run_steps = runsteps;
28988e562f8dSJames Wright   }
28998e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
29008e562f8dSJames Wright }
29018e562f8dSJames Wright 
29028e562f8dSJames Wright /*@
29038e562f8dSJames Wright   TSGetRunSteps - Gets the maximum number of steps to take in each call to `TSSolve()`.
29048e562f8dSJames Wright 
29058e562f8dSJames Wright   Not Collective
29068e562f8dSJames Wright 
29078e562f8dSJames Wright   Input Parameter:
29088e562f8dSJames Wright . ts - the `TS` context obtained from `TSCreate()`
29098e562f8dSJames Wright 
29108e562f8dSJames Wright   Output Parameter:
29118e562f8dSJames Wright . runsteps - maximum number of steps to take in each call to `TSSolve`.
29128e562f8dSJames Wright 
29138e562f8dSJames Wright   Level: advanced
29148e562f8dSJames Wright 
29158e562f8dSJames Wright .seealso: [](ch_ts), `TS`, `TSSetRunSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`, `TSGetMaxSteps()`
29168e562f8dSJames Wright @*/
TSGetRunSteps(TS ts,PetscInt * runsteps)29178e562f8dSJames Wright PetscErrorCode TSGetRunSteps(TS ts, PetscInt *runsteps)
29188e562f8dSJames Wright {
29198e562f8dSJames Wright   PetscFunctionBegin;
29208e562f8dSJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29218e562f8dSJames Wright   PetscAssertPointer(runsteps, 2);
29228e562f8dSJames Wright   *runsteps = ts->run_steps;
29238e562f8dSJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
29248e562f8dSJames Wright }
29258e562f8dSJames Wright 
29268e562f8dSJames Wright /*@
2927618ce8baSLisandro Dalcin   TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2928618ce8baSLisandro Dalcin 
2929c3339decSBarry Smith   Logically Collective
2930618ce8baSLisandro Dalcin 
2931618ce8baSLisandro Dalcin   Input Parameters:
2932bcf0153eSBarry Smith + ts      - the `TS` context obtained from `TSCreate()`
2933618ce8baSLisandro Dalcin - maxtime - final time to step to
2934618ce8baSLisandro Dalcin 
2935bcf0153eSBarry Smith   Options Database Key:
2936ef85077eSLisandro Dalcin . -ts_max_time <maxtime> - Sets maxtime
2937618ce8baSLisandro Dalcin 
2938bcf0153eSBarry Smith   Level: intermediate
2939bcf0153eSBarry Smith 
2940618ce8baSLisandro Dalcin   Notes:
294109cb0f53SBarry Smith   Use `PETSC_DETERMINE` to reset the maximum time to the default from when the object's type was set
294209cb0f53SBarry Smith 
2943618ce8baSLisandro Dalcin   The default maximum time is 5.0
2944618ce8baSLisandro Dalcin 
294509cb0f53SBarry Smith   Fortran Note:
294609cb0f53SBarry Smith   Use `PETSC_DETERMINE_REAL`
294709cb0f53SBarry Smith 
29481cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2949618ce8baSLisandro Dalcin @*/
TSSetMaxTime(TS ts,PetscReal maxtime)2950d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2951d71ae5a4SJacob Faibussowitsch {
2952618ce8baSLisandro Dalcin   PetscFunctionBegin;
2953618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2954618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
295509cb0f53SBarry Smith   if (maxtime == PETSC_DETERMINE) {
295609cb0f53SBarry Smith     ts->max_time = ts->default_max_time;
295709cb0f53SBarry Smith   } else {
2958618ce8baSLisandro Dalcin     ts->max_time = maxtime;
295909cb0f53SBarry Smith   }
29603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2961618ce8baSLisandro Dalcin }
2962618ce8baSLisandro Dalcin 
2963618ce8baSLisandro Dalcin /*@
2964618ce8baSLisandro Dalcin   TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2965618ce8baSLisandro Dalcin 
2966618ce8baSLisandro Dalcin   Not Collective
2967618ce8baSLisandro Dalcin 
29682fe279fdSBarry Smith   Input Parameter:
2969bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
2970618ce8baSLisandro Dalcin 
2971618ce8baSLisandro Dalcin   Output Parameter:
2972618ce8baSLisandro Dalcin . maxtime - final time to step to
2973618ce8baSLisandro Dalcin 
2974618ce8baSLisandro Dalcin   Level: advanced
2975618ce8baSLisandro Dalcin 
29761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2977618ce8baSLisandro Dalcin @*/
TSGetMaxTime(TS ts,PetscReal * maxtime)2978d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2979d71ae5a4SJacob Faibussowitsch {
2980618ce8baSLisandro Dalcin   PetscFunctionBegin;
2981618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29824f572ea9SToby Isaac   PetscAssertPointer(maxtime, 2);
2983618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
29843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
2985618ce8baSLisandro Dalcin }
2986618ce8baSLisandro Dalcin 
298714d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
2988618ce8baSLisandro Dalcin /*@
2989bcf0153eSBarry Smith   TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2990edc382c3SSatish Balay 
2991edc382c3SSatish Balay   Level: deprecated
2992edc382c3SSatish Balay 
2993aaa6c58dSLisandro Dalcin @*/
TSSetInitialTimeStep(TS ts,PetscReal initial_time,PetscReal time_step)2994d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2995d71ae5a4SJacob Faibussowitsch {
2996aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2997aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29989566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29999566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
30003ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3001aaa6c58dSLisandro Dalcin }
3002aaa6c58dSLisandro Dalcin 
300314d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3004aaa6c58dSLisandro Dalcin /*@
3005bcf0153eSBarry Smith   TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
3006edc382c3SSatish Balay 
3007edc382c3SSatish Balay   Level: deprecated
3008edc382c3SSatish Balay 
3009adb62b0dSMatthew Knepley @*/
TSGetDuration(TS ts,PetscInt * maxsteps,PetscReal * maxtime)3010d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
3011d71ae5a4SJacob Faibussowitsch {
3012adb62b0dSMatthew Knepley   PetscFunctionBegin;
30130700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3014abc0a331SBarry Smith   if (maxsteps) {
30154f572ea9SToby Isaac     PetscAssertPointer(maxsteps, 2);
3016adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
3017adb62b0dSMatthew Knepley   }
3018abc0a331SBarry Smith   if (maxtime) {
30194f572ea9SToby Isaac     PetscAssertPointer(maxtime, 3);
3020adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
3021adb62b0dSMatthew Knepley   }
30223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3023adb62b0dSMatthew Knepley }
3024adb62b0dSMatthew Knepley 
302514d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3026d763cef2SBarry Smith /*@
3027bcf0153eSBarry Smith   TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
3028edc382c3SSatish Balay 
3029edc382c3SSatish Balay   Level: deprecated
3030edc382c3SSatish Balay 
3031d763cef2SBarry Smith @*/
TSSetDuration(TS ts,PetscInt maxsteps,PetscReal maxtime)3032d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
3033d71ae5a4SJacob Faibussowitsch {
3034d763cef2SBarry Smith   PetscFunctionBegin;
3035835f2295SStefano Zampini   if (maxsteps != PETSC_CURRENT) PetscCall(TSSetMaxSteps(ts, maxsteps));
303609cb0f53SBarry Smith   if (maxtime != (PetscReal)PETSC_CURRENT) PetscCall(TSSetMaxTime(ts, maxtime));
30373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3038d763cef2SBarry Smith }
3039d763cef2SBarry Smith 
304014d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
3041d763cef2SBarry Smith /*@
3042bcf0153eSBarry Smith   TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
3043edc382c3SSatish Balay 
3044edc382c3SSatish Balay   Level: deprecated
3045edc382c3SSatish Balay 
30465c5f5948SLisandro Dalcin @*/
TSGetTimeStepNumber(TS ts,PetscInt * steps)3047d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
3048d71ae5a4SJacob Faibussowitsch {
30499371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30509371c9d4SSatish Balay }
30515c5f5948SLisandro Dalcin 
305214d0ab18SJacob Faibussowitsch // PetscClangLinter pragma disable: -fdoc-*
305319eac22cSLisandro Dalcin /*@
3054bcf0153eSBarry Smith   TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
3055edc382c3SSatish Balay 
3056edc382c3SSatish Balay   Level: deprecated
3057edc382c3SSatish Balay 
30584f4e0956SLisandro Dalcin @*/
TSGetTotalSteps(TS ts,PetscInt * steps)3059d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
3060d71ae5a4SJacob Faibussowitsch {
30619371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
30629371c9d4SSatish Balay }
30634f4e0956SLisandro Dalcin 
30644f4e0956SLisandro Dalcin /*@
3065d763cef2SBarry Smith   TSSetSolution - Sets the initial solution vector
3066bcf0153eSBarry Smith   for use by the `TS` routines.
3067d763cef2SBarry Smith 
3068c3339decSBarry Smith   Logically Collective
3069d763cef2SBarry Smith 
3070d763cef2SBarry Smith   Input Parameters:
3071bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
30720910c330SBarry Smith - u  - the solution vector
3073d763cef2SBarry Smith 
3074d763cef2SBarry Smith   Level: beginner
3075d763cef2SBarry Smith 
30761cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3077d763cef2SBarry Smith @*/
TSSetSolution(TS ts,Vec u)3078d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3079d71ae5a4SJacob Faibussowitsch {
3080496e6a7aSJed Brown   DM dm;
30818737fe31SLisandro Dalcin 
3082d763cef2SBarry Smith   PetscFunctionBegin;
30830700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30840910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30859566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30869566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30870910c330SBarry Smith   ts->vec_sol = u;
3088bbd56ea5SKarl Rupp 
30899566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30909566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
30913ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3092d763cef2SBarry Smith }
3093d763cef2SBarry Smith 
3094ac226902SBarry Smith /*@C
3095000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30963f2090d5SJed Brown   called once at the beginning of each time step.
3097000e7ae3SMatthew Knepley 
3098c3339decSBarry Smith   Logically Collective
3099000e7ae3SMatthew Knepley 
3100000e7ae3SMatthew Knepley   Input Parameters:
3101bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3102000e7ae3SMatthew Knepley - func - The function
3103000e7ae3SMatthew Knepley 
310420f4b53cSBarry Smith   Calling sequence of `func`:
310514d0ab18SJacob Faibussowitsch . ts - the `TS` context
3106000e7ae3SMatthew Knepley 
3107000e7ae3SMatthew Knepley   Level: intermediate
3108000e7ae3SMatthew Knepley 
31091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3110000e7ae3SMatthew Knepley @*/
TSSetPreStep(TS ts,PetscErrorCode (* func)(TS ts))311114d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS ts))
3112d71ae5a4SJacob Faibussowitsch {
3113000e7ae3SMatthew Knepley   PetscFunctionBegin;
31140700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3115ae60f76fSBarry Smith   ts->prestep = func;
31163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3117000e7ae3SMatthew Knepley }
3118000e7ae3SMatthew Knepley 
311909ee8438SJed Brown /*@
3120bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
31213f2090d5SJed Brown 
3122c3339decSBarry Smith   Collective
31233f2090d5SJed Brown 
31242fe279fdSBarry Smith   Input Parameter:
3125bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
31263f2090d5SJed Brown 
31273f2090d5SJed Brown   Level: developer
31283f2090d5SJed Brown 
3129bcf0153eSBarry Smith   Note:
3130bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3131bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3132bcf0153eSBarry Smith 
31331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
31343f2090d5SJed Brown @*/
TSPreStep(TS ts)3135d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3136d71ae5a4SJacob Faibussowitsch {
31373f2090d5SJed Brown   PetscFunctionBegin;
31380700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3139ae60f76fSBarry Smith   if (ts->prestep) {
31405efd42a4SStefano Zampini     Vec              U;
3141ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3142ef8d1ce0SJohann Rudi     PetscBool        sameObject;
31435efd42a4SStefano Zampini     PetscObjectState sprev, spost;
31445efd42a4SStefano Zampini 
31459566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31469566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
31479566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
314825e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
31499566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
31509566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
31519566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
31529566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3153312ce896SJed Brown   }
31543ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
31553f2090d5SJed Brown }
31563f2090d5SJed Brown 
3157b8123daeSJed Brown /*@C
3158b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3159b8123daeSJed Brown   called once at the beginning of each stage.
3160b8123daeSJed Brown 
3161c3339decSBarry Smith   Logically Collective
3162b8123daeSJed Brown 
3163b8123daeSJed Brown   Input Parameters:
3164bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3165b8123daeSJed Brown - func - The function
3166b8123daeSJed Brown 
316720f4b53cSBarry Smith   Calling sequence of `func`:
316814d0ab18SJacob Faibussowitsch + ts        - the `TS` context
316914d0ab18SJacob Faibussowitsch - stagetime - the stage time
3170b8123daeSJed Brown 
3171b8123daeSJed Brown   Level: intermediate
3172b8123daeSJed Brown 
3173b8123daeSJed Brown   Note:
3174b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3175bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3176bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3177b8123daeSJed Brown 
31781cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3179b8123daeSJed Brown @*/
TSSetPreStage(TS ts,PetscErrorCode (* func)(TS ts,PetscReal stagetime))318014d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime))
3181d71ae5a4SJacob Faibussowitsch {
3182b8123daeSJed Brown   PetscFunctionBegin;
3183b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3184ae60f76fSBarry Smith   ts->prestage = func;
31853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3186b8123daeSJed Brown }
3187b8123daeSJed Brown 
31889be3e283SDebojyoti Ghosh /*@C
31890d56bcf9SIlya Fursov   TSSetPostStage - Sets the general-purpose function
31909be3e283SDebojyoti Ghosh   called once at the end of each stage.
31919be3e283SDebojyoti Ghosh 
3192c3339decSBarry Smith   Logically Collective
31939be3e283SDebojyoti Ghosh 
31949be3e283SDebojyoti Ghosh   Input Parameters:
3195bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31969be3e283SDebojyoti Ghosh - func - The function
31979be3e283SDebojyoti Ghosh 
319820f4b53cSBarry Smith   Calling sequence of `func`:
319914d0ab18SJacob Faibussowitsch + ts         - the `TS` context
320014d0ab18SJacob Faibussowitsch . stagetime  - the stage time
320114d0ab18SJacob Faibussowitsch . stageindex - the stage index
320214d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
32039be3e283SDebojyoti Ghosh 
32049be3e283SDebojyoti Ghosh   Level: intermediate
32059be3e283SDebojyoti Ghosh 
32069be3e283SDebojyoti Ghosh   Note:
32079be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3208bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3209bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
32109be3e283SDebojyoti Ghosh 
32111cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
32129be3e283SDebojyoti Ghosh @*/
TSSetPostStage(TS ts,PetscErrorCode (* func)(TS ts,PetscReal stagetime,PetscInt stageindex,Vec * Y))321314d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y))
3214d71ae5a4SJacob Faibussowitsch {
32159be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32169be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32179be3e283SDebojyoti Ghosh   ts->poststage = func;
32183ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
32199be3e283SDebojyoti Ghosh }
32209be3e283SDebojyoti Ghosh 
3221c688d042SShri Abhyankar /*@C
3222c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
32230d56bcf9SIlya Fursov   called at the end of each step evaluation.
3224c688d042SShri Abhyankar 
3225c3339decSBarry Smith   Logically Collective
3226c688d042SShri Abhyankar 
3227c688d042SShri Abhyankar   Input Parameters:
3228bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3229c688d042SShri Abhyankar - func - The function
3230c688d042SShri Abhyankar 
323120f4b53cSBarry Smith   Calling sequence of `func`:
323214d0ab18SJacob Faibussowitsch . ts - the `TS` context
3233c688d042SShri Abhyankar 
3234c688d042SShri Abhyankar   Level: intermediate
3235c688d042SShri Abhyankar 
3236c688d042SShri Abhyankar   Note:
32370d56bcf9SIlya Fursov   The function set by `TSSetPostEvaluate()` is called after the solution is evaluated, or after the step rollback.
32380d56bcf9SIlya Fursov   Inside the `func` callback, the solution vector can be obtained with `TSGetSolution()`, and modified, if need be.
32390d56bcf9SIlya Fursov   The time step can be obtained with `TSGetTimeStep()`, and the time at the start of the step - via `TSGetTime()`.
32400d56bcf9SIlya Fursov   The potential changes to the solution vector introduced by event handling (`postevent()`) are not relevant for `TSSetPostEvaluate()`,
32410d56bcf9SIlya Fursov   but are relevant for `TSSetPostStep()`, according to the function call scheme in `TSSolve()`, as shown below
32420d56bcf9SIlya Fursov .vb
32430d56bcf9SIlya Fursov   ...
32440d56bcf9SIlya Fursov   Step()
32450d56bcf9SIlya Fursov   PostEvaluate()
32460d56bcf9SIlya Fursov   EventHandling()
32470d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
32480d56bcf9SIlya Fursov   ...
32490d56bcf9SIlya Fursov .ve
32500d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
32510d56bcf9SIlya Fursov .vb
32520d56bcf9SIlya Fursov   (1) | successful step | solution intact
32530d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
32540d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
32550d56bcf9SIlya Fursov .ve
3256c688d042SShri Abhyankar 
32571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3258c688d042SShri Abhyankar @*/
TSSetPostEvaluate(TS ts,PetscErrorCode (* func)(TS ts))325914d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS ts))
3260d71ae5a4SJacob Faibussowitsch {
3261c688d042SShri Abhyankar   PetscFunctionBegin;
3262c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3263c688d042SShri Abhyankar   ts->postevaluate = func;
32643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3265c688d042SShri Abhyankar }
3266c688d042SShri Abhyankar 
3267b8123daeSJed Brown /*@
3268bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3269b8123daeSJed Brown 
3270c3339decSBarry Smith   Collective
3271b8123daeSJed Brown 
3272b8123daeSJed Brown   Input Parameters:
327314d0ab18SJacob Faibussowitsch + ts        - The `TS` context obtained from `TSCreate()`
327414d0ab18SJacob Faibussowitsch - stagetime - The absolute time of the current stage
3275b8123daeSJed Brown 
3276b8123daeSJed Brown   Level: developer
3277b8123daeSJed Brown 
3278bcf0153eSBarry Smith   Note:
3279bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3280bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3281bcf0153eSBarry Smith 
32821cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3283b8123daeSJed Brown @*/
TSPreStage(TS ts,PetscReal stagetime)3284d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3285d71ae5a4SJacob Faibussowitsch {
3286b8123daeSJed Brown   PetscFunctionBegin;
3287b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32881e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
32893ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3290b8123daeSJed Brown }
3291b8123daeSJed Brown 
32929be3e283SDebojyoti Ghosh /*@
3293bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32949be3e283SDebojyoti Ghosh 
3295c3339decSBarry Smith   Collective
32969be3e283SDebojyoti Ghosh 
32979be3e283SDebojyoti Ghosh   Input Parameters:
329814d0ab18SJacob Faibussowitsch + ts         - The `TS` context obtained from `TSCreate()`
329914d0ab18SJacob Faibussowitsch . stagetime  - The absolute time of the current stage
330014d0ab18SJacob Faibussowitsch . stageindex - Stage number
330114d0ab18SJacob Faibussowitsch - Y          - Array of vectors (of size = total number of stages) with the stage solutions
33029be3e283SDebojyoti Ghosh 
33039be3e283SDebojyoti Ghosh   Level: developer
33049be3e283SDebojyoti Ghosh 
3305bcf0153eSBarry Smith   Note:
3306bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3307bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3308bcf0153eSBarry Smith 
33091cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
33109be3e283SDebojyoti Ghosh @*/
TSPostStage(TS ts,PetscReal stagetime,PetscInt stageindex,Vec Y[])33110fc7ecceSBarry Smith PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec Y[])
3312d71ae5a4SJacob Faibussowitsch {
33139be3e283SDebojyoti Ghosh   PetscFunctionBegin;
33149be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
33151e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
33163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
33179be3e283SDebojyoti Ghosh }
33189be3e283SDebojyoti Ghosh 
3319c688d042SShri Abhyankar /*@
3320bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3321c688d042SShri Abhyankar 
3322c3339decSBarry Smith   Collective
3323c688d042SShri Abhyankar 
33242fe279fdSBarry Smith   Input Parameter:
3325bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3326c688d042SShri Abhyankar 
3327c688d042SShri Abhyankar   Level: developer
3328c688d042SShri Abhyankar 
3329bcf0153eSBarry Smith   Note:
3330bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3331bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3332bcf0153eSBarry Smith 
33331cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3334c688d042SShri Abhyankar @*/
TSPostEvaluate(TS ts)3335d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3336d71ae5a4SJacob Faibussowitsch {
3337c688d042SShri Abhyankar   PetscFunctionBegin;
3338c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3339c688d042SShri Abhyankar   if (ts->postevaluate) {
3340dcb233daSLisandro Dalcin     Vec              U;
3341dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3342dcb233daSLisandro Dalcin 
33439566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33449566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
334525e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
33469566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33479566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3348c688d042SShri Abhyankar   }
33493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3350c688d042SShri Abhyankar }
3351c688d042SShri Abhyankar 
3352ac226902SBarry Smith /*@C
3353000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
33540d56bcf9SIlya Fursov   called once at the end of each successful time step.
3355000e7ae3SMatthew Knepley 
3356c3339decSBarry Smith   Logically Collective
3357000e7ae3SMatthew Knepley 
3358000e7ae3SMatthew Knepley   Input Parameters:
3359bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3360000e7ae3SMatthew Knepley - func - The function
3361000e7ae3SMatthew Knepley 
336220f4b53cSBarry Smith   Calling sequence of `func`:
336314d0ab18SJacob Faibussowitsch . ts - the `TS` context
3364000e7ae3SMatthew Knepley 
3365000e7ae3SMatthew Knepley   Level: intermediate
3366000e7ae3SMatthew Knepley 
3367bcf0153eSBarry Smith   Note:
33680d56bcf9SIlya Fursov   The function set by `TSSetPostStep()` is called after each successful step. If the event handler locates an event at the
33690d56bcf9SIlya Fursov   given step, and `postevent()` modifies the solution vector, the solution vector obtained by `TSGetSolution()` inside `func` will
33700d56bcf9SIlya Fursov   contain the changes. To get the solution without these changes, use `TSSetPostEvaluate()` to set the appropriate callback.
33710d56bcf9SIlya Fursov   The scheme of the relevant function calls in `TSSolve()` is shown below
33720d56bcf9SIlya Fursov .vb
33730d56bcf9SIlya Fursov   ...
33740d56bcf9SIlya Fursov   Step()
33750d56bcf9SIlya Fursov   PostEvaluate()
33760d56bcf9SIlya Fursov   EventHandling()
33770d56bcf9SIlya Fursov   step_rollback ? PostEvaluate() : PostStep()
33780d56bcf9SIlya Fursov   ...
33790d56bcf9SIlya Fursov .ve
33800d56bcf9SIlya Fursov   where EventHandling() may result in one of the following three outcomes
33810d56bcf9SIlya Fursov .vb
33820d56bcf9SIlya Fursov   (1) | successful step | solution intact
33830d56bcf9SIlya Fursov   (2) | successful step | solution modified by `postevent()`
33840d56bcf9SIlya Fursov   (3) | step_rollback   | solution rolled back
33850d56bcf9SIlya Fursov .ve
3386bcf0153eSBarry Smith 
33871cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3388000e7ae3SMatthew Knepley @*/
TSSetPostStep(TS ts,PetscErrorCode (* func)(TS ts))338914d0ab18SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS ts))
3390d71ae5a4SJacob Faibussowitsch {
3391000e7ae3SMatthew Knepley   PetscFunctionBegin;
33920700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3393ae60f76fSBarry Smith   ts->poststep = func;
33943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3395000e7ae3SMatthew Knepley }
3396000e7ae3SMatthew Knepley 
339709ee8438SJed Brown /*@
3398195e9b02SBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPostStep()`
33993f2090d5SJed Brown 
3400c3339decSBarry Smith   Collective
34013f2090d5SJed Brown 
34022fe279fdSBarry Smith   Input Parameter:
3403bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
34043f2090d5SJed Brown 
3405bcf0153eSBarry Smith   Note:
3406bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
34073f2090d5SJed Brown   so most users would not generally call this routine themselves.
34083f2090d5SJed Brown 
34093f2090d5SJed Brown   Level: developer
34103f2090d5SJed Brown 
3411bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPostStep()`
34123f2090d5SJed Brown @*/
TSPostStep(TS ts)3413d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3414d71ae5a4SJacob Faibussowitsch {
34153f2090d5SJed Brown   PetscFunctionBegin;
34160700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3417ae60f76fSBarry Smith   if (ts->poststep) {
34185efd42a4SStefano Zampini     Vec              U;
3419ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3420ef8d1ce0SJohann Rudi     PetscBool        sameObject;
34215efd42a4SStefano Zampini     PetscObjectState sprev, spost;
34225efd42a4SStefano Zampini 
34239566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34249566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
34259566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
342625e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
34279566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
34289566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
34299566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
34309566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
343172ac3e02SJed Brown   }
34323ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
34333f2090d5SJed Brown }
34343f2090d5SJed Brown 
3435cd652676SJed Brown /*@
3436cd652676SJed Brown   TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3437cd652676SJed Brown 
3438c3339decSBarry Smith   Collective
3439cd652676SJed Brown 
34404165533cSJose E. Roman   Input Parameters:
3441cd652676SJed Brown + ts - time stepping context
3442cd652676SJed Brown - t  - time to interpolate to
3443cd652676SJed Brown 
34444165533cSJose E. Roman   Output Parameter:
34450910c330SBarry Smith . U - state at given time
3446cd652676SJed Brown 
3447cd652676SJed Brown   Level: intermediate
3448cd652676SJed Brown 
3449b43aa488SJacob Faibussowitsch   Developer Notes:
3450bcf0153eSBarry Smith   `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3451cd652676SJed Brown 
34521cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3453cd652676SJed Brown @*/
TSInterpolate(TS ts,PetscReal t,Vec U)3454d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3455d71ae5a4SJacob Faibussowitsch {
3456cd652676SJed Brown   PetscFunctionBegin;
3457cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3458b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
345963a3b9bcSJacob 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);
3460dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
34613ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3462cd652676SJed Brown }
3463cd652676SJed Brown 
3464d763cef2SBarry Smith /*@
34656d9e5789SSean Farley   TSStep - Steps one time step
3466d763cef2SBarry Smith 
3467c3339decSBarry Smith   Collective
3468d763cef2SBarry Smith 
3469d763cef2SBarry Smith   Input Parameter:
3470bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
3471d763cef2SBarry Smith 
347227829d71SBarry Smith   Level: developer
3473d763cef2SBarry Smith 
3474b8123daeSJed Brown   Notes:
3475bcf0153eSBarry Smith   The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
347627829d71SBarry Smith 
3477bcf0153eSBarry Smith   The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3478b8123daeSJed Brown   be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3479b8123daeSJed Brown 
3480bcf0153eSBarry Smith   This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3481bcf0153eSBarry Smith   time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
348225cb2221SBarry Smith 
34831cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3484d763cef2SBarry Smith @*/
TSStep(TS ts)3485d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3486d71ae5a4SJacob Faibussowitsch {
3487fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3488be5899b3SLisandro Dalcin   PetscReal        ptime;
3489d763cef2SBarry Smith 
3490d763cef2SBarry Smith   PetscFunctionBegin;
34910700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3492d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3493fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3494f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3495f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3496f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3497f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34989371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34999371c9d4SSatish Balay                                    &cite));
35009566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
35019566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3502136cf249SJames Wright   if (ts->eval_times)
3503136cf249SJames Wright     ts->eval_times->worktol = 0; /* In each step of TSSolve() 'eval_times->worktol' will be meaningfully defined (later) only once:
3504ca4445c7SIlya Fursov                                                    in TSAdaptChoose() or TSEvent_dt_cap(), and then reused till the end of the step */
3505d405a339SMatthew Knepley 
35068e562f8dSJames Wright   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
35073c633725SBarry 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()");
35083c633725SBarry 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");
3509a6772fa2SLisandro Dalcin 
3510c61711c8SStefano Zampini   if (!ts->vec_sol0) PetscCall(VecDuplicate(ts->vec_sol, &ts->vec_sol0));
3511c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol, ts->vec_sol0));
3512c61711c8SStefano Zampini   ts->time_step0 = ts->time_step;
3513c61711c8SStefano Zampini 
3514be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
35159371c9d4SSatish Balay   ptime = ts->ptime;
3516c61711c8SStefano Zampini 
35179371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
35182808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3519fc8dbba5SLisandro Dalcin 
35209566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3521dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
35229566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3523fc8dbba5SLisandro Dalcin 
3524fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3525be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
35262808aa04SLisandro Dalcin     ts->steps++;
3527be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
352828d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3529c6bf8827SStefano Zampini     ts->stepresize   = PETSC_FALSE;
3530d2daff3dSHong Zhang   }
3531fc8dbba5SLisandro Dalcin 
35325c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
35335c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
3534764c9dfdSStefano Zampini     if (ts->usessnes && ts->snes) PetscCall(SNESMonitorCancel(ts->snes));
353509cb0f53SBarry 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]);
35365c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
35375c9bbc89SJed Brown   }
35383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
353908c7845fSBarry Smith }
354008c7845fSBarry Smith 
354108c7845fSBarry Smith /*@
35427cbde773SLisandro Dalcin   TSEvaluateWLTE - Evaluate the weighted local truncation error norm
35437cbde773SLisandro Dalcin   at the end of a time step with a given order of accuracy.
35447cbde773SLisandro Dalcin 
3545c3339decSBarry Smith   Collective
35467cbde773SLisandro Dalcin 
35474165533cSJose E. Roman   Input Parameters:
35487cbde773SLisandro Dalcin + ts        - time stepping context
3549bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
35507cbde773SLisandro Dalcin 
355197bb3fdcSJose E. Roman   Input/Output Parameter:
3552bcf0153eSBarry Smith . order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
355397bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
355497bb3fdcSJose E. Roman 
355597bb3fdcSJose E. Roman   Output Parameter:
355697bb3fdcSJose E. Roman . wlte - the weighted local truncation error norm
35577cbde773SLisandro Dalcin 
35587cbde773SLisandro Dalcin   Level: advanced
35597cbde773SLisandro Dalcin 
3560bcf0153eSBarry Smith   Note:
35617cbde773SLisandro Dalcin   If the timestepper cannot evaluate the error in a particular step
35627cbde773SLisandro Dalcin   (eg. in the first step or restart steps after event handling),
35637cbde773SLisandro Dalcin   this routine returns wlte=-1.0 .
35647cbde773SLisandro Dalcin 
35651cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
35667cbde773SLisandro Dalcin @*/
TSEvaluateWLTE(TS ts,NormType wnormtype,PetscInt * order,PetscReal * wlte)3567d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3568d71ae5a4SJacob Faibussowitsch {
35697cbde773SLisandro Dalcin   PetscFunctionBegin;
35707cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35717cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3572064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
35734f572ea9SToby Isaac   if (order) PetscAssertPointer(order, 3);
35747cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
35754f572ea9SToby Isaac   PetscAssertPointer(wlte, 4);
35763c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3577dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
35783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
35797cbde773SLisandro Dalcin }
35807cbde773SLisandro Dalcin 
358105175c85SJed Brown /*@
358205175c85SJed Brown   TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
358305175c85SJed Brown 
3584c3339decSBarry Smith   Collective
358505175c85SJed Brown 
35864165533cSJose E. Roman   Input Parameters:
35871c3436cfSJed Brown + ts    - time stepping context
35881c3436cfSJed Brown . order - desired order of accuracy
3589195e9b02SBarry Smith - done  - whether the step was evaluated at this order (pass `NULL` to generate an error if not available)
359005175c85SJed Brown 
35914165533cSJose E. Roman   Output Parameter:
35920910c330SBarry Smith . U - state at the end of the current step
359305175c85SJed Brown 
359405175c85SJed Brown   Level: advanced
359505175c85SJed Brown 
3596108c343cSJed Brown   Notes:
3597108c343cSJed Brown   This function cannot be called until all stages have been evaluated.
3598108c343cSJed Brown 
3599bcf0153eSBarry 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.
3600bcf0153eSBarry Smith 
36011cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSStep()`, `TSAdapt`
360205175c85SJed Brown @*/
TSEvaluateStep(TS ts,PetscInt order,Vec U,PetscBool * done)3603d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3604d71ae5a4SJacob Faibussowitsch {
360505175c85SJed Brown   PetscFunctionBegin;
360605175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
360705175c85SJed Brown   PetscValidType(ts, 1);
36080910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3609dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
36103ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
361105175c85SJed Brown }
361205175c85SJed Brown 
3613aad739acSMatthew G. Knepley /*@C
36142e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3615aad739acSMatthew G. Knepley 
3616aad739acSMatthew G. Knepley   Not collective
3617aad739acSMatthew G. Knepley 
36184165533cSJose E. Roman   Input Parameter:
3619aad739acSMatthew G. Knepley . ts - time stepping context
3620aad739acSMatthew G. Knepley 
36214165533cSJose E. Roman   Output Parameter:
3622b43aa488SJacob Faibussowitsch . initCondition - The function which computes an initial condition
3623aad739acSMatthew G. Knepley 
362420f4b53cSBarry Smith   Calling sequence of `initCondition`:
362520f4b53cSBarry Smith + ts - The timestepping context
362620f4b53cSBarry Smith - u  - The input vector in which the initial condition is stored
3627bcf0153eSBarry Smith 
3628aad739acSMatthew G. Knepley   Level: advanced
3629aad739acSMatthew G. Knepley 
36301cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3631aad739acSMatthew G. Knepley @*/
TSGetComputeInitialCondition(TS ts,PetscErrorCode (** initCondition)(TS ts,Vec u))363214d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS ts, Vec u))
3633d71ae5a4SJacob Faibussowitsch {
3634aad739acSMatthew G. Knepley   PetscFunctionBegin;
3635aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36364f572ea9SToby Isaac   PetscAssertPointer(initCondition, 2);
36372e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
36383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3639aad739acSMatthew G. Knepley }
3640aad739acSMatthew G. Knepley 
3641aad739acSMatthew G. Knepley /*@C
36422e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3643aad739acSMatthew G. Knepley 
3644c3339decSBarry Smith   Logically collective
3645aad739acSMatthew G. Knepley 
36464165533cSJose E. Roman   Input Parameters:
3647aad739acSMatthew G. Knepley + ts            - time stepping context
36482e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3649aad739acSMatthew G. Knepley 
365020f4b53cSBarry Smith   Calling sequence of `initCondition`:
3651a96d6ef6SBarry Smith + ts - The timestepping context
365214d0ab18SJacob Faibussowitsch - e  - The input vector in which the initial condition is to be stored
3653aad739acSMatthew G. Knepley 
3654bcf0153eSBarry Smith   Level: advanced
3655bcf0153eSBarry Smith 
36561cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3657aad739acSMatthew G. Knepley @*/
TSSetComputeInitialCondition(TS ts,PetscErrorCode (* initCondition)(TS ts,Vec e))365814d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS ts, Vec e))
3659d71ae5a4SJacob Faibussowitsch {
3660aad739acSMatthew G. Knepley   PetscFunctionBegin;
3661aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
36622e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
36632e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
36643ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3665aad739acSMatthew G. Knepley }
3666aad739acSMatthew G. Knepley 
3667aad739acSMatthew G. Knepley /*@
3668bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3669aad739acSMatthew G. Knepley 
3670c3339decSBarry Smith   Collective
3671aad739acSMatthew G. Knepley 
36724165533cSJose E. Roman   Input Parameters:
3673aad739acSMatthew G. Knepley + ts - time stepping context
3674bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3675aad739acSMatthew G. Knepley 
3676aad739acSMatthew G. Knepley   Level: advanced
3677aad739acSMatthew G. Knepley 
36781cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3679aad739acSMatthew G. Knepley @*/
TSComputeInitialCondition(TS ts,Vec u)3680d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3681d71ae5a4SJacob Faibussowitsch {
3682aad739acSMatthew G. Knepley   PetscFunctionBegin;
3683aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3684aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3685dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
36863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3687aad739acSMatthew G. Knepley }
3688aad739acSMatthew G. Knepley 
3689aad739acSMatthew G. Knepley /*@C
3690aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3691aad739acSMatthew G. Knepley 
3692aad739acSMatthew G. Knepley   Not collective
3693aad739acSMatthew G. Knepley 
36944165533cSJose E. Roman   Input Parameter:
3695aad739acSMatthew G. Knepley . ts - time stepping context
3696aad739acSMatthew G. Knepley 
36974165533cSJose E. Roman   Output Parameter:
3698aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3699aad739acSMatthew G. Knepley 
370020f4b53cSBarry Smith   Calling sequence of `exactError`:
3701a96d6ef6SBarry Smith + ts - The timestepping context
3702a96d6ef6SBarry Smith . u  - The approximate solution vector
370320f4b53cSBarry Smith - e  - The vector in which the error is stored
3704aad739acSMatthew G. Knepley 
3705bcf0153eSBarry Smith   Level: advanced
3706bcf0153eSBarry Smith 
370742747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSComputeExactError()`
3708aad739acSMatthew G. Knepley @*/
TSGetComputeExactError(TS ts,PetscErrorCode (** exactError)(TS ts,Vec u,Vec e))370914d0ab18SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS ts, Vec u, Vec e))
3710d71ae5a4SJacob Faibussowitsch {
3711aad739acSMatthew G. Knepley   PetscFunctionBegin;
3712aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
37134f572ea9SToby Isaac   PetscAssertPointer(exactError, 2);
3714aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
37153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3716aad739acSMatthew G. Knepley }
3717aad739acSMatthew G. Knepley 
3718aad739acSMatthew G. Knepley /*@C
3719aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3720aad739acSMatthew G. Knepley 
3721c3339decSBarry Smith   Logically collective
3722aad739acSMatthew G. Knepley 
37234165533cSJose E. Roman   Input Parameters:
3724aad739acSMatthew G. Knepley + ts         - time stepping context
3725aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3726aad739acSMatthew G. Knepley 
372720f4b53cSBarry Smith   Calling sequence of `exactError`:
3728a96d6ef6SBarry Smith + ts - The timestepping context
3729a96d6ef6SBarry Smith . u  - The approximate solution vector
373020f4b53cSBarry Smith - e  - The  vector in which the error is stored
3731aad739acSMatthew G. Knepley 
3732bcf0153eSBarry Smith   Level: advanced
3733bcf0153eSBarry Smith 
37341cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3735aad739acSMatthew G. Knepley @*/
TSSetComputeExactError(TS ts,PetscErrorCode (* exactError)(TS ts,Vec u,Vec e))373614d0ab18SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS ts, Vec u, Vec e))
3737d71ae5a4SJacob Faibussowitsch {
3738aad739acSMatthew G. Knepley   PetscFunctionBegin;
3739aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3740f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3741aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
37423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3743aad739acSMatthew G. Knepley }
3744aad739acSMatthew G. Knepley 
3745aad739acSMatthew G. Knepley /*@
3746bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3747aad739acSMatthew G. Knepley 
3748c3339decSBarry Smith   Collective
3749aad739acSMatthew G. Knepley 
37504165533cSJose E. Roman   Input Parameters:
3751aad739acSMatthew G. Knepley + ts - time stepping context
3752aad739acSMatthew G. Knepley . u  - The approximate solution
3753bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3754aad739acSMatthew G. Knepley 
3755aad739acSMatthew G. Knepley   Level: advanced
3756aad739acSMatthew G. Knepley 
37571cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3758aad739acSMatthew G. Knepley @*/
TSComputeExactError(TS ts,Vec u,Vec e)3759d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3760d71ae5a4SJacob Faibussowitsch {
3761aad739acSMatthew G. Knepley   PetscFunctionBegin;
3762aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3763aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3764aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3765dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
37663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
3767aad739acSMatthew G. Knepley }
3768aad739acSMatthew G. Knepley 
37696bd3a4fdSStefano Zampini /*@C
37706bd3a4fdSStefano Zampini   TSSetResize - Sets the resize callbacks.
37716bd3a4fdSStefano Zampini 
37726bd3a4fdSStefano Zampini   Logically Collective
37736bd3a4fdSStefano Zampini 
37746bd3a4fdSStefano Zampini   Input Parameters:
37756bd3a4fdSStefano Zampini + ts       - The `TS` context obtained from `TSCreate()`
3776ecc87898SStefano Zampini . rollback - Whether a resize will restart the step
37776bd3a4fdSStefano Zampini . setup    - The setup function
377814d0ab18SJacob Faibussowitsch . transfer - The transfer function
377914d0ab18SJacob Faibussowitsch - ctx      - [optional] The user-defined context
37806bd3a4fdSStefano Zampini 
37816bd3a4fdSStefano Zampini   Calling sequence of `setup`:
37828847d985SBarry Smith + ts     - the `TS` context
37836bd3a4fdSStefano Zampini . step   - the current step
37846bd3a4fdSStefano Zampini . time   - the current time
37856bd3a4fdSStefano Zampini . state  - the current vector of state
37866bd3a4fdSStefano Zampini . resize - (output parameter) `PETSC_TRUE` if need resizing, `PETSC_FALSE` otherwise
37876bd3a4fdSStefano Zampini - ctx    - user defined context
37886bd3a4fdSStefano Zampini 
37896bd3a4fdSStefano Zampini   Calling sequence of `transfer`:
37908847d985SBarry Smith + ts      - the `TS` context
37916bd3a4fdSStefano Zampini . nv      - the number of vectors to be transferred
37926bd3a4fdSStefano Zampini . vecsin  - array of vectors to be transferred
37936bd3a4fdSStefano Zampini . vecsout - array of transferred vectors
37946bd3a4fdSStefano Zampini - ctx     - user defined context
37956bd3a4fdSStefano Zampini 
37966bd3a4fdSStefano Zampini   Notes:
3797ecc87898SStefano Zampini   The `setup` function is called inside `TSSolve()` after `TSEventHandler()` or after `TSPostStep()`
3798ecc87898SStefano Zampini   depending on the `rollback` value: if `rollback` is true, then these callbacks behave as error indicators
3799ecc87898SStefano Zampini   and will flag the need to remesh and restart the current step. Otherwise, they will simply flag the solver
3800ecc87898SStefano Zampini   that the size of the discrete problem has changed.
3801ecc87898SStefano Zampini   In both cases, the solver will collect the needed vectors that will be
3802ecc87898SStefano Zampini   transferred from the old to the new sizes using the `transfer` callback. These vectors will include the
3803ecc87898SStefano Zampini   current solution vector, and other vectors needed by the specific solver used.
38046bd3a4fdSStefano Zampini   For example, `TSBDF` uses previous solutions vectors to solve for the next time step.
38056bd3a4fdSStefano Zampini   Other application specific objects associated with the solver, i.e. Jacobian matrices and `DM`,
38066bd3a4fdSStefano Zampini   will be automatically reset if the sizes are changed and they must be specified again by the user
38076bd3a4fdSStefano Zampini   inside the `transfer` function.
38086bd3a4fdSStefano Zampini   The input and output arrays passed to `transfer` are allocated by PETSc.
38096bd3a4fdSStefano Zampini   Vectors in `vecsout` must be created by the user.
38106bd3a4fdSStefano Zampini   Ownership of vectors in `vecsout` is transferred to PETSc.
38116bd3a4fdSStefano Zampini 
38126bd3a4fdSStefano Zampini   Level: advanced
38136bd3a4fdSStefano Zampini 
38146bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetDM()`, `TSSetIJacobian()`, `TSSetRHSJacobian()`
38156bd3a4fdSStefano Zampini @*/
TSSetResize(TS ts,PetscBool rollback,PetscErrorCode (* setup)(TS ts,PetscInt step,PetscReal time,Vec state,PetscBool * resize,PetscCtx ctx),PetscErrorCode (* transfer)(TS ts,PetscInt nv,Vec vecsin[],Vec vecsout[],PetscCtx ctx),PetscCtx ctx)3816*2a8381b2SBarry Smith PetscErrorCode TSSetResize(TS ts, PetscBool rollback, PetscErrorCode (*setup)(TS ts, PetscInt step, PetscReal time, Vec state, PetscBool *resize, PetscCtx ctx), PetscErrorCode (*transfer)(TS ts, PetscInt nv, Vec vecsin[], Vec vecsout[], PetscCtx ctx), PetscCtx ctx)
38176bd3a4fdSStefano Zampini {
38186bd3a4fdSStefano Zampini   PetscFunctionBegin;
38196bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3820ecc87898SStefano Zampini   ts->resizerollback = rollback;
38216bd3a4fdSStefano Zampini   ts->resizesetup    = setup;
38226bd3a4fdSStefano Zampini   ts->resizetransfer = transfer;
38236bd3a4fdSStefano Zampini   ts->resizectx      = ctx;
38246bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38256bd3a4fdSStefano Zampini }
38266bd3a4fdSStefano Zampini 
382714d0ab18SJacob Faibussowitsch /*
38286bd3a4fdSStefano Zampini   TSResizeRegisterOrRetrieve - Register or import vectors transferred with `TSResize()`.
38296bd3a4fdSStefano Zampini 
38306bd3a4fdSStefano Zampini   Collective
38316bd3a4fdSStefano Zampini 
38326bd3a4fdSStefano Zampini   Input Parameters:
38336bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
38346bd3a4fdSStefano 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.
38356bd3a4fdSStefano Zampini 
38366bd3a4fdSStefano Zampini   Level: developer
38376bd3a4fdSStefano Zampini 
38386bd3a4fdSStefano Zampini   Note:
38396bd3a4fdSStefano Zampini   `TSResizeRegisterOrRetrieve()` is declared PETSC_INTERN since it is
38406bd3a4fdSStefano Zampini    used within time stepping implementations,
38416bd3a4fdSStefano Zampini    so most users would not generally call this routine themselves.
38426bd3a4fdSStefano Zampini 
38436bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
38446bd3a4fdSStefano Zampini @*/
TSResizeRegisterOrRetrieve(TS ts,PetscBool flg)384514d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeRegisterOrRetrieve(TS ts, PetscBool flg)
38466bd3a4fdSStefano Zampini {
38476bd3a4fdSStefano Zampini   PetscFunctionBegin;
38486bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38496bd3a4fdSStefano Zampini   PetscTryTypeMethod(ts, resizeregister, flg);
38506bd3a4fdSStefano Zampini   /* PetscTryTypeMethod(adapt, resizeregister, flg); */
38516bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38526bd3a4fdSStefano Zampini }
38536bd3a4fdSStefano Zampini 
TSResizeReset(TS ts)385414d0ab18SJacob Faibussowitsch static PetscErrorCode TSResizeReset(TS ts)
38556bd3a4fdSStefano Zampini {
38566bd3a4fdSStefano Zampini   PetscFunctionBegin;
38576bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38586bd3a4fdSStefano Zampini   PetscCall(PetscObjectListDestroy(&ts->resizetransferobjs));
38596bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38606bd3a4fdSStefano Zampini }
38616bd3a4fdSStefano Zampini 
TSResizeTransferVecs(TS ts,PetscInt cnt,Vec vecsin[],Vec vecsout[])38626bd3a4fdSStefano Zampini static PetscErrorCode TSResizeTransferVecs(TS ts, PetscInt cnt, Vec vecsin[], Vec vecsout[])
38636bd3a4fdSStefano Zampini {
38646bd3a4fdSStefano Zampini   PetscFunctionBegin;
38656bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38666bd3a4fdSStefano Zampini   PetscValidLogicalCollectiveInt(ts, cnt, 2);
38676bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPush(vecsin[i]));
38686bd3a4fdSStefano Zampini   if (ts->resizetransfer) {
38696bd3a4fdSStefano Zampini     PetscCall(PetscInfo(ts, "Transferring %" PetscInt_FMT " vectors\n", cnt));
38706bd3a4fdSStefano Zampini     PetscCallBack("TS callback resize transfer", (*ts->resizetransfer)(ts, cnt, vecsin, vecsout, ts->resizectx));
38716bd3a4fdSStefano Zampini   }
38726bd3a4fdSStefano Zampini   for (PetscInt i = 0; i < cnt; i++) PetscCall(VecLockReadPop(vecsin[i]));
38736bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
38746bd3a4fdSStefano Zampini }
38756bd3a4fdSStefano Zampini 
38766bd3a4fdSStefano Zampini /*@C
38776bd3a4fdSStefano Zampini   TSResizeRegisterVec - Register a vector to be transferred with `TSResize()`.
38786bd3a4fdSStefano Zampini 
38796bd3a4fdSStefano Zampini   Collective
38806bd3a4fdSStefano Zampini 
38816bd3a4fdSStefano Zampini   Input Parameters:
38826bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3883baca6076SPierre Jolivet . name - A string identifying the vector
38846bd3a4fdSStefano Zampini - vec  - The vector
38856bd3a4fdSStefano Zampini 
38866bd3a4fdSStefano Zampini   Level: developer
38876bd3a4fdSStefano Zampini 
38886bd3a4fdSStefano Zampini   Note:
38896bd3a4fdSStefano Zampini   `TSResizeRegisterVec()` is typically used within time stepping implementations,
38906bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
38916bd3a4fdSStefano Zampini 
38926bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRetrieveVec()`
38936bd3a4fdSStefano Zampini @*/
TSResizeRegisterVec(TS ts,const char name[],Vec vec)3894cc4c1da9SBarry Smith PetscErrorCode TSResizeRegisterVec(TS ts, const char name[], Vec vec)
38956bd3a4fdSStefano Zampini {
38966bd3a4fdSStefano Zampini   PetscFunctionBegin;
38976bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
38984f572ea9SToby Isaac   PetscAssertPointer(name, 2);
38996bd3a4fdSStefano Zampini   if (vec) PetscValidHeaderSpecific(vec, VEC_CLASSID, 3);
39006bd3a4fdSStefano Zampini   PetscCall(PetscObjectListAdd(&ts->resizetransferobjs, name, (PetscObject)vec));
39016bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39026bd3a4fdSStefano Zampini }
39036bd3a4fdSStefano Zampini 
39046bd3a4fdSStefano Zampini /*@C
39056bd3a4fdSStefano Zampini   TSResizeRetrieveVec - Retrieve a vector registered with `TSResizeRegisterVec()`.
39066bd3a4fdSStefano Zampini 
39076bd3a4fdSStefano Zampini   Collective
39086bd3a4fdSStefano Zampini 
39096bd3a4fdSStefano Zampini   Input Parameters:
39106bd3a4fdSStefano Zampini + ts   - The `TS` context obtained from `TSCreate()`
3911baca6076SPierre Jolivet . name - A string identifying the vector
39126bd3a4fdSStefano Zampini - vec  - The vector
39136bd3a4fdSStefano Zampini 
39146bd3a4fdSStefano Zampini   Level: developer
39156bd3a4fdSStefano Zampini 
39166bd3a4fdSStefano Zampini   Note:
39176bd3a4fdSStefano Zampini   `TSResizeRetrieveVec()` is typically used within time stepping implementations,
39186bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39196bd3a4fdSStefano Zampini 
39206bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`, `TSResize()`, `TSResizeRegisterVec()`
39216bd3a4fdSStefano Zampini @*/
TSResizeRetrieveVec(TS ts,const char name[],Vec * vec)3922cc4c1da9SBarry Smith PetscErrorCode TSResizeRetrieveVec(TS ts, const char name[], Vec *vec)
39236bd3a4fdSStefano Zampini {
39246bd3a4fdSStefano Zampini   PetscFunctionBegin;
39256bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39264f572ea9SToby Isaac   PetscAssertPointer(name, 2);
39274f572ea9SToby Isaac   PetscAssertPointer(vec, 3);
39286bd3a4fdSStefano Zampini   PetscCall(PetscObjectListFind(ts->resizetransferobjs, name, (PetscObject *)vec));
39296bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39306bd3a4fdSStefano Zampini }
39316bd3a4fdSStefano Zampini 
TSResizeGetVecArray(TS ts,PetscInt * nv,const char ** names[],Vec * vecs[])39326bd3a4fdSStefano Zampini static PetscErrorCode TSResizeGetVecArray(TS ts, PetscInt *nv, const char **names[], Vec *vecs[])
39336bd3a4fdSStefano Zampini {
39346bd3a4fdSStefano Zampini   PetscInt        cnt;
39356bd3a4fdSStefano Zampini   PetscObjectList tmp;
39366bd3a4fdSStefano Zampini   Vec            *vecsin  = NULL;
39376bd3a4fdSStefano Zampini   const char    **namesin = NULL;
39386bd3a4fdSStefano Zampini 
39396bd3a4fdSStefano Zampini   PetscFunctionBegin;
39406bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next)
39416bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) cnt++;
394203ba6ac9SBarry Smith   if (names) PetscCall(PetscMalloc1(cnt, &namesin));
394303ba6ac9SBarry Smith   if (vecs) PetscCall(PetscMalloc1(cnt, &vecsin));
39446bd3a4fdSStefano Zampini   for (tmp = ts->resizetransferobjs, cnt = 0; tmp; tmp = tmp->next) {
39456bd3a4fdSStefano Zampini     if (tmp->obj && tmp->obj->classid == VEC_CLASSID) {
39466bd3a4fdSStefano Zampini       if (vecs) vecsin[cnt] = (Vec)tmp->obj;
39476bd3a4fdSStefano Zampini       if (names) namesin[cnt] = tmp->name;
39486bd3a4fdSStefano Zampini       cnt++;
39496bd3a4fdSStefano Zampini     }
39506bd3a4fdSStefano Zampini   }
39516bd3a4fdSStefano Zampini   if (nv) *nv = cnt;
39526bd3a4fdSStefano Zampini   if (names) *names = namesin;
39536bd3a4fdSStefano Zampini   if (vecs) *vecs = vecsin;
39546bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
39556bd3a4fdSStefano Zampini }
39566bd3a4fdSStefano Zampini 
39576bd3a4fdSStefano Zampini /*@
39586bd3a4fdSStefano Zampini   TSResize - Runs the user-defined transfer functions provided with `TSSetResize()`
39596bd3a4fdSStefano Zampini 
39606bd3a4fdSStefano Zampini   Collective
39616bd3a4fdSStefano Zampini 
39626bd3a4fdSStefano Zampini   Input Parameter:
39636bd3a4fdSStefano Zampini . ts - The `TS` context obtained from `TSCreate()`
39646bd3a4fdSStefano Zampini 
39656bd3a4fdSStefano Zampini   Level: developer
39666bd3a4fdSStefano Zampini 
39676bd3a4fdSStefano Zampini   Note:
39686bd3a4fdSStefano Zampini   `TSResize()` is typically used within time stepping implementations,
39696bd3a4fdSStefano Zampini   so most users would not generally call this routine themselves.
39706bd3a4fdSStefano Zampini 
39716bd3a4fdSStefano Zampini .seealso: [](ch_ts), `TS`, `TSSetResize()`
39726bd3a4fdSStefano Zampini @*/
TSResize(TS ts)39736bd3a4fdSStefano Zampini PetscErrorCode TSResize(TS ts)
39746bd3a4fdSStefano Zampini {
39756bd3a4fdSStefano Zampini   PetscInt     nv      = 0;
39766bd3a4fdSStefano Zampini   const char **names   = NULL;
39776bd3a4fdSStefano Zampini   Vec         *vecsin  = NULL;
39786bd3a4fdSStefano Zampini   const char  *solname = "ts:vec_sol";
39796bd3a4fdSStefano Zampini 
39806bd3a4fdSStefano Zampini   PetscFunctionBegin;
39816bd3a4fdSStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3982ecc87898SStefano Zampini   if (!ts->resizesetup) PetscFunctionReturn(PETSC_SUCCESS);
39836bd3a4fdSStefano Zampini   if (ts->resizesetup) {
39846bd3a4fdSStefano Zampini     PetscCall(VecLockReadPush(ts->vec_sol));
3985c6bf8827SStefano Zampini     PetscCallBack("TS callback resize setup", (*ts->resizesetup)(ts, ts->steps, ts->ptime, ts->vec_sol, &ts->stepresize, ts->resizectx));
39866bd3a4fdSStefano Zampini     PetscCall(VecLockReadPop(ts->vec_sol));
3987c6bf8827SStefano Zampini     if (ts->stepresize) {
3988ecc87898SStefano Zampini       if (ts->resizerollback) {
3989ecc87898SStefano Zampini         PetscCall(TSRollBack(ts));
3990ecc87898SStefano Zampini         ts->time_step = ts->time_step0;
3991ecc87898SStefano Zampini       }
39926bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, solname, ts->vec_sol));
39936bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_TRUE)); /* specific impls register their own objects */
39946bd3a4fdSStefano Zampini     }
39956bd3a4fdSStefano Zampini   }
39966bd3a4fdSStefano Zampini 
39976bd3a4fdSStefano Zampini   PetscCall(TSResizeGetVecArray(ts, &nv, &names, &vecsin));
39986bd3a4fdSStefano Zampini   if (nv) {
39996bd3a4fdSStefano Zampini     Vec *vecsout, vecsol;
40006bd3a4fdSStefano Zampini 
40016bd3a4fdSStefano Zampini     /* Reset internal objects */
40026bd3a4fdSStefano Zampini     PetscCall(TSReset(ts));
40036bd3a4fdSStefano Zampini 
4004ecc87898SStefano Zampini     /* Transfer needed vectors (users can call SetJacobian, SetDM, etc. here) */
40056bd3a4fdSStefano Zampini     PetscCall(PetscCalloc1(nv, &vecsout));
40066bd3a4fdSStefano Zampini     PetscCall(TSResizeTransferVecs(ts, nv, vecsin, vecsout));
40076bd3a4fdSStefano Zampini     for (PetscInt i = 0; i < nv; i++) {
4008ecc87898SStefano Zampini       const char *name;
4009ecc87898SStefano Zampini       char       *oname;
4010ecc87898SStefano Zampini 
4011ecc87898SStefano Zampini       PetscCall(PetscObjectGetName((PetscObject)vecsin[i], &name));
4012ecc87898SStefano Zampini       PetscCall(PetscStrallocpy(name, &oname));
40136bd3a4fdSStefano Zampini       PetscCall(TSResizeRegisterVec(ts, names[i], vecsout[i]));
4014ecc87898SStefano Zampini       if (vecsout[i]) PetscCall(PetscObjectSetName((PetscObject)vecsout[i], oname));
4015ecc87898SStefano Zampini       PetscCall(PetscFree(oname));
40166bd3a4fdSStefano Zampini       PetscCall(VecDestroy(&vecsout[i]));
40176bd3a4fdSStefano Zampini     }
40186bd3a4fdSStefano Zampini     PetscCall(PetscFree(vecsout));
40196bd3a4fdSStefano Zampini     PetscCall(TSResizeRegisterOrRetrieve(ts, PETSC_FALSE)); /* specific impls import the transferred objects */
40206bd3a4fdSStefano Zampini 
40216bd3a4fdSStefano Zampini     PetscCall(TSResizeRetrieveVec(ts, solname, &vecsol));
40226bd3a4fdSStefano Zampini     if (vecsol) PetscCall(TSSetSolution(ts, vecsol));
40236bd3a4fdSStefano Zampini     PetscAssert(ts->vec_sol, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_NULL, "Missing TS solution");
40246bd3a4fdSStefano Zampini   }
40256bd3a4fdSStefano Zampini 
40266bd3a4fdSStefano Zampini   PetscCall(PetscFree(names));
40276bd3a4fdSStefano Zampini   PetscCall(PetscFree(vecsin));
40286bd3a4fdSStefano Zampini   PetscCall(TSResizeReset(ts));
40296bd3a4fdSStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
40306bd3a4fdSStefano Zampini }
40316bd3a4fdSStefano Zampini 
4032b1cb36f3SHong Zhang /*@
40336a4d4014SLisandro Dalcin   TSSolve - Steps the requested number of timesteps.
40346a4d4014SLisandro Dalcin 
4035c3339decSBarry Smith   Collective
40366a4d4014SLisandro Dalcin 
4037d8d19677SJose E. Roman   Input Parameters:
4038bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4039bcf0153eSBarry Smith - u  - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
40400b4b7b1cSBarry Smith        otherwise it must contain the initial conditions and will contain the solution at the final requested time
40415a3a76d0SJed Brown 
40426a4d4014SLisandro Dalcin   Level: beginner
40436a4d4014SLisandro Dalcin 
40445a3a76d0SJed Brown   Notes:
40455a3a76d0SJed Brown   The final time returned by this function may be different from the time of the internally
4046bcf0153eSBarry Smith   held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
40475a3a76d0SJed Brown   stepped over the final time.
40485a3a76d0SJed Brown 
40491cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
40506a4d4014SLisandro Dalcin @*/
TSSolve(TS ts,Vec u)4051d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
4052d71ae5a4SJacob Faibussowitsch {
4053b06615a5SLisandro Dalcin   Vec solution;
4054f22f69f0SBarry Smith 
40556a4d4014SLisandro Dalcin   PetscFunctionBegin;
40560700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4057f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
4058303a5415SBarry Smith 
40599566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
4060ee41a567SStefano 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 */
40610910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
40629566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
40639566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
40649566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
40655a3a76d0SJed Brown     }
40669566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
40673c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
40681baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
40699566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
40709566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
4071a6772fa2SLisandro Dalcin 
40728e562f8dSJames Wright   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->run_steps != PETSC_INT_MAX || ts->max_steps != PETSC_INT_MAX, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime(), TSSetMaxSteps(), or TSSetRunSteps() or use -ts_max_time <time>, -ts_max_steps <steps>, -ts_run_steps <steps>");
40733c633725SBarry 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()");
40743c633725SBarry 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");
4075136cf249SJames Wright   PetscCheck(!(ts->eval_times && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span or evaluation times");
40764a658b32SHong Zhang 
4077136cf249SJames Wright   if (ts->eval_times) {
4078264c38b7SJames Wright     if (!ts->eval_times->sol_vecs) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
4079136cf249SJames Wright     for (PetscInt i = 0; i < ts->eval_times->num_time_points; i++) {
4080136cf249SJames Wright       PetscBool is_close = PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[i], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4081136cf249SJames Wright       if (ts->ptime <= ts->eval_times->time_points[i] || is_close) {
4082136cf249SJames Wright         ts->eval_times->time_point_idx = i;
4083264c38b7SJames Wright 
4084264c38b7SJames Wright         PetscBool is_ptime_in_sol_times = PETSC_FALSE; // If current solution has already been saved, we should not save it again
4085264c38b7SJames Wright         if (ts->eval_times->sol_idx > 0) is_ptime_in_sol_times = PetscIsCloseAtTol(ts->ptime, ts->eval_times->sol_times[ts->eval_times->sol_idx - 1], ts->eval_times->reltol * ts->time_step + ts->eval_times->abstol, 0);
4086264c38b7SJames Wright         if (is_close && !is_ptime_in_sol_times) {
4087264c38b7SJames Wright           PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4088264c38b7SJames Wright           ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4089264c38b7SJames Wright           ts->eval_times->sol_idx++;
4090136cf249SJames Wright           ts->eval_times->time_point_idx++;
40918343f784SJames Wright         }
40928343f784SJames Wright         break;
40938343f784SJames Wright       }
40948343f784SJames Wright     }
40954a658b32SHong Zhang   }
4096a6772fa2SLisandro Dalcin 
40971baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
4098715f1b00SHong Zhang 
4099e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
4100715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
4101e7069c78SShri      TSTrajectory to incorrectly save the output files
4102e7069c78SShri   */
4103715f1b00SHong Zhang   /* reset time step and iteration counters */
41042808aa04SLisandro Dalcin   if (!ts->steps) {
41055ef26d82SJed Brown     ts->ksp_its           = 0;
41065ef26d82SJed Brown     ts->snes_its          = 0;
4107c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
4108c610991cSLisandro Dalcin     ts->reject            = 0;
41092808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
41102808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
4111c6bf8827SStefano Zampini     ts->stepresize        = PETSC_FALSE;
41127d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
41132808aa04SLisandro Dalcin   }
4114e97c63d7SStefano Zampini 
4115136cf249SJames Wright   /* make sure initial time step does not overshoot final time or the next point in evaluation times */
4116e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
41174a658b32SHong Zhang     PetscReal maxdt;
4118e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
4119e97c63d7SStefano Zampini 
4120136cf249SJames Wright     if (ts->eval_times) maxdt = ts->eval_times->time_points[ts->eval_times->time_point_idx] - ts->ptime;
41214a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
4122e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
4123e97c63d7SStefano Zampini   }
4124193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
4125193ac0bcSJed Brown 
4126900f6b5bSMatthew G. Knepley   {
4127900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
4128900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
4129900f6b5bSMatthew G. Knepley     PetscBool         flg;
4130900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
4131900f6b5bSMatthew G. Knepley 
4132900f6b5bSMatthew G. Knepley     if (!incall) {
4133900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
4134648c30bcSBarry Smith       PetscCall(PetscOptionsCreateViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
4135900f6b5bSMatthew G. Knepley       if (flg) {
4136900f6b5bSMatthew G. Knepley         PetscConvEst conv;
4137900f6b5bSMatthew G. Knepley         DM           dm;
4138900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
4139900f6b5bSMatthew G. Knepley         PetscInt     Nf;
4140f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
4141900f6b5bSMatthew G. Knepley 
4142900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
41439566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
41449566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
41459566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
41469566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
41479566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
41489566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
41499566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
41509566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
41519566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
41529566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
41539566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
41549566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
41559566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
4156648c30bcSBarry Smith         PetscCall(PetscViewerDestroy(&viewer));
41579566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
41589566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
4159900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
4160900f6b5bSMatthew G. Knepley       }
4161900f6b5bSMatthew G. Knepley     }
4162900f6b5bSMatthew G. Knepley   }
4163900f6b5bSMatthew G. Knepley 
41649566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
4165f05ece33SBarry Smith 
4166193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
4167dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
41689566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
4169cc708dedSBarry Smith     ts->solvetime = ts->ptime;
4170a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
4171be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
4172db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
4173db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
4174e7069c78SShri 
41752808aa04SLisandro Dalcin     if (!ts->steps) {
41769566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
41779566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
41782808aa04SLisandro Dalcin     }
41796427ac75SLisandro Dalcin 
41808e562f8dSJames Wright     ts->start_step = ts->steps; // records starting step
4181e1a7a14fSJed Brown     while (!ts->reason) {
41829566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
4183c6bf8827SStefano Zampini       if (!ts->steprollback || (ts->stepresize && ts->resizerollback)) PetscCall(TSPreStep(ts));
41849566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
41851baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
41861baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
4187cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
41887b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
41899566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
41907b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4191b1cb36f3SHong Zhang       }
419258818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
41937b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
41949566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
41957b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
4196715f1b00SHong Zhang       }
41979566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
41989566063dSJacob 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. */
41991baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
4200ecc87898SStefano Zampini       if (!ts->steprollback && ts->resizerollback) PetscCall(TSResize(ts));
420190d719a4SStefano Zampini       /* check convergence */
420290d719a4SStefano Zampini       if (!ts->reason) {
42038e562f8dSJames Wright         if ((ts->steps - ts->start_step) >= ts->run_steps) ts->reason = TS_CONVERGED_ITS;
42048e562f8dSJames Wright         else if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
420590d719a4SStefano Zampini         else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
420690d719a4SStefano Zampini       }
4207e783b05fSHong Zhang       if (!ts->steprollback) {
42089566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
42099566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
4210ecc87898SStefano Zampini         if (!ts->resizerollback) PetscCall(TSResize(ts));
4211ca4445c7SIlya Fursov 
421226077dccSJames Wright         if (ts->eval_times && ts->eval_times->time_point_idx < ts->eval_times->num_time_points && ts->reason >= 0) {
4213136cf249SJames Wright           PetscCheck(ts->eval_times->worktol > 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_PLIB, "Unexpected state !(eval_times->worktol > 0) in TSSolve()");
4214136cf249SJames Wright           if (PetscIsCloseAtTol(ts->ptime, ts->eval_times->time_points[ts->eval_times->time_point_idx], ts->eval_times->worktol, 0)) {
4215264c38b7SJames Wright             ts->eval_times->sol_times[ts->eval_times->sol_idx] = ts->ptime;
4216264c38b7SJames Wright             PetscCall(VecCopy(ts->vec_sol, ts->eval_times->sol_vecs[ts->eval_times->sol_idx]));
4217264c38b7SJames Wright             ts->eval_times->sol_idx++;
4218136cf249SJames Wright             ts->eval_times->time_point_idx++;
42198343f784SJames Wright           }
4220ca4445c7SIlya Fursov         }
4221aeb4809dSShri Abhyankar       }
4222193ac0bcSJed Brown     }
42239566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
42246427ac75SLisandro Dalcin 
422549354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
42265dbbf88eSStefano Zampini       if (!u) u = ts->vec_sol;
42279566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
4228cc708dedSBarry Smith       ts->solvetime = ts->max_time;
4229b06615a5SLisandro Dalcin       solution      = u;
42309566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
42310574a7fbSJed Brown     } else {
42329566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
4233cc708dedSBarry Smith       ts->solvetime = ts->ptime;
4234b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
42350574a7fbSJed Brown     }
4236193ac0bcSJed Brown   }
4237d2daff3dSHong Zhang 
42389566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
42399566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
42409566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
42411baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
42423ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
42436a4d4014SLisandro Dalcin }
42446a4d4014SLisandro Dalcin 
4245d763cef2SBarry Smith /*@
4246b8123daeSJed Brown   TSGetTime - Gets the time of the most recently completed step.
4247d763cef2SBarry Smith 
4248d763cef2SBarry Smith   Not Collective
4249d763cef2SBarry Smith 
4250d763cef2SBarry Smith   Input Parameter:
4251bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4252d763cef2SBarry Smith 
4253d763cef2SBarry Smith   Output Parameter:
4254bcf0153eSBarry Smith . t - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
4255d763cef2SBarry Smith 
4256d763cef2SBarry Smith   Level: beginner
4257d763cef2SBarry Smith 
4258b8123daeSJed Brown   Note:
4259bcf0153eSBarry Smith   When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
4260bcf0153eSBarry Smith   `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
4261b8123daeSJed Brown 
4262a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
4263d763cef2SBarry Smith @*/
TSGetTime(TS ts,PetscReal * t)4264d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
4265d71ae5a4SJacob Faibussowitsch {
4266d763cef2SBarry Smith   PetscFunctionBegin;
42670700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42684f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4269d763cef2SBarry Smith   *t = ts->ptime;
42703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4271d763cef2SBarry Smith }
4272d763cef2SBarry Smith 
4273e5e524a1SHong Zhang /*@
4274e5e524a1SHong Zhang   TSGetPrevTime - Gets the starting time of the previously completed step.
4275e5e524a1SHong Zhang 
4276e5e524a1SHong Zhang   Not Collective
4277e5e524a1SHong Zhang 
4278e5e524a1SHong Zhang   Input Parameter:
4279bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
4280e5e524a1SHong Zhang 
4281e5e524a1SHong Zhang   Output Parameter:
4282e5e524a1SHong Zhang . t - the previous time
4283e5e524a1SHong Zhang 
4284e5e524a1SHong Zhang   Level: beginner
4285e5e524a1SHong Zhang 
4286a94f484eSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
4287e5e524a1SHong Zhang @*/
TSGetPrevTime(TS ts,PetscReal * t)4288d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
4289d71ae5a4SJacob Faibussowitsch {
4290e5e524a1SHong Zhang   PetscFunctionBegin;
4291e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
42924f572ea9SToby Isaac   PetscAssertPointer(t, 2);
4293e5e524a1SHong Zhang   *t = ts->ptime_prev;
42943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4295e5e524a1SHong Zhang }
4296e5e524a1SHong Zhang 
42976a4d4014SLisandro Dalcin /*@
42986a4d4014SLisandro Dalcin   TSSetTime - Allows one to reset the time.
42996a4d4014SLisandro Dalcin 
4300c3339decSBarry Smith   Logically Collective
43016a4d4014SLisandro Dalcin 
43026a4d4014SLisandro Dalcin   Input Parameters:
4303bcf0153eSBarry Smith + ts - the `TS` context obtained from `TSCreate()`
4304b43aa488SJacob Faibussowitsch - t  - the time
43056a4d4014SLisandro Dalcin 
43066a4d4014SLisandro Dalcin   Level: intermediate
43076a4d4014SLisandro Dalcin 
43081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
43096a4d4014SLisandro Dalcin @*/
TSSetTime(TS ts,PetscReal t)4310d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
4311d71ae5a4SJacob Faibussowitsch {
43126a4d4014SLisandro Dalcin   PetscFunctionBegin;
43130700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4314c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
43156a4d4014SLisandro Dalcin   ts->ptime = t;
43163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
43176a4d4014SLisandro Dalcin }
43186a4d4014SLisandro Dalcin 
4319cc4c1da9SBarry Smith /*@
4320d763cef2SBarry Smith   TSSetOptionsPrefix - Sets the prefix used for searching for all
4321d763cef2SBarry Smith   TS options in the database.
4322d763cef2SBarry Smith 
4323c3339decSBarry Smith   Logically Collective
4324d763cef2SBarry Smith 
4325d8d19677SJose E. Roman   Input Parameters:
4326bcf0153eSBarry Smith + ts     - The `TS` context
4327d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4328d763cef2SBarry Smith 
4329bcf0153eSBarry Smith   Level: advanced
4330bcf0153eSBarry Smith 
4331bcf0153eSBarry Smith   Note:
4332d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4333d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4334d763cef2SBarry Smith   hyphen.
4335d763cef2SBarry Smith 
43361cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
4337d763cef2SBarry Smith @*/
TSSetOptionsPrefix(TS ts,const char prefix[])4338d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
4339d71ae5a4SJacob Faibussowitsch {
4340089b2837SJed Brown   SNES snes;
4341d763cef2SBarry Smith 
4342d763cef2SBarry Smith   PetscFunctionBegin;
43430700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43449566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
43459566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43469566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
43473ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4348d763cef2SBarry Smith }
4349d763cef2SBarry Smith 
4350cc4c1da9SBarry Smith /*@
4351d763cef2SBarry Smith   TSAppendOptionsPrefix - Appends to the prefix used for searching for all
4352d763cef2SBarry Smith   TS options in the database.
4353d763cef2SBarry Smith 
4354c3339decSBarry Smith   Logically Collective
4355d763cef2SBarry Smith 
4356d8d19677SJose E. Roman   Input Parameters:
4357bcf0153eSBarry Smith + ts     - The `TS` context
4358d763cef2SBarry Smith - prefix - The prefix to prepend to all option names
4359d763cef2SBarry Smith 
4360bcf0153eSBarry Smith   Level: advanced
4361bcf0153eSBarry Smith 
4362bcf0153eSBarry Smith   Note:
4363d763cef2SBarry Smith   A hyphen (-) must NOT be given at the beginning of the prefix name.
4364d763cef2SBarry Smith   The first character of all runtime options is AUTOMATICALLY the
4365d763cef2SBarry Smith   hyphen.
4366d763cef2SBarry Smith 
43671cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
4368d763cef2SBarry Smith @*/
TSAppendOptionsPrefix(TS ts,const char prefix[])4369d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
4370d71ae5a4SJacob Faibussowitsch {
4371089b2837SJed Brown   SNES snes;
4372d763cef2SBarry Smith 
4373d763cef2SBarry Smith   PetscFunctionBegin;
43740700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43759566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
43769566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
43779566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
43783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4379d763cef2SBarry Smith }
4380d763cef2SBarry Smith 
4381cc4c1da9SBarry Smith /*@
4382d763cef2SBarry Smith   TSGetOptionsPrefix - Sets the prefix used for searching for all
4383bcf0153eSBarry Smith   `TS` options in the database.
4384d763cef2SBarry Smith 
4385d763cef2SBarry Smith   Not Collective
4386d763cef2SBarry Smith 
4387d763cef2SBarry Smith   Input Parameter:
4388bcf0153eSBarry Smith . ts - The `TS` context
4389d763cef2SBarry Smith 
4390d763cef2SBarry Smith   Output Parameter:
4391d763cef2SBarry Smith . prefix - A pointer to the prefix string used
4392d763cef2SBarry Smith 
4393d763cef2SBarry Smith   Level: intermediate
4394d763cef2SBarry Smith 
43951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4396d763cef2SBarry Smith @*/
TSGetOptionsPrefix(TS ts,const char * prefix[])4397d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4398d71ae5a4SJacob Faibussowitsch {
4399d763cef2SBarry Smith   PetscFunctionBegin;
44000700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44014f572ea9SToby Isaac   PetscAssertPointer(prefix, 2);
44029566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
44033ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4404d763cef2SBarry Smith }
4405d763cef2SBarry Smith 
4406d763cef2SBarry Smith /*@C
4407d763cef2SBarry Smith   TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4408d763cef2SBarry Smith 
4409bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
4410d763cef2SBarry Smith 
4411d763cef2SBarry Smith   Input Parameter:
4412bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
4413d763cef2SBarry Smith 
4414d763cef2SBarry Smith   Output Parameters:
4415195e9b02SBarry Smith + Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or `NULL`)
4416195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, usually the same as `Amat`  (or `NULL`)
4417195e9b02SBarry Smith . func - Function to compute the Jacobian of the RHS  (or `NULL`)
4418195e9b02SBarry Smith - ctx  - User-defined context for Jacobian evaluation routine  (or `NULL`)
4419d763cef2SBarry Smith 
4420d763cef2SBarry Smith   Level: intermediate
4421d763cef2SBarry Smith 
4422bcf0153eSBarry Smith   Note:
4423195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4424bcf0153eSBarry Smith 
44251cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4426d763cef2SBarry Smith 
4427d763cef2SBarry Smith @*/
TSGetRHSJacobian(TS ts,Mat * Amat,Mat * Pmat,TSRHSJacobianFn ** func,PetscCtxRt ctx)4428*2a8381b2SBarry Smith PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobianFn **func, PetscCtxRt ctx)
4429d71ae5a4SJacob Faibussowitsch {
443024989b8cSPeter Brune   DM dm;
4431089b2837SJed Brown 
4432d763cef2SBarry Smith   PetscFunctionBegin;
443323a57915SBarry Smith   if (Amat || Pmat) {
443423a57915SBarry Smith     SNES snes;
44359566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44369566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44379566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
443823a57915SBarry Smith   }
44399566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44409566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
44413ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4442d763cef2SBarry Smith }
4443d763cef2SBarry Smith 
44442eca1d9cSJed Brown /*@C
44452eca1d9cSJed Brown   TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
44462eca1d9cSJed Brown 
4447bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if ts is parallel
44482eca1d9cSJed Brown 
44492eca1d9cSJed Brown   Input Parameter:
4450bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
44512eca1d9cSJed Brown 
44522eca1d9cSJed Brown   Output Parameters:
4453e4357dc4SBarry Smith + Amat - The (approximate) Jacobian of F(t,U,U_t)
4454195e9b02SBarry Smith . Pmat - The matrix from which the preconditioner is constructed, often the same as `Amat`
44552eca1d9cSJed Brown . f    - The function to compute the matrices
44562eca1d9cSJed Brown - ctx  - User-defined context for Jacobian evaluation routine
44572eca1d9cSJed Brown 
44582eca1d9cSJed Brown   Level: advanced
44592eca1d9cSJed Brown 
4460bcf0153eSBarry Smith   Note:
4461195e9b02SBarry Smith   You can pass in `NULL` for any return argument you do not need.
4462bcf0153eSBarry Smith 
44631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
44642eca1d9cSJed Brown @*/
TSGetIJacobian(TS ts,Mat * Amat,Mat * Pmat,TSIJacobianFn ** f,PetscCtxRt ctx)4465*2a8381b2SBarry Smith PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobianFn **f, PetscCtxRt ctx)
4466d71ae5a4SJacob Faibussowitsch {
446724989b8cSPeter Brune   DM dm;
44680910c330SBarry Smith 
44692eca1d9cSJed Brown   PetscFunctionBegin;
4470c0aab802Sstefano_zampini   if (Amat || Pmat) {
4471c0aab802Sstefano_zampini     SNES snes;
44729566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
44739566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
44749566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4475c0aab802Sstefano_zampini   }
44769566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
44779566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
44783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
44792eca1d9cSJed Brown }
44802eca1d9cSJed Brown 
4481af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
44826c699258SBarry Smith /*@
4483bcf0153eSBarry Smith   TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
44846c699258SBarry Smith 
4485c3339decSBarry Smith   Logically Collective
44866c699258SBarry Smith 
44876c699258SBarry Smith   Input Parameters:
4488bcf0153eSBarry Smith + ts - the `TS` integrator object
4489195e9b02SBarry Smith - dm - the dm, cannot be `NULL`
44906c699258SBarry Smith 
44916c699258SBarry Smith   Level: intermediate
44926c699258SBarry Smith 
4493bcf0153eSBarry Smith   Notes:
4494bcf0153eSBarry Smith   A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4495bcf0153eSBarry Smith   even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4496bcf0153eSBarry Smith   different problems using the same function space.
4497bcf0153eSBarry Smith 
44981cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
44996c699258SBarry Smith @*/
TSSetDM(TS ts,DM dm)4500d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4501d71ae5a4SJacob Faibussowitsch {
4502089b2837SJed Brown   SNES snes;
4503942e3340SBarry Smith   DMTS tsdm;
45046c699258SBarry Smith 
45056c699258SBarry Smith   PetscFunctionBegin;
45060700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45072a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
45089566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4509942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
45102a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
45119566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
45129566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
45131e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
45141e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
451524989b8cSPeter Brune     }
45169566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
451724989b8cSPeter Brune   }
45186c699258SBarry Smith   ts->dm = dm;
4519bbd56ea5SKarl Rupp 
45209566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
45219566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
45223ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45236c699258SBarry Smith }
45246c699258SBarry Smith 
45256c699258SBarry Smith /*@
4526bcf0153eSBarry Smith   TSGetDM - Gets the `DM` that may be used by some preconditioners
45276c699258SBarry Smith 
45283f9fe445SBarry Smith   Not Collective
45296c699258SBarry Smith 
45306c699258SBarry Smith   Input Parameter:
4531bcf0153eSBarry Smith . ts - the `TS`
45326c699258SBarry Smith 
45336c699258SBarry Smith   Output Parameter:
4534195e9b02SBarry Smith . dm - the `DM`
45356c699258SBarry Smith 
45366c699258SBarry Smith   Level: intermediate
45376c699258SBarry Smith 
45381cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
45396c699258SBarry Smith @*/
TSGetDM(TS ts,DM * dm)4540d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4541d71ae5a4SJacob Faibussowitsch {
45426c699258SBarry Smith   PetscFunctionBegin;
45430700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4544496e6a7aSJed Brown   if (!ts->dm) {
45459566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
45464bd3aaa3SHong Zhang     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4547496e6a7aSJed Brown   }
45486c699258SBarry Smith   *dm = ts->dm;
45493ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45506c699258SBarry Smith }
45511713a123SBarry Smith 
45520f5c6efeSJed Brown /*@
45532ba42892SBarry Smith   SNESTSFormFunction - Function to evaluate nonlinear residual defined by an ODE solver algorithm implemented within `TS`
45540f5c6efeSJed Brown 
4555c3339decSBarry Smith   Logically Collective
45560f5c6efeSJed Brown 
4557d8d19677SJose E. Roman   Input Parameters:
4558d42a1c89SJed Brown + snes - nonlinear solver
45590910c330SBarry Smith . U    - the current state at which to evaluate the residual
45602ba42892SBarry Smith - ctx  - user context, must be a `TS`
45610f5c6efeSJed Brown 
45620f5c6efeSJed Brown   Output Parameter:
45630f5c6efeSJed Brown . F - the nonlinear residual
45640f5c6efeSJed Brown 
45652ba42892SBarry Smith   Level: developer
45660f5c6efeSJed Brown 
4567bcf0153eSBarry Smith   Note:
4568bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4569bcf0153eSBarry Smith   It is most frequently passed to `MatFDColoringSetFunction()`.
4570bcf0153eSBarry Smith 
45711cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
45720f5c6efeSJed Brown @*/
SNESTSFormFunction(SNES snes,Vec U,Vec F,PetscCtx ctx)4573*2a8381b2SBarry Smith PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, PetscCtx ctx)
4574d71ae5a4SJacob Faibussowitsch {
45750f5c6efeSJed Brown   TS ts = (TS)ctx;
45760f5c6efeSJed Brown 
45770f5c6efeSJed Brown   PetscFunctionBegin;
45780f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
45790910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
45800f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
45810f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
4582346ce620SStefano Zampini   PetscCheck(ts->ops->snesfunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesfunction for TS of type %s", ((PetscObject)ts)->type_name);
4583346ce620SStefano Zampini   PetscCall((*ts->ops->snesfunction)(snes, U, F, ts));
45843ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
45850f5c6efeSJed Brown }
45860f5c6efeSJed Brown 
45870f5c6efeSJed Brown /*@
45882ba42892SBarry Smith   SNESTSFormJacobian - Function to evaluate the Jacobian defined by an ODE solver algorithm implemented within `TS`
45890f5c6efeSJed Brown 
4590c3339decSBarry Smith   Collective
45910f5c6efeSJed Brown 
4592d8d19677SJose E. Roman   Input Parameters:
45930f5c6efeSJed Brown + snes - nonlinear solver
45940910c330SBarry Smith . U    - the current state at which to evaluate the residual
4595bcf0153eSBarry Smith - ctx  - user context, must be a `TS`
45960f5c6efeSJed Brown 
4597d8d19677SJose E. Roman   Output Parameters:
45980f5c6efeSJed Brown + A - the Jacobian
45997addb90fSBarry Smith - B - the matrix used to construct the preconditioner (often the same as `A`)
46000f5c6efeSJed Brown 
46010f5c6efeSJed Brown   Level: developer
46020f5c6efeSJed Brown 
4603bcf0153eSBarry Smith   Note:
4604bcf0153eSBarry Smith   This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4605bcf0153eSBarry Smith 
46061cc06b55SBarry Smith .seealso: [](ch_ts), `SNESSetJacobian()`
46070f5c6efeSJed Brown @*/
SNESTSFormJacobian(SNES snes,Vec U,Mat A,Mat B,PetscCtx ctx)4608*2a8381b2SBarry Smith PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, PetscCtx ctx)
4609d71ae5a4SJacob Faibussowitsch {
46100f5c6efeSJed Brown   TS ts = (TS)ctx;
46110f5c6efeSJed Brown 
46120f5c6efeSJed Brown   PetscFunctionBegin;
46130f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
46140910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
461594ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
461694ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4617064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
4618346ce620SStefano Zampini   PetscCheck(ts->ops->snesjacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No method snesjacobian for TS of type %s", ((PetscObject)ts)->type_name);
4619346ce620SStefano Zampini   PetscCall((*ts->ops->snesjacobian)(snes, U, A, B, ts));
46203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46210f5c6efeSJed Brown }
4622325fc9f4SBarry Smith 
46230e4ef248SJed Brown /*@C
4624dd8e379bSPierre Jolivet   TSComputeRHSFunctionLinear - Evaluate the right-hand side via the user-provided Jacobian, for linear problems Udot = A U only
46250e4ef248SJed Brown 
4626c3339decSBarry Smith   Collective
46270e4ef248SJed Brown 
46284165533cSJose E. Roman   Input Parameters:
46290e4ef248SJed Brown + ts  - time stepping context
46300e4ef248SJed Brown . t   - time at which to evaluate
46310910c330SBarry Smith . U   - state at which to evaluate
46320e4ef248SJed Brown - ctx - context
46330e4ef248SJed Brown 
46344165533cSJose E. Roman   Output Parameter:
4635dd8e379bSPierre Jolivet . F - right-hand side
46360e4ef248SJed Brown 
46370e4ef248SJed Brown   Level: intermediate
46380e4ef248SJed Brown 
4639bcf0153eSBarry Smith   Note:
4640dd8e379bSPierre Jolivet   This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right-hand side for linear problems.
4641bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
46420e4ef248SJed Brown 
46431cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
46440e4ef248SJed Brown @*/
TSComputeRHSFunctionLinear(TS ts,PetscReal t,Vec U,Vec F,PetscCtx ctx)4645*2a8381b2SBarry Smith PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, PetscCtx ctx)
4646d71ae5a4SJacob Faibussowitsch {
46470e4ef248SJed Brown   Mat Arhs, Brhs;
46480e4ef248SJed Brown 
46490e4ef248SJed Brown   PetscFunctionBegin;
46509566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
46512663174eSHong Zhang   /* undo the damage caused by shifting */
46529566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
46539566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
46549566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
46553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46560e4ef248SJed Brown }
46570e4ef248SJed Brown 
46580e4ef248SJed Brown /*@C
46590e4ef248SJed Brown   TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
46600e4ef248SJed Brown 
4661c3339decSBarry Smith   Collective
46620e4ef248SJed Brown 
46634165533cSJose E. Roman   Input Parameters:
46640e4ef248SJed Brown + ts  - time stepping context
46650e4ef248SJed Brown . t   - time at which to evaluate
46660910c330SBarry Smith . U   - state at which to evaluate
46670e4ef248SJed Brown - ctx - context
46680e4ef248SJed Brown 
46694165533cSJose E. Roman   Output Parameters:
46707addb90fSBarry Smith + A - Jacobian
46717addb90fSBarry Smith - B - matrix used to construct the preconditioner, often the same as `A`
46720e4ef248SJed Brown 
46730e4ef248SJed Brown   Level: intermediate
46740e4ef248SJed Brown 
4675bcf0153eSBarry Smith   Note:
4676bcf0153eSBarry Smith   This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
46770e4ef248SJed Brown 
46781cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
46790e4ef248SJed Brown @*/
TSComputeRHSJacobianConstant(TS ts,PetscReal t,Vec U,Mat A,Mat B,PetscCtx ctx)4680*2a8381b2SBarry Smith PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, PetscCtx ctx)
4681d71ae5a4SJacob Faibussowitsch {
46820e4ef248SJed Brown   PetscFunctionBegin;
46833ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
46840e4ef248SJed Brown }
46850e4ef248SJed Brown 
46860026cea9SSean Farley /*@C
46870026cea9SSean Farley   TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
46880026cea9SSean Farley 
4689c3339decSBarry Smith   Collective
46900026cea9SSean Farley 
46914165533cSJose E. Roman   Input Parameters:
46920026cea9SSean Farley + ts   - time stepping context
46930026cea9SSean Farley . t    - time at which to evaluate
46940910c330SBarry Smith . U    - state at which to evaluate
46950910c330SBarry Smith . Udot - time derivative of state vector
46960026cea9SSean Farley - ctx  - context
46970026cea9SSean Farley 
46984165533cSJose E. Roman   Output Parameter:
46990026cea9SSean Farley . F - left hand side
47000026cea9SSean Farley 
47010026cea9SSean Farley   Level: intermediate
47020026cea9SSean Farley 
47030026cea9SSean Farley   Notes:
47040910c330SBarry 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
4705bcf0153eSBarry Smith   user is required to write their own `TSComputeIFunction()`.
4706bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4707bcf0153eSBarry Smith   The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
47080026cea9SSean Farley 
4709bcf0153eSBarry Smith   Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
47109ae8fd06SBarry Smith 
47111cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
47120026cea9SSean Farley @*/
TSComputeIFunctionLinear(TS ts,PetscReal t,Vec U,Vec Udot,Vec F,PetscCtx ctx)4713*2a8381b2SBarry Smith PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, PetscCtx ctx)
4714d71ae5a4SJacob Faibussowitsch {
47150026cea9SSean Farley   Mat A, B;
47160026cea9SSean Farley 
47170026cea9SSean Farley   PetscFunctionBegin;
47189566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
47199566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
47209566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
47213ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47220026cea9SSean Farley }
47230026cea9SSean Farley 
47240026cea9SSean Farley /*@C
47258434afd1SBarry Smith   TSComputeIJacobianConstant - Reuses the matrix previously computed with the provided `TSIJacobianFn` for a semi-implicit DAE or ODE
47260026cea9SSean Farley 
4727c3339decSBarry Smith   Collective
47280026cea9SSean Farley 
47294165533cSJose E. Roman   Input Parameters:
47300026cea9SSean Farley + ts    - time stepping context
47310026cea9SSean Farley . t     - time at which to evaluate
47320910c330SBarry Smith . U     - state at which to evaluate
47330910c330SBarry Smith . Udot  - time derivative of state vector
47340026cea9SSean Farley . shift - shift to apply
47350026cea9SSean Farley - ctx   - context
47360026cea9SSean Farley 
47374165533cSJose E. Roman   Output Parameters:
47380026cea9SSean Farley + A - pointer to operator
4739d1c5d1fcSBarry Smith - B - pointer to matrix from which the preconditioner is built (often `A`)
47400026cea9SSean Farley 
4741b41af12eSJed Brown   Level: advanced
47420026cea9SSean Farley 
47430026cea9SSean Farley   Notes:
4744bcf0153eSBarry Smith   This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
47450026cea9SSean Farley 
4746b41af12eSJed Brown   It is only appropriate for problems of the form
4747b41af12eSJed Brown 
4748d1c5d1fcSBarry Smith   $$
4749d1c5d1fcSBarry Smith   M \dot{U} = F(U,t)
4750d1c5d1fcSBarry Smith   $$
4751b41af12eSJed Brown 
4752bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4753bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4754b41af12eSJed Brown   an implicit operator of the form
4755b41af12eSJed Brown 
4756d1c5d1fcSBarry Smith   $$
4757d1c5d1fcSBarry Smith   shift*M + J
4758d1c5d1fcSBarry Smith   $$
4759b41af12eSJed Brown 
4760b41af12eSJed 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
4761b41af12eSJed Brown   a copy of M or reassemble it when requested.
4762b41af12eSJed Brown 
47631cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
47640026cea9SSean Farley @*/
TSComputeIJacobianConstant(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat A,Mat B,PetscCtx ctx)4765*2a8381b2SBarry Smith PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscCtx ctx)
4766d71ae5a4SJacob Faibussowitsch {
47670026cea9SSean Farley   PetscFunctionBegin;
47689566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4769b41af12eSJed Brown   ts->ijacobian.shift = shift;
47703ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
47710026cea9SSean Farley }
4772b41af12eSJed Brown 
4773e817cc15SEmil Constantinescu /*@
4774bcf0153eSBarry Smith   TSGetEquationType - Gets the type of the equation that `TS` is solving.
4775e817cc15SEmil Constantinescu 
4776e817cc15SEmil Constantinescu   Not Collective
4777e817cc15SEmil Constantinescu 
4778e817cc15SEmil Constantinescu   Input Parameter:
4779bcf0153eSBarry Smith . ts - the `TS` context
4780e817cc15SEmil Constantinescu 
4781e817cc15SEmil Constantinescu   Output Parameter:
4782bcf0153eSBarry Smith . equation_type - see `TSEquationType`
4783e817cc15SEmil Constantinescu 
4784e817cc15SEmil Constantinescu   Level: beginner
4785e817cc15SEmil Constantinescu 
47861cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4787e817cc15SEmil Constantinescu @*/
TSGetEquationType(TS ts,TSEquationType * equation_type)4788d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4789d71ae5a4SJacob Faibussowitsch {
4790e817cc15SEmil Constantinescu   PetscFunctionBegin;
4791e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
47924f572ea9SToby Isaac   PetscAssertPointer(equation_type, 2);
4793e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
47943ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4795e817cc15SEmil Constantinescu }
4796e817cc15SEmil Constantinescu 
4797e817cc15SEmil Constantinescu /*@
4798bcf0153eSBarry Smith   TSSetEquationType - Sets the type of the equation that `TS` is solving.
4799e817cc15SEmil Constantinescu 
4800e817cc15SEmil Constantinescu   Not Collective
4801e817cc15SEmil Constantinescu 
4802d8d19677SJose E. Roman   Input Parameters:
4803bcf0153eSBarry Smith + ts            - the `TS` context
4804bcf0153eSBarry Smith - equation_type - see `TSEquationType`
4805e817cc15SEmil Constantinescu 
4806e817cc15SEmil Constantinescu   Level: advanced
4807e817cc15SEmil Constantinescu 
48081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4809e817cc15SEmil Constantinescu @*/
TSSetEquationType(TS ts,TSEquationType equation_type)4810d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4811d71ae5a4SJacob Faibussowitsch {
4812e817cc15SEmil Constantinescu   PetscFunctionBegin;
4813e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4814e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
48153ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4816e817cc15SEmil Constantinescu }
48170026cea9SSean Farley 
48184af1b03aSJed Brown /*@
4819bcf0153eSBarry Smith   TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
48204af1b03aSJed Brown 
48214af1b03aSJed Brown   Not Collective
48224af1b03aSJed Brown 
48234af1b03aSJed Brown   Input Parameter:
4824bcf0153eSBarry Smith . ts - the `TS` context
48254af1b03aSJed Brown 
48264af1b03aSJed Brown   Output Parameter:
4827bcf0153eSBarry Smith . reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
48284af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
48294af1b03aSJed Brown 
4830487e0bb9SJed Brown   Level: beginner
48314af1b03aSJed Brown 
4832bcf0153eSBarry Smith   Note:
4833bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
48344af1b03aSJed Brown 
48357d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
48364af1b03aSJed Brown @*/
TSGetConvergedReason(TS ts,TSConvergedReason * reason)4837d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4838d71ae5a4SJacob Faibussowitsch {
48394af1b03aSJed Brown   PetscFunctionBegin;
48404af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48414f572ea9SToby Isaac   PetscAssertPointer(reason, 2);
48424af1b03aSJed Brown   *reason = ts->reason;
48433ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
48444af1b03aSJed Brown }
48454af1b03aSJed Brown 
4846d6ad946cSShri Abhyankar /*@
4847bcf0153eSBarry Smith   TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4848d6ad946cSShri Abhyankar 
48496b221cbeSPatrick Sanan   Logically Collective; reason must contain common value
4850d6ad946cSShri Abhyankar 
48516b221cbeSPatrick Sanan   Input Parameters:
4852bcf0153eSBarry Smith + ts     - the `TS` context
4853bcf0153eSBarry Smith - reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4854d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4855d6ad946cSShri Abhyankar 
4856f5abba47SShri Abhyankar   Level: advanced
4857d6ad946cSShri Abhyankar 
4858bcf0153eSBarry Smith   Note:
4859bcf0153eSBarry Smith   Can only be called while `TSSolve()` is active.
4860d6ad946cSShri Abhyankar 
48611cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4862d6ad946cSShri Abhyankar @*/
TSSetConvergedReason(TS ts,TSConvergedReason reason)4863d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4864d71ae5a4SJacob Faibussowitsch {
4865d6ad946cSShri Abhyankar   PetscFunctionBegin;
4866d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4867d6ad946cSShri Abhyankar   ts->reason = reason;
48683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4869d6ad946cSShri Abhyankar }
4870d6ad946cSShri Abhyankar 
4871cc708dedSBarry Smith /*@
4872bcf0153eSBarry Smith   TSGetSolveTime - Gets the time after a call to `TSSolve()`
4873cc708dedSBarry Smith 
4874cc708dedSBarry Smith   Not Collective
4875cc708dedSBarry Smith 
4876cc708dedSBarry Smith   Input Parameter:
4877bcf0153eSBarry Smith . ts - the `TS` context
4878cc708dedSBarry Smith 
4879cc708dedSBarry Smith   Output Parameter:
4880bcf0153eSBarry Smith . ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4881cc708dedSBarry Smith 
4882487e0bb9SJed Brown   Level: beginner
4883cc708dedSBarry Smith 
4884bcf0153eSBarry Smith   Note:
4885bcf0153eSBarry Smith   Can only be called after the call to `TSSolve()` is complete.
4886cc708dedSBarry Smith 
48877d66147cSPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4888cc708dedSBarry Smith @*/
TSGetSolveTime(TS ts,PetscReal * ftime)4889d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4890d71ae5a4SJacob Faibussowitsch {
4891cc708dedSBarry Smith   PetscFunctionBegin;
4892cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
48934f572ea9SToby Isaac   PetscAssertPointer(ftime, 2);
4894cc708dedSBarry Smith   *ftime = ts->solvetime;
48953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4896cc708dedSBarry Smith }
4897cc708dedSBarry Smith 
48982c18e0fdSBarry Smith /*@
48995ef26d82SJed Brown   TSGetSNESIterations - Gets the total number of nonlinear iterations
49009f67acb7SJed Brown   used by the time integrator.
49019f67acb7SJed Brown 
49029f67acb7SJed Brown   Not Collective
49039f67acb7SJed Brown 
49049f67acb7SJed Brown   Input Parameter:
4905bcf0153eSBarry Smith . ts - `TS` context
49069f67acb7SJed Brown 
49079f67acb7SJed Brown   Output Parameter:
49089f67acb7SJed Brown . nits - number of nonlinear iterations
49099f67acb7SJed Brown 
49109f67acb7SJed Brown   Level: intermediate
49119f67acb7SJed Brown 
4912195e9b02SBarry Smith   Note:
4913bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4914bcf0153eSBarry Smith 
49151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
49169f67acb7SJed Brown @*/
TSGetSNESIterations(TS ts,PetscInt * nits)4917d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4918d71ae5a4SJacob Faibussowitsch {
49199f67acb7SJed Brown   PetscFunctionBegin;
49209f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49214f572ea9SToby Isaac   PetscAssertPointer(nits, 2);
49225ef26d82SJed Brown   *nits = ts->snes_its;
49233ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49249f67acb7SJed Brown }
49259f67acb7SJed Brown 
49269f67acb7SJed Brown /*@
49275ef26d82SJed Brown   TSGetKSPIterations - Gets the total number of linear iterations
49289f67acb7SJed Brown   used by the time integrator.
49299f67acb7SJed Brown 
49309f67acb7SJed Brown   Not Collective
49319f67acb7SJed Brown 
49329f67acb7SJed Brown   Input Parameter:
4933bcf0153eSBarry Smith . ts - `TS` context
49349f67acb7SJed Brown 
49359f67acb7SJed Brown   Output Parameter:
49369f67acb7SJed Brown . lits - number of linear iterations
49379f67acb7SJed Brown 
49389f67acb7SJed Brown   Level: intermediate
49399f67acb7SJed Brown 
4940bcf0153eSBarry Smith   Note:
4941bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4942bcf0153eSBarry Smith 
4943bfe80ac4SPierre Jolivet .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`
49449f67acb7SJed Brown @*/
TSGetKSPIterations(TS ts,PetscInt * lits)4945d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4946d71ae5a4SJacob Faibussowitsch {
49479f67acb7SJed Brown   PetscFunctionBegin;
49489f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49494f572ea9SToby Isaac   PetscAssertPointer(lits, 2);
49505ef26d82SJed Brown   *lits = ts->ksp_its;
49513ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
49529f67acb7SJed Brown }
49539f67acb7SJed Brown 
4954cef5090cSJed Brown /*@
4955cef5090cSJed Brown   TSGetStepRejections - Gets the total number of rejected steps.
4956cef5090cSJed Brown 
4957cef5090cSJed Brown   Not Collective
4958cef5090cSJed Brown 
4959cef5090cSJed Brown   Input Parameter:
4960bcf0153eSBarry Smith . ts - `TS` context
4961cef5090cSJed Brown 
4962cef5090cSJed Brown   Output Parameter:
4963cef5090cSJed Brown . rejects - number of steps rejected
4964cef5090cSJed Brown 
4965cef5090cSJed Brown   Level: intermediate
4966cef5090cSJed Brown 
4967bcf0153eSBarry Smith   Note:
4968bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4969bcf0153eSBarry Smith 
49701cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4971cef5090cSJed Brown @*/
TSGetStepRejections(TS ts,PetscInt * rejects)4972d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4973d71ae5a4SJacob Faibussowitsch {
4974cef5090cSJed Brown   PetscFunctionBegin;
4975cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
49764f572ea9SToby Isaac   PetscAssertPointer(rejects, 2);
4977cef5090cSJed Brown   *rejects = ts->reject;
49783ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
4979cef5090cSJed Brown }
4980cef5090cSJed Brown 
4981cef5090cSJed Brown /*@
4982bcf0153eSBarry Smith   TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4983cef5090cSJed Brown 
4984cef5090cSJed Brown   Not Collective
4985cef5090cSJed Brown 
4986cef5090cSJed Brown   Input Parameter:
4987bcf0153eSBarry Smith . ts - `TS` context
4988cef5090cSJed Brown 
4989cef5090cSJed Brown   Output Parameter:
4990cef5090cSJed Brown . fails - number of failed nonlinear solves
4991cef5090cSJed Brown 
4992cef5090cSJed Brown   Level: intermediate
4993cef5090cSJed Brown 
4994bcf0153eSBarry Smith   Note:
4995bcf0153eSBarry Smith   This counter is reset to zero for each successive call to `TSSolve()`.
4996bcf0153eSBarry Smith 
49971cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4998cef5090cSJed Brown @*/
TSGetSNESFailures(TS ts,PetscInt * fails)4999d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
5000d71ae5a4SJacob Faibussowitsch {
5001cef5090cSJed Brown   PetscFunctionBegin;
5002cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
50034f572ea9SToby Isaac   PetscAssertPointer(fails, 2);
5004cef5090cSJed Brown   *fails = ts->num_snes_failures;
50053ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5006cef5090cSJed Brown }
5007cef5090cSJed Brown 
5008cef5090cSJed Brown /*@
5009188af4bfSBarry Smith   TSSetMaxStepRejections - Sets the maximum number of step rejections allowed in a single time-step attempt before a time step fails in `TSSolve()` with `TS_DIVERGED_STEP_REJECTED`
5010cef5090cSJed Brown 
5011cef5090cSJed Brown   Not Collective
5012cef5090cSJed Brown 
5013d8d19677SJose E. Roman   Input Parameters:
5014bcf0153eSBarry Smith + ts      - `TS` context
501509cb0f53SBarry Smith - rejects - maximum number of rejected steps, pass `PETSC_UNLIMITED` for unlimited
5016cef5090cSJed Brown 
5017cef5090cSJed Brown   Options Database Key:
5018188af4bfSBarry Smith . -ts_max_step_rejections - Maximum number of step rejections before a step fails
5019cef5090cSJed Brown 
5020cef5090cSJed Brown   Level: intermediate
5021cef5090cSJed Brown 
502209cb0f53SBarry Smith   Developer Note:
502309cb0f53SBarry Smith   The options database name is incorrect.
502409cb0f53SBarry Smith 
5025188af4bfSBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`,
5026188af4bfSBarry Smith           `TSGetConvergedReason()`, `TSSolve()`, `TS_DIVERGED_STEP_REJECTED`
5027cef5090cSJed Brown @*/
TSSetMaxStepRejections(TS ts,PetscInt rejects)5028d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
5029d71ae5a4SJacob Faibussowitsch {
5030cef5090cSJed Brown   PetscFunctionBegin;
5031cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
503209cb0f53SBarry Smith   if (rejects == PETSC_UNLIMITED || rejects == -1) {
503309cb0f53SBarry Smith     ts->max_reject = PETSC_UNLIMITED;
503409cb0f53SBarry Smith   } else {
503509cb0f53SBarry Smith     PetscCheck(rejects >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of rejections");
5036cef5090cSJed Brown     ts->max_reject = rejects;
503709cb0f53SBarry Smith   }
50383ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5039cef5090cSJed Brown }
5040cef5090cSJed Brown 
5041cef5090cSJed Brown /*@
5042188af4bfSBarry Smith   TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves allowed before `TSSolve()` is ended with a `TSConvergedReason` of `TS_DIVERGED_NONLINEAR_SOLVE`
5043cef5090cSJed Brown 
5044cef5090cSJed Brown   Not Collective
5045cef5090cSJed Brown 
5046d8d19677SJose E. Roman   Input Parameters:
5047bcf0153eSBarry Smith + ts    - `TS` context
504809cb0f53SBarry Smith - fails - maximum number of failed nonlinear solves, pass `PETSC_UNLIMITED` to allow any number of failures.
5049cef5090cSJed Brown 
5050cef5090cSJed Brown   Options Database Key:
5051cef5090cSJed Brown . -ts_max_snes_failures - Maximum number of nonlinear solve failures
5052cef5090cSJed Brown 
5053cef5090cSJed Brown   Level: intermediate
5054cef5090cSJed Brown 
5055188af4bfSBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`,
5056188af4bfSBarry Smith           `TSGetConvergedReason()`, `TS_DIVERGED_NONLINEAR_SOLVE`, `TSConvergedReason`
5057cef5090cSJed Brown @*/
TSSetMaxSNESFailures(TS ts,PetscInt fails)5058d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
5059d71ae5a4SJacob Faibussowitsch {
5060cef5090cSJed Brown   PetscFunctionBegin;
5061cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
506209cb0f53SBarry Smith   if (fails == PETSC_UNLIMITED || fails == -1) {
506309cb0f53SBarry Smith     ts->max_snes_failures = PETSC_UNLIMITED;
506409cb0f53SBarry Smith   } else {
506509cb0f53SBarry Smith     PetscCheck(fails >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Cannot have a negative maximum number of failures");
5066cef5090cSJed Brown     ts->max_snes_failures = fails;
506709cb0f53SBarry Smith   }
50683ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5069cef5090cSJed Brown }
5070cef5090cSJed Brown 
5071cef5090cSJed Brown /*@
5072195e9b02SBarry Smith   TSSetErrorIfStepFails - Immediately error if no step succeeds during `TSSolve()`
5073cef5090cSJed Brown 
5074cef5090cSJed Brown   Not Collective
5075cef5090cSJed Brown 
5076d8d19677SJose E. Roman   Input Parameters:
5077bcf0153eSBarry Smith + ts  - `TS` context
5078bcf0153eSBarry Smith - err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
5079cef5090cSJed Brown 
5080cef5090cSJed Brown   Options Database Key:
5081cef5090cSJed Brown . -ts_error_if_step_fails - Error if no step succeeds
5082cef5090cSJed Brown 
5083cef5090cSJed Brown   Level: intermediate
5084cef5090cSJed Brown 
508542747ad1SJacob Faibussowitsch .seealso: [](ch_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSGetConvergedReason()`
5086cef5090cSJed Brown @*/
TSSetErrorIfStepFails(TS ts,PetscBool err)5087d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
5088d71ae5a4SJacob Faibussowitsch {
5089cef5090cSJed Brown   PetscFunctionBegin;
5090cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5091cef5090cSJed Brown   ts->errorifstepfailed = err;
50923ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5093cef5090cSJed Brown }
5094cef5090cSJed Brown 
509584df9cb4SJed Brown /*@
5096552698daSJed Brown   TSGetAdapt - Get the adaptive controller context for the current method
509784df9cb4SJed Brown 
50988f14a041SBarry Smith   Collective if controller has not yet been created
509984df9cb4SJed Brown 
51004165533cSJose E. Roman   Input Parameter:
5101ed81e22dSJed Brown . ts - time stepping context
510284df9cb4SJed Brown 
51034165533cSJose E. Roman   Output Parameter:
5104ed81e22dSJed Brown . adapt - adaptive controller
510584df9cb4SJed Brown 
510684df9cb4SJed Brown   Level: intermediate
510784df9cb4SJed Brown 
51081cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
510984df9cb4SJed Brown @*/
TSGetAdapt(TS ts,TSAdapt * adapt)5110d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
5111d71ae5a4SJacob Faibussowitsch {
511284df9cb4SJed Brown   PetscFunctionBegin;
511384df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51144f572ea9SToby Isaac   PetscAssertPointer(adapt, 2);
511584df9cb4SJed Brown   if (!ts->adapt) {
51169566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
51179566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
511884df9cb4SJed Brown   }
5119bec58848SLisandro Dalcin   *adapt = ts->adapt;
51203ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
512184df9cb4SJed Brown }
5122d6ebe24aSShri Abhyankar 
51231c3436cfSJed Brown /*@
5124195e9b02SBarry Smith   TSSetTolerances - Set tolerances for local truncation error when using an adaptive controller
51251c3436cfSJed Brown 
51261c3436cfSJed Brown   Logically Collective
51271c3436cfSJed Brown 
51284165533cSJose E. Roman   Input Parameters:
51291c3436cfSJed Brown + ts    - time integration context
513009cb0f53SBarry Smith . atol  - scalar absolute tolerances
513109cb0f53SBarry Smith . vatol - vector of absolute tolerances or `NULL`, used in preference to `atol` if present
513209cb0f53SBarry Smith . rtol  - scalar relative tolerances
513309cb0f53SBarry Smith - vrtol - vector of relative tolerances or `NULL`, used in preference to `rtol` if present
51341c3436cfSJed Brown 
5135195e9b02SBarry Smith   Options Database Keys:
5136a3cdaa26SBarry Smith + -ts_rtol <rtol> - relative tolerance for local truncation error
513767b8a455SSatish Balay - -ts_atol <atol> - Absolute tolerance for local truncation error
5138a3cdaa26SBarry Smith 
5139bcf0153eSBarry Smith   Level: beginner
5140bcf0153eSBarry Smith 
51413ff766beSShri Abhyankar   Notes:
514209cb0f53SBarry Smith   `PETSC_CURRENT` or `PETSC_DETERMINE` may be used for `atol` or `rtol` to indicate the current value
514309cb0f53SBarry Smith   or the default value from when the object's type was set.
514409cb0f53SBarry Smith 
51453ff766beSShri Abhyankar   With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
51463ff766beSShri Abhyankar   (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
51473ff766beSShri Abhyankar   computed only for the differential or the algebraic part then this can be done using the vector of
51483ff766beSShri Abhyankar   tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
51493ff766beSShri Abhyankar   differential part and infinity for the algebraic part, the LTE calculation will include only the
51503ff766beSShri Abhyankar   differential variables.
51513ff766beSShri Abhyankar 
515209cb0f53SBarry Smith   Fortran Note:
515309cb0f53SBarry Smith   Use `PETSC_CURRENT_INTEGER` or `PETSC_DETERMINE_INTEGER`.
515409cb0f53SBarry Smith 
51551cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
51561c3436cfSJed Brown @*/
TSSetTolerances(TS ts,PetscReal atol,Vec vatol,PetscReal rtol,Vec vrtol)5157d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
5158d71ae5a4SJacob Faibussowitsch {
51591c3436cfSJed Brown   PetscFunctionBegin;
516009cb0f53SBarry Smith   if (atol == (PetscReal)PETSC_DETERMINE) {
5161dd460d27SBarry Smith     ts->atol = ts->default_atol;
516209cb0f53SBarry Smith   } else if (atol != (PetscReal)PETSC_CURRENT) {
516309cb0f53SBarry Smith     PetscCheck(atol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Absolute tolerance %g must be non-negative", (double)atol);
516409cb0f53SBarry Smith     ts->atol = atol;
516509cb0f53SBarry Smith   }
516609cb0f53SBarry Smith 
51671c3436cfSJed Brown   if (vatol) {
51689566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
51699566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
51701c3436cfSJed Brown     ts->vatol = vatol;
51711c3436cfSJed Brown   }
517209cb0f53SBarry Smith 
517309cb0f53SBarry Smith   if (rtol == (PetscReal)PETSC_DETERMINE) {
5174dd460d27SBarry Smith     ts->rtol = ts->default_rtol;
517509cb0f53SBarry Smith   } else if (rtol != (PetscReal)PETSC_CURRENT) {
517609cb0f53SBarry Smith     PetscCheck(rtol >= 0.0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Relative tolerance %g must be non-negative", (double)rtol);
517709cb0f53SBarry Smith     ts->rtol = rtol;
517809cb0f53SBarry Smith   }
517909cb0f53SBarry Smith 
51801c3436cfSJed Brown   if (vrtol) {
51819566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
51829566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
51831c3436cfSJed Brown     ts->vrtol = vrtol;
51841c3436cfSJed Brown   }
51853ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
51861c3436cfSJed Brown }
51871c3436cfSJed Brown 
5188c5033834SJed Brown /*@
5189c5033834SJed Brown   TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
5190c5033834SJed Brown 
5191c5033834SJed Brown   Logically Collective
5192c5033834SJed Brown 
51934165533cSJose E. Roman   Input Parameter:
5194c5033834SJed Brown . ts - time integration context
5195c5033834SJed Brown 
51964165533cSJose E. Roman   Output Parameters:
5197195e9b02SBarry Smith + atol  - scalar absolute tolerances, `NULL` to ignore
5198195e9b02SBarry Smith . vatol - vector of absolute tolerances, `NULL` to ignore
5199195e9b02SBarry Smith . rtol  - scalar relative tolerances, `NULL` to ignore
5200195e9b02SBarry Smith - vrtol - vector of relative tolerances, `NULL` to ignore
5201c5033834SJed Brown 
5202c5033834SJed Brown   Level: beginner
5203c5033834SJed Brown 
52041cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
5205c5033834SJed Brown @*/
TSGetTolerances(TS ts,PetscReal * atol,Vec * vatol,PetscReal * rtol,Vec * vrtol)5206d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
5207d71ae5a4SJacob Faibussowitsch {
5208c5033834SJed Brown   PetscFunctionBegin;
5209c5033834SJed Brown   if (atol) *atol = ts->atol;
5210c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
5211c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
5212c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
52133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5214c5033834SJed Brown }
5215c5033834SJed Brown 
52169c6b16b5SShri Abhyankar /*@
52178a175baeSEmil Constantinescu   TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
52181c3436cfSJed Brown 
5219c3339decSBarry Smith   Collective
52201c3436cfSJed Brown 
52214165533cSJose E. Roman   Input Parameters:
52221c3436cfSJed Brown + ts        - time stepping context
5223a4868fbcSLisandro Dalcin . U         - state vector, usually ts->vec_sol
5224a4868fbcSLisandro Dalcin . Y         - state vector to be compared to U
5225bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52267619abb3SShri 
52274165533cSJose E. Roman   Output Parameters:
5228a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52298a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5230a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5231a4868fbcSLisandro Dalcin 
5232bcf0153eSBarry Smith   Options Database Key:
5233a4868fbcSLisandro Dalcin . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5234a4868fbcSLisandro Dalcin 
52351c3436cfSJed Brown   Level: developer
52361c3436cfSJed Brown 
52378c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedENorm()`
52381c3436cfSJed Brown @*/
TSErrorWeightedNorm(TS ts,Vec U,Vec Y,NormType wnormtype,PetscReal * norm,PetscReal * norma,PetscReal * normr)5239d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5240d71ae5a4SJacob Faibussowitsch {
5241037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
52428a175baeSEmil Constantinescu 
52438a175baeSEmil Constantinescu   PetscFunctionBegin;
52448a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5245dabfcb17SStefano Zampini   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5246dabfcb17SStefano Zampini   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5247dabfcb17SStefano Zampini   PetscValidLogicalCollectiveEnum(ts, wnormtype, 4);
5248dabfcb17SStefano Zampini   PetscAssertPointer(norm, 5);
5249dabfcb17SStefano Zampini   PetscAssertPointer(norma, 6);
5250dabfcb17SStefano Zampini   PetscAssertPointer(normr, 7);
5251037d63e4SStefano 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));
5252037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5253037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5254037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5255037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
52568a175baeSEmil Constantinescu   }
52573c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
52583c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
52593c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
52603ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
52618a175baeSEmil Constantinescu }
52628a175baeSEmil Constantinescu 
52638a175baeSEmil Constantinescu /*@
52648a175baeSEmil Constantinescu   TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
52658a175baeSEmil Constantinescu 
5266c3339decSBarry Smith   Collective
52678a175baeSEmil Constantinescu 
52684165533cSJose E. Roman   Input Parameters:
52698a175baeSEmil Constantinescu + ts        - time stepping context
52708a175baeSEmil Constantinescu . E         - error vector
52718a175baeSEmil Constantinescu . U         - state vector, usually ts->vec_sol
52728a175baeSEmil Constantinescu . Y         - state vector, previous time step
5273bcf0153eSBarry Smith - wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
52748a175baeSEmil Constantinescu 
52754165533cSJose E. Roman   Output Parameters:
5276a2b725a8SWilliam Gropp + norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
52778a175baeSEmil Constantinescu . norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5278a2b725a8SWilliam Gropp - normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
52798a175baeSEmil Constantinescu 
5280bcf0153eSBarry Smith   Options Database Key:
52818a175baeSEmil Constantinescu . -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
52828a175baeSEmil Constantinescu 
52838a175baeSEmil Constantinescu   Level: developer
52848a175baeSEmil Constantinescu 
52858c38e02aSSatish Balay .seealso: [](ch_ts), `TS`, `VecErrorWeightedNorms()`, `TSErrorWeightedNorm()`
52868a175baeSEmil Constantinescu @*/
TSErrorWeightedENorm(TS ts,Vec E,Vec U,Vec Y,NormType wnormtype,PetscReal * norm,PetscReal * norma,PetscReal * normr)5287d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5288d71ae5a4SJacob Faibussowitsch {
5289037d63e4SStefano Zampini   PetscInt norma_loc, norm_loc, normr_loc;
5290037d63e4SStefano Zampini 
52918a175baeSEmil Constantinescu   PetscFunctionBegin;
5292037d63e4SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5293037d63e4SStefano 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));
5294037d63e4SStefano Zampini   if (wnormtype == NORM_2) {
5295037d63e4SStefano Zampini     if (norm_loc) *norm = PetscSqrtReal(PetscSqr(*norm) / norm_loc);
5296037d63e4SStefano Zampini     if (norma_loc) *norma = PetscSqrtReal(PetscSqr(*norma) / norma_loc);
5297037d63e4SStefano Zampini     if (normr_loc) *normr = PetscSqrtReal(PetscSqr(*normr) / normr_loc);
5298037d63e4SStefano Zampini   }
5299037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
5300037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
5301037d63e4SStefano Zampini   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
53023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53038a175baeSEmil Constantinescu }
53048a175baeSEmil Constantinescu 
53058d59e960SJed Brown /*@
53068d59e960SJed Brown   TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
53078d59e960SJed Brown 
5308c3339decSBarry Smith   Logically Collective
53098d59e960SJed Brown 
53104165533cSJose E. Roman   Input Parameters:
53118d59e960SJed Brown + ts      - time stepping context
53128d59e960SJed Brown - cfltime - maximum stable time step if using forward Euler (value can be different on each process)
53138d59e960SJed Brown 
53148d59e960SJed Brown   Note:
53158d59e960SJed Brown   After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
53168d59e960SJed Brown 
53178d59e960SJed Brown   Level: intermediate
53188d59e960SJed Brown 
53191cc06b55SBarry Smith .seealso: [](ch_ts), `TSGetCFLTime()`, `TSADAPTCFL`
53208d59e960SJed Brown @*/
TSSetCFLTimeLocal(TS ts,PetscReal cfltime)5321d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5322d71ae5a4SJacob Faibussowitsch {
53238d59e960SJed Brown   PetscFunctionBegin;
53248d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53258d59e960SJed Brown   ts->cfltime_local = cfltime;
53268d59e960SJed Brown   ts->cfltime       = -1.;
53273ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53288d59e960SJed Brown }
53298d59e960SJed Brown 
53308d59e960SJed Brown /*@
53318d59e960SJed Brown   TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
53328d59e960SJed Brown 
5333c3339decSBarry Smith   Collective
53348d59e960SJed Brown 
53354165533cSJose E. Roman   Input Parameter:
53368d59e960SJed Brown . ts - time stepping context
53378d59e960SJed Brown 
53384165533cSJose E. Roman   Output Parameter:
53398d59e960SJed Brown . cfltime - maximum stable time step for forward Euler
53408d59e960SJed Brown 
53418d59e960SJed Brown   Level: advanced
53428d59e960SJed Brown 
53431cc06b55SBarry Smith .seealso: [](ch_ts), `TSSetCFLTimeLocal()`
53448d59e960SJed Brown @*/
TSGetCFLTime(TS ts,PetscReal * cfltime)5345d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5346d71ae5a4SJacob Faibussowitsch {
53478d59e960SJed Brown   PetscFunctionBegin;
5348462c564dSBarry Smith   if (ts->cfltime < 0) PetscCallMPI(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
53498d59e960SJed Brown   *cfltime = ts->cfltime;
53503ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
53518d59e960SJed Brown }
53528d59e960SJed Brown 
5353d6ebe24aSShri Abhyankar /*@
5354d6ebe24aSShri Abhyankar   TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5355d6ebe24aSShri Abhyankar 
5356d6ebe24aSShri Abhyankar   Input Parameters:
5357bcf0153eSBarry Smith + ts - the `TS` context.
5358d6ebe24aSShri Abhyankar . xl - lower bound.
5359a2b725a8SWilliam Gropp - xu - upper bound.
5360d6ebe24aSShri Abhyankar 
53612bd2b0e6SSatish Balay   Level: advanced
53622bd2b0e6SSatish Balay 
5363bcf0153eSBarry Smith   Note:
5364bcf0153eSBarry Smith   If this routine is not called then the lower and upper bounds are set to
5365bcf0153eSBarry Smith   `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5366bcf0153eSBarry Smith 
53671cc06b55SBarry Smith .seealso: [](ch_ts), `TS`
5368d6ebe24aSShri Abhyankar @*/
TSVISetVariableBounds(TS ts,Vec xl,Vec xu)5369d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5370d71ae5a4SJacob Faibussowitsch {
5371d6ebe24aSShri Abhyankar   SNES snes;
5372d6ebe24aSShri Abhyankar 
5373d6ebe24aSShri Abhyankar   PetscFunctionBegin;
53749566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
53759566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
53763ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5377d6ebe24aSShri Abhyankar }
5378d6ebe24aSShri Abhyankar 
5379f9c1d6abSBarry Smith /*@
5380f9c1d6abSBarry Smith   TSComputeLinearStability - computes the linear stability function at a point
5381f9c1d6abSBarry Smith 
5382c3339decSBarry Smith   Collective
5383f9c1d6abSBarry Smith 
5384f9c1d6abSBarry Smith   Input Parameters:
5385bcf0153eSBarry Smith + ts - the `TS` context
53862fe279fdSBarry Smith . xr - real part of input argument
53872fe279fdSBarry Smith - xi - imaginary part of input argument
5388f9c1d6abSBarry Smith 
5389f9c1d6abSBarry Smith   Output Parameters:
53902fe279fdSBarry Smith + yr - real part of function value
53912fe279fdSBarry Smith - yi - imaginary part of function value
5392f9c1d6abSBarry Smith 
5393f9c1d6abSBarry Smith   Level: developer
5394f9c1d6abSBarry Smith 
53951cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5396f9c1d6abSBarry Smith @*/
TSComputeLinearStability(TS ts,PetscReal xr,PetscReal xi,PetscReal * yr,PetscReal * yi)5397d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5398d71ae5a4SJacob Faibussowitsch {
5399f9c1d6abSBarry Smith   PetscFunctionBegin;
5400f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5401dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
54023ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5403f9c1d6abSBarry Smith }
540424655328SShri 
540524655328SShri /*@
5406dcb233daSLisandro Dalcin   TSRestartStep - Flags the solver to restart the next step
5407dcb233daSLisandro Dalcin 
5408c3339decSBarry Smith   Collective
5409dcb233daSLisandro Dalcin 
5410dcb233daSLisandro Dalcin   Input Parameter:
5411bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5412dcb233daSLisandro Dalcin 
5413dcb233daSLisandro Dalcin   Level: advanced
5414dcb233daSLisandro Dalcin 
5415dcb233daSLisandro Dalcin   Notes:
5416bcf0153eSBarry Smith   Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5417dcb233daSLisandro Dalcin   discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5418dcb233daSLisandro Dalcin   vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5419bcf0153eSBarry Smith   the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5420dcb233daSLisandro Dalcin   discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5421dcb233daSLisandro Dalcin   discontinuous source terms).
5422dcb233daSLisandro Dalcin 
54231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5424dcb233daSLisandro Dalcin @*/
TSRestartStep(TS ts)5425d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5426d71ae5a4SJacob Faibussowitsch {
5427dcb233daSLisandro Dalcin   PetscFunctionBegin;
5428dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5429dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
54303ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5431dcb233daSLisandro Dalcin }
5432dcb233daSLisandro Dalcin 
5433dcb233daSLisandro Dalcin /*@
543424655328SShri   TSRollBack - Rolls back one time step
543524655328SShri 
5436c3339decSBarry Smith   Collective
543724655328SShri 
543824655328SShri   Input Parameter:
5439bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
544024655328SShri 
544124655328SShri   Level: advanced
544224655328SShri 
54439dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSGetStepRollBack()`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
544424655328SShri @*/
TSRollBack(TS ts)5445d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5446d71ae5a4SJacob Faibussowitsch {
544724655328SShri   PetscFunctionBegin;
544824655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54493c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5450c61711c8SStefano Zampini   PetscTryTypeMethod(ts, rollback);
5451c61711c8SStefano Zampini   PetscCall(VecCopy(ts->vec_sol0, ts->vec_sol));
545224655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
545324655328SShri   ts->ptime      = ts->ptime_prev;
5454be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
54552808aa04SLisandro Dalcin   ts->steps--;
5456b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
54573ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
545824655328SShri }
5459aeb4809dSShri Abhyankar 
5460ff22ae23SHong Zhang /*@
54619dc50cb5SStefano Zampini   TSGetStepRollBack - Get the internal flag indicating if you are rolling back a step
54629dc50cb5SStefano Zampini 
54639dc50cb5SStefano Zampini   Not collective
54649dc50cb5SStefano Zampini 
54659dc50cb5SStefano Zampini   Input Parameter:
54669dc50cb5SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
54679dc50cb5SStefano Zampini 
54689dc50cb5SStefano Zampini   Output Parameter:
54699dc50cb5SStefano Zampini . flg - the rollback flag
54709dc50cb5SStefano Zampini 
54719dc50cb5SStefano Zampini   Level: advanced
54729dc50cb5SStefano Zampini 
54739dc50cb5SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSRollBack()`
54749dc50cb5SStefano Zampini @*/
TSGetStepRollBack(TS ts,PetscBool * flg)54759dc50cb5SStefano Zampini PetscErrorCode TSGetStepRollBack(TS ts, PetscBool *flg)
54769dc50cb5SStefano Zampini {
54779dc50cb5SStefano Zampini   PetscFunctionBegin;
54789dc50cb5SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54799dc50cb5SStefano Zampini   PetscAssertPointer(flg, 2);
54809dc50cb5SStefano Zampini   *flg = ts->steprollback;
54819dc50cb5SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
54829dc50cb5SStefano Zampini }
54839dc50cb5SStefano Zampini 
54849dc50cb5SStefano Zampini /*@
5485c6bf8827SStefano Zampini   TSGetStepResize - Get the internal flag indicating if the current step is after a resize.
5486c6bf8827SStefano Zampini 
5487c6bf8827SStefano Zampini   Not collective
5488c6bf8827SStefano Zampini 
5489c6bf8827SStefano Zampini   Input Parameter:
5490c6bf8827SStefano Zampini . ts - the `TS` context obtained from `TSCreate()`
5491c6bf8827SStefano Zampini 
5492c6bf8827SStefano Zampini   Output Parameter:
5493c6bf8827SStefano Zampini . flg - the resize flag
5494c6bf8827SStefano Zampini 
5495c6bf8827SStefano Zampini   Level: advanced
5496c6bf8827SStefano Zampini 
5497c6bf8827SStefano Zampini .seealso: [](ch_ts), `TS`, `TSCreate()`, `TSSetResize()`
5498c6bf8827SStefano Zampini @*/
TSGetStepResize(TS ts,PetscBool * flg)5499c6bf8827SStefano Zampini PetscErrorCode TSGetStepResize(TS ts, PetscBool *flg)
5500c6bf8827SStefano Zampini {
5501c6bf8827SStefano Zampini   PetscFunctionBegin;
5502c6bf8827SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5503c6bf8827SStefano Zampini   PetscAssertPointer(flg, 2);
5504c6bf8827SStefano Zampini   *flg = ts->stepresize;
5505c6bf8827SStefano Zampini   PetscFunctionReturn(PETSC_SUCCESS);
5506c6bf8827SStefano Zampini }
5507c6bf8827SStefano Zampini 
5508c6bf8827SStefano Zampini /*@
5509ff22ae23SHong Zhang   TSGetStages - Get the number of stages and stage values
5510ff22ae23SHong Zhang 
5511ff22ae23SHong Zhang   Input Parameter:
5512bcf0153eSBarry Smith . ts - the `TS` context obtained from `TSCreate()`
5513ff22ae23SHong Zhang 
55140429704eSStefano Zampini   Output Parameters:
55150429704eSStefano Zampini + ns - the number of stages
55160429704eSStefano Zampini - Y  - the current stage vectors
55170429704eSStefano Zampini 
5518ff22ae23SHong Zhang   Level: advanced
5519ff22ae23SHong Zhang 
5520bcf0153eSBarry Smith   Note:
5521195e9b02SBarry Smith   Both `ns` and `Y` can be `NULL`.
55220429704eSStefano Zampini 
55231cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSCreate()`
5524ff22ae23SHong Zhang @*/
TSGetStages(TS ts,PetscInt * ns,Vec ** Y)5525d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5526d71ae5a4SJacob Faibussowitsch {
5527ff22ae23SHong Zhang   PetscFunctionBegin;
5528ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
55294f572ea9SToby Isaac   if (ns) PetscAssertPointer(ns, 2);
55304f572ea9SToby Isaac   if (Y) PetscAssertPointer(Y, 3);
55310429704eSStefano Zampini   if (!ts->ops->getstages) {
55320429704eSStefano Zampini     if (ns) *ns = 0;
55330429704eSStefano Zampini     if (Y) *Y = NULL;
5534dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
55353ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5536ff22ae23SHong Zhang }
5537ff22ae23SHong Zhang 
5538847ff0e1SMatthew G. Knepley /*@C
5539847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5540847ff0e1SMatthew G. Knepley 
5541c3339decSBarry Smith   Collective
5542847ff0e1SMatthew G. Knepley 
5543847ff0e1SMatthew G. Knepley   Input Parameters:
5544bcf0153eSBarry Smith + ts    - the `TS` context
5545847ff0e1SMatthew G. Knepley . t     - current timestep
5546847ff0e1SMatthew G. Knepley . U     - state vector
5547847ff0e1SMatthew G. Knepley . Udot  - time derivative of state vector
5548847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5549847ff0e1SMatthew G. Knepley - ctx   - an optional user context
5550847ff0e1SMatthew G. Knepley 
5551847ff0e1SMatthew G. Knepley   Output Parameters:
5552847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5553195e9b02SBarry Smith - B - newly computed Jacobian matrix to use with preconditioner (generally the same as `J`)
5554847ff0e1SMatthew G. Knepley 
5555847ff0e1SMatthew G. Knepley   Level: intermediate
5556847ff0e1SMatthew G. Knepley 
5557847ff0e1SMatthew G. Knepley   Notes:
5558847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5559847ff0e1SMatthew G. Knepley 
5560847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5561847ff0e1SMatthew G. Knepley 
5562847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5563847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5564847ff0e1SMatthew G. Knepley 
5565bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5566847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5567847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5568847ff0e1SMatthew G. Knepley 
55691cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5570847ff0e1SMatthew G. Knepley @*/
TSComputeIJacobianDefaultColor(TS ts,PetscReal t,Vec U,Vec Udot,PetscReal shift,Mat J,Mat B,PetscCtx ctx)5571*2a8381b2SBarry Smith PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, PetscCtx ctx)
5572d71ae5a4SJacob Faibussowitsch {
5573847ff0e1SMatthew G. Knepley   SNES          snes;
5574847ff0e1SMatthew G. Knepley   MatFDColoring color;
5575847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5576847ff0e1SMatthew G. Knepley 
5577847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
55789566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
55799566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5580847ff0e1SMatthew G. Knepley   if (!color) {
5581847ff0e1SMatthew G. Knepley     DM         dm;
5582847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5583847ff0e1SMatthew G. Knepley 
55849566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
55859566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5586847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
55879566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
55889566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
55892ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
55909566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
55919566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
55929566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5593847ff0e1SMatthew G. Knepley     } else {
5594847ff0e1SMatthew G. Knepley       MatColoring mc;
5595847ff0e1SMatthew G. Knepley 
55969566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
55979566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
55989566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
55999566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
56009566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
56019566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
56029566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
56032ba42892SBarry Smith       PetscCall(MatFDColoringSetFunction(color, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
56049566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
56059566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
56069566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5607847ff0e1SMatthew G. Knepley     }
56089566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
56099566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5610847ff0e1SMatthew G. Knepley   }
56119566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
56129566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5613847ff0e1SMatthew G. Knepley   if (J != B) {
56149566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
56159566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5616847ff0e1SMatthew G. Knepley   }
56173ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5618847ff0e1SMatthew G. Knepley }
561993b34091SDebojyoti Ghosh 
5620b43aa488SJacob Faibussowitsch /*@C
56216bc98fa9SBarry Smith   TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5622cb9d8021SPierre Barbier de Reuille 
562352f13ae7SStefano Zampini   Logically collective
562452f13ae7SStefano Zampini 
5625cb9d8021SPierre Barbier de Reuille   Input Parameters:
5626bcf0153eSBarry Smith + ts   - the `TS` context
5627bcf0153eSBarry Smith - func - function called within `TSFunctionDomainError()`
56286bc98fa9SBarry Smith 
562920f4b53cSBarry Smith   Calling sequence of `func`:
56308847d985SBarry Smith + ts     - the `TS` context
56316bc98fa9SBarry Smith . time   - the current time (of the stage)
56326bc98fa9SBarry Smith . state  - the state to check if it is valid
5633a144a63fSStefano Zampini - accept - (output parameter) `PETSC_FALSE` if the state is not acceptable, `PETSC_TRUE` if acceptable
5634cb9d8021SPierre Barbier de Reuille 
5635cb9d8021SPierre Barbier de Reuille   Level: intermediate
5636cb9d8021SPierre Barbier de Reuille 
56376bc98fa9SBarry Smith   Notes:
563852f13ae7SStefano Zampini   `accept` must be collectively specified.
56396bc98fa9SBarry Smith   If an implicit ODE solver is being used then, in addition to providing this routine, the
5640bcf0153eSBarry Smith   user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5641bcf0153eSBarry Smith   function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5642bcf0153eSBarry Smith   Use `TSGetSNES()` to obtain the `SNES` object
56436bc98fa9SBarry Smith 
5644b43aa488SJacob Faibussowitsch   Developer Notes:
5645bcf0153eSBarry Smith   The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
56466bc98fa9SBarry Smith   since one takes a function pointer and the other does not.
56476bc98fa9SBarry Smith 
56481cc06b55SBarry Smith .seealso: [](ch_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5649cb9d8021SPierre Barbier de Reuille @*/
TSSetFunctionDomainError(TS ts,PetscErrorCode (* func)(TS ts,PetscReal time,Vec state,PetscBool * accept))5650a144a63fSStefano Zampini PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS ts, PetscReal time, Vec state, PetscBool *accept))
5651d71ae5a4SJacob Faibussowitsch {
5652cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5653cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5654cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
56553ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5656cb9d8021SPierre Barbier de Reuille }
5657cb9d8021SPierre Barbier de Reuille 
5658cb9d8021SPierre Barbier de Reuille /*@
56596bc98fa9SBarry Smith   TSFunctionDomainError - Checks if the current state is valid
5660cb9d8021SPierre Barbier de Reuille 
566152f13ae7SStefano Zampini   Collective
566252f13ae7SStefano Zampini 
5663cb9d8021SPierre Barbier de Reuille   Input Parameters:
5664bcf0153eSBarry Smith + ts        - the `TS` context
56656bc98fa9SBarry Smith . stagetime - time of the simulation
56666bc98fa9SBarry Smith - Y         - state vector to check.
5667cb9d8021SPierre Barbier de Reuille 
5668cb9d8021SPierre Barbier de Reuille   Output Parameter:
5669bcf0153eSBarry Smith . accept - Set to `PETSC_FALSE` if the current state vector is valid.
567096a0c994SBarry Smith 
56716bc98fa9SBarry Smith   Level: developer
56726bc98fa9SBarry Smith 
5673bcf0153eSBarry Smith   Note:
5674bcf0153eSBarry Smith   This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5675bcf0153eSBarry Smith   to check if the current state is valid.
5676bcf0153eSBarry Smith 
56771cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetFunctionDomainError()`
5678cb9d8021SPierre Barbier de Reuille @*/
TSFunctionDomainError(TS ts,PetscReal stagetime,Vec Y,PetscBool * accept)5679d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5680d71ae5a4SJacob Faibussowitsch {
5681cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5682cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
568352f13ae7SStefano Zampini   PetscValidLogicalCollectiveReal(ts, stagetime, 2);
568452f13ae7SStefano Zampini   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
568552f13ae7SStefano Zampini   PetscAssertPointer(accept, 4);
5686cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
56871e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
56883ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5689cb9d8021SPierre Barbier de Reuille }
56901ceb14c0SBarry Smith 
5691cc4c1da9SBarry Smith /*@
5692195e9b02SBarry Smith   TSClone - This function clones a time step `TS` object.
569393b34091SDebojyoti Ghosh 
5694d083f849SBarry Smith   Collective
569593b34091SDebojyoti Ghosh 
569693b34091SDebojyoti Ghosh   Input Parameter:
5697bcf0153eSBarry Smith . tsin - The input `TS`
569893b34091SDebojyoti Ghosh 
569993b34091SDebojyoti Ghosh   Output Parameter:
5700bcf0153eSBarry Smith . tsout - The output `TS` (cloned)
57015eca1a21SEmil Constantinescu 
57025eca1a21SEmil Constantinescu   Level: developer
570393b34091SDebojyoti Ghosh 
5704bcf0153eSBarry Smith   Notes:
5705bcf0153eSBarry 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.
5706bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5707bcf0153eSBarry Smith 
5708195e9b02SBarry 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
5709195e9b02SBarry Smith .vb
5710195e9b02SBarry Smith  SNES snes_dup = NULL;
5711195e9b02SBarry Smith  TSGetSNES(ts,&snes_dup);
5712195e9b02SBarry Smith  TSSetSNES(ts,snes_dup);
5713195e9b02SBarry Smith .ve
5714bcf0153eSBarry Smith 
57151cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
571693b34091SDebojyoti Ghosh @*/
TSClone(TS tsin,TS * tsout)5717d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5718d71ae5a4SJacob Faibussowitsch {
571993b34091SDebojyoti Ghosh   TS     t;
5720dc846ba4SSatish Balay   SNES   snes_start;
5721dc846ba4SSatish Balay   DM     dm;
5722dc846ba4SSatish Balay   TSType type;
572393b34091SDebojyoti Ghosh 
572493b34091SDebojyoti Ghosh   PetscFunctionBegin;
57254f572ea9SToby Isaac   PetscAssertPointer(tsin, 1);
572693b34091SDebojyoti Ghosh   *tsout = NULL;
572793b34091SDebojyoti Ghosh 
57289566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
572993b34091SDebojyoti Ghosh 
573093b34091SDebojyoti Ghosh   /* General TS description */
573193b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5732371d2eb7SMartin Diehl   t->setupcalled       = PETSC_FALSE;
573393b34091SDebojyoti Ghosh   t->ksp_its           = 0;
573493b34091SDebojyoti Ghosh   t->snes_its          = 0;
573593b34091SDebojyoti Ghosh   t->nwork             = 0;
57367d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
573793b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
573893b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
573993b34091SDebojyoti Ghosh 
57409566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
57419566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5742d15a3a53SEmil Constantinescu 
57439566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
57449566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
574593b34091SDebojyoti Ghosh 
574693b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
57479566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
574893b34091SDebojyoti Ghosh 
5749e7069c78SShri   t->trajectory = tsin->trajectory;
57509566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5751e7069c78SShri 
5752e7069c78SShri   t->event = tsin->event;
57536b10a48eSSatish Balay   if (t->event) t->event->refct++;
5754e7069c78SShri 
575593b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
575693b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5757e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
575893b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
575993b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
576093b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
576193b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
576293b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
576393b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
576493b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
576593b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
576693b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
576793b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
576893b34091SDebojyoti Ghosh 
57699566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
57709566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
577193b34091SDebojyoti Ghosh 
577293b34091SDebojyoti Ghosh   t->vec_sol = NULL;
577393b34091SDebojyoti Ghosh 
577493b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
577593b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
577693b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
577793b34091SDebojyoti Ghosh 
5778aea10558SJacob Faibussowitsch   t->ops[0] = tsin->ops[0];
577993b34091SDebojyoti Ghosh 
57800d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
57810d4fed19SBarry Smith     PetscInt i;
57825ebfa9e9SBarry Smith     PetscCall(PetscMalloc((10) * sizeof(PetscFortranCallbackFn *), &((PetscObject)t)->fortran_func_pointers));
5783ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
57840d4fed19SBarry Smith   }
578593b34091SDebojyoti Ghosh   *tsout = t;
57863ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
578793b34091SDebojyoti Ghosh }
5788f3b1f45cSBarry Smith 
RHSWrapperFunction_TSRHSJacobianTest(PetscCtx ctx,Vec x,Vec y)5789*2a8381b2SBarry Smith static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(PetscCtx ctx, Vec x, Vec y)
5790d71ae5a4SJacob Faibussowitsch {
5791f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5792f3b1f45cSBarry Smith 
5793f3b1f45cSBarry Smith   PetscFunctionBegin;
57949566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
57953ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5796f3b1f45cSBarry Smith }
5797f3b1f45cSBarry Smith 
5798f3b1f45cSBarry Smith /*@
5799bcf0153eSBarry Smith   TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5800f3b1f45cSBarry Smith 
5801c3339decSBarry Smith   Logically Collective
5802f3b1f45cSBarry Smith 
58032fe279fdSBarry Smith   Input Parameter:
5804b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5805f3b1f45cSBarry Smith 
5806f3b1f45cSBarry Smith   Output Parameter:
5807bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5808f3b1f45cSBarry Smith 
5809bcf0153eSBarry Smith   Options Database Key:
5810f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5811f3b1f45cSBarry Smith 
5812f3b1f45cSBarry Smith   Level: advanced
5813f3b1f45cSBarry Smith 
5814bcf0153eSBarry Smith   Note:
5815195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5816f3b1f45cSBarry Smith 
58171cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5818f3b1f45cSBarry Smith @*/
TSRHSJacobianTest(TS ts,PetscBool * flg)5819d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5820d71ae5a4SJacob Faibussowitsch {
5821f3b1f45cSBarry Smith   Mat              J, B;
58228434afd1SBarry Smith   TSRHSJacobianFn *func;
5823f3b1f45cSBarry Smith   void            *ctx;
5824f3b1f45cSBarry Smith 
5825f3b1f45cSBarry Smith   PetscFunctionBegin;
58269566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58279566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58289566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58293ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5830f3b1f45cSBarry Smith }
5831f3b1f45cSBarry Smith 
5832cc4c1da9SBarry Smith /*@
5833bcf0153eSBarry Smith   TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5834f3b1f45cSBarry Smith 
5835c3339decSBarry Smith   Logically Collective
5836f3b1f45cSBarry Smith 
58372fe279fdSBarry Smith   Input Parameter:
5838b43aa488SJacob Faibussowitsch . ts - the time stepping routine
5839f3b1f45cSBarry Smith 
5840f3b1f45cSBarry Smith   Output Parameter:
5841bcf0153eSBarry Smith . flg - `PETSC_TRUE` if the multiply is likely correct
5842f3b1f45cSBarry Smith 
5843bcf0153eSBarry Smith   Options Database Key:
5844f3b1f45cSBarry Smith . -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5845f3b1f45cSBarry Smith 
5846bcf0153eSBarry Smith   Level: advanced
5847bcf0153eSBarry Smith 
584895452b02SPatrick Sanan   Notes:
5849195e9b02SBarry Smith   This only works for problems defined using `TSSetRHSFunction()` and Jacobian NOT `TSSetIFunction()` and Jacobian
5850f3b1f45cSBarry Smith 
58511cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5852f3b1f45cSBarry Smith @*/
TSRHSJacobianTestTranspose(TS ts,PetscBool * flg)5853d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5854d71ae5a4SJacob Faibussowitsch {
5855f3b1f45cSBarry Smith   Mat              J, B;
5856f3b1f45cSBarry Smith   void            *ctx;
58578434afd1SBarry Smith   TSRHSJacobianFn *func;
5858f3b1f45cSBarry Smith 
5859f3b1f45cSBarry Smith   PetscFunctionBegin;
58609566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
58619566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
58629566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
58633ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5864f3b1f45cSBarry Smith }
58650fe4d17eSHong Zhang 
58660fe4d17eSHong Zhang /*@
58670fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
58680fe4d17eSHong Zhang 
586920f4b53cSBarry Smith   Logically Collective
58700fe4d17eSHong Zhang 
5871d8d19677SJose E. Roman   Input Parameters:
58720fe4d17eSHong Zhang + ts                   - timestepping context
5873bcf0153eSBarry Smith - use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
58740fe4d17eSHong Zhang 
5875bcf0153eSBarry Smith   Options Database Key:
58760fe4d17eSHong Zhang . -ts_use_splitrhsfunction - <true,false>
58770fe4d17eSHong Zhang 
58780fe4d17eSHong Zhang   Level: intermediate
58790fe4d17eSHong Zhang 
5880bcf0153eSBarry Smith   Note:
5881195e9b02SBarry Smith   This is only for multirate methods
5882bcf0153eSBarry Smith 
58831cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSGetUseSplitRHSFunction()`
58840fe4d17eSHong Zhang @*/
TSSetUseSplitRHSFunction(TS ts,PetscBool use_splitrhsfunction)5885d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
5886d71ae5a4SJacob Faibussowitsch {
58870fe4d17eSHong Zhang   PetscFunctionBegin;
58880fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
58890fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
58903ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
58910fe4d17eSHong Zhang }
58920fe4d17eSHong Zhang 
58930fe4d17eSHong Zhang /*@
58940fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
58950fe4d17eSHong Zhang 
589620f4b53cSBarry Smith   Not Collective
58970fe4d17eSHong Zhang 
58980fe4d17eSHong Zhang   Input Parameter:
58990fe4d17eSHong Zhang . ts - timestepping context
59000fe4d17eSHong Zhang 
59010fe4d17eSHong Zhang   Output Parameter:
5902bcf0153eSBarry Smith . use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
59030fe4d17eSHong Zhang 
59040fe4d17eSHong Zhang   Level: intermediate
59050fe4d17eSHong Zhang 
59061cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `TSSetUseSplitRHSFunction()`
59070fe4d17eSHong Zhang @*/
TSGetUseSplitRHSFunction(TS ts,PetscBool * use_splitrhsfunction)5908d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
5909d71ae5a4SJacob Faibussowitsch {
59100fe4d17eSHong Zhang   PetscFunctionBegin;
59110fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
59120fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
59133ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
59140fe4d17eSHong Zhang }
5915d60b7d5cSBarry Smith 
5916d60b7d5cSBarry Smith /*@
5917d60b7d5cSBarry Smith   TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
5918d60b7d5cSBarry Smith 
5919c3339decSBarry Smith   Logically  Collective
5920d60b7d5cSBarry Smith 
5921d60b7d5cSBarry Smith   Input Parameters:
5922d60b7d5cSBarry Smith + ts  - the time-stepper
5923bcf0153eSBarry Smith - str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
5924d60b7d5cSBarry Smith 
5925d60b7d5cSBarry Smith   Level: intermediate
5926d60b7d5cSBarry Smith 
5927bcf0153eSBarry Smith   Note:
5928d60b7d5cSBarry Smith   When the relationship between the nonzero structures is known and supplied the solution process can be much faster
5929d60b7d5cSBarry Smith 
59301cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatAXPY()`, `MatStructure`
5931d60b7d5cSBarry Smith  @*/
TSSetMatStructure(TS ts,MatStructure str)5932d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
5933d71ae5a4SJacob Faibussowitsch {
5934d60b7d5cSBarry Smith   PetscFunctionBegin;
5935d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5936d60b7d5cSBarry Smith   ts->axpy_pattern = str;
59373ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
5938d60b7d5cSBarry Smith }
59394a658b32SHong Zhang 
59404a658b32SHong Zhang /*@
59418343f784SJames Wright   TSSetEvaluationTimes - sets the evaluation points. The solution will be computed and stored for each time requested
59424a658b32SHong Zhang 
5943c3339decSBarry Smith   Collective
59444a658b32SHong Zhang 
59454a658b32SHong Zhang   Input Parameters:
59464a658b32SHong Zhang + ts          - the time-stepper
59478343f784SJames Wright . n           - number of the time points
5948264c38b7SJames Wright - time_points - array of the time points, must be increasing
59494a658b32SHong Zhang 
5950bcf0153eSBarry Smith   Options Database Key:
59518343f784SJames Wright . -ts_eval_times <t0,...tn> - Sets the evaluation times
59524a658b32SHong Zhang 
5953bcf0153eSBarry Smith   Level: intermediate
59544a658b32SHong Zhang 
59554a658b32SHong Zhang   Notes:
5956264c38b7SJames Wright   The elements in `time_points` must be all increasing. They correspond to the intermediate points to be saved.
59574a658b32SHong Zhang 
59588343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
59598343f784SJames Wright 
5960c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using evaluation times may
59618343f784SJames Wright   pressure the memory system when using a large number of time points.
59628343f784SJames Wright 
5963c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`, `TSSetTimeSpan()`
59644a658b32SHong Zhang  @*/
TSSetEvaluationTimes(TS ts,PetscInt n,PetscReal time_points[])59650fc7ecceSBarry Smith PetscErrorCode TSSetEvaluationTimes(TS ts, PetscInt n, PetscReal time_points[])
5966d71ae5a4SJacob Faibussowitsch {
59678343f784SJames Wright   PetscBool is_sorted;
59688343f784SJames Wright 
59694a658b32SHong Zhang   PetscFunctionBegin;
59704a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5971264c38b7SJames Wright   if (ts->eval_times) { // Reset eval_times
5972264c38b7SJames Wright     ts->eval_times->sol_idx        = 0;
5973264c38b7SJames Wright     ts->eval_times->time_point_idx = 0;
5974264c38b7SJames Wright     if (n != ts->eval_times->num_time_points) {
5975136cf249SJames Wright       PetscCall(PetscFree(ts->eval_times->time_points));
5976264c38b7SJames Wright       PetscCall(PetscFree(ts->eval_times->sol_times));
5977136cf249SJames Wright       PetscCall(VecDestroyVecs(ts->eval_times->num_time_points, &ts->eval_times->sol_vecs));
5978264c38b7SJames Wright     } else {
5979264c38b7SJames Wright       PetscCall(PetscArrayzero(ts->eval_times->sol_times, n));
5980264c38b7SJames Wright       for (PetscInt i = 0; i < n; i++) PetscCall(VecZeroEntries(ts->eval_times->sol_vecs[i]));
59814a658b32SHong Zhang     }
5982264c38b7SJames Wright   } else { // Create/initialize eval_times
5983136cf249SJames Wright     TSEvaluationTimes eval_times;
5984136cf249SJames Wright     PetscCall(PetscNew(&eval_times));
5985136cf249SJames Wright     PetscCall(PetscMalloc1(n, &eval_times->time_points));
5986264c38b7SJames Wright     PetscCall(PetscMalloc1(n, &eval_times->sol_times));
5987136cf249SJames Wright     eval_times->reltol  = 1e-6;
5988136cf249SJames Wright     eval_times->abstol  = 10 * PETSC_MACHINE_EPSILON;
5989136cf249SJames Wright     eval_times->worktol = 0;
5990136cf249SJames Wright     ts->eval_times      = eval_times;
59914a658b32SHong Zhang   }
5992136cf249SJames Wright   ts->eval_times->num_time_points = n;
59938343f784SJames Wright   PetscCall(PetscSortedReal(n, time_points, &is_sorted));
59948343f784SJames Wright   PetscCheck(is_sorted, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "time_points array must be sorted");
5995136cf249SJames Wright   PetscCall(PetscArraycpy(ts->eval_times->time_points, time_points, n));
5996264c38b7SJames Wright   // Note: ts->vec_sol not guaranteed to exist, so ts->eval_times->sol_vecs allocated at TSSolve time
59978343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
59988343f784SJames Wright }
59998343f784SJames Wright 
60008343f784SJames Wright /*@C
60018343f784SJames Wright   TSGetEvaluationTimes - gets the evaluation times set with `TSSetEvaluationTimes()`
60028343f784SJames Wright 
60038343f784SJames Wright   Not Collective
60048343f784SJames Wright 
60058343f784SJames Wright   Input Parameter:
60068343f784SJames Wright . ts - the time-stepper
60078343f784SJames Wright 
60088343f784SJames Wright   Output Parameters:
60098343f784SJames Wright + n           - number of the time points
60108343f784SJames Wright - time_points - array of the time points
60118343f784SJames Wright 
60128343f784SJames Wright   Level: beginner
60138343f784SJames Wright 
60148343f784SJames Wright   Note:
60158343f784SJames Wright   The values obtained are valid until the `TS` object is destroyed.
60168343f784SJames Wright 
60178343f784SJames Wright   Both `n` and `time_points` can be `NULL`.
60188343f784SJames Wright 
60198343f784SJames Wright   Also used to see time points set by `TSSetTimeSpan()`.
60208343f784SJames Wright 
6021c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationSolutions()`
60228343f784SJames Wright  @*/
TSGetEvaluationTimes(TS ts,PetscInt * n,const PetscReal * time_points[])60238343f784SJames Wright PetscErrorCode TSGetEvaluationTimes(TS ts, PetscInt *n, const PetscReal *time_points[])
60248343f784SJames Wright {
60258343f784SJames Wright   PetscFunctionBegin;
60268343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60278343f784SJames Wright   if (n) PetscAssertPointer(n, 2);
60288343f784SJames Wright   if (time_points) PetscAssertPointer(time_points, 3);
6029136cf249SJames Wright   if (!ts->eval_times) {
60308343f784SJames Wright     if (n) *n = 0;
60318343f784SJames Wright     if (time_points) *time_points = NULL;
60328343f784SJames Wright   } else {
6033136cf249SJames Wright     if (n) *n = ts->eval_times->num_time_points;
6034136cf249SJames Wright     if (time_points) *time_points = ts->eval_times->time_points;
60358343f784SJames Wright   }
60368343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60378343f784SJames Wright }
60388343f784SJames Wright 
60398343f784SJames Wright /*@C
6040c80d56d9SJames Wright   TSGetEvaluationSolutions - Get the number of solutions and the solutions at the evaluation time points specified
60418343f784SJames Wright 
60428343f784SJames Wright   Input Parameter:
60438343f784SJames Wright . ts - the `TS` context obtained from `TSCreate()`
60448343f784SJames Wright 
60458343f784SJames Wright   Output Parameters:
60468343f784SJames Wright + nsol      - the number of solutions
60478343f784SJames Wright . sol_times - array of solution times corresponding to the solution vectors. See note below
60488343f784SJames Wright - Sols      - the solution vectors
60498343f784SJames Wright 
60508343f784SJames Wright   Level: intermediate
60518343f784SJames Wright 
60528343f784SJames Wright   Notes:
60538343f784SJames Wright   Both `nsol` and `Sols` can be `NULL`.
60548343f784SJames Wright 
60558343f784SJames Wright   Some time points in the evaluation points may be skipped by `TS` so that `nsol` is less than the number of points specified by `TSSetEvaluationTimes()`.
60568343f784SJames Wright   For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain evaluation times.
60578343f784SJames Wright 
60588343f784SJames Wright   Also used to see view solutions requested by `TSSetTimeSpan()`.
60598343f784SJames Wright 
60608343f784SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`
60618343f784SJames Wright @*/
TSGetEvaluationSolutions(TS ts,PetscInt * nsol,const PetscReal * sol_times[],Vec * Sols[])60620fc7ecceSBarry Smith PetscErrorCode TSGetEvaluationSolutions(TS ts, PetscInt *nsol, const PetscReal *sol_times[], Vec *Sols[])
60638343f784SJames Wright {
60648343f784SJames Wright   PetscFunctionBegin;
60658343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60668343f784SJames Wright   if (nsol) PetscAssertPointer(nsol, 2);
60678343f784SJames Wright   if (sol_times) PetscAssertPointer(sol_times, 3);
60688343f784SJames Wright   if (Sols) PetscAssertPointer(Sols, 4);
6069136cf249SJames Wright   if (!ts->eval_times) {
60708343f784SJames Wright     if (nsol) *nsol = 0;
60718343f784SJames Wright     if (sol_times) *sol_times = NULL;
60728343f784SJames Wright     if (Sols) *Sols = NULL;
60738343f784SJames Wright   } else {
6074264c38b7SJames Wright     if (nsol) *nsol = ts->eval_times->sol_idx;
6075136cf249SJames Wright     if (sol_times) *sol_times = ts->eval_times->sol_times;
6076136cf249SJames Wright     if (Sols) *Sols = ts->eval_times->sol_vecs;
60778343f784SJames Wright   }
60788343f784SJames Wright   PetscFunctionReturn(PETSC_SUCCESS);
60798343f784SJames Wright }
60808343f784SJames Wright 
60818343f784SJames Wright /*@
60828343f784SJames Wright   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60838343f784SJames Wright 
60848343f784SJames Wright   Collective
60858343f784SJames Wright 
60868343f784SJames Wright   Input Parameters:
60878343f784SJames Wright + ts         - the time-stepper
60888343f784SJames Wright . n          - number of the time points (>=2)
6089264c38b7SJames Wright - span_times - array of the time points, must be increasing. The first element and the last element are the initial time and the final time respectively.
60908343f784SJames Wright 
60918343f784SJames Wright   Options Database Key:
60928343f784SJames Wright . -ts_time_span <t0,...tf> - Sets the time span
60938343f784SJames Wright 
60948343f784SJames Wright   Level: intermediate
60958343f784SJames Wright 
60968343f784SJames Wright   Notes:
6097c80d56d9SJames Wright   This function is identical to `TSSetEvaluationTimes()`, except that it also sets the initial time and final time for the `ts` to the first and last `span_times` entries.
60988343f784SJames Wright 
6099264c38b7SJames Wright   The elements in `span_times` must be all increasing. They correspond to the intermediate points to be saved.
61008343f784SJames Wright 
61018343f784SJames Wright   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
61028343f784SJames Wright 
6103c80d56d9SJames Wright   The intermediate solutions are saved in a vector array that can be accessed with `TSGetEvaluationSolutions()`. Thus using time span may
61048343f784SJames Wright   pressure the memory system when using a large number of span points.
61058343f784SJames Wright 
6106c80d56d9SJames Wright .seealso: [](ch_ts), `TS`, `TSSetEvaluationTimes()`, `TSGetEvaluationTimes()`, `TSGetEvaluationSolutions()`
61078343f784SJames Wright  @*/
TSSetTimeSpan(TS ts,PetscInt n,PetscReal span_times[])61080fc7ecceSBarry Smith PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal span_times[])
61098343f784SJames Wright {
61108343f784SJames Wright   PetscFunctionBegin;
61118343f784SJames Wright   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61128343f784SJames Wright   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
61138343f784SJames Wright   PetscCall(TSSetEvaluationTimes(ts, n, span_times));
61148343f784SJames Wright   PetscCall(TSSetTime(ts, span_times[0]));
61158343f784SJames Wright   PetscCall(TSSetMaxTime(ts, span_times[n - 1]));
61163ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
61174a658b32SHong Zhang }
61184a658b32SHong Zhang 
6119cc4c1da9SBarry Smith /*@
61207b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6121d7cfae9bSHong Zhang 
6122195e9b02SBarry Smith   Collective
6123d7cfae9bSHong Zhang 
6124d7cfae9bSHong Zhang   Input Parameters:
6125195e9b02SBarry Smith + ts - the `TS` context
6126d7cfae9bSHong Zhang . J  - Jacobian matrix (not altered in this routine)
6127195e9b02SBarry Smith - B  - newly computed Jacobian matrix to use with preconditioner
6128d7cfae9bSHong Zhang 
6129d7cfae9bSHong Zhang   Level: intermediate
6130d7cfae9bSHong Zhang 
6131d7cfae9bSHong Zhang   Notes:
6132195e9b02SBarry Smith   This function improves the `MatFDColoring` performance when the Jacobian matrix was over-allocated or contains
6133195e9b02SBarry Smith   many constant zeros entries, which is typically the case when the matrix is generated by a `DM`
6134d7cfae9bSHong Zhang   and multiple fields are involved.
6135d7cfae9bSHong Zhang 
6136d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
6137195e9b02SBarry Smith   structure. For `MatFDColoring`, the values of nonzero entries are not important. So one can
61387b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
61397b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6140d7cfae9bSHong Zhang 
61411cc06b55SBarry Smith .seealso: [](ch_ts), `TS`, `MatFDColoring`, `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6142d7cfae9bSHong Zhang @*/
TSPruneIJacobianColor(TS ts,Mat J,Mat B)6143d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6144d7cfae9bSHong Zhang {
6145d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6146d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6147d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6148d7cfae9bSHong Zhang 
6149d7cfae9bSHong Zhang   PetscFunctionBegin;
6150d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
615158c11ad4SPierre Jolivet   PetscCall(MatEliminateZeros(B, PETSC_TRUE));
6152d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6153d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6154d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6155d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6156d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6157d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6158d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6159d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
61602ba42892SBarry Smith   PetscCall(MatFDColoringSetFunction(matfdcoloring, (MatFDColoringFn *)SNESTSFormFunction, (void *)ts));
6161d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6162d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6163d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6164d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6165d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
61663ba16761SJacob Faibussowitsch   PetscFunctionReturn(PETSC_SUCCESS);
6167d7cfae9bSHong Zhang }
6168