content
stringlengths
0
14.9M
filename
stringlengths
44
136
**xaringanthemer** includes a number of functions that provide themed **xaringan** styles. All of the styling functions start with the `style_` prefix. The goal of each style function is to quickly set up a coordinated color palette for your slides based on one or two starter colors. Styles based on one color start with `style_mono_` and styles based on two colors start with `style_duo_`. How the starter colors are used is described in the final portion of the style function name. For example, `style_mono_accent()` uses a single color as an accent color. Note that the colors used below are for demonstration only, the point of the `style_` functions is for you to choose your own color palette! If your color palette uses more than two colors, you can add additional colors with the `colors` argument. See the [Colors](#colors) section for more information. ### Monotone ```{r include=FALSE} IS_README <- exists("IS_README") && IS_README include_graphic <- function(img_path) { glue::glue( '<img src="https://raw.githubusercontent.com/gadenbuie/', 'xaringanthemer/assets/{img_path}" data-external="1" />' ) } ``` Use these functions to automatically create a consistent color palette for your slides, based around a single color. #### `style_mono_light()` A light theme based around a single color. ```{r style_mono_light} demo_function_call <- function(f, n_params = 1) { cat(sep = "", "```r\n", paste(substitute(f)), "(", if (n_params > 0) paste(collapse = ", ", sapply(1:n_params, function(i) { paste0(names(formals(f))[i], ' = "', formals(f)[[i]], '"')})), ")\n```" ) } demo_function_call(style_mono_light, 1) ``` `r include_graphic("example_mono_light.png")` #### `style_mono_dark()` A dark theme based around a single color. ```{r style_mono_dark} demo_function_call(style_mono_dark, 1) ``` `r include_graphic("example_mono_dark.png")` #### `style_mono_accent()` The default xaringan theme with a single color used for color accents on select elements (headers, bold text, etc.). ```{r style_mono_accent} demo_function_call(style_mono_accent, 1) ``` `r include_graphic("example_mono_accent.png")` #### `style_mono_accent_inverse()` An "inverted" default xaringan theme with a single color used for color accents on select elements (headers, bold text, etc.). ```{r style_mono_accent_inverse} demo_function_call(style_mono_accent_inverse, 1) ``` `r include_graphic("example_mono_accent_inverse.png")` ### Duotone These themes build from two (ideally) complementary colors. #### `style_duo()` A two-colored theme based on a primary and secondary color. ```{r style_duo} demo_function_call(style_duo, 2) ``` `r include_graphic("example_duo.png")` #### `style_duo_accent()` The default Xaringan theme with two accent colors. ```{r style_duo_accent} demo_function_call(style_duo_accent, 2) ``` `r include_graphic("example_duo_accent.png")` #### `style_duo_accent_inverse()` An "inverted" default Xaringan theme with two accent colors. ```{r style_duo_accent_inverse} demo_function_call(style_duo_accent_inverse, 2) ``` `r include_graphic("example_duo_accent_inverse.png")` ### Solarized There are also two themes based around the [solarized color palette](https://ethanschoonover.com/solarized/), `style_solarized_light()` and `style_solarized_dark()`. For both themes, it is advisted to change the syntax highlighting theme to `solarized-light` or `solarized-dark` (looks great paired or constrasted). #### `style_solarized_light()` ```{r style_solarized_light} demo_function_call(style_solarized_light, 0) ``` `r include_graphic("example_solarized_light.png")` #### `style_solarized_dark()` ```{r style_solarized_dark} demo_function_call(style_solarized_dark, 0) ``` `r include_graphic("example_solarized_dark.png")` To do this, your YAML header should look more-or-less like this: ```yaml output: xaringan::moon_reader: css: ["xaringan-themer.css"] nature: highlightStyle: solarized-dark highlightLines: true countIncrementalSlides: false ```
/scratch/gouwar.j/cran-all/cranData/xaringanthemer/man/fragments/_themes.Rmd
--- title: "ggplot2 Themes" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{ggplot2 Themes} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, comment = "#>", fig.width = 6, fig.height = 4 ) ``` ```{css echo=FALSE} img { max-width: 100%; border: none; } ``` **xaringanthemer** provides two [ggplot2] themes for your [xaringan] slides to help your data visualizations blend seamlessly into your slides. Use `theme_xaringan()` to create plots that match your primary slide style or `theme_xaringan_inverse()` to match the style of your inverse slides. <img src="https://raw.githubusercontent.com/gadenbuie/xaringanthemer/assets/theme-xaringan-inverse.png" alt="Examples slides with ggplot2 plots that match the xaringanthemer theme" data-external="1" /> ### Key Features - The ggplot2 themes [uses the colors and themes](#setup-your-theme) from the **xaringanthemer** style functions, if you set your theme inside your slides. Otherwise, it [draws from the `xaringan-themer.css` file](#using-xaringan-themer-css). - The themes [pick appropriate colors](#colors) for titles, grid lines, and axis text, and also sets the default colors of geoms like `ggplot2::geom_point()` and `ggplot2::geom_text()`. There are also monotone [color and fill scales](#scale-xaringan) based around the primary accent color used in your xaringan theme. - If you use Google Fonts in your slides, the ggplot2 themes use the showtext package to [automatically match the title and axis text fonts](#fonts) of your plots to the heading and text fonts in your xaringan theme. - I've done my best to set up everything so that _it just works_, but sometimes the showtext package adds a bit of complication to the routine data visualization workflow. At the end of this vignette I include [a few tips](#tips) for working with showtext. ## Setup Your Theme `theme_xaringan()` is designed to automatically use the fonts and colors you used for your slides' style theme. Here I'm going to use a moderately customized color theme based on `style_mono_accent()`, that results in the xaringan theme previewed in the slides above. I've also picked out a few fonts from [Google Fonts][google-fonts] that I would probably never use in a real presentation, but they're flashy enough to make it easy to see that we're not using the standard default fonts. ````markdown ```{r xaringan-themer, include=FALSE, warning=FALSE}`r ''` library(xaringanthemer) style_mono_accent( base_color = "#DC322F", # bright red inverse_background_color = "#002B36", # dark dark blue inverse_header_color = "#31b09e", # light aqua green inverse_text_color = "#FFFFFF", # white title_slide_background_color = "var(--base)", text_font_google = google_font("Kelly Slab"), header_font_google = google_font("Oleo Script") ) ``` ```` ```{r setup, include=FALSE} library(xaringanthemer) style_mono_accent( base_color = "#DC322F", inverse_background_color = "#002B36", inverse_header_color = "#31b09e", inverse_text_color = "#FFFFFF", title_slide_background_color = "var(--base)", text_font_google = google_font("Kelly Slab"), header_font_google = google_font("Oleo Script"), outfile = NULL ) ``` If you use a hidden chunk like this one inside your slides' R Markdown source file, `theme_xaringan()` will know which colors and fonts you've picked. Adding `theme_xaringan()` to a ggplot, like this demonstration plot using the `mpg` dataset from ggplot2, changes the colors and fonts of your plot theme. ```{r ggplot2-demo-1, out.width = "48%", fig.show="hide"} library(ggplot2) g_base <- ggplot(mpg) + aes(hwy, cty) + geom_point() + labs(x = "Highway MPG", y = "City MPG", title = "Fuel Efficiency") # Basic plot with default theme g_base ``` ```{r ggplot2-demo-2, fig.show="hide"} # Fancy slide-matching themed plot g_base + theme_xaringan() ``` <img src="`r knitr::fig_chunk("ggplot2-demo-1", "png")`" width="48%" /><img src="`r knitr::fig_chunk("ggplot2-demo-2", "png")`" width="48%" /> With `theme_xaringan()` the fonts and colors match the slide theme. The default colors of points (like other geometries) has been changed as well to match the slide colors. To restore the previous default colors of ggplot2 geoms, call ```{r eval=FALSE} theme_xaringan_restore_defaults() ``` Add `theme_xaringan_inverse()` to automatically create a plot that matches the inverse slide style. ```{r ggplot2-demo-inverse, fig.show="hide"} # theme_xaringan() on the left, theme_xaringan_inverse() on the right g_base + theme_xaringan_inverse() ``` <img src="`r knitr::fig_chunk("ggplot2-demo-2", "png")`" width="48%" /><img src="`r knitr::fig_chunk("ggplot2-demo-inverse", "png")`" width="48%" /> ## Using `theme_xaringan()` without calling a style function {#using-xaringan-themer-css} Once you've set up your custom xaringan theme, you might want to use the theme's CSS file for new presentations instead of rebuilding your theme with every new slide deck. In these cases, `theme_xaringan()` will look for a CSS file written by **xaringanthemer** in your slides' directory or in a sub-folder under the same directory that it can use to determine the colors and fonts used in your slides. If you happen to have multiple slide themes written by **xaringanthemer** in the same directory, the one named `xaringan-themer.css` will be used. If xaringanthemer picks the wrong file, you can use the `css_file` in `theme_xaringan()` to specify exactly which CSS file to use. ```{r eval=FALSE} theme_xaringan(css_file = "my-slide-style.css") ``` Note that you can use `theme_xaringan()` anywhere you want, not just in xaringan slides! (For example, `theme_xaringan()` is working great in these vignettes!) This means that you can use your plot theme in reports and websites while maintaining a consistent look and feel or brand. Finally, you don't even need a xaringanthemer CSS file. You can specify the key ingredients for the theme as arguments to `theme_xaringan()`, namely text, background, and accent colors as well as text and title fonts. The R chunk below replicated the demonstrated theme, but doesn't require a slide style to be set or stored in a CSS file. ```{r eval=FALSE} theme_xaringan( text_color = "#3D3E38", background_color = "#FFFFFF", accent_color = "#DC322F", text_font = "Kelly Slab", text_font_use_google = TRUE, title_font = "Oleo Script", title_font_use_google = TRUE ) ``` ## Colors As demonstrated above, `theme_xaringan()` and `theme_xaringan_inverse()` modify the default colors and fonts of geometries. This means that `geom_point()`, `geom_bar()`, `geom_text()` and other geoms used in your plots will reasonably match your slide themes with no extra work. ```{r demo-geom-defaults, fig.width = 10} g_diamonds <- ggplot(diamonds, aes(x = cut)) + geom_bar() + labs(x = NULL, y = NULL, title = "Diamond Cut Quality") + ylim(0, 25000) g_diamonds + theme_xaringan() ``` Whenever `theme_xaringan()` or `theme_xaringan_inverse()` are called, the default values of many of ggplot2 geoms are set by default. You can opt out of this by setting `set_ggplot_defaults = FALSE` when using either theme. You can also restore the geom aesthetic defaults to their original values before the first time `theme_xaringan()` or `theme_xaringan_inverse()` were used by running ```{r eval=FALSE} theme_xaringan_restore_defaults() ``` ### Custom Color and Fill Scales {#scale-xaringan} xaringanthemer includes monotone color and fill scales to match your ggplot2 theme. The scale functions all follow the naming pattern `scale_xaringan_<aes>_<data_type>()`, where `<aes>` is replaced with either `color` or `fill` and `<data_type>` is one of `discrete` or `continuous`. These scales use `colorspace::sequential_hcl()` to create a sequential, monotone color scale based on the primary accent color in your slides. Color scales matching the inverse slides are possible by setting the argument `inverse = TRUE`. ```{r scale-xaringan, fig.width = 9, fig.height = 5, out.width="48%", fig.show="hold", echo = TRUE} ggplot(diamonds, aes(x = cut)) + geom_bar(aes(fill = ..count..), show.legend = FALSE) + labs(x = NULL, y = "Count", title = "Diamond Cut Quality") + theme_xaringan() + scale_xaringan_fill_continuous() ggplot(mpg, aes(x = hwy, y = cty)) + geom_count(aes(color = ..n..), show.legend = FALSE) + labs(x = "Highway MPG", y = "City MPG", title = "Fuel Efficiency") + theme_xaringan_inverse() + scale_xaringan_color_continuous(breaks = seq(3, 12, 2), inverse = TRUE, begin = 1, end = 0) ``` In general, these color scales aren't great at representing the underlying data. In both examples above, the color and fill scales duplicate information displayed via other aesthetics (the height of the bar or the size of the point). I recommend using these scales primarily for style, although the scales can be more or less effective depending on your color scheme. The scales come with a few more options: - Choose a different primary color using the `color` argument. - Use the inverse color slide theme color with `inverse = TRUE` (only applies when `color` is not supplied). - Invert the direction of the discrete scales with `direction = -1`. - Control the range of the continuous color scale used with `begin` and `end`. You can also invert the direction of the continuous color scale by setting `begin = 1` and `end = 0`. ## Fonts ### Automatically match slide and plot fonts xaringanthemer uses the [showtext] and [sysfonts] packages by Yixuan Qiu to automatically download and register [Google Fonts][google-fonts] for use with your ggplot2 plots. In your slide theme, use the `<type>_font_google` argument with the `google_font("<font name>")` helper (or the default xaringanthemer fonts) and `theme_xaringan()` will handle the rest. In our demo theme, we used `style_mono_accent()` with - `text_font_google = google_font("Kelley Slab")` and - `header_font_google = google_font("Oleo Script")`. ```{r text demo, fig.width = 10} g_diamonds_with_text <- g_diamonds + geom_text(aes(y = ..count.., label = format(..count.., big.mark = ",")), vjust = -0.30, size = 8, stat = "count") + labs(x = "Cut", y = "Count") g_diamonds_with_text + theme_xaringan() ``` `theme_xaringan()` applies the header font to the plot and axis titles and the text font to the axis ticks labels and any text geoms or annotations. ### Manually specify plot fonts You can also specify specific fonts for your plot theme. Both `text_font` and `title_font` in `theme_xaringan()` and `theme_xaringan_inverse()` accept `google_font()`s directly. ```{r text-demo-2, fig.width = 10} g_diamonds_with_text + theme_xaringan( text_font = google_font("Ranga"), title_font = google_font("Holtwood One SC") ) ``` ### Using fonts not in Google Fonts If you want to use a font that isn't in the Google Fonts collection, you need to manually register the font with sysfonts so that it can be used in your plots. I found a nice open source font called [Glacial Indifference](https://fontlibrary.org/en/font/glacial-indifference) by Alfredo Marco Pradil available at [fontlibrary.org](https://fontlibrary.org). In my theme style function, I would use ``` style_mono_accent( text_font_family = "GlacialIndifferenceRegular", text_font_url = "https://fontlibrary.org/face/glacial-indifference" ) ``` but sysfonts won't know where to find the TTF font files for this font. To register the font with sysfonts, we use `sysfonts::font_add()`, but first we need to download the font file — the `sysfonts::font_add()` function requires the font file to be local. By inspecting the CSS file at the link I used in `text_font_url`, I found a direct URL for the `.ttf` files for _GlacialIndifferenceRegular_. I've included the code I used to download the font to a temporary file below, but in case the URL breaks, I've included _Glacial Indifference_ in the xaringanthemer package. ```{r eval=FALSE} font_url <- file.path( "https://fontlibrary.org/assets/fonts/glacial-indifference/", "5f2cf277506e19ec77729122f27b1faf/0820b3c58fed35de298219f314635982", "GlacialIndifferenceRegular.ttf" ) font_temp <- tempfile() download.file(font_url, font_temp) ``` ```{r sysfonts-custom-font, fig.width = 10} # Path to the local custom font file font_temp <- system.file( "fonts/GlacialIndifferenceRegular.ttf", package = "xaringanthemer" ) # Register the font with sysfonts/showtext sysfonts::font_add(family = "GlacialIndifferenceRegular", regular = font_temp) # Now it's available for use! g_diamonds_with_text + theme_xaringan( text_font = "GlacialIndifferenceRegular", title_font = "GlacialIndifferenceRegular" ) ``` ## Tips for using the showtext package {#tips} Working with fonts is notoriously frustrating, but [showtext] and [sysfonts] do a great job ensuring that Google Fonts and custom fonts work on all platforms. As you've seen in the examples above, the process is mostly seamless, but there are a few caveats and places where the methods used by these packages may interrupt a typical ggplot2 workflow. ### R Markdown To use the showtext package in R Markdown, knitr requires that the `fig.showtext` chunk option be set to `TRUE`, either in the chunk producing the figure or globally in the document. xaringanthemer tries to set this chunk option for you, but in some circumstances it's possible to call `theme_xaringan()` in a way that xaringanthemer can't set this option for you. When this happens, xaringanthemer will produce an error: ``` Error in verify_fig_showtext(fn) : To use theme_xaringan_base() with knitr, you need to set the chunk option `fig.showtext = TRUE` for this chunk. Or you can set this option globally with `knitr::opts_chunk$set(fig.showtext = TRUE)`. ``` If you find yourself facing this error, follow the instructions and choose one of the two suggestions: 1. Add `fig.showtext = TRUE` to the chunk producing the figure 2. Or set the option globally in your `setup` chunk with `knitr::opts_chunk$set(fig.showtext = TRUE)`. ### MacOS On MacOS, you'll need to have `xquartz` installed for `sysfonts` to work properly. If you use [homebrew](https://brew.sh/), you can install `xquartz` with ```bash brew cask install xquartz ``` ### In RStudio showtext and RStudio's graphic device don't always work well together. Depending on your version of RStudio, if you try to preview plots that use `theme_xaringan()`, the fonts in the preview will still be the default sans font or you may not see a plot at all. To work around this, open a new `quartz()` (MacOS) or `x11()` (Windows/Unix) plot device. The plots will then render in a separate window. I usually create a `quartz()` device with a similar size ratio to my slides. ```{r eval=FALSE} ## On Windows # x11(width = 16 * 2/3, height = 9 * 2/3) ## On MacOS quartz(width = 16 * 2/3, height = 9 * 2/3) ## run plot code to preview in separate window dev.off() # call when done to close the device ``` [ggplot2]: https://ggplot2.tidyverse.org [xaringan]: https://github.com/yihui/xaringan [google-fonts]: https://fonts.google.com [showtext]: https://github.com/yixuan/showtext [sysfonts]: https://github.com/yixuan/sysfonts
/scratch/gouwar.j/cran-all/cranData/xaringanthemer/vignettes/ggplot2-themes.Rmd
--- title: "Template Variables" output: rmarkdown::html_vignette: default vignette: > %\VignetteIndexEntry{Template Variables} %\VignetteEncoding{UTF-8} %\VignetteEngine{knitr::rmarkdown} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "#>" ) ``` The following table shows the template variables, their default values in the standard `xaringanthemer` theme, the primary element to which the property is applied, and a brief description of the template variable. For example, `background_color` by default sets the `background-color` CSS property of the `.remark-slide-content` class to `#FFF`. Use this table to find the template variable you would like to modify. You can also use this table to find the CSS class or element associated with a particular template item. Note that some theme functions, like `style_mono_accent()`, have additional parameters and a specific set of default values unique to the theme. However, with any theme function you can override the theme's defaults by directly setting any of the arguments listed below when calling the theme function. To be concrete, `style_mono_accent()` has three additional arguments: `base_color` (the accent color), `white_color`, and `black_color`. In this theme, the background slide color defaults to `white_color`, but you can choose a different slide background color by setting `background_color`, for example `background_color = "#EAEAEA"`. ```{r table, results = "asis", echo=FALSE} tv <- xaringanthemer:::template_variables tv$variable <- glue::glue_data(tv, "`{variable}`") tv[!is.na(tv$css_variable), "css_variable"] <- glue::glue("`{tv$css_variable[!is.na(tv$css_variable)]}`") tv[is.na(tv$css_variable), "css_variable"] <- "" tv[is.na(tv$css_property), "css_property"] <- "" tv$default <- gsub("[{}]", "", tv$default) tv <- tv[, c( "variable", "description", "element", "css_property", "default", "css_variable" )] knitr::kable( tv, col.names = c("Variable", "Description", "Element", "CSS Property", "Default", "CSS Variable") ) ```
/scratch/gouwar.j/cran-all/cranData/xaringanthemer/vignettes/template-variables.Rmd
--- title: "Xaringan CSS Theme Generator" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Overview of xaringanthemer} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, results = "asis", echo = FALSE, comment = "#>", out.width = "100%" ) library(xaringanthemer) ``` ```{css echo=FALSE} img { max-width: 100%; } ``` [xaringan]: https://github.com/yihui/xaringan [remarkjs]: https://github.com/gnab/remark Jump to: [Quick Intro](#quick-intro), [Themes](#themes), [Theme Settings](#theme-settings), [Fonts](#fonts), [Colors](#colors), [Adding Custom CSS](#adding-custom-css) ## Quick Intro [theme-functions]: #themes [theme-settings]: #theme-settings [template-variables]: template-variables.html ```{r child="../man/fragments/_quick-intro.Rmd"} ``` ## Themes ```{r child="../man/fragments/_themes.Rmd"} ``` ## Theme Settings The theme functions listed above are just wrappers around the central function of this package, `style_xaringan()`. If you want to start from the default **xaringan** theme and make a few modifications, start there. All of the theme template variables are repeated in each of the theme functions (instead of relying on `...`) so that you can use autocompletion to find and change the defaults for any theme function. To override the default value of any theme functions, set the appropriate argument in the theme function. A table of all template variables is included in [`vignette("template-variables", "xaringanthemer")`](template-variables.html). As an example, try loading `xaringanthemer`, type out `style_duo_theme(` and then press <kbd>Tab</kbd> to see all of the theme options. All of the theme options are named so that you first think of the element you want to change, then the property of that element. Here are some of the `text_` theme options: ```{r, results='asis', echo=FALSE} tvv <- xaringanthemer:::template_variables$variable cat(paste0("- `", tvv[grepl("^text_", tvv)][1:5], "`"), sep = "\n") cat("- *and more ...*") ``` And here are the title slide theme options: ```{r results='asis', echo=FALSE} cat(paste0("- `", tvv[grepl("^title_slide_", tvv)], "`"), sep = "\n") ``` ## Fonts [adding-custom-css]: #adding-custom-css ```{r child="../man/fragments/_fonts.Rmd"} ``` ## Colors ```{r child="../man/fragments/_colors.Rmd"} ``` ## Adding Custom CSS You can also add custom CSS classes using the `extra_css` argument in the theme functions. This argument takes a named list of CSS definitions each containing a named list of CSS property-value pairs. ```r extra_css <- list( ".small" = list("font-size" = "90%"), ".full-width" = list( display = "flex", width = "100%", flex = "1 1 auto" ) ) ``` If you would rather keep your additional css definitions in a separate file, you can call `style_extra_css()` separately. Just be sure to include your new CSS file in the list of applied files in your YAML header. ```r style_extra_css(css = extra_css, outfile = "custom.css") ``` ```{r results='asis', echo=FALSE} extra_css <- list( ".small" = list("font-size" = "90%"), ".full-width" = list( display = "flex", width = "100%", flex = "1 1 auto" ) ) cat( "\n```css", "/* Extra CSS */", xaringanthemer:::list2css(extra_css), "```", sep = "\n" ) ``` This is most helpful when wanting to define helper classes to work with the [remark.js][remarkjs] `.class[]` syntax. Using the above example, we could add slide text `.small[in smaller font size]`. ```{r child="../man/fragments/_thanks.Rmd"} ```
/scratch/gouwar.j/cran-all/cranData/xaringanthemer/vignettes/xaringanthemer.Rmd
# Generated by using Rcpp::compileAttributes() -> do not edit by hand # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #' @useDynLib xdcclarge, .registration = TRUE #' @importFrom Rcpp evalCpp NULL #' This function calculates log-likelihood of cDCC-garch model with composite likelihood method. #' @param alpha cDCC-GARCH parameter #' @param beta cDCC-GARCH parameter #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param nobs the length of time-series (T) #' @param ndim the dimension of time-series (N) #' #' @return log-likelihood of cDCC-GARCH model(scaler) NULL cdcc_compositelik <- function(alpha, beta, ht, residuals, stdresids, uncR, nobs, ndim) { .Call(`_xdcclarge_cdcc_compositelik`, alpha, beta, ht, residuals, stdresids, uncR, nobs, ndim) } #' @useDynLib xdcclarge, .registration = TRUE #' @importFrom Rcpp evalCpp NULL #' This function constructs DCC-garch model's correlation term(Rt). #' @param alpha DCC-GARCH parameter #' @param beta DCC-GARCH parameter #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param nobs the length of time-series (T) #' @param ndim the dimension of time-series (N) #' @param ts how many time series are you taking #' #' @return DCC-garch model's correlation term(Rt) NULL cdcc_construct <- function(alpha, beta, stdresids, uncR, nobs, ndim, ts) { .Call(`_xdcclarge_cdcc_construct`, alpha, beta, stdresids, uncR, nobs, ndim, ts) } #' @useDynLib xdcclarge, .registration = TRUE #' @importFrom Rcpp evalCpp NULL #' This function calculates log-likelihood of DCC-garch model with composite likelihood method. #' @param alpha DCC-GARCH parameter #' @param beta DCC-GARCH parameter #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param nobs the length of time-series (T) #' @param ndim the dimension of time-series (N) #' #' @return log-likelihood of DCC-GARCH model(scaler) NULL dcc_compositelik <- function(alpha, beta, ht, residuals, stdresids, uncR, nobs, ndim) { .Call(`_xdcclarge_dcc_compositelik`, alpha, beta, ht, residuals, stdresids, uncR, nobs, ndim) } #' @useDynLib xdcclarge, .registration = TRUE #' @importFrom Rcpp evalCpp NULL #' This function constructs DCC-garch model's correlation term(Rt). #' @param alpha DCC-GARCH parameter #' @param beta DCC-GARCH parameter #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param nobs the length of time-series (T) #' @param ndim the dimension of time-series (N) #' @param ts how many time series are you taking #' #' @return DCC-garch model's correlation term(Rt) NULL dcc_construct <- function(alpha, beta, stdresids, uncR, nobs, ndim, ts) { .Call(`_xdcclarge_dcc_construct`, alpha, beta, stdresids, uncR, nobs, ndim, ts) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/RcppExports.R
#' This function get the correlation matrix (Rt) of estimated cDCC-GARCH model. #' @param param cDCC-GARCH parameters(alpha,beta) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param ts ts how many time series are you taking #' #' @return the correlation matrix (Rt) of estimated cDCC-GARCH model (T by N^2) #' @note Rt are vectorized values of the conditional correlation matrix(Rt) until time t(ts) for each row. #' @export cdcc_correlations <- function(param, stdresids, uncR, ts){ nobs <- dim(stdresids)[1] ndim <- dim(stdresids)[2] tmp<-cdcc_construct(param[1], param[2], stdresids, uncR, nobs, ndim, ts) result<-tmp[1:ts,] return(result) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/cdcc_correlations.R
#' This function estimates the parameters(alpha,beta) and time-varying correlation matrices(Rt) of cDCC-GARCH model. #' @param ini.para initial cDCC-GARCH parameters(alpha,beta) of optimization #' @param ht matrix of conditional variance vectors #' @param residuals matrix of residual(de-mean) returns #' @param method shrinkage method of unconditional correlation matrix(Cov:sample,LS:Linear Shrinkage,NLS:NonLinear Shrinkage) #' @param ts ts how many time series are you taking(dufalut:1 latest value) #' #' @return time-varying correlations(Rt) and the result of estimation #' @note Rt are vectorized values of the conditional correlation matrix(Rt) until time t(ts) for each row. #' @export #' @examples #' library(rugarch) #' library(xdcclarge) #' #load data #' data(us_stocks) #' n<-3 #' Rtn<-log(us_stocks[-1,1:n]/us_stocks[-nrow(us_stocks),1:n]) #' #' # Step 1:GARCH Parameter Estimation with rugarch #' spec = ugarchspec() #' mspec = multispec( replicate(spec, n = n) ) #' fitlist = multifit(multispec = mspec, data = Rtn) #' ht<-sigma(fitlist)^2 #' residuals<-residuals(fitlist) #' #' # Step 2:cDCC-GARCH Parameter Estimation with xdcclarge #' cDCC<-cdcc_estimation(ini.para=c(0.05,0.93) ,ht ,residuals) #' #Time varying correlation matrix Rt at time t #' (Rt<-matrix(cDCC$cdcc_Rt,n,n)) #' #' \dontrun{ #' #If you want Rt at time t-s,then #' s<-10 #' cDCC<-cdcc_estimation(ini.para=c(0.05,0.93) ,ht ,residuals,ts = s) #' matrix(cDCC$cdcc_Rt[s,],n,n) #' } #' cdcc_estimation <- function(ini.para=c(0.05,0.93) ,ht ,residuals, method=c("COV","LS","NLS"), ts = 1){ #de-garch residual returns stdresids <- residuals/sqrt(ht) flag <- match.arg(method) if(flag == "NLS"){ print("non-linear shrinkage Step Now...") uncR <- nlshrink::nlshrink_cov(stdresids) } else if(flag == "LS"){ print("linear shrinkage Step Now...") uncR <- nlshrink::linshrink_cov(stdresids) } else{ uncR <- stats::cov(stdresids) } print("Optimization Step Now...") result <- cdcc_optim(param=ini.para,ht=ht, residuals=residuals, stdresids=stdresids, uncR=uncR) print("Construction Rt Step Now...") cdcc_Rt <- cdcc_correlations(result$par, stdresids, uncR, ts) list(result=result,cdcc_Rt=cdcc_Rt) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/cdcc_estimation.R
#' This functions calculates numerical gradient of log-likelihood of cDCC-GARCH model. #' @param param cDCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param d (log-lik(x+d) - log-lik(x))/d #' #' @return numerical gradient of log-likelihood of cDCC-GARCH model(vector) #' @export cdcc_gradient <- function(param, ht, residuals, stdresids, uncR, d=1e-5){ nobs <- dim(residuals)[1] ndim <- dim(residuals)[2] npara <- length(param) Id <- d*diag(npara) param1 <- param + Id[,1] param2 <- param + Id[,2] lfc <- cdcc_compositelik(param[1], param[2], ht, residuals, stdresids, uncR, nobs, ndim) lfc1 <- cdcc_compositelik(param1[1], param1[2], ht, residuals, stdresids, uncR, nobs, ndim) lfc2 <- cdcc_compositelik(param2[1], param2[2], ht, residuals, stdresids, uncR, nobs, ndim) c(sum((lfc1 - lfc)/d), sum((lfc2 - lfc)/d) ) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/cdcc_gradient.R
#' This function calculates log-likelihood of cDCC-GARCH model. #' @param param cDCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' #' @return log-likelihood of cDCC-GARCH model (scaler) #' @export cdcc_loglikelihood <- function(param, ht, residuals, stdresids, uncR){ nobs <- dim(stdresids)[1] ndim <- dim(stdresids)[2] lf <- cdcc_compositelik(param[1], param[2], ht, residuals, stdresids, uncR, nobs, ndim) return(lf) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/cdcc_loglikelihood.R
#' This function optimizes log-likelihood of cDCC-GARCH model. #' @param param cDCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' #' @return results of optimization #' @export cdcc_optim <- function(param, ht, residuals, stdresids, uncR){ resta <- rbind(c(-1, -1), diag(2)) restb <- c(-1, 0, 0) opt <- stats::constrOptim(theta=param, f=cdcc_loglikelihood, grad=cdcc_gradient, ui=resta, ci=restb, mu=1e-5, outer.iterations=10, outer.eps=1e-2, control=list(maxit=10,reltol=1e-5), ht=ht, residuals=residuals, stdresids=stdresids, uncR=uncR) return(opt) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/cdcc_optim.R
#' This function get the correlation matrix (Rt) of estimated DCC-GARCH model. #' @param param DCC-GARCH parameters(alpha,beta) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param ts ts how many time series are you taking #' #' @return the correlation matrix (Rt) of estimated DCC-GARCH model (T by N^2) #' @note Rt are vectorized values of the conditional correlation matrix(Rt) until time t(ts) for each row. #' @export dcc_correlations <- function(param, stdresids, uncR, ts){ nobs <- dim(stdresids)[1] ndim <- dim(stdresids)[2] tmp<-dcc_construct(param[1], param[2], stdresids, uncR, nobs, ndim, ts) result<-tmp[1:ts,] return(result) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/dcc_correlations.R
#' This function estimates the parameters(alpha,beta) and time-varying correlation matrices(Rt) of DCC-GARCH model. #' @param ini.para initial DCC-GARCH parameters(alpha,beta) of optimization #' @param ht matrix of conditional variance vectors #' @param residuals matrix of residual(de-mean) returns #' @param method shrinkage method of unconditional correlation matrix(Cov:sample,LS:Linear Shrinkage,NLS:NonLinear Shrinkage) #' @param ts ts how many time series are you taking(dufalut:1 latest value) #' #' @return time-varying correlations(Rt) and the result of estimation #' @note Rt are vectorized values of the conditional correlation matrix(Rt) until time t(ts) for each row. #' @export #' @examples #' library(rugarch) #' library(xdcclarge) #' #load data #' data(us_stocks) #' n<-3 #' Rtn<-log(us_stocks[-1,1:n]/us_stocks[-nrow(us_stocks),1:n]) #' #' # Step 1:GARCH Parameter Estimation with rugarch #' spec = ugarchspec() #' mspec = multispec( replicate(spec, n = n) ) #' fitlist = multifit(multispec = mspec, data = Rtn) #' ht<-sigma(fitlist)^2 #' residuals<-residuals(fitlist) #' #' # Step 2:DCC-GARCH Parameter Estimation with xdcclarge #' DCC<-dcc_estimation(ini.para=c(0.05,0.93) ,ht ,residuals) #' #Time varying correlation matrix Rt at time t #' (Rt<-matrix(DCC$dcc_Rt,n,n)) #' #' \dontrun{ #' #If you want Rt at time t-s,then #' s<-10 #' DCC<-dcc_estimation(ini.para=c(0.05,0.93) ,ht ,residuals,ts = s) #' matrix(DCC$cdcc_Rt[s,],n,n) #' } dcc_estimation <- function(ini.para=c(0.05,0.93) ,ht ,residuals, method=c("COV","LS","NLS"), ts = 1){ #de-garch residual returns stdresids <- residuals/sqrt(ht) flag <- match.arg(method) if(flag == "NLS"){ print("non-linear shrinkage Step Now...") uncR <- nlshrink::nlshrink_cov(stdresids) } else if(flag == "LS"){ print("linear shrinkage Step Now...") uncR <- nlshrink::linshrink_cov(stdresids) } else{ uncR <- stats::cov(stdresids) } print("Optimization Step Now...") result <- dcc_optim(param=ini.para,ht=ht, residuals=residuals, stdresids=stdresids, uncR=uncR) print("Construction Rt Step Now...") dcc_Rt <- dcc_correlations(result$par, stdresids, uncR, ts) list(result=result,dcc_Rt=dcc_Rt) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/dcc_estimation.R
#' This functions calculates numerical gradient of log-likelihood of DCC-GARCH model. #' @param param DCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' @param d (log-lik(x+d) - log-lik(x))/d #' #' @return numerical gradient of log-likelihood of DCC-GARCH model (vector) #' @export dcc_gradient <- function(param, ht, residuals, stdresids, uncR, d=1e-5){ nobs <- dim(residuals)[1] ndim <- dim(residuals)[2] npara <- length(param) Id <- d*diag(npara) param1 <- param + Id[,1] param2 <- param + Id[,2] lfc <- dcc_compositelik(param[1], param[2], ht, residuals, stdresids, uncR, nobs, ndim) lfc1 <- dcc_compositelik(param1[1], param1[2], ht, residuals, stdresids, uncR, nobs, ndim) lfc2 <- dcc_compositelik(param2[1], param2[2], ht, residuals, stdresids, uncR, nobs, ndim) c(sum((lfc1 - lfc)/d), sum((lfc2 - lfc)/d) ) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/dcc_gradient.R
#' This function calculates log-likelihood of DCC-GARCH model. #' @param param DCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' #' @return log-likelihood of DCC-GARCH model (scaler) dcc_loglikelihood <- function(param, ht, residuals, stdresids, uncR){ nobs <- dim(stdresids)[1] ndim <- dim(stdresids)[2] lf <- dcc_compositelik(param[1], param[2], ht, residuals, stdresids, uncR, nobs, ndim) return(lf) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/dcc_loglikelihood.R
#' This function optimizes log-likelihood of DCC-GARCH model. #' @param param DCC-GARCH parameters(alpha,beta) #' @param ht matrix of conditional variance vectors (T by N) #' @param residuals matrix of residual(de-mean) returns (T by N) #' @param stdresids matrix of standrdized(De-GARCH) residual returns (T by N) #' @param uncR unconditional correlation matrix of stdresids (N by N) #' #' @return results of optimization #' @export dcc_optim <- function(param, ht, residuals, stdresids, uncR){ resta <- rbind(c(-1, -1), diag(2)) restb <- c(-1, 0, 0) opt <- stats::constrOptim(theta=param, f=dcc_loglikelihood, grad=dcc_gradient, ui=resta, ci=restb, mu=1e-5, outer.iterations=10, outer.eps=1e-2, control=list(maxit=10,reltol=1e-5), ht=ht, residuals=residuals, stdresids=stdresids, uncR=uncR) return(opt) }
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/dcc_optim.R
#' the closing price data of us stocks in SP500 index from 2006-03-31 to 2014-03-31 from yahoo finance. #' #' @name us_stocks #' @docType data #' @format A data frame with 2013 rows and 460 variables: #' @source Yahoo finance NULL
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/us_stocks.R
#' Package #' #' @description Functions for Estimating a (c)DCC-GARCH Model in large dimensions based on a publication by Engle et,al (2017) and Nakagawa et,al (2018). #' This estimation method is consist of composite likelihood method by Pakel et al. (2014) and (Non-)linear shrinkage estimation of covariance matrices by Ledoit and Wolf (2004,2015,2016). #' #' @details To estimate the covariance matrix in financial time series, #' it is necessary consider two important aspects: the cross section and the time series. #' With regard to the cross section, we have the difficulty of correcting the biases of #' the sample covariance matrix eigenvalues in a large number of time series. #' With regard to the time series aspect, we have to account for volatility clustering and time-varying correlations. #' This package is implemented the improved estimation of the covariance matrix based on the following publications: #' #' \itemize{\item Aielli, Gian Piero. (2013). #' Dynamic conditional correlation: on properties and estimation. Journal of Business & Economic Statistics 31: 282-99. <doi:10.1080/07350015.2013.771027> #' \item Engle, Robert F. (2002). #' Dynamic conditional correlation: A simple class of multivariate generalized autoregressive conditional heteroskedasticity models. #' Journal of Business & Economic Statistics 20: 339-50. <doi:10.1198/073500102288618487> #' \item Engle, Robert F, Olivier Ledoit, and Michael Wolf. (2017). #' Large dynamic covariance matrices. Journal of Business & Economic Statistics, 1-13. <doi:10.1080/07350015.2017.1345683> #' \item Kei Nakagawa, Mitsuyoshi Imamura and Kenichi Yoshida. (2018). Risk-Based Portfolios with Large Dynamic Covariance Matrices. #' International Journal of Financial Studies, 6(2), 1-14. <doi:10.3390/ijfs6020052> #' \item Ledoit, O. and Wolf, M. (2004). A well-conditioned #' estimator for large-dimensional covariance matrices. Journal of #' Multivariate Analysis, 88(2). <doi:10.1016/S0047-259X(03)00096-4> #' \item Ledoit, O. and Wolf, M. (2012). #' Nonlinear shrinkage estimation of large-dimensional covariance matrices. #' Annals of Statistics, 40(2). <doi:10.1214/12-AOS989> #' \item Ledoit, O. and Wolf, M. (2015). Spectrum #' estimation: a unified framework for covariance matrix estimation and PCA in #' large dimensions. Journal of Multivariate Analysis, 139(2). <doi:10.1016/j.jmva.2015.04.006> #' \item Pakel, Cavit and Shephard, Neil and Sheppard, Kevin and Engle, Robert F. (2014). Fitting vast dimensional time-varying covariance models. #' Technical report <http://paneldataconference2015.ceu.hu/Program/Cavit-Pakel.pdf> #' } #' #' @name xdcclarge #' @docType package #' @import stats Rcpp nlshrink NULL
/scratch/gouwar.j/cran-all/cranData/xdcclarge/R/xdcclarge.R
#' rounding of numbers #' #' The ceiling2 is ceiling of numeric values by digits. The floor2 is floor of numeric values by digits. #' #' @param x a numeric vector. #' @param digits integer indicating the number of significant digits. #' #' @return #' ceiling2 rounds the elements in x to the specified number of significant digits that is the smallest number not less than the corresponding elements. #' #' floor2 rounds the elements in x to the specified number of significant digits that is the largest number not greater than the corresponding elements. #' #' @examples #' x = c(12345, 54.321) #' #' ceiling2(x) #' ceiling2(x, 2) #' ceiling2(x, 3) #' #' floor2(x) #' floor2(x, 2) #' floor2(x, 3) #' #' @export ceiling2 = function(x, digits=1) { if (digits < 0) stop('The argument digits should be nonnegative vlaues.') x_sci = format(x, scientific = TRUE, digits=digits+1) z = ceiling(as.numeric(sub('e.+$', '', x_sci)) * 10^(digits-1))/10^(digits-1) e = sub('.+(e.+)$', '\\1', x_sci) as.numeric(paste0(z, e)) } #' @export #' @rdname ceiling2 floor2 = function(x, digits=1) { if (digits < 0) stop('The argument digits should be nonnegative vlaues.') x_sci = format(x, scientific = TRUE, digits=digits+1) z = floor(as.numeric(sub('e.+$', '', x_sci)) * 10^(digits-1))/10^(digits-1) e = sub('.+(e.+)$', '\\1', x_sci) as.numeric(paste0(z, e)) }
/scratch/gouwar.j/cran-all/cranData/xefun/R/ceiling2.R
#' continuous counting #' #' It counts the number of continuous identical values. #' #' @param x a vector or data frame. #' @param cnt whether to count the number rows in each continuous groups. #' @param ... ignored #' #' @return A integer vector indicating the number of continuous identical elements in x. #' #' @examples #' # example I #' x1 = c(0,0,0, 1,1,1) #' conticnt(x1) #' conticnt(x1, cnt=TRUE) #' #' x2 = c(1, 2,2, 3,3,3) #' conticnt(x2) #' conticnt(x2, cnt=TRUE) #' #' x3 = c('c','c','c', 'b','b', 'a') #' conticnt(x3) #' conticnt(x3, cnt=TRUE) #' #' # example II #' dt = data.frame(c1=x1, c2=x2, c3=x3) #' conticnt(dt, col=c('c1', 'c2')) #' conticnt(dt, col=c('c1', 'c2'), cnt = TRUE) #' #' @import data.table #' @importFrom stats setNames #' @export conticnt = function(x, cnt=FALSE, ...) { UseMethod('conticnt') } #' @export conticnt.character = function(x, cnt=FALSE, ...) { setNames(conticnt1(x, cnt), x) } #' @export conticnt.numeric = function(x, cnt=FALSE, ...) { setNames(conticnt1(x, cnt), x) } #' @export conticnt.data.frame = function(x, cnt=FALSE, ...) { col = list(...)$col dtconti = setDT(x)[,(paste0('conti_', col)) := lapply(.SD, function(xi) conticnt1(xi,cnt)), .SDcols = col] return(dtconti[]) } conticnt1 = function(x, cnt=FALSE) { conti = v1 = NULL dt = data.table( v1 = x )[, conti := as.integer(v1 != shift(v1, type='lag')) ][!(conti %in% 0), conti := 1 ][, conti := cumsum(conti)] if (cnt) dt = dt[, conti := seq(.N), by = conti][] return(dt$conti) }
/scratch/gouwar.j/cran-all/cranData/xefun/R/conticnt.R
as_date = function(x, format = NULL) { d = try(as.Date(x), silent = TRUE) if (inherits(d, 'try-error')) { if (is.null(format)) { if (all(nchar(x) == 8)) format = '%Y%m%d' } d = as.Date(x, format = format) } return(d) } #' start/end date by period #' #' The date of bop (beginning of period) or eop (end of period). #' #' @param freq the frequency of period. It supports weekly, monthly, quarterly and yearly. #' @param x a date #' @param workday logical, whether to return the latest workday #' #' @return #' date_bop returns the beginning date of period of corresponding x by frequency. #' #' date_eop returns the end date of period of corresponding x by frequency. #' #' @examples #' date_bop('weekly', Sys.Date()) #' date_eop('weekly', Sys.Date()) #' #' date_bop('monthly', Sys.Date()) #' date_eop('monthly', Sys.Date()) #' #' @export date_bop = function(freq, x, workday = FALSE) { bop_mthday = NULL freq = match.arg(freq, c('daily', 'weekly', 'monthly', 'quarterly', 'yearly')) x = as_date(x) monthday = data.table( m = 1:12, bop_mthday = sprintf('-%02i-01', 1:12), key = 'm' ) if (freq == 'yearly') { x = as_date(sub('-[0-9]{2}-[0-9]{2}$', '-01-01', x)) } else if (freq == 'quarterly') { x = monthday[(quarter(x)-1)*3+1, as_date(paste0(year(x),bop_mthday))] } else if (freq == 'monthly') { x = as_date(sub('[0-9]{2}$', '01', x)) } else if (freq == 'weekly') { x = x - wday(x) + 1 } else if (freq == 'daily') { return(x) } if (workday) x = date_lwd(-1, x) return(x) } #' @export #' @rdname date_bop date_eop = function(freq, x, workday = FALSE) { freq = match.arg(freq, c('daily', 'weekly', 'monthly', 'quarterly', 'yearly')) if (inherits(x, 'character')) x = as_date(x) if (freq == 'yearly') { x = as_date(sub('-[0-9]{2}-[0-9]{2}$', '-12-31', x)) } else if (freq == 'quarterly') { x = date_eop(sprintf('%s-%s-01', year(x), quarter(x)*3), freq = 'monthly') } else if (freq == 'monthly') { x = date_bop(date_bop(x, freq='monthly') + 45, freq='monthly') - 1 } else if (freq == 'weekly') { x = x - wday(x) + 7 } else if (freq == 'daily') { return(x) } if (workday) x = date_lwd(1, x) return(x) } #' start date by range #' #' The date before a specified date by date_range. #' #' @param date_range date range, available value including nd, nm, mtd, qtd, ytd, ny, max. #' @param to a date, default is current system date. #' @param default_from the default date when date_range is sett to max #' #' @return It returns the start date of a date_range with a specified end date. #' #' @examples #' date_from(3) #' date_from('3d') #' #' date_from('3m') #' date_from('3q') #' date_from('3y') #' #' date_from('mtd') #' date_from('qtd') #' date_from('ytd') #' #' @export date_from = function(date_range, to=Sys.Date(), default_from='1000-01-01') { UseMethod('date_from') } # last calendar day by xtd (ytd/qtd/mtd) date_from_xtd = function(date_range, to = Sys.Date()) { if (inherits(to, 'character')) to = as_date(to) to_year = year(to) to_quarter = quarter(to) to_month = month(to) if (date_range == 'ytd') { from_month = '01' } else if (date_range == 'qtd') { from_month = to_quarter*3-2 } else if (date_range == 'mtd') { from_month = to_month } from = as_date(sprintf('%s-%s-01', to_year, from_month)) return(from) } date_from_xm = function(date_range, to = Sys.Date()) { if (inherits(to, 'character')) to = as_date(to) to_year = year(to) to_month = month(to) to_day = mday(to) xm = as.integer(sub("m","",date_range)) rng_year = floor(xm / 12) rng_month = xm %% 12 if (to_month <= rng_month) { rng_year = rng_year + 1 rng_month = rng_month - 12 } from = as_date(sprintf('%s-%s-%s', to_year-rng_year, to_month-rng_month, to_day)) return(from) } date_from_ym = function(date_range, to = Sys.Date()) { from_year = year(to) - as.integer(sub("y","",date_range)) from = as_date(sub("^[0-9]{4}", from_year, to)) return(from) } # the date from date_range before (calendar day) #' @export date_from.character = function(date_range, to = Sys.Date(), default_from='1000-01-01') { V1 = rid = NULL data.table(t = to)[ , rid := .I ][, date_from_char1(date_range, t, default_from), by = rid ][, V1] } date_from_char1 = function(date_range, to = Sys.Date(), default_from='1000-01-01') { to = as_date(to) from = NULL if (grepl("[1-9][0-9]*q", date_range)) date_range = sprintf('%sm', as.integer(sub('q', '', date_range))) if (date_range == 'max') { from = as_date(default_from) } else if (grepl("[yqm]td", date_range)) { from = date_from_xtd(date_range, to) } else { if (grepl("[1-9][0-9]*d", date_range)) { from = to - as.integer(sub("d","",date_range)) } else if (grepl("[1-9][0-9]*w", date_range)) { from = to - as.integer(sub("w","",date_range))*7 } else if (grepl("[1-9][0-9]*m", date_range)) { for (i in c(0, 1, -1, 2, -2)) { from = try(date_from_xm(date_range, to+i), silent = TRUE) if (!inherits(from, 'try-error')) { if (i != 0) from = from - i/abs(i) break } } } else if (grepl("[1-9][0-9]*y", date_range)) { for (i in c(0, 1, -1, 2, -2)) { from = try(date_from_ym(date_range, to+i), silent = TRUE) if (!inherits(from, 'try-error')) { if (i != 0) from = from - i/abs(i) break } } } from = from + 1 } return(from) } #' @export date_from.numeric <- function(date_range, to = Sys.Date(), ...) { ft = NULL # , tz = Sys.timezone() to = as_date(to) from = to - date_range + 1 return(from) } #' latest workday #' #' The latest workday date of n days before a specified date. #' #' @param n number of days #' @param to a date, default is current system date. #' #' @return It returns the latest workday date that is n days before a specified date. #' #' @examples #' date_lwd(5) #' date_lwd(3, "2016-01-01") #' date_lwd(3, "20160101") #' #' @export date_lwd = function(n, to = Sys.Date()) { ft = NULL to = as_date(to) n2 = abs(n) + ceiling(abs(n)/7)*2 from = sapply( to, function(x) { data.table( ft = seq(x, x - sign(n) * n2, by = -sign(n)) )[wday(ft) %in% 2:6 ][abs(n), as.character(ft)] } ) return(as_date(from)) } is.datetime = function(x) { inherits(x, c("Date","POSIXlt","POSIXct","POSIXt")) } #' date to number #' #' It converts date to numeric value in specified unit. #' #' @param x date. #' @param unit time unit, available values including milliseconds, seconds, minutes, hours, days, weeks. #' @param origin original date, defaults to 1970-01-01. #' @param scientific logical, whether to encode the number in scientific format, defaults to FALSE. #' #' @examples #' # setting unit #' date_num(Sys.time(), unit='milliseconds') #' date_num(Sys.time(), unit='mil') #' #' date_num(Sys.time(), unit='seconds') #' date_num(Sys.time(), unit='s') #' #' date_num(Sys.time(), unit='days') #' date_num(Sys.time(), unit='d') #' #' # setting origin #' date_num(Sys.time(), unit='d', origin = '1970-01-01') #' date_num(Sys.time(), unit='d', origin = '2022-01-01') #' #' # setting scientific format #' date_num(Sys.time(), unit='mil', scientific = FALSE) #' date_num(Sys.time(), unit='mil', scientific = TRUE) #' date_num(Sys.time(), unit='mil', scientific = NULL) #' #' @export date_num = function(x, unit="s", origin = "1970-01-01", scientific = FALSE) { sec = NULL if (unit == 'ms') unit = 'milliseconds' unit = match.arg(unit, c('milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks')) unit2sec = data.table( unit = c('milliseconds', 'seconds', 'minutes', 'hours', 'days', 'weeks'), sec = c(1/1000, 1, 60, 60*60, 60*60*24, 60*60*24*7), key = 'unit' ) xnum = (as.numeric(as.POSIXct(x)) - as.numeric(as.POSIXct(origin))) / unit2sec[unit, sec] if (is.logical(scientific)) xnum = format(xnum, scientific = scientific) return(xnum) } dat_filter = function(dat, date_range, timestamp, timesubmit) { if (!is.null(date_range) && !is.na(date_range)) { timestamp_col = timesubmit_col = NULL timecols = c(timestamp, timesubmit) dat = copy(dat)[, (c('timestamp_col', 'timesubmit_col')) := lapply(.SD, as_date), .SDcols = timecols] dat = dat[ timestamp_col >= date_from(date_range, timesubmit_col) & timestamp_col < timesubmit_col ][, (c('timestamp_col', 'timesubmit_col')) := NULL] } return(dat) }
/scratch/gouwar.j/cran-all/cranData/xefun/R/date_funcs.R
#' char repetition rate #' #' reprate estimates the max rate of character repetition. #' #' @param x a character vector or a data frame. #' @param col a character column name. #' #' @return a numeric vector indicating the max rate of character repetition in the corresponding elements in argument x vector. #' #' @examples #' x = c('a', 'aa', 'ab', 'aab', 'aaab') #' reprate(x) #' #' reprate(data.frame(x=x), 'x') #' #' @export reprate = function(x, col) { UseMethod('reprate') } #' @export reprate.character = function(x, ...) { reprate.data.frame(data.table(V1=x), 'V1')[['reprate_V1']] } #' @export reprate.data.frame = function(x, col) { num = repn = rid = NULL dat = setDT(copy(x))[, rid := .I] dat2 = dat[!is.na(get(col)),c('rid', col),with=FALSE ][, strsplit(get(col),''), by = 'rid' ][, num := .N, by = 'rid' ][, repn := .N, by = c('rid', 'V1') ][][, max(repn/num), by = 'rid'][] setnames(dat2, 'V1', paste0('reprate_', col)) dat3 = merge(dat, dat2, by = 'rid', all = TRUE)[, rid := NULL] return(dat3[]) }
/scratch/gouwar.j/cran-all/cranData/xefun/R/reprate.R
#' vector to list #' #' Converting a vector to a list with names specified. #' #' @param x a vector. #' @param name specify the names of list. Setting the names of list as x by default. #' @param ... Additional parameters provided in the as.list function. #' #' @examples #' as.list2(c('a', 'b')) #' #' as.list2(c('a', 'b'), name = FALSE) #' #' as.list2(c('a', 'b'), name = c('c', 'd')) #' #' @export as.list2 = function(x, name=TRUE, ...) { lst = as.list(x, ...) if (isTRUE(name)) { lst = setNames(lst, x) } else if (length(name) == length(x)) { lst = setNames(lst, name) } return(lst) } c_list = function(x, name=TRUE, ...) { as.list2(x, name, ...) } #' merge data.frames list #' #' Merge a list of data.frames by common columns or row names. #' #' @param datlst a list of data.frames. #' @param by A vector of shared column names in x and y to merge on. This defaults to the shared key columns between the two tables. If y has no key columns, this defaults to the key of x. #' @param all logical; all = TRUE is shorthand to save setting both all.x = TRUE and all.y = TRUE. #' @param ... Additional parameters provided in the merge function. #' #' @export merge2 = function(datlst, by = NULL, all = TRUE, ...) { Reduce(function(x,y) merge(setDT(x), setDT(y), by = by, all=all, ...), datlst ) } #' columns by type #' #' The columns name of a data frame by given data types. #' #' @param dt a data frame. #' @param type a string of data types, available values including character, numeric, double, integer, logical, factor, datetime. #' #' @examples #' dt = data.frame(a = sample(0:9, 6), b = sample(letters, 6), #' c = Sys.Date()-1:6, d = Sys.time() - 1:6) #' dt #' # numeric columns #' cols_type(dt, 'numeric') #' # or #' cols_type(dt, 'n') #' #' # numeric and character columns #' cols_type(dt, c('character', 'numeric')) #' # or #' cols_type(dt, c('c', 'n')) #' #' # date time columns #' cols_type(dt, 'datetime') #' #' @export cols_type = function(dt, type) UseMethod('cols_type') #' @export cols_type.data.frame = function(dt, type) { type = sapply(type, function(x) match.arg(x, c('character', 'numeric', 'double', 'integer', 'logical', 'factor', 'datetime')), USE.NAMES = FALSE) as.vector(unlist(sapply( type, function(t) names(which(setDT(dt)[, sapply(.SD, paste0('is.',t))])), USE.NAMES = FALSE ))) } #' constant columns #' #' The columns name of a data frame with constant value. #' #' @param dt a data frame. #' #' @examples #' dt = data.frame(a = sample(0:9, 6), b = sample(letters, 6), #' c = rep(1, 6), d = rep('a', 6)) #' dt #' cols_const(dt) #' #' @export cols_const = function(dt) UseMethod('cols_const') #' @export cols_const.data.frame = function(dt) { names(which(setDT(dt)[,sapply(.SD, function(x) length(unique(x))==1)])) }
/scratch/gouwar.j/cran-all/cranData/xefun/R/utils.R
#' Factory for configuring a gene dependent Crossover function. #' #' @description \code{sgXCrossoverFactory()} selects #' \enumerate{ #' \item the algorithm specific crossover factory and #' \item the method in this factory. #' } #' #' @details The available methods for each algorithm are: #' \itemize{ #' \item "sga": #' "Cross2Gene", "UCross2Gene", "UPCross2Gene", #' "CrossGene", "UCrossGene", "UPCrossGene". #' \item "sge": #' "Cross2Gene", "UCross2Gene", "UPCross2Gene", #' "CrossGene", "UCrossGene", "UPCrossGene". #' \item "sgp": #' "CrossGene", "Cross2Gene". #' \item "sgde": #' "CrossGene", "UCrossGene", "UPCrossGene". #' \item "sgperm": #' "CrossGene", "Cross2Gene". #' } #' #' @param algorithm Specifies algorithm. #' Available: "sga", "sgde", "sgperm", "sge", sgp". #' Default: "sga". #' @param method Crossover method. Algorithm (gene representation) #' dependent. Default: \code{Crossgene()}. #' Must be available in the gene specific #' crossover factories. #' @return Crossover Crossover function from the crossover factory of #' the selected package. #' #' @family Configuration #' #' @examples #' sgXCrossoverFactory(algorithm="sga", method="CrossGene") #' #'@importFrom xegaGaGene xegaGaCrossoverFactory #'@importFrom xegaGpGene xegaGpCrossoverFactory #'@importFrom xegaDfGene xegaDfCrossoverFactory #'@importFrom xegaPermGene xegaPermCrossoverFactory #'@export sgXCrossoverFactory<-function(algorithm="sga", method="CrossGene") { if (algorithm=="sga") {Factory<-xegaGaGene::xegaGaCrossoverFactory} if (algorithm=="sgp") {Factory<-xegaGpGene::xegaGpCrossoverFactory} if (algorithm=="sge") {Factory<-xegaGaGene::xegaGaCrossoverFactory} if (algorithm=="sgde") {Factory<-xegaDfGene::xegaDfCrossoverFactory} if (algorithm=="sgperm") {Factory<-xegaPermGene::xegaPermCrossoverFactory} if (!exists("Factory", inherits=FALSE)) {stop("sgX Crossover Factory label ", algorithm, " does not exist")} return(Factory(method)) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXCrossoverFactory.R
#' Factory for configuring a gene dependent DecodeGene function. #' #' @description A gene specific decoder must be provided. #' #' @param algorithm "sga", "sgde", "sgperm", "sge", sgp". Default: "sga". #' #' @param method Method. Default: "DecodeGene". #' #' @returns Decode function for the selected algorithm from the correct package. #' #' @family Configuration #' #' @examples #' sgXDecodeGeneFactory(algorithm="sgperm", method="DecodeGene") #' #'@importFrom xegaGaGene xegaGaDecodeGene #'@importFrom xegaGpGene xegaGpDecodeGene #'@importFrom xegaGeGene xegaGeDecodeGene #'@importFrom xegaDfGene xegaDfDecodeGene #'@importFrom xegaPermGene xegaPermDecodeGene #'@export sgXDecodeGeneFactory<-function(algorithm="sga", method="DecodeGene") { if (algorithm=="sga") {f<-xegaGaGene::xegaGaDecodeGene} if (algorithm=="sgp") {f<-xegaGpGene::xegaGpDecodeGene} if (algorithm=="sge") {f<-xegaGeGene::xegaGeDecodeGene} if (algorithm=="sgde") {f<-xegaDfGene::xegaDfDecodeGene} if (algorithm=="sgperm") {f<-xegaPermGene::xegaPermDecodeGene} if (!exists("f", inherits=FALSE)) {stop("sgX DecodeGene Factory label ", algorithm, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXDecodeFactory.R
#' Factory for configuring a gene dependent geneMap function. #' #' @description The geneMap function depends on the gene representation and #' the algorithm selected. #' #' @details Methods available for the different algorithms are: #' \itemize{ #' \item "sga": "Bin2Dec", "Gray2Dec", "Identity", "Permutation". #' \item "sgde": "Identity". #' \item "sgperm": "Identity". The gene map function is not used in #' the decoder. #' \item "sgp": "Identity". The gene map function is not used in #' the decoder. #' \item "sge": "Mod" or "Bucket". #' } #' #' @param algorithm Algorithm. #' Available: "sga", "sgde", "sgperm", "sge", sgp". #' Default: "sga". #' #' @param method The GeneMap method. The choices depend on the #' \code{algorithm}. #' #' @return GeneMap function for the selected algorithm from the correct package. #' #' @family Configuration #' #' @examples #' sgXGeneMapFactory(algorithm="sga", method="Bin2Dec") #' #'@importFrom xegaGaGene xegaGaGeneMapFactory #'@importFrom xegaGeGene xegaGeGeneMapFactory #'@importFrom xegaDfGene xegaDfGeneMapFactory #'@export sgXGeneMapFactory<-function(algorithm="sga", method="Bin2Dec") { if (algorithm=="sga") {Factory<-xegaGaGene::xegaGaGeneMapFactory} if (algorithm=="sgp") {Factory<-xegaGaGene::xegaGaGeneMapFactory} if (algorithm=="sge") {Factory<-xegaGeGene::xegaGeGeneMapFactory} if (algorithm=="sgde") {Factory<-xegaDfGene::xegaDfGeneMapFactory} if (algorithm=="sgperm") {Factory<-xegaDfGene::xegaDfGeneMapFactory} if (!exists("Factory", inherits=FALSE)) {stop("sgX GeneMap Factory label ", algorithm, " does not exist")} return(Factory(method)) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXGeneMapFactory.R
#' Factory for configuring a gene dependent InitGene function. #' #' @param algorithm Algorithm. #' Available: "sga", "sgde", "sgperm", "sge", sgp". #' Default: "sga". #' #' @param method Method. Default: "InitGene". #' #' @return InitGene function from the correct package. #' #' @family Configuration #' #' @examples #' sgXInitGeneFactory(algorithm="sgperm") #' #'@importFrom xegaGaGene xegaGaInitGene #'@importFrom xegaGpGene xegaGpInitGene #'@importFrom xegaGeGene xegaGeInitGene #'@importFrom xegaDfGene xegaDfInitGene #'@importFrom xegaPermGene xegaPermInitGene #'@export sgXInitGeneFactory<-function(algorithm="sga", method="InitGene") { if (algorithm=="sga") {f<-xegaGaGene::xegaGaInitGene} if (algorithm=="sgp") {f<-xegaGpGene::xegaGpInitGene} if (algorithm=="sge") {f<-xegaGeGene::xegaGeInitGene} if (algorithm=="sgde") {f<-xegaDfGene::xegaDfInitGene} if (algorithm=="sgperm") {f<-xegaPermGene::xegaPermInitGene} if (!exists("f", inherits=FALSE)) {stop("sgX InitGene Factory label ", algorithm, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXInitFactory.R
#' Factory for configuring a gene dependent Mutation function. #' #' @description \code{sgXMutationFactory()} selects #' \enumerate{ #' \item the algorithm specific crossover factory and #' \item the method in this factory. #' } #' #' @details The available methods for each factory are: #' \itemize{ #' \item "sga": "MutateGene", "IVM". #' \item "sge": "MutateGene", "IVM". #' \item "sgp": "MutateGene". #' \item "sgde": "MutateGeneDE". #' \item "sgperm": "MutateGeneOrderBased", #' "MutateGenekInversion", "MutateGene2Opt", "MutateGenekOptLK", #' "MutateGeneGreedy", "MutateGeneBestGreedy", "MutateGeneMix". #' } #' #' @param algorithm Algorithm. #' Available: "sga", "sgde", "sgperm", "sge", sgp". #' Default: "sga". #' #' @param method Method. Available methods are package-dependent. #' #' @return MutateGene Function for the selected algorithm #' from the correct package. #' #' @family Configuration #' #'@examples #' sgXMutationFactory(algorithm="sga", method="MutateGene") #' #'@importFrom xegaGaGene xegaGaMutationFactory #'@importFrom xegaGpGene xegaGpMutationFactory #'@importFrom xegaDfGene xegaDfMutationFactory #'@importFrom xegaPermGene xegaPermMutationFactory #'@export sgXMutationFactory<-function(algorithm="sga", method="MutateGene") { if (algorithm=="sga") {Factory<-xegaGaGene::xegaGaMutationFactory} if (algorithm=="sgp") {Factory<-xegaGpGene::xegaGpMutationFactory} if (algorithm=="sge") {Factory<-xegaGaGene::xegaGaMutationFactory} if (algorithm=="sgde") {Factory<-xegaDfGene::xegaDfMutationFactory} if (algorithm=="sgperm") {Factory<-xegaPermGene::xegaPermMutationFactory} if (!exists("Factory", inherits=FALSE)) {stop("sgX Mutation Factory label ", algorithm, " does not exist")} return(Factory(method)) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXMutationFactory.R
#' Factory for configuring a gene dependent Replication function. #' #' @param algorithm Algorithm. #' Available: "sga", "sgde", "sgperm", "sge", sgp". #' Default: "sga". #' #' @param method Method. #' #' Options are package-dependent: #' \itemize{ #' \item "sga", "sgperm", "sge", sgp": #' "Kid1", "Kid2". #' \item "sgde": #' "DE". #' } #' #' @family Configuration #' #' @examples #' sgXReplicationFactory(algorithm="sgp", method="Kid1") #' #' @return A replication function for the algorithm from the correct package. #' #'@importFrom xegaGaGene xegaGaReplicationFactory #'@importFrom xegaDfGene xegaDfReplicationFactory #'@export sgXReplicationFactory<-function(algorithm="sga", method="Kid1") { if (algorithm=="sga") {Factory<-xegaGaGene::xegaGaReplicationFactory} if (algorithm=="sgp") {Factory<-xegaGaGene::xegaGaReplicationFactory} if (algorithm=="sge") {Factory<-xegaGaGene::xegaGaReplicationFactory} if (algorithm=="sgde") {Factory<-xegaDfGene::xegaDfReplicationFactory} if (algorithm=="sgperm") {Factory<-xegaGaGene::xegaGaReplicationFactory} if (!exists("Factory", inherits=FALSE)) {stop("sgX Replication Factory label ", algorithm, " does not exist")} return(Factory(method)) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgXReplicationFactory.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Top-level main programs. # Package: xega # #' Problem environment for a 2-dimensional quadratic parabola #' #' @description Problem environment for finding maxima and minima #' of a 2-dimensional quadratic parabola. #' #' @return A named list #' \itemize{ #' \item \code{$name()}: Returns the name of the problem environment. #' \item \code{$bitlength()}: The vector of the #' bitlengths of the parameters. #' \item \code{$genelength()}: The number of bits of a gene. #' \item \code{$lb()}: The vector of lower bounds #' of the parameters. #' \item \code{$ub()}: The vector of upper bounds of the parameters. #' \item \code{$f(parm)}: The implementation of the function of the #' quadratic parabola. #' \itemize{ #' \item \code{parm}: A 2-element vector of reals. #' \item Returns the value of the function. #' } #' \item \code{$describe()}: Returns the description of #' the problem environment. #' \item \code{$solution()}: The solutions (maxima/minima) of the #' problem environment (if known). #' } #' #' @family Problem Environment #' #' @examples #' names(Parabola2D) #' Parabola2D$name() #' Parabola2D$describe() #' Parabola2D$bitlength() #' Parabola2D$genelength() #' Parabola2D$lb() #' Parabola2D$ub() #' Parabola2D$f #' Parabola2D$f(c(2.2, -1.37)) #' Parabola2D$solution() #' Parabola2D$solution()$minimum #' Parabola2D$solution()$minpoints #' Parabola2D$solution()$maximum #' Parabola2D$solution()$maxpoints #' @importFrom xegaSelectGene Parabola2DFactory #' @export Parabola2D<-xegaSelectGene::Parabola2DFactory() #' Problem environment for a 2-dimensional quadratic parabola. #' #' @description An example of a problem environment with an #' early termination condition. #' #' @return A problem environment (see \link{Parabola2D}). #' \code{Parabola2DEarly$terminate(solution, lF)} #' is a test function which returns true if the \code{solution} #' is in an epsilon environment of a known solution. #' To invoke this function, use \code{Run( ..., early=TRUE, ...)}. #' The epsilon which determines #' the length of the interval as a fraction #' of the known optimal solution is configured by #' e.g. \code{Run( ..., terminationEps=0.001, ...)}. #' #' @family Problem Environment #' #' @importFrom xegaSelectGene Parabola2DEarlyFactory #' @export Parabola2DEarly<-xegaSelectGene::Parabola2DEarlyFactory()
/scratch/gouwar.j/cran-all/cranData/xega/R/sgaProblems.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # For gene representation of derivation trees. # Package: xegaGpGene # #' A constant function with a boolean grammar. #' #' @description For the distribution of examples of BNF in grammars. #' #' @details Imported from package xegaBNF for use in examples. #' #' @return A named list with $filename and $BNF, #' the grammar of a boolean grammar with two variables. #' #' @family Grammar #' #' @examples #' booleanGrammar() #' @importFrom xegaBNF booleanGrammar #' @export booleanGrammar<-xegaBNF::booleanGrammar #' Compile a BNF. #' #' @description \code{compileBNF()} produces a context-free grammar #' from its specification of in Backus-Naur form (BNF). #' Warning: No error checking implemented. #' #' @details A grammar consists of the symbol table \code{ST}, the production #' table \code{PT}, the start symbol \code{Start}, #' and the short production #' table \code{SPT}. An example BNF is provided #' by \code{booleanGrammar()}. #' #' The function performs the following steps: #' \enumerate{ #' \item Make the symbol table. #' \item Make the production table. #' \item Extract the start symbol. #' \item Compile a short production table. #' \item Return the grammar.} #' #' For a full documentation, see <https://CRAN.R-project.org/package=xegaBNF> #' #' @param g A character string with a BNF. #' @param verbose Boolean. TRUE: Show progress. Default: FALSE. #' #' @return A grammar object (list) with the attributes #' \code{name} (the filename of the grammar), #' \code{ST} (symbol table), #' \code{PT} (production table), #' \code{Start} (the start symbol of the grammar), #' and \code{SPT} (the short production table). #' #' @family Grammar #' #' @examples #' g<-compileBNF(booleanGrammar()) #' g$ST #' g$PT #' g$Start #' g$SPT #' @importFrom xegaBNF compileBNF #' @export compileBNF<-xegaBNF::compileBNF #' Generate the problem environment EnvXOR #' #' @description \code{NewEnvXOR()} generates the problem environment #' for the XOR-Problem. #' #' The problem environment provides an abstract interface #' to the simple genetic programming algorithm. #' \code{ProblemEnv$f(parm)} defines the function we want to optimize. #' #' A problem environment is a function factory with the following #' elements: #' #' \enumerate{ #' \item #' \code{name()} a string with the name of the environment #' \item #' \code{ProblemEnv$f(word)} #' function with word a word of the language (as text string). #' } #' #' Should be provided by the user as standard R-file. #' #' @family Problem Environment #' #' @return The problem environment: #' \itemize{ #' \item \code{$name}: The name of the problem environment. #' \item \code{$f}: The fitness function. #' For this environment number of correct test cases #' (correct function) #' and the inverse of the number of terminal symbols #' (boolean function with small number of elements). #' } #' @examples #' EnvXOR<-NewEnvXOR() #' EnvXOR$name() #' a2<-"OR(OR(D1, D2), (AND(NOT(D1), NOT(D2))))" #' a3<-"OR(OR(D1, D2), AND(D1, D2))" #' a4<-"AND(OR(D1,D2),NOT(AND(D1,D2)))" #' gp4<-"(AND(AND(OR(D2,D1),NOT(AND(D1,D2))),(OR(D2,D1))))" #' EnvXOR$f(a2) #' EnvXOR$f(a3) #' EnvXOR$f(a4) #' EnvXOR$f(gp4) #' #' @importFrom xegaDerivationTrees treeLeaves #' @export NewEnvXOR<-function() { penv<-list() penv[["name"]]<-function() {"EnvXOR"} penv[["BuildTEST"]]<-function(expr) { f<-paste("function(v) { AND<-function(x,y){return(x & y)} NAND<-function(x,y){return(!(x & y))} OR<-function(x,y){return(x|y)} NOT<-function(x){return(!x)} D1<-v[1] D2<-v[2] return(", expr, ")}", sep="") return(eval(parse(text=f))) } penv[["TestCases"]]<-matrix(c(0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0), nrow=4, ncol=3, byrow=TRUE) penv[["f"]]<-function(expr, gene=NULL, lF=NULL) { TEST<-penv$BuildTEST(expr) s<-0 for (i in 1:nrow(penv$TestCases)) { s<-s+ (penv$TestCases[i,ncol(penv$TestCases)]==TEST(penv$TestCases[i,])) } if (identical(gene, NULL)) {return(s)} b<-xegaDerivationTrees::treeLeaves(gene$gene1, lF$Grammar$ST) s<-(s+(1/(b^2))) return(s) } return(penv) }
/scratch/gouwar.j/cran-all/cranData/xega/R/sgpProblems.R
#' The main program of the e(x)tended (e)volutionary and (g)enetic (a)lgorithm #' (xega) package. #' #' @section Layers (in top-down direction): #' #' \enumerate{ #' \item \strong{Top-level main programs} #' (Package \code{xega}): #' \code{RunGA()}, \code{ReRun()} #' \item \strong{Population level operations - independent of representation} #' (Package \code{xegaPopulation}): #' The population layer consists of functions for initializing, #' logging, observing, evaluating a population of genes, #' as well as of computing the next population. #' \item \strong{Gene level operations - representation-dependent}. #' \enumerate{ #' \item #' \strong{Binary representation} (Package \code{xegaGaGene}): #' Initialization of random binary genes, #' several gene maps for binary genes, #' several mutation operators, #' several crossover operators with 1 and 2 kids, #' replication pipelines for 1 and 2 kids, #' and, last but not least, function factories for configuration. #' \item \strong{Real-coded genes} (Package \code{xegaDfGene}). #' \item \strong{Permutation genes} (Package \code{xegaPermGene}). #' \item \strong{Derivation-tree genes} (Package \code{xegaGpGene}). #' \item \strong{Binary genes with a grammar-driven decoder} #' (Package \code{xegaGeGene}). #' } #' \item \strong{Gene level operations - independent of representation} #' (Package \code{selectGene}): #' Functions for static and adaptive fitness scaling, #' gene selection, and gene evaluation #' as well as for the measurement of performance and for configuration. #' } #' #' @section Early Termination: #' #' A problem environment may implement a function #' \code{terminate(solution)} which returns TRUE #' if the \code{solution} meets a condition for early #' termination. #' #' @section Parallel and Distributed Execution: #' #' Parallel and distributed execution is supported for #' several combinations of hard- and software architectures #' by overloading the \code{lapply()}-function used in the #' evaluation of a fitness function for a population of genes #' with a parallel version with the abstract interface: #' #' \code{parallelApply(pop, EvalGene, lF)} #' #' where \code{pop} is a list of genes, \code{EvalGene} the evaluation #' function for the fitness of a gene, and \code{lF} the local function #' configuration of the algorithm. #' #' The several implementations of a \code{parallelApply()} function #' are provided. The implementations use #' #' \itemize{ #' \item the function \code{parallel::mclapply()} for multicore #' parallelization by the fork mechanism of Unix-based operating systems #' on a single machine. #' \item the function \code{parallel::parLapply()} for socket connections #' on a single or multiple machines on the Internet. #' \item the function \code{future.apply::future_lapply()} for #' asynchronous parallelization based on future packages. #' } #' #' In addition, user-defined parallel apply functions can be provided. #' Example scripts for using the \code{Rmpi::mpi.parLapply()} function #' of the \code{Rmpi} package are provided for a HPC environment with Slurm #' as well as on a notebook. #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' e(x)tended (e)volutionary and (g)enetic (a)lgorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega} #' <https://CRAN.R-project.org/package=xega> #' ) provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation} #' <https://CRAN.R-project.org/package=xegaPopulation> #' ) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and #' for parallelization. #' #' \item #' The gene layer is split in a representation independent and #' a representation dependent part: #' \enumerate{ #' \item #' The representation indendent part #' (package \code{xegaSelectGene} #' <https://CRAN.R-project.org/package=xegaSelectGene> #' ) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} #' <https://CRAN.R-project.org/package=xegaGaGene> #' for binary coded genetic algorithms. #' \item \code{xegaPermGene} #' <https://CRAN.R-project.org/package=xegaPermGene> #' for permutation-based genetic algorithms. #' \item \code{xegaDfGene} #' <https://CRAN.R-project.org/package=xegaDfGene> #' for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} #' <https://CRAN.R-project.org/package=xegaGpGene> #' for grammar-based genetic algorithms. #' \item \code{xegaGeGene} #' <https://CRAN.R-project.org/package=xegaGaGene> #' for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the packages \code{xegaGpGene} and \code{xegaGeGene}: #' \itemize{ #' \item \code{xegaBNF} #' <https://CRAN.R-project.org/package=xegaBNF> #' essentially provides a grammar compiler and #' \item #' \code{xegaDerivationTrees} #' <https://CRAN.R-project.org/package=xegaDerivationTrees> #' an abstract data type for derivation trees. #' } #' }} #' #' @family Package Description #' #' @name xega #' @aliases xega #' @docType package #' @title Package xega #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: https://github.com/ageyerschulz/xega #' @section Installation: From CRAN by \code{install.packages('xega')} NULL
/scratch/gouwar.j/cran-all/cranData/xega/R/xega-package.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Top-level main programs. # Package: xega # # Distributed Master-Worker Configuration. # # @description Provided as a concrete example configuration. # The master must be able to launch ssh-authenticated # R-processes (without interactive login) as workers. # The example shown builds a cluster of 4 R-processes # on three machines which communicate via socket connections. # # @details A named list with the following elements: # \enumerate{ # \item \code{$port}: The IP port number of the master. # E.g. in 1024 -65353. # \item \code{$master}: The domain name of the master. # \item \code{$workers}: A list of domain names of workers. # } # # # workers <- c("em-pop.iism.kit.edu", "em-pop.iism.kit.edu", # "em-folk.iism.kit.edu") # master <- "em-ags-nb2.iism.kit.edu" # port <- 10250 # # @export # Cluster<-list( # port=10250, # master="em-ags-nb2.iism.kit.edu", # workers=c("em-pop.iism.kit.edu", # "em-pop.iism.kit.edu", # "em-pop.iism.kit.edu", # "em-folk.iism.kit.edu")) #
/scratch/gouwar.j/cran-all/cranData/xega/R/xegaCluster.R
#' The problem environment lau15 #' #' @description #' 15 abstract cities for which a traveling salesman solution is sought. #' Solution: A path with a length of 291. #' #' @references #' Lau, H. T. (1986): #' \emph{Combinatorial Heuristic Algorithms in FORTRAN}. #' Springer, 1986. #' <doi:10.1007/978-3-642-61649-5> #' #' @family Problem Environment #' #' @examples #' names(lau15) #' lau15$genelength() #' @importFrom xegaSelectGene lau15 #' @export lau15<-xegaSelectGene::lau15
/scratch/gouwar.j/cran-all/cranData/xega/R/xegaPermProblems.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Top-level main programs. # Package: xega # #' Run an evolutionary or genetic algorithm #' with the same configuration as in the previous run. #' #' @description \code{xegaReRun()} runs a simple genetic algorithm with #' the same configuration as in the run specified by the #' list element \code{$GAconfig} of the solution of #' a simple genetic algorithm. #' #' @details \code{xegaReRun()} does not capture the configuration for #' parallel/distributed processing for the execution model #' "FutureApply", because the user defines the configuration #' before calling \code{xegaRun()}. #' #' If \code{executionModel} matches neither \code{"Sequential"} nor \code{"MultiCore"} #' or \code{!is.null(uParApply)==TRUE}, #' a warning is printed, and the previous solution is returned. #' #' @param solution The solution of a #' previous run of \code{xegaRun()}. #' #' @return A list of #' \enumerate{ #' \item #' \code{$popStat}: A matrix with #' mean, min, Q1, median, Q3, max, var, mad #' of population fitness as columns: #' i-th row for i-th each generation. #' \item #' \code{$solution}: With fields #' \code{$solution$fitness}, #' \code{$solution$value}, #' \code{$solution$genotype}, and #' \item #' \code{$GAconfig}: The configuration of the GA used by \code{xegaReRun()}. #' \item #' \code{$GAenv}: Attribute value list of GAconfig. #' \item \code{$timer}: An attribute value list with #' the time used (in seconds) in the main blocks of the GA: #' tUsed, tInit, tNext, tEval, tObserve, and tSummary. #' } #' #' @family Main Program #' #' @examples #' a<-xegaRun(Parabola2D, max=FALSE, algorithm="sga", generations=10, popsize=20, verbose=1) #' b<-xegaReRun(a) #' seqApply<-function(pop, EvalGene, lF) {lapply(pop, EvalGene, lF)} #' c<-xegaRun(Parabola2D, max=FALSE, algorithm="sga", uParApply=seqApply) #' b<-xegaReRun(c) #' #' @export xegaReRun<-function(solution) { if (!is.null(solution$GAenv$uParApply)) {warning("Error: Re-run of configuration with a user supplied parallel apply not supported."); return(solution)} if (!(solution$GAenv$executionModel %in% c("Sequential", "MultiCore"))) {warning("Error: Re-run of parallel or distributed configurations not possible."); return(solution)} eval(parse(text=solution$GAconfig)) }
/scratch/gouwar.j/cran-all/cranData/xega/R/xegaRerun.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Top-level main programs. # Package: xega # #' Run an evolutionary or genetic algorithm for a problem environment #' which contains a function to optimize. #' #' @description \code{Run} runs an evolutionary or genetic algorithm #' whose type is selected by \code{algorithm}. Available #' algorithms are: #' \enumerate{ #' \item \code{"sga"}: Genetic algorithm with binary genes. #' \item \code{"sgde"}: Differential evolution with real genes. #' \item \code{"sgperm"}: Genetic algorithm with permutation genes. #' \item \code{"sgp"}: Grammar-based genetic programming with #' derivation-tree genes. #' \item \code{"sge"}: Grammatical evolution (genetic algorithm #' with binary genes and a grammar-driven #' decoder. #' } #' #' The choice of the algorithm determines the gene-dependent #' configuration options. #' #' @details The algorithm expects a problem environment \code{penv} which is a #' named list with at least the following functions: #' \itemize{ #' \item \code{$name()}: The name of the problem environment. #' \item \code{$f(parm, gene=0, lF=0)}: The function to optimize. #' The parameters gene and lF are provided #' for future extensions. #' } #' #' Additional parameters needed depend on the algorithm #' and the problem environment. #' For example, for binary genes for function optimization, #' additional elements must be provided: #' #' \itemize{ #' \item \code{$bitlength()}: The vector of the #' bitlengths of the parameters. #' \item \code{$genelength()}: The number of bits of a gene. #' \item \code{$lb()}: The vector of lower bounds #' of the parameters. #' \item \code{$ub()}: The vector of upper bounds of the parameters. #' } #' #' @section Problem Specification: #' #' The problem specification consists of #' \itemize{ #' \item \code{penv}: The problem environment. #' \item \code{max}: Maximize? Boolean. Default: \code{TRUE}. #' \item \code{grammar}: A grammar object. For the algorithms \code{"sgp"} and \code{"sge"}. #' } #' #' @section Basic Parameters: #' #' The main parameters of a ``standard'' genetic algorithm are: #' \itemize{ #' \item \code{popsize}: Population size. #' \item \code{generations}: Number of generations. #' \item \code{crossrate}: Constant probability of one-point crossover. #' \item \code{mutrate}: Constant probability of mutation. #' } #' #' \code{crossrate} and \code{mutrate} specify the probability of #' applying the genetic operators crossover and mutation to a gene. #' #' Two more parameters are important: #' #' \itemize{ #' \item \code{elitist}: Boolean. If \code{TRUE} (default), the fittest gene always survives. #' \item \code{replay}: Integer. If \code{0} (default), a random seed of the random number generator is chosen. #' For exact replications of a run of a genetic algorithm, set replay to a positive integer. #' } #' #' @section Global and Local Parameters: #' #' However, when using uniform crossover instead of one-point crossover, #' an additional parameter which specifies the probability of taking a bit #' from the first parent becomes necessary. #' Therefore, we distinguish between global and local operator parameters: #' \enumerate{ #' \item Global operator parameters: #' The probabilities of applying a crossover (\code{crossrate}) or #' a mutation operator (\code{mutrate}) to a gene. #' \item Local operator parameters: #' E.g. the per bit probability of mutation or the probability #' of taking a bit from parent 1 for the uniform crossover operator. #' Local operator parameters affect only #' the genetic operator which needs them. #' } #' #' There exist several advantages of this classification of parameters: #' \itemize{ #' \item For the formal analysis of the behavior of the algorithms, #' we achieve a division in two parts: The equations of the #' global parameters with operator specific expressions as plug-ins. #' \item For empirically finding parameterizations for problem classes, #' we propose to fix local parameters at reasonable values #' (e.g. based on biological evidence) and #' and conditional on this optimize the (few) remaining global #' parameters. #' \item For parallelization specialized #' gene processing pipelines can be built and more efficiently executed, #' because the global parameters \code{crossrate} and \code{mutrate} decide #' which genes survive #' \enumerate{ #' \item unchanged, #' \item mutated, #' \item crossed, and #' \item crossed as well as mutated. #' }} #' #' To mimic a classic genetic algorithm with crossover and bit mutation rate, #' the probability of applying the mutation operator to a gene #' should be set to \code{1}. #' #' @section Global Adaptive Mechanisms: #' #' The adaptive mechanisms described in the following are based on threshold #' rules which determine how a parameter of the genetic operator is adapted. #' The threshold conditions are based on population statistics: # For scaling, on thresholds of a ratio of a dispersion measure (RDM) at generation # \code{k} and a dispersion measure at generation \code{k-1}. For the global # crossover and mutation rates, on a comparison of a gene's fitness with # a population statistic. #' #' \strong{Adaptive Scaling.} For adaptive scaling, select a dynamic scaling method, #' e.g. \code{scaling="ThresholdScaling"}. #' A high selection pressure decreases the dispersion in the population. #' The parameter \code{scalingThreshold} is a numerical parameter which defines #' an interval from \code{1-scalingThreshold} to \code{1+scalingThreshold}: #' \enumerate{ #' \item If the RDM is in this interval, the fitness function is not scaled. #' \item If the RDM is larger than the upper bound of the interval, #' the constant \code{scalingExp} which is higher than \code{1} is chosen for the scaling function. #' This implements the rule: If the dispersion has increased, increase the selection pressure. #' \item If the RDM is smaller than the lower bound of the interval, #' the constant \code{scalingExp2} which is smaller than \code{1} is chosen for the scaling function. #' This implements the rule: If the dispersion has decreased, increase the selection pressure. #' } #' #' The dispersion measure is computed as ratio of the dispersion measure at \code{t} relative to the #' dispersion measure at \code{t-scalingDelay}. #' The default dispersion measure is the variance of the population fitness (\code{dispersionMeasure="var"}). #' However, other dispersion measures ("std", "mad", "cv", "range", "iqr") can be configured. #' #' Another adaptive scaling method is continuous scaling (\code{scaling="ContinuousScaling"}). #' The scaling exponent is adapted by a weighted ratio of dispersion measures. The weight #' of the exponent is set by \code{rdmWeight=1.1}, its default is \code{1.0}. Since the ratio #' of dispersion measures may be quite unstable, the default limits for the ratio are \code{drMin=0.5} #' and \code{drMax=2.0}. #' #' \strong{Individually Variable Mutation and Crossover Probabilities} #' #' The rationale of individually variable mutation and crossover rates is that selected genes #' with a low fitness should be changed by a genetic operator with a higher probability. #' This increases the chance of survival of the gene because of the chance of a fitness increase through #' crossover or mutation. #' #' Select an adaptive genetic operator rate: #' For the crossover rate, \code{ivcrossrate="IV"}. For the mutation rate, \code{ivmutrate="IV"}. #' #' If the fitness of a gene is higher than \code{cutoffFit} times the current best fitness, #' the crossover rate is \code{crossrate} else the crossover rate is \code{crossrate2}. #' #' If the fitness of a gene is higher than \code{cutoffFit} times the current best fitness, #' the mutation rate is \code{mutrate} else the mutation rate is \code{mutrate2}. #' #' @section The Initialization of a Population: #' #' For the algorithms "sga", "sgde", and "sgperm" the information needed for #' initialization is the length of the gene in bits, in parameters, and in #' the number of symbols of a permutation. #' For "sgp", the depth bound gives an upper limit for the #' program which can be represented by a derivation tree. #' For "sge", a codon is an integer for selecting a production rule. #' The number of bits of a genes is \code{codons*codonBits}. #' #' \tabular{lll}{ #' \strong{Algorithm}\tab \tab \strong{Parameters} \cr #' \strong{"sga"}\tab Number of bits. \tab \code{penv$genelength()} \cr #' \strong{"sgde"}\tab Number of parameters. \tab #' \code{length(penv$bitlength()}, #' \code{penv$lb()}, \code{penv$ub()}\cr #' \strong{"sgperm"}\tab Number of symbols. \tab \code{penv$genelength()} \cr #' \strong{"sgp"}\tab Depth bound of derivation tree. \tab \code{maxdepth} \cr #' \strong{"sge"}\tab Number of codons and #' \tab\code{codons}, \code{codonBits}, #' \code{codonPrecision}, \code{maxPBias} \cr #' \tab number of bits of a codon. \tab #' } #' #' @section The Pipeline of Genetic Operators: #' #' The pipeline of genetic operators merges the pipeline of a genetic algorithm with the pipeline of #' evolutionary algorithms and simulated annealing by adding an acceptance step: #' \itemize{ #' \item For evolutionary algorithms, #' the acceptance rule \code{accept="Best"} means that the fitter gene out of a parent and its kid survives #' (is copied into the next generation). #' \item For genetic algorithms the acceptance rule \code{accept="All"} means that always the kid survives. #' \item For simulated annealing the acceptance rule \code{accept="Metropolis"} #' means that the survival probability of a kid with a fitness #' worse than its parent decreases as the number of generations executed increases. #' } #' #' Proper configuration of the pipeline allows the configuration of new algorithm variants which mix elements #' of genetic, evolutionary, and simulated annealing algorithms. #' #' The following table gives a working standard configuration of the pipeline of the genetic operators for each #' of the five algorithms: #' #' \tabular{lccccc}{ #' \strong{Step/Algorithm}\tab\strong{"sga"}\tab\strong{"sgde"}\tab\strong{"sgperm"}\tab\strong{"sgp"}\tab\strong{"sge"}\cr #' (next) Scaling \tab NoScaling \tab NoScaling \tab NoScaling \tab NoScaling \tab NoScaling \cr #' (next) Selection \tab SUS \tab UniformP \tab SUS \tab SUS \tab SUS \cr #' (next) Replication \tab Kid2 \tab DE \tab Kid2 \tab Kid2 \tab Kid2 \cr #' (next) Crossover \tab Cross2Gene \tab UCrossGene \tab Cross2Gene \tab Cross2Gene \tab Cross2Gene \cr #' (next) Mutation \tab MutateGene \tab MutateGeneDE \tab MutateGene \tab MutateGene \tab MutateGene \cr #' (next) Acceptance \tab All \tab Best \tab All \tab All \tab All \cr #' (eval) Decoder \tab Bin2Dec \tab Identity \tab Identity \tab - \tab Mod \cr #' (eval) Evaluation \tab EvalGeneU \tab EvalGeneU \tab EvalGeneU \tab EvalGeneU \tab EvalGeneU #' } #' #' @section Scaling: #' #' In genetic algorithms scaling of the fitness functions has the purpose of increasing or decreasing #' the selection pressure. Two classes of scaling methods are available: #' #' \itemize{ #' \item Constant scaling methods. #' \itemize{ #' \item No scaling (configured by \code{scaling="NoScaling"}). #' \item Constant scaling (configured by \code{scaling="ConstantScaling"}). #' Depends on scaling exponent \code{scalingExp}. #' } #' \item Adaptive scaling methods. #' \itemize{ #' \item Threshold scaling (configured by \code{scaling="ThresholdScaling"}). #' It is configured with the scaling exponents \code{scalingExp} and \code{scalingExp2}, #' and the scaling threshold \code{scalingThreshold}. #' It uses a threshold rule about the change of a dispersion measure #' of the population fitness \code{lF$RDM()} #' to choose the scaling exponent: #' \itemize{ #' \item \code{lF$RDM()>1+scalingThreshold}: The scaling exponent is \code{scalingExp} #' which should be greater than \code{1}. #' Rationale: Increase selection pressure to reduce dispersion of fitness. #' \item \code{lF$RDM()<1-scalingThreshold}: The scaling exponent is \code{scalingExp2} #' which should be lower than \code{1}. #' Rationale: Decrease selection pressure to increase dispersion of fitness. #' \item Else: Scaling exponent is \code{1}. Fitness is not scaled. #' } #' \item Continuous scaling (configured by \code{scaling="ContinuousScaling"}). #' The ratio of the dispersion measures \code{lF$RDM()} is #' greater than 1 if the dispersion increased in the last generation and #' less than 1 if the dispersion decreased in the last generation. #' The scaling exponent is the product of the ratio of the #' dispersion measures \code{lF$RDM()} with the #' weight \code{rdmWeight}. #' } #' } #' #' The change of the dispersion measure of the population fitness is measured by the function \code{lF$RDM()} #' (RDM means (R)atio of (D)ispersion (M)easure). This function depends on #' \itemize{ #' \item the choice of a dispersion measure of the population fitness \code{dispersionMeasure}. #' The variance is the default (\code{dispersionMeasure="var"}). #' The following dispersion measure of the population fitness are avalaible: #' Variance (\code{"var"}), #' standard deviation (\code{"std"}), #' median absolute deviation (\code{"mad"}), #' coefficient of variation (\code{"cv"}), #' range (\code{"range"}), #' inter quartile range (\code{"iqr"}). #' \item the scaling delay \code{scalingDelay}. The default is \code{scalingDelay=1}. #' This means the ratio of the variance of the fitness of the population at time t #' and the variance of the fitness of the population at time t-1 is computed. #' \item the upper and lower bounds of the ratio of dispersion measures. #' \item Dispersion ratios may have extreme fluctuations: The parameters \code{drMax} and \code{drMin} #' define upper and lower bounds of the ratio of dispersion measures. #' The defaults are \code{drMax=2} and \code{drMin=1}. #' } #' See package \code{xegaSelectGene} <https://CRAN.R-project.org/package=xegaSelectGene> #' #' @section Selection: #' #' Selection operators determine which genes are chosen for the replication process for the next generation. #' Selection operators are configured by \code{selection} and \code{mateselection} #' (the 2nd parent for crossover). The default operator is stochastic universal selection #' for both parents (configured by \code{selection="SUS"} and \code{mateselection="SUS"}). #' The following operators are implemented: #' \itemize{ #' \item Uniform random selection with replacement (configured by \code{"Uniform"}). #' Needed for simulating uniform random mating behavior, computer experiments without #' selection pressure, for computing random search solutions as naive benchmarks. #' \item Uniform random selection without replacement (configured by \code{"UniformP"}). #' Needed for differential evolution. #' \item Selection proportional to fitness #' (in \code{O(n)} by \code{"SelectPropFit"}, in \code{O(n*log(n))} by \code{"SelectPropFitOnln"}, #' and in \code{O(n^2)} by \code{"SelectPropFitM"}). #' \code{offset} configures the shift of the fitness vector if \code{min(fit)=<0}. #' \item Selection proportional to fitness differences #' (in \code{O(n)} by \code{"SelectPropFitDiff"}, in \code{O(n*log(n))} by \code{"SelectPropFitDiffOnln"}, #' and in \code{O(n^2)} by \code{"SelectPropFitDiffM"}). #' Even the worst gene should have a minimal chance of survival: \code{eps} is added to the #' fitness difference vector. This also guarantees numerical stability for populations #' in which all genes have the same fitness. #' \item Deterministic tournament selection of \code{k} genes (configured by \code{"Tournament"}). #' The tournament size is configured by \code{tournamentSize}. #' Selection pressure increases with tournament size. #' The worst \code{k-1} genes of a population never survive. #' \item Deterministic tournament selection of \code{2} genes (configured by \code{"Duel"}). #' \item Stochastic tournament selection of \code{k} genes (configured by \code{"STournament"}). #' The tournament size is configured by \code{tournamentSize}. #' \item Linear rank selection with selective pressure (configured by \code{"LRSelective"}). #' The selection bias which regulates the selection pressure #' is configured by \code{selectionBias} #' (should be between \code{1.0} (uniform selection) and \code{2.0}). #' \item Linear rank selection with interpolated target sampling rates (configured by \code{"LRTSR"}). #' The maximal target sampling rate is configured by \code{maxTSR} #' (should be between \code{1} and \code{2}). #' \item Stochastic universal sampling (configured by \code{"SUS"}). #' } #' #' If \code{selectionContinuation=TRUE} then selection functions are computed exactly once #' per generation. They are transformed into lookup-functions which deliver the index of selected genes by #' indexing a vector of integers. #' #' See package \code{xegaSelectGene} <https://CRAN.R-project.org/package=xegaSelectGene> #' #' @section Replication: #' #' For genetic algorithms ("sga", "sgp", sgperm", and "sge") #' in the replication process of a gene the crossover operator may #' by configured to produce one new gene (\code{replication="Kid1"}) #' or two new genes (\code{replication="Kid2"}). The first version #' looses genetic information in the crossover operation, whereas the second version #' retains the genetic material in the population. #' There is a dependency between \code{replication} and \code{crossover}: #' \code{"Kid2"} requires a crossover operator which produces two kids. #' The replication method is configured by the function #' \code{xegaGaReplicationFactory()} of package \code{xegaGaGene}. #' #' Note that only the function \code{xegaGaReplicateGene} of \code{xegaGaGene} #' (configured with \code{replication="Kid1"}) implements a genetic operator pipeline #' with an acceptance rule. #' #' For differential evolution (algorithm "sgde"), \code{replication="DE"} #' must be configured. #' The replication method for differential evolution is configured by the function #' \code{xegaDfReplicationFactory()} of package \code{xegaDfGene}. #' It implements a configurable acceptance rule. For classic differential evolution, #' use \code{accept="Best"}. #' #' @section Crossover: #' #' The table below summarizes the available crossover operators of the current version. #' #' \tabular{lllll}{ #' \strong{Algorithm:} \tab \strong{"sga"} and \strong{"sge"} \tab \strong{Package:} \tab \strong{xegaGaGene} \tab\cr #' Kids \tab Name \tab Function \tab crossover= \tab Influenced by\cr #' (2 kids) \tab 1-Point \tab xegaGaCross2Gene() \tab "Cross2Gene" \tab \cr #' \tab Uniform \tab xegaGaUCross2Gene() \tab "UCross2Gene" \tab \cr #' \tab Parametrized Uniform \tab xegaGaUPCross2Gene() \tab "UPCross2Gene" \tab ucrossSwap \cr #' (1 kid) \tab 1-Point \tab xegaGaCrossGene() \tab "CrossGene" \tab \cr #' \tab Uniform \tab xegaGaUCrossGene() \tab "UCrossGene" \tab \cr #' \tab Parametrized Uniform \tab xegaGaUPCrossGene() \tab "UPCrossGene" \tab ucrossSwap \cr #' \strong{Algorithm:} \tab \strong{"sgde"} \tab \strong{Package:} \tab \strong{xegaDfGene} \tab \cr #' (1 kid) \tab 1-Point \tab xegaDfCrossGene() \tab "CrossGene" \tab \cr #' \tab Uniform \tab xegaDfCrossGene() \tab "UCrossGene" \tab \cr #' \tab Parametrized Uniform \tab xegaDfUPCrossGene() \tab "UPCrossGene" \tab ucrossSwap \cr #' \strong{Algorithm:} \tab \strong{"sgperm"} \tab \strong{Package:} \tab \strong{xegaPermGene} \tab \cr #' (2 kids) \tab Position-Based \tab xegaPermCross2Gene() \tab "Cross2Gene" \tab \cr #' (1 kid) \tab Position-Based \tab xegaPermCrossGene() \tab "CrossGene" \tab \cr #' \strong{Algorithm:} \tab \strong{"sgp"} \tab \strong{Package:} \tab \strong{xegaGpGene} \tab \cr #' (2 kids) \tab of Derivation Trees \tab xegaGpAllCross2Gene() \tab "Cross2Gene" or \tab maxcrossdepth, \cr #' \tab \tab \tab "All2Cross2Gene" \tab maxdepth, \cr #' \tab \tab \tab \tab and maxtrials \cr #' \tab of Depth-Filtered \tab xegaGpFilterCross2Gene() \tab "FilterCross2Gene" \tab maxcrossdepth,\cr #' \tab Derivation Trees \tab \tab \tab mincrossdepth, \cr #' \tab \tab \tab \tab maxdepth, \cr #' \tab \tab \tab \tab and maxtrials \cr #' (1 kid) \tab of Derivation Trees \tab xegaGpAllCrossGene() \tab "CrossGene" \tab maxcrossdepth, \cr #' \tab \tab \tab \tab maxdepth, \cr #' \tab \tab \tab \tab and maxtrials \cr #' \tab of Depth-Filtered \tab xegaGpFilterCrossGene() \tab "FilterCrossGene" \tab maxcrossdepth, \cr #' \tab Derivation Trees \tab \tab \tab mincrossdepth, \cr #' \tab \tab \tab \tab maxdepth, \cr #' \tab \tab \tab \tab and maxtrials \cr #' } #' #' @section Mutation: #' #' The table below summarizes the available mutation operators of the current version. #' #' \tabular{llll}{ #' \strong{Algorithm:} \tab \strong{"sga"} and \strong{"sge"} \tab \strong{Package:} \tab \strong{xegaGaGene} \cr #' Name \tab Function \tab mutation= \tab Influenced by\cr #' Bit Mutation \tab xegaGaMutateGene() \tab "MutateGene" \tab bitmutrate \cr #' Individually \tab xegaGaIVAdaptiveMutateGene() \tab "IVM" \tab bitmutrate, \cr #' Variable Bit \tab \tab \tab bitmutrate2, \cr #' Mutation \tab \tab \tab and cutoffFit \cr #' \strong{Algorithm:} \tab \strong{"sgde"} \tab \strong{Package:} \tab \strong{xegaDfGene} \cr #' Differential \tab xegaDfMutateGeneDE() \tab "MutateGene" or \tab lF$ScaleFactor() \cr #' Evolution Mutation \tab \tab "MutateGeneDe" \tab (Configurable) \cr #' \strong{Algorithm:} \tab \strong{"sgperm"} \tab \strong{Package:} \tab \strong{xegaPermGene}\cr #' Generalized Order \tab xegaPermMutateGeneOrderBased() \tab "MutateGene" \tab bitmutrate \cr #' Based Mutation \tab \tab "MutateGeneOrderBased" \tab \cr #' k Inversion \tab xegaPermMutateGenekInversion() \tab "MutateGenekInversion" \tab lambda \cr #' Mutation \tab \tab \tab \cr #' 2-Opt Mutation \tab xegaPermMutateGene2Opt() \tab "MutateGene2Opt" \tab max2opt \cr #' k-Opt LK Mutation \tab xegaPermMutateGenekOptLK() \tab "MutateGenekOptLK" \tab max2opt \cr #' (Lin-Kernighan) \tab \tab \tab \cr #' Greedy Path \tab xegaPermMutateGeneGreedy() \tab "MutateGeneGreedy" \tab lambda \cr #' Mutation \tab \tab \tab \cr #' Best Greedy Path \tab xegaPermMutateGeneBestGreedy() \tab "MutateGeneBestGreedy" \tab lambda \cr #' Mutation \tab \tab \tab \cr #' Random Mutation \tab xegaPermMutateMix() \tab "MutateGeneMix" \tab \cr #' Operator \tab \tab \tab \cr #' \strong{Algorithm:} \tab \strong{"sgp"} \tab \strong{Package:} \tab \strong{xegaGpGene} \cr #' Derivation Tree \tab xegaGpMutateAllGene() \tab "MutateGene" or \tab maxmutdepth \cr #' Mutation \tab \tab "MutateAllGene" \tab \cr #' Filtered Derivation \tab xegaGpMutateGeneFilter() \tab "MutateFilterGene" \tab maxmutdepth, \cr #' Tree Mutation \tab \tab \tab minmutinsertiondepth, \cr #' \tab \tab \tab and maxmutinsertiondepth \cr #' } #' #' @section Acceptance: #' #' Acceptance rules are extensions of genetic and evolutionary algorithms #' which to the best of my knowledge have their origin in simulated annealing. #' An acceptance rule compares the fitness value of a modified gene with the #' fitness value of its parent and determines which of the two genes is passed #' into the next population. #' #' An acceptance rule is only executed as part of the genetic operator pipeline, if #' \code{replicate="Kid1"} or \code{replicate="DE"}. #' #' Two classes of acceptance rules are provided: #' \itemize{ #' \item Simple acceptance rules. #' \itemize{ #' \item Accept the new gene unconditionally (configured by \code{accept="All"}). #' The new gene is always passed to the next population. #' Choose the rule for configuring a classic genetic algorithm. #' (The default). #' \item Accept only best gene (configured by \code{accept="Best"}). #' This acceptance rule guarantees an increasing fitness curve over the run #' of the algorithm. For example, classic differential evolution uses this acceptance rule. #' } #' \item Configurable acceptance rules. #' The rules always accept a new gene with a fitness improvement. #' They also accept a new gene with a lower fitness with a probability which depends #' on the fitness difference of the old and the new gene #' and a temperature parameter which is reduced over the algorithm #' run by a configurable cooling schedule. #' \itemize{ #' \item The Metropolis acceptance rule (configured by \code{accept="Metropolis"}). #' The larger the parameter \code{beta} is set, the faster the drop in acceptance probability. #' \item The individually adaptive Metropolis acceptance rule (configured by \code{accept="IVMetropolis"}). #' The larger the parameter \code{beta} is set, the faster the drop in acceptance probability. #' Individually adaptive means that the temperature is corrected. The correction (increase) of temperature #' depends on the difference between the fitness of the currently known best solution and the #' and the fitness of the new gene. #' } #' } #' #' The cooling schedule updates the temperature parameter at the end of the main loop. #' The following cooling schedules are available: #' \itemize{ #' \item Exponential multiplicative cooling (configured by \code{cooling="ExponentialMultiplicative"}). #' Depends on the discount factor \code{alpha} #' and the start temperature \code{temp0}. #' \item Logarithmic multiplicative cooling (configured by \code{cooling="LogarithmicMultiplicative"}). #' Depends on the scaling factor \code{alpha} #' and the start temperature \code{temp0}. #' \item Power multiplicative cooling (configured by \code{cooling="PowerMultiplicative"}). #' Depends on the scaling factor \code{alpha}, #' the cooling power exponent \code{coolingPower}, #' and the start temperature \code{temp0}. #' \item Power additive cooling (configured by \code{cooling="PowerAdditive"}). #' Depends on the number of generations \code{generations}, #' the cooling power exponent \code{coolingPower}, #' the start temperature \code{temp0}, and the final temperature \code{tempN}. #' \item Exponential additive cooling (configured by \code{cooling="ExponentialAdditive"}). #' Depends on the number of generations \code{generations}, the #' start temperature \code{temp0}, and the final temperature \code{tempN}. #' \item Trigonometric additive cooling (configured by \code{cooling="TrigonometricAdditive"}). #' Depends on the number of generations \code{generations}, the #' start temperature \code{temp0}, and the final temperature \code{tempN}. #' } #' #' See package \code{xegaPopulation} <https://CRAN.R-project.org/package=xegaPopulation> #' #' @section Decoder: #' #' Decoders are algorithm and task dependent. Their implementation often makes use of a gene map. #' The table below summarizes the available decoders #' and gene maps of the current version. #' #' \tabular{lccc}{ #' Algorithm: \tab\strong{"sga"} \tab\strong{"sgde"} \tab\strong{"sgperm"} \cr #' In package: \tab xegaGaGene \tab xegaDfGene \tab xegaPermGene \cr #' Decoder: \tab xegaGaDecodeGene() \tab xegaDfDecodeGene() \tab xegaPermDecodeGene() \cr #' Gene map factories: \tab xegaGaGeneMapFactory() \tab xegaDfGeneMapFactory() \tab (Not configurable) \cr #' Method \tab "Bin2Dec" \tab "Identity" \tab \cr #' Method \tab "Gray2Dec" \tab \tab \cr #' Method \tab "Identity" \tab \tab \cr #' Method \tab "Permutation" \tab \tab \cr #' } #' #' \tabular{lcc}{ #' Algorithm: \tab \strong{"sgp"} \tab\strong{"sge"} \cr #' In package: \tab xegaGpGene \tab xegaGeGene \cr #' Decoder: \tab xegaGpDecodeGene() \tab xegaGeDecodeGene() \cr #' Gene map factories: \tab (Not configurable) \tab xegaGeGeneMapFactory() \cr #' Method \tab \tab "Mod" \cr #' Method \tab \tab "Buck" \cr #' } #' #' @section Evaluation: #' #' The method of evaluation of a gene is configured by #' \code{evalmethod}: "EvalGeneU" means that the function is always executed, # "EvalGeneR" allows repairs a gene by a decoder (e.g. in grammatical evolution), #' "Deterministic" evaluates a gene only once, and "Stochastic" incrementally updates mean and #' variance of a stochastic function. #' If \code{reportEvalErrors==TRUE}, evaluation failures are reported. However, for grammatical #' evolution without gene repair this should be set to \code{FALSE}. #' See package \code{xegaSelectGene} <https://CRAN.R-project.org/package=xegaSelectGene> #' #' @section Distributed and Parallel Processing: #' #' The current scope of parallelization is the parallel evaluation of genes (the steps marked with (eval) in the #' genetic operator pipeline. This strategy is less efficient for differential evolution and permutation-based genetic #' algorithms because of the embedding of repeated evaluations into genetic operators. #' #' In general, distributed and parallel processing requires a sequence of three steps: #' \enumerate{ #' \item Configure and start the distributed or parallel infrastructure. #' \item Distribute processing and collect results. #' In a evolutionary or genetic algorithm the architectural pattern used for implementation #' coarse-grained parallelism by parallel evaluation of the fitness of the genes of a population #' is the master/worker pattern. In principle, the \code{lapply()}-function for evaluating a population #' of genes is replaced by a parallel version. #' \item Stop the distributed or parallel infrastructure. #' } #' #' For evolutionary and genetic algorithm, the second step is controlled by two parameters, #' namely \code{executionModel} and \code{uParApply}: #' \enumerate{ #' \item If \code{uParApply=NULL}, then \code{executionModel} provides four ways of evaluating the #' fitness of a population of genes: #' \enumerate{ #' \item \code{executionModel="Sequential"}: The apply function used is \code{base::lapply()}. (Default). #' \item \code{executionModel="MultiCore"}: The apply function used is \code{parallel::mclapply()}. #' If the number of cores is not specied by \code{cores}, the number of available cores #' is determined by \code{parallelly::availableCores()}. #' \item \code{executionModel="FutureApply"}: The apply function used is \code{future.apply::future_lapply()}. #' The parallel/distributed model depends on a proper \code{future::plan()} statement. #' \item \code{executionModel="Cluster"}: The apply function used is \code{parallel::parLapply()}. #' The information about the configuration of the computing cluster (master, port, list of workers) #' must be provided by \code{Cluster=cl} where #' \code{cl<-parallel::makeClusterPSOCK( rep(localhost, 5))} #' generates the cluster object and starts the R processes (of 5 workers in the same machine). #' } #' \item Assume that a user-defined parallel apply function has been defined and called \code{UPARAPPLY}. #' By setting \code{uParApply=UPARAPPLY}, the \code{lapply()} function used is \code{UPARAPPLY()}. #' This overrides the specification by \code{executionModel}. For example, #' parallelization via the MPI interface can be achieved by providing a user-defined parallel #' \code{lapply()} function which is implemented by a user-defined function whose function body #' is the line \code{Rmpi::mpi.parLapply( pop, FUN=EvalGene, lF=lF)}. #' } #' #' See package \code{xegaPopulation} <https://CRAN.R-project.org/package=xegaPopulation> #' #' \strong{Acknowledgment.}The author acknowledges support by the state of Baden-Württemberg through bwHPC. #' #' @section Reporting: #' #' \itemize{ #' \item \code{verbose} controls the information reported on the screen. #' If \code{verbose} is \code{1}, then one dot is printed per generation to the console. #' \item \code{reportEvalErrors=TRUE} reports the output of errors of fitness function evaluations #' to the console. Grammatical evolution (algorithm "sge") routinely attempts to evaluate #' incomplete derivation trees. This leads to an evaluation error of the fitness function. #' \item \code{profile=TRUE} measures the time spent in executing the main blocks of the algorithm: #' \code{InitPopulation()}, \code{NextPopulation()}, \code{EvalPopulation()}, #' \code{ObservePopulation()}, and \code{SummaryPopulation()}. The measurements are stored in the #' named list \code{$timer} of the result object of the algorithm. #' \item \code{allSolutions=TRUE} collects all solutions with the same fitness value. #' The lists of the genotypes and phenotypes of these solutions are stored #' in \code{$solution$allgenotypes} and \code{$allphenotypes} of the result object of the algorithm. #' \item \code{batch=TRUE} writes the result object and \code{logevals=TRUE} writes a list of all evaluated genes #' to a \code{rds}-file in the current directory. \code{path} allows to write the \code{rds}-files #' into another directory. The existence of the directory specified by \code{path} is not checked. #' \code{batch=TRUE} combined with \code{verbose=TRUE} should be used in batch environments on #' HPC environments. #' } #' ### Problem Specification #' #' @param penv Problem environment. #' #' @param grammar A compiled grammar object. Default: NULL. #' Example: \code{compileBNF(booleanGrammar())} #' #' @param max If \code{TRUE} then Maximize! Default: TRUE. #' Used in functions \code{EvalGeneDet}, \code{EvalGeneStoch}, #' \code{EvalGeneU}, and \code{EvalGeneR} #' of package \code{xegaSelectGene}. #' ### Algorithm #' #' @param algorithm Specifies the algorithm class dependend #' on gene representation: #' \itemize{ #' \item "sga": Binary representation (Default). #' \item "sgde": Real representation. #' E.g. Differential evolution. #' \item "sgperm": Permutation representation. #' \item "sge": Binary representation. #' Grammatical evolution. #' (Not yet variable length.) #' \item "sgp": Derivation tree representation. #' Grammar Based Genetic Programming. #' } #' ### Basic Parameters #' #' @param popsize Population size. Default: 100. #' @param generations Number of generations. Default: 20. #' @param crossrate Probability of applying crossover operator. Default: 0.20. #' (Global parameter) #' @param mutrate Probability of applying mutation operator. Default: 1.0. #' (Global parameter) #' #' @param elitist Boolean. If \code{TRUE}, #' then keep best solution in population. #' Default: \code{TRUE}. #' @param replay Integer. If \code{replay>0} then use \code{replay} #' as seed of random number generator and #' store it for exact repetition of run. #' Default: 0. ### #' @param maxdepth The maximal depth of a derivation tree. Default: 7. (\code{"sgp"}). #' @param maxtrials Maximal number of trials of finding subtrees with same root symbol. #' Default: 5. (\code{sgp}). #' #' @param codons The maximal number of codons of derivations on a gene. #' Default: 25. (\code{"sge"}). #' @param codonBits The number of bits of a codon. #' Default: 0. (\code{"sge"}). #' @param codonPrecision Specify the method to set the number of bits of a #' codon (\code{"sge"}): #' \itemize{ #' \item "Min": Sufficient to code the maximal number #' of choices of production rules for #' a non-terminal. #' \item "LCM": Contains the least common multiple #' of the prime factors of the number of #' choices of production rules for all #' non-terminals. #' \item "MaxPBias": The computed precision guarantees #' that the choice rule bias for a non-terminal #' is below \code{maxPBias}. #' } #' Argument of function factory #' \code{xegaGePrecisionFactory} in package \code{xegaGeGene}. #' @param maxPBias The threshold of the choice rule bias. #' Default: \code{0.01}. (\code{sge}"). #' #' @param evalmethod Specifies the method of function evaluation: #' \itemize{ #' \item "EvalGeneU": The function is always evaluated. (Default) #' \item "EvalGeneR": The function is always evaluated. #' Repairs of the gene by the decoder are #' possible. #' \item "Deterministic": The function is evaluated only once. #' \item "Stochastic": The expected function value and its #' variance are incrementally updated. #' } #' Argument of function factory #' \code{EvalGeneFactory} in package xegaSelectGene. #' #' @param reportEvalErrors Report errors in the evaluation #' of fitness functions. Default: TRUE. #' #' @param genemap Gene map for decoding. Default: "Bin2Dec". #' The default value works only for algorithm "sga". #' Used as \code{method} argument of the function factory #' \code{sgXGeneMapFactory} of package \code{xega}. #' #' Available available options determined by #' \code{algorithm}: #' \itemize{ #' \item "sga": Binary representation (Default). #' \itemize{ #' \item "Bin2Dec": For real parameter vectors. #' \item "Gray2Dec": For real parameter vectors. #' \item "Identity": For 0/1 parameter vectors. #' \item "Permutation": For permutations. #' } #' See the function factory #' \code{xegaGaGeneMapFactory} in package \code{xegaGaGene}. #' \item "sgp": Derivation tree. #' Gene map is not used, but must be specified. #' We use \code{xegaGaGene::xegaGaGeneMapFactory} #' with \code{method="Identity"}. #' \item "sge": Binary representation (Default). #' How are genes decoded? #' \itemize{ #' \item "Mod": The modulo rule. #' \item "Bucket": The bucket rule (with the mLCM). #' Problem: Mapping \code{1: 2^k} to \code{1:mLCMG}. #' } #' See the function factory #' \code{xegaGeGeneMapFactory} in package \code{xegaGeGene}. #' \item "sgde": Real coded gene. #' We use \code{xegaDfGene::xegaDfGeneMapFactory} #' with \code{method="Identity"}. #' Function used: \code{xegaDfGene::xegaDfGeneMapIdentity} #' \item "sgperm": Permutation gene. #' Gene map is not used, but must be specified. #' We use \code{xegaDfGene::xegaDfGeneMapFactory} #' with \code{method="Identity"}. #' Function used: \code{xegaDfGene::xegaDfGeneMapIdentity} #' #' } # end of genemap #' #' @param crossrate2 Crossover rate for genes with below #' ``average'' fitness. #' Probability of applying crossover operator #' for genes with a ``below average'' fitness. #' Default: 0.30. #' (Global parameter) #' #' @param ivcrossrate Specifies the method of determining the crossover rate. #' \itemize{ #' \item #' "Const" Constant crossover rate. #' The probability of applying the crossover operator #' is constant for the whole run of the algorithm. #' Default: "Const". #' \item "IV" Individually variable crossover rate. #' The crossrate of a gene is determined by the following threshold #' rule: #' If the fitness of the gene is higher than #' \code{lF$CutoffFit()*} \code{lF$CBestFitness()} then #' \code{lF$CrossRate1()} else \code{lF$CrossRate2()} #' is used. #' } #' Argument of function factory #' \code{CrossRateFactory} in package \code{xegaPopulation}. #' #' @param uCrossSwap The fraction of positions swapped in the #' parametrized uniform crossover operator. #' A local crossover parameter. #' Default: 0.2. (\code{"sga"} and \code{"sgde"}). #' Used in packages \code{xegaGaGene} and \code{xegaDfGene} #' for functions #' \code{xegaGaUPCross2Gene}, #' \code{xegaDfUPCross2Gene}, #' \code{xegaGaUPCrossGene}, and #' \code{xegaDfUPCrossGene}. #' #' @param mincrossdepth minimal depth of exchange nodes (roots of subtrees #' swapped by crossover). (\code{"sgp"}). #' @param maxcrossdepth Maximal depth of exchange nodes (roots of subtrees #' swapped by crossover). (\code{"sgp"}). #' Used in package \code{xegaGpGene} functions #' \code{xegaGpCrossGene} and \code{xegaGpCross2Gene} #' in package xegaGpGene. #' #' @param crossover Crossover method. Default: "CrossGene". #' The choice of crossover methods depends on the #' setting of the argument \code{algorithm}. #' Used as the \code{method} argument in function factory #' \code{sgXCrossoverFactory} of package \code{xega}. #' #' \itemize{ #' \item \code{algorithm="sga"}: #' \code{crossover} is argument of function factory #' \code{xegaGaCrossoverFactory} in package \code{xegaGaGene}. #' \itemize{ #' \item Crossover operators with 1 kid: #' \itemize{ #' \item "CrossGene" one-point crossover. #' \item "UCrossGene" uniform crossover. #' \item "UPCrossgene" parameterized uniform crossover. #' Local parameter: \code{uCrossSwap}. #' } #' \item Crossover operators with 2 kids: #' \itemize{ #' \item "Cross2Gene" one-point crossover. #' \item "UCross2Gene" uniform crossover. #' \item "UPCross2gene" parameterized uniform crossover. #' Local parameter: \code{uCrossSwap}. #' } #' } #' \item \code{algorithm="sgp"}: #' \code{crossover} is argument of function factory #' \code{xegaGpCrossoverFactory} in package \code{xegaGpGene}. #' \itemize{ #' \item Crossover operators with 1 kid: #' \itemize{ #' \item "CrossGene" position based one-point crossover. #' } #' \item Crossover operators with 2 kids: #' \itemize{ #' \item "Cross2Gene" position based one-point crossover. #' } #' } #' \item \code{algorithm="sge"}: #' We use the factory \code{xegaGaCrossoverFactory}. #' #' (Adpatation needed for variable-length binary #' representation.) #' #' \item \code{algorithm="sgde"}: #' \code{crossover} is argument of function factory #' \code{xegaDfCrossoverFactory} in package \code{xegaDfGene}. #' \itemize{ #' \item Crossover operators with 1 kid: #' \itemize{ #' \item "CrossGene" one-point crossover (of reals) #' \item "UCrossGene" uniform crossover (of reals) #' \item "UPCrossGene" parametrized #' uniform crossover (of reals). #' Local parameter: \code{uCrossSwap}. #' } #' \item Crossover operators with 2 kids: Not implemented. #' } #' #' \item \code{algorithm="sgperm"}: #' \code{crossover} is argument of function factory #' \code{xegaPermCrossoverFactory} in package \code{xegaPermGene}. #' \itemize{ #' \item Crossover operators with 1 kid: #' \itemize{ #' \item "CrossGene" position based one-point crossover. #' } #' \item Crossover operators with 2 kids: #' \itemize{ #' \item "Cross2Gene" position based one-point crossover. #' } #' } #' } #' #' @param mutrate2 Mutation rate. Default: 1.0. #' (Global parameter). #' #' @param ivmutrate "Const" or "IV" (individually variable). #' Default: "Const". #' #' @param bitmutrate Bit mutation rate. Default: 0.005. #' A local mutation parameter. (\code{"sga"} and \code{"sge"}). #' Used in package \code{xegaGaGene} functions #' \code{MutateGene} #' \code{IVAdaptiveMutateGene} #' #' @param bitmutrate2 Bit mutation rate for genes #' with ``below average'' fitness. Default: 0.01. #' A local mutation parameter. (\code{"sga"} and \code{"sge"}). #' Used in package \code{xegaGaGene} functions #' \code{IVAdaptiveMutateGene} #' #' @param maxmutdepth Maximal depth of a derivation tree inserted #' by mutation. Default: 3. (\code{"sgp"}). #' @param minmutinsertiondepth Minimal depth at which an insertion tree #' is inserted. Default: 1. (\code{"sgp"}). #' @param maxmutinsertiondepth Maximal depth at which an insertion tree #' is inserted. Default: 7. (\code{"sgp"}). #' Used in package \code{xegaGpGene} function #' \code{xegaGpMutateGene}. #' #' @param lambda Decay rate. Default: 0.05. #' A local mutation parameter. (\code{"sgperm"}). #' Used in package \code{xegaPermGene} function #' \code{xegaPermMutateGenekInversion}. #' #' @param max2opt Maximal number of trials to find #' an improvement by a random edge exchange #' in a permutation. Default: \code{100}. (\code{"sgperm"}). #' Used in package \code{xegaPermGene} function #' \code{xegaPermMutateGene2Opt}. #' and \code{xegaPermMutateGeneOptLK}. #' #' @param scalefactor1 Scale factor for differential mutation operator (Default: 0.9). (\code{"sgde"}). #' @param scalefactor2 Scale factor for differential mutation operator (Default: 0.2). (\code{"sgde"}). #' @param scalefactor Method for setting scale factor (\code{"sgde"}): #' \itemize{ #' \item "Const": constant scale factor. #' \item "Uniform": a random scale factor in 0.000001 to 1.0. #' } #' @param cutoffFit Cutoff for fitness. Default: 0.5. (\code{"sga"} and \code{"sge"}). #' Used in package \code{xegaGaGene} function #' \code{IVAdaptiveMutateGene}. #' #' @param mutation Label specifies mutation method #' dependend on \code{algorithm}. Default: "MutateGene". #' The (global) probability of calling a mutation method #' is specified by \code{mutrate} and \code{mutrate2}. #' Used as \code{method} argument of function factory #' \code{sgXMutationFactory} package \code{xega}. #' #' \itemize{ #' \item \code{algorithm="sga"}: #' \code{mutation} is argument of function factory #' \code{xegaGaMutationFactory} in package \code{xegaGaGene}. #' \itemize{ #' \item "MutateGene": Bitwise mutation. #' Local parameter: \code{bitmutrate}. #' Function used: \code{xegaGaGene::xegaGaMutateGene}. #' \item "IVM": Invividually variable mutation. #' Intuitively we know that #' bad genes need higher mutation rates. #' Good genes have a fitness which is #' above a threshold fitness. The threshold #' is determined as a percentage of the #' current best fitness in the population. #' The percentage is set by the parameter #' \code{cutoffFit}. #' Local parameters: \code{bitmutrate} for good genes. #' \code{bitmutrate2} for bad genes. #' \code{bitmutrate2} should be higher then #' \code{bitmutrate}. #' } #' \item \code{algorithm="sgp"}: #' \code{mutation} is argument of function factory #' \code{xegaGpMutationFactory} in package \code{xegaGpGene}. #' #' \itemize{ #' \item "MutateGene": Random insertion of #' a random derivation tree. #' Local parameter: \code{maxmutdepth}. #' Function used: \code{xegaGpGene::xegaGpMutateGene}. #' } #' #' \item \code{algorithm="sge"}: #' \code{mutation} is argument of function factory #' \code{xegaGaMutationFactory}. #' Nothing specific to grammatical evolution implemented. #' #' \item \code{algorithm="sgde"}: #' \code{mutation} is argument of function factory #' \code{xegaDfMutationFactory} in package \code{xegaDfGene}. #' #' \itemize{ #' \item "MutateGene": Add the scaled difference #' of the parameters of two randomly selected #' to a gene. #' Local parameters: Choice of function for #' \code{scalefactor} as well as #' \code{scalefactor1} #' and \code{scalefactor2}. #' Function used: \code{xegaDfGene::xegaDfMutateGeneDE}. #' } #' #' \item \code{algorithm="sgperm"}: #' \code{mutation} is argument of function factory #' \code{xegaPermMutationFactory} in package \code{xegaPermGene}. #' #' \itemize{ #' \item "MutateGene": #' Function used: \code{xegaPermGene::xegaPermMutateGeneOrderBased}. #' \item "MutateGeneOrderBased": See "MutateGene". #' \item "MutateGenekInversion": #' Function used: \code{xegaPermGene::xegaPermMutateGenekInversion}. #' \item "MutateGene2Opt": #' Function used: \code{xegaPermGene::xegaPermMutateGene2Opt}. #' \item "MutateGenekOptLK": #' Function used: \code{xegaPermGene::xegaPermMutateGenekOptLK}. #' \item "MutateGeneGreedy": #' Function used: \code{xegaPermGene::xegaPermMutateGeneGreedy}. #' \item "MutateGeneBestGreedy": #' Function used: \code{xegaPermGene::xegaPermMutateGeneBestGreedy}. #' \item "MutateGeneMix": #' Function used: \code{xegaPermGene::xegaPermMutateMix}. #' } #' } #' #' @param replication "Kid1" or "Kid2". Default: "Kid1". #' For algorithms "sga", "sgPerm", "sgp", and "sge": #' "Kid1" means a crossover operator with one kid, #' "Kid2" means a crossover operator with two kids. #' #' For algorithm "sgde", \code{replication} must be #' set to "DE". #' #' Used as the \code{method} argument of the #' function factory \code{sgXReplicationFactory} #' of package \code{xega}. #' #' @param offset Offset used in proportional selection. Default: 1. #' Used in the following functions of package \code{xegaSelectGene}: #' \code{ScaleFitness}, #' \code{PropFitOnLn}, #' \code{PropFit}, #' \code{PropFitM}, #' \code{PropFitDiffOnLn}, #' \code{PropFitDiff}, #' \code{SUS}. #' ## \code{\link[xegaSelectGene:ScaleFitness]{ScaleFitness}}, ## \code{\link[xegaSelectGene:PropFitOnLn]{PropFitOnLn}}, ## \code{\link[xegaSelectGene:PropFit]{PropFit}}, ## \code{\link[xegaSelectGene:PropFitM]{PropFitM}}, ## \code{\link[xegaSelectGene:PropFitDiffOnLn]{PropFitDiffOnLn}}, ## \code{\link[xegaSelectGene:PropFitDiff]{PropFitDiff}}, ## \code{\link[xegaSelectGene:SUS]{SUS}}. #' #' @param eps Epsilon in proportional #' fitness difference selection. Default: 0.01. #' Used in package \code{xegaSelectGene} function #' \code{PropFitDiffM}. #' ## \code{\link[xegaSelectGene:PropFitDiffM]{PropFitDiffM}}. #' #' @param scaling Scaling method. Default: "NoScaling". #' Available scaling methods: #' \itemize{ #' \item "NoScaling", #' \item "ConstantScaling" (Static), #' \item "ThresholdScaling" (Dynamic), #' \item "ContinuousScaling" (Dynamic). #' } #' Argument of function factory #' \code{ScalingFactory} in package \code{xegaSelectGene}. #' #' @param scalingExp Scaling exponent \code{k} in \code{fit^k}. #' With "ConstantScaling": 0 =< k. #' With "ThresholdScaling": 1 < k. (Default: 1) #' Used in package \code{xegaSelectGene}, functions #' \code{ScalingFitness}, #' \code{ThresholdScaleFitness}. #' ## \code{\link[xegaSelectGene:ScalingFitness]{ScalingFitness}}, ## \code{\link[xegaSelectGene:ThresholdScaleFitness]{ThresholdScaleFitness}}. #' #' @param scalingExp2 Scaling exponent #' for "ThresholdScaling": 0 <= k <1. (Default:1) #' Used in package \code{xegaSelectGene} function #' \code{ThresholdScaleFitness}. #' ## \code{\link[xegaSelectGene:ThresholdScaleFitness]{ThresholdScaleFitness}}. #' #' @param scalingThreshold Numerical constant. Default: 0.0. #' If ratio of dispersion measures is in #' [(1-scalingThreshold), 1+scalingThreshold)], #' fitness is not scaled. #' Used in package \code{xegaSelectGene} function #' \code{ThresholdScaleFitness}. #' ## \code{\link[xegaSelectGene:ThresholdScaleFitness]{ThresholdScaleFitness}}. #' #' @param rdmWeight Numerical constant. Default: 1.0. Weight of #' ratio of dispersion measures in continuous scaling. #' Used in package \code{xegaSelectGene} function #' \code{ContinuousScaleFitness}. #' ## \code{\link[xegaSelectGene:ContinuousScaleFitness]{ContinuousScaleFitness}}. #' #' @param drMin Minimal allowable dispersion ratio. Default: 0.5. #' Used in package \code{xegaSelectGene} function #' \code{DispersionRatio}. ## \code{\link[xegaSelectGene:DispersionRatio]{DispersionRatio}}. #' #' @param drMax Maximal allowable dispersion ratio. Default: 2.0. #' Used in package \code{xegaSelectGene} function #' \code{DispersionRatio}. ## \code{\link[xegaSelectGene:DispersionRatio]{DispersionRatio}}. #' #' @param dispersionMeasure Dispersion measure used for computation of the #' ratio of dispersion measures for dynamic scaling methods. #' Default: "var". #' Available dispersion measures: #' "var, "std", "mad", "cv", "range", "iqr". #' Argument of function factory #' \code{DispersionMeasureFactory} in package \code{xegaSelectGene}. #' #' @param scalingDelay The ratio of dispersion measures compares the current #' population dispersion at t with the population dispersion #' at t-scalingdelay. Default: 1. #' Used in package \code{xegaSelectGene} function #' \code{DispersionRatio}. ## \code{\link[xegaSelectGene:DispersionRatio]{DispersionRatio}}. #' #' @param tournamentSize Tournament size. Default: 2. #' Used in package \code{xegaSelectGene} functions #' \code{SelectTournament}, #' \code{SelectSTournament}. ## \code{\link[xegaSelectGene:SelectTournament]{SelectTournament}}, ## \code{\link[xegaSelectGene:SelectSTournament]{SelectSTournament}}. #' #' @param selectionBias (> 1.0). Controls selection pressure for #' Whitley's linear rank selection #' with selective pressure. Default: 1.5. Near 1.0: almost #' uniform selection. #' Used in package \code{xegaSelectGene} function #' \code{SelectLRSelective}, #' #' @param maxTSR Controls selection pressure for #' Grefenstette and Baker's linear rank selection #' method. Should be higher than 1.0 and lower equal 2.0. #' Default: 1.5. #' Used in package \code{xegaSelectGene} function #' \code{SelectLinearRankTSR}. ## \code{\link[xegaSelectGene:SelectLinearRankTSR]{SelectLinearRankTSR}}, #' #' @param selection Selection method for first parent of crossover. #' Default: "SUS". #' @param mateselection Selection method for second parent of crossover. #' Default: "SUS". #' #' Available selection methods for selection method of a parent: #' \itemize{ #' \item Uniform random selection: "Uniform". #' \item Uniform random selection without replacement: "UniformP". #' \item Proportional to fitness: #' "ProportionalOnln" (fastest), "Proportional", "ProportionalM", #' \item Proportional to fitness differences: #' "PropFitDiffOnln" (fastest), "PropfitDiff", "PropfitDiffM", #' \item Stochastic universal sampling: "SUS", #' \item Tournament selection: "Duel" (fastest), "Tournament", "STournament", #' \item Rank selection: "LRSelective" (fastest), "LRTSR". #' } #' Argument of function factory #' \code{SelectGeneFactory} in package \code{xegaSelectGene}. #' #' @param selectionContinuation Boolean. If \code{TRUE}, #' precomputes selection indices for next generation once and #' transforms selection function to index lookup continuation. #' Default: \code{TRUE}. #' Used in package \code{xegaPopulation} function \code{xegaNextPopulation}. #' #' @param accept Acceptance rule for new gene. Default: "All". #' \itemize{ #' \item "All" function \code{AcceptNewGene} #' \item "Best" function \code{AcceptBest} #' \item "Metropolis" function \code{AcceptMetropolis}. #' The behavior of this acceptance rule depends on: #' \enumerate{ #' \item The distance between the fitness values. #' The larger the distance the larger the drop #' in acceptance probability. #' \item \code{alpha} is \code{1} minus the discount rate of the cooling #' schedule. \code{alpha} is in \code{[0, 1]}. #' The smaller \code{alpha} the faster the drop #' in temperatur and thus acceptance probability. #' \item \code{beta} a constant. The larger \code{beta} #' the faster the drop in acceptance probability. #' \item \code{temperature} the starting value of the #' temperature. Must be higher than the number of #' generations. #' } #' \item "IVMetropolis" function \code{AcceptIVMetropolis}. #' The behavior of this acceptance rule is qualitatively the same as that #' of the Metropolis acceptance rule above. #' The acceptance rule is adaptive by a correction of the temperature #' in proportion to the difference between the fitness of the current best and #' the fitness of the gene considered. #' } #' Argument of function factory #' \code{AcceptFactory} in package \code{xegaPopulation}. #' #' @param alpha \code{1} minus the discount rate for temperature. (Default: 0.99). #' (Used in cooling schedule at the end of main GA-loop.) #' #' @param beta Constant in Metropolis acceptance rule. (Default: 2.0). #' (Used in Metroplis acceptance rule.) #' #' @param temp0 Starting value of temperature (Default: 40). #' (Used in Metroplis acceptance rule. Updated in cooling schedule.) #' #' @param tempN Final value of temperature (Default: 0.01). #' (Used in Metroplis acceptance rule. Updated in cooling schedule.) #' #' @param cooling Cooling schedule for temperature. (Default: "ExponentialMultiplicative") #' \itemize{ #' \item "ExponentialMultiplicative" calls \code{ExponentialMultiplicativeCooling} #' \item "LogarithmicMultiplicative" calls \code{LogarithmicMultiplicativeCooling} #' \item "PowerMultiplicative" calls \code{PowerMultiplicativeCooling} #' \item "PowerAdditive" calls \code{PowerAdditiveCooling} #' \item "ExponentialAdditive" calls \code{ExponentialAdditiveCooling} #' \item "TrigonometricAdditive" calls \code{TrigonometricAdditiveCooling} #' } #' Argument of function factory #' \code{CoolingFactory} in package \code{xegaPopulation}. #' #' @param coolingPower Exponent for PowerMultiplicative cooling schedule. #' (Default: 1. This is called linear multiplicative cooling.) #' #' @param verbose #' The value of \code{verbose} (Default: 1) controls the #' information displayed: #' \enumerate{ #' \item \code{== 0}: Nothing is displayed. #' #' \item \code{== 1}: 1 point per generation. #' #' \item \code{> 1}: Max(fit), number of solutions, indices. #' #' \item \code{> 2}: and population fitness statistics. #' #' \item \code{> 3}: and fitness, value of phenotype, #' and phenotype. #' \item \code{> 4}: and str(genotype). #' } #' #' #' @param logevals Boolean. #' If \code{TRUE} then log all evaluations and their parameters #' in the file #' \code{xegaEvalLog<time stamp>.rds}. Default: FALSE. #' #' \code{log<-readRDS(xegaEvalLog<time stamp>.rds)} reads the log. #' The format of a row of \code{log} is <fitness> <parameters>. #' #' @param allsolutions Boolean. If \code{TRUE}, then return all best solutions. #' Default: \code{FALSE}. #' #' @param early Boolean. If FALSE (Default), ignore code for #' early termination. #' See \link{Parabola2DEarly}. #' @param terminationEps Fraction of known optimal solution #' for computing termination interval. Default: 0.01 #' See \link{Parabola2DEarly}. #' #' @param cores Number of cores used for multi core parallel execution. #' (Default: NA. NA means that the number of cores #' is set by \code{parallelly:availableCores()} #' if the execution model is "MultiCore". #' #' @param executionModel Execution model of fitness function evaluation. #' Available: #' \itemize{ #' \item "Sequential": \code{base::lapply} is used. #' \item "MultiCore": \code{parallel::mclapply} is used. #' \item "FutureApply": #' \code{future.apply::future_lapply} is used. #' \item "Cluster": Requires a proper configuration of the cluster. #' } #' Default: "Sequential". #' #' @param uParApply A user defined parallel apply function #' (e.g. for Rmpi). If specified, overrides #' settings for \code{executionModel}. #' Default: \code{NULL}. #' #' @param Cluster A cluster object generated by #' \code{parallel::makeCluster()} or #' \code{parallelly::makeCluster()}. #' Default: \code{NULL}. #' #' @param profile Boolean. #' If \code{TRUE} measures execution time and counts number of executions #' to main components of genetic algorithms. Default: \code{FALSE}. #' #' @param batch Boolean. #' If \code{TRUE} then save result in file #' \code{xegaResult<time stamp>.rds}. Default: FALSE #' #' @param path #' Path. Default: \code{""}. #' #' @return Result object. A named list of #' \enumerate{ #' \item #' \code{$popStat}: A matrix with mean, min, Q1, median, Q3, max, #' variance, and median absolute deviation #' of population fitness as columns: #' i-th row for the measures of the i-th generation. #' \item #' \code{$fit}: Fitness vector if \code{generations<=1} else: NULL. #' \item #' \code{$solution}: Named list with fields #' \itemize{ #' \item #' \code{$solution$name}: Name of problem environment. #' \item #' \code{$solution$fitness}: Fitness value of the best solution. #' \item #' \code{$solution$value}: The evaluated best gene. #' \item #' \code{$solution$numberofsolutions}: #' Number of solutions with the same fitness. #' \item #' \code{$solution$genotype}: The gene a genetic code. #' \item #' \code{$solution$phenotype}: The decoded gene. #' \item #' \code{$solution$phenotypeValue}: The value of the #' function of the parameters of the solution. #' \item #' \code{$solution$evalFail}: Number of failures or fitness evaluations #' \item #' and, if configured, #' \code{$solution$allgenotypes}, as well as #' \code{$solution$allphenotypes}. #' } #' \item #' \code{$GAconfig}: For rerun with \code{xegaReRun()}. #' \item #' \code{$GAenv}: Attribute value list of GAconfig. #' \item \code{$timer}: An attribute value list with #' the time used (in seconds) in the main blocks of the GA: #' tUsed, tInit, tNext, tEval, tObserve, and tSummary. #' } #' #' @family Main Program #' #' @examples #' a<-xegaRun(penv=Parabola2D, generations=10, popsize=20, verbose=0) #' b<-xegaRun(penv=Parabola2D, algorithm="sga", generations=10, max=FALSE, #' verbose=1, replay=5, profile=TRUE) #' c<-xegaRun(penv=Parabola2D, max=FALSE, algorithm="sgde", #' popsize=20, generations=50, #' mutation="MutateGeneDE", scalefactor="Uniform", crossover="UCrossGene", #' genemap="Identity", replication="DE", #' selection="UniformP", mateselection="UniformP", accept="Best") #' envXOR<-NewEnvXOR() #' BG<-compileBNF(booleanGrammar()) #' d<-xegaRun(penv=envXOR, grammar=BG, algorithm="sgp", #' generations=5, popsize=20, verbose=0) #' e<-xegaRun(penv=envXOR, grammar=BG, algorithm="sge", genemap="Mod", #' generations=5, popsize=20, reportEvalErrors=FALSE, verbose=1) #' f<-xegaRun(penv=lau15, max=FALSE, algorithm="sgperm", #' genemap="Identity", mutation="MutateGeneMix") #' #' @importFrom parallelly availableCores #' @importFrom parallelly supportsMulticore #' @importFrom xegaSelectGene newCounter #' @importFrom xegaSelectGene newTimer #' @importFrom xegaSelectGene Timed #' @importFrom xegaSelectGene EvalGeneFactory #' @importFrom xegaSelectGene SelectGeneFactory #' @importFrom xegaSelectGene ScalingFactory #' @importFrom xegaSelectGene DispersionMeasureFactory #' @importFrom xegaSelectGene DispersionRatio #' @importFrom xegaSelectGene parm #### TODO #' @importFrom xegaGeGene xegaGePrecisionFactory #' @importFrom xegaDfGene xegaDfScaleFactorFactory #' @importFrom xegaPopulation xegaInitPopulation #' @importFrom xegaPopulation xegaEvalPopulation #' @importFrom xegaPopulation xegaObservePopulation #' @importFrom xegaPopulation xegaSummaryPopulation #' @importFrom xegaPopulation xegaNextPopulation #' @importFrom xegaPopulation xegaBestInPopulation #' @importFrom xegaPopulation xegaConfiguration #' @importFrom xegaPopulation ApplyFactory #' @importFrom xegaPopulation CrossRateFactory #' @importFrom xegaPopulation AcceptFactory #' @importFrom xegaPopulation CoolingFactory #' @importFrom xegaPopulation xegaLogEvalsPopulation ##### TODO #' @importFrom xegaPopulation MutationRateFactory ##### TODO #' @export xegaRun<-function( ### Problem Specification penv, # Problem environment. grammar=NULL, # a grammar object. max=TRUE, # TRUE: max penv$f; FALSE: min penv$f ### Algorithm algorithm="sga", # "sga", "sgde", "sgperm", "sge", "sgp" ### Basic Parameters popsize=100, # Population size generations=20, # Number of generations crossrate=0.2, # (Probability crossover operator is used) mutrate=1.0, # (Probability mutation operator is used.) elitist=TRUE, # TRUE: Best gene always survives. replay=0, # replay=0: current seed of random number generator. # replay>0: use small integer. # Same integer = same seed. ### maxdepth=7, # maximal depth of a derivation tree maxtrials=5, # maximal of number of trials of # finding subtrees with common root codons=25, # number of codons (GE) codonBits=0, # precision of codon in bits codonPrecision="LCM", # Precision methods: # "Min", # "LCM", # "MaxPBias". maxPBias=0.01, evalmethod="EvalGeneU", # # Evaluation methods: # "EvalGeneU", # "EvalGeneR", # "EvalGeneDet", # "EvalGeneStoch". reportEvalErrors=TRUE, # Report errors in fitness functions. # genemap="Bin2Dec", # Gene map for decoding. # crossrate2=0.3, # Crossover Rate 2 # (Probability crossover operator is used) ivcrossrate="Const", # "Const" or "IV" crossover="Cross2Gene", # Crossover operator: # 1 Kid: "CrossGene", UCrossGene, UPCrossGene # 2 Kids: "Cross2Gene", UCross2Gene, UPCross2Gene uCrossSwap=0.2, # fraction of positions swapped in. # mincrossdepth=1, # maximal depth of exchange nodes maxcrossdepth=7, # maximal depth of exchange nodes # for swapping derivation trees # crossover ivmutrate="Const", # "Const" or "IV" mutrate2=1.0, # Mutation Rate 2 # (Probability mutation operator is used.) bitmutrate=0.005, # bit Mutation Rate bitmutrate2=0.01, # bit Mutation Rate 2 maxmutdepth=3, # maximal depth of a derivation tree # generated by mutation minmutinsertiondepth=1, # minimal depth of insertion node maxmutinsertiondepth=7, # maximal depth of insertion node lambda=0.05, # decay rate max2opt=100, # maximal number of trials xegaPermGene. scalefactor1=0.9, # scale factor (differential evolution) scalefactor2=0.3, # scale factor (differential evolution) scalefactor="Const", # scale factor method label # cutoffFit=0.5, # Cutoff percentage for good genes. # mutation="MutateGene", # Mutation operator: # "MutateGene" or "IVM" # replication="Kid2", # Replication method. # offset=1, # offset in proportional selection eps=0.01, # Small number in proportional selection. tournamentSize=2, # size of tournament selectionBias=1.5, # selection pressure for Whitleys # selective rank selection maxTSR=1.5, # selection pressure for Grefenstette # and Bakers linear rank selection # method selection="SUS", # Selection Method: mateselection="SUS", # Selection Method: # "Proportional": proportional to fitness # "PropFitDiff": prop. to fitness diff # "Uniform": with equal probability # "Tournament": tournament selection # "SUS": Baker's stochastic universal selection selectionContinuation=TRUE, # scaling="NoScaling", # Scaling method: # "NoScaling" # "ConstantScaling" (Static) # "ThresholdScaling" (Dynamic) # "ContinuousScaling" (Dynamic) scalingThreshold=0.0, # Ratio of Dispersion Measures (RDM) # in [1+/-scalingThreshold]: Do not scale! scalingExp=1, # For static and threshold scaling (>1) scalingExp2=1, # For threshold scaling (<1) rdmWeight=1, # Weight constant continuous scaling drMax=2.0, # Maximum of dispersion ratio drMin=0.5, # Minimum of dispersion ratio dispersionMeasure="var", # Dispersion measure: # "var", "std", "mad", "cv", # "range", "iqr" scalingDelay=1, # delay in ratio computation: DM(t)/DM(t-scalingDelay) accept="All", # accept new gene # Options: "All", "Best", "Metropolis" alpha=0.99, # Discount rate for temperature. beta=2, # Constant (in Boltzmann's formula: # k an arbitrary scaling constant). cooling="ExponentialMultiplicative", # accept new gene coolingPower=1, # power of PowerMultiplicativeCooling. # Default: Linear! temp0=40, # Higher than generations. tempN=0.01, # Final temperature. # verbose=1, # Maximal output per generation displayed. # logevals=FALSE, # If TRUE: log evals and parms to file allsolutions=FALSE, # TRUE: All best solutions are returned. # at the end of the run. early=FALSE, # FALSE: Ignore code for early termination. terminationEps=0.01, # fraction of known optimal solution # for termination interval cores=NA, # Number of cores. executionModel="Sequential", # Execution models are: # "Sequential" # "MultiCore" # "Cluster" # needs master, workers, port. # default: my minimal configuration. uParApply=NULL, # user-defined execution model. Cluster=NULL, # A cluster object generated by # parallel::makeCluster() or # parallelly::makeCluster() or profile=FALSE, # If TRUE: Measure time spent in # main blocks of GA. batch=FALSE, # If TRUE: save result to file path="" # path to files. ) { # Self description for re-running: # eval(parse(text=GAconfig)) # TODO: More precise reporting on RNG used. ### The following MUST be the first line of the main program. GAconfiguration<-xegaPopulation::xegaConfiguration("xegaRun", substitute(penv), substitute(grammar), environment()) #parm<-function(x){function() {return(x)}} # Random number generator: TODO. At the moment just for reporting ... # Report RNG RGused<-RNGkind("L'Ecuyer-CMRG") if (replay>0) {set.seed(replay)} else {set.seed(NULL)} RGseed<-replay if (executionModel=="MultiCore") { if (parallelly::supportsMulticore()==FALSE) {stop("Execution model MultiCore not supported")} if (is.na(cores)) {cores<-parallelly::availableCores()} } ### Tentative code! if (executionModel=="Cluster") { if (is.null(Cluster)) {stop("Execution model Cluster requires a cluster object!")} cluster<-xegaSelectGene::parm(Cluster) # nocov } else {cluster<-xegaSelectGene::parm(NULL)} if (max) {MAX<-xegaSelectGene::parm(1)} else {MAX<-xegaSelectGene::parm(-1)} if (is.null(uParApply)) {parApply<-xegaPopulation::ApplyFactory(method=executionModel)} else {parApply<-uParApply} ### shortest representation with potential bias. if ((algorithm=="sge") && (codonBits==0)) { Precision<-xegaGeGene::xegaGePrecisionFactory(method=codonPrecision) CodonPrecision<-Precision(grammar$PT$LHS, maxPBias) } else {CodonPrecision<-codonBits} # We do not check the feasibility of codonPrecision. bitsOnGene<-codons*CodonPrecision # Build local configuration (local functions) lF<-list( penv=penv, Grammar=grammar, MaxDepth=xegaSelectGene::parm(maxdepth), MaxTrials=xegaSelectGene::parm(maxtrials), Codons=xegaSelectGene::parm(codons), CodonPrecision=xegaSelectGene::parm(CodonPrecision), BitsOnGene=xegaSelectGene::parm(bitsOnGene), MutationRate=xegaPopulation::MutationRateFactory(method=ivmutrate), MutationRate1=xegaSelectGene::parm(mutrate), MutationRate2=xegaSelectGene::parm(mutrate2), BitMutationRate1=xegaSelectGene::parm(bitmutrate), BitMutationRate2=xegaSelectGene::parm(bitmutrate2), MaxMutDepth=xegaSelectGene::parm(maxmutdepth), MinMutInsertionDepth=xegaSelectGene::parm(minmutinsertiondepth), MaxMutInsertionDepth=xegaSelectGene::parm(maxmutinsertiondepth), Lambda=xegaSelectGene::parm(lambda), Max2Opt=xegaSelectGene::parm(max2opt), ScaleFactor1=xegaSelectGene::parm(scalefactor1), ScaleFactor2=xegaSelectGene::parm(scalefactor2), ScaleFactor=xegaDfGene::xegaDfScaleFactorFactory(method=scalefactor), CutoffFit=xegaSelectGene::parm(cutoffFit), CBestFitness=xegaSelectGene::parm(0.0), CMeanFitness=xegaSelectGene::parm(0.0), CVarFitness=xegaSelectGene::parm(0.0), CWorstFitness=xegaSelectGene::parm(0.0), CrossRate=xegaPopulation::CrossRateFactory(method=ivcrossrate), CrossRate1=xegaSelectGene::parm(crossrate), CrossRate2=xegaSelectGene::parm(crossrate2), UCrossSwap=xegaSelectGene::parm(uCrossSwap), MinCrossDepth=xegaSelectGene::parm(mincrossdepth), MaxCrossDepth=xegaSelectGene::parm(maxcrossdepth), Max=MAX, Offset=xegaSelectGene::parm(offset), Eps=xegaSelectGene::parm(eps), TerminationEps=xegaSelectGene::parm(terminationEps), Accept=xegaPopulation::AcceptFactory(method=accept), Alpha=xegaSelectGene::parm(alpha), Beta=xegaSelectGene::parm(beta), Cooling=xegaPopulation::CoolingFactory(method=cooling), CoolingPower=xegaSelectGene::parm(coolingPower), Generations=xegaSelectGene::parm(generations), Temp0=xegaSelectGene::parm(temp0), TempK=xegaSelectGene::parm(temp0), TempN=xegaSelectGene::parm(tempN), Elitist=xegaSelectGene::parm(elitist), Selection = xegaSelectGene::parm(selection), MateSelection = xegaSelectGene::parm(mateselection), SelectionContinuation = xegaSelectGene::parm(selectionContinuation), ScalingFitness = xegaSelectGene::ScalingFactory(method=scaling), ScalingExp = xegaSelectGene::parm(scalingExp), ScalingExp2 = xegaSelectGene::parm(scalingExp2), DispersionMeasure = xegaSelectGene::DispersionMeasureFactory(method=dispersionMeasure), RDM = xegaSelectGene::parm(1.0), DRmax = xegaSelectGene::parm(drMax), DRmin = xegaSelectGene::parm(drMin), RDMWeight = parm(rdmWeight), ScalingThreshold = xegaSelectGene::parm(scalingThreshold), ScalingDelay = xegaSelectGene::parm(scalingDelay), AllSolutions=xegaSelectGene::parm(allsolutions), Verbose=xegaSelectGene::parm(verbose), TournamentSize=xegaSelectGene::parm(tournamentSize), SelectionBias=xegaSelectGene::parm(selectionBias), MaxTSR=xegaSelectGene::parm(maxTSR), SelectGene=xegaSelectGene::SelectGeneFactory(method=selection), SelectMate=xegaSelectGene::SelectGeneFactory(method=mateselection), MutateGene=sgXMutationFactory(algorithm=algorithm, method=mutation), # gene dependent CrossGene=sgXCrossoverFactory(algorithm=algorithm, method=crossover), # gene dependent InitGene=sgXInitGeneFactory(algorithm), # gene dependent DecodeGene=sgXDecodeGeneFactory(algorithm), # gene dependent GeneMap=sgXGeneMapFactory(algorithm=algorithm, method=genemap), # gene dependent EvalGene=xegaSelectGene::EvalGeneFactory(method=evalmethod), ReportEvalErrors=xegaSelectGene::parm(reportEvalErrors), ReplicateGene=sgXReplicationFactory(algorithm=algorithm, method=replication), # gene dependent Cores=xegaSelectGene::parm(cores), # number of cores lapply=parApply, cluster=cluster ) # Configure timing. # Get timers. mainLoopTimer<-xegaSelectGene::newTimer() initPopulationTimer<-xegaSelectGene::newTimer() evalPopulationTimer<-xegaSelectGene::newTimer() observePopulationTimer<-xegaSelectGene::newTimer() summaryPopulationTimer<-xegaSelectGene::newTimer() nextPopulationTimer<-xegaSelectGene::newTimer() if (profile==TRUE) { InitPopulation<-xegaSelectGene::Timed(xegaPopulation::xegaInitPopulation, initPopulationTimer) EvalPopulation<-xegaSelectGene::Timed(xegaPopulation::xegaEvalPopulation, evalPopulationTimer) ObservePopulation<-xegaSelectGene::Timed(xegaPopulation::xegaObservePopulation, observePopulationTimer) SummaryPopulation<-xegaSelectGene::Timed(xegaPopulation::xegaSummaryPopulation, summaryPopulationTimer) NextPopulation<-xegaSelectGene::Timed(xegaPopulation::xegaNextPopulation, nextPopulationTimer) } if (profile==FALSE) { InitPopulation<-xegaPopulation::xegaInitPopulation EvalPopulation<-xegaPopulation::xegaEvalPopulation ObservePopulation<-xegaPopulation::xegaObservePopulation SummaryPopulation<-xegaPopulation::xegaSummaryPopulation NextPopulation<-xegaPopulation::xegaNextPopulation } # RunGA Main tUsed<-mainLoopTimer() pop<-InitPopulation(popsize, lF) popfit<-EvalPopulation(pop, lF) pop<-popfit$pop fit<-popfit$fit evalFail<-popfit$evalFail popStat<-ObservePopulation(fit) if (logevals==TRUE) {evallog<-xegaLogEvalsPopulation(pop=pop, evallog=list(), generation=0, lF=lF)} # nocov ### Tentative. # TODO: The interface is too restricted. # Needs to see e.g. history of solutions, known optima, # distance from reference points. if (early && ("terminate" %in% names(penv))) { Terminate<-penv$terminate} # nocov else { Terminate<-function(solution, lF) {FALSE} } if (generations>1) { for(i in 1:generations) { rc<-SummaryPopulation(pop, fit, lF, i) if (scaling %in% c("ThresholdScaling", "ContinuousScaling")) {lF$RDM<-xegaSelectGene::parm(xegaSelectGene::DispersionRatio( matrix(popStat, byrow=TRUE, ncol=8), lF$DispersionMeasure, lF)) # cat("lF$RDM:", lF$RDM(), "\n") } pop<-NextPopulation(pop, lF$ScalingFitness(fit, lF), lF) popfit<-EvalPopulation(pop, lF) pop<-popfit$pop fit<-popfit$fit evalFail<-evalFail+popfit$evalFail if (length(fit)<popsize) {return(popfit)} # nocov popStat<-ObservePopulation(fit, popStat) if (logevals==TRUE) {evallog<-xegaLogEvalsPopulation(pop=pop, evallog=evallog, generation=i, lF=lF)} # nocov if (Terminate(xegaBestInPopulation(pop, fit, lF, FALSE), lF)==TRUE) {break} # nocov # Cooling schedule for Metropolis acceptance rule. Abstract out? # cat("Temperature:", lF$TempK(), "\n") # cat("new Temperature:", lF$TempK(), "\n") newTemperature<-force(lF$Cooling(i, lF)) # cat("new Temperature:", newTemperature, "\n") lF$TempK<-parm(newTemperature) } } rc<-SummaryPopulation(pop, fit, lF, generations) tUsed<-mainLoopTimer() timer=list() timer[["tMainLoop"]]<-mainLoopTimer("TimeUsed") timer[["tInitPopulation"]]<-initPopulationTimer("TimeUsed") timer[["tNextPopulation"]]<-nextPopulationTimer("TimeUsed") timer[["tEvalPopulation"]]<-evalPopulationTimer("TimeUsed") timer[["tObservePopulation"]]<-observePopulationTimer("TimeUsed") timer[["tSummaryPopulation"]]<-summaryPopulationTimer("TimeUsed") timer[["cMainLoop"]]<-mainLoopTimer("Count") timer[["cInitPopulation"]]<-initPopulationTimer("Count") timer[["cNextPopulation"]]<-nextPopulationTimer("Count") timer[["cEvalPopulation"]]<-evalPopulationTimer("Count") timer[["cObservePopulation"]]<-observePopulationTimer("Count") timer[["cSummaryPopulation"]]<-summaryPopulationTimer("Count") rc<-xegaBestInPopulation(pop, fit, lF, allsolutions) if (generations>1) {fit=NULL} result<-list(popStat=matrix(popStat, byrow=TRUE, ncol=8), fit=fit, solution=rc, evalFail=evalFail, GAconfig=list(GAconfiguration$GAconf), GAenv=GAconfiguration$GAenv, timer=timer) if (lF$Verbose()==1) {cat("\n")} if (logevals==TRUE) { fn<-paste(path,"xegaEvalLog", Sys.time(), ".rds", sep="") # nocov fn<-chartr(old=" :", new="--", fn) # nocov saveRDS(object=evallog, file=fn) # nocov } if (batch==TRUE) { fn<-paste(path,"xegaResult", Sys.time(), ".rds", sep="") # nocov fn<-chartr(old=" :", new="--", fn) # nocov saveRDS(object=result, file=fn) # nocov } return(result) }
/scratch/gouwar.j/cran-all/cranData/xega/R/xegaRun.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Top-level main programs. # Package: xega # #' About this version. #' #' @param verbose Boolean. If \code{TRUE} (Default), print #' package information and version number to console. #' #' @return Version number (invisible). #' #' @examples #' xegaVersion() #' @export xegaVersion<-function(verbose=TRUE) { version<-"0.9.0.0" if (verbose) {cat('Package xega. Version', version, 'As of 2024/03/15 \n') cat('(c) Andreas Geyer-Schulz\n')} invisible(version) }
/scratch/gouwar.j/cran-all/cranData/xega/R/xegaVersion.R
# # Grammar Compiler for BNFs # (c) 2020 A. Geyer-Schulz # Package BNF # # (2) Make Symbol Table ST #' Build a symbol table from a character string which contains a BNF. #' #' @description \code{makeSymbolTable()} extracts all terminal #' and non-terminal symbols from a BNF #' and builds a data frame with the columns #' Symbols (string), NonTerminal (0 or 1), and SymbolId (int). #' The symbol "NotExpanded" is added which codes #' depth violations of a derivation tree. #' #' @param BNF A character string with the BNF. #' #' @return A data frame with the columns #' \code{Symbols}, \code{NonTerminal}, and \code{SymbolID}. #' #' @examples #' makeSymbolTable(booleanGrammar()$BNF) #' #' @export makeSymbolTable<-function(BNF) { b<-strsplit(BNF,";")[[1]] c<-chartr("|", " ",paste(b[2:length(b)], sep=" ", collapse="")) d<-gsub(pattern=":=", replacement="",x=c) e<-gsub(pattern="\"", replacement="",x=d) f<-unique(strsplit(e, " ")[[1]]) Symbols<-c("NotExpanded", sort(f[!f==""])) NonTerminal<- as.numeric(grepl(pattern="<",Symbols)) SymbolId<-1:length(Symbols) return(data.frame(Symbols, NonTerminal, SymbolId))} # Object definition: # r<-list() # r[["ST"]]<-ST # r[["id"]]<-function(sym){return(ST[sym==ST[,1],3])} # r[["symbol"]]<-function(SymbId){return(ST[SymbId==ST[,3],1])} # r[["Terminal"]]<-function(SymbId){return(1-ST[SymbId,2])} # r[["NonTerminal"]]<-function(SymbId){return(ST[SymbId,2])} #' Convert a symbol to a numeric identifier. #' #' @description \code{symb2id()} converts a symbol to a numeric id. #' #' @param sym A character string with the symbol, e.g. <fe> or "NOT". #' @param ST A symbol table. #' #' @return \itemize{ #' \item A positive integer if the symbol exists or #' \item an empty integer (\code{integer(0)}) #' if the symbol does not exist.} #' #' @family Utility Functions #' #' @examples #' g<-compileBNF(booleanGrammar()) #' symb2id("<fe>", g$ST) #' symb2id("NOT", g$ST) #' symb2id("<fe", g$ST) #' symb2id("NO", g$ST) #' identical(symb2id("NO", g$ST), integer(0)) #' #' @export symb2id<-function(sym, ST) {return(as.integer(ST[sym==ST[,1],3]))} #' Convert a numeric identifier to a symbol. #' #' @description \code{id2symb()} converts a numeric id to a symbol. #' #' @param Id A numeric identifier (integer). #' @param ST A symbol table. #' #' @return \itemize{ #' \item A symbol string if the identifier exists or #' \item an empty character string (\code{character(0)}) #' if the identifier #' does not exist.} #' #' @family Utility Functions #' #' @examples #' g<-compileBNF(booleanGrammar()) #' id2symb(1, g$ST) #' id2symb(2, g$ST) #' id2symb(5, g$ST) #' id2symb(12, g$ST) #' id2symb(15, g$ST) #' identical(id2symb(15, g$ST), character(0)) #' #' @export id2symb<-function(Id, ST) {return(as.character(ST[Id==ST[,3],1]))} #' Is the numeric identifier a terminal symbol? #' #' @description \code{isTerminal()} tests if the numeric identifier #' is a terminal symbol. #' #' @details \code{isTerminal()} is one of the most frequently used #' functions of a grammar-based genetic programming algorithm. #' Careful coding pays off! #' Do not index the symbol table as a matrix #' (e.g. \code{ST[2,2]}), because this is really slow! #' #' @param Id A numeric identifier (integer). #' @param ST A symbol table. #' #' @return \itemize{ #' \item \code{TRUE} if the numeric identifier is a terminal symbol. #' \item \code{FALSE} if the numeric identifier is a non-terminal symbol. #' \item \code{NA} if the symbol does not exist.} #' #' @family Utility Functions #' #' @examples #' g<-compileBNF(booleanGrammar()) #' isTerminal(1, g$ST) #' isTerminal(2, g$ST) #' isTerminal(5, g$ST) #' isTerminal(12, g$ST) #' isTerminal(15, g$ST) #' identical(isTerminal(15, g$ST), NA) #' #' @export isTerminal<-function(Id, ST) {return(as.logical(1-ST$NonTerminal[Id]))} # isTerminal<-function(Id, ST) # {return(as.logical(1-ST[Id,2]))} #' Is the numeric identifier a non-terminal symbol? #' #' @description \code{isNonTerminal()} tests if the numeric identifier #' is a non-terminal symbol. #' #' @details \code{isNonTerminal()} is one of the most frequently used #' functions of a grammar-based genetic programming algorithm. #' Careful coding pays off! #' Do not index the symbol table as a matrix #' (e.g. \code{ST[2,2]}), because this is really slow! #' #' @param Id A numeric identifier (integer). #' @param ST A symbol table. #' #' @return \itemize{ #' \item \code{TRUE} if the numeric identifier is a terminal symbol. #' \item \code{FALSE} if the numeric identifier is a non-terminal symbol. #' \item \code{NA} if the symbol does not exist.} #' #' @family Utility Functions #' #' @examples #' g<-compileBNF(booleanGrammar()) #' isNonTerminal(1, g$ST) #' isNonTerminal(2, g$ST) #' isNonTerminal(5, g$ST) #' isNonTerminal(12, g$ST) #' isNonTerminal(15, g$ST) #' identical(isNonTerminal(15, g$ST), NA) #' #' @export isNonTerminal<-function(Id, ST) {return(as.logical(ST$NonTerminal[Id]))} #isNonTerminal<-function(Id, ST) # {return(as.logical(ST[Id,2]))} # (3) Make Production Table PT #' Transforms a single BNF rule into a production table. #' #' @description \code{makeRule()} transforms a single BNF rule #' into a production table. #' #' @details Because a single BNF rule can provide a set of substitutions, #' more than one line in a production table may result. #' The number of substitutions corresponds to the number of lines #' in the production table. #' #' @param Rule A rule. #' @param ST A symbol table. #' #' @return A named list with 2 elements, namely \code{$LHS} and \code{$RHS}. #' The left-hand side \code{$LHS} is #' a vector of non-terminal identifiers #' and the right-hand side \code{$RHS} is a vector of vectors #' of numerical identifiers. #' The list represents the substitution of \code{$LHS[i]} #' by the identifier list \code{$RHS[[i]]}. #' #' @examples #' c<-booleanGrammar()$BNF #' ST<-makeSymbolTable(c) #' c<-booleanGrammar()$BNF #' b<-strsplit(c,";")[[1]] #' a<-b[2:4] #' a<-gsub(pattern=";",replacement="", paste(a[1], a[2], a[3], sep="")) #' makeRule(a, ST) #' #' @export makeRule<-function(Rule, ST) { LHS<-vector('integer') RHS<-vector('list') PT<-list() c<-strsplit(Rule, ":=")[[1]] d<-gsub(pattern=" ", replacement="", c[1]) left<-symb2id(d,ST) # length(LHS)==0 implies error! if (0==length(left)) { PT[["LHS"]]<-LHS PT[["RHS"]]<-RHS return(PT) } d<-strsplit(c[2], "\\|")[[1]] for (i in 1:length(d)) {e<-strsplit(gsub(pattern="\"",replacement="", d[i]), " ")[[1]] f<-vector("integer") for (j in 1:length(e)) {f<-c(f,symb2id(e[j], ST))} LHS<-c(LHS, left) RHS[[i]]<-f } PT[["LHS"]]<-LHS PT[["RHS"]]<-RHS return(PT) } #' Produces a production table. #' #' @description \code{makeProductionTable()} produces a production table #' from a specification of a BNF. #' Warning: No error checking implemented. #' #' @param BNF A character string with the BNF. #' @param ST A symbol table. #' #' @return A production table is a named list with elements #' \code{$LHS} and \code{$RHS}: #' \itemize{ #' \item The left-hand side \code{LHS} # is a vector #' of non-terminal identifiers. #' \item The right-hand side \code{RHS} is represented as a #' vector of vectors of numerical identifiers. #' } #' The non-terminal identifier \code{LHS[i]} derives into \code{RHS[i]}. #' #' @examples #' a<-booleanGrammar()$BNF #' ST<-makeSymbolTable(a) #' makeProductionTable(a,ST) #' #' @export makeProductionTable<-function(BNF, ST) { LHS<-vector('integer') RHS<-vector('list') b<-strsplit(BNF,";")[[1]] c<-b[2:length(b)] for (i in 1:length(c)) { rule<-makeRule(c[i], ST) LHS<-c(LHS, rule$LHS) RHS<-c(RHS, rule$RHS) } PT<-list() PT[["LHS"]]<-LHS PT[["RHS"]]<-RHS return(PT) } # Object PT: # # rules(numeric index of nonterminal) # PT[["rules"]]<-function(sym){return(as.vector((1:length(LHS))[sym==LHS]))} # derive(index of rule in production table) # PT[["derive"]]<-function(ri){return(RHS[[ri]])} # # If not OK, with some error checking ... # # PT[["rules"]]<- function(sym) { # a<-(sym==LHS) # if (Reduce(f="|", a)) # {return(as.vector((1:length(a))[a]))} # else # {return(vector("integer"))}} # PT[["derive"]]<- function(rindex) { # if (rindex>length(LHS)){return(vector("integer"))} # if (rindex<1){return(vector("integer"))} # return(RHS[[rindex]]) } #' Returns all indices of rules applicable for a non-terminal identifier. #' #' @description \code{rules()} finds #' all applicable production rules #' for a non-terminal identifier. #' #' @param Id A numerical identifier. #' @param LHS The left-hand side of a production table. #' #' @return \itemize{ #' \item A vector of indices of all applicable rules #' in the production table or #' \item an empty integer (\code{integer(0)}), #' if the numerical identifier is not found #' in the left-hand side of the production table.} #' #' @family Utility Functions #' #' @examples #' a<-booleanGrammar()$BNF #' ST<-makeSymbolTable(a) #' PT<-makeProductionTable(a,ST) #' rules(5, PT$LHS) #' rules(8, PT$LHS) #' rules(9, PT$LHS) #' rules(1, PT$LHS) #' #' @export rules<-function(Id, LHS){return(as.vector((1:length(LHS))[Id==LHS]))} #' Derives the identifier list which expands the non-terminal identifier. #' #' @description \code{derives()} returns the identifier list which expands #' a non-terminal identifier. #' Warning: No error checking implemented. #' #' @param RuleIndex An index (integer) in the production table. #' @param RHS The right-hand side of the production table. #' #' @return A vector of numerical identifiers. #' #' @family Utility Functions #' #' @examples #' a<-booleanGrammar()$BNF #' ST<-makeSymbolTable(a) #' PT<-makeProductionTable(a,ST) #' derive(1, PT$RHS) #' derive(2, PT$RHS) #' derive(3, PT$RHS) #' derive(5, PT$RHS) #' #' @export derive<-function(RuleIndex, RHS){return(RHS[[RuleIndex]])} # (4) Make Start Symbol #' Extracts the numerical identifier of the start symbol of the grammar. #' #' @description \code{makeStartSymbol()} returns #' the start symbol's numerical identifier #' from a specification of a context-free grammar in BNF. #' Warning: No error checking implemented. #' #' @param BNF A character string with the BNF. #' @param ST A symbol table. #' #' @return The numerical identifier of the start symbol of the BNF. #' #' @examples #' a<-booleanGrammar()$BNF #' ST<-makeSymbolTable(a) #' makeStartSymbol(a,ST) #' #' @export makeStartSymbol<-function(BNF, ST) { b<-strsplit(BNF,";")[[1]] c<-strsplit(b,":=")[[1]] d<-gsub(pattern=" ", replacement="", x=c[2]) return(symb2id(d, ST)) } # (5) Make Short Production Table PT #' Produces a production table with non-recursive productions only. #' #' @description \code{compileShortPT()} produces a ``short'' production table #' from a context-free grammar. The short production table does not #' contain recursive production rules. #' Warning: No error checking implemented. #' #' @param G A grammar with symbol table \code{ST}, #' production table \code{PT}, #' and start symbol \code{Start}. #' #' @details \code{compileShortPT()} starts with production rules whose #' right-hand side contains only terminals. #' It incrementally builds up the new PT until at least one #' production rule sequence from a non-terminal to a terminal symbol. #' #' The short production rule provides for each non-terminal #' symbol a minimal finite derivation into terminals. #' Instead #' of the full production table, it is used #' for generating depth-bounded derivation trees. #' #' @return A (short) production table is a named list with 2 columns. #' The first column #' (the left-hand side \code{LHS}) is a vector #' of non-terminal identifiers. #' The second column #' (the right-hand side \code{RHS}) is a #' vector of vectors of numerical identifiers. #' \code{LHS[i]} derives into \code{RHS[i]}. #' #' @examples #' g<-compileBNF(booleanGrammar()) #' compileShortPT(g) #' #' @export compileShortPT<-function(G) { ST<-G$ST allTerminal<-function(symbols) { return(Reduce(as.logical(unlist( lapply(symbols,FUN=isTerminal, ST=ST))), f="&")) } RHS<-G$PT$RHS LHS<-G$PT$LHS Nonterminals<-ST[as.logical(ST[,2]),3] RHSshort<-list() LHSshort<-vector("integer") while(length(Nonterminals)>0) { finiterules<-unlist(lapply(RHS, FUN=allTerminal)) RHSshort<-append(RHSshort, RHS[finiterules]) LHSshort<-c(LHSshort,LHS[finiterules]) RHS<-RHS[!finiterules] LHS<-LHS[!finiterules] fNTs<-unique(LHSshort) ST[fNTs,2]<-rep(0,length(fNTs)) Nonterminals<-Nonterminals[(!Nonterminals %in% fNTs)] } PT<-list() PT[["LHS"]]<-LHSshort PT[["RHS"]]<-RHSshort return(PT) } # (6) Compile BNF #' Compile a BNF (Backus-Naur Form) of a context-free grammar. #' #' @description \code{compileBNF} produces a context-free grammar #' from its specification in Backus-Naur form (BNF). #' Warning: No error checking is implemented. #' #' @details A grammar consists of the symbol table \code{ST}, the production #' table \code{PT}, the start symbol \code{Start}, #' and the short production #' table \code{SPT}. #' #' @details The function performs the following steps: #' \enumerate{ #' \item Make the symbol table. See \code{\link{makeSymbolTable}}. #' \item Make the production table. See \code{\link{makeProductionTable}}. #' \item Extract the start symbol. See \code{\link{makeStartSymbol}}. #' \item Compile a short production table. See \code{\link{compileShortPT}}. #' \item Return the grammar.} #' #' @param g A character string with a BNF. #' @param verbose Boolean. TRUE: Show progress. Default: FALSE. #' #' @return A grammar object (list) with the attributes #' \itemize{ #' \item \code{name} (the filename of the grammar), #' \item \code{ST} (symbol table), #' \item \code{PT} (production table), #' \item \code{Start} (the start symbol of the grammar), and #' \item \code{SPT} (the short production table). #' } #' #' @references Geyer-Schulz, Andreas (1997): #' \emph{Fuzzy Rule-Based Expert Systems and Genetic Machine Learning}, #' Physica, Heidelberg. (ISBN:978-3-7908-0830-X) #' #' @family Grammar Compiler #' #' @examples #' g<-compileBNF(booleanGrammar()) #' g$ST #' g$PT #' g$Start #' g$SPT #' @export compileBNF<-function(g, verbose=FALSE) { CFG<-list() CFG[["name"]]<-g$filename ST<-makeSymbolTable(g$BNF) if (verbose) {cat("Symbol table done.\n")} CFG[["ST"]]<-ST CFG[["PT"]]<-makeProductionTable(g$BNF,ST) if (verbose) {cat("Production table done.\n")} CFG[["Start"]]<-makeStartSymbol(g$BNF,ST) if (verbose) {cat("Start symbol done.\n")} CFG[["SPT"]]<-compileShortPT(CFG) if (verbose) {cat("Short production table done.\n")} return(CFG) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaBNF/R/BNF.R
# # Grammar Compiler for BNFs # (c) 2020 A. Geyer-Schulz # Package BNF # #' A constant function which returns the BNF (Backus-Naur Form) #' of a context-free grammar for the XOR problem. #' #' @return A named list with $filename and $BNF, #' the grammar of a boolean grammar with two variables and #' the boolean functions AND, OR, and NOT. #' #' @examples #' booleanGrammar() #' @export booleanGrammar<-function() { fn<-"~/dev/cran/xega/xegaBNF/BooleanGrammar.txt" bnf<-"S := <fe>; <fe> := <f0> | " bnf<-paste(bnf, " <f1> \"(\" <fe> \")\" | ") bnf<-paste(bnf, " <f2> \"(\" <fe> \",\" <fe> \")\"; ") bnf<-paste(bnf, " <f0> := \"D1\" | \"D2\"; ") bnf<-paste(bnf, " <f1> := \"NOT\"; ") bnf<-paste(bnf, " <f2> := \"OR\" | \"AND\"; ") return(list(filename=fn, BNF=bnf)) } #booleanGrammar<-newBNF("~/dev/cran/xega/xegaBNF/BooleanGrammar.txt") #' Write BNF into text file. #' #' @description \code{writeBNF()} writes a character string into a textfile. #' #' @details The user writes the BNF to a text file which he edits. #' The newline symbols are inserted after each substitution variant #' and after each production rule to improve the readability #' of the grammar by the user. #' #' @param g A named list with $filename and $BNF as a character string. #' @param fn A file name. Default: NULL. #' @param eol End-of-line symbol(s). Default: \code{"\\n"} #' #' @return Invisible NULL. #' #' @family File I/O #' #' @examples #' g<-booleanGrammar() #' fn<-tempfile() #' writeBNF(g, fn) #' g1<-readBNF(fn, eol="\n") #' unlink(fn) #' @export writeBNF<-function(g, fn=NULL, eol="\n") { fname<-fn if (identical(fn, NULL)) {fname<-g$filename} con<-file(fname, "wb") g1<-gsub("\\|", paste0("\\|",eol), gsub(";", paste0(";",eol), g$BNF)) b<-writeChar(g1, con, eos=NULL) close(con) return(invisible(b)) } #' Read text file. #' #' @description \code{readBNF()} reads a text file and #' returns a character string. #' #' @param filename A file name. #' @param eol End-of-line symbol(s). Default: "" #' #' @return A named list with #' \itemize{ #' \item $filename the filename. #' \item $BNF a character string with the newline symbol \\n. #' } #' #' @family File I/O #' #' @examples #' g<-booleanGrammar() #' fn<-tempfile() #' writeBNF(g, fn) #' g1<-readBNF(fn) #' unlink(fn) #' @export readBNF<-function(filename, eol="") { con<-file(filename, "rb") BNF<-readChar(con, file.size(filename)) if (!identical(eol, "")) {BNF<-gsub(eol, "", BNF)} close(con) return(list(filename=filename, BNF=BNF)) } #' Convert grammar file into a constant function. #' #' @description \code{newBNF()} reads a text file and #' returns a constant function which returns #' the BNF as a character string. #' #' @details The purpose of this function is to include examples #' of grammars in packages. #' #' @param filename A file name. #' @param eol End-of-line symbol(s). Default: \code{"\\n"} #' #' @return Returns a constant function which returns a BNF. #' #' @family File I/O #' #' @examples #' g<-booleanGrammar() #' fn<-tempfile() #' writeBNF(g, fn) #' g1<-newBNF(fn) #' unlink(fn) #' @export newBNF<-function(filename, eol="\n") { parm<-function(x){function() {return(x)}} b<-readBNF(filename) b$BNF<-gsub(eol, "", b$BNF) f<-parm(b) x<-f() return(f) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaBNF/R/BNFfileIO.R
#' \code{xegaBNF} implements a grammar compiler for context-free languages #' specified in BNF and a few utility functions. #' The grammar compiler #' generates a grammar object. #' This object used by the package #' \code{xegaDerivationTrees}, as well as for grammar-based genetic #' programming (\code{xegaGpGene}) and grammatical evolution #' (\code{xegaGeGene}. #' #' @section BNF (Backus-Naur Form): #' #' Grammars of context-free languages are represented #' in Backus-Naur Form (BNF). See e.g. Backus et al. (1962). #' #' The BNF is a meta-language for specifying the syntax of context-free #' languages. The BNF provides #' \enumerate{ #' \item non-terminal symbols, #' \item terminal symbols, and #' \item meta-symbols of the BNF. #' } #' A non-terminal symbol has the following form: #' \code{<pattern>}, where pattern is an arbitrary sequence of letters, numbers, #' and symbols. #' #' A terminal symbol has the following form: #' \code{"pattern"}, where pattern is an arbitrary sequence of letters, numbers, #' and symbols. #' #' The BNF has three meta symbols, namely \code{::=}, \code{|}, and \code{;} #' which are used for the specification of production (substitution) rules. #' \code{::=} separates the left-hand side of the rule from the right-hand #' side of the rule. \code{;} indicates the end of a production rule. #' \code{|} separates the symbol sequences of a compound production rule. #' A production rule has the following form: #' #' \code{LHS ::= RHS;} #' #' where \code{LHS} is a single non-terminal symbol and #' \code{RHS} is either a simple symbol sequence or a compound symbol #' sequence. #' #' A production rule with a simple symbol sequence #' specifies the substitution of #' the non-terminal symbol on the \code{LHS} by the symbol sequence of #' the \code{RHS}. #' #' A production rule with a compound symbol sequence #' specifies the substitution of #' the non-terminal symbol on the \code{LHS} by one of the symbol sequences of #' the \code{RHS}. #' #' @references #' Backus, J. W., Bauer, F. L., Green, J., Katz, C., McCarthy, J., #' Naur, Peter, Perlis, A. J., Ruthishauser, H., and Samelson, K. #' (1962) #' Revised Report on the Algorithmic Language ALGOL 60, IFIP, Rome. #' #' #' @section Editing BNFs: #' #' The BNF may be stored in ASCII text files and edited with standard editors. #' #' @section The Internal Representation of a Grammar Object: #' #' A grammar object is represented as a named list: #' \itemize{ #' \item $name contains the filename of the BNF. #' \item $ST the symbol table. #' \item $PT the production table. #' \item $Start the start symbol of the grammar. #' \item $SPT a short production table without recursive rules. #' } #' #' @section The Compilation Process: #' #' The main steps of the compilation process are: #' \enumerate{ #' \item Store the filename. #' \item Make the symbol table. See \code{\link{makeSymbolTable}}. #' \item Make the production table. See \code{\link{makeProductionTable}}. #' \item Extract the start symbol. See \code{\link{makeStartSymbol}}. #' \item Compile a short production table. See \code{\link{compileShortPT}}. #' \item Return the grammar.} #' #' @section The User-Interface of the Compiler: #' #' \code{compileBNF(g)} where \code{g} is a character string with a BNF. #' #' @section Utility Functions for xegaX-Packages: #' #' \itemize{ #' \item isTerminal, isNonTerminal: For testing the symbol type of #' identifiers in a grammar object. #' \item rules, derives: For choosing rules and for substitutions. #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation-free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split into a representation-independent and #' a representation-dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \itemize{ #' \item \code{xegaBNF} essentially provides a grammar compiler. #' \item \code{xegaDerivationTrees} implements an abstract data type for derivation trees. #' } #' }} #' #' @family Package Description #' #' @name xegaBNF #' @aliases xegaBNF #' @docType package #' @title Package xegaBNF #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaBNF> #' @section Installation: From CRAN by \code{install.packages('xegaBNF')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaBNF/R/xegaBNF-package.R
# # Derivation Tree Package # (c) 2020 A. Geyer-Schulz # Package derivationTrees # # # Generating a random derivation tree # #' A constant function which returns the BNF (Backus-Naur Form) #' of a context-free grammar for the XOR problem. #' #' @details Imported from package xegaBNF for use in examples. #' #' @return A named list with elements \code{$filename} and \code{$BNF} #' representing the grammar of a boolean grammar with two variables and #' the boolean functions \code{AND}, \code{OR}, and \code{NOT}. #' #' @family Grammar #' #' @examples #' booleanGrammar() #' @importFrom xegaBNF booleanGrammar #' @export booleanGrammar<-xegaBNF::booleanGrammar #' Compile a BNF (Backus-Naur Form) of a context-free grammar. #' #' @description \code{compileBNF()} produces a context-free grammar #' from its specification in Backus-Naur form (BNF). #' Warning: No error checking is implemented. #' #' @details A grammar consists of the symbol table \code{ST}, the production #' table \code{PT}, the start symbol \code{Start}, #' and the short production #' table \code{SPT}. #' #' The function performs the following steps: #' \enumerate{ #' \item Make the symbol table. #' \item Make the production table. #' \item Extract the start symbol. #' \item Compile a short production table. #' \item Return the grammar.} #' #' @param g A character string with a BNF. #' @param verbose Boolean. TRUE: Show progress. Default: FALSE. #' #' @return A grammar object (list) with the attributes #' \itemize{ #' \item \code{name}: Filename of the grammar. #' \item \code{ST}: Symbol table. #' \item \code{PT}: Production table. #' \item \code{Start}: Start symbol of the grammar. #' \item \code{SPT}: Short production table. #' } #' #' @family Grammar #' #' @examples #' g<-compileBNF(booleanGrammar()) #' g$ST #' g$PT #' g$Start #' g$SPT #' @importFrom xegaBNF compileBNF #' @export compileBNF<-xegaBNF::compileBNF #' Selects a production rule index at random from a vector of production rules. #' #' @description \code{chooseRule()} selects a production rule index #' from the vector of production rule indices #' in the \code{g$PT$LHS$} for a non-terminal symbol. #' #' @param riv Vector of production rules indices for #' a non-terminal symbol. #' #' @return Integer. Index of the production rule. #' #' @family Random Choice #' #' @examples #' chooseRule(c(7, 8, 9)) #' chooseRule(as.vector(1)) #' @export chooseRule<- function(riv) {return(riv[sample(length(riv),1)])} #' Codes the substitution of a non-terminal symbol by the symbols #' derived by a production rule as a nested list. #' #' @description \code{substituteSymbol()} #' generates a nested list with the non-terminal symbol as the root #' (first list element) and the derived symbols as the second list element. #' #' @param rindex Rule index. #' @param PT Production table. #' #' @return 2-element list. #' #' @family Generate Derivation Tree #' #' @examples #' g<-compileBNF(booleanGrammar()) #' substituteSymbol(3, g$PT) #' #' @importFrom xegaBNF derive #' @export substituteSymbol<- function(rindex, PT) { a<-xegaBNF::derive(rindex, PT$RHS) b<-list() b[[1]]<-PT$LHS[rindex] b[[2]]<-a return(b)} #' Transforms a non-terminal symbol into a random 1-level derivation tree. #' #' @description \code{rndsub()} expands a non-terminal by a random derivation #' and returns a 1-level derivation tree. #' #' @param sym Non-terminal symbol. #' @param PT Production table. #' #' @return Derivation tree with 1-level. #' #' @family Generate Derivation Tree #' #' @examples #' g<-compileBNF(booleanGrammar()) #' rndsub(g$Start, g$PT) #' #' @importFrom xegaBNF rules #' @export rndsub<-function(sym, PT){substituteSymbol(chooseRule(xegaBNF::rules(sym, PT$LHS)),PT)} #' Generates a random derivation tree. #' #' @description \code{randomDerivationTree()} #' generates a random derivation tree. #' #' @details \code{RandomDerivationTree()} recursively expands #' non-terminals and builds a depth-bounded derivation tree. #' #' @param sym Non-terminal symbol. #' @param G Grammar. #' @param maxdepth Integer. Maximal depth of the derivation tree. #' @param CompleteDT Boolean. Generate a complete derivation tree? #' Default: TRUE. #' #' @return Derivation tree (a nested list). #' #' @family Generate Derivation Tree #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' b<-randomDerivationTree(g$Start, g, maxdepth=10) #' c<-randomDerivationTree(g$Start, g, 2, FALSE) #' #' @importFrom xegaBNF isTerminal #' @export randomDerivationTree<-function(sym, G, maxdepth=5, CompleteDT=TRUE) { if (xegaBNF::isTerminal(sym, G$ST)) { return(sym) } # if ((maxdepth<0) && (!CompleteDT)) {return(1)} if ((maxdepth<0) && (!CompleteDT)) {return(sym)} else { if (maxdepth<0) {PT<-G$SPT} else {PT<-G$PT} } tmp<-rndsub(sym, PT) symbols<-tmp[[2]] l<-list() for (i in 1:length(symbols)) { h<-randomDerivationTree(symbols[i], G, maxdepth-1, CompleteDT) l[[i]]<-h } tmp[[2]]<-l return(tmp) } #' Randomly partitions n in k parts. #' #' @description Sampling a partition is a two-step process: #' \enumerate{ #' \item The k parts of the partion are sampled in the loop. #' This implies that the first partition p is a random number #' between 1 and 1+n-k. The next partition is sampled from #' 1 to 1+n-k-p. #' \item We permute the partitions. #' } #' #' @param n The integer to divide. #' @param k Number of parts. #' #' @return The integer partition of n in k parts. #' #' @family Unused #' #' @examples #' rndPartition(10, 4) #'@export rndPartition<-function(n, k) { if (k==1) {return(n)} r<-rep(0,k) nn<-1+n-k for (i in (1:(k-1))) { r[i]<-sample(1:nn, 1) nn<-1+nn-r[i] } r[k]<-n-sum(r) p<-sample(k, k, replace=FALSE) return(r[p]) } # # Measures of tree attributes # #' Measures the depth of a (nested) list. #' #' @description \code{treeListDepth()} returns the depth of a nested list. #' For a derivation tree, this is approximately twice #' the derivation depth. #' #' @param t List. #' @param tDepth Integer. List depth. Default: 0. #' #' @return Depth of a nested list. #' #' @family Measures of Tree Attributes #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeListDepth(a) #' #' @export treeListDepth <- function(t,tDepth=0){ if(is.list(t) && length(t) == 0){return(0)} if(!is.list(t)){ return(tDepth) }else{ return(max(unlist(lapply(t,treeListDepth,tDepth=tDepth+1)))) } } #' Measures the number of symbols in a derivation tree. #' #' @description \code{treeSize()} returns the number of symbols in a #' derivation tree. #' #' @param tree Derivation tree. #' #' @return Integer. Number of symbols in a derivation tree. #' #' @family Measures of Tree Attributes #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeSize(a) #' #' @export treeSize<-function(tree) { return(length(unlist(tree)))} #' Measures the number of inner nodes in a derivation tree. #' #' @description \code{treeNodes()} returns #' the number of non-terminal symbols in a #' derivation tree. #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return Integer. Number of non-terminal symbols in a derivation tree. #' #' @family Measures of Tree Attributes #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeNodes(a, g$ST) #' #' @importFrom xegaBNF isNonTerminal #' @export treeNodes<-function(tree, ST) { return(sum(unlist(lapply(unlist(tree),FUN=xegaBNF::isNonTerminal, ST=ST))))} #' Measures the number of leaves of a complete derivation tree. #' #' @description \code{treeLeaves()} returns #' the number of terminal symbols in a #' complete derivation tree. #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return Integer. Number of terminal symbols in a complete derivation tree. #' #' @family Measures of Tree Attributes #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeLeaves(a, g$ST) #' ((treeLeaves(a, g$ST)+treeNodes(a, g$ST)) == treeSize(a)) #' #' @importFrom xegaBNF isTerminal #' @export treeLeaves<-function(tree, ST) { return(sum(unlist(lapply(unlist(tree),FUN=xegaBNF::isTerminal, ST=ST))))} # # tree Helpers: # #' Returns the root of a derivation tree. #' #' @description \code{treeRoot()} returns the root of a derivation tree. #' #' @param tree Derivation tree. #' #' @return Root of a derivation tree. #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeRoot(a) #' #' @family Access Tree Parts #' #' @export treeRoot<-function(tree) { return(tree[[1]][1])} #' Returns the children of a derivation tree. #' #' @description \code{treeChildren()} returns the children of a derivation tree #' represented as a list of derivation trees. #' #' @param tree Derivation tree. #' #' @return The children of a derivation tree (a list of derivation trees). #' #' @family Access Tree Parts #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' treeChildren(a) #' #' @export treeChildren<-function(tree) { return(tree[[2]])} # # treeANL: Attributed Node List: # Node$ID, Node$NT, Node$Pos, Node$Depth, Node$RDepth, Node$subtreedepth # Node$Index, #' Builds an Attributed Node List (ANL) of a derivation tree. #' #' @description \code{treeANL()} recursively traverses a derivation tree #' and collects information about the derivation tree in an attributed #' node list (ANL). #' #' @details An attributed \code{node} has the following elements: #' \itemize{ #' \item \code{$ID}: Id in the symbol table \code{ST}. #' \item \code{$NT}: Is the symbol a non-terminal? #' \item \code{$Pos}: Position in the trail. #' \item \code{$Depth}: Depth of node. #' \item \code{$RDepth}: Residual depth for expansion. #' \item \code{$subtreedepth}: Depth of subtree starting here. #' \item \code{$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' These elements can be used e.g. #' \itemize{ #' \item for inserting and extracting subtrees #' (\code{Pos} or \code{node$Index}), #' \item for checking #' the feasibility of subtree substitution (\code{ID}), #' \item for checking depth bounds #' (\code{Depth}, \code{RDepth}, and \code{subtreedepth}), #' \dots #' } #' #' @param tree A derivation tree. #' @param ST A symbol table. #' @param maxdepth Limit on the depth of a derivation tree. #' @param ANL Attributed node list (empty on invocation). #' @param IL Index function list (empty on invocation). #' @param count Trail count (1 on invocation). #' @param depth Derivation tree depth (1 on invocation). #' # Node$ID, Node$NT, Node$Pos, Node$Depth, Node$RDepth, Node$subtreedepth # Node$Index, #' @return A list with three elements: #' \enumerate{ #' \item \code{r$count}: The trail length (not needed). #' \item \code{r$depth}: The derivation tree depth (not needed). #' \item \code{r$ANL}: The attributed node list is a list of nodes. #' Each node is represented as a list of the following attributes: #' \itemize{ #' \item \code{Node$ID}: Id in the symbol table ST. #' \item \code{Node$NT}: Is the symbol a non-terminal? #' \item \code{Node$Pos}: Position in the trail. #' \item \code{Node$Depth}: Depth of node. #' \item \code{Node$RDepth}: Residual depth for expansion. #' \item \code{Node$subtreedepth}: Depth of subtree starting here. #' \item \code{Node$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' #' } #' #' @family Access Tree Parts #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' b<-treeANL(a, g$ST) #' c<-treeANL(a, g$ST, 10) #' d<-treeANL(a, g$ST, maxdepth=10) #' #' @importFrom xegaBNF isTerminal #' @importFrom xegaBNF isNonTerminal #' @export treeANL<-function(tree, ST, maxdepth=5, ANL=list(), IL=list(), count=1, depth=1) { root<-treeRoot(tree) thiscount<-count if (xegaBNF::isTerminal(root, ST)) { r<-list() r$count<-count r$subtreedepth<-1 r$ANL<list() return(r)} kids<-treeChildren(tree) subtreedepth<-0 anl<-list() inl<-list() for (i in 1:length(kids)) { #### Control of the depth of the insertion point? TBD inl<-append(IL, paste("[[2]][[", as.character(i), "]]", sep="")) r<-treeANL(kids[[i]], ST, maxdepth, ANL=list(), inl, count+1, depth+1) count<-r$count subtreedepth<-max(subtreedepth, r$subtreedepth) anl<-append(anl,r$ANL) } Node<-list() Node$ID<-root Node$NonTerminal<-xegaBNF::isNonTerminal(root,ST) Node$Pos<-thiscount Node$Depth<-depth Node$Rdepth<-maxdepth-depth Node$subtreedepth<-subtreedepth Node$Index<-paste(unlist(IL), sep="", collapse="") ANL<-append(ANL, list(Node)) ANL<-append(ANL, anl) r<-list() r$count<-count r$subtreedepth<-subtreedepth+1 r$ANL<-ANL return(r) } #' Filter an Attributed Node List (ANL) of a derivation tree by depth. #' #' @description \code{filterANL()} deletes all nodes whose depth #' \code{node$Depth} is #' less than \code{minb} and larger than \code{maxb} #' from the ANL. #' However, if the resulting list is empty, the original #' ANL is returned. #' #' #' @details An attributed \code{node} has the following elements: #' \itemize{ #' \item \code{$ID}: Id in the symbol table \code{ST}. #' \item \code{$NT}: Is the symbol a non-terminal? #' \item \code{$Pos}: Position in the trail. #' \item \code{$Depth}: Depth of node. #' \item \code{$RDepth}: Residual depth for expansion. #' \item \code{$subtreedepth}: Depth of subtree starting here. #' \item \code{$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' #' @param ANL Attributed node list. #' @param minb Integer. #' @param maxb Integer. #' #' @return An attributed node list with nodes whose depths are in #' \code{minb:maxb}. #' Each node is represented as a list of the following attributes: #' \itemize{ #' \item \code{Node$ID}: Id in the symbol table ST. #' \item \code{Node$NT}: Is the symbol a non-terminal? #' \item \code{Node$Pos}: Position in the trail. #' \item \code{Node$Depth}: Depth of node. #' \item \code{Node$RDepth}: Residual depth for expansion. #' \item \code{Node$subtreedepth}: Depth of subtree starting here. #' \item \code{Node$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' #' @family Access Tree Parts #' #' @examples #' g<-compileBNF(booleanGrammar()) #' set.seed(111) #' a<-randomDerivationTree(g$Start, g, maxdepth=10) #' b<-treeANL(a, g$ST) #' c<-filterANL(b, minb=1, maxb=3) #' d<-filterANL(b, minb=3, maxb=5) #' e<-filterANL(b, minb=14, maxb=15) #' f<-filterANL(b, minb=13, maxb=15) #' #' @importFrom xegaBNF isTerminal #' @importFrom xegaBNF isNonTerminal #' @export filterANL<-function(ANL, minb=1, maxb=3) { nodelist<-ANL$ANL nlist<-list() for (i in (1:length(nodelist))) { if (nodelist[[i]]$Depth %in% (minb:maxb)) {nlist<-c(nlist, nodelist[i])} } if (length(nlist)==0) {nlist<-ANL$ANL} return(list(count=ANL$count, subtreedepth=ANL$subtreedepth, ANL=nlist)) } #' Filter an Attributed Node List (ANL) of a derivation tree by a symbol identifier. #' #' @description \code{filterANLid()} deletes all nodes whose \code{node$ID} does not match #' \code{node$ID}. #' If the resulting list is empty, a list of length 0 is returned. #' #' @details An attributed \code{node} has the following elements: #' \itemize{ #' \item \code{$ID}: Id in the symbol table \code{ST}. #' \item \code{$NT}: Is the symbol a non-terminal? #' \item \code{$Pos}: Position in the trail. #' \item \code{$Depth}: Depth of node. #' \item \code{$RDepth}: Residual depth for expansion. #' \item \code{$subtreedepth}: Depth of subtree starting here. #' \item \code{$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' #' For the implementation of crossover and mutation, we expect a non-terminal symbol identifier. #' #' @param ANL Attributed node list. #' @param nodeID Integer. The identifier of a symbol. #' # Node$ID, Node$NT, Node$Pos, Node$Depth, Node$RDepth, Node$subtreedepth # Node$Index, #' @return An attributed node list with nodes whose depths are in #' \code{minb:maxb}. #' Each node is represented as a list of the following attributes: #' \itemize{ #' \item \code{Node$ID}: Id in the symbol table ST. #' \item \code{Node$NT}: Is the symbol a non-terminal? #' \item \code{Node$Pos}: Position in the trail. #' \item \code{Node$Depth}: Depth of node. #' \item \code{Node$RDepth}: Residual depth for expansion. #' \item \code{Node$subtreedepth}: Depth of subtree starting here. #' \item \code{Node$Index}: R index of the node in the derivation tree. #' Allows fast tree extraction and insertion. #' } #' #' @family Access Tree Parts #' #' @examples #' g<-compileBNF(booleanGrammar()) #' set.seed(111) #' a<-randomDerivationTree(g$Start, g, maxdepth=10) #' b<-treeANL(a, g$ST) #' c<-filterANLid(b, nodeID=5) #' d<-filterANLid(b, nodeID=6) #' e<-filterANLid(b, nodeID=7) #' f<-filterANLid(b, nodeID=8) #' #' @importFrom xegaBNF isTerminal #' @importFrom xegaBNF isNonTerminal #' @export filterANLid<-function(ANL, nodeID=1) { nodelist<-ANL$ANL nlist<-list() for (i in (1:length(nodelist))) { if (nodelist[[i]]$ID == nodeID) {nlist<-c(nlist, nodelist[i])} } return(list(count=ANL$count, subtreedepth=ANL$subtreedepth, ANL=nlist)) } # # Random choice in node list. # #' Selects an attributed node in an attributed node list randomly. #' #' @description \code{chooseNode()} returns a random attributed node #' from an attributed node list # #' @details An attributed \code{node} has the following elements: #' \itemize{ #' \item \code{ID} #' \item \code{NonTerminal} #' \item \code{Pos} #' \item \code{Depth} #' \item \code{Rdepth} #' \item \code{subtreedepth} #' \item \code{node$Index} #' } #' These elements can be used e.g. #' \itemize{ #' \item for inserting and extracting subtrees #' (\code{Pos} or \code{node$Index}), #' \item for checking #' the feasibility of subtree substitution (\code{ID}), #' \item for checking depth bounds #' (\code{Depth}, \code{RDepth}, and \code{subtreedepth}), #' \dots #' } #' #' @param ANL Attributed node list. #' #' @return Attributed node. #' #' @family Random Choice #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' b<-treeANL(a, g$ST) #' c<-chooseNode(b$ANL) #' #' @export chooseNode<-function(ANL) { return(ANL[[sample(length(ANL), 1)]]) } # # Test of compatibility of subtrees: # 1. same root symbol # Depth bounds: # 2.1 depth(node1) + depth(subtree2) \leq maxdepth+2 # 2.2 depth(node2) + depth(subtree1) \leq maxdepth+2 # # TODO: Replace 3 by Max derivations needed in SPT. #' Test the compatibility of subtrees. #' #' @description \code{compatibleSubtrees()} tests the compatibility of two #' subtrees. #' #' @details \code{compatibleSubtrees()} tests the compatibility of two #' subtrees: #' \enumerate{ #' \item The root symbol of the two subtrees must be identical: #' \code{(n1$ID==n2$ID)}. #' \item The depth restrictions must hold: #' \enumerate{ #' \item \code{depth(n1) + depth(subtree2) <= maxdepth+maxSPT} #' \item \code{depth(n2) + depth(subtree1) <= maxdepth+maxSPT} #' } #' maxSPT is the maximal number of derivations needed #' to generate a complete derivation tree.} #' #' @param n1 Attributed node of the root of subtree 1. #' @param n2 Attributed node of the root of subtree 2. #' @param maxdepth Integer. Maximal derivation depth. #' @param DepthBounded \itemize{ #' \item \code{TRUE}: Only subtrees #' with the same root symbol and which respect #' the depth restrictions are compatible. #' \item \code{FALSE}: The depth restrictions are not #' checked.} #' #' @family Tree Operations #' #' @return \code{TRUE} or \code{FALSE} #' #' @examples #' g<-compileBNF(booleanGrammar()) #' t1<-randomDerivationTree(g$Start, g) #' t1anl<-treeANL(t1, g$ST) #' t2<-randomDerivationTree(g$Start, g) #' t2anl<-treeANL(t2, g$ST) #' n1<-chooseNode(t1anl$ANL) #' n2<-chooseNode(t2anl$ANL) #' compatibleSubtrees(n1, n2) #' compatibleSubtrees(n1, n2, maxdepth=1) #' compatibleSubtrees(n1, n2, DepthBounded=FALSE) #' #' @export compatibleSubtrees<-function(n1, n2, maxdepth=5, DepthBounded=TRUE) { if (!identical(n1$ID, n2$ID)) {return(FALSE)} if (identical(DepthBounded,FALSE)) {return(TRUE)} if (((n1$Depth+n2$subtreedepth)<(maxdepth+3)) && ((n2$Depth+n1$subtreedepth)<(maxdepth+3))) { return(TRUE)} else {return(FALSE)} } # # Extracting a subtree of a derivation tree # #' Extracts the subtree at position \code{pos} in a derivation tree. #' #' @description \code{treeExtract()} returns #' the subtree at position \code{pos} in a derivation tree. #' #' @details An attributed \code{node} is a list #' whose element \code{node$Index} contains #' an access function to the node. #' The access function is represented as a string #' with an executable R index expression. #' All what remains to be done, is #' \itemize{ #' \item to complete #' the access statement and #' \item to return #' the result of parsing and evaluating the string. #' } #' #' @param tree Derivation tree. #' @param node Attributed node. #' #' @return Derivation tree. #' #' @family Tree Operations #' #' @examples #' g<-compileBNF(booleanGrammar()) #' t1<-randomDerivationTree(g$Start, g) #' t1anl<-treeANL(t1, g$ST) #' n1<-chooseNode(t1anl$ANL) #' st1<-treeExtract(t1, n1) #' decodeCDT(st1, g$ST) #' st2<-treeExtract(t1, chooseNode(t1anl$ANLa)) #' decodeCDT(st2, g$ST) #' #' @export treeExtract<-function(tree, node) { a<-paste("tree",node$Index, sep="") return(eval(parse(text=a))) } # # Inserting a subtree of a derivation tree # #' Inserts a subtree into a derivation tree at a \code{node}. #' #' @description \code{treeInsert()} inserts a \code{subtree} into #' a \code{tree} at a \code{node}. #' #' @details An attributed \code{node} is a list #' whose element \code{node$Index} contains #' an access function to the node. #' The access function is represented as a string #' which contains an executable R index expression. #' All what remains to be done, is #' \itemize{ #' \item to complete #' the assignment statement and #' \item to parse and evaluate the string. #' } #' #' @param tree Derivation tree. #' @param subtree Subtree. #' @param node Attributed node. #' #' @return A derivation tree. #' #' @family Tree Operations #' #' @examples #' g<-compileBNF(booleanGrammar()) #' t1<-randomDerivationTree(g$Start, g) #' t2<-randomDerivationTree(g$Start, g) #' t1anl<-treeANL(t1, g$ST) #' n1<-chooseNode(t1anl$ANL) #' t2<-randomDerivationTree(n1$ID, g) #' tI1<-treeInsert(t1, t2, n1) #' decodeCDT(tI1, g$ST) #' #' @export treeInsert<-function(tree, subtree, node) { a<-paste("tree",node$Index,"<-subtree", sep="") eval(parse(text=a)) return(tree) } # # 4. decode a random derivation tree # #' Returns a list of all symbols of a derivation tree #' in depth-first left-to-right order. #' #' @description \code{decodeTree()} returns a #' list of all symbols of a derivation tree #' in depth-first left-to-right order #' (coded as R Factor with the symbol identifiers as levels). #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return List of all symbols in depth-first left-to-right order. #' #' @family Decoder #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' decodeTree(a, g$ST) #' #' @export decodeTree<-function(tree, ST) { ST[unlist(tree),1] } #' Converts a complete derivation tree into a program. #' #' @description \code{decodeCDT()} returns a program #' (a text string with the terminal symbol string). #' If the derivation tree still has non-terminal leaves, #' the non-terminal leaves are omitted. #' The program produces a syntax error. #' The program can not be repaired. #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return Program. #' #' @family Decoder #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' decodeCDT(a, g$ST) #' #' @importFrom xegaBNF isTerminal #' @export decodeCDT<-function(tree, ST) { a<-unlist(tree) c<-a[as.logical(unlist(lapply(a,FUN=xegaBNF::isTerminal, ST=ST)))] b<-unlist(lapply(ST[c,1],as.character)) d<-Reduce(b, f=paste0) return(d) } #' Returns the list of symbol identifiers #' of the leaves of a derivation tree. #' #' @description For incomplete derivation trees, non-terminal symbols #' are leaves. #' #' @details Must perform a depth-first left-to-right tree traversal to collect #' all leave symbols (terminal and non-terminal symbols). #' #' @param tree Derivation tree. #' @param ST Symbol table. #' @param leavesList List of symbol identifiers. #' #' @return List of symbol identifiers. #' #' @family Decoder #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-randomDerivationTree(g$Start, g) #' leavesIncompleteDT(a, g$ST) #' #' @importFrom xegaBNF isTerminal #' @export leavesIncompleteDT<-function(tree, ST, leavesList=list()) { root<-treeRoot(tree) if (xegaBNF::isTerminal(root, ST)) { leavesList<-append(leavesList, root); return(leavesList)} if ((xegaBNF::isNonTerminal(root, ST)) & (length(tree)==1)) { leavesList<-append(leavesList, root); return(leavesList)} kids<-treeChildren(tree) lL<-list() for (i in 1:length(kids)) { r<-leavesIncompleteDT(kids[[i]], ST, leavesList) lL<-append(lL, r) } return(lL) } #' Decodes a derivation tree into a list of the leaf symbols #' of the derivation tree. #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return List of the leaf symbols of the derivation tree. #' #' @family Decoder #' #' @examples #' g<-compileBNF(booleanGrammar()) #' t1<-generateDerivationTree(sym=g$Start,sample(100, 10, replace=TRUE), G=g) #' decodeDTsym(t1$tree, g$ST) #' #' @importFrom xegaBNF isTerminal #' @export decodeDTsym<-function(tree, ST) { a<-unlist(leavesIncompleteDT(tree, ST)) return(ST[a,1]) } #' Decodes a derivation tree into a program. #' #' @description The program may contain non-terminal symbols #' and its evaluation may fail. #' #' @param tree Derivation tree. #' @param ST Symbol table. #' #' @return Program #' #' @family Decoder #' #' @examples #' g<-compileBNF(booleanGrammar()) #' t1<-generateDerivationTree(sym=g$Start,sample(100, 10, replace=TRUE), G=g) #' decodeDT(t1$tree, g$ST) #' #' @importFrom xegaBNF isTerminal #' @export decodeDT<-function(tree, ST) { a<-unlist(leavesIncompleteDT(tree, ST)) return(Reduce(ST[a,1], f=paste0)) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaDerivationTrees/R/derivationTrees.R
#' Selects k-th production rule index from a vector of production rules. #' #' @description \code{chooseRulek()} selects the k-th production rule index #' from the vector of production rule indices #' in the \code{g$PT$LHS$} for a non-terminal symbol. #' #' @param riv Vector of production rules indices for #' a non-terminal symbol. #' @param k Integer. #' #' @return The index of the production rule. #' #' @family Choice #' #' @examples #' chooseRulek(c(7, 8, 9), 9) #' chooseRulek(as.vector(1), 9) #' @export chooseRulek<- function(riv, k) {return(riv[1+(k%%length(riv))])} #' Transforms a non-terminal symbol into a 1-level derivation tree #' for a given k. #' #' @description \code{rndsubk()} expands a non-terminal by a derivation #' specified by k and returns a 1-level derivation tree. #' #' @param sym Non-terminal symbol. #' @param k Codon (An integer). #' @param PT Production table. #' #' @return 1-level derivation tree. #' #' @family Generate Derivation Tree #' #' @examples #' g<-compileBNF(booleanGrammar()) #' rndsubk(g$Start, 207, g$PT) #' #' @importFrom xegaBNF rules #' @export rndsubk<-function(sym, k, PT) {substituteSymbol(chooseRulek(xegaBNF::rules(sym, PT$LHS), k),PT)} #' Generates a derivation tree from an integer vector. #' #' @description \code{generateDerivationTree()} #' generates a derivation tree from an integer vector. #' The derivation tree may be incomplete. #' #' @param sym Non-terminal symbol. #' @param kvec Integer vector. #' @param complete Boolean. FALSE for incomplete derivation trees. #' @param G Grammar. #' @param maxdepth Integer. Maximal depth of the derivation tree. #' #' @details \code{generateDerivationTree()} recursively expands #' non-terminals and builds a derivation tree. #' #' @return A named list l$tree, l$kvec, l$complete. #' #' @family Generate Derivation Tree #' #' @examples #' g<-compileBNF(booleanGrammar()) #' a<-sample(100, 100, replace=TRUE) #' b<-generateDerivationTree(sym=g$Start, kvec=a, G=g, maxdepth=10) #' decodeDT(b$tree, g$ST) #' #' @importFrom xegaBNF isTerminal #' @export generateDerivationTree<-function(sym, kvec, complete=TRUE, G, maxdepth=5) { if (xegaBNF::isTerminal(sym, G$ST)) { return(list(tree=sym, kvec=kvec, complete=complete)) } if (length(kvec)==0) { return(list(tree=sym, kvec=kvec, complete=complete)) } tmp<-rndsubk(sym, kvec[1], G$PT) if (length(kvec)==1) { # cat("integers used up.\n") return(list(tree=tmp, kvec=vector(), complete=FALSE)) } nvec<-kvec[2:length(kvec)] symbols<-tmp[[2]] l<-list() for (i in 1:length(symbols)) { m<-generateDerivationTree(symbols[i], nvec, complete, G, maxdepth-1) h<-m$tree nvec<-m$kvec complete<-m$complete l[[i]]<-h } tmp[[2]]<-l return(list(tree=tmp, kvec=nvec, complete=complete)) } #' Generate, decode, and show \code{times} derivation trees from random #' integer vectors for grammar BNF on the console. #' #' @param times Number of derivation trees which should be generated. #' @param BNF BNF. #' @param verbose Boolean. If TRUE (default) , print decoded derivation tree on console. #' #' @return Number of complete derivation trees generated. #' #' @family Tests #' #' @examples #' testGenerateDerivationTree(5, BNF=booleanGrammar()) #' @export testGenerateDerivationTree<-function(times, BNF, verbose=TRUE) { g<-compileBNF(BNF) cDT<-0 for (i in 1:times) { a<-sample(100, 100, replace=TRUE) b<-generateDerivationTree(sym=g$Start, kvec= a, complete=TRUE, G=g, maxdepth=10) if (b$complete) {cDT<-cDT+1} if (verbose) { cat("Derivation Tree", i, "Complete:", b$complete, "\n") cat(decodeDT(b$tree, g$ST), "\n")} } return(cDT) }
/scratch/gouwar.j/cran-all/cranData/xegaDerivationTrees/R/geTree.R
#' Derivation Trees #' #' The implementation of a data type for derivation trees. #' #' The derivation tree operations for generating complete random subtrees and for #' for subtree extraction and insertion are formally introduced in Geyer-Schulz (1997) #' and used for implementing mutation and crossover operations. #' #' Efficient selection of random subtrees is implemented by building a list of annotated #' tree nodes by a left-right depth-first tree traversal. For each node, the R-index #' to access the subtree is built and stored in the node. The R-index element of a node #' allows subtree extraction and insertion operations with the cost of the R-index operation. #' In addition, filtering operations the node list by different criteria (min depth, max depth, and #' non-terminal symbol type) allow the implementation of flexible and #' configurable crossover and mutation operations. #' #' @references Geyer-Schulz, Andreas (1997): #' \emph{Fuzzy Rule-Based Expert Systems and Genetic Machine Learning}, #' Physica, Heidelberg. #' (ISBN:978-3-7908-0830-X) #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation-free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population-related functionality as well as support for #' adaptive mechanisms which depend on population statistics. #' In addition, support for parallel evaluation of genes is implemented here. #' #' \item #' The gene layer is split in a representation-independent and #' a representation-dependent part: #' \enumerate{ #' \item #' The representation-indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation-dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary-coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation-free algorithms. For example, #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler, and #' \code{xegaDerivationTrees} an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaDerivationTrees #' @aliases xegaDerivationTrees #' @docType package #' @title Package xegaDerivationTrees #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaDerivationTrees> #' @section Installation: #' From cran with \code{install.packages("xegaDerivationTrees")} NULL
/scratch/gouwar.j/cran-all/cranData/xegaDerivationTrees/R/xegaDerivationTrees-package.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a real-coded gene representation. # Package: xegaDfGene # #' One point crossover of 2 genes. #' #' @description \code{CrossGene} randomly determines a cut point. #' It combines the parameters before the cut point of the first gene #' with the parameters after the cut point from the second gene (kid 1). #' #' @param gg1 Real-coded gene. #' @param gg2 Real-coded gene. #' @param lF Local configuration of the genetic algorithm. #' #' @return Real-coded gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' gene3<-xegaDfCrossGene(gene1, gene2, lFxegaDfGene) #' @importFrom utils head #' @importFrom utils tail #' @export xegaDfCrossGene<-function(gg1, gg2, lF) { g1<-gg1$gene1; g2<-gg2$gene1 cut<-sample(1:length(g1), 1) ng<-gg1 ng$gene1<-c(head(g1,cut), tail(g2, length(g2)-cut)) # Tests on equality? ng$evaluated<-FALSE return(list(ng)) } #' Uniform crossover of 2 genes. #' #' @description \code{UCrossGene} swaps alleles of both genes #' with a probability of 0.5. It generates a random #' mask which is used to build the new gene. #' #' @references #' Syswerda, Gilbert (1989): #' Uniform Crossover in Genetic Algorithms. #' In: Schaffer, J. David (Ed.) #' Proceedings of the Third International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 2-9. #' (ISBN:1-55860-066-3) #' #' @param gg1 Real-coded gene. #' @param gg2 Real-coded gene. #' @param lF Local configuration of the genetic algorithm. #' #' @return Real-coded gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' gene3<-xegaDfUCrossGene(gene1, gene2, lFxegaDfGene) #' @importFrom stats runif #' @export xegaDfUCrossGene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-gg1$gene1; g2<-gg2$gene1 mask<-0.5>runif(rep(1, length(n1))) n1[mask]<-g2[mask] # Tests on equality? ng1$evaluated<-FALSE ng1$gene1<-n1 return(list(ng1)) } #' Parameterized uniform crossover of 2 genes. #' #' @description \code{UPCrossGene} swaps alleles of both genes #' with a probability of \code{lF$UCrossSwap}. #' It generate a random #' mask which is used to build the new gene. #' #' @references #' Spears William and De Jong, Kenneth (1991): #' On the Virtues of Parametrized Uniform Crossover. #' In: Belew, Richard K. and Booker, Lashon B. (Ed.) #' Proceedings of the Fourth International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 230-236. #' (ISBN: 1-55860-208-9) #' #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @param gg1 Real-coded gene. #' @param gg2 Real-coded gene. #' @param lF Local configuration of the genetic algorithm. #' #' @return Real-coded gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' gene3<-xegaDfUPCrossGene(gene1, gene2, lFxegaDfGene) #' @importFrom stats runif #' @export xegaDfUPCrossGene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-gg1$gene1; g2<-gg2$gene1 mask<-lF$UCrossSwap()>runif(rep(1, length(n1))) n1[mask]<-g2[mask] # Tests on equality? ng1$evaluated<-FALSE ng1$gene1<-n1 return(list(ng1)) } #' Configure the crossover function of a genetic algorithm. #' #' @description \code{xegaDfCrossoverFactory} implements the selection #' of one of the crossover functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' Crossover functions with one kid: #' \enumerate{ #' \item "CrossGene" returns \code{CrossGene}. #' \item "UCrossGene" returns \code{UCrossGene}. Default. #' \item "PUCrossGene" returns \code{PUCrossGene}. #' } #' #' @param method A string specifying the crossover function. #' #' @return Crossover function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaDfCrossoverFactory("UCrossGene") #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' XGene(gene1, gene2, lFxegaDfGene) #' @export xegaDfCrossoverFactory<-function(method="UCrossGene") { if (method=="CrossGene") {f<- xegaDfCrossGene} if (method=="UCrossGene") {f<- xegaDfUCrossGene} if (method=="UPCrossGene") {f<- xegaDfUPCrossGene} if (!exists("f", inherits=FALSE)) {stop("sgde Crossover label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfCrossover.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # for a real coded gene representation. # Package: xegaDfGene # #' Map the parameter vector of a real-coded gene to an identical vector. #' #' @description \code{GenemapIdentity} maps the real parameter vector #' to an identical vector. #' #' @details A \emph{gene} is a list with #' \enumerate{ #' \item \code{$evaluated} Boolean: TRUE if the fitness is known. #' \item \code{$fit} The fitness of the genotype of #' \code{$gene1} #' \item \code{$gene1} a real parameter vector (the genetopye). #' } #' #' This representation simplifies the implementation #' af various optimizations #' and generalizations. #' #' @param gene Real-coded gene (the genotype). #' @param penv Problem environment. #' #' @return Decoded gene (the phenotype). #' #' @family Decoder #' #' @examples #' gene<-xegaDfInitGene(lFxegaDfGene) #' xegaDfGeneMapIdentity(gene$gene1, lFxegaDfGene$penv) #' #' @export xegaDfGeneMapIdentity<-function(gene, penv) { return(gene) } #' Configure the gene map function of a genetic algorithm. #' #' @description \code{xegaDfGeneMapFactory} implements the selection #' of one of the GeneMap functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Identity" returns \code{GeneMapIdentity}. (Default) #' } #' #' @param method String specifying the GeneMap function. #' #' @return Gene map function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaDfGeneMapFactory("Identity") #' gene1<-xegaDfInitGene(lFxegaDfGene) #' XGene(gene1, lFxegaDfGene$penv) #' @export xegaDfGeneMapFactory<-function(method="Identity") { if (method=="Identity") {f<-xegaDfGeneMapIdentity} if (!exists("f", inherits=FALSE)) {stop("sgde GeneMap label ", method, " does not exist")} return(f) } #' Decode a gene #' #' @description \code{xegaDfDecodeGene} decodes a real gene. #' @details \code{xegaDfDecodeGene} is the identy function. #' #' @param gene Real gene #' @param lF Local configuration of the genetic algorithm #' #' @return Decoded gene. #' #' @family Decoder #' #' @examples #' gene<-xegaDfInitGene(lFxegaDfGene) #' xegaDfDecodeGene(gene, lFxegaDfGene) #' #' @export xegaDfDecodeGene<-function(gene, lF) { lF$GeneMap(gene$gene1, lF$penv) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfDecode.R
#' Genetic operations for real-coded genetic and evolutionary algorithms. #' #' For real-coded genes, the \code{xegaDfGene} package provides #' \itemize{ #' \item Gene initialization. #' \item Decoding of parameters. #' \item Scaling functions as a function factory for configuration. #' \item Mutation functions as well as a function factory for configuration. #' \item Crossover functions as well as a function factory for configuration. #' \item Replication functions as well as a function factory for configuration. #' } #' #' Current support: #' Functions for differential evolution (de). See Price et al. (2005). #' #' @section Real-Coded Gene Representation: #' #' A real-coded gene is a named list: #' \itemize{ #' \item $gene1 the gene must be a vector of reals. #' \item $fit the fitness value of the gene #' (for EvalGeneDet and EvalGeneU) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch). #' \item $evaluated has the gene been evaluated? #' \item $evalFail has the evaluation of the gene failed? #' \item $var the cumulative variance of the fitness #' of all evaluations of a gene. #' (For stochastic functions) #' \item $sigma the standard deviation of the fitness of #' all evaluations of a gene. #' (For stochastic functions) #' \item $obs the number evaluations of a gene. #' (For stochastic functions) #' } #' #' @section Abstract Interface of Problem Environment: #' #' We reuse the abstract interface of a problem environment #' for binary-coded genes. The number of parameters #' is given by \code{length(penv$bitlength())}. #' #' A problem environment \code{penv} must provide: #' \itemize{ #' \item \code{$f(parameters, gene, lF)}: #' Function with a real parameter vector as first argument #' which returns a gene #' with evaluated fitness. #' #' \item $genelength(): The number of bits of the binary coded #' real parameter vector. Used in \code{InitGene}. #' \item $bitlength(): A vector specifying the number of bits #' used for coding each real parameter. #' If \code{penv$bitlength()[1]} is \code{20}, #' then \code{parameters[1]} is coded by 20 bits. #' Used in \code{GeneMap}. #' \item $lb(): The lower bound vector of each parameter. #' Used in \code{GeneMap}. #' \item $ub(): The upper bound vector of each paremeter. #' Used in \code{GeneMap}. #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation-free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population-related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split in a representation-independent and #' a representation-dependent part: #' \enumerate{ #' \item #' The representation-independent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation-dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation-free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler, and #' \code{xegaDerivationTrees} is an abstract data type for derivation trees. #' }} #' #' @references #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @family Package Description #' #' @name xegaDfGene #' @aliases xegaDfGene #' @docType package #' @title Package xegaDfGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section <URL: https://github.com/ageyerschulz/xegaDfGene> #' @section Installation: From CRAN by \code{install.packages('xegaDfGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfGene-package.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a real-coded gene representation. # Package: xegaDfGene # #' Initialize a real-coded gene. #' #' @description \code{xegaDfInitGene} generates a random real-coded gene #' with a given length. #' #' @details In the real-coded representation of #' package \code{xegaDf}, \emph{gene} is a list with #' \enumerate{ #' \item \code{$evaluated} Boolean: TRUE if the fitness is known. #' \item \code{$fit} The fitness of the genotype of #' \code{$gene1} #' \item \code{$gene1} a real vector (the genetopye). #' } #' #' This representation simplifies the implementation #' af various optimizations #' and generalizations. #' #' @param lF Local configuration of the genetic algorithm. #' #' @return A real-coded gene (a named list): #' \itemize{ #' \item \code{$evaluated}: FALSE. See package \code{xegaEvalGene}. #' \item \code{$evalFail}: FALSE. Set by the error handler(s) #' in package \code{xegaEvalGene} #' in the case of failure. #' \item \code{$fit}: Fitness. #' \item \code{$gene1}: A vector of reals. #' } #' #' @family Intialization #' #' @references #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @examples #' xegaDfInitGene(lFxegaDfGene) #' #' @importFrom stats runif #' @export xegaDfInitGene<-function(lF) { r<-runif(length(lF$penv$bitlength())) gene1<-lF$penv$lb()+r*(lF$penv$ub()-lF$penv$lb()) return(list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=gene1)) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfInitGene.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaDfGene # #' Mutate a gene (differential mutation). #' #' @description \code{xegaDfMutateGeneDE} mutates a real-coded gene. #' The scale factor is given by Scalefactor(). #' #' @details The difference of gene1 and gene2 is scaled by #' ScaleFactor() and added to gene0. #' #' @param gene0 Real-coded gene (the base vector). #' @param gene1 Real-coded gene. #' @param gene2 Real-coded gene. #' @param lF Local configuration. #' #' @return Real-coded gene. #' #' @references #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @family Mutation #' #' @examples #' gene0<-xegaDfInitGene(lFxegaDfGene) #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' gene<-xegaDfMutateGeneDE(gene0, gene1, gene2, lFxegaDfGene) #' @export xegaDfMutateGeneDE<-function(gene0, gene1, gene2, lF) { ng<-gene0 ng$gene1<-gene0$gene1+lF$ScaleFactor(lF)*(gene1$gene1-gene2$gene1) ng$evaluated<-FALSE return(ng) } #' Configure the mutation function of a genetic algorithm. #' #' @description \code{xegaDfMutationFactory} implements the selection #' of one of the mutation functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "MutateGene" returns \code{xegaDfMutateGeneDE}. #' To provide a working default for more than #' one gene representation. #' \item "MutateGeneDE" returns \code{xegaDfMutateGeneDE}. #' } #' #' @param method A string specifying the mutation function. #' #' @return A mutation function for genes. #' #' @family Configuration #' #' @examples #' Mutate<-xegaDfMutationFactory("MutateGene") #' gene1<-xegaDfInitGene(lFxegaDfGene) #' gene2<-xegaDfInitGene(lFxegaDfGene) #' gene3<-xegaDfInitGene(lFxegaDfGene) #' Mutate(gene1, gene2, gene3, lFxegaDfGene) #' @export xegaDfMutationFactory<-function(method="MutateGene") { if (method=="MutateGene") {f<- xegaDfMutateGeneDE} if (method=="MutateGeneDE") {f<- xegaDfMutateGeneDE} if (!exists("f", inherits=FALSE)) {stop("sgde Mutation label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfMutate.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Population-level functions. # Independent of gene representation. # The replication mechanism and its variants # Package: xegaPopulation. # #' Replicates a gene (differential evolution). #' #' @description \code{ReplicateGeneDE} replicates a gene. Replication #' is the reproduction function which uses crossover and #' mutation. The control flow of differential evolution #' is as follows: #' \itemize{ #' \item A target gene is selected from the population. #' \item A mutant gene is generated by differential mutation. #' \item The gene and the mutant gene are crossed to get a #' new gene. #' \item The gene is accepted if it is at least as good #' as the target gene. #' } #' #' @details For \code{selection="UniformP"}, #' for \code{crossover="UPCrossGene"} and #' for \code{accept="Best"} #' this is #' the algorithm of Price, Storn and Lampinen (2005), page 41. #' #' @param pop Population of binary genes. #' @param fit Fitness vector. #' @param lF Local configuration of the genetic algorithm. #' #' @return A list of one gene. #' #' @family Replication #' #' @references #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @examples #' pop10<-lapply(rep(0,10), function(x) xegaDfGene::xegaDfInitGene(lFxegaDfGene)) #' epop10<-lapply(pop10, lFxegaDfGene$EvalGene, lF=lFxegaDfGene) #' fit10<-unlist(lapply(epop10, function(x) {x$fit})) #' newgenes<-xegaDfReplicateGeneDE(pop10, fit10, lFxegaDfGene) #' @importFrom xegaSelectGene parm #' @export xegaDfReplicateGeneDE<- function(pop, fit, lF) { targetGene<-pop[[lF$SelectGene(fit, lF)]] gene0<-pop[[lF$SelectGene(fit, lF)]] gene1<-pop[[lF$SelectGene(fit, lF)]] gene2<-pop[[lF$SelectGene(fit, lF)]] trialGene<-lF$CrossGene(targetGene,lF$MutateGene(gene0, gene1, gene2, lF))[[1]] t1<-lF$EvalGene(trialGene, lF) lF$trialGene<-parm(t1) OperatorPipeline<-function(g, lF) {lF$trialGene()} return(list(lF$Accept(OperatorPipeline, targetGene, lF))) } #' Configure the replication function of a genetic algorithm. #' #' @description \code{ReplicationFactory} implements the selection #' of a replication method. #' #' Current support: #' #' \enumerate{ #' \item "DE" returns \code{ReplicateGeneDE}. #' } #' #' @param method A string specifying the replication function. #' #' @return A replication function for genes. #' #' @family Configuration #' #' @examples #' pop10<-lapply(rep(0,10), function(x) xegaDfInitGene(lFxegaDfGene)) #' epop10<-lapply(pop10, lFxegaDfGene$EvalGene, lF=lFxegaDfGene) #' fit10<-unlist(lapply(epop10, function(x) {x$fit})) #' Replicate<-xegaDfReplicationFactory("DE") #' newgenes2<-Replicate(pop10, fit10, lFxegaDfGene) #' @export xegaDfReplicationFactory<-function(method="DE") { if (method=="DE") {f<- xegaDfReplicateGeneDE} if (!exists("f", inherits=FALSE)) {stop("sgde Replication label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfReplicate.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a real-coded gene representation. # Package: xegaDfGene # #' Constant scale factor for differential evolution. #' #' @param lF Local configuration. #' #' @return A constant scale factor. #' #' @family ScaleFactor #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list() #' lF$ScaleFactor1<-parm(0.90) #' ConstScaleFactor(lF) #' ConstScaleFactor(lF) #' @export ConstScaleFactor<-function(lF) { lF$ScaleFactor1() } #' Uniform random scale factor for differential evolution. #' #' @description The scale factor is drawn from #' \code{0.000001} to \code{1.0}. #' #' @param lF Local configuration. #' #' @return A constant scale factor. #' #' @family ScaleFactor #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list() #' lF$ScaleFactor1<-parm(0.90) #' UniformRandomScaleFactor(lF) #' UniformRandomScaleFactor(lF) #' @importFrom stats runif #' @export UniformRandomScaleFactor<-function(lF) { stats::runif(1, min=0.000001, max=1.0)} #' Configure the scale factor function for differential mutation. #' #' @description \code{xegaDfScaleFactorFactory} implements the selection #' of one of the scale factor functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Const" returns \code{ConstScaleFactor}. #' \item "Uniform" returns \code{UniformRandomScaleFactor}. #' } #' #' @details In the literature, several approaches have been suggested. #' For a review see Sharma et al. (2019). #' #' @param method A string specifying the scale factor function. #' #' @return A scale factor function for genes. #' #' @references #' Sharma, Prashant; Sharma, Harish; Kumar, Sandeep; Bansal, Jagdish Chand #' (2019): #' A Review on Scale Factor Strategies in Differential Evolution Algorithm. #' pp. 925-934. In: #' Bansal, Jagdish Chand et al. (2019) #' Soft Computing for Problem Solving. #' Advances in Intelligent Systems and Computing, Vol. 817. #' Springer, Singapore, 2019. (ISBN:978-981-13-1594-7) #' #' @family Configuration #' #' @examples #' f<-xegaDfScaleFactorFactory("Uniform") #' f(lFxegaDfGene) #' f(lFxegaDfGene) #' @export xegaDfScaleFactorFactory<-function(method="Const") { if (method=="Const") {f<-ConstScaleFactor} if (method=="Uniform") {f<-UniformRandomScaleFactor} if (!exists("f", inherits=FALSE)) {stop("sgde Mutation label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDfScaleFactor.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a real-coded gene representation. # Package: xegaDfGene # #' Generate local functions and objects #' #'@description \code{lFxegaDfGene} is #' the list of functions containing #' a definition of all local objects required for the use #' of evaluation functions. We reference this object #' as local configuration. When adding additional #' functions, this list must be extended #' by the constant (functions) needed to configure them. #' #' @details #' We use the local configuration for: #' \enumerate{ #' \item #' Replacing all constants with constant functions. #' #' Rationale: We need one formal argument (the local function list lF) #' and we can dispatch multiple functions. E.g. \code{lF$verbose()} #' \item #' We can dynamically bind a local function with a definition from a #' proper function factory. E.g., the selection methods #' \code{lf$SelectGene} and \code{lF$SelectMate}. #' #' \item Gene representations require special functions to handle them: #' \code{lf$InitGene}, \code{lF$DecodeGene}, \code{lf$EvalGene} #' \code{lf$ReplicateGene}, ... #' #' } #' #' @family Configuration #' #' @importFrom xegaSelectGene Parabola2DFactory #' @importFrom xegaSelectGene SelectGeneFactory #' @importFrom xegaSelectGene parm #' @importFrom xegaSelectGene EvalGeneFactory #' @export lFxegaDfGene<-list( penv=xegaSelectGene::Parabola2DFactory(), replay=xegaSelectGene::parm(0), verbose=xegaSelectGene::parm(4), CutoffFit=xegaSelectGene::parm(0.5), CBestFitness=xegaSelectGene::parm(100), ScaleFactor1=parm(0.9), ScaleFactor2=parm(0.3), ScaleFactor=xegaDfScaleFactorFactory("Const"), MutationRate1=xegaSelectGene::parm(0.01), MutationRate2=xegaSelectGene::parm(0.20), MutateGene=xegaDfMutationFactory("MutateGeneDE"), CrossRate=function(fit, lF) {0.8}, UCrossSwap=xegaSelectGene::parm(0.2), CrossGene=xegaDfCrossoverFactory("UCrossGene"), Max=xegaSelectGene::parm(1), Offset=xegaSelectGene::parm(1), Eps=xegaSelectGene::parm(0.01), Elitist=xegaSelectGene::parm(TRUE), TournamentSize=xegaSelectGene::parm(2), GeneMap=xegaDfGeneMapFactory(method="Identity"), SelectGene=xegaSelectGene::SelectGeneFactory(method="UniformP"), SelectMate=xegaSelectGene::SelectGeneFactory(method="Uniform"), InitGene=xegaDfInitGene, DecodeGene=xegaDfDecodeGene, EvalGene=xegaSelectGene::EvalGeneFactory(method="EvalGeneU"), SelectionContinuation=xegaSelectGene::parm(TRUE), ReplicateGene=xegaDfReplicateGeneDE, # Accept=function(OperatorPipeline, gene, lF) {gene}, Accept=function(OperatorPipeline, gene, lF) { newGene<- lF$EvalGene(OperatorPipeline(gene, lF), lF) if(newGene$fit>=gene$fit) {return(newGene)} else {return(gene)} }, Verbose=xegaSelectGene::parm(4), lapply=base::lapply )
/scratch/gouwar.j/cran-all/cranData/xegaDfGene/R/xegaDflF.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGaGene # #' One point crossover of 2 genes. #' #' @description \code{xegaGaCross2Gene} randomly determines a cut point. #' It combines the bits before the cut point of the first gene #' with the bits after the cut point from the second gene (kid 1). #' It combines the bits before the cut point of the second gene #' with the bits after the cut point from the first gene (kid 2). #' It returns 2 genes. #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of 2 binary genes. #' #' @family Crossover (2) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' newgenes<-xegaGaCross2Gene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[1]], lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[2]], lFxegaGaGene) #' @importFrom utils head #' @importFrom utils tail #' @export xegaGaCross2Gene<-function(gg1, gg2, lF) { g1<-gg1$gene1; g2<-gg2$gene1 cut<-sample(1:max(1,(length(g1)-1)), 1) ng1<-gg1; ng2<-gg2 ng1$gene1<-c(head(g1,cut), tail(g2, length(g2)-cut)) # Tests on equality? ng1$evaluated<-FALSE ng2$gene1<-c(head(g2,cut), tail(g1, length(g2)-cut)) # Tests on equality? ng2$evaluated<-FALSE return(list(ng1, ng2)) } #' Uniform crossover of 2 genes. #' #' @description \code{xegaGaUCross2Gene} swaps alleles of both genes #' with a probability of 0.5. It generates a random #' mask which is used to build the new genes. #' It returns 2 genes. #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of 2 binary genes. #' #' @references #' Syswerda, Gilbert (1989): #' Uniform Crossover in Genetic Algorithms. #' In: Schaffer, J. David (Ed.) #' Proceedings of the Third International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 2-9. #' (ISBN:1-55860-066-3) #' #' @family Crossover (2) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' newgenes<-xegaGaUCross2Gene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[1]], lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[2]], lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaUCross2Gene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-g1<-gg1$gene1; n2<-g2<-gg2$gene1 mask<-0.5>runif(rep(1, length(g1))) n1[mask]<-g2[mask]; n2[mask]<-g1[mask] # Tests on equality? ng1$evaluated<-FALSE; ng2$evaluated<-FALSE ng1$gene1<-n1; ng2$gene1<-n2 return(list(ng1, ng2)) } #' Parameterized uniform crossover of 2 genes. #' #' @description \code{xegaGaUP2CrossGene} swaps alleles of both genes #' with a probability of \code{lF$UCrossSwap}. #' It generates a random #' mask which is used to build the new gene. #' It returns 2 genes. #' @references #' Spears William and De Jong, Kenneth (1991): #' On the Virtues of Parametrized Uniform Crossover. #' In: Belew, Richar K. and Booker, Lashon B. (Ed.) #' Proceedings of the Fourth International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 230-236. #' (ISBN:1-55860-208-9) #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of 2 binary genes. #' #' @family Crossover (2) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' newgenes<-xegaGaUPCross2Gene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[1]], lFxegaGaGene) #' xegaGaDecodeGene(newgenes[[2]], lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaUPCross2Gene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-g1<-gg1$gene1; n2<-g2<-gg2$gene1 mask<-lF$UCrossSwap()>runif(rep(1, length(n1))) n1[mask]<-g2[mask]; n2[mask]<-g1[mask] # Tests on equality? ng1$evaluated<-FALSE; ng2$evaluated<-FALSE ng1$gene1<-n1; ng2$gene1<-n2 return(list(ng1, ng2)) } #' One point crossover of 2 genes. #' #' @description \code{xegaGaCrossGene} randomly determines a cut point. #' It combines the bits before the cut point of the first gene #' with the bits after the cut point from the second gene (kid 1). #' It combines the bits before the cut point of the second gene #' with the bits after the cut point from the first gene (kid 2). #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of one binary gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' gene3<-xegaGaCrossGene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(gene3[[1]], lFxegaGaGene) #' @importFrom utils head #' @importFrom utils tail #' @export xegaGaCrossGene<-function(gg1, gg2, lF) { g1<-gg1$gene1; g2<-gg2$gene1 cut<-sample(1:max(1,(length(g1)-1)), 1) ng<-gg1 ng$gene1<-c(head(g1,cut), tail(g2, length(g2)-cut)) # Tests on equality? ng$evaluated<-FALSE return(list(ng)) } #' Uniform crossover of 2 genes. #' #' @description \code{xegaGaUCrossGene} swaps alleles of both genes #' with a probability of 0.5. It generates a random #' mask which is used to build the new gene. #' #' @references #' Syswerda, Gilbert (1989): #' Uniform Crossover in Genetic Algorithms. #' In: Schaffer, J. David (Ed.) #' Proceedings of the Third International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 2-9. #' (ISBN:1-55860-066-3) #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of one binary gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' gene3<-xegaGaUCrossGene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(gene3[[1]], lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaUCrossGene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-gg1$gene1; g2<-gg2$gene1 mask<-0.5>runif(rep(1, length(n1))) n1[mask]<-g2[mask] # Tests on equality? ng1$evaluated<-FALSE ng1$gene1<-n1 return(list(ng1)) } #' Parameterized uniform crossover of 2 genes. #' #' @description \code{xegaGaUPCrossGene} swaps alleles of both genes #' with a probability of \code{lF$UCrossSwap}. #' It generates a random #' mask which is used to build the new gene. #' #' @references #' Spears William and De Jong, Kenneth (1991): #' On the Virtues of Parametrized Uniform Crossover. #' In: Belew, Richar K. and Booker, Lashon B. (Ed.) #' Proceedings of the Fourth International Conference on Genetic Algorithms, #' Morgan Kaufmann Publishers, Los Altos, California, pp. 230-236. #' (ISBN:1-55860-208-9) #' #' @param gg1 A binary gene. #' @param gg2 A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of one binary gene. #' #' @family Crossover (1) #' #' @examples #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene2, lFxegaGaGene) #' gene3<-xegaGaUPCrossGene(gene1, gene2, lFxegaGaGene) #' xegaGaDecodeGene(gene3[[1]], lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaUPCrossGene<-function(gg1, gg2, lF) { ng1<-gg1; ng2<-gg2 n1<-gg1$gene1; g2<-gg2$gene1 mask<-lF$UCrossSwap()>runif(rep(1, length(n1))) n1[mask]<-g2[mask] # Tests on equality? ng1$evaluated<-FALSE ng1$gene1<-n1 return(list(ng1)) } #' Configure the crossover function of a genetic algorithm. #' #' @description \code{xegaGaCrossoverFactory} implements the selection #' of one of the crossover functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item Crossover functions with two kids: #' \enumerate{ #' \item "Cross2Gene" returns \code{xegaGaCross2Gene}. #' \item "UCross2Gene" returns \code{xegaGaUCross2Gene}. #' \item "PUCross2Gene" returns \code{xegaGaUPCross2Gene}. #' } #' \item Crossover functions with one kid: #' \enumerate{ #' \item "CrossGene" returns \code{xegaGaCrossGene}. #' \item "UCrossGene" returns \code{xegaGaUCrossGene}. #' \item "PUCrossGene" returns \code{xegaGaUPCrossGene}. #' } #' } #' #' @param method A string specifying the crossover function. #' #' @return A crossover function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaGaCrossoverFactory("Cross2Gene") #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene2<-xegaGaInitGene(lFxegaGaGene) #' XGene(gene1, gene2, lFxegaGaGene) #' @export xegaGaCrossoverFactory<-function(method="Cross2Gene") { if (method=="Cross2Gene") {f<- xegaGaCross2Gene} if (method=="UCross2Gene") {f<- xegaGaUCross2Gene} if (method=="UPCross2Gene") {f<- xegaGaUPCross2Gene} if (method=="CrossGene") {f<- xegaGaCrossGene} if (method=="UCrossGene") {f<- xegaGaUCrossGene} if (method=="UPCrossGene") {f<- xegaGaUPCrossGene} if (!exists("f", inherits=FALSE)) {stop("sga Crossover label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaCrossover.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGaGene # # # TODO: Bin2IEEE754 # See Goldberg, 1991, CSUR, # What Every Computer Scientist Should Know About Floating-point Arithmetic # IEEE 754 Standard. # 1 bit: Sign # m bit: Mantissa # r bit: Exponent # # b: Base 2 or 10 # Bias: 2^r-1-1 (for unsigned exponents. # #' Map the bit strings of a binary gene to an identical bit vector. #' #' @description \code{xegaGaGenemapIdentity} maps the bit strings #' of a binary vector #' to an identical binary vector. #' Faster for all problems with single-bit coding. #' Examples: Knapsack, Number Partitioning into 2 partitions. #' #' @param gene A binary gene (the genotype). #' @param penv A problem environment. #' #' @return The decoded gene (the phenotype). #' #' @family Decoder #' #' @examples #' gene<-xegaGaInitGene(lFxegaGaGene) #' xegaGaGeneMapIdentity(gene$gene1, lFxegaGaGene$penv) #' #' @export xegaGaGeneMapIdentity<-function(gene, penv) { return(gene) } #' Map the bit strings of a binary gene to parameters in an interval. #' #' @description \code{xegaGaGenemap} maps the bit strings of a binary string #' to parameters in an interval. #' Bit vectors are mapped into equispaced numbers in the interval. #' Examples: Optimization of problems with real-valued #' parameter vectors. #' #' @param gene A binary gene (the genotype). #' @param penv A problem environment. #' #' @return The decoded gene (the phenotype). #' #' @family Decoder #' #' @examples #' gene<-xegaGaInitGene(lFxegaGaGene) #' xegaGaGeneMap(gene$gene1, lFxegaGaGene$penv) #' #' @export xegaGaGeneMap<-function(gene, penv) { nparm<-length(penv$bitlength()) parm<-rep(0, nparm) s<-1 for (i in 1:nparm) { bv<-gene[s:(s-1+penv$bitlength()[i])] s<-s+penv$bitlength()[i] parm[i]<-penv$lb()[i]+(penv$ub()[i]-penv$lb()[i])* (sum(bv*2^((length(bv)-1):0))/(2^length(bv)-1)) } return(parm) } #' Map Gray code to binary. #' #' @details Start with the highest order bit, and #' \code{r[k-i]<- xor(n[k], n[k-1])}. #' #' @param x Gray code (boolean vector). #' #' @return Binary code (boolean vector). #' #' @references #' Gray, Frank (1953): #' Pulse Code Communication. US Patent 2 632 058. #' #'@examples #' Gray2Bin(c(1, 0, 0, 0)) #' Gray2Bin(c(1, 1, 1, 1)) #'@export Gray2Bin<-function(x) { r<-rep(0, length(x)) r[1]<-x[1] for (i in 2:length(x)) {r[i]<-xor(r[i-1], x[i])} return(r) } #' Map the bit strings of a gray-coded gene to parameters in an interval. #' #' @description \code{xegaGaGenemapGray} maps the bit strings of #' a binary string #' interpreted as Gray codes to parameters in an interval. #' Bit vectors are mapped into equispaced numbers in the interval. #' Examples: Optimization of problems with real-valued #' parameter vectors. #' #' #' @param gene A binary gene (the genotype). #' @param penv A problem environment. #' #' @return The decoded gene (the phenotype). #' #' @family Decoder #' #' @examples #' gene<-xegaGaInitGene(lFxegaGaGene) #' xegaGaGeneMapGray(gene$gene1, lFxegaGaGene$penv) #' #' @export xegaGaGeneMapGray<-function(gene, penv) { nparm<-length(penv$bitlength()) parm<-rep(0, nparm) s<-1 for (i in 1:nparm) { bv<-Gray2Bin(gene[s:(s-1+penv$bitlength()[i])]) s<-s+penv$bitlength()[i] parm[i]<-penv$lb()[i]+(penv$ub()[i]-penv$lb()[i])* (sum(bv*2^((length(bv)-1):0))/(2^length(bv)-1)) } return(parm) } #' Returns elements of #' vector \code{x} without elements in \code{y}. #' #' @param x A vector. #' @param y A vector. #' #' @return A vector. #' #' @family Utility #' #' @examples #' a<-sample(1:15,15, replace=FALSE) #' b<-c(1, 3, 5) #' without(a, b) #' @export without<-function(x, y) { x[!unlist(lapply(x, function(z) is.element(z, y)))] } #' Map the bit strings of a binary gene to a permutation. #' #' @description \code{xegaGaGeneMapPerm} maps the bit strings of a binary string #' to a permutation of integers. #' Example: Traveling Salesman Problem (TSP). #' #' @param gene A binary gene (the genotype). #' @param penv A problem environment. #' #' @return A permutation (the decoded gene (the phenotype)) #' #' @family Decoder #' #' @examples #' gene<-xegaGaInitGene(lFxegaGaGene) #' xegaGaGeneMapPerm(gene$gene1, lFxegaGaGene$penv) #' #' @export xegaGaGeneMapPerm<-function(gene, penv) { nparm<-length(penv$bitlength()) p<-1:nparm parm<-rep(0, nparm) s<-1 for (i in 1:nparm) { bv<-gene[s:(s-1+penv$bitlength()[i])] s<-s+penv$bitlength()[i] parm[i]<-p[(sum(bv*2^((length(bv)-1):0))%%(nparm+1-i))+1] p<-without(p, parm[i]) } return(parm) } #' Configure the gene map function of a genetic algorithm. #' #' @description \code{xegaGaGeneMapFactory} implements the selection #' of one of the GeneMap functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Bin2Dec" returns \code{GeneMap}. (Default). #' \item "Gray2Dec" returns \code{GeneMapGray}. #' \item "Identity" returns \code{GeneMapIdentity}. #' \item "Permutation" returns \code{GeneMapPerm}. #' } #' #' @param method A string specifying the GeneMap function. #' #' @return A gene map function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaGaGeneMapFactory("Identity") #' gene1<-xegaGaInitGene(lFxegaGaGene) #' XGene(gene1, lFxegaGaGene$penv) #' @export xegaGaGeneMapFactory<-function(method="Bin2Dec") { if (method=="Bin2Dec") {f<-xegaGaGeneMap} if (method=="Gray2Dec") {f<-xegaGaGeneMapGray} if (method=="Identity") {f<-xegaGaGeneMapIdentity} if (method=="Permutation") {f<-xegaGaGeneMapPerm} if (!exists("f", inherits=FALSE)) {stop("sga GeneMap label ", method, " does not exist")} return(f) } #' Decode a gene. #' #' @description \code{xegaGaDecodeGene} decodes a binary gene. #' #' @param gene A binary gene (the genotype). #' @param lF The local configuration of the genetic algorithm. #' #' @return The decoded gene (the phenotype). #' #' @family Decoder #' #' @examples #' gene<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene, lFxegaGaGene) #' #' @export xegaGaDecodeGene<-function(gene, lF) { lF$GeneMap(gene$gene1, lF$penv) }
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaDecode.R
#' Genetic operations for binary coded genetic algorithms. #' #' For an introduction to this class of algorithms, see Goldberg, D. (1989). #' #' For binary-coded genes, the \code{xegaGaGene} package provides #' \itemize{ #' \item Gene initiatilization. #' \item Decoding of parameters as well as a function factory for configuration. #' \item Mutation functions as well as a function factory for configuration. #' \item Crossover functions as well as a function factory for configuration. #' We provide two families of crossover functions: #' \enumerate{ #' \item Crossover functions with two kids: #' Crossover preserves the genetic information in the gene pool. #' \item Crossover functions with one kid: #' These functions allow the construction of gene evaluation pipelines. #' One advantage of this is a simple control structure #' at the population level. #' \item Gene replication functions as well as a function factory for #' configuration. The replication functions implement control flows #' for sequences of gene operations. For \code{xegaReplicateGene}, #' an acceptance step has been added. Simulated annealing algorithms #' can be configured e.g. by configuring uniform random selection combined #' with a Metropolis Acceptance Rule and a suitable cooling schedule. #' } #' } #' #' @section Binary Gene Representation: #' #' A binary gene is a named list: #' \itemize{ #' \item $gene1 the gene must be a binary vector. #' \item $fit the fitness value of the gene #' (for EvalGeneDet and EvalGeneU) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch). #' \item $evaluated has the gene been evaluated? #' \item $evalFail has the evaluation of the gene failed? #' \item $var the cumulative variance of the fitness #' of all evaluations of a gene. #' (For stochastic functions) #' \item $sigma the standard deviation of the fitness of #' all evaluations of a gene. #' (For stochastic functions) #' \item $obs the number of evaluations of a gene. #' (For stochastic functions) #' } #' #' @section Abstract Interface of Problem Environment: #' #' A problem environment \code{penv} must provide: #' \itemize{ #' \item \code{$f(parameters, gene, lF)}: #' Function with a real parameter vector as first argument #' which returns a gene #' with evaluated fitness. #' #' \item $genelength(): The number of bits of the binary-coded #' real parameter vector. Used in \code{InitGene}. #' \item $bitlength(): A vector specifying the number of bits #' used for coding each real parameter. #' If \code{penv$bitlength()[1]} is \code{20}, #' then \code{parameters[1]} is coded by 20 bits. #' Used in \code{GeneMap}. #' \item $lb(): The lower bound vector of each parameter. #' Used in \code{GeneMap}. #' \item $ub(): The upper bound vector of each parameter. #' Used in \code{GeneMap}. #' } #' #' @section Abstract Interface of Mutation Functions: #' #' Each mutation function has the following function signature: #' #' newGene<-Mutate(gene, lF) #' #' All local parameters of the mutation function configured are #' expected in the local function list lF. #' #' @section Local Constants of Mutation Functions: #' #' The local constants of a mutation function determine #' the behavior of the function. #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$BitMutationRate1 \tab 0.005 \tab MutateGene \cr #' \tab \tab IVAdaptiveMutateGene \cr #' lF$BitMutationRate2 \tab 0.01 \tab IVAdaptiveMutateGene \cr #' lF$CutoffFit \tab 0.5 \tab IVADaptiveMutateGene \cr #' } #' #' @section Abstract Interface of Crossover Functions: #' #' The signatures of the abstract interface to the 2 families #' of crossover functions are: #' #' ListOfTwoGenes<-Crossover2(gene1, gene2, lF) #' #' ListOfOneGene<-Crossover(gene1, gene2, lF) #' #' All local parameters of the crossover function configured are #' expected in the local function list lF. #' #' @section Local Constants of Crossover Functions: #' #' The local constants of a crossover function determine the #' the behavior of the function. #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$UCrossSwap \tab 0.2 \tab UPCross2Gene \cr #' \tab \tab UPCrossGene \cr #' } #' #' @section Abstract Interface of Gene Replication Functions: #' #' The signatures of the abstract interface to the 2 #' gene replication functions are: #' #' ListOfTwoGenes<-Replicate2Gene(gene1, gene2, lF) #' #' ListOfOneGene<-ReplicateGene(gene1, gene2, lF) #' #' @section Configuration and Constants of Replication Functions: #' #' \strong{Configuration for ReplicateGene (1 Kid, Default).} #' #' \tabular{rcl}{ #' \strong{Function} \tab \strong{Default} \tab Configured By \cr #' lF$SelectGene \tab SelectSUS \tab SelectGeneFactory \cr #' lF$SelectMate \tab SelectSUS \tab SelectGeneFactory \cr #' lF$CrossGene \tab CrossGene \tab xegaGaCrossoverFactory \cr #' lF$MutateGene \tab MutateGene \tab xegaGaMutationFactory \cr #' lF$Accept \tab AcceptNewGene \tab AcceptFactory \cr #' } #' #' \strong{Configuration for Replicate2Gene (2 Kids).} #' #' \tabular{rcl}{ #' \strong{Function} \tab \strong{Default} \tab Configured By \cr #' lF$SelectGene \tab SelectSUS \tab SelectGeneFactory \cr #' lF$SelectMate \tab SelectSUS \tab SelectGeneFactory \cr #' lF$CrossGene \tab CrossGene \tab xegaGaCrossoverFactory \cr #' lF$MutateGene \tab MutateGene \tab xegaGaMutationFactory \cr #' } #' #' \strong{Global Constants.} #' #' Global constants specify the probability that a mutation or #' crossover operator is applied to a gene. #' In the xega-architecture, these rates can be configured to be #' adaptive. #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$MutationRate \tab 1.0 (static) \tab xegaGaReplicateGene \cr #' \tab \tab xegaGaReplicate2Gene \cr #' lF$CrossRate \tab 0.2 (static) \tab xegaGaReplicateGene \cr #' \tab \tab xegaGaReplicate2Gene \cr #' } #' #' \strong{Local Constants.} #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$BitMutationRate1 \tab 0.005 \tab MutateGene \cr #' \tab \tab IVAdaptiveMutateGene \cr #' lF$BitMutationRate2 \tab 0.01 \tab IVAdaptiveMutateGene \cr #' lF$CutoffFit \tab 0.5 \tab IVADaptiveMutateGene \cr #' lF$UCrossSwap \tab 0.2 \tab UPCross2Gene \cr #' \tab \tab UPCrossGene \cr #' } #' #' In the xega-architecture, these rates can be configured to be #' adaptive. #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation-free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population-related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split into a representation-independent and #' a representation-dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation-free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler, and #' \code{xegaDerivationTrees} is an abstract data type for derivation trees. #' }} #' #' @references #' Goldberg, David E. (1989) #' Genetic Algorithms in Search, Optimization and Machine Learning. #' Addison-Wesley, Reading. #' (ISBN:0-201-15767-5) #' #' @family Package Description #' #' @name xegaGaGene #' @aliases xegaGaGene #' @docType package #' @title Package xegaGaGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaGaGene> #' @section Installation: From CRAN by \code{install.packages('xegaGaGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaGene-package.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGaGene # #' Generate a random binary gene. #' #' @description \code{xegaGaInitGene} generates a random binary gene #' with a given length. #' #' @param lF The local configuration of the genetic algorithm. #' #' @return A binary gene (a named list): #' \itemize{ #' \item \code{$evaluated}: FALSE. See package \code{xegaEvalGene} #' \item \code{$evalFail}: FALSE. Set by the error handler(s) #' in package \code{xegaEvalGene} #' in the case of failure. #' \item \code{$fit}: the fitness #' \item \code{$gene1}: a binary gene #' } #' #' @family Gene Generation. #' #' @examples #' xegaGaInitGene(lFxegaGaGene) #' #' @export xegaGaInitGene<-function(lF) {gene1<-sample(0:1, lF$penv$genelength(), replace=TRUE) return(list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=gene1)) }
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaInitGene.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGaGene # #' Mutate a gene. #' #' @description \code{xegaGaMutateGene} mutates a binary gene. #' The per-bit mutation rate is given by MutationRate(). #' #' @param gene A binary gene. #' @param lF The local configuration of the genetic algorithm #' #' @return A binary gene. #' #' @family Mutation #' #' @examples #' parm<-function(x) {function() {return(x)}} #' lFxegaGaGene$BitMutationRate1<-parm(1.0) #' gene1<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' lFxegaGaGene$BitMutationRate1() #' gene<-xegaGaMutateGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene, lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaMutateGene<-function(gene, lF) { ng<-gene gene1<-gene$gene1 ng$gene1<-1*xor(gene1,stats::runif(length(gene1), 0, 1)<lF$BitMutationRate1()) if ((ng$evaluated==TRUE) && all(gene1==ng$gene1)) {ng$evaluated<-TRUE} else {ng$evaluated<-FALSE} return(ng) } #' Individually variable adaptive mutation of a gene. #' #' @description \code{xegaGaIVAdaptiveMutateGene} mutates a binary gene. #' Two mutation rates (\code{lF$MutationRate()} #' and \code{lF$MutationRate2()} which is higher than the first) #' are used depending on the relative fitness of the gene. #' \code{lF$CutoffFit} and \code{lF$CBestFitness} are used #' to determine the relative fitness of the gene. #' The rationale is that mutating genes having a low fitness #' with a higher probability rate improves the performance #' of a genetic algorithm, because the gene gets a higher #' chance to improve. #' #' @details This principle is a candidate for a more abstract implementation, #' because it applies to all variants of evolutionary algorithms. #' #' The goal is to separate the threshold code and the #' representation-dependent part and #' to combine them in the factory properly. #' #' @references #' Stanhope, Stephen A. and Daida, Jason M. (1996) #' An Individually Variable Mutation-rate Strategy for Genetic Algorithms. #' In: Koza, John (Ed.) #' Late Breaking Papers at the Genetic Programming 1996 Conference. #' Stanford University Bookstore, Stanford, pp. 177-185. #' (ISBN:0-18-201-031-7) #' #' @param gene A binary gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A binary gene #' #' @family Mutation #' #' @examples #' parm<-function(x) {function() {return(x)}} #' lFxegaGaGene$BitMutationRate1<-parm(1.0) #' lFxegaGaGene$BitMutationRate2<-parm(0.5) #' gene1<-xegaGaInitGene(lFxegaGaGene) #' xegaGaDecodeGene(gene1, lFxegaGaGene) #' gene<-xegaGaIVAdaptiveMutateGene(gene1, lFxegaGaGene) #' xegaGaDecodeGene(gene, lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaIVAdaptiveMutateGene<-function(gene, lF) { ng<-gene gene1<-gene$gene1 f<-gene$fit ### A threshold based rate adaptation function. if (f>(lF$CutoffFit()*lF$CBestFitness())) {MutRate<-lF$BitMutationRate1()} else {MutRate<-lF$BitMutationRate2()} ### ng$gene1<-1*xor(gene1, stats::runif(length(gene1), 0, 1)<MutRate) if ((ng$evaluated==TRUE) && all(gene1==ng$gene1)) {ng$evaluated<-TRUE} else {ng$evaluated<-FALSE} return(ng) } #' Configure the mutation function of a genetic algorithm. #' #' @description \code{xegaGaMutationFactory} implements the selection #' of one of the mutation functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "MutateGene" returns \code{xegaGaMutateGene}. #' \item "IVMGene" returns \code{xegaGaIVAdaptiveMutateGene}. #' } #' #' @param method A string specifying the mutation function. #' #' @return A mutation function for genes. #' #' @family Configuration #' #' @examples #' parm<-function(x) {function() {return(x)}} #' lFxegaGaGene$BitMutationRate1<-parm(1.0) #' Mutate<-xegaGaMutationFactory("MutateGene") #' gene1<-xegaGaInitGene(lFxegaGaGene) #' gene1 #' Mutate(gene1, lFxegaGaGene) #' @export xegaGaMutationFactory<-function(method="MutateGene") { if (method=="MutateGene") {f<- xegaGaMutateGene} if (method=="IVM") {f<- xegaGaIVAdaptiveMutateGene} if (!exists("f", inherits=FALSE)) {stop("sga Mutation label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaMutate.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene/Population-level functions. # Independent of gene representation. # The replication mechanism and its variants # Package: xegaGaGene # #' Replicates a gene. #' #' @description \code{xegaGaReplicate2Gene} replicates a gene #' by applying a gene reproduction pipeline #' which uses crossover and #' mutation. The control flow is as follows: #' \itemize{ #' \item A gene is selected from the population. #' Check if the crossover operation should be applied. #' (The check is \code{TRUE} with a probability of \code{crossrate}). #' If the check is \code{TRUE}: #' \itemize{ #' \item Select a mating gene from the population. #' \item Perform the crossover operation. #' \item Apply mutation with a probability of \code{mutrate}. #' \item Return a list with both genes. #' } #' \item Apply mutation with a probability of \code{mutrate}. #' \item Return a list with a single gene. #' } #' #' @param pop A population of binary genes. #' @param fit Fitness vector. #' @param lF The local configuration of the genetic algorithm. #' #' @return A list of either 1 or 2 binary genes. #' #' @family Replication #' #' @examples #' lFxegaGaGene$CrossGene<-xegaGaCross2Gene #' lFxegaGaGene$MutationRate<-function(fit, lF) {0.001} #' names(lFxegaGaGene) #' pop10<-lapply(rep(0,10), function(x) xegaGaInitGene(lFxegaGaGene)) #' epop10<-lapply(pop10, lFxegaGaGene$EvalGene, lF=lFxegaGaGene) #' fit10<-unlist(lapply(epop10, function(x) {x$fit})) #' newgenes<-xegaGaReplicate2Gene(pop10, fit10, lFxegaGaGene) #' #' @importFrom stats runif #' @export xegaGaReplicate2Gene<- function(pop, fit, lF) { g<-pop[[lF$SelectGene(fit, lF)]] mut<-runif(1)<lF$MutationRate(g$fit, lF) cross<-runif(1)<lF$CrossRate(g$fit, lF) if (cross && mut) { return(lapply(lF$CrossGene(g, pop[[lF$SelectMate(fit, lF)]], lF), lF$MutateGene, lF=lF))} if ((cross) && (!mut)) { return(lF$CrossGene(g, pop[[lF$SelectMate(fit, lF)]], lF)) } if ((!cross) && (mut)) { return(list(lF$MutateGene(g, lF))) } return(list(g)) } #' Replicates a gene. #' #' @description \code{xegaGaReplicateGene} replicates a gene #' by applying a gene reproduction pipeline #' which uses crossover and #' mutation. #' The control flow may have the following steps: #' \itemize{ #' \item A gene is selected from the population. #' Check if the crossover operation should be applied. #' (The check is \code{TRUE} with a probability of \code{crossrate}). #' If the check is \code{TRUE}: #' \itemize{ #' \item Select a mating gene from the population. #' \item Perform the crossover operation. #' \item Apply mutation with a probability of \code{mutrate}. #' \item Return a list one gene. #' } #' \item Apply mutation with a probability of \code{mutrate}. #' \item Accept gene. For genetic algorithms: Identity. #' \item Return a list with a single gene. #' } #' #' @details \code{xegaGaReplicateGene} implements the control flow #' by a dynamic definition of the operator pipeline depending #' on the random choices for mutation and crossover: #' \enumerate{ #' \item A gene \code{g} is selected and the boolean variables \code{mut} #' and \code{cross} are set to \code{runif(1)<rate}. #' \item The local function for the operator pipeline \code{OPpip(g, lF)} #' is defined by the truth values of \code{cross} and \code{mut}: #' \enumerate{ #' \item \code{(cross==FALSE) & (mut==FALSE)}: #' Identity function. #' \item \code{(cross==TRUE) & (mut==TRUE)}: #' Mate selection, crossover, mutation. #' \item \code{(cross==TRUE) & (mut==FALSE)}: #' Mate selection, crossover. #' \item \code{(cross==FALSE) & (mut==TRUE)}: #' Mutation. #' } #' \item Perform the operator pipeline and accept the result. #' } #' #' @param pop Population of binary genes. #' @param fit Fitness vector. #' @param lF Local configuration of the genetic algorithm. #' #' @return A list of one gene. #' #' @family Replication #' #' @examples #' lFxegaGaGene$CrossGene<-xegaGaCrossGene #' lFxegaGaGene$MutationRate<-function(fit, lF) {0.001} #' lFxegaGaGene$Accept<-function(OperatorPipeline, gene, lF) {gene} #' pop10<-lapply(rep(0,10), function(x) xegaGaInitGene(lFxegaGaGene)) #' epop10<-lapply(pop10, lFxegaGaGene$EvalGene, lF=lFxegaGaGene) #' fit10<-unlist(lapply(epop10, function(x) {x$fit})) #' newgenes<-xegaGaReplicateGene(pop10, fit10, lFxegaGaGene) #' @importFrom stats runif #' @export xegaGaReplicateGene<- function(pop, fit, lF) { g<-pop[[lF$SelectGene(fit, lF)]] mut<-runif(1)<lF$MutationRate(g$fit, lF) cross<-runif(1)<lF$CrossRate(g$fit, lF) OPpip<-function(g, lF) {g} if (cross && mut) {OPpip<-function(g, lF) { g1<-lF$CrossGene(g, pop[[lF$SelectMate(fit, lF)]], lF) lF$MutateGene(g1[[1]], lF) }} if ((cross) && (!mut)) {OPpip<-function(g, lF) { lF$CrossGene(g, pop[[lF$SelectMate(fit, lF)]], lF)[[1]]}} if ((!cross) && (mut)) {OPpip<-function(g, lF) { lF$MutateGene(g, lF)}} return(list(lF$Accept(OPpip, g, lF))) } #' Configure the replication function of a genetic algorithm. #' #' @description \code{ReplicationFactory} implements the selection #' of a replication method. #' #' Current support: #' #' \enumerate{ #' \item "Kid1" returns \code{ReplicateGene}. #' \item "Kid2" returns \code{Replicate2Gene}. #' } #' #' @param method A string specifying the replication function. #' #' @return A replication function for genes. #' #' @family Configuration #' #' @examples #' lFxegaGaGene$CrossGene<-xegaGaCrossGene #' lFxegaGaGene$MutationRate<-function(fit, lF) {0.001} #' lFxegaGaGene$Accept<-function(OperatorPipeline, gene, lF) {gene} #' Replicate<-xegaGaReplicationFactory("Kid1") #' pop10<-lapply(rep(0,10), function(x) xegaGaInitGene(lFxegaGaGene)) #' epop10<-lapply(pop10, lFxegaGaGene$EvalGene, lF=lFxegaGaGene) #' fit10<-unlist(lapply(epop10, function(x) {x$fit})) #' newgenes1<-Replicate(pop10, fit10, lFxegaGaGene) #' lFxegaGaGene$CrossGene<-xegaGaCross2Gene #' Replicate<-xegaGaReplicationFactory("Kid2") #' newgenes2<-Replicate(pop10, fit10, lFxegaGaGene) #' @export xegaGaReplicationFactory<-function(method="Kid1") { if (method=="Kid1") {f<- xegaGaReplicateGene} if (method=="Kid2") {f<- xegaGaReplicate2Gene} if (!exists("f", inherits=FALSE)) {stop("xegaGaGene Replication label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGaReplicate.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGaGene # #' The local function list lFxegaGaGene. #' #' @description #' We enhance the configurability of our code by introducing #' a function factory. The function factory contains #' all the functions that are needed for defining #' local functions in genetic operators. The local function #' list keeps the signatures of functions (e.g. mutation functions) #' uniform and small. At the same time, variants of functions #' can use different local functions. #' #' @details #' We use the local function list for #' \enumerate{ #' \item #' replacing all constants by constant functions. #' #' Rationale: We need one formal argument (the local function list lF) #' and we can dispatch multiple functions. E.g. \code{lF$verbose()} #' \item #' dynamically binding a local function with a definition from a #' proper function factory. E.g., the selection methods #' \code{lf$SelectGene} and \code{SelectMate}. #' #' \item gene representations which require special functions to handle them: #' \code{lf$InitGene}, \code{lF$DecodeGene}, \code{lf$EvalGene} #' \code{lf$ReplicateGene}, ... #' #' } #' #' @family Configuration #' #' @importFrom xegaSelectGene Parabola2DFactory #' @importFrom xegaSelectGene SelectGeneFactory #' @importFrom xegaSelectGene parm #' @importFrom xegaSelectGene EvalGeneFactory #' @export lFxegaGaGene<-list( penv=xegaSelectGene::Parabola2DFactory(), replay=xegaSelectGene::parm(0), verbose=xegaSelectGene::parm(4), CutoffFit=xegaSelectGene::parm(0.5), CBestFitness=xegaSelectGene::parm(100), CWorstFitness=xegaSelectGene::parm(-100), MutationRate1=xegaSelectGene::parm(0.01), MutationRate2=xegaSelectGene::parm(0.20), BitMutationRate1=xegaSelectGene::parm(0.01), BitMutationRate2=xegaSelectGene::parm(0.20), MutateGene=xegaGaMutationFactory(), CrossRate=function(fit, lF) {0.5}, UCrossSwap=xegaSelectGene::parm(0.2), CrossGene=xegaGaCrossoverFactory(), Max=xegaSelectGene::parm(1), Offset=xegaSelectGene::parm(1), Eps=xegaSelectGene::parm(0.01), Elitist=xegaSelectGene::parm(TRUE), TournamentSize=xegaSelectGene::parm(2), GeneMap=xegaGaGeneMapFactory(method="Bin2Dec"), SelectGene=xegaSelectGene::SelectGeneFactory(method="Proportional"), SelectMate=xegaSelectGene::SelectGeneFactory(method="Uniform"), InitGene=xegaGaInitGene, DecodeGene=xegaGaDecodeGene, EvalGene=xegaSelectGene::EvalGeneFactory(method="EvalGeneU"), SelectionContinuation=xegaSelectGene::parm(TRUE), Verbose=xegaSelectGene::parm(4), lapply=base::lapply )
/scratch/gouwar.j/cran-all/cranData/xegaGaGene/R/xegaGalF.R
# # (c) 2024 Andreas Geyer-Schulz # # Layer: Gene Layer # Package: xegaGeGene # # # Methods for setting the codon precision in # grammatical evolution. # #' Computes the largest least common multiple of all prime factors #' of the integers in the interval \code{1:m} for k-bit integers. #' #' @description For 64 bit numbers, numerically stable up to \code{m==42}. #' The modulo rule in grammatical evolution assigns to the choices #' of substitutions for a non-terminal slightly (biased) probabilities. #' For an integer coding, the least common multiple of all rule choices #' from no choice (1) to the maximal number of substitutions of a non-terminal #' removes this bias completely. However, whenever the prime factors of the #' least common multiple contain a prime different from \code{2}, #' the bias cannot be removed completely for a binary gene coding. #' However, each additional bit used for coding approximately halves the bias. #' #' @details This could be done with the help of #' the function mLCM of the R-package \code{numbers}. #' We implement this by enumerating the vector of prime factors #' in \code{1:42}. #' #' @param k Number of bits. #' #' @return A list of three elements: #' \itemize{ #' \item \code{$k}: The number of bits. #' \item \code{$m}: Maximal number of substitutions for a non-terminal symbol #' in a grammar. #' \item \code{$mLCM}: Least common multiple of the prime factors of #' all rule choices from 1 to \code{$m}. #' } #' #' @family Diagnostics #' #' @examples #' tLCM(8) #' tLCM(16) #' tLCM(32) #' @export tLCM<-function(k) { pfv<-rep(1, 42) pfv[2]<-2; pfv[3]<-3; pfv[4]<-2; pfv[5]<-5; pfv[7]<-7; pfv[8]<-2; pfv[9]<-3 pfv[11]<-11; pfv[13]<-13; pfv[16]<-2; pfv[17]<-17; pfv[19]<-19 pfv[23]<-23; pfv[25]<-5; pfv[27]<-3; pfv[29]<-29 pfv[31]<-31; pfv[32]<-2; pfv[37]<-37; pfv[41]<-41 cpfv<-cumprod(pfv) if (!k %in% (1:64)) {stop("xegaGeGene::tLCM argument k=", k, " must be an integer in 1:64")} b<-cpfv<2^k return(list(k=k, m=sum(b), mLCM=cpfv[sum(b)])) } #' Choice vector of a grammar. #' #' @param LHS Vector of Integers. #' The left-hand side \code{G$LHS} of a grammar object \code{G}. #' #' @return Vector of the number of choices for non-terminal symbols. #' #' @family Utility #' #' @examples #' NT<-sample(5, 50, replace=TRUE) #' ChoiceVector(NT) #' @export ChoiceVector<-function(LHS) {unique(colSums(outer(LHS, unique(LHS), FUN="==")))} #' Minimal precision of codon. #' #' @description The minimal precision of the codon needed for generating a working #' decoder for a context-free grammar \code{G}. However, the decoder #' has some choice bias which reduces the efficiency of grammar evolution. #' #' @param LHS Vector of Integers. The left-hand side of a grammar object \code{G}. #' @param ... Unused. Needed for common abstract interface of #' precision functions. #' #' @return Integer. The Precision of a codon whose upper bound is the least power of 2 #' above the maximum number of rules for a non-terminal of a grammar. #' #' @family Precision #' #' @examples #' NT<-sample(5, 50, replace=TRUE) #' MinCodonPrecision(NT) #' @export MinCodonPrecision<-function(LHS, ...) {ceiling(log(max(ChoiceVector(LHS)),2))} #' Compute the mLCM of the vector of the number of production rules #' in a production table. #' #' @description Compute the least common multiple of the prime factors #' of the vector of the number of rules applicable for each #' non-terminal symbol. #' #' @details For removing the bias of the modulo rule in #' grammatical evolution, see Keijzer, M., O'Neill, M., #' Ryan, C. and Cattolico, M. (2002). #' This version works for integer genes coded in the #' domain \code{1:mlCM} without bias in choosing a rule. #' See Keijzer et al. (2002). #' However, if the mLCM and \code{2^k} are relative prime, it is impossible #' to find an unbiased binary coding. #' The choice bias is considerable lower than for \code{MinCodonPrecision()}. #' #' @references Keijzer, M., O'Neill, M., Ryan, C. and Cattolico, M. (2002) #' Grammatical Evolution Rules: The Mod and the Bucket Rule, #' pp. 123-130. #' In: Foster, J. A., Lutton, E., Miller, J., Ryan, C. and #' Tettamanzi, A. (Eds.): Genetic Programming. #' Lecture Notes in Computer Science, Vol.2278, #' Springer, Heidelberg. #' <doi:10.1007/3-540-45984-7_12> #' #' @param LHS Vector of integers. The left-hand side of a grammar object \code{G}. #' #' @return Integer. The least common multiple of the vector of the available #' rules for each non-terminal. #' #' @family Utility #' #' @examples #' library(xegaBNF) #' g<-compileBNF(booleanGrammar()) #' mLCMG(g$PT$LHS) #' @importFrom numbers mLCM #' @export mLCMG<-function(LHS) {numbers::mLCM(ChoiceVector(LHS))} #' mLCMG precision of codon. #' #' @param LHS Vector of Integers. The left-hand side of a grammar object \code{G}. #' @param ... Unused. Needed for common abstract interface of #' precision functions. #' #' @return Integer. The precision of a codon whose upper bound is larger than #' least common multiple of the prime factors of the #' vector of the available rules #' for each non-terminal of a grammar. #' #' @family Precision #' #' @examples #' NT<-sample(5, 50, replace=TRUE) #' mLCMGCodonPrecision(NT) #' @export mLCMGCodonPrecision<-function(LHS, ...) {ceiling(log(mLCMG(LHS),2))} #' Biases in Rule Choice. #' #' @description Measures the biases in rule choice for each non-terminal. #' Statistics computed: #' \itemize{ #' \item dP: Difference in probability #' between random choice with equal #' probability and modulo rule with a codon #' \code{precision}. #' \item dH: Difference in entropy #' between random choice with equal #' probability and modulo rule with a codon #' \code{precision}. #' } #' #' @param cv Choice vector of grammar. #' @param precision Number of bits of codon. #' #' @return Data frame with the following columns #' \itemize{ #' \item \code{$precision}: Number of bits. #' \item \code{$cv}: i-th element of choice vector. #' \item \code{$dp}: Deviation from choice with equal probability for \code{$precision}. #' \item \code{$dH}: Entropy difference between choice with equal probability #' and biased choice for \code{$precision}. #' } #' #' @family Diagnostics #' #' @examples #' CodonChoiceBiases(c(1, 2, 3, 5), 3) #' CodonChoiceBiases(c(1, 2, 3, 5), 5) #' @export CodonChoiceBiases<-function(cv,precision) { df<-data.frame() entropy<-function(p) {sum(-p*log(p, 2))} for (i in (1:length(cv))) { r<-(2^precision)/cv[i] ub<-(2^precision) %% cv[i] lb<-cv[i]-ub l<-floor(r) h<-ceiling(r) d<-c(rep(l, lb), rep(h, ub)) diff<-length(d)-max(ub, lb) u<-rep(1, cv[i])/cv[i] p<-d/sum(d) dp<-sum(abs(u-p)) dH<-entropy(u)-entropy(p) df<-rbind(df, c(precision, cv[i], dp, dH)) } colNames<-c("Bits", "Choices", "dP", "dh") colnames(df)<-colNames return(df) } #' Biases in Rule Choice (Deprecated) #' #' @description See \code{CodonChoiceBiases}. #' The use of the outer product leads to memory problems for #' \code{precision>31} and becomes slow for \code{precision>24}. #' #' @param cv Choice vector of grammar. #' @param precision Number of bits of codon. #' #' @return Data frame with the following columns #' \itemize{ #' \item \code{$precision}: Number of bits. #' \item \code{$cv}: i-th element of choice vector. #' \item \code{$dp}: Deviation from choice with equal probability for \code{$precision}. #' \item \code{$dH}: Entropy difference between choice with equal probability #' and biased choice for \code{$precision}. #' } #' #' @family Diagnostics #' #' @examples #' CodonChoiceBiasesDeprecated(c(1, 2, 3, 5), 3) #' CodonChoiceBiasesDeprecated(c(1, 2, 3, 5), 5) #' @export CodonChoiceBiasesDeprecated<-function(cv,precision) { df<-data.frame() entropy<-function(p) {sum(-p*log(p, 2))} for (i in (1:length(cv))) { # The following code uses outer products and vector operations a<-(1:(2^precision)) %% cv[i] d<-colSums(outer(a, (0:(cv[i]-1)), FUN="==")) l<-min(d) h<-max(d) cl<-sum(min(d)==d) ch<-sum(max(d)==d) # end of comment diff<-length(d)-max(cl, ch) u<-rep(1, cv[i])/cv[i] p<-d/sum(d) dp<-sum(abs(u-p)) dH<-entropy(u)-entropy(p) df<-rbind(df, c(precision, cv[i], dp, dH)) } colNames<-c("Bits", "Choices", "dP", "dh") colnames(df)<-colNames return(df) } #' Compute codon precision with the choice bias of rules below a threshold. #' #' @description For automatic determination of the least codon precision for grammar evolution #' with an upper threshold on the choice bias of for the substitution of all #' non-terminal symbols. #' #' @param cv Choice vector of a context-free grammar. #' @param pCrit Threhold for choice bias. #' #' @return Precision of codon. #' #' @family Diagnostics #' #' @examples #' CodonPrecision(c(1, 2, 3, 5), 0.1) #' CodonPrecision(c(1, 2, 3, 5), 0.01) #' #' @export CodonPrecision<-function(cv, pCrit) { precs<-rep(0, length(cv)) start<-ceiling(log(max(cv),2)) for (i in (1:length(cv))) { for (precision in (start:64)) { # a<-(1:2^precision) %% cv[i] # d<-colSums(outer(a, (0:(cv[i]-1)), FUN="==")) r<-(2^precision)/cv[i] ub<-(2^precision) %% cv[i] lb<-cv[i]-ub l<-floor(r) h<-ceiling(r) d<-c(rep(l, lb), rep(h, ub)) diff<-length(d)-max(ub, lb) u<-rep(1, cv[i])/cv[i] p<-d/sum(d) dp<-sum(abs(u-p)) if (dp<pCrit) {precs[i]<-precision; break} }} return(max(precs)) } #' Precision of a codon which has a choice bias below a probability threshold. #' #' @description The choice bias is the sum of the absolute values of the #' difference between a k equally probable choices and the #' probability distribution of the modulo choice rule. #' #' @param LHS The left-hand side of a grammar object \code{G}. #' @param pCrit Threshold for the choice bias for single non-terminal. #' #' @return The precision of a codon which guarantees that the choice bias #' for all nonterminals is below a probability threshold of #' \code{PCrit}. #' #' @family Precision #' #' @examples #' NT<-sample(5, 50, replace=TRUE) #' CodonPrecisionWithThreshold(NT, 0.1) #' CodonPrecisionWithThreshold(NT, 0.01) #' @export CodonPrecisionWithThreshold<-function(LHS, pCrit) { CodonPrecision(ChoiceVector(LHS), pCrit) } #' Configure the function for computing the codon precision for grammar evolution. #' #' @description \code{xegaGePrecisionFactory()} implements the selection #' of one of the functions for computing the codon precision in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Min" returns \code{MinCodonPrecision}. #' Shortest coding, but some choice bias. #' \item "LCM" returns \code{mLCMGCodonPrecision}. (Default) #' \item "MaxPBias" returns \code{CodonPrecisionWithThreshold}. #' } #' #' @param method String specifying the GeneMap function. #' #' @return Precision of codon function. #' #' @family Configuration #' #' @examples #' CodonPrecision<-xegaGePrecisionFactory("Min") #' NT<-sample(5, 50, replace=TRUE) #' CodonPrecision(NT) #' CodonPrecision<-xegaGePrecisionFactory("MaxPBias") #' CodonPrecision(NT, 0.1) #' @export xegaGePrecisionFactory<-function(method="LCM") { if (method=="Min") {f<-MinCodonPrecision} if (method=="LCM") {f<-mLCMGCodonPrecision} if (method=="MaxPBias") {f<-CodonPrecisionWithThreshold} if (!exists("f", inherits=FALSE)) {stop("sge Precision label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGeGene/R/xegaGeCodonPrecision.R
# # (c) 2024 Andreas Geyer-Schulz # Grammatical Evolution V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGeGene # #' Map the bit strings of a binary gene to parameters in the interval #' \code{1:2^k}. #' #' @description \code{xegaGeGeneMapMod()} maps the bit strings of a binary string #' to integers in the interval \code{1} to #' \code{lF$CodonPrecision()}. #' Bit vectors are mapped into equispaced numbers in the interval. #' #' @details The modulo rule of grammatical evolution produces (slightly) #' biased choices of rules with this mapping. The bias goes to #' zero as \code{lF$CodonPrecision()} \code{>>} number of rules #' to choose from. #' #' @references Keijzer, M., O'Neill, M., Ryan, C. and Cattolico, M. (2002) #' Grammatical Evolution Rules: The Mod and the Bucket Rule, #' pp. 123-130. #' In: Foster, J. A., Lutton, E., Miller, J., Ryan, C. and #' Tettamanzi, A. (Eds.): Genetic Programming. #' Lecture Notes in Computer Science, Vol.2278, #' Springer, Heidelberg. #' <doi:10.1007/3-540-45984-7_12> #' #' @param gene Binary gene (the genotype). #' @param lF Local configuration. #' #' @return Integer vector. #' #' @family Decoder #' #' @examples #' gene<-xegaGeInitGene(lFxegaGeGene) #' xegaGeGeneMapMod(gene$gene1, lFxegaGeGene) #' #' @export xegaGeGeneMapMod<-function(gene, lF) { nparm<-lF$Codons() precision<-lF$CodonPrecision() ub<-(-1)+2^precision parm<-rep(0, nparm) s<-1 for (i in 1:nparm) { bv<-gene[s:(s-1+precision)] s<-s+precision parm[i]<-1+ub* (sum(bv*2^((precision-1):0)))/ub} return(parm) } #' Map the bit strings of a binary gene to integer parameters in the interval #' \code{1} to \code{numbers::mLCM(x) < 2^k}. #' #' @description \code{xegaGeGeneMapmLCM()} #' maps the bit strings of a binary string #' to integers in the interval \code{1} to #' \code{lF$CodonPrecision()}. #' Bit vectors are mapped into equispaced numbers in the interval. #' #' @details Using the interval of \code{1} to \code{numbers::mLCM(1:m)} #' provides a the least common multiple of all prime factors #' of the numbers in the interval \code{1:m}. #' This corresponds to the bucket rule of Keijzer et al. (2002). #' For 16-bit precision, the highest number of rules #' for the same non-terminal symbols is 12. #' For 8-bit precision,this reduces to 6. #' With 64-bit integer arithmetic, the bucket rule works up to #' 42 rules starting with the same non-terminal. #' #' @references Keijzer, M., O'Neill, M., Ryan, C. and Cattolico, M. (2002) #' Grammatical Evolution Rules: The Mod and the Bucket Rule, #' pp. 123-130. #' In: Foster, J. A., Lutton, E., Miller, J., Ryan, C. and #' Tettamanzi, A. (Eds.): Genetic Programming. #' Lecture Notes in Computer Science, Vol.2278, #' Springer, Heidelberg. #' <doi:10.1007/3-540-45984-7_12> #' #' @param gene Binary gene (the genotype). #' @param lF Local configuration. #' #' @return Integer vector. #' #' @family Decoder #' #' @examples #' gene<-xegaGeInitGene(lFxegaGeGene) #' xegaGeGeneMapmLCM(gene$gene1, lFxegaGeGene) #' #' @export xegaGeGeneMapmLCM<-function(gene, lF) { nparm<-lF$Codons() precision<-lF$CodonPrecision() diff<-lF$CodonLCM()-1 ub<-(-1)+2^precision parm<-rep(0, nparm) s<-1 for (i in 1:nparm) { bv<-gene[s:(s-1+precision)] s<-s+precision parm[i]<-1+diff* (sum(bv*2^((precision-1):0)))/ub} return(floor(parm)) } #' Configure the gene map function of a genetic algorithm for grammar evolution. #' #' @description \code{xegaGeGeneMapFactory()} implements the selection #' of one of the GeneMap functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Mod" returns \code{GeneMapMod()}. (Default). #' \item "Bucket" returns \code{GeneMapmLCM()}. #' } #' #' @param method String specifying the GeneMap function. #' #' @return Gene map function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaGeGeneMapFactory("Mod") #' gene<-xegaGeInitGene(lFxegaGeGene) #' XGene(gene$gene1, lFxegaGeGene) #' @export xegaGeGeneMapFactory<-function(method="Mod") { if (method=="Mod") {f<-xegaGeGeneMapMod} if (method=="Bucket") {f<-xegaGeGeneMapmLCM} if (!exists("f", inherits=FALSE)) {stop("sge GeneMap label ", method, " does not exist")} return(f) } #' Decode a gene for a context free grammar. #' #' @description \code{xegaGeDecodeGene()} decodes a binary gene with #' a context-free grammar. #' #' @details The codons (k-bit sequences) of the binary gene are determining #' the choices of non-terminal symbols of a depth-first left-to-right #' tree traversal. Decoding works in 2 steps: #' \enumerate{ #' \item From the binary gene and a grammar a potentially #' incomplete derivation tree is built. #' \item The leaves of the derivation tree are extracted. #' } #' #' It is not guaranteed that a complete derivation trees is returned. #' #' @param gene Binary gene. #' @param lF Local configuration of the genetic algorithm. #' #' @return Decoded gene. #' #' @family Decoder #' #' @examples #' lFxegaGeGene$GeneMap<-xegaGeGeneMapFactory("Mod") #' gene<-xegaGeInitGene(lFxegaGeGene) #' xegaGeDecodeGene(gene, lFxegaGeGene) #' #' @importFrom xegaDerivationTrees generateDerivationTree #' @importFrom xegaDerivationTrees decodeDT #' @export xegaGeDecodeGene<-function(gene, lF) { kvec<-lF$GeneMap(gene$gene1, lF) t<-xegaDerivationTrees::generateDerivationTree( sym=lF$Grammar$Start, kvec=kvec, G=lF$Grammar, maxdepth=lF$maxdepth) return(xegaDerivationTrees::decodeDT(t$tree, lF$Grammar$ST)) }
/scratch/gouwar.j/cran-all/cranData/xegaGeGene/R/xegaGeDecode.R
#' The \code{xegaGeGene} package #' provides functions implementing #' grammatical evolution with binary coded genes: #' #' \itemize{ #' \item Gene initialization. #' \item Gene maps for the mod and (approximately) for the bucket rule. #' \item Grammar-based decoders for binary coded genes. #' \item Analysis of the interaction of codon precision #' with the rule choice bias for a given grammar. #' \item Automatic determination of codon precision #' with a limited rule choice bias. #' } #' #' @references Ryan, Conor and Collins, J. J. AND Neill, Michael O. (1998) #' Grammatical evolution: Evolving programs for an arbitrary language. #' In: Banzhaf, Wolfgang and Poli, Riccardo, Schoenauer, Marc and #' Fogarty, Terence C. (1998): #' Genetic Programming. First European Workshop, EuroGP' 98 #' Paris, France, April 14-15, 1998 Proceedings, #' Lecture Notes in Computer Science, 1391, Springer, Heidelberg. #' <doi:10.1007/BFb0055930> #' #' O'Neil, Michael AND Ryan, Conor (2003) #' Grammatical Evolution: #' Evolutionary Automatic Programming in an Arbitrary Language. #' Kluwer, Dordrecht. #' <ISBN:1-4020-7444-1> #' #' Ryan, Conor and O'Neill, Michael and Collins, J. J. (2018) #' Handbook of Grammatical Evolution. #' Springer International Publishing, Cham. #' <doi:10.1007/978-3-319-78717-6> #' #' @section Gene Initialization: #' #' The number of bits of a gene are specified by \code{lF$BitsOnGene()}. #' #' The number of bits of a codon are specified #' by \code{lF$CodonPrecision()}. #' #' @section Binary Gene Representation: #' #' A binary gene is a named list: #' \itemize{ #' \item $gene1 the gene must be a binary vector. #' \item $fit the fitness value of the gene #' (for EvalGeneDet and EvalGeneU) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch). #' \item $evaluated has the gene been evaluated? #' \item $evalFail has the evaluation of the gene failed? #' \item $var the cumulative variance of the fitness #' of all evaluations of a gene. #' (For stochastic functions) #' \item $sigma the standard deviation of the fitness of #' all evaluations of a gene. #' (For stochastic functions) #' \item $obs the number evaluations of a gene. #' (For stochastic functions) #' } #' #' @section Abstract Interface of Problem Environment: #' #' A problem environment \code{penv} must provide: #' \itemize{ #' \item \code{$f(parameters, gene, lF)}: #' Function with a real parameter vector as first argument #' which returns a gene #' with evaluated fitness. #' #' \item $genelength(): The number of bits of the binary coded #' real parameter vector. Used in \code{InitGene}. #' \item $bitlength(): A vector specifying the number of bits #' used for coding each real parameter. #' If \code{penv$bitlength()[1]} is \code{20}, #' then \code{parameters[1]} is coded by 20 bits. #' Used in \code{GeneMap}. #' \item $lb(): The lower bound vector of each parameter. #' Used in \code{GeneMap}. #' \item $ub(): The upper bound vector of each parameter. #' Used in \code{GeneMap}. #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split in a representation independent and #' a representation dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler and #' \code{xegaDerivationTrees} an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaGeGene #' @aliases xegaGeGene #' @docType package #' @title Package xegaGeGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2024 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: https://github.com/ageyerschulz/xegaGeGene #' @section Installation: From CRAN by \code{install.packages('xegaGeGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaGeGene/R/xegaGeGene-package.R
# # (c) 2024 Andreas Geyer-Schulz # Grammatical Evolution in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaGeGene # #' Initialize a binary gene #' #' @description \code{xegaGeInitGene()} generates a random binary gene #' with a given length. #' #' @details In the binary representation of #' package \code{xega}, \emph{gene} is a list with #' \enumerate{ #' \item \code{$evaluated} Boolean: TRUE if the fitness is known. #' \item \code{$fit} The fitness of the genotype of #' \code{$gene1} #' \item \code{$gene1} a bit string (the genetopye). #' } #' #' This representation makes several code optimizations #' and generalizations easier. #' #' @param lF the local configuration of the genetic algorithm #' #' @return a binary gene (a named list): #' \itemize{ #' \item \code{$evaluated}: FALSE. See package \code{xegaEvalGene} #' \item \code{$evalFail}: FALSE. Set by the error handler(s) #' in package \code{xegaEvalGene} #' in the case of failure. #' \item \code{$fit}: Fitness vector. #' \item \code{$gene1}: Binary gene. #' } #' #' @family Gene Generation #' #' @examples #' xegaGeInitGene(lFxegaGeGene) #' #' @export xegaGeInitGene<-function(lF) {gene1<-sample(0:1, lF$BitsOnGene(), replace=TRUE) return(list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=gene1)) }
/scratch/gouwar.j/cran-all/cranData/xegaGeGene/R/xegaGeInitGene.R
# # (c) 2021 Andreas Geyer-Schulz # Grammatical Evolution in R. V0.1 # Layer: Gene-Level Functions # Binary representation of genes. # Package: xegaGeGene # #' The local function list lFxegaGeGene. #' #' @importFrom xegaBNF compileBNF #' @importFrom xegaBNF booleanGrammar #' @importFrom xegaSelectGene parm #' @importFrom xegaSelectGene envXOR #' @export lFxegaGeGene<-list( penv=xegaSelectGene::envXOR, Grammar=xegaBNF::compileBNF(xegaBNF::booleanGrammar()), Codons=xegaSelectGene::parm(25), CodonPrecision=xegaSelectGene::parm(16), BitsOnGene=xegaSelectGene::parm(25*16), CodonLCM=xegaSelectGene::parm(2*3*2*5*7*2*3*11), replay=xegaSelectGene::parm(0), verbose=xegaSelectGene::parm(4), MaxDepth=xegaSelectGene::parm(5), CBestFitness=xegaSelectGene::parm(100), CWorstFitness=xegaSelectGene::parm(-100), MutationRate1=xegaSelectGene::parm(0.01), MutationRate2=xegaSelectGene::parm(0.20), BitMutationRate1=xegaSelectGene::parm(0.01), BitMutationRate2=xegaSelectGene::parm(0.20), Max=xegaSelectGene::parm(1), Offset=xegaSelectGene::parm(1), Eps=xegaSelectGene::parm(0.01), Elitist=xegaSelectGene::parm(TRUE), TournamentSize=xegaSelectGene::parm(2), SelectGene=xegaSelectGene::SelectGeneFactory(method="PropFitDiff"), SelectMate=xegaSelectGene::SelectGeneFactory(method="Uniform"), EvalGene=xegaSelectGene::EvalGeneFactory(method="EvalGeneU") )
/scratch/gouwar.j/cran-all/cranData/xegaGeGene/R/xegaGelF.R
# # (c) 2021 Andreas Geyer-Schulz # Grammar-based Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # Gene operations with derivation trees. # Package: xegaGpGene # #' Crossover of 2 derivation tree genes with node filter. #' #' @description \code{xegaGpFilterCross2Gene()} swaps two randomly extracted #' subtrees between 2 genes. Subtrees must have the same #' root in order to be compatible. The current implementation #' performs at most \code{maxtrials} trials to find compatible #' subtrees. If this fails, the original genes are returned. #' Only nodes with a depth #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()} are considered as #' candidate roots of derivation trees to be swapped #' by crossover. #' #' @details Crossover is controlled by three local parameters: #' \itemize{ #' \item \code{lF$MinCrossDepth()} and #' \code{lF$MaxCrossDepth()} control the possible exchange points #' for subtrees. The depth of the exchange node must be #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()}. #' \item \code{lF$MaxTrials()}: Maximal number of trials to find #' compatible subtrees. If compatible subtrees are not #' found, the gene is returned unchanged. #' } #' #' @param ng1 Derivation tree. #' @param ng2 Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return List of 2 derivation trees. #' #' @family Crossover #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene2<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene2, lFxegaGpGene) #' newgenes<-xegaGpFilterCross2Gene(gene1, gene2, lFxegaGpGene) #' xegaGpDecodeGene(newgenes[[1]], lFxegaGpGene) #' xegaGpDecodeGene(newgenes[[2]], lFxegaGpGene) #' #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees filterANL #' @importFrom xegaDerivationTrees filterANLid #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees compatibleSubtrees #' @importFrom xegaDerivationTrees treeExtract #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpFilterCross2Gene<-function(ng1, ng2, lF) { g1<-ng1$gene1 g2<-ng2$gene1 anl1<-xegaDerivationTrees::treeANL(g1, lF$Grammar$ST, lF$MaxDepth()) anl1<-xegaDerivationTrees::filterANL(anl1, minb=lF$MinCrossDepth(), maxb=lF$MaxCrossDepth()) anl2<-xegaDerivationTrees::treeANL(g2, lF$Grammar$ST, lF$MaxDepth()) anl2<-xegaDerivationTrees::filterANL(anl2, minb=lF$MinCrossDepth(), maxb=lF$MaxCrossDepth()) rg<-list() # TODO: Replace the maxtrials loop ... for (i in 1: lF$MaxTrials()) { n1<-xegaDerivationTrees::chooseNode(anl1$ANL) ANL2<-filterANLid(anl2, n1$ID) if (length(ANL2$ANL)==0) {next} n2<-xegaDerivationTrees::chooseNode(ANL2$ANL) if (xegaDerivationTrees::compatibleSubtrees(n1, n2, lF$MaxDepth())) { subtree1<-xegaDerivationTrees::treeExtract(g1, n1) subtree2<-xegaDerivationTrees::treeExtract(g2, n2) newg1<-xegaDerivationTrees::treeInsert(g1, subtree2, n1) newg2<-xegaDerivationTrees::treeInsert(g2, subtree1, n2) # print("cross over SUCESS.") rg[[1]]<-list(evaluated=FALSE, fit=0, gene1=newg1) rg[[2]]<-list(evaluated=FALSE, fit=0, gene1=newg2) return(rg)}} # print("cross over fails. Return genes.") rg[[1]]<-ng1 rg[[2]]<-ng2 return(rg) } #' Crossover of 2 derivation tree genes #' #' @description \code{xegaGpAllCross2Gene()} swaps two randomly extracted #' subtrees between 2 genes. Subtrees must have the same #' root in order to be compatible. The current implementation #' performs at most \code{maxtrials} trials to find compatible #' subtrees. If this fails, the original genes are returned. #' #' @details Crossover is controlled by one local parameter: #' \itemize{ #' \item \code{lF$MaxTrials()}: Maximal number of trials to find #' compatible subtrees. If compatible subtrees are not #' found, the gene is returned unchanged. #' } #' #' @param ng1 Derivation tree. #' @param ng2 Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return List of 2 derivation trees. #' #' @family Crossover #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene2<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene2, lFxegaGpGene) #' newgenes<-xegaGpAllCross2Gene(gene1, gene2, lFxegaGpGene) #' xegaGpDecodeGene(newgenes[[1]], lFxegaGpGene) #' xegaGpDecodeGene(newgenes[[2]], lFxegaGpGene) #' #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees filterANLid #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees compatibleSubtrees #' @importFrom xegaDerivationTrees treeExtract #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpAllCross2Gene<-function(ng1, ng2, lF) { g1<-ng1$gene1 g2<-ng2$gene1 anl1<-xegaDerivationTrees::treeANL(g1, lF$Grammar$ST, lF$MaxCrossDepth()) anl2<-xegaDerivationTrees::treeANL(g2, lF$Grammar$ST, lF$MaxCrossDepth()) rg<-list() # TODO: Replace the maxtrials loop ... for (i in 1: lF$MaxTrials()) { n1<-xegaDerivationTrees::chooseNode(anl1$ANL) ANL2<-filterANLid(anl2, n1$ID) if (length(ANL2$ANL)==0) {next} n2<-xegaDerivationTrees::chooseNode(ANL2$ANL) if (xegaDerivationTrees::compatibleSubtrees(n1, n2, lF$MaxDepth())) { subtree1<-xegaDerivationTrees::treeExtract(g1, n1) subtree2<-xegaDerivationTrees::treeExtract(g2, n2) newg1<-xegaDerivationTrees::treeInsert(g1, subtree2, n1) newg2<-xegaDerivationTrees::treeInsert(g2, subtree1, n2) # print("cross over SUCESS.") rg[[1]]<-list(evaluated=FALSE, fit=0, gene1=newg1) rg[[2]]<-list(evaluated=FALSE, fit=0, gene1=newg2) return(rg)}} # print("cross over fails. Return genes.") rg[[1]]<-ng1 rg[[2]]<-ng2 return(rg) } #' Crossover of 2 derivation tree genes. #' #' @description \code{xegaGpAllCrossGene()} swaps two randomly extracted #' subtrees between 2 genes. Subtrees must have the same #' root in order to be compatible. The current implementation #' performs at most \code{lF$MaxTrials()} #' attempts to find compatible #' subtrees. If this fails, the original gene is returned. #' #' @details Crossover is controlled by one local parameter: #' \itemize{ #' \item \code{lF$MaxTrials()}: Maximal number of trials to find #' compatible subtrees. If compatible subtrees are not #' found, the gene is returned unchanged. #' } #' #' @param ng1 Derivation tree. #' @param ng2 Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return List of 1 derivation tree. #' #' @family Crossover #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene2<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene2, lFxegaGpGene) #' newgene<-xegaGpAllCrossGene(gene1, gene2, lFxegaGpGene) #' xegaGpDecodeGene(newgene[[1]], lFxegaGpGene) #' #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees filterANLid #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees compatibleSubtrees #' @importFrom xegaDerivationTrees treeExtract #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpAllCrossGene<-function(ng1, ng2, lF) { g1<-ng1$gene1 g2<-ng2$gene1 anl1<-xegaDerivationTrees::treeANL(g1, lF$Grammar$ST, lF$MaxDepth()) anl2<-xegaDerivationTrees::treeANL(g2, lF$Grammar$ST, lF$MaxDepth()) rg<-list() # TODO: Replace the maxtrials loop ... for (i in 1: lF$MaxTrials()) { n1<-xegaDerivationTrees::chooseNode(anl1$ANL) ANL2<-filterANLid(anl2, n1$ID) if (length(ANL2$ANL)==0) {next} n2<-xegaDerivationTrees::chooseNode(ANL2$ANL) if (xegaDerivationTrees::compatibleSubtrees(n1, n2, lF$MaxDepth())) { subtree2<-xegaDerivationTrees::treeExtract(g2, n2) newg1<-xegaDerivationTrees::treeInsert(g1, subtree2, n1) # print("cross over SUCESS.") rg[[1]]<-list(evaluated=FALSE, fit=0, gene1=newg1) return(rg)}} # print("cross over fails. Return genes.") rg[[1]]<-ng1 return(rg) } #' Crossover of 2 derivation tree genes with node filter. #' #' @description \code{xegaGpFilterCrossGene()} swaps two randomly extracted #' subtrees between 2 genes. Subtrees must have the same #' root in order to be compatible. The current implementation #' performs at most \code{lF$maxtrials()} #' attempts to find compatible #' subtrees. If this fails, the original gene is returned. #' Only nodes with a depth #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()} are considered as #' candidate roots of derivation trees to be swapped #' by crossover. #' #' @details Crossover is controlled by three local parameters: #' \itemize{ #' \item \code{lF$MinCrossDepth()} and #' \code{lF$MaxCrossDepth()} control the possible exchange points #' for subtrees. The depth of the exchange node must be #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()}. #' \item \code{lF$MaxTrials()}: Maximal number of trials to find #' compatible subtrees. If compatible subtrees are not #' found, the gene is returned unchanged. #' } #' #' @param ng1 Derivation tree. #' @param ng2 Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return List of 1 derivation tree. #' #' @family Crossover #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene2<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene2, lFxegaGpGene) #' newgene<-xegaGpFilterCrossGene(gene1, gene2, lFxegaGpGene) #' xegaGpDecodeGene(newgene[[1]], lFxegaGpGene) #' #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees filterANL #' @importFrom xegaDerivationTrees filterANLid #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees compatibleSubtrees #' @importFrom xegaDerivationTrees treeExtract #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpFilterCrossGene<-function(ng1, ng2, lF) { g1<-ng1$gene1 g2<-ng2$gene1 anl1<-xegaDerivationTrees::treeANL(g1, lF$Grammar$ST, lF$MaxDepth()) anl1<-xegaDerivationTrees::filterANL(anl1, minb=lF$MinCrossDepth(), maxb=lF$MaxCrossDepth()) anl2<-xegaDerivationTrees::treeANL(g2, lF$Grammar$ST, lF$MaxDepth()) anl2<-xegaDerivationTrees::filterANL(anl2, minb=lF$MinCrossDepth(), maxb=lF$MaxCrossDepth()) rg<-list() # TODO: Replace the maxtrials loop ... for (i in 1: lF$MaxTrials()) { n1<-xegaDerivationTrees::chooseNode(anl1$ANL) ANL2<-filterANLid(anl2, n1$ID) if (length(ANL2$ANL)==0) {next} n2<-xegaDerivationTrees::chooseNode(ANL2$ANL) if (xegaDerivationTrees::compatibleSubtrees(n1, n2, lF$MaxDepth())) { subtree2<-xegaDerivationTrees::treeExtract(g2, n2) newg1<-xegaDerivationTrees::treeInsert(g1, subtree2, n1) # print("cross over SUCESS.") rg[[1]]<-list(evaluated=FALSE, fit=0, gene1=newg1) return(rg)}} # print("cross over fails. Return genes.") rg[[1]]<-ng1 return(rg) } #' Configure the crossover function of a grammar-based genetic algorithm. #' #' @description \code{xegaGpCrossoverFactory()} implements the selection #' of one of the crossover functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item Crossover functions with two kids: #' \enumerate{ #' \item "Cross2Gene" returns \code{xegaGpAllCross2Gene()}. #' \item "AllCross2Gene" returns \code{xegaGpAllCross2Gene()}. #' \item "FilterCross2Gene" returns \code{xegaGpFilterCross2Gene()}. #' } #' \item Crossover functions with one kid: #' \enumerate{ #' \item "AllCrossGene" returns \code{xegaGpAllCrossGene()}. #' \item "FilterCrossGene" returns \code{xegaGpFilterCrossGene()}. #' } #' } #' #' @param method String specifying the crossover function. #' #' @return Crossover function for genes. #' #' @family Configuration #' #' @examples #' XGeneTwo<-xegaGpCrossoverFactory("Cross2Gene") #' XGeneOne<-xegaGpCrossoverFactory("FilterCrossGene") #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene2<-xegaGpInitGene(lFxegaGpGene) #' XGeneTwo(gene1, gene2, lFxegaGpGene) #' XGeneOne(gene1, gene2, lFxegaGpGene) #' @export xegaGpCrossoverFactory<-function(method="Cross2Gene") { if (method=="Cross2Gene") {f<- xegaGpAllCross2Gene} if (method=="AllCross2Gene") {f<- xegaGpAllCross2Gene} if (method=="AllCrossGene") {f<- xegaGpAllCrossGene} if (method=="FilterCross2Gene") {f<- xegaGpFilterCross2Gene} if (method=="FilterCrossGene") {f<- xegaGpFilterCrossGene} if (!exists("f", inherits=FALSE)) {stop("sgp Crossover label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpCrossover.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # For gene representation of derivation trees. # Package: xegaGpGene # #' Decode a derivation tree. #' #' @description \code{xegaGpDecodeGene()} decodes a derivation tree. #' #' @details The recursive algorithm for the decoder is imported #' from package \code{xegaDerivationTrees}. #' #' @param gene Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return Decoded gene. Program. #' #' @family Decoder #' #' @examples #' gene<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene, lFxegaGpGene) #' #' @importFrom xegaDerivationTrees decodeCDT #' @export xegaGpDecodeGene<-function(gene, lF) { xegaDerivationTrees::decodeCDT(gene$gene1, lF$Grammar$ST) }
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpDecode.R
#' Prints a random example of crossover for a crossover method given #' a random number seed. #' #' @description The purpose of this function is to support the search #' for examples for generating unit tests for crossover #' functions whose behavior depends on random numbers. #' #' @param FUN String. Specification of crossover method. #' @param s Integer. Seed of random number generator. #' @param verbose Boolean. #' If \code{TRUE} (default), print example to console. #' #' @return No return. #' #' @family Testing #' #' @examples #' findCrossoverExample(FUN="AllCross2Gene", s=2) # findCrossoverExample(FUN="FilterCross2Gene", s=19) #' @export findCrossoverExample<-function(FUN, s, verbose=TRUE) { set.seed(s) gene1<-xegaGpInitGene(lFxegaGpGene) gene2<-xegaGpInitGene(lFxegaGpGene) CROSSOVER<-xegaGpCrossoverFactory(method=FUN) gene<-CROSSOVER(gene1, gene2, lFxegaGpGene) a<-xegaGpDecodeGene(gene1, lFxegaGpGene) c<-xegaGpDecodeGene(gene2, lFxegaGpGene) if (verbose) {cat(" g1", a, "\n") cat(" g2", c, "\n")} for (i in (1:length(gene))) { b<-xegaGpDecodeGene(gene[[i]], lFxegaGpGene) if (verbose) {cat("ng", i, ":", b, "\n")} } }
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpFindExample.R
#' Genetic operations for grammar-based genetic algorithms. #' #' For derivation tree genes, the \code{xegaGpGene} package provides #' \itemize{ #' \item Gene initiatilization. #' \item Decoding of parameters. #' \item Mutation functions as well as a function factory for configuration. #' \item Crossover functions as well as a function factory for configuration. #' Crossover functions can be restricted by depth or by the non-terminal #' symbols which are allowed as roots of the subtrees which are exchanged #' between 2 genes. #' We provide two families of crossover functions: #' \enumerate{ #' \item Crossover functions with two kids: #' Crossover preserves the genetic information in the gene pool. #' \item Crossover functions with one kid: #' These functions allow the construction of evaluation pipelines #' for genes. One advantage of this is a simple control structure #' at the population level. #' } #' } #' #' @references Geyer-Schulz, Andreas (1997): #' \emph{Fuzzy Rule-Based Expert Systems and Genetic Machine Learning}, #' Physica, Heidelberg. #' (ISBN:978-3-7908-0830-X) #' #' @section Derivation Tree Gene Representation: #' #' A derivation tree gene is a named list: #' \itemize{ #' \item \code{$gene1}: The gene must be a complete derivation tree. #' \item \code{$fit}: The fitness value of the gene #' (for EvalGeneDet() and EvalGeneU()) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch()). #' \item \code{$evaluated}: Boolean. Has the gene been evaluated? #' \item \code{$evalFail}: Boolean. Has the evaluation of the gene failed? #' \item \code{$var}: The variance of the fitness #' of all evaluations of a gene is updated #' after each evaluation of a gene. #' (For stochastic functions.) #' \item \code{$sigma}: The standard deviation of the fitness of #' all evaluations of a gene. #' (For stochastic functions.) #' \item \code{$obs:} The number evaluations of a gene. #' (For stochastic functions.) #' } #' #' @section Abstract Interface of Problem Environment: #' #' A problem environment \code{penv} must provide: #' \itemize{ #' \item \code{$f(word, gene, lF)}: #' Function with a word of a language as first argument #' which the fitness of the gene. #' #' } #' #' @section Abstract Interface of Mutation Functions: #' #' Each mutation function has the following function signature: #' #' \code{newGene<-Mutate(gene, lF)} #' #' All local parameters of the mutation function configured are #' expected in the local function list lF. #' #' @section Local Constants of Mutation Functions: #' #' The local constants of a mutation function determine the #' the behavior of the function. #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' \code{lF$MaxMutDepth()} \tab 3 \tab xegaGpMutateAllGene(), \cr #' \tab 3 \tab xegaGpMutateFilterGene() \cr #' \code{lF$MinMutInsertiontDepth()} \tab 3 \tab xegaGpMutateFilterGene() \cr #' \code{lF$MaxMutInsertiontDepth()} \tab 4 \tab xegaGpMutateFilterGene() \cr #' } #' #' @section Abstract Interface of Crossover Functions: #' #' The signatures of the abstract interface to the 2 families #' of crossover functions are: #' #' \code{ListOfTwoGenes<-Crossover2(gene1, gene2, lF)} #' #' \code{ListOfOneGene<-Crossover(gene1, gene2, lF)} #' #' All local parameters of the crossover function configured are #' expected in the local function list lF. #' #' @section Local Constants of Crossover Functions: #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' \code{lF$MinCrossDepth()} \tab 1 \tab xegaGpFilterCross2Gene(), \cr #' \tab \tab xegaGpFilterCrossGene(), \cr #' \code{lF$MaxCrossDepth()} \tab 7 \tab xegaGpFilterCross2Gene(), \cr #' \tab \tab xegaGpFilterCrossGene(), \cr #' \code{lF$MaxTrials()} \tab 5 \tab xegaGpAllCross2Gene() \cr #' \tab \tab xegaGpAllCrossGene(), \cr #' \tab \tab xegaGpFilter2CrossGene(), \cr #' \tab \tab xegaGpFilterCrossGene(), \cr #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split in a representation independent and #' a representation dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler and #' \code{xegaDerivationTrees} an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaGpGene #' @aliases xegaGpGene #' @docType package #' @title Package xegaGpGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaGpGene> #' @section Installation: From CRAN by \code{install.packages('xegaGpGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpGene-package.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # For gene representation of derivation trees. # Package: xegaGpGene # #' Generates a gene as a random derivation tree. #' #' @description For a given grammar, \code{xegaGpInitGene()} #' generates a gene as a random derivation tree #' with a depth-bound. #' #' @details In the derivation tree representation of #' package \code{xegaGp}, \emph{gene} is a list with #' \enumerate{ #' \item \code{$evaluated}: Boolean: TRUE if the fitness is known. #' \item \code{$fit}: The fitness of the genotype of #' \code{$gene1} #' \item \code{$gene1}: a derivation tree. #' } #' #' This representation makes implementation of several #' code optimizations and generalizations easier. #' #' The algorithm for generating a complete derivation tree #' with a depth-bound #' is imported from package \code{xegaDerivationTrees}. #' #' @param lF Local configuration of the genetic algorithm. #' #' @return Derivation tree. #' #' @family Initialization #' #' @examples #' gene<-xegaGpInitGene(lFxegaGpGene) #' #' @importFrom xegaDerivationTrees randomDerivationTree #' @export xegaGpInitGene<-function(lF) { gene1<-xegaDerivationTrees::randomDerivationTree(lF$Grammar$Start, lF$Grammar, lF$MaxDepth()) return(list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=gene1)) }
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpInitGene.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # For gene representation of derivation trees. # Package: xegaGpGene # #' Mutate a gene. #' #' @description \code{xegaGpMutateAllGene()} #' replaces a randomly selected subtree by #' a random derivation tree with the same root symbol #' with small probability. #' All non-terminal nodes are considered as insertion points. #' Depth-bounds are respected. #' #' @details Mutation is controlled by one local parameter: #' \enumerate{ #' \item \code{lF$MaxMutDepth()} controls the maximal depth of #' of the new random generation tree. #' } #' This version of the genetic operator skips the filter loop. #' #' @param g Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return Derivation tree. #' #' @family Mutation #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' gene<-xegaGpMutateAllGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene, lFxegaGpGene) #' #' @importFrom stats runif #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees randomDerivationTree #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpMutateAllGene<-function(g, lF) { gene<-g$gene1 anl<-xegaDerivationTrees::treeANL(gene, ST=lF$Grammar$ST, maxdepth=lF$MaxDepth()) node<-xegaDerivationTrees::chooseNode(anl$ANL) mutgene<-xegaDerivationTrees::randomDerivationTree( node$ID, lF$Grammar, min(lF$MaxMutDepth(),node$Rdepth)) newgene<-xegaDerivationTrees::treeInsert(gene, mutgene, node) return(list(evaluated=FALSE, fit=0, gene1=newgene)) } #' Mutate a gene (with a node filter) #' #' @description \code{xegaGpMutateGeneFilter()} replaces #' a randomly selected subtree by #' a random derivation tree with the same root symbol #' with small probability. #' Only non-terminal nodes with a depth #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()} are considered #' as tree insertion points. #' Depth-bounds are respected. #' #' @details Mutation is controlled by three local parameters: #' \enumerate{ #' \item \code{lF$MaxMutDepth()} controls the maximal depth of #' of the new random generation tree. #' \item \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()} control the possible #' insertion points for the new random derivation tree. #' The depth of the insertion node must be #' between \code{lF$MinMutInsertionDepth()} and #' \code{lF$MaxMutInsertionDepth()}. #' } #' #' @param g Derivation tree. #' @param lF Local configuration of the genetic algorithm. #' #' @return Derivation tree. #' #' @family Mutation #' #' @examples #' gene1<-xegaGpInitGene(lFxegaGpGene) #' xegaGpDecodeGene(gene1, lFxegaGpGene) #' gene<-xegaGpMutateFilterGene(gene1, lFxegaGpGene) #' xegaGpDecodeGene(gene, lFxegaGpGene) #' #' @importFrom stats runif #' @importFrom xegaDerivationTrees treeANL #' @importFrom xegaDerivationTrees filterANL #' @importFrom xegaDerivationTrees chooseNode #' @importFrom xegaDerivationTrees randomDerivationTree #' @importFrom xegaDerivationTrees treeInsert #' @export xegaGpMutateFilterGene<-function(g, lF) { gene<-g$gene1 anl<-xegaDerivationTrees::treeANL(gene, ST=lF$Grammar$ST, maxdepth=lF$MaxDepth()) anl<-xegaDerivationTrees::filterANL(anl, minb=lF$MinMutInsertionDepth(), maxb=lF$MaxMutInsertionDepth()) node<-xegaDerivationTrees::chooseNode(anl$ANL) mutgene<-xegaDerivationTrees::randomDerivationTree( node$ID, lF$Grammar, min(lF$MaxMutDepth(),node$Rdepth)) newgene<-xegaDerivationTrees::treeInsert(gene, mutgene, node) return(list(evaluated=FALSE, fit=0, gene1=newgene)) } #' Configure the mutation function of a genetic algorithm. #' #' @description \code{xegaGpMutationFactory()} implements the selection #' of one of the mutation functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "MutateGene" returns \code{xegaGpMutateAllGene()}. #' \item "MutateAllGene" returns \code{xegaGpMutateAllGene()}. #' \item "MutateFilterGene" returns \code{xegaGpMutateFilterGene()}. #' } #' #' @param method String specifying the mutation function. #' #' @return Mutation function for genes. #' #' @family Configuration #' #' @examples #' Mutate<-xegaGpMutationFactory("MutateGene") #' gene1<-xegaGpInitGene(lFxegaGpGene) #' gene1 #' Mutate(gene1, lFxegaGpGene) #' @export xegaGpMutationFactory<-function(method="MutateGene") { if (method=="MutateGene") {f<- xegaGpMutateAllGene} if (method=="MutateAllGene") {f<- xegaGpMutateAllGene} if (method=="MutateFilterGene") {f<- xegaGpMutateFilterGene} if (!exists("f", inherits=FALSE)) {stop("sgp Mutation label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGpMutate.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Programming in R. V0.1 # Layer: Gene-Level Functions # For gene representation of derivation trees. # Package: xegaGpGene # #' Generate local functions and objects. #' #' @description #' \code{lFxegaPermGene} is a list of functions #' which contains a definition of all local objects #' required for the use of genetic operators with the # permutation representation. #' We refer to this object as local configuration. #' #' @importFrom xegaBNF compileBNF #' @importFrom xegaBNF booleanGrammar #' @importFrom xegaSelectGene parm #' @importFrom xegaSelectGene envXOR #' @export lFxegaGpGene<-list( penv=xegaSelectGene::envXOR, Grammar=xegaBNF::compileBNF(xegaBNF::booleanGrammar()), replay=xegaSelectGene::parm(0), verbose=xegaSelectGene::parm(4), MaxDepth=xegaSelectGene::parm(5), MaxMutDepth=xegaSelectGene::parm(3), MinMutInsertionDepth=xegaSelectGene::parm(1), MaxMutInsertionDepth=xegaSelectGene::parm(5), MinCrossDepth=xegaSelectGene::parm(1), MaxCrossDepth=xegaSelectGene::parm(5), MaxTrials=xegaSelectGene::parm(5), MutationRate=xegaSelectGene::parm(0.05), CrossRate=xegaSelectGene::parm(0.2), Max=xegaSelectGene::parm(1), Offset=xegaSelectGene::parm(1), Eps=xegaSelectGene::parm(0.01), Elitist=xegaSelectGene::parm(TRUE), TournamentSize=xegaSelectGene::parm(2), SelectGene=xegaSelectGene::SelectGeneFactory(method="PropFitDiff"), SelectMate=xegaSelectGene::SelectGeneFactory(method="Uniform"), InitGene=xegaGpInitGene, MutateGene=xegaGpMutateAllGene, CrossGene=xegaGpFilterCross2Gene, DecodeGene=xegaGpDecodeGene, EvalGene=xegaSelectGene::EvalGeneFactory(method="EvalGeneU") )
/scratch/gouwar.j/cran-all/cranData/xegaGpGene/R/xegaGplF.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Position based crossover of 2 genes. #' #' @description \code{xegaPermCross2Gene} determines #' a random subschedule of random length. #' #' It copies the random subschedule into a new gene. #' The rest of the positions of the new scheme is filled #' with the elements of the other gene to complete the #' permutation. This is done for each gene. #' #' @param gg1 Permutation. #' @param gg2 Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return List of 2 permutations. #' #' @references Syswerda, G. (1991): #' Schedule Optimization Using Genetic Algorithms. #' In: Davis, L. (Ed.): #' Handbook of Genetic Algorithms, Chapter 21, p. 343. #' Van Nostrand Reinhold, New York. #' (ISBN:0-442-00173-8) #' #' @family Crossover #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' gene2<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene2, lFxegaPermGene) #' newgenes<-xegaPermCross2Gene(gene1, gene2) #' xegaPermDecodeGene(newgenes[[1]], lFxegaPermGene) #' xegaPermDecodeGene(newgenes[[2]], lFxegaPermGene) #' @export xegaPermCross2Gene<-function(gg1, gg2, lF) { newg1<-gg1; newg2<-gg2 ng1<-g1<-gg1$gene1; ng2<-g2<-gg2$gene1 l<-length(g1) index<-1:l cut<-sl<-sample(index, 1); ss1<-sample(index, sl, replace=FALSE) ng2[ss1]<-g1[ss1] ng1[ss1]<-g2[ss1] ss2<-without(index, ss1) ng2[ss2]<-without(g2, g1[ss1]) ng1[ss2]<-without(g1, g2[ss1]) newg1$evaluated<-FALSE newg1$gene1<-ng1 newg2$evaluated<-FALSE newg2$gene1<-ng2 return(list(newg1, newg2)) } #' Position based crossover of 2 genes. #' #' @description \code{xegaPermCrossGene} determines #' a random subschedule of random length. #' #' It copies the random subschedule into a new gene. #' The rest of the positions of the new scheme is filled #' with the elements of the other gene to complete the #' permutation. #' #' @param gg1 Permutation. #' @param gg2 Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A list of 2 permutations. #' #' @references Syswerda, G. (1991): #' Schedule Optimization Using Genetic Algorithms. #' In: Davis, L. (Ed.): #' Handbook of Genetic Algorithms, Chapter 21, p. 343. #' Van Nostrand Reinhold, New York. #' (ISBN:0-442-00173-8) #' #' @family Crossover #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' gene2<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene2, lFxegaPermGene) #' newgenes<-xegaPermCrossGene(gene1, gene2) #' xegaPermDecodeGene(newgenes[[1]], lFxegaPermGene) #' @export xegaPermCrossGene<-function(gg1, gg2, lF) { newg1<-gg1 ng1<-g1<-gg1$gene1; g2<-gg2$gene1 l<-length(g1) index<-1:l cut<-sl<-sample(index, 1); ss1<-sample(index, sl, replace=FALSE) ng1[ss1]<-g2[ss1] ss2<-without(index, ss1) ng1[ss2]<-without(g1, g2[ss1]) newg1$evaluated<-FALSE newg1$gene1<-ng1 return(list(newg1)) } #' Configure the crossover function of a genetic algorithm. #' #' @description \code{xegaPermCrossoverFactory} implements the selection #' of one of the crossover functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item Crossover functions with two kids: #' \enumerate{ #' \item "Cross2Gene" returns \code{xegaPermCross2Gene}. #' } #' \item Crossover functions with one kid: #' \enumerate{ #' \item "CrossGene" returns \code{xegaPermCrossGene}. #' } #' } #' #' @param method A string specifying the crossover function. #' #' @return A crossover function for genes. #' #' @family Configuration #' #' @examples #' XGene<-xegaPermCrossoverFactory("Cross2Gene") #' gene1<-xegaPermInitGene(lFxegaPermGene) #' gene2<-xegaPermInitGene(lFxegaPermGene) #' XGene(gene1, gene2, lFxegaPermGene) #' @export xegaPermCrossoverFactory<-function(method="Cross2Gene") { if (method=="Cross2Gene") {f<- xegaPermCross2Gene} if (method=="CrossGene") {f<- xegaPermCrossGene} if (!exists("f", inherits=FALSE)) {stop("xegaPerm Crossover label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermCrossover.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Decode a permutation. #' #' @description \code{xegaPermDecodeGene} decodes a permutation gene. #' @details \code{xegaPermDecodeGene} is the identy function. #' #' @param gene Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A permutation gene. #' #' @family Decoder #' #' @examples #' g<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(g) #' @export xegaPermDecodeGene<-function(gene, lF) { gene$gene1 }
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermDecode.R
#' Genetic operations for permutation genes. #' #' Permutation genes are a representation of a tour of a #' Traveling Salesman Problem (TSP). #' #' For permutation genes, the \code{xegaPermGene} package provides #' \itemize{ #' \item Gene initiatilization. #' \item Decoding of parameters. #' \item Mutation functions as well as a function factory for configuration. #' \item Crossover functions as well as a function factory for configuration. #' } #' #' @section Permutation Gene Representation: #' #' A permutation gene is a named list with at least the following elements: #' \itemize{ #' \item \code{$gene1}: The gene must be a permutation vector. #' \item \code{$fit}: The fitness value of the gene #' (for EvalGeneDet and EvalGeneU) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch). #' \item \code{$evaluated}: Boolean. Has the gene been evaluated? #' \item \code{$evalFail}: Boolean. Has the evaluation of the gene failed? #' } #' #' @section Abstract Interface of a Problem Environment for the TSP: #' #' A problem environment \code{penv} for the TSP must provide: #' \itemize{ #' \item \code{$name()}: Returns the name of the problem environment. #' \item \code{$genelength()}: The number of bits of the binary coded #' real parameter vector. Used in \code{InitGene}. #' \item \code{$dist()}: The distance matrix of the TSP. #' \item \code{$cities()}: A list of city names or \code{1:numberOfCities}. #' \item \code{$f(permutation, gene, lF)}: #' Returns the fitness of the permutation (the length of a tour). #' \item \code{$solution()}: The minimal tour length (if known). #' \item \code{$path()}: An optimal TSP tour. #' \item \code{$show(permutation)}: Prints the tour with the distances #' and the cumulative distances between the cities. #' \item TSP Heuristics: #' \itemize{ #' \item \code{$greedy(startposition, k)}: #' Computes a greedy tour of length k. #' \item \code{$kBestgreedy(k)}: #' Computes the best greedy tour of length k. #' \item \code{$rnd2Opt(permutation, maxTries)}: #' Generate a new permutation by a random 2-change. #' \code{maxTries} is the maximal number of trials #' to find a better permutation. #' \code{$rnd2Opt} either returns #' a better permutation or, if no better permutation can be found #' in \code{maxTries} attempts, the original permutation. #' \item \code{$LinKernighan(permutation, maxTries)}: #' Returns a permutation generated by a random sequence of 2-changes #' with improving performance. The optimality criterion of the #' k Lin-Kernighan heuristics is replaced by the necessity of #' finding a sequence of random 2-changes with strictly #' increasing performance. #' } #' } #' #' @section Abstract Interface of Mutation Functions: #' #' Each mutation function has the following function signature: #' #' \code{newGene<-Mutate(gene, lF)} #' #' All local parameters of the mutation function configured are #' expected in the local configuration \code{lF}. #' #' @section Local Constants of Mutation Functions: #' #' The local constants of a mutation function determine the #' the behavior of the function. #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' \code{lF$BitMutationRate1()} \tab 0.005 \tab xegaPermMutateGeneOrderBased \cr #' \code{lF$Lambda()} \tab 0.05 \tab xegaPermMutateGenekInversion \cr #' \tab \tab xegaPermMutateGenekGreedy \cr #' \tab \tab xegaPermMutateGeneBestGreedy \cr #' \code{lF$max2Opt()} \tab 100 \tab xegaPermMutateGene2Opt \cr #' \tab \tab xegaPermMutateGenekOptLK \cr #' } #' #' @section Abstract Interface of Crossover Functions: #' #' The signatures of the abstract interface to the 2 families #' of crossover functions are: #' #' \code{ListOfTwoGenes<-Crossover2(gene1, gene2, lF)} #' #' \code{newGene<-Crossover(gene1, gene2, lF)} #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split in a representation independent and #' a representation dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler and #' \code{xegaDerivationTrees} an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaPermGene #' @aliases xegaPermGene #' @docType package #' @title Package xegaPermGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaPermGene> #' @section Installation: From CRAN by \code{install.packages('xegaPermGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermGene-package.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # # require(xegaSelectGene) #' Returns elements of #' vector \code{x} without elements in \code{y}. #' #' @param x Vector. #' @param y Vector. #' #' @return Vector. #' #' @family Utility #' #' @examples #' a<-sample(1:15,15, replace=FALSE) #' b<-c(1, 3, 5) #' without(a, b) #' @export without<-function(x, y) { x[!unlist(lapply(x, function(z) is.element(z, y)))] } #' Exponential decay. #' #' @param t Number of objects. #' @param lambda Exponential decay constant. #' #' @return Vector with t elements with values of exponential decay. #' #' @family Utility #' #' @examples #' Decay(5, 0.4) #' Decay(10, 0.4) #' #' @export Decay<-function(t, lambda=0.05) { exp(1)^(-lambda*(1:t))}
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermGene.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Initialize a gene with a permutation of integers #' #' @description \code{xegaPermInitGene} generates a random permutation #' with a given length n. #' #' #' @details In the permutation representation of #' package \code{xegaPerm}, \emph{gene} is a list with #' \enumerate{ #' \item \code{$evaluated}: Boolean: TRUE if the fitness is known. #' \item \code{$fit}: The fitness of the genotype of #' \code{$gene1}. #' \item \code{$gene1}: The permutation (the genetopye). #' } #' #' This representation makes several code optimizations #' and generalizations easier. #' #' @param lF Local configuration of the genetic algorithm. #' #' @return A permutation gene. #' #' @family Initialization #' #' @examples #' xegaPermInitGene(lFxegaPermGene) #' #' @export xegaPermInitGene<-function(lF) { gene1<-sample(1:lF$penv$genelength(), lF$penv$genelength(), replace=FALSE) return(list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=gene1)) }
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermInitGene.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Mutate a gene (generalized order based mutation). #' #' @description \code{xegaPermMutateGene} mutates a permutation. #' The per position mutation rate is given by #' \code{lF$BitMutationRate1()}. #' #' @details This operator is an implementation of a generalized #' order based mutation operator (Syswerda, 1991). #' #' \enumerate{ #' \item The indices of a random subschedule are extracted. #' \item The subschedule is extracted, permuted, and reinserted. #' } #' #' @references Syswerda, G. (1991): #' Schedule Optimization Using Genetic Algorithms. #' In: Davis, L. (Ed.): #' Handbook of Genetic Algorithms, Chapter 21, pp. 332-349. #' Van Nostrand Reinhold, New York. #' (ISBN:0-442-00173-8) #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGeneOrderBased(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' @importFrom stats runif #' @export xegaPermMutateGeneOrderBased<-function(gene, lF) { ng<-gene newgene1<-gene1<-gene$gene1 l<-length(gene1) pos<-(1:l)[stats::runif(l, 0, 1)<lF$BitMutationRate1()] p<-length(pos) gene1[pos]<-gene1[pos[sample(1:p, p, replace=FALSE)]] ng$evaluated<-FALSE ng$gene1<-gene1 return(ng) } #' Mutate a gene (k random inversions). #' #' @description \code{xegaPermMutateGenekInversion} performs k random inversions. #' The number of inversions is expontially decaying #' with exponential decay constant \code{lambda}. #' #' @details The only difference to the order based mutation #' operator (Syswerda, 1991) is the exponential decay #' in the number of inversions. #' #' \enumerate{ #' \item The indices of a random subschedule are extracted. #' \item The subschedule is extracted, permuted, and reinserted. #' } #' #' @references Syswerda, G. (1991): #' Schedule Optimization Using Genetic Algorithms. #' In: Davis, L. (Ed.): #' Handbook of Genetic Algorithms, Chapter 21, pp. 332-349. #' Van Nostrand Reinhold, New York. #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGenekInversion(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' #' @importFrom xegaSelectGene SelectPropFitDiff #' @export xegaPermMutateGenekInversion<-function(gene, lF) { ng<-gene newgene1<-gene1<-gene$gene1 len<-length(gene1) l<-xegaSelectGene::SelectPropFitDiff(Decay(len-1, lF$Lambda()), lF) pos<-sample((1:len), l, replace=FALSE) p<-length(pos) gene1[pos]<-gene1[pos[sample(1:p, p, replace=FALSE)]] ng$evaluated<-FALSE ng$gene1<-gene1 return(ng) } #' Mutate a gene (by a random 2-Opt move). #' #' @description \code{xegaPermMutateGene2Opt} mutates a permutation. #' The per position mutation rate is given by MutationRate(). #' #' @details This operator is an implementation of the 2-Opt move #' due to Croes (1958). #' #' Two edges are exchanged, if the exchange improves the result. #' #' @references Croes, G. A. (1958): #' A Method for Solving Traveling-Salesman Problems. #' Operations Research, 6(6), pp. 791-812. #' <doi:10.1287/opre.6.6.791> #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGene2Opt(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' @importFrom stats runif #' @export xegaPermMutateGene2Opt<-function(gene, lF) { newgene<-gene tour<-lF$penv$rnd2Opt(gene$gene1, lF$Max2Opt()) newgene$evaluated<-FALSE newgene$gene1<-tour newgene<-lF$EvalGene(newgene, lF) return(newgene) } #' Mutate a gene (by a random Lin-Kernighan k-OPT move). #' #' @description \code{xegaPermMutateGenekOptLK} mutates a permutation. #' The mutation rate of a gene is given by MutationRate(). #' #' @details This operator is an implementation of the random k-Opt move #' version of the Lin-Kernighan heuristic. #' #' A sequence of random 2-Opt moves, all of which improve #' the result is executed. #' #' @references Lin, S. and Kernighan. B. W. (1973): #' An Effective Heuristic Algorithm #' for the Traveling-Salesman Problem. #' Operations Research, 21(2), pp. 791-812. #' <doi:10.1287/opre.21.2.498> #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGenekOptLK(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' @importFrom stats runif #' @export xegaPermMutateGenekOptLK<-function(gene, lF) { newgene<-gene tour<-lF$penv$LinKernighan(gene$gene1, lF$Max2Opt()) newgene$evaluated<-FALSE newgene$gene1<-tour newgene<-lF$EvalGene(newgene, lF) return(newgene) } #' Mutate a gene (by inserting a greedy path at start of random length k). #' #' @description \code{xegaPermMutateGeneGreedy} mutates a permutation #' by inserting a greedy path of length \code{k} #' at a random position \code{start}. #' The mutation rate for a gene is given by MutationRate(). #' #' @details The path length \code{k} is expontially decaying #' with exponential decay constant \code{lambda}. #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGeneGreedy(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' @importFrom xegaSelectGene SelectPropFit #' @export xegaPermMutateGeneGreedy<-function(gene, lF) { newgene<-gene ng1<-newgene$gene1 l<-length(ng1) start<-sample(1:l, 1) k<-xegaSelectGene::SelectPropFit(Decay(l-1, lF$Lambda()), lF) path<-lF$penv$greedy(ng1[start], k) if (length(path)==length(ng1)) { newgene$evaluated<-TRUE newgene$gene1<-path newgene<-lF$EvalGene(newgene, lF) return(newgene)} ng<-without(ng1,path) index<-(1:length(ng))<sample(1:length(ng),1) new<-c(ng[index], path, ng[!index]) newgene$evaluated<-TRUE newgene$gene1<-new newgene<-lF$EvalGene(newgene, lF) return(newgene)} #' Mutate a gene (by inserting a greedy path at start of random length k). #' #' @description \code{xegaPermMutateGeneGreedy} mutates a permutation #' by inserting a greedy path of length \code{k} #' at a random position \code{start}. #' The mutation rate for a gene is given by \code{MutationRate()}. #' #' @details The path length \code{k} is expontially decaying #' with exponential decay constant \code{lF$lambda()}. #' #' @param gene A Permutation. #' @param lF Local configuration of the genetic algorithm. #' #' @return A Permutation #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateGeneGreedy(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #' @importFrom xegaSelectGene SelectPropFit #' @export xegaPermMutateGeneBestGreedy<-function(gene, lF) { newgene<-gene ng1<-newgene$gene1 l<-length(ng1) k<-xegaSelectGene::SelectPropFit(Decay(l-1, lF$Lambda()), lF) path<-lF$penv$kBestGreedy(k) if (length(path)==length(ng1)) { newgene$evaluated<-TRUE newgene$gene1<-path newgene<-lF$EvalGene(newgene, lF) return(newgene)} ng<-without(ng1,path) index<-(1:length(ng))<sample(1:length(ng),1) new<-c(ng[index], path, ng[!index]) newgene$evaluated<-TRUE newgene$gene1<-new newgene<-lF$EvalGene(newgene, lF) return(newgene)} #' Mutation by a random mutation function. #' #' A mutation function is randomly selected from the following list: #' xegaPermMutateGeneOrderBased, xegaPermMutateGenekInversion, #' xegaPermMutateGene2Opt, xegaPermMutateGenekOptLK, xegaPermMutateGeneGreedy, #' xegaPermMutateGeneBestGreedy. #' #' @param gene A permutation. #' @param lF Local configuration. #' #' @return A permutation. #' #' @family Mutation #' #' @examples #' gene1<-xegaPermInitGene(lFxegaPermGene) #' xegaPermDecodeGene(gene1, lFxegaPermGene) #' gene<-xegaPermMutateMix(gene1, lFxegaPermGene) #' xegaPermDecodeGene(gene, lFxegaPermGene) #'@export xegaPermMutateMix<-function(gene, lF) { ML<-list(xegaPermMutateGeneOrderBased, xegaPermMutateGenekInversion, xegaPermMutateGene2Opt, xegaPermMutateGenekOptLK, xegaPermMutateGeneGreedy, xegaPermMutateGeneBestGreedy) ng<-ML[[sample(1:length(ML),1)]](gene, lF) return(ng) } #' Configure the mutation function of a genetic algorithm. #' #' @description \code{xegaPermMutationFactory} implements the selection #' of one of the gene mutation functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current Support: #' #' \enumerate{ #' \item "MutateGene" returns \code{xegaPermMutateGeneOrderBased}. #' \item "MutateGeneOrderBased" returns \code{xegaPermMutateGeneOrderBased}. #' \item "MutateGenekInversion" returns \code{xegaPermMutateGenekInversion}. #' \item "MutateGene2Opt" returns \code{xegaPermMutateGene2Opt}. #' \item "MutateGenekOptLK" returns \code{xegaPermMutateGenekOptLK}. #' \item "MutateGeneGreedy" returns \code{xegaPermMutateGeneGreedy}. #' \item "MutateGeneBestGreedy" returns \code{xegaPermMutateGeneBestGreedy}. #' \item "MutateGeneMix" returns \code{xegaPermMutateMix}. #' } #' #' @param method The name of the mutation method. #' #' @return A permutation based mutation function. #' #' @family Configuration #' #' @examples #' xegaPermMutationFactory(method="MutateGene") #' @export xegaPermMutationFactory<-function(method="MutateGene") { if (method=="MutateGene") {f<- xegaPermMutateGeneOrderBased} if (method=="MutateGeneOrderBased") {f<- xegaPermMutateGeneOrderBased} if (method=="MutateGenekInversion") {f<- xegaPermMutateGenekInversion} if (method=="MutateGene2Opt") {f<- xegaPermMutateGene2Opt} if (method=="MutateGenekOptLK") {f<- xegaPermMutateGenekOptLK} if (method=="MutateGeneGreedy") {f<- xegaPermMutateGeneGreedy} if (method=="MutateGeneBestGreedy") {f<- xegaPermMutateGeneBestGreedy} if (method=="MutateGeneMix") {f<- xegaPermMutateMix} if (!exists("f", inherits=FALSE)) {stop("xegaPerm Mutation Factory label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermMutate.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Generate local functions and objects. #' #' @description #' \code{lFxegaPermGene} is a list of functions #' which contains a definition of all local objects #' required for the use of genetic operators with the # permutation representation. #' We refer to this object as local configuration. #' #' @details #' We use the local function list (the local configuration) for #' \enumerate{ #' \item #' replacing all constants by constant functions. #' #' Rationale: We need one formal argument (the local function list lF) #' and we can dispatch multiple functions. E.g. \code{lF$verbose()} #' \item #' for dynamically binding a local function with a definition from a #' proper function factory. E.g. the selection methods #' \code{lf$SelectGene} and \code{SelectMate}. #' #' \item for gene representation specific special functions: #' \code{lf$InitGene}, \code{lF$DecodeGene}, \code{lf$EvalGene} #' \code{lf$ReplicateGene}, ... #' #' } #' #' @family Configuration #' #' @importFrom xegaSelectGene parm #' @importFrom xegaSelectGene lau15 #' @export lFxegaPermGene<-list( penv=xegaSelectGene::lau15, replay=xegaSelectGene::parm(0), verbose=xegaSelectGene::parm(4), MutationRate=xegaSelectGene::parm(0.2), BitMutationRate1=xegaSelectGene::parm(0.2), Max2Opt=xegaSelectGene::parm(100), Lambda=xegaSelectGene::parm(0.05), CrossRate=xegaSelectGene::parm(0.8), Max=xegaSelectGene::parm(1), Offset=xegaSelectGene::parm(1), Eps=xegaSelectGene::parm(0.01), Elitist=xegaSelectGene::parm(TRUE), TournamentSize=xegaSelectGene::parm(2), SelectGene=xegaSelectGene::SelectGeneFactory(method="Proportional"), SelectMate=xegaSelectGene::SelectGeneFactory(method="Proportional"), MutateGene=xegaPermMutationFactory(method="MutateGene2Opt"), CrossGene=xegaPermCrossGene, InitGene=xegaPermInitGene, DecodeGene=xegaPermDecodeGene, EvalGene=xegaSelectGene::EvalGeneFactory(method="EvalGeneU"), lapply=base::lapply )
/scratch/gouwar.j/cran-all/cranData/xegaPermGene/R/xegaPermlF.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-level functions. # Independent of gene representation. # Package: # #' Accepts a new gene. #' #' @description Executes a genetic operator pipeline. #' The new gene is returned. #' #' @param OperatorPipeline Genetic operator pipeline (an R function). #' @param gene Gene. #' @param lF Local configuration. #' #' @return New gene. #' #' @family Acceptance Rule #' #' @examples #' id<-function(x, lF){x} #' g1<-InitGene(lFxegaGaGene) #' AcceptNewGene(id, g1, lFxegaGaGene) #' @export AcceptNewGene<-function(OperatorPipeline, gene, lF) { newGene<-OperatorPipeline(gene, lF) if (newGene$evalFail) { warning("AcceptNewGene: Evaluation failed. Gene: \n", newGene) } return(newGene)} #' Accepts only genes with equal or better fitness. #' #' @description Change the gene by a genetic operator pipeline #' and return the new gene only if the new gene #' has at least the same fitness as the gene. #' #' @details The fitness of genes never decreases. #' New genes with inferior fitness do not survive. #' #' @param OperatorPipeline Genetic operator pipeline. #' @param gene Gene. #' @param lF Local configuration. #' #' @return The new gene, if it is at least as fit as \code{gene} else #' the old gene \code{gene}. #' #' @family Acceptance Rule #' #' @examples #' OPpipe1<-function(g, lF){InitGene(lF)} #' g1<-lFxegaGaGene$EvalGene(InitGene(lFxegaGaGene), lFxegaGaGene) #' g2<-AcceptBest(OPpipe1, g1, lFxegaGaGene) #' identical(g1, g2) #' @export AcceptBest<-function(OperatorPipeline, gene, lF) { newGene<- lF$EvalGene(OperatorPipeline(gene, lF), lF) if (newGene$evalFail) { warning("AcceptBest: Evaluation failed. Gene: \n", newGene) } if(newGene$fit>=gene$fit) {return(newGene)} else {return(gene)}} #' Metropolis Acceptance Rule. #' #' @description Change the gene by a genetic operator pipeline. #' Always accept a new gene with a fitness improvement. #' For maximizing fitness #' accept genes with lower fitness with probability #' \code{(runif(1)<exp(-(fitness-newfitness)*beta/Temperature)} #' and reduce temperature with a cooling schedule. #' Used: \code{Temperature<-alpha*Temperature} with #' \code{alpha<1}. #' #' @details The temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' #' @param OperatorPipeline Genetic operator pipeline. #' @param gene Gene. #' @param lF Local configuration. #' #' @return The new gene if it has at least equal performance as the #' old gene else the old gene. #' #' @references #' Kirkpatrick, S., Gelatt, C. D. J, and Vecchi, M. P. (1983): #' Optimization by Simulated Annealing. #' Science, 220(4598): 671-680. #' <doi:10.1126/science.220.4598.671> #' #' Metropolis, N., Rosenbluth, A. W., Rosenbluth, M. N., Teller, A. H., #' Teller, E. (1953): #' Equation of state calculations by fast computing machines. #' Journal of Chemical Physics, 21(6):1087 – 1092. #' <doi:10.1063/1.1699114> #' #' @family Acceptance Rule #' #' @examples #' parm<-function(x){function() {return(x)}} #' lFxegaGaGene$Beta<-parm(1) #' lFxegaGaGene$TempK<-parm(10) #' OPpipe1<-function(g, lF){InitGene(lF)} #' g1<-lFxegaGaGene$EvalGene(InitGene(lFxegaGaGene), lFxegaGaGene) #' g2<-AcceptMetropolis(OPpipe1, g1, lFxegaGaGene) #' @importFrom stats runif #' @export AcceptMetropolis<-function(OperatorPipeline, gene, lF) { newGene<- lF$EvalGene(OperatorPipeline(gene, lF), lF) if (newGene$evalFail) { warning("Accept Best: Evaluation failed. Gene: \n", newGene) } if(newGene$fit>=gene$fit) {return(newGene)} d<-gene$fit-newGene$fit if (runif(1) < exp(-d*lF$Beta()/lF$TempK())) {return(newGene)} else {return(gene)} } #' Individually Adaptive Metropolis Acceptance Rule. #' #' @description Change the gene by a genetic operator pipeline. #' Always accept new genes with fitness improvement. #' For maximizing fitness #' accept genes with lower fitness with probability #' \code{(runif(1)<exp(-(fitness-newfitness)*beta/Temperature)} #' and reduce temperature with a cooling schedule. #' For each gene, the temperature is corrected upward by a term #' whose size is proportional to #' the difference between the fitness of the current best gene #' in the population and the fitness of the gene. #' #' @details The temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' #' @param OperatorPipeline Genetic operator pipeline. #' @param gene Gene. #' @param lF Local configuration. #' #' @return The new gene if it has at least equal performance as the old gene #' else the old gene. #' #' @references #' Locatelli, M. (2000): #' Convergence of a Simulated Annealing Algorithm for #' Continuous Global Optimization. #' Journal of Global Optimization, 18:219-233. #' <doi:10.1023/A:1008339019740> #' #' The-Crankshaft Publishing (2023): #' A Comparison of Cooling Schedules for Simulated Annealing. #' <URL:https://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/> #' #' @family Acceptance Rule #' #' @examples #' parm<-function(x){function() {return(x)}} #' lFxegaGaGene$Beta<-parm(1) #' lFxegaGaGene$TempK<-parm(10) #' set.seed(2) #' OPpipe1<-function(g, lF){InitGene(lF)} #' g1<-lFxegaGaGene$EvalGene(InitGene(lFxegaGaGene), lFxegaGaGene) #' lFxegaGaGene$CBestFitness<-parm(g1$fit) #' g2<-AcceptMetropolis(OPpipe1, g1, lFxegaGaGene) #' @importFrom stats runif #' @export AcceptIVMetropolis<-function(OperatorPipeline, gene, lF) { newGene<- lF$EvalGene(OperatorPipeline(gene, lF), lF) if (newGene$evalFail) { warning("Accept Best: Evaluation failed. Gene: \n", newGene) } if(newGene$fit>=gene$fit) {return(newGene)} d<-gene$fit-newGene$fit # Individually Variable adaptive correction of temperature: Tcorrected<-lF$TempK()*min(2,(1+((lF$CBestFitness()-gene$fit)/gene$fit))) if (runif(1) < exp(-d*lF$Beta()/Tcorrected)) {return(newGene)} else {return(gene)} } #' Metropolis acceptance probability. #' #' @param d Distance between the fitness of the old and the new gene. #' @param beta Constant. #' @param temperature Temperature. #' #' @return Acceptance probability. #' #' @family Diagnostic #' #' @examples #' MetropolisAcceptanceProbability(d=0, beta=1, temperature=10) #' MetropolisAcceptanceProbability(d=1, beta=1, temperature=10) #'@export MetropolisAcceptanceProbability<-function(d, beta, temperature) { exp(-d*beta/temperature) } #' Metropolis acceptance probability table. #' #' @param d Distance between the fitness of the old and the new gene. #' @param beta Constant. #' @param temperature Temperature. #' @param alpha Cooling constant in [0, 1]. #' @param steps Number of steps. #' #' @return Data frame with the columns alpha, beta, temperature, #' d (distance between fitness), and probability of acceptance. #' #' @family Diagnostic #' #' @examples #' MetropolisTable(d=2, beta=2, temperature=10, alpha=0.99, steps=10) #'@export MetropolisTable<-function(d=1, beta=2, temperature=1000, alpha=0.9, steps=1000) { df<-data.frame(matrix(ncol=5, nrow=steps)) colnames(df)<-c("alpha", "beta", "Temperature", "d", "P(Accept)") for (i in (1:steps)) { df[i,]<-c(alpha, beta, temperature, d, MetropolisAcceptanceProbability(d, beta, temperature)) temperature<-alpha*temperature } return(df) } #' Configure the acceptance function of a genetic algorithm. #' #' @description \code{AcceptanceFactory()} implements selection #' of an acceptance rule. #' #' Current support: #' #' \enumerate{ #' \item "All" returns \code{AcceptNewGene()} (Default). #' \item "Best" returns \code{AcceptBest()}. #' \item "Metropolis" returns \code{AcceptMetropolis()}. #' \item "IVMetropolis" returns \code{AcceptIVMetropolis()}. #' } #' #' @param method A string specifying the acceptance rule. #' #' @return An acceptance rule for genes. #' #' @family Configuration #' #' @export AcceptFactory<-function(method="All") { if (method=="All") {f<- AcceptNewGene} if (method=="Best") {f<- AcceptBest} if (method=="Metropolis") {f<- AcceptMetropolis} if (method=="IVMetropolis") {f<- AcceptIVMetropolis} if (!exists("f", inherits=FALSE)) {stop("Acceptance label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/acceptance.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-level functions. # Independent of gene representation. # Package: # #' Individually adaptive crossover rate. #' #' @description The basic idea is to apply crossover to a gene whose #' fitness is below a threshold value with higher probability #' to give it a chance #' to improve. The threshold value is computed by #' \code{lF$CutoffFit()*lF$CBestFitness()}. #' #' @details The following constants are used: #' \code{lF$CrossRate1()<lF$CrossRate2()}, and #' \code{lF$CutoffFit()} in [0, 1]. #' #' @references #' Stanhope, Stephen A. and Daida, Jason M. (1996) #' An Individually Variable Mutation-rate Strategy for Genetic Algorithms. #' In: Koza, John (Ed.) #' Late Breaking Papers at the Genetic Programming 1996 Conference. #' Stanford University Bookstore, Stanford, pp. 177-185. #' (ISBN:0-18-201-031-7) #' #' @param fit Fitness of gene. #' @param lF Local configuration. #' #' @return Crossover rate of a gene depending on its fitness. #' #' @family Adaptive Rates #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list() #' lF$CrossRate1<-parm(0.20) #' lF$CrossRate2<-parm(0.40) #' lF$CutoffFit<-parm(0.60) #' lF$CBestFitness<-parm(105) #' IACRate(100, lF) #' IACRate(50, lF) #' @export IACRate<-function(fit, lF) { if (fit>(lF$CutoffFit()*lF$CBestFitness())) {lF$CrossRate1()} else {lF$CrossRate2()} } #' Constant crossover rate. #' #' #' @param fit Fitness of gene. #' @param lF Local configuration. #' #' @return Constant crossover rate. #' #' @family Rates #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(CrossRate1=parm(0.20)) #' ConstCRate(100, lF) #' ConstCRate(50, lF) #' @export ConstCRate<-function(fit, lF) { lF$CrossRate1() } #' Configure the crossover function of a genetic algorithm. #' #' @description \code{CrossRateFactory()} implements selection #' of one of the crossover rate functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Const" returns \code{ConstCRate()}. #' \item "IV" returns \code{IACrate()}. #' This function gives bad genes a higher cross rate. #' } #' #' @param method A string specifying a function for the crossover rate. #' #' @return Crossover rate function. #' #' @family Configuration #' #' @examples #' f<-CrossRateFactory("Const") #' f(10, list(CrossRate1=function() {0.2})) #' @export CrossRateFactory<-function(method="Const") { if (method=="Const") {f<- ConstCRate} if (method=="IV") {f<- IACRate} if (!exists("f", inherits=FALSE)) {stop("Crossover Rate label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/adaptivityCrossover.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-level functions. # Independent of gene representation. # Package: # #' Individually adaptive mutation rate. #' #' @description The probability of applying a mutation operator #' to a gene. The idea is that a gene selected for #' reproduction whose fitness is #' below a threshold value is mutated with a higher #' probability to give it a chance. #' #' @details The probability of applying a mutation operator is #' determined by a threshold: If the fitness of a gene #' is higher than \code{lF$CutoffFit()*lF$CBestFitness()}, #' than return \code{lF$MutationRate1()} #' else \code{lF$MutationRate2()}. #' #' Note that the idea is also applicable to gene specific #' local mutation operators. For example, the bit mutation rate #' of mutation operators for binary genes. #' #' @references #' Stanhope, Stephen A. and Daida, Jason M. (1996) #' An Individually Variable Mutation-rate Strategy for Genetic Algorithms. #' In: Koza, John (Ed.) #' Late Breaking Papers at the Genetic Programming 1996 Conference. #' Stanford University Bookstore, Stanford, pp. 177-185. #' (ISBN:0-18-201-031-7) #' #' @param fit Fitness of gene. #' @param lF Local configuration. #' #' @return Mutation rate of a gene depending on its fitness. #' #' @family Adaptive Rates #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list() #' lF$MutationRate1<-parm(0.20) #' lF$MutationRate2<-parm(0.40) #' lF$CutoffFit<-parm(0.60) #' lF$CBestFitness=parm(105) #' IAMRate(100, lF) #' IAMRate(50, lF) #' @export IAMRate<-function(fit, lF) { if (fit>(lF$CutoffFit()*lF$CBestFitness())) {lF$MutationRate1()} else {lF$MutationRate2()} } #' Constant mutation rate. #' #' @param fit Fitness of gene. #' @param lF Local configuration. #' #' @return Constant mutation rate. #' #' @family Rates #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list() #' lF$MutationRate1<-parm(0.20) #' ConstMRate(100, lF) #' ConstMRate(50, lF) #' @export ConstMRate<-function(fit, lF) { lF$MutationRate1() } #' Configure the mutation rate function of a genetic algorithm. #' #' @description The \code{MutationRateFactory()} implements selection #' of one of the crossover rate functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Const" returns \code{ConstMRate()} (Default). #' \item "IV" returns \code{IAMrate()}. #' This function gives bad genes a higher mutation rate. #' } #' #' @param method A string specifying a function for the mutation rate. #' #' @return A mutation rate function. #' #' @family Configuration #' #' @examples #' f<-MutationRateFactory("Const") #' f(10, list(MutationRate1=function() {0.2})) #' @export MutationRateFactory<-function(method="Const") { if (method=="Const") {f<- ConstMRate} if (method=="IV") {f<- IAMRate} if (!exists("f", inherits=FALSE)) {stop("Mutation Rate label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/adaptivityMutation.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Population-level functions. # Independent of gene representation. # Package: xegaPopulation. # #' Remembers R command command with which algorithm has been called. #' #' @description \code{xegaConfiguration()} returns the command with which #' the genetic algorithm has been called. #' For replicating computational experiments with #' genetic algorithms. #' #' @param GAname Name of genetic algorithm's main function. #' (Currently: "Run"). #' @param penv The expression for the problem environment \code{penv}. #' Use: \code{substitute(penv)}. #' @param grammar The grammar \code{grammar}. #' Use: \code{substitute(grammar)}. #' @param env Environment with variable value bindings. #' Use: \code{environment()}. #' #' @return A named list with the following elements: #' \itemize{ #' \item \code{$GAconf}: #' A text string with the call of the genetic algorithm #' (the function we want to capture the call). #' \item \code{$GAenv}: The environment with the arguments bound to the #' values when the genetic algorithm was called. #' } #' #' @section Warning: #' \itemize{ #' \item #' $GAenv is correct only for simple arguments (strings or numbers) #' not for complex objects like problem environments. #' \item #' \code{future.apply::future_lapply()} is configured by a plan #' statement which must be issued before calling the genetic #' algorithm. At the moment, the plan chosen is not remembered. #' } #' #' @family Configuration #' #' @examples #' GA<-function(pe, grammar=NULL, nope=1.5, sle="test", ok=TRUE) #' {xegaConfiguration("GA", substitute(pe), substitute(grammar), environment())} #' Para<-5 #' GA(Para) #' Cube<-7 #' GA(Cube, 2, 3, 4) #' #' @export xegaConfiguration<-function(GAname, penv, grammar, env) { arglst<-as.list(env) penvName<-as.character(penv) if (is.null(grammar)) {grammarName<-"grammar=NULL"} else {grammarName<-as.character(grammar)} GAcall<-paste(GAname,"(", penvName, ",", grammarName, sep="") for (i in 3: length(arglst)) { if (typeof(unlist(arglst[i]))=="character") {GAcall<-paste(GAcall, ",", names(arglst[i]), "=\"", arglst[i], "\"", sep="")} else {GAcall<-paste(GAcall, ",", names(arglst[i]), "=", arglst[i], sep="")} } GAcall<-paste(GAcall,")", sep="") return(list(GAconf=GAcall, GAenv=arglst)) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/configuration.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-level functions. # Independent of gene representation. # Package: # #' Exponential multiplicative cooling. #' #' @description The temperature at time k is the net present value #' of the starting temperature. The discount factor #' is \code{lF$Alpha()}. #' \code{lF$Alpha()} should be in \code{[0, 1]}. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$Alpha()} is the discount factor. #' #' @param k Number of steps to discount. #' @param lF Local configuration. #' #' @return Temperature at time k. #' #' @references #' Kirkpatrick, S., Gelatt, C. D. J, and Vecchi, M. P. (1983): #' Optimization by Simulated Annealing. #' Science, 220(4598): 671-680. #' <doi:10.1126/science.220.4598.671> #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), Alpha=parm(0.99)) #' ExponentialMultiplicativeCooling(0, lF) #' ExponentialMultiplicativeCooling(2, lF) #' @export ExponentialMultiplicativeCooling<-function(k, lF) { return(lF$Temp0()*lF$Alpha()^k) } #' Logarithmic multiplicative cooling. #' #' @description This schedule decreases by the inverse proportion of the #' natural logarithm #' of \code{k}. \code{lF$Alpha()} should be larger than 1. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$Alpha()} is a scaling factor. #' #' @param k Number of steps to discount. #' @param lF Local configuration. #' #' @return Temperature at time k. #' #' Aarts, E., and Korst, J. (1989): #' Simulated Annealing and Boltzmann Machines. #' A Stochastic Approach to Combinatorial Optimization and #' Neural Computing. #' John Wiley & Sons, Chichester. #' (ISBN:0-471-92146-7) #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), Alpha=parm(1.01)) #' LogarithmicMultiplicativeCooling(0, lF) #' LogarithmicMultiplicativeCooling(2, lF) #' @export LogarithmicMultiplicativeCooling<-function(k, lF) { return(lF$Temp0()/(1+lF$Alpha()*log(1+k))) } #' Power multiplicative cooling. #' #' @description This schedule decreases by the inverse proportion of #' a power #' of \code{k}. \code{lF$Alpha()} should be larger than 1. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' For \code{lF$CoolingPower()==1} and #' \code{lF$CoolingPower()==2} this results in the #' the linear and quadratic multiplicative cooling schemes #' in A Comparison of Cooling Schedules for Simulated Annealing. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$Alpha()} is a scaling factor. #' \code{lF$CoolingPower()} is an exponential factor. #' #' @param k Number of steps to discount. #' @param lF Local configuration. #' #' @return Temperature at time k. #' #' @references The-Crankshaft Publishing (2023) #' A Comparison of Cooling Schedules for Simulated Annealing. #' <https://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/> #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), Alpha=parm(1.01), CoolingPower=parm(2)) #' PowerMultiplicativeCooling(0, lF) #' PowerMultiplicativeCooling(2, lF) #' @export PowerMultiplicativeCooling<-function(k, lF) { return(lF$Temp0()/(1+lF$Alpha()*(k^lF$CoolingPower()))) } #' Power additive cooling. #' #' @description This schedule decreases by a power of the #' n (= number of generations) linear fractions #' between the starting temperature \code{lF$Temp0} #' and the final temperature \code{lF$tempN}. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$TempN()} is the final temperature. #' \code{lF$CoolingPower()} is an exponential factor. #' \code{lF$Generations()} is the number of generations (time). #' #' @param k Number of steps to discount. #' @param lF Local configuration. #' #' @return Temperature at time k. #' #' @references The-Crankshaft Publishing (2023) #' A Comparison of Cooling Schedules for Simulated Annealing. #' <https://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/> #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), TempN=parm(10), Generations=parm(50), CoolingPower=parm(2)) #' PowerAdditiveCooling(0, lF) #' PowerAdditiveCooling(2, lF) #' @export PowerAdditiveCooling<-function(k, lF) { fraction<-((lF$Generations()-k)/lF$Generations())^lF$CoolingPower() return(lF$TempN()+(lF$Temp0()-lF$TempN())*fraction) } #' Exponential additive cooling. #' #' @description This schedule decreases in proportion to the #' inverse of \code{exp} raised to the #' power of the temperature cycle in #' \code{lF$Generations()} (= number of generations) fractions #' between the starting temperature \code{temp0} #' and the final temperature \code{tempN}. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$TempN()} is the final temperature. #' \code{lF$Generations()} is the number of generations (time). #' #' @param k Number of steps to discount. #' @param lF Local configuration. #' #' @return The temperature at time k. #' #' @references The-Crankshaft Publishing (2023) #' A Comparison of Cooling Schedules for Simulated Annealing. #' <https://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/> #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), TempN=parm(10), Generations=parm(50)) #' ExponentialAdditiveCooling(0, lF) #' ExponentialAdditiveCooling(2, lF) #' @export ExponentialAdditiveCooling<-function(k, lF) { d<-lF$Temp0()-lF$TempN() t<-2*log(d)/lF$Generations() fraction<-1/(1+exp(t*(k-0.5*lF$Generations()))) return(lF$TempN()+d*fraction) } #' Trigonometric additive cooling. #' #' @description This schedule decreases in proportion to the #' cosine of the temperature cycle in #' \code{lF$Generations()} (= number of generations) fractions #' between the starting temperature \code{lF$Temp0()} #' and the final temperature \code{lF$TempN()}. #' #' @details Temperature is updated at the end of each generation #' in the main loop of the genetic algorithm. #' \code{lF$Temp0()} is the starting temperature. #' \code{lF$TempN()} is the final temperature. #' \code{lF$Generations()} is the number of generations (time). #' #' @param k Number of steps (time). #' @param lF Local configuration. #' #' @return Temperature at time k. #' #' @references The-Crankshaft Publishing (2023) #' A Comparison of Cooling Schedules for Simulated Annealing. #' <https://what-when-how.com/artificial-intelligence/a-comparison-of-cooling-schedules-for-simulated-annealing-artificial-intelligence/> #' #' @family Cooling #' #' @examples #' parm<-function(x){function() {return(x)}} #' lF<-list(Temp0=parm(100), TempN=parm(10), Generations=parm(50)) #' TrigonometricAdditiveCooling(0, lF) #' TrigonometricAdditiveCooling(2, lF) #' @export TrigonometricAdditiveCooling<-function(k, lF) { fraction<-0.5*(1+cos(k*pi/lF$Generations())) return(lF$TempN()+(lF$Temp0()-lF$TempN())*fraction) } #' Configure the cooling schedule of the acceptance #' function of a genetic algorithm. #' #' @description \code{CoolingFactory()} implements selection #' of a cooling schedule method. #' #' Current support: #' #' \enumerate{ #' \item "ExponentialMultiplicative" returns #' \code{ExponentialMultiplicativeCooling}. (Default) #' \item "LogarithmicMultiplicative" returns #' \code{LogarithmicMultiplicativeCooling}. #' \item "PowerMultiplicative" returns #' \code{PowerMultiplicativeCooling}. #' \code{coolingPower=1} specifies linear multiplicative cooling, #' \code{coolingPower=2} specifies quadratic multiplicative cooling. #' \item "PowerAdditive" returns #' \code{PowerAdditiveCooling}. #' \code{coolingPower=1} specifies linear additive cooling, #' \code{coolingPower=2} specifies quadratic additive cooling. #' \item "ExponentialAdditive" returns #' \code{ExponentialAdditiveCooling}. #' \item "TrigonometricAdditive" returns #' \code{TrigonometricAdditiveCooling}. #' } #' #' @param method A string specifying the cooling schedule. #' #' @return A cooling schedule. #' #' @family Configuration #' #' @export CoolingFactory<-function(method="ExponentialMultiplicative") { if (method=="ExponentialMultiplicative") {f<- ExponentialMultiplicativeCooling} if (method=="LogarithmicMultiplicative") {f<- LogarithmicMultiplicativeCooling} if (method=="PowerMultiplicative") {f<- PowerMultiplicativeCooling} if (method=="PowerAdditive") {f<- PowerAdditiveCooling} if (method=="ExponentialAdditive") {f<- ExponentialAdditiveCooling} if (method=="TrigonometricAdditive") {f<- TrigonometricAdditiveCooling} if (!exists("f", inherits=FALSE)) {stop("Acceptance label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/cooling.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-level functions. # Independent of gene representation. # Package: # #' Individually adaptive mutation rate. (Bit mutation Rate) #' #' @description Adaptivity of a local operator mutation parameter. #' Currently not used. Implements a threshold rule. #' The rule is implemented directly in IVAdaptiveMutateGene. #' in package xegaGaGene. Move? #' #' @details TODO: Move this xegaGaGene and generalize the #' bit mutation operator and introduce a factory #' for bit mutation rates. Rationale: Local parameters #' are representation dependent. #' #' @param fit Fitness of gene. #' @param lF Local configuration. #' #' @return Mutation rate of a gene depending on its fitness. #' #' @export IAMBitRate<-function(fit, lF) { if (fit>(lF$CutoffFit()*lF$CBestFitness())) {lF$BitMutationRate1()} else {lF$BitMutationRate2()} }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/localAdaptivity.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Population-level functions. # Independent of gene representation. # Package: xegaPopulation. # # # Execution models of evaluation of a population: # #' MultiCore apply of library parallel. #' #' @description #' The evaluation of the fitness of the genes of the population #' is distributed to one worker on each core of the CPU of the #' local machine. #' The package of \code{parallel} of base R is used. #' The number of cores is provided by \code{lF$Cores}. #' #' @details #' Be aware that #' \itemize{ #' \item \code{parallel::mclapply()} assumes that each function evaluation #' needs approximately the same time. #' \item Best results are obtained if \code{popsize} modulo \code{cores-1} is 0. #' \item Does not work on Windows. #' } #' #' @param pop Population of genes. #' @param EvalGene Function for evaluating a gene. #' @param lF Local function configuration which provides #' all functions needed in \code{EvalGene()}. #' #' @return Fitness vector. #' #' @family Execution Model #' #' @examples #' library(parallelly) #' if (supportsMulticore()){ #' lFxegaGaGene$Cores<-function() {2} #' pop<-xegaInitPopulation(1000, lFxegaGaGene) #' popnew<-MClapply(pop, lFxegaGaGene$EvalGene, lFxegaGaGene) #' } #' #' @importFrom parallel mclapply #' @importFrom parallel detectCores #' @export MClapply<-function(pop, EvalGene, lF) # nocov start { # z<-runif(1) parallel::mclapply(pop, EvalGene, lF=lF, mc.cores=max(1, lF$Cores()), mc.set.seed = TRUE) } # nocov end #' Future apply of R-package \code{future.apply}. #' #' @description #' The \code{lapply()} function is redefined as as #' \code{future.apply::future_lapply()}. #' Henrik Bengtsson recommends that the configuration of the #' parallel/distributed programming environment should be kept #' outside the package and left to the user. #' The advantage is that the user may take advantage of all #' parallel/distributed available backends for the Future API. #' #' @details #' Be aware that #' \itemize{ #' \item \code{future_lapply()} assumes that each function evaluation #' need approximately the same time. #' \item Best results are obtained #' if \code{popsize} modulo \code{workers} is \code{0}. #' } #' #' @param pop Population of genes. #' @param EvalGene Function for evaluating a gene. #' @param lF Local function factory which provides #' all functions needed in \code{EvalGene}. #' #' @return Fitness vector. #' #' @references #' Bengtsson H (2021). “A Unifying Framework for Parallel and #' Distributed Processing in R using Futures.” #' The R Journal, 13(2), 208–227. <doi:10.32614/RJ-2021-048> #' #' @family Execution Model #' #' @examples #' pop<-xegaInitPopulation(1000, lFxegaGaGene) #' library(future) #' plan(multisession, workers=2) #' popnew<-futureLapply(pop, lFxegaGaGene$EvalGene, lFxegaGaGene) #' plan(sequential) #' #' @importFrom future.apply future_lapply #' @export futureLapply<-function(pop, EvalGene, lF) # nocov start { future.apply::future_lapply(pop, EvalGene, lF=lF, future.seed=TRUE) } # nocov end #' uses parLapply of library parallel for using workers on #' machines in a local network. #' #' @section Warning: #' #' This section has not been properly tested. #' Random number generation? #' Examples? #' #' @param pop a population of genes. #' @param EvalGene the function for evaluating a gene. #' @param lF the local function factory which provides #' all functions needed in \code{EvalGene}. #' #' @return Fitness vector. #' #' @family Execution Model #' #' @examples #' parm<-function(x) {function() {x}} #' pop<-xegaInitPopulation(1000, lFxegaGaGene) #' library(parallel) #' clus<-makeCluster(spec=c("localhost", "localhost"), master="localhost", #' port=1250, homogeneous=TRUE) #' lFxegaGaGene$cluster<-parm(clus) #' popnew<-PparLapply(pop, lFxegaGaGene$EvalGene, lFxegaGaGene) #' stopCluster(clus) #' #' @importFrom parallel clusterSetRNGStream #' @importFrom parallel parLapply #' @export PparLapply<-function(pop, EvalGene, lF) # nocov start { z<-runif(1) parallel::clusterSetRNGStream(lF$cluster(), NULL) # not reproducible. parallel::parLapply(lF$cluster(), pop, EvalGene, lF=lF) } # nocov end # to export data: see parallel::clusterExport #' Configure the the execution model for gene evaluation. #' #' @description #' The current approach to distribution/parallelization of the genetic #' algorithm is to parallelize the evaluation of the fitness function #' only. The execution model defines the function \code{lF$lapply()} #' used in the function \code{EvalPopulation()}. #' #' @details #' Currently we support the following parallelization models: #' \enumerate{ #' \item "Sequential": Uses \code{base::apply()}. (Default). #' \item "MultiCore": Uses \code{parallel::mclapply()}. #' \item "FutureApply": Uses \code{future.apply::future_lapply()} #' Plans must be set up and #' worker processes must be stopped. #' \item "Cluster": Uses \code{parallel:parLapply()}. #' A cluster object must be set up and the #' worker processes must be stopped. #' } #' #' The execution model \strong{"MultiCore"} provides parallelization restricted #' to a single computer: The master process starts R slave processes #' by fork() which are are run in separate memory spaces. #' At the time of fork() both memory spaces #' have the same content. Memory writes performed by one of the processes #' do not affect the other. #' #' The execution model \strong{"FutureApply"} makes the possibilities #' of the future backends for a wide range of parallel and distributed #' architectures available. #' The models of parallel resolving a future use #' different types of communication between master #' and slaves: #' \enumerate{ #' \item \code{plan(sequential)} configures sequential execution. Default. #' #' \item \code{w<-5; plan(multicore, workers=w)} configures an #' asynchronous multicore execution of futures on 5 workers. #' #' \item \code{w<-8; plan(multisession, workers=w)} configures a #' multisession environment with 5 workers. #' The evaluation of the future is done in parallel in 5 other #' R sessions on the same machine. #' Communication is done via socket connections, #' the R sessions started serve multiple futures over their life time. #' The worker R sessions are stopped by calling \code{plan(sequential)}. #' The number of parallel sessions is restricted by the availability #' of connections. Up to R version 4.3, #' a maximum of 125 connections is available. #' #' \item \code{w<-7; plan(callr, workers=w)} configures #' the evaluation of futures on top of the \code{callr} package. #' The \code{callr} package creates for each future a separate R session. #' The communications is via files of serialized R objects. #' The advantages of \code{callr} are: #' \enumerate{ #' \item Each \code{callr} future is evaluated in a new R session #' which ends as soon as the value of the future has been #' collected. #' \item The number of parallel \code{callr} futures is not restricted #' by the number of available connections, because the #' communication is based on files of serialized R objects. #' \item No ports are used. This means no port clashes with other #' processes and no firewall issues. #' } #' #' \item Setting up a cluster environment for resolving futures works #' as follows. Write a function with the following elements: #' \enumerate{ #' \item Generate a cluster object: #' #' \code{cl<-makeClusterPSOCK(rep("localhost", workers)} #' \item Set up an on.exit condition for stopping the worker processes. #' #' \code{on.exit(parallel::stopCluster(cl))} #' \item Set up the plan for resolving the future: #' #' \code{oldplan<-plan(cluster, workers=cl)} #' \item Call the function with \code{future.apply::future_lapply}. #' E.g. the genetic algorithm. #' \item Restore the previous plan: #' \code{plan(oldplan)} #' } #' The cluster processes may be located on one or several computers. #' The communication between the processes is via sockets. #' Remote computers must allow the use of ssh to start R-processes #' without an interactive login. #' } #' #' The execution model \strong{"Cluster"} allows the configuration of #' master-slave processing on local and remote machines. #' #' @param method The label of the execution model: #' "Sequential" | "MultiCore" | #' "FutureApply" | "Cluster". #' #' @return A function with the same result as the \code{lapply()}-function. #' #' @family Configuration #' #' @export ApplyFactory<- function(method="Sequential") { if (method=="Sequential") {f<-base::lapply} if (method=="MultiCore") {f<-MClapply} if (method=="FutureApply") {f<-futureLapply} if (method=="Cluster") {f<-PparLapply} if (!exists("f", inherits=FALSE)) {stop("Execution Model label ", method, " does not exist")} return(f) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/parModel.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Population-level functions. # Independent of gene representation. # The replication mechanism and its variants # Package: xegaPopulation. # #' Import for examples. #' @importFrom xegaGaGene lFxegaGaGene #' @export lFxegaGaGene<-xegaGaGene::lFxegaGaGene #' Import for examples. #' @param lF a list of local functions #' @return a new random gene #' @importFrom xegaGaGene xegaGaInitGene #' @export InitGene<-xegaGaGene::xegaGaInitGene #' Import for examples. #' #' @param gg1 a gene #' @param gg2 a gene #' @param lF list of local functions #' #' @return a list of one gene #' #' @importFrom xegaGaGene xegaGaCrossGene #' @export CrossGene<-xegaGaGene::xegaGaCrossGene #' Import for examples. #' #' @param gg1 a gene #' @param gg2 a gene #' @param lF list of local functions #' #' @return a list of two genes #' #' @importFrom xegaGaGene xegaGaCross2Gene #' @export Cross2Gene<-xegaGaGene::xegaGaCross2Gene #' Import for examples. #' #' @param pop the population. #' @param fit the fitness- #' @param lF list of local functions #' #' @return a list with one gene #' #' @importFrom xegaGaGene xegaGaReplicateGene #' @export ReplicateGene<-xegaGaGene::xegaGaReplicateGene #' Computes the next population of genes. #' #' @description \code{xegaNextPopulation()} #' builds the next population by repeatedly #' calling \code{ReplicateGene()}. #' #' @details The current version is sequential. #' For parallelization, a restructuring of the #' main loop with an integration of \code{xegaNextPopulation} #' and \code{xegaEvalPopulation} is planned, because #' this allows the parallelization of a large part of #' the genetic operations which are sequential in the #' current version. #' #' @param pop Population of genes. #' @param fit Fitness. #' @param lF Local configuration. #' #' @return Population of genes. #' #' @family Population Layer #' #' @examples #' lFxegaGaGene$MutationRate<-MutationRateFactory(method="Const") #' lFxegaGaGene$ReplicateGene<-ReplicateGene #' lFxegaGaGene$Accept<-AcceptFactory(method="All") #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' newpop<-xegaNextPopulation(epop10$pop, epop10$fit, lFxegaGaGene) #' #' @importFrom stats var #' @importFrom xegaSelectGene TransformSelect #' @importFrom xegaSelectGene parm #' @export xegaNextPopulation<-function(pop, fit, lF) { if (lF$Elitist()) { newpop<-list(pop[[xegaBestGeneInPopulation(fit)[1]]]) } else { newpop<-list() } newlF<-lF newlF$CBestFitness<-xegaSelectGene::parm(max(fit)) newlF$CMeanFitness<-xegaSelectGene::parm(mean(fit)) newlF$CVarFitness<-xegaSelectGene::parm(var(fit)) newlF$CWorstFitness<-xegaSelectGene::parm(min(fit)) if (lF$SelectionContinuation()==TRUE) { newlF$SelectGene<-TransformSelect(fit, lF, lF$SelectGene) newlF$SelectMate<-TransformSelect(fit, lF, lF$SelectMate)} while(length(newpop)<length(pop)) { newpop<-append(newpop, lF$ReplicateGene(pop, fit, newlF)) } return(head(newpop,length(pop))) } #' Evaluates a population of genes in a a problem environment #' #' @description \code{EvalPopulation()} evaluates a population #' of genes in a problem environment. #' #' @details Parallelization of the evaluation of fitness functions #' is possible by defining \code{lf$evalPopLapply}. #' #' @param pop Population of genes. #' @param lF Local function configuration. #' #' @return List of fitness values. #' #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' lFxegaGaGene[["evalPopLapply"]]<-ApplyFactory(method="Sequential") #' fit<-xegaEvalPopulation(pop10, lFxegaGaGene) #' #' @export xegaEvalPopulation<-function(pop, lF) #{ unlist(lF$evalPopLapply(pop, lF$EvalGene, lF=lF)) } # Parallel loops here. { pop<- lF$lapply(pop, lF$EvalGene, lF=lF) fit<- unlist(lapply(pop, function(x) {x$fit})) evalFail<-sum(unlist(lapply(pop, function(x) {x$evalFail}))) return(list(pop=pop, fit=fit, evalFail=evalFail)) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/xegaNextPopulation.R
#' Population level functions #' #' The \code{xegaPopulation} package provides the representation independent #' functions of the population level of the simple genetic #' algorithm xegaX packages: #' \itemize{ #' \item File xegaPopulation.R: #' \itemize{ #' \item Initializing a population of genes. #' \item Getting the indices of the best genes in a population of genes #' for getting the best solution(s) in a population of genes. #' \item Configurable summary report of population fitness statistics. #' \item Observation of the summary statistics of a population of genes. #' \item Logging of the phenotype and the value of the phenotype. #' } #' \item File xegaNextPopulation.R: #' \itemize{ #' \item Computation of the next population of genes. #' \item Evaluation of the next population of genes. #' } #' #' \strong{Future}: Improved support for parallelization suggests a #' different division of labor: #' \itemize{ #' \item Construct a list of abstract task descriptions #' with one element per gene. #' \item Provide for a parallel execution of these task descriptions. #' This requires changes in the structuring of the #' operator pipelines and the replicate gene functions #' for the different gene representations and algorithms. #' \item Performance improvement depends on the gene representation #' and on the use of function evaluations in the genetic #' machinery. For example, for the TSP problem, #' function evaluations #' are embedded into most of the mutation operators. #' } #' #' \item File acceptance.R: #' Acceptance rules for new genes and a function factory for configuring #' them. #' \item File cooling.R: Cooling schedules for temperature reduction. #' #' \item File localAdaptivity.R: Unused. #' Move to gene dependent packages planned. #' \item File adaptivityCrossover.R: #' Functions constant and adaptive crossover rates. #' \item File adaptivityMutation.R: #' Functions constant and adaptive mutation rates. #' \item File parModel.R: Execution models for parallelization. #' \itemize{ #' \item "Sequential": Configures lapply as \code{lapply()}. #' \item "MultiCore": Configures lapply as \code{parallel::mclapply()}. #' The number of cores is set by \code{lF$Core()}. #' } #' \item File configuration.R: Documenting how the algorithm was called. #' Support for the replication of computational #' experiments (replicate and replay). #' } #' #' @section Interface of Acceptance Rules: #' #' \code{newGene<-accept(OperatorPipeline, gene, lF)} #' #' \enumerate{ #' \item Accept all new genes: Identity function. For genetic algorithms. #' \item Accept best: Accepts the gene with the highest fitness. #' For greedy and randomized greedy algorithms #' (hill-climbing algorithms). #' \item The Metropolis and the individually variable Metropolis rule: #' If the new gene gene is better, accept it. #' If the old gene is better, make a biased random choice. #' The probability of accepting a decrease in fitness depends on #' the fitness distance between genes, a constant beta for scaling #' the exponential decay and a temperature parameter and for #' the individually variable Metropolis rule a correction term #' which depends on the distance to the best known fitness of the run. #' } #' #' \strong{Constants for Acceptance Rules.} #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$Beta() \tab ? \tab AcceptMetropolis() \cr #' \tab \tab AcceptIVMetropolis() \cr #' lF$TempK() \tab ? \tab AcceptMetropolis() \cr #' \tab \tab AcceptIVMetropolis() \cr #' lF$lFCBestFitness() \tab None \tab AcceptIVMetropolis() \cr #' } #' #' @section Interface of Cooling Schedules: #' #' \code{Temperature<-cooling(k, lF)} #' #' Cooling schedules convert the progress of the time in the algorithm #' (measured in generations) into a temperature. #' The temperature influences the probability of accepting a gene #' with less fitness than its parent gene. #' #' \strong{Constants for Cooling Schedules.} #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$Alpha() \tab ? \tab ExponentialMultiplicativeCooling() \cr #' \tab ? \tab LogarithmicMultiplicativeCooling() \cr #' \tab ? \tab PowerMultiplicativeCooling() \cr #' lF$Temp0() \tab ? \tab ExponentialMultiplicativeCooling() \cr #' \tab ? \tab LogarithmicMultiplicativeCooling() \cr #' \tab ? \tab PowerMultiplicativeCooling() \cr #' \tab ? \tab PowerAdditiveCooling() \cr #' \tab ? \tab ExponentialAdditiveCooling() \cr #' \tab ? \tab TrigonometricAdditiveCooling() \cr #' lF$TempN() \tab ? \tab PowerAdditiveCooling() \cr #' \tab ? \tab ExponentialAdditiveCooling() \cr #' \tab ? \tab TrigonometricAdditiveCooling() \cr #' lF$CoolingPower() \tab ? \tab PowerMultiplicativeCooling() \cr #' \tab ? \tab PowerAdditiveCooling() \cr #' lF$Generations() \tab \tab PowerAdditiveCooling() \cr #' \tab \tab ExponentialAdditiveCooling() \cr #' \tab ? \tab TrigonometricAdditiveCooling() \cr #' } #' #' @section Interface of Rates: #' #' \code{rate<-rateFunction(fit, lF)} #' #' Crossover and mutation rate functions may be adaptive. #' The interface allows for dependencies of the rate #' on fitness and constants in the local configuration. #' #' \strong{Constants for Adaptive Crossover and Mutation Rates} #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$CrossRate1() \tab ? \tab IACRate() \cr #' lF$CrossRate2() \tab ? \tab IACRate() \cr #' lF$MutationRate1() \tab \tab IAMRate() \cr #' lF$MutationRate2() \tab \tab IAMRate() \cr #' lF$CutoffFit() \tab ? \tab IACRate() \cr #' lF$CBestFitness() \tab \tab IACRate() \cr #' \tab \tab IAMRate() \cr #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' #' \item #' The population layer (package \code{xegaPopulation}) contains #' population related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' #' \item #' The gene layer is split in a representation independent and #' a representation dependent part: #' \enumerate{ #' \item #' The representation indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, as well as profiling and timing capabilities. #' \item #' The representation dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler and #' \code{xegaDerivationTrees} an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaPopulation #' @aliases xegaPopulation #' @docType package #' @title Package xegaPopulation. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: https://github.com/ageyerschulz/xegaPopulation #' @section Installation: From CRAN by \code{install.packages('xegaPopulation')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/xegaPopulation-package.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Population-level functions. # Independent of gene representation. # Package: xegaPopulation. # #' Import lFxegaGaGene #' @importFrom xegaGaGene lFxegaGaGene lFxegaGaGene<-xegaGaGene::lFxegaGaGene #' Initializes a population of genes. #' #' @description \code{xegaInitPopulation()} initializes a population #' of genes. #' #' @param popsize Population size. #' @param lF Local function configuration. #' #' @return List of genes. #' #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' #' @export xegaInitPopulation<-function(popsize, lF) { pop<-list() for (i in 1:popsize) { pop[[i]]<-lF$InitGene(lF)} return(pop) } #' Observe summary statistics of the fitness of the population. #' #' @description \code{xegaObservePopulation()} reports #' summary statistics of the fitness of the population. #' #' @details Population statistics are used for #' \itemize{ #' \item implementing individually variable operator rates and #' \item visualizing the progress of the algorithm. #' } #' #' @param fit Vector of fitness values of a population. #' @param v Vector of population statistic vectors. #' #' @return Vector of population statistics. If position #' \code{x} modulo \code{8} equals #' \enumerate{ #' \item \code{1}: Mean fitness. #' \item \code{2}: Min fitness. #' \item \code{3}: Lower-hinge #' (approx. 1st quartile) of fitness. #' \item \code{4}: Median fitness. #' \item \code{5}: Upper-hinge #' (approx. 3rd quartile) of fitness. #' \item \code{6}: Max fitness. #' \item \code{7}: Variance. #' \item \code{8}: Mean absolute deviation. #' } #' #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' popStats<-xegaObservePopulation(epop10$fit) #' popStats<-xegaObservePopulation(epop10$fit, popStats) #' matrix(popStats, ncol=8, byrow=TRUE) #' #' @importFrom stats fivenum #' @importFrom stats mad #' @export xegaObservePopulation<-function(fit, v=vector()) { return(append(v, c(mean(fit), fivenum(fit), var(fit), mad(fit, constant=1)))) } #' Combine fitness, generations, and the phentype of the gene. #' #' @param pop Population. #' @param evallog Evaluation log. #' @param generation Generation logged. #' @param lF Local function configuration. #' #' @return Update of the evaluation log. #' The evaluation log is a list of decoded and evaluated genes. #' A list item of the evaluation log has the following #' elements: #' \itemize{ #' \item \code{$generation}: The generation. #' \item \code{$fit}: The fitness value. #' \item \code{$phenotype}: The phenotype of the gene. #' } #' #' @family Population Layer #' #'@examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' logevals<-list() #' logevals #' logevals<-xegaLogEvalsPopulation(epop10$pop, logevals, 1, lFxegaGaGene) #' logevals #'@export xegaLogEvalsPopulation<-function(pop, evallog, generation, lF) { new<-list() for (i in (1:length(pop))) { v<-list() v$generation<-generation v$fit<-pop[[i]]$fit v$phenotype<-lF$DecodeGene(pop[[i]], lF) new[[i]]<-v} return(c(evallog,new)) } #' Extracts indices of best genes in population. #' #' @description \code{BestGeneInPopulation()} extracts the indices of #' the best genes in the population. #' #' @details You might use: #' \code{which(max(fit)==fit)}. But this is slower! #' #' @param fit Fitness vector of a population of genes. #' #' @return List of the indices of the best genes in the population. #' #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' xegaBestGeneInPopulation(epop10$fit) #' #' @export xegaBestGeneInPopulation<-function(fit){ (1:length(fit))[max(fit)==fit] } #' Best solution in the population. #' #' @description \code{BestInPopulation()} extracts the best #' individual of a population and #' reports fitness, value, genotype, and phenotype: #' #' \enumerate{ #' \item #' \code{fitness}: The fitness value of the genetic algorithm. #' \item #' \code{value}: The function value of the problem environment. #' \item #' \code{genotype}: The gene representation. #' \item #' \code{phenotype}: The problem representation. #' E.g. a parameter list, a program, ... #' } #' #' We report one of the best solutions. #' #' @param pop Population of genes. #' @param fit Vector of fitness values of \code{pop}. #' @param lF Local function configuration. #' @param allsolutions If TRUE, also return a list of all solutions. #' #' @return Named list with the following elements: #' \itemize{ #' \item \code{$name}: The name of the problem environment. #' \item \code{$fitness}: The fitness value of the best solution. #' \item \code{$val}: The evaluted best gene. #' \item \code{$numberOfSolutions}: The number of solutions. #' \item \code{$genotype}: The best gene. #' \item \code{$phenotype}: The parameters of the solution #' (the decoded gene). #' \item \code{$phenotypeValue}: The value of the #' function of the parameters of the solution #' (the decoded gene). #' \item \code{$allgenotypes}: The genotypes of all best solutions. #' (allsolutions==TRUE) #' \item \code{$allphenotypes}: The phenotypes of all best solutions. #' (allsolutions==TRUE) #' } #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' xegaBestInPopulation(epop10$pop, epop10$fit, lFxegaGaGene) #' #' @importFrom utils head #' @export xegaBestInPopulation<-function(pop, fit, lF, allsolutions=FALSE) { best<-(1:length(fit))[max(fit)==fit] bestGene<- pop[[head(best,1)]] parms<- lF$DecodeGene(bestGene,lF) val<-lF$EvalGene(bestGene, lF) solution<-list( name=list(lF$penv$name()), fitness=max(fit), value=val, numberOfSolutions=length(best), genotype=bestGene, phenotype=parms, phenotypeValue=lF$penv$f(parms)) if ((allsolutions) && (length(best)>1)) { solution[["allgenotypes"]]<-pop[best] solution[["allphenotypes"]]<- lapply(pop[best], lF$DecodeGene, lF=lF) } return(solution) } #' Provide elementary summary statistics of the fitness of the population. #' #' @description \code{SummaryPopulation()} reports #' on the fitness and the value of the best solution #' in the population. #' #' The value of \code{lF$Verbose()} controls the #' information displayed: #' \enumerate{ #' \item \code{== 0}: Nothing is displayed. #' #' \item \code{== 1}: 1 point per generation. #' #' \item \code{> 1}: Max(fit), number of solutions, indices. #' #' \item \code{> 2}: and population fitness statistics. #' #' \item \code{> 3}: and 1 solution. #' } #' #' @param pop Population of genes. #' @param fit Vector of fitness values of \code{pop}. #' @param lF Local function configuration. #' @param iter The generation. Default: \code{0}. #' #' @return The number \code{0}. #' #' @family Population Layer #' #' @examples #' pop10<-xegaInitPopulation(10, lFxegaGaGene) #' epop10<-xegaEvalPopulation(pop10, lFxegaGaGene) #' rc<-xegaSummaryPopulation(epop10$pop, epop10$fit, lFxegaGaGene, iter=12) #' #' @importFrom utils str #' @export xegaSummaryPopulation<-function(pop, fit, lF, iter=0) { if (lF$Verbose()==0) {return(0)} if (lF$Verbose()==1) { if (0==(iter%%50)) {cat("\n")} cat(".") return(0)} if (lF$Verbose()>1) { if (iter==0) { cat("Best solution:\n") } else { cat("Best Solution in Iteration:", iter, "\n") } best<-(1:length(fit))[max(fit)==fit] cat("Max(fit): ", max(fit), "No. solutions: ", length(best), "Indices of best genes: ", best, "\n") } if (lF$Verbose()>2) { stats<-xegaObservePopulation(fit) cat( "Fitness Min:", stats[2], " Q1:", stats[3], " Mean:", stats[1], " Q3:", stats[5], " Max:", stats[6], "\n") } if (lF$Verbose()>3) { #cat("In Summary:Best in Population.\n") solution<-xegaBestInPopulation(pop, fit, lF) cat("Fitness:", solution$fitness, "Value of Phenotype:", solution$phenotypeValue, "\n") cat("Phenotype:\n") print(solution$phenotype) } if (lF$Verbose()>4) { #cat("In Summary:Best in Population.\n") solution<-xegaBestInPopulation(pop, fit, lF) cat("str(Genotype):\n") str(solution$genotype) } return(0) }
/scratch/gouwar.j/cran-all/cranData/xegaPopulation/R/xegaPopulation.R
#' Factory for function F4 (30-dimensional quartic with noise) #' #' @description This function factory sets up the problem environment #' for De Jong's function F4. #' F4 is a 30-dimensional quartic function with Gaussian noise. #' It is a continuous, convex, unimodal, high-dimensional quartic function #' with Gaussian noise. For validation, \eqn{\epsilon = 3*\sigma} #' will work most of the time. #' Note: There exist \eqn{2^{30}} maxima (without noise)! #' #' @references De Jong, Kenneth A. (1975): #' \emph{An Analysis of the Behavior of a Class of Genetic Adaptive Systems.} #' PhD thesis, Michigan, Ann Arbor, pp. 203-206. #' <https://deepblue.lib.umich.edu/handle/2027.42/4507> #' #' @inherit DelayedPFactory return #' #' @family Problem Environments #' #' @examples #' DeJongF4<-DeJongF4Factory() #' DeJongF4$name() #' DeJongF4$bitlength() #' DeJongF4$genelength() #' DeJongF4$lb() #' DeJongF4$ub() #' DeJongF4$f(c(2.01, -1.05, 4.95, -4.3, -3.0)) #' DeJongF4$f(c(2.01, -1.05, 4.95, -4.3, -3.0)) #' DeJongF4$describe() #' DeJongF4$solution() #' @importFrom stats rnorm #' @export DeJongF4Factory<-function() { self<-list() self<-c(self, name=function() {"DeJongF4"}) self<-c(self, bitlength=function() {rep(64,30)}) self<-c(self, genelength=function() {sum(self$bitlength())}) self<-c(self, lb=function() {rep(-1.28,30)}) self<-c(self, ub=function() {rep(1.28,30)}) self<-c(self, f=function(parm, gene=0, lF=0) { sum(seq(1:length(parm))*parm^{4})+stats::rnorm(1) }) # { sum(seq(1:length(parm))*parm^{4})}) self<-c(self, describe=function() { cat("See", "\n") cat("De Jong (1975) ") cat("An Analysis of the Behavior of a Class of Genetic Adaptive Systems.", "\n") cat("PhD thesis, Michigan, Ann Arbor, pp. 203-206", "\n\n") cat("F4 is a 30-dimensional quartic function with Gaussian noise.", "\n") cat("It is a continuous, convex, unimodal, high-dimensional quartic function", "\n") cat("with Gaussian noise. For validation: eps=3*sigma will work most of the time.", "\n") cat("Note: There exist 2^30 maxima (without noise)!", "\n") }) self<-c(self, maxp=function() { c(1.28, -1.28)[sample((1:2), 30, replace=TRUE)] } ) self<-c(self, solution=function() { s<-list() s[["minimum"]]<-0 s[["minpoints"]]<-list(rep(0, 30)) s[["maximum"]]<-1248.225 s[["maxpoints"]]<-list(rep(1.28,30), self$maxp(), rep(-1.28,30)) return(s) }) return(self) }
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/DeJongF4.R
# Problem Environments: Parabola2D # (c) 2023 Andreas Geyer-Schulz #' Factory for a 2-dimensional quadratic parabola with delayed execution. #' #' @description This list of functions sets up the problem environment #' for a 2-dimensional #' quadratic parabola with a delayed execution of 0.1s. #' This function aims to test strategies #' of distributed/parallel execution of functions. #' #' @details The factory contains examples of all functions #' which form the interface of a problem environment to #' the simple genetic algorithm with binary-coded genes #' of package \code{xega}. #' #' @return A problem environment represented as a list of functions: #' \itemize{ #' \item \code{$name()}: The name of the problem environment. #' \item \code{$bitlength()}: The vector of the number of bits of #' each parameter of the function. #' \item \code{$genelength()}: The number of bits of the gene. #' \item \code{$lb()}: The vector of lower bounds of the parameters. #' \item \code{$ub()}: The vector of upper bounds of the parameters. #' \item \code{$f(parm, gene=0, lF=0)}): The fitness function. #' } #' Additional elements: #' \itemize{ #' \item \code{$describe()}: Print a description of the problem environment to the console. #' \item \code{$solution()}: The solution structure. A named list with \code{minimum}, \code{maximum} and #' 2 lists of equivalent solutions: \code{minpoints}, \code{maxpoints}. #' } #' #' @family Problem Environments #' @seealso Parabola2D #' #' @examples #' DelayedP<-DelayedPFactory() #' DelayedP$f(c(2.2, 1.0)) #' @export DelayedPFactory<-function(){ self<-list() self<-c(self, name=function() {"DelayedP"}) self<-c(self, bitlength=function() {c(20, 20)}) self<-c(self, genelength=function() {sum(self$bitlength())}) self<-c(self, lb=function() {c(-4.5, -4.5)}) self<-c(self, ub=function() {c(4.5, 4.5)}) self<-c(self, f=function(parm, gene=0, lF=0) { Sys.sleep(0.1) sum(parm^{2}) }) self<-c(self, describe=function() { cat("DelayedP is a 2-dimensional parabola with spherical constant-cost contours.", "\n") cat("It is a continuous, convex, unimodal, 2-dimensional quadratic function.", "\n") cat("The function sleeps 0.1s before it is executed.", "\n") }) self<-c(self, solution=function() { s<-list() s[["minimum"]]<-0 s[["minpoints"]]<-list(rep(0, 2)) s[["maximum"]]<-40.5 s[["maxpoints"]]<-list( c(4.5, 4.5), c(4.5, -4.5), c(-4.5, 4.5), c(-4.5, -4.5)) return(s) }) return(self) } #' Factory for a 2-dimensional quadratic parabola. #' #' @description This list of functions sets up the problem environment #' for a 2-dimensional #' quadratic parabola. #' #' @details The factory contains examples of all functions #' which form the interface of a problem environment to #' the simple genetic algorithm with binary-coded genes #' of package \code{xega}. #' #' @inherit DelayedPFactory return #' #' @family Problem Environments #' @seealso DelayedP, Parabola2DErr #' #' @examples #' Parabola2D<-Parabola2DFactory() #' Parabola2D$f(c(2.2, 1.0)) #' @export Parabola2DFactory<-function(){ self<-list() self<-c(self, name=function() {"Parabola2D"}) self<-c(self, bitlength=function() {c(20, 20)}) self<-c(self, genelength=function() {sum(self$bitlength())}) self<-c(self, lb=function() {c(-4.5, -4.5)}) self<-c(self, ub=function() {c(4.5, 4.5)}) self<-c(self, f=function(parm, gene=0, lF=0) { sum(parm^{2}) }) self<-c(self, describe=function() { cat("Parabola2D is a 2-dimensional parabola with spherical constant-cost contours.", "\n") cat("It is a continuous, convex, unimodal, 2-dimensional quadratic function.", "\n") }) self<-c(self, solution=function() { s<-list() s[["minimum"]]<-0 s[["minpoints"]]<-list(c(0, 0)) s[["maximum"]]<-40.5 s[["maxpoints"]]<-list( c(4.5, 4.5), c(4.5, -4.5), c(-4.5, 4.5), c(-4.5, -4.5)) return(s) }) return(self) } #' Factory for a 2-dimensional quadratic parabola with early termination check. #' #' @description This list of functions sets up the problem environment #' for a 2-dimensional #' quadratic parabola. #' #' @details The factory contains examples of all functions #' which form the interface of a problem environment to #' the simple genetic algorithm with binary-coded genes #' of package \code{xega}. #' This factory provides examples of a termination condition, #' a description function, and a solution function: #' \itemize{ #' \item \code{terminate(solution)} #' checks for an early termination condition. #' \item \code{describe()} #' shows a description of the function. #' \item \code{solution()} #' returns a list with the #' \code{minimum} and the #' \code{maximum} values as well as the lists #' \code{minpoints} and \code{maxpoints} of #' the minimal and the maximal points. #' } #' #' @inherit DelayedPFactory return #' #' @family Problem Environments #' @seealso DelayedP, Parabola2DErr #' #' @examples #' Parabola2D<-Parabola2DEarlyFactory() #' Parabola2D$f(c(2.2, 1.0)) #' @export Parabola2DEarlyFactory<-function(){ self<-list() self<-c(self, name=function() {"Parabola2DEarly"}) self<-c(self, bitlength=function() {c(20, 20)}) self<-c(self, genelength=function() {sum(self$bitlength())}) self<-c(self, lb=function() {c(-4.5, -4.5)}) self<-c(self, ub=function() {c(4.5, 4.5)}) self<-c(self, f=function(parm, gene=0, lF=0) { sum(parm^{2}) }) ### TODO. ### The solution is the result of bestInPopulation in xegaPopulation.R ### We stop as soon as we are within 5 percent of the optimum. self<-c(self, terminate=function(solution, lF) { if (lF$Max()==TRUE) {opt<-lF$penv$solution()$maximum} else {opt<-lF$penv$solution()$minimum} eps<-max((lF$TerminationEps()*opt), lF$TerminationEps()) # cat("Solution:", solution$phenotypeValue) # cat(" [", (opt-eps), (opt+eps), "]\n") if ((solution$phenotypeValue>(opt-eps)) & (solution$phenotypeValue<(opt+eps))) {return(TRUE)} else {return(FALSE)} }) ### TODO. self<-c(self, describe=function() { cat("Parabola2D is a 2-dimensional parabola with spherical constant-cost contours.", "\n") cat("It is a continuous, convex, unimodal, 2-dimensional quadratic function.", "\n") }) self<-c(self, solution=function() { s<-list() s[["minimum"]]<-0 s[["minpoints"]]<-list(c(0, 0)) s[["maximum"]]<-40.5 s[["maxpoints"]]<-list( c(4.5, 4.5), c(4.5, -4.5), c(-4.5, 4.5), c(-4.5, -4.5)) return(s) }) return(self) } #' Factory for a randomly failing 2-dimensional quadratic parabola. #' #' @description This list of functions sets up the problem environment #' for a 2-dimensional #' quadratic parabola which produces an error #' with a probability of 0.5. #' #' @details The factory contains examples of all functions #' which form the interface of a problem environment to #' the simple genetic algorithm with binary-coded genes #' of package \code{xega}. #' #' @inherit DelayedPFactory return #' #' @family Problem Environments #' @seealso DelayedP #' #' @examples #' Parabola2DErr<-Parabola2DErrFactory() #' @importFrom stats runif #' @export Parabola2DErrFactory<-function(){ self<-list() self<-c(self, name=function() {"Parabola2D"}) self<-c(self, bitlength=function() {c(20, 20)}) self<-c(self, genelength=function() {sum(self$bitlength())}) self<-c(self, lb=function() {c(-4.5, -4.5)}) self<-c(self, ub=function() {c(4.5, 4.5)}) self<-c(self, f=function(parm, gene=0, lF=0) { if (0.5>runif(1)) {"a"+3} sum(parm^{2}) }) self<-c(self, describe=function() { cat("Parabola2D is a 2-dimensional parabola with spherical constant-cost contours.", "\n") cat("It is a continuous, convex, unimodal, 2-dimensional quadratic function.", "\n") cat("It produces an error 50 percent of the time.", "\n") }) self<-c(self, solution=function() { s<-list() s[["minimum"]]<-0 s[["minpoints"]]<-list(c(0, 0)) s[["maximum"]]<-40.5 s[["maxpoints"]]<-list( c(4.5, 4.5), c(4.5, -4.5), c(-4.5, 4.5), c(-4.5, -4.5)) return(s) }) return(self) }
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/Parabola2D.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # Representation independent. # Package: xegaEvalGene # #' Generate local functions and objects #' #'@description \code{NewlFevalGenes} returns #' the list of functions containing #' a definition of all local objects required for the use #' of evaluation functions. We reference this object #' as local configuration. When adding additional #' evaluation functions, this must be extended #' by the constant (functions) needed to configure them. #' #'@param penv A problem environment. #'@return The local configuration. A list of functions. #' #'@examples #' Parabola2D<-Parabola2DFactory() #' lF<-NewlFevalGenes(Parabola2D) #' lF$Max() #'@export NewlFevalGenes<-function(penv) { list( Max=function() {1}, ReportEvalErrors=function() {TRUE}, DecodeGene=function(gene, lF) {gene$gene1}, penv=penv ) } #' Evaluates a gene in a problem environment #' #' @description \code{EvalGeneU} evaluates a gene in #' a problem environment. #' #' @details If the evaluation of the fitness function of the #' problem environment fails, the following #' strategy is used: #' We catch the error #' and print it, ignore it: #' #' The error handler returns \code{NA}. #' #' We check for the error and update the gene: #' \itemize{ #' \item \code{$evaluated} TRUE. #' \item \code{$evalFail} TRUE. #' \item \code{$fit} is set to the minimum fitness in the #' population. #' } #' #' The boolean function \code{lF$ReportEvalErrors} controls #' the output of error messages for evaluation failures. #' Rationale: In grammatical evolution, the standard approach #' ignores attempts the evaluate incomplete programs. #' #' @section Future improvement: #' Provide configurable error handlers. #' Rationale: Make debugging for new problem environments easier. #' Catch communication problems in distributed/parallel #' environments. #' #' @param gene A gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A gene (with \code{$evaluated==TRUE}). #' #' @family Evaluation Functions #' #' @examples #' Parabola2D<-Parabola2DFactory() #' lF<-NewlFevalGenes(Parabola2D) #' g1<-list(evaluated=FALSE, fit=0, gene1=c(1.0, -1.5, 3.37)) #' g2<-list(evaluated=FALSE, fit=0, gene1=c(0.0, 0.0, 0.0)) #' EvalGeneU(g1, lF) #' EvalGeneU(g2, lF) #' @export EvalGeneU<-function(gene, lF) { ng<-gene ReportEvalErrors<-lF$ReportEvalErrors ng$fit<-tryCatch( lF$Max()*lF$penv$f(lF$DecodeGene(gene, lF), gene, lF), error = function(e) {if (ReportEvalErrors()) {message("EvalGeneU:") message(conditionMessage(e))} NA}) if (is.na(ng$fit)) # ignore and report! { ng$fit<-lF$CWorstFitness() ng$evalFail<-TRUE} else {ng$evalFail<-FALSE} ng$evaluated<-TRUE return(ng) } #' Evaluates a repaired gene in a problem environment. #' #' @description \code{EvalGeneR} evaluates a repaired gene in #' a problem environment. #' #' @details If the decoder repairs a gene, the repaired gene #' must replace the original gene. #' #' @param gene A gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A gene (with \code{$evaluated==TRUE}). #' #' @family Evaluation Functions #' @seealso EvalGeneU #' #' @examples #' Parabola2D<-Parabola2DFactory() #' lF<-NewlFevalGenes(Parabola2D) #' g1<-list(evaluated=FALSE, fit=0, gene1=c(1.0, -1.5, 3.37)) #' g2<-list(evaluated=FALSE, fit=0, gene1=c(0.0, 0.0, 0.0)) #' EvalGeneR(g1, lF) #' EvalGeneR(g2, lF) #' @export EvalGeneR<-function(gene, lF) { ng<-gene dg<-lF$DecodeGene(gene, lF) if (!is.null(names(dg))) { p<-dg$parm; ng<-dg$gene } else { p<-dg } ReportEvalErrors<-lF$ReportEvalErrors ng$fit<-tryCatch( lF$Max()*lF$penv$f(p, ng, lF), error = function(e) {if (ReportEvalErrors()) {message("EvalGeneU:") message(conditionMessage(e))} NA}) if (is.na(ng$fit)) # ignore and report! { ng$fit<-lF$CWorstFitness() ng$evalFail<-TRUE} else {ng$evalFail<-FALSE} ng$evaluated<-TRUE return(ng) } #' Evaluates a gene in a deterministic problem environment. #' #' @description \code{EvalGeneDet} evaluates a gene in #' a problem environment if it has not been evaluated yet. #' The repeated evaluations of a gene are omitted. #' #' @details If the evaluation of the fitness function of the #' problem environment fails, we catch the error and #' return \code{NA}. #' #' @param gene A gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A gene (with \code{$evaluated==TRUE}). #' #' @family Evaluation Functions #' #' @examples #' Parabola2D<-Parabola2DFactory() #' lF<-NewlFevalGenes(Parabola2D) #' g1<-list(evaluated=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g2<-list(evaluated=FALSE, fit=0, gene1=c(0.0, 0.0)) #' g1a<-EvalGeneDet(g1, lF) #' EvalGeneDet(g1a, lF) #' g2a<-EvalGeneDet(g2, lF) #' EvalGeneDet(g2a, lF) #' @export EvalGeneDet<-function(gene, lF) { if (gene$evaluated) gene else EvalGeneU(gene, lF) } #' Evaluates a gene in a stochastic problem environment. #' #' @description \code{EvalGeneStoch} evaluates a gene in #' a stochastic problem environment. #' #' @details In a stochastic problem environment, the expected fitness #' is maximized. The computation of the expectation is #' done by incrementally updating the mean. #' For this, need the number of evaluations of the gene #' (\code{$obs} of the gene). #' In addition, we compute the incremental variance #' of the expected fitness #' stored in \code{$var}. #' The standard deviation is then \code{gene$var/gene$obs}. #' #' If the evaluation of the fitness function of the #' problem environment fails, we catch the error and #' return \code{NA} for the first evaluation of the gene. #' If the gene has been evaluated, we return the old gene. #' #' @param gene A gene. #' @param lF The local configuration of the genetic algorithm. #' #' @return A gene with the elements #' \itemize{ #' \item \code{$evaluated}: Boolean. #' \item \code{$evalFail}: Boolean. #' \item \code{$fit}: Mean fitness of gene. #' \item \code{$gene1}: Gene. #' \item \code{$obs}: Number of evaluations of gene. #' \item \code{$var}: Variance of fitness. #' \item \code{$sigma}: Standard deviation of fitness. #' } #' #' @family Evaluation Functions #' #' @examples #' DeJongF4<-DeJongF4Factory() #' lF<-NewlFevalGenes(DeJongF4) #' g1<-list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g1 #' g2<-EvalGeneStoch(g1, lF) #' g2 #' g3<-EvalGeneStoch(g2, lF) #' g3 #' g4<-EvalGeneStoch(g3, lF) #' g4 #' g5<-EvalGeneStoch(g4, lF) #' g5 #' @export EvalGeneStoch<-function(gene, lF) { if (!gene$evaluated) { ng<-EvalGeneU(gene, lF) if (ng$evalFail==TRUE) {ng$obs<-0; ng$var<-0; return(ng)} ng$obs<-1 ng$var<-0 ng$sigma<-0 return(ng)} else { ng<-EvalGeneU(gene, lF) if (ng$evalFail==TRUE) {return(ng)} ng$obs<-gene$obs+1 fit<-ng$fit ng$fit<- (gene$obs)/(ng$obs)*gene$fit + (fit/(ng$obs)) ng$var<-gene$var+(fit-gene$fit)*(fit-ng$fit) ng$sigma<-sqrt(ng$var/ng$obs) return(ng)} } #' Test of incremental mean, variance, and standard deviation. #' #' @param gene A gene. #' @param lF A local function list with a problem environment. #' @param rep Number of repeated evaluations. #' #' @return A gene. #' #' @family Tests #' #' @examples #' DeJongF4<-DeJongF4Factory() #' lF<-NewlFevalGenes(DeJongF4) #' g1<-list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g10<-testEvalGeneStoch(g1, lF, rep=10) #' g10 #' @export testEvalGeneStoch<-function(gene, lF, rep) { ng<-gene for (i in (1:rep)) {ng1<-EvalGeneStoch(ng, lF); ng<-ng1} return(ng)} #' Configure the evaluation function of a genetic algorithm. #' #' @description \code{EvalGeneFactory} implements the selection #' of one of the evaluation functions for a gene #' in this package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error) if the label does not match. #' The functions are specified locally. #' #' @param method Available methods are: #' #' \itemize{ #' \item "EvalGeneU": Evaluate gene (Default). #' Function \code{EvalGeneU}. #' \item "EvalGeneR": If the gene has been repaired by a decoder, #' the gene is replaced by the repaired gene. #' Function \code{EvalGeneR}. #' \item "Deterministic": A gene which has been evaluated is #' not reevaluated. #' Function \code{EvalGeneDet}. #' \item "Stochastic": The fitness mean and #' the fitness variance #' are incrementally updated. #' Genes remaining in the population over several #' generations, the fitness mean converges to the #' expected mean. #' Function \code{EvalGeneStoch}. #' } #' #' @return An evaluation function. #' #' @family Configuration #' #' @examples #' set.seed(5) #' DeJongF4<-DeJongF4Factory() #' lF<-NewlFevalGenes(DeJongF4) #' EvalGene<-EvalGeneFactory("EvalGeneU") #' g1<-list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g1 #' g2<-EvalGene(g1, lF) #' g2 #' EvalGene<-EvalGeneFactory("Deterministic") #' g3<-EvalGene(g2, lF) #' g3 #' set.seed(5) #' EvalGene<-EvalGeneFactory("Stochastic") #' g1<-list(evaluated=FALSE, evalFail=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g1 #' g2<-EvalGene(g1, lF) #' g2 #' g3<-EvalGene(g2, lF) #' g3 #' @export EvalGeneFactory<-function(method="EvalGeneU") { if (method=="EvalGeneU") {f<- EvalGeneU} if (method=="EvalGeneR") {f<- EvalGeneR} if (method=="Deterministic") {f<- EvalGeneDet} if (method=="Stochastic") {f<- EvalGeneStoch} if (!exists("f", inherits=FALSE)) {stop("Evaluation method label ", method, " does not exist")} return(f) } #' Evaluate a gene #' #' @description \code{EvalGene} is the abstract function which evaluates #' a gene. #' #' @details For minimization problems, the fitness value #' must be multiplied by -1. The constant function #' \code{lF$Max()} returns 1 for a maximization and #' -1 for a minimization problem. #' #' @param gene A gene (representation independent). #' @param lF The local configuration (a function factory provided by #' the \code{xegaX} package). #' #' @return A gene. #' #' @family Evaluation Functions #' #' @examples #' DeJongF4<-DeJongF4Factory() #' lF<-NewlFevalGenes(DeJongF4) #' EvalGene<-EvalGeneFactory() #' g1<-list(evaluated=FALSE, fit=0, gene1=c(1.0, -1.5)) #' g1 #' g2<-EvalGene(g1, lF) #' g2 #' @export EvalGene<-EvalGeneFactory(method="EvalGeneU")
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/evalGene.R
# # (c) 2021 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V0.1 # Layer: Gene-Level Functions # For a binary gene representation. # Package: xegaPermGene # #' Generate a TSP problem environment #' #' @description \code{newTSP} generates the problem environment #' for a traveling salesman problem (TSP). #' #' @details \code{newTSP} provides several local permutation #' improvement heuristics: #' a greedy path of length k starting #' from city i, #' the best greedy path of length k, #' a random 2-Opt-move, #' and a sequence of random 2-Opt moves. #' They help to find bounds for the TSP #' or to implement special purpose mutation operators. #' #' @param D A \code{n} x \code{n} distance matrix. #' @param Cities The names of the cities. #' @param Name The name of the problem environment. #' @param Solution Solution of problem (if known). #' Default: \code{NA} #' @param Path Optimal permutation of cities (if known). As integer vector. #' Default: \code{NA}. #' #' @family Problem Environments #' #' @return A problem environment for the TSP. #' \enumerate{ #' \item #' \code{$name()} a string with the name of the environment #' \item #' \code{$cities()} a vector length \code{n} of city names. #' \item #' \code{$dist()} the \code{n} x \code{n} distance matrix #' between \code{n} cities. #' \item #' \code{$genelength()} the size of the permutation \code{n}. #' E.g. for a TSP: the number of cities. #' \item #' \code{$f(permutation, gene, lF, tour=TRUE)} #' the fitness function of the TSP. If \code{tour==FALSE}, #' the path length is computed #' (without the cost from city n to city 1). #' #' With a permutation of size \code{n} as argument. #' \item #' \code{$show(p)} shows tour through the cities in #' path \code{p} with its cost. #' \item #' \code{$greedy(startPosition, k)} #' computes a \code{k}-step greedy minimal cost path #' beginning at the city \code{start}. #' For \code{k+1=n} the greedy solution gives #' an upper bound for the TSP. #' \item #' \code{$kBestGreedy(k, tour=TRUE)} computes the best greedy #' subtour with \code{k+1} cities. #' For \code{tour=FALSE}, the best greedy #' subpath with \code{k+1} cities is #' computed. #' #' \item #' \code{$rnd2Opt(permutation, maxTries=5)} returns a permutation #' improved by a single random 2-Opt-move #' after at most \code{maxTries=5} attempts. #' #' \item #' \code{$LinKernighan(permutation, maxTries=5, show=FALSE)} returns #' the best permutation found after #' several random 2-Opt-moves #' with at most \code{maxTries=5} attempts. #' The loop stops after the first 2-Opt-move #' which does not improve the solution. #' #' \item #' \code{$solution()} known optimal solution #' \item #' \code{$path()} known optimal round trip #' } #' #' @examples ## a<-read.table("lau15distAGS.txt") #' a<-matrix(0, nrow=15, ncol=15) #' a[1,]<- c(0, 29, 82, 46, 68, 52, 72, 42, 51, 55, 29, 74, 23, 72, 46) #' a[2,]<- c(29, 0, 55, 46, 42, 43, 43, 23, 23, 31, 41, 51, 11, 52, 21) #' a[3,]<- c(82, 55, 0, 68, 46, 55, 23, 43, 41, 29, 79, 21, 64, 31, 51) #' a[4,]<-c(46, 46, 68, 0, 82, 15, 72, 31, 62, 42, 21, 51, 51, 43, 64) #' a[5,]<-c(68, 42, 46, 82, 0, 74, 23, 52, 21, 46, 82, 58, 46, 65, 23) #' a[6,]<-c(52, 43, 55, 15, 74, 0, 61, 23, 55, 31, 33, 37, 51, 29, 59) #' a[7,]<-c(72, 43, 23, 72, 23, 61, 0, 42, 23, 31, 77, 37, 51, 46, 33) #' a[8,]<-c(42, 23, 43, 31, 52, 23, 42, 0, 33, 15, 37, 33, 33, 31, 37) #' a[9,]<-c(51, 23, 41, 62, 21, 55, 23, 33, 0, 29, 62, 46, 29, 51, 11) #' a[10,]<-c(55, 31, 29, 42, 46, 31, 31, 15, 29, 0, 51, 21, 41, 23, 37) #' a[11,]<-c(29, 41, 79, 21, 82, 33, 77, 37, 62, 51, 0, 65, 42, 59, 61) #' a[12,]<-c(74, 51, 21, 51, 58, 37, 37, 33, 46, 21, 65, 0, 61, 11, 55) #' a[13,]<-c(23, 11, 64, 51, 46, 51, 51, 33, 29, 41, 42, 61, 0, 62, 23) #' a[14,]<-c(72, 52, 31, 43, 65, 29, 46, 31, 51, 23, 59, 11, 62, 0, 59) #' a[15,]<-c(46, 21, 51, 64, 23, 59, 33, 37, 11, 37, 61, 55, 23, 59, 0) #' lau15<-newTSP(a, Name="lau15") #' lau15$name() #' lau15$genelength() #' b<-sample(1:15, 15, FALSE) #' lau15$f(b) #' lau15$f(b, tour=TRUE) #' lau15$show(b) #' lau15$greedy(1, 14) #' lau15$greedy(1, 1) #' #' @export newTSP<-function(D, Name, Cities=NA, Solution=NA, Path=NA) { d<-dim(D) if (!length(d)==2) stop("n times n matrix expected") if (!d[1]==d[2]) stop("n times n matrix expected") # constant functions name<-parm(Name) genelength<-parm(d[1]) dist<-parm(D) #### if (all(is.na(Cities))) {cit<-1:d[1]} else {if (!length(Cities)==d[1]) {stop("List of n cities expected")} else {cit<-Cities}} cities<-parm(cit) if (!all(is.na(Path))) {if (!length(Path)==d[1]) {stop("Path of n cities expected")}} if (!all(is.na(Path))) { if (!all(Path %in% (1:d[1]))) {stop("Permutation of n integers expected")}} solution<-parm(Solution) path<-parm(Path) # f f<-function(permutation, gene=0, lF=0, tour=TRUE) { cost<-0 l<-length(permutation)-1 for (i in 1:l) { cost<- cost+self$dist()[permutation[i], permutation[i+1]]} if (tour==TRUE) {cost<-cost+self$dist()[permutation[l+1], permutation[1]]} return(cost)} # show. p is a path. show<-function(p) { l<-length(p)-1 pl<-0 for (i in 1:l) {d<-self$dist()[p[i], p[i+1]] pl<-pl+d cat(i, "From:", self$cities()[p[i]], " to ", self$cities()[p[i+1]], " Distance: ", d, " ", pl, "\n")} d<-self$dist()[p[l+1], p[1]] pl<-pl+d cat((l+1), "From:", self$cities()[p[l+1]], " to ", self$cities()[p[1]], " Distance: ", d, " ", pl, "\n") } # greedy greedy<-function(startPosition, k) { # local functions without<-function(set, element) {set[!set==element]} # v a vector findMinIndex<-function(indexSet, v) {v<-indexSet[v==min(v)] return(v[sample(1:length(v),1)]) } nextPosition<-startPosition path<-as.vector(startPosition) indexSet<-without(1:self$genelength(), nextPosition) for (i in 1:k) {nextPosition<-findMinIndex(indexSet, self$dist()[nextPosition, indexSet]) path<-c(path, nextPosition) indexSet<-without(indexSet, nextPosition)} return(path)} kBestGreedy<-function(k, tour=TRUE) { l<-self$genelength() best<-self$greedy(1, k) costBest<-self$f(best, tour) for (i in 2:l) { new<-self$greedy(i, k) costNew<-self$f(new, tour) if (costNew<costBest) {best<-new; costBest<-costNew} } return(best) } rnd2Opt<-function(permutation, maxTries=5) { randomSplit<-function(l) { kpos<-sample(1:l, 2, replace=FALSE) if (kpos[1]>kpos[2]) {kpos[c(2, 1)]<-kpos} if ((kpos[2]==l) & (kpos[1]==1)) {kpos[2]<-l-1} if ((kpos[2]-kpos[1])==1) {if (kpos[2]==l) {kpos[1]<-kpos[1] -1} else {kpos[2]<-kpos[2]+1}} x1<-1:kpos[1] if (kpos[2]<l) {x2<-(kpos[2]+1):l} else {x2<-rep(0,0)} y<-(kpos[1]+1):kpos[2] return(c(x2, x1, y[length(y):1])) } cost1<-self$f(permutation) l<-length(permutation) for (i in 1:maxTries) { newpermutation<-permutation[randomSplit(l)] cost2<-self$f(newpermutation) if (cost1>cost2) {return(newpermutation)} if (i==maxTries) {break} } return(permutation) } LinKernighan<-function(permutation, maxTries=5, show=FALSE) { epsilon<-parm(0.000001) newpermutation<-permutation; i<-1 repeat { c1<-self$f(newpermutation); i<-i+1 newpermutation<-self$rnd2Opt(newpermutation, maxTries) c2<-self$f(newpermutation) if (show) { cat(i,"p: ", newpermutation, "c1:", c1, "c2:", c2, "diff:", (c1-c2), "\n")} if (abs(c1-c2)<epsilon()) {break} } return(newpermutation) } self=list(name=name, genelength=genelength, dist=dist, cities=cities, f=f, solution=solution, path=path, show=show, greedy=greedy, kBestGreedy=kBestGreedy, rnd2Opt=rnd2Opt, LinKernighan=LinKernighan) # The next 6 statements are needed to evaluate the promises # and to force a static binding despite lazy evaluation of # arguments. a<-self$name() a<-self$genelength() a<-self$dist() a<-self$cities() a<-self$solution() a<-self$path() return(self) } # # Data for lau15 # a<-matrix(0, nrow=15, ncol=15) a[1,]<- c(0, 29, 82, 46, 68, 52, 72, 42, 51, 55, 29, 74, 23, 72, 46) a[2,]<- c(29, 0, 55, 46, 42, 43, 43, 23, 23, 31, 41, 51, 11, 52, 21) a[3,]<- c(82, 55, 0, 68, 46, 55, 23, 43, 41, 29, 79, 21, 64, 31, 51) a[4,]<-c(46, 46, 68, 0, 82, 15, 72, 31, 62, 42, 21, 51, 51, 43, 64) a[5,]<-c(68, 42, 46, 82, 0, 74, 23, 52, 21, 46, 82, 58, 46, 65, 23) a[6,]<-c(52, 43, 55, 15, 74, 0, 61, 23, 55, 31, 33, 37, 51, 29, 59) a[7,]<-c(72, 43, 23, 72, 23, 61, 0, 42, 23, 31, 77, 37, 51, 46, 33) a[8,]<-c(42, 23, 43, 31, 52, 23, 42, 0, 33, 15, 37, 33, 33, 31, 37) a[9,]<-c(51, 23, 41, 62, 21, 55, 23, 33, 0, 29, 62, 46, 29, 51, 11) a[10,]<-c(55, 31, 29, 42, 46, 31, 31, 15, 29, 0, 51, 21, 41, 23, 37) a[11,]<-c(29, 41, 79, 21, 82, 33, 77, 37, 62, 51, 0, 65, 42, 59, 61) a[12,]<-c(74, 51, 21, 51, 58, 37, 37, 33, 46, 21, 65, 0, 61, 11, 55) a[13,]<-c(23, 11, 64, 51, 46, 51, 51, 33, 29, 41, 42, 61, 0, 62, 23) a[14,]<-c(72, 52, 31, 43, 65, 29, 46, 31, 51, 23, 59, 11, 62, 0, 59) a[15,]<-c(46, 21, 51, 64, 23, 59, 33, 37, 11, 37, 61, 55, 23, 59, 0) path<-c(1, 13, 2, 15, 9, 5, 7, 3, 12, 14, 10, 8, 6, 4, 11) #' The problem environment \code{lau15} for a traveling salesman problem. #' #' @description #' 15 abstract cities for which a traveling salesman solution is sought. #' Solution: A path with a length of 291. #' #' The problem environment \code{lau15} is a list with the following functions: #' #' \enumerate{ #' \item \code{lau15$name()}: \code{"lau15"}, the name of the TSP #' problem environment. #' \item \code{lau15$genelength()}: 15, the number of cities on the round trip. #' \item \code{lau15$dist()}: The distance matrix of the problem. #' \item \code{lau15$cities()}: A list of city names or the vector #' \code{1:lau15$genelength()}. #' \item \code{lau15$f (permutation, gene = 0, lF = 0, tour = TRUE)}: #' The fitness function. Computes the roundtrip #' for permutation of cities. #' \item \code{lau15$solution()}: 291, the known optimal solution of lau15. #' \item \code{lau15$path()}: The permutation for the optimal roundtrip. #' \item \code{lau15$show(p)}: Prints the roundtrip \code{p}. #' \item \code{lau15$greedy(startposition, k)}: Computes a path of length #' \code{k} starting at \code{startposition} #' by choosing the nearest city. #' \item \code{lau15$kBestGreedy(k, tour=TRUE)}: #' Computes the best greedy path/tour with #' k cities. #' \item \code{lau15$rnd2Opt(permutation, maxtries=5)}: #' Tries to find a better permutation by #' at most 5 random 2-opt heuristics. #' \item \code{lau15$LinKernighan(permutation, maxtries=5)}: #' A randomized Lin-Kernigan heuristic implemented #' as a sequence of randomized 2-opt moves. #' } #' #' @references #' Lau, H. T. (1986): #' \emph{Combinatorial Heuristic Algorithms in FORTRAN}. #' Springer, 1986. p. 61. <doi:10.1007/978-3-642-61649-5> #' #' @family Problem Environments #' #' @export lau15<-newTSP(a, Name="lau15", Solution= 291, Path=path)
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/newTSP.R
#' Generates a problem environment for the XOR problem. #' #' @return The problem environment for the XOR problem with #' \itemize{ #' \item \code{$name}: #' \code{"envXOR"}, the name of the problem environment. #' \item \code{$buildtest(expr)}: #' The function which builds the environment #' for evaluating the expression #' by binding the variables to the parameters. #' \item \code{$TestCases}: The truthtable of the XOR function. #' \item \code{$f(expr, gene=NULL, lF=NULL)}: The fitness function. #' \code{expr} is the string with the #' logical expression to be evaluated. #' } #' #' @family Problem Environments #' #' @return The problem environment. #' @examples #' envXOR<-newEnvXOR() #' envXOR$name() #' a2<-"OR(OR(D1, D2), (AND(NOT(D1), NOT(D2))))" #' a3<-"OR(OR(D1, D2), AND(D1, D2))" #' a4<-"AND(OR(D1,D2),NOT(AND(D1,D2)))" #' gp4<-"(AND(AND(OR(D2,D1),NOT(AND(D1,D2))),(OR(D2,D1))))" #' envXOR$f(a2) #' envXOR$f(a3) #' envXOR$f(a4) #' envXOR$f(gp4) #' ## @importFrom xegaDerivationTrees treeLeaves #' @export newEnvXOR<-function() { self<-list() self$name<-function() {"envXOR"} self$buildTest<-function(expr) { f<-paste("function(v) { AND<-function(x,y){return(x & y)} NAND<-function(x,y){return(!(x & y))} OR<-function(x,y){return(x|y)} NOT<-function(x){return(!x)} D1<-v[1] D2<-v[2] return(", expr, ")}", sep="") return(eval(parse(text=f))) } self$TestCases<-matrix(c(0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0), nrow=4, ncol=3, byrow=TRUE) self$f<-function(expr, gene=NULL, lF=NULL) { test<-self$buildTest(expr) s<-0 for (i in 1:nrow(self$TestCases)) { s<-s+ (self$TestCases[i,ncol(self$TestCases)]==test(self$TestCases[i,])) } if (identical(gene, NULL)) {return(s)} # b<-xegaDerivationTrees::treeLeaves(gene$gene1, lF$Grammar$ST) # s<-(s+(1/(b^2))) return(s) } a<-self$name() a<-self$buildTest("D1") a<-self$TestCases return(self) } #' The problem environment \code{envXOR} for programming the XOR function #' either by grammar-based genetic programming or grammatical evolution. #' #' @description #' The problem environment \code{envXOR} is a list with the following elements: #' \itemize{ #' \item \code{envXOR$name}: #' \code{"envXOR"}, the name of the problem environment. #' \item \code{envXOR$buildtest(expr)}: #' The function which builds the environment #' for evaluating the expression with #' a binding of the variables to the parameters. #' \item \code{envXOR$TestCases}: The truth table of the XOR function. #' \item \code{envXOR$f(expr, gene=NULL, lF=NULL)}: The fitness function. #' \code{expr} is the string with the #' logical expression to be evaluated. #' } #' #' @family Problem Environments #' #' @export envXOR<-newEnvXOR()
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/newXOR.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-Level Functions # Independent of gene representation. # Package: selectGene # # - Scaling functions: identity, dynamic, linear, power law, logarithmic, ... # #' Scaling Fitness #' #' @description Fitness is transformed by a power function #' \code{fit^k}. #' If \code{k} is #' \itemize{ #' \item less than 1: Selection pressure is decreased. #' \item 1: Selection pressure remains constant. #' \item larger than 1: Selection pressure is increased. #' \item 0: Fitness is constant. Random selection. #' \item smaller than 0: Fitness is #' \code{1/k}. #' } #' #' @details Power functions are used for contrast sharpening or softening #' in image analysis. #' For fuzzy sets representing the value of a linguistic variable, #' the power function has been used as concentration or dilation #' transformations for modeling adverbs. #' #' @references Wenstop, Fred (1980) #' Quantitative Analysis with Linguistic Variables. #' Fuzzy Sets and Systems, 4(2), pp. 99-115. #' <doi:10.1016/0165-0114(80)90031-7> #' #' @param fit A fitness vector. #' @param k Scaling exponent. #' @param lF Local configuration. #' #' @return A scaled fitness vector. #' #' @family Scaling #' #' @examples #' lF<-list() #' lF$Offset<-parm(0.0001) #' fit<-sample(10, 20, replace=TRUE) #' fit #' ScaleFitness(fit, 0.5, lF) #' @export ScaleFitness<-function(fit, k, lF) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} return(fit^k) } #' Abstract interface for ScaleFitness. #' #' @description The scaling constant \code{k} is #' set by the function \code{lF$ScalingExp}. #' #' @param fit A fitness vector. #' @param lF Local configuration. #' #' @return Scaled fitness vector #' #' @family Scaling #' #' @examples #' lF<-list() #' lF$Offset<-parm(0.0001) #' lF$ScalingExp<-parm(2) #' fit<-sample(10, 20, replace=TRUE) #' fit #' ScalingFitness(fit, lF) #' @export ScalingFitness<-function(fit, lF) { ScaleFitness(fit, lF$ScalingExp(), lF)} #' Dispersion Ratio Based Fitness Scaling. #' #' @description Fitness is transformed by a power function #' \code{fit^lF$ScalingExp}. #' If \code{lF$ScalingExp} is #' \itemize{ #' \item less than 1: Selection pressure is decreased. #' \item 1: Selection pressure remains constant. #' \item larger than 1: Selection pressure is increased. #' \item 0: Fitness is constant. Random selection. #' \item smaller than 1: Fitness is #' \code{1/fit^lF$ScalingExp}. #' } #' #' @param fit Fitness vector. #' @param lF Local configuration. #' #' @return Scaled fitness vector. #' #' @family Scaling #' @family Adaptive Parameter #' #' @examples #' lF<-list() #' lF$Offset<-parm(0.0001) #' lF$ScalingThreshold<-parm(0.05) #' lF$RDM<-parm(1.0) #' lF$ScalingExp<-parm(0.5) #' lF$ScalingExp2<-parm(2) #' fit<-sample(10, 20, replace=TRUE) #' fit #' ThresholdScaleFitness(fit, lF) #' lF$RDM<-parm(1.2) #' ThresholdScaleFitness(fit, lF) #' lF$RDM<-parm(0.8) #' ThresholdScaleFitness(fit, lF) #' @export ThresholdScaleFitness<-function(fit, lF) { if (lF$RDM()>1+lF$ScalingThreshold()) # decrease pressure {return(ScaleFitness(fit, lF$ScalingExp(), lF))} if (lF$RDM()<1-lF$ScalingThreshold()) # increase pressure {return(ScaleFitness(fit, lF$ScalingExp2(), lF))} return(fit) } #' Dispersion Ratio Based Fitness Scaling. #' #' @param fit A fitness vector. #' @param lF Local configuration. #' #' @return Scaled fitness vector. #' #' @family Scaling #' @family Adaptive Parameter #' #' @examples #' lF<-list() #' lF$Offset<-parm(0.0001) #' lF$RDMWeight<-parm(2) #' lF$RDM<-parm(1.2) #' fit<-sample(10, 20, replace=TRUE) #' fit #' ContinuousScaleFitness(fit, lF) #' @export ContinuousScaleFitness<-function(fit, lF) {return(ScaleFitness(fit,(lF$RDMWeight()*lF$RDM()), lF))} #' Scaling Factory #' #' @param method A scaling method. Available methods are: #' \itemize{ #' \item "NoScaling": Identity (Default). #' \item "ConstantScaling": \code{fit^k} with constant exponent. #' Function \code{ConstantScaling}. #' \item "ThresholdScaling": #' If the dispersion ratio is larger than \code{1+threshold}, #' use a constant scaling exponent with a value below 1 #' (decrease of selection pressure). #' Function \code{ThresholdScaling}. #' \item If the dispersion ratio is lower than \code{1-threshold}, #' use a constant scaling exponent with a value above 1 #' (increase of selection pressure). #' \item "ContinuousScaling": Use weighted dispersion ratio #' as scaling exponent. #' Function \code{ContinuousScaling}. #' } #' #' @return A scaling function. #' #' @family Configuration #' #' @examples #' fit<-sample(10, 20, replace=TRUE) #' lF<-list() #' lF$ScalingExp<-parm(2) #' Scale<-ScalingFactory() #' fit #' Scale(fit, lF) #' Scale<-ScalingFactory("ConstantScaling") #' Scale(fit, lF) #' @export ScalingFactory<-function(method="NoScaling") { if (method=="NoScaling") {f<-function(x, lF) {x}} if (method=="ConstantScaling") {f<-ScalingFitness} if (method=="ThresholdScaling") {f<-ThresholdScaleFitness} if (method=="ContinuousScaling") {f<-ContinuousScaleFitness} if (!exists("f", inherits=FALSE)) {stop("Scaling label ", method, " does not exist")} return(f) } #' Dispersion Ratio #' #' @description The dispersion ratio is computed as #' the ratio \code{DM(t)/DM(k)} #' where \code{DM(t)} is the dispersion measure of period t and #' \code{DM(k)} the dispersion measure of period \code{max(1, (t-k))}. #' \code{k} is specified by \code{lF$ScalingDelay}. #' #' @details The dispersion ratio may take unreasonably high and low values #' leading to numerical underflow or overflow #' of fitness values. Therefore, #' we use hard thresholding to force #' the dispersion ratio into the interval #' \code{[lF$DRmin(), lF$DRmax()]}. #' The default interval is \code{[0.5, 2.0]}. #' #' @param popStat Population statistics. #' @param DM Dispersion function. #' @param lF Local configuration. #' #' @return Dispersion ratio. #' #' @family Scaling #' #' @examples #' p<-matrix(0, nrow=3, ncol=8) #' p[1,]<-c(14.1, 0.283, 5.53, 14.0, 19.4, 38.1, 90.2, 6.54) #' p[2,]<-c(20.7, 0.794, 14.63, 19.0, 26.5, 38.8, 71.4, 5.27) #' p[3,]<-c(24.0, 6.007, 16.89, 24.1, 29.2, 38.8, 73.4, 6.50) #' F<-list() #' F$ScalingDelay<-function() {1} #' F$DRmax<-function() {2.0} #' F$DRmin<-function() {0.5} #' dm<-DispersionMeasureFactory("var") #' DispersionRatio(p, dm, F) #' F$ScalingDelay<-function() {2} #' DispersionRatio(p, dm, F) #' @export DispersionRatio<-function(popStat, DM, lF) { t<-nrow(popStat) k<-max(1, (t-lF$ScalingDelay())) # cat("DM(popStat[t,]):",DM(popStat[t,]), # "divided", "DM(popStat[k,]):", DM(popStat[k,]), # "is", (DM(popStat[t,])/DM(popStat[k,])), "\n") ratio<-DM(popStat[t,])/DM(popStat[k,]) ### In case of overflow/underflow, set ratio to 1.0 if (is.na(ratio)) {ratio<-1.0} # nocov ##### lF$DRmin / lF$DRmax ?? ### smoothing by tanh centered on 1. ### hard thresholding! if (ratio>lF$DRmax()) {ratio<-lF$DRmax()} if (ratio<lF$DRmin()) {ratio<-lF$DRmin()} return(ratio) } #' Configure dispersion measure. #' #' \code{DispersionMeasureFactory} returns a function #' for the dispersion measure as specified by a label. #' If an invalid label is #' specified, the configuration fails. #' #' @param method A dispersion measure. #' \itemize{ #' \item "var": Variance (Default). #' \item "std": Standard deviation. #' \item "mad": Median absolute deviation (\code{mad(vec, constant=1)}). #' \item "cv": Coefficient of variation". #' \item "range": Range. #' \item "iqr": Inter quartile range #' (approximated by the lower and upper hinge of \code{fivenum}). #' } #' If an invalid label is #' specified, the configuration fails. #' #' @return A function which computes the dispersion measure from the vector of #' population statistics produced by \code{xegaObservePopulation} #' of package \code{xegaPopulation}. #' #' @family Configuration #' #' @examples #' require(stats) #' fit<-sample(30, 20, replace=TRUE) #' populationStats<-c(mean(fit), fivenum(fit), var(fit), mad(fit, constant=1)) #' dm<-DispersionMeasureFactory("var") #' dm(populationStats) #' dm<-DispersionMeasureFactory("range") #' dm(populationStats) #' @export DispersionMeasureFactory<-function(method="var") { if (method == "var") {f<-function(popstatvec) {popstatvec[7]}} if (method == "std") {f<-function(popstatvec) {popstatvec[7]^0.5}} if (method == "mad") {f<-function(popstatvec) {popstatvec[8]}} if (method == "cv") {f<-function(popstatvec) {(popstatvec[7]^0.5)/popstatvec[1]}} if (method == "range") {f<-function(popstatvec) {(popstatvec[6]-popstatvec[2])}} if (method == "iqr") {f<-function(popstatvec) {(popstatvec[5]-popstatvec[3])}} if (!exists("f", inherits=FALSE)) {stop("Dispersion measure label ", method, " does not exist")} return(f) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/scaling.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-Level Functions # Independent of gene representation. # Package: selectGene # # TODO: # - Annealing like acceptance functions and temperature. # # # Part I.1. Function Factories for Constants. # Part I.2. Object with local constant functions. # #' Factory for constants #' #'@description \code{parm} builds a constant function for \code{x}. #' See Wickham (2019). #' #'@references Wickham, Hadley (2019): Advanced R, CRC Press, Boca Raton. #' #'@param x A constant. #' #'@return The constant function. #' #'@examples #' TournamentSize<-parm(2) #' TournamentSize() #' Eps<-parm(0.01) #' Eps() #'@export parm<-function(x){function() {return(x)}} #' Generate local functions and objects. #' #'@description \code{NewlFselectGenes} returns #' the list of functions which contains #' a definition of all local objects required for the use #' of selection functions. We reference this object #' as local configuration. When adding additional #' selection functions, this must be extended #' by the constant (functions) needed to configure them. #' #'@return Local configuration \code{lF}. #' #'@examples #' lF<-NewlFselectGenes() #' lF$Max() #'@export NewlFselectGenes<-function() { list( SelectionContinuation = parm(TRUE), Max=parm(1), Offset = parm(1), Eps = parm(0.01), TournamentSize = parm(2), SelectionBias = parm(1.5), MaxTSR = parm(1.9), DRmax = parm(2.0), DRmin = parm(0.5), ScalingDelay = parm(1) ## ) } # # Part 2. Selection functions. # #' Selection proportional to fitness O(n ln(n)). #' #' @description \code{SelectPropFitOnln} implements selection #' proportional to fitness. Negative fitness #' vectors are shifted to \eqn{R^+}. #' The default of the function \code{lf$Offset} is \code{1}. #' Holland's schema theorem uses this selection function. #' See John Holland (1975) for further information. #' #' @details This is a fast implementation with equivalent results #' to the functions \code{SelectPropFit} and \code{SelectPropFitM}. #' Its runtime is \eqn{O(n . ln(n))}. #' #' @section Credits: #' The code of this function has been written by #' Fabian Aisenbrey. #' #' @references Holland, John (1975): #' \emph{Adaptation in Natural and Artificial Systems}, #' The University of Michigan Press, Ann Arbor. #' (ISBN:0-472-08460-7) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFitOnln(fit, NewlFselectGenes()) #' SelectPropFitOnln(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFitOnln<- function(fit, lF, size=1) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} weights<-fit/sum(fit) randoms<-sort(stats::runif(size)) index<-rep(0, size) outputIndex<-1; weightIndex<-1; cumWeight<-0.0; while (outputIndex<=size && weightIndex <= length(weights)) { cumWeight <- cumWeight + weights[weightIndex] while (outputIndex<= size && randoms[outputIndex]<cumWeight) { index[outputIndex]<-weightIndex outputIndex=outputIndex+1} weightIndex<-weightIndex+1 } # return(index[sample((1:size), size)]) return(index) } #' Selection proportional to fitness \eqn{O(n^2)}. #' #' @description \code{SelectPropFit} implements selection #' proportional to fitness. Negative fitness #' vectors are shifted to \eqn{R^+}. #' The default of the function \code{lf$Offset} is \code{1}. #' Holland's schema theorem uses this selection function. #' See John Holland (1975) for further information. #' #' @section Warning: #' There is a potential slow for-loop in the code. #' #' @references Holland, John (1975): #' \emph{Adaptation in Natural and Artificial Systems}, #' The University of Michigan Press, Ann Arbor. #' (ISBN:0-472-08460-7) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFit(fit, NewlFselectGenes()) #' SelectPropFit(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFit<- function(fit, lF, size=1) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} slots<-cumsum(fit)/sum(fit) index<-rep(0, size) for (i in (1:size)) { index[i]<-1+sum(1*slots<stats::runif(1)) } return(index) } #' Selection proportional to fitness (vector/matrix). #' #' @description \code{SelectPropFitM} implements selection #' proportional to fitness. Negative fitness #' vectors are shifted to \eqn{R^+}. #' The default of the function \code{lf$Offset} is \code{1}. #' Holland's schema theorem uses this selection function. #' See John Holland (1975) for further information. #' #' @section Warning: #' The code is completely written in vector/matrix #' operations. #' \code{outer} uses \eqn{O(n^2)} memory cells. #' #' @references Holland, John (1975): #' \emph{Adaptation in Natural and Artificial Systems}, #' The University of Michigan Press, Ann Arbor. #' (ISBN:0-472-08460-7) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFitM(fit, NewlFselectGenes()) #' SelectPropFitM(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFitM<- function(fit, lF, size=1) { if (min(fit)<= 0) {fit<-lF$Offset()+abs(min(fit))+fit} 1+colSums(1*outer((cumsum(fit)/sum(fit)), stats::runif(rep(1,size)), FUN="<")) } #' Selection proportional to fitness differences O(n ln(n)). #' #' @description \code{SelectPropFitDiffOnln} implements selection #' proportional to fitness differences. Negative fitness #' vectors are shifted to \eqn{R^+}. #' The default of the function \code{lf$Offset} is \code{1}. #' Holland's schema theorem uses this selection function. #' See John Holland (1975) for further information. #' #' @details This is a fast implementation which gives exactly the same #' results as the functions \code{SelectPropFitDiff} #' and \code{SelectPropDiffFitM}. #' Its runtime is \eqn{O(n . ln(n))}. #' #' @section Credits: #' The code of this function has been adapted by #' Fabian Aisenbrey. #' #' @section Warning: #' There is a potential slow for-loop in the code. #' #' @references Holland, John (1975): #' \emph{Adaptation in Natural and Artificial Systems}, #' The University of Michigan Press, Ann Arbor. #' (ISBN:0-472-08460-7) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFitDiffOnln(fit, NewlFselectGenes()) #' SelectPropFitOnln(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFitDiffOnln<- function(fit, lF, size=1) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} fitdiff<-fit-minimum weights<-fitdiff/sum(fitdiff) randoms<-sort(stats::runif(size)) index<-rep(0, size) outputIndex<-1; weightIndex<-1; cumWeight<-0.0; while (outputIndex<=size && weightIndex <= length(weights)) { cumWeight <- cumWeight + weights[weightIndex] while (outputIndex<= size && randoms[outputIndex]<cumWeight) { index[outputIndex]<-weightIndex outputIndex=outputIndex+1} weightIndex<-weightIndex+1 } # return(index[sample((1:size), size)]) return(index) } #' Selection proportional to fitness differences. #' #' @description \code{SelectPropFitDiff} implements selection #' proportional to fitness differences. #' It selects a gene out of the population #' with a probability proportional to the fitness #' difference to the gene with minimal fitness. #' The fitness of survival of the gene with #' minimal fitness is set by \code{lF$Eps()} #' to \code{0.01} per default. #' See equation (7.45) Andreas Geyer-Schulz (1997), p. 205. #' #' @references Geyer-Schulz, Andreas (1997): #' \emph{Fuzzy Rule-Based Expert Systems and Genetic Machine Learning}, #' Physica, Heidelberg. #' (ISBN:978-3-7908-0830-X) #' #' @section Note: #' \code{SelectPopFitDiff} is a dynamic scaling function. #' Complexity: \eqn{O(n^2)}. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFitDiff(fit, NewlFselectGenes()) #' SelectPropFitDiff(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFitDiff<- function(fit, lF, size=1) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} fitdiff<-fit-minimum slots<-cumsum(fitdiff)/sum(fitdiff) index<-rep(0, size) for (i in (1:size)) { index[i]<-1+sum(1*slots<stats::runif(1)) } return(index) } #' Selection proportional to fitness differences. #' #' @description \code{SelectPropFitDiffM} implements selection #' proportional to fitness differences. #' It selects a gene from the population #' with a probability proportional to the fitness #' difference to the gene with minimal fitness. #' The fitness of survival of the gene with #' minimal fitness is set by \code{lF$Eps()} #' to \code{0.01} per default. #' See equation (7.45) Andreas Geyer-Schulz (1997), p. 205. #' #' @section Warning: #' \code{outer} uses \eqn{O(n^2)} memory cells. #' #' @references Andreas Geyer-Schulz (1997): #' \emph{Fuzzy Rule-Based Expert Systems and Genetic Machine Learning}, #' Physica, Heidelberg. #' <978-3-7908-0830-X> #' #' @section Note: #' \code{SelectPopFitDiff} is a dynamic scaling function. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectPropFitDiffM(fit, NewlFselectGenes()) #' SelectPropFitDiffM(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectPropFitDiffM<- function(fit, lF, size=1) {1+colSums(1* outer((cumsum(lF$Eps()+(fit-min(fit)))/(lF$Eps()+sum(fit-min(fit)))), stats::runif(rep(1,size)),FUN="<"))} #' Selection with uniform probability. #' #' @description \code{SelectUniform} implements selection #' by choosing a gene with equal probability. #' #' @details This selection function is useful: #' \enumerate{ #' \item #' To specify mating behavior in crossover operators. #' \item #' For computer experiments without selection pressure. #' \item #' For computing random search solutions as a benchmark. #' } #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectUniform(fit, NewlFselectGenes()) #' SelectUniform(fit, NewlFselectGenes(), length(fit)) #' @export SelectUniform<- function(fit, lF, size=1) { sample(length(fit), size=size, replace=TRUE)} #' Selection with uniform probability without replacement. #' #' @description \code{SelectUniformP} implements selection #' by choosing a gene with equal probability without #' replacement. #' Usage: #' \enumerate{ #' \item #' To specify mating behavior in crossover operators. #' \item #' For computer experiments without selection pressure. #' } #' #' @details Selection without replacement guarantees that #' vectors of different indices are selected. #' A vector of the size of the population is a permutation #' of indices. This property is needed for the classic #' variant of differential evolution. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @references #' Price, Kenneth V., Storn, Rainer M. and Lampinen, Jouni A. (2005) #' The Differential Evolution Algorithm (Chapter 2), pp. 37-134. #' In: Differential Evolution. A Practical Approach to Global Optimization. #' Springer, Berlin. #' <doi:10.1007/3-540-31306-0> #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectUniformP(fit, NewlFselectGenes()) #' SelectUniformP(fit, NewlFselectGenes(), length(fit)) #' @export SelectUniformP<- function(fit, lF, size=1) { if (size <=length(fit)) {replace=FALSE} else {replace=TRUE} sample(length(fit), size=size, replace=replace)} #' Deterministic duel. #' #' @description \code{SelectDuel} implements selection #' by a tournament between 2 #' randomly selected genes. The best gene always wins. #' This is the version of tournament selection #' with the least selection pressure. #' #' @details This is an O(n) implementation of tournament selection with #' a tournament size of 2. #' #' @details A special case of tournament selection. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectDuel(fit, NewlFselectGenes()) #' SelectDuel(fit, NewlFselectGenes(), length(fit)) #' @export SelectDuel<-function(fit, lF, size=1) { l<-length(fit) cand1<-sample(1:l, size, replace=TRUE) cand2<-sample(1:l, size, replace=TRUE) cand1wins<-fit[cand1]>fit[cand2] i1<-cand1[cand1wins] i2<-cand2[!cand1wins] return(c(i1, i2)) } #' Deterministic tournament of size \code{k}. #' #' @description \code{Tournament} is implemented in two steps: #' \enumerate{ #' \item #' A subset of size k of the population is selected with uniform probability. #' \item #' A gene is selected with probability proportional to fitness. #' } #' #' @details In each generation, the worst gene in a population dies. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' #' @return Index of the best candidate. #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' Tournament(fit, NewlFselectGenes()) #' @export Tournament<-function(fit, lF) { cand<-sample(length(fit), size=lF$TournamentSize()) (cand[max(fit[cand])==fit[cand]])[1] } #' Stochastic tournament of size \code{k}. #' #' @description \code{STournament} is implemented in two steps: #' \enumerate{ #' \item #' A subset of size k of the population is selected with uniform probability. #' \item #' A gene is selected with probability proportional to fitness. #' } #' #' @param fit Fitness vector. #' @param lF Local configuration. #' #' @return Index of candidate. #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' STournament(fit, NewlFselectGenes()) #' @export STournament<-function(fit, lF) { cand<-sample(length(fit), size=lF$TournamentSize()) cand[SelectPropFit(fit[cand], lF)]} #' Tournament selection. #' #' @description \code{SelectTournament} implements selection #' by doing a tournament between \code{lF$TournamentSize()} #' randomly selected genes. The best gene always wins. #' The default of \code{lF$TournamentSize()} is \code{2}. This #' is the version with the least selection pressure. #' #' \code{lF$TournamentSize} must be less than the population size. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: \code{1}. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectTournament(fit, NewlFselectGenes()) #' SelectTournament(fit, NewlFselectGenes(), length(fit)) #' @export SelectTournament<-function(fit, lF, size=1) { index<-rep(0, size) for (i in (1:size)) { index[i]<-Tournament(fit, lF) } return(index) } #' Stochastic tournament selection. #' #' @description \code{SelectSTournament} implements selection #' through a stochastic tournament between #' \code{lF$TournamentSize()} #' randomly selected genes. A gene wins a tournament #' with a probability proportional to its fitness. #' The default of \code{lF$TournamentSize()} is \code{2}. #' A tournament #' with 2 participants has the least selection pressure. #' #' \code{lF$TournamentSize} must be less than the population size. #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectSTournament(fit, NewlFselectGenes()) #' SelectSTournament(fit, NewlFselectGenes(), length(fit)) #' @export SelectSTournament<-function(fit, lF, size=1) { index<-rep(0, size) for (i in (1:size)) { index[i]<-STournament(fit, lF) } return(index) } #' Stochastic universal sampling. #' #' @description \code{SelectSUS} implements selection #' by Baker's stochastic universal sampling method. #' SUS is a strictly sequential algorithm #' which has zero bias and minimal spread. #' SUS uses a single random number for each generation. #' See Baker, James E. (1987), p. 16. #' #' @references Baker, James E. (1987): #' Reducing Bias and Inefficiency in the Selection Algorithm. #' In Grefenstette, John J.(Ed.) #' \emph{Proceedings of the Second International #' Conference on Genetic Algorithms on Genetic Algorithms}, pp. 14-21. #' (ISBN:978-08058-0158-8) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Number of selected genes. Default: 1. #' #' @return The index vector of the selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectSUS(fit, NewlFselectGenes()) #' SelectSUS(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectSUS<-function(fit, lF, size=1) { minimum<-min(fit) if (minimum<= 0) {fit<-lF$Offset()+abs(minimum)+fit} sum<-0; pos<-1 ptr<-stats::runif(1) expVal<-fit/mean(fit) index<-rep(0, size) for (j in (1:length(fit))) { sum<-sum+expVal[j] while (sum>ptr) {index[pos]<-j; pos<-pos+1; ptr<-ptr+1} } return(index[sample(length(index), size=size, replace=(size>length(fit)))]) } #' Linear rank selection with selective pressure. #' #' @description \code{SelectLRSelective} implements selection #' by Whitley's linear rank selection with selective pressure #' for the GENITOR algorithm. #' See Whitley, Darrell (1989), p. 121. #' #' @details The selection pressure is configured by the constant function #' \code{lF$SelectionBias()}. Its values should be strictly larger #' than 1 and preferably below 2. The default is set to 1.5. #' A value of 1.0 means uniform random selection. #' #' @references Whitley, Darrell (1989): #' The GENITOR Algorithm and Selection Pressure. #' Why Rank-Based Allocation of Reproductive Trials is Best. #' In Schaffer, J. David (Ed.) #' \emph{Proceedings of the Third International #' Conference on Genetic Algorithms on Genetic Algorithms}, pp. 116-121. #' (ISBN:1-55860-066-3) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Size of return vector (default: 1). #' #' @return The index vector of selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectLRSelective(fit, NewlFselectGenes()) #' SelectLRSelective(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectLRSelective<- function(fit, lF, size=1) { sB<-lF$SelectionBias() i<-1.0+length(fit)*(sB-sqrt(sB*sB-4.0*(sB-1.0)*stats::runif(rep(1, size))))/2.0/(sB-1.0) f<-sort(fit, decreasing=TRUE, index.return=TRUE) return(f$ix[as.integer(i)]) } #' Linear rank selection. #' #' @description \code{SelectLinearRankTSR} implements selection #' with interpolated target sampling rates. #' #' @details The target sampling rate is a linear interpolation #' between \code{lF$MaxTSR} and \code{Min<-2-lF$MaxTSR}, #' because the sum of the target sampling rates is $n$. #' The target sampling rates are computed and used as a fitness #' vector for stochastic universal sampling algorithm #' implemented by \code{SelectSUS}. #' \code{lF$MaxTSR} should be in [1.0, 2.0]. #' #' TODO: More efficient implementation. We use two sorts! #' #' @references Grefenstette, John J. and Baker, James E. (1989): #' How Genetic Algorithms Work: A Critical Look at Implicit Parallelism #' In Schaffer, J. David (Ed.) #' \emph{Proceedings of the Third International #' Conference on Genetic Algorithms on Genetic Algorithms}, pp. 20-27. #' (ISBN:1-55860-066-3) #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param size Size of return vector (default: 1). #' #' @return The index vector of selected genes. #' #' @family Selection Functions #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' SelectLinearRankTSR(fit, NewlFselectGenes()) #' SelectLinearRankTSR(fit, NewlFselectGenes(), length(fit)) #' @importFrom stats runif #' @export SelectLinearRankTSR <- function(fit, lF, size=1) { Max<-lF$MaxTSR() Min<-2-Max n<-length(fit) tsr<-Min+(Max-Min)*((n:1)-1)/n f<-sort(fit, decreasing=TRUE, index.return=TRUE) fix<-sort(f$ix, decreasing=FALSE, index.return=TRUE) ftsr<-tsr[fix$ix] return(SelectSUS(ftsr, lF, size)) } # # Part 3. Configuration of selection functions. # #' Convert a selection function into a continuation. #' #' @description \code{TransformSelect} precomputes #' the indices of genes to be selected and #' converts the selection function into an access function to the #' next index. #' The access function provides a periodic random #' index stream with a period length of the population size. #' In a genetic algorithm with a fixed size population, #' this avoids recomputation of the selection functions #' for each gene #' and its mate. #' #' @details The motivation for this transformation is: #' \enumerate{ #' \item We avoid the recomputation of potentially #' expensive selection functions. #' E.g. In population-based genetic algorithms, #' the selection function #' is computed twice per generation instead of #' more than generation times the population size. #' \item No additional control flow is needed. #' \item Dynamic reconfiguration is possible. #' \item All selection functions have a #' common abstract interface and, #' therefore, can be overloaded by #' specialized concrete implementations. #' (Polymorphism). #' } #' #' The implementation idea is adapted from the #' continuation passing style #' in functional programming. See Reynolds, J. C. (1993). #' #' @section Parallelization/Distribution: #' \enumerate{ #' \item We use this tranformation if only the evaluation of genes #' should be parallelized/distributed. #' \item If the complete replication of genes is parallelized, #' this transformation cannot be used in its current form. #' The current implementations of the selection functions #' can not easily be parallelized. #' } #' #' @references Reynolds, J. C. (1993): #' The discoveries of continuations. #' \emph{LISP and Symbolic Computation} 6, 233-247. #' <doi:10.1007/BF01019459> #' #' @param fit Fitness vector. #' @param lF Local configuration. #' @param SelectFUN Selection function. #' #' @return A function with a state which consists of #' the precomputed gene index #' vector, its \code{length}, and a \code{counter}. #' The function increments the counter in the state #' of its environment and #' returns the precomputed gene index at position #' \code{modulo((counter+1),length)} in #' the precomputed index vector in its environment. #' The function supports the same interface as a selection function. #' #' @family Performance Optimization #' #' @examples #' fit<-sample(10, 15, replace=TRUE) #' newselect<-TransformSelect(fit, NewlFselectGenes(), SelectSUS) #' newselect(fit, NewlFselectGenes()) #' newselect(fit, NewlFselectGenes(), 5) #' newselect(fit, NewlFselectGenes(), 10) #' newselect(fit, NewlFselectGenes(), 10) #' @export TransformSelect<-function(fit, lF, SelectFUN) { c<-0 index<-SelectFUN(fit, lF, length(fit)) ilen<-length(index) return(function(fit, lF, size=1) { i<-index[1+(c+seq(1:size))%%ilen]; c<<-c+size; i}) } #' Configure the selection function of a genetic algorithm. #' #' @description \code{SelectGeneFactory} implements selection #' of one of the gene selection functions in this #' package by specifying a text string. #' The selection fails ungracefully (produces #' a runtime error), if the label does not match. #' The functions are specified locally. #' #' Current support: #' #' \enumerate{ #' \item "Uniform" returns \code{SelectUniform}. #' \item "UniformP" returns \code{SelectUniformP}. #' \item "ProportionalOnln" returns \code{SelectPropFitOnln}. #' \item "Proportional" returns \code{SelectPropFit}. #' \item "ProportionalM" returns \code{SelectPropFitM}. #' \item "PropFitDiffOnln" returns \code{SelectPropFitDiffOnln}. #' \item "PropFitDiff" returns \code{SelectPropFitDiff}. #' \item "PropFitDiffM" returns \code{SelectPropFitDiffM}. #' \item "Tournament" returns \code{SelectTournament}. #' \item "STournament" returns \code{SelectSTournament}. #' \item "Duel" returns \code{SelectDuel}. #' \item "LRSelective" returns \code{SelectLRSelective}. #' \item "LRTSR" returns \code{SelectLinearRankTSR}. #' \item "SUS" returns a function factory for \code{SelectSUS}. #' } #' #' @details #' If \code{SelectionContinuation()==TRUE} then: #' \enumerate{ #' \item In package xegaPopulation function \code{NextPopulation}, #' first the functions #' \code{SelectGene} and \code{SelectMate} #' are transformed by \code{TransformSelect} to #' a continuation function with #' embedded index vector and counter. #' \item For each call in \code{ReplicateGene}, #' \code{SelectGene} and \code{SelectMate} #' return the index of the selected gene. #' } #' #' @param method A string specifying the selection function. #' #' @return A selection function for genes. #' #' @family Configuration #' #' @examples #' SelectGene<-SelectGeneFactory("Uniform") #' fit<-sample(10, 15, replace=TRUE) #' SelectGene(fit, lFselectGenes) #' sel<-"Proportional" #' SelectGene<-SelectGeneFactory(method=sel) #' fit<-sample(10, 15, replace=TRUE) #' SelectGene(fit, lFselectGenes) #' @export SelectGeneFactory<-function(method="PropFitDiffOnln") { if (method=="Uniform") {f<- SelectUniform} if (method=="UniformP") {f<- SelectUniformP} if (method=="ProportionalOnln") {f<-SelectPropFitOnln} if (method=="Proportional") {f<-SelectPropFit} if (method=="ProportionalM") {f<-SelectPropFitM} if (method=="PropFitDiffOnln") {f<-SelectPropFitDiffOnln} if (method=="PropFitDiff") {f<-SelectPropFitDiff} if (method=="PropFitDiffM") {f<-SelectPropFitDiffM} if (method=="Duel") {f<- SelectDuel} if (method=="Tournament") {f<- SelectTournament} if (method=="STournament") {f<- SelectSTournament} if (method=="LRSelective") {f<- SelectLRSelective} if (method=="LRTSR") {f<- SelectLinearRankTSR} if (method=="SUS") {f<- SelectSUS} if (!exists("f", inherits=FALSE)) {stop("Selection label ", method, " does not exist")} return(f) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/selectGene.R
# # (c) 2023 Andreas Geyer-Schulz # selectGeneBenchmark.R: # Benchmark of # Package: selectGene # Simple Genetic Algorithm in R. V 0.1 # Layer: Gene-Level Functions # Independent of gene representation. # Package: selectGene # #' Test a gene selection function #' #' @description \code{testSelectGene} implements #' testing a selection function. #' It collects the results of the repeated execution #' of the selection function #' given a fitness function. #' #' @param fit Fitness vector. #' @param method String specifying the selection function. #' See \code{SelectGeneFactory}. #' @param howOften Integer. #' @param lF Local configuration. #' @param continuation Convert to index function? #' @param verbose Boolean. Default: \code{FALSE}. #' If \code{TRUE}, the exection time of the transformation of the selection function #' into a quasi-continuation function is printed on the console. #' #' @return #' \itemize{ #' \item \code{$fit} fitness vector. #' \item \code{$newPop} indices of survivors in fitness vector. #' \item \code{$time} time in seconds. #' \item \code{$size} population size. #' \item \code{$method} selection method used. #' } #' #' @family Benchmark Selection Functions #' #' @examples #' fit1<-rep(10,10) #' fit2<-fit1+runif(rep(10,1)) #' fit3<-sample(100, 10, replace=TRUE) #' testSelectGene(fit2, method="Tournament", howOften=100) #' testSelectGene(fit3, method="Tournament", howOften=10) #' @export testSelectGene<-function(fit, method="Uniform", howOften=100, lF=NewlFselectGenes(), continuation=TRUE, verbose=FALSE) { SelectGene<-SelectGeneFactory(method=method) v<-rep(0,howOften) gc() selectTimer<-newTimer() if (continuation) { selectTimer() SelectGene<-TransformSelect(fit, lF, SelectGene) selectTimer() if (verbose) cat("TransformSelect:", selectTimer("TimeUsed"), "\n") } selectTimer() for (i in 1: howOften) { v[i]<-SelectGene(fit, lF) } selectTimer() return(list(fit=fit, newPop=v, time=selectTimer("TimeUsed"), size=howOften, method=method, continuation=continuation)) #count<-rowSums(outer((1:length(fit)), v, FUN="==")) #freq<-count/size # #t<-t(matrix(c(fit, freq, count), nrow=3, byrow=TRUE)) # #return(t) } #' Benchmark and stress test of selection functions. #' #' @description Times a selection function #' for populations of size 10 to \eqn{10^{limit}}. #' #' @param method Selection function. Default: Uniform. #' @param continuation Convert to index function? Default: TRUE. #' @param limit Vector of population sizes. #' @param verbose Boolean. Default: \code{FALSE}. #' If \code{TRUE}, the function benchmarked and the population size #' are printed to the console. #' #' @return Vector of execution times in seconds. #' #' @family Benchmark Selection Functions #' @examples #' selectBenchmark(method="Uniform", continuation=TRUE, limit=c(10, 100, 1000)) #' selectBenchmark(method="SUS", continuation=TRUE, limit=c(5000, 10000, 15000)) #' selectBenchmark(method="SUS", continuation=FALSE, limit=seq(from=100, to=1000, length.out=5)) #' @export selectBenchmark<-function(method="Uniform", continuation=TRUE, limit=c(10, 100, 1000), verbose=FALSE) { result<-vector("double", length(limit)) for (i in (1:length(limit))) { size<-limit[i] if (verbose) cat(method,"Selecting n=",size, "candidates\n") fit<-sample(1000, size, replace=TRUE) a<-try(testSelectGene(fit, method=method, howOften=size, continuation=continuation)) result[i]<-a$time } return(result) #unlist(result[sapply(result, function(x) !inherits(x, "try-error"))]) } #' Script for testing a single selection functions #' #' @param name Name is one of the following strings. #' #' \enumerate{ #' \item "Uniform" benchmarks \code{SelectUniform}. #' \item "ProportionalOnln" benchmarks \code{SelectPropFitOnln}. #' \item "Proportional" benchmarks \code{SelectPropFit}. #' \item "ProportionalM" benchmarks \code{SelectPropFitM}. #' \item "PropFitDiffOnln" benchmarks \code{SelectPropFitDiffOnln}. #' \item "PropFitDiff" benchmarks \code{SelectPropFitDiff}. #' \item "PropFitDiffM" benchmarks \code{SelectPropFitDiffM}. #' \item "Tournament" benchmarks \code{SelectTournament}. #' \item "Duel" benchmarks \code{SelectDuel}. #' \item "LinearRank" benchmarks \code{SelectLinearRank}. #' \item "SUS" benchmarks \code{SelectSUS}. #' } #' #' @param limit Vector of population sizes. #' @param both For \code{both=TRUE} the selection function #' is benchmarked with and without transformation. #' For \code{both=FALSE}, only the transformed selection functions #' are benchmarked. #' @param verbose Boolean. Default: \code{FALSE}. #' If \code{TRUE}, the function benchmarked and the population size #' are printed to the console. #' #' @section Warning: #' The time to run the function for \code{lim>6} explodes #' for all benchmark functions with higher than linear complexity. #' (e.g. \code{PropFit}, \code{PropFitdiff}, and \code{Tournament}). #' #' @return A data frame sorted in ascending order of time of last column. #' #' @family Benchmark Selection Functions #' #' @examples #' runOneBenchmark("Duel", 5, both=FALSE) #' runOneBenchmark("PropFitDiffOnln") #' @export runOneBenchmark<-function(name, limit=c(10, 100, 1000), both=TRUE, verbose=FALSE) { d<-data.frame() n<-data.frame() n<-rbind(n, paste(name," C")) d<-rbind(d, selectBenchmark(method=name, continuation=TRUE, limit=limit, verbose=verbose)) if (both) { n<-rbind(n, name) d<-rbind(d, selectBenchmark(method=name, continuation=FALSE, limit=limit, verbose=verbose))} df<-cbind(n,d) names(df)<-c("Benchmark", unlist(lapply(limit, toString))) return(df) } #' Script for testing all selection functions #' #' #' #' @param lim Vector of population sizes. #' @param both For \code{both=TRUE} the selection function #' is benchmarked with and without transformation. #' For \code{both=FALSE}, only the transformed selection functions #' are benchmarked. #' @param verbose Boolean. Default: \code{FALSE}. #' If \code{TRUE}, the function benchmarked and the population size #' are printed to the console. #' #' #' @return A data frame sorted in ascending order of the time of #' the last column. #' The fastest selection methods come first. #' The first row contains the population sizes with which #' the benchmark has been performed. #' The data frame has \code{1+length(lim)} columns: #' \itemize{ #' \item "Benchmark": The name of the benchmarked selection #' function. A "C" after the name indicates #' that the selection function has been #' transformed into a lookup function. #' \item \code{length(lim)} columns with the execution times in seconds. #' } #' #' @family Benchmark Selection Functions #' #' @examples #' runSelectBenchmarks(lim=c(10, 100), both=TRUE, verbose=TRUE) #' runSelectBenchmarks(lim=c(10, 100), both=FALSE) #' @export runSelectBenchmarks<-function(lim=c(10, 100), both=TRUE, verbose=FALSE) { df<-data.frame() try(df<-rbind(df,runOneBenchmark("Uniform", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("Proportional", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("ProportionalOnln", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("ProportionalM", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("PropFitDiffOnln", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("PropFitDiff", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("PropFitDiffM", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("SUS", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("LRTSR", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("LRSelective", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("Duel", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("Tournament", lim, both, verbose))) try(df<-rbind(df,runOneBenchmark("STournament", lim, both, verbose))) # record with vector of population sizes (independent variable) n<-data.frame() n<-rbind(n, "popsize") d<-data.frame() d<-rbind(d, lim) pf<-cbind(n,d) names(pf)<-c("Benchmark", unlist(lapply(lim, toString))) # bind to matrix of timings ndf<-df[order(df[,length(lim)+1]),] ndf<-rbind(pf, ndf) return(ndf) } #### TODO! #' Predict the time use of a selection method for a popsize. #' #' @section Warning: #' #' Uses a quadratic regression model. #' But the complexities of the functions are of orders #' O(1), O(n), O(n.ln(n)) and O(n^2). #' #' @param df Data frame. #' @param method Selection method. #' @param popsize Population size. #' #' @return List with #' \itemize{ #' \item #' \code{$model}: The result of \code{stats::lm}. #' \item #' \code{$predict}: The result of \code{stats::predict}. #' } #' #' @family Benchmark Selection Functions #' #'@examples #' popsizes<-as.integer(seq(from=100, to=200, length.out=5)) #' a<-runSelectBenchmarks(popsizes, both=TRUE) #' b<-predictSelectTime(a, method="SUS", 155) #' summary(b$model) #' b$predicted #' c<- predictSelectTime(a, method="SUS C", c(155, 500)) #' summary(c$model) #' c$predicted #'@importFrom stats lm predict #'@export predictSelectTime<-function(df, method="Uniform", popsize=100000) { l<-ncol(df) ix<-unlist(lapply(df[,1], function(x) {is.element(x, "popsize")})) iy<-unlist(lapply(df[,1], function(x) {is.element(x, method)})) y<-as.vector(unlist(df[iy,2:l])) x<-as.vector(unlist(df[ix,2:l])) dt<-data.frame(matrix(c(y, x,(x * log(x)) , (x^2)), ncol=4)) names(dt)<-c("Y", "X1", "X2", "X3") model<-stats::lm(dt$Y~dt$X1+dt$X2+dt$X3) dt<-data.frame(X1=popsize, X2=popsize*log(popsize), X3=popsize^2) pred<-stats::predict(object=model, newdata=dt, interval="prediction") return(list(model=model, predicted=pred)) } # end of file
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/selectGeneBenchmark.R
# # (c) 2023 Andreas Geyer-Schulz # Simple Genetic Algorithm xegaX packages in R. V 0.1 # Layer: General Profiling functions. # #' Counter #' #' @description \code{newCounter} sets up a counter object with one #' internal state variable, namely \code{count} #' to count the number of counter calls. #' #' @details #' Generate a counter: #' \code{a<-newCounter()} sets up the counter \code{a}. #' The counter \code{a} supports three methods: #' \enumerate{ #' \item \code{a()} or #' \code{a("Measure")} or #' \code{a(method="Measure")} #' \strong{starts} the timer when called 1st, 3rd, 5th, ... time #' and \strong{stops} the timer #' when called the 2nd, 4th, 6th, ... time. #' The calls can be manually inserted #' before and after a block of R-code for profiling. #' \item \code{a("Count")} or #' \code{a(method="Count")} returns the number of times #' the function/block or R-code has been executed. #' } #' #' @return \code{newCounter()} returns a counter function. #' @return \code{a_counter_function()} returns the #' number of times it has been called #' (invisible). #' @return \code{a_counter_function("Show")} returns the number of executions #' of the \code{a_counter_function}. #' #' @family Performance Measurement #' #' @examples #' a<-newCounter() #' a(); a() #' a("Show") #' @export newCounter<-function() { count<-0 Counter<-function(method="Count") { if (method=="Count") { count<<-count+1 invisible<-count } if (method=="Show") { count } } return(Counter) } #' Timer for R code chunks. #' #' @description \code{newTimer} sets up a timer object with two #' internal state variables, namely \code{count} #' to count the number of timer calls and #' \code{tUsed} to calculate the total time spent in a code block #' between two timer calls. #' #' @details #' \itemize{ #' \item #' Generate a timer: #' \code{a<-newTimer()} sets up the timer \code{a}. #' The timer \code{a} supports three methods: #' \enumerate{ #' \item \code{a()} or #' \code{a("Measure")} or #' \code{a(method="Measure")} #' \strong{starts} the timer when called 1st, 3rd, 5th, ... time #' and \strong{stops} the timer #' when called the 2nd, 4th, 6th, ... time. #' The calls can be manually inserted #' before and after a block of R-code for profiling. #' \item \code{a("TimeUsed")} or #' \code{a(method="TimeUsed")} returns the time used in seconds. #' \item \code{a("Count")} or #' \code{a(method="Count")} returns the number of times #' the function/block or R-code has been executed. #' } #' \item #' The second way of usage is with the \code{Timed} function: #' \enumerate{ #' \item Generate a timer: #' \code{a<-newTimer()} sets up the timer \code{a}. #' \item You convert a function \code{b} into a timed function #' \code{bTimed} by #' \code{bTimed<-Timed(a, b)}. #' \item You use \code{bTimed} instead of \code{b}. #' \item At the end, you can query the aggregated time and #' the aggregated number of executions by #' \code{a("TimeUsed")} and #' \code{a("Count")}, respectively. #' } #' } #' #' @return \code{newTimer()} returns a timer function. #' @return \code{a_timer_function()} returns the used time in seconds #' (invisible). #' @return \code{a_timer_function("TimeUsed")} returns the used time in seconds. #' @return \code{a_timer_function("Count")} returns the number of executions #' of a timed function and/or a timed block of R-Code in seconds. #' #' @family Performance Measurement #' #' @examples #' a<-newTimer() #' a(); Sys.sleep(2); a() #' a("TimeUsed") #' a("Count") #' @export newTimer<-function() { tUsed<-0 tStart<-0 count<-0 Timer<-function(method="Measure") { if (method=="Measure") { if (count%%2) { tEnd<-Sys.time() tUsed<<-tUsed+as.numeric(tEnd-tStart, units="secs") count<<-count+1 invisible(tUsed) } else { tStart<<-Sys.time() count<<-count+1 invisible(tUsed) } } if (method=="TimeUsed") { return(tUsed) } if (method=="Count") { return(count/2) } } return(Timer) } #' Transformation into a counted function #' #' @description #' \code{Counted} takes two functions as arguments: #' The function whose call frequency #' should be measured and a counter object created by \code{newCounter()}. #' It returns a counted function. #' #' @param FUN A function whose run time should be measured. #' @param counter A counter generated by \code{newCounter()}. #' #' @return A counted function. #' #' @family Performance Measurement #' #' @examples #' test<-function(v) {sum(v)} #' testCounter<-newCounter() #' testCounted<-Counted(test, testCounter) #' testCounter("Show") #' testCounted(sample(10,10)); testCounted(sample(10,10)) #' testCounter("Show") #' @export Counted<-function(FUN, counter) { cFUN<-function(...){z<-FUN(...);counter();return(z)} return(cFUN) } #' Transformation into a timed function #' #' @description #' \code{Timed} takes two functions as arguments, #' namely the function whose time and call frequency #' should be measured and a timer object created by \code{newTimer()}. #' It returns a timed function. #' #' @param FUN A function whose run time should be measured. #' @param timer A timer generated by \code{newTimer()}. #' #' @return A timed function. #' #' @family Performance Measurement #' #' @examples #' test<-function(seconds) {Sys.sleep(seconds)} #' testTimer<-newTimer() #' testTimed<-Timed(test, testTimer) #' testTimer("Count"); testTimer("TimeUsed") #' testTimed(1); testTimed(2) #' testTimer("Count") #' testTimer("TimeUsed") #' @export Timed<-function(FUN, timer) { tFUN<-function(...){timer();z<-FUN(...);timer();return(z)} return(tFUN) }
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/timer.R
#' Selection functions for genetic algorithms. #' #' The \code{selectGene} package provides selection and scaling functions #' for genetic algorithms. #' All functions of this package are independent of the gene #' representation. #' #' \itemize{ #' \item Scaling functions and dispersion measures are in scaling.R #' \item Selection functions are in selectGene.R. #' For selection functions, a transformation to index access #' functions is provided (a limited form of function continuation). #' \item Benchmark functions for selection functions are in #' selectGeneBenchmark.R. #' Except for uniform selection, the continuation form of #' selection functions should be used. #' \item Evaluation functions are in evalGene.R. #' \item Counting and timing of function executions #' are provided by transformation functions in timer.R #' \item Problem environments for examples and unit tests for #' \itemize{ #' \item function optimization: #' DeJongF4.R (stochastic functions) and Parabola2D.R #' (delayed execution for benchmarking of parallelism, #' deterministic function, #' deterministic function with early termination check, #' function with random failures) #' \item combinatorial optimization: #' newTSP.R (for the traveling salesman problem). #' \item boolean function learning: #' newXOR.R (for the XOR problem). #' } #' } #' #' @section Interface Scaling Functions: #' #' All scaling functions must implement #' the following abstract interface: #' #' \code{function name}(\code{fit}, \code{lF}) #' #' \strong{Parameters} #' #' \itemize{ #' \item \code{fit} A fitness vector. #' \item \code{lF} Local configuration. #' } #' #' \strong{Return Value} #' #' Scaled fitness vector. #' #' @section Interface Dispersion Measures: #' #' All dispersion measure functions must implement #' the following abstract interface: #' #' \code{function name}(\code{popstatvec}) #' #' \strong{Parameters} #' #' \itemize{ #' \item \code{popstatvec} Vector of population statistics. #' #' The internal state of the genetic algorithm is described #' by a matrix of the history of population statistics. #' Each row consists of 8 population statistics #' (mean, min, Q1, median, Q3, max, var, mad). #' A row is a vector of population statistics. #' #' } #' #' \strong{Return Value} #' #' Dispersion measure (real). #' #' @section Interface Selection Functions: #' #' All selection functions must implement #' the following abstract interface: #' #' \code{function name}(\code{fit}, \code{lF}, \code{size}) #' #' \strong{Parameters} #' #' \itemize{ #' \item \code{fit} a vector of fitness values. #' \item \code{lF} a local function list. #' \item \code{size} the number of indices returned. #' } #' #' \strong{Return Value} #' #' A vector of indices of length \code{size}. #' #' All selection functions are implemented #' WITHOUT a default assignment to \code{lF}. #' #' A missing configuration should raise an error! #' #' The default value of \code{size} is \code{1}. #' #' #'@section Constants: #' #' Some scaling and selection functions use constants which should #' be configured. #' We handle these constants by #' constant functions created by \code{parm(constant)}. #' We store all of these functions in the list of #' local functions \code{lF}. #' The rationale is to reduce the number of parameters #' of selection functions and to provide a uniform #' interface for selection functions. #' #'@section Table of Scaling Constants: #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$Offset \tab 1 \tab ScaleFitness \cr #' lF$ScalingExp \tab 1 \tab ScalingFitness, \cr #' \tab \tab ThresholdScaleFitness \cr #' lF$ScalingExp2 \tab 1 \tab ThresholdScaleFitness \cr #' lF$ScalingThreshold \tab 1 \tab ThresholdScaleFitness \cr #' lF$RDMWeight \tab 1.0 \tab ContinuousScaleFitness \cr #' lF$DRMin \tab 0.5 \tab DispersionRatio \cr #' lF$DRMax \tab 2.0 \tab DispersionRatio \cr #' lF$ScalingDelay \tab 1 \tab DispersionRatio \cr #' } #' #' \tabular{rcl}{ #' \strong{State Variable} \tab \strong{Start Value} \tab \strong{Used in} \cr #' lF$RDM \tab 1.0 \tab ThresholdScaleFitness \cr #' \tab \tab ContinuousScaleFitness \cr #' \tab \tab xega::RunGA \cr #' } #' #'@section Table of Selection Constants: #' #' \tabular{rcl}{ #' \strong{Constant} \tab \strong{Default} \tab \strong{Used in} \cr #' lF$SelectionContinuation \tab TRUE \tab xegaPopulation::xegaNextPopulation \cr #' lF$Offset \tab 1 \tab SelectPropFitOnLn \cr #' \tab \tab SelectPropFit \cr #' \tab \tab SelectPropFitM \cr #' \tab \tab SelectPropFitDiffOnLn \cr #' \tab \tab SelectPropFitDiff \cr #' \tab \tab SUS \cr #' \tab \tab SelectLinearRankTSR \cr #' lF$eps \tab 0.01 \tab SelectPropFitDiffM \cr #' lF$TournamentSize \tab 2 \tab Tournament \cr #' \tab \tab SelectTournament \cr #' \tab \tab STournament \cr #' \tab \tab SelectSTournament \cr #' lF$SelectionBias \tab 1.5 \tab SelectLRSelective \cr #' lF$MaxTSR \tab 1.5 \tab SelectLinearRankTSR #' } #' #'@section Parallel/Distributed Execution: #' #' All selection functions in this package return #' \enumerate{ #' \item the index of a selected gene. #' The configured selection function is executed each time #' a gene must be selected in the gene replication process. #' This allows a parallelization/distribution of the #' complete gene replication process and the fitness evaluation. #' However, the price to pay is a recomputation of the selection #' algorithms for each gene and each mate (which may be costly). #' The execution time of Baker's SUS function explodes #' when used in this way. #' \item a vector of indices of the selected genes. #' We compute #' a vector of indices for genes and their mates, #' and we replace the selection function with a #' quasi-continuation function #' with precomputed indices #' which when called, returns the next index. #' The selection computation is executed once for each generation #' without costly recomputation. #' The cost of selecting a gene and its mate is the cost of indexing #' an integer in a vector. #' This version is faster for almost all selection functions #' (Sequential computation). #' #' The parallelization of quasi-continuation function is not yet implemented. #' } #' #' @section Constant Functions for Configuration: #' #' The following constant functions are expected to be in the local function list lF. #' \itemize{ #' \item \code{Offset()} in \code{SelectPropFit}: #' Since all fitness values must be larger than 0, #' in case of negative fitness values, \code{Offset()} #' is the value of the minimum fitness value (default: 1). #' \item \code{Eps()} in \code{SelectPropFitDiff}: #' \code{Eps()} is a very small value to eliminate #' differences of 0. #' \item \code{TournamentSize()} in \code{SelectTournament}: #' Specifies the size of the tournament. Per default: 2. #' \item \code{SelectionBias()} in \code{SelectLinearRank}. #' This constant must be larger than 1.0 and usually #' should be set at most to 2.0. #' Increasing \code{SelectionBias()} #' increases selection pressure. #' Beyond 2.0, there is the danger of premature convergence. #' } #' #' @section Performance Measurement: #' #' The file \code{Timer.R}: Functions for timing and counting. #' #' The file \code{selectGeneBenchmark.R}: A benchmark of selection functions. #' #' @section Interface Function Evaluation and Methods: #' #' All evaluation functions must implement #' the following abstract interface: #' #' \code{function name}(\code{gene}, \code{lF}) #' #' \strong{Parameters} #' #' \itemize{ #' \item \code{gene} a gene. #' \item \code{lF} a local function list. #' } #' #' \strong{Return Value} #' #' A gene. #' #' The file \code{evalGene.R} contains different function evaluation methods. #' \enumerate{ #' \item \code{EvalGeneU} evaluates a gene unconditionally. (Default.) #' \item \code{EvalGeneR} evaluates a gene unconditionally #' and allows the repair of the gene by the decoder. #' #' \item \code{EvalGeneDet} memoizes the evaluation of a gene in the #' in the gene. Genes are evaluated only once. #' This leads to a performance improvement for #' deterministic functions. #' #' \item \code{EvalGeneStoch} computes an incremental average of #' the value of a gene. #' The average converges to the true value as the number #' of repeated evaluations of a gene increases. #' } #' #' @section Gene Representation: #' #' A gene is a named list: #' \itemize{ #' \item $gene1 the gene. #' \item $fit the fitness value of the gene #' (for EvalGeneDet and EvalGeneU) or #' the mean fitness (for stochastic functions #' evaluated with EvalGeneStoch). #' \item $evaluated has the gene been evaluated? #' \item $evalFail has the evaluation of the gene failed? #' \item $var the cumulative variance of the fitness #' of all evaluations of a gene. #' (For stochastic functions) #' \item $sigma the standard deviation of the fitness of #' all evaluations of a gene. #' (For stochastic functions) #' \item $obs the number of evaluations of a gene. #' (For stochastic functions) #' } #' #' @section The Architecture of the xegaX-Packages: #' #' The xegaX-packages are a family of R-packages which implement #' eXtended Evolutionary and Genetic Algorithms (xega). #' The architecture has 3 layers, #' namely the user interface layer, #' the population layer, and the gene layer: #' #' \itemize{ #' \item #' The user interface layer (package \code{xega}) #' provides a function call interface and configuration support #' for several algorithms: genetic algorithms (sga), #' permutation-based genetic algorithms (sgPerm), #' derivation-free algorithms as e.g. differential evolution (sgde), #' grammar-based genetic programming (sgp) and grammatical evolution #' (sge). #' \item #' The population layer (package \code{xegaPopulation}) contains #' population-related functionality as well as support for #' population statistics dependent adaptive mechanisms and parallelization. #' \item #' The gene layer is split into a representation-independent and #' a representation-dependent part: #' \enumerate{ #' \item #' The representation-indendent part (package \code{xegaSelectGene}) #' is responsible for variants of selection operators, evaluation #' strategies for genes, and profiling and timing capabilities. #' \item #' The representation-dependent part consists of the following packages: #' \itemize{ #' \item \code{xegaGaGene} for binary coded genetic algorithms. #' \item \code{xegaPermGene} for permutation-based genetic algorithms. #' \item \code{xegaDfGene} for derivation-free algorithms as e.g. #' differential evolution. #' \item \code{xegaGpGene} for grammar-based genetic algorithms. #' \item \code{xegaGeGene} for grammatical evolution algorithms. #' } #' The packages \code{xegaDerivationTrees} and \code{xegaBNF} support #' the last two packages: #' \code{xegaBNF} essentially provides a grammar compiler, and #' \code{xegaDerivationTrees} is an abstract data type for derivation trees. #' }} #' #' @family Package Description #' #' @name xegaSelectGene #' @aliases xegaSelectGene #' @docType package #' @title Package xegaSelectGene. #' @author Andreas Geyer-Schulz #' @section Copyright: (c) 2023 Andreas Geyer-Schulz #' @section License: MIT #' @section URL: <https://github.com/ageyerschulz/xegaSelectGene> #' @section Installation: From CRAN by \code{install.packages('xegaSelectGene')} NULL
/scratch/gouwar.j/cran-all/cranData/xegaSelectGene/R/xegaSelectGene-package.R
# This file contains preprocessing functions for btergm and tnam. # check if a matrix is a one-mode matrix is.mat.onemode <- function(mat) { if (nrow(mat) != ncol(mat)) { return(FALSE) } else if (!is.null(rownames(mat)) && !is.null(colnames(mat)) && any(rownames(mat) != colnames(mat))) { return(FALSE) } else { return(TRUE) } } # check if a matrix represents a directed network is.mat.directed <- function(mat) { if (nrow(mat) != ncol(mat)) { return(FALSE) } else if (!is.null(rownames(mat)) && !is.null(colnames(mat)) && any(rownames(mat) != colnames(mat), na.rm = TRUE)) { return(FALSE) } else { if (any(as.matrix(mat) != t(as.matrix(mat)), na.rm = TRUE)) { return(TRUE) } else { return(FALSE) } } } # how many NAs are there per row or column? numMissing <- function(mat, type = "both", na = NA) { numrow <- apply(as.matrix(mat), 1, function(x) sum(x %in% na)) numcol <- apply(as.matrix(mat), 2, function(x) sum(x %in% na)) if (type == "both") { return(numrow + numcol) } else if (type == "row") { return(numrow) } else if (type == "col") { return(numcol) } else { stop("Unknown 'type' argument in the 'numMissing' function.") } } # process NA values (= remove nodes with NAs iteratively) handleMissings <- function(mat, na = NA, method = "remove", logical = FALSE) { # check and convert arguments if (is.null(mat)) { stop("The 'mat' argument is not valid.") } else if ("list" %in% class(mat)) { # OK; do nothing; check later in next step initialtype <- "list" } else if (is.matrix(mat) || is.network(mat) || is.data.frame(mat)) { # wrap in list initialtype <- class(mat) mat <- list(mat) } else if (length(mat) > 1) { # vector --> wrap in list initialtype <- class(mat) mat <- list(mat) } else if (is.function(mat)) { stop(paste("The input object is a function. Did you choose a name", "for the input object which already exists as a function in the", "workspace?")) } else { stop("The 'mat' argument is not valid.") } onemode <- list() # will indicate whether it is a one- or two-mode network directed <- list() # will indicate whether the network is directed attribnames <- list() # will contain the names of nodal attributes attributes <- list() # will contain the nodal attributes at each time step type <- list() # will indicate the type of data structure at time step i for (i in 1:length(mat)) { if (is.matrix(mat[[i]])) { # check manually if onemode and directed onemode[[i]] <- is.mat.onemode(mat[[i]]) # helper function directed[[i]] <- is.mat.directed(mat[[i]]) # helper function type[[i]] <- "matrix" } else if (is.network(mat[[i]])) { # save onemode and directed information; save attributes for later use if (is.bipartite(mat[[i]])) { onemode[[i]] <- FALSE } else { onemode[[i]] <- TRUE } if (is.directed(mat[[i]])) { directed[[i]] <- TRUE } else { directed[[i]] <- FALSE } attribnames[[i]] <- list.vertex.attributes(mat[[i]]) attrib <- list() # list of attributes at time i if (network.size(mat[[i]]) == 0) { attribnames[[i]] <- character() attributes[[i]] <- list(character()) } else { for (j in 1:length(attribnames[[i]])) { attrib[[j]] <- get.vertex.attribute(mat[[i]], attribnames[[i]][j]) } } attributes[[i]] <- attrib mat[[i]] <- as.matrix(mat[[i]]) type[[i]] <- "network" } else if (is.data.frame(mat[[i]])) { type[[i]] <- "data.frame" } else { type[[i]] <- class(mat[[i]]) } } if (is.null(logical) || !is.logical(logical) || length(logical) > 1) { stop("The 'logical' argument should be either TRUE or FALSE.") } if (is.null(method) || !is.character(method)) { stop("The 'method' argument should be a character object.") } if (length(method) > 1) { method <- method[1] } na.mat <- list() # will contain matrices indicating which values are NA for (i in 1:length(mat)) { na.mat[[i]] <- apply(mat[[i]], 1:2, function(x) x %in% NA) if (length(mat) == 1) { # used for reporting later time <- "" } else { time <- paste0("t = ", i, ": ") } if (is.matrix(mat[[i]])) { # matrix objects # replace by real NAs, then count NAs obs <- length(mat[[i]]) missing.abs <- length(which(mat[[i]] %in% na)) missing.perc <- round(100 * missing.abs / obs, digits = 2) # do the actual work if (method == "fillmode") { # fill with modal value (often 0 but not always) nwunique <- unique(as.numeric(mat[[i]][!mat[[i]] %in% na])) nwmode <- nwunique[which.max(tabulate(match(mat[[i]][!mat[[i]] %in% na], nwunique)))] mat[[i]][mat[[i]] %in% na] <- nwmode message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " ties) were replaced by the mode (", nwmode, ") because they were NA.")) } else if (method == "zero") { # impute 0 when NA mat[[i]][mat[[i]] %in% na] <- 0 message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " ties) were replaced by 0 because they were NA.")) } else if (method == "remove") { # remove rows and columns with NA values iteratively rowLabels <- rownames(mat[[i]]) colLabels <- colnames(mat[[i]]) if (onemode[[i]] == TRUE) { while(sum(numMissing(mat[[i]], na = na)) > 0) { indices <- which(numMissing(mat[[i]], na = na) == max(numMissing(mat[[i]], na = na))) mat[[i]] <- mat[[i]][-indices, -indices] rowLabels <- rowLabels[-indices] colLabels <- colLabels[-indices] na.mat[[i]][indices, ] <- TRUE na.mat[[i]][, indices] <- TRUE if ("network" %in% type[[i]]) { if (length(attribnames[[i]]) > 0) { for (j in 1:length(attribnames[[i]])) { attributes[[i]][[j]] <- attributes[[i]][[j]][-indices] } } } } } else { while(sum(numMissing(mat[[i]], type = "row", na = na)) + sum(numMissing(mat[[i]], type = "col", na = na)) > 0) { rowNAs <- numMissing(mat[[i]], type = "row", na = na) colNAs <- numMissing(mat[[i]], type = "col", na = na) maxNA <- max(c(rowNAs, colNAs)) if (length(which(rowNAs == maxNA)) > 0) { indices <- which(rowNAs == maxNA) mat[[i]] <- mat[[i]][-indices, ] rowLabels <- rowLabels[-indices] na.mat[[i]][indices, ] <- TRUE if ("network" %in% type[[i]]) { if (length(attribnames[[i]]) > 0) { for (j in 1:length(attribnames[[i]])) { attributes[[i]][[j]] <- attributes[[i]][[j]][-indices] } } } } else if (length(which(colNAs == maxNA)) > 0) { indices <- which(colNAs == maxNA) mat[[i]] <- mat[[i]][, -indices] colLabels <- colLabels[-indices] na.mat[[i]][, indices] <- TRUE # in bipartite networks, attributes for rows and columns are # saved in a single vector consecutively indices.bip <- nrow(mat[[i]]) + indices if ("network" %in% type[[i]]) { if (length(attribnames[[i]]) > 0) { for (j in 1:length(attribnames[[i]])) { attributes[[i]][[j]] <- attributes[[i]][[j]][-indices.bip] } } } } } } rownames(mat[[i]]) <- rowLabels colnames(mat[[i]]) <- colLabels removed.abs <- obs - length(mat[[i]]) removed.perc <- round(100 * removed.abs / obs, digits = 2) if (is.nan(removed.perc)) { removed.perc <- 0 } if (is.nan(missing.perc)) { missing.perc <- 0 } message(paste0("t = ", i, ": ", removed.perc, "% of the data (= ", removed.abs, " ties) were dropped due to ", missing.perc, "% (= ", missing.abs, ") missing ties.")) } else { stop("Method not supported.") } # convert back into network if initial item was a network if ("network" %in% type[[i]]) { bip <- (onemode[[i]] == FALSE) mat[[i]] <- network(mat[[i]], directed = directed[[i]], bipartite = bip) if (length(attribnames[[i]]) > 0) { for (j in 1:length(attribnames[[i]])) { mat[[i]] <- set.vertex.attribute(mat[[i]], attribnames[[i]][j], attributes[[i]][[j]]) } } } } else if (is.data.frame(mat[[i]])) { # data.frame objects # replace by real NAs, then count NAs for (j in 1:nrow(mat[[i]])) { for (k in 1:ncol(mat[[i]])) { if (mat[[i]][j, k] %in% na) { mat[[i]][j, k] <- NA } } } obs <- nrow(mat[[i]]) * ncol(mat[[i]]) missing.abs <- length(which(is.na(mat[[i]]))) missing.perc <- round(100 * missing.abs / obs, digits = 2) # do the actual work if (method == "fillmode") { # fill with modal value (often 0 but not always) for (j in 1:ncol(mat[[i]])) { if (is.numeric(mat[[i]][, j])) { nwunique <- unique(as.numeric(mat[[i]][, j])) nwmode <- nwunique[which.max(tabulate(match(mat[[i]][, j], nwunique)))] mat[[i]][, j][is.na(mat[[i]][, j])] <- nwmode } } message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " ties) were replaced by the mode in the respective ", "column because they were NA.")) } else if (method == "zero") { # impute 0 when NA for (j in 1:ncol(mat[[i]])) { mat[[i]][, j][is.na(mat[[i]][, j])] <- 0 } message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " elements) were replaced by 0 because they were NA.")) } else if (method == "remove") { # remove rows with NA values before <- nrow(mat[[i]]) mat[[i]] <- mat[[i]][complete.cases(mat[[i]]), ] after <- nrow(mat[[i]]) removed <- before - after rem.perc <- 100 * (1 - after / before) message(paste0("t = ", i, ": ", removed, " rows (", rem.perc, "% of all rows) were removed due to missing elements.")) } else { stop("Method not supported.") } } else if (length(mat[[i]]) > 1) { # vectors of arbitrary content mat[[i]][mat[[i]] %in% na] <- NA obs <- length(mat[[i]]) missing.abs <- length(which(is.na(mat[[i]]))) missing.perc <- round(100 * missing.abs / obs, digits = 2) # do the actual work if (method == "fillmode") { # fill with modal value (often 0 but not always) if (!is.numeric(mat[[i]])) { stop("'fillmode' is only compatible with numeric objects.") } nwunique <- unique(as.numeric(mat[[i]])) nwmode <- nwunique[which.max(tabulate(match(mat[[i]], nwunique)))] mat[[i]][is.na(mat[[i]])] <- nwmode message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " ties) were replaced by the mode in the respective ", "column because they were NA.")) } else if (method == "zero") { # impute 0 when NA mat[[i]][is.na(mat[[i]])] <- 0 message(paste0("t = ", i, ": ", missing.perc, "% of the data (= ", missing.abs, " ties) were replaced by 0 because they were NA.")) } else if (method == "remove") { # remove NA values mat[[i]] <- mat[[i]][!is.na(mat[[i]])] message(paste0(time, missing.perc, "% of the data (= ", missing.abs, " elements) were removed because they were NA.")) } else { stop("Method not supported.") } } } if (logical == TRUE) { if (length(na.mat) == 1 && !"list" %in% initialtype) { return(na.mat[[1]]) } else { return(na.mat) } } else { if (length(mat) == 1 && !"list" %in% initialtype) { return(mat[[1]]) } else { return(mat) } } } # adjust the dimensions of a source object to the dimensions of a target object adjust <- function(source, target, remove = TRUE, add = TRUE, value = NA, returnlabels = FALSE) { # make sure the source is a list if (is.null(source)) { stop("The 'source' argument was not recognized.") } else if (is.matrix(source)) { # wrap in list sources <- list() sources[[1]] <- source sources.initialtype <- "matrix" } else if (is.network(source)) { # wrap in list sources <- list() sources[[1]] <- source sources.initialtype <- "network" } else if ("list" %in% class(source)) { # rename sources <- source sources.initialtype <- "list" } else if (is.vector(source)) { # vector of some type; wrap in list sources <- list() sources[[1]] <- source sources.initialtype <- "vector" } else { stop(paste("Source data type not supported. Supported types are 'matrix',", "'network', and 'list' objects and vectors.")) } # make sure the target is a list if (is.null(target)) { stop("The 'target' argument was not recognized.") } else if (is.matrix(target)) { # wrap in list targets <- list() targets[[1]] <- target targets.initialtype <- "matrix" } else if (is.network(target)) { # wrap in list targets <- list() targets[[1]] <- target targets.initialtype <- "network" } else if ("list" %in% class(target)) { # rename targets <- target targets.initialtype <- "list" } else if (is.vector(target)) { # vector of some type; wrap in list targets <- list() targets[[1]] <- target targets.initialtype <- "vector" } else { stop(paste("Target data type not supported. Supported types are 'matrix',", "'network', and 'list' objects and vectors.")) } # make sure that both lists (sources and targets) have the same length if (length(sources) == length(targets)) { # OK; do nothing } else if (length(sources) == 1) { for (i in 2:length(targets)) { sources[[i]] <- sources[[1]] } } else if (length(targets) == 1) { for (i in 2:length(sources)) { targets[[i]] <- targets[[1]] } } else { stop("Different numbers of sources and targets were provided.") } # convert each item if necessary and save nodal attributes sources.attribnames <- list() # names of additional vertex attributes sources.attributes <- list() # additional vertex attributes sources.types <- list() # matrix, network etc. sources.onemode <- list() # is the source network a one-mode network? sources.directed <- list() # is the source network directed? sources.matrixnames <- list() # names of additional matrices sources.matrices <- list() # additional matrices stored in the source network targets.attribnames <- list() # names of additional vertex attributes targets.attributes <- list() # additional vertex attributes targets.types <- list() # matrix, network etc. targets.onemode <- list() # is the target network a one-mode network? targets.directed <- list() # is the source network directed? for (i in 1:length(sources)) { sources.types[[i]] <- class(sources[[i]]) if (is.network(sources[[i]])) { # save source attributes and other meta information in list sources.attribnames[[i]] <- list.vertex.attributes(sources[[i]]) attributes <- list() if (!is.null(sources.attribnames[[i]]) && length(sources.attribnames[[i]]) > 0) { for (j in 1:length(sources.attribnames[[i]])) { attributes[[j]] <- get.vertex.attribute(sources[[i]], sources.attribnames[[i]][j]) } } sources.attributes[[i]] <- attributes sources.onemode[[i]] <- !is.bipartite(sources[[i]]) sources.directed[[i]] <- is.directed(sources[[i]]) # network attributes (= other matrices) temp <- list.network.attributes(sources[[i]]) temp <- temp[!temp %in% c("bipartite", "directed", "hyper", "loops", "mnext", "multiple", "n")] if (length(temp) > 0) { for (j in length(temp):1) { cl <- class(get.network.attribute(sources[[i]], temp[j])) if (!"network" %in% cl && !"matrix" %in% cl && !"Matrix" %in% cl) { temp <- temp[-j] } } } sources.matrixnames[[i]] <- temp matrices <- list() if (!is.null(sources.matrixnames[[i]]) && length(sources.matrixnames[[i]]) > 0) { for (j in 1:length(sources.matrixnames[[i]])) { matrices[[j]] <- get.network.attribute(sources[[i]], sources.matrixnames[[i]][j]) } } sources.matrices[[i]] <- matrices rm(temp) sources[[i]] <- as.matrix(sources[[i]]) # convert to matrix } else if (is.matrix(sources[[i]])) { sources.onemode[[i]] <- is.mat.onemode(sources[[i]]) sources.directed[[i]] <- is.mat.directed(sources[[i]]) } else { sources[[i]] <- as.matrix(sources[[i]], ncol = 1) } targets.types[[i]] <- class(targets[[i]]) if (is.network(targets[[i]])) { # save target attributes and other meta information in list targets.attribnames[[i]] <- list.vertex.attributes(targets[[i]]) attributes <- list() if (!is.null(targets.attribnames[[i]]) && length(targets.attribnames[[i]]) > 0) { for (j in 1:length(targets.attribnames[[i]])) { attributes[[j]] <- get.vertex.attribute(targets[[i]], targets.attribnames[[i]][j]) } } targets.attributes[[i]] <- attributes targets.onemode[[i]] <- !is.bipartite(targets[[i]]) targets.directed[[i]] <- is.directed(targets[[i]]) targets[[i]] <- as.matrix(targets[[i]]) # convert to matrix } else if (is.matrix(targets[[i]])) { targets.onemode[[i]] <- is.mat.onemode(targets[[i]]) targets.directed[[i]] <- is.mat.directed(targets[[i]]) } else { targets[[i]] <- as.matrix(targets[[i]], ncol = 1) } } # impute row or column labels if only one of them is present for (i in 1:length(sources)) { if (is.null(rownames(sources[[i]])) && !is.null(colnames(sources[[i]])) && nrow(sources[[i]]) == ncol(sources[[i]])) { rownames(sources[[i]]) <- colnames(sources[[i]]) } if (is.null(colnames(sources[[i]])) && !is.null(rownames(sources[[i]])) && nrow(sources[[i]]) == ncol(sources[[i]])) { colnames(sources[[i]]) <- rownames(sources[[i]]) } if (is.null(rownames(targets[[i]])) && !is.null(colnames(targets[[i]])) && nrow(targets[[i]]) == ncol(targets[[i]])) { rownames(targets[[i]]) <- colnames(targets[[i]]) } if (is.null(colnames(targets[[i]])) && !is.null(rownames(targets[[i]])) && nrow(targets[[i]]) == ncol(targets[[i]])) { colnames(targets[[i]]) <- rownames(targets[[i]]) } } # throw error if there are duplicate names (first sources, then targets) for (i in 1:length(sources)) { if ("matrix" %in% class(sources[[i]]) || "data.frame" %in% class(sources[[i]])) { # row names if (!is.null(rownames(sources[[i]]))) { test.actual <- nrow(sources[[i]]) test.unique <- length(unique(rownames(sources[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate source row names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate source row name.")) } } # column names if (!is.null(colnames(sources[[i]]))) { test.actual <- ncol(sources[[i]]) test.unique <- length(unique(colnames(sources[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate source column names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate source column name.")) } } } else { # vector names if (!is.null(names(sources[[i]]))) { test.actual <- length(sources[[i]]) test.unique <- length(unique(names(sources[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate source names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate source name.")) } } } } for (i in 1:length(targets)) { if ("matrix" %in% class(targets[[i]]) || "data.frame" %in% class(targets[[i]])) { # row names if (!is.null(rownames(targets[[i]]))) { test.actual <- nrow(targets[[i]]) test.unique <- length(unique(rownames(targets[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate target row names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate target row name.")) } } # column names if (!is.null(colnames(targets[[i]]))) { test.actual <- ncol(targets[[i]]) test.unique <- length(unique(colnames(targets[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate target column names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate target column name.")) } } } else { # vector names if (!is.null(names(targets[[i]]))) { test.actual <- length(targets[[i]]) test.unique <- length(unique(names(targets[[i]]))) dif <- test.actual - test.unique if (dif > 1) { stop(paste0("At t = ", i, ", there are ", dif, " duplicate target names.")) } else if (dif == 1) { stop(paste0("At t = ", i, ", there is ", dif, " duplicate target name.")) } } } } # add original labels to saved network attributes (= matrices) if necessary for (i in 1:length(sources)) { if ("network" %in% sources.types[[i]] && !is.null(sources.matrices[[i]]) && length(sources.matrices[[i]]) > 0) { for (j in 1:length(sources.matrices[[i]])) { if (nrow(as.matrix(sources.matrices[[i]][[j]])) != nrow(as.matrix(sources[[i]])) || ncol(as.matrix(sources.matrices[[i]][[j]])) != ncol(as.matrix(sources[[i]]))) { warning(paste("Network attribute", sources.matrixnames[[i]][j], "does not have the same dimensions as the source network at", "time step", i, ".")) } if (is.network(sources.matrices[[i]][[j]])) { if (sources.onemode[[i]] == TRUE) { sources.matrices[[i]][[j]] <- set.vertex.attribute( sources.matrices[[i]][[j]], "vertex.names", rownames(as.matrix(sources[[i]]))) } else { sources.matrices[[i]][[j]] <- set.vertex.attribute( sources.matrices[[i]][[j]], "vertex.names", c(rownames(as.matrix(sources[[i]])), colnames(as.matrix(sources[[i]])))) } } else { rownames(sources.matrices[[i]][[j]]) <- rownames(as.matrix(sources[[i]])) colnames(sources.matrices[[i]][[j]]) <- colnames(as.matrix(sources[[i]])) } } } } # go through sources and targets and do the actual adjustment for (i in 1:length(sources)) { if (!is.vector(sources[[i]]) && !is.matrix(sources[[i]]) && !is.network(sources[[i]])) { stop(paste("Source item", i, "is not a matrix, network, or vector.")) } if (!is.vector(targets[[i]]) && !is.matrix(targets[[i]]) && !is.network(targets[[i]])) { stop(paste("Target item", i, "is not a matrix, network, or vector.")) } # add add.row.labels <- character() add.col.labels <- character() if (add == TRUE) { # compile source and target row and column labels nr <- nrow(sources[[i]]) # save for later use source.row.labels <- rownames(sources[[i]]) if (!"matrix" %in% sources.types[[i]] && !"network" %in% sources.types[[i]]) { source.col.labels <- rownames(sources[[i]]) } else { source.col.labels <- colnames(sources[[i]]) } if ("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) { if (is.null(source.row.labels)) { stop(paste0("The source at t = ", i, " does not contain any row labels.")) } if (is.null(source.col.labels)) { stop(paste0("The source at t = ", i, " does not contain any column labels.")) } } target.row.labels <- rownames(targets[[i]]) if (!"matrix" %in% targets.types[[i]] && !"network" %in% targets.types[[i]]) { target.col.labels <- rownames(targets[[i]]) } else { target.col.labels <- colnames(targets[[i]]) } if (is.null(target.row.labels)) { stop(paste0("The target at t = ", i, " does not contain any row labels.")) } if ("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]]) { if (is.null(target.col.labels)) { stop(paste0("The target at t = ", i, " does not contain any column labels.")) } } add.row.indices <- which(!target.row.labels %in% source.row.labels) add.row.labels <- target.row.labels[add.row.indices] add.col.indices <- which(!target.col.labels %in% source.col.labels) add.col.labels <- target.col.labels[add.col.indices] # adjust rows if (length(add.row.indices) > 0) { for (j in 1:length(add.row.indices)) { insert <- rep(value, ncol(sources[[i]])) part1 <- sources[[i]][0:(add.row.indices[j] - 1), ] if (!is.matrix(part1)) { if ("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) { part1 <- matrix(part1, nrow = 1) } else { part1 <- matrix(part1, ncol = 1) } } rownames(part1) <- rownames(sources[[i]])[0:(add.row.indices[j] - 1)] if (add.row.indices[j] <= nrow(sources[[i]])) { part2 <- sources[[i]][add.row.indices[j]:nrow(sources[[i]]), ] } else { part2 <- matrix(ncol = ncol(sources[[i]]), nrow = 0) } if (!is.matrix(part2)) { part2 <- matrix(part2, nrow = 1) } if (nrow(part2) > 0) { rownames(part2) <- rownames(sources[[i]])[add.row.indices[j]: nrow(sources[[i]])] sources[[i]] <- rbind(part1, insert, part2) } else { sources[[i]] <- rbind(part1, insert) } rownames(sources[[i]])[add.row.indices[j]] <- add.row.labels[j] # adjust nodal attributes (in the one-mode case) if ("network" %in% sources.types[[i]] && sources.onemode[[i]] == TRUE) { for (k in 1:length(sources.attributes[[i]])) { at1 <- sources.attributes[[i]][[k]][0:(add.row.indices[j] - 1)] at2 <- sources.attributes[[i]][[k]][add.row.indices[j]:length( sources.attributes[[i]][[k]])] if (sources.attribnames[[i]][k] == "vertex.names") { sources.attributes[[i]][[k]] <- c(at1, add.row.labels[j], at2) } else if (sources.attribnames[[i]][k] == "na") { sources.attributes[[i]][[k]] <- c(at1, TRUE, at2) } else { sources.attributes[[i]][[k]] <- c(at1, value, at2) } } } } } # adjust columns if (length(add.col.indices) > 0 && ("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]])) { for (j in 1:length(add.col.indices)) { insert <- rep(value, nrow(sources[[i]])) part1 <- sources[[i]][, 0:(add.col.indices[j] - 1)] if (!is.matrix(part1)) { part1 <- matrix(part1, ncol = 1) } colnames(part1) <- colnames(sources[[i]])[0:(add.col.indices[j] - 1)] if (add.col.indices[j] <= ncol(sources[[i]])) { part2 <- sources[[i]][, add.col.indices[j]:ncol(sources[[i]])] } else { # if last column, add empty column as second part part2 <- matrix(nrow = nrow(sources[[i]]), ncol = 0) } if (!is.matrix(part2)) { part2 <- matrix(part2, ncol = 1) } if (ncol(part2) > 0) { colnames(part2) <- colnames(sources[[i]])[add.col.indices[j]: ncol(sources[[i]])] sources[[i]] <- cbind(part1, insert, part2) } else { sources[[i]] <- cbind(part1, insert) } colnames(sources[[i]])[add.col.indices[j]] <- add.col.labels[j] } } # adjust nodal attributes for two-mode networks if ("network" %in% sources.types[[i]] && sources.onemode[[i]] == FALSE) { add.col.indices <- sapply(add.col.indices, function(x) x + nr) combined.indices <- c(add.row.indices, add.col.indices) for (j in 1:length(sources.attributes[[i]])) { if (length(combined.indices) > 0) { for (k in 1:length(combined.indices)) { at1 <- sources.attributes[[i]][[j]][0:(combined.indices[k] - 1)] at2 <- sources.attributes[[i]][[j]][combined.indices[k]:length( sources.attributes[[i]][[j]])] if (sources.attribnames[[i]][j] == "vertex.names") { sources.attributes[[i]][[j]] <- c(at1, add.col.labels[j], at2) } else if (sources.attribnames[[i]][j] == "na") { sources.attributes[[i]][[j]] <- c(at1, TRUE, at2) } else { sources.attributes[[i]][[j]] <- c(at1, value, at2) } } } } } } removed.rows <- character() removed.columns <- character() if (remove == TRUE) { # compile source and target row and column labels nr <- nrow(sources[[i]]) # save for later use source.row.labels <- rownames(sources[[i]]) if (!("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]])) { source.col.labels <- rownames(sources[[i]]) } else { source.col.labels <- colnames(sources[[i]]) } if ("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) { if (nr == 0) { stop(paste0("The source at t = ", i, " has no rows.")) } if (is.null(source.row.labels)) { stop(paste0("The source at t = ", i, " does not contain any row labels.")) } if (is.null(source.col.labels)) { stop(paste0("The source at t = ", i, " does not contain any column labels.")) } } target.row.labels <- rownames(targets[[i]]) if (!("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]])) { target.col.labels <- rownames(targets[[i]]) } else { target.col.labels <- colnames(targets[[i]]) } if ("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]]) { if (is.null(target.row.labels)) { stop(paste0("The target at t = ", i, " does not contain any row labels.")) } if (is.null(target.col.labels)) { stop(paste0("The target at t = ", i, " does not contain any column labels.")) } } # remove source.row.labels <- rownames(sources[[i]]) source.col.labels <- colnames(sources[[i]]) target.row.labels <- rownames(targets[[i]]) target.col.labels <- colnames(targets[[i]]) keep.row.indices <- which(source.row.labels %in% target.row.labels) if (("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) && ("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]])) { keep.col.indices <- which(source.col.labels %in% target.col.labels) } else if (("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) && !("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]])) { # target is a vector -> keep all columns of source if not onemode if (sources.onemode[[i]] == TRUE) { # columns same as rows keep.col.indices <- keep.row.indices } else { keep.col.indices <- 1:ncol(sources[[i]]) } } else { keep.col.indices <- 1 } removed.rows <- which(!1:nrow(as.matrix(sources[[i]])) %in% keep.row.indices) removed.columns <- which(!1:ncol(as.matrix(sources[[i]])) %in% keep.col.indices) sources[[i]] <- as.matrix(sources[[i]][keep.row.indices, keep.col.indices]) if ("network" %in% sources.types[[i]]) { if (sources.onemode[[i]] == TRUE) { for (j in 1:length(sources.attributes[[i]])) { sources.attributes[[i]][[j]] <- sources.attributes[[i]][[j]][ keep.row.indices] } } else { keep.col.indices <- sapply(keep.col.indices, function(x) x + nr) combined.indices <- c(keep.row.indices, keep.col.indices) for (j in 1:length(sources.attributes[[i]])) { sources.attributes[[i]][[j]] <- sources.attributes[[i]][[j]][ combined.indices] } } } } # sort source (and attributes) according to row and column names of target # if (length(sources.attributes[[i]]) > 0) { # for (j in 1:length(sources.attributes[[i]])) { # if (!is.null(sources.attributes[[i]][[j]]) && # length(sources.attributes[[i]][[j]]) > 0) { # if (sources.onemode[[i]] == TRUE) { # names(sources.attributes[[i]][[j]]) <- rownames(sources[[i]]) # sources.attributes[[i]][[j]] <- # sources.attributes[[i]][[j]][rownames(sources[[i]])] # } else { # names(sources.attributes[[i]][[j]]) <- c(rownames(sources[[i]]), # rownames(sources[[i]])) # sources.attributes[[i]][[j]] <- # c(sources.attributes[[i]][[j]][rownames(sources[[i]])], # sources.attributes[[i]][[j]][colnames(sources[[i]])]) # } # } # } # } # if (("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) && ("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]]) && nrow(sources[[i]]) == nrow(targets[[i]]) && ncol(sources[[i]]) == ncol(targets[[i]])) { sources[[i]] <- sources[[i]][rownames(targets[[i]]), colnames(targets[[i]])] } else if (("matrix" %in% sources.types[[i]] || "network" %in% sources.types[[i]]) && !("matrix" %in% targets.types[[i]] || "network" %in% targets.types[[i]]) && nrow(sources[[i]]) == nrow(targets[[i]])) { sources[[i]] <- sources[[i]][rownames(targets[[i]]), rownames(targets[[i]])] } else if (length(sources[[i]]) == nrow(targets[[i]])) { # source is a vector, irrespective of the target sources[[i]] <- sources[[i]][rownames(targets[[i]]), ] } else if (add == FALSE && (nrow(sources[[i]]) < nrow(targets[[i]]) || any(rownames(sources[[i]]) != rownames(targets[[i]])))) { } # convert back into network if ("network" %in% sources.types[[i]]) { sources[[i]] <- network(sources[[i]], directed = sources.directed[[i]], bipartite = !sources.onemode[[i]]) for (j in 1:length(sources.attribnames[[i]])) { sources[[i]] <- set.vertex.attribute(sources[[i]], sources.attribnames[[i]][j], sources.attributes[[i]][[j]]) } } # convert vectors back from one-column matrices to vectors if (!"matrix" %in% sources.types[[i]] && !"network" %in% sources.types[[i]] && is.matrix(sources[[i]]) && ncol(sources[[i]]) == 1) { sources[[i]] <- sources[[i]][, 1] } # return added and removed labels instead of actual objects if (returnlabels == TRUE) { sources[[i]] <- list() sources[[i]]$removed.row <- removed.rows sources[[i]]$removed.col <- removed.columns sources[[i]]$added.row <- add.row.labels sources[[i]]$added.col <- add.col.labels } } # adjust network attributes (= matrices) recursively and add back in for (i in 1:length(sources)) { if ("network" %in% sources.types[[i]] && !is.null(sources.matrixnames[[i]]) && length(sources.matrixnames[[i]]) > 0) { for (j in 1:length(sources.matrixnames[[i]])) { mat <- adjust(source = sources.matrices[[i]][[j]], target = sources[[i]], add = add, remove = remove, value = value) set.network.attribute(sources[[i]], sources.matrixnames[[i]][j], mat) } } } if ("list" %in% sources.initialtype) { return(sources) } else { return(sources[[1]]) } }
/scratch/gouwar.j/cran-all/cranData/xergm.common/R/preprocess.R
# generics for extracting the formula from an estimation object setGeneric("getformula", function(x) standardGeneric("getformula"), package = "xergm.common") # generic interpretation function setGeneric("interpret", function(object, ...) standardGeneric("interpret"), package = "xergm.common") # generics for goodness-of-fit assessment setGeneric("gof", function(object, ...) standardGeneric("gof"), package = "xergm.common") # generic checkdegeneracy function setGeneric("checkdegeneracy", function(object, ...) standardGeneric("checkdegeneracy"), package = "xergm.common")
/scratch/gouwar.j/cran-all/cranData/xergm.common/R/xergm.common.R
createXES<- function(file, traces, events, classifiers = NULL, logattributes = NULL, caseid_field = NULL, case_classifier){ # File: The location of the output file # Traces: a dataframe where each row represents a trace and each column represents # a trace attribute. # Events: a dataframe where each row represents an event and each column represents # an event attribute. (This dataframe also has a column which refers to the # traceid) # Classifiers: A list of classifiers. The key represents the name of the classifier # and the value contains a string vector of the respective event attributes # Logatrributes: A list of log atributes. The key represents the attribute name and the # value represents the attribute value. The attribute type is derived from # the attribute value # Caseid_field: The columnname which acts as traceid in the events dataframe. # DEFAULT: The first column of the events dataframe is used as traceID. ##################HELPER FUNCTIONS############################ add <- function(text){ xml_i <<- xml_i + 1 xml[xml_i] <<- text #xml #cat(text, file, append=TRUE) } addAttribute <- function(datatype, key, value){ if(is.null(value)){ return() } if(datatype == "date"){ value = strftime(value,format="%Y-%m-%dT%H:%M:%S.000+00:00") } add(paste0('<',datatype,' key="',key,'" value="',value,'"/>')) } addExtensions <- function(attrs){ #add concept extension if any of the event attributes start with the "concept:" prefix if(any(grepl("^concept:", names(attrs)))){ add('<extension name="Concept" prefix="concept" uri="http://www.xes-standard.org/concept.xesext" />') } #add time extension if any of the event attributes start with the "time:" prefix if(any(grepl("^time:", names(attrs)))){ add('<extension name="Time" prefix="concept" uri="http://www.xes-standard.org/time.xesext" />') } } addGlobals <- function(data, attrs, scope){ temp <- sapply(data[,names(attrs)],function(x){all(!is.na(x))}) globals <- names(temp[temp==TRUE]) add(paste0('<global scope="',scope,'">')) for(key in globals){ datatype <- attrs[key] addAttribute(datatype, key, defaultvalues[[datatype]]) } add('</global>') } addClassifiers <- function(){ if(is.null(classifiers)){ return() } for(name in names(classifiers)){ add(paste0('<classifier name="',name,'" keys="', paste(classifiers[[name]], collapse=" "),'"/>')) } } addLogAttributes <- function(){ if(is.null(logattributes)){ return() } for(name in names(logattributes)){ value = logattributes[[name]] datatype = attribute_types[class(value)[1]] if(datatype == "date"){ value = strftime(value,format="%Y-%m-%dT%H:%M:%S.000+00:00") } add(paste0('<', datatype,' key="',name,'" value="', value,'"/>')) } } addTraces <- function(){ # apply(traces, 1, addTrace) total = dim(traces)[1] pb <- txtProgressBar(min=0, max = total, style = 3) for(i in 1:total){ trace <- traces[i,,drop=FALSE] addTrace(trace) setTxtProgressBar(pb, i) } } addTrace <- function(trace){ add('<trace>') for(name in names(trace_attrs)){ addAttribute(trace_attrs[name], name, trace[name]) } trace_id <- as.character(trace[[trace_caseid_field]]) addEvents(events_per_trace[[trace_id]]) add('</trace>') } addEvents <- function(trace_events){ apply(trace_events, 1, addEvent) } addEvent <- function(event){ add('<event>') for(name in names(event_attrs)){ addAttribute(event_attrs[name], name, event[name]) } add('</event>') } detectAttrType <- function(key, data){ detected = class(data[[key]])[1] attribute_types[[detected]] } get_attr_info<- function(data){ sapply(colnames(data), detectAttrType, data) } ############PRELIMINARIES################## defaultvalues <- list("string"="default", "int"="0", "date"="1970-01-01T00:00:00.000+00:00", "boolean" = "false") attribute_types <- list("factor"="string", "POSIXct"="date", "integer"="int", "ordered"="string", "character"="string", "logical" = "boolean") trace_attrs <- get_attr_info(traces) if(is.null(caseid_field)){ event_attrs <- get_attr_info(events[,-1]) } else{ event_attrs <- get_attr_info(events[,names(events)!=caseid_field]) } if(is.null(caseid_field)){ events_caseid_field <- colnames(events)[1] } else { #adjustment Gert events_caseid_field <- caseid_field } events_per_trace <- split(events,events[events_caseid_field]) if("concept:name" %in% names(trace_attrs)){ trace_caseid_field <- "concept:name" } else if(events_caseid_field %in% names(trace_attrs)){ trace_caseid_field <- events_caseid_field } else{ trace_caseid_field <- colnames(traces)[1] } n_event_attrs = length(event_attrs) n_trace_attrs = length(trace_attrs) n_classifiers = length(classifiers) n_logattributes = length(logattributes) n_traces = dim(traces)[1] n_events = dim(events)[1] maxsize = 4+ 3*n_event_attrs + 3*n_trace_attrs + n_classifiers + n_logattributes + n_traces*(2+n_trace_attrs)+n_events*(2+n_event_attrs) xml <- rep(NA,maxsize) xml_i = 1 ############GENERATE XML################### #fileConn <- file(file, open="at") add('<?xml version="1.0"?>') #cat('<?xml version="1.0"?>', file=file) add('<log xmlns="http://www.xes-standard.org/" xes.version="2.0">') addExtensions(c(trace_attrs, event_attrs)) addGlobals(traces, trace_attrs, "trace") addGlobals(events, event_attrs, "event") addClassifiers() addLogAttributes() addTraces() add('</log>') xml <- na.omit(xml) xml <- str_replace_all(xml, case_classifier, "concept:name") writeLines(xml, file) #close(fileConn) }
/scratch/gouwar.j/cran-all/cranData/xesreadR/R/XES.r
#' @title Case Attributes from Xes-file #' @description Extracts case attributes from a xes-file. #' @param xesfile Reference to a .xes file, conforming to the xes-standard. #' @seealso \url{http://www.xes-standard.org/} #' @export case_attributes_from_xes case_attributes_from_xes <- function(xesfile = file.choose()) { warning("Function deprecated. Please use read_xes_cases") return(read_xes_cases(xesfile)) }
/scratch/gouwar.j/cran-all/cranData/xesreadR/R/case_attributes_from_xes.R