Anatole
Anatole

Reputation: 43

How to pass non-optimizing arguments into fitness function in GA package

I use GA package in R (an R package for optimisation using genetic algorithms) and need to optimize fitness function F(x1, x2, A_dataframe, b_const), where x1 - variable for optimization, min=0, max=1. x2 - variable for optimization, min=2, max=3. A_dataframe - a data frame which is not optimization variable, but known data frame needed for fitness function calculation. b_const - a constant variable which is not for optimization too, but known variable needed for fitness function calculation. So fitness function=F.

I try to use the next code.

TotalFunction <- function(A_dataframe, b_const) {

    F <- function(x1, x2, A_dataframe, b_const) {
        #code of fitness function
    }

    GA <- ga(type="real-valued", fitness=function(x) F(x[1], x[2], A_dataframe, b_const),
    A_dataframe, b_const, min=c(0, 2), max=(1, 3), popSize=50, maxiter=100)

    return(GA)
}     

Could you help me create right ga-function. Is it possible to pass a known data frame into fitness function through ga-function? Thanks a lot.

Upvotes: 4

Views: 814

Answers (1)

Artem Sokolov
Artem Sokolov

Reputation: 13691

I suggest moving your fitness function outside of TotalFunction to improve readability and avoid name collision / confusion.

F <- function( x1, x2, A_dataframe, b_const ) {
    #code of fitness function
}

Given the above definition of F, you can call the ga function with pre-specified values of A_dataframe and b_const as following:

## A <- ... define your data frame
## B <- ... define your constant
result <- ga(type="real-valued", fitness=function(x) F(x[1], x[2], A, b),
    min=c(0, 2), max=(1, 3), popSize=50, maxiter=100)

This will correctly utilize your fitness function F using pre-defined values of parameters A_dataframe, and b_const. To make this dynamically depend on A and B, we can wrap this into a function:

ga_Ab <- function( A, b )
{
  ga(type="real-valued", fitness=function(x) F(x[1], x[2], A, b),
    min=c(0, 2), max=(1, 3), popSize=50, maxiter=100)
}

Upvotes: 5

Related Questions