shawn
shawn

Reputation: 21

How can i setup Gurobi environment in Julia by a function?

i am trying to use a code in a paper but the code for gurobi seems changed these days, it showed some error and i want to put the gurobi environment setting below into my optimization.

the gurobi environment setting is below :

function setup_gurobi_env(; quiet_mode = true, method_type = :barrier, use_time_limit = true, time_limit = 60.0)
    env = Gurobi.Env()

    if quiet_mode
        setparams!(env; OutputFlag = 0)
    end

    if method_type == :barrier
        setparams!(env; Method = 2)
    elseif method_type == :method3
        setparams!(env; Method = 3)
    elseif method_type != :default
        error("Enter a valid method type for Gurobi.")
    end

    if use_time_limit
        setparams!(env; TimeLimit = time_limit)
    end

    return env
end

the author of the paper use the method below to use this setting:

function portfolio_simplex_jump_setup(Sigma::Matrix{Float64}, gamma::Float64; gurobiEnv = setup_gurobi_env(method_type = :default, use_time_limit = false))
    (d, d2) = size(Sigma)

    if d != d2
        error("Sigma dimensions don't match")
    end

    mod = Model(with_optimizer(Gurobi.Optimizer, gurobiEnv))
    @variable(mod, w[1:d] >= 0)
    @constraint(mod, sum(w[i] for i = 1:d) <= 1)
    @constraint(mod, w'*Sigma*w <= gamma)

    function local_portfolio_oracle(c::Vector{Float64})
        @objective(mod, Min, dot(c, w))

        optimize!(mod)
        z_ast = objective_value(mod)
        w_ast = value.(w)

        return (z_ast, w_ast)
    end

    return c -> local_portfolio_oracle(c)
end

i changed the function into this but it still showed error for not be able to use gurobi since my coding is too old.

function portfolio_simplex_jump_setup(; gurobiEnv = setup_gurobi_env(method_type = :default, use_time_limit = false))

    mod = Model(Gurobi.Optimizer)
    @variable(mod, 0 <=w[1:d] <= 1)
    @constraint(mod, sum(w[i] for i = 1:d) <= 3)
  

    function local_portfolio_oracle(c::Vector{Float64})
        @objective(mod, Min, dot(c, w))

        optimize!(mod)
        z_ast = objective_value(mod)
        w_ast = value.(w)

        return (z_ast, w_ast)
    end

    return c -> local_portfolio_oracle(c)
end

i think the problem is in here

mod = Model(with_optimizer(Gurobi.Optimizer, gurobiEnv))

maybe gurobi just upload the new coding method?

Thank you to everyone who replied to me~

Upvotes: 2

Views: 325

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42214

This is the current pattern to use Gurobi (taken from one of my academic codes):

const GRB_ENV = Gurobi.Env()
m = Model(()->Gurobi.Optimizer(GRB_ENV))
set_optimizer_attribute(m, "OutputFlag", 0)
set_optimizer_attribute(m, "TimeLimit", 100)
set_optimizer_attribute(m, "MIPGap", 0.001)
set_optimizer_attribute(m, "Threads", min(length(Sys.cpu_info()),16))

Upvotes: 3

Related Questions