Skip to content

Commit 61067b7

Browse files
authored
Fix convert(::VariableIndex, ::ScalarAffineFunction) with zero coefficients (#2173)
1 parent 393825a commit 61067b7

File tree

3 files changed

+38
-6
lines changed

3 files changed

+38
-6
lines changed

.github/workflows/solver-tests.yml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ jobs:
6060
shell: julia --color=yes {0}
6161
run: |
6262
import Pkg
63+
Pkg.develop(Pkg.PackageSpec(; path = pwd()))
6364
Pkg.develop(ENV["PACKAGE"])
6465
Pkg.test(ENV["PACKAGE"])
6566
test-cplex:
@@ -95,6 +96,7 @@ jobs:
9596
SECRET_CPLEX_URL_2210: ${{ secrets.SECRET_CPLEX_URL_2210 }}
9697
run: |
9798
import Pkg
99+
Pkg.develop(Pkg.PackageSpec(; path = pwd()))
98100
Pkg.develop(ENV["PACKAGE"])
99101
Pkg.test(ENV["PACKAGE"])
100102
# TODO(odow): enable testing Xpress

src/functions.jl

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -701,14 +701,21 @@ end
701701
# VariableIndex
702702

703703
function Base.convert(::Type{VariableIndex}, f::ScalarAffineFunction)
704-
if (
705-
!iszero(f.constant) ||
706-
!isone(length(f.terms)) ||
707-
!isone(f.terms[1].coefficient)
708-
)
704+
if !iszero(f.constant)
705+
throw(InexactError(:convert, VariableIndex, f))
706+
end
707+
scalar_term = nothing
708+
for term in f.terms
709+
if isone(term.coefficient) && scalar_term === nothing
710+
scalar_term = term
711+
elseif !iszero(term.coefficient)
712+
throw(InexactError(:convert, VariableIndex, f))
713+
end
714+
end
715+
if scalar_term === nothing
709716
throw(InexactError(:convert, VariableIndex, f))
710717
end
711-
return f.terms[1].variable
718+
return scalar_term.variable::VariableIndex
712719
end
713720

714721
function Base.convert(

test/functions.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,29 @@ function test_functions_copy_VectorOfVariables()
4949
@test f.variables[2] == y
5050
end
5151

52+
function test_functions_convert_to_variable_index()
53+
model = MOI.Utilities.Model{Float64}()
54+
x = MOI.add_variable(model)
55+
y = MOI.add_variable(model)
56+
for f in (
57+
1.0 * x,
58+
1.0 * x + 0.0,
59+
1.0 * x + 0.0 * y + 0.0,
60+
0.0 * y + 1.0 * x + 0.0,
61+
)
62+
@test convert(MOI.VariableIndex, f) === x
63+
end
64+
for f in (
65+
1.0 * x + 0.5,
66+
0.5 * x + 0.0,
67+
1.0 * x + 1.0 * y + 0.0,
68+
MOI.ScalarAffineFunction(MOI.ScalarAffineTerm{Float64}[], 0.0),
69+
)
70+
@test_throws InexactError convert(MOI.VariableIndex, f)
71+
end
72+
return
73+
end
74+
5275
function test_functions_convert_VariableIndex()
5376
model = MOI.Utilities.Model{Float64}()
5477
x = MOI.add_variable(model)

0 commit comments

Comments
 (0)