[R] Maximum number of iterations (maxit) does not work in hydroPSO-modFit-optimr in r

Ahmed Attia @hmed@ti@80 @ending from gm@il@com
Wed Oct 3 19:30:56 CEST 2018


The argument maxit used in libraries optimr, hydroPSO, and FME to
control the maximal number of iterations to be performed does not work
at ALL!!

This needs to be fixed...



mysamp <- function(n, m, s, lwr, upr, nnorm) {
  samp <- rnorm(nnorm, m, s)
  samp <- samp[samp >= lwr & samp <= upr]
  if (length(samp) >= n) {
    return(sample(samp, n))
  }
  stop(simpleError("Not enough values to sample from. Try increasing nnorm."))
}

x <- mysamp(1000,0.8117648,0.1281839,0,1,1000000)
y <- mysamp(1000,0.7530346,0.1865946,0,1,1000000)

n <- length(x)
xgroup <- c('a','b')
ygroup <- c('c','d')

for (i in c(2:n)){
  xgroup[i] <-  c('b')
  ygroup[i] <-  c('d')
}

dataset <- data.frame(x = x, y = y, xgroup = as.factor(xgroup),
                      ygroup = as.factor(ygroup))
dataset$ObsNo <- 1:n
dataset <- dataset[order(dataset$x,decreasing=F),]

xopt <- c(dataset$x[1],0.95)    #Initial critical x,y values


my.function <- function(xopt){
  for (i in c(1:n)){
    dataset$xgroup[i] <- if(dataset$x[i] < xopt[1]) 'a' else 'b'
    dataset$ygroup[i] <- if(dataset$y[i] < xopt[2]) 'c' else 'd'
    dataset$q.i[i] <- with(dataset, ifelse
                           (dataset$xgroup[i]=='a' &
dataset$ygroup[i]=='d', 1, 0))
    dataset$q.ii[i] <- with(dataset, ifelse
                            (dataset$xgroup[i]=='b' &
dataset$ygroup[i]=='d', 1, 0))
    dataset$q.iii[i] <- with(dataset, ifelse
                             (dataset$xgroup[i]=='b' &
dataset$ygroup[i]=='c', 1, 0))
    dataset$q.iv[i] <- with(dataset, ifelse
                            (dataset$xgroup[i]=='a' &
dataset$ygroup[i]=='c', 1, 0))

    dataset$q.err[i] <- sum(dataset$q.i[i] + dataset$q.iii[i])
  }
  min.qerr <- sum(dataset$q.err)
  q.I <- sum(dataset$q.i)
  q.II <- sum(dataset$q.ii)
  q.III <- sum(dataset$q.iii)
  q.IV <- sum(dataset$q.iv)
  q.Iandq.III <- sum(dataset$q.err)
  print(c(q.I,
          q.II,
          q.III,
          q.IV,
          q.Iandq.III))
  return(min.qerr)
}

my.function(xopt)

#-------Algorithm

xmin=c(0,0.60)
xmax=c(0.95,0.95)

res= hydroPSO(par=xopt,my.function,method="spso2011",
              lower=xmin,upper=xmax,control=list(maxit=3))


res= modFit(my.function,p=xopt,method="Pseudo",
            lower=xmin,upper=xmax,control=list(numiter=3))

res= optimr(par=xopt,my.function,method="L-BFGS-B",
            lower=xmin,upper=xmax,control=list(maxit=3,trace=T))

#Only the hjkb form dfoptim that has argument maxfeval and it works.

res=hjkb(par=xopt,my.function,
         lower=xmin,upper=xmax,control=list(maxfeval=3,tol=2^-10,info=T))






Ahmed Attia, Ph.D.
Agronomist & Crop Modeler



More information about the R-help mailing list