@@ -12,7 +12,8 @@ SciMLBase.allowsbounds(opt::Union{NLopt.Algorithm, NLopt.Opt}) = true
1212 SciMLBase. supports_opt_cache_interface (opt:: Union{NLopt.Algorithm, NLopt.Opt} ) = true
1313end
1414@static if isdefined (OptimizationBase, :supports_opt_cache_interface )
15- OptimizationBase. supports_opt_cache_interface (opt:: Union{NLopt.Algorithm, NLopt.Opt} ) = true
15+ OptimizationBase. supports_opt_cache_interface (opt:: Union {
16+ NLopt. Algorithm, NLopt. Opt}) = true
1617end
1718
1819function SciMLBase. requiresgradient (opt:: Union{NLopt.Algorithm, NLopt.Opt} )
@@ -70,7 +71,8 @@ function __map_optimizer_args!(cache::OptimizationBase.OptimizationCache, opt::N
7071 kwargs... )
7172
7273 # Check if AUGLAG algorithm requires local_method
73- if opt. algorithm ∈ (NLopt. LN_AUGLAG, NLopt. LD_AUGLAG, NLopt. AUGLAG) && local_method === nothing
74+ if opt. algorithm ∈ (NLopt. LN_AUGLAG, NLopt. LD_AUGLAG, NLopt. AUGLAG) &&
75+ local_method === nothing
7476 error (" NLopt.$(opt. algorithm) requires a local optimization method. " *
7577 " Please specify a local_method, e.g., solve(prob, NLopt.$(opt. algorithm) (); " *
7678 " local_method = NLopt.LN_NELDERMEAD())" )
@@ -167,6 +169,15 @@ function SciMLBase.__solve(cache::OptimizationBase.OptimizationCache{
167169}
168170 local x
169171
172+ # Check if algorithm requires gradients but none are provided
173+ opt = cache. opt isa NLopt. Opt ? cache. opt. algorithm : cache. opt
174+ if SciMLBase. requiresgradient (opt) && isnothing (cache. f. grad)
175+ throw (OptimizationBase. IncompatibleOptimizerError (
176+ " The NLopt algorithm $(opt) requires gradients, but no gradient function is available. " *
177+ " Please use `OptimizationFunction` with an automatic differentiation backend, " *
178+ " e.g., `OptimizationFunction(f, AutoForwardDiff())`, or provide gradients manually via the `grad` kwarg." ))
179+ end
180+
170181 _loss = function (θ)
171182 x = cache. f (θ, cache. p)
172183 opt_state = OptimizationBase. OptimizationState (u = θ, p = cache. p, objective = x[1 ])
0 commit comments