Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add explanatory error message for VariableNotOwned errors #3520

Merged
merged 2 commits into from
Sep 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions src/variables.jl
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,41 @@ struct VariableNotOwned{V<:AbstractVariableRef} <: Exception
variable::V
end

function Base.showerror(io::IO, err::VariableNotOwned)
return print(
io,
"""
$err: the variable $(err.variable) cannot be used in this model because
it belongs to a different model.

## Explanation

Each variable belongs to a particular model. You cannot use a variable
inside a model to which it does not belong. For example:

```julia
model = Model()
@variable(model, x >= 0)
model2 = Model()
@objective(model2, Min, x) # Errors because x belongs to `model`
```

One common cause of this error is working with a main problem and a
subproblem.

```julia
model = Model()
@variable(model, x, Bin)
subproblem = Model()
@variable(subproblem, 0 <= x <= 1)
# The Julia binding `x` now refers to `subproblem[:x]`, not `model[:x]`
@objective(model, Min, x) # Errors because x belongs to `subproblem`
# do instead
@objective(model, Min, model[:x])
```""",
)
end

"""
check_belongs_to_model(func::AbstractJuMPScalar, model::AbstractModel)

Expand Down
9 changes: 9 additions & 0 deletions test/test_model.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1207,4 +1207,13 @@ function test_bridges_add_remove_coefficient_type()
return
end

function test_show_variable_not_owned()
model = Model()
@variable(model, x)
err = VariableNotOwned(x)
contents = sprint(showerror, err)
@test occursin("## Explanation", contents)
return
end

end # module TestModels