GLPK/Julia
外观
< GLPK
该GLPK.jl包允许以不同的方式在Julia中使用GLPK。在抽象层次不断提高的情况下,这些方式包括:(a) 直接使用(通过包装C API);(b) 作为MathOptInterface的接口;或者 (c) 作为代数建模语言JuMP.jl的“求解器引擎”。
例如,要解决问题 `Maxx,y x + 2y`,受限于 `x+y = 3` 且 `x,y >=0`,您可以编写以下代码:
(a) 使用GLPK C API包装器
using Pkg; Pkg.add("GLPK") # Just once to install the packages
using GLPK
lp = GLPK.Prob()
GLPK.set_obj_dir(lp, GLPK.MAX)
GLPK.add_rows(lp, 1)
GLPK.set_row_bnds(lp, 1, GLPK.FX, 3.0, 3.0)
GLPK.add_cols(lp, 2)
GLPK.set_col_bnds(lp, 1, GLPK.LO, 0.0, +Inf)
GLPK.set_obj_coef(lp, 1, 1.0)
GLPK.set_col_bnds(lp, 2, GLPK.LO, 0.0, +Inf)
GLPK.set_obj_coef(lp, 2, 2.0)
GLPK.set_mat_row(lp, 1, [1,2], [1,1]) # coefficients given in sparse form
param = GLPK.SimplexParam()
flag = GLPK.simplex(lp, param) # solves
GLPK.get_obj_val(lp) # 6
GLPK.get_col_prim(lp, 1) # 0
GLPK.get_col_prim(lp, 2) # 3
(c) 使用JuMP API
using Pkg; Pkg.add(["GLPK","JuMP"]) # Just once to install the packages
using GLPK, JuMP
model = Model(GLPK.Optimizer)
set_optimizer_attribute(model, "msg_lev", GLPK.MSG_OFF)
@variables model begin
x >= 0 # could be parts of n-dimensional arrays, like x[p in plants, m in markets]
y >= 0
end
@constraints model begin
bound1, x+y == 3
end
@objective model Max begin
x + 2*y
end
print(model)
optimize!(model)
objective_value(model) # 6
value(x) # 0
value(y) # 3