我有兴趣在线性程序中构建本质上是or语句的东西。目前我在 R 中使用 lpSolveAPI,但我也希望得到有关此类问题的线性编程最佳实践的答案。
这是使用 lpSolveAPI 包的一些工作代码:
library(lpSolveAPI)
# Defines the 'score' which we seek to maximize
mat <- data.frame(score = c(0.04, 0.04, -.11, -.03, 0.04, 0.04, -0.06, 0.01))
# Side specifies whether something is a 'sell' or a 'buy'
mat[, 'side'] <- c(1, 1, -1, -1, 1, 1, -1, -1)
# 'a' and 'b' are descriptive factors defining what something is thing a or thing b.
mat[, 'a'] <- c(1, 1, 1, 1, 0, 0, 0, 0)
mat[, 'b'] <- c(0, 0, 0, 0, 1, 1, 1, 1)
# the lower bound for all sides = -1 have a lower bound of some negative value and an upper bound of zero
mat[, "lb"] <- c(0, 0, -0.2, -0.4, 0, 0, -.1, -.2)
# the upper bound for all sides = 1 have a lower bound of zero and an upper bound of 1
mat[, 'ub'] <- c(1, 1, 0, 0, 1, 1, 0, 0)
# this is just initializing our variables field which will be populated later
mat[, 'x'] <- rep(0, 8)
# using the lpSolveAPI package, create a program with the number of rows in the matrix 'mat'
LP <- make.lp(0, nrow(mat))
set.objfn(LP, -mat[, 'score'])
set.bounds(LP, lower = mat[, 'lb'])
set.bounds(LP, upper = mat[, 'ub'])
# This constraint requires that the sum of all of x must be equal to zero. In other words, the amount of sells equals the amount of buys
add.constraint(LP, rep(1, nrow(mat)), "=", 0)
solve(LP)
get.objective(LP)
get.variables(LP)
mat$x <- get.variables(LP)
当您运行此代码并查看结果时,您会看到 x6 = 0.9、x7 = -0.1 和 x8 = -0.2。对此的解释是 90% 的b被购买而 30% 的b被出售。
我正在寻找建立一个约束,要求如果a或b在任何地方出售,它也不能被购买。(反之亦然)
在这种特殊情况下,我希望最佳解决方案是出售 20% 的a(x3)和购买 20% 的b(x5 或 x6)。x = (0, 0, -0.2, 0, 0.2, 0, 0, 0)
换句话说,如果您选择在 x1 和/或 x2 中具有非零值,则在 x3 和/或 x4 中必须具有 0。类似地,如果您选择在 x3 和/或 x4 中具有非零值,则在 x1 和 x2 中必须具有零值。