2017-06-20 52 views
2

我想在R(LPsolve)中运行LP,但是我的组合之一应该永远不会发生。例如,如果我正在尝试配对男性和女性(不是人类:-))来最大化函数值(下面称为“级别”的矩阵)。然而,其中一个男性是女性的一个完整的兄弟,所以我不希望这种交配永远发生(例如,下面矩阵中的男性1 &女性1)。我希望所有的女性交配(即约束),并且我希望所有男性有2次交配(只有2次交配)(另一个约束)。我试着让[1,1]交配真的是负面的,这可以帮助,但我希望它是愚蠢的证据。我试过NA,NULL等,但无济于事。 在此先感谢R:LPsolve(线性编程)“缺失值”

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 

回答

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 
+1

这工作一种享受!非常感谢!!! –