Solving
CommonSolve.solve Function
CommonSolve.solve(args...; kwargs...) -> solutionSolve an equation or other mathematical problem using the algorithm specified in the arguments. Generally, downstream packages extend:
CommonSolve.solve(prob::ProblemType, alg::SolverType; kwargs...)::SolutionTypeIf a package only defines the iterator interface, solve falls back to:
solve(args...; kwargs...) = solve!(init(args...; kwargs...))Arguments
args...: Problem, algorithm, and implementation-specific positional arguments.
Keywords
kwargs...: Implementation-specific solver options.
Interface
Extensions must dispatch the first positional argument on a type that they own. This prevents type piracy and ambiguities between independently developed solver packages.
Returns
The solution object defined by the downstream solver implementation.
Examples
struct MyProblem end
struct MyAlg end
CommonSolve.solve(::MyProblem, ::MyAlg; kwargs...) = :solution
CommonSolve.solve(MyProblem(), MyAlg())solve(
nlp,
solver::CTSolvers.Solvers.AbstractNLPSolver;
display
) -> SolverCore.GenericExecutionStats{T, S} where {T>:Float64, S>:Vector{Float64}}Mid-level solve: solve an NLP problem directly with a solver strategy.
Contract
Concrete solvers implement this method, typically in a backend extension, dispatching on both the problem type and the solver type, e.g. CommonSolve.solve(nlp::NLPModels.AbstractNLPModel, solver::Ipopt; display) in the CTSolversIpopt extension. This generic stub throws NotImplemented. NLPModels is a weak dep — the typed method lives in each solver extension.
Arguments
nlp: The NLP problem to solve (type depends on backend).solver::AbstractNLPSolver: Solver to use.display::Bool: Whether to show solver output (default:true).
Returns
SolverCore.AbstractExecutionStats: Solver execution statistics.
Throws
CTBase.Exceptions.NotImplemented: until a backend extension provides the typed method.
See also: AbstractNLPSolver.
solve(
problem::CTSolvers.Optimization.AbstractOptimizationProblem,
initial_guess,
modeler::CTSolvers.Modelers.AbstractNLPModeler,
solver::CTSolvers.Solvers.AbstractNLPSolver;
display
) -> AnyHigh-level solve: Build NLP model, solve it, and build solution.
Arguments
problem::Optimization.AbstractOptimizationProblem: The optimization probleminitial_guess: Initial guess for the solutionmodeler::Modelers.AbstractNLPModeler: Modeler to build NLPsolver::AbstractNLPSolver: Solver to usedisplay::Bool: Whether to show solver output (default: true)
Returns
- Solution object from the optimization problem
Example
# Conceptual usage pattern
# problem = ...
# x0 = ...
# modeler = Modelers.ADNLP()
# solver = Solvers.Ipopt(max_iter=1000)
# solution = solve(problem, x0, modeler, solver, display=true)See also: Optimization.build_model, Optimization.build_solution
solve(
prob,
integ::AbstractIntegrator;
kwargs...
) -> CTSolversSciMLIntegrator.SciMLIntegrationResultMid-level solve: integrate an ODE problem directly with an integrator strategy.
Contract
Concrete integrators implement this method, typically in a backend extension, dispatching on both the problem type and the integrator type, e.g. CommonSolve.solve(prob::SciMLBase.AbstractODEProblem, integ::SciML; options, unsafe) in the CTSolversSciMLIntegrator extension. This generic stub throws NotImplemented. SciMLBase is a weak dep — the typed method lives in the integrator extension.
Arguments
prob: The ODE problem to integrate (type depends on backend; the time span is embedded).integ::AbstractIntegrator: Integrator strategy to use.options: Resolved solver options.unsafe::Bool: Iftrue, bypass retcode checking (default:false).
Returns
Throws
CTBase.Exceptions.NotImplemented: until a backend extension provides the typed method.
See also: CTSolvers.Integrators.AbstractIntegrator.
solve(
ocp::CTModels.Models.AbstractModel,
description::Symbol...;
kwargs...
) -> CTModels.Solutions.Solution{TimeGridModelType, TimesModelType, StateModelType, ControlModelType, VariableModelType, ModelType, CostateModelType, Float64, DualModelType, CTModels.Solutions.SolverInfos{Any, Dict{Symbol, Any}}} where {TimeGridModelType<:Union{CTModels.Solutions.MultipleTimeGridModel, CTModels.Solutions.UnifiedTimeGridModel{Vector{Float64}}}, TimesModelType<:CTModels.Components.TimesModel, StateModelType<:(CTModels.Components.StateModelSolution{TS} where TS<:CTModels.Components.CoercedTrajectory), ControlModelType<:(CTModels.Components.ControlModelSolution{TS} where TS<:CTModels.Components.CoercedTrajectory), VariableModelType<:Union{CTModels.Components.VariableModelSolution{Vector{Float64}}, CTModels.Components.VariableModelSolution{Float64}}, ModelType<:(CTModels.Models.Model{<:CTBase.Traits.TimeDependence, T} where T<:CTModels.Components.TimesModel), CostateModelType<:CTModels.Components.CoercedTrajectory, DualModelType<:Union{CTModels.Solutions.DualModel{PC_Dual, Vector{Float64}, SC_LB_Dual, SC_UB_Dual, CC_LB_Dual, CC_UB_Dual, Vector{Float64}, Vector{Float64}} where {PC_Dual<:CTModels.Components.CoercedTrajectory, SC_LB_Dual<:CTModels.Components.CoercedTrajectory, SC_UB_Dual<:CTModels.Components.CoercedTrajectory, CC_LB_Dual<:CTModels.Components.CoercedTrajectory, CC_UB_Dual<:CTModels.Components.CoercedTrajectory}, CTModels.Solutions.DualModel{PC_Dual, Nothing, SC_LB_Dual, SC_UB_Dual, CC_LB_Dual, CC_UB_Dual, Vector{Float64}, Vector{Float64}} where {PC_Dual<:CTModels.Components.CoercedTrajectory, SC_LB_Dual<:CTModels.Components.CoercedTrajectory, SC_UB_Dual<:CTModels.Components.CoercedTrajectory, CC_LB_Dual<:CTModels.Components.CoercedTrajectory, CC_UB_Dual<:CTModels.Components.CoercedTrajectory}}}Main entry point for optimal control problem resolution.
This function orchestrates the complete solve workflow by: 2. Detecting the resolution mode (explicit vs descriptive) from arguments
Extracting or creating the strategy registry for component completion
Dispatching to the appropriate Layer 2 solver based on the detected mode
Arguments
ocp::CTModels.AbstractModel: The optimal control problem to solvedescription::Symbol...: Symbolic description tokens (e.g.,:collocation,:adnlp,:ipopt)kwargs...: All keyword arguments. Action options (initial_guess/init,display) are extracted by the appropriate Layer 2 function. Explicit components (discretizer,modeler,solver) are identified by abstract type. Aregistrykeyword can be provided to override the default strategy registry.
Returns
CTModels.AbstractSolution: Solution to the optimal control problem
Examples
# Descriptive mode (symbolic description)
solve(ocp, :collocation, :adnlp, :ipopt)
# With initial guess alias
solve(ocp, :collocation; init=x0, display=false)
# Explicit mode (typed components)
solve(ocp; discretizer=OptimalControl.Collocation(),
modeler=OptimalControl.ADNLP(), solver=OptimalControl.Ipopt())Throws
CTBase.Exceptions.IncorrectArgument: If explicit components and symbolic description are mixed
Notes
This is the main entry point (Layer 1) of the solve architecture
Mode detection determines whether to use explicit or descriptive resolution path
The registry can be injected for testing or customization purposes
Action options and strategy-specific options are handled by Layer 2 functions
See also: _explicit_or_descriptive, solve_explicit, solve_descriptive, get_strategy_registry
solve(
ocp::CTModels.Models.AbstractModel,
initial_guess::CTModels.Init.AbstractInitialGuess,
discretizer::CTSolvers.DOCP.AbstractDiscretizer,
modeler::CTSolvers.Modelers.AbstractNLPModeler,
solver::CTSolvers.Solvers.AbstractNLPSolver;
display
)Resolve an optimal control problem using fully specified, concrete components (Layer 3).
This is the lowest-level execution layer for solving an optimal control problem. It expects all components (initial guess, discretizer, modeler, and solver) to be fully instantiated and normalized. It discretizes the problem and passes it to the underlying solve pipeline.
Arguments
ocp::CTModels.AbstractModel: The optimal control problem to solveinitial_guess::CTModels.AbstractInitialGuess: Normalized initial guess for the solutiondiscretizer::CTSolvers.DOCP.AbstractDiscretizer: Concrete discretization strategymodeler::CTSolvers.Modelers.AbstractNLPModeler: Concrete NLP modeling strategysolver::CTSolvers.Solvers.AbstractNLPSolver: Concrete NLP solver strategydisplay::Bool: Whether to display the OCP configuration before solving
Returns
CTModels.AbstractSolution: The solution to the optimal control problem
Example
# Conceptual usage pattern for Layer 3 solve
ocp = Model(time=:final)
# ... define OCP ...
init = CTModels.build_initial_guess(ocp, nothing)
disc = OptimalControl.Collocation(grid_size=100)
mod = OptimalControl.ADNLP()
sol = OptimalControl.Ipopt()
solution = solve(ocp, init, disc, mod, sol; display=true)Notes
This is Layer 3 of the solve architecture - all inputs must be concrete, fully specified types
No defaults, no normalization, no component completion occurs at this level
The function performs: (1) optional configuration display, (2) problem discretization, (3) NLP solving
This function is typically called by higher-level solvers (
solve_explicit,solve_descriptive)
See also: solve_explicit, solve_descriptive
solve(
nlp::NLPModels.AbstractNLPModel,
solver::CTSolvers.Solvers.MadNLP;
display
) -> MadNLPExecutionStatsSolve an NLP problem using MadNLP.
Arguments
nlp::NLPModels.AbstractNLPModel: The NLP problem to solvedisplay::Bool: Whether to show solver output (default: true)
Returns
MadNLP.MadNLPExecutionStats: MadNLP execution statistics
solve(
nlp::NLPModels.AbstractNLPModel,
solver::CTSolvers.Solvers.MadNCL;
display
) -> MadNCL.NCLStatsSolve an NLP problem using MadNCL.
Arguments
nlp::NLPModels.AbstractNLPModel: The NLP problem to solvedisplay::Bool: Whether to show solver output (default: true)
Returns
MadNCL.NCLStats: MadNCL execution statistics
solve(
nlp::NLPModels.AbstractNLPModel,
solver::CTSolvers.Solvers.Ipopt;
display
) -> SolverCore.GenericExecutionStats{T, S} where {T>:Float64, S>:Vector{Float64}}Solve an NLP problem using Ipopt.
Arguments
nlp::NLPModels.AbstractNLPModel: The NLP problem to solvedisplay::Bool: Whether to show solver output (default: true)
Returns
SolverCore.GenericExecutionStats: Solver execution statistics
solve(
nlp::NLPModels.AbstractNLPModel,
solver::CTSolvers.Solvers.Knitro;
display
) -> SolverCore.GenericExecutionStats{T, S} where {T>:Float64, S>:Vector{Float64}}Solve an NLP problem using Knitro.
Arguments
nlp::NLPModels.AbstractNLPModel: The NLP problem to solvedisplay::Bool: Whether to show solver output (default: true)
Returns
SolverCore.GenericExecutionStats: Solver execution statistics
solve(prob::NonlinearProblem, alg::Union{AbstractNonlinearAlgorithm,Nothing}; kwargs...)Arguments
The only positional argument is alg which is optional. By default, alg = nothing. If alg = nothing, then solve dispatches to the NonlinearSolve.jl automated algorithm selection (if using NonlinearSolve was done, otherwise it will error with a MethodError).
Keyword Arguments
The NonlinearSolve.jl universe has a large set of common arguments available for the solve function. These arguments apply to solve on any problem type and are only limited by limitations of the specific implementations.
Many of the defaults depend on the algorithm or the package the algorithm derives from. Not all of the interface is provided by every algorithm. For more detailed information on the defaults and the available options for specific algorithms / packages, see the manual pages for the solvers of specific problems.
Error Control
abstol: Absolute tolerance.reltol: Relative tolerance.
These tolerances are interpreted by the termination condition.
Nonlinear Preconditioning
precondition: a left preconditionerGapplied to the residual, giving the root-equivalent systemG(f(u, p), u, p) = 0. Out-of-place problems return the transformed residual,Gfu = precondition(fu, u, p); in-place problems overwrite the first argument,precondition(fu, u, p) -> nothing. The composition is what the solver evaluates and differentiates, so termination andsol.residare measured on it.Gmust be root-preserving:G(r, u, p) = 0if and only ifr = 0.postcondition: an iterate correctorHapplied to every accepted iterate before the residual is evaluated or convergence tested there, and once to the initial guess. Out-of-place problems return the corrected iterate,u_new = postcondition(u_proposed, u_prev, p, cache); in-place problems overwrite the first argument,postcondition(u_proposed, u_prev, p, cache) -> nothing. The fourth argument is the solver cache —nothingfor the initial-guess correction, since that runs before a cache exists — and correctors that do not need solver state simply ignore it.Hmust satisfyH(u, u, p, cache) = uat solutions so that roots are unchanged. On a problem withlb/ubbounds the solver iterates on an unconstrained reparameterization ofu, andHis applied in the original bounded variable by default. Wrap it in aPostconditionSpecifierto say otherwise:postcondition = PostconditionSpecifier(H; space = PostconditionSpace.Transformed)applies it to the unconstrained iterate instead.
Both are ordinary solver options: pass them to solve/init, or carry them on the problem and have them forwarded like any other keyword.
Miscellaneous
maxiters: Maximum number of iterations before stopping. Defaults to 1000.verbose: Toggles whether warnings are thrown when the solver exits early. Defaults to true.
Sensitivity Algorithms (sensealg)
sensealg is used for choosing the way the automatic differentiation is performed. For more information, see the documentation for SciMLSensitivity
solve(prob::AbstractDEProblem, alg::Union{AbstractDEAlgorithm, Nothing}; kwargs...)Arguments
The only positional argument is alg which is optional. By default, alg = nothing. If alg = nothing, then solve dispatches to the DifferentialEquations.jl automated algorithm selection (if using DifferentialEquations was done, otherwise it will error with a MethodError).
Keyword Arguments
The DifferentialEquations.jl universe has a large set of common arguments available for the solve function. These arguments apply to solve on any problem type and are only limited by limitations of the specific implementations.
Many of the defaults depend on the algorithm or the package the algorithm derives from. Not all of the interface is provided by every algorithm. For more detailed information on the defaults and the available options for specific algorithms / packages, see the manual pages for the solvers of specific problems. To see whether a specific package is compatible with the use of a given option, see the Solver Compatibility Chart
Default Algorithm Hinting
To help choose the default algorithm, the keyword argument alg_hints is provided to solve. alg_hints is a Vector{Symbol} which describe the problem at a high level to the solver. The options are:
:autovs:nonstiffvs:stiff- Denotes the equation as nonstiff/stiff.:autoallow the default handling algorithm to choose stiffness detection algorithms. The default handling defaults to using:auto.
Currently unused options include:
:interpolant- Denotes that a high-precision interpolation is important.:memorybound- Denotes that the solver will be memory bound.
This functionality is derived via the benchmarks in SciMLBenchmarks.jl
SDE Specific Alghints
:additive- Denotes that the underlying SDE has additive noise.:stratonovich- Denotes that the solution should adhere to the Stratonovich interpretation.
Output Control
These arguments control the output behavior of the solvers. It defaults to maximum output to give the best interactive user experience, but can be reduced all the way to only saving the solution at the final timepoint.
The following options are all related to output control. See the "Examples" section at the end of this page for some example usage.
dense: Denotes whether to save the extra pieces required for dense (continuous) output. Default issave_everystep && isempty(saveat)for algorithms which have the ability to produce dense output, i.e. by default it'strueunless the user has turned off saving on steps or has chosen asaveatvalue. Ifdense=false, the solution still acts like a function, andsol(t)is a linear interpolation between the saved time points.saveat: Denotes specific times to save the solution at, during the solving phase. The solver will save at each of the timepoints in this array in the most efficient manner available to the solver. If onlysaveatis given, then the argumentssave_everystepanddensearefalseby default. Ifsaveatis given a number, then it will automatically expand totspan[1]:saveat:tspan[2]. For methods where interpolation is not possible,saveatmay be equivalent totstops. The default value is[].save_idxs: Denotes the indices for the components of the equation to save. Defaults to saving all indices. For example, if you are solving a 3-dimensional ODE, and givensave_idxs = [1, 3], only the first and third components of the solution will be outputted. Notice that of course in this case the outputted solution will be two-dimensional.tstops: Denotes extra times that the timestepping algorithm must step to. This should be used to help the solver deal with discontinuities and singularities, since stepping exactly at the time of the discontinuity will improve accuracy. If a method cannot change timesteps (fixed timestep multistep methods), thentstopswill use an interpolation, matching the behavior ofsaveat. If a method cannot change timesteps and also cannot interpolate, thentstopsmust be a multiple ofdtor else an error will be thrown.tstopsmay also be a functiontstops(p, tspan), accepting the parameter object andtspan, returning the vector of time points to stop at. Default is[].d_discontinuities: Denotes locations of discontinuities in low-order derivatives of the vector fieldf. Each entryt_dis added as a tstop, and when the integrator lands ont_dit advancestby one ULP in the integration direction and re-evaluates the FSAL cache on the post-discontinuity side. The convention is right-continuous:fevaluated att_dis the "old" regime andfatnextfloat(t_d)is the "new" regime, so user code should be written asjuliaif t > t_d # new regime else # old regime endWriting
t >= t_dalso works but means the solver takes one step of post-regime integration with a pre-regime-evaluated FSAL, which is less efficient and can reduce step acceptance near the discontinuity. Ad_discontinuitiesentry attspan[1]is supported (the starting-time case), in which case the first step begins atnextfloat(tspan[1]); this is useful for callbacks that need to activate immediately. The default is[].save_everystep: Saves the result at every step. Default is true ifisempty(saveat).save_on: Denotes whether intermediate solutions are saved. This overrides the settings ofdense,saveatandsave_everystepand is used by some applications to manually turn off saving temporarily. Everyday use of the solvers should leave this unchanged. Defaults totrue.save_start: Denotes whether the initial condition should be included in the solution type as the first timepoint. This setting overridessaveatwhen set tofalse. Defaults tosave_everystep || isempty(saveat) || saveat isa Number || prob.tspan[1] in saveat.save_end: Denotes whether the final condition should be included in the solution type as the final timepoint. This setting is overridden by other saving settings when set tofalse. Defaults tosave_everystep || isempty(saveat) || saveat isa Number || prob.tspan[2] in saveat.initialize_save: Denotes whether to save after the callback initialization phase (whenderivative_discontinuity=true). Defaults totrue.
Note that dense requires save_everystep=true and saveat=false. If you need additional saving while keeping dense output, see the SavingCallback in the Callback Library.
Stepsize Control
These arguments control the timestepping routines.
Basic Stepsize Control
These are the standard options for controlling stepping behavior. Error estimates do the comparison
The scaled error is guaranteed to be <1 for a given local error estimate (note: error estimates are local unless the method specifies otherwise). abstol controls the non-scaling error and thus can be thought of as the error around zero. reltol scales with the size of the dependent variables and so one can interpret reltol=1e-3 as roughly being (locally) correct to 3 digits. Note tolerances can be specified element-wise by passing a vector whose size matches u0.
adaptive: Turns on adaptive timestepping for appropriate methods. Default is true.abstol: Absolute tolerance in adaptive timestepping. This is the tolerance on local error estimates, not necessarily the global error (though these quantities are related). Defaults to1e-6on deterministic equations (ODEs/DDEs/DAEs) and1e-2on stochastic equations (SDEs/RODEs).reltol: Relative tolerance in adaptive timestepping. This is the tolerance on local error estimates, not necessarily the global error (though these quantities are related). Defaults to1e-3on deterministic equations (ODEs/DDEs/DAEs) and1e-2on stochastic equations (SDEs/RODEs).dt: Sets the initial stepsize. This is also the stepsize for fixed timestep methods. Defaults to an automatic choice if the method is adaptive.dtmax: Maximum dt for adaptive timestepping. Defaults are package-dependent.dtmin: Minimum dt for adaptive timestepping. Defaults are package-dependent.force_dtmin: Declares whether to continue, forcing the minimumdtusage. Default isfalse, which has the solver throw a warning and exit early when encountering the minimumdt. Setting this true allows the solver to continue, never lettingdtgo belowdtmin(and ignoring error tolerances in those cases). Note thattrueis not compatible with most interop packages.
Fixed Stepsize Usage
Note that if a method does not have adaptivity, the following rules apply:
If
dtis set, then the algorithm will step with sizedteach iteration.If
tstopsanddtare both set, then the algorithm will step with either a sizedt, or use a smaller step to hit thetstopspoint.If
tstopsis set withoutdt, then the algorithm will step directly to each value intstopsIf neither
dtnortstopsare set, the solver will throw an error.
Advanced Adaptive Stepsize Control
These arguments control more advanced parts of the internals of adaptive timestepping and are mostly used to make it more efficient on specific problems. For detailed explanations of the timestepping algorithms, see the timestepping descriptions
internalnorm: The norm functioninternalnorm(u,t)which error estimates are calculated. Required are two dispatches: one dispatch for the state variable and the other on the elements of the state variable (scalar norm). Defaults are package-dependent.controller: Possible examples areIController,PIController,PIDController,PredictiveController. Default is algorithm-dependent.gamma: The risk-factor γ in the q equation for adaptive timestepping of the controllers using it. Default is algorithm-dependent.beta1: The Lund stabilization α parameter. Default is algorithm-dependent.beta2: The Lund stabilization β parameter. Default is algorithm-dependent.qmax: Defines the maximum value possible for the adaptive q. Default is algorithm-dependent.qmin: Defines the minimum value possible for the adaptive q. Default is algorithm-dependent.qsteady_min: Defines the minimum for the range around 1 where the timestep is held constant. Default is algorithm-dependent.qsteady_max: Defines the maximum for the range around 1 where the timestep is held constant. Default is algorithm-dependent.qoldinit: The initialqoldin stabilization stepping. Default is algorithm-dependent.failfactor: The amount to decrease the timestep by if the Newton iterations of an implicit method fail. Default is 2.
Memory Optimizations
calck: Turns on and off the internal ability for intermediate interpolations (also known as intermediate density). Not the same asdense, which is post-solution interpolation. This defaults todense || !isempty(saveat) || "no custom callback is given". This can be used to turn off interpolations (to save memory) if one isn't using interpolations when a custom callback is used. Another case where this may be used is to turn on interpolations for usage in the integrator interface even when interpolations are used nowhere else. Note that this is only required if the algorithm doesn't have a free or lazy interpolation (DP8()). Ifcalck = false,saveatcannot be used. The rare keywordcalckcan be useful in event handling.alias: anAbstractAliasSpecifierobject that holds fields specifying which variables to alias when solving. For example, to tell an ODE solver to alias theu0array, you can use anODEAliasesobject, and thealias_u0keyword argument, e.g.solve(prob,alias = ODEAliases(alias_u0 = true)). For more information on what can be aliased for each problem type, see the documentation for theAbstractAliasSpecifierassociated with that problem type. Set totrueto alias every variable possible, or tofalseto disable aliasing. Defaults to anAbstractAliasSpecifierinstance withnothingfor all fields, which tells the solver to use the default behavior.
Miscellaneous
maxiters: Maximum number of iterations before stopping. Defaults to 1e5.callback: Specifies a callback. Defaults to a callback function which performs the saving routine. For more information, see the Event Handling and Callback Functions manual page.initializealg: The initialization algorithm for DAEs and ODEs with constraints. Available options include:DefaultInit()(default): Automatically chooses the best initialization algorithmCheckInit(): Only checks that initial conditions are consistent, errors if notNoInit(): Skip initialization completely (for when you know conditions are consistent)OverrideInit(): Use problem's initialization_data (typically from ModelingToolkit)BrownBasicInit(): Brown's basic initialization algorithm for index-1 DAEsShampineCollocationInit(): Shampine's collocation initialization for general DAEs
See the DAE initialization documentation for more details.
isoutofdomain: Specifies a functionisoutofdomain(u,p,t)where, when it returns true, it will reject the timestep. Disabled by default.unstable_check: Specifies a functionunstable_check(dt,u,p,t)where, when it returns true, it will cause the solver to exit and throw a warning. Defaults toany(isnan,u), i.e. checking if any value is a NaN.verbose: Toggles whether warnings are thrown when the solver exits early. Defaults to true.merge_callbacks: Toggles whether to mergeprob.callbackwith thesolvekeyword argumentcallback. Defaults totrue.wrap: Toggles whether to wrap the solution ifprob.problem_typehas a preferred alternate wrapper type for the solution. Useful when speed, but not shape of solution is important. Defaults toVal(true).Val(false)will cancel wrapping the solution.u0: The initial condition, overrides the one defined in the problem struct. Defaults tonothing(no override, use theu0defined inprob).p: The parameters, overrides the one defined in the problem struct. Defaults tonothing(no override, use thepdefined inprob).
Progress Monitoring
These arguments control the usage of the progressbar in ProgressLogging.jl compatible environments. For information on setting up progress bars in VS Code and other environments, see the progress bar documentation.
progress: Turns on/off the Juno progressbar. Default is false.progress_steps: Numbers of steps between updates of the progress bar. Default is 1000.progress_name: Controls the name of the progressbar. Default is the name of the problem type.progress_message: Controls the message with the progressbar. Defaults to showingdt,t, the maximum ofu.progress_id: Controls the ID of the progress log message to distinguish simultaneous simulations.
Error Calculations
If you are using the test problems (ex: ODETestProblem), then the following options control the errors which are calculated:
timeseries_errors: Turns on and off the calculation of errors at the steps which were taken, such as thel2error. Default is true.dense_errors: Turns on and off the calculation of errors at the steps which require dense output and calculate the error at 100 evenly-spaced points throughouttspan. An example is theL2error. Default is false.
Sensitivity Algorithms (sensealg)
sensealg is used for choosing the way the automatic differentiation is performed. For more information, see the documentation for SciMLSensitivity: https://docs.sciml.ai/SciMLSensitivity/stable/
Examples
The following lines are examples of how one could use the configuration of solve(). For these examples a 3-dimensional ODE problem is assumed, however the extension to other types is straightforward. 2. solve(prob, AlgorithmName()) : The "default" setting, with a user-specified algorithm (given by AlgorithmName()). All parameters get their default values. This means that the solution is saved at the steps the Algorithm stops internally and dense output is enabled if the chosen algorithm allows for it. All other integration parameters (e.g. stepsize) are chosen automatically.
solve(prob, saveat = 0.01, abstol = 1e-9, reltol = 1e-9): Standard setting for accurate output at specified (and equidistant) time intervals, used for e.g. Fourier Transform. The solution is given every 0.01 time units, starting fromtspan[1]. The solver used isTsit5()since no keywordalg_hintsis given.solve(prob, maxiters = 1e7, progress = true, save_idxs = [1]): Using longer maximum number of solver iterations can be useful when a giventspanis very long. This example only saves the first of the variables of the system, either to save size or because the user does not care about the others. Finally, withprogress = trueyou are enabling the progress bar.
solve(
prob::SciMLBase.AbstractODEProblem,
integ::SciML;
options,
unsafe
) -> CTSolversSciMLIntegrator.SciMLIntegrationResultIntegrate an ODEProblem with a SciML integrator and resolved options. Returns a SciMLIntegrationResult wrapping the raw ODESolution.
Arguments
prob::SciMLBase.AbstractODEProblem: The ODE problem to integrate (time span embedded).integ::Integrators.SciML: The SciML integrator strategy.options: Resolved solver options (defaults to the integrator's trajectory option dict).unsafe::Bool: Iftrue, bypass retcode checking; iffalse, throw on integration failure.
Throws
CTBase.Exceptions.SolverFailure: If the ODE solver returns an unsuccessful retcode andunsafe=false.
Base.methods Function
methods(f, [types], [module])Return the method table for f.
If types is specified, return an array of methods whose types match. If module is specified, return an array of methods defined in that module. A list of modules can also be specified as an array or set.
Julia 1.4
At least Julia 1.4 is required for specifying a module.
See also: which, @which and methodswith.
methods() -> NTuple{12, NTuple{4, Symbol}}Return the tuple of available method quadruplets for solving optimal control problems.
Each quadruplet consists of (discretizer_id, modeler_id, solver_id, parameter) where:
discretizer_id::Symbol: Discretization strategy identifier (e.g.,:collocation)modeler_id::Symbol: NLP modeling strategy identifier (e.g.,:adnlp,:exa)solver_id::Symbol: NLP solver identifier (e.g.,:ipopt,:madnlp,:madncl,:knitro)parameter::Symbol: Execution parameter (:cpuor:gpu)
Returns
Tuple{Vararg{Tuple{Symbol, Symbol, Symbol, Symbol}}}: Available method combinations
Examples
julia> m = methods()
((:collocation, :adnlp, :ipopt, :cpu), (:collocation, :adnlp, :madnlp, :cpu), ...)
julia> length(m)
12 # 10 CPU methods + 2 GPU methods
julia> # CPU methods
julia> methods()[1]
(:collocation, :adnlp, :ipopt, :cpu)
julia> methods()[9]
(:collocation, :exa, :madncl, :cpu)
julia> # GPU methods
julia> methods()[11]
(:collocation, :exa, :madnlp, :gpu)Notes
Returns a precomputed constant tuple (allocation-free, type-stable)
All methods currently use
:collocationdiscretizationCPU methods (10 total): All combinations of
{adnlp, exa}×{ipopt, madnlp, uno, madncl, knitro}GPU methods (2 total): Only GPU-capable combinations
exa×{madnlp, madncl}GPU-capable strategies use parameterized types with automatic defaults
Used by
CTBase.Descriptions.completeto complete partial method descriptions
See also: solve, CTBase.Descriptions.complete, get_strategy_registry
CTSolvers.DOCP.discretize Function
discretize(
ocp::CTModels.Models.AbstractModel,
discretizer::CTSolvers.DOCP.AbstractDiscretizer
) -> CTSolvers.DOCP.DiscretizedModel{TO, CTDirect.Collocation, TC} where {TO<:CTModels.Models.AbstractModel, TC<:(CTDirect.DOCPCache{D} where D<:(CTDirect.DOCP{_A, CTModels.Models.Model{TD, TimesModelType, StateModelType, ControlModelType, VariableModelType, DynamicsModelType, ObjectiveModelType, ConstraintsModelType, DefinitionType, BuildExaModelType}, CTDirect.DOCPshape{CX, CU, CV}} where {_A<:CTDirect.Scheme, TD<:CTBase.Traits.TimeDependence, TimesModelType<:CTModels.Components.AbstractTimesModel, StateModelType<:CTModels.Components.AbstractStateModel, ControlModelType<:CTModels.Components.AbstractControlModel, VariableModelType<:CTModels.Components.AbstractVariableModel, DynamicsModelType<:Function, ObjectiveModelType<:CTModels.Components.AbstractObjectiveModel, ConstraintsModelType<:CTModels.Components.AbstractConstraintsModel, DefinitionType<:CTModels.Components.AbstractDefinition, BuildExaModelType<:Union{Nothing, Function}, CX<:Union{typeof(identity), typeof(only)}, CU<:Union{typeof(identity), typeof(only)}, CV<:Union{typeof(identity), typeof(only)}}))}Discretize an optimal control problem into a DiscretizedModel.
Contract
Must be implemented in the package providing discretizer, dispatching on its concrete type, e.g. CTSolvers.discretize(ocp, ::Collocation) in CTDirect.
Arguments
ocp::CTModels.AbstractModel: The optimal control problem.discretizer::AbstractDiscretizer: The discretization strategy.
Returns
- A
DiscretizedModelwith a populated cache.
See also: build_model, build_solution.
discretize(
ocp::CTModels.Models.AbstractModel,
discretizer::CTDirect.Collocation
) -> CTSolvers.DOCP.DiscretizedModel{TO, CTDirect.Collocation, TC} where {TO<:CTModels.Models.AbstractModel, TC<:(CTDirect.DOCPCache{D} where D<:(CTDirect.DOCP{_A, CTModels.Models.Model{TD, TimesModelType, StateModelType, ControlModelType, VariableModelType, DynamicsModelType, ObjectiveModelType, ConstraintsModelType, DefinitionType, BuildExaModelType}, CTDirect.DOCPshape{CX, CU, CV}} where {_A<:CTDirect.Scheme, TD<:CTBase.Traits.TimeDependence, TimesModelType<:CTModels.Components.AbstractTimesModel, StateModelType<:CTModels.Components.AbstractStateModel, ControlModelType<:CTModels.Components.AbstractControlModel, VariableModelType<:CTModels.Components.AbstractVariableModel, DynamicsModelType<:Function, ObjectiveModelType<:CTModels.Components.AbstractObjectiveModel, ConstraintsModelType<:CTModels.Components.AbstractConstraintsModel, DefinitionType<:CTModels.Components.AbstractDefinition, BuildExaModelType<:Union{Nothing, Function}, CX<:Union{typeof(identity), typeof(only)}, CU<:Union{typeof(identity), typeof(only)}, CV<:Union{typeof(identity), typeof(only)}}))}Discretize an OCP with the Collocation strategy into a CTSolvers.DiscretizedModel holding a DOCPCache with the precomputed DOCP.
discretize(
ocp::CTModels.Models.AbstractModel,
discretizer::CTDirect.DirectShooting
) -> CTSolvers.DOCP.DiscretizedModel{TO, CTDirect.DirectShooting, TC} where {TO<:CTModels.Models.AbstractModel, TC<:(CTDirect.DOCPCache{D} where D<:(CTDirect.DOCP{_A, CTModels.Models.Model{TD, TimesModelType, StateModelType, ControlModelType, VariableModelType, DynamicsModelType, ObjectiveModelType, ConstraintsModelType, DefinitionType, BuildExaModelType}, CTDirect.DOCPshape{CX, CU, CV}} where {_A<:CTDirect.Scheme, TD<:CTBase.Traits.TimeDependence, TimesModelType<:CTModels.Components.AbstractTimesModel, StateModelType<:CTModels.Components.AbstractStateModel, ControlModelType<:CTModels.Components.AbstractControlModel, VariableModelType<:CTModels.Components.AbstractVariableModel, DynamicsModelType<:Function, ObjectiveModelType<:CTModels.Components.AbstractObjectiveModel, ConstraintsModelType<:CTModels.Components.AbstractConstraintsModel, DefinitionType<:CTModels.Components.AbstractDefinition, BuildExaModelType<:Union{Nothing, Function}, CX<:Union{typeof(identity), typeof(only)}, CU<:Union{typeof(identity), typeof(only)}, CV<:Union{typeof(identity), typeof(only)}}))}Discretize an OCP with the DirectShooting strategy into a CTSolvers.DiscretizedModel holding a DOCPCache with the precomputed DOCP.
CTSolvers.DOCP.ocp_model Function
ocp_model(
docp::CTSolvers.DOCP.DiscretizedModel
) -> CTModels.Models.AbstractModelExtract the original optimal control problem from a discretized problem.
Arguments
docp::DiscretizedModel: The discretized optimal control problem
Returns
- The original optimal control problem
Example
ocp = ocp_model(docp)See also: DiscretizedModel
CTSolvers.DOCP.nlp_model Function
nlp_model(
prob::CTSolvers.DOCP.DiscretizedModel,
initial_guess,
modeler::CTSolvers.Modelers.AbstractNLPModeler
) -> AnyBuild an NLP model from a discretized optimal control problem.
This is a convenience wrapper around build_model that returns only the backend NLP model (the nlp field of the BuiltModel). Use build_model directly when the build-time cache is needed (e.g. before build_solution).
Arguments
prob::DiscretizedModel: The discretized OCPinitial_guess: Initial guess for the NLP solvermodeler: The modeler to use (e.g., Modelers.ADNLP, Modelers.Exa)
Returns
NLPModels.AbstractNLPModel: The NLP model
Example
nlp = nlp_model(docp, initial_guess, modeler)See also: ocp_solution, Optimization.build_model, Optimization.BuiltModel
CTSolvers.DOCP.ocp_solution Function
ocp_solution(
built::CTSolvers.Optimization.BuiltModel,
model_solution::SolverCore.AbstractExecutionStats,
modeler::CTSolvers.Modelers.AbstractNLPModeler
) -> AnyBuild an optimal control solution from NLP execution statistics.
This is a convenience wrapper around build_solution that dispatches on the BuiltModel returned by build_model and ensures the return type is an optimal control solution.
Arguments
built::BuiltModel: The built model bundle returned bybuild_modelmodel_solution::SolverCore.AbstractExecutionStats: NLP solver outputmodeler: The modeler used for building
Returns
AbstractSolution: The OCP solution
Example
built = build_model(docp, initial_guess, modeler)
sol = ocp_solution(built, nlp_stats, modeler)See also: nlp_model, Optimization.build_solution, Optimization.BuiltModel
CTModels.Models.get_build_examodel Function
get_build_examodel(
ocp::CTModels.Models.Model{<:CTBase.Traits.TimeDependence, <:CTModels.Components.AbstractTimesModel, <:CTModels.Components.AbstractStateModel, <:CTModels.Components.AbstractControlModel, <:CTModels.Components.AbstractVariableModel, <:Function, <:CTModels.Components.AbstractObjectiveModel, <:CTModels.Components.AbstractConstraintsModel, <:CTModels.Components.AbstractDefinition, BE<:Function}
) -> FunctionReturn the build_examodel.
Arguments
ocp::Model: The optimal control problem with ExaModels builder.
Returns
BE: The ExaModels builder function.
See also: CTModels.Models.dynamics.
get_build_examodel(
_::CTModels.Models.Model{<:CTBase.Traits.TimeDependence, <:CTModels.Components.AbstractTimesModel, <:CTModels.Components.AbstractStateModel, <:CTModels.Components.AbstractControlModel, <:CTModels.Components.AbstractVariableModel, <:Function, <:CTModels.Components.AbstractObjectiveModel, <:CTModels.Components.AbstractConstraintsModel, <:CTModels.Components.AbstractDefinition, <:Nothing}
)Fallback: throw when no Exa builder is present.