Skip to content

Commit

Permalink
Fix converting Number to GenericNonlinearExpr (#3672)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Feb 10, 2024
1 parent e2149bf commit 7181551
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/nlp_expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -698,6 +698,13 @@ function Base.promote_rule(
return GenericNonlinearExpr{V}
end

function Base.promote_rule(
::Type{GenericNonlinearExpr{V}},
::Type{<:Number},
) where {V<:AbstractVariableRef}
return GenericNonlinearExpr{V}
end

function Base.promote_rule(
::Type{GenericNonlinearExpr{V}},
::Type{<:Union{GenericAffExpr{C,V},GenericQuadExpr{C,V}}},
Expand All @@ -709,6 +716,10 @@ function Base.convert(::Type{GenericNonlinearExpr{V}}, x::V) where {V}
return GenericNonlinearExpr{V}(:+, Any[x])
end

function Base.convert(::Type{GenericNonlinearExpr{V}}, x::Number) where {V}
return GenericNonlinearExpr{V}(:+, Any[x])
end

function Base.convert(
::Type{<:GenericNonlinearExpr},
x::GenericAffExpr{C,V},
Expand Down
16 changes: 16 additions & 0 deletions test/test_nlp_expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1019,4 +1019,20 @@ function test_convert_vector_aff_expr()
return
end

function test_convert_float_nonlinear_expr()
model = Model()
@variable(model, x)
@test [0.0, x, sin(x)] isa Vector{NonlinearExpr}
@test [0.0, sin(x), x] isa Vector{NonlinearExpr}
@test [x, 0.0, sin(x)] isa Vector{NonlinearExpr}
@test [x, sin(x), 0.0] isa Vector{NonlinearExpr}
@test [sin(x), 0.0, x] isa Vector{NonlinearExpr}
@test [sin(x), x, 0.0] isa Vector{NonlinearExpr}
@test isequal_canonical(
convert(NonlinearExpr, 2),
NonlinearExpr(:+, Any[2]),
)
return
end

end # module

0 comments on commit 7181551

Please sign in to comment.