Search code examples
rgenetic-algorithminteger-programming

Generalized Assignment Problem with Genetic Algorithms in R


How can I implement a Generalized Assignment Problem: https://en.wikipedia.org/wiki/Generalized_assignment_problem to be solved with Genetic Algorithms https://cran.r-project.org/web/packages/GA/GA.pdf in R.

I have a working example of the code but its not working:

require(GA)
p <- matrix(c(5, 1, 5, 1, 5, 5, 5, 5, 1), nrow = 3)
t <- c(2, 2, 2) 
w <- c(2, 2, 2)

assigment <- function(x) {
  f <- sum(x * p)
  penalty1 <- sum(w)*(sum(t)-sum(w*x))
  penalty2 <- sum(w)*(1-sum(x))
  f - penalty1 - penalty2  
}  

GA <- ga(type = "binary", fitness = assigment, nBits = length(p),
       maxiter = 1000, run = 200, popSize = 20)
summary(GA) 

Solution

  • It seems there are problems in your definition of the fitness function, i.e. the assigment() function.

    • x is a binary vector, and not a matrix as in the theory, so sum(x * p) is not doing what you likely expect (note that x has length 9 and p is a 3x3 matrix in your example);
    • the constrain on the sum of x_{ij} is not correctly taken into account by the penalty2 term;
    • the penalisations should act differently for penalty1 and penalty2, the first is an inequality (i.e. <=) while the second is a strict equality (i.e. =).
    • w is defined as a vector, but it should be a matrix of the same size as x