Search code examples
rgenetic-algorithm

Error in in running genetic algorithm for a custom function in R


Goal

I want to estimate the 'best' parameters of the Intelligent Driver Car-Following Model (IDM). The 'best' refers to those parameters that produce the minimum root mean squared error between the observed and predicted speed. The following shows a reproducible example where I successfully used grid search to find the best parameters but I have been unsuccessful in running genetic algorithm to do the same.

Function for IDM

The following IDM function in R takes in 6 parameters and outputs a dataframe of 3 columns, acceleration rate a_i, speed v_i and distance g_x_i:

calculate_IDM <- function(A_i, 
         v_0, 
         g_0,
         g_t_i, 
         b_i, 
         small_delta){
  
  ####################
  ## Allocate Vectors
  ####################
  
  # acceleration rate
  a_i <- rep(NA_real_, time_length)
  
  # speed
  v_i <- rep(NA_real_, time_length)
  
  
  # position
  x_i <- rep(NA_real_, time_length)
  
  # spacing
  g_x_i <- rep(NA_real_, time_length)
  
  # speed difference
  delta_v_i <- rep(NA_real_, time_length)
  
  
  # desired spacing
  g_star_i <- rep(NA_real_, time_length)
  
  
  
   ##########################################
  ## Initial values for Following vehicle
  ##########################################
  
  # speed
  v_i[1] <- v_i_first
  
  # position
  x_i[1] <- x_i_first
  
  # spacing
  g_x_i[1] <- xn1_first - x_i_first
  
  # speed difference
  delta_v_i[1] <- v_i_first - vn1_first
  
  # desired spacing
  g_star_i[1] <- g_0 + max(0, (v_i[1] * g_t_i) + ((v_i[1] * delta_v_i[1]) / (2 * sqrt((A_i * b_i)))))
  
  
  # acceleration rate
  a_i[1] <- A_i * (1 - ((v_i[1] / v_0)^small_delta) - ((g_star_i[1] / g_x_i[1])^2))
  
  # a_i[1] <- ifelse(is.nan(a_i[1]), A_i, a_i[1])
  
  
  
  # speed
  v_i[2] <- v_i[1] + (a_i[1] * time_frame)
  
  ### if the speed is negative, make it zero
  v_i[2] <- ifelse(v_i[2] < 0, 0, v_i[2])
  
  
  
  # position
  x_i[2] <- x_i[1] + (v_i[1] * time_frame) + (0.5 * a_i[1] * (time_frame)^2)
  
  # spacing
  g_x_i[2] <- xn1_complete[2] - x_i[2]
  
  
  # speed difference
  delta_v_i[2] <- v_i[2] - vn1_complete[2]
  
  
  
  ####################
  ## IDM Calculations
  ####################
  
  
  for (t in 2:(time_length-1)) { 
    
    # desired spacing
    g_star_i[t] <- g_0 + max(0, (v_i[t] * g_t_i) + ((v_i[t] * delta_v_i[t]) / (2 * sqrt((A_i * b_i)))))
    
    
    # acceleration rate
    a_i[t] <- A_i * (1 - ((v_i[t] / v_0)^small_delta) - ((g_star_i[t] / g_x_i[t])^2))
    
    # a_i[t] <- ifelse(is.nan(a_i[t]), A_i, a_i[t])
    
    
    
    # speed
    v_i[t+1] <- v_i[t] + (a_i[t] * time_frame)
    
    ### if the speed is negative, make it zero
    v_i[t+1] <- ifelse(v_i[t+1] < 0, 0, v_i[t+1])
    
    
    
    # position
    x_i[t+1] <- x_i[t] + (v_i[t] * time_frame) + (0.5 * a_i[t] * (time_frame)^2)
    
    # spacing
    g_x_i[t+1] <- xn1_complete[t+1] - x_i[t+1]
    
    
    # speed difference
    delta_v_i[t+1] <- v_i[t+1] - vn1_complete[t+1]
    
    
  }
  
  data.frame(a_i, v_i, g_x_i)
}

Running the function with one set of parameters

To run the above function, the speed of the lead vehicle and Time vectors are required:

# Time
last_time <- 300 ## s
time_frame <- 0.1 ## s
Time <- seq(from = 0, to = last_time, by = time_frame)
time_length <- length(Time)


v_i_first <- 0
x_i_first <- 5


## Lead vehicle
vn1_first <- 0 ## first speed m/s
xn1_first <- 100 ## position of lead vehicle front center m
bn1_complete <- c(rep(x = 4, length.out = time_length-2951),
                  rep(x = 0, length.out = time_length-50)) ## acceleration rate 



#############################################
### Complete speed trajectory of Lead vehicle
#############################################

vn1_complete <- rep(NA_real_, time_length) ### an empty vector 
xn1_complete <- rep(NA_real_, time_length) ### an empty vector 

vn1_complete[1] <- vn1_first
xn1_complete[1] <- xn1_first

for (t in 2:time_length) { 
  
  ### Lead vehicle calculations
  vn1_complete[t] <- vn1_complete[t-1] + (bn1_complete[t-1] * time_frame)
  
  
  xn1_complete[t] <- xn1_complete[t-1] + (vn1_complete[t-1] * time_frame) + (0.5 * bn1_complete[t-1] * (time_frame)^2)
  
}

Now, I can apply the function:

## one example
dff <- calculate_IDM(4, 30, 6.5, 1, 4, 2)
head(dff)
       a_i       v_i    g_x_i
1 3.981274 0.0000000 95.00000
2 3.978206 0.3981274 95.00009
3 3.973594 0.7959480 95.00039
4 3.967446 1.1933075 95.00093
5 3.959771 1.5900521 95.00176
6 3.950581 1.9860292 95.00296

Using Grid Search to find best parameters:

The observed speed and the parameters list are as follows:

library(tidyverse)

obs_data <- tibble(
obs_v_i = dff$v_i
)

# Parameters list
parameters_grid <- list(
  A_i = c(2, 4),
  v_0 = c(27, 30),
  g_0 = c(6.5, 7),
  g_t_i = c(1, 3),
  b_i = c(4, 5),
  small_delta = c(2, 3)
) %>% 
  expand.grid() %>% 
  as_tibble()

The fitness function and 2 examples are below:

# Fitness function
fitness_func <- function(obs_data,
                         A_i, 
                         v_0, 
                         g_0,
                         g_t_i, 
                         b_i, 
                         small_delta) {
  
  df <- cbind(obs_data, calculate_IDM(A_i, 
                                v_0, 
                                g_0,
                                g_t_i, 
                                b_i, 
                                small_delta))
  
  sqrt(sum((df$obs_v_i - df$v_i)^2)/nrow(df))
  
}

> fitness_func(obs_data, 4, 30, 6.5, 1, 4, 2)
[1] 0
> fitness_func(obs_data, 2, 27, 7, 3, 5, 3)
[1] 1.406937

Now I can use the rowwise() function from dplyr to do grid search:

parameters_grid %>% 
  rowwise() %>% 
  mutate(RMSE = fitness_func(obs_data,
                             A_i, 
                             v_0, 
                             g_0,
                             g_t_i, 
                             b_i, 
                             small_delta))

# A tibble: 64 x 7
# Rowwise: 
     A_i   v_0   g_0 g_t_i   b_i small_delta    RMSE
   <dbl> <dbl> <dbl> <dbl> <dbl>       <dbl>   <dbl>
 1     2    27   6.5     1     4           2 1.68   
 2     4    27   6.5     1     4           2 0.213  
 3     2    30   6.5     1     4           2 1.65   
 4     4    30   6.5     1     4           2 0      
 5     2    27   7       1     4           2 1.68   
 6     4    27   7       1     4           2 0.218  
 7     2    30   7       1     4           2 1.65   
 8     4    30   7       1     4           2 0.00794
 9     2    27   6.5     3     4           2 1.57   
10     4    27   6.5     3     4           2 0.814  
# ... with 54 more rows

Error with Genetic Algorithm

You can imagine that if the parameters list is bigger it will increase the calculation time significantly. So, I want to run the genetic algorithm. Using the example here, I tried using the GA library to estimate the parameters but getting error:

library(GA)
GA <- ga(type = "real-valued", 
         fitness =  -fitness_func(obs_data,
                                 A_i, 
                                 v_0, 
                                 g_0,
                                 g_t_i, 
                                 b_i, 
                                 small_delta),
         lower = c(2, 27, 6.5, 1, 4, 2), upper = c(4, 30, 7, 3, 5, 3), 
         popSize = 5, maxiter = 10, run = 10)

 Error in calculate_IDM(A_i, v_0, g_0, g_t_i, b_i, small_delta) : 
  object 'g_0' not found 

Please let me know what I'm doing wrong here.


Solution

  • The fitness as documented in the ?ga is

    the fitness function, any allowable R function which takes as input an individual string representing a potential solution, and returns a numerical value describing its “fitness”.

    So, we could wrap it as a function with two arguments, and then use fitness_func arguments as x[1], x[2], ..., x[6] which would be the same length as the lower and upper bound values. Here, we can also pass the data separately

    library(GA)
    GA <- ga(type = "real-valued", 
             fitness =  function(dat, x) {-fitness_func(dat,
                                     x[1], 
                                     x[2], 
                                     x[3],
                                     x[4], 
                                     x[5], 
                                     x[6])},
              dat = obs_data,
             lower = c(2, 27, 6.5, 1, 4, 2), upper = c(4, 30, 7, 3, 5, 3), 
             popSize = 5, maxiter = 1000, run = 100)
    #GA | iter = 1 | Mean = -0.5668704 | Best = -0.3523867
    #GA | iter = 2 | Mean = -0.3762976 | Best = -0.3523867
    #GA | iter = 3 | Mean = -0.3529940 | Best = -0.3523867
    #GA | iter = 4 | Mean = -0.3523867 | Best = -0.3523867
    #GA | iter = 5 | Mean = -0.3523867 | Best = -0.3523867
    #GA | iter = 6 | Mean = -0.3523867 | Best = -0.3523867
    #GA | iter = 7 | Mean = -0.3523867 | Best = -0.3523867
    #GA | iter = 8 | Mean = -0.3640060 | Best = -0.3523867
    #...
    #GA | iter = 519 | Mean = -0.08506463 | Best = -0.08505393
    #GA | iter = 520 | Mean = -0.08505440 | Best = -0.08505393
    #GA | iter = 521 | Mean = -0.14507196 | Best = -0.08505393
    #GA | iter = 522 | Mean = -0.08505393 | Best = -0.08505393
    #GA | iter = 523 | Mean = -0.08505393 | Best = -0.08505393
    #GA | iter = 524 | Mean = -0.11238973 | Best = -0.08505393
    #GA | iter = 525 | Mean = -0.31888465 | Best = -0.08505393
    #GA | iter = 526 | Mean = -0.09641056 | Best = -0.08505393
    

    There is a warning at the end though