Skip to content

Commit 00925e3

Browse files
SebastianM-Cclaude
andcommitted
Fix Lagrangian Hessian prototype dimensions in OptimizationDIExt
The Lagrangian Hessian prototype was incorrectly sized as (num_constraints × num_variables) instead of (num_variables × num_variables). This caused a `BoundsError` when computing the Lagrangian Hessian with more variables than constraints, as the prototype was used as a buffer for the n×n Hessian matrix. Changes: - Fix lag_hess_prototype initialization to use zeros(Bool, length(x), length(x)) in both in-place and out-of-place function instantiation - Add tests to verify prototype dimensions This ensures the Lagrangian Hessian is always correctly sized as n×n regardless of the number of constraints, matching the mathematical definition of the Lagrangian Hessian as the second derivative with respect to the decision variables. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
1 parent 654f65f commit 00925e3

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

lib/OptimizationBase/src/OptimizationDIExt.jl

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ function instantiate_function(
198198
lag_prep = prepare_hessian(
199199
lagrangian, soadtype, x, Constant(one(eltype(x))),
200200
Constant(ones(eltype(x), num_cons)), Constant(p))
201-
lag_hess_prototype = zeros(Bool, num_cons, length(x))
201+
lag_hess_prototype = zeros(Bool, length(x), length(x))
202202

203203
function lag_h!(H::AbstractMatrix, θ, σ, λ)
204204
if σ == zero(eltype(θ))
@@ -457,7 +457,7 @@ function instantiate_function(
457457
lag_prep = prepare_hessian(
458458
lagrangian, soadtype, x, Constant(one(eltype(x))),
459459
Constant(ones(eltype(x), num_cons)), Constant(p))
460-
lag_hess_prototype = zeros(Bool, num_cons, length(x))
460+
lag_hess_prototype = zeros(Bool, length(x), length(x))
461461

462462
function lag_h!(θ, σ, λ)
463463
if σ == zero(eltype(θ))

lib/OptimizationBase/test/adtests.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,17 @@ optprob.cons_h(H3, x0)
144144
optprob.lag_h(H4, x0, σ, μ)
145145
@test H4σ * H2 + μ[1] * H3[1] rtol=1e-6
146146

147+
# Test that the AD-generated lag_hess_prototype has correct dimensions
148+
@test !isnothing(optprob.lag_hess_prototype)
149+
@test size(optprob.lag_hess_prototype) == (length(x0), length(x0)) # Should be n×n, not num_cons×n
150+
151+
# Test that we can actually use it as a buffer
152+
if !isnothing(optprob.lag_hess_prototype)
153+
H_proto = similar(optprob.lag_hess_prototype, Float64)
154+
optprob.lag_h(H_proto, x0, σ, μ)
155+
@test H_proto σ * H2 + μ[1] * H3[1] rtol=1e-6
156+
end
157+
147158
G2 = Array{Float64}(undef, 2)
148159
H2 = Array{Float64}(undef, 2, 2)
149160

0 commit comments

Comments
 (0)