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)
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);penalty2
term;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