# Genetic algorithm with constraint in R

I am trying to estimate a set of parameters using a genetic algorithm in R with the 'GA' package. So far I am doing something very simple (which works):

library(GA)
df <- data.frame(DM=c(1000,1500),
c1=c(50,75),
c2=c(90,105))

func <- function(x1, x2, theta) theta[1]*x1 + theta[2]*x2
fitnessL2 <- function(theta, x1, x2, y) {
f <- -sum((y - func(x1, x2, theta))^2)
}
GA2 <- ga(type = "real-valued", fitness = fitnessL2,
x1 = df$c1, x2 = df$c2, y = df$DM, names = c("a", "b"), min = c(0, 0), max = c(100, 100))  which produces values for a,b. However, I want to constrain a and b not individually, but as something like a + b == 20. Can someone please let me know if this is possible? Thanks in advance. ## 1 Answer If you have$a+b=20$, you have only one parameter, say$a$; the second is just$20-a$. This way you only need to tweak the function a bit and you are left with a single, simple constraint over$a$. • Thanks, but in reality I have something with about 20 parameters so more like A+B+C+D+E.... = 20. I need to know if this situation is possible. Feb 11, 2014 at 14:05 • Ok, it is hard to tell without the full knowledge of what constraints do you have, but it still holds that it is better to use the constraint to simplify the fitness function than to limit the search to some crazy subspace. Even if this is impossible, there is still an option to make a "smooth constraint", i.e. add something like$A\cdot C(\mathbf{p})^2$to your fitness, where$C(\mathbf{p})=0$is your problematic constraint,$\mathbf{p}$are the parameters and$A\$ is something that makes this term larger than the fitness deviations near the optimum.
– user88
Feb 11, 2014 at 14:44