---
title: "Three ways to call the user functions"
author: "Fabrice Zaoui"
date: "October 01 2020"
output: html_document
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{Options for the carallel parameter}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Short Description

**caRamel** is a multiobjective evolutionary algorithm combining the MEAS algorithm and the NGSA-II algorithm.

Download the package from CRAN or [GitHub](https://github.com/fzao/caRamel) and then install and load it.

```{r caRa}
library(caRamel)
```

There are three possible choices on how **caRamel** can call the R user functions. Each choice is parameterized by the *carallel* value.

# Sequential or parallel mode

The computation of the user functions can be done sequentially or in parallel for each individual of the genetic population according to the choice of *carallel* when calling **caRamel**.

The evaluation of the population is done in a sequential mode if *carallel* is 0, or in parallel if *carallel* is 1 (this last one is the default option).

For these two options, the R user function takes a single input parameter *i* giving the number of the individual of the population *x*. For instance:

```{r kursawe1}
kursawe <- function(i) {
  k1 <- -10 * exp(-0.2 * sqrt(x[i,1] ^ 2 + x[i,2] ^ 2)) - 10 * exp(-0.2 * sqrt(x[i,2] ^2 + x[i,3] ^ 2))
  k2 <- abs(x[i,1]) ^ 0.8 + 5 * sin(x[i,1] ^ 3) + abs(x[i,2]) ^ 0.8 + 5 * sin(x[i,2] ^3) + abs(x[i,3]) ^ 0.8 + 5 * sin(x[i,3] ^ 3)
  return(c(k1, k2))
}
```

Two objectives are evaluated here and a vector of the corresponding values is returned for the individual *x[i,]*.

# User-defined mode

If the value of *carallel* is 2 then the entire population is given to the R user function and one has to decide how to evaluate it. For instance hereafter with a simple for-loop:

```{r kursawe2}
kursawe <- function(x) { # receipt of the entire population
  popsize <- dim(x)[1] # size of the population to evaluate
  nobj <- 2 # number of objectives
  results <- matrix(0, nrow = popsize, ncol = nobj) # matrix of results
  for(i in 1:popsize){
      k1 <- -10 * exp(-0.2 * sqrt(x[i,1] ^ 2 + x[i,2] ^ 2)) - 10 * exp(-0.2 * sqrt(x[i,2] ^2 + x[i,3] ^ 2))
      k2 <- abs(x[i,1]) ^ 0.8 + 5 * sin(x[i,1] ^ 3) + abs(x[i,2]) ^ 0.8 + 5 * sin(x[i,2] ^3) + abs(x[i,3]) ^ 0.8 + 5 * sin(x[i,3] ^ 3)
      results[i,] <- c(k1, k2)
  }
  return(results)
}
```

