Skip to content

Better error message when gradient is required but not available #865

@LilithHafner

Description

@LilithHafner

When running an optimizer that requires a gradient on a problem without a specified gradient, the error message is not as helpful as it could be:

julia> using Optimization

julia> f(u,p) = u[1]^2+p[1]
f (generic function with 1 method)

julia> optf = OptimizationFunction(f)
(::OptimizationFunction{true, SciMLBase.NoAD, typeof(f), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, typeof(SciMLBase.DEFAULT_OBSERVED_NO_TIME), Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing}) (generic function with 1 method)

julia> u0 = [1.0]
1-element Vector{Float64}:
 1.0

julia> p = [1.0]
1-element Vector{Float64}:
 1.0

julia> prob = OptimizationProblem(optf, u0, p)
OptimizationProblem. In-place: true
u0: 1-element Vector{Float64}:
 1.0

julia> sol = solve(prob, Optimization.LBFGS())
ERROR: MethodError: objects of type Nothing are not callable
The object of type `Nothing` exists, but no method is defined for this combination of argument types when trying to treat it as a callable object.
Stacktrace:
 [1] (::LBFGSB.L_BFGS_B)(func::Optimization.var"#16#28"{…}, grad!::Nothing, x0::Vector{…}, bounds::Matrix{…}; m::Int64, factr::Float64, pgtol::Float64, iprint::Int64, maxfun::Int64, maxiter::Int64)
   @ LBFGSB ~/.julia/packages/LBFGSB/UZibA/src/wrapper.jl:62
 [2] __solve(cache::OptimizationCache{…})
   @ Optimization ~/.julia/packages/Optimization/cfp9i/src/lbfgsb.jl:240
 [3] solve!
   @ ~/.julia/packages/SciMLBase/0ZQSg/src/solve.jl:186 [inlined]
 [4] #solve#718
   @ ~/.julia/packages/SciMLBase/0ZQSg/src/solve.jl:94 [inlined]
 [5] solve(::OptimizationProblem{true, OptimizationFunction{…}, Vector{…}, Vector{…}, Nothing, Nothing, Nothing, Nothing, Nothing, Nothing, @Kwargs{}}, ::Optimization.LBFGS)
   @ SciMLBase ~/.julia/packages/SciMLBase/0ZQSg/src/solve.jl:91
 [6] top-level scope
   @ REPL[9]:1
Some type information was truncated. Use `show(err)` to see complete types.

It would be nice to give a specific "gradient provider required" error with a hint on how to fix it.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions