我正在寻找一种方法来解决-在R中-形式的约束优化问题
min sum(x)
s.t. f(x) < k其中x是长度为n的二元变量(0或1),f(x)是依赖于整个x变量的函数,k是整数常量。因此,f( x )不是对x的每个值(例如sqrt(x))的n个约束的集合,而是基于二元变量x的整个值集所满足的约束。
我尝试使用具有以下语法的ompr R包
v < 1:10
result <- MILPModel() %>%
add_variable(x[i], i = 1:v, type = "binary") %>%
set_objective(sum_expr(x[i], i = 1:v), sense = "min") %>%
add_constraint(f(x) <= 60) %>%
solve_model(with_ROI(solver = "glpk"))但是它不起作用,因为我相信这个包不接受全局f(x)约束。
发布于 2019-09-09 19:16:07
这是一个使用rgenoud包的解决方案。
library(rgenoud)
g <- function(x){
c(
ifelse(sd(x) > 0.2, 0, 1), # set the constraint (here sd(x)>0.2) in this way
sum(x) # the objective function (to minimize/maximize)
)
}
solution <- genoud(
g, lexical = 2,
nvars = 30,
starting.values = rep(0, 30),
Domains = cbind(rep(0,30), rep(1,30)),
data.type.int = TRUE)
solution$par # the values of x
## [1] 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
sd(solution$par) # is the constraint satisfied ?
## [1] 0.2537081
solution$value
## [1] 0 2 ; 0 is the value of ifelse(sd(x)>0.2,0,1) and 2 is the value of sum(x)要理解lexical参数,请参阅?genoud中的Notes部分。
https://stackoverflow.com/questions/57850149
复制相似问题