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

OptimizerWithAttributes direct model constructor #2614

Merged
merged 6 commits into from
May 27, 2021
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
29 changes: 29 additions & 0 deletions src/JuMP.jl
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,35 @@ function direct_model(backend::MOI.ModelLike)
)
end

"""
direct_model(factory::MOI.OptimizerWithAttributes)
Create a [`direct_model`](@ref) using `factory`, a `MOI.OptimizerWithAttributes`
object created by [`optimizer_with_attributes`](@ref).
## Example
```julia
model = direct_model(
optimizer_with_attributes(
Gurobi.Optimizer,
"Presolve" => 0,
"OutputFlag" => 1,
)
)
```
is equivalent to:
```julia
model = direct_model(Gurobi.Optimizer())
set_optimizer_attribute(model, "Presolve", 0)
set_optimizer_attribute(model, "OutputFlag", 1)
```
"""
function direct_model(factory::MOI.OptimizerWithAttributes)
optimizer = MOI.instantiate(factory)
return direct_model(optimizer)
end

Base.broadcastable(model::Model) = Ref(model)

"""
Expand Down
14 changes: 14 additions & 0 deletions test/model.jl
Original file line number Diff line number Diff line change
Expand Up @@ -609,6 +609,20 @@ function test_copy_direct_mode()
@test_throws ErrorException JuMP.copy(model)
end

function test_direct_mode_using_OptimizerWithAttributes()
function fake_optimizer()
return MOIU.MockOptimizer(
MOI.Utilities.UniversalFallback(MOI.Utilities.Model{Float64}()),
)
end

optimizer = optimizer_with_attributes(fake_optimizer, "a" => 1, "b" => 2)
model = JuMP.direct_model(optimizer)
@test model.moi_backend isa MOIU.MockOptimizer
@test MOI.get(model.moi_backend, MOI.RawParameter("a")) == 1
@test MOI.get(model.moi_backend, MOI.RawParameter("b")) == 2
end

function test_copy_expr_aff()
model = Model()
@variable(model, x)
Expand Down