Skip to content

Commit 42668d1

Browse files
authored
Add checks and tests for NaN in constraints (#2272)
1 parent a62cc35 commit 42668d1

File tree

3 files changed

+29
-1
lines changed

3 files changed

+29
-1
lines changed

src/aff_expr.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -329,6 +329,12 @@ function _assert_isfinite(a::AffExpr)
329329
for (coef, var) in linear_terms(a)
330330
isfinite(coef) || error("Invalid coefficient $coef on variable $var.")
331331
end
332+
if isnan(a.constant)
333+
error(
334+
"Expression contains an invalid NaN constant. This could be " *
335+
"produced by `Inf - Inf`."
336+
)
337+
end
332338
end
333339

334340
"""

src/macros.jl

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,6 +312,9 @@ end
312312
# three-argument build_constraint is used for two-sided constraints.
313313
function build_constraint(_error::Function, func::AbstractJuMPScalar,
314314
lb::Real, ub::Real)
315+
if isnan(lb) || isnan(ub)
316+
_error("Invalid bounds, cannot contain NaN: [$(lb), $(ub)].")
317+
end
315318
return build_constraint(_error, func, MOI.Interval(Float64(lb), Float64(ub)))
316319
end
317320

@@ -1182,7 +1185,7 @@ macro variable(args...)
11821185
_error("Ambiguous variable name $x detected. To specify an anonymous binary " *
11831186
"variable, use `@variable(model, binary = true)` instead.")
11841187
elseif x == :PSD
1185-
_error("Size of anonymous square matrix of positive semidefinite anonymous variables is not specified. To specify size of square matrix " *
1188+
_error("Size of anonymous square matrix of positive semidefinite anonymous variables is not specified. To specify size of square matrix " *
11861189
"use `@variable(model, [1:n, 1:n], PSD)` instead.")
11871190
end
11881191
anon_singleton = false

test/macros.jl

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,25 @@ end
631631
) @NLparameter(model, p[axes(A)...] == x)
632632
end
633633

634+
@testset "NaN in constraints" begin
635+
model = Model()
636+
@variable(model, x >= 0)
637+
@test_throws(
638+
ErrorException(
639+
"Expression contains an invalid NaN constant. This could be produced by `Inf - Inf`."
640+
),
641+
@constraint(model, x >= NaN)
642+
)
643+
@test_throws ErrorException(
644+
"Expression contains an invalid NaN constant. This could be produced by `Inf - Inf`."
645+
) @constraint(model, 1 <= x + NaN <= 2)
646+
@test_throws ErrorException(
647+
"Expression contains an invalid NaN constant. This could be produced by `Inf - Inf`."
648+
) @constraint(model, 1 <= x + Inf <= 2)
649+
@test_throws ErrorException(
650+
"In `@constraint(model, 1 <= x <= NaN)`: Invalid bounds, cannot contain NaN: [1, NaN]."
651+
) @constraint(model, 1 <= x <= NaN)
652+
end
634653
end
635654

636655
@testset "Macros for JuMPExtension.MyModel" begin

0 commit comments

Comments
 (0)