Search code examples
roptimizationfitness

how do i print iterations in fitness function


I want to monitor the progress of the algorithm in order to understand how long the algorithm will work I would like to see something like

for(i in 1:100) print( paste("iter number",i))
[1] "iter number 1"
[1] "iter number 2"
[1] "iter number 3"
[1] "iter number 4"
[1] "iter number 5"
[1] "iter number 6"
[1] "iter number 7"

I tried to do something like this, but my counter is not updating.

i <- 0
fit <- function(x) {
  
  ##/// my count
  i <- i+1
  print( paste("iter number",i))
  ##////
  
  
  y <- numeric(2)
  y[1] <- crossprod(x, x)
  y[2] <- crossprod(x - 5, x - 5)

  return (y)
}

when I run the optimization algorithm I get the following result

library(mco)
ns <- nsga2(fit, 2, 2,
            generations=150, popsize=100,
            lower.bounds=rep(-5, 2),
            upper.bounds=rep(10, 2))

[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"
[1] "iter number 1"

How can this be done correctly?


Solution

  • As explained in the comments, here a small demo.

    This is because i will only be updated within your function and not outside your function. That is why your function does not print 0 but prints 1 all the time. Because of the environment. What you can do is change i <- i+1 to i <<- i+1 and i will be updated outside the function.

    Simple demo

    i <- 0
    z <- 0
    
    fit <- function() {
      i <- i + 1
      print(paste("i iter number:", i))
      z <<- z + 1 # note the <<- instead of <-
      print(paste("z iter number:", z))
    }
    
    for(x in 1:3) fit()
    
    [1] "i iter number: 1"
    [1] "z iter number: 1"
    [1] "i iter number: 1"
    [1] "z iter number: 2"
    [1] "i iter number: 1"
    [1] "z iter number: 3"
    
    i # is still 0
    [1] 0
    z # is now 3
    [1] 3