在 CVXR 中为 objective 函数传递一个字符串
Pass a string for objective function in CVXR
我正在尝试围绕 CVXR 编写一个包装函数,这样 'objective' 和 'constraint' 就可以通过函数传递。我使用以下示例:
示例:
x1 <- Variable(1) # a scalar
x2 <- Variable(1) # a scalar
objective <- Minimize( x1^2 + x2^2 )
constraints <- list(x1 <= 0, x1 + x2 == 0)
problem <- Problem(objective, constraints)
## Checking problem solution
solution <- solve(problem)
我目前的尝试:
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars = c("x1", "x2")
obj = "x1^2 + x2^2"
const = "(x1 <= 0, x1 + x2 == 0)"
for(i in 1:length(vars)) {assign(vars[i], Variable(1, name = vars[i]))}
objective <- eval(paste("Minimize(", obj, ")"))
}
问题:
objective 变量的计算结果不是 x1^2 + x2^2,而是带引号的。我试过 as.formula、eval、substitute 等
也许你可以尝试 parse
和 eval
如下所示
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars <- c("x1", "x2")
obj <- "x1^2 + x2^2"
const <- "(x1 <= 0, x1 + x2 == 0)"
for (i in 1:length(vars)) {
assign(vars[i], Variable(1, name = vars[i]))
}
objective <- eval(parse(text = paste("Minimize(", obj, ")")))
constraints <- eval(parse(text = paste("list", const)))
problem <- Problem(objective, constraints)
solve(problem)
}
我正在尝试围绕 CVXR 编写一个包装函数,这样 'objective' 和 'constraint' 就可以通过函数传递。我使用以下示例:
示例:
x1 <- Variable(1) # a scalar
x2 <- Variable(1) # a scalar
objective <- Minimize( x1^2 + x2^2 )
constraints <- list(x1 <= 0, x1 + x2 == 0)
problem <- Problem(objective, constraints)
## Checking problem solution
solution <- solve(problem)
我目前的尝试:
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars = c("x1", "x2")
obj = "x1^2 + x2^2"
const = "(x1 <= 0, x1 + x2 == 0)"
for(i in 1:length(vars)) {assign(vars[i], Variable(1, name = vars[i]))}
objective <- eval(paste("Minimize(", obj, ")"))
}
问题:
objective 变量的计算结果不是 x1^2 + x2^2,而是带引号的。我试过 as.formula、eval、substitute 等
也许你可以尝试 parse
和 eval
如下所示
foo <- function(vars, const, obj) {
# for testing these values are passed inside
vars <- c("x1", "x2")
obj <- "x1^2 + x2^2"
const <- "(x1 <= 0, x1 + x2 == 0)"
for (i in 1:length(vars)) {
assign(vars[i], Variable(1, name = vars[i]))
}
objective <- eval(parse(text = paste("Minimize(", obj, ")")))
constraints <- eval(parse(text = paste("list", const)))
problem <- Problem(objective, constraints)
solve(problem)
}