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
行如下所示:
To accomplish this, the @NLobjective
line looks like this:
@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.
我的问题是:我如何才能实现相同的功能-在可变的x[1],...,x[n]
自变量中让@NLobjective
调用myf
–在本地(未知)中-at-compilation的功能范围?
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屋!