xref: /petsc/src/ts/interface/ts.c (revision f3fa974cd8ac3307c23c9d7e81b13b5f402f9e6e)
1af0996ceSBarry Smith #include <petsc/private/tsimpl.h> /*I "petscts.h"  I*/
2496e6a7aSJed Brown #include <petscdmshell.h>
31e25c274SJed Brown #include <petscdmda.h>
42d5ee99bSBarry Smith #include <petscviewer.h>
52d5ee99bSBarry Smith #include <petscdraw.h>
6900f6b5bSMatthew G. Knepley #include <petscconvest.h>
7d763cef2SBarry Smith 
89371c9d4SSatish Balay #define SkipSmallValue(a, b, tol) \
99371c9d4SSatish Balay   if (PetscAbsScalar(a) < tol || PetscAbsScalar(b) < tol) continue;
101c167fc2SEmil Constantinescu 
11d5ba7fb7SMatthew Knepley /* Logging support */
12d74926cbSBarry Smith PetscClassId  TS_CLASSID, DMTS_CLASSID;
13a05bf03eSHong Zhang PetscLogEvent TS_Step, TS_PseudoComputeTimeStep, TS_FunctionEval, TS_JacobianEval;
14d405a339SMatthew Knepley 
15c793f718SLisandro Dalcin const char *const TSExactFinalTimeOptions[] = {"UNSPECIFIED", "STEPOVER", "INTERPOLATE", "MATCHSTEP", "TSExactFinalTimeOption", "TS_EXACTFINALTIME_", NULL};
1649354f04SShri Abhyankar 
17d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSAdaptSetDefaultType(TSAdapt adapt, TSAdaptType default_type)
18d71ae5a4SJacob Faibussowitsch {
192ffb9264SLisandro Dalcin   PetscFunctionBegin;
20b92453a8SLisandro Dalcin   PetscValidHeaderSpecific(adapt, TSADAPT_CLASSID, 1);
21b92453a8SLisandro Dalcin   PetscValidCharPointer(default_type, 2);
221e66621cSBarry Smith   if (!((PetscObject)adapt)->type_name) PetscCall(TSAdaptSetType(adapt, default_type));
232ffb9264SLisandro Dalcin   PetscFunctionReturn(0);
242ffb9264SLisandro Dalcin }
252ffb9264SLisandro Dalcin 
26bdad233fSMatthew Knepley /*@
27bcf0153eSBarry Smith    TSSetFromOptions - Sets various `TS` parameters from user options.
28bdad233fSMatthew Knepley 
29c3339decSBarry Smith    Collective
30bdad233fSMatthew Knepley 
31bdad233fSMatthew Knepley    Input Parameter:
32bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
33bdad233fSMatthew Knepley 
34bdad233fSMatthew Knepley    Options Database Keys:
35bcf0153eSBarry Smith +  -ts_type <type> - EULER, BEULER, SUNDIALS, PSEUDO, CN, RK, THETA, ALPHA, GLLE,  SSP, GLEE, BSYMP, IRK
36ef222394SBarry Smith .  -ts_save_trajectory - checkpoint the solution at each time-step
37ef85077eSLisandro Dalcin .  -ts_max_time <time> - maximum time to compute to
384a658b32SHong Zhang .  -ts_time_span <t0,...tf> - sets the time span, solutions are computed and stored for each indicated time
39ef85077eSLisandro Dalcin .  -ts_max_steps <steps> - maximum number of time-steps to take
40ef85077eSLisandro Dalcin .  -ts_init_time <time> - initial time to start computation
414dc72f7fSBarry Smith .  -ts_final_time <time> - final time to compute to (deprecated: use -ts_max_time)
423e4cdcaaSBarry Smith .  -ts_dt <dt> - initial time step
431628793fSSatish 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
44a3cdaa26SBarry Smith .  -ts_max_snes_failures <maxfailures> - Maximum number of nonlinear solve failures allowed
45a3cdaa26SBarry Smith .  -ts_max_reject <maxrejects> - Maximum number of step rejections before step fails
46a3cdaa26SBarry Smith .  -ts_error_if_step_fails <true,false> - Error if no step succeeds
47a3cdaa26SBarry Smith .  -ts_rtol <rtol> - relative tolerance for local truncation error
4867b8a455SSatish Balay .  -ts_atol <atol> - Absolute tolerance for local truncation error
49f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - test the Jacobian at each iteration against finite difference with RHS function
50f3b1f45cSBarry Smith .  -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - test the Jacobian at each iteration against finite difference with RHS function
5167b8a455SSatish Balay .  -ts_adjoint_solve <yes,no> - After solving the ODE/DAE solve the adjoint problem (requires -ts_save_trajectory)
52847ff0e1SMatthew G. Knepley .  -ts_fd_color - Use finite differences with coloring to compute IJacobian
53bdad233fSMatthew Knepley .  -ts_monitor - print information at each timestep
54aee7a9fbSMatthew G. Knepley .  -ts_monitor_cancel - Cancel all monitors
55de06c3feSJed Brown .  -ts_monitor_lg_solution - Monitor solution graphically
56de06c3feSJed Brown .  -ts_monitor_lg_error - Monitor error graphically
577cf37e64SBarry Smith .  -ts_monitor_error - Monitors norm of error
586934998bSLisandro Dalcin .  -ts_monitor_lg_timestep - Monitor timestep size graphically
598b668821SLisandro Dalcin .  -ts_monitor_lg_timestep_log - Monitor log timestep size graphically
60de06c3feSJed Brown .  -ts_monitor_lg_snes_iterations - Monitor number nonlinear iterations for each timestep graphically
61de06c3feSJed Brown .  -ts_monitor_lg_ksp_iterations - Monitor number nonlinear iterations for each timestep graphically
62de06c3feSJed Brown .  -ts_monitor_sp_eig - Monitor eigenvalues of linearized operator graphically
63de06c3feSJed Brown .  -ts_monitor_draw_solution - Monitor solution graphically
643e4cdcaaSBarry Smith .  -ts_monitor_draw_solution_phase  <xleft,yleft,xright,yright> - Monitor solution graphically with phase diagram, requires problem with exactly 2 degrees of freedom
653e4cdcaaSBarry Smith .  -ts_monitor_draw_error - Monitor error graphically, requires use to have provided TSSetSolutionFunction()
66fde5950dSBarry Smith .  -ts_monitor_solution [ascii binary draw][:filename][:viewerformat] - monitors the solution at each timestep
679812b6beSJed Brown    -ts_monitor_solution_interval <interval> - output once every interval (default=1) time steps; used with -ts_monitor_solution
6863a3b9bcSJacob Faibussowitsch .  -ts_monitor_solution_vtk <filename.vts,filename.vtu> - Save each time step to a binary file, use filename-%%03" PetscInt_FMT ".vts (filename-%%03" PetscInt_FMT ".vtu)
699e336e28SPatrick Sanan -  -ts_monitor_envelope - determine maximum and minimum value of each component of the solution over the solution time
7053ea634cSHong Zhang 
71bcf0153eSBarry Smith    Level: beginner
723d5a8a6aSBarry Smith 
73bcf0153eSBarry Smith    Notes:
74bcf0153eSBarry Smith      See `SNESSetFromOptions()` and `KSPSetFromOptions()` for how to control the nonlinear and linear solves used by the time-stepper.
75bcf0153eSBarry Smith 
76bcf0153eSBarry Smith      Certain `SNES` options get reset for each new nonlinear solver, for example -snes_lag_jacobian <its> and -snes_lag_preconditioner <its>, in order
773d5a8a6aSBarry Smith      to retain them over the multiple nonlinear solves that TS uses you mush also provide -snes_lag_jacobian_persists true and
783d5a8a6aSBarry Smith      -snes_lag_preconditioner_persists true
793d5a8a6aSBarry Smith 
809e336e28SPatrick Sanan    Developer Note:
819e336e28SPatrick Sanan      We should unify all the -ts_monitor options in the way that -xxx_view has been unified
82bdad233fSMatthew Knepley 
83bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetType()`
84bdad233fSMatthew Knepley @*/
85d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFromOptions(TS ts)
86d71ae5a4SJacob Faibussowitsch {
87bc952696SBarry Smith   PetscBool              opt, flg, tflg;
88eabae89aSBarry Smith   char                   monfilename[PETSC_MAX_PATH_LEN];
894a658b32SHong Zhang   PetscReal              time_step, tspan[100];
904a658b32SHong Zhang   PetscInt               nt = PETSC_STATIC_ARRAY_LENGTH(tspan);
9149354f04SShri Abhyankar   TSExactFinalTimeOption eftopt;
92d1212d36SBarry Smith   char                   dir[16];
93cd11d68dSLisandro Dalcin   TSIFunction            ifun;
946991f827SBarry Smith   const char            *defaultType;
956991f827SBarry Smith   char                   typeName[256];
96bdad233fSMatthew Knepley 
97bdad233fSMatthew Knepley   PetscFunctionBegin;
980700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
996991f827SBarry Smith 
1009566063dSJacob Faibussowitsch   PetscCall(TSRegisterAll());
1019566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
102cd11d68dSLisandro Dalcin 
103d0609cedSBarry Smith   PetscObjectOptionsBegin((PetscObject)ts);
1041ef27442SStefano Zampini   if (((PetscObject)ts)->type_name) defaultType = ((PetscObject)ts)->type_name;
1051ef27442SStefano Zampini   else defaultType = ifun ? TSBEULER : TSEULER;
1069566063dSJacob Faibussowitsch   PetscCall(PetscOptionsFList("-ts_type", "TS method", "TSSetType", TSList, defaultType, typeName, 256, &opt));
1071e66621cSBarry Smith   if (opt) PetscCall(TSSetType(ts, typeName));
1081e66621cSBarry Smith   else PetscCall(TSSetType(ts, defaultType));
109bdad233fSMatthew Knepley 
110bdad233fSMatthew Knepley   /* Handle generic TS options */
1119566063dSJacob Faibussowitsch   PetscCall(PetscOptionsDeprecated("-ts_final_time", "-ts_max_time", "3.10", NULL));
1129566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_max_time", "Maximum time to run to", "TSSetMaxTime", ts->max_time, &ts->max_time, NULL));
1134a658b32SHong Zhang   PetscCall(PetscOptionsRealArray("-ts_time_span", "Time span", "TSSetTimeSpan", tspan, &nt, &flg));
1144a658b32SHong Zhang   if (flg) PetscCall(TSSetTimeSpan(ts, nt, tspan));
1159566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_steps", "Maximum number of time steps", "TSSetMaxSteps", ts->max_steps, &ts->max_steps, NULL));
1169566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_init_time", "Initial time", "TSSetTime", ts->ptime, &ts->ptime, NULL));
1179566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_dt", "Initial time step", "TSSetTimeStep", ts->time_step, &time_step, &flg));
1189566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetTimeStep(ts, time_step));
1199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsEnum("-ts_exact_final_time", "Option for handling of final time step", "TSSetExactFinalTime", TSExactFinalTimeOptions, (PetscEnum)ts->exact_final_time, (PetscEnum *)&eftopt, &flg));
1209566063dSJacob Faibussowitsch   if (flg) PetscCall(TSSetExactFinalTime(ts, eftopt));
1219566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_snes_failures", "Maximum number of nonlinear solve failures", "TSSetMaxSNESFailures", ts->max_snes_failures, &ts->max_snes_failures, NULL));
1229566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_max_reject", "Maximum number of step rejections before step fails", "TSSetMaxStepRejections", ts->max_reject, &ts->max_reject, NULL));
1239566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_error_if_step_fails", "Error if no step succeeds", "TSSetErrorIfStepFails", ts->errorifstepfailed, &ts->errorifstepfailed, NULL));
1249566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_rtol", "Relative tolerance for local truncation error", "TSSetTolerances", ts->rtol, &ts->rtol, NULL));
1259566063dSJacob Faibussowitsch   PetscCall(PetscOptionsReal("-ts_atol", "Absolute tolerance for local truncation error", "TSSetTolerances", ts->atol, &ts->atol, NULL));
126bdad233fSMatthew Knepley 
1279566063dSJacob 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));
1289566063dSJacob 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));
1299566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_use_splitrhsfunction", "Use the split RHS function for multirate solvers ", "TSSetUseSplitRHSFunction", ts->use_splitrhsfunction, &ts->use_splitrhsfunction, NULL));
13056f85f32SBarry Smith #if defined(PETSC_HAVE_SAWS)
13156f85f32SBarry Smith   {
13256f85f32SBarry Smith     PetscBool set;
13356f85f32SBarry Smith     flg = PETSC_FALSE;
1349566063dSJacob Faibussowitsch     PetscCall(PetscOptionsBool("-ts_saws_block", "Block for SAWs memory snooper at end of TSSolve", "PetscObjectSAWsBlock", ((PetscObject)ts)->amspublishblock, &flg, &set));
1351baa6e33SBarry Smith     if (set) PetscCall(PetscObjectSAWsSetBlock((PetscObject)ts, flg));
13656f85f32SBarry Smith   }
13756f85f32SBarry Smith #endif
13856f85f32SBarry Smith 
139bdad233fSMatthew Knepley   /* Monitor options */
1409566063dSJacob Faibussowitsch   PetscCall(PetscOptionsInt("-ts_monitor_frequency", "Number of time steps between monitor output", "TSMonitorSetFrequency", ts->monitorFrequency, &ts->monitorFrequency, NULL));
1419566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor", "Monitor time and timestep size", "TSMonitorDefault", TSMonitorDefault, NULL));
1429566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_extreme", "Monitor extreme values of the solution", "TSMonitorExtreme", TSMonitorExtreme, NULL));
1439566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_solution", "View the solution at each timestep", "TSMonitorSolution", TSMonitorSolution, NULL));
1449566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_dmswarm_monitor_moments", "Monitor moments of particle distribution", "TSDMSwarmMonitorMoments", TSDMSwarmMonitorMoments, NULL));
145fde5950dSBarry Smith 
1469566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_python", "Use Python function", "TSMonitorSet", NULL, monfilename, sizeof(monfilename), &flg));
1479566063dSJacob Faibussowitsch   if (flg) PetscCall(PetscPythonMonitorSet((PetscObject)ts, monfilename));
1485180491cSLisandro Dalcin 
1499566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", &opt));
150b3603a34SBarry Smith   if (opt) {
1513923b477SBarry Smith     PetscInt  howoften = 1;
152e669de00SBarry Smith     DM        dm;
153e669de00SBarry Smith     PetscBool net;
154b3603a34SBarry Smith 
1559566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_solution", "Monitor solution graphically", "TSMonitorLGSolution", howoften, &howoften, NULL));
1569566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
1579566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompare((PetscObject)dm, DMNETWORK, &net));
158e669de00SBarry Smith     if (net) {
159e669de00SBarry Smith       TSMonitorLGCtxNetwork ctx;
1609566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxNetworkCreate(ts, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &ctx));
1619566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGCtxNetworkSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxNetworkDestroy));
1629566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_lg_solution_semilogy", "Plot the solution with a semi-log axis", "", ctx->semilogy, &ctx->semilogy, NULL));
163e669de00SBarry Smith     } else {
164e669de00SBarry Smith       TSMonitorLGCtx ctx;
1659566063dSJacob Faibussowitsch       PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1669566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorLGSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
167bdad233fSMatthew Knepley     }
168e669de00SBarry Smith   }
1696ba87a44SLisandro Dalcin 
1709566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", &opt));
171ef20d060SBarry Smith   if (opt) {
1720b039ecaSBarry Smith     TSMonitorLGCtx ctx;
1733923b477SBarry Smith     PetscInt       howoften = 1;
174ef20d060SBarry Smith 
1759566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_error", "Monitor error graphically", "TSMonitorLGError", howoften, &howoften, NULL));
1769566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1779566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGError, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
178ef20d060SBarry Smith   }
1799566063dSJacob Faibussowitsch   PetscCall(TSMonitorSetFromOptions(ts, "-ts_monitor_error", "View the error at each timestep", "TSMonitorError", TSMonitorError, NULL));
1807cf37e64SBarry Smith 
1819566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", &opt));
1826934998bSLisandro Dalcin   if (opt) {
1836934998bSLisandro Dalcin     TSMonitorLGCtx ctx;
1846934998bSLisandro Dalcin     PetscInt       howoften = 1;
1856934998bSLisandro Dalcin 
1869566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep", "Monitor timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1879566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1889566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1896934998bSLisandro Dalcin   }
1909566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", &opt));
1918b668821SLisandro Dalcin   if (opt) {
1928b668821SLisandro Dalcin     TSMonitorLGCtx ctx;
1938b668821SLisandro Dalcin     PetscInt       howoften = 1;
1948b668821SLisandro Dalcin 
1959566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_timestep_log", "Monitor log timestep size graphically", "TSMonitorLGTimeStep", howoften, &howoften, NULL));
1969566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
1979566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGTimeStep, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
1988b668821SLisandro Dalcin     ctx->semilogy = PETSC_TRUE;
1998b668821SLisandro Dalcin   }
2008b668821SLisandro Dalcin 
2019566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", &opt));
202201da799SBarry Smith   if (opt) {
203201da799SBarry Smith     TSMonitorLGCtx ctx;
204201da799SBarry Smith     PetscInt       howoften = 1;
205201da799SBarry Smith 
2069566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_snes_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGSNESIterations", howoften, &howoften, NULL));
2079566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2089566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGSNESIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
209201da799SBarry Smith   }
2109566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", &opt));
211201da799SBarry Smith   if (opt) {
212201da799SBarry Smith     TSMonitorLGCtx ctx;
213201da799SBarry Smith     PetscInt       howoften = 1;
214201da799SBarry Smith 
2159566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_lg_ksp_iterations", "Monitor number nonlinear iterations for each timestep graphically", "TSMonitorLGKSPIterations", howoften, &howoften, NULL));
2169566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 400, 300, howoften, &ctx));
2179566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGKSPIterations, ctx, (PetscErrorCode(*)(void **))TSMonitorLGCtxDestroy));
218201da799SBarry Smith   }
2199566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", &opt));
2208189c53fSBarry Smith   if (opt) {
2218189c53fSBarry Smith     TSMonitorSPEigCtx ctx;
2228189c53fSBarry Smith     PetscInt          howoften = 1;
2238189c53fSBarry Smith 
2249566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_sp_eig", "Monitor eigenvalues of linearized operator graphically", "TSMonitorSPEig", howoften, &howoften, NULL));
2259566063dSJacob Faibussowitsch     PetscCall(TSMonitorSPEigCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2269566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSPEig, ctx, (PetscErrorCode(*)(void **))TSMonitorSPEigCtxDestroy));
2278189c53fSBarry Smith   }
2289566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_sp_swarm", "Display particle phase from the DMSwarm", "TSMonitorSPSwarm", &opt));
2291b575b74SJoseph Pusztay   if (opt) {
2301b575b74SJoseph Pusztay     TSMonitorSPCtx ctx;
231d7462660SMatthew Knepley     PetscInt       howoften = 1, retain = 0;
2326a5217c0SMatthew G. Knepley     PetscBool      phase = PETSC_TRUE, create = PETSC_TRUE;
233d7462660SMatthew Knepley 
2349371c9d4SSatish Balay     for (PetscInt i = 0; i < ts->numbermonitors; ++i)
2359371c9d4SSatish Balay       if (ts->monitor[i] == TSMonitorSPSwarmSolution) {
2369371c9d4SSatish Balay         create = PETSC_FALSE;
2379371c9d4SSatish Balay         break;
2389371c9d4SSatish Balay       }
2396a5217c0SMatthew G. Knepley     if (create) {
2409566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm", "Display particles phase from the DMSwarm", "TSMonitorSPSwarm", howoften, &howoften, NULL));
2419566063dSJacob Faibussowitsch       PetscCall(PetscOptionsInt("-ts_monitor_sp_swarm_retain", "Retain n points plotted to show trajectory, -1 for all points", "TSMonitorSPSwarm", retain, &retain, NULL));
2429566063dSJacob Faibussowitsch       PetscCall(PetscOptionsBool("-ts_monitor_sp_swarm_phase", "Plot in phase space rather than coordinate space", "TSMonitorSPSwarm", phase, &phase, NULL));
2439566063dSJacob Faibussowitsch       PetscCall(TSMonitorSPCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, retain, phase, &ctx));
2449566063dSJacob Faibussowitsch       PetscCall(TSMonitorSet(ts, TSMonitorSPSwarmSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorSPCtxDestroy));
2451b575b74SJoseph Pusztay     }
2466a5217c0SMatthew G. Knepley   }
247ef20d060SBarry Smith   opt = PETSC_FALSE;
2489566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", &opt));
249a7cc72afSBarry Smith   if (opt) {
25083a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
25183a4ac43SBarry Smith     PetscInt         howoften = 1;
252a80ad3e0SBarry Smith 
2539566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution", "Monitor solution graphically", "TSMonitorDrawSolution", howoften, &howoften, NULL));
2549566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Computed Solution", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2559566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolution, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
256bdad233fSMatthew Knepley   }
257fb1732b5SBarry Smith   opt = PETSC_FALSE;
2589566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", &opt));
2592d5ee99bSBarry Smith   if (opt) {
2602d5ee99bSBarry Smith     TSMonitorDrawCtx ctx;
2612d5ee99bSBarry Smith     PetscReal        bounds[4];
2622d5ee99bSBarry Smith     PetscInt         n = 4;
2632d5ee99bSBarry Smith     PetscDraw        draw;
2646934998bSLisandro Dalcin     PetscDrawAxis    axis;
2652d5ee99bSBarry Smith 
2669566063dSJacob Faibussowitsch     PetscCall(PetscOptionsRealArray("-ts_monitor_draw_solution_phase", "Monitor solution graphically", "TSMonitorDrawSolutionPhase", bounds, &n, NULL));
2673c633725SBarry Smith     PetscCheck(n == 4, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Must provide bounding box of phase field");
2689566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 300, 300, 1, &ctx));
2699566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(ctx->viewer, 0, &draw));
2709566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDrawAxis(ctx->viewer, 0, &axis));
2719566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLimits(axis, bounds[0], bounds[2], bounds[1], bounds[3]));
2729566063dSJacob Faibussowitsch     PetscCall(PetscDrawAxisSetLabels(axis, "Phase Diagram", "Variable 1", "Variable 2"));
2739566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionPhase, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2742d5ee99bSBarry Smith   }
2752d5ee99bSBarry Smith   opt = PETSC_FALSE;
2769566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", &opt));
2773a471f94SBarry Smith   if (opt) {
27883a4ac43SBarry Smith     TSMonitorDrawCtx ctx;
27983a4ac43SBarry Smith     PetscInt         howoften = 1;
2803a471f94SBarry Smith 
2819566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_error", "Monitor error graphically", "TSMonitorDrawError", howoften, &howoften, NULL));
2829566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Error", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2839566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawError, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2843a471f94SBarry Smith   }
2850ed3bfb6SBarry Smith   opt = PETSC_FALSE;
2869566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", &opt));
2870ed3bfb6SBarry Smith   if (opt) {
2880ed3bfb6SBarry Smith     TSMonitorDrawCtx ctx;
2890ed3bfb6SBarry Smith     PetscInt         howoften = 1;
2900ed3bfb6SBarry Smith 
2919566063dSJacob Faibussowitsch     PetscCall(PetscOptionsInt("-ts_monitor_draw_solution_function", "Monitor solution provided by TSMonitorSetSolutionFunction() graphically", "TSMonitorDrawSolutionFunction", howoften, &howoften, NULL));
2929566063dSJacob Faibussowitsch     PetscCall(TSMonitorDrawCtxCreate(PetscObjectComm((PetscObject)ts), NULL, "Solution provided by user function", PETSC_DECIDE, PETSC_DECIDE, 300, 300, howoften, &ctx));
2939566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDrawSolutionFunction, ctx, (PetscErrorCode(*)(void **))TSMonitorDrawCtxDestroy));
2940ed3bfb6SBarry Smith   }
295fde5950dSBarry Smith 
296ed81e22dSJed Brown   opt = PETSC_FALSE;
29763a3b9bcSJacob 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));
298ed81e22dSJed Brown   if (flg) {
299ed81e22dSJed Brown     const char *ptr, *ptr2;
300ed81e22dSJed Brown     char       *filetemplate;
30163a3b9bcSJacob Faibussowitsch     PetscCheck(monfilename[0], PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
302ed81e22dSJed Brown     /* Do some cursory validation of the input. */
3039566063dSJacob Faibussowitsch     PetscCall(PetscStrstr(monfilename, "%", (char **)&ptr));
30463a3b9bcSJacob Faibussowitsch     PetscCheck(ptr, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "-ts_monitor_solution_vtk requires a file template, e.g. filename-%%03" PetscInt_FMT ".vts");
305ed81e22dSJed Brown     for (ptr++; ptr && *ptr; ptr++) {
3069566063dSJacob Faibussowitsch       PetscCall(PetscStrchr("DdiouxX", *ptr, (char **)&ptr2));
30763a3b9bcSJacob Faibussowitsch       PetscCheck(ptr2 || (*ptr >= '0' && *ptr <= '9'), PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Invalid file template argument to -ts_monitor_solution_vtk, should look like filename-%%03" PetscInt_FMT ".vts");
308ed81e22dSJed Brown       if (ptr2) break;
309ed81e22dSJed Brown     }
3109566063dSJacob Faibussowitsch     PetscCall(PetscStrallocpy(monfilename, &filetemplate));
3119566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorSolutionVTK, filetemplate, (PetscErrorCode(*)(void **))TSMonitorSolutionVTKDestroy));
312ed81e22dSJed Brown   }
313bdad233fSMatthew Knepley 
3149566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_dmda_ray", "Display a ray of the solution", "None", "y=0", dir, sizeof(dir), &flg));
315d1212d36SBarry Smith   if (flg) {
316d1212d36SBarry Smith     TSMonitorDMDARayCtx *rayctx;
317d1212d36SBarry Smith     int                  ray = 0;
3183ee9839eSMatthew G. Knepley     DMDirection          ddir;
319d1212d36SBarry Smith     DM                   da;
320d1212d36SBarry Smith     PetscMPIInt          rank;
321d1212d36SBarry Smith 
3223c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
3233ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3243ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
32598921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray %s", dir);
326d1212d36SBarry Smith     sscanf(dir + 2, "%d", &ray);
327d1212d36SBarry Smith 
3289566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying DMDA ray %c = %d\n", dir[0], ray));
3299566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3309566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3319566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3329566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PetscObjectComm((PetscObject)ts), &rank));
3331e66621cSBarry Smith     if (rank == 0) PetscCall(PetscViewerDrawOpen(PETSC_COMM_SELF, NULL, NULL, 0, 0, 600, 300, &rayctx->viewer));
33451b4a12fSMatthew G. Knepley     rayctx->lgctx = NULL;
3359566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorDMDARay, rayctx, TSMonitorDMDARayDestroy));
336d1212d36SBarry Smith   }
3379566063dSJacob Faibussowitsch   PetscCall(PetscOptionsString("-ts_monitor_lg_dmda_ray", "Display a ray of the solution", "None", "x=0", dir, sizeof(dir), &flg));
33851b4a12fSMatthew G. Knepley   if (flg) {
33951b4a12fSMatthew G. Knepley     TSMonitorDMDARayCtx *rayctx;
34051b4a12fSMatthew G. Knepley     int                  ray = 0;
3413ee9839eSMatthew G. Knepley     DMDirection          ddir;
34251b4a12fSMatthew G. Knepley     DM                   da;
34351b4a12fSMatthew G. Knepley     PetscInt             howoften = 1;
344d1212d36SBarry Smith 
3453c633725SBarry Smith     PetscCheck(dir[1] == '=', PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Malformed ray %s", dir);
3463ee9839eSMatthew G. Knepley     if (dir[0] == 'x') ddir = DM_X;
3473ee9839eSMatthew G. Knepley     else if (dir[0] == 'y') ddir = DM_Y;
34898921bdaSJacob Faibussowitsch     else SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Unknown ray direction %s", dir);
34951b4a12fSMatthew G. Knepley     sscanf(dir + 2, "%d", &ray);
3501c3436cfSJed Brown 
3519566063dSJacob Faibussowitsch     PetscCall(PetscInfo(((PetscObject)ts), "Displaying LG DMDA ray %c = %d\n", dir[0], ray));
3529566063dSJacob Faibussowitsch     PetscCall(PetscNew(&rayctx));
3539566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &da));
3549566063dSJacob Faibussowitsch     PetscCall(DMDAGetRay(da, ddir, ray, &rayctx->ray, &rayctx->scatter));
3559566063dSJacob Faibussowitsch     PetscCall(TSMonitorLGCtxCreate(PETSC_COMM_SELF, NULL, NULL, PETSC_DECIDE, PETSC_DECIDE, 600, 400, howoften, &rayctx->lgctx));
3569566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorLGDMDARay, rayctx, TSMonitorDMDARayDestroy));
35751b4a12fSMatthew G. Knepley   }
358a7a1495cSBarry Smith 
3599566063dSJacob Faibussowitsch   PetscCall(PetscOptionsName("-ts_monitor_envelope", "Monitor maximum and minimum value of each component of the solution", "TSMonitorEnvelope", &opt));
360b3d3934dSBarry Smith   if (opt) {
361b3d3934dSBarry Smith     TSMonitorEnvelopeCtx ctx;
362b3d3934dSBarry Smith 
3639566063dSJacob Faibussowitsch     PetscCall(TSMonitorEnvelopeCtxCreate(ts, &ctx));
3649566063dSJacob Faibussowitsch     PetscCall(TSMonitorSet(ts, TSMonitorEnvelope, ctx, (PetscErrorCode(*)(void **))TSMonitorEnvelopeCtxDestroy));
365b3d3934dSBarry Smith   }
366aee7a9fbSMatthew G. Knepley   flg = PETSC_FALSE;
3679566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_monitor_cancel", "Remove all monitors", "TSMonitorCancel", flg, &flg, &opt));
3689566063dSJacob Faibussowitsch   if (opt && flg) PetscCall(TSMonitorCancel(ts));
369b3d3934dSBarry Smith 
370847ff0e1SMatthew G. Knepley   flg = PETSC_FALSE;
371d7cfae9bSHong Zhang   PetscCall(PetscOptionsBool("-ts_fd_color", "Use finite differences with coloring to compute IJacobian", "TSComputeIJacobianDefaultColor", flg, &flg, NULL));
372847ff0e1SMatthew G. Knepley   if (flg) {
373847ff0e1SMatthew G. Knepley     DM dm;
374847ff0e1SMatthew G. Knepley 
3759371c9d4SSatish Balay     PetscCall(TSGetDM(ts, &dm));
3769371c9d4SSatish Balay     PetscCall(DMTSUnsetIJacobianContext_Internal(dm));
3779566063dSJacob Faibussowitsch     PetscCall(TSSetIJacobian(ts, NULL, NULL, TSComputeIJacobianDefaultColor, NULL));
3789566063dSJacob Faibussowitsch     PetscCall(PetscInfo(ts, "Setting default finite difference coloring Jacobian matrix\n"));
379847ff0e1SMatthew G. Knepley   }
380847ff0e1SMatthew G. Knepley 
381d763cef2SBarry Smith   /* Handle specific TS options */
382dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setfromoptions, PetscOptionsObject);
383fbc52257SHong Zhang 
384a7bdc993SLisandro Dalcin   /* Handle TSAdapt options */
3859566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
3869566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
387dbbe0bcdSBarry Smith   PetscCall(TSAdaptSetFromOptions(ts->adapt, PetscOptionsObject));
388a7bdc993SLisandro Dalcin 
38968bece0bSHong Zhang   /* TS trajectory must be set after TS, since it may use some TS options above */
3904f122a70SLisandro Dalcin   tflg = ts->trajectory ? PETSC_TRUE : PETSC_FALSE;
3919566063dSJacob Faibussowitsch   PetscCall(PetscOptionsBool("-ts_save_trajectory", "Save the solution at each timestep", "TSSetSaveTrajectory", tflg, &tflg, NULL));
3921baa6e33SBarry Smith   if (tflg) PetscCall(TSSetSaveTrajectory(ts));
393a05bf03eSHong Zhang 
394dbbe0bcdSBarry Smith   PetscCall(TSAdjointSetFromOptions(ts, PetscOptionsObject));
395d763cef2SBarry Smith 
396d763cef2SBarry Smith   /* process any options handlers added with PetscObjectAddOptionsHandler() */
397dbbe0bcdSBarry Smith   PetscCall(PetscObjectProcessOptionsHandlers((PetscObject)ts, PetscOptionsObject));
398d0609cedSBarry Smith   PetscOptionsEnd();
399d763cef2SBarry Smith 
4001baa6e33SBarry Smith   if (ts->trajectory) PetscCall(TSTrajectorySetFromOptions(ts->trajectory, ts));
40168bece0bSHong Zhang 
4021ef27442SStefano Zampini   /* why do we have to do this here and not during TSSetUp? */
4039566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &ts->snes));
4041ef27442SStefano Zampini   if (ts->problem_type == TS_LINEAR) {
4059566063dSJacob Faibussowitsch     PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &flg, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
4069566063dSJacob Faibussowitsch     if (!flg) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
4071ef27442SStefano Zampini   }
4089566063dSJacob Faibussowitsch   PetscCall(SNESSetFromOptions(ts->snes));
409d763cef2SBarry Smith   PetscFunctionReturn(0);
410d763cef2SBarry Smith }
411d763cef2SBarry Smith 
412d2daff3dSHong Zhang /*@
413bcf0153eSBarry Smith    TSGetTrajectory - Gets the trajectory from a `TS` if it exists
41478fbdcc8SBarry Smith 
415c3339decSBarry Smith    Collective
41678fbdcc8SBarry Smith 
41778fbdcc8SBarry Smith    Input Parameters:
418bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
41978fbdcc8SBarry Smith 
4207a7aea1fSJed Brown    Output Parameters:
421bcf0153eSBarry Smith .  tr - the `TSTrajectory` object, if it exists
42278fbdcc8SBarry Smith 
42378fbdcc8SBarry Smith    Level: advanced
42478fbdcc8SBarry Smith 
425bcf0153eSBarry Smith    Note:
426bcf0153eSBarry Smith    This routine should be called after all `TS` options have been set
42778fbdcc8SBarry Smith 
428bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSAdjointSolve()`, `TSTrajectory`, `TSTrajectoryCreate()`
42978fbdcc8SBarry Smith @*/
430d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTrajectory(TS ts, TSTrajectory *tr)
431d71ae5a4SJacob Faibussowitsch {
43278fbdcc8SBarry Smith   PetscFunctionBegin;
43378fbdcc8SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
43478fbdcc8SBarry Smith   *tr = ts->trajectory;
43578fbdcc8SBarry Smith   PetscFunctionReturn(0);
43678fbdcc8SBarry Smith }
43778fbdcc8SBarry Smith 
43878fbdcc8SBarry Smith /*@
439bcf0153eSBarry Smith    TSSetSaveTrajectory - Causes the `TS` to save its solutions as it iterates forward in time in a `TSTrajectory` object
440d2daff3dSHong Zhang 
441c3339decSBarry Smith    Collective
442d2daff3dSHong Zhang 
443f899ff85SJose E. Roman    Input Parameter:
444bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
445bc952696SBarry Smith 
446bcf0153eSBarry Smith    Options Database Keys:
44778fbdcc8SBarry Smith +  -ts_save_trajectory - saves the trajectory to a file
44867b8a455SSatish Balay -  -ts_trajectory_type type - set trajectory type
44978fbdcc8SBarry Smith 
450d2daff3dSHong Zhang    Level: intermediate
451d2daff3dSHong Zhang 
452bcf0153eSBarry Smith    Notes:
453bcf0153eSBarry Smith    This routine should be called after all `TS` options have been set
454d2daff3dSHong Zhang 
455bcf0153eSBarry Smith    The `TSTRAJECTORYVISUALIZATION` files can be loaded into Python with $PETSC_DIR/lib/petsc/bin/PetscBinaryIOTrajectory.py and
456bcf0153eSBarry Smith    MATLAB with $PETSC_DIR/share/petsc/matlab/PetscReadBinaryTrajectory.m
457bcf0153eSBarry Smith 
458bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`
459d2daff3dSHong Zhang @*/
460d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSaveTrajectory(TS ts)
461d71ae5a4SJacob Faibussowitsch {
462d2daff3dSHong Zhang   PetscFunctionBegin;
463d2daff3dSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
46463a3b9bcSJacob Faibussowitsch   if (!ts->trajectory) PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
465d2daff3dSHong Zhang   PetscFunctionReturn(0);
466d2daff3dSHong Zhang }
467d2daff3dSHong Zhang 
468a7a1495cSBarry Smith /*@
469bcf0153eSBarry Smith    TSResetTrajectory - Destroys and recreates the internal `TSTrajectory` object
4702d29f1f2SStefano Zampini 
471c3339decSBarry Smith    Collective
4722d29f1f2SStefano Zampini 
4732d29f1f2SStefano Zampini    Input Parameters:
474bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
4752d29f1f2SStefano Zampini 
4762d29f1f2SStefano Zampini    Level: intermediate
4772d29f1f2SStefano Zampini 
478bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSGetTrajectory()`, `TSAdjointSolve()`, `TSRemoveTrajectory()`
4792d29f1f2SStefano Zampini @*/
480d71ae5a4SJacob Faibussowitsch PetscErrorCode TSResetTrajectory(TS ts)
481d71ae5a4SJacob Faibussowitsch {
4822d29f1f2SStefano Zampini   PetscFunctionBegin;
4832d29f1f2SStefano Zampini   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4842d29f1f2SStefano Zampini   if (ts->trajectory) {
4859566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryDestroy(&ts->trajectory));
4869566063dSJacob Faibussowitsch     PetscCall(TSTrajectoryCreate(PetscObjectComm((PetscObject)ts), &ts->trajectory));
4872d29f1f2SStefano Zampini   }
4882d29f1f2SStefano Zampini   PetscFunctionReturn(0);
4892d29f1f2SStefano Zampini }
4902d29f1f2SStefano Zampini 
4912d29f1f2SStefano Zampini /*@
492bcf0153eSBarry Smith    TSRemoveTrajectory - Destroys and removes the internal `TSTrajectory` object from TS
49367a3cfb0SHong Zhang 
494c3339decSBarry Smith    Collective
49567a3cfb0SHong Zhang 
49667a3cfb0SHong Zhang    Input Parameters:
497bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
49867a3cfb0SHong Zhang 
49967a3cfb0SHong Zhang    Level: intermediate
50067a3cfb0SHong Zhang 
501bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSTrajectory`, `TSResetTrajectory()`, `TSAdjointSolve()`
50267a3cfb0SHong Zhang @*/
503d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRemoveTrajectory(TS ts)
504d71ae5a4SJacob Faibussowitsch {
50567a3cfb0SHong Zhang   PetscFunctionBegin;
50667a3cfb0SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5071e66621cSBarry Smith   if (ts->trajectory) PetscCall(TSTrajectoryDestroy(&ts->trajectory));
50867a3cfb0SHong Zhang   PetscFunctionReturn(0);
50967a3cfb0SHong Zhang }
51067a3cfb0SHong Zhang 
51167a3cfb0SHong Zhang /*@
512a7a1495cSBarry Smith    TSComputeRHSJacobian - Computes the Jacobian matrix that has been
513bcf0153eSBarry Smith       set with `TSSetRHSJacobian()`.
514a7a1495cSBarry Smith 
515c3339decSBarry Smith    Collective
516a7a1495cSBarry Smith 
517a7a1495cSBarry Smith    Input Parameters:
518bcf0153eSBarry Smith +  ts - the `TS` context
519a7a1495cSBarry Smith .  t - current timestep
5200910c330SBarry Smith -  U - input vector
521a7a1495cSBarry Smith 
522a7a1495cSBarry Smith    Output Parameters:
523a7a1495cSBarry Smith +  A - Jacobian matrix
5246b867d5aSJose E. Roman -  B - optional preconditioning matrix
525a7a1495cSBarry Smith 
526bcf0153eSBarry Smith    Level: developer
527bcf0153eSBarry Smith 
528bcf0153eSBarry Smith    Note:
529a7a1495cSBarry Smith    Most users should not need to explicitly call this routine, as it
530a7a1495cSBarry Smith    is used internally within the nonlinear solvers.
531a7a1495cSBarry Smith 
532bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `KSPSetOperators()`
533a7a1495cSBarry Smith @*/
534d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobian(TS ts, PetscReal t, Vec U, Mat A, Mat B)
535d71ae5a4SJacob Faibussowitsch {
536270bf2e7SJed Brown   PetscObjectState Ustate;
5376c1e1eecSBarry Smith   PetscObjectId    Uid;
53824989b8cSPeter Brune   DM               dm;
539942e3340SBarry Smith   DMTS             tsdm;
54024989b8cSPeter Brune   TSRHSJacobian    rhsjacobianfunc;
54124989b8cSPeter Brune   void            *ctx;
542b2df71adSDebojyoti Ghosh   TSRHSFunction    rhsfunction;
543a7a1495cSBarry Smith 
544a7a1495cSBarry Smith   PetscFunctionBegin;
5450700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5460910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
5470910c330SBarry Smith   PetscCheckSameComm(ts, 1, U, 3);
5489566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
5499566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &tsdm));
5509566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
5519566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobianfunc, &ctx));
5529566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
5539566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
554971015bcSStefano Zampini 
5552663174eSHong Zhang   if (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && (rhsfunction != TSComputeRHSFunctionLinear)) PetscFunctionReturn(0);
556d90be118SSean Farley 
55763a3b9bcSJacob 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);
55824989b8cSPeter Brune   if (rhsjacobianfunc) {
5599566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
560792fecdfSBarry Smith     PetscCallBack("TS callback Jacobian", (*rhsjacobianfunc)(ts, t, U, A, B, ctx));
561a6ab3590SBarry Smith     ts->rhsjacs++;
5629566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
563ef66eb69SBarry Smith   } else {
5649566063dSJacob Faibussowitsch     PetscCall(MatZeroEntries(A));
5659566063dSJacob Faibussowitsch     if (B && A != B) PetscCall(MatZeroEntries(B));
566ef66eb69SBarry Smith   }
5670e4ef248SJed Brown   ts->rhsjacobian.time  = t;
568971015bcSStefano Zampini   ts->rhsjacobian.shift = 0;
569971015bcSStefano Zampini   ts->rhsjacobian.scale = 1.;
5709566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetId((PetscObject)U, &ts->rhsjacobian.Xid));
5719566063dSJacob Faibussowitsch   PetscCall(PetscObjectStateGet((PetscObject)U, &ts->rhsjacobian.Xstate));
572a7a1495cSBarry Smith   PetscFunctionReturn(0);
573a7a1495cSBarry Smith }
574a7a1495cSBarry Smith 
575316643e7SJed Brown /*@
576bcf0153eSBarry Smith    TSComputeRHSFunction - Evaluates the right-hand-side function for a `TS`
577d763cef2SBarry Smith 
578c3339decSBarry Smith    Collective
579316643e7SJed Brown 
580316643e7SJed Brown    Input Parameters:
581bcf0153eSBarry Smith +  ts - the `TS` context
582316643e7SJed Brown .  t - current time
5830910c330SBarry Smith -  U - state vector
584316643e7SJed Brown 
585316643e7SJed Brown    Output Parameter:
586316643e7SJed Brown .  y - right hand side
587316643e7SJed Brown 
588bcf0153eSBarry Smith    Level: developer
589bcf0153eSBarry Smith 
590316643e7SJed Brown    Note:
591316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
592316643e7SJed Brown    is used internally within the nonlinear solvers.
593316643e7SJed Brown 
594bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
595316643e7SJed Brown @*/
596d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunction(TS ts, PetscReal t, Vec U, Vec y)
597d71ae5a4SJacob Faibussowitsch {
59824989b8cSPeter Brune   TSRHSFunction rhsfunction;
59924989b8cSPeter Brune   TSIFunction   ifunction;
60024989b8cSPeter Brune   void         *ctx;
60124989b8cSPeter Brune   DM            dm;
60224989b8cSPeter Brune 
603d763cef2SBarry Smith   PetscFunctionBegin;
6040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6050910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6060700a824SBarry Smith   PetscValidHeaderSpecific(y, VEC_CLASSID, 4);
6079566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6089566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, &ctx));
6099566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, NULL));
610d763cef2SBarry Smith 
6113c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
612d763cef2SBarry Smith 
61324989b8cSPeter Brune   if (rhsfunction) {
6149566063dSJacob Faibussowitsch     PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, y, 0));
6159566063dSJacob Faibussowitsch     PetscCall(VecLockReadPush(U));
616792fecdfSBarry Smith     PetscCallBack("TS callback right-hand-side", (*rhsfunction)(ts, t, U, y, ctx));
6179566063dSJacob Faibussowitsch     PetscCall(VecLockReadPop(U));
618a6ab3590SBarry Smith     ts->rhsfuncs++;
6199566063dSJacob Faibussowitsch     PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, y, 0));
6201e66621cSBarry Smith   } else PetscCall(VecZeroEntries(y));
621d763cef2SBarry Smith   PetscFunctionReturn(0);
622d763cef2SBarry Smith }
623d763cef2SBarry Smith 
624ef20d060SBarry Smith /*@
625ef20d060SBarry Smith    TSComputeSolutionFunction - Evaluates the solution function.
626ef20d060SBarry Smith 
627c3339decSBarry Smith    Collective
628ef20d060SBarry Smith 
629ef20d060SBarry Smith    Input Parameters:
630bcf0153eSBarry Smith +  ts - the `TS` context
631ef20d060SBarry Smith -  t - current time
632ef20d060SBarry Smith 
633ef20d060SBarry Smith    Output Parameter:
6340910c330SBarry Smith .  U - the solution
635ef20d060SBarry Smith 
636ef20d060SBarry Smith    Level: developer
637ef20d060SBarry Smith 
638bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
639ef20d060SBarry Smith @*/
640d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeSolutionFunction(TS ts, PetscReal t, Vec U)
641d71ae5a4SJacob Faibussowitsch {
642ef20d060SBarry Smith   TSSolutionFunction solutionfunction;
643ef20d060SBarry Smith   void              *ctx;
644ef20d060SBarry Smith   DM                 dm;
645ef20d060SBarry Smith 
646ef20d060SBarry Smith   PetscFunctionBegin;
647ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6480910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6509566063dSJacob Faibussowitsch   PetscCall(DMTSGetSolutionFunction(dm, &solutionfunction, &ctx));
651792fecdfSBarry Smith   if (solutionfunction) PetscCallBack("TS callback solution", (*solutionfunction)(ts, t, U, ctx));
652ef20d060SBarry Smith   PetscFunctionReturn(0);
653ef20d060SBarry Smith }
6549b7cd975SBarry Smith /*@
6559b7cd975SBarry Smith    TSComputeForcingFunction - Evaluates the forcing function.
6569b7cd975SBarry Smith 
657c3339decSBarry Smith    Collective
6589b7cd975SBarry Smith 
6599b7cd975SBarry Smith    Input Parameters:
660bcf0153eSBarry Smith +  ts - the `TS` context
6619b7cd975SBarry Smith -  t - current time
6629b7cd975SBarry Smith 
6639b7cd975SBarry Smith    Output Parameter:
6649b7cd975SBarry Smith .  U - the function value
6659b7cd975SBarry Smith 
6669b7cd975SBarry Smith    Level: developer
6679b7cd975SBarry Smith 
668bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSSetRHSFunction()`, `TSComputeIFunction()`
6699b7cd975SBarry Smith @*/
670d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeForcingFunction(TS ts, PetscReal t, Vec U)
671d71ae5a4SJacob Faibussowitsch {
6729b7cd975SBarry Smith   void             *ctx;
6739b7cd975SBarry Smith   DM                dm;
6745f80ce2aSJacob Faibussowitsch   TSForcingFunction forcing;
6759b7cd975SBarry Smith 
6769b7cd975SBarry Smith   PetscFunctionBegin;
6779b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6789b7cd975SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
6799566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
6809566063dSJacob Faibussowitsch   PetscCall(DMTSGetForcingFunction(dm, &forcing, &ctx));
6819b7cd975SBarry Smith 
682792fecdfSBarry Smith   if (forcing) PetscCallBack("TS callback forcing function", (*forcing)(ts, t, U, ctx));
6839b7cd975SBarry Smith   PetscFunctionReturn(0);
6849b7cd975SBarry Smith }
685ef20d060SBarry Smith 
686d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSGetRHSVec_Private(TS ts, Vec *Frhs)
687d71ae5a4SJacob Faibussowitsch {
6882dd45cf8SJed Brown   Vec F;
689214bc6a2SJed Brown 
690214bc6a2SJed Brown   PetscFunctionBegin;
6910298fd71SBarry Smith   *Frhs = NULL;
6929566063dSJacob Faibussowitsch   PetscCall(TSGetIFunction(ts, &F, NULL, NULL));
6931e66621cSBarry Smith   if (!ts->Frhs) PetscCall(VecDuplicate(F, &ts->Frhs));
694214bc6a2SJed Brown   *Frhs = ts->Frhs;
695214bc6a2SJed Brown   PetscFunctionReturn(0);
696214bc6a2SJed Brown }
697214bc6a2SJed Brown 
698d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSMats_Private(TS ts, Mat *Arhs, Mat *Brhs)
699d71ae5a4SJacob Faibussowitsch {
700214bc6a2SJed Brown   Mat         A, B;
70141a1d4d2SBarry Smith   TSIJacobian ijacobian;
702214bc6a2SJed Brown 
703214bc6a2SJed Brown   PetscFunctionBegin;
704c0cd0301SJed Brown   if (Arhs) *Arhs = NULL;
705c0cd0301SJed Brown   if (Brhs) *Brhs = NULL;
7069566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, &ijacobian, NULL));
707214bc6a2SJed Brown   if (Arhs) {
708214bc6a2SJed Brown     if (!ts->Arhs) {
70941a1d4d2SBarry Smith       if (ijacobian) {
7109566063dSJacob Faibussowitsch         PetscCall(MatDuplicate(A, MAT_DO_NOT_COPY_VALUES, &ts->Arhs));
7119566063dSJacob Faibussowitsch         PetscCall(TSSetMatStructure(ts, SAME_NONZERO_PATTERN));
71241a1d4d2SBarry Smith       } else {
71341a1d4d2SBarry Smith         ts->Arhs = A;
7149566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
71541a1d4d2SBarry Smith       }
7163565c898SBarry Smith     } else {
7173565c898SBarry Smith       PetscBool flg;
7189566063dSJacob Faibussowitsch       PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
7193565c898SBarry Smith       /* Handle case where user provided only RHSJacobian and used -snes_mf_operator */
7203565c898SBarry Smith       if (flg && !ijacobian && ts->Arhs == ts->Brhs) {
7219566063dSJacob Faibussowitsch         PetscCall(PetscObjectDereference((PetscObject)ts->Arhs));
7223565c898SBarry Smith         ts->Arhs = A;
7239566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)A));
7243565c898SBarry Smith       }
725214bc6a2SJed Brown     }
726214bc6a2SJed Brown     *Arhs = ts->Arhs;
727214bc6a2SJed Brown   }
728214bc6a2SJed Brown   if (Brhs) {
729214bc6a2SJed Brown     if (!ts->Brhs) {
730bdb70873SJed Brown       if (A != B) {
73141a1d4d2SBarry Smith         if (ijacobian) {
7329566063dSJacob Faibussowitsch           PetscCall(MatDuplicate(B, MAT_DO_NOT_COPY_VALUES, &ts->Brhs));
733bdb70873SJed Brown         } else {
73441a1d4d2SBarry Smith           ts->Brhs = B;
7359566063dSJacob Faibussowitsch           PetscCall(PetscObjectReference((PetscObject)B));
73641a1d4d2SBarry Smith         }
73741a1d4d2SBarry Smith       } else {
7389566063dSJacob Faibussowitsch         PetscCall(PetscObjectReference((PetscObject)ts->Arhs));
73951699248SLisandro Dalcin         ts->Brhs = ts->Arhs;
740bdb70873SJed Brown       }
741214bc6a2SJed Brown     }
742214bc6a2SJed Brown     *Brhs = ts->Brhs;
743214bc6a2SJed Brown   }
744214bc6a2SJed Brown   PetscFunctionReturn(0);
745214bc6a2SJed Brown }
746214bc6a2SJed Brown 
747316643e7SJed Brown /*@
7480910c330SBarry Smith    TSComputeIFunction - Evaluates the DAE residual written in implicit form F(t,U,Udot)=0
749316643e7SJed Brown 
750c3339decSBarry Smith    Collective
751316643e7SJed Brown 
752316643e7SJed Brown    Input Parameters:
753bcf0153eSBarry Smith +  ts - the `TS` context
754316643e7SJed Brown .  t - current time
7550910c330SBarry Smith .  U - state vector
7560910c330SBarry Smith .  Udot - time derivative of state vector
757bcf0153eSBarry Smith -  imex - flag indicates if the method is `TSIMEX` so that the RHSFunction should be kept separate
758316643e7SJed Brown 
759316643e7SJed Brown    Output Parameter:
760316643e7SJed Brown .  Y - right hand side
761316643e7SJed Brown 
762bcf0153eSBarry Smith    Level: developer
763bcf0153eSBarry Smith 
764316643e7SJed Brown    Note:
765316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
766316643e7SJed Brown    is used internally within the nonlinear solvers.
767316643e7SJed Brown 
768316643e7SJed Brown    If the user did did not write their equations in implicit form, this
769316643e7SJed Brown    function recasts them in implicit form.
770316643e7SJed Brown 
771bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSComputeRHSFunction()`
772316643e7SJed Brown @*/
773d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunction(TS ts, PetscReal t, Vec U, Vec Udot, Vec Y, PetscBool imex)
774d71ae5a4SJacob Faibussowitsch {
77524989b8cSPeter Brune   TSIFunction   ifunction;
77624989b8cSPeter Brune   TSRHSFunction rhsfunction;
77724989b8cSPeter Brune   void         *ctx;
77824989b8cSPeter Brune   DM            dm;
779316643e7SJed Brown 
780316643e7SJed Brown   PetscFunctionBegin;
7810700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
7820910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
7830910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
7840700a824SBarry Smith   PetscValidHeaderSpecific(Y, VEC_CLASSID, 5);
785316643e7SJed Brown 
7869566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
7879566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, &ifunction, &ctx));
7889566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
78924989b8cSPeter Brune 
7903c633725SBarry Smith   PetscCheck(rhsfunction || ifunction, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSFunction() and / or TSSetIFunction()");
791d90be118SSean Farley 
7929566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, Udot, Y));
79324989b8cSPeter Brune   if (ifunction) {
794792fecdfSBarry Smith     PetscCallBack("TS callback implicit function", (*ifunction)(ts, t, U, Udot, Y, ctx));
795a6ab3590SBarry Smith     ts->ifuncs++;
796214bc6a2SJed Brown   }
797214bc6a2SJed Brown   if (imex) {
7981e66621cSBarry Smith     if (!ifunction) PetscCall(VecCopy(Udot, Y));
79924989b8cSPeter Brune   } else if (rhsfunction) {
80024989b8cSPeter Brune     if (ifunction) {
801214bc6a2SJed Brown       Vec Frhs;
8029566063dSJacob Faibussowitsch       PetscCall(TSGetRHSVec_Private(ts, &Frhs));
8039566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
8049566063dSJacob Faibussowitsch       PetscCall(VecAXPY(Y, -1, Frhs));
8052dd45cf8SJed Brown     } else {
8069566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSFunction(ts, t, U, Y));
8079566063dSJacob Faibussowitsch       PetscCall(VecAYPX(Y, -1, Udot));
808316643e7SJed Brown     }
8094a6899ffSJed Brown   }
8109566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, Udot, Y));
811316643e7SJed Brown   PetscFunctionReturn(0);
812316643e7SJed Brown }
813316643e7SJed Brown 
814cfa8a9a2SHong Zhang /*
815cfa8a9a2SHong Zhang    TSRecoverRHSJacobian - Recover the Jacobian matrix so that one can call TSComputeRHSJacobian() on it.
816cfa8a9a2SHong Zhang 
817cfa8a9a2SHong Zhang    Note:
818cfa8a9a2SHong Zhang    This routine is needed when one switches from TSComputeIJacobian() to TSComputeRHSJacobian() because the Jacobian matrix may be shifted or scaled in TSComputeIJacobian().
819cfa8a9a2SHong Zhang 
820cfa8a9a2SHong Zhang */
821d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSRecoverRHSJacobian(TS ts, Mat A, Mat B)
822d71ae5a4SJacob Faibussowitsch {
823cfa8a9a2SHong Zhang   PetscFunctionBegin;
824cfa8a9a2SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8253c633725SBarry Smith   PetscCheck(A == ts->Arhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Amat");
8263c633725SBarry Smith   PetscCheck(B == ts->Brhs, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Invalid Bmat");
827cfa8a9a2SHong Zhang 
8281baa6e33SBarry Smith   if (ts->rhsjacobian.shift) PetscCall(MatShift(A, -ts->rhsjacobian.shift));
82948a46eb9SPierre Jolivet   if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(A, -1));
830cfa8a9a2SHong Zhang   if (B && B == ts->Brhs && A != B) {
8311baa6e33SBarry Smith     if (ts->rhsjacobian.shift) PetscCall(MatShift(B, -ts->rhsjacobian.shift));
8321e66621cSBarry Smith     if (ts->rhsjacobian.scale == -1.) PetscCall(MatScale(B, -1));
833cfa8a9a2SHong Zhang   }
834cfa8a9a2SHong Zhang   ts->rhsjacobian.shift = 0;
835cfa8a9a2SHong Zhang   ts->rhsjacobian.scale = 1.;
836cfa8a9a2SHong Zhang   PetscFunctionReturn(0);
837cfa8a9a2SHong Zhang }
838cfa8a9a2SHong Zhang 
839316643e7SJed Brown /*@
840316643e7SJed Brown    TSComputeIJacobian - Evaluates the Jacobian of the DAE
841316643e7SJed Brown 
842c3339decSBarry Smith    Collective
843316643e7SJed Brown 
844316643e7SJed Brown    Input
845316643e7SJed Brown       Input Parameters:
846bcf0153eSBarry Smith +  ts - the `TS` context
847316643e7SJed Brown .  t - current timestep
8480910c330SBarry Smith .  U - state vector
8490910c330SBarry Smith .  Udot - time derivative of state vector
850214bc6a2SJed Brown .  shift - shift to apply, see note below
851bcf0153eSBarry Smith -  imex - flag indicates if the method is `TSIMEX` so that the RHSJacobian should be kept separate
852316643e7SJed Brown 
853316643e7SJed Brown    Output Parameters:
854316643e7SJed Brown +  A - Jacobian matrix
8553565c898SBarry Smith -  B - matrix from which the preconditioner is constructed; often the same as A
856316643e7SJed Brown 
857bcf0153eSBarry Smith    Level: developer
858bcf0153eSBarry Smith 
859316643e7SJed Brown    Notes:
8600910c330SBarry Smith    If F(t,U,Udot)=0 is the DAE, the required Jacobian is
861316643e7SJed Brown 
8620910c330SBarry Smith    dF/dU + shift*dF/dUdot
863316643e7SJed Brown 
864316643e7SJed Brown    Most users should not need to explicitly call this routine, as it
865316643e7SJed Brown    is used internally within the nonlinear solvers.
866316643e7SJed Brown 
867bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIJacobian()`
86863495f91SJed Brown @*/
869d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobian(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, PetscBool imex)
870d71ae5a4SJacob Faibussowitsch {
87124989b8cSPeter Brune   TSIJacobian   ijacobian;
87224989b8cSPeter Brune   TSRHSJacobian rhsjacobian;
87324989b8cSPeter Brune   DM            dm;
87424989b8cSPeter Brune   void         *ctx;
875316643e7SJed Brown 
876316643e7SJed Brown   PetscFunctionBegin;
8770700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
8780910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
8790910c330SBarry Smith   PetscValidHeaderSpecific(Udot, VEC_CLASSID, 4);
880316643e7SJed Brown   PetscValidPointer(A, 6);
88194ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 6);
882316643e7SJed Brown   PetscValidPointer(B, 7);
88394ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 7);
88424989b8cSPeter Brune 
8859566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
8869566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, &ctx));
8879566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
88824989b8cSPeter Brune 
8893c633725SBarry Smith   PetscCheck(rhsjacobian || ijacobian, PetscObjectComm((PetscObject)ts), PETSC_ERR_USER, "Must call TSSetRHSJacobian() and / or TSSetIJacobian()");
890316643e7SJed Brown 
8919566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, A, B));
89224989b8cSPeter Brune   if (ijacobian) {
893792fecdfSBarry Smith     PetscCallBack("TS callback implicit Jacobian", (*ijacobian)(ts, t, U, Udot, shift, A, B, ctx));
894a6ab3590SBarry Smith     ts->ijacs++;
8954a6899ffSJed Brown   }
896214bc6a2SJed Brown   if (imex) {
897b5abc632SBarry Smith     if (!ijacobian) { /* system was written as Udot = G(t,U) */
8984c26be97Sstefano_zampini       PetscBool assembled;
899971015bcSStefano Zampini       if (rhsjacobian) {
900971015bcSStefano Zampini         Mat Arhs = NULL;
9019566063dSJacob Faibussowitsch         PetscCall(TSGetRHSMats_Private(ts, &Arhs, NULL));
902971015bcSStefano Zampini         if (A == Arhs) {
9033c633725SBarry 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 */
904971015bcSStefano Zampini           ts->rhsjacobian.time = PETSC_MIN_REAL;
905971015bcSStefano Zampini         }
906971015bcSStefano Zampini       }
9079566063dSJacob Faibussowitsch       PetscCall(MatZeroEntries(A));
9089566063dSJacob Faibussowitsch       PetscCall(MatAssembled(A, &assembled));
9094c26be97Sstefano_zampini       if (!assembled) {
9109566063dSJacob Faibussowitsch         PetscCall(MatAssemblyBegin(A, MAT_FINAL_ASSEMBLY));
9119566063dSJacob Faibussowitsch         PetscCall(MatAssemblyEnd(A, MAT_FINAL_ASSEMBLY));
9124c26be97Sstefano_zampini       }
9139566063dSJacob Faibussowitsch       PetscCall(MatShift(A, shift));
91494ab13aaSBarry Smith       if (A != B) {
9159566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(B));
9169566063dSJacob Faibussowitsch         PetscCall(MatAssembled(B, &assembled));
9174c26be97Sstefano_zampini         if (!assembled) {
9189566063dSJacob Faibussowitsch           PetscCall(MatAssemblyBegin(B, MAT_FINAL_ASSEMBLY));
9199566063dSJacob Faibussowitsch           PetscCall(MatAssemblyEnd(B, MAT_FINAL_ASSEMBLY));
9204c26be97Sstefano_zampini         }
9219566063dSJacob Faibussowitsch         PetscCall(MatShift(B, shift));
922214bc6a2SJed Brown       }
923214bc6a2SJed Brown     }
924214bc6a2SJed Brown   } else {
925e1244c69SJed Brown     Mat Arhs = NULL, Brhs = NULL;
9261e66621cSBarry Smith 
9271e66621cSBarry Smith     /* RHSJacobian needs to be converted to part of IJacobian if exists */
9281e66621cSBarry Smith     if (rhsjacobian) PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
929e8b1e424SHong Zhang     if (Arhs == A) { /* No IJacobian matrix, so we only have the RHS matrix */
930e8b1e424SHong Zhang       PetscObjectState Ustate;
931e8b1e424SHong Zhang       PetscObjectId    Uid;
932e8b1e424SHong Zhang       TSRHSFunction    rhsfunction;
933e8b1e424SHong Zhang 
9349566063dSJacob Faibussowitsch       PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
9359566063dSJacob Faibussowitsch       PetscCall(PetscObjectStateGet((PetscObject)U, &Ustate));
9369566063dSJacob Faibussowitsch       PetscCall(PetscObjectGetId((PetscObject)U, &Uid));
9379371c9d4SSatish Balay       if ((rhsjacobian == TSComputeRHSJacobianConstant || (ts->rhsjacobian.time == t && (ts->problem_type == TS_LINEAR || (ts->rhsjacobian.Xid == Uid && ts->rhsjacobian.Xstate == Ustate)) && rhsfunction != TSComputeRHSFunctionLinear)) &&
9389371c9d4SSatish Balay           ts->rhsjacobian.scale == -1.) {                      /* No need to recompute RHSJacobian */
9399566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift - ts->rhsjacobian.shift)); /* revert the old shift and add the new shift with a single call to MatShift */
9401e66621cSBarry Smith         if (A != B) PetscCall(MatShift(B, shift - ts->rhsjacobian.shift));
941e8b1e424SHong Zhang       } else {
9423565c898SBarry Smith         PetscBool flg;
943e8b1e424SHong Zhang 
944e8b1e424SHong Zhang         if (ts->rhsjacobian.reuse) { /* Undo the damage */
945e8b1e424SHong Zhang           /* MatScale has a short path for this case.
946e8b1e424SHong Zhang              However, this code path is taken the first time TSComputeRHSJacobian is called
947e8b1e424SHong Zhang              and the matrices have not been assembled yet */
9489566063dSJacob Faibussowitsch           PetscCall(TSRecoverRHSJacobian(ts, A, B));
949e8b1e424SHong Zhang         }
9509566063dSJacob Faibussowitsch         PetscCall(TSComputeRHSJacobian(ts, t, U, A, B));
9519566063dSJacob Faibussowitsch         PetscCall(SNESGetUseMatrixFree(ts->snes, NULL, &flg));
9523565c898SBarry Smith         /* since -snes_mf_operator uses the full SNES function it does not need to be shifted or scaled here */
9533565c898SBarry Smith         if (!flg) {
9549566063dSJacob Faibussowitsch           PetscCall(MatScale(A, -1));
9559566063dSJacob Faibussowitsch           PetscCall(MatShift(A, shift));
9563565c898SBarry Smith         }
95794ab13aaSBarry Smith         if (A != B) {
9589566063dSJacob Faibussowitsch           PetscCall(MatScale(B, -1));
9599566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
960316643e7SJed Brown         }
961e8b1e424SHong Zhang       }
962e8b1e424SHong Zhang       ts->rhsjacobian.scale = -1;
963e8b1e424SHong Zhang       ts->rhsjacobian.shift = shift;
964d60b7d5cSBarry Smith     } else if (Arhs) {  /* Both IJacobian and RHSJacobian */
965e1244c69SJed Brown       if (!ijacobian) { /* No IJacobian provided, but we have a separate RHS matrix */
9669566063dSJacob Faibussowitsch         PetscCall(MatZeroEntries(A));
9679566063dSJacob Faibussowitsch         PetscCall(MatShift(A, shift));
96894ab13aaSBarry Smith         if (A != B) {
9699566063dSJacob Faibussowitsch           PetscCall(MatZeroEntries(B));
9709566063dSJacob Faibussowitsch           PetscCall(MatShift(B, shift));
971214bc6a2SJed Brown         }
972316643e7SJed Brown       }
9739566063dSJacob Faibussowitsch       PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
9749566063dSJacob Faibussowitsch       PetscCall(MatAXPY(A, -1, Arhs, ts->axpy_pattern));
9751e66621cSBarry Smith       if (A != B) PetscCall(MatAXPY(B, -1, Brhs, ts->axpy_pattern));
976316643e7SJed Brown     }
977316643e7SJed Brown   }
9789566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, A, B));
979316643e7SJed Brown   PetscFunctionReturn(0);
980316643e7SJed Brown }
981316643e7SJed Brown 
982d763cef2SBarry Smith /*@C
983d763cef2SBarry Smith     TSSetRHSFunction - Sets the routine for evaluating the function,
984b5abc632SBarry Smith     where U_t = G(t,u).
985d763cef2SBarry Smith 
986c3339decSBarry Smith     Logically Collective
987d763cef2SBarry Smith 
988d763cef2SBarry Smith     Input Parameters:
989bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
9900298fd71SBarry Smith .   r - vector to put the computed right hand side (or NULL to have it created)
991d763cef2SBarry Smith .   f - routine for evaluating the right-hand-side function
992d763cef2SBarry Smith -   ctx - [optional] user-defined context for private data for the
9930298fd71SBarry Smith           function evaluation routine (may be NULL)
994d763cef2SBarry Smith 
995a96d6ef6SBarry Smith     Calling sequence of f:
996a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec F,void *ctx);
997d763cef2SBarry Smith 
998a96d6ef6SBarry Smith +   ts - timestep context
999a96d6ef6SBarry Smith .   t - current timestep
1000d763cef2SBarry Smith .   u - input vector
1001d763cef2SBarry Smith .   F - function vector
1002d763cef2SBarry Smith -   ctx - [optional] user-defined function context
1003d763cef2SBarry Smith 
1004d763cef2SBarry Smith     Level: beginner
1005d763cef2SBarry Smith 
1006bcf0153eSBarry Smith     Note:
1007bcf0153eSBarry Smith     You must call this function or `TSSetIFunction()` to define your ODE. You cannot use this function when solving a DAE.
10082bbac0d3SBarry Smith 
1009bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSSetIFunction()`
1010d763cef2SBarry Smith @*/
1011d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSFunction(TS ts, Vec r, PetscErrorCode (*f)(TS, PetscReal, Vec, Vec, void *), void *ctx)
1012d71ae5a4SJacob Faibussowitsch {
1013089b2837SJed Brown   SNES snes;
10140298fd71SBarry Smith   Vec  ralloc = NULL;
101524989b8cSPeter Brune   DM   dm;
1016d763cef2SBarry Smith 
1017089b2837SJed Brown   PetscFunctionBegin;
10180700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1019ca94891dSJed Brown   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
102024989b8cSPeter Brune 
10219566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10229566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSFunction(dm, f, ctx));
10239566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
1024e856ceecSJed Brown   if (!r && !ts->dm && ts->vec_sol) {
10259566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
1026e856ceecSJed Brown     r = ralloc;
1027e856ceecSJed Brown   }
10289566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
10299566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1030d763cef2SBarry Smith   PetscFunctionReturn(0);
1031d763cef2SBarry Smith }
1032d763cef2SBarry Smith 
1033ef20d060SBarry Smith /*@C
1034abd5a294SJed Brown     TSSetSolutionFunction - Provide a function that computes the solution of the ODE or DAE
1035ef20d060SBarry Smith 
1036c3339decSBarry Smith     Logically Collective
1037ef20d060SBarry Smith 
1038ef20d060SBarry Smith     Input Parameters:
1039bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1040ef20d060SBarry Smith .   f - routine for evaluating the solution
1041ef20d060SBarry Smith -   ctx - [optional] user-defined context for private data for the
10420298fd71SBarry Smith           function evaluation routine (may be NULL)
1043ef20d060SBarry Smith 
1044a96d6ef6SBarry Smith     Calling sequence of f:
1045a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,void *ctx);
1046ef20d060SBarry Smith 
1047ef20d060SBarry Smith +   t - current timestep
1048ef20d060SBarry Smith .   u - output vector
1049ef20d060SBarry Smith -   ctx - [optional] user-defined function context
1050ef20d060SBarry Smith 
1051bcf0153eSBarry Smith     Options Database Keys:
1052bcf0153eSBarry Smith +  -ts_monitor_lg_error - create a graphical monitor of error history, requires user to have provided `TSSetSolutionFunction()`
1053bcf0153eSBarry Smith -  -ts_monitor_draw_error - Monitor error graphically, requires user to have provided `TSSetSolutionFunction()`
1054bcf0153eSBarry Smith 
1055bcf0153eSBarry Smith     Level: intermediate
10560ed3bfb6SBarry Smith 
1057abd5a294SJed Brown     Notes:
1058abd5a294SJed Brown     This routine is used for testing accuracy of time integration schemes when you already know the solution.
1059abd5a294SJed Brown     If analytic solutions are not known for your system, consider using the Method of Manufactured Solutions to
1060abd5a294SJed Brown     create closed-form solutions with non-physical forcing terms.
1061abd5a294SJed Brown 
1062bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
1063abd5a294SJed Brown 
1064bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetForcingFunction()`, `TSSetSolution()`, `TSGetSolution()`, `TSMonitorLGError()`, `TSMonitorDrawError()`
1065ef20d060SBarry Smith @*/
1066d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolutionFunction(TS ts, PetscErrorCode (*f)(TS, PetscReal, Vec, void *), void *ctx)
1067d71ae5a4SJacob Faibussowitsch {
1068ef20d060SBarry Smith   DM dm;
1069ef20d060SBarry Smith 
1070ef20d060SBarry Smith   PetscFunctionBegin;
1071ef20d060SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
10729566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
10739566063dSJacob Faibussowitsch   PetscCall(DMTSSetSolutionFunction(dm, f, ctx));
1074ef20d060SBarry Smith   PetscFunctionReturn(0);
1075ef20d060SBarry Smith }
1076ef20d060SBarry Smith 
10779b7cd975SBarry Smith /*@C
10789b7cd975SBarry Smith     TSSetForcingFunction - Provide a function that computes a forcing term for a ODE or PDE
10799b7cd975SBarry Smith 
1080c3339decSBarry Smith     Logically Collective
10819b7cd975SBarry Smith 
10829b7cd975SBarry Smith     Input Parameters:
1083bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1084e162b725SBarry Smith .   func - routine for evaluating the forcing function
10859b7cd975SBarry Smith -   ctx - [optional] user-defined context for private data for the
10860298fd71SBarry Smith           function evaluation routine (may be NULL)
10879b7cd975SBarry Smith 
10889b7cd975SBarry Smith     Calling sequence of func:
10896bc98fa9SBarry Smith $     PetscErrorCode func (TS ts,PetscReal t,Vec f,void *ctx);
10909b7cd975SBarry Smith 
10919b7cd975SBarry Smith +   t - current timestep
1092e162b725SBarry Smith .   f - output vector
10939b7cd975SBarry Smith -   ctx - [optional] user-defined function context
10949b7cd975SBarry Smith 
1095bcf0153eSBarry Smith     Level: intermediate
1096bcf0153eSBarry Smith 
10979b7cd975SBarry Smith     Notes:
10989b7cd975SBarry Smith     This routine is useful for testing accuracy of time integration schemes when using the Method of Manufactured Solutions to
1099e162b725SBarry 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
1100e162b725SBarry Smith     definition of the problem you are solving and hence possibly introducing bugs.
1101e162b725SBarry Smith 
1102e162b725SBarry Smith     This replaces the ODE F(u,u_t,t) = 0 the TS is solving with F(u,u_t,t) - func(t) = 0
1103e162b725SBarry Smith 
1104e162b725SBarry 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
1105e162b725SBarry Smith     parameters can be passed in the ctx variable.
11069b7cd975SBarry Smith 
1107bcf0153eSBarry Smith     For low-dimensional problems solved in serial, such as small discrete systems, `TSMonitorLGError()` can be used to monitor the error history.
11089b7cd975SBarry Smith 
1109bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetIJacobian()`, `TSComputeSolutionFunction()`, `TSSetSolutionFunction()`
11109b7cd975SBarry Smith @*/
1111d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetForcingFunction(TS ts, TSForcingFunction func, void *ctx)
1112d71ae5a4SJacob Faibussowitsch {
11139b7cd975SBarry Smith   DM dm;
11149b7cd975SBarry Smith 
11159b7cd975SBarry Smith   PetscFunctionBegin;
11169b7cd975SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
11179566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11189566063dSJacob Faibussowitsch   PetscCall(DMTSSetForcingFunction(dm, func, ctx));
11199b7cd975SBarry Smith   PetscFunctionReturn(0);
11209b7cd975SBarry Smith }
11219b7cd975SBarry Smith 
1122d763cef2SBarry Smith /*@C
1123f7ab8db6SBarry Smith    TSSetRHSJacobian - Sets the function to compute the Jacobian of G,
1124b5abc632SBarry Smith    where U_t = G(U,t), as well as the location to store the matrix.
1125d763cef2SBarry Smith 
1126c3339decSBarry Smith    Logically Collective
1127d763cef2SBarry Smith 
1128d763cef2SBarry Smith    Input Parameters:
1129bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1130e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1131e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1132d763cef2SBarry Smith .  f   - the Jacobian evaluation routine
1133d763cef2SBarry Smith -  ctx - [optional] user-defined context for private data for the
11340298fd71SBarry Smith          Jacobian evaluation routine (may be NULL)
1135d763cef2SBarry Smith 
1136f7ab8db6SBarry Smith    Calling sequence of f:
1137a96d6ef6SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Mat A,Mat B,void *ctx);
1138d763cef2SBarry Smith 
1139d763cef2SBarry Smith +  t - current timestep
1140d763cef2SBarry Smith .  u - input vector
1141e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1142e5d3d808SBarry Smith .  Pmat - matrix from which preconditioner is to be constructed (usually the same as Amat)
1143d763cef2SBarry Smith -  ctx - [optional] user-defined context for matrix evaluation routine
1144d763cef2SBarry Smith 
1145bcf0153eSBarry Smith    Level: beginner
1146bcf0153eSBarry Smith 
11476cd88445SBarry Smith    Notes:
11486cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
11496cd88445SBarry Smith 
1150bcf0153eSBarry Smith    The `TS` solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1151ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1152d763cef2SBarry Smith 
1153bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNESComputeJacobianDefaultColor()`, `TSSetRHSFunction()`, `TSRHSJacobianSetReuse()`, `TSSetIJacobian()`
1154d763cef2SBarry Smith @*/
1155d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetRHSJacobian(TS ts, Mat Amat, Mat Pmat, TSRHSJacobian f, void *ctx)
1156d71ae5a4SJacob Faibussowitsch {
1157089b2837SJed Brown   SNES        snes;
115824989b8cSPeter Brune   DM          dm;
115924989b8cSPeter Brune   TSIJacobian ijacobian;
1160277b19d0SLisandro Dalcin 
1161d763cef2SBarry Smith   PetscFunctionBegin;
11620700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1163e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1164e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1165e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1166e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
1167d763cef2SBarry Smith 
11689566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
11699566063dSJacob Faibussowitsch   PetscCall(DMTSSetRHSJacobian(dm, f, ctx));
11709566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijacobian, NULL));
11719566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
11721e66621cSBarry Smith   if (!ijacobian) PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1173e5d3d808SBarry Smith   if (Amat) {
11749566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Amat));
11759566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Arhs));
1176e5d3d808SBarry Smith     ts->Arhs = Amat;
11770e4ef248SJed Brown   }
1178e5d3d808SBarry Smith   if (Pmat) {
11799566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)Pmat));
11809566063dSJacob Faibussowitsch     PetscCall(MatDestroy(&ts->Brhs));
1181e5d3d808SBarry Smith     ts->Brhs = Pmat;
11820e4ef248SJed Brown   }
1183d763cef2SBarry Smith   PetscFunctionReturn(0);
1184d763cef2SBarry Smith }
1185d763cef2SBarry Smith 
1186316643e7SJed Brown /*@C
1187b5abc632SBarry Smith    TSSetIFunction - Set the function to compute F(t,U,U_t) where F() = 0 is the DAE to be solved.
1188316643e7SJed Brown 
1189c3339decSBarry Smith    Logically Collective
1190316643e7SJed Brown 
1191316643e7SJed Brown    Input Parameters:
1192bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
11930298fd71SBarry Smith .  r   - vector to hold the residual (or NULL to have it created internally)
1194316643e7SJed Brown .  f   - the function evaluation routine
11950298fd71SBarry Smith -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1196316643e7SJed Brown 
1197316643e7SJed Brown    Calling sequence of f:
11986bc98fa9SBarry Smith $     PetscErrorCode f(TS ts,PetscReal t,Vec u,Vec u_t,Vec F,ctx);
1199316643e7SJed Brown 
1200316643e7SJed Brown +  t   - time at step/stage being solved
1201316643e7SJed Brown .  u   - state vector
1202316643e7SJed Brown .  u_t - time derivative of state vector
1203316643e7SJed Brown .  F   - function vector
1204316643e7SJed Brown -  ctx - [optional] user-defined context for matrix evaluation routine
1205316643e7SJed Brown 
1206316643e7SJed Brown    Level: beginner
1207316643e7SJed Brown 
1208bcf0153eSBarry Smith    Note:
1209bcf0153eSBarry Smith    The user MUST call either this routine or `TSSetRHSFunction()` to define the ODE.  When solving DAEs you must use this function.
1210bcf0153eSBarry Smith 
1211bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSSetRHSFunction()`, `TSSetIJacobian()`
1212316643e7SJed Brown @*/
1213d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIFunction(TS ts, Vec r, TSIFunction f, void *ctx)
1214d71ae5a4SJacob Faibussowitsch {
1215089b2837SJed Brown   SNES snes;
121651699248SLisandro Dalcin   Vec  ralloc = NULL;
121724989b8cSPeter Brune   DM   dm;
1218316643e7SJed Brown 
1219316643e7SJed Brown   PetscFunctionBegin;
12200700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
122151699248SLisandro Dalcin   if (r) PetscValidHeaderSpecific(r, VEC_CLASSID, 2);
122224989b8cSPeter Brune 
12239566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12249566063dSJacob Faibussowitsch   PetscCall(DMTSSetIFunction(dm, f, ctx));
122524989b8cSPeter Brune 
12269566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
122751699248SLisandro Dalcin   if (!r && !ts->dm && ts->vec_sol) {
12289566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->vec_sol, &ralloc));
122951699248SLisandro Dalcin     r = ralloc;
1230e856ceecSJed Brown   }
12319566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(snes, r, SNESTSFormFunction, ts));
12329566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ralloc));
1233089b2837SJed Brown   PetscFunctionReturn(0);
1234089b2837SJed Brown }
1235089b2837SJed Brown 
1236089b2837SJed Brown /*@C
1237a5b23f4aSJose E. Roman    TSGetIFunction - Returns the vector where the implicit residual is stored and the function/context to compute it.
1238089b2837SJed Brown 
1239089b2837SJed Brown    Not Collective
1240089b2837SJed Brown 
1241089b2837SJed Brown    Input Parameter:
1242bcf0153eSBarry Smith .  ts - the `TS` context
1243089b2837SJed Brown 
1244d8d19677SJose E. Roman    Output Parameters:
12450298fd71SBarry Smith +  r - vector to hold residual (or NULL)
12460298fd71SBarry Smith .  func - the function to compute residual (or NULL)
12470298fd71SBarry Smith -  ctx - the function context (or NULL)
1248089b2837SJed Brown 
1249089b2837SJed Brown    Level: advanced
1250089b2837SJed Brown 
1251bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`
1252089b2837SJed Brown @*/
1253d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIFunction(TS ts, Vec *r, TSIFunction *func, void **ctx)
1254d71ae5a4SJacob Faibussowitsch {
1255089b2837SJed Brown   SNES snes;
125624989b8cSPeter Brune   DM   dm;
1257089b2837SJed Brown 
1258089b2837SJed Brown   PetscFunctionBegin;
1259089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12609566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12619566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12629566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12639566063dSJacob Faibussowitsch   PetscCall(DMTSGetIFunction(dm, func, ctx));
1264089b2837SJed Brown   PetscFunctionReturn(0);
1265089b2837SJed Brown }
1266089b2837SJed Brown 
1267089b2837SJed Brown /*@C
1268089b2837SJed Brown    TSGetRHSFunction - Returns the vector where the right hand side is stored and the function/context to compute it.
1269089b2837SJed Brown 
1270089b2837SJed Brown    Not Collective
1271089b2837SJed Brown 
1272089b2837SJed Brown    Input Parameter:
1273bcf0153eSBarry Smith .  ts - the `TS` context
1274089b2837SJed Brown 
1275d8d19677SJose E. Roman    Output Parameters:
12760298fd71SBarry Smith +  r - vector to hold computed right hand side (or NULL)
12770298fd71SBarry Smith .  func - the function to compute right hand side (or NULL)
12780298fd71SBarry Smith -  ctx - the function context (or NULL)
1279089b2837SJed Brown 
1280089b2837SJed Brown    Level: advanced
1281089b2837SJed Brown 
1282bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `SNESGetFunction()`
1283089b2837SJed Brown @*/
1284d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSFunction(TS ts, Vec *r, TSRHSFunction *func, void **ctx)
1285d71ae5a4SJacob Faibussowitsch {
1286089b2837SJed Brown   SNES snes;
128724989b8cSPeter Brune   DM   dm;
1288089b2837SJed Brown 
1289089b2837SJed Brown   PetscFunctionBegin;
1290089b2837SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
12919566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
12929566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
12939566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
12949566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, func, ctx));
1295316643e7SJed Brown   PetscFunctionReturn(0);
1296316643e7SJed Brown }
1297316643e7SJed Brown 
1298316643e7SJed Brown /*@C
1299a4f0a591SBarry Smith    TSSetIJacobian - Set the function to compute the matrix dF/dU + a*dF/dU_t where F(t,U,U_t) is the function
1300bcf0153eSBarry Smith         provided with `TSSetIFunction()`.
1301316643e7SJed Brown 
1302c3339decSBarry Smith    Logically Collective
1303316643e7SJed Brown 
1304316643e7SJed Brown    Input Parameters:
1305bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1306e5d3d808SBarry Smith .  Amat - (approximate) Jacobian matrix
1307e5d3d808SBarry Smith .  Pmat - matrix used to compute preconditioner (usually the same as Amat)
1308316643e7SJed Brown .  f   - the Jacobian evaluation routine
13090298fd71SBarry Smith -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1310316643e7SJed Brown 
1311316643e7SJed Brown    Calling sequence of f:
13126bc98fa9SBarry Smith $    PetscErrorCode f(TS ts,PetscReal t,Vec U,Vec U_t,PetscReal a,Mat Amat,Mat Pmat,void *ctx);
1313316643e7SJed Brown 
1314316643e7SJed Brown +  t    - time at step/stage being solved
13151b4a444bSJed Brown .  U    - state vector
13161b4a444bSJed Brown .  U_t  - time derivative of state vector
1317316643e7SJed Brown .  a    - shift
1318e5d3d808SBarry Smith .  Amat - (approximate) Jacobian of F(t,U,W+a*U), equivalent to dF/dU + a*dF/dU_t
1319e5d3d808SBarry Smith .  Pmat - matrix used for constructing preconditioner, usually the same as Amat
1320316643e7SJed Brown -  ctx  - [optional] user-defined context for matrix evaluation routine
1321316643e7SJed Brown 
1322bcf0153eSBarry Smith    Level: beginner
1323316643e7SJed Brown 
1324bcf0153eSBarry Smith    Notes:
1325bcf0153eSBarry Smith    The matrices Amat and Pmat are exactly the matrices that are used by `SNES` for the nonlinear solve.
1326bcf0153eSBarry Smith 
1327bcf0153eSBarry Smith    If you know the operator Amat has a null space you can use `MatSetNullSpace()` and `MatSetTransposeNullSpace()` to supply the null
1328bcf0153eSBarry Smith    space to Amat and the `KSP` solvers will automatically use that null space as needed during the solution process.
1329895c21f2SBarry Smith 
1330a4f0a591SBarry Smith    The matrix dF/dU + a*dF/dU_t you provide turns out to be
1331b5abc632SBarry Smith    the Jacobian of F(t,U,W+a*U) where F(t,U,U_t) = 0 is the DAE to be solved.
1332a4f0a591SBarry Smith    The time integrator internally approximates U_t by W+a*U where the positive "shift"
1333a4f0a591SBarry Smith    a and vector W depend on the integration method, step size, and past states. For example with
1334a4f0a591SBarry Smith    the backward Euler method a = 1/dt and W = -a*U(previous timestep) so
1335a4f0a591SBarry Smith    W + a*U = a*(U - U(previous timestep)) = (U - U(previous timestep))/dt
1336a4f0a591SBarry Smith 
13376cd88445SBarry Smith    You must set all the diagonal entries of the matrices, if they are zero you must still set them with a zero value
13386cd88445SBarry Smith 
13396cd88445SBarry Smith    The TS solver may modify the nonzero structure and the entries of the matrices Amat and Pmat between the calls to f()
1340ca5f011dSBarry Smith    You should not assume the values are the same in the next call to f() as you set them in the previous call.
1341ca5f011dSBarry Smith 
1342bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetRHSJacobian()`, `SNESComputeJacobianDefaultColor()`, `SNESComputeJacobianDefault()`, `TSSetRHSFunction()`
1343316643e7SJed Brown @*/
1344d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetIJacobian(TS ts, Mat Amat, Mat Pmat, TSIJacobian f, void *ctx)
1345d71ae5a4SJacob Faibussowitsch {
1346089b2837SJed Brown   SNES snes;
134724989b8cSPeter Brune   DM   dm;
1348316643e7SJed Brown 
1349316643e7SJed Brown   PetscFunctionBegin;
13500700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1351e5d3d808SBarry Smith   if (Amat) PetscValidHeaderSpecific(Amat, MAT_CLASSID, 2);
1352e5d3d808SBarry Smith   if (Pmat) PetscValidHeaderSpecific(Pmat, MAT_CLASSID, 3);
1353e5d3d808SBarry Smith   if (Amat) PetscCheckSameComm(ts, 1, Amat, 2);
1354e5d3d808SBarry Smith   if (Pmat) PetscCheckSameComm(ts, 1, Pmat, 3);
135524989b8cSPeter Brune 
13569566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
13579566063dSJacob Faibussowitsch   PetscCall(DMTSSetIJacobian(dm, f, ctx));
135824989b8cSPeter Brune 
13599566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
13609566063dSJacob Faibussowitsch   PetscCall(SNESSetJacobian(snes, Amat, Pmat, SNESTSFormJacobian, ts));
1361316643e7SJed Brown   PetscFunctionReturn(0);
1362316643e7SJed Brown }
1363316643e7SJed Brown 
1364e1244c69SJed Brown /*@
1365bcf0153eSBarry Smith    TSRHSJacobianSetReuse - restore RHS Jacobian before re-evaluating.  Without this flag, `TS` will change the sign and
1366e1244c69SJed Brown    shift the RHS Jacobian for a finite-time-step implicit solve, in which case the user function will need to recompute
1367e1244c69SJed Brown    the entire Jacobian.  The reuse flag must be set if the evaluation function will assume that the matrix entries have
1368e1244c69SJed Brown    not been changed by the TS.
1369e1244c69SJed Brown 
1370e1244c69SJed Brown    Logically Collective
1371e1244c69SJed Brown 
13724165533cSJose E. Roman    Input Parameters:
1373bcf0153eSBarry Smith +  ts - `TS` context obtained from `TSCreate()`
1374bcf0153eSBarry Smith -  reuse - `PETSC_TRUE` if the RHS Jacobian
1375e1244c69SJed Brown 
1376e1244c69SJed Brown    Level: intermediate
1377e1244c69SJed Brown 
1378bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
1379e1244c69SJed Brown @*/
1380d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianSetReuse(TS ts, PetscBool reuse)
1381d71ae5a4SJacob Faibussowitsch {
1382e1244c69SJed Brown   PetscFunctionBegin;
1383e1244c69SJed Brown   ts->rhsjacobian.reuse = reuse;
1384e1244c69SJed Brown   PetscFunctionReturn(0);
1385e1244c69SJed Brown }
1386e1244c69SJed Brown 
1387efe9872eSLisandro Dalcin /*@C
1388efe9872eSLisandro Dalcin    TSSetI2Function - Set the function to compute F(t,U,U_t,U_tt) where F = 0 is the DAE to be solved.
1389efe9872eSLisandro Dalcin 
1390c3339decSBarry Smith    Logically Collective
1391efe9872eSLisandro Dalcin 
1392efe9872eSLisandro Dalcin    Input Parameters:
1393bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1394efe9872eSLisandro Dalcin .  F   - vector to hold the residual (or NULL to have it created internally)
1395efe9872eSLisandro Dalcin .  fun - the function evaluation routine
1396efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the function evaluation routine (may be NULL)
1397efe9872eSLisandro Dalcin 
1398efe9872eSLisandro Dalcin    Calling sequence of fun:
13996bc98fa9SBarry Smith $     PetscErrorCode fun(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,Vec F,ctx);
1400efe9872eSLisandro Dalcin 
1401efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1402efe9872eSLisandro Dalcin .  U    - state vector
1403efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1404efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1405efe9872eSLisandro Dalcin .  F    - function vector
1406efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine (may be NULL)
1407efe9872eSLisandro Dalcin 
1408efe9872eSLisandro Dalcin    Level: beginner
1409efe9872eSLisandro Dalcin 
1410bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`, `TSSetIFunction()`, `TSCreate()`, `TSSetRHSFunction()`
1411efe9872eSLisandro Dalcin @*/
1412d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Function(TS ts, Vec F, TSI2Function fun, void *ctx)
1413d71ae5a4SJacob Faibussowitsch {
1414efe9872eSLisandro Dalcin   DM dm;
1415efe9872eSLisandro Dalcin 
1416efe9872eSLisandro Dalcin   PetscFunctionBegin;
1417efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1418efe9872eSLisandro Dalcin   if (F) PetscValidHeaderSpecific(F, VEC_CLASSID, 2);
14199566063dSJacob Faibussowitsch   PetscCall(TSSetIFunction(ts, F, NULL, NULL));
14209566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14219566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Function(dm, fun, ctx));
1422efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1423efe9872eSLisandro Dalcin }
1424efe9872eSLisandro Dalcin 
1425efe9872eSLisandro Dalcin /*@C
1426a5b23f4aSJose E. Roman   TSGetI2Function - Returns the vector where the implicit residual is stored and the function/context to compute it.
1427efe9872eSLisandro Dalcin 
1428efe9872eSLisandro Dalcin   Not Collective
1429efe9872eSLisandro Dalcin 
1430efe9872eSLisandro Dalcin   Input Parameter:
1431bcf0153eSBarry Smith . ts - the `TS` context
1432efe9872eSLisandro Dalcin 
1433d8d19677SJose E. Roman   Output Parameters:
1434efe9872eSLisandro Dalcin + r - vector to hold residual (or NULL)
1435efe9872eSLisandro Dalcin . fun - the function to compute residual (or NULL)
1436efe9872eSLisandro Dalcin - ctx - the function context (or NULL)
1437efe9872eSLisandro Dalcin 
1438efe9872eSLisandro Dalcin   Level: advanced
1439efe9872eSLisandro Dalcin 
1440bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `SNESGetFunction()`, `TSCreate()`
1441efe9872eSLisandro Dalcin @*/
1442d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Function(TS ts, Vec *r, TSI2Function *fun, void **ctx)
1443d71ae5a4SJacob Faibussowitsch {
1444efe9872eSLisandro Dalcin   SNES snes;
1445efe9872eSLisandro Dalcin   DM   dm;
1446efe9872eSLisandro Dalcin 
1447efe9872eSLisandro Dalcin   PetscFunctionBegin;
1448efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
14499566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
14509566063dSJacob Faibussowitsch   PetscCall(SNESGetFunction(snes, r, NULL, NULL));
14519566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
14529566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, fun, ctx));
1453efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1454efe9872eSLisandro Dalcin }
1455efe9872eSLisandro Dalcin 
1456efe9872eSLisandro Dalcin /*@C
1457bc77d74cSLisandro Dalcin    TSSetI2Jacobian - Set the function to compute the matrix dF/dU + v*dF/dU_t  + a*dF/dU_tt
1458bcf0153eSBarry Smith         where F(t,U,U_t,U_tt) is the function you provided with `TSSetI2Function()`.
1459efe9872eSLisandro Dalcin 
1460c3339decSBarry Smith    Logically Collective
1461efe9872eSLisandro Dalcin 
1462efe9872eSLisandro Dalcin    Input Parameters:
1463bcf0153eSBarry Smith +  ts  - the `TS` context obtained from `TSCreate()`
1464efe9872eSLisandro Dalcin .  J   - Jacobian matrix
1465efe9872eSLisandro Dalcin .  P   - preconditioning matrix for J (may be same as J)
1466efe9872eSLisandro Dalcin .  jac - the Jacobian evaluation routine
1467efe9872eSLisandro Dalcin -  ctx - user-defined context for private data for the Jacobian evaluation routine (may be NULL)
1468efe9872eSLisandro Dalcin 
1469efe9872eSLisandro Dalcin    Calling sequence of jac:
14706bc98fa9SBarry Smith $    PetscErrorCode jac(TS ts,PetscReal t,Vec U,Vec U_t,Vec U_tt,PetscReal v,PetscReal a,Mat J,Mat P,void *ctx);
1471efe9872eSLisandro Dalcin 
1472efe9872eSLisandro Dalcin +  t    - time at step/stage being solved
1473efe9872eSLisandro Dalcin .  U    - state vector
1474efe9872eSLisandro Dalcin .  U_t  - time derivative of state vector
1475efe9872eSLisandro Dalcin .  U_tt - second time derivative of state vector
1476efe9872eSLisandro Dalcin .  v    - shift for U_t
1477efe9872eSLisandro Dalcin .  a    - shift for U_tt
1478efe9872eSLisandro Dalcin .  J    - Jacobian of G(U) = F(t,U,W+v*U,W'+a*U), equivalent to dF/dU + v*dF/dU_t  + a*dF/dU_tt
1479efe9872eSLisandro Dalcin .  P    - preconditioning matrix for J, may be same as J
1480efe9872eSLisandro Dalcin -  ctx  - [optional] user-defined context for matrix evaluation routine
1481efe9872eSLisandro Dalcin 
1482bcf0153eSBarry Smith    Level: beginner
1483bcf0153eSBarry Smith 
1484efe9872eSLisandro Dalcin    Notes:
1485bcf0153eSBarry Smith    The matrices J and P are exactly the matrices that are used by `SNES` for the nonlinear solve.
1486efe9872eSLisandro Dalcin 
1487efe9872eSLisandro Dalcin    The matrix dF/dU + v*dF/dU_t + a*dF/dU_tt you provide turns out to be
1488efe9872eSLisandro 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.
1489efe9872eSLisandro Dalcin    The time integrator internally approximates U_t by W+v*U and U_tt by W'+a*U  where the positive "shift"
1490bc77d74cSLisandro Dalcin    parameters 'v' and 'a' and vectors W, W' depend on the integration method, step size, and past states.
1491efe9872eSLisandro Dalcin 
1492bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Jacobian()`
1493efe9872eSLisandro Dalcin @*/
1494d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetI2Jacobian(TS ts, Mat J, Mat P, TSI2Jacobian jac, void *ctx)
1495d71ae5a4SJacob Faibussowitsch {
1496efe9872eSLisandro Dalcin   DM dm;
1497efe9872eSLisandro Dalcin 
1498efe9872eSLisandro Dalcin   PetscFunctionBegin;
1499efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1500efe9872eSLisandro Dalcin   if (J) PetscValidHeaderSpecific(J, MAT_CLASSID, 2);
1501efe9872eSLisandro Dalcin   if (P) PetscValidHeaderSpecific(P, MAT_CLASSID, 3);
15029566063dSJacob Faibussowitsch   PetscCall(TSSetIJacobian(ts, J, P, NULL, NULL));
15039566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15049566063dSJacob Faibussowitsch   PetscCall(DMTSSetI2Jacobian(dm, jac, ctx));
1505efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1506efe9872eSLisandro Dalcin }
1507efe9872eSLisandro Dalcin 
1508efe9872eSLisandro Dalcin /*@C
1509efe9872eSLisandro Dalcin   TSGetI2Jacobian - Returns the implicit Jacobian at the present timestep.
1510efe9872eSLisandro Dalcin 
1511bcf0153eSBarry Smith   Not Collective, but parallel objects are returned if `TS` is parallel
1512efe9872eSLisandro Dalcin 
1513efe9872eSLisandro Dalcin   Input Parameter:
1514bcf0153eSBarry Smith . ts  - The `TS` context obtained from `TSCreate()`
1515efe9872eSLisandro Dalcin 
1516efe9872eSLisandro Dalcin   Output Parameters:
1517efe9872eSLisandro Dalcin + J  - The (approximate) Jacobian of F(t,U,U_t,U_tt)
1518efe9872eSLisandro Dalcin . P - The matrix from which the preconditioner is constructed, often the same as J
1519efe9872eSLisandro Dalcin . jac - The function to compute the Jacobian matrices
1520efe9872eSLisandro Dalcin - ctx - User-defined context for Jacobian evaluation routine
1521efe9872eSLisandro Dalcin 
1522bcf0153eSBarry Smith   Level: advanced
1523bcf0153eSBarry Smith 
152495452b02SPatrick Sanan   Notes:
152595452b02SPatrick Sanan     You can pass in NULL for any return argument you do not need.
1526efe9872eSLisandro Dalcin 
1527bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`, `TSSetI2Jacobian()`, `TSGetI2Function()`, `TSCreate()`
1528efe9872eSLisandro Dalcin @*/
1529d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetI2Jacobian(TS ts, Mat *J, Mat *P, TSI2Jacobian *jac, void **ctx)
1530d71ae5a4SJacob Faibussowitsch {
1531efe9872eSLisandro Dalcin   SNES snes;
1532efe9872eSLisandro Dalcin   DM   dm;
1533efe9872eSLisandro Dalcin 
1534efe9872eSLisandro Dalcin   PetscFunctionBegin;
15359566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
15369566063dSJacob Faibussowitsch   PetscCall(SNESSetUpMatrices(snes));
15379566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(snes, J, P, NULL, NULL));
15389566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15399566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, jac, ctx));
1540efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1541efe9872eSLisandro Dalcin }
1542efe9872eSLisandro Dalcin 
1543efe9872eSLisandro Dalcin /*@
1544efe9872eSLisandro Dalcin   TSComputeI2Function - Evaluates the DAE residual written in implicit form F(t,U,U_t,U_tt) = 0
1545efe9872eSLisandro Dalcin 
1546c3339decSBarry Smith   Collective
1547efe9872eSLisandro Dalcin 
1548efe9872eSLisandro Dalcin   Input Parameters:
1549bcf0153eSBarry Smith + ts - the `TS` context
1550efe9872eSLisandro Dalcin . t - current time
1551efe9872eSLisandro Dalcin . U - state vector
1552efe9872eSLisandro Dalcin . V - time derivative of state vector (U_t)
1553efe9872eSLisandro Dalcin - A - second time derivative of state vector (U_tt)
1554efe9872eSLisandro Dalcin 
1555efe9872eSLisandro Dalcin   Output Parameter:
1556efe9872eSLisandro Dalcin . F - the residual vector
1557efe9872eSLisandro Dalcin 
1558bcf0153eSBarry Smith   Level: developer
1559bcf0153eSBarry Smith 
1560efe9872eSLisandro Dalcin   Note:
1561efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1562efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1563efe9872eSLisandro Dalcin 
1564bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Function()`, `TSGetI2Function()`
1565efe9872eSLisandro Dalcin @*/
1566d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Function(TS ts, PetscReal t, Vec U, Vec V, Vec A, Vec F)
1567d71ae5a4SJacob Faibussowitsch {
1568efe9872eSLisandro Dalcin   DM            dm;
1569efe9872eSLisandro Dalcin   TSI2Function  I2Function;
1570efe9872eSLisandro Dalcin   void         *ctx;
1571efe9872eSLisandro Dalcin   TSRHSFunction rhsfunction;
1572efe9872eSLisandro Dalcin 
1573efe9872eSLisandro Dalcin   PetscFunctionBegin;
1574efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1575efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1576efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1577efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1578efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(F, VEC_CLASSID, 6);
1579efe9872eSLisandro Dalcin 
15809566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
15819566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Function(dm, &I2Function, &ctx));
15829566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSFunction(dm, &rhsfunction, NULL));
1583efe9872eSLisandro Dalcin 
1584efe9872eSLisandro Dalcin   if (!I2Function) {
15859566063dSJacob Faibussowitsch     PetscCall(TSComputeIFunction(ts, t, U, A, F, PETSC_FALSE));
1586efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1587efe9872eSLisandro Dalcin   }
1588efe9872eSLisandro Dalcin 
15899566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_FunctionEval, ts, U, V, F));
1590efe9872eSLisandro Dalcin 
1591792fecdfSBarry Smith   PetscCallBack("TS callback implicit function", I2Function(ts, t, U, V, A, F, ctx));
1592efe9872eSLisandro Dalcin 
1593efe9872eSLisandro Dalcin   if (rhsfunction) {
1594efe9872eSLisandro Dalcin     Vec Frhs;
15959566063dSJacob Faibussowitsch     PetscCall(TSGetRHSVec_Private(ts, &Frhs));
15969566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSFunction(ts, t, U, Frhs));
15979566063dSJacob Faibussowitsch     PetscCall(VecAXPY(F, -1, Frhs));
1598efe9872eSLisandro Dalcin   }
1599efe9872eSLisandro Dalcin 
16009566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_FunctionEval, ts, U, V, F));
1601efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1602efe9872eSLisandro Dalcin }
1603efe9872eSLisandro Dalcin 
1604efe9872eSLisandro Dalcin /*@
1605efe9872eSLisandro Dalcin   TSComputeI2Jacobian - Evaluates the Jacobian of the DAE
1606efe9872eSLisandro Dalcin 
1607c3339decSBarry Smith   Collective
1608efe9872eSLisandro Dalcin 
1609efe9872eSLisandro Dalcin   Input Parameters:
1610bcf0153eSBarry Smith + ts - the `TS` context
1611efe9872eSLisandro Dalcin . t - current timestep
1612efe9872eSLisandro Dalcin . U - state vector
1613efe9872eSLisandro Dalcin . V - time derivative of state vector
1614efe9872eSLisandro Dalcin . A - second time derivative of state vector
1615efe9872eSLisandro Dalcin . shiftV - shift to apply, see note below
1616efe9872eSLisandro Dalcin - shiftA - shift to apply, see note below
1617efe9872eSLisandro Dalcin 
1618efe9872eSLisandro Dalcin   Output Parameters:
1619efe9872eSLisandro Dalcin + J - Jacobian matrix
1620efe9872eSLisandro Dalcin - P - optional preconditioning matrix
1621efe9872eSLisandro Dalcin 
1622bcf0153eSBarry Smith   Level: developer
1623bcf0153eSBarry Smith 
1624efe9872eSLisandro Dalcin   Notes:
1625efe9872eSLisandro Dalcin   If F(t,U,V,A)=0 is the DAE, the required Jacobian is
1626efe9872eSLisandro Dalcin 
1627efe9872eSLisandro Dalcin   dF/dU + shiftV*dF/dV + shiftA*dF/dA
1628efe9872eSLisandro Dalcin 
1629efe9872eSLisandro Dalcin   Most users should not need to explicitly call this routine, as it
1630efe9872eSLisandro Dalcin   is used internally within the nonlinear solvers.
1631efe9872eSLisandro Dalcin 
1632bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetI2Jacobian()`
1633efe9872eSLisandro Dalcin @*/
1634d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeI2Jacobian(TS ts, PetscReal t, Vec U, Vec V, Vec A, PetscReal shiftV, PetscReal shiftA, Mat J, Mat P)
1635d71ae5a4SJacob Faibussowitsch {
1636efe9872eSLisandro Dalcin   DM            dm;
1637efe9872eSLisandro Dalcin   TSI2Jacobian  I2Jacobian;
1638efe9872eSLisandro Dalcin   void         *ctx;
1639efe9872eSLisandro Dalcin   TSRHSJacobian rhsjacobian;
1640efe9872eSLisandro Dalcin 
1641efe9872eSLisandro Dalcin   PetscFunctionBegin;
1642efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1643efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
1644efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(V, VEC_CLASSID, 4);
1645efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(A, VEC_CLASSID, 5);
1646efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(J, MAT_CLASSID, 8);
1647efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(P, MAT_CLASSID, 9);
1648efe9872eSLisandro Dalcin 
16499566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
16509566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &I2Jacobian, &ctx));
16519566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjacobian, NULL));
1652efe9872eSLisandro Dalcin 
1653efe9872eSLisandro Dalcin   if (!I2Jacobian) {
16549566063dSJacob Faibussowitsch     PetscCall(TSComputeIJacobian(ts, t, U, A, shiftA, J, P, PETSC_FALSE));
1655efe9872eSLisandro Dalcin     PetscFunctionReturn(0);
1656efe9872eSLisandro Dalcin   }
1657efe9872eSLisandro Dalcin 
16589566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_JacobianEval, ts, U, J, P));
1659792fecdfSBarry Smith   PetscCallBack("TS callback implicit Jacobian", I2Jacobian(ts, t, U, V, A, shiftV, shiftA, J, P, ctx));
1660efe9872eSLisandro Dalcin   if (rhsjacobian) {
1661d60b7d5cSBarry Smith     Mat Jrhs, Prhs;
16629566063dSJacob Faibussowitsch     PetscCall(TSGetRHSMats_Private(ts, &Jrhs, &Prhs));
16639566063dSJacob Faibussowitsch     PetscCall(TSComputeRHSJacobian(ts, t, U, Jrhs, Prhs));
16649566063dSJacob Faibussowitsch     PetscCall(MatAXPY(J, -1, Jrhs, ts->axpy_pattern));
16659566063dSJacob Faibussowitsch     if (P != J) PetscCall(MatAXPY(P, -1, Prhs, ts->axpy_pattern));
1666efe9872eSLisandro Dalcin   }
1667efe9872eSLisandro Dalcin 
16689566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_JacobianEval, ts, U, J, P));
1669efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1670efe9872eSLisandro Dalcin }
1671efe9872eSLisandro Dalcin 
1672438f35afSJed Brown /*@C
1673438f35afSJed Brown    TSSetTransientVariable - sets function to transform from state to transient variables
1674438f35afSJed Brown 
1675438f35afSJed Brown    Logically Collective
1676438f35afSJed Brown 
16774165533cSJose E. Roman    Input Parameters:
1678438f35afSJed Brown +  ts - time stepping context on which to change the transient variable
1679a96d6ef6SBarry Smith .  tvar - a function that transforms to transient variables
1680438f35afSJed Brown -  ctx - a context for tvar
1681438f35afSJed Brown 
1682a96d6ef6SBarry Smith     Calling sequence of tvar:
1683a96d6ef6SBarry Smith $     PetscErrorCode tvar(TS ts,Vec p,Vec c,void *ctx);
1684a96d6ef6SBarry Smith 
1685a96d6ef6SBarry Smith +   ts - timestep context
16866aad120cSJose E. Roman .   p - input vector (primitive form)
1687a96d6ef6SBarry Smith .   c - output vector, transient variables (conservative form)
1688a96d6ef6SBarry Smith -   ctx - [optional] user-defined function context
1689a96d6ef6SBarry Smith 
1690438f35afSJed Brown    Level: advanced
1691438f35afSJed Brown 
1692438f35afSJed Brown    Notes:
1693bcf0153eSBarry Smith    This is typically used to transform from primitive to conservative variables so that a time integrator (e.g., `TSBDF`)
1694438f35afSJed Brown    can be conservative.  In this context, primitive variables P are used to model the state (e.g., because they lead to
1695438f35afSJed Brown    well-conditioned formulations even in limiting cases such as low-Mach or zero porosity).  The transient variable is
1696438f35afSJed Brown    C(P), specified by calling this function.  An IFunction thus receives arguments (P, Cdot) and the IJacobian must be
1697438f35afSJed Brown    evaluated via the chain rule, as in
1698438f35afSJed Brown 
1699438f35afSJed Brown      dF/dP + shift * dF/dCdot dC/dP.
1700438f35afSJed Brown 
1701bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `DMTSGetTransientVariable()`, `TSSetIFunction()`, `TSSetIJacobian()`
1702438f35afSJed Brown @*/
1703d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTransientVariable(TS ts, TSTransientVariable tvar, void *ctx)
1704d71ae5a4SJacob Faibussowitsch {
1705438f35afSJed Brown   DM dm;
1706438f35afSJed Brown 
1707438f35afSJed Brown   PetscFunctionBegin;
1708438f35afSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17099566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17109566063dSJacob Faibussowitsch   PetscCall(DMTSSetTransientVariable(dm, tvar, ctx));
1711438f35afSJed Brown   PetscFunctionReturn(0);
1712438f35afSJed Brown }
1713438f35afSJed Brown 
1714efe9872eSLisandro Dalcin /*@
1715e3c11fc1SJed Brown    TSComputeTransientVariable - transforms state (primitive) variables to transient (conservative) variables
1716e3c11fc1SJed Brown 
1717e3c11fc1SJed Brown    Logically Collective
1718e3c11fc1SJed Brown 
1719e3c11fc1SJed Brown    Input Parameters:
1720e3c11fc1SJed Brown +  ts - TS on which to compute
1721e3c11fc1SJed Brown -  U - state vector to be transformed to transient variables
1722e3c11fc1SJed Brown 
1723e3c11fc1SJed Brown    Output Parameters:
1724e3c11fc1SJed Brown .  C - transient (conservative) variable
1725e3c11fc1SJed Brown 
1726e3c11fc1SJed Brown    Level: developer
1727e3c11fc1SJed Brown 
1728bcf0153eSBarry Smith    Developer Note:
1729bcf0153eSBarry Smith    If `DMTSSetTransientVariable()` has not been called, then C is not modified in this routine and C = NULL is allowed.
1730bcf0153eSBarry Smith    This makes it safe to call without a guard.  One can use `TSHasTransientVariable()` to check if transient variables are
1731bcf0153eSBarry Smith    being used.
1732bcf0153eSBarry Smith 
1733bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeIFunction()`, `TSComputeIJacobian()`
1734e3c11fc1SJed Brown @*/
1735d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeTransientVariable(TS ts, Vec U, Vec C)
1736d71ae5a4SJacob Faibussowitsch {
1737e3c11fc1SJed Brown   DM   dm;
1738e3c11fc1SJed Brown   DMTS dmts;
1739e3c11fc1SJed Brown 
1740e3c11fc1SJed Brown   PetscFunctionBegin;
1741e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1742e3c11fc1SJed Brown   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
17439566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17449566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1745e3c11fc1SJed Brown   if (dmts->ops->transientvar) {
1746e3c11fc1SJed Brown     PetscValidHeaderSpecific(C, VEC_CLASSID, 3);
17479566063dSJacob Faibussowitsch     PetscCall((*dmts->ops->transientvar)(ts, U, C, dmts->transientvarctx));
1748e3c11fc1SJed Brown   }
1749e3c11fc1SJed Brown   PetscFunctionReturn(0);
1750e3c11fc1SJed Brown }
1751e3c11fc1SJed Brown 
1752e3c11fc1SJed Brown /*@
1753e3c11fc1SJed Brown    TSHasTransientVariable - determine whether transient variables have been set
1754e3c11fc1SJed Brown 
1755e3c11fc1SJed Brown    Logically Collective
1756e3c11fc1SJed Brown 
1757e3c11fc1SJed Brown    Input Parameters:
1758e3c11fc1SJed Brown .  ts - TS on which to compute
1759e3c11fc1SJed Brown 
1760e3c11fc1SJed Brown    Output Parameters:
1761bcf0153eSBarry Smith .  has - `PETSC_TRUE` if transient variables have been set
1762e3c11fc1SJed Brown 
1763e3c11fc1SJed Brown    Level: developer
1764e3c11fc1SJed Brown 
1765bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `DMTSSetTransientVariable()`, `TSComputeTransientVariable()`
1766e3c11fc1SJed Brown @*/
1767d71ae5a4SJacob Faibussowitsch PetscErrorCode TSHasTransientVariable(TS ts, PetscBool *has)
1768d71ae5a4SJacob Faibussowitsch {
1769e3c11fc1SJed Brown   DM   dm;
1770e3c11fc1SJed Brown   DMTS dmts;
1771e3c11fc1SJed Brown 
1772e3c11fc1SJed Brown   PetscFunctionBegin;
1773e3c11fc1SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
17749566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
17759566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(dm, &dmts));
1776e3c11fc1SJed Brown   *has = dmts->ops->transientvar ? PETSC_TRUE : PETSC_FALSE;
1777e3c11fc1SJed Brown   PetscFunctionReturn(0);
1778e3c11fc1SJed Brown }
1779e3c11fc1SJed Brown 
1780e3c11fc1SJed Brown /*@
1781efe9872eSLisandro Dalcin    TS2SetSolution - Sets the initial solution and time derivative vectors
1782bcf0153eSBarry Smith    for use by the `TS` routines handling second order equations.
1783efe9872eSLisandro Dalcin 
1784c3339decSBarry Smith    Logically Collective
1785efe9872eSLisandro Dalcin 
1786efe9872eSLisandro Dalcin    Input Parameters:
1787bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
1788efe9872eSLisandro Dalcin .  u - the solution vector
1789efe9872eSLisandro Dalcin -  v - the time derivative vector
1790efe9872eSLisandro Dalcin 
1791efe9872eSLisandro Dalcin    Level: beginner
1792efe9872eSLisandro Dalcin 
1793bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
1794efe9872eSLisandro Dalcin @*/
1795d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2SetSolution(TS ts, Vec u, Vec v)
1796d71ae5a4SJacob Faibussowitsch {
1797efe9872eSLisandro Dalcin   PetscFunctionBegin;
1798efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1799efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
1800efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(v, VEC_CLASSID, 3);
18019566063dSJacob Faibussowitsch   PetscCall(TSSetSolution(ts, u));
18029566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)v));
18039566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
1804efe9872eSLisandro Dalcin   ts->vec_dot = v;
1805efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1806efe9872eSLisandro Dalcin }
1807efe9872eSLisandro Dalcin 
1808efe9872eSLisandro Dalcin /*@
1809efe9872eSLisandro Dalcin    TS2GetSolution - Returns the solution and time derivative at the present timestep
1810efe9872eSLisandro Dalcin    for second order equations. It is valid to call this routine inside the function
1811efe9872eSLisandro Dalcin    that you are evaluating in order to move to the new timestep. This vector not
1812efe9872eSLisandro Dalcin    changed until the solution at the next timestep has been calculated.
1813efe9872eSLisandro Dalcin 
1814bcf0153eSBarry Smith    Not Collective, but Vec returned is parallel if `TS` is parallel
1815efe9872eSLisandro Dalcin 
1816efe9872eSLisandro Dalcin    Input Parameter:
1817bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
1818efe9872eSLisandro Dalcin 
1819d8d19677SJose E. Roman    Output Parameters:
1820efe9872eSLisandro Dalcin +  u - the vector containing the solution
1821efe9872eSLisandro Dalcin -  v - the vector containing the time derivative
1822efe9872eSLisandro Dalcin 
1823efe9872eSLisandro Dalcin    Level: intermediate
1824efe9872eSLisandro Dalcin 
1825bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TS2SetSolution()`, `TSGetTimeStep()`, `TSGetTime()`
1826efe9872eSLisandro Dalcin @*/
1827d71ae5a4SJacob Faibussowitsch PetscErrorCode TS2GetSolution(TS ts, Vec *u, Vec *v)
1828d71ae5a4SJacob Faibussowitsch {
1829efe9872eSLisandro Dalcin   PetscFunctionBegin;
1830efe9872eSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1831efe9872eSLisandro Dalcin   if (u) PetscValidPointer(u, 2);
1832efe9872eSLisandro Dalcin   if (v) PetscValidPointer(v, 3);
1833efe9872eSLisandro Dalcin   if (u) *u = ts->vec_sol;
1834efe9872eSLisandro Dalcin   if (v) *v = ts->vec_dot;
1835efe9872eSLisandro Dalcin   PetscFunctionReturn(0);
1836efe9872eSLisandro Dalcin }
1837efe9872eSLisandro Dalcin 
183855849f57SBarry Smith /*@C
1839bcf0153eSBarry Smith   TSLoad - Loads a `TS` that has been stored in binary  with `TSView()`.
184055849f57SBarry Smith 
1841c3339decSBarry Smith   Collective
184255849f57SBarry Smith 
184355849f57SBarry Smith   Input Parameters:
1844bcf0153eSBarry Smith + newdm - the newly loaded `TS`, this needs to have been created with `TSCreate()` or
1845bcf0153eSBarry Smith            some related function before a call to `TSLoad()`.
1846bcf0153eSBarry Smith - viewer - binary file viewer, obtained from `PetscViewerBinaryOpen()`
184755849f57SBarry Smith 
184855849f57SBarry Smith    Level: intermediate
184955849f57SBarry Smith 
1850bcf0153eSBarry Smith   Note:
1851bcf0153eSBarry Smith  The type is determined by the data in the file, any type set into the `TS` before this call is ignored.
185255849f57SBarry Smith 
1853bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerBinaryOpen()`, `TSView()`, `MatLoad()`, `VecLoad()`
185455849f57SBarry Smith @*/
1855d71ae5a4SJacob Faibussowitsch PetscErrorCode TSLoad(TS ts, PetscViewer viewer)
1856d71ae5a4SJacob Faibussowitsch {
185755849f57SBarry Smith   PetscBool isbinary;
185855849f57SBarry Smith   PetscInt  classid;
185955849f57SBarry Smith   char      type[256];
18602d53ad75SBarry Smith   DMTS      sdm;
1861ad6bc421SBarry Smith   DM        dm;
186255849f57SBarry Smith 
186355849f57SBarry Smith   PetscFunctionBegin;
1864f2c2a1b9SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
186555849f57SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
18669566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
18673c633725SBarry Smith   PetscCheck(isbinary, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Invalid viewer; open viewer with PetscViewerBinaryOpen()");
186855849f57SBarry Smith 
18699566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, &classid, 1, NULL, PETSC_INT));
18703c633725SBarry Smith   PetscCheck(classid == TS_FILE_CLASSID, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Not TS next in file");
18719566063dSJacob Faibussowitsch   PetscCall(PetscViewerBinaryRead(viewer, type, 256, NULL, PETSC_CHAR));
18729566063dSJacob Faibussowitsch   PetscCall(TSSetType(ts, type));
1873dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, load, viewer);
18749566063dSJacob Faibussowitsch   PetscCall(DMCreate(PetscObjectComm((PetscObject)ts), &dm));
18759566063dSJacob Faibussowitsch   PetscCall(DMLoad(dm, viewer));
18769566063dSJacob Faibussowitsch   PetscCall(TSSetDM(ts, dm));
18779566063dSJacob Faibussowitsch   PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
18789566063dSJacob Faibussowitsch   PetscCall(VecLoad(ts->vec_sol, viewer));
18799566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
18809566063dSJacob Faibussowitsch   PetscCall(DMTSLoad(sdm, viewer));
188155849f57SBarry Smith   PetscFunctionReturn(0);
188255849f57SBarry Smith }
188355849f57SBarry Smith 
18849804daf3SBarry Smith #include <petscdraw.h>
1885e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1886e04113cfSBarry Smith   #include <petscviewersaws.h>
1887f05ece33SBarry Smith #endif
1888fe2efc57SMark 
1889fe2efc57SMark /*@C
1890bcf0153eSBarry Smith    TSViewFromOptions - View a `TS` based on values in the options database
1891fe2efc57SMark 
1892c3339decSBarry Smith    Collective
1893fe2efc57SMark 
1894fe2efc57SMark    Input Parameters:
1895bcf0153eSBarry Smith +  ts - the `TS` context
1896bcf0153eSBarry Smith .  obj - Optional object that provides the prefix for the options database keys
1897bcf0153eSBarry Smith -  name - command line option string to be passed by user
1898fe2efc57SMark 
1899fe2efc57SMark    Level: intermediate
1900bcf0153eSBarry Smith 
1901bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSView`, `PetscObjectViewFromOptions()`, `TSCreate()`
1902fe2efc57SMark @*/
1903bcf0153eSBarry Smith PetscErrorCode TSViewFromOptions(TS ts, PetscObject obj, const char name[])
1904d71ae5a4SJacob Faibussowitsch {
1905fe2efc57SMark   PetscFunctionBegin;
1906bcf0153eSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
1907bcf0153eSBarry Smith   PetscCall(PetscObjectViewFromOptions((PetscObject)ts, obj, name));
1908fe2efc57SMark   PetscFunctionReturn(0);
1909fe2efc57SMark }
1910fe2efc57SMark 
19117e2c5f70SBarry Smith /*@C
1912bcf0153eSBarry Smith     TSView - Prints the `TS` data structure.
1913d763cef2SBarry Smith 
1914c3339decSBarry Smith     Collective
1915d763cef2SBarry Smith 
1916d763cef2SBarry Smith     Input Parameters:
1917bcf0153eSBarry Smith +   ts - the `TS` context obtained from `TSCreate()`
1918d763cef2SBarry Smith -   viewer - visualization context
1919d763cef2SBarry Smith 
1920d763cef2SBarry Smith     Options Database Key:
1921bcf0153eSBarry Smith .   -ts_view - calls `TSView()` at end of `TSStep()`
1922bcf0153eSBarry Smith 
1923bcf0153eSBarry Smith     Level: beginner
1924d763cef2SBarry Smith 
1925d763cef2SBarry Smith     Notes:
1926d763cef2SBarry Smith     The available visualization contexts include
1927bcf0153eSBarry Smith +     `PETSC_VIEWER_STDOUT_SELF` - standard output (default)
1928bcf0153eSBarry Smith -     `PETSC_VIEWER_STDOUT_WORLD` - synchronized standard
1929d763cef2SBarry Smith          output where only the first processor opens
1930d763cef2SBarry Smith          the file.  All other processors send their
1931d763cef2SBarry Smith          data to the first processor to print.
1932d763cef2SBarry Smith 
1933d763cef2SBarry Smith     The user can open an alternative visualization context with
1934bcf0153eSBarry Smith     `PetscViewerASCIIOpen()` - output to a specified file.
1935d763cef2SBarry Smith 
1936bcf0153eSBarry Smith     In the debugger you can do call `TSView`(ts,0) to display the `TS` solver. (The same holds for any PETSc object viewer).
1937595c91d4SBarry Smith 
1938bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `PetscViewer`, `PetscViewerASCIIOpen()`
1939d763cef2SBarry Smith @*/
1940d71ae5a4SJacob Faibussowitsch PetscErrorCode TSView(TS ts, PetscViewer viewer)
1941d71ae5a4SJacob Faibussowitsch {
194219fd82e9SBarry Smith   TSType    type;
19432b0a91c0SBarry Smith   PetscBool iascii, isstring, isundials, isbinary, isdraw;
19442d53ad75SBarry Smith   DMTS      sdm;
1945e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
1946536b137fSBarry Smith   PetscBool issaws;
1947f05ece33SBarry Smith #endif
1948d763cef2SBarry Smith 
1949d763cef2SBarry Smith   PetscFunctionBegin;
19500700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
19511e66621cSBarry Smith   if (!viewer) PetscCall(PetscViewerASCIIGetStdout(PetscObjectComm((PetscObject)ts), &viewer));
19520700a824SBarry Smith   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 2);
1953c9780b6fSBarry Smith   PetscCheckSameComm(ts, 1, viewer, 2);
1954fd16b177SBarry Smith 
19559566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
19569566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSTRING, &isstring));
19579566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
19589566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERDRAW, &isdraw));
1959e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
19609566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERSAWS, &issaws));
1961f05ece33SBarry Smith #endif
196232077d6dSBarry Smith   if (iascii) {
19639566063dSJacob Faibussowitsch     PetscCall(PetscObjectPrintClassNamePrefixType((PetscObject)ts, viewer));
1964efd4aadfSBarry Smith     if (ts->ops->view) {
19659566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPushTab(viewer));
1966dbbe0bcdSBarry Smith       PetscUseTypeMethod(ts, view, viewer);
19679566063dSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPopTab(viewer));
1968efd4aadfSBarry Smith     }
19691e66621cSBarry Smith     if (ts->max_steps < PETSC_MAX_INT) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum steps=%" PetscInt_FMT "\n", ts->max_steps));
19701e66621cSBarry Smith     if (ts->max_time < PETSC_MAX_REAL) PetscCall(PetscViewerASCIIPrintf(viewer, "  maximum time=%g\n", (double)ts->max_time));
19711e66621cSBarry Smith     if (ts->ifuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I function evaluations=%" PetscInt_FMT "\n", ts->ifuncs));
19721e66621cSBarry Smith     if (ts->ijacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of I Jacobian evaluations=%" PetscInt_FMT "\n", ts->ijacs));
19731e66621cSBarry Smith     if (ts->rhsfuncs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS function evaluations=%" PetscInt_FMT "\n", ts->rhsfuncs));
19741e66621cSBarry Smith     if (ts->rhsjacs) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of RHS Jacobian evaluations=%" PetscInt_FMT "\n", ts->rhsjacs));
1975efd4aadfSBarry Smith     if (ts->usessnes) {
1976efd4aadfSBarry Smith       PetscBool lin;
19771e66621cSBarry Smith       if (ts->problem_type == TS_NONLINEAR) PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of nonlinear solver iterations=%" PetscInt_FMT "\n", ts->snes_its));
197863a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of linear solver iterations=%" PetscInt_FMT "\n", ts->ksp_its));
19799566063dSJacob Faibussowitsch       PetscCall(PetscObjectTypeCompareAny((PetscObject)ts->snes, &lin, SNESKSPONLY, SNESKSPTRANSPOSEONLY, ""));
198063a3b9bcSJacob Faibussowitsch       PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of %slinear solve failures=%" PetscInt_FMT "\n", lin ? "" : "non", ts->num_snes_failures));
1981efd4aadfSBarry Smith     }
198263a3b9bcSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPrintf(viewer, "  total number of rejected steps=%" PetscInt_FMT "\n", ts->reject));
19831e66621cSBarry Smith     if (ts->vrtol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of relative error tolerances, "));
19841e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using relative error tolerance of %g, ", (double)ts->rtol));
19851e66621cSBarry Smith     if (ts->vatol) PetscCall(PetscViewerASCIIPrintf(viewer, "  using vector of absolute error tolerances\n"));
19861e66621cSBarry Smith     else PetscCall(PetscViewerASCIIPrintf(viewer, "  using absolute error tolerance of %g\n", (double)ts->atol));
19879566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
19889566063dSJacob Faibussowitsch     PetscCall(TSAdaptView(ts->adapt, viewer));
19899566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
19900f5bd95cSBarry Smith   } else if (isstring) {
19919566063dSJacob Faibussowitsch     PetscCall(TSGetType(ts, &type));
19929566063dSJacob Faibussowitsch     PetscCall(PetscViewerStringSPrintf(viewer, " TSType: %-7.7s", type));
1993dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
199455849f57SBarry Smith   } else if (isbinary) {
199555849f57SBarry Smith     PetscInt    classid = TS_FILE_CLASSID;
199655849f57SBarry Smith     MPI_Comm    comm;
199755849f57SBarry Smith     PetscMPIInt rank;
199855849f57SBarry Smith     char        type[256];
199955849f57SBarry Smith 
20009566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetComm((PetscObject)ts, &comm));
20019566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(comm, &rank));
2002dd400576SPatrick Sanan     if (rank == 0) {
20039566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, &classid, 1, PETSC_INT));
20049566063dSJacob Faibussowitsch       PetscCall(PetscStrncpy(type, ((PetscObject)ts)->type_name, 256));
20059566063dSJacob Faibussowitsch       PetscCall(PetscViewerBinaryWrite(viewer, type, 256, PETSC_CHAR));
200655849f57SBarry Smith     }
2007dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20089566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20099566063dSJacob Faibussowitsch     PetscCall(DMView(ts->dm, viewer));
20109566063dSJacob Faibussowitsch     PetscCall(VecView(ts->vec_sol, viewer));
20119566063dSJacob Faibussowitsch     PetscCall(DMGetDMTS(ts->dm, &sdm));
20129566063dSJacob Faibussowitsch     PetscCall(DMTSView(sdm, viewer));
20132b0a91c0SBarry Smith   } else if (isdraw) {
20142b0a91c0SBarry Smith     PetscDraw draw;
20152b0a91c0SBarry Smith     char      str[36];
201689fd9fafSBarry Smith     PetscReal x, y, bottom, h;
20172b0a91c0SBarry Smith 
20189566063dSJacob Faibussowitsch     PetscCall(PetscViewerDrawGetDraw(viewer, 0, &draw));
20199566063dSJacob Faibussowitsch     PetscCall(PetscDrawGetCurrentPoint(draw, &x, &y));
20209566063dSJacob Faibussowitsch     PetscCall(PetscStrcpy(str, "TS: "));
20219566063dSJacob Faibussowitsch     PetscCall(PetscStrcat(str, ((PetscObject)ts)->type_name));
20229566063dSJacob Faibussowitsch     PetscCall(PetscDrawStringBoxed(draw, x, y, PETSC_DRAW_BLACK, PETSC_DRAW_BLACK, str, NULL, &h));
202389fd9fafSBarry Smith     bottom = y - h;
20249566063dSJacob Faibussowitsch     PetscCall(PetscDrawPushCurrentPoint(draw, x, bottom));
2025dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
20269566063dSJacob Faibussowitsch     if (ts->adapt) PetscCall(TSAdaptView(ts->adapt, viewer));
20279566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESView(ts->snes, viewer));
20289566063dSJacob Faibussowitsch     PetscCall(PetscDrawPopCurrentPoint(draw));
2029e04113cfSBarry Smith #if defined(PETSC_HAVE_SAWS)
2030536b137fSBarry Smith   } else if (issaws) {
2031d45a07a7SBarry Smith     PetscMPIInt rank;
20322657e9d9SBarry Smith     const char *name;
20332657e9d9SBarry Smith 
20349566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetName((PetscObject)ts, &name));
20359566063dSJacob Faibussowitsch     PetscCallMPI(MPI_Comm_rank(PETSC_COMM_WORLD, &rank));
2036dd400576SPatrick Sanan     if (!((PetscObject)ts)->amsmem && rank == 0) {
2037d45a07a7SBarry Smith       char dir[1024];
2038d45a07a7SBarry Smith 
20399566063dSJacob Faibussowitsch       PetscCall(PetscObjectViewSAWs((PetscObject)ts, viewer));
20409566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time_step", name));
2041792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->steps, 1, SAWs_READ, SAWs_INT));
20429566063dSJacob Faibussowitsch       PetscCall(PetscSNPrintf(dir, 1024, "/PETSc/Objects/%s/time", name));
2043792fecdfSBarry Smith       PetscCallSAWs(SAWs_Register, (dir, &ts->ptime, 1, SAWs_READ, SAWs_DOUBLE));
2044d763cef2SBarry Smith     }
2045dbbe0bcdSBarry Smith     PetscTryTypeMethod(ts, view, viewer);
2046f05ece33SBarry Smith #endif
2047f05ece33SBarry Smith   }
204836a9e3b9SBarry Smith   if (ts->snes && ts->usessnes) {
20499566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPushTab(viewer));
20509566063dSJacob Faibussowitsch     PetscCall(SNESView(ts->snes, viewer));
20519566063dSJacob Faibussowitsch     PetscCall(PetscViewerASCIIPopTab(viewer));
205236a9e3b9SBarry Smith   }
20539566063dSJacob Faibussowitsch   PetscCall(DMGetDMTS(ts->dm, &sdm));
20549566063dSJacob Faibussowitsch   PetscCall(DMTSView(sdm, viewer));
2055f05ece33SBarry Smith 
20569566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPushTab(viewer));
20579566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts, TSSUNDIALS, &isundials));
20589566063dSJacob Faibussowitsch   PetscCall(PetscViewerASCIIPopTab(viewer));
2059d763cef2SBarry Smith   PetscFunctionReturn(0);
2060d763cef2SBarry Smith }
2061d763cef2SBarry Smith 
2062b07ff414SBarry Smith /*@
2063d763cef2SBarry Smith    TSSetApplicationContext - Sets an optional user-defined context for
2064d763cef2SBarry Smith    the timesteppers.
2065d763cef2SBarry Smith 
2066c3339decSBarry Smith    Logically Collective
2067d763cef2SBarry Smith 
2068d763cef2SBarry Smith    Input Parameters:
2069bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2070bcf0153eSBarry Smith -  usrP -  user context
2071daf670e6SBarry Smith 
2072d763cef2SBarry Smith    Level: intermediate
2073d763cef2SBarry Smith 
2074bcf0153eSBarry Smith    Fortran Note:
2075bcf0153eSBarry Smith     To use this from Fortran you must write a Fortran interface definition for this
2076bcf0153eSBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2077bcf0153eSBarry Smith 
2078bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetApplicationContext()`
2079d763cef2SBarry Smith @*/
2080d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetApplicationContext(TS ts, void *usrP)
2081d71ae5a4SJacob Faibussowitsch {
2082d763cef2SBarry Smith   PetscFunctionBegin;
20830700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2084d763cef2SBarry Smith   ts->user = usrP;
2085d763cef2SBarry Smith   PetscFunctionReturn(0);
2086d763cef2SBarry Smith }
2087d763cef2SBarry Smith 
2088b07ff414SBarry Smith /*@
2089d763cef2SBarry Smith     TSGetApplicationContext - Gets the user-defined context for the
2090bcf0153eSBarry Smith     timestepper that was set with `TSSetApplicationContext()`
2091d763cef2SBarry Smith 
2092d763cef2SBarry Smith     Not Collective
2093d763cef2SBarry Smith 
2094d763cef2SBarry Smith     Input Parameter:
2095bcf0153eSBarry Smith .   ts - the `TS` context obtained from `TSCreate()`
2096d763cef2SBarry Smith 
2097d763cef2SBarry Smith     Output Parameter:
2098d763cef2SBarry Smith .   usrP - user context
2099d763cef2SBarry Smith 
2100bcf0153eSBarry Smith     Level: intermediate
2101bcf0153eSBarry Smith 
2102bcf0153eSBarry Smith     Fortran Note:
210395452b02SPatrick Sanan     To use this from Fortran you must write a Fortran interface definition for this
2104daf670e6SBarry Smith     function that tells Fortran the Fortran derived data type that you are passing in as the ctx argument.
2105daf670e6SBarry Smith 
2106bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetApplicationContext()`
2107d763cef2SBarry Smith @*/
2108d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetApplicationContext(TS ts, void *usrP)
2109d71ae5a4SJacob Faibussowitsch {
2110d763cef2SBarry Smith   PetscFunctionBegin;
21110700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2112e71120c6SJed Brown   *(void **)usrP = ts->user;
2113d763cef2SBarry Smith   PetscFunctionReturn(0);
2114d763cef2SBarry Smith }
2115d763cef2SBarry Smith 
2116d763cef2SBarry Smith /*@
2117bcf0153eSBarry Smith    TSGetStepNumber - Gets the number of time steps completed.
2118d763cef2SBarry Smith 
2119d763cef2SBarry Smith    Not Collective
2120d763cef2SBarry Smith 
2121d763cef2SBarry Smith    Input Parameter:
2122bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2123d763cef2SBarry Smith 
2124d763cef2SBarry Smith    Output Parameter:
212580275a0aSLisandro Dalcin .  steps - number of steps completed so far
2126d763cef2SBarry Smith 
2127d763cef2SBarry Smith    Level: intermediate
2128d763cef2SBarry Smith 
2129bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSGetTimeStep()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`
2130d763cef2SBarry Smith @*/
2131d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepNumber(TS ts, PetscInt *steps)
2132d71ae5a4SJacob Faibussowitsch {
2133d763cef2SBarry Smith   PetscFunctionBegin;
21340700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
213580275a0aSLisandro Dalcin   PetscValidIntPointer(steps, 2);
213680275a0aSLisandro Dalcin   *steps = ts->steps;
213780275a0aSLisandro Dalcin   PetscFunctionReturn(0);
213880275a0aSLisandro Dalcin }
213980275a0aSLisandro Dalcin 
214080275a0aSLisandro Dalcin /*@
214180275a0aSLisandro Dalcin    TSSetStepNumber - Sets the number of steps completed.
214280275a0aSLisandro Dalcin 
2143c3339decSBarry Smith    Logically Collective
214480275a0aSLisandro Dalcin 
214580275a0aSLisandro Dalcin    Input Parameters:
2146bcf0153eSBarry Smith +  ts - the `TS` context
214780275a0aSLisandro Dalcin -  steps - number of steps completed so far
214880275a0aSLisandro Dalcin 
2149bcf0153eSBarry Smith    Level: developer
2150bcf0153eSBarry Smith 
2151bcf0153eSBarry Smith    Note:
2152bcf0153eSBarry Smith    For most uses of the `TS` solvers the user need not explicitly call
2153bcf0153eSBarry Smith    `TSSetStepNumber()`, as the step counter is appropriately updated in
2154bcf0153eSBarry Smith    `TSSolve()`/`TSStep()`/`TSRollBack()`. Power users may call this routine to
215580275a0aSLisandro Dalcin    reinitialize timestepping by setting the step counter to zero (and time
215680275a0aSLisandro Dalcin    to the initial time) to solve a similar problem with different initial
215780275a0aSLisandro Dalcin    conditions or parameters. Other possible use case is to continue
215880275a0aSLisandro Dalcin    timestepping from a previously interrupted run in such a way that TS
215980275a0aSLisandro Dalcin    monitors will be called with a initial nonzero step counter.
216080275a0aSLisandro Dalcin 
2161bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetStepNumber()`, `TSSetTime()`, `TSSetTimeStep()`, `TSSetSolution()`
216280275a0aSLisandro Dalcin @*/
2163d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetStepNumber(TS ts, PetscInt steps)
2164d71ae5a4SJacob Faibussowitsch {
216580275a0aSLisandro Dalcin   PetscFunctionBegin;
216680275a0aSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
216780275a0aSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, steps, 2);
21683c633725SBarry Smith   PetscCheck(steps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Step number must be non-negative");
216980275a0aSLisandro Dalcin   ts->steps = steps;
2170d763cef2SBarry Smith   PetscFunctionReturn(0);
2171d763cef2SBarry Smith }
2172d763cef2SBarry Smith 
2173d763cef2SBarry Smith /*@
2174d763cef2SBarry Smith    TSSetTimeStep - Allows one to reset the timestep at any time,
2175d763cef2SBarry Smith    useful for simple pseudo-timestepping codes.
2176d763cef2SBarry Smith 
2177c3339decSBarry Smith    Logically Collective
2178d763cef2SBarry Smith 
2179d763cef2SBarry Smith    Input Parameters:
2180bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2181d763cef2SBarry Smith -  time_step - the size of the timestep
2182d763cef2SBarry Smith 
2183d763cef2SBarry Smith    Level: intermediate
2184d763cef2SBarry Smith 
2185bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPSEUDO`, `TSGetTimeStep()`, `TSSetTime()`
2186d763cef2SBarry Smith @*/
2187d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeStep(TS ts, PetscReal time_step)
2188d71ae5a4SJacob Faibussowitsch {
2189d763cef2SBarry Smith   PetscFunctionBegin;
21900700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2191c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, time_step, 2);
2192d763cef2SBarry Smith   ts->time_step = time_step;
2193d763cef2SBarry Smith   PetscFunctionReturn(0);
2194d763cef2SBarry Smith }
2195d763cef2SBarry Smith 
2196a43b19c4SJed Brown /*@
219749354f04SShri Abhyankar    TSSetExactFinalTime - Determines whether to adapt the final time step to
219849354f04SShri Abhyankar      match the exact final time, interpolate solution to the exact final time,
2199bcf0153eSBarry Smith      or just return at the final time `TS` computed.
2200a43b19c4SJed Brown 
2201c3339decSBarry Smith   Logically Collective
2202a43b19c4SJed Brown 
2203d8d19677SJose E. Roman    Input Parameters:
2204a43b19c4SJed Brown +   ts - the time-step context
220549354f04SShri Abhyankar -   eftopt - exact final time option
2206bcf0153eSBarry Smith .vb
2207bcf0153eSBarry Smith   TS_EXACTFINALTIME_STEPOVER    - Don't do anything if final time is exceeded
2208bcf0153eSBarry Smith   TS_EXACTFINALTIME_INTERPOLATE - Interpolate back to final time
2209bcf0153eSBarry Smith   TS_EXACTFINALTIME_MATCHSTEP - Adapt final time step to match the final time
2210bcf0153eSBarry Smith .ve
2211a43b19c4SJed Brown 
2212bcf0153eSBarry Smith    Options Database Key:
2213feed9e9dSBarry Smith .   -ts_exact_final_time <stepover,interpolate,matchstep> - select the final step at runtime
2214feed9e9dSBarry Smith 
2215a43b19c4SJed Brown    Level: beginner
2216a43b19c4SJed Brown 
2217bcf0153eSBarry Smith    Note:
2218bcf0153eSBarry Smith    If you use the option `TS_EXACTFINALTIME_STEPOVER` the solution may be at a very different time
2219bcf0153eSBarry Smith    then the final time you selected.
2220bcf0153eSBarry Smith 
2221bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSGetExactFinalTime()`
2222a43b19c4SJed Brown @*/
2223d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetExactFinalTime(TS ts, TSExactFinalTimeOption eftopt)
2224d71ae5a4SJacob Faibussowitsch {
2225a43b19c4SJed Brown   PetscFunctionBegin;
2226a43b19c4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
222749354f04SShri Abhyankar   PetscValidLogicalCollectiveEnum(ts, eftopt, 2);
222849354f04SShri Abhyankar   ts->exact_final_time = eftopt;
2229a43b19c4SJed Brown   PetscFunctionReturn(0);
2230a43b19c4SJed Brown }
2231a43b19c4SJed Brown 
2232d763cef2SBarry Smith /*@
2233bcf0153eSBarry Smith    TSGetExactFinalTime - Gets the exact final time option set with `TSSetExactFinalTime()`
2234f6953c82SLisandro Dalcin 
2235f6953c82SLisandro Dalcin    Not Collective
2236f6953c82SLisandro Dalcin 
2237f6953c82SLisandro Dalcin    Input Parameter:
2238bcf0153eSBarry Smith .  ts - the `TS` context
2239f6953c82SLisandro Dalcin 
2240f6953c82SLisandro Dalcin    Output Parameter:
2241f6953c82SLisandro Dalcin .  eftopt - exact final time option
2242f6953c82SLisandro Dalcin 
2243f6953c82SLisandro Dalcin    Level: beginner
2244f6953c82SLisandro Dalcin 
2245bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSExactFinalTimeOption`, `TSSetExactFinalTime()`
2246f6953c82SLisandro Dalcin @*/
2247d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetExactFinalTime(TS ts, TSExactFinalTimeOption *eftopt)
2248d71ae5a4SJacob Faibussowitsch {
2249f6953c82SLisandro Dalcin   PetscFunctionBegin;
2250f6953c82SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2251f6953c82SLisandro Dalcin   PetscValidPointer(eftopt, 2);
2252f6953c82SLisandro Dalcin   *eftopt = ts->exact_final_time;
2253f6953c82SLisandro Dalcin   PetscFunctionReturn(0);
2254f6953c82SLisandro Dalcin }
2255f6953c82SLisandro Dalcin 
2256f6953c82SLisandro Dalcin /*@
2257d763cef2SBarry Smith    TSGetTimeStep - Gets the current timestep size.
2258d763cef2SBarry Smith 
2259d763cef2SBarry Smith    Not Collective
2260d763cef2SBarry Smith 
2261d763cef2SBarry Smith    Input Parameter:
2262bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2263d763cef2SBarry Smith 
2264d763cef2SBarry Smith    Output Parameter:
2265d763cef2SBarry Smith .  dt - the current timestep size
2266d763cef2SBarry Smith 
2267d763cef2SBarry Smith    Level: intermediate
2268d763cef2SBarry Smith 
2269bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeStep()`, `TSGetTime()`
2270d763cef2SBarry Smith @*/
2271d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStep(TS ts, PetscReal *dt)
2272d71ae5a4SJacob Faibussowitsch {
2273d763cef2SBarry Smith   PetscFunctionBegin;
22740700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2275f7cf8827SBarry Smith   PetscValidRealPointer(dt, 2);
2276d763cef2SBarry Smith   *dt = ts->time_step;
2277d763cef2SBarry Smith   PetscFunctionReturn(0);
2278d763cef2SBarry Smith }
2279d763cef2SBarry Smith 
2280d8e5e3e6SSatish Balay /*@
2281d763cef2SBarry Smith    TSGetSolution - Returns the solution at the present timestep. It
2282d763cef2SBarry Smith    is valid to call this routine inside the function that you are evaluating
2283d763cef2SBarry Smith    in order to move to the new timestep. This vector not changed until
2284d763cef2SBarry Smith    the solution at the next timestep has been calculated.
2285d763cef2SBarry Smith 
2286bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
2287d763cef2SBarry Smith 
2288d763cef2SBarry Smith    Input Parameter:
2289bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2290d763cef2SBarry Smith 
2291d763cef2SBarry Smith    Output Parameter:
2292d763cef2SBarry Smith .  v - the vector containing the solution
2293d763cef2SBarry Smith 
2294d763cef2SBarry Smith    Level: intermediate
2295d763cef2SBarry Smith 
2296bcf0153eSBarry Smith    Note:
2297bcf0153eSBarry Smith    If you used `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`); this does not return the solution at the requested
2298bcf0153eSBarry Smith    final time. It returns the solution at the next timestep.
2299d763cef2SBarry Smith 
2300bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetTime()`, `TSGetSolveTime()`, `TSGetSolutionComponents()`, `TSSetSolutionFunction()`
2301d763cef2SBarry Smith @*/
2302d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolution(TS ts, Vec *v)
2303d71ae5a4SJacob Faibussowitsch {
2304d763cef2SBarry Smith   PetscFunctionBegin;
23050700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
23064482741eSBarry Smith   PetscValidPointer(v, 2);
23078737fe31SLisandro Dalcin   *v = ts->vec_sol;
2308d763cef2SBarry Smith   PetscFunctionReturn(0);
2309d763cef2SBarry Smith }
2310d763cef2SBarry Smith 
231103fe5f5eSDebojyoti Ghosh /*@
2312b2bf4f3aSDebojyoti Ghosh    TSGetSolutionComponents - Returns any solution components at the present
231303fe5f5eSDebojyoti Ghosh    timestep, if available for the time integration method being used.
2314b2bf4f3aSDebojyoti Ghosh    Solution components are quantities that share the same size and
231503fe5f5eSDebojyoti Ghosh    structure as the solution vector.
231603fe5f5eSDebojyoti Ghosh 
2317bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
231803fe5f5eSDebojyoti Ghosh 
231903fe5f5eSDebojyoti Ghosh    Parameters :
2320bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2321*f3fa974cSJacob Faibussowitsch .  n - If v is NULL, then the number of solution components is
2322b2bf4f3aSDebojyoti Ghosh        returned through n, else the n-th solution component is
232303fe5f5eSDebojyoti Ghosh        returned in v.
2324a2b725a8SWilliam Gropp -  v - the vector containing the n-th solution component
2325*f3fa974cSJacob Faibussowitsch        (may be NULL to use this function to find out
2326b2bf4f3aSDebojyoti Ghosh         the number of solutions components).
232703fe5f5eSDebojyoti Ghosh 
23284cdd57e5SDebojyoti Ghosh    Level: advanced
232903fe5f5eSDebojyoti Ghosh 
2330bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
233103fe5f5eSDebojyoti Ghosh @*/
2332d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolutionComponents(TS ts, PetscInt *n, Vec *v)
2333d71ae5a4SJacob Faibussowitsch {
233403fe5f5eSDebojyoti Ghosh   PetscFunctionBegin;
233503fe5f5eSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2336b2bf4f3aSDebojyoti Ghosh   if (!ts->ops->getsolutioncomponents) *n = 0;
2337dbbe0bcdSBarry Smith   else PetscUseTypeMethod(ts, getsolutioncomponents, n, v);
233803fe5f5eSDebojyoti Ghosh   PetscFunctionReturn(0);
233903fe5f5eSDebojyoti Ghosh }
234003fe5f5eSDebojyoti Ghosh 
23414cdd57e5SDebojyoti Ghosh /*@
23424cdd57e5SDebojyoti Ghosh    TSGetAuxSolution - Returns an auxiliary solution at the present
23434cdd57e5SDebojyoti Ghosh    timestep, if available for the time integration method being used.
23444cdd57e5SDebojyoti Ghosh 
2345bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23464cdd57e5SDebojyoti Ghosh 
23474cdd57e5SDebojyoti Ghosh    Parameters :
2348bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2349a2b725a8SWilliam Gropp -  v - the vector containing the auxiliary solution
23504cdd57e5SDebojyoti Ghosh 
23514cdd57e5SDebojyoti Ghosh    Level: intermediate
23524cdd57e5SDebojyoti Ghosh 
2353bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSolution()`
23544cdd57e5SDebojyoti Ghosh @*/
2355d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAuxSolution(TS ts, Vec *v)
2356d71ae5a4SJacob Faibussowitsch {
23574cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23584cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2359dbbe0bcdSBarry Smith   if (ts->ops->getauxsolution) PetscUseTypeMethod(ts, getauxsolution, v);
23601e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23614cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
23624cdd57e5SDebojyoti Ghosh }
23634cdd57e5SDebojyoti Ghosh 
23644cdd57e5SDebojyoti Ghosh /*@
23654cdd57e5SDebojyoti Ghosh    TSGetTimeError - Returns the estimated error vector, if the chosen
2366bcf0153eSBarry Smith    `TSType` has an error estimation functionality and `TSSetTimeError()` was called
23674cdd57e5SDebojyoti Ghosh 
2368bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
23699657682dSDebojyoti Ghosh 
23704cdd57e5SDebojyoti Ghosh    Parameters :
2371bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2372657c1e31SEmil Constantinescu .  n - current estimate (n=0) or previous one (n=-1)
2373a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
23744cdd57e5SDebojyoti Ghosh 
23754cdd57e5SDebojyoti Ghosh    Level: intermediate
23764cdd57e5SDebojyoti Ghosh 
2377bcf0153eSBarry Smith    Note:
2378bcf0153eSBarry Smith    MUST call after `TSSetUp()`
23794cdd57e5SDebojyoti Ghosh 
2380bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetSolution()`, `TSSetTimeError()`
23814cdd57e5SDebojyoti Ghosh @*/
2382d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeError(TS ts, PetscInt n, Vec *v)
2383d71ae5a4SJacob Faibussowitsch {
23844cdd57e5SDebojyoti Ghosh   PetscFunctionBegin;
23854cdd57e5SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2386dbbe0bcdSBarry Smith   if (ts->ops->gettimeerror) PetscUseTypeMethod(ts, gettimeerror, n, v);
23871e66621cSBarry Smith   else PetscCall(VecZeroEntries(*v));
23884cdd57e5SDebojyoti Ghosh   PetscFunctionReturn(0);
23894cdd57e5SDebojyoti Ghosh }
23904cdd57e5SDebojyoti Ghosh 
239157df6a1bSDebojyoti Ghosh /*@
239257df6a1bSDebojyoti Ghosh    TSSetTimeError - Sets the estimated error vector, if the chosen
2393bcf0153eSBarry Smith    `TSType` has an error estimation functionality. This can be used
239457df6a1bSDebojyoti Ghosh    to restart such a time integrator with a given error vector.
239557df6a1bSDebojyoti Ghosh 
2396bcf0153eSBarry Smith    Not Collective, but v returned is parallel if ts is parallel
239757df6a1bSDebojyoti Ghosh 
239857df6a1bSDebojyoti Ghosh    Parameters :
2399bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()` (input parameter).
2400a2b725a8SWilliam Gropp -  v - the vector containing the error (same size as the solution).
240157df6a1bSDebojyoti Ghosh 
240257df6a1bSDebojyoti Ghosh    Level: intermediate
240357df6a1bSDebojyoti Ghosh 
2404bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolution()`, `TSGetTimeError)`
240557df6a1bSDebojyoti Ghosh @*/
2406d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeError(TS ts, Vec v)
2407d71ae5a4SJacob Faibussowitsch {
240857df6a1bSDebojyoti Ghosh   PetscFunctionBegin;
240957df6a1bSDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24103c633725SBarry Smith   PetscCheck(ts->setupcalled, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetUp() first");
2411dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, settimeerror, v);
241257df6a1bSDebojyoti Ghosh   PetscFunctionReturn(0);
241357df6a1bSDebojyoti Ghosh }
241457df6a1bSDebojyoti Ghosh 
2415bdad233fSMatthew Knepley /* ----- Routines to initialize and destroy a timestepper ---- */
2416d8e5e3e6SSatish Balay /*@
2417bdad233fSMatthew Knepley   TSSetProblemType - Sets the type of problem to be solved.
2418d763cef2SBarry Smith 
2419bdad233fSMatthew Knepley   Not collective
2420d763cef2SBarry Smith 
2421bdad233fSMatthew Knepley   Input Parameters:
2422bcf0153eSBarry Smith + ts   - The `TS`
2423bcf0153eSBarry Smith - type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2424d763cef2SBarry Smith .vb
24250910c330SBarry Smith          U_t - A U = 0      (linear)
24260910c330SBarry Smith          U_t - A(t) U = 0   (linear)
24270910c330SBarry Smith          F(t,U,U_t) = 0     (nonlinear)
2428d763cef2SBarry Smith .ve
2429d763cef2SBarry Smith 
2430d763cef2SBarry Smith    Level: beginner
2431d763cef2SBarry Smith 
2432bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2433d763cef2SBarry Smith @*/
2434d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetProblemType(TS ts, TSProblemType type)
2435d71ae5a4SJacob Faibussowitsch {
2436d763cef2SBarry Smith   PetscFunctionBegin;
24370700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2438bdad233fSMatthew Knepley   ts->problem_type = type;
24399e2a6581SJed Brown   if (type == TS_LINEAR) {
24409e2a6581SJed Brown     SNES snes;
24419566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
24429566063dSJacob Faibussowitsch     PetscCall(SNESSetType(snes, SNESKSPONLY));
24439e2a6581SJed Brown   }
2444d763cef2SBarry Smith   PetscFunctionReturn(0);
2445d763cef2SBarry Smith }
2446d763cef2SBarry Smith 
2447bdad233fSMatthew Knepley /*@C
2448bdad233fSMatthew Knepley   TSGetProblemType - Gets the type of problem to be solved.
2449bdad233fSMatthew Knepley 
2450bdad233fSMatthew Knepley   Not collective
2451bdad233fSMatthew Knepley 
2452bdad233fSMatthew Knepley   Input Parameter:
2453bcf0153eSBarry Smith . ts   - The `TS`
2454bdad233fSMatthew Knepley 
2455bdad233fSMatthew Knepley   Output Parameter:
2456bcf0153eSBarry Smith . type - One of `TS_LINEAR`, `TS_NONLINEAR` where these types refer to problems of the forms
2457bdad233fSMatthew Knepley .vb
2458089b2837SJed Brown          M U_t = A U
2459089b2837SJed Brown          M(t) U_t = A(t) U
2460b5abc632SBarry Smith          F(t,U,U_t)
2461bdad233fSMatthew Knepley .ve
2462bdad233fSMatthew Knepley 
2463bdad233fSMatthew Knepley    Level: beginner
2464bdad233fSMatthew Knepley 
2465bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetUp()`, `TSProblemType`, `TS`
2466bdad233fSMatthew Knepley @*/
2467d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetProblemType(TS ts, TSProblemType *type)
2468d71ae5a4SJacob Faibussowitsch {
2469bdad233fSMatthew Knepley   PetscFunctionBegin;
24700700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
24714482741eSBarry Smith   PetscValidIntPointer(type, 2);
2472bdad233fSMatthew Knepley   *type = ts->problem_type;
2473bdad233fSMatthew Knepley   PetscFunctionReturn(0);
2474bdad233fSMatthew Knepley }
2475d763cef2SBarry Smith 
2476303a5415SBarry Smith /*
2477303a5415SBarry 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()
2478303a5415SBarry Smith */
2479d71ae5a4SJacob Faibussowitsch static PetscErrorCode TSSetExactFinalTimeDefault(TS ts)
2480d71ae5a4SJacob Faibussowitsch {
2481303a5415SBarry Smith   PetscBool isnone;
2482303a5415SBarry Smith 
2483303a5415SBarry Smith   PetscFunctionBegin;
24849566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
24859566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
2486303a5415SBarry Smith 
24879566063dSJacob Faibussowitsch   PetscCall(PetscObjectTypeCompare((PetscObject)ts->adapt, TSADAPTNONE, &isnone));
24881e66621cSBarry Smith   if (!isnone && ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_MATCHSTEP;
24891e66621cSBarry Smith   else if (ts->exact_final_time == TS_EXACTFINALTIME_UNSPECIFIED) ts->exact_final_time = TS_EXACTFINALTIME_INTERPOLATE;
2490303a5415SBarry Smith   PetscFunctionReturn(0);
2491303a5415SBarry Smith }
2492303a5415SBarry Smith 
2493d763cef2SBarry Smith /*@
2494303a5415SBarry Smith    TSSetUp - Sets up the internal data structures for the later use of a timestepper.
2495d763cef2SBarry Smith 
2496c3339decSBarry Smith    Collective
2497d763cef2SBarry Smith 
2498d763cef2SBarry Smith    Input Parameter:
2499bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2500d763cef2SBarry Smith 
2501d763cef2SBarry Smith    Level: advanced
2502d763cef2SBarry Smith 
2503bcf0153eSBarry Smith    Note:
2504bcf0153eSBarry Smith    For basic use of the `TS` solvers the user need not explicitly call
2505bcf0153eSBarry Smith    `TSSetUp()`, since these actions will automatically occur during
2506bcf0153eSBarry Smith    the call to `TSStep()` or `TSSolve()`.  However, if one wishes to control this
2507bcf0153eSBarry Smith    phase separately, `TSSetUp()` should be called after `TSCreate()`
2508bcf0153eSBarry Smith    and optional routines of the form TSSetXXX(), but before `TSStep()` and `TSSolve()`.
2509bcf0153eSBarry Smith 
2510bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSCreate()`, `TS`, `TSStep()`, `TSDestroy()`, `TSSolve()`
2511d763cef2SBarry Smith @*/
2512d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUp(TS ts)
2513d71ae5a4SJacob Faibussowitsch {
25146c6b9e74SPeter Brune   DM dm;
25156c6b9e74SPeter Brune   PetscErrorCode (*func)(SNES, Vec, Vec, void *);
2516d1e9a80fSBarry Smith   PetscErrorCode (*jac)(SNES, Vec, Mat, Mat, void *);
2517cd11d68dSLisandro Dalcin   TSIFunction   ifun;
25186c6b9e74SPeter Brune   TSIJacobian   ijac;
2519efe9872eSLisandro Dalcin   TSI2Jacobian  i2jac;
25206c6b9e74SPeter Brune   TSRHSJacobian rhsjac;
2521d763cef2SBarry Smith 
2522d763cef2SBarry Smith   PetscFunctionBegin;
25230700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2524277b19d0SLisandro Dalcin   if (ts->setupcalled) PetscFunctionReturn(0);
2525277b19d0SLisandro Dalcin 
25267adad957SLisandro Dalcin   if (!((PetscObject)ts)->type_name) {
25279566063dSJacob Faibussowitsch     PetscCall(TSGetIFunction(ts, NULL, &ifun, NULL));
25289566063dSJacob Faibussowitsch     PetscCall(TSSetType(ts, ifun ? TSBEULER : TSEULER));
2529d763cef2SBarry Smith   }
2530277b19d0SLisandro Dalcin 
25311a638600SStefano Zampini   if (!ts->vec_sol) {
25321e66621cSBarry Smith     PetscCheck(ts->dm, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONGSTATE, "Must call TSSetSolution() first");
25339566063dSJacob Faibussowitsch     PetscCall(DMCreateGlobalVector(ts->dm, &ts->vec_sol));
25341a638600SStefano Zampini   }
2535277b19d0SLisandro Dalcin 
25364a658b32SHong Zhang   if (ts->tspan) {
25371e66621cSBarry Smith     if (!ts->tspan->vecs_sol) PetscCall(VecDuplicateVecs(ts->vec_sol, ts->tspan->num_span_times, &ts->tspan->vecs_sol));
25384a658b32SHong Zhang   }
2539298bade4SHong Zhang   if (!ts->Jacp && ts->Jacprhs) { /* IJacobianP shares the same matrix with RHSJacobianP if only RHSJacobianP is provided */
25409566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)ts->Jacprhs));
2541298bade4SHong Zhang     ts->Jacp = ts->Jacprhs;
2542298bade4SHong Zhang   }
2543298bade4SHong Zhang 
2544cd4cee2dSHong Zhang   if (ts->quadraturets) {
25459566063dSJacob Faibussowitsch     PetscCall(TSSetUp(ts->quadraturets));
25469566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
25479566063dSJacob Faibussowitsch     PetscCall(VecDuplicate(ts->quadraturets->vec_sol, &ts->vec_costintegrand));
2548cd4cee2dSHong Zhang   }
2549cd4cee2dSHong Zhang 
25509566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, NULL, NULL, &rhsjac, NULL));
2551f23ba4b3SHong Zhang   if (rhsjac == TSComputeRHSJacobianConstant) {
2552e1244c69SJed Brown     Mat  Amat, Pmat;
2553e1244c69SJed Brown     SNES snes;
25549566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
25559566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, &Amat, &Pmat, NULL, NULL));
2556e1244c69SJed Brown     /* Matching matrices implies that an IJacobian is NOT set, because if it had been set, the IJacobian's matrix would
2557e1244c69SJed Brown      * have displaced the RHS matrix */
2558971015bcSStefano Zampini     if (Amat && Amat == ts->Arhs) {
2559abc0d4abSBarry 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 */
25609566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Arhs, MAT_COPY_VALUES, &Amat));
25619566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, Amat, NULL, NULL, NULL));
25629566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Amat));
2563e1244c69SJed Brown     }
2564971015bcSStefano Zampini     if (Pmat && Pmat == ts->Brhs) {
25659566063dSJacob Faibussowitsch       PetscCall(MatDuplicate(ts->Brhs, MAT_COPY_VALUES, &Pmat));
25669566063dSJacob Faibussowitsch       PetscCall(SNESSetJacobian(snes, NULL, Pmat, NULL, NULL));
25679566063dSJacob Faibussowitsch       PetscCall(MatDestroy(&Pmat));
2568e1244c69SJed Brown     }
2569e1244c69SJed Brown   }
25702ffb9264SLisandro Dalcin 
25719566063dSJacob Faibussowitsch   PetscCall(TSGetAdapt(ts, &ts->adapt));
25729566063dSJacob Faibussowitsch   PetscCall(TSAdaptSetDefaultType(ts->adapt, ts->default_adapt_type));
25732ffb9264SLisandro Dalcin 
2574dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, setup);
2575277b19d0SLisandro Dalcin 
25769566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
25772ffb9264SLisandro Dalcin 
2578a6772fa2SLisandro Dalcin   /* In the case where we've set a DMTSFunction or what have you, we need the default SNESFunction
25796c6b9e74SPeter Brune      to be set right but can't do it elsewhere due to the overreliance on ctx=ts.
25806c6b9e74SPeter Brune    */
25819566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
25829566063dSJacob Faibussowitsch   PetscCall(DMSNESGetFunction(dm, &func, NULL));
25831e66621cSBarry Smith   if (!func) PetscCall(DMSNESSetFunction(dm, SNESTSFormFunction, ts));
25841e66621cSBarry Smith 
2585a6772fa2SLisandro 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.
25866c6b9e74SPeter Brune      Otherwise, the SNES will use coloring internally to form the Jacobian.
25876c6b9e74SPeter Brune    */
25889566063dSJacob Faibussowitsch   PetscCall(DMSNESGetJacobian(dm, &jac, NULL));
25899566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, &ijac, NULL));
25909566063dSJacob Faibussowitsch   PetscCall(DMTSGetI2Jacobian(dm, &i2jac, NULL));
25919566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, &rhsjac, NULL));
25921e66621cSBarry Smith   if (!jac && (ijac || i2jac || rhsjac)) PetscCall(DMSNESSetJacobian(dm, SNESTSFormJacobian, ts));
2593c0517034SDebojyoti Ghosh 
2594c0517034SDebojyoti Ghosh   /* if time integration scheme has a starting method, call it */
2595dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, startingmethod);
2596c0517034SDebojyoti Ghosh 
2597277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_TRUE;
2598277b19d0SLisandro Dalcin   PetscFunctionReturn(0);
2599277b19d0SLisandro Dalcin }
2600277b19d0SLisandro Dalcin 
2601f6a906c0SBarry Smith /*@
2602bcf0153eSBarry Smith    TSReset - Resets a `TS` context and removes any allocated `Vec`s and `Mat`s.
2603277b19d0SLisandro Dalcin 
2604c3339decSBarry Smith    Collective
2605277b19d0SLisandro Dalcin 
2606277b19d0SLisandro Dalcin    Input Parameter:
2607bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2608277b19d0SLisandro Dalcin 
2609277b19d0SLisandro Dalcin    Level: beginner
2610277b19d0SLisandro Dalcin 
2611bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetup()`, `TSDestroy()`
2612277b19d0SLisandro Dalcin @*/
2613d71ae5a4SJacob Faibussowitsch PetscErrorCode TSReset(TS ts)
2614d71ae5a4SJacob Faibussowitsch {
26151d06f6b3SHong Zhang   TS_RHSSplitLink ilink = ts->tsrhssplit, next;
2616277b19d0SLisandro Dalcin 
2617277b19d0SLisandro Dalcin   PetscFunctionBegin;
2618277b19d0SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2619b18ea86cSHong Zhang 
2620dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, reset);
26219566063dSJacob Faibussowitsch   if (ts->snes) PetscCall(SNESReset(ts->snes));
26229566063dSJacob Faibussowitsch   if (ts->adapt) PetscCall(TSAdaptReset(ts->adapt));
2623bbd56ea5SKarl Rupp 
26249566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Arhs));
26259566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Brhs));
26269566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->Frhs));
26279566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
26289566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_dot));
26299566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vatol));
26309566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vrtol));
26319566063dSJacob Faibussowitsch   PetscCall(VecDestroyVecs(ts->nwork, &ts->work));
2632bbd56ea5SKarl Rupp 
26339566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacprhs));
26349566063dSJacob Faibussowitsch   PetscCall(MatDestroy(&ts->Jacp));
26351baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardReset(ts));
2636cd4cee2dSHong Zhang   if (ts->quadraturets) {
26379566063dSJacob Faibussowitsch     PetscCall(TSReset(ts->quadraturets));
26389566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vec_costintegrand));
2639cd4cee2dSHong Zhang   }
26401d06f6b3SHong Zhang   while (ilink) {
26411d06f6b3SHong Zhang     next = ilink->next;
26429566063dSJacob Faibussowitsch     PetscCall(TSDestroy(&ilink->ts));
26439566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink->splitname));
26449566063dSJacob Faibussowitsch     PetscCall(ISDestroy(&ilink->is));
26459566063dSJacob Faibussowitsch     PetscCall(PetscFree(ilink));
26461d06f6b3SHong Zhang     ilink = next;
264787f4e208SHong Zhang   }
26486bf673ebSJoe Pusztay   ts->tsrhssplit     = NULL;
2649545aaa6fSHong Zhang   ts->num_rhs_splits = 0;
26504a658b32SHong Zhang   if (ts->tspan) {
26514a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
26524a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
26534a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan));
26544a658b32SHong Zhang   }
2655277b19d0SLisandro Dalcin   ts->setupcalled = PETSC_FALSE;
2656d763cef2SBarry Smith   PetscFunctionReturn(0);
2657d763cef2SBarry Smith }
2658d763cef2SBarry Smith 
26591fb7b255SJunchao Zhang /*@C
2660d763cef2SBarry Smith    TSDestroy - Destroys the timestepper context that was created
2661bcf0153eSBarry Smith    with `TSCreate()`.
2662d763cef2SBarry Smith 
2663c3339decSBarry Smith    Collective
2664d763cef2SBarry Smith 
2665d763cef2SBarry Smith    Input Parameter:
2666bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2667d763cef2SBarry Smith 
2668d763cef2SBarry Smith    Level: beginner
2669d763cef2SBarry Smith 
2670bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2671d763cef2SBarry Smith @*/
2672d71ae5a4SJacob Faibussowitsch PetscErrorCode TSDestroy(TS *ts)
2673d71ae5a4SJacob Faibussowitsch {
2674d763cef2SBarry Smith   PetscFunctionBegin;
26756bf464f9SBarry Smith   if (!*ts) PetscFunctionReturn(0);
2676ecf68647SHong Zhang   PetscValidHeaderSpecific(*ts, TS_CLASSID, 1);
26779371c9d4SSatish Balay   if (--((PetscObject)(*ts))->refct > 0) {
26789371c9d4SSatish Balay     *ts = NULL;
26799371c9d4SSatish Balay     PetscFunctionReturn(0);
26809371c9d4SSatish Balay   }
2681d763cef2SBarry Smith 
26829566063dSJacob Faibussowitsch   PetscCall(TSReset(*ts));
26839566063dSJacob Faibussowitsch   PetscCall(TSAdjointReset(*ts));
26841e66621cSBarry Smith   if ((*ts)->forward_solve) PetscCall(TSForwardReset(*ts));
26851e66621cSBarry Smith 
2686e04113cfSBarry Smith   /* if memory was published with SAWs then destroy it */
26879566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsViewOff((PetscObject)*ts));
2688dbbe0bcdSBarry Smith   PetscTryTypeMethod((*ts), destroy);
26896d4c513bSLisandro Dalcin 
26909566063dSJacob Faibussowitsch   PetscCall(TSTrajectoryDestroy(&(*ts)->trajectory));
2691bc952696SBarry Smith 
26929566063dSJacob Faibussowitsch   PetscCall(TSAdaptDestroy(&(*ts)->adapt));
26939566063dSJacob Faibussowitsch   PetscCall(TSEventDestroy(&(*ts)->event));
26946427ac75SLisandro Dalcin 
26959566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&(*ts)->snes));
26969566063dSJacob Faibussowitsch   PetscCall(DMDestroy(&(*ts)->dm));
26979566063dSJacob Faibussowitsch   PetscCall(TSMonitorCancel((*ts)));
26989566063dSJacob Faibussowitsch   PetscCall(TSAdjointMonitorCancel((*ts)));
26996d4c513bSLisandro Dalcin 
27009566063dSJacob Faibussowitsch   PetscCall(TSDestroy(&(*ts)->quadraturets));
27019566063dSJacob Faibussowitsch   PetscCall(PetscHeaderDestroy(ts));
2702d763cef2SBarry Smith   PetscFunctionReturn(0);
2703d763cef2SBarry Smith }
2704d763cef2SBarry Smith 
2705d8e5e3e6SSatish Balay /*@
2706bcf0153eSBarry Smith    TSGetSNES - Returns the `SNES` (nonlinear solver) associated with
2707bcf0153eSBarry Smith    a `TS` (timestepper) context. Valid only for nonlinear problems.
2708d763cef2SBarry Smith 
2709bcf0153eSBarry Smith    Not Collective, but snes is parallel if ts is parallel
2710d763cef2SBarry Smith 
2711d763cef2SBarry Smith    Input Parameter:
2712bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2713d763cef2SBarry Smith 
2714d763cef2SBarry Smith    Output Parameter:
2715d763cef2SBarry Smith .  snes - the nonlinear solver context
2716d763cef2SBarry Smith 
2717d763cef2SBarry Smith    Level: beginner
2718d763cef2SBarry Smith 
2719bcf0153eSBarry Smith    Notes:
2720bcf0153eSBarry Smith    The user can then directly manipulate the `SNES` context to set various
2721bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2722bcf0153eSBarry Smith    `KSP`, and `PC` contexts as well.
2723bcf0153eSBarry Smith 
2724bcf0153eSBarry Smith    `TSGetSNES()` does not work for integrators that do not use `SNES`; in
2725bcf0153eSBarry Smith    this case `TSGetSNES()` returns NULL in snes.
2726bcf0153eSBarry Smith 
2727bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`
2728d763cef2SBarry Smith @*/
2729d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNES(TS ts, SNES *snes)
2730d71ae5a4SJacob Faibussowitsch {
2731d763cef2SBarry Smith   PetscFunctionBegin;
27320700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
27334482741eSBarry Smith   PetscValidPointer(snes, 2);
2734d372ba47SLisandro Dalcin   if (!ts->snes) {
27359566063dSJacob Faibussowitsch     PetscCall(SNESCreate(PetscObjectComm((PetscObject)ts), &ts->snes));
27369566063dSJacob Faibussowitsch     PetscCall(PetscObjectSetOptions((PetscObject)ts->snes, ((PetscObject)ts)->options));
27379566063dSJacob Faibussowitsch     PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27389566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->snes, (PetscObject)ts, 1));
27399566063dSJacob Faibussowitsch     if (ts->dm) PetscCall(SNESSetDM(ts->snes, ts->dm));
27401e66621cSBarry Smith     if (ts->problem_type == TS_LINEAR) PetscCall(SNESSetType(ts->snes, SNESKSPONLY));
2741d372ba47SLisandro Dalcin   }
2742d763cef2SBarry Smith   *snes = ts->snes;
2743d763cef2SBarry Smith   PetscFunctionReturn(0);
2744d763cef2SBarry Smith }
2745d763cef2SBarry Smith 
2746deb2cd25SJed Brown /*@
2747bcf0153eSBarry Smith    TSSetSNES - Set the `SNES` (nonlinear solver) to be used by the timestepping context
2748deb2cd25SJed Brown 
2749deb2cd25SJed Brown    Collective
2750deb2cd25SJed Brown 
2751d8d19677SJose E. Roman    Input Parameters:
2752bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2753deb2cd25SJed Brown -  snes - the nonlinear solver context
2754deb2cd25SJed Brown 
2755deb2cd25SJed Brown    Level: developer
2756deb2cd25SJed Brown 
2757bcf0153eSBarry Smith    Note:
2758bcf0153eSBarry Smith    Most users should have the `TS` created by calling `TSGetSNES()`
2759bcf0153eSBarry Smith 
2760bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2761deb2cd25SJed Brown @*/
2762d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSNES(TS ts, SNES snes)
2763d71ae5a4SJacob Faibussowitsch {
2764d1e9a80fSBarry Smith   PetscErrorCode (*func)(SNES, Vec, Mat, Mat, void *);
2765deb2cd25SJed Brown 
2766deb2cd25SJed Brown   PetscFunctionBegin;
2767deb2cd25SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2768deb2cd25SJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 2);
27699566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)snes));
27709566063dSJacob Faibussowitsch   PetscCall(SNESDestroy(&ts->snes));
2771bbd56ea5SKarl Rupp 
2772deb2cd25SJed Brown   ts->snes = snes;
2773bbd56ea5SKarl Rupp 
27749566063dSJacob Faibussowitsch   PetscCall(SNESSetFunction(ts->snes, NULL, SNESTSFormFunction, ts));
27759566063dSJacob Faibussowitsch   PetscCall(SNESGetJacobian(ts->snes, NULL, NULL, &func, NULL));
27761e66621cSBarry Smith   if (func == SNESTSFormJacobian) PetscCall(SNESSetJacobian(ts->snes, NULL, NULL, SNESTSFormJacobian, ts));
2777deb2cd25SJed Brown   PetscFunctionReturn(0);
2778deb2cd25SJed Brown }
2779deb2cd25SJed Brown 
2780d8e5e3e6SSatish Balay /*@
2781bcf0153eSBarry Smith    TSGetKSP - Returns the `KSP` (linear solver) associated with
2782bcf0153eSBarry Smith    a `TS` (timestepper) context.
2783d763cef2SBarry Smith 
2784bcf0153eSBarry Smith    Not Collective, but ksp is parallel if ts is parallel
2785d763cef2SBarry Smith 
2786d763cef2SBarry Smith    Input Parameter:
2787bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2788d763cef2SBarry Smith 
2789d763cef2SBarry Smith    Output Parameter:
279094b7f48cSBarry Smith .  ksp - the nonlinear solver context
2791d763cef2SBarry Smith 
2792d763cef2SBarry Smith    Level: beginner
2793d763cef2SBarry Smith 
2794bcf0153eSBarry Smith    Notes:
2795bcf0153eSBarry Smith    The user can then directly manipulate the `KSP` context to set various
2796bcf0153eSBarry Smith    options, etc.  Likewise, the user can then extract and manipulate the
2797bcf0153eSBarry Smith    `PC` context as well.
2798bcf0153eSBarry Smith 
2799bcf0153eSBarry Smith    `TSGetKSP()` does not work for integrators that do not use `KSP`;
2800bcf0153eSBarry Smith    in this case `TSGetKSP()` returns NULL in ksp.
2801bcf0153eSBarry Smith 
2802bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `KSP`, `TSCreate()`, `TSSetUp()`, `TSSolve()`, `TSGetSNES()`
2803d763cef2SBarry Smith @*/
2804d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSP(TS ts, KSP *ksp)
2805d71ae5a4SJacob Faibussowitsch {
2806089b2837SJed Brown   SNES snes;
2807d372ba47SLisandro Dalcin 
2808d763cef2SBarry Smith   PetscFunctionBegin;
28090700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
28104482741eSBarry Smith   PetscValidPointer(ksp, 2);
28113c633725SBarry Smith   PetscCheck(((PetscObject)ts)->type_name, PETSC_COMM_SELF, PETSC_ERR_ARG_NULL, "KSP is not created yet. Call TSSetType() first");
28123c633725SBarry Smith   PetscCheck(ts->problem_type == TS_LINEAR, PETSC_COMM_SELF, PETSC_ERR_ARG_WRONG, "Linear only; use TSGetSNES()");
28139566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
28149566063dSJacob Faibussowitsch   PetscCall(SNESGetKSP(snes, ksp));
2815d763cef2SBarry Smith   PetscFunctionReturn(0);
2816d763cef2SBarry Smith }
2817d763cef2SBarry Smith 
2818d763cef2SBarry Smith /* ----------- Routines to set solver parameters ---------- */
2819d763cef2SBarry Smith 
2820adb62b0dSMatthew Knepley /*@
2821618ce8baSLisandro Dalcin    TSSetMaxSteps - Sets the maximum number of steps to use.
2822618ce8baSLisandro Dalcin 
2823c3339decSBarry Smith    Logically Collective
2824618ce8baSLisandro Dalcin 
2825618ce8baSLisandro Dalcin    Input Parameters:
2826bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2827618ce8baSLisandro Dalcin -  maxsteps - maximum number of steps to use
2828618ce8baSLisandro Dalcin 
2829bcf0153eSBarry Smith    Options Database Key:
2830618ce8baSLisandro Dalcin .  -ts_max_steps <maxsteps> - Sets maxsteps
2831618ce8baSLisandro Dalcin 
2832618ce8baSLisandro Dalcin    Level: intermediate
2833618ce8baSLisandro Dalcin 
2834bcf0153eSBarry Smith    Note:
2835bcf0153eSBarry Smith    The default maximum number of steps is 5000
2836bcf0153eSBarry Smith 
2837bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxSteps()`, `TSSetMaxTime()`, `TSSetExactFinalTime()`
2838618ce8baSLisandro Dalcin @*/
2839d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSteps(TS ts, PetscInt maxsteps)
2840d71ae5a4SJacob Faibussowitsch {
2841618ce8baSLisandro Dalcin   PetscFunctionBegin;
2842618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2843618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
28443c633725SBarry Smith   PetscCheck(maxsteps >= 0, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_OUTOFRANGE, "Maximum number of steps must be non-negative");
2845618ce8baSLisandro Dalcin   ts->max_steps = maxsteps;
2846618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2847618ce8baSLisandro Dalcin }
2848618ce8baSLisandro Dalcin 
2849618ce8baSLisandro Dalcin /*@
2850618ce8baSLisandro Dalcin    TSGetMaxSteps - Gets the maximum number of steps to use.
2851618ce8baSLisandro Dalcin 
2852618ce8baSLisandro Dalcin    Not Collective
2853618ce8baSLisandro Dalcin 
2854618ce8baSLisandro Dalcin    Input Parameters:
2855bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2856618ce8baSLisandro Dalcin 
2857618ce8baSLisandro Dalcin    Output Parameter:
2858618ce8baSLisandro Dalcin .  maxsteps - maximum number of steps to use
2859618ce8baSLisandro Dalcin 
2860618ce8baSLisandro Dalcin    Level: advanced
2861618ce8baSLisandro Dalcin 
2862bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxSteps()`, `TSGetMaxTime()`, `TSSetMaxTime()`
2863618ce8baSLisandro Dalcin @*/
2864d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxSteps(TS ts, PetscInt *maxsteps)
2865d71ae5a4SJacob Faibussowitsch {
2866618ce8baSLisandro Dalcin   PetscFunctionBegin;
2867618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2868618ce8baSLisandro Dalcin   PetscValidIntPointer(maxsteps, 2);
2869618ce8baSLisandro Dalcin   *maxsteps = ts->max_steps;
2870618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2871618ce8baSLisandro Dalcin }
2872618ce8baSLisandro Dalcin 
2873618ce8baSLisandro Dalcin /*@
2874618ce8baSLisandro Dalcin    TSSetMaxTime - Sets the maximum (or final) time for timestepping.
2875618ce8baSLisandro Dalcin 
2876c3339decSBarry Smith    Logically Collective
2877618ce8baSLisandro Dalcin 
2878618ce8baSLisandro Dalcin    Input Parameters:
2879bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
2880618ce8baSLisandro Dalcin -  maxtime - final time to step to
2881618ce8baSLisandro Dalcin 
2882bcf0153eSBarry Smith    Options Database Key:
2883ef85077eSLisandro Dalcin .  -ts_max_time <maxtime> - Sets maxtime
2884618ce8baSLisandro Dalcin 
2885bcf0153eSBarry Smith    Level: intermediate
2886bcf0153eSBarry Smith 
2887618ce8baSLisandro Dalcin    Notes:
2888618ce8baSLisandro Dalcin    The default maximum time is 5.0
2889618ce8baSLisandro Dalcin 
2890bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetMaxTime()`, `TSSetMaxSteps()`, `TSSetExactFinalTime()`
2891618ce8baSLisandro Dalcin @*/
2892d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxTime(TS ts, PetscReal maxtime)
2893d71ae5a4SJacob Faibussowitsch {
2894618ce8baSLisandro Dalcin   PetscFunctionBegin;
2895618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2896618ce8baSLisandro Dalcin   PetscValidLogicalCollectiveReal(ts, maxtime, 2);
2897618ce8baSLisandro Dalcin   ts->max_time = maxtime;
2898618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2899618ce8baSLisandro Dalcin }
2900618ce8baSLisandro Dalcin 
2901618ce8baSLisandro Dalcin /*@
2902618ce8baSLisandro Dalcin    TSGetMaxTime - Gets the maximum (or final) time for timestepping.
2903618ce8baSLisandro Dalcin 
2904618ce8baSLisandro Dalcin    Not Collective
2905618ce8baSLisandro Dalcin 
2906618ce8baSLisandro Dalcin    Input Parameters:
2907bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
2908618ce8baSLisandro Dalcin 
2909618ce8baSLisandro Dalcin    Output Parameter:
2910618ce8baSLisandro Dalcin .  maxtime - final time to step to
2911618ce8baSLisandro Dalcin 
2912618ce8baSLisandro Dalcin    Level: advanced
2913618ce8baSLisandro Dalcin 
2914bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetMaxTime()`, `TSGetMaxSteps()`, `TSSetMaxSteps()`
2915618ce8baSLisandro Dalcin @*/
2916d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetMaxTime(TS ts, PetscReal *maxtime)
2917d71ae5a4SJacob Faibussowitsch {
2918618ce8baSLisandro Dalcin   PetscFunctionBegin;
2919618ce8baSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2920618ce8baSLisandro Dalcin   PetscValidRealPointer(maxtime, 2);
2921618ce8baSLisandro Dalcin   *maxtime = ts->max_time;
2922618ce8baSLisandro Dalcin   PetscFunctionReturn(0);
2923618ce8baSLisandro Dalcin }
2924618ce8baSLisandro Dalcin 
2925618ce8baSLisandro Dalcin /*@
2926bcf0153eSBarry Smith    TSSetInitialTimeStep - Deprecated, use `TSSetTime()` and `TSSetTimeStep()`.
2927edc382c3SSatish Balay 
2928edc382c3SSatish Balay    Level: deprecated
2929edc382c3SSatish Balay 
2930aaa6c58dSLisandro Dalcin @*/
2931d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetInitialTimeStep(TS ts, PetscReal initial_time, PetscReal time_step)
2932d71ae5a4SJacob Faibussowitsch {
2933aaa6c58dSLisandro Dalcin   PetscFunctionBegin;
2934aaa6c58dSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
29359566063dSJacob Faibussowitsch   PetscCall(TSSetTime(ts, initial_time));
29369566063dSJacob Faibussowitsch   PetscCall(TSSetTimeStep(ts, time_step));
2937aaa6c58dSLisandro Dalcin   PetscFunctionReturn(0);
2938aaa6c58dSLisandro Dalcin }
2939aaa6c58dSLisandro Dalcin 
2940aaa6c58dSLisandro Dalcin /*@
2941bcf0153eSBarry Smith    TSGetDuration - Deprecated, use `TSGetMaxSteps()` and `TSGetMaxTime()`.
2942edc382c3SSatish Balay 
2943edc382c3SSatish Balay    Level: deprecated
2944edc382c3SSatish Balay 
2945adb62b0dSMatthew Knepley @*/
2946d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDuration(TS ts, PetscInt *maxsteps, PetscReal *maxtime)
2947d71ae5a4SJacob Faibussowitsch {
2948adb62b0dSMatthew Knepley   PetscFunctionBegin;
29490700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2950abc0a331SBarry Smith   if (maxsteps) {
29514482741eSBarry Smith     PetscValidIntPointer(maxsteps, 2);
2952adb62b0dSMatthew Knepley     *maxsteps = ts->max_steps;
2953adb62b0dSMatthew Knepley   }
2954abc0a331SBarry Smith   if (maxtime) {
2955064a246eSJacob Faibussowitsch     PetscValidRealPointer(maxtime, 3);
2956adb62b0dSMatthew Knepley     *maxtime = ts->max_time;
2957adb62b0dSMatthew Knepley   }
2958adb62b0dSMatthew Knepley   PetscFunctionReturn(0);
2959adb62b0dSMatthew Knepley }
2960adb62b0dSMatthew Knepley 
2961d763cef2SBarry Smith /*@
2962bcf0153eSBarry Smith    TSSetDuration - Deprecated, use `TSSetMaxSteps()` and `TSSetMaxTime()`.
2963edc382c3SSatish Balay 
2964edc382c3SSatish Balay    Level: deprecated
2965edc382c3SSatish Balay 
2966d763cef2SBarry Smith @*/
2967d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDuration(TS ts, PetscInt maxsteps, PetscReal maxtime)
2968d71ae5a4SJacob Faibussowitsch {
2969d763cef2SBarry Smith   PetscFunctionBegin;
29700700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
2971c5eb9154SBarry Smith   PetscValidLogicalCollectiveInt(ts, maxsteps, 2);
2972064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveReal(ts, maxtime, 3);
297339b7ec4bSSean Farley   if (maxsteps >= 0) ts->max_steps = maxsteps;
297439b7ec4bSSean Farley   if (maxtime != PETSC_DEFAULT) ts->max_time = maxtime;
2975d763cef2SBarry Smith   PetscFunctionReturn(0);
2976d763cef2SBarry Smith }
2977d763cef2SBarry Smith 
2978d763cef2SBarry Smith /*@
2979bcf0153eSBarry Smith    TSGetTimeStepNumber - Deprecated, use `TSGetStepNumber()`.
2980edc382c3SSatish Balay 
2981edc382c3SSatish Balay    Level: deprecated
2982edc382c3SSatish Balay 
29835c5f5948SLisandro Dalcin @*/
2984d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeStepNumber(TS ts, PetscInt *steps)
2985d71ae5a4SJacob Faibussowitsch {
29869371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29879371c9d4SSatish Balay }
29885c5f5948SLisandro Dalcin 
298919eac22cSLisandro Dalcin /*@
2990bcf0153eSBarry Smith    TSGetTotalSteps - Deprecated, use `TSGetStepNumber()`.
2991edc382c3SSatish Balay 
2992edc382c3SSatish Balay    Level: deprecated
2993edc382c3SSatish Balay 
29944f4e0956SLisandro Dalcin @*/
2995d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTotalSteps(TS ts, PetscInt *steps)
2996d71ae5a4SJacob Faibussowitsch {
29979371c9d4SSatish Balay   return TSGetStepNumber(ts, steps);
29989371c9d4SSatish Balay }
29994f4e0956SLisandro Dalcin 
30004f4e0956SLisandro Dalcin /*@
3001d763cef2SBarry Smith    TSSetSolution - Sets the initial solution vector
3002bcf0153eSBarry Smith    for use by the `TS` routines.
3003d763cef2SBarry Smith 
3004c3339decSBarry Smith    Logically Collective
3005d763cef2SBarry Smith 
3006d763cef2SBarry Smith    Input Parameters:
3007bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
30080910c330SBarry Smith -  u - the solution vector
3009d763cef2SBarry Smith 
3010d763cef2SBarry Smith    Level: beginner
3011d763cef2SBarry Smith 
3012bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetSolutionFunction()`, `TSGetSolution()`, `TSCreate()`
3013d763cef2SBarry Smith @*/
3014d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetSolution(TS ts, Vec u)
3015d71ae5a4SJacob Faibussowitsch {
3016496e6a7aSJed Brown   DM dm;
30178737fe31SLisandro Dalcin 
3018d763cef2SBarry Smith   PetscFunctionBegin;
30190700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
30200910c330SBarry Smith   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
30219566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)u));
30229566063dSJacob Faibussowitsch   PetscCall(VecDestroy(&ts->vec_sol));
30230910c330SBarry Smith   ts->vec_sol = u;
3024bbd56ea5SKarl Rupp 
30259566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
30269566063dSJacob Faibussowitsch   PetscCall(DMShellSetGlobalVector(dm, u));
3027d763cef2SBarry Smith   PetscFunctionReturn(0);
3028d763cef2SBarry Smith }
3029d763cef2SBarry Smith 
3030ac226902SBarry Smith /*@C
3031000e7ae3SMatthew Knepley   TSSetPreStep - Sets the general-purpose function
30323f2090d5SJed Brown   called once at the beginning of each time step.
3033000e7ae3SMatthew Knepley 
3034c3339decSBarry Smith   Logically Collective
3035000e7ae3SMatthew Knepley 
3036000e7ae3SMatthew Knepley   Input Parameters:
3037bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3038000e7ae3SMatthew Knepley - func - The function
3039000e7ae3SMatthew Knepley 
3040000e7ae3SMatthew Knepley   Calling sequence of func:
304167b8a455SSatish Balay .vb
304267b8a455SSatish Balay   PetscErrorCode func (TS ts);
304367b8a455SSatish Balay .ve
3044000e7ae3SMatthew Knepley 
3045000e7ae3SMatthew Knepley   Level: intermediate
3046000e7ae3SMatthew Knepley 
3047bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPostStage()`, `TSSetPostStep()`, `TSStep()`, `TSRestartStep()`
3048000e7ae3SMatthew Knepley @*/
3049d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStep(TS ts, PetscErrorCode (*func)(TS))
3050d71ae5a4SJacob Faibussowitsch {
3051000e7ae3SMatthew Knepley   PetscFunctionBegin;
30520700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3053ae60f76fSBarry Smith   ts->prestep = func;
3054000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3055000e7ae3SMatthew Knepley }
3056000e7ae3SMatthew Knepley 
305709ee8438SJed Brown /*@
3058bcf0153eSBarry Smith   TSPreStep - Runs the user-defined pre-step function provided with `TSSetPreStep()`
30593f2090d5SJed Brown 
3060c3339decSBarry Smith   Collective
30613f2090d5SJed Brown 
30623f2090d5SJed Brown   Input Parameters:
3063bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
30643f2090d5SJed Brown 
30653f2090d5SJed Brown   Level: developer
30663f2090d5SJed Brown 
3067bcf0153eSBarry Smith   Note:
3068bcf0153eSBarry Smith   `TSPreStep()` is typically used within time stepping implementations,
3069bcf0153eSBarry Smith   so most users would not generally call this routine themselves.
3070bcf0153eSBarry Smith 
3071bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSPreStage()`, `TSPostStage()`, `TSPostStep()`
30723f2090d5SJed Brown @*/
3073d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStep(TS ts)
3074d71ae5a4SJacob Faibussowitsch {
30753f2090d5SJed Brown   PetscFunctionBegin;
30760700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3077ae60f76fSBarry Smith   if (ts->prestep) {
30785efd42a4SStefano Zampini     Vec              U;
3079ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3080ef8d1ce0SJohann Rudi     PetscBool        sameObject;
30815efd42a4SStefano Zampini     PetscObjectState sprev, spost;
30825efd42a4SStefano Zampini 
30839566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30849566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
30859566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
308625e27a38SBarry Smith     PetscCallBack("TS callback preset", (*ts->prestep)(ts));
30879566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
30889566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
30899566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
30909566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
3091312ce896SJed Brown   }
30923f2090d5SJed Brown   PetscFunctionReturn(0);
30933f2090d5SJed Brown }
30943f2090d5SJed Brown 
3095b8123daeSJed Brown /*@C
3096b8123daeSJed Brown   TSSetPreStage - Sets the general-purpose function
3097b8123daeSJed Brown   called once at the beginning of each stage.
3098b8123daeSJed Brown 
3099c3339decSBarry Smith   Logically Collective
3100b8123daeSJed Brown 
3101b8123daeSJed Brown   Input Parameters:
3102bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3103b8123daeSJed Brown - func - The function
3104b8123daeSJed Brown 
3105b8123daeSJed Brown   Calling sequence of func:
310667b8a455SSatish Balay .vb
310767b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime);
310867b8a455SSatish Balay .ve
3109b8123daeSJed Brown 
3110b8123daeSJed Brown   Level: intermediate
3111b8123daeSJed Brown 
3112b8123daeSJed Brown   Note:
3113b8123daeSJed Brown   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3114bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3115bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
3116b8123daeSJed Brown 
3117bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3118b8123daeSJed Brown @*/
3119d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPreStage(TS ts, PetscErrorCode (*func)(TS, PetscReal))
3120d71ae5a4SJacob Faibussowitsch {
3121b8123daeSJed Brown   PetscFunctionBegin;
3122b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3123ae60f76fSBarry Smith   ts->prestage = func;
3124b8123daeSJed Brown   PetscFunctionReturn(0);
3125b8123daeSJed Brown }
3126b8123daeSJed Brown 
31279be3e283SDebojyoti Ghosh /*@C
3128bcf0153eSBarry Smith   TSSetPostStage - Sets the general-purpose function, provided with `TSSetPostStep()`,
31299be3e283SDebojyoti Ghosh   called once at the end of each stage.
31309be3e283SDebojyoti Ghosh 
3131c3339decSBarry Smith   Logically Collective
31329be3e283SDebojyoti Ghosh 
31339be3e283SDebojyoti Ghosh   Input Parameters:
3134bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
31359be3e283SDebojyoti Ghosh - func - The function
31369be3e283SDebojyoti Ghosh 
31379be3e283SDebojyoti Ghosh   Calling sequence of func:
313867b8a455SSatish Balay .vb
313967b8a455SSatish Balay   PetscErrorCode func(TS ts, PetscReal stagetime, PetscInt stageindex, Vec* Y);
314067b8a455SSatish Balay .ve
31419be3e283SDebojyoti Ghosh 
31429be3e283SDebojyoti Ghosh   Level: intermediate
31439be3e283SDebojyoti Ghosh 
31449be3e283SDebojyoti Ghosh   Note:
31459be3e283SDebojyoti Ghosh   There may be several stages per time step. If the solve for a given stage fails, the step may be rejected and retried.
3146bcf0153eSBarry Smith   The time step number being computed can be queried using `TSGetStepNumber()` and the total size of the step being
3147bcf0153eSBarry Smith   attempted can be obtained using `TSGetTimeStep()`. The time at the start of the step is available via `TSGetTime()`.
31489be3e283SDebojyoti Ghosh 
3149bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
31509be3e283SDebojyoti Ghosh @*/
3151d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStage(TS ts, PetscErrorCode (*func)(TS, PetscReal, PetscInt, Vec *))
3152d71ae5a4SJacob Faibussowitsch {
31539be3e283SDebojyoti Ghosh   PetscFunctionBegin;
31549be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
31559be3e283SDebojyoti Ghosh   ts->poststage = func;
31569be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
31579be3e283SDebojyoti Ghosh }
31589be3e283SDebojyoti Ghosh 
3159c688d042SShri Abhyankar /*@C
3160c688d042SShri Abhyankar   TSSetPostEvaluate - Sets the general-purpose function
3161c688d042SShri Abhyankar   called once at the end of each step evaluation.
3162c688d042SShri Abhyankar 
3163c3339decSBarry Smith   Logically Collective
3164c688d042SShri Abhyankar 
3165c688d042SShri Abhyankar   Input Parameters:
3166bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3167c688d042SShri Abhyankar - func - The function
3168c688d042SShri Abhyankar 
3169c688d042SShri Abhyankar   Calling sequence of func:
317067b8a455SSatish Balay .vb
317167b8a455SSatish Balay   PetscErrorCode func(TS ts);
317267b8a455SSatish Balay .ve
3173c688d042SShri Abhyankar 
3174c688d042SShri Abhyankar   Level: intermediate
3175c688d042SShri Abhyankar 
3176c688d042SShri Abhyankar   Note:
3177bcf0153eSBarry Smith   Semantically, `TSSetPostEvaluate()` differs from `TSSetPostStep()` since the function it sets is called before event-handling
3178bcf0153eSBarry Smith   thus guaranteeing the same solution (computed by the time-stepper) will be passed to it. On the other hand, `TSPostStep()`
3179bcf0153eSBarry Smith   may be passed a different solution, possibly changed by the event handler. `TSPostEvaluate()` is called after the next step
3180bcf0153eSBarry Smith   solution is evaluated allowing to modify it, if need be. The solution can be obtained with `TSGetSolution()`, the time step
3181bcf0153eSBarry Smith   with `TSGetTimeStep()`, and the time at the start of the step is available via `TSGetTime()`
3182c688d042SShri Abhyankar 
3183bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStage()`, `TSSetPreStep()`, `TSSetPostStep()`, `TSGetApplicationContext()`
3184c688d042SShri Abhyankar @*/
3185d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostEvaluate(TS ts, PetscErrorCode (*func)(TS))
3186d71ae5a4SJacob Faibussowitsch {
3187c688d042SShri Abhyankar   PetscFunctionBegin;
3188c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3189c688d042SShri Abhyankar   ts->postevaluate = func;
3190c688d042SShri Abhyankar   PetscFunctionReturn(0);
3191c688d042SShri Abhyankar }
3192c688d042SShri Abhyankar 
3193b8123daeSJed Brown /*@
3194bcf0153eSBarry Smith   TSPreStage - Runs the user-defined pre-stage function set using `TSSetPreStage()`
3195b8123daeSJed Brown 
3196c3339decSBarry Smith   Collective
3197b8123daeSJed Brown 
3198b8123daeSJed Brown   Input Parameters:
3199bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32009be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
3201b8123daeSJed Brown 
3202b8123daeSJed Brown   Level: developer
3203b8123daeSJed Brown 
3204bcf0153eSBarry Smith   Note:
3205bcf0153eSBarry Smith   `TSPreStage()` is typically used within time stepping implementations,
3206bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3207bcf0153eSBarry Smith 
3208bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPostStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3209b8123daeSJed Brown @*/
3210d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPreStage(TS ts, PetscReal stagetime)
3211d71ae5a4SJacob Faibussowitsch {
3212b8123daeSJed Brown   PetscFunctionBegin;
3213b8123daeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32141e66621cSBarry Smith   if (ts->prestage) PetscCallBack("TS callback prestage", (*ts->prestage)(ts, stagetime));
3215b8123daeSJed Brown   PetscFunctionReturn(0);
3216b8123daeSJed Brown }
3217b8123daeSJed Brown 
32189be3e283SDebojyoti Ghosh /*@
3219bcf0153eSBarry Smith   TSPostStage - Runs the user-defined post-stage function set using `TSSetPostStage()`
32209be3e283SDebojyoti Ghosh 
3221c3339decSBarry Smith   Collective
32229be3e283SDebojyoti Ghosh 
32239be3e283SDebojyoti Ghosh   Input Parameters:
3224bcf0153eSBarry Smith . ts          - The `TS` context obtained from `TSCreate()`
32259be3e283SDebojyoti Ghosh   stagetime   - The absolute time of the current stage
32269be3e283SDebojyoti Ghosh   stageindex  - Stage number
32279be3e283SDebojyoti Ghosh   Y           - Array of vectors (of size = total number
32289be3e283SDebojyoti Ghosh                 of stages) with the stage solutions
32299be3e283SDebojyoti Ghosh 
32309be3e283SDebojyoti Ghosh   Level: developer
32319be3e283SDebojyoti Ghosh 
3232bcf0153eSBarry Smith   Note:
3233bcf0153eSBarry Smith   `TSPostStage()` is typically used within time stepping implementations,
3234bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3235bcf0153eSBarry Smith 
3236bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSPreStage()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
32379be3e283SDebojyoti Ghosh @*/
3238d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStage(TS ts, PetscReal stagetime, PetscInt stageindex, Vec *Y)
3239d71ae5a4SJacob Faibussowitsch {
32409be3e283SDebojyoti Ghosh   PetscFunctionBegin;
32419be3e283SDebojyoti Ghosh   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
32421e66621cSBarry Smith   if (ts->poststage) PetscCallBack("TS callback poststage", (*ts->poststage)(ts, stagetime, stageindex, Y));
32439be3e283SDebojyoti Ghosh   PetscFunctionReturn(0);
32449be3e283SDebojyoti Ghosh }
32459be3e283SDebojyoti Ghosh 
3246c688d042SShri Abhyankar /*@
3247bcf0153eSBarry Smith   TSPostEvaluate - Runs the user-defined post-evaluate function set using `TSSetPostEvaluate()`
3248c688d042SShri Abhyankar 
3249c3339decSBarry Smith   Collective
3250c688d042SShri Abhyankar 
3251c688d042SShri Abhyankar   Input Parameters:
3252bcf0153eSBarry Smith . ts - The `TS` context obtained from `TSCreate()`
3253c688d042SShri Abhyankar 
3254c688d042SShri Abhyankar   Level: developer
3255c688d042SShri Abhyankar 
3256bcf0153eSBarry Smith   Note:
3257bcf0153eSBarry Smith   `TSPostEvaluate()` is typically used within time stepping implementations,
3258bcf0153eSBarry Smith   most users would not generally call this routine themselves.
3259bcf0153eSBarry Smith 
3260bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPostEvaluate()`, `TSSetPreStep()`, `TSPreStep()`, `TSPostStep()`
3261c688d042SShri Abhyankar @*/
3262d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostEvaluate(TS ts)
3263d71ae5a4SJacob Faibussowitsch {
3264c688d042SShri Abhyankar   PetscFunctionBegin;
3265c688d042SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3266c688d042SShri Abhyankar   if (ts->postevaluate) {
3267dcb233daSLisandro Dalcin     Vec              U;
3268dcb233daSLisandro Dalcin     PetscObjectState sprev, spost;
3269dcb233daSLisandro Dalcin 
32709566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
32719566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
327225e27a38SBarry Smith     PetscCallBack("TS callback postevaluate", (*ts->postevaluate)(ts));
32739566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
32749566063dSJacob Faibussowitsch     if (sprev != spost) PetscCall(TSRestartStep(ts));
3275c688d042SShri Abhyankar   }
3276c688d042SShri Abhyankar   PetscFunctionReturn(0);
3277c688d042SShri Abhyankar }
3278c688d042SShri Abhyankar 
3279ac226902SBarry Smith /*@C
3280000e7ae3SMatthew Knepley   TSSetPostStep - Sets the general-purpose function
32813f2090d5SJed Brown   called once at the end of each time step.
3282000e7ae3SMatthew Knepley 
3283c3339decSBarry Smith   Logically Collective
3284000e7ae3SMatthew Knepley 
3285000e7ae3SMatthew Knepley   Input Parameters:
3286bcf0153eSBarry Smith + ts   - The `TS` context obtained from `TSCreate()`
3287000e7ae3SMatthew Knepley - func - The function
3288000e7ae3SMatthew Knepley 
3289000e7ae3SMatthew Knepley   Calling sequence of func:
3290b8123daeSJed Brown $ func (TS ts);
3291000e7ae3SMatthew Knepley 
3292000e7ae3SMatthew Knepley   Level: intermediate
3293000e7ae3SMatthew Knepley 
3294bcf0153eSBarry Smith   Note:
3295bcf0153eSBarry Smith   The function set by `TSSetPostStep()` is called after each successful step. The solution vector X
3296bcf0153eSBarry Smith   obtained by `TSGetSolution()` may be different than that computed at the step end if the event handler
3297bcf0153eSBarry Smith   locates an event and `TSPostEvent()` modifies it. Use `TSSetPostEvaluate()` if an unmodified solution is needed instead.
3298bcf0153eSBarry Smith 
3299bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSRestartStep()`
3300000e7ae3SMatthew Knepley @*/
3301d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetPostStep(TS ts, PetscErrorCode (*func)(TS))
3302d71ae5a4SJacob Faibussowitsch {
3303000e7ae3SMatthew Knepley   PetscFunctionBegin;
33040700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3305ae60f76fSBarry Smith   ts->poststep = func;
3306000e7ae3SMatthew Knepley   PetscFunctionReturn(0);
3307000e7ae3SMatthew Knepley }
3308000e7ae3SMatthew Knepley 
330909ee8438SJed Brown /*@
3310bcf0153eSBarry Smith   TSPostStep - Runs the user-defined post-step function that was set with `TSSetPotsStep()`
33113f2090d5SJed Brown 
3312c3339decSBarry Smith   Collective
33133f2090d5SJed Brown 
33143f2090d5SJed Brown   Input Parameters:
3315bcf0153eSBarry Smith . ts   - The `TS` context obtained from `TSCreate()`
33163f2090d5SJed Brown 
3317bcf0153eSBarry Smith   Note:
3318bcf0153eSBarry Smith   `TSPostStep()` is typically used within time stepping implementations,
33193f2090d5SJed Brown   so most users would not generally call this routine themselves.
33203f2090d5SJed Brown 
33213f2090d5SJed Brown   Level: developer
33223f2090d5SJed Brown 
3323bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostEvaluate()`, `TSGetTimeStep()`, `TSGetStepNumber()`, `TSGetTime()`, `TSSetPotsStep()`
33243f2090d5SJed Brown @*/
3325d71ae5a4SJacob Faibussowitsch PetscErrorCode TSPostStep(TS ts)
3326d71ae5a4SJacob Faibussowitsch {
33273f2090d5SJed Brown   PetscFunctionBegin;
33280700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3329ae60f76fSBarry Smith   if (ts->poststep) {
33305efd42a4SStefano Zampini     Vec              U;
3331ef8d1ce0SJohann Rudi     PetscObjectId    idprev;
3332ef8d1ce0SJohann Rudi     PetscBool        sameObject;
33335efd42a4SStefano Zampini     PetscObjectState sprev, spost;
33345efd42a4SStefano Zampini 
33359566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33369566063dSJacob Faibussowitsch     PetscCall(PetscObjectGetId((PetscObject)U, &idprev));
33379566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &sprev));
333825e27a38SBarry Smith     PetscCallBack("TS callback poststep", (*ts->poststep)(ts));
33399566063dSJacob Faibussowitsch     PetscCall(TSGetSolution(ts, &U));
33409566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompareId((PetscObject)U, idprev, &sameObject));
33419566063dSJacob Faibussowitsch     PetscCall(PetscObjectStateGet((PetscObject)U, &spost));
33429566063dSJacob Faibussowitsch     if (!sameObject || sprev != spost) PetscCall(TSRestartStep(ts));
334372ac3e02SJed Brown   }
33443f2090d5SJed Brown   PetscFunctionReturn(0);
33453f2090d5SJed Brown }
33463f2090d5SJed Brown 
3347cd652676SJed Brown /*@
3348cd652676SJed Brown    TSInterpolate - Interpolate the solution computed during the previous step to an arbitrary location in the interval
3349cd652676SJed Brown 
3350c3339decSBarry Smith    Collective
3351cd652676SJed Brown 
33524165533cSJose E. Roman    Input Parameters:
3353cd652676SJed Brown +  ts - time stepping context
3354cd652676SJed Brown -  t - time to interpolate to
3355cd652676SJed Brown 
33564165533cSJose E. Roman    Output Parameter:
33570910c330SBarry Smith .  U - state at given time
3358cd652676SJed Brown 
3359cd652676SJed Brown    Level: intermediate
3360cd652676SJed Brown 
3361bcf0153eSBarry Smith    Developer Note:
3362bcf0153eSBarry Smith    `TSInterpolate()` and the storing of previous steps/stages should be generalized to support delay differential equations and continuous adjoints.
3363cd652676SJed Brown 
3364bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetExactFinalTime()`, `TSSolve()`
3365cd652676SJed Brown @*/
3366d71ae5a4SJacob Faibussowitsch PetscErrorCode TSInterpolate(TS ts, PetscReal t, Vec U)
3367d71ae5a4SJacob Faibussowitsch {
3368cd652676SJed Brown   PetscFunctionBegin;
3369cd652676SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3370b06615a5SLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
337163a3b9bcSJacob 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);
3372dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, interpolate, t, U);
3373cd652676SJed Brown   PetscFunctionReturn(0);
3374cd652676SJed Brown }
3375cd652676SJed Brown 
3376d763cef2SBarry Smith /*@
33776d9e5789SSean Farley    TSStep - Steps one time step
3378d763cef2SBarry Smith 
3379c3339decSBarry Smith    Collective
3380d763cef2SBarry Smith 
3381d763cef2SBarry Smith    Input Parameter:
3382bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3383d763cef2SBarry Smith 
338427829d71SBarry Smith    Level: developer
3385d763cef2SBarry Smith 
3386b8123daeSJed Brown    Notes:
3387bcf0153eSBarry Smith    The public interface for the ODE/DAE solvers is `TSSolve()`, you should almost for sure be using that routine and not this routine.
338827829d71SBarry Smith 
3389bcf0153eSBarry Smith    The hook set using `TSSetPreStep()` is called before each attempt to take the step. In general, the time step size may
3390b8123daeSJed Brown    be changed due to adaptive error controller or solve failures. Note that steps may contain multiple stages.
3391b8123daeSJed Brown 
3392bcf0153eSBarry Smith    This may over-step the final time provided in `TSSetMaxTime()` depending on the time-step used. `TSSolve()` interpolates to exactly the
3393bcf0153eSBarry Smith    time provided in `TSSetMaxTime()`. One can use `TSInterpolate()` to determine an interpolated solution within the final timestep.
339425cb2221SBarry Smith 
3395bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSSetPostStage()`, `TSInterpolate()`
3396d763cef2SBarry Smith @*/
3397d71ae5a4SJacob Faibussowitsch PetscErrorCode TSStep(TS ts)
3398d71ae5a4SJacob Faibussowitsch {
3399fffbeea8SBarry Smith   static PetscBool cite = PETSC_FALSE;
3400be5899b3SLisandro Dalcin   PetscReal        ptime;
3401d763cef2SBarry Smith 
3402d763cef2SBarry Smith   PetscFunctionBegin;
34030700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3404d0609cedSBarry Smith   PetscCall(PetscCitationsRegister("@article{tspaper,\n"
3405fffbeea8SBarry Smith                                    "  title         = {{PETSc/TS}: A Modern Scalable {DAE/ODE} Solver Library},\n"
3406f1d62c27SHong Zhang                                    "  author        = {Abhyankar, Shrirang and Brown, Jed and Constantinescu, Emil and Ghosh, Debojyoti and Smith, Barry F. and Zhang, Hong},\n"
3407f1d62c27SHong Zhang                                    "  journal       = {arXiv e-preprints},\n"
3408f1d62c27SHong Zhang                                    "  eprint        = {1806.01437},\n"
3409f1d62c27SHong Zhang                                    "  archivePrefix = {arXiv},\n"
34109371c9d4SSatish Balay                                    "  year          = {2018}\n}\n",
34119371c9d4SSatish Balay                                    &cite));
34129566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
34139566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3414d405a339SMatthew Knepley 
34153c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
34163c633725SBarry 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()");
34173c633725SBarry 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");
3418a6772fa2SLisandro Dalcin 
3419be5899b3SLisandro Dalcin   if (!ts->steps) ts->ptime_prev = ts->ptime;
34209371c9d4SSatish Balay   ptime                   = ts->ptime;
34219371c9d4SSatish Balay   ts->ptime_prev_rollback = ts->ptime_prev;
34222808aa04SLisandro Dalcin   ts->reason              = TS_CONVERGED_ITERATING;
3423fc8dbba5SLisandro Dalcin 
34249566063dSJacob Faibussowitsch   PetscCall(PetscLogEventBegin(TS_Step, ts, 0, 0, 0));
3425dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, step);
34269566063dSJacob Faibussowitsch   PetscCall(PetscLogEventEnd(TS_Step, ts, 0, 0, 0));
3427fc8dbba5SLisandro Dalcin 
34289371c9d4SSatish Balay   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[ts->tspan->spanctr], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0) && ts->tspan->spanctr < ts->tspan->num_span_times)
34299371c9d4SSatish Balay     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[ts->tspan->spanctr++]));
3430fc8dbba5SLisandro Dalcin   if (ts->reason >= 0) {
3431be5899b3SLisandro Dalcin     ts->ptime_prev = ptime;
34322808aa04SLisandro Dalcin     ts->steps++;
3433be5899b3SLisandro Dalcin     ts->steprollback = PETSC_FALSE;
343428d5b5d6SLisandro Dalcin     ts->steprestart  = PETSC_FALSE;
3435d2daff3dSHong Zhang   }
3436fc8dbba5SLisandro Dalcin   if (!ts->reason) {
343708c7845fSBarry Smith     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
343808c7845fSBarry Smith     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
343908c7845fSBarry Smith   }
3440fc8dbba5SLisandro Dalcin 
34415c9bbc89SJed Brown   if (ts->reason < 0 && ts->errorifstepfailed) {
34425c9bbc89SJed Brown     PetscCall(TSMonitorCancel(ts));
34435c9bbc89SJed Brown     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 make negative to attempt recovery", TSConvergedReasons[ts->reason]);
34445c9bbc89SJed Brown     SETERRQ(PetscObjectComm((PetscObject)ts), PETSC_ERR_NOT_CONVERGED, "TSStep has failed due to %s", TSConvergedReasons[ts->reason]);
34455c9bbc89SJed Brown   }
344608c7845fSBarry Smith   PetscFunctionReturn(0);
344708c7845fSBarry Smith }
344808c7845fSBarry Smith 
344908c7845fSBarry Smith /*@
34507cbde773SLisandro Dalcin    TSEvaluateWLTE - Evaluate the weighted local truncation error norm
34517cbde773SLisandro Dalcin    at the end of a time step with a given order of accuracy.
34527cbde773SLisandro Dalcin 
3453c3339decSBarry Smith    Collective
34547cbde773SLisandro Dalcin 
34554165533cSJose E. Roman    Input Parameters:
34567cbde773SLisandro Dalcin +  ts - time stepping context
3457bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
34587cbde773SLisandro Dalcin 
345997bb3fdcSJose E. Roman    Input/Output Parameter:
3460bcf0153eSBarry Smith .  order - optional, desired order for the error evaluation or `PETSC_DECIDE`;
346197bb3fdcSJose E. Roman            on output, the actual order of the error evaluation
346297bb3fdcSJose E. Roman 
346397bb3fdcSJose E. Roman    Output Parameter:
346497bb3fdcSJose E. Roman .  wlte - the weighted local truncation error norm
34657cbde773SLisandro Dalcin 
34667cbde773SLisandro Dalcin    Level: advanced
34677cbde773SLisandro Dalcin 
3468bcf0153eSBarry Smith    Note:
34697cbde773SLisandro Dalcin    If the timestepper cannot evaluate the error in a particular step
34707cbde773SLisandro Dalcin    (eg. in the first step or restart steps after event handling),
34717cbde773SLisandro Dalcin    this routine returns wlte=-1.0 .
34727cbde773SLisandro Dalcin 
3473bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`, `TSErrorWeightedNorm()`
34747cbde773SLisandro Dalcin @*/
3475d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateWLTE(TS ts, NormType wnormtype, PetscInt *order, PetscReal *wlte)
3476d71ae5a4SJacob Faibussowitsch {
34777cbde773SLisandro Dalcin   PetscFunctionBegin;
34787cbde773SLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
34797cbde773SLisandro Dalcin   PetscValidType(ts, 1);
3480064a246eSJacob Faibussowitsch   PetscValidLogicalCollectiveEnum(ts, wnormtype, 2);
34817cbde773SLisandro Dalcin   if (order) PetscValidIntPointer(order, 3);
34827cbde773SLisandro Dalcin   if (order) PetscValidLogicalCollectiveInt(ts, *order, 3);
34837cbde773SLisandro Dalcin   PetscValidRealPointer(wlte, 4);
34843c633725SBarry Smith   PetscCheck(wnormtype == NORM_2 || wnormtype == NORM_INFINITY, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
3485dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatewlte, wnormtype, order, wlte);
34867cbde773SLisandro Dalcin   PetscFunctionReturn(0);
34877cbde773SLisandro Dalcin }
34887cbde773SLisandro Dalcin 
348905175c85SJed Brown /*@
349005175c85SJed Brown    TSEvaluateStep - Evaluate the solution at the end of a time step with a given order of accuracy.
349105175c85SJed Brown 
3492c3339decSBarry Smith    Collective
349305175c85SJed Brown 
34944165533cSJose E. Roman    Input Parameters:
34951c3436cfSJed Brown +  ts - time stepping context
34961c3436cfSJed Brown .  order - desired order of accuracy
34970298fd71SBarry Smith -  done - whether the step was evaluated at this order (pass NULL to generate an error if not available)
349805175c85SJed Brown 
34994165533cSJose E. Roman    Output Parameter:
35000910c330SBarry Smith .  U - state at the end of the current step
350105175c85SJed Brown 
350205175c85SJed Brown    Level: advanced
350305175c85SJed Brown 
3504108c343cSJed Brown    Notes:
3505108c343cSJed Brown    This function cannot be called until all stages have been evaluated.
3506108c343cSJed Brown 
3507bcf0153eSBarry 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.
3508bcf0153eSBarry Smith 
3509bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSStep()`, `TSAdapt`
351005175c85SJed Brown @*/
3511d71ae5a4SJacob Faibussowitsch PetscErrorCode TSEvaluateStep(TS ts, PetscInt order, Vec U, PetscBool *done)
3512d71ae5a4SJacob Faibussowitsch {
351305175c85SJed Brown   PetscFunctionBegin;
351405175c85SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
351505175c85SJed Brown   PetscValidType(ts, 1);
35160910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
3517dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, evaluatestep, order, U, done);
351805175c85SJed Brown   PetscFunctionReturn(0);
351905175c85SJed Brown }
352005175c85SJed Brown 
3521aad739acSMatthew G. Knepley /*@C
35222e61be88SMatthew G. Knepley   TSGetComputeInitialCondition - Get the function used to automatically compute an initial condition for the timestepping.
3523aad739acSMatthew G. Knepley 
3524aad739acSMatthew G. Knepley   Not collective
3525aad739acSMatthew G. Knepley 
35264165533cSJose E. Roman   Input Parameter:
3527aad739acSMatthew G. Knepley . ts - time stepping context
3528aad739acSMatthew G. Knepley 
35294165533cSJose E. Roman   Output Parameter:
35302e61be88SMatthew G. Knepley . initConditions - The function which computes an initial condition
3531aad739acSMatthew G. Knepley 
3532bcf0153eSBarry Smith   The calling sequence for the function is
3533bcf0153eSBarry Smith .vb
3534bcf0153eSBarry Smith  initCondition(TS ts, Vec u)
3535bcf0153eSBarry Smith  ts - The timestepping context
3536bcf0153eSBarry Smith  u  - The input vector in which the initial condition is stored
3537bcf0153eSBarry Smith .ve
3538bcf0153eSBarry Smith 
3539aad739acSMatthew G. Knepley    Level: advanced
3540aad739acSMatthew G. Knepley 
3541bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetComputeInitialCondition()`, `TSComputeInitialCondition()`
3542aad739acSMatthew G. Knepley @*/
3543d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeInitialCondition(TS ts, PetscErrorCode (**initCondition)(TS, Vec))
3544d71ae5a4SJacob Faibussowitsch {
3545aad739acSMatthew G. Knepley   PetscFunctionBegin;
3546aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35472e61be88SMatthew G. Knepley   PetscValidPointer(initCondition, 2);
35482e61be88SMatthew G. Knepley   *initCondition = ts->ops->initcondition;
3549aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3550aad739acSMatthew G. Knepley }
3551aad739acSMatthew G. Knepley 
3552aad739acSMatthew G. Knepley /*@C
35532e61be88SMatthew G. Knepley   TSSetComputeInitialCondition - Set the function used to automatically compute an initial condition for the timestepping.
3554aad739acSMatthew G. Knepley 
3555c3339decSBarry Smith   Logically collective
3556aad739acSMatthew G. Knepley 
35574165533cSJose E. Roman   Input Parameters:
3558aad739acSMatthew G. Knepley + ts  - time stepping context
35592e61be88SMatthew G. Knepley - initCondition - The function which computes an initial condition
3560aad739acSMatthew G. Knepley 
3561a96d6ef6SBarry Smith   Calling sequence for initCondition:
3562a96d6ef6SBarry Smith $ PetscErrorCode initCondition(TS ts, Vec u)
3563a96d6ef6SBarry Smith + ts - The timestepping context
3564a96d6ef6SBarry Smith - u  - The input vector in which the initial condition is to be stored
3565aad739acSMatthew G. Knepley 
3566bcf0153eSBarry Smith   Level: advanced
3567bcf0153eSBarry Smith 
3568bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSComputeInitialCondition()`
3569aad739acSMatthew G. Knepley @*/
3570d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeInitialCondition(TS ts, PetscErrorCode (*initCondition)(TS, Vec))
3571d71ae5a4SJacob Faibussowitsch {
3572aad739acSMatthew G. Knepley   PetscFunctionBegin;
3573aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
35742e61be88SMatthew G. Knepley   PetscValidFunction(initCondition, 2);
35752e61be88SMatthew G. Knepley   ts->ops->initcondition = initCondition;
3576aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3577aad739acSMatthew G. Knepley }
3578aad739acSMatthew G. Knepley 
3579aad739acSMatthew G. Knepley /*@
3580bcf0153eSBarry Smith   TSComputeInitialCondition - Compute an initial condition for the timestepping using the function previously set with `TSSetComputeInitialCondition()`
3581aad739acSMatthew G. Knepley 
3582c3339decSBarry Smith   Collective
3583aad739acSMatthew G. Knepley 
35844165533cSJose E. Roman   Input Parameters:
3585aad739acSMatthew G. Knepley + ts - time stepping context
3586bcf0153eSBarry Smith - u  - The `Vec` to store the condition in which will be used in `TSSolve()`
3587aad739acSMatthew G. Knepley 
3588aad739acSMatthew G. Knepley   Level: advanced
3589aad739acSMatthew G. Knepley 
3590bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3591aad739acSMatthew G. Knepley @*/
3592d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeInitialCondition(TS ts, Vec u)
3593d71ae5a4SJacob Faibussowitsch {
3594aad739acSMatthew G. Knepley   PetscFunctionBegin;
3595aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3596aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3597dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, initcondition, u);
3598aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3599aad739acSMatthew G. Knepley }
3600aad739acSMatthew G. Knepley 
3601aad739acSMatthew G. Knepley /*@C
3602aad739acSMatthew G. Knepley   TSGetComputeExactError - Get the function used to automatically compute the exact error for the timestepping.
3603aad739acSMatthew G. Knepley 
3604aad739acSMatthew G. Knepley   Not collective
3605aad739acSMatthew G. Knepley 
36064165533cSJose E. Roman   Input Parameter:
3607aad739acSMatthew G. Knepley . ts - time stepping context
3608aad739acSMatthew G. Knepley 
36094165533cSJose E. Roman   Output Parameter:
3610aad739acSMatthew G. Knepley . exactError - The function which computes the solution error
3611aad739acSMatthew G. Knepley 
3612a96d6ef6SBarry Smith   Calling sequence for exactError:
3613a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3614a96d6ef6SBarry Smith + ts - The timestepping context
3615a96d6ef6SBarry Smith . u  - The approximate solution vector
3616a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3617aad739acSMatthew G. Knepley 
3618bcf0153eSBarry Smith   Level: advanced
3619bcf0153eSBarry Smith 
3620bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3621aad739acSMatthew G. Knepley @*/
3622d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetComputeExactError(TS ts, PetscErrorCode (**exactError)(TS, Vec, Vec))
3623d71ae5a4SJacob Faibussowitsch {
3624aad739acSMatthew G. Knepley   PetscFunctionBegin;
3625aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3626aad739acSMatthew G. Knepley   PetscValidPointer(exactError, 2);
3627aad739acSMatthew G. Knepley   *exactError = ts->ops->exacterror;
3628aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3629aad739acSMatthew G. Knepley }
3630aad739acSMatthew G. Knepley 
3631aad739acSMatthew G. Knepley /*@C
3632aad739acSMatthew G. Knepley   TSSetComputeExactError - Set the function used to automatically compute the exact error for the timestepping.
3633aad739acSMatthew G. Knepley 
3634c3339decSBarry Smith   Logically collective
3635aad739acSMatthew G. Knepley 
36364165533cSJose E. Roman   Input Parameters:
3637aad739acSMatthew G. Knepley + ts - time stepping context
3638aad739acSMatthew G. Knepley - exactError - The function which computes the solution error
3639aad739acSMatthew G. Knepley 
3640a96d6ef6SBarry Smith   Calling sequence for exactError:
3641a96d6ef6SBarry Smith $ PetscErrorCode exactError(TS ts, Vec u)
3642a96d6ef6SBarry Smith + ts - The timestepping context
3643a96d6ef6SBarry Smith . u  - The approximate solution vector
3644a96d6ef6SBarry Smith - e  - The input vector in which the error is stored
3645aad739acSMatthew G. Knepley 
3646bcf0153eSBarry Smith   Level: advanced
3647bcf0153eSBarry Smith 
3648bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeExactError()`, `TSComputeExactError()`
3649aad739acSMatthew G. Knepley @*/
3650d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetComputeExactError(TS ts, PetscErrorCode (*exactError)(TS, Vec, Vec))
3651d71ae5a4SJacob Faibussowitsch {
3652aad739acSMatthew G. Knepley   PetscFunctionBegin;
3653aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3654f907fdbfSMatthew G. Knepley   PetscValidFunction(exactError, 2);
3655aad739acSMatthew G. Knepley   ts->ops->exacterror = exactError;
3656aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3657aad739acSMatthew G. Knepley }
3658aad739acSMatthew G. Knepley 
3659aad739acSMatthew G. Knepley /*@
3660bcf0153eSBarry Smith   TSComputeExactError - Compute the solution error for the timestepping using the function previously set with `TSSetComputeExactError()`
3661aad739acSMatthew G. Knepley 
3662c3339decSBarry Smith   Collective
3663aad739acSMatthew G. Knepley 
36644165533cSJose E. Roman   Input Parameters:
3665aad739acSMatthew G. Knepley + ts - time stepping context
3666aad739acSMatthew G. Knepley . u  - The approximate solution
3667bcf0153eSBarry Smith - e  - The `Vec` used to store the error
3668aad739acSMatthew G. Knepley 
3669aad739acSMatthew G. Knepley   Level: advanced
3670aad739acSMatthew G. Knepley 
3671bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetComputeInitialCondition()`, `TSSetComputeInitialCondition()`, `TSSolve()`
3672aad739acSMatthew G. Knepley @*/
3673d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeExactError(TS ts, Vec u, Vec e)
3674d71ae5a4SJacob Faibussowitsch {
3675aad739acSMatthew G. Knepley   PetscFunctionBegin;
3676aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3677aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3678aad739acSMatthew G. Knepley   PetscValidHeaderSpecific(e, VEC_CLASSID, 3);
3679dbbe0bcdSBarry Smith   PetscTryTypeMethod(ts, exacterror, u, e);
3680aad739acSMatthew G. Knepley   PetscFunctionReturn(0);
3681aad739acSMatthew G. Knepley }
3682aad739acSMatthew G. Knepley 
3683b1cb36f3SHong Zhang /*@
36846a4d4014SLisandro Dalcin    TSSolve - Steps the requested number of timesteps.
36856a4d4014SLisandro Dalcin 
3686c3339decSBarry Smith    Collective
36876a4d4014SLisandro Dalcin 
3688d8d19677SJose E. Roman    Input Parameters:
3689bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
3690bcf0153eSBarry Smith -  u - the solution vector  (can be null if `TSSetSolution()` was used and `TSSetExactFinalTime`(ts,`TS_EXACTFINALTIME_MATCHSTEP`) was not used,
369163e21af5SBarry Smith                              otherwise must contain the initial conditions and will contain the solution at the final requested time
36925a3a76d0SJed Brown 
36936a4d4014SLisandro Dalcin    Level: beginner
36946a4d4014SLisandro Dalcin 
36955a3a76d0SJed Brown    Notes:
36965a3a76d0SJed Brown    The final time returned by this function may be different from the time of the internally
3697bcf0153eSBarry Smith    held state accessible by `TSGetSolution()` and `TSGetTime()` because the method may have
36985a3a76d0SJed Brown    stepped over the final time.
36995a3a76d0SJed Brown 
3700bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetSolution()`, `TSStep()`, `TSGetTime()`, `TSGetSolveTime()`
37016a4d4014SLisandro Dalcin @*/
3702d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSolve(TS ts, Vec u)
3703d71ae5a4SJacob Faibussowitsch {
3704b06615a5SLisandro Dalcin   Vec solution;
3705f22f69f0SBarry Smith 
37066a4d4014SLisandro Dalcin   PetscFunctionBegin;
37070700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3708f2c2a1b9SBarry Smith   if (u) PetscValidHeaderSpecific(u, VEC_CLASSID, 2);
3709303a5415SBarry Smith 
37109566063dSJacob Faibussowitsch   PetscCall(TSSetExactFinalTimeDefault(ts));
3711ee41a567SStefano 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 */
37120910c330SBarry Smith     if (!ts->vec_sol || u == ts->vec_sol) {
37139566063dSJacob Faibussowitsch       PetscCall(VecDuplicate(u, &solution));
37149566063dSJacob Faibussowitsch       PetscCall(TSSetSolution(ts, solution));
37159566063dSJacob Faibussowitsch       PetscCall(VecDestroy(&solution)); /* grant ownership */
37165a3a76d0SJed Brown     }
37179566063dSJacob Faibussowitsch     PetscCall(VecCopy(u, ts->vec_sol));
37183c633725SBarry Smith     PetscCheck(!ts->forward_solve, PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "Sensitivity analysis does not support the mode TS_EXACTFINALTIME_INTERPOLATE");
37191baa6e33SBarry Smith   } else if (u) PetscCall(TSSetSolution(ts, u));
37209566063dSJacob Faibussowitsch   PetscCall(TSSetUp(ts));
37219566063dSJacob Faibussowitsch   PetscCall(TSTrajectorySetUp(ts->trajectory, ts));
3722a6772fa2SLisandro Dalcin 
37233c633725SBarry Smith   PetscCheck(ts->max_time < PETSC_MAX_REAL || ts->max_steps != PETSC_MAX_INT, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "You must call TSSetMaxTime() or TSSetMaxSteps(), or use -ts_max_time <time> or -ts_max_steps <steps>");
37243c633725SBarry 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()");
37253c633725SBarry 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");
37264a658b32SHong Zhang   PetscCheck(!(ts->tspan && ts->exact_final_time != TS_EXACTFINALTIME_MATCHSTEP), PetscObjectComm((PetscObject)ts), PETSC_ERR_SUP, "You must use TS_EXACTFINALTIME_MATCHSTEP when using time span");
37274a658b32SHong Zhang 
3728e1db57b0SHong Zhang   if (ts->tspan && PetscIsCloseAtTol(ts->ptime, ts->tspan->span_times[0], ts->tspan->reltol * ts->time_step + ts->tspan->abstol, 0)) { /* starting point in time span */
37294a658b32SHong Zhang     PetscCall(VecCopy(ts->vec_sol, ts->tspan->vecs_sol[0]));
37304a658b32SHong Zhang     ts->tspan->spanctr = 1;
37314a658b32SHong Zhang   }
3732a6772fa2SLisandro Dalcin 
37331baa6e33SBarry Smith   if (ts->forward_solve) PetscCall(TSForwardSetUp(ts));
3734715f1b00SHong Zhang 
3735e7069c78SShri   /* reset number of steps only when the step is not restarted. ARKIMEX
3736715f1b00SHong Zhang      restarts the step after an event. Resetting these counters in such case causes
3737e7069c78SShri      TSTrajectory to incorrectly save the output files
3738e7069c78SShri   */
3739715f1b00SHong Zhang   /* reset time step and iteration counters */
37402808aa04SLisandro Dalcin   if (!ts->steps) {
37415ef26d82SJed Brown     ts->ksp_its           = 0;
37425ef26d82SJed Brown     ts->snes_its          = 0;
3743c610991cSLisandro Dalcin     ts->num_snes_failures = 0;
3744c610991cSLisandro Dalcin     ts->reject            = 0;
37452808aa04SLisandro Dalcin     ts->steprestart       = PETSC_TRUE;
37462808aa04SLisandro Dalcin     ts->steprollback      = PETSC_FALSE;
37477d51462cSStefano Zampini     ts->rhsjacobian.time  = PETSC_MIN_REAL;
37482808aa04SLisandro Dalcin   }
3749e97c63d7SStefano Zampini 
37504a658b32SHong Zhang   /* make sure initial time step does not overshoot final time or the next point in tspan */
3751e97c63d7SStefano Zampini   if (ts->exact_final_time == TS_EXACTFINALTIME_MATCHSTEP) {
37524a658b32SHong Zhang     PetscReal maxdt;
3753e97c63d7SStefano Zampini     PetscReal dt = ts->time_step;
3754e97c63d7SStefano Zampini 
37554a658b32SHong Zhang     if (ts->tspan) maxdt = ts->tspan->span_times[ts->tspan->spanctr] - ts->ptime;
37564a658b32SHong Zhang     else maxdt = ts->max_time - ts->ptime;
3757e97c63d7SStefano Zampini     ts->time_step = dt >= maxdt ? maxdt : (PetscIsCloseAtTol(dt, maxdt, 10 * PETSC_MACHINE_EPSILON, 0) ? maxdt : dt);
3758e97c63d7SStefano Zampini   }
3759193ac0bcSJed Brown   ts->reason = TS_CONVERGED_ITERATING;
3760193ac0bcSJed Brown 
3761900f6b5bSMatthew G. Knepley   {
3762900f6b5bSMatthew G. Knepley     PetscViewer       viewer;
3763900f6b5bSMatthew G. Knepley     PetscViewerFormat format;
3764900f6b5bSMatthew G. Knepley     PetscBool         flg;
3765900f6b5bSMatthew G. Knepley     static PetscBool  incall = PETSC_FALSE;
3766900f6b5bSMatthew G. Knepley 
3767900f6b5bSMatthew G. Knepley     if (!incall) {
3768900f6b5bSMatthew G. Knepley       /* Estimate the convergence rate of the time discretization */
37699566063dSJacob Faibussowitsch       PetscCall(PetscOptionsGetViewer(PetscObjectComm((PetscObject)ts), ((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_estimate", &viewer, &format, &flg));
3770900f6b5bSMatthew G. Knepley       if (flg) {
3771900f6b5bSMatthew G. Knepley         PetscConvEst conv;
3772900f6b5bSMatthew G. Knepley         DM           dm;
3773900f6b5bSMatthew G. Knepley         PetscReal   *alpha; /* Convergence rate of the solution error for each field in the L_2 norm */
3774900f6b5bSMatthew G. Knepley         PetscInt     Nf;
3775f2ed2dc7SMatthew G. Knepley         PetscBool    checkTemporal = PETSC_TRUE;
3776900f6b5bSMatthew G. Knepley 
3777900f6b5bSMatthew G. Knepley         incall = PETSC_TRUE;
37789566063dSJacob Faibussowitsch         PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_convergence_temporal", &checkTemporal, &flg));
37799566063dSJacob Faibussowitsch         PetscCall(TSGetDM(ts, &dm));
37809566063dSJacob Faibussowitsch         PetscCall(DMGetNumFields(dm, &Nf));
37819566063dSJacob Faibussowitsch         PetscCall(PetscCalloc1(PetscMax(Nf, 1), &alpha));
37829566063dSJacob Faibussowitsch         PetscCall(PetscConvEstCreate(PetscObjectComm((PetscObject)ts), &conv));
37839566063dSJacob Faibussowitsch         PetscCall(PetscConvEstUseTS(conv, checkTemporal));
37849566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetSolver(conv, (PetscObject)ts));
37859566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetFromOptions(conv));
37869566063dSJacob Faibussowitsch         PetscCall(PetscConvEstSetUp(conv));
37879566063dSJacob Faibussowitsch         PetscCall(PetscConvEstGetConvRate(conv, alpha));
37889566063dSJacob Faibussowitsch         PetscCall(PetscViewerPushFormat(viewer, format));
37899566063dSJacob Faibussowitsch         PetscCall(PetscConvEstRateView(conv, alpha, viewer));
37909566063dSJacob Faibussowitsch         PetscCall(PetscViewerPopFormat(viewer));
37919566063dSJacob Faibussowitsch         PetscCall(PetscViewerDestroy(&viewer));
37929566063dSJacob Faibussowitsch         PetscCall(PetscConvEstDestroy(&conv));
37939566063dSJacob Faibussowitsch         PetscCall(PetscFree(alpha));
3794900f6b5bSMatthew G. Knepley         incall = PETSC_FALSE;
3795900f6b5bSMatthew G. Knepley       }
3796900f6b5bSMatthew G. Knepley     }
3797900f6b5bSMatthew G. Knepley   }
3798900f6b5bSMatthew G. Knepley 
37999566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view_pre"));
3800f05ece33SBarry Smith 
3801193ac0bcSJed Brown   if (ts->ops->solve) { /* This private interface is transitional and should be removed when all implementations are updated. */
3802dbbe0bcdSBarry Smith     PetscUseTypeMethod(ts, solve);
38039566063dSJacob Faibussowitsch     if (u) PetscCall(VecCopy(ts->vec_sol, u));
3804cc708dedSBarry Smith     ts->solvetime = ts->ptime;
3805a6772fa2SLisandro Dalcin     solution      = ts->vec_sol;
3806be5899b3SLisandro Dalcin   } else { /* Step the requested number of timesteps. */
3807db4deed7SKarl Rupp     if (ts->steps >= ts->max_steps) ts->reason = TS_CONVERGED_ITS;
3808db4deed7SKarl Rupp     else if (ts->ptime >= ts->max_time) ts->reason = TS_CONVERGED_TIME;
3809e7069c78SShri 
38102808aa04SLisandro Dalcin     if (!ts->steps) {
38119566063dSJacob Faibussowitsch       PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38129566063dSJacob Faibussowitsch       PetscCall(TSEventInitialize(ts->event, ts, ts->ptime, ts->vec_sol));
38132808aa04SLisandro Dalcin     }
38146427ac75SLisandro Dalcin 
3815e1a7a14fSJed Brown     while (!ts->reason) {
38169566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38171e66621cSBarry Smith       if (!ts->steprollback) PetscCall(TSPreStep(ts));
38189566063dSJacob Faibussowitsch       PetscCall(TSStep(ts));
38191baa6e33SBarry Smith       if (ts->testjacobian) PetscCall(TSRHSJacobianTest(ts, NULL));
38201baa6e33SBarry Smith       if (ts->testjacobiantranspose) PetscCall(TSRHSJacobianTestTranspose(ts, NULL));
3821cd4cee2dSHong Zhang       if (ts->quadraturets && ts->costintegralfwd) { /* Must evaluate the cost integral before event is handled. The cost integral value can also be rolled back. */
38227b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--;            /* Revert the step number changed by TSStep() */
38239566063dSJacob Faibussowitsch         PetscCall(TSForwardCostIntegral(ts));
38247b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3825b1cb36f3SHong Zhang       }
382658818c2dSLisandro Dalcin       if (ts->forward_solve) {            /* compute forward sensitivities before event handling because postevent() may change RHS and jump conditions may have to be applied */
38277b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps--; /* Revert the step number changed by TSStep() */
38289566063dSJacob Faibussowitsch         PetscCall(TSForwardStep(ts));
38297b0e2f17SHong Zhang         if (ts->reason >= 0) ts->steps++;
3830715f1b00SHong Zhang       }
38319566063dSJacob Faibussowitsch       PetscCall(TSPostEvaluate(ts));
38329566063dSJacob 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. */
38331baa6e33SBarry Smith       if (ts->steprollback) PetscCall(TSPostEvaluate(ts));
3834e783b05fSHong Zhang       if (!ts->steprollback) {
38359566063dSJacob Faibussowitsch         PetscCall(TSTrajectorySet(ts->trajectory, ts, ts->steps, ts->ptime, ts->vec_sol));
38369566063dSJacob Faibussowitsch         PetscCall(TSPostStep(ts));
3837aeb4809dSShri Abhyankar       }
3838193ac0bcSJed Brown     }
38399566063dSJacob Faibussowitsch     PetscCall(TSMonitor(ts, ts->steps, ts->ptime, ts->vec_sol));
38406427ac75SLisandro Dalcin 
384149354f04SShri Abhyankar     if (ts->exact_final_time == TS_EXACTFINALTIME_INTERPOLATE && ts->ptime > ts->max_time) {
38429566063dSJacob Faibussowitsch       PetscCall(TSInterpolate(ts, ts->max_time, u));
3843cc708dedSBarry Smith       ts->solvetime = ts->max_time;
3844b06615a5SLisandro Dalcin       solution      = u;
38459566063dSJacob Faibussowitsch       PetscCall(TSMonitor(ts, -1, ts->solvetime, solution));
38460574a7fbSJed Brown     } else {
38479566063dSJacob Faibussowitsch       if (u) PetscCall(VecCopy(ts->vec_sol, u));
3848cc708dedSBarry Smith       ts->solvetime = ts->ptime;
3849b06615a5SLisandro Dalcin       solution      = ts->vec_sol;
38500574a7fbSJed Brown     }
3851193ac0bcSJed Brown   }
3852d2daff3dSHong Zhang 
38539566063dSJacob Faibussowitsch   PetscCall(TSViewFromOptions(ts, NULL, "-ts_view"));
38549566063dSJacob Faibussowitsch   PetscCall(VecViewFromOptions(solution, (PetscObject)ts, "-ts_view_solution"));
38559566063dSJacob Faibussowitsch   PetscCall(PetscObjectSAWsBlock((PetscObject)ts));
38561baa6e33SBarry Smith   if (ts->adjoint_solve) PetscCall(TSAdjointSolve(ts));
38576a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
38586a4d4014SLisandro Dalcin }
38596a4d4014SLisandro Dalcin 
3860d763cef2SBarry Smith /*@
3861b8123daeSJed Brown    TSGetTime - Gets the time of the most recently completed step.
3862d763cef2SBarry Smith 
3863d763cef2SBarry Smith    Not Collective
3864d763cef2SBarry Smith 
3865d763cef2SBarry Smith    Input Parameter:
3866bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3867d763cef2SBarry Smith 
3868d763cef2SBarry Smith    Output Parameter:
3869bcf0153eSBarry Smith .  t  - the current time. This time may not corresponds to the final time set with `TSSetMaxTime()`, use `TSGetSolveTime()`.
3870d763cef2SBarry Smith 
3871d763cef2SBarry Smith    Level: beginner
3872d763cef2SBarry Smith 
3873b8123daeSJed Brown    Note:
3874bcf0153eSBarry Smith    When called during time step evaluation (e.g. during residual evaluation or via hooks set using `TSSetPreStep()`,
3875bcf0153eSBarry Smith    `TSSetPreStage()`, `TSSetPostStage()`, or `TSSetPostStep()`), the time is the time at the start of the step being evaluated.
3876b8123daeSJed Brown 
3877bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetSolveTime()`, `TSSetTime()`, `TSGetTimeStep()`, `TSGetStepNumber()`
3878d763cef2SBarry Smith @*/
3879d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTime(TS ts, PetscReal *t)
3880d71ae5a4SJacob Faibussowitsch {
3881d763cef2SBarry Smith   PetscFunctionBegin;
38820700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3883f7cf8827SBarry Smith   PetscValidRealPointer(t, 2);
3884d763cef2SBarry Smith   *t = ts->ptime;
3885d763cef2SBarry Smith   PetscFunctionReturn(0);
3886d763cef2SBarry Smith }
3887d763cef2SBarry Smith 
3888e5e524a1SHong Zhang /*@
3889e5e524a1SHong Zhang    TSGetPrevTime - Gets the starting time of the previously completed step.
3890e5e524a1SHong Zhang 
3891e5e524a1SHong Zhang    Not Collective
3892e5e524a1SHong Zhang 
3893e5e524a1SHong Zhang    Input Parameter:
3894bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
3895e5e524a1SHong Zhang 
3896e5e524a1SHong Zhang    Output Parameter:
3897e5e524a1SHong Zhang .  t  - the previous time
3898e5e524a1SHong Zhang 
3899e5e524a1SHong Zhang    Level: beginner
3900e5e524a1SHong Zhang 
3901bcf0153eSBarry Smith .seealso: [](chapter_ts), TS`, ``TSGetTime()`, `TSGetSolveTime()`, `TSGetTimeStep()`
3902e5e524a1SHong Zhang @*/
3903d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetPrevTime(TS ts, PetscReal *t)
3904d71ae5a4SJacob Faibussowitsch {
3905e5e524a1SHong Zhang   PetscFunctionBegin;
3906e5e524a1SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3907e5e524a1SHong Zhang   PetscValidRealPointer(t, 2);
3908e5e524a1SHong Zhang   *t = ts->ptime_prev;
3909e5e524a1SHong Zhang   PetscFunctionReturn(0);
3910e5e524a1SHong Zhang }
3911e5e524a1SHong Zhang 
39126a4d4014SLisandro Dalcin /*@
39136a4d4014SLisandro Dalcin    TSSetTime - Allows one to reset the time.
39146a4d4014SLisandro Dalcin 
3915c3339decSBarry Smith    Logically Collective
39166a4d4014SLisandro Dalcin 
39176a4d4014SLisandro Dalcin    Input Parameters:
3918bcf0153eSBarry Smith +  ts - the `TS` context obtained from `TSCreate()`
39196a4d4014SLisandro Dalcin -  time - the time
39206a4d4014SLisandro Dalcin 
39216a4d4014SLisandro Dalcin    Level: intermediate
39226a4d4014SLisandro Dalcin 
3923bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTime()`, `TSSetMaxSteps()`
39246a4d4014SLisandro Dalcin @*/
3925d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTime(TS ts, PetscReal t)
3926d71ae5a4SJacob Faibussowitsch {
39276a4d4014SLisandro Dalcin   PetscFunctionBegin;
39280700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
3929c5eb9154SBarry Smith   PetscValidLogicalCollectiveReal(ts, t, 2);
39306a4d4014SLisandro Dalcin   ts->ptime = t;
39316a4d4014SLisandro Dalcin   PetscFunctionReturn(0);
39326a4d4014SLisandro Dalcin }
39336a4d4014SLisandro Dalcin 
3934d763cef2SBarry Smith /*@C
3935d763cef2SBarry Smith    TSSetOptionsPrefix - Sets the prefix used for searching for all
3936d763cef2SBarry Smith    TS options in the database.
3937d763cef2SBarry Smith 
3938c3339decSBarry Smith    Logically Collective
3939d763cef2SBarry Smith 
3940d8d19677SJose E. Roman    Input Parameters:
3941bcf0153eSBarry Smith +  ts     - The `TS` context
3942d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3943d763cef2SBarry Smith 
3944bcf0153eSBarry Smith    Level: advanced
3945bcf0153eSBarry Smith 
3946bcf0153eSBarry Smith    Note:
3947d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3948d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3949d763cef2SBarry Smith    hyphen.
3950d763cef2SBarry Smith 
3951bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFromOptions()`, `TSAppendOptionsPrefix()`
3952d763cef2SBarry Smith @*/
3953d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetOptionsPrefix(TS ts, const char prefix[])
3954d71ae5a4SJacob Faibussowitsch {
3955089b2837SJed Brown   SNES snes;
3956d763cef2SBarry Smith 
3957d763cef2SBarry Smith   PetscFunctionBegin;
39580700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39599566063dSJacob Faibussowitsch   PetscCall(PetscObjectSetOptionsPrefix((PetscObject)ts, prefix));
39609566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
39619566063dSJacob Faibussowitsch   PetscCall(SNESSetOptionsPrefix(snes, prefix));
3962d763cef2SBarry Smith   PetscFunctionReturn(0);
3963d763cef2SBarry Smith }
3964d763cef2SBarry Smith 
3965d763cef2SBarry Smith /*@C
3966d763cef2SBarry Smith    TSAppendOptionsPrefix - Appends to the prefix used for searching for all
3967d763cef2SBarry Smith    TS options in the database.
3968d763cef2SBarry Smith 
3969c3339decSBarry Smith    Logically Collective
3970d763cef2SBarry Smith 
3971d8d19677SJose E. Roman    Input Parameters:
3972bcf0153eSBarry Smith +  ts     - The `TS` context
3973d763cef2SBarry Smith -  prefix - The prefix to prepend to all option names
3974d763cef2SBarry Smith 
3975bcf0153eSBarry Smith    Level: advanced
3976bcf0153eSBarry Smith 
3977bcf0153eSBarry Smith    Note:
3978d763cef2SBarry Smith    A hyphen (-) must NOT be given at the beginning of the prefix name.
3979d763cef2SBarry Smith    The first character of all runtime options is AUTOMATICALLY the
3980d763cef2SBarry Smith    hyphen.
3981d763cef2SBarry Smith 
3982bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetOptionsPrefix()`, `TSSetOptionsPrefix()`, `TSSetFromOptions()`
3983d763cef2SBarry Smith @*/
3984d71ae5a4SJacob Faibussowitsch PetscErrorCode TSAppendOptionsPrefix(TS ts, const char prefix[])
3985d71ae5a4SJacob Faibussowitsch {
3986089b2837SJed Brown   SNES snes;
3987d763cef2SBarry Smith 
3988d763cef2SBarry Smith   PetscFunctionBegin;
39890700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
39909566063dSJacob Faibussowitsch   PetscCall(PetscObjectAppendOptionsPrefix((PetscObject)ts, prefix));
39919566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
39929566063dSJacob Faibussowitsch   PetscCall(SNESAppendOptionsPrefix(snes, prefix));
3993d763cef2SBarry Smith   PetscFunctionReturn(0);
3994d763cef2SBarry Smith }
3995d763cef2SBarry Smith 
3996d763cef2SBarry Smith /*@C
3997d763cef2SBarry Smith    TSGetOptionsPrefix - Sets the prefix used for searching for all
3998bcf0153eSBarry Smith    `TS` options in the database.
3999d763cef2SBarry Smith 
4000d763cef2SBarry Smith    Not Collective
4001d763cef2SBarry Smith 
4002d763cef2SBarry Smith    Input Parameter:
4003bcf0153eSBarry Smith .  ts - The `TS` context
4004d763cef2SBarry Smith 
4005d763cef2SBarry Smith    Output Parameter:
4006d763cef2SBarry Smith .  prefix - A pointer to the prefix string used
4007d763cef2SBarry Smith 
4008d763cef2SBarry Smith    Level: intermediate
4009d763cef2SBarry Smith 
4010bcf0153eSBarry Smith    Fortran Note:
4011bcf0153eSBarry Smith    On the fortran side, the user should pass in a string 'prefix' of
4012bcf0153eSBarry Smith    sufficient length to hold the prefix.
4013bcf0153eSBarry Smith 
4014bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAppendOptionsPrefix()`, `TSSetFromOptions()`
4015d763cef2SBarry Smith @*/
4016d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetOptionsPrefix(TS ts, const char *prefix[])
4017d71ae5a4SJacob Faibussowitsch {
4018d763cef2SBarry Smith   PetscFunctionBegin;
40190700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
40204482741eSBarry Smith   PetscValidPointer(prefix, 2);
40219566063dSJacob Faibussowitsch   PetscCall(PetscObjectGetOptionsPrefix((PetscObject)ts, prefix));
4022d763cef2SBarry Smith   PetscFunctionReturn(0);
4023d763cef2SBarry Smith }
4024d763cef2SBarry Smith 
4025d763cef2SBarry Smith /*@C
4026d763cef2SBarry Smith    TSGetRHSJacobian - Returns the Jacobian J at the present timestep.
4027d763cef2SBarry Smith 
4028bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
4029d763cef2SBarry Smith 
4030d763cef2SBarry Smith    Input Parameter:
4031bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
4032d763cef2SBarry Smith 
4033d763cef2SBarry Smith    Output Parameters:
4034e4357dc4SBarry Smith +  Amat - The (approximate) Jacobian J of G, where U_t = G(U,t)  (or NULL)
4035e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, usually the same as Amat  (or NULL)
4036e4357dc4SBarry Smith .  func - Function to compute the Jacobian of the RHS  (or NULL)
4037e4357dc4SBarry Smith -  ctx - User-defined context for Jacobian evaluation routine  (or NULL)
4038d763cef2SBarry Smith 
4039d763cef2SBarry Smith    Level: intermediate
4040d763cef2SBarry Smith 
4041bcf0153eSBarry Smith    Note:
4042bcf0153eSBarry Smith     You can pass in NULL for any return argument you do not need.
4043bcf0153eSBarry Smith 
4044bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
4045d763cef2SBarry Smith 
4046d763cef2SBarry Smith @*/
4047d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetRHSJacobian(TS ts, Mat *Amat, Mat *Pmat, TSRHSJacobian *func, void **ctx)
4048d71ae5a4SJacob Faibussowitsch {
404924989b8cSPeter Brune   DM dm;
4050089b2837SJed Brown 
4051d763cef2SBarry Smith   PetscFunctionBegin;
405223a57915SBarry Smith   if (Amat || Pmat) {
405323a57915SBarry Smith     SNES snes;
40549566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
40559566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40569566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
405723a57915SBarry Smith   }
40589566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
40599566063dSJacob Faibussowitsch   PetscCall(DMTSGetRHSJacobian(dm, func, ctx));
4060d763cef2SBarry Smith   PetscFunctionReturn(0);
4061d763cef2SBarry Smith }
4062d763cef2SBarry Smith 
40632eca1d9cSJed Brown /*@C
40642eca1d9cSJed Brown    TSGetIJacobian - Returns the implicit Jacobian at the present timestep.
40652eca1d9cSJed Brown 
4066bcf0153eSBarry Smith    Not Collective, but parallel objects are returned if ts is parallel
40672eca1d9cSJed Brown 
40682eca1d9cSJed Brown    Input Parameter:
4069bcf0153eSBarry Smith .  ts  - The `TS` context obtained from `TSCreate()`
40702eca1d9cSJed Brown 
40712eca1d9cSJed Brown    Output Parameters:
4072e4357dc4SBarry Smith +  Amat  - The (approximate) Jacobian of F(t,U,U_t)
4073e4357dc4SBarry Smith .  Pmat - The matrix from which the preconditioner is constructed, often the same as Amat
40742eca1d9cSJed Brown .  f   - The function to compute the matrices
40752eca1d9cSJed Brown - ctx - User-defined context for Jacobian evaluation routine
40762eca1d9cSJed Brown 
40772eca1d9cSJed Brown    Level: advanced
40782eca1d9cSJed Brown 
4079bcf0153eSBarry Smith    Note:
4080bcf0153eSBarry Smith     You can pass in NULL for any return argument you do not need.
4081bcf0153eSBarry Smith 
4082bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeStep()`, `TSGetRHSJacobian()`, `TSGetMatrices()`, `TSGetTime()`, `TSGetStepNumber()`
40832eca1d9cSJed Brown 
40842eca1d9cSJed Brown @*/
4085d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetIJacobian(TS ts, Mat *Amat, Mat *Pmat, TSIJacobian *f, void **ctx)
4086d71ae5a4SJacob Faibussowitsch {
408724989b8cSPeter Brune   DM dm;
40880910c330SBarry Smith 
40892eca1d9cSJed Brown   PetscFunctionBegin;
4090c0aab802Sstefano_zampini   if (Amat || Pmat) {
4091c0aab802Sstefano_zampini     SNES snes;
40929566063dSJacob Faibussowitsch     PetscCall(TSGetSNES(ts, &snes));
40939566063dSJacob Faibussowitsch     PetscCall(SNESSetUpMatrices(snes));
40949566063dSJacob Faibussowitsch     PetscCall(SNESGetJacobian(snes, Amat, Pmat, NULL, NULL));
4095c0aab802Sstefano_zampini   }
40969566063dSJacob Faibussowitsch   PetscCall(TSGetDM(ts, &dm));
40979566063dSJacob Faibussowitsch   PetscCall(DMTSGetIJacobian(dm, f, ctx));
40982eca1d9cSJed Brown   PetscFunctionReturn(0);
40992eca1d9cSJed Brown }
41002eca1d9cSJed Brown 
4101af0996ceSBarry Smith #include <petsc/private/dmimpl.h>
41026c699258SBarry Smith /*@
4103bcf0153eSBarry Smith    TSSetDM - Sets the `DM` that may be used by some nonlinear solvers or preconditioners under the `TS`
41046c699258SBarry Smith 
4105c3339decSBarry Smith    Logically Collective
41066c699258SBarry Smith 
41076c699258SBarry Smith    Input Parameters:
4108bcf0153eSBarry Smith +  ts - the `TS` integrator object
41092a808120SBarry Smith -  dm - the dm, cannot be NULL
41106c699258SBarry Smith 
41116c699258SBarry Smith    Level: intermediate
41126c699258SBarry Smith 
4113bcf0153eSBarry Smith    Notes:
4114bcf0153eSBarry Smith    A `DM` can only be used for solving one problem at a time because information about the problem is stored on the `DM`,
4115bcf0153eSBarry Smith    even when not using interfaces like `DMTSSetIFunction()`.  Use `DMClone()` to get a distinct `DM` when solving
4116bcf0153eSBarry Smith    different problems using the same function space.
4117bcf0153eSBarry Smith 
4118bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSGetDM()`, `SNESSetDM()`, `SNESGetDM()`
41196c699258SBarry Smith @*/
4120d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetDM(TS ts, DM dm)
4121d71ae5a4SJacob Faibussowitsch {
4122089b2837SJed Brown   SNES snes;
4123942e3340SBarry Smith   DMTS tsdm;
41246c699258SBarry Smith 
41256c699258SBarry Smith   PetscFunctionBegin;
41260700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
41272a808120SBarry Smith   PetscValidHeaderSpecific(dm, DM_CLASSID, 2);
41289566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)dm));
4129942e3340SBarry Smith   if (ts->dm) { /* Move the DMTS context over to the new DM unless the new DM already has one */
41302a34c10cSBarry Smith     if (ts->dm->dmts && !dm->dmts) {
41319566063dSJacob Faibussowitsch       PetscCall(DMCopyDMTS(ts->dm, dm));
41329566063dSJacob Faibussowitsch       PetscCall(DMGetDMTS(ts->dm, &tsdm));
41331e66621cSBarry Smith       /* Grant write privileges to the replacement DM */
41341e66621cSBarry Smith       if (tsdm->originaldm == ts->dm) tsdm->originaldm = dm;
413524989b8cSPeter Brune     }
41369566063dSJacob Faibussowitsch     PetscCall(DMDestroy(&ts->dm));
413724989b8cSPeter Brune   }
41386c699258SBarry Smith   ts->dm = dm;
4139bbd56ea5SKarl Rupp 
41409566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
41419566063dSJacob Faibussowitsch   PetscCall(SNESSetDM(snes, dm));
41426c699258SBarry Smith   PetscFunctionReturn(0);
41436c699258SBarry Smith }
41446c699258SBarry Smith 
41456c699258SBarry Smith /*@
4146bcf0153eSBarry Smith    TSGetDM - Gets the `DM` that may be used by some preconditioners
41476c699258SBarry Smith 
41483f9fe445SBarry Smith    Not Collective
41496c699258SBarry Smith 
41506c699258SBarry Smith    Input Parameter:
4151bcf0153eSBarry Smith . ts - the `TS`
41526c699258SBarry Smith 
41536c699258SBarry Smith    Output Parameter:
41546c699258SBarry Smith .  dm - the dm
41556c699258SBarry Smith 
41566c699258SBarry Smith    Level: intermediate
41576c699258SBarry Smith 
4158bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `DM`, `TSSetDM()`, `SNESSetDM()`, `SNESGetDM()`
41596c699258SBarry Smith @*/
4160d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetDM(TS ts, DM *dm)
4161d71ae5a4SJacob Faibussowitsch {
41626c699258SBarry Smith   PetscFunctionBegin;
41630700a824SBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4164496e6a7aSJed Brown   if (!ts->dm) {
41659566063dSJacob Faibussowitsch     PetscCall(DMShellCreate(PetscObjectComm((PetscObject)ts), &ts->dm));
41669566063dSJacob Faibussowitsch     if (ts->snes) PetscCall(SNESSetDM(ts->snes, ts->dm));
4167496e6a7aSJed Brown   }
41686c699258SBarry Smith   *dm = ts->dm;
41696c699258SBarry Smith   PetscFunctionReturn(0);
41706c699258SBarry Smith }
41711713a123SBarry Smith 
41720f5c6efeSJed Brown /*@
41730f5c6efeSJed Brown    SNESTSFormFunction - Function to evaluate nonlinear residual
41740f5c6efeSJed Brown 
4175c3339decSBarry Smith    Logically Collective
41760f5c6efeSJed Brown 
4177d8d19677SJose E. Roman    Input Parameters:
4178d42a1c89SJed Brown + snes - nonlinear solver
41790910c330SBarry Smith . U - the current state at which to evaluate the residual
4180d42a1c89SJed Brown - ctx - user context, must be a TS
41810f5c6efeSJed Brown 
41820f5c6efeSJed Brown    Output Parameter:
41830f5c6efeSJed Brown . F - the nonlinear residual
41840f5c6efeSJed Brown 
41850f5c6efeSJed Brown    Level: advanced
41860f5c6efeSJed Brown 
4187bcf0153eSBarry Smith    Note:
4188bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4189bcf0153eSBarry Smith    It is most frequently passed to `MatFDColoringSetFunction()`.
4190bcf0153eSBarry Smith 
4191bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetFunction()`, `MatFDColoringSetFunction()`
41920f5c6efeSJed Brown @*/
4193d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormFunction(SNES snes, Vec U, Vec F, void *ctx)
4194d71ae5a4SJacob Faibussowitsch {
41950f5c6efeSJed Brown   TS ts = (TS)ctx;
41960f5c6efeSJed Brown 
41970f5c6efeSJed Brown   PetscFunctionBegin;
41980f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
41990910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42000f5c6efeSJed Brown   PetscValidHeaderSpecific(F, VEC_CLASSID, 3);
42010f5c6efeSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 4);
42029566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesfunction)(snes, U, F, ts));
42030f5c6efeSJed Brown   PetscFunctionReturn(0);
42040f5c6efeSJed Brown }
42050f5c6efeSJed Brown 
42060f5c6efeSJed Brown /*@
42070f5c6efeSJed Brown    SNESTSFormJacobian - Function to evaluate the Jacobian
42080f5c6efeSJed Brown 
4209c3339decSBarry Smith    Collective
42100f5c6efeSJed Brown 
4211d8d19677SJose E. Roman    Input Parameters:
42120f5c6efeSJed Brown + snes - nonlinear solver
42130910c330SBarry Smith . U - the current state at which to evaluate the residual
4214bcf0153eSBarry Smith - ctx - user context, must be a `TS`
42150f5c6efeSJed Brown 
4216d8d19677SJose E. Roman    Output Parameters:
42170f5c6efeSJed Brown + A - the Jacobian
42186b867d5aSJose E. Roman - B - the preconditioning matrix (may be the same as A)
42190f5c6efeSJed Brown 
42200f5c6efeSJed Brown    Level: developer
42210f5c6efeSJed Brown 
4222bcf0153eSBarry Smith    Note:
4223bcf0153eSBarry Smith    This function is not normally called by users and is automatically registered with the `SNES` used by `TS`.
4224bcf0153eSBarry Smith 
4225bcf0153eSBarry Smith .seealso: [](chapter_ts), `SNESSetJacobian()`
42260f5c6efeSJed Brown @*/
4227d71ae5a4SJacob Faibussowitsch PetscErrorCode SNESTSFormJacobian(SNES snes, Vec U, Mat A, Mat B, void *ctx)
4228d71ae5a4SJacob Faibussowitsch {
42290f5c6efeSJed Brown   TS ts = (TS)ctx;
42300f5c6efeSJed Brown 
42310f5c6efeSJed Brown   PetscFunctionBegin;
42320f5c6efeSJed Brown   PetscValidHeaderSpecific(snes, SNES_CLASSID, 1);
42330910c330SBarry Smith   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
42340f5c6efeSJed Brown   PetscValidPointer(A, 3);
423594ab13aaSBarry Smith   PetscValidHeaderSpecific(A, MAT_CLASSID, 3);
42360f5c6efeSJed Brown   PetscValidPointer(B, 4);
423794ab13aaSBarry Smith   PetscValidHeaderSpecific(B, MAT_CLASSID, 4);
4238064a246eSJacob Faibussowitsch   PetscValidHeaderSpecific(ts, TS_CLASSID, 5);
42399566063dSJacob Faibussowitsch   PetscCall((ts->ops->snesjacobian)(snes, U, A, B, ts));
42400f5c6efeSJed Brown   PetscFunctionReturn(0);
42410f5c6efeSJed Brown }
4242325fc9f4SBarry Smith 
42430e4ef248SJed Brown /*@C
42449ae8fd06SBarry Smith    TSComputeRHSFunctionLinear - Evaluate the right hand side via the user-provided Jacobian, for linear problems Udot = A U only
42450e4ef248SJed Brown 
4246c3339decSBarry Smith    Collective
42470e4ef248SJed Brown 
42484165533cSJose E. Roman    Input Parameters:
42490e4ef248SJed Brown +  ts - time stepping context
42500e4ef248SJed Brown .  t - time at which to evaluate
42510910c330SBarry Smith .  U - state at which to evaluate
42520e4ef248SJed Brown -  ctx - context
42530e4ef248SJed Brown 
42544165533cSJose E. Roman    Output Parameter:
42550e4ef248SJed Brown .  F - right hand side
42560e4ef248SJed Brown 
42570e4ef248SJed Brown    Level: intermediate
42580e4ef248SJed Brown 
4259bcf0153eSBarry Smith    Note:
4260bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSFunction()` to evaluate the right hand side for linear problems.
4261bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetRHSJacobian()`.
42620e4ef248SJed Brown 
4263bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSJacobianConstant()`
42640e4ef248SJed Brown @*/
4265d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSFunctionLinear(TS ts, PetscReal t, Vec U, Vec F, void *ctx)
4266d71ae5a4SJacob Faibussowitsch {
42670e4ef248SJed Brown   Mat Arhs, Brhs;
42680e4ef248SJed Brown 
42690e4ef248SJed Brown   PetscFunctionBegin;
42709566063dSJacob Faibussowitsch   PetscCall(TSGetRHSMats_Private(ts, &Arhs, &Brhs));
42712663174eSHong Zhang   /* undo the damage caused by shifting */
42729566063dSJacob Faibussowitsch   PetscCall(TSRecoverRHSJacobian(ts, Arhs, Brhs));
42739566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSJacobian(ts, t, U, Arhs, Brhs));
42749566063dSJacob Faibussowitsch   PetscCall(MatMult(Arhs, U, F));
42750e4ef248SJed Brown   PetscFunctionReturn(0);
42760e4ef248SJed Brown }
42770e4ef248SJed Brown 
42780e4ef248SJed Brown /*@C
42790e4ef248SJed Brown    TSComputeRHSJacobianConstant - Reuses a Jacobian that is time-independent.
42800e4ef248SJed Brown 
4281c3339decSBarry Smith    Collective
42820e4ef248SJed Brown 
42834165533cSJose E. Roman    Input Parameters:
42840e4ef248SJed Brown +  ts - time stepping context
42850e4ef248SJed Brown .  t - time at which to evaluate
42860910c330SBarry Smith .  U - state at which to evaluate
42870e4ef248SJed Brown -  ctx - context
42880e4ef248SJed Brown 
42894165533cSJose E. Roman    Output Parameters:
42900e4ef248SJed Brown +  A - pointer to operator
429197bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
42920e4ef248SJed Brown 
42930e4ef248SJed Brown    Level: intermediate
42940e4ef248SJed Brown 
4295bcf0153eSBarry Smith    Note:
4296bcf0153eSBarry Smith    This function is intended to be passed to `TSSetRHSJacobian()` to evaluate the Jacobian for linear time-independent problems.
42970e4ef248SJed Brown 
4298bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSSetRHSJacobian()`, `TSComputeRHSFunctionLinear()`
42990e4ef248SJed Brown @*/
4300d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeRHSJacobianConstant(TS ts, PetscReal t, Vec U, Mat A, Mat B, void *ctx)
4301d71ae5a4SJacob Faibussowitsch {
43020e4ef248SJed Brown   PetscFunctionBegin;
43030e4ef248SJed Brown   PetscFunctionReturn(0);
43040e4ef248SJed Brown }
43050e4ef248SJed Brown 
43060026cea9SSean Farley /*@C
43070026cea9SSean Farley    TSComputeIFunctionLinear - Evaluate the left hand side via the user-provided Jacobian, for linear problems only
43080026cea9SSean Farley 
4309c3339decSBarry Smith    Collective
43100026cea9SSean Farley 
43114165533cSJose E. Roman    Input Parameters:
43120026cea9SSean Farley +  ts - time stepping context
43130026cea9SSean Farley .  t - time at which to evaluate
43140910c330SBarry Smith .  U - state at which to evaluate
43150910c330SBarry Smith .  Udot - time derivative of state vector
43160026cea9SSean Farley -  ctx - context
43170026cea9SSean Farley 
43184165533cSJose E. Roman    Output Parameter:
43190026cea9SSean Farley .  F - left hand side
43200026cea9SSean Farley 
43210026cea9SSean Farley    Level: intermediate
43220026cea9SSean Farley 
43230026cea9SSean Farley    Notes:
43240910c330SBarry 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
4325bcf0153eSBarry Smith    user is required to write their own `TSComputeIFunction()`.
4326bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIFunction()` to evaluate the left hand side for linear problems.
4327bcf0153eSBarry Smith    The matrix (and optionally the evaluation context) should be passed to `TSSetIJacobian()`.
43280026cea9SSean Farley 
4329bcf0153eSBarry Smith    Note that using this function is NOT equivalent to using `TSComputeRHSFunctionLinear()` since that solves Udot = A U
43309ae8fd06SBarry Smith 
4331bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIJacobianConstant()`, `TSComputeRHSFunctionLinear()`
43320026cea9SSean Farley @*/
4333d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIFunctionLinear(TS ts, PetscReal t, Vec U, Vec Udot, Vec F, void *ctx)
4334d71ae5a4SJacob Faibussowitsch {
43350026cea9SSean Farley   Mat A, B;
43360026cea9SSean Farley 
43370026cea9SSean Farley   PetscFunctionBegin;
43389566063dSJacob Faibussowitsch   PetscCall(TSGetIJacobian(ts, &A, &B, NULL, NULL));
43399566063dSJacob Faibussowitsch   PetscCall(TSComputeIJacobian(ts, t, U, Udot, 1.0, A, B, PETSC_TRUE));
43409566063dSJacob Faibussowitsch   PetscCall(MatMult(A, Udot, F));
43410026cea9SSean Farley   PetscFunctionReturn(0);
43420026cea9SSean Farley }
43430026cea9SSean Farley 
43440026cea9SSean Farley /*@C
4345b41af12eSJed Brown    TSComputeIJacobianConstant - Reuses a time-independent for a semi-implicit DAE or ODE
43460026cea9SSean Farley 
4347c3339decSBarry Smith    Collective
43480026cea9SSean Farley 
43494165533cSJose E. Roman    Input Parameters:
43500026cea9SSean Farley +  ts - time stepping context
43510026cea9SSean Farley .  t - time at which to evaluate
43520910c330SBarry Smith .  U - state at which to evaluate
43530910c330SBarry Smith .  Udot - time derivative of state vector
43540026cea9SSean Farley .  shift - shift to apply
43550026cea9SSean Farley -  ctx - context
43560026cea9SSean Farley 
43574165533cSJose E. Roman    Output Parameters:
43580026cea9SSean Farley +  A - pointer to operator
435997bb3fdcSJose E. Roman -  B - pointer to preconditioning matrix
43600026cea9SSean Farley 
4361b41af12eSJed Brown    Level: advanced
43620026cea9SSean Farley 
43630026cea9SSean Farley    Notes:
4364bcf0153eSBarry Smith    This function is intended to be passed to `TSSetIJacobian()` to evaluate the Jacobian for linear time-independent problems.
43650026cea9SSean Farley 
4366b41af12eSJed Brown    It is only appropriate for problems of the form
4367b41af12eSJed Brown 
4368b41af12eSJed Brown $     M Udot = F(U,t)
4369b41af12eSJed Brown 
4370bcf0153eSBarry Smith   where M is constant and F is non-stiff.  The user must pass M to `TSSetIJacobian()`.  The current implementation only
4371bcf0153eSBarry Smith   works with IMEX time integration methods such as `TSROSW` and `TSARKIMEX`, since there is no support for de-constructing
4372b41af12eSJed Brown   an implicit operator of the form
4373b41af12eSJed Brown 
4374b41af12eSJed Brown $    shift*M + J
4375b41af12eSJed Brown 
4376b41af12eSJed 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
4377b41af12eSJed Brown   a copy of M or reassemble it when requested.
4378b41af12eSJed Brown 
4379bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSROSW`, `TSARKIMEX`, `TSSetIFunction()`, `TSSetIJacobian()`, `TSComputeIFunctionLinear()`
43800026cea9SSean Farley @*/
4381d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianConstant(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat A, Mat B, void *ctx)
4382d71ae5a4SJacob Faibussowitsch {
43830026cea9SSean Farley   PetscFunctionBegin;
43849566063dSJacob Faibussowitsch   PetscCall(MatScale(A, shift / ts->ijacobian.shift));
4385b41af12eSJed Brown   ts->ijacobian.shift = shift;
43860026cea9SSean Farley   PetscFunctionReturn(0);
43870026cea9SSean Farley }
4388b41af12eSJed Brown 
4389e817cc15SEmil Constantinescu /*@
4390bcf0153eSBarry Smith    TSGetEquationType - Gets the type of the equation that `TS` is solving.
4391e817cc15SEmil Constantinescu 
4392e817cc15SEmil Constantinescu    Not Collective
4393e817cc15SEmil Constantinescu 
4394e817cc15SEmil Constantinescu    Input Parameter:
4395bcf0153eSBarry Smith .  ts - the `TS` context
4396e817cc15SEmil Constantinescu 
4397e817cc15SEmil Constantinescu    Output Parameter:
4398bcf0153eSBarry Smith .  equation_type - see `TSEquationType`
4399e817cc15SEmil Constantinescu 
4400e817cc15SEmil Constantinescu    Level: beginner
4401e817cc15SEmil Constantinescu 
4402bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetEquationType()`, `TSEquationType`
4403e817cc15SEmil Constantinescu @*/
4404d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetEquationType(TS ts, TSEquationType *equation_type)
4405d71ae5a4SJacob Faibussowitsch {
4406e817cc15SEmil Constantinescu   PetscFunctionBegin;
4407e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4408e817cc15SEmil Constantinescu   PetscValidPointer(equation_type, 2);
4409e817cc15SEmil Constantinescu   *equation_type = ts->equation_type;
4410e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4411e817cc15SEmil Constantinescu }
4412e817cc15SEmil Constantinescu 
4413e817cc15SEmil Constantinescu /*@
4414bcf0153eSBarry Smith    TSSetEquationType - Sets the type of the equation that `TS` is solving.
4415e817cc15SEmil Constantinescu 
4416e817cc15SEmil Constantinescu    Not Collective
4417e817cc15SEmil Constantinescu 
4418d8d19677SJose E. Roman    Input Parameters:
4419bcf0153eSBarry Smith +  ts - the `TS` context
4420bcf0153eSBarry Smith -  equation_type - see `TSEquationType`
4421e817cc15SEmil Constantinescu 
4422e817cc15SEmil Constantinescu    Level: advanced
4423e817cc15SEmil Constantinescu 
4424bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetEquationType()`, `TSEquationType`
4425e817cc15SEmil Constantinescu @*/
4426d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetEquationType(TS ts, TSEquationType equation_type)
4427d71ae5a4SJacob Faibussowitsch {
4428e817cc15SEmil Constantinescu   PetscFunctionBegin;
4429e817cc15SEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4430e817cc15SEmil Constantinescu   ts->equation_type = equation_type;
4431e817cc15SEmil Constantinescu   PetscFunctionReturn(0);
4432e817cc15SEmil Constantinescu }
44330026cea9SSean Farley 
44344af1b03aSJed Brown /*@
4435bcf0153eSBarry Smith    TSGetConvergedReason - Gets the reason the `TS` iteration was stopped.
44364af1b03aSJed Brown 
44374af1b03aSJed Brown    Not Collective
44384af1b03aSJed Brown 
44394af1b03aSJed Brown    Input Parameter:
4440bcf0153eSBarry Smith .  ts - the `TS` context
44414af1b03aSJed Brown 
44424af1b03aSJed Brown    Output Parameter:
4443bcf0153eSBarry Smith .  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
44444af1b03aSJed Brown             manual pages for the individual convergence tests for complete lists
44454af1b03aSJed Brown 
4446487e0bb9SJed Brown    Level: beginner
44474af1b03aSJed Brown 
4448bcf0153eSBarry Smith    Note:
4449bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
44504af1b03aSJed Brown 
4451bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
44524af1b03aSJed Brown @*/
4453d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetConvergedReason(TS ts, TSConvergedReason *reason)
4454d71ae5a4SJacob Faibussowitsch {
44554af1b03aSJed Brown   PetscFunctionBegin;
44564af1b03aSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
44574af1b03aSJed Brown   PetscValidPointer(reason, 2);
44584af1b03aSJed Brown   *reason = ts->reason;
44594af1b03aSJed Brown   PetscFunctionReturn(0);
44604af1b03aSJed Brown }
44614af1b03aSJed Brown 
4462d6ad946cSShri Abhyankar /*@
4463bcf0153eSBarry Smith    TSSetConvergedReason - Sets the reason for handling the convergence of `TSSolve()`.
4464d6ad946cSShri Abhyankar 
44656b221cbeSPatrick Sanan    Logically Collective; reason must contain common value
4466d6ad946cSShri Abhyankar 
44676b221cbeSPatrick Sanan    Input Parameters:
4468bcf0153eSBarry Smith +  ts - the `TS` context
4469bcf0153eSBarry Smith -  reason - negative value indicates diverged, positive value converged, see `TSConvergedReason` or the
4470d6ad946cSShri Abhyankar             manual pages for the individual convergence tests for complete lists
4471d6ad946cSShri Abhyankar 
4472f5abba47SShri Abhyankar    Level: advanced
4473d6ad946cSShri Abhyankar 
4474bcf0153eSBarry Smith    Note:
4475bcf0153eSBarry Smith    Can only be called while `TSSolve()` is active.
4476d6ad946cSShri Abhyankar 
4477bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSConvergedReason`
4478d6ad946cSShri Abhyankar @*/
4479d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetConvergedReason(TS ts, TSConvergedReason reason)
4480d71ae5a4SJacob Faibussowitsch {
4481d6ad946cSShri Abhyankar   PetscFunctionBegin;
4482d6ad946cSShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4483d6ad946cSShri Abhyankar   ts->reason = reason;
4484d6ad946cSShri Abhyankar   PetscFunctionReturn(0);
4485d6ad946cSShri Abhyankar }
4486d6ad946cSShri Abhyankar 
4487cc708dedSBarry Smith /*@
4488bcf0153eSBarry Smith    TSGetSolveTime - Gets the time after a call to `TSSolve()`
4489cc708dedSBarry Smith 
4490cc708dedSBarry Smith    Not Collective
4491cc708dedSBarry Smith 
4492cc708dedSBarry Smith    Input Parameter:
4493bcf0153eSBarry Smith .  ts - the `TS` context
4494cc708dedSBarry Smith 
4495cc708dedSBarry Smith    Output Parameter:
4496bcf0153eSBarry Smith .  ftime - the final time. This time corresponds to the final time set with `TSSetMaxTime()`
4497cc708dedSBarry Smith 
4498487e0bb9SJed Brown    Level: beginner
4499cc708dedSBarry Smith 
4500bcf0153eSBarry Smith    Note:
4501bcf0153eSBarry Smith    Can only be called after the call to `TSSolve()` is complete.
4502cc708dedSBarry Smith 
4503bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSSetConvergenceTest()`, `TSConvergedReason`
4504cc708dedSBarry Smith @*/
4505d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSolveTime(TS ts, PetscReal *ftime)
4506d71ae5a4SJacob Faibussowitsch {
4507cc708dedSBarry Smith   PetscFunctionBegin;
4508cc708dedSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4509dadcf809SJacob Faibussowitsch   PetscValidRealPointer(ftime, 2);
4510cc708dedSBarry Smith   *ftime = ts->solvetime;
4511cc708dedSBarry Smith   PetscFunctionReturn(0);
4512cc708dedSBarry Smith }
4513cc708dedSBarry Smith 
45142c18e0fdSBarry Smith /*@
45155ef26d82SJed Brown    TSGetSNESIterations - Gets the total number of nonlinear iterations
45169f67acb7SJed Brown    used by the time integrator.
45179f67acb7SJed Brown 
45189f67acb7SJed Brown    Not Collective
45199f67acb7SJed Brown 
45209f67acb7SJed Brown    Input Parameter:
4521bcf0153eSBarry Smith .  ts - `TS` context
45229f67acb7SJed Brown 
45239f67acb7SJed Brown    Output Parameter:
45249f67acb7SJed Brown .  nits - number of nonlinear iterations
45259f67acb7SJed Brown 
45269f67acb7SJed Brown    Level: intermediate
45279f67acb7SJed Brown 
4528bcf0153eSBarry Smith    Notes:
4529bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4530bcf0153eSBarry Smith 
4531bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetKSPIterations()`
45329f67acb7SJed Brown @*/
4533d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESIterations(TS ts, PetscInt *nits)
4534d71ae5a4SJacob Faibussowitsch {
45359f67acb7SJed Brown   PetscFunctionBegin;
45369f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45379f67acb7SJed Brown   PetscValidIntPointer(nits, 2);
45385ef26d82SJed Brown   *nits = ts->snes_its;
45399f67acb7SJed Brown   PetscFunctionReturn(0);
45409f67acb7SJed Brown }
45419f67acb7SJed Brown 
45429f67acb7SJed Brown /*@
45435ef26d82SJed Brown    TSGetKSPIterations - Gets the total number of linear iterations
45449f67acb7SJed Brown    used by the time integrator.
45459f67acb7SJed Brown 
45469f67acb7SJed Brown    Not Collective
45479f67acb7SJed Brown 
45489f67acb7SJed Brown    Input Parameter:
4549bcf0153eSBarry Smith .  ts - `TS` context
45509f67acb7SJed Brown 
45519f67acb7SJed Brown    Output Parameter:
45529f67acb7SJed Brown .  lits - number of linear iterations
45539f67acb7SJed Brown 
45549f67acb7SJed Brown    Level: intermediate
45559f67acb7SJed Brown 
4556bcf0153eSBarry Smith    Note:
4557bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4558bcf0153eSBarry Smith 
4559bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `SNESGetKSPIterations()`
45609f67acb7SJed Brown @*/
4561d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetKSPIterations(TS ts, PetscInt *lits)
4562d71ae5a4SJacob Faibussowitsch {
45639f67acb7SJed Brown   PetscFunctionBegin;
45649f67acb7SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
45659f67acb7SJed Brown   PetscValidIntPointer(lits, 2);
45665ef26d82SJed Brown   *lits = ts->ksp_its;
45679f67acb7SJed Brown   PetscFunctionReturn(0);
45689f67acb7SJed Brown }
45699f67acb7SJed Brown 
4570cef5090cSJed Brown /*@
4571cef5090cSJed Brown    TSGetStepRejections - Gets the total number of rejected steps.
4572cef5090cSJed Brown 
4573cef5090cSJed Brown    Not Collective
4574cef5090cSJed Brown 
4575cef5090cSJed Brown    Input Parameter:
4576bcf0153eSBarry Smith .  ts - `TS` context
4577cef5090cSJed Brown 
4578cef5090cSJed Brown    Output Parameter:
4579cef5090cSJed Brown .  rejects - number of steps rejected
4580cef5090cSJed Brown 
4581cef5090cSJed Brown    Level: intermediate
4582cef5090cSJed Brown 
4583bcf0153eSBarry Smith    Note:
4584bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4585bcf0153eSBarry Smith 
4586bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetSNESFailures()`, `TSSetMaxSNESFailures()`, `TSSetErrorIfStepFails()`
4587cef5090cSJed Brown @*/
4588d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStepRejections(TS ts, PetscInt *rejects)
4589d71ae5a4SJacob Faibussowitsch {
4590cef5090cSJed Brown   PetscFunctionBegin;
4591cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4592cef5090cSJed Brown   PetscValidIntPointer(rejects, 2);
4593cef5090cSJed Brown   *rejects = ts->reject;
4594cef5090cSJed Brown   PetscFunctionReturn(0);
4595cef5090cSJed Brown }
4596cef5090cSJed Brown 
4597cef5090cSJed Brown /*@
4598bcf0153eSBarry Smith    TSGetSNESFailures - Gets the total number of failed `SNES` solves in a `TS`
4599cef5090cSJed Brown 
4600cef5090cSJed Brown    Not Collective
4601cef5090cSJed Brown 
4602cef5090cSJed Brown    Input Parameter:
4603bcf0153eSBarry Smith .  ts - `TS` context
4604cef5090cSJed Brown 
4605cef5090cSJed Brown    Output Parameter:
4606cef5090cSJed Brown .  fails - number of failed nonlinear solves
4607cef5090cSJed Brown 
4608cef5090cSJed Brown    Level: intermediate
4609cef5090cSJed Brown 
4610bcf0153eSBarry Smith    Note:
4611bcf0153eSBarry Smith    This counter is reset to zero for each successive call to `TSSolve()`.
4612bcf0153eSBarry Smith 
4613bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSolve()`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSSetMaxSNESFailures()`
4614cef5090cSJed Brown @*/
4615d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetSNESFailures(TS ts, PetscInt *fails)
4616d71ae5a4SJacob Faibussowitsch {
4617cef5090cSJed Brown   PetscFunctionBegin;
4618cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4619cef5090cSJed Brown   PetscValidIntPointer(fails, 2);
4620cef5090cSJed Brown   *fails = ts->num_snes_failures;
4621cef5090cSJed Brown   PetscFunctionReturn(0);
4622cef5090cSJed Brown }
4623cef5090cSJed Brown 
4624cef5090cSJed Brown /*@
4625bcf0153eSBarry Smith    TSSetMaxStepRejections - Sets the maximum number of step rejections before a time step fails
4626cef5090cSJed Brown 
4627cef5090cSJed Brown    Not Collective
4628cef5090cSJed Brown 
4629d8d19677SJose E. Roman    Input Parameters:
4630bcf0153eSBarry Smith +  ts - `TS` context
4631cef5090cSJed Brown -  rejects - maximum number of rejected steps, pass -1 for unlimited
4632cef5090cSJed Brown 
4633cef5090cSJed Brown    Options Database Key:
4634cef5090cSJed Brown .  -ts_max_reject - Maximum number of step rejections before a step fails
4635cef5090cSJed Brown 
4636cef5090cSJed Brown    Level: intermediate
4637cef5090cSJed Brown 
4638bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxSNESFailures()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4639cef5090cSJed Brown @*/
4640d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxStepRejections(TS ts, PetscInt rejects)
4641d71ae5a4SJacob Faibussowitsch {
4642cef5090cSJed Brown   PetscFunctionBegin;
4643cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4644cef5090cSJed Brown   ts->max_reject = rejects;
4645cef5090cSJed Brown   PetscFunctionReturn(0);
4646cef5090cSJed Brown }
4647cef5090cSJed Brown 
4648cef5090cSJed Brown /*@
4649bcf0153eSBarry Smith    TSSetMaxSNESFailures - Sets the maximum number of failed `SNES` solves
4650cef5090cSJed Brown 
4651cef5090cSJed Brown    Not Collective
4652cef5090cSJed Brown 
4653d8d19677SJose E. Roman    Input Parameters:
4654bcf0153eSBarry Smith +  ts - `TS` context
4655cef5090cSJed Brown -  fails - maximum number of failed nonlinear solves, pass -1 for unlimited
4656cef5090cSJed Brown 
4657cef5090cSJed Brown    Options Database Key:
4658cef5090cSJed Brown .  -ts_max_snes_failures - Maximum number of nonlinear solve failures
4659cef5090cSJed Brown 
4660cef5090cSJed Brown    Level: intermediate
4661cef5090cSJed Brown 
4662bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `SNESGetConvergedReason()`, `TSGetConvergedReason()`
4663cef5090cSJed Brown @*/
4664d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMaxSNESFailures(TS ts, PetscInt fails)
4665d71ae5a4SJacob Faibussowitsch {
4666cef5090cSJed Brown   PetscFunctionBegin;
4667cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4668cef5090cSJed Brown   ts->max_snes_failures = fails;
4669cef5090cSJed Brown   PetscFunctionReturn(0);
4670cef5090cSJed Brown }
4671cef5090cSJed Brown 
4672cef5090cSJed Brown /*@
4673bcf0153eSBarry Smith    TSSetErrorIfStepFails - Immediately error if no step succeeds
4674cef5090cSJed Brown 
4675cef5090cSJed Brown    Not Collective
4676cef5090cSJed Brown 
4677d8d19677SJose E. Roman    Input Parameters:
4678bcf0153eSBarry Smith +  ts - `TS` context
4679bcf0153eSBarry Smith -  err - `PETSC_TRUE` to error if no step succeeds, `PETSC_FALSE` to return without failure
4680cef5090cSJed Brown 
4681cef5090cSJed Brown    Options Database Key:
4682cef5090cSJed Brown .  -ts_error_if_step_fails - Error if no step succeeds
4683cef5090cSJed Brown 
4684cef5090cSJed Brown    Level: intermediate
4685cef5090cSJed Brown 
4686bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetSNESIterations()`, `TSGetKSPIterations()`, `TSSetMaxStepRejections()`, `TSGetStepRejections()`, `TSGetSNESFailures()`, `TSSetErrorIfStepFails()`, `TSGetConvergedReason()`
4687cef5090cSJed Brown @*/
4688d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetErrorIfStepFails(TS ts, PetscBool err)
4689d71ae5a4SJacob Faibussowitsch {
4690cef5090cSJed Brown   PetscFunctionBegin;
4691cef5090cSJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4692cef5090cSJed Brown   ts->errorifstepfailed = err;
4693cef5090cSJed Brown   PetscFunctionReturn(0);
4694cef5090cSJed Brown }
4695cef5090cSJed Brown 
469684df9cb4SJed Brown /*@
4697552698daSJed Brown    TSGetAdapt - Get the adaptive controller context for the current method
469884df9cb4SJed Brown 
4699bcf0153eSBarry Smith    Collective on ts if controller has not been created yet
470084df9cb4SJed Brown 
47014165533cSJose E. Roman    Input Parameter:
4702ed81e22dSJed Brown .  ts - time stepping context
470384df9cb4SJed Brown 
47044165533cSJose E. Roman    Output Parameter:
4705ed81e22dSJed Brown .  adapt - adaptive controller
470684df9cb4SJed Brown 
470784df9cb4SJed Brown    Level: intermediate
470884df9cb4SJed Brown 
4709bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSAdaptSetType()`, `TSAdaptChoose()`
471084df9cb4SJed Brown @*/
4711d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetAdapt(TS ts, TSAdapt *adapt)
4712d71ae5a4SJacob Faibussowitsch {
471384df9cb4SJed Brown   PetscFunctionBegin;
471484df9cb4SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4715bec58848SLisandro Dalcin   PetscValidPointer(adapt, 2);
471684df9cb4SJed Brown   if (!ts->adapt) {
47179566063dSJacob Faibussowitsch     PetscCall(TSAdaptCreate(PetscObjectComm((PetscObject)ts), &ts->adapt));
47189566063dSJacob Faibussowitsch     PetscCall(PetscObjectIncrementTabLevel((PetscObject)ts->adapt, (PetscObject)ts, 1));
471984df9cb4SJed Brown   }
4720bec58848SLisandro Dalcin   *adapt = ts->adapt;
472184df9cb4SJed Brown   PetscFunctionReturn(0);
472284df9cb4SJed Brown }
4723d6ebe24aSShri Abhyankar 
47241c3436cfSJed Brown /*@
47251c3436cfSJed Brown    TSSetTolerances - Set tolerances for local truncation error when using adaptive controller
47261c3436cfSJed Brown 
47271c3436cfSJed Brown    Logically Collective
47281c3436cfSJed Brown 
47294165533cSJose E. Roman    Input Parameters:
47301c3436cfSJed Brown +  ts - time integration context
4731bcf0153eSBarry Smith .  atol - scalar absolute tolerances, `PETSC_DECIDE` to leave current value
47320298fd71SBarry Smith .  vatol - vector of absolute tolerances or NULL, used in preference to atol if present
4733bcf0153eSBarry Smith .  rtol - scalar relative tolerances, `PETSC_DECIDE` to leave current value
47340298fd71SBarry Smith -  vrtol - vector of relative tolerances or NULL, used in preference to atol if present
47351c3436cfSJed Brown 
4736a3cdaa26SBarry Smith    Options Database keys:
4737a3cdaa26SBarry Smith +  -ts_rtol <rtol> - relative tolerance for local truncation error
473867b8a455SSatish Balay -  -ts_atol <atol> - Absolute tolerance for local truncation error
4739a3cdaa26SBarry Smith 
4740bcf0153eSBarry Smith    Level: beginner
4741bcf0153eSBarry Smith 
47423ff766beSShri Abhyankar    Notes:
47433ff766beSShri Abhyankar    With PETSc's implicit schemes for DAE problems, the calculation of the local truncation error
47443ff766beSShri Abhyankar    (LTE) includes both the differential and the algebraic variables. If one wants the LTE to be
47453ff766beSShri Abhyankar    computed only for the differential or the algebraic part then this can be done using the vector of
47463ff766beSShri Abhyankar    tolerances vatol. For example, by setting the tolerance vector with the desired tolerance for the
47473ff766beSShri Abhyankar    differential part and infinity for the algebraic part, the LTE calculation will include only the
47483ff766beSShri Abhyankar    differential variables.
47493ff766beSShri Abhyankar 
4750bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSGetTolerances()`
47511c3436cfSJed Brown @*/
4752d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTolerances(TS ts, PetscReal atol, Vec vatol, PetscReal rtol, Vec vrtol)
4753d71ae5a4SJacob Faibussowitsch {
47541c3436cfSJed Brown   PetscFunctionBegin;
4755c5033834SJed Brown   if (atol != PETSC_DECIDE && atol != PETSC_DEFAULT) ts->atol = atol;
47561c3436cfSJed Brown   if (vatol) {
47579566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vatol));
47589566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vatol));
47591c3436cfSJed Brown     ts->vatol = vatol;
47601c3436cfSJed Brown   }
4761c5033834SJed Brown   if (rtol != PETSC_DECIDE && rtol != PETSC_DEFAULT) ts->rtol = rtol;
47621c3436cfSJed Brown   if (vrtol) {
47639566063dSJacob Faibussowitsch     PetscCall(PetscObjectReference((PetscObject)vrtol));
47649566063dSJacob Faibussowitsch     PetscCall(VecDestroy(&ts->vrtol));
47651c3436cfSJed Brown     ts->vrtol = vrtol;
47661c3436cfSJed Brown   }
47671c3436cfSJed Brown   PetscFunctionReturn(0);
47681c3436cfSJed Brown }
47691c3436cfSJed Brown 
4770c5033834SJed Brown /*@
4771c5033834SJed Brown    TSGetTolerances - Get tolerances for local truncation error when using adaptive controller
4772c5033834SJed Brown 
4773c5033834SJed Brown    Logically Collective
4774c5033834SJed Brown 
47754165533cSJose E. Roman    Input Parameter:
4776c5033834SJed Brown .  ts - time integration context
4777c5033834SJed Brown 
47784165533cSJose E. Roman    Output Parameters:
47790298fd71SBarry Smith +  atol - scalar absolute tolerances, NULL to ignore
47800298fd71SBarry Smith .  vatol - vector of absolute tolerances, NULL to ignore
47810298fd71SBarry Smith .  rtol - scalar relative tolerances, NULL to ignore
47820298fd71SBarry Smith -  vrtol - vector of relative tolerances, NULL to ignore
4783c5033834SJed Brown 
4784c5033834SJed Brown    Level: beginner
4785c5033834SJed Brown 
4786bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSAdapt`, `TSErrorWeightedNorm()`, `TSSetTolerances()`
4787c5033834SJed Brown @*/
4788d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTolerances(TS ts, PetscReal *atol, Vec *vatol, PetscReal *rtol, Vec *vrtol)
4789d71ae5a4SJacob Faibussowitsch {
4790c5033834SJed Brown   PetscFunctionBegin;
4791c5033834SJed Brown   if (atol) *atol = ts->atol;
4792c5033834SJed Brown   if (vatol) *vatol = ts->vatol;
4793c5033834SJed Brown   if (rtol) *rtol = ts->rtol;
4794c5033834SJed Brown   if (vrtol) *vrtol = ts->vrtol;
4795c5033834SJed Brown   PetscFunctionReturn(0);
4796c5033834SJed Brown }
4797c5033834SJed Brown 
47989c6b16b5SShri Abhyankar /*@
4799a4868fbcSLisandro Dalcin    TSErrorWeightedNorm2 - compute a weighted 2-norm of the difference between two state vectors
48009c6b16b5SShri Abhyankar 
4801c3339decSBarry Smith    Collective
48029c6b16b5SShri Abhyankar 
48034165533cSJose E. Roman    Input Parameters:
48049c6b16b5SShri Abhyankar +  ts - time stepping context
4805a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4806a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
48079c6b16b5SShri Abhyankar 
48084165533cSJose E. Roman    Output Parameters:
4809a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
48107453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4811a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
48129c6b16b5SShri Abhyankar 
48139c6b16b5SShri Abhyankar    Level: developer
48149c6b16b5SShri Abhyankar 
4815bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNormInfinity()`
48169c6b16b5SShri Abhyankar @*/
4817d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm2(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
4818d71ae5a4SJacob Faibussowitsch {
48199c6b16b5SShri Abhyankar   PetscInt           i, n, N, rstart;
48207453f775SEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
48217453f775SEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
48229c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
48237453f775SEmil Constantinescu   PetscReal          sum, suma, sumr, gsum, gsuma, gsumr, diff;
48247453f775SEmil Constantinescu   PetscReal          tol, tola, tolr;
48257453f775SEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
48269c6b16b5SShri Abhyankar 
48279c6b16b5SShri Abhyankar   PetscFunctionBegin;
48289c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
4829a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
4830a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
4831a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
4832a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
4833a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
4834dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
4835dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
4836dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
48373c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
48389c6b16b5SShri Abhyankar 
48399566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
48409566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
48419566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
48429566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
48439566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
48449371c9d4SSatish Balay   sum    = 0.;
48459371c9d4SSatish Balay   n_loc  = 0;
48469371c9d4SSatish Balay   suma   = 0.;
48479371c9d4SSatish Balay   na_loc = 0;
48489371c9d4SSatish Balay   sumr   = 0.;
48499371c9d4SSatish Balay   nr_loc = 0;
48509c6b16b5SShri Abhyankar   if (ts->vatol && ts->vrtol) {
48519c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
48529566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
48539566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
48549c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
485576cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
48567453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48577453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48587453f775SEmil Constantinescu       if (tola > 0.) {
48597453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
48607453f775SEmil Constantinescu         na_loc++;
48617453f775SEmil Constantinescu       }
48627453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
48637453f775SEmil Constantinescu       if (tolr > 0.) {
48647453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
48657453f775SEmil Constantinescu         nr_loc++;
48667453f775SEmil Constantinescu       }
48677453f775SEmil Constantinescu       tol = tola + tolr;
48687453f775SEmil Constantinescu       if (tol > 0.) {
48697453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
48707453f775SEmil Constantinescu         n_loc++;
48717453f775SEmil Constantinescu       }
48729c6b16b5SShri Abhyankar     }
48739566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
48749566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
48759c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
48769c6b16b5SShri Abhyankar     const PetscScalar *atol;
48779566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
48789c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
487976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
48807453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
48817453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
48827453f775SEmil Constantinescu       if (tola > 0.) {
48837453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
48847453f775SEmil Constantinescu         na_loc++;
48857453f775SEmil Constantinescu       }
48867453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
48877453f775SEmil Constantinescu       if (tolr > 0.) {
48887453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
48897453f775SEmil Constantinescu         nr_loc++;
48907453f775SEmil Constantinescu       }
48917453f775SEmil Constantinescu       tol = tola + tolr;
48927453f775SEmil Constantinescu       if (tol > 0.) {
48937453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
48947453f775SEmil Constantinescu         n_loc++;
48957453f775SEmil Constantinescu       }
48969c6b16b5SShri Abhyankar     }
48979566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
48989c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
48999c6b16b5SShri Abhyankar     const PetscScalar *rtol;
49009566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
49019c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
490276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49037453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49047453f775SEmil Constantinescu       tola = ts->atol;
49057453f775SEmil Constantinescu       if (tola > 0.) {
49067453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49077453f775SEmil Constantinescu         na_loc++;
49087453f775SEmil Constantinescu       }
49097453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49107453f775SEmil Constantinescu       if (tolr > 0.) {
49117453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49127453f775SEmil Constantinescu         nr_loc++;
49137453f775SEmil Constantinescu       }
49147453f775SEmil Constantinescu       tol = tola + tolr;
49157453f775SEmil Constantinescu       if (tol > 0.) {
49167453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49177453f775SEmil Constantinescu         n_loc++;
49187453f775SEmil Constantinescu       }
49199c6b16b5SShri Abhyankar     }
49209566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
49219c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
49229c6b16b5SShri Abhyankar     for (i = 0; i < n; i++) {
492376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
49247453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
49257453f775SEmil Constantinescu       tola = ts->atol;
49267453f775SEmil Constantinescu       if (tola > 0.) {
49277453f775SEmil Constantinescu         suma += PetscSqr(diff / tola);
49287453f775SEmil Constantinescu         na_loc++;
49297453f775SEmil Constantinescu       }
49307453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
49317453f775SEmil Constantinescu       if (tolr > 0.) {
49327453f775SEmil Constantinescu         sumr += PetscSqr(diff / tolr);
49337453f775SEmil Constantinescu         nr_loc++;
49347453f775SEmil Constantinescu       }
49357453f775SEmil Constantinescu       tol = tola + tolr;
49367453f775SEmil Constantinescu       if (tol > 0.) {
49377453f775SEmil Constantinescu         sum += PetscSqr(diff / tol);
49387453f775SEmil Constantinescu         n_loc++;
49397453f775SEmil Constantinescu       }
49409c6b16b5SShri Abhyankar     }
49419c6b16b5SShri Abhyankar   }
49429566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
49439566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
49449c6b16b5SShri Abhyankar 
49457453f775SEmil Constantinescu   err_loc[0] = sum;
49467453f775SEmil Constantinescu   err_loc[1] = suma;
49477453f775SEmil Constantinescu   err_loc[2] = sumr;
49487453f775SEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
49497453f775SEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
49507453f775SEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
49517453f775SEmil Constantinescu 
49521c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
49537453f775SEmil Constantinescu 
49547453f775SEmil Constantinescu   gsum   = err_glb[0];
49557453f775SEmil Constantinescu   gsuma  = err_glb[1];
49567453f775SEmil Constantinescu   gsumr  = err_glb[2];
49577453f775SEmil Constantinescu   n_glb  = err_glb[3];
49587453f775SEmil Constantinescu   na_glb = err_glb[4];
49597453f775SEmil Constantinescu   nr_glb = err_glb[5];
49607453f775SEmil Constantinescu 
4961b1316ef9SEmil Constantinescu   *norm = 0.;
49621e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
4963b1316ef9SEmil Constantinescu   *norma = 0.;
49641e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
4965b1316ef9SEmil Constantinescu   *normr = 0.;
49661e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
49679c6b16b5SShri Abhyankar 
49683c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
49693c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
49703c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
49719c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
49729c6b16b5SShri Abhyankar }
49739c6b16b5SShri Abhyankar 
49749c6b16b5SShri Abhyankar /*@
4975a4868fbcSLisandro Dalcin    TSErrorWeightedNormInfinity - compute a weighted infinity-norm of the difference between two state vectors
49769c6b16b5SShri Abhyankar 
4977c3339decSBarry Smith    Collective
49789c6b16b5SShri Abhyankar 
49794165533cSJose E. Roman    Input Parameters:
49809c6b16b5SShri Abhyankar +  ts - time stepping context
4981a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
4982a4868fbcSLisandro Dalcin -  Y - state vector to be compared to U
49839c6b16b5SShri Abhyankar 
49844165533cSJose E. Roman    Output Parameters:
4985a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
49867453f775SEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
4987a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
49889c6b16b5SShri Abhyankar 
49899c6b16b5SShri Abhyankar    Level: developer
49909c6b16b5SShri Abhyankar 
4991bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNorm()`, `TSErrorWeightedNorm2()`
49929c6b16b5SShri Abhyankar @*/
4993d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNormInfinity(TS ts, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
4994d71ae5a4SJacob Faibussowitsch {
49957453f775SEmil Constantinescu   PetscInt           i, n, N, rstart;
49969c6b16b5SShri Abhyankar   const PetscScalar *u, *y;
49977453f775SEmil Constantinescu   PetscReal          max, gmax, maxa, gmaxa, maxr, gmaxr;
49987453f775SEmil Constantinescu   PetscReal          tol, tola, tolr, diff;
49997453f775SEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
50009c6b16b5SShri Abhyankar 
50019c6b16b5SShri Abhyankar   PetscFunctionBegin;
50029c6b16b5SShri Abhyankar   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5003a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(U, VEC_CLASSID, 2);
5004a4868fbcSLisandro Dalcin   PetscValidHeaderSpecific(Y, VEC_CLASSID, 3);
5005a4868fbcSLisandro Dalcin   PetscValidType(U, 2);
5006a4868fbcSLisandro Dalcin   PetscValidType(Y, 3);
5007a4868fbcSLisandro Dalcin   PetscCheckSameComm(U, 2, Y, 3);
5008dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 4);
5009dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 5);
5010dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 6);
50113c633725SBarry Smith   PetscCheck(U != Y, PetscObjectComm((PetscObject)U), PETSC_ERR_ARG_IDN, "U and Y cannot be the same vector");
50129c6b16b5SShri Abhyankar 
50139566063dSJacob Faibussowitsch   PetscCall(VecGetSize(U, &N));
50149566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(U, &n));
50159566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(U, &rstart, NULL));
50169566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
50179566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
50187453f775SEmil Constantinescu 
50197453f775SEmil Constantinescu   max  = 0.;
50207453f775SEmil Constantinescu   maxa = 0.;
50217453f775SEmil Constantinescu   maxr = 0.;
50227453f775SEmil Constantinescu 
50237453f775SEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
50249c6b16b5SShri Abhyankar     const PetscScalar *atol, *rtol;
50259566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50269566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50277453f775SEmil Constantinescu 
50287453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
502976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50307453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50317453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50327453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50337453f775SEmil Constantinescu       tol  = tola + tolr;
50341e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50351e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50361e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50379c6b16b5SShri Abhyankar     }
50389566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50399566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50409c6b16b5SShri Abhyankar   } else if (ts->vatol) { /* vector atol, scalar rtol */
50419c6b16b5SShri Abhyankar     const PetscScalar *atol;
50429566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
50437453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
504476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50457453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50467453f775SEmil Constantinescu       tola = PetscRealPart(atol[i]);
50477453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50487453f775SEmil Constantinescu       tol  = tola + tolr;
50491e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50501e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50511e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50529c6b16b5SShri Abhyankar     }
50539566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
50549c6b16b5SShri Abhyankar   } else if (ts->vrtol) { /* scalar atol, vector rtol */
50559c6b16b5SShri Abhyankar     const PetscScalar *rtol;
50569566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
50577453f775SEmil Constantinescu 
50587453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
505976cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50607453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50617453f775SEmil Constantinescu       tola = ts->atol;
50627453f775SEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50637453f775SEmil Constantinescu       tol  = tola + tolr;
50641e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50651e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50661e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50679c6b16b5SShri Abhyankar     }
50689566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
50699c6b16b5SShri Abhyankar   } else { /* scalar atol, scalar rtol */
50707453f775SEmil Constantinescu 
50717453f775SEmil Constantinescu     for (i = 0; i < n; i++) {
507276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
50737453f775SEmil Constantinescu       diff = PetscAbsScalar(y[i] - u[i]);
50747453f775SEmil Constantinescu       tola = ts->atol;
50757453f775SEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
50767453f775SEmil Constantinescu       tol  = tola + tolr;
50771e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, diff / tola);
50781e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, diff / tolr);
50791e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, diff / tol);
50809c6b16b5SShri Abhyankar     }
50819c6b16b5SShri Abhyankar   }
50829566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
50839566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
50847453f775SEmil Constantinescu   err_loc[0] = max;
50857453f775SEmil Constantinescu   err_loc[1] = maxa;
50867453f775SEmil Constantinescu   err_loc[2] = maxr;
50871c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
50887453f775SEmil Constantinescu   gmax  = err_glb[0];
50897453f775SEmil Constantinescu   gmaxa = err_glb[1];
50907453f775SEmil Constantinescu   gmaxr = err_glb[2];
50919c6b16b5SShri Abhyankar 
50929c6b16b5SShri Abhyankar   *norm  = gmax;
50937453f775SEmil Constantinescu   *norma = gmaxa;
50947453f775SEmil Constantinescu   *normr = gmaxr;
50953c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
50963c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
50973c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
50989c6b16b5SShri Abhyankar   PetscFunctionReturn(0);
50999c6b16b5SShri Abhyankar }
51009c6b16b5SShri Abhyankar 
51011c3436cfSJed Brown /*@
51028a175baeSEmil Constantinescu    TSErrorWeightedNorm - compute a weighted norm of the difference between two state vectors based on supplied absolute and relative tolerances
51031c3436cfSJed Brown 
5104c3339decSBarry Smith    Collective
51051c3436cfSJed Brown 
51064165533cSJose E. Roman    Input Parameters:
51071c3436cfSJed Brown +  ts - time stepping context
5108a4868fbcSLisandro Dalcin .  U - state vector, usually ts->vec_sol
5109a4868fbcSLisandro Dalcin .  Y - state vector to be compared to U
5110bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
51117619abb3SShri 
51124165533cSJose E. Roman    Output Parameters:
5113a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
51148a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5115a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
5116a4868fbcSLisandro Dalcin 
5117bcf0153eSBarry Smith    Options Database Key:
5118a4868fbcSLisandro Dalcin .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
5119a4868fbcSLisandro Dalcin 
51201c3436cfSJed Brown    Level: developer
51211c3436cfSJed Brown 
5122bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`, `TSErrorWeightedENorm`
51231c3436cfSJed Brown @*/
5124d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedNorm(TS ts, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5125d71ae5a4SJacob Faibussowitsch {
51261c3436cfSJed Brown   PetscFunctionBegin;
51271e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedNorm2(ts, U, Y, norm, norma, normr));
51281e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedNormInfinity(ts, U, Y, norm, norma, normr));
51291e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
51301c3436cfSJed Brown   PetscFunctionReturn(0);
51311c3436cfSJed Brown }
51321c3436cfSJed Brown 
51338a175baeSEmil Constantinescu /*@
51348a175baeSEmil Constantinescu    TSErrorWeightedENorm2 - compute a weighted 2 error norm based on supplied absolute and relative tolerances
51358a175baeSEmil Constantinescu 
5136c3339decSBarry Smith    Collective
51378a175baeSEmil Constantinescu 
51384165533cSJose E. Roman    Input Parameters:
51398a175baeSEmil Constantinescu +  ts - time stepping context
51408a175baeSEmil Constantinescu .  E - error vector
51418a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
51428a175baeSEmil Constantinescu -  Y - state vector, previous time step
51438a175baeSEmil Constantinescu 
51444165533cSJose E. Roman    Output Parameters:
5145a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
51468a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5147a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
51488a175baeSEmil Constantinescu 
51498a175baeSEmil Constantinescu    Level: developer
51508a175baeSEmil Constantinescu 
5151bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENormInfinity()`
51528a175baeSEmil Constantinescu @*/
5153d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm2(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5154d71ae5a4SJacob Faibussowitsch {
51558a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
51568a175baeSEmil Constantinescu   PetscInt           n_loc, na_loc, nr_loc;
51578a175baeSEmil Constantinescu   PetscReal          n_glb, na_glb, nr_glb;
51588a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
51598a175baeSEmil Constantinescu   PetscReal          err, sum, suma, sumr, gsum, gsuma, gsumr;
51608a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
51618a175baeSEmil Constantinescu   PetscReal          err_loc[6], err_glb[6];
51628a175baeSEmil Constantinescu 
51638a175baeSEmil Constantinescu   PetscFunctionBegin;
51648a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
51658a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
51668a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
51678a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
51688a175baeSEmil Constantinescu   PetscValidType(E, 2);
51698a175baeSEmil Constantinescu   PetscValidType(U, 3);
51708a175baeSEmil Constantinescu   PetscValidType(Y, 4);
51718a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5172064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5173dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5174dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5175dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
51768a175baeSEmil Constantinescu 
51779566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
51789566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
51799566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
51809566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
51819566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
51829566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
51839371c9d4SSatish Balay   sum    = 0.;
51849371c9d4SSatish Balay   n_loc  = 0;
51859371c9d4SSatish Balay   suma   = 0.;
51869371c9d4SSatish Balay   na_loc = 0;
51879371c9d4SSatish Balay   sumr   = 0.;
51889371c9d4SSatish Balay   nr_loc = 0;
51898a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) {
51908a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
51919566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
51929566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
51938a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
519476cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
51958a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
51968a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
51978a175baeSEmil Constantinescu       if (tola > 0.) {
51988a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
51998a175baeSEmil Constantinescu         na_loc++;
52008a175baeSEmil Constantinescu       }
52018a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52028a175baeSEmil Constantinescu       if (tolr > 0.) {
52038a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52048a175baeSEmil Constantinescu         nr_loc++;
52058a175baeSEmil Constantinescu       }
52068a175baeSEmil Constantinescu       tol = tola + tolr;
52078a175baeSEmil Constantinescu       if (tol > 0.) {
52088a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52098a175baeSEmil Constantinescu         n_loc++;
52108a175baeSEmil Constantinescu       }
52118a175baeSEmil Constantinescu     }
52129566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52139566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52148a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
52158a175baeSEmil Constantinescu     const PetscScalar *atol;
52169566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
52178a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
521876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52198a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52208a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
52218a175baeSEmil Constantinescu       if (tola > 0.) {
52228a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52238a175baeSEmil Constantinescu         na_loc++;
52248a175baeSEmil Constantinescu       }
52258a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52268a175baeSEmil Constantinescu       if (tolr > 0.) {
52278a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52288a175baeSEmil Constantinescu         nr_loc++;
52298a175baeSEmil Constantinescu       }
52308a175baeSEmil Constantinescu       tol = tola + tolr;
52318a175baeSEmil Constantinescu       if (tol > 0.) {
52328a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52338a175baeSEmil Constantinescu         n_loc++;
52348a175baeSEmil Constantinescu       }
52358a175baeSEmil Constantinescu     }
52369566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
52378a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
52388a175baeSEmil Constantinescu     const PetscScalar *rtol;
52399566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
52408a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
524176cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52428a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52438a175baeSEmil Constantinescu       tola = ts->atol;
52448a175baeSEmil Constantinescu       if (tola > 0.) {
52458a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52468a175baeSEmil Constantinescu         na_loc++;
52478a175baeSEmil Constantinescu       }
52488a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52498a175baeSEmil Constantinescu       if (tolr > 0.) {
52508a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52518a175baeSEmil Constantinescu         nr_loc++;
52528a175baeSEmil Constantinescu       }
52538a175baeSEmil Constantinescu       tol = tola + tolr;
52548a175baeSEmil Constantinescu       if (tol > 0.) {
52558a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52568a175baeSEmil Constantinescu         n_loc++;
52578a175baeSEmil Constantinescu       }
52588a175baeSEmil Constantinescu     }
52599566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
52608a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
52618a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
526276cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
52638a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
52648a175baeSEmil Constantinescu       tola = ts->atol;
52658a175baeSEmil Constantinescu       if (tola > 0.) {
52668a175baeSEmil Constantinescu         suma += PetscSqr(err / tola);
52678a175baeSEmil Constantinescu         na_loc++;
52688a175baeSEmil Constantinescu       }
52698a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
52708a175baeSEmil Constantinescu       if (tolr > 0.) {
52718a175baeSEmil Constantinescu         sumr += PetscSqr(err / tolr);
52728a175baeSEmil Constantinescu         nr_loc++;
52738a175baeSEmil Constantinescu       }
52748a175baeSEmil Constantinescu       tol = tola + tolr;
52758a175baeSEmil Constantinescu       if (tol > 0.) {
52768a175baeSEmil Constantinescu         sum += PetscSqr(err / tol);
52778a175baeSEmil Constantinescu         n_loc++;
52788a175baeSEmil Constantinescu       }
52798a175baeSEmil Constantinescu     }
52808a175baeSEmil Constantinescu   }
52819566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
52829566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
52839566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
52848a175baeSEmil Constantinescu 
52858a175baeSEmil Constantinescu   err_loc[0] = sum;
52868a175baeSEmil Constantinescu   err_loc[1] = suma;
52878a175baeSEmil Constantinescu   err_loc[2] = sumr;
52888a175baeSEmil Constantinescu   err_loc[3] = (PetscReal)n_loc;
52898a175baeSEmil Constantinescu   err_loc[4] = (PetscReal)na_loc;
52908a175baeSEmil Constantinescu   err_loc[5] = (PetscReal)nr_loc;
52918a175baeSEmil Constantinescu 
52921c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 6, MPIU_REAL, MPIU_SUM, PetscObjectComm((PetscObject)ts)));
52938a175baeSEmil Constantinescu 
52948a175baeSEmil Constantinescu   gsum   = err_glb[0];
52958a175baeSEmil Constantinescu   gsuma  = err_glb[1];
52968a175baeSEmil Constantinescu   gsumr  = err_glb[2];
52978a175baeSEmil Constantinescu   n_glb  = err_glb[3];
52988a175baeSEmil Constantinescu   na_glb = err_glb[4];
52998a175baeSEmil Constantinescu   nr_glb = err_glb[5];
53008a175baeSEmil Constantinescu 
53018a175baeSEmil Constantinescu   *norm = 0.;
53021e66621cSBarry Smith   if (n_glb > 0.) *norm = PetscSqrtReal(gsum / n_glb);
53038a175baeSEmil Constantinescu   *norma = 0.;
53041e66621cSBarry Smith   if (na_glb > 0.) *norma = PetscSqrtReal(gsuma / na_glb);
53058a175baeSEmil Constantinescu   *normr = 0.;
53061e66621cSBarry Smith   if (nr_glb > 0.) *normr = PetscSqrtReal(gsumr / nr_glb);
53078a175baeSEmil Constantinescu 
53083c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
53093c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
53103c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
53118a175baeSEmil Constantinescu   PetscFunctionReturn(0);
53128a175baeSEmil Constantinescu }
53138a175baeSEmil Constantinescu 
53148a175baeSEmil Constantinescu /*@
53158a175baeSEmil Constantinescu    TSErrorWeightedENormInfinity - compute a weighted infinity error norm based on supplied absolute and relative tolerances
5316bcf0153eSBarry Smith 
5317c3339decSBarry Smith    Collective
53188a175baeSEmil Constantinescu 
53194165533cSJose E. Roman    Input Parameters:
53208a175baeSEmil Constantinescu +  ts - time stepping context
53218a175baeSEmil Constantinescu .  E - error vector
53228a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
53238a175baeSEmil Constantinescu -  Y - state vector, previous time step
53248a175baeSEmil Constantinescu 
53254165533cSJose E. Roman    Output Parameters:
5326a2b725a8SWilliam Gropp +  norm - weighted norm, a value of 1.0 means that the error matches the tolerances
53278a175baeSEmil Constantinescu .  norma - weighted norm based on the absolute tolerance, a value of 1.0 means that the error matches the tolerances
5328a2b725a8SWilliam Gropp -  normr - weighted norm based on the relative tolerance, a value of 1.0 means that the error matches the tolerances
53298a175baeSEmil Constantinescu 
53308a175baeSEmil Constantinescu    Level: developer
53318a175baeSEmil Constantinescu 
5332bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENorm()`, `TSErrorWeightedENorm2()`
53338a175baeSEmil Constantinescu @*/
5334d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENormInfinity(TS ts, Vec E, Vec U, Vec Y, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5335d71ae5a4SJacob Faibussowitsch {
53368a175baeSEmil Constantinescu   PetscInt           i, n, N, rstart;
53378a175baeSEmil Constantinescu   const PetscScalar *e, *u, *y;
53388a175baeSEmil Constantinescu   PetscReal          err, max, gmax, maxa, gmaxa, maxr, gmaxr;
53398a175baeSEmil Constantinescu   PetscReal          tol, tola, tolr;
53408a175baeSEmil Constantinescu   PetscReal          err_loc[3], err_glb[3];
53418a175baeSEmil Constantinescu 
53428a175baeSEmil Constantinescu   PetscFunctionBegin;
53438a175baeSEmil Constantinescu   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
53448a175baeSEmil Constantinescu   PetscValidHeaderSpecific(E, VEC_CLASSID, 2);
53458a175baeSEmil Constantinescu   PetscValidHeaderSpecific(U, VEC_CLASSID, 3);
53468a175baeSEmil Constantinescu   PetscValidHeaderSpecific(Y, VEC_CLASSID, 4);
53478a175baeSEmil Constantinescu   PetscValidType(E, 2);
53488a175baeSEmil Constantinescu   PetscValidType(U, 3);
53498a175baeSEmil Constantinescu   PetscValidType(Y, 4);
53508a175baeSEmil Constantinescu   PetscCheckSameComm(E, 2, U, 3);
5351064a246eSJacob Faibussowitsch   PetscCheckSameComm(U, 3, Y, 4);
5352dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norm, 5);
5353dadcf809SJacob Faibussowitsch   PetscValidRealPointer(norma, 6);
5354dadcf809SJacob Faibussowitsch   PetscValidRealPointer(normr, 7);
53558a175baeSEmil Constantinescu 
53569566063dSJacob Faibussowitsch   PetscCall(VecGetSize(E, &N));
53579566063dSJacob Faibussowitsch   PetscCall(VecGetLocalSize(E, &n));
53589566063dSJacob Faibussowitsch   PetscCall(VecGetOwnershipRange(E, &rstart, NULL));
53599566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(E, &e));
53609566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(U, &u));
53619566063dSJacob Faibussowitsch   PetscCall(VecGetArrayRead(Y, &y));
53628a175baeSEmil Constantinescu 
53638a175baeSEmil Constantinescu   max  = 0.;
53648a175baeSEmil Constantinescu   maxa = 0.;
53658a175baeSEmil Constantinescu   maxr = 0.;
53668a175baeSEmil Constantinescu 
53678a175baeSEmil Constantinescu   if (ts->vatol && ts->vrtol) { /* vector atol, vector rtol */
53688a175baeSEmil Constantinescu     const PetscScalar *atol, *rtol;
53699566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
53709566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
53718a175baeSEmil Constantinescu 
53728a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
537376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
53748a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
53758a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
53768a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
53778a175baeSEmil Constantinescu       tol  = tola + tolr;
53781e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
53791e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
53801e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
53818a175baeSEmil Constantinescu     }
53829566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
53839566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
53848a175baeSEmil Constantinescu   } else if (ts->vatol) { /* vector atol, scalar rtol */
53858a175baeSEmil Constantinescu     const PetscScalar *atol;
53869566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vatol, &atol));
53878a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
538876cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
53898a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
53908a175baeSEmil Constantinescu       tola = PetscRealPart(atol[i]);
53918a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
53928a175baeSEmil Constantinescu       tol  = tola + tolr;
53931e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
53941e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
53951e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
53968a175baeSEmil Constantinescu     }
53979566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vatol, &atol));
53988a175baeSEmil Constantinescu   } else if (ts->vrtol) { /* scalar atol, vector rtol */
53998a175baeSEmil Constantinescu     const PetscScalar *rtol;
54009566063dSJacob Faibussowitsch     PetscCall(VecGetArrayRead(ts->vrtol, &rtol));
54018a175baeSEmil Constantinescu 
54028a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
540376cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54048a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54058a175baeSEmil Constantinescu       tola = ts->atol;
54068a175baeSEmil Constantinescu       tolr = PetscRealPart(rtol[i]) * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54078a175baeSEmil Constantinescu       tol  = tola + tolr;
54081e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54091e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54101e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54118a175baeSEmil Constantinescu     }
54129566063dSJacob Faibussowitsch     PetscCall(VecRestoreArrayRead(ts->vrtol, &rtol));
54138a175baeSEmil Constantinescu   } else { /* scalar atol, scalar rtol */
54148a175baeSEmil Constantinescu 
54158a175baeSEmil Constantinescu     for (i = 0; i < n; i++) {
541676cddca1SEmil Constantinescu       SkipSmallValue(y[i], u[i], ts->adapt->ignore_max);
54178a175baeSEmil Constantinescu       err  = PetscAbsScalar(e[i]);
54188a175baeSEmil Constantinescu       tola = ts->atol;
54198a175baeSEmil Constantinescu       tolr = ts->rtol * PetscMax(PetscAbsScalar(u[i]), PetscAbsScalar(y[i]));
54208a175baeSEmil Constantinescu       tol  = tola + tolr;
54211e66621cSBarry Smith       if (tola > 0.) maxa = PetscMax(maxa, err / tola);
54221e66621cSBarry Smith       if (tolr > 0.) maxr = PetscMax(maxr, err / tolr);
54231e66621cSBarry Smith       if (tol > 0.) max = PetscMax(max, err / tol);
54248a175baeSEmil Constantinescu     }
54258a175baeSEmil Constantinescu   }
54269566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(E, &e));
54279566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(U, &u));
54289566063dSJacob Faibussowitsch   PetscCall(VecRestoreArrayRead(Y, &y));
54298a175baeSEmil Constantinescu   err_loc[0] = max;
54308a175baeSEmil Constantinescu   err_loc[1] = maxa;
54318a175baeSEmil Constantinescu   err_loc[2] = maxr;
54321c2dc1cbSBarry Smith   PetscCall(MPIU_Allreduce(err_loc, err_glb, 3, MPIU_REAL, MPIU_MAX, PetscObjectComm((PetscObject)ts)));
54338a175baeSEmil Constantinescu   gmax  = err_glb[0];
54348a175baeSEmil Constantinescu   gmaxa = err_glb[1];
54358a175baeSEmil Constantinescu   gmaxr = err_glb[2];
54368a175baeSEmil Constantinescu 
54378a175baeSEmil Constantinescu   *norm  = gmax;
54388a175baeSEmil Constantinescu   *norma = gmaxa;
54398a175baeSEmil Constantinescu   *normr = gmaxr;
54403c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norm), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norm");
54413c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*norma), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in norma");
54423c633725SBarry Smith   PetscCheck(!PetscIsInfOrNanScalar(*normr), PetscObjectComm((PetscObject)ts), PETSC_ERR_FP, "Infinite or not-a-number generated in normr");
54438a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54448a175baeSEmil Constantinescu }
54458a175baeSEmil Constantinescu 
54468a175baeSEmil Constantinescu /*@
54478a175baeSEmil Constantinescu    TSErrorWeightedENorm - compute a weighted error norm based on supplied absolute and relative tolerances
54488a175baeSEmil Constantinescu 
5449c3339decSBarry Smith    Collective
54508a175baeSEmil Constantinescu 
54514165533cSJose E. Roman    Input Parameters:
54528a175baeSEmil Constantinescu +  ts - time stepping context
54538a175baeSEmil Constantinescu .  E - error vector
54548a175baeSEmil Constantinescu .  U - state vector, usually ts->vec_sol
54558a175baeSEmil Constantinescu .  Y - state vector, previous time step
5456bcf0153eSBarry Smith -  wnormtype - norm type, either `NORM_2` or `NORM_INFINITY`
54578a175baeSEmil Constantinescu 
54584165533cSJose E. Roman    Output Parameters:
5459a2b725a8SWilliam Gropp +  norm  - weighted norm, a value of 1.0 achieves a balance between absolute and relative tolerances
54608a175baeSEmil Constantinescu .  norma - weighted norm, a value of 1.0 means that the error meets the absolute tolerance set by the user
5461a2b725a8SWilliam Gropp -  normr - weighted norm, a value of 1.0 means that the error meets the relative tolerance set by the user
54628a175baeSEmil Constantinescu 
5463bcf0153eSBarry Smith    Options Database Key:
54648a175baeSEmil Constantinescu .  -ts_adapt_wnormtype <wnormtype> - 2, INFINITY
54658a175baeSEmil Constantinescu 
54668a175baeSEmil Constantinescu    Level: developer
54678a175baeSEmil Constantinescu 
5468bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSErrorWeightedENormInfinity()`, `TSErrorWeightedENorm2()`, `TSErrorWeightedNormInfinity()`, `TSErrorWeightedNorm2()`
54698a175baeSEmil Constantinescu @*/
5470d71ae5a4SJacob Faibussowitsch PetscErrorCode TSErrorWeightedENorm(TS ts, Vec E, Vec U, Vec Y, NormType wnormtype, PetscReal *norm, PetscReal *norma, PetscReal *normr)
5471d71ae5a4SJacob Faibussowitsch {
54728a175baeSEmil Constantinescu   PetscFunctionBegin;
54731e66621cSBarry Smith   if (wnormtype == NORM_2) PetscCall(TSErrorWeightedENorm2(ts, E, U, Y, norm, norma, normr));
54741e66621cSBarry Smith   else if (wnormtype == NORM_INFINITY) PetscCall(TSErrorWeightedENormInfinity(ts, E, U, Y, norm, norma, normr));
54751e66621cSBarry Smith   else SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "No support for norm type %s", NormTypes[wnormtype]);
54768a175baeSEmil Constantinescu   PetscFunctionReturn(0);
54778a175baeSEmil Constantinescu }
54788a175baeSEmil Constantinescu 
54798d59e960SJed Brown /*@
54808d59e960SJed Brown    TSSetCFLTimeLocal - Set the local CFL constraint relative to forward Euler
54818d59e960SJed Brown 
5482c3339decSBarry Smith    Logically Collective
54838d59e960SJed Brown 
54844165533cSJose E. Roman    Input Parameters:
54858d59e960SJed Brown +  ts - time stepping context
54868d59e960SJed Brown -  cfltime - maximum stable time step if using forward Euler (value can be different on each process)
54878d59e960SJed Brown 
54888d59e960SJed Brown    Note:
54898d59e960SJed Brown    After calling this function, the global CFL time can be obtained by calling TSGetCFLTime()
54908d59e960SJed Brown 
54918d59e960SJed Brown    Level: intermediate
54928d59e960SJed Brown 
5493bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSGetCFLTime()`, `TSADAPTCFL`
54948d59e960SJed Brown @*/
5495d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetCFLTimeLocal(TS ts, PetscReal cfltime)
5496d71ae5a4SJacob Faibussowitsch {
54978d59e960SJed Brown   PetscFunctionBegin;
54988d59e960SJed Brown   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
54998d59e960SJed Brown   ts->cfltime_local = cfltime;
55008d59e960SJed Brown   ts->cfltime       = -1.;
55018d59e960SJed Brown   PetscFunctionReturn(0);
55028d59e960SJed Brown }
55038d59e960SJed Brown 
55048d59e960SJed Brown /*@
55058d59e960SJed Brown    TSGetCFLTime - Get the maximum stable time step according to CFL criteria applied to forward Euler
55068d59e960SJed Brown 
5507c3339decSBarry Smith    Collective
55088d59e960SJed Brown 
55094165533cSJose E. Roman    Input Parameter:
55108d59e960SJed Brown .  ts - time stepping context
55118d59e960SJed Brown 
55124165533cSJose E. Roman    Output Parameter:
55138d59e960SJed Brown .  cfltime - maximum stable time step for forward Euler
55148d59e960SJed Brown 
55158d59e960SJed Brown    Level: advanced
55168d59e960SJed Brown 
5517bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSSetCFLTimeLocal()`
55188d59e960SJed Brown @*/
5519d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetCFLTime(TS ts, PetscReal *cfltime)
5520d71ae5a4SJacob Faibussowitsch {
55218d59e960SJed Brown   PetscFunctionBegin;
55221e66621cSBarry Smith   if (ts->cfltime < 0) PetscCall(MPIU_Allreduce(&ts->cfltime_local, &ts->cfltime, 1, MPIU_REAL, MPIU_MIN, PetscObjectComm((PetscObject)ts)));
55238d59e960SJed Brown   *cfltime = ts->cfltime;
55248d59e960SJed Brown   PetscFunctionReturn(0);
55258d59e960SJed Brown }
55268d59e960SJed Brown 
5527d6ebe24aSShri Abhyankar /*@
5528d6ebe24aSShri Abhyankar    TSVISetVariableBounds - Sets the lower and upper bounds for the solution vector. xl <= x <= xu
5529d6ebe24aSShri Abhyankar 
5530d6ebe24aSShri Abhyankar    Input Parameters:
5531bcf0153eSBarry Smith +  ts   - the `TS` context.
5532d6ebe24aSShri Abhyankar .  xl   - lower bound.
5533a2b725a8SWilliam Gropp -  xu   - upper bound.
5534d6ebe24aSShri Abhyankar 
55352bd2b0e6SSatish Balay    Level: advanced
55362bd2b0e6SSatish Balay 
5537bcf0153eSBarry Smith    Note:
5538bcf0153eSBarry Smith    If this routine is not called then the lower and upper bounds are set to
5539bcf0153eSBarry Smith    `PETSC_NINFINITY` and `PETSC_INFINITY` respectively during `SNESSetUp()`.
5540bcf0153eSBarry Smith 
5541bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`
5542d6ebe24aSShri Abhyankar @*/
5543d71ae5a4SJacob Faibussowitsch PetscErrorCode TSVISetVariableBounds(TS ts, Vec xl, Vec xu)
5544d71ae5a4SJacob Faibussowitsch {
5545d6ebe24aSShri Abhyankar   SNES snes;
5546d6ebe24aSShri Abhyankar 
5547d6ebe24aSShri Abhyankar   PetscFunctionBegin;
55489566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
55499566063dSJacob Faibussowitsch   PetscCall(SNESVISetVariableBounds(snes, xl, xu));
5550d6ebe24aSShri Abhyankar   PetscFunctionReturn(0);
5551d6ebe24aSShri Abhyankar }
5552d6ebe24aSShri Abhyankar 
5553f9c1d6abSBarry Smith /*@
5554f9c1d6abSBarry Smith    TSComputeLinearStability - computes the linear stability function at a point
5555f9c1d6abSBarry Smith 
5556c3339decSBarry Smith    Collective
5557f9c1d6abSBarry Smith 
5558f9c1d6abSBarry Smith    Input Parameters:
5559bcf0153eSBarry Smith +  ts - the `TS` context
5560f9c1d6abSBarry Smith -  xr,xi - real and imaginary part of input arguments
5561f9c1d6abSBarry Smith 
5562f9c1d6abSBarry Smith    Output Parameters:
5563f9c1d6abSBarry Smith .  yr,yi - real and imaginary part of function value
5564f9c1d6abSBarry Smith 
5565f9c1d6abSBarry Smith    Level: developer
5566f9c1d6abSBarry Smith 
5567bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetRHSFunction()`, `TSComputeIFunction()`
5568f9c1d6abSBarry Smith @*/
5569d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeLinearStability(TS ts, PetscReal xr, PetscReal xi, PetscReal *yr, PetscReal *yi)
5570d71ae5a4SJacob Faibussowitsch {
5571f9c1d6abSBarry Smith   PetscFunctionBegin;
5572f9c1d6abSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5573dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, linearstability, xr, xi, yr, yi);
5574f9c1d6abSBarry Smith   PetscFunctionReturn(0);
5575f9c1d6abSBarry Smith }
557624655328SShri 
557724655328SShri /*@
5578dcb233daSLisandro Dalcin    TSRestartStep - Flags the solver to restart the next step
5579dcb233daSLisandro Dalcin 
5580c3339decSBarry Smith    Collective
5581dcb233daSLisandro Dalcin 
5582dcb233daSLisandro Dalcin    Input Parameter:
5583bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
5584dcb233daSLisandro Dalcin 
5585dcb233daSLisandro Dalcin    Level: advanced
5586dcb233daSLisandro Dalcin 
5587dcb233daSLisandro Dalcin    Notes:
5588bcf0153eSBarry Smith    Multistep methods like `TSBDF` or Runge-Kutta methods with FSAL property require restarting the solver in the event of
5589dcb233daSLisandro Dalcin    discontinuities. These discontinuities may be introduced as a consequence of explicitly modifications to the solution
5590dcb233daSLisandro Dalcin    vector (which PETSc attempts to detect and handle) or problem coefficients (which PETSc is not able to detect). For
5591bcf0153eSBarry Smith    the sake of correctness and maximum safety, users are expected to call `TSRestart()` whenever they introduce
5592dcb233daSLisandro Dalcin    discontinuities in callback routines (e.g. prestep and poststep routines, or implicit/rhs function routines with
5593dcb233daSLisandro Dalcin    discontinuous source terms).
5594dcb233daSLisandro Dalcin 
5595bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSBDF`, `TSSolve()`, `TSSetPreStep()`, `TSSetPostStep()`
5596dcb233daSLisandro Dalcin @*/
5597d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRestartStep(TS ts)
5598d71ae5a4SJacob Faibussowitsch {
5599dcb233daSLisandro Dalcin   PetscFunctionBegin;
5600dcb233daSLisandro Dalcin   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5601dcb233daSLisandro Dalcin   ts->steprestart = PETSC_TRUE;
5602dcb233daSLisandro Dalcin   PetscFunctionReturn(0);
5603dcb233daSLisandro Dalcin }
5604dcb233daSLisandro Dalcin 
5605dcb233daSLisandro Dalcin /*@
560624655328SShri    TSRollBack - Rolls back one time step
560724655328SShri 
5608c3339decSBarry Smith    Collective
560924655328SShri 
561024655328SShri    Input Parameter:
5611bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
561224655328SShri 
561324655328SShri    Level: advanced
561424655328SShri 
5615bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`, `TSSetUp()`, `TSDestroy()`, `TSSolve()`, `TSSetPreStep()`, `TSSetPreStage()`, `TSInterpolate()`
561624655328SShri @*/
5617d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRollBack(TS ts)
5618d71ae5a4SJacob Faibussowitsch {
561924655328SShri   PetscFunctionBegin;
562024655328SShri   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
56213c633725SBarry Smith   PetscCheck(!ts->steprollback, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONGSTATE, "TSRollBack already called");
5622dbbe0bcdSBarry Smith   PetscUseTypeMethod(ts, rollback);
562324655328SShri   ts->time_step  = ts->ptime - ts->ptime_prev;
562424655328SShri   ts->ptime      = ts->ptime_prev;
5625be5899b3SLisandro Dalcin   ts->ptime_prev = ts->ptime_prev_rollback;
56262808aa04SLisandro Dalcin   ts->steps--;
5627b3de5cdeSLisandro Dalcin   ts->steprollback = PETSC_TRUE;
562824655328SShri   PetscFunctionReturn(0);
562924655328SShri }
5630aeb4809dSShri Abhyankar 
5631ff22ae23SHong Zhang /*@
5632ff22ae23SHong Zhang    TSGetStages - Get the number of stages and stage values
5633ff22ae23SHong Zhang 
5634ff22ae23SHong Zhang    Input Parameter:
5635bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
5636ff22ae23SHong Zhang 
56370429704eSStefano Zampini    Output Parameters:
56380429704eSStefano Zampini +  ns - the number of stages
56390429704eSStefano Zampini -  Y - the current stage vectors
56400429704eSStefano Zampini 
5641ff22ae23SHong Zhang    Level: advanced
5642ff22ae23SHong Zhang 
5643bcf0153eSBarry Smith    Note:
5644bcf0153eSBarry Smith    Both ns and Y can be NULL.
56450429704eSStefano Zampini 
5646bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSCreate()`
5647ff22ae23SHong Zhang @*/
5648d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetStages(TS ts, PetscInt *ns, Vec **Y)
5649d71ae5a4SJacob Faibussowitsch {
5650ff22ae23SHong Zhang   PetscFunctionBegin;
5651ff22ae23SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5652dadcf809SJacob Faibussowitsch   if (ns) PetscValidIntPointer(ns, 2);
56530429704eSStefano Zampini   if (Y) PetscValidPointer(Y, 3);
56540429704eSStefano Zampini   if (!ts->ops->getstages) {
56550429704eSStefano Zampini     if (ns) *ns = 0;
56560429704eSStefano Zampini     if (Y) *Y = NULL;
5657dbbe0bcdSBarry Smith   } else PetscUseTypeMethod(ts, getstages, ns, Y);
5658ff22ae23SHong Zhang   PetscFunctionReturn(0);
5659ff22ae23SHong Zhang }
5660ff22ae23SHong Zhang 
5661847ff0e1SMatthew G. Knepley /*@C
5662847ff0e1SMatthew G. Knepley   TSComputeIJacobianDefaultColor - Computes the Jacobian using finite differences and coloring to exploit matrix sparsity.
5663847ff0e1SMatthew G. Knepley 
5664c3339decSBarry Smith   Collective
5665847ff0e1SMatthew G. Knepley 
5666847ff0e1SMatthew G. Knepley   Input Parameters:
5667bcf0153eSBarry Smith + ts - the `TS` context
5668847ff0e1SMatthew G. Knepley . t - current timestep
5669847ff0e1SMatthew G. Knepley . U - state vector
5670847ff0e1SMatthew G. Knepley . Udot - time derivative of state vector
5671847ff0e1SMatthew G. Knepley . shift - shift to apply, see note below
5672847ff0e1SMatthew G. Knepley - ctx - an optional user context
5673847ff0e1SMatthew G. Knepley 
5674847ff0e1SMatthew G. Knepley   Output Parameters:
5675847ff0e1SMatthew G. Knepley + J - Jacobian matrix (not altered in this routine)
5676847ff0e1SMatthew G. Knepley - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
5677847ff0e1SMatthew G. Knepley 
5678847ff0e1SMatthew G. Knepley   Level: intermediate
5679847ff0e1SMatthew G. Knepley 
5680847ff0e1SMatthew G. Knepley   Notes:
5681847ff0e1SMatthew G. Knepley   If F(t,U,Udot)=0 is the DAE, the required Jacobian is
5682847ff0e1SMatthew G. Knepley 
5683847ff0e1SMatthew G. Knepley   dF/dU + shift*dF/dUdot
5684847ff0e1SMatthew G. Knepley 
5685847ff0e1SMatthew G. Knepley   Most users should not need to explicitly call this routine, as it
5686847ff0e1SMatthew G. Knepley   is used internally within the nonlinear solvers.
5687847ff0e1SMatthew G. Knepley 
5688bcf0153eSBarry Smith   This will first try to get the coloring from the `DM`.  If the `DM` type has no coloring
5689847ff0e1SMatthew G. Knepley   routine, then it will try to get the coloring from the matrix.  This requires that the
5690847ff0e1SMatthew G. Knepley   matrix have nonzero entries precomputed.
5691847ff0e1SMatthew G. Knepley 
5692bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetIJacobian()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
5693847ff0e1SMatthew G. Knepley @*/
5694d71ae5a4SJacob Faibussowitsch PetscErrorCode TSComputeIJacobianDefaultColor(TS ts, PetscReal t, Vec U, Vec Udot, PetscReal shift, Mat J, Mat B, void *ctx)
5695d71ae5a4SJacob Faibussowitsch {
5696847ff0e1SMatthew G. Knepley   SNES          snes;
5697847ff0e1SMatthew G. Knepley   MatFDColoring color;
5698847ff0e1SMatthew G. Knepley   PetscBool     hascolor, matcolor = PETSC_FALSE;
5699847ff0e1SMatthew G. Knepley 
5700847ff0e1SMatthew G. Knepley   PetscFunctionBegin;
57019566063dSJacob Faibussowitsch   PetscCall(PetscOptionsGetBool(((PetscObject)ts)->options, ((PetscObject)ts)->prefix, "-ts_fd_color_use_mat", &matcolor, NULL));
57029566063dSJacob Faibussowitsch   PetscCall(PetscObjectQuery((PetscObject)B, "TSMatFDColoring", (PetscObject *)&color));
5703847ff0e1SMatthew G. Knepley   if (!color) {
5704847ff0e1SMatthew G. Knepley     DM         dm;
5705847ff0e1SMatthew G. Knepley     ISColoring iscoloring;
5706847ff0e1SMatthew G. Knepley 
57079566063dSJacob Faibussowitsch     PetscCall(TSGetDM(ts, &dm));
57089566063dSJacob Faibussowitsch     PetscCall(DMHasColoring(dm, &hascolor));
5709847ff0e1SMatthew G. Knepley     if (hascolor && !matcolor) {
57109566063dSJacob Faibussowitsch       PetscCall(DMCreateColoring(dm, IS_COLORING_GLOBAL, &iscoloring));
57119566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57129566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57139566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57149566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57159566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5716847ff0e1SMatthew G. Knepley     } else {
5717847ff0e1SMatthew G. Knepley       MatColoring mc;
5718847ff0e1SMatthew G. Knepley 
57199566063dSJacob Faibussowitsch       PetscCall(MatColoringCreate(B, &mc));
57209566063dSJacob Faibussowitsch       PetscCall(MatColoringSetDistance(mc, 2));
57219566063dSJacob Faibussowitsch       PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
57229566063dSJacob Faibussowitsch       PetscCall(MatColoringSetFromOptions(mc));
57239566063dSJacob Faibussowitsch       PetscCall(MatColoringApply(mc, &iscoloring));
57249566063dSJacob Faibussowitsch       PetscCall(MatColoringDestroy(&mc));
57259566063dSJacob Faibussowitsch       PetscCall(MatFDColoringCreate(B, iscoloring, &color));
57269566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFunction(color, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
57279566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetFromOptions(color));
57289566063dSJacob Faibussowitsch       PetscCall(MatFDColoringSetUp(B, iscoloring, color));
57299566063dSJacob Faibussowitsch       PetscCall(ISColoringDestroy(&iscoloring));
5730847ff0e1SMatthew G. Knepley     }
57319566063dSJacob Faibussowitsch     PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)color));
57329566063dSJacob Faibussowitsch     PetscCall(PetscObjectDereference((PetscObject)color));
5733847ff0e1SMatthew G. Knepley   }
57349566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(ts, &snes));
57359566063dSJacob Faibussowitsch   PetscCall(MatFDColoringApply(B, color, U, snes));
5736847ff0e1SMatthew G. Knepley   if (J != B) {
57379566063dSJacob Faibussowitsch     PetscCall(MatAssemblyBegin(J, MAT_FINAL_ASSEMBLY));
57389566063dSJacob Faibussowitsch     PetscCall(MatAssemblyEnd(J, MAT_FINAL_ASSEMBLY));
5739847ff0e1SMatthew G. Knepley   }
5740847ff0e1SMatthew G. Knepley   PetscFunctionReturn(0);
5741847ff0e1SMatthew G. Knepley }
574293b34091SDebojyoti Ghosh 
5743cb9d8021SPierre Barbier de Reuille /*@
57446bc98fa9SBarry Smith     TSSetFunctionDomainError - Set a function that tests if the current state vector is valid
5745cb9d8021SPierre Barbier de Reuille 
5746cb9d8021SPierre Barbier de Reuille     Input Parameters:
5747bcf0153eSBarry Smith +    ts - the `TS` context
5748bcf0153eSBarry Smith -    func - function called within `TSFunctionDomainError()`
57496bc98fa9SBarry Smith 
57506bc98fa9SBarry Smith     Calling sequence of func:
57516bc98fa9SBarry Smith $     PetscErrorCode func(TS ts,PetscReal time,Vec state,PetscBool reject)
57526bc98fa9SBarry Smith 
57536bc98fa9SBarry Smith +   ts - the TS context
57546bc98fa9SBarry Smith .   time - the current time (of the stage)
57556bc98fa9SBarry Smith .   state - the state to check if it is valid
57566bc98fa9SBarry Smith -   reject - (output parameter) PETSC_FALSE if the state is acceptable, PETSC_TRUE if not acceptable
5757cb9d8021SPierre Barbier de Reuille 
5758cb9d8021SPierre Barbier de Reuille     Level: intermediate
5759cb9d8021SPierre Barbier de Reuille 
57606bc98fa9SBarry Smith     Notes:
57616bc98fa9SBarry Smith       If an implicit ODE solver is being used then, in addition to providing this routine, the
5762bcf0153eSBarry Smith       user's code should call `SNESSetFunctionDomainError()` when domain errors occur during
5763bcf0153eSBarry Smith       function evaluations where the functions are provided by `TSSetIFunction()` or `TSSetRHSFunction()`.
5764bcf0153eSBarry Smith       Use `TSGetSNES()` to obtain the `SNES` object
57656bc98fa9SBarry Smith 
5766bcf0153eSBarry Smith     Developer Note:
5767bcf0153eSBarry Smith       The naming of this function is inconsistent with the `SNESSetFunctionDomainError()`
57686bc98fa9SBarry Smith       since one takes a function pointer and the other does not.
57696bc98fa9SBarry Smith 
5770bcf0153eSBarry Smith .seealso: [](chapter_ts), `TSAdaptCheckStage()`, `TSFunctionDomainError()`, `SNESSetFunctionDomainError()`, `TSGetSNES()`
5771cb9d8021SPierre Barbier de Reuille @*/
5772cb9d8021SPierre Barbier de Reuille 
5773d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetFunctionDomainError(TS ts, PetscErrorCode (*func)(TS, PetscReal, Vec, PetscBool *))
5774d71ae5a4SJacob Faibussowitsch {
5775cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5776cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5777cb9d8021SPierre Barbier de Reuille   ts->functiondomainerror = func;
5778cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5779cb9d8021SPierre Barbier de Reuille }
5780cb9d8021SPierre Barbier de Reuille 
5781cb9d8021SPierre Barbier de Reuille /*@
57826bc98fa9SBarry Smith     TSFunctionDomainError - Checks if the current state is valid
5783cb9d8021SPierre Barbier de Reuille 
5784cb9d8021SPierre Barbier de Reuille     Input Parameters:
5785bcf0153eSBarry Smith +    ts - the `TS` context
57866bc98fa9SBarry Smith .    stagetime - time of the simulation
57876bc98fa9SBarry Smith -    Y - state vector to check.
5788cb9d8021SPierre Barbier de Reuille 
5789cb9d8021SPierre Barbier de Reuille     Output Parameter:
5790bcf0153eSBarry Smith .    accept - Set to `PETSC_FALSE` if the current state vector is valid.
579196a0c994SBarry Smith 
57926bc98fa9SBarry Smith     Level: developer
57936bc98fa9SBarry Smith 
5794bcf0153eSBarry Smith     Note:
5795bcf0153eSBarry Smith     This function is called by the `TS` integration routines and calls the user provided function (set with `TSSetFunctionDomainError()`)
5796bcf0153eSBarry Smith     to check if the current state is valid.
5797bcf0153eSBarry Smith 
5798bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetFunctionDomainError()`
5799cb9d8021SPierre Barbier de Reuille @*/
5800d71ae5a4SJacob Faibussowitsch PetscErrorCode TSFunctionDomainError(TS ts, PetscReal stagetime, Vec Y, PetscBool *accept)
5801d71ae5a4SJacob Faibussowitsch {
5802cb9d8021SPierre Barbier de Reuille   PetscFunctionBegin;
5803cb9d8021SPierre Barbier de Reuille   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
5804cb9d8021SPierre Barbier de Reuille   *accept = PETSC_TRUE;
58051e66621cSBarry Smith   if (ts->functiondomainerror) PetscCall((*ts->functiondomainerror)(ts, stagetime, Y, accept));
5806cb9d8021SPierre Barbier de Reuille   PetscFunctionReturn(0);
5807cb9d8021SPierre Barbier de Reuille }
58081ceb14c0SBarry Smith 
580993b34091SDebojyoti Ghosh /*@C
5810e5168f73SEmil Constantinescu   TSClone - This function clones a time step object.
581193b34091SDebojyoti Ghosh 
5812d083f849SBarry Smith   Collective
581393b34091SDebojyoti Ghosh 
581493b34091SDebojyoti Ghosh   Input Parameter:
5815bcf0153eSBarry Smith . tsin    - The input `TS`
581693b34091SDebojyoti Ghosh 
581793b34091SDebojyoti Ghosh   Output Parameter:
5818bcf0153eSBarry Smith . tsout   - The output `TS` (cloned)
58195eca1a21SEmil Constantinescu 
58205eca1a21SEmil Constantinescu   Level: developer
582193b34091SDebojyoti Ghosh 
5822bcf0153eSBarry Smith   Notes:
5823bcf0153eSBarry 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.
5824bcf0153eSBarry Smith   It will likely be replaced in the future with a mechanism of switching methods on the fly.
5825bcf0153eSBarry Smith 
5826bcf0153eSBarry 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 `SNES` snes_dup=NULL; `TSGetSNES`(ts,&snes_dup); `TSSetSNES`(ts,snes_dup);
5827bcf0153eSBarry Smith 
5828bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `SNES`, `TSCreate()`, `TSSetType()`, `TSSetUp()`, `TSDestroy()`, `TSSetProblemType()`
582993b34091SDebojyoti Ghosh @*/
5830d71ae5a4SJacob Faibussowitsch PetscErrorCode TSClone(TS tsin, TS *tsout)
5831d71ae5a4SJacob Faibussowitsch {
583293b34091SDebojyoti Ghosh   TS     t;
5833dc846ba4SSatish Balay   SNES   snes_start;
5834dc846ba4SSatish Balay   DM     dm;
5835dc846ba4SSatish Balay   TSType type;
583693b34091SDebojyoti Ghosh 
583793b34091SDebojyoti Ghosh   PetscFunctionBegin;
583893b34091SDebojyoti Ghosh   PetscValidPointer(tsin, 1);
583993b34091SDebojyoti Ghosh   *tsout = NULL;
584093b34091SDebojyoti Ghosh 
58419566063dSJacob Faibussowitsch   PetscCall(PetscHeaderCreate(t, TS_CLASSID, "TS", "Time stepping", "TS", PetscObjectComm((PetscObject)tsin), TSDestroy, TSView));
584293b34091SDebojyoti Ghosh 
584393b34091SDebojyoti Ghosh   /* General TS description */
584493b34091SDebojyoti Ghosh   t->numbermonitors    = 0;
5845d0c080abSJoseph Pusztay   t->monitorFrequency  = 1;
584693b34091SDebojyoti Ghosh   t->setupcalled       = 0;
584793b34091SDebojyoti Ghosh   t->ksp_its           = 0;
584893b34091SDebojyoti Ghosh   t->snes_its          = 0;
584993b34091SDebojyoti Ghosh   t->nwork             = 0;
58507d51462cSStefano Zampini   t->rhsjacobian.time  = PETSC_MIN_REAL;
585193b34091SDebojyoti Ghosh   t->rhsjacobian.scale = 1.;
585293b34091SDebojyoti Ghosh   t->ijacobian.shift   = 1.;
585393b34091SDebojyoti Ghosh 
58549566063dSJacob Faibussowitsch   PetscCall(TSGetSNES(tsin, &snes_start));
58559566063dSJacob Faibussowitsch   PetscCall(TSSetSNES(t, snes_start));
5856d15a3a53SEmil Constantinescu 
58579566063dSJacob Faibussowitsch   PetscCall(TSGetDM(tsin, &dm));
58589566063dSJacob Faibussowitsch   PetscCall(TSSetDM(t, dm));
585993b34091SDebojyoti Ghosh 
586093b34091SDebojyoti Ghosh   t->adapt = tsin->adapt;
58619566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->adapt));
586293b34091SDebojyoti Ghosh 
5863e7069c78SShri   t->trajectory = tsin->trajectory;
58649566063dSJacob Faibussowitsch   PetscCall(PetscObjectReference((PetscObject)t->trajectory));
5865e7069c78SShri 
5866e7069c78SShri   t->event = tsin->event;
58676b10a48eSSatish Balay   if (t->event) t->event->refct++;
5868e7069c78SShri 
586993b34091SDebojyoti Ghosh   t->problem_type      = tsin->problem_type;
587093b34091SDebojyoti Ghosh   t->ptime             = tsin->ptime;
5871e7069c78SShri   t->ptime_prev        = tsin->ptime_prev;
587293b34091SDebojyoti Ghosh   t->time_step         = tsin->time_step;
587393b34091SDebojyoti Ghosh   t->max_time          = tsin->max_time;
587493b34091SDebojyoti Ghosh   t->steps             = tsin->steps;
587593b34091SDebojyoti Ghosh   t->max_steps         = tsin->max_steps;
587693b34091SDebojyoti Ghosh   t->equation_type     = tsin->equation_type;
587793b34091SDebojyoti Ghosh   t->atol              = tsin->atol;
587893b34091SDebojyoti Ghosh   t->rtol              = tsin->rtol;
587993b34091SDebojyoti Ghosh   t->max_snes_failures = tsin->max_snes_failures;
588093b34091SDebojyoti Ghosh   t->max_reject        = tsin->max_reject;
588193b34091SDebojyoti Ghosh   t->errorifstepfailed = tsin->errorifstepfailed;
588293b34091SDebojyoti Ghosh 
58839566063dSJacob Faibussowitsch   PetscCall(TSGetType(tsin, &type));
58849566063dSJacob Faibussowitsch   PetscCall(TSSetType(t, type));
588593b34091SDebojyoti Ghosh 
588693b34091SDebojyoti Ghosh   t->vec_sol = NULL;
588793b34091SDebojyoti Ghosh 
588893b34091SDebojyoti Ghosh   t->cfltime          = tsin->cfltime;
588993b34091SDebojyoti Ghosh   t->cfltime_local    = tsin->cfltime_local;
589093b34091SDebojyoti Ghosh   t->exact_final_time = tsin->exact_final_time;
589193b34091SDebojyoti Ghosh 
58929566063dSJacob Faibussowitsch   PetscCall(PetscMemcpy(t->ops, tsin->ops, sizeof(struct _TSOps)));
589393b34091SDebojyoti Ghosh 
58940d4fed19SBarry Smith   if (((PetscObject)tsin)->fortran_func_pointers) {
58950d4fed19SBarry Smith     PetscInt i;
58969566063dSJacob Faibussowitsch     PetscCall(PetscMalloc((10) * sizeof(void (*)(void)), &((PetscObject)t)->fortran_func_pointers));
5897ad540459SPierre Jolivet     for (i = 0; i < 10; i++) ((PetscObject)t)->fortran_func_pointers[i] = ((PetscObject)tsin)->fortran_func_pointers[i];
58980d4fed19SBarry Smith   }
589993b34091SDebojyoti Ghosh   *tsout = t;
590093b34091SDebojyoti Ghosh   PetscFunctionReturn(0);
590193b34091SDebojyoti Ghosh }
5902f3b1f45cSBarry Smith 
5903d71ae5a4SJacob Faibussowitsch static PetscErrorCode RHSWrapperFunction_TSRHSJacobianTest(void *ctx, Vec x, Vec y)
5904d71ae5a4SJacob Faibussowitsch {
5905f3b1f45cSBarry Smith   TS ts = (TS)ctx;
5906f3b1f45cSBarry Smith 
5907f3b1f45cSBarry Smith   PetscFunctionBegin;
59089566063dSJacob Faibussowitsch   PetscCall(TSComputeRHSFunction(ts, 0, x, y));
5909f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5910f3b1f45cSBarry Smith }
5911f3b1f45cSBarry Smith 
5912f3b1f45cSBarry Smith /*@
5913bcf0153eSBarry Smith     TSRHSJacobianTest - Compares the multiply routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5914f3b1f45cSBarry Smith 
5915c3339decSBarry Smith    Logically Collective
5916f3b1f45cSBarry Smith 
5917f3b1f45cSBarry Smith     Input Parameters:
5918f3b1f45cSBarry Smith     TS - the time stepping routine
5919f3b1f45cSBarry Smith 
5920f3b1f45cSBarry Smith    Output Parameter:
5921bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5922f3b1f45cSBarry Smith 
5923bcf0153eSBarry Smith    Options Database Key:
5924f3b1f45cSBarry Smith  .   -ts_rhs_jacobian_test_mult -mat_shell_test_mult_view - run the test at each timestep of the integrator
5925f3b1f45cSBarry Smith 
5926f3b1f45cSBarry Smith    Level: advanced
5927f3b1f45cSBarry Smith 
5928bcf0153eSBarry Smith    Note:
592995452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5930f3b1f45cSBarry Smith 
5931bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MATSHELL`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTestTranspose()`
5932f3b1f45cSBarry Smith @*/
5933d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTest(TS ts, PetscBool *flg)
5934d71ae5a4SJacob Faibussowitsch {
5935f3b1f45cSBarry Smith   Mat           J, B;
5936f3b1f45cSBarry Smith   TSRHSJacobian func;
5937f3b1f45cSBarry Smith   void         *ctx;
5938f3b1f45cSBarry Smith 
5939f3b1f45cSBarry Smith   PetscFunctionBegin;
59409566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
59419566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
59429566063dSJacob Faibussowitsch   PetscCall(MatShellTestMult(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
5943f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5944f3b1f45cSBarry Smith }
5945f3b1f45cSBarry Smith 
5946f3b1f45cSBarry Smith /*@C
5947bcf0153eSBarry Smith     TSRHSJacobianTestTranspose - Compares the multiply transpose routine provided to the `MATSHELL` with differencing on the `TS` given RHS function.
5948f3b1f45cSBarry Smith 
5949c3339decSBarry Smith    Logically Collective
5950f3b1f45cSBarry Smith 
5951f3b1f45cSBarry Smith     Input Parameters:
5952f3b1f45cSBarry Smith     TS - the time stepping routine
5953f3b1f45cSBarry Smith 
5954f3b1f45cSBarry Smith    Output Parameter:
5955bcf0153eSBarry Smith .   flg - `PETSC_TRUE` if the multiply is likely correct
5956f3b1f45cSBarry Smith 
5957bcf0153eSBarry Smith    Options Database Key:
5958f3b1f45cSBarry Smith .   -ts_rhs_jacobian_test_mult_transpose -mat_shell_test_mult_transpose_view - run the test at each timestep of the integrator
5959f3b1f45cSBarry Smith 
5960bcf0153eSBarry Smith    Level: advanced
5961bcf0153eSBarry Smith 
596295452b02SPatrick Sanan    Notes:
596395452b02SPatrick Sanan     This only works for problems defined only the RHS function and Jacobian NOT IFunction and IJacobian
5964f3b1f45cSBarry Smith 
5965bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `Mat`, `MatCreateShell()`, `MatShellGetContext()`, `MatShellGetOperation()`, `MatShellTestMultTranspose()`, `TSRHSJacobianTest()`
5966f3b1f45cSBarry Smith @*/
5967d71ae5a4SJacob Faibussowitsch PetscErrorCode TSRHSJacobianTestTranspose(TS ts, PetscBool *flg)
5968d71ae5a4SJacob Faibussowitsch {
5969f3b1f45cSBarry Smith   Mat           J, B;
5970f3b1f45cSBarry Smith   void         *ctx;
5971f3b1f45cSBarry Smith   TSRHSJacobian func;
5972f3b1f45cSBarry Smith 
5973f3b1f45cSBarry Smith   PetscFunctionBegin;
59749566063dSJacob Faibussowitsch   PetscCall(TSGetRHSJacobian(ts, &J, &B, &func, &ctx));
59759566063dSJacob Faibussowitsch   PetscCall((*func)(ts, 0.0, ts->vec_sol, J, B, ctx));
59769566063dSJacob Faibussowitsch   PetscCall(MatShellTestMultTranspose(J, RHSWrapperFunction_TSRHSJacobianTest, ts->vec_sol, ts, flg));
5977f3b1f45cSBarry Smith   PetscFunctionReturn(0);
5978f3b1f45cSBarry Smith }
59790fe4d17eSHong Zhang 
59800fe4d17eSHong Zhang /*@
59810fe4d17eSHong Zhang   TSSetUseSplitRHSFunction - Use the split RHSFunction when a multirate method is used.
59820fe4d17eSHong Zhang 
59830fe4d17eSHong Zhang   Logically collective
59840fe4d17eSHong Zhang 
5985d8d19677SJose E. Roman   Input Parameters:
59860fe4d17eSHong Zhang +  ts - timestepping context
5987bcf0153eSBarry Smith -  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
59880fe4d17eSHong Zhang 
5989bcf0153eSBarry Smith   Options Database Key:
59900fe4d17eSHong Zhang .   -ts_use_splitrhsfunction - <true,false>
59910fe4d17eSHong Zhang 
59920fe4d17eSHong Zhang   Level: intermediate
59930fe4d17eSHong Zhang 
5994bcf0153eSBarry Smith   Note:
5995bcf0153eSBarry Smith     This is only useful for multirate methods
5996bcf0153eSBarry Smith 
5997bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetUseSplitRHSFunction()`
59980fe4d17eSHong Zhang @*/
5999d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetUseSplitRHSFunction(TS ts, PetscBool use_splitrhsfunction)
6000d71ae5a4SJacob Faibussowitsch {
60010fe4d17eSHong Zhang   PetscFunctionBegin;
60020fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60030fe4d17eSHong Zhang   ts->use_splitrhsfunction = use_splitrhsfunction;
60040fe4d17eSHong Zhang   PetscFunctionReturn(0);
60050fe4d17eSHong Zhang }
60060fe4d17eSHong Zhang 
60070fe4d17eSHong Zhang /*@
60080fe4d17eSHong Zhang   TSGetUseSplitRHSFunction - Gets whether to use the split RHSFunction when a multirate method is used.
60090fe4d17eSHong Zhang 
60100fe4d17eSHong Zhang   Not collective
60110fe4d17eSHong Zhang 
60120fe4d17eSHong Zhang   Input Parameter:
60130fe4d17eSHong Zhang .  ts - timestepping context
60140fe4d17eSHong Zhang 
60150fe4d17eSHong Zhang   Output Parameter:
6016bcf0153eSBarry Smith .  use_splitrhsfunction - `PETSC_TRUE` indicates that the split RHSFunction will be used
60170fe4d17eSHong Zhang 
60180fe4d17eSHong Zhang   Level: intermediate
60190fe4d17eSHong Zhang 
6020bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetUseSplitRHSFunction()`
60210fe4d17eSHong Zhang @*/
6022d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetUseSplitRHSFunction(TS ts, PetscBool *use_splitrhsfunction)
6023d71ae5a4SJacob Faibussowitsch {
60240fe4d17eSHong Zhang   PetscFunctionBegin;
60250fe4d17eSHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
60260fe4d17eSHong Zhang   *use_splitrhsfunction = ts->use_splitrhsfunction;
60270fe4d17eSHong Zhang   PetscFunctionReturn(0);
60280fe4d17eSHong Zhang }
6029d60b7d5cSBarry Smith 
6030d60b7d5cSBarry Smith /*@
6031d60b7d5cSBarry Smith     TSSetMatStructure - sets the relationship between the nonzero structure of the RHS Jacobian matrix to the IJacobian matrix.
6032d60b7d5cSBarry Smith 
6033c3339decSBarry Smith    Logically  Collective
6034d60b7d5cSBarry Smith 
6035d60b7d5cSBarry Smith    Input Parameters:
6036d60b7d5cSBarry Smith +  ts - the time-stepper
6037bcf0153eSBarry Smith -  str - the structure (the default is `UNKNOWN_NONZERO_PATTERN`)
6038d60b7d5cSBarry Smith 
6039d60b7d5cSBarry Smith    Level: intermediate
6040d60b7d5cSBarry Smith 
6041bcf0153eSBarry Smith    Note:
6042d60b7d5cSBarry Smith      When the relationship between the nonzero structures is known and supplied the solution process can be much faster
6043d60b7d5cSBarry Smith 
6044bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `MatAXPY()`, `MatStructure`
6045d60b7d5cSBarry Smith  @*/
6046d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetMatStructure(TS ts, MatStructure str)
6047d71ae5a4SJacob Faibussowitsch {
6048d60b7d5cSBarry Smith   PetscFunctionBegin;
6049d60b7d5cSBarry Smith   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
6050d60b7d5cSBarry Smith   ts->axpy_pattern = str;
6051d60b7d5cSBarry Smith   PetscFunctionReturn(0);
6052d60b7d5cSBarry Smith }
60534a658b32SHong Zhang 
60544a658b32SHong Zhang /*@
6055bcf0153eSBarry Smith   TSSetTimeSpan - sets the time span. The solution will be computed and stored for each time requested in the span
60564a658b32SHong Zhang 
6057c3339decSBarry Smith   Collective
60584a658b32SHong Zhang 
60594a658b32SHong Zhang   Input Parameters:
60604a658b32SHong Zhang + ts - the time-stepper
60614a658b32SHong Zhang . n - number of the time points (>=2)
60624a658b32SHong Zhang - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
60634a658b32SHong Zhang 
6064bcf0153eSBarry Smith   Options Database Key:
60654a658b32SHong Zhang . -ts_time_span <t0,...tf> - Sets the time span
60664a658b32SHong Zhang 
6067bcf0153eSBarry Smith   Level: intermediate
60684a658b32SHong Zhang 
60694a658b32SHong Zhang   Notes:
60704a658b32SHong Zhang   The elements in tspan must be all increasing. They correspond to the intermediate points for time integration.
6071bcf0153eSBarry Smith   `TS_EXACTFINALTIME_MATCHSTEP` must be used to make the last time step in each sub-interval match the intermediate points specified.
6072bcf0153eSBarry Smith   The intermediate solutions are saved in a vector array that can be accessed with `TSGetTimeSpanSolutions()`. Thus using time span may
60734a658b32SHong Zhang   pressure the memory system when using a large number of span points.
60744a658b32SHong Zhang 
6075bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSGetTimeSpan()`, `TSGetTimeSpanSolutions()`
60764a658b32SHong Zhang  @*/
6077d71ae5a4SJacob Faibussowitsch PetscErrorCode TSSetTimeSpan(TS ts, PetscInt n, PetscReal *span_times)
6078d71ae5a4SJacob Faibussowitsch {
60794a658b32SHong Zhang   PetscFunctionBegin;
60804a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
608163a3b9bcSJacob Faibussowitsch   PetscCheck(n >= 2, PetscObjectComm((PetscObject)ts), PETSC_ERR_ARG_WRONG, "Minimum time span size is 2 but %" PetscInt_FMT " is provided", n);
60824a658b32SHong Zhang   if (ts->tspan && n != ts->tspan->num_span_times) {
60834a658b32SHong Zhang     PetscCall(PetscFree(ts->tspan->span_times));
60844a658b32SHong Zhang     PetscCall(VecDestroyVecs(ts->tspan->num_span_times, &ts->tspan->vecs_sol));
60854a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &ts->tspan->span_times));
60864a658b32SHong Zhang   }
60874a658b32SHong Zhang   if (!ts->tspan) {
60884a658b32SHong Zhang     TSTimeSpan tspan;
60894a658b32SHong Zhang     PetscCall(PetscNew(&tspan));
60904a658b32SHong Zhang     PetscCall(PetscMalloc1(n, &tspan->span_times));
6091e1db57b0SHong Zhang     tspan->reltol = 1e-6;
6092e1db57b0SHong Zhang     tspan->abstol = 10 * PETSC_MACHINE_EPSILON;
60934a658b32SHong Zhang     ts->tspan     = tspan;
60944a658b32SHong Zhang   }
60954a658b32SHong Zhang   ts->tspan->num_span_times = n;
60964a658b32SHong Zhang   PetscCall(PetscArraycpy(ts->tspan->span_times, span_times, n));
60974a658b32SHong Zhang   PetscCall(TSSetTime(ts, ts->tspan->span_times[0]));
60984a658b32SHong Zhang   PetscCall(TSSetMaxTime(ts, ts->tspan->span_times[n - 1]));
60994a658b32SHong Zhang   PetscFunctionReturn(0);
61004a658b32SHong Zhang }
61014a658b32SHong Zhang 
61024a658b32SHong Zhang /*@C
61034a658b32SHong Zhang   TSGetTimeSpan - gets the time span.
61044a658b32SHong Zhang 
61054a658b32SHong Zhang   Not Collective
61064a658b32SHong Zhang 
61074a658b32SHong Zhang   Input Parameter:
61084a658b32SHong Zhang . ts - the time-stepper
61094a658b32SHong Zhang 
61104a658b32SHong Zhang   Output Parameters:
61114a658b32SHong Zhang + n - number of the time points (>=2)
6112bcf0153eSBarry Smith - span_times - array of the time points. The first element and the last element are the initial time and the final time respectively.
6113bcf0153eSBarry Smith   The values are valid until the `TS` object is destroyed.
61144a658b32SHong Zhang 
61154a658b32SHong Zhang   Level: beginner
61164a658b32SHong Zhang 
6117bcf0153eSBarry Smith   Note:
6118bcf0153eSBarry Smith   Both n and span_times can be NULL.
6119bcf0153eSBarry Smith 
6120bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`, `TSGetTimeSpanSolutions()`
61214a658b32SHong Zhang  @*/
6122d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpan(TS ts, PetscInt *n, const PetscReal **span_times)
6123d71ae5a4SJacob Faibussowitsch {
61244a658b32SHong Zhang   PetscFunctionBegin;
61254a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61264a658b32SHong Zhang   if (n) PetscValidIntPointer(n, 2);
61274a658b32SHong Zhang   if (span_times) PetscValidPointer(span_times, 3);
61284a658b32SHong Zhang   if (!ts->tspan) {
61294a658b32SHong Zhang     if (n) *n = 0;
61304a658b32SHong Zhang     if (span_times) *span_times = NULL;
61314a658b32SHong Zhang   } else {
61324a658b32SHong Zhang     if (n) *n = ts->tspan->num_span_times;
61334a658b32SHong Zhang     if (span_times) *span_times = ts->tspan->span_times;
61344a658b32SHong Zhang   }
61354a658b32SHong Zhang   PetscFunctionReturn(0);
61364a658b32SHong Zhang }
61374a658b32SHong Zhang 
61384a658b32SHong Zhang /*@
61394a658b32SHong Zhang    TSGetTimeSpanSolutions - Get the number of solutions and the solutions at the time points specified by the time span.
61404a658b32SHong Zhang 
61414a658b32SHong Zhang    Input Parameter:
6142bcf0153eSBarry Smith .  ts - the `TS` context obtained from `TSCreate()`
61434a658b32SHong Zhang 
61444a658b32SHong Zhang    Output Parameters:
61454a658b32SHong Zhang +  nsol - the number of solutions
61464a658b32SHong Zhang -  Sols - the solution vectors
61474a658b32SHong Zhang 
6148bcf0153eSBarry Smith    Level: intermediate
61494a658b32SHong Zhang 
615040bd4cedSHong Zhang    Notes:
615140bd4cedSHong Zhang     Both nsol and Sols can be NULL.
61524a658b32SHong Zhang 
6153bcf0153eSBarry Smith     Some time points in the time span may be skipped by TS so that nsol is less than the number of points specified by `TSSetTimeSpan()`.
6154bcf0153eSBarry Smith     For example, manipulating the step size, especially with a reduced precision, may cause `TS` to step over certain points in the span.
6155bcf0153eSBarry Smith 
6156bcf0153eSBarry Smith .seealso: [](chapter_ts), `TS`, `TSSetTimeSpan()`
61574a658b32SHong Zhang @*/
6158d71ae5a4SJacob Faibussowitsch PetscErrorCode TSGetTimeSpanSolutions(TS ts, PetscInt *nsol, Vec **Sols)
6159d71ae5a4SJacob Faibussowitsch {
61604a658b32SHong Zhang   PetscFunctionBegin;
61614a658b32SHong Zhang   PetscValidHeaderSpecific(ts, TS_CLASSID, 1);
61624a658b32SHong Zhang   if (nsol) PetscValidIntPointer(nsol, 2);
61634a658b32SHong Zhang   if (Sols) PetscValidPointer(Sols, 3);
61644a658b32SHong Zhang   if (!ts->tspan) {
61654a658b32SHong Zhang     if (nsol) *nsol = 0;
61664a658b32SHong Zhang     if (Sols) *Sols = NULL;
61674a658b32SHong Zhang   } else {
616840bd4cedSHong Zhang     if (nsol) *nsol = ts->tspan->spanctr;
61694a658b32SHong Zhang     if (Sols) *Sols = ts->tspan->vecs_sol;
61704a658b32SHong Zhang   }
61714a658b32SHong Zhang   PetscFunctionReturn(0);
61724a658b32SHong Zhang }
6173d7cfae9bSHong Zhang 
6174d7cfae9bSHong Zhang /*@C
61757b2dc123SHong Zhang   TSPruneIJacobianColor - Remove nondiagonal zeros in the Jacobian matrix and update the `MatMFFD` coloring information.
6176d7cfae9bSHong Zhang 
6177d7cfae9bSHong Zhang   Collective on TS
6178d7cfae9bSHong Zhang 
6179d7cfae9bSHong Zhang   Input Parameters:
6180d7cfae9bSHong Zhang + ts - the TS context
6181d7cfae9bSHong Zhang . J - Jacobian matrix (not altered in this routine)
6182d7cfae9bSHong Zhang - B - newly computed Jacobian matrix to use with preconditioner (generally the same as J)
6183d7cfae9bSHong Zhang 
6184d7cfae9bSHong Zhang   Level: intermediate
6185d7cfae9bSHong Zhang 
6186d7cfae9bSHong Zhang   Notes:
61877b2dc123SHong Zhang   This function improves the `MatMFFD` coloring performance when the Jacobian matrix is overallocated or contains
6188d7cfae9bSHong Zhang   many constant zeros entries, which is typically the case when the matrix is generated by a DM
6189d7cfae9bSHong Zhang   and multiple fields are involved.
6190d7cfae9bSHong Zhang 
6191d7cfae9bSHong Zhang   Users need to make sure that the Jacobian matrix is properly filled to reflect the sparsity
61927b2dc123SHong Zhang   structure. For `MatMFFD` coloring, the values of nonzero entries are not important. So one can
61937b2dc123SHong Zhang   usually call `TSComputeIJacobian()` with randomized input vectors to generate a dummy Jacobian.
61947b2dc123SHong Zhang   `TSComputeIJacobian()` should be called before `TSSolve()` but after `TSSetUp()`.
6195d7cfae9bSHong Zhang 
6196d7cfae9bSHong Zhang .seealso: `TSComputeIJacobianDefaultColor()`, `MatEliminateZeros()`, `MatFDColoringCreate()`, `MatFDColoringSetFunction()`
6197d7cfae9bSHong Zhang @*/
6198d7cfae9bSHong Zhang PetscErrorCode TSPruneIJacobianColor(TS ts, Mat J, Mat B)
6199d7cfae9bSHong Zhang {
6200d7cfae9bSHong Zhang   MatColoring   mc            = NULL;
6201d7cfae9bSHong Zhang   ISColoring    iscoloring    = NULL;
6202d7cfae9bSHong Zhang   MatFDColoring matfdcoloring = NULL;
6203d7cfae9bSHong Zhang 
6204d7cfae9bSHong Zhang   PetscFunctionBegin;
6205d7cfae9bSHong Zhang   /* Generate new coloring after eliminating zeros in the matrix */
6206d7cfae9bSHong Zhang   PetscCall(MatEliminateZeros(B));
6207d7cfae9bSHong Zhang   PetscCall(MatColoringCreate(B, &mc));
6208d7cfae9bSHong Zhang   PetscCall(MatColoringSetDistance(mc, 2));
6209d7cfae9bSHong Zhang   PetscCall(MatColoringSetType(mc, MATCOLORINGSL));
6210d7cfae9bSHong Zhang   PetscCall(MatColoringSetFromOptions(mc));
6211d7cfae9bSHong Zhang   PetscCall(MatColoringApply(mc, &iscoloring));
6212d7cfae9bSHong Zhang   PetscCall(MatColoringDestroy(&mc));
6213d7cfae9bSHong Zhang   /* Replace the old coloring with the new one */
6214d7cfae9bSHong Zhang   PetscCall(MatFDColoringCreate(B, iscoloring, &matfdcoloring));
6215d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFunction(matfdcoloring, (PetscErrorCode(*)(void))SNESTSFormFunction, (void *)ts));
6216d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetFromOptions(matfdcoloring));
6217d7cfae9bSHong Zhang   PetscCall(MatFDColoringSetUp(B, iscoloring, matfdcoloring));
6218d7cfae9bSHong Zhang   PetscCall(PetscObjectCompose((PetscObject)B, "TSMatFDColoring", (PetscObject)matfdcoloring));
6219d7cfae9bSHong Zhang   PetscCall(PetscObjectDereference((PetscObject)matfdcoloring));
6220d7cfae9bSHong Zhang   PetscCall(ISColoringDestroy(&iscoloring));
6221d7cfae9bSHong Zhang   PetscFunctionReturn(0);
6222d7cfae9bSHong Zhang }
6223