2017-06-20 67 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

這工作一種享受!非常感謝!!! –