# Example:  The response function is the negative of Rosenbrock's banana 
# function in two dimensions.  The response function has a maximum value of 
# 0 at the input point (x1, x2) = (1, 1).  For illustration 
# the level set of interest is defined by the -50 contour, which is non-convex 
# and highly curved.  Also for illustration, the feasible region is set to 
# be the half-plane x1 >= -2.
#
# This script creates and saves (as 'banana_2dEx.rda' in directory '../../data') 
# a list with components:
#  fobj : 'fnObj' object with the response function and its gradient, input  
#      space specifications, and feasible region function.
#  thresh : Scalar with the contour value defining the level set 
#      of interest (-50).
#  rect0 : 'inpRect' object with an initial hyper-rectangle in input 
#      space, to guide the search for the level set boundary.

# 02 Jan 2026 / Richard Raubertas

local({
  respf <- function(x, inclGrad=FALSE) {
    y <- -1 * (100*((x[, 2] - x[, 1]^2)^2) + (1 - x[, 1])^2)
    if (inclGrad) {
      grad <- cbind(400*(x[, 1]*(x[, 2] - x[, 1]^2)) + 2*(1 - x[, 1]), 
                    -200*(x[, 2] - x[, 1]^2))
      attr(y, "gradient") <- grad
    }
    y
  }
  feasf <- function(x) {
       (x[, 1] >= -2)
  }
  fobj <- fnObj(c("x1", "x2"), respfn=respf, feasfn=feasf, hasgrad=TRUE)
  
  # Level set of interest:
  thresh <- -50
  
  # Initial search region:
  rect0 <- inpRect(cbind(c(-3, 3), c(-3, 6)), spec=fobj)
  
  banana_2dEx <- list(fobj=fobj, thresh=thresh, rect0=rect0)
  
  objs <- c("banana_2dEx")
  for (obj in objs) {
    save(list=obj, file=paste0("../../data/", obj, ".rda"), compress=TRUE)
  }

  # Clean up.  (This may not be necessary due to 'local()' wrap.)
  rm(respf, feasf, fobj, thresh, rect0, banana_2dEx, obj, objs)
})

if (FALSE) {
  # Code like this can be inserted at the start of example sections of 
  # help pages for functions that work with 'fnObj' objects:
  Ex <- banana_2dEx  # see '?banana_2dEx'
  fobj <- Ex$fobj
  thresh <- Ex$thresh
  rect0 <- Ex$rect0
  
}