{"id":13400724,"url":"https://github.com/dirkschumacher/armacmp","last_synced_at":"2025-07-13T05:40:03.385Z","repository":{"id":145906303,"uuid":"199329081","full_name":"dirkschumacher/armacmp","owner":"dirkschumacher","description":"🚀 Automatically compile linear algebra R code to C++ with Armadillo","archived":false,"fork":false,"pushed_at":"2021-10-20T14:05:47.000Z","size":306,"stargazers_count":99,"open_issues_count":18,"forks_count":5,"subscribers_count":3,"default_branch":"master","last_synced_at":"2025-05-12T02:07:33.123Z","etag":null,"topics":["armadillo-library","c-plus-plus","experimental","linear-algebra","optimization","r"],"latest_commit_sha":null,"homepage":"https://dirkschumacher.github.io/armacmp/","language":"R","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/dirkschumacher.png","metadata":{"files":{"readme":"README.Rmd","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2019-07-28T19:33:01.000Z","updated_at":"2025-01-27T15:30:38.000Z","dependencies_parsed_at":"2024-01-18T11:03:47.357Z","dependency_job_id":"172a9b72-97aa-40bd-8ff5-0c899dd2dd23","html_url":"https://github.com/dirkschumacher/armacmp","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkschumacher%2Farmacmp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkschumacher%2Farmacmp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkschumacher%2Farmacmp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/dirkschumacher%2Farmacmp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/dirkschumacher","download_url":"https://codeload.github.com/dirkschumacher/armacmp/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254323292,"owners_count":22051757,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["armadillo-library","c-plus-plus","experimental","linear-algebra","optimization","r"],"created_at":"2024-07-30T19:00:54.935Z","updated_at":"2025-05-15T10:33:22.419Z","avatar_url":"https://github.com/dirkschumacher.png","language":"R","funding_links":[],"categories":["R"],"sub_categories":[],"readme":"---\noutput: github_document\neditor_options: \n  chunk_output_type: console\n---\n\n\u003c!-- README.md is generated from README.Rmd. Please edit that file --\u003e\n\n```{r, include = FALSE}\nknitr::opts_chunk$set(\n  collapse = TRUE,\n  comment = \"#\u003e\",\n  fig.path = \"man/figures/README-\",\n  out.width = \"100%\"\n)\n```\n# armacmp\n\n\u003c!-- badges: start --\u003e\n[![Lifecycle: experimental](https://img.shields.io/badge/lifecycle-experimental-orange.svg)](https://www.tidyverse.org/lifecycle/#experimental)\n[![R-CMD-check](https://github.com/dirkschumacher/armacmp/workflows/R-CMD-check/badge.svg)](https://github.com/dirkschumacher/armacmp/actions)\n[![Codecov test coverage](https://codecov.io/gh/dirkschumacher/armacmp/branch/master/graph/badge.svg)](https://app.codecov.io/gh/dirkschumacher/armacmp?branch=master)\n\u003c!-- badges: end --\u003e\n\nThe goal of `armacmp` is to create a DSL to formulate linear algebra code in R that is compiled to C++ using the Armadillo Template Library. It also offers an mathematical optimization that uses `RcppEnsmallen` to optimize functions in C++.\n\nThe scope of the package is linear algebra and Armadillo. It is not meant to evolve into a general purpose R to C++ transpiler.\n\nIt has three main functions:\n\n* `compile` compiles an R function to C++ and makes that function again avaliable in your R session.\n* `translate` translates an R function to C++ and returns the code as text.\n* `compile_optimization_problem` uses `RcppEnsmallen` and the functions above to compile continuous mathematical optimizations problems to C++.\n\nThis is currently an *experimental prototype* with most certainly bugs or unexpected behaviour. However I would be happy for any type of feedback, alpha testers, feature requests and potential use cases.\n\nPotential use cases:\n\n* Speed up your code :)\n* Quickly estimate `Rcpp` speedup gain for linear algebra code\n* Learn how R linear algebra code can be expressed in C++ using `translate` and use the code as a starting point for further development.\n* Mathematical optimization with `optimize`\n* ...\n\n\n## Installation\n\n``` r\nremotes::install_github(\"dirkschumacher/armacmp\")\n```\n\n## Caveats and limitations\n\n* *speed*: R is already really fast when it comes to linear algebra operations. So simply compiling your code to C++ might not give you a *significant and relevant* speed boost. The best way to check is to measure it yourself and see for your specific use-case, if compiling your code to C++ justifies the additional complexity.\n* *NAs*: there is currently no NA handling. In fact everything is assumed to be double (if you use matrices/vectors).\n* *numerical stability*: Note that your C++ code might produce different results in certain situations. Always validate before you use it for important applications.\n\n## Example\n\nYou can compile R like code to C++. Not all R functions are supported.\n\n```{r}\nlibrary(armacmp)\n```\n\nTakes a matrix and returns its transpose.\n\n```{r}\ntrans \u003c- compile(function(X) {\n  return(t(X))\n})\ntrans(matrix(1:10))\n```\n\nOr a slightly larger example using QR decomposition\n\n```{r, echo=TRUE, eval=TRUE}\n# from Arnold, T., Kane, M., \u0026 Lewis, B. W. (2019). A Computational Approach to Statistical Learning. CRC Press.\nlm_cpp \u003c- compile(function(X, y = type_colvec()) {\n  qr_res \u003c- qr(X)\n  qty \u003c- t(qr.Q(qr_res)) %*% y\n  beta_hat \u003c- backsolve(qr.R(qr_res), qty)\n  return(beta_hat, type = type_colvec())\n})\n\n# example from the R docs of lm.fit\nn \u003c- 70000 ; p \u003c- 20\nX \u003c- matrix(rnorm(n * p), n, p) \ny \u003c- rnorm(n)\nall.equal(\n  as.numeric(coef(lm.fit(X, y))),\n  as.numeric(lm_cpp(X, y))\n)\n```\n\n## API\n\n`armacmp` always compiles functions. Every function needs to have a `return` statement with an optional type argument.\n\n```{r, eval=FALSE}\nmy_fun \u003c- compile(function(X, y = type_colvec())) {\n  return(X %*% y, type = type_colvec())\n}\n```\n\nA lot of linear algebra functions/operators are defined as well some control flow (for loops and if/else).\nPlease take a look at the [function reference article](https://dirkschumacher.github.io/armacmp/articles/function-reference.html) for more details what can be expressed.\n\n### Optimization of arbitrary and differentiable functions using `ensmallen`\n\nThe package now also supports optimization of functions using `RcppEnsmallen`. Find out more at [ensmallen.org](https://ensmallen.org/).\n\nAll code is compiled to C++. During the optimization there is no context switch back to R.\n\n#### Arbitrary function\n\nHere we minimize `2 * norm(x)^2` using simulated annealing.\n\n```{r}\n# taken from the docs of ensmallen.org\noptimize \u003c- compile_optimization_problem(\n  data = list(),\n  evaluate = function(x) {\n    return(2 * norm(x)^2)\n  },\n  optimizer = optimizer_SA()\n)\n\n# should be roughly 0\noptimize(matrix(c(1, -1, 1), ncol = 1))\n```\n\nOptimizers:\n\n* Simulated Annealing through `optimizer_SA`\n* Conventional Neural Evolution `optimizer_CNE`\n* ...\n\n#### Differentiable functions\n\nHere solve a linear regression problem using L-BFGS.\n\n```{r}\noptimize_lbfgs \u003c- compile_optimization_problem(\n  data = list(design_matrix = type_matrix(), response = type_colvec()),\n  evaluate = function(beta) {\n    return(norm(response - design_matrix %*% beta)^2)\n  },\n  gradient = function(beta) {\n    return(-2 %*% t(design_matrix) %*% (response - design_matrix %*% beta))\n  },\n  optimizer = optimizer_L_BFGS()\n)\n\n# this example is taken from the RcppEnsmallen package\n# https://github.com/coatless/rcppensmallen/blob/master/src/example-linear-regression-lbfgs.cpp\nn \u003c- 1e6\nbeta \u003c- c(-2, 1.5, 3, 8.2, 6.6)\np \u003c- length(beta)\nX \u003c- cbind(1, matrix(rnorm(n), ncol = p - 1))\ny \u003c- X %*% beta + rnorm(n / (p - 1))\n\n# Run optimization with lbfgs fullly in C++\noptimize_lbfgs(\n  design_matrix = X,\n  response = y,\n  beta = matrix(runif(p), ncol = 1)\n)\n```\n\nOptimizers:\n\n* L-BFGS through `optimizer_L_BFGS`\n* Gradient Descent through `optimizer_GradientDescent`\n* ...\n\n### When does `armacmp` improve performance?\n\nIt really depends on the use-case and your code. In general Armadillo can combine linear algebra operations. For example the addition of 4 matrices `A + B + C + D` can be done in a single for loop. Armadillo can detect that and generates efficient code. \n\nSo whenever you combine many different operations, `armacmp` _might_ be helpful in speeding things up.\n\nWe gather some examples on the wiki to further explore if compiling linear algebra code to C++ actually makes sense for pure speed reasons.\n\n### Related projects\n\n* [nCompiler](https://github.com/nimble-dev/nCompiler) - Code-generate C++ from R. Inspired the approach to compile R functions directly instead of just a code block as in the initial version.\n\n### Contribute\n\n`armacmp` is experimental and has a volatile codebase. The best way to contribute is to write issues/report bugs/propose features and test the package with your specific use-case.\n\n### Code of conduct\n\nPlease note that the 'armacmp' project is released with a\n[Contributor Code of Conduct](CODE_OF_CONDUCT.md).\nBy contributing to this project, you agree to abide by its terms.\n\n### References\n\n* Conrad Sanderson and Ryan Curtin. Armadillo: a template-based C++ library for linear algebra. Journal of Open Source Software, Vol. 1, pp. 26, 2016.\n* S. Bhardwaj, R. Curtin, M. Edel, Y. Mentekidis, C. Sanderson. ensmallen: a flexible C++ library for efficient function optimization. Workshop on Systems for ML and Open Source Software at NIPS 2018.\n* Dirk Eddelbuettel, Conrad Sanderson (2014). RcppArmadillo: Accelerating R\n  with high-performance C++ linear algebra. Computational Statistics and Data\n  Analysis, Volume 71, March 2014, pages 1054-1063. URL\n  http://dx.doi.org/10.1016/j.csda.2013.02.005\n* Dirk Eddelbuettel and Romain Francois (2011). Rcpp: Seamless R and C++\n  Integration. Journal of Statistical Software, 40(8), 1-18. URL\n  https://www.jstatsoft.org/v40/i08/.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdirkschumacher%2Farmacmp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdirkschumacher%2Farmacmp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdirkschumacher%2Farmacmp/lists"}