From a2b60c8d6f76000b7cde961b2683763137e60c71 Mon Sep 17 00:00:00 2001 From: ChrisRackauckas Date: Wed, 23 Jul 2025 00:48:57 -0400 Subject: [PATCH] Fix LBFGS iteration counter always showing 0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes #907 - Added iteration tracking to LBFGS callbacks so that OptimizationState.iter properly increments during optimization. Previously, the iteration counter was always 0 in callbacks because the LBFGS solver wasn't tracking iterations. Now uses a Ref counter that increments with each function evaluation. Changes: - Added iter_count = Ref(0) before _loss function definition - Increment iter_count[] in _loss function - Pass iter_count[] to OptimizationState constructor - Applied fix to both constrained and unconstrained cases 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- src/lbfgsb.jl | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/lbfgsb.jl b/src/lbfgsb.jl index c0ee97f60..5e8f14d98 100644 --- a/src/lbfgsb.jl +++ b/src/lbfgsb.jl @@ -116,13 +116,15 @@ function SciMLBase.__solve(cache::OptimizationCache{ cache.f.cons(cons_tmp, cache.u0) ρ = max(1e-6, min(10, 2 * (abs(cache.f(cache.u0, cache.p))) / norm(cons_tmp))) + iter_count = Ref(0) _loss = function (θ) x = cache.f(θ, cache.p) + iter_count[] += 1 cons_tmp .= zero(eltype(θ)) cache.f.cons(cons_tmp, θ) cons_tmp[eq_inds] .= cons_tmp[eq_inds] - cache.lcons[eq_inds] cons_tmp[ineq_inds] .= cons_tmp[ineq_inds] .- cache.ucons[ineq_inds] - opt_state = Optimization.OptimizationState(u = θ, objective = x[1]) + opt_state = Optimization.OptimizationState(u = θ, objective = x[1], iter = iter_count[]) if cache.callback(opt_state, x...) error("Optimization halted by callback.") end @@ -206,10 +208,12 @@ function SciMLBase.__solve(cache::OptimizationCache{ cache, cache.opt, res[2], cache.f(res[2], cache.p)[1], stats = stats, retcode = opt_ret) else + iter_count = Ref(0) _loss = function (θ) x = cache.f(θ, cache.p) + iter_count[] += 1 - opt_state = Optimization.OptimizationState(u = θ, objective = x[1]) + opt_state = Optimization.OptimizationState(u = θ, objective = x[1], iter = iter_count[]) if cache.callback(opt_state, x...) error("Optimization halted by callback.") end