diff --git a/src/aff_expr.jl b/src/aff_expr.jl index 69c230fb927..9377d16bc63 100644 --- a/src/aff_expr.jl +++ b/src/aff_expr.jl @@ -837,7 +837,16 @@ expressions. To make common operations like `lower_bound(x)` work, we should forward the method if and only if `x` is convertible to a `GenericVariableRef`. """ function _eval_as_variable(f::F, x::GenericAffExpr, args...) where {F} - if length(x.terms) != 1 + if !iszero(x.constant) + error( + """ + Cannot call `$f` with the affine expression `$x` because the expression \ + has a non-zero constant. + + `$f` can be called only with affine expressions of the form `1.0 * x`. + """, + ) + elseif length(x.terms) != 1 error( """ Cannot call `$f` with the affine expression `$x` because the expression diff --git a/test/test_expr.jl b/test/test_expr.jl index b86230924b8..921f73ecf50 100644 --- a/test/test_expr.jl +++ b/test/test_expr.jl @@ -507,6 +507,10 @@ function test_aff_expr_complex_HermitianPSDCone() ), start_value(imag(x[2, 1])), ) + return +end + +function test_eval_as_variable_no_terms() y = AffExpr(0.0) @test_throws( ErrorException( @@ -522,6 +526,24 @@ function test_aff_expr_complex_HermitianPSDCone() return end +function test_eval_as_variable_with_constant() + model = Model() + @variable(model, x, start = 1) + y = 1.0 * x + 2.0 + @test_throws( + ErrorException( + """ + Cannot call `$start_value` with the affine expression `$y` because \ + the expression has a non-zero constant. + + `$start_value` can be called only with affine expressions of the form `1.0 * x`. + """, + ), + start_value(y), + ) + return +end + function test_multiply_expr_MA_Zero() model = Model() @variable(model, x)