# JuMP 如何将优化问题嵌套进另一个优化中

using JuMP

import Ipopt

function ss1(z)

``````mss1 = Model(Ipopt.Optimizer)

set_silent(mss1)

@variable(

mss1,

x[1:7]

#[2.6,0.7,17,7.3,7.3,2.9,5] <= x[1:7] <= [3.6,0.8,28,8.3,8.3,3.9,5.5]

)

@expression(

mss1,

J1,

sum((x-z).^2)

)

@objective(

mss1,

Min,

sum((x-z).^2)

)

@NLconstraints(

mss1,

begin

27*x[1]^(-1)*x[2]^(-2)*x[3]^(-1)-1 <= 0

397.5*x[1]^(-1)*x[2]^(-2)*x[3]^(-2)-1 <= 0

x[2]*x[3]-40 <= 0

x[1]/x[2]-12 <= 0

5-x[1]/x[2] <= 0

end

)

@constraints(

mss1,

begin

[2.6,0.7,17,7.3,7.3,2.9,5] .<= x[1:7]

x[1:7] .<= [3.6,0.8,28,8.3,8.3,3.9,5.5]

end

)

optimize!(mss1)

return value(J1)
``````

end

function ss2(z)

``````mss2 = Model(Ipopt.Optimizer)

set_silent(mss2)

@variable(

mss2,

x[1:7]

)

@expression(

mss2,

J2,

sum((x-z).^2)

)

@objective(

mss2,

Min,

sum((x-z).^2)

)

@NLconstraints(

mss2,

begin

27*x[1]^(-1)*x[2]^(-2)*x[3]^(-1)-1 <= 0

97.5*x[1]^(-1)*x[2]^(-2)*x[3]^(-2)-1 <= 0

1.93*x[2]^(-1)*x[3]^(-1)*x[4]^3*x[6]^(-4)-1 <= 0

((745*x[4]/(x[2]*x[3]))^2+1.69*1e7)^(1/2)/(0.1*x[6]^3)-1100 <= 0

x[2]*x[3]-40 <= 0

x[1]/x[2]-12 <= 0

5-x[1]/x[2] <= 0

(1.5*x[6]+1.9)*x[4]^(-1)-1 <= 0

end

)

@constraints(

mss2,

begin

[2.6,0.7,17,7.3,7.3,2.9,5] .<= x[1:7]

x[1:7] .<= [3.6,0.8,28,8.3,8.3,3.9,5.5]

end

)

optimize!(mss2)

return value(J2)
``````

end

function ss3(z)

``````mss3 = Model(Ipopt.Optimizer)

set_silent(mss3)

@variable(

mss3,

x[1:7]

)

@expression(

mss3,

J3,

sum((x-z).^2)

)

@objective(

mss3,

Min,

sum((x-z).^2)

)

@NLconstraints(

mss3,

begin

27*x[1]^(-1)*x[2]^(-2)*x[3]^(-1)-1 <= 0

397.5*x[1]^(-1)*x[2]^(-2)*x[3]^(-2)-1 <= 0

1.93*x[2]^(-1)*x[3]^(-1)*x[5]^3*x[7]^(-4)-1 <= 0

((745*x[4]/(x[2]*x[3]))^2+1.69*1e7)^(1/2)/(0.1*x[6]^3)-1100 <= 0

((745*x[5]/(x[2]*x[3]))^2+1.575*1e8)^(1/2)/(0.1*x[7]^3)-850 <= 0

x[2]*x[3]-40 <= 0

x[1]/x[2]-12 <= 0

5-x[1]/x[2] <= 0

(1.1*x[7]+1.9)*x[5]^(-1)-1 <= 0

end

)

@constraints(

mss3,

begin

[2.6,0.7,17,7.3,7.3,2.9,5] .<= x[1:7]

x[1:7] .<= [3.6,0.8,28,8.3,8.3,3.9,5.5]

end

)

optimize!(mss3)

return value(J3)
``````

end

function opt()

``````msys = Model(Ipopt.Optimizer)

set_silent(msys)

@variable(

msys,

x[1:7]

)

@expressions(

msys,

begin

J1, ss1(x)^2

J2, ss2(x)^2

J3, ss3(x)^2

end

)

@NLobjective(

msys,

Min,

0.7854*x[1]*x[2]^2*(3.333*x[3]^2+14.933*x[3]-43.0934)-1.508*x[1]*(x[6]^2+x[7]^2)+7.447*(x[6]^3+x[7]^3)+0.7854*(x[4]*x[6]^2+x[5]*x[7]^2)

)

@NLconstraints(

msys,

begin

J1 <= 1e-5

J2 <= 1e-5

J3 <= 1e-5

end

)

@constraints(

msys,

begin

[2.6,0.7,17,7.3,7.3,2.9,5] .<= x[1:7]

x[1:7] .<= [3.6,0.8,28,8.3,8.3,3.9,5.5]

end

)

optimize!(sys)

return value(x)
``````

end

opt()

min obj_opt
s.t. J1<=1E-5
J2<=1E-5
J3<=1E-5

1、我印象里面好像Ipopt不支持隐函数？可以看看user-defined-functions那块。
2、你的子函数能顺利运行吗？
3、或者你看能不能把问题转化一下，一步优化到位