Per the docs, it looks like the right way to handle an error that occurs within an objective function during .optimize() is to call .force_stop():
In certain cases, the caller may wish to force the optimization to halt, for some reason unknown to NLopt. For example, if the user presses Ctrl-C, or there is an error of some sort in the objective function. In this case, it is possible to tell NLopt to halt the optimization gracefully, returning the best point found so far, by calling this function from within your objective or constraint functions.
However, currently .force_stop() requires a mutable reference to the optimizer, and if one of those exists (like, in a closure or something), it's impossible to call .optimize(), so it doesn't seem like this pattern is actually possible.
More generally, even if it were, it's pretty awkward, because at the time the closure or whatnot that's being used as the objective function is created, the optimizer doesn't exist yet, so there's not really a clean way to build this functionality. I'm not sure what the best way is to address that, though maybe the most idiomatic would be some way to have an objective function with the signature (&[f64], Option<&mut [f64]>, T) -> Result<f64, E> that automatically does the force_stop behind the scenes on error?
Per the docs, it looks like the right way to handle an error that occurs within an objective function during
.optimize()is to call.force_stop():However, currently
.force_stop()requires a mutable reference to the optimizer, and if one of those exists (like, in a closure or something), it's impossible to call.optimize(), so it doesn't seem like this pattern is actually possible.More generally, even if it were, it's pretty awkward, because at the time the closure or whatnot that's being used as the objective function is created, the optimizer doesn't exist yet, so there's not really a clean way to build this functionality. I'm not sure what the best way is to address that, though maybe the most idiomatic would be some way to have an objective function with the signature
(&[f64], Option<&mut [f64]>, T) -> Result<f64, E>that automatically does theforce_stopbehind the scenes on error?