DEV Community

Konrad
Konrad

Posted on

ast2ast v0.5: Translate R Functions to Optimized C++: Now with automatic differentiation!

Why ast2ast?

Want C++ speed without writing C++? ast2ast does it for you:

a <- runif (100000)
b <- runif (100)
convolve <- function(a, b) {
  ab <- numeric(length(a) + length(b) - 1)
  for (i in 1L:length(a)) {
    for (j in 1L:length(b)) {
      ab[i+j-1] <- ab[i+j-1] + a[i] * b[j]
    }
  }
  return(ab)
}
convolve_cpp <- ast2ast::translate(convolve)
convolve(a, b) # Call R function
convolve_cpp(a, b) # Call the C++ function
Enter fullscreen mode Exit fullscreen mode

Speedup for the convolve function by using ast2ast

Derivatives

In the most recent version, it is possible to calculate derivatives using automatic differentiation.

f <- function(y, x) {
  y[[1L]] <- x[[1L]] * x[[2L]]
  y[[2L]] <- x[[1L]] + x[[2L]]*x[[2L]]
  jac <- deriv(y, x)
  return(jac)
}
fcpp_reverse <- ast2ast::translate(f, derivative = "reverse")
y <- c(0, 0)
x <- c(2, 3)
fcpp_reverse(y, x)
Enter fullscreen mode Exit fullscreen mode

How can you help:

I’d love your feedback after testing ast2ast.
You can find the project at https://github.com/Konrad1991/ast2ast. Feel free to open an issue if you encounter any bugs or have suggestions for improvement.

Top comments (0)