Julia+JuMP:函数的可变参数数量 [英] Julia+JuMP: variable number of arguments to function
问题描述
我正在尝试使用 JuMP 来解决非线性问题,其中变量的数量由用户决定 - 也就是说,在编译时不知道.
I'm trying to use JuMP to solve a non-linear problem, where the number of variables are decided by the user - that is, not known at compile time.
为此,@NLobjective
行如下所示:
@eval @JuMP.NLobjective(m, Min, $(Expr(:call, :myf, [Expr(:ref, :x, i) for i=1:n]...)))
例如,如果 n=3
,编译器会将该行解释为与以下内容相同:
Where, for instance, if n=3
, the compiler interprets the line as identical to:
@JuMP.NLobjective(m, Min, myf(x[1], x[2], x[3]))
问题是 @eval
只能在全局范围内工作,当包含在函数中时,会抛出错误.
The issue is that @eval
works only in the global scope, and when contained in a function, an error is thrown.
我的问题是:我怎样才能完成同样的功能——让 @NLobjective
用可变数量的 调用
参数——在函数的本地、编译时未知范围内?myf
>x[1],...,x[n]
My question is: how can I accomplish this same functionality -- getting @NLobjective
to call myf
with a variable number of x[1],...,x[n]
arguments -- within the local, not-known-at-compilation scope of a function?
def testme(n)
myf(a...) = sum(collect(a).^2)
m = JuMP.Model(solver=Ipopt.IpoptSolver())
JuMP.register(m, :myf, n, myf, autodiff=true)
@JuMP.variable(m, x[1:n] >= 0.5)
@eval @JuMP.NLobjective(m, Min, $(Expr(:call, :myf, [Expr(:ref, :x, i) for i=1:n]...)))
JuMP.solve(m)
end
testme(3)
谢谢!
推荐答案
如 http://jump.readthedocs.io/en/latest/nlp.html#raw-expression-input ,可以在没有宏的情况下给出目标函数.相关表达:
As explained in http://jump.readthedocs.io/en/latest/nlp.html#raw-expression-input , objective functions can be given without the macro. The relevant expression:
JuMP.setNLobjective(m, :Min, Expr(:call, :myf, [x[i] for i=1:n]...))
甚至比基于 @eval
的更简单,并且可以在函数中使用.代码是:
is even simpler than the @eval
based one and works in the function. The code is:
using JuMP, Ipopt
function testme(n)
myf(a...) = sum(collect(a).^2)
m = JuMP.Model(solver=Ipopt.IpoptSolver())
JuMP.register(m, :myf, n, myf, autodiff=true)
@JuMP.variable(m, x[1:n] >= 0.5)
JuMP.setNLobjective(m, :Min, Expr(:call, :myf, [x[i] for i=1:n]...))
JuMP.solve(m)
return [getvalue(x[i]) for i=1:n]
end
testme(3)
然后它返回:
julia> testme(3)
:
EXIT: Optimal Solution Found.
3-element Array{Float64,1}:
0.5
0.5
0.5
这篇关于Julia+JuMP:函数的可变参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!