我想用JuMP和Julia解决一个简单的线性优化问题。 这是我的代码:
using JuMP
using Mosek
model = Model(solver=MosekSolver())
@variable(model, 2.5 <= z1 <= 5.0)
@variable(model, -1.0 <= z2 <= 1.0)
@objective(model, Min, abs(z1+5.0) + abs(z2-3.0))
status = solve(model)
println("Objective value: ", getobjectivevalue(model))
println("z1:",getvalue(z1))
println("z2:",getvalue(z2))
但是,我收到此错误消息。
> ERROR: LoadError: MethodError: no method matching
> abs(::JuMP.GenericAffExpr{Float64,JuMP.Variable}) Closest candidates
> are: abs(!Matched::Bool) at bool.jl:77 abs(!Matched::Float16) at
> float.jl:512 abs(!Matched::Float32) at float.jl:513
如何在JuMP代码中使用abs函数?
答案 0 :(得分:3)
@ rickhg12hs的通讯解决了我的问题。 如果我使用@NLobjective而不是@objective,它可以工作。 这是最终的代码。
using JuMP
using Mosek
model = Model(solver=MosekSolver())
@variable(model, 2.5 <= z1 <= 5.0)
@variable(model, -1.0 <= z2 <= 1.0)
@NLobjective(model, Min, abs(z1+5.0) + abs(z2-3.0))
status = solve(model)
println("Objective value: ", getobjectivevalue(model))
println("z1:",getvalue(z1))
println("z2:",getvalue(z2))
答案 1 :(得分:0)
我以不同的方式做到了
AvgOperationtime = [1 2]#[2.0 2.0 2.0 3.3333333333333335 2.5 2.0 2.0 2.5 2.5 2.0 2.0] Operationsnumberremovecounter = [1 0;1 1]#[1.0 1.0 1.0 1.0 -0.0 1.0 1.0 1.0 -0.0 1.0 1.0; 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0; 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0; 1.0 1.0 1.0 -0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0; 1.0 1.0 1.0 -0.0 1.0 1.0 1.0 -0.0 1.0 1.0 1.0] 型号 = 2 操作数 = 2 基本案例工作量 = 2 y = 0.1 最高数字 = 999 求解器 = GLPK.Optimizer #操作时间[1,1 X;0,9 2] m = 模型(with_optimizer(求解器)); @variable(m, Operationtime[1:Modelnumber,1:Operationsnumber]>=0); @variable(m, Absoluttime[1:Modelnumber,1:Operationsnumber]>=0); @variable(m, Absolutchoice[1:Modelnumber,1:Operationsnumber,1:2], Bin); @objective(m, Max, sum(Absoluttime[M,O]Operationsnumberremovecounter[M,O] for M=1:Modelnumber,O=1:Operationsnumber)) #多少时间可以不同 @constraint(m, BorderOperationtime1[M=1:Modelnumber,O=1:Operationsnumber], AvgOperationtime[O](1-y) <= Operationtime[M,O]); @constraint(m, BorderOperationtime2[M=1:Modelnumber,O=1:Operationsnumber], AvgOperationtime[O]*(1+y) >= Operationtime[M,O]); #工作量 @constraint(m, Worklimit[O=1:Operationsnumber], sum(Operationtime[M,O]*Operationsnumberremovecounter[M,O] for M=1:Modelnumber) == Basecaseworkload); #绝对 @constraint(m, Absolutchoice1[M=1:Modelnumber,O=1:Operationsnumber], sum(Absolutchoice[M,O,X] for X=1:2) == 1); @constraint(m, Absoluttime1[M=1:Modelnumber,O=1:Operationsnumber],Absoluttime[M,O] <= Operationtime[M,O]-AvgOperationtime[O]+Absolutchoice[M,O,1]*Highestnumber ); @constraint(m, Absoluttime2[M=1:Modelnumber,O=1:Operationsnumber],Absoluttime[M,O] <= AvgOperationtime[O]-Operationtime[M,O]+Absolutchoice[M,O,2]*Highestnumber );
optimize!(m);
println("Termination status: ", JuMP.termination_status(m));
println("Primal status: ", JuMP.primal_status(m));