Skip to content

Commit

Permalink
Merge pull request #1420 from JuliaOpt/bl/factoryfun
Browse files Browse the repository at this point in the history
Allow Function and UnionAll in with_optimizer
  • Loading branch information
blegat committed Aug 15, 2018
2 parents b659bde + 4cb7d0a commit 329aa51
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/JuMP.jl
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ struct OptimizerFactory
# * `Function`: a function, or
# * `DataType`: a type, or
# * `UnionAll`: a type with missing parameters.
constructor::Union{Function, DataType, UnionAll}
constructor
args::Tuple
kwargs # type changes from Julia v0.6 to v0.7 so we leave it untyped for now
end

"""
with_optimizer(constructor::Type, args...; kwargs...)
with_optimizer(constructor, args...; kwargs...)
Return an `OptimizerFactory` that creates optimizers using the constructor
`constructor` with positional arguments `args` and keyword arguments `kwargs`.
Expand All @@ -102,7 +102,13 @@ the constructor call `IpoptOptimizer(print_level=0)`:
with_optimizer(IpoptOptimizer, print_level=0)
```
"""
function with_optimizer(constructor::Type, args...; kwargs...)
function with_optimizer(constructor,
args...; kwargs...)
if !applicable(constructor, args...)
error("$constructor is does not have any method with arguments $args.",
"The first argument of `with_optimizer` should be callable with",
" the other argument of `with_optimizer`.")
end
return OptimizerFactory(constructor, args, kwargs)
end

Expand Down
26 changes: 26 additions & 0 deletions test/model.jl
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,29 @@ end
@test_throws ErrorException @constraint model 0 <= x + 1 <= 1
end
end

struct Optimizer
a::Int
b::Int
end
function f(a::Int; b::Int = 1)
return Optimizer(a, b)
end

@testset "Factories" begin
factory = with_optimizer(Optimizer, 1, 2)
@test factory.constructor == Optimizer
@test factory.args == (1, 2)
optimizer = factory()
@test optimizer isa Optimizer
@test optimizer.a == 1
@test optimizer.b == 2
@test_throws ErrorException factory = with_optimizer(f, 1, 2)
factory = with_optimizer(f, 1, b = 2)
@test factory.constructor == f
@test factory.args == (1,)
optimizer = factory()
@test optimizer isa Optimizer
@test optimizer.a == 1
@test optimizer.b == 2
end

0 comments on commit 329aa51

Please sign in to comment.