从lpSolve转换为lpSolveAPI程序包

问题描述 投票:0回答:1

目标:使用当前的lpSolve代码使用lpSolveAPI程序包创建新代码。

背景:我一直在使用lpSolve来找到最佳解决方案,以创建幻想体育比赛阵容,该阵容将团队中球员的预计得分(DK)与允许的最高总薪水(薪水)-带有一些其他限制条件以适应比赛规则。我发现了一些实例,但是lpSolve找不到最佳的解决方案。由于某种未知原因,它似乎忽略了最佳积分/美元解决方案,而只找到了第n个最佳解决方案。不幸的是,我没有这个例子,因为我最近的存档驱动器出现问题,丢失了很多数据。

我的研究/要求:我在这里阅读了其他与lpSolve(like this one here)存在类似问题的线程。在那些情况下,当lpSolve无法看到时,lpSolveAPI能够看到最佳解决方案。我不熟悉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,]

谢谢您的帮助!

r optimization linear-programming integer-programming lpsolve
1个回答
0
投票

这应该很简单:

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)

此代码未经测试,因为您的问题缺少数据引用,也没有预期的解决方案。

© www.soinside.com 2019 - 2024. All rights reserved.