Skip to content

Commit

Permalink
OptimizerWithAttributes direct model constructor (#2614)
Browse files Browse the repository at this point in the history
* OptimizerWithAttributes direct model constructor

* fix whitespace

* change implementation

* add test

* use current MOI

* change docstring according to pr feedback
  • Loading branch information
jd-lara authored May 27, 2021
1 parent 02b1b6d commit 5bdec26
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
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

0 comments on commit 5bdec26

Please sign in to comment.