Skip to content

Commit

Permalink
Add methods for Base.complex (#3734)
Browse files Browse the repository at this point in the history
  • Loading branch information
odow authored Apr 17, 2024
1 parent 0f3f329 commit c99024d
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -531,3 +531,40 @@ function Base.:*(
)
return x * A
end

function Base.complex(
r::Union{
GenericVariableRef{<:Real},
GenericAffExpr{<:Real},
GenericQuadExpr{<:Real},
},
i::Real,
)
return r + im * i
end

function Base.complex(
r::Real,
i::Union{
GenericVariableRef{<:Real},
GenericAffExpr{<:Real},
GenericQuadExpr{<:Real},
},
)
return r + im * i
end

function Base.complex(
r::Union{
GenericVariableRef{<:Real},
GenericAffExpr{<:Real},
GenericQuadExpr{<:Real},
},
i::Union{
GenericVariableRef{<:Real},
GenericAffExpr{<:Real},
GenericQuadExpr{<:Real},
},
)
return r + im * i
end
11 changes: 11 additions & 0 deletions src/quad_expr.jl
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,17 @@ function GenericQuadExpr{V,K}(aff::GenericAffExpr{V,K}, kv::Pair...) where {K,V}
)
end

function GenericQuadExpr(
aff::GenericAffExpr{T,V},
quad::OrderedDict{UnorderedPair{V},S},
) where {T,S,V}
C = promote_type(T, S)
return GenericQuadExpr(
convert(GenericAffExpr{C,V}, aff),
convert(OrderedDict{UnorderedPair{V},C}, quad),
)
end

function Base.iszero(expr::GenericQuadExpr)
return iszero(expr.aff) && all(iszero, values(expr.terms))
end
Expand Down
16 changes: 16 additions & 0 deletions test/test_operator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -673,4 +673,20 @@ function test_matrix_abstractscalar_add()
return
end

function test_base_complex()
model = Model()
@variable(model, x)
for f in (x, 1.0 * x, x^2)
@test isequal_canonical(complex(3, f), 3 + im * f)
@test isequal_canonical(complex(f, 2.0), f + 2.0im)
end
for f in (x, 1.0 * x, x^2), g in (x, 1.0 * x, x^2)
@test isequal_canonical(complex(f, g), f + im * g)
end
@test_throws MethodError complex(x, 2im)
@test_throws MethodError complex(2im, x)
@test_throws MethodError complex(2.0 + x, im * x)
return
end

end

0 comments on commit c99024d

Please sign in to comment.