Skip to content

Commit

Permalink
Add error message for Matrix ± AbstractJuMPScalar (#3557)
Browse files Browse the repository at this point in the history
  • Loading branch information
jd-foster authored Nov 2, 2023
1 parent b11f744 commit 944e5c5
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/operators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,23 @@ function LinearAlgebra.issymmetric(x::Matrix{T}) where {T<:_JuMPTypes}
end
return true
end

function Base.:+(A::AbstractMatrix, x::AbstractJuMPScalar)
return error(
"Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " *
"do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " *
"do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
)
end

Base.:+(x::AbstractJuMPScalar, A::AbstractMatrix) = A + x

function Base.:-(A::AbstractMatrix, x::AbstractJuMPScalar)
return error(
"Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " *
"do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " *
"do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
)
end

Base.:-(x::AbstractJuMPScalar, A::AbstractMatrix) = A - x
39 changes: 39 additions & 0 deletions test/test_operator.jl
Original file line number Diff line number Diff line change
Expand Up @@ -625,4 +625,43 @@ function test_complex_pow()
return
end

function test_matrix_abstractscalar_add()
model = Model()
@variable(model, x)
A = rand(Float64, 2, 2)
@test_throws(
ErrorException(
"Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " *
"do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " *
"do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
),
A + x
),
@test_throws(
ErrorException(
"Addition between a Matrix and a JuMP variable is not supported: instead of `A + x`, " *
"do `A .+ x` for element-wise addition, or if you are modifying the diagonal entries of the matrix " *
"do `A + x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
),
x + A
),
@test_throws(
ErrorException(
"Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " *
"do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " *
"do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
),
A - x
),
@test_throws(
ErrorException(
"Subtraction between a Matrix and a JuMP variable is not supported: instead of `A - x`, " *
"do `A .- x` for element-wise subtraction, or if you are modifying the diagonal entries of the matrix " *
"do `A - x * LinearAlgebra.I(n)`, where `n` is the diagonal length.",
),
x - A
),
return
end

end

0 comments on commit 944e5c5

Please sign in to comment.