Giter Club home page Giter Club logo

konrad1991 / ast2ast Goto Github PK

View Code? Open in Web Editor NEW
34.0 34.0 3.0 98.03 MB

Translates an R function into a to a C++ function which is callable from within R. The typical use case intended by 'ast2ast' are functions describing ode-systems.

Home Page: https://konrad1991.github.io/ast2ast/

License: GNU General Public License v2.0

R 40.74% C++ 58.44% C 0.11% Vim Script 0.30% Lua 0.25% Shell 0.12% Dockerfile 0.05%
abstract-syntax-tree c c-plus-plus expression-template matrix r rcpp transpiler vector

ast2ast's People

Contributors

fangzhou-xie avatar konrad1991 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

ast2ast's Issues

subsetting

[x] define structs SubsetNumeric, SubsetInteger and SubsetLogical
[ ] create getter and setter for those structs
[ ] identify in R when variable is subsetted
[ ] first create symbol table
[ ] traverse again and find subsetted variables.
Store corresponding subsets for each expression
- the variable which is subsetted
- the expression defining the indices of the subset
* possible expressions to define indices:
* int, double, Numeric, Integer, Logical,
SubsetNumeric, SubsetInteger and SubsetLogical
but not a calculation
[ ] define SubsetManager
[ ] pass SubsetManager to EXPRXY
[ ] throw error in R if user tries to subset scalar

Derivatives

AIM is to calculate the derivatives based on a type.

Proof of principle is done

Now a detailed plan has to be done

Performance of Leibniz formula

Fantastic idea for package! Recently there was an interesting benchmark comparing different programming languages for calculating pi using Leibniz formula (https://github.com/niklas-heer/speed-comparison). I was curious what the benefits would be of using {ast2ast} and here are the results:

leibniz = function(rounds) {
  x = 1.0
  pi = 1.0
  for (i in 2:(rounds + 2)) {
    x = x * -1
    pi = pi + (x / (2 * i - 1))
  }
  pi = pi * 4
  return(pi)
}

leibniz_vectorized = function(rounds) {
  pi = sum(4 / seq.int(-2 * rounds + 1, 2 * rounds, by = 4))
  return(pi)
}

leibniz_cpp = ast2ast::translate(leibniz)

rounds = 10000000
system.time(leibniz(rounds)) #> 1.171
system.time(leibniz_vectorized(rounds)) #> 0.235
system.time(leibniz_cpp(rounds)) #> 2.323

So it looks like the computation is slower than in R. I also tried to translate the leibniz_vectorized(), but sum() and seq.int() are not implemented.

resize c

create resize function which replaces:
if (s > vm->numerics[var_left]->size) {
alloc_numeric(var_left, s, vm);
}

detect correct resize fct in R

Add missing functions

abs
Some cases of at
atan2, other trigo functions
while loop
Maybe repeat?
Missing distri functions
Etc

Define all functions as functors

This is needed for derivative. So the functions are baked on the type. As the functor instances have the r value trait this can be used during calculating derivatives without creating extra variables for these functions

Use basetype everywhere

If all functions can handle int, double and Vec one can think about enable different basetypes. Short, int, long long, float, double and long double
One could also think about type complex

Derivative calculation

The independent variable is properly not needed anymore for the calculation of the derivative function

R value trait

Add a r value trait for functions such as coca or vector. Than if such a variable is assigned to a sexp the original pointer is deleted. And the pointer of the r value variable is used instead

Remove const

Remove const references. Instead define two functions for r values and another for l values

support for lambda functions

Hi, it seems to me that lambda functions (and single line functions without curly brackets) are not supported by ast2ast::translate().

f1 <- function(x) sin(x)
f2 <- function(x) {sin(x)}

ast2ast::translate(f1)
#> Error in `purrr::map_if()`:
#> ! `.x` must be a vector, not a symbol.
#> Backtrace:
#>      ▆
#>   1. └─ast2ast::translate(f1)
#>   2.   └─ast2ast:::compiler_a2a(...)
#>   3.     └─a$build_own_SEXP(verbose, reference = reference)
#>   4.       └─self$ast2call()
#>   5.         └─self$get_calls(self$ast[[i]])
#>   6.           └─purrr::map_if(code, is.list, self$get_calls)
#>   7.             └─purrr:::where_if(.x, .p)
#>   8.               └─purrr:::map_(.x, .p, ..., .type = "logical", .purrr_error_call = .purrr_error_call)
#>   9.                 └─vctrs::vec_assert(.x, arg = ".x", call = .purrr_error_call)
#>  10.                   └─vctrs:::stop_scalar_type(x, arg, call = call)
#>  11.                     └─vctrs:::stop_vctrs(...)
#>  12.                       └─rlang::abort(message, class = c(class, "vctrs_error"), ..., call = call)
ast2ast::translate(f2)
#> function (xSEXP) 
#> .Call(<pointer: 0x7fee734d82a0>, xSEXP)
#> <environment: 0x5621d09c6428>
ast2ast::translate(function(x) {sin(x)})
#> g++ -std=gnu++17 -I"/usr/share/R/include" -DNDEBUG -I../inst/include -fopenmp  -I"/home/fangzhou/R/x86_64-pc-linux-gnu-library/4.3/Rcpp/include" -I"/home/fangzhou/R/x86_64-pc-linux-gnu-library/4.3/ast2ast/include" -I"/home/fangzhou/R/x86_64-pc-linux-gnu-library/4.3/RcppArmadillo/include" -I"/tmp/Rtmprk7h9f/sourceCpp-x86_64-pc-linux-gnu-1.0.10"    -DRFCT -fpic  -g -O2 -ffile-prefix-map=/build/r-base-sYMOIw/r-base-4.3.1=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2  -c file46304a55efdd.cpp -o file46304a55efdd.o
#> [1] "Sorry compilation failed!"
#> NULL

Created on 2023-07-08 with reprex v2.0.2

From this example, only the second translation works. The first (without bracket) and the third (lambda function) failed.

I also took a quick look at the source code of translate() function. Maybe something like this will be a quick fix (before line 97. This will probably only fix for the bracket issue, and perhaps not for the lambda function.)?

if (deparse(body(f))[[1]] != "{") {
  body(f) <- parse(text = paste0("{", deparse(body(f)), "}"))[[1]]
}

Identify different assignment cases

On left side: bool,int,double, Logical, Integer or Numeric

On right side: bool,int,double, Logical, Integer,Numeric or an expression.

  • Ignore self assignment e.g. a = a. Throw an error in R.
  • Define c code for a scalar on left side:
    vm -> scalarNum[idx] = ...
  • define c code for a Vector on left side:
    vm -> numerics[vecIdx] -> data[i] = ...
  • Check whether the variable to which the result get assigned is found on the rhs. In case it is found use the temp vectors I.e. the c code from the last bullet point. Otherwise define c code where the result of an expression is directly stored in the variable at lhs.
  • Throw error in R if expression is on left side.
  • Deduce types of expressions on rhs. Check each type of the variables directly involved in the calculation of the result. Thus, ignore for example variables passed to cmr or subsetting. Take the most flexible type which is found. Double > int> bool. If at least one double is found than the type of the expression is double. If no double but at least one integer is found than the type is integer. If only boils are found than the type is bool
  • Check types of lhs and rhs. Add required casts. Each element of the rhs directly involved in calculating the result which has a different type than the lhs has to be casted. Thus,for the term a = b*c[d] where a is of type Numeric, b is of type Integer, c is of type Numeric and d is of type Integer, b has to be casted but not d.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.