r - 从 lpSolve 转换为 lpSolveAPI 包
问题描述
目标:使用当前 lpSolve 代码使用 lpSolveAPI 包创建新代码。
背景:我一直在使用 lpSolve 寻找最佳解决方案,以创建梦幻体育比赛阵容,最大限度地提高团队中球员的预计得分 (DK) 与允许的最高总工资 (SALARY) - 与少数其他约束条件以适应竞赛规则。然而,我在少数情况下发现 lpSolve 无法找到最佳解决方案。它似乎由于某种未知原因而忽略了最佳积分/美元解决方案,而是仅找到第 n 个最佳解决方案。不幸的是,我没有这样的例子,因为我的存档驱动器最近出现了问题并且丢失了很多数据。
我的研究/提问:我在这里阅读了与 lpSolve 有类似问题的其他线程(比如这里的这个)。在这些情况下,lpSolveAPI 能够看到 lpSolve 无法看到的最佳解决方案。由于不熟悉 lpSolveAPI,我正在寻求熟悉这两个包的人的帮助,以将我当前的代码转换为利用 lpSolveAPI 包并消除未来的 lpSolve 监督。我试过了,但由于某种原因,我一直在翻译中迷失方向。
我的 lpSolve 代码:
# count the number of unique teams and players
unique_teams = unique(slate_players$TEAM)
unique_players = unique(slate_players$PLAYERID)
# define the objective for the solver
obj = slate_players$DK
# create a constraint matrix for the solver
con = rbind(t(model.matrix(~ POS + 0, slate_players)), #Positions
t(model.matrix(~ PLAYERID + 0, slate_players)), #DupPlayers
t(model.matrix(~ TEAM + 0, slate_players)), #SameTeam
rep(1,nrow(slate_players)), #TotPlayers
slate_players$SALARY) #MaxSalary
# set the direction for each of the constraints
dir = c("==", #1B
"==", #2B
"==", #3B
"==", #C
"==", #OF
"==", #SP
"==", #SS
rep('<=',length(unique_players)), #DupPlayers
rep('<=',length(unique_teams)), #SameTeam
"==", #TotPlayers
"<=") #MaxSalary
# set the limits for the right-hand side of the constraints
rhs = c(1, #1B
1, #2B
1, #3B
1, #C
3, #OF
2, #SP
1, #SS
rep(1,length(unique_players)), #DupPlayers
rep(5,length(unique_teams)), #SameTeam
10, #TotPlayers
50000) #MaxSalary
# find the optimal solution using the solver
result = lp("max", obj, con, dir, rhs, all.bin = TRUE)
# create a data frame for the players in the optimal solution
solindex = which(result$solution==1)
optsolution = slate_players[solindex,]
谢谢您的帮助!
解决方案
这应该很简单:
library(lpSolveAPI)
ncons <- nrow(con)
nvars <- length(obj)
lprec <- make.lp(nrow=ncons, ncol=ncols)
set.objfn(lprec, obj)
set.type(lprec, 1:nvars, "binary") # all.bin=TRUE
for (i in 1:ncons) {
set.row(lprec, row=i, xt=con[i,])
set.constr.type(lprec, dir[i], constraints=i)
set.rhs(lprec, b=rhs[i], constraints=i)
}
status <- solve(lprec)
if(status!=0) stop("no solution found, error code=", status)
sol <- get.variables(lprec)
此代码未经测试,因为您的问题缺少数据引用并且没有预期的解决方案。
推荐阅读
- javascript - 如何进行firebase多路径推送?
- node.js - pm2重启时如何保留ram数据?Nodejs
- python - Python函数没有返回任何值
- python - 当小部件中的其他内容更改宽度时,PyQt Image(pixmap) 会被裁剪
- jwt - Auth0 如何使用 Lock 登录,然后根据我自己的数据库验证用户?
- mysql - Mysql Workbench - 将 sql 脚本从 ER 图中导出到数据库
- android - 如何将每天的上午 9:00 与 Android 系统时间进行比较?
- json - 如何获取 fetch 方法的返回值以放入警报中?
- javascript - 带函数参数的函数
- python - python和join混淆