Skip to content

Implementing an Optimization Problem ​

This guide explains how to implement an optimization problem in CTSolvers. An optimization problem is a concrete subtype of AbstractOptimizationProblem that pairs problem data with a discretizer and a backend-opaque cache. We use DiscretizedModel (DOCP) as the reference implementation.

Prerequisites

Read Architecture and Implementing a Modeler first. The optimization problem is the data holder; the modeler and the package providing the problem (e.g. CTDirect) implement the NLP building logic.

The AbstractOptimizationProblem Contract ​

AbstractOptimizationProblem is a marker abstract type with no required methods of its own. The contract is expressed through two generic functions that must be implemented by multiple dispatch in the package providing the concrete problem:

MethodSignatureReturnsImplemented in
build_model(prob::MyProblem, init, modeler::ADNLP)BuiltModelpackage providing MyProblem
build_solution(built::BuiltModel{<:MyProblem}, stats, modeler::ADNLP)domain solutionpackage providing MyProblem

The generic stubs in CTSolvers throw NotImplemented with guidance. Defining a subtype without these methods is valid — the error only fires when the pipeline is actually invoked:

julia
using CTSolvers
using CTSolvers: Optimization
struct EmptyProblem <: Optimization.AbstractOptimizationProblem end

BuiltModel and NoCache ​

build_model does not return a raw NLP model. It returns a CTSolvers.Optimization.BuiltModel — an immutable bundle that carries everything build_solution needs:

text
BuiltModel{TP <: AbstractOptimizationProblem, TN, TC <: AbstractCache}
├─ problem::TP   — the original problem (gives access to ocp, discretizer, cache)
├─ nlp::TN       — the backend NLP model (ADNLPModel, ExaModel, …)
└─ cache::TC     — immutable build-time auxiliary

CTSolvers.Optimization.NoCache is the default cache for backends that produce no auxiliary data:

julia
CTSolvers.Optimization.NoCache()
CTSolvers.Optimization.NoCache()

Implementing DiscretizedModel ​

DiscretizedModel is the canonical AbstractOptimizationProblem implementation in CTSolvers. It pairs an OCP with the discretizer that produced it and a backend-opaque cache:

Step 1 — Define the struct ​

julia
struct DiscretizedModel{
    TO <: CTModels.AbstractModel,
    TD <: AbstractDiscretizer,
    TC <: CTBase.Core.AbstractCache,
} <: AbstractOptimizationProblem
    ocp::TO          # original OCP
    discretizer::TD  # e.g. Collocation
    cache::TC        # opaque to CTSolvers, filled by the discretizer
end

The accessor ocp_model(docp) returns the original OCP.

Once built, the BuiltModel of a DiscretizedModel has the same accessors: use them rather than its fields.

julia
built = CTSolvers.build_model(docp, init, modeler)
nlp = CTSolvers.DOCP.nlp_model(built)  # the NLP, not built.nlp
ocp = CTSolvers.DOCP.ocp_model(built)  # the OCP, same as ocp_model(docp)
stats = ipopt(nlp)
sol = CTSolvers.DOCP.ocp_solution(built, stats, modeler)

These two methods, like ocp_solution, only exist for a BuiltModel of a DiscretizedModel: on the BuiltModel of another problem type they throw a MethodError; call build_solution directly for it.

Step 2 — Construct via discretize (in CTDirect) ​

DiscretizedModel is not constructed by calling the struct directly. CTSolvers owns a generic CTSolvers.discretize stub (src/DOCP/contract.jl) that throws NotImplemented; the package providing the discretizer implements the typed method. In CTDirect (src/collocation.jl) it preprocesses the OCP into a DOCP and wraps it in a cache:

julia
# In CTDirect — typed method for the Collocation discretizer
function CTSolvers.discretize(ocp::AbstractModel, discretizer::Collocation)
    docp = get_docp(discretizer, ocp)  # problem-specific preprocessing
    return CTSolvers.DiscretizedModel(ocp, discretizer, DOCPCache(docp))
end

DOCPCache is a CTBase.Core.AbstractCache subtype defined in CTDirect — CTSolvers only requires the cache field to be <: CTBase.Core.AbstractCache.

Step 3 — Implement build_model / build_solution (in CTDirect) ​

CTSolvers owns the generic stubs; CTDirect owns the concrete methods via multiple dispatch:

Simplified from CTDirect/src/collocation.jl:

julia
# In CTDirect — concrete methods for
# (DiscretizedModel + Collocation, ADNLP)
function CTSolvers.build_model(
    dm::CTSolvers.DiscretizedModel{<:Any,<:Collocation},
    initial_guess::CTModels.AbstractInitialGuess,
    modeler::CTSolvers.Modelers.ADNLP,
)
    docp = dm.cache.docp
    # the modeler's validated options
    options = Strategies.options_dict(modeler)
    backend = pop!(options, :backend)
    # ... objective f, constraints c!, x0 and bounds from docp ...
    nlp = ADNLPModels.ADNLPModel!(
        f, x0, lvar, uvar, c!, lcon, ucon; backend, options...,
    )
    # ADNLP needs no auxiliary cache
    return CTSolvers.BuiltModel(dm, nlp, CTSolvers.NoCache())
end

function CTSolvers.build_solution(
    built::CTSolvers.BuiltModel{
        <:CTSolvers.DiscretizedModel{<:Any,<:Collocation},
    },
    nlp_solution::SolverCore.AbstractExecutionStats,
    ::CTSolvers.Modelers.ADNLP,
)
    docp = built.problem.cache.docp
    # objective, iterations, status, …
    infos = CTSolvers.extract_solver_infos(nlp_solution)
    # ... time grid T from the NLP solution ...
    # the OCP solution
    return build_OCP_solution(docp, nlp_solution, T, infos...)
end

Displaying DiscretizedModel and BuiltModel ​

CTSolvers provides Base.show methods for both types. In the REPL, they are shown as a short tree, whose length does not depend on the grid size. This is the output for the double integrator discretized by CTDirect with grid_size=100 and the trapeze scheme:

text
julia> docp = CTSolvers.DOCP.discretize(ocp, CTDirect.Collocation(grid_size=100, scheme=:trapeze))
DiscretizedModel
├─ problem: state ∈ R², control ∈ R, times [0, 1]
├─ discretizer: Collocation(grid_size=100, scheme=trapeze, time_grid=nothing)
└─ cache: CTDirect.DOCPCache

julia> built = CTSolvers.Optimization.build_model(docp, init, CTSolvers.Modelers.ADNLP())
BuiltModel
├─ problem: DiscretizedModel(Collocation(grid_size=100, scheme=trapeze, time_grid=nothing))
├─ nlp: ADNLPModels.ADNLPModel (nvar=303, ncon=204)
└─ cache: CTSolvers.Optimization.NoCache

The compact form, used by print and inside other displays, fits on one line:

text
julia> print(docp)
DiscretizedModel(Collocation(grid_size=100, scheme=trapeze, time_grid=nothing))

What each line shows:

  • problem: for a CTModels model, the state, control and variable spaces (a space of dimension zero is omitted) and the time interval, where a free time is written by its name. For any other problem type, only its type name.

  • discretizer: the compact display of the strategy, with its options.

  • nlp: the type name of the NLP model with its numbers of variables and constraints. The sizes come from the CTSolversNLPModels extension, which is loaded whenever NLPModels is, for instance through ADNLPModels or ExaModels. Without it, only the type name is shown.

  • cache: only the type name. The cache is opaque to CTSolvers, and its contents (bounds, time grid, …) grow with the grid.

None of these lines contains type parameters.

Integration with the Pipeline ​

The complete data flow from user call to solution:

text
User
 │
 ▼  solve(docp, x0, modeler, solver)
CommonSolve.solve
 │
 ├─► build_model(docp, x0, modeler)
 │       │
 │       ├─► (CTDirect) ADNLPModels.ADNLPModel!(f, x0, …)  →  ADNLPModel
 │       └─► BuiltModel(docp, nlp, NoCache())
 │
 ├─► solve(nlp, solver) → ExecutionStats
 │
 └─► build_solution(built, stats, modeler)
         └─► (CTDirect) build_OCP_solution(docp, stats, …)  →  OCP solution

Separation of responsibilities:

  • CTSolvers declares build_model/build_solution and owns the NotImplemented stubs

  • CTDirect provides the concrete methods dispatched on (DiscretizedModel, ADNLP/Exa)

  • CTSolvers orchestrates the pipeline in CommonSolve.solve without knowing NLP internals

Summary: Adding a New Optimization Problem ​

To add a new optimization problem type that plugs into the CTSolvers pipeline:

  • Define MyProblem <: AbstractOptimizationProblem with your data fields

  • Implement CTSolvers.Optimization.build_model(prob::MyProblem, init, modeler::ADNLP) returning a BuiltModel

  • Implement CTSolvers.Optimization.build_solution(built::BuiltModel{<:MyProblem}, stats, modeler::ADNLP) returning your domain solution

  • Optionally add methods for other modelers (Exa, future backends) following the same dispatch pattern

  • If build_model produces auxiliary data needed by build_solution, store it in a custom <: CTBase.Core.AbstractCache subtype rather than NoCache

  • Optionally define Base.show for MyProblem: the display of a BuiltModel shows its problem by its type name only (see Displaying DiscretizedModel and BuiltModel)