我试图在R(LPsolve)中运行LP,但我的组合之一永远不会发生。例如,如果我试图交配男性和女性(而不是人类:-))以最大化功能值(矩阵称为"排名"下面)。然而,其中一个男性是一个女性的完整兄弟所以我不希望交配永远发生(例如男性1和女性1在下面的矩阵中)。我希望所有的雌性交配(即约束),我希望所有雄性都有2只交配(另一种约束)。我试图让[1,1]交配真正消极,这可以帮助但我希望它是万无一失的。我尝试过NA,NULL等但无济于事。 提前致谢
rank <- matrix (0,3, 6) # matrix of males (rows) x females (columns) with the value to maximize for each combination
for (i in 1:3) {
for (j in 1:6)
{
rank[i,j] <-i*j
}
}
m <- NROW(rank) #number of males
f <- NCOL(rank) # number of females
row.signs <- c(rep("=", m))
row.rhs <- c(rep(2,m))
col.signs <- rep ("=", f)
col.rhs <- c(rep(1,f))
lp.transport (rank, "max", row.signs, row.rhs, col.signs, col.rhs)$solution
答案 0 :(得分:1)
我认为您不能使用默认的运输问题公式来定义该约束... 我建议您手动定义运输问题,然后添加排除约束:
library(lpSolve)
m <- 3 # n of males
f <- 6 # n of females
# rank matrix
rank <- matrix(1:(m*f),nrow=m)
# sibling exclusions (where the matrix is 1, we don't allow mating for that combination)
# here we block male 1 with female 1
exclusions <- matrix(0,nrow=m,ncol=f)
exclusions[1,1] <- 1
# transportation problem definition
obj <- as.numeric(rank)
nMalePerFemaleRhs <- rep(1,f)
nMalePerFemaleSign <- rep("=",f)
nMalePerFemaleConstr <- matrix(0,nrow=f,ncol=m*f)
for(i in 1:f){
nMalePerFemaleConstr[i,(i-1)*m+(1:m)] <- 1
}
nFemalePerMaleRhs <- rep(2,m)
nFemalePerMaleSign <- rep("=",m)
nFemalePerMaleConstr <- matrix(0,nrow=m,ncol=m*f)
for(i in 1:m){
nFemalePerMaleConstr[i,seq(from=i,length.out=f,by=m)] <- 1
}
# sibling exclusions constraint
siblingConstr <- t(as.numeric(exclusions))
siblingRhs <- 0
siblingSign <- '='
res <- lp(direction='max',
objective.in=obj,
const.mat = rbind(nMalePerFemaleConstr,nFemalePerMaleConstr,siblingConstr),
const.dir = c(nMalePerFemaleSign,nFemalePerMaleSign,siblingSign),
const.rhs = c(nMalePerFemaleRhs,nFemalePerMaleRhs,siblingRhs),
all.int = TRUE
)
solutionMx <- matrix(res$solution,nrow=m)
结果:
> solutionMx
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 0 0 0 0 1 1
[2,] 0 0 1 1 0 0
[3,] 1 1 0 0 0 0