SlideShare une entreprise Scribd logo
1  sur  31
Télécharger pour lire hors ligne
Rcpp11
Romain François
romain@r-enthusiasts.com @romain_francois
R
Rcpp
Rcpp11
• C++ = C++11
• Smaller code base (than Rcpp)
• Header only
Rcpp11
#include <Rcpp.h>
!
// [[Rcpp::export]]
int foo(){
return 2 ;
}
Rcpp
Rcpp11
0 1 2 3 4
Less code -> faster compiles
!
Interface simplification
NumericVector constructors
Vector() {
Vector( const Vector& other){
Vector( SEXP x ) {
!
Vector( const GenericProxy<Proxy>& proxy ){
explicit Vector( const no_init& obj) {
Vector( const int& size, const stored_type& u ) {
Vector( const std::string& st ){
Vector( const char* st ) {
Vector( const int& siz, stored_type (*gen)(void) ) {
Vector( const int& size ) {
Vector( const Dimension& dims) {
Vector( const Dimension& dims, const U& u) {
Vector( const VectorBase<RTYPE,NA,VEC>& other ) {
Vector( const int& size, const U& u) {
Vector( const sugar::SingleLogicalResult<NA,T>& obj ) {
Vector( const int& siz, stored_type (*gen)(U1), const U1& u1) {
Vector( const int& siz, stored_type (*gen)(U1,U2), const U1& u1, const U2& u2) {
Vector( const int& siz, stored_type (*gen)(U1,U2,U3), const U1& u1, const U2& u2, const U3& u3) {
Vector( InputIterator first, InputIterator last){
Vector( InputIterator first, InputIterator last, int n) {
Vector( InputIterator first, InputIterator last, Func func) {
Vector( InputIterator first, InputIterator last, Func func, int n){
Vector( std::initializer_list<init_type> list ) {
23 constructors in Rcpp
NumericVector constructors
11 constructors in Rcpp
Vector(){
Vector( const Vector& other){
Vector( Vector&& other){
!
explicit Vector(int n) {
explicit Vector(R_xlen_t n) {
!
Vector( R_xlen_t n, value_type x ) {
Vector( std::initializer_list<value_type> list ){
Vector( std::initializer_list<traits::named_object<value_type>> list ){
!
Vector( const SugarVectorExpression<eT, Expr>& other ) {
Vector( const LazyVector<RT,Expr>& other ) {
Vector( const GenericProxy<Proxy>& proxy ){
NumericVector constructors
Vector( const int& siz, stored_type (*gen)(U1), const U1& u1) -> replicate
double fun( int power ){
return pow(2.0, power) ;
}
!
// Rcpp
NumericVector x(10, fun, 10.0) ;
// Rcpp11
NumericVector x = replicate(10, fun, 10.0) ;
NumericVector constructors
std::vector<double> v = /* ... */ ;
!
// Rcpp
NumericVector x(v.begin(), v.end()) ;
// Rcpp11
NumericVector x = import(begin(v), end(v)) ;
NumericVector x = import(v) ;
Vector( InputIterator first, InputIterator last) -> import
Some examples
NumericVector ctors
// C++ uniform initialization
NumericVector x = {1.0, 2.0, 3.0} ;
!
// init with given size
NumericVector y( 2 ) ; // data is not initialized
NumericVector y( 2, 3.0 ) ; // initialize all to 3.0
!
// fuse several vectors (similar to c in R)
NumericVector z = fuse(x, y) ;
NumericVector z = fuse(x, y, 3.0) ;
create
// old school NumericVector::create (Rcpp style).
NumericVector x = NumericVector::create(1.0, 2.0, 3.0) ;
NumericVector x = NumericVector::create(
_["a"] = 1.0, _["b"] = 2.0, _["c"] = 3.0
) ;
!
!
// create as a free function. Rcpp11 style
NumericVector x = create(1.0, 2.0, 3.0) ;
NumericVector x = create(
_["a"] = 1.0, _["b"] = 2.0, _["c"] = 3.0
) ;
sapply + lambda
sapply + lambda
#include <Rcpp11>
!
// [[export]]
NumericVector foo( NumericVector x ){
return sapply(x, [](double d){
return exp(d * 2) ;
});
}
x <- 1:3
sapply( x, function(d){
exp(d*2) ;
})
Rcpp11 release cycle
• Available from CRAN:
!
• Evolves quickly. Get it from github
!
• Next Release: 3.1.1 (same time as R 3.1.1)
> install.packages( "Rcpp11" )
> install_github( "Rcpp11/Rcpp11" )
attributes companion package
• Standalone impl of Rcpp attributes
[[Rcpp::export]], sourceCpp, compileAttributes
!
• Only available from github:
> install_github( "Rcpp11/attributes" )
Use Rcpp11 in your package
• Write your .cpp files
#include <Rcpp11>
!
// [[export]]
void foo( … ) { … } // your code
SystemRequirements: C++11
LinkingTo: Rcpp11
library(attributes)
compileAttributes( "mypkg" )
• Express dep on C++11 and Rcpp11 headers
• Generate the boiler plate
Header only
• No runtime dependency
!
• Snapshot the code base
!
• Better control for package authors
error handling
C level try/catch
Internal C level try catch
• Problem: evaluate an R call that might error (long jump)
!
• Rcpp solution: wrap the call in R's tryCatch
!
• Rcpp11 hack solution:
• Leverage R_ToplevelExec / mess with the context
• New problem. R_ToplevelExec expectations
Internal C level try catch
SEXP res ;
try_catch( [&](){
// some unsafe C code that might JUMP
res = Rf_eval(expr, env) ;
}) ;
return res ;
Internal C level try catch
/* R_ToplevelExec - call fun(data) within a top level context to
insure that this functin cannot be left by a LONGJMP. R errors in
the call to fun will result in a jump to top level. The return
value is TRUE if fun returns normally, FALSE if it results in a
jump to top level. */
!
Rboolean R_ToplevelExec(void (*fun)(void *), void *data)
pointer to a function
taking data as void*
Data
Internal C level try catch
template <typename Fun>
void try_catch( Fun fun ) {
typedef std::pair<Fun*, SEXP&> Pair ;
!
SEXP return_value ;
!
Pair pair = std::make_pair(&fun, std::ref(return_value)) ;
!
bool ok = R_ToplevelExec( &internal::try_catch_helper<Fun>, &pair ) ;
!
if( !ok ){
!
SEXP condition = VECTOR_ELT(return_value,0) ;
!
if( Rf_isNull(condition) ){
stop("eval error : %s", R_curErrorBuf()) ;
} else {
Shield<SEXP> msg = Rf_eval( Rf_lang2( Rf_install( "conditionMessage"), condition ), R_GlobalEnv )
;
stop("eval error : %s", CHAR(STRING_ELT(msg, 0)) ) ;
}
}
}
The function
templated by the real
function to call
Data, also
parameterise by Fun
Internal C level try catch
template <typename Fun>
void try_catch_helper( void* data ){
typedef std::pair<Fun*, SEXP&> Pair ;
Pair* pair = reinterpret_cast<Pair*>(data) ;
RCNTXT* ctx = (RCNTXT*) R_GlobalContext ;
ctx->callflag = CTXT_FUNCTION ;
// first call to .addCondHands to add a handler
SEXP args = pairlist(
Rf_mkString("error"),
Rf_allocVector(VECSXP,1),
ctx->cloenv,
ctx->cloenv,
R_FalseValue
) ;
SEXP symb = Rf_install(".addCondHands") ;
SEXP ifun = INTERNAL( symb ) ;
PRIMFUN(ifun)(symb, ifun, args, R_GlobalEnv );
// call it a second time to get the current R_HandlerStack
CAR(args) = R_NilValue ;
SEXP value = PRIMFUN(ifun)(symb, ifun, args, R_GlobalEnv ) ;
pair->second = VECTOR_ELT(CAR(value),4) ;
Fun& fun = *reinterpret_cast<Fun*>(pair->first) ;
fun() ;
}
the actual function
passed to R_ToplevelExec
hack the contexts
Finally calling the
real function
Internal C level try catch
SEXP res ;
try_catch( [&](){
// some unsafe C code that might JUMP
res = Rf_eval(expr, env) ;
}) ;
return res ;
Nice syntax :
Better performance than Rcpp's solution
Rcpp
Rcpp11
0 1 2 3 4 5 6 7 8 9 10 11 12
overhead of safely calling a function (microseconds)
Internal C level try catch
• Problem: evaluate an R call that might error
• Rcpp solution: wrap the call in R's tryCatch
• Rcpp11 hack: leverage R_ToplevelExec / mess
with the context
• Question: Can you help ? Please.
R_PreserveObject
R_ReleaseObject
/* This code keeps a list of objects which are not assigned to variables
but which are required to persist across garbage collections. The
objects are registered with R_PreserveObject and deregistered with
R_ReleaseObject. */
!
void R_PreserveObject(SEXP object)
{
R_PreciousList = CONS(object, R_PreciousList);
}
!
static SEXP RecursiveRelease(SEXP object, SEXP list)
{
if (!isNull(list)) {
if (object == CAR(list))
return CDR(list);
else
CDR(list) = RecursiveRelease(object, CDR(list));
}
return list;
}
!
void R_ReleaseObject(SEXP object)
{
R_PreciousList = RecursiveRelease(object, R_PreciousList);
}
!
R_PreserveObject / R_ReleaseObject
Romain François
romain@r-enthusiasts.com @romain_francois
Questions ?

Contenu connexe

Tendances

Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.UA Mobile
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184Mahmoud Samir Fayed
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone DevelopmentGiordano Scalzo
 
Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015Fernando Daciuk
 
Let's meet your expectations!
Let's meet your expectations!Let's meet your expectations!
Let's meet your expectations!Bartosz Polaczyk
 
Php 5.6 From the Inside Out
Php 5.6 From the Inside OutPhp 5.6 From the Inside Out
Php 5.6 From the Inside OutFerenc Kovács
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayGiordano Scalzo
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015Michiel Borkent
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency PatternsElifTech
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьPlatonov Sergey
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Mr. Vengineer
 
TestR: generating unit tests for R internals
TestR: generating unit tests for R internalsTestR: generating unit tests for R internals
TestR: generating unit tests for R internalsRoman Tsegelskyi
 

Tendances (20)

Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
 
3 rd animation
3 rd animation3 rd animation
3 rd animation
 
MUST CS101 Lab11
MUST CS101 Lab11 MUST CS101 Lab11
MUST CS101 Lab11
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
 
Agile Iphone Development
Agile Iphone DevelopmentAgile Iphone Development
Agile Iphone Development
 
Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015Javascript Secrets - Front in Floripa 2015
Javascript Secrets - Front in Floripa 2015
 
Coroutines in Kotlin
Coroutines in KotlinCoroutines in Kotlin
Coroutines in Kotlin
 
Let's meet your expectations!
Let's meet your expectations!Let's meet your expectations!
Let's meet your expectations!
 
Php 5.6 From the Inside Out
Php 5.6 From the Inside OutPhp 5.6 From the Inside Out
Php 5.6 From the Inside Out
 
XpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp wayXpUg Coding Dojo: KataYahtzee in Ocp way
XpUg Coding Dojo: KataYahtzee in Ocp way
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
 
C++ programming
C++ programmingC++ programming
C++ programming
 
Go Concurrency Patterns
Go Concurrency PatternsGo Concurrency Patterns
Go Concurrency Patterns
 
One definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим житьOne definition rule - что это такое, и как с этим жить
One definition rule - что это такое, и как с этим жить
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
TensorFlow XLA RPC
TensorFlow XLA RPCTensorFlow XLA RPC
TensorFlow XLA RPC
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)Bridge TensorFlow to run on Intel nGraph backends (v0.4)
Bridge TensorFlow to run on Intel nGraph backends (v0.4)
 
Loop c++
Loop c++Loop c++
Loop c++
 
TestR: generating unit tests for R internals
TestR: generating unit tests for R internalsTestR: generating unit tests for R internals
TestR: generating unit tests for R internals
 

Similaire à Rcpp11

Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for RSeth Falcon
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
please help me with two partI Bold it out as wrong part which in t.pdf
please help me with two partI Bold it out as wrong part which in t.pdfplease help me with two partI Bold it out as wrong part which in t.pdf
please help me with two partI Bold it out as wrong part which in t.pdfRBMADU
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the mastersAra Pehlivanian
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)jeffz
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsMorteza Mahdilar
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Romain Francois
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js ModuleFred Chien
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftFlorent Pillet
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaFlorent Pillet
 
Please determine all the bugs that exist in this program. You must a.pdf
Please determine all the bugs that exist in this program. You must a.pdfPlease determine all the bugs that exist in this program. You must a.pdf
Please determine all the bugs that exist in this program. You must a.pdfamarnathmahajansport
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxpriestmanmable
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptMuhammad Sikandar Mustafa
 

Similaire à Rcpp11 (20)

Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for R
 
R and C++
R and C++R and C++
R and C++
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
please help me with two partI Bold it out as wrong part which in t.pdf
please help me with two partI Bold it out as wrong part which in t.pdfplease help me with two partI Bold it out as wrong part which in t.pdf
please help me with two partI Bold it out as wrong part which in t.pdf
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Expert JavaScript tricks of the masters
Expert JavaScript  tricks of the mastersExpert JavaScript  tricks of the masters
Expert JavaScript tricks of the masters
 
The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)The Evolution of Async-Programming (SD 2.0, JavaScript)
The Evolution of Async-Programming (SD 2.0, JavaScript)
 
Router Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditionsRouter Queue Simulation in C++ in MMNN and MM1 conditions
Router Queue Simulation in C++ in MMNN and MM1 conditions
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Advance ROP Attacks
Advance ROP AttacksAdvance ROP Attacks
Advance ROP Attacks
 
Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
How to Write Node.js Module
How to Write Node.js ModuleHow to Write Node.js Module
How to Write Node.js Module
 
Reactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwiftReactive Programming Patterns with RxSwift
Reactive Programming Patterns with RxSwift
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Introduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoaIntroduction to reactive programming & ReactiveCocoa
Introduction to reactive programming & ReactiveCocoa
 
Please determine all the bugs that exist in this program. You must a.pdf
Please determine all the bugs that exist in this program. You must a.pdfPlease determine all the bugs that exist in this program. You must a.pdf
Please determine all the bugs that exist in this program. You must a.pdf
 
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docxjava compilerCompiler1.javajava compilerCompiler1.javaimport.docx
java compilerCompiler1.javajava compilerCompiler1.javaimport.docx
 
Advanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter pptAdvanced procedures in assembly language Full chapter ppt
Advanced procedures in assembly language Full chapter ppt
 

Plus de Romain Francois

Plus de Romain Francois (15)

R/C++
R/C++R/C++
R/C++
 
dplyr and torrents from cpasbien
dplyr and torrents from cpasbiendplyr and torrents from cpasbien
dplyr and torrents from cpasbien
 
dplyr use case
dplyr use casedplyr use case
dplyr use case
 
dplyr
dplyrdplyr
dplyr
 
user2015 keynote talk
user2015 keynote talkuser2015 keynote talk
user2015 keynote talk
 
SevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittrSevillaR meetup: dplyr and magrittr
SevillaR meetup: dplyr and magrittr
 
dplyr
dplyrdplyr
dplyr
 
Data manipulation with dplyr
Data manipulation with dplyrData manipulation with dplyr
Data manipulation with dplyr
 
R and cpp
R and cppR and cpp
R and cpp
 
Rcpp attributes
Rcpp attributesRcpp attributes
Rcpp attributes
 
Rcpp is-ready
Rcpp is-readyRcpp is-ready
Rcpp is-ready
 
Rcpp
RcppRcpp
Rcpp
 
Integrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBufIntegrating R with C++: Rcpp, RInside and RProtoBuf
Integrating R with C++: Rcpp, RInside and RProtoBuf
 
Object Oriented Design(s) in R
Object Oriented Design(s) in RObject Oriented Design(s) in R
Object Oriented Design(s) in R
 
RProtoBuf: protocol buffers for R
RProtoBuf: protocol buffers for RRProtoBuf: protocol buffers for R
RProtoBuf: protocol buffers for R
 

Dernier

Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsJaydeep Chhasatia
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeNeo4j
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptkinjal48
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native BuildpacksVish Abrams
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfBrain Inventory
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionsNirav Modi
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...OnePlan Solutions
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024Mind IT Systems
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfTobias Schneck
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageDista
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.Sharon Liu
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyRaymond Okyere-Forson
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorShane Coughlan
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Jaydeep Chhasatia
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?AmeliaSmith90
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntelliSource Technologies
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxJoão Esperancinha
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxAutus Cyber Tech
 

Dernier (20)

Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software TeamsYour Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
Your Vision, Our Expertise: TECUNIQUE's Tailored Software Teams
 
IA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG timeIA Generativa y Grafos de Neo4j: RAG time
IA Generativa y Grafos de Neo4j: RAG time
 
Webinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.pptWebinar_050417_LeClair12345666777889.ppt
Webinar_050417_LeClair12345666777889.ppt
 
Streamlining Your Application Builds with Cloud Native Buildpacks
Streamlining Your Application Builds  with Cloud Native BuildpacksStreamlining Your Application Builds  with Cloud Native Buildpacks
Streamlining Your Application Builds with Cloud Native Buildpacks
 
Why Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdfWhy Choose Brain Inventory For Ecommerce Development.pdf
Why Choose Brain Inventory For Ecommerce Development.pdf
 
eAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspectionseAuditor Audits & Inspections - conduct field inspections
eAuditor Audits & Inspections - conduct field inspections
 
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
Transforming PMO Success with AI - Discover OnePlan Strategic Portfolio Work ...
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
Top Software Development Trends in 2024
Top Software Development Trends in  2024Top Software Development Trends in  2024
Top Software Development Trends in 2024
 
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdfARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
ARM Talk @ Rejekts - Will ARM be the new Mainstream in our Data Centers_.pdf
 
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales CoverageSales Territory Management: A Definitive Guide to Expand Sales Coverage
Sales Territory Management: A Definitive Guide to Expand Sales Coverage
 
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
20240319 Car Simulator Plan.pptx . Plan for a JavaScript Car Driving Simulator.
 
AI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human BeautyAI Embracing Every Shade of Human Beauty
AI Embracing Every Shade of Human Beauty
 
OpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS CalculatorOpenChain Webinar: Universal CVSS Calculator
OpenChain Webinar: Universal CVSS Calculator
 
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
Optimizing Business Potential: A Guide to Outsourcing Engineering Services in...
 
How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?How Does the Epitome of Spyware Differ from Other Malicious Software?
How Does the Epitome of Spyware Differ from Other Malicious Software?
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
Introduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptxIntroduction-to-Software-Development-Outsourcing.pptx
Introduction-to-Software-Development-Outsourcing.pptx
 
Fields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptxFields in Java and Kotlin and what to expect.pptx
Fields in Java and Kotlin and what to expect.pptx
 
ERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptxERP For Electrical and Electronics manufecturing.pptx
ERP For Electrical and Electronics manufecturing.pptx
 

Rcpp11

  • 2. R
  • 4. Rcpp11 • C++ = C++11 • Smaller code base (than Rcpp) • Header only
  • 6. #include <Rcpp.h> ! // [[Rcpp::export]] int foo(){ return 2 ; } Rcpp Rcpp11 0 1 2 3 4 Less code -> faster compiles
  • 8. NumericVector constructors Vector() { Vector( const Vector& other){ Vector( SEXP x ) { ! Vector( const GenericProxy<Proxy>& proxy ){ explicit Vector( const no_init& obj) { Vector( const int& size, const stored_type& u ) { Vector( const std::string& st ){ Vector( const char* st ) { Vector( const int& siz, stored_type (*gen)(void) ) { Vector( const int& size ) { Vector( const Dimension& dims) { Vector( const Dimension& dims, const U& u) { Vector( const VectorBase<RTYPE,NA,VEC>& other ) { Vector( const int& size, const U& u) { Vector( const sugar::SingleLogicalResult<NA,T>& obj ) { Vector( const int& siz, stored_type (*gen)(U1), const U1& u1) { Vector( const int& siz, stored_type (*gen)(U1,U2), const U1& u1, const U2& u2) { Vector( const int& siz, stored_type (*gen)(U1,U2,U3), const U1& u1, const U2& u2, const U3& u3) { Vector( InputIterator first, InputIterator last){ Vector( InputIterator first, InputIterator last, int n) { Vector( InputIterator first, InputIterator last, Func func) { Vector( InputIterator first, InputIterator last, Func func, int n){ Vector( std::initializer_list<init_type> list ) { 23 constructors in Rcpp
  • 9. NumericVector constructors 11 constructors in Rcpp Vector(){ Vector( const Vector& other){ Vector( Vector&& other){ ! explicit Vector(int n) { explicit Vector(R_xlen_t n) { ! Vector( R_xlen_t n, value_type x ) { Vector( std::initializer_list<value_type> list ){ Vector( std::initializer_list<traits::named_object<value_type>> list ){ ! Vector( const SugarVectorExpression<eT, Expr>& other ) { Vector( const LazyVector<RT,Expr>& other ) { Vector( const GenericProxy<Proxy>& proxy ){
  • 10. NumericVector constructors Vector( const int& siz, stored_type (*gen)(U1), const U1& u1) -> replicate double fun( int power ){ return pow(2.0, power) ; } ! // Rcpp NumericVector x(10, fun, 10.0) ; // Rcpp11 NumericVector x = replicate(10, fun, 10.0) ;
  • 11. NumericVector constructors std::vector<double> v = /* ... */ ; ! // Rcpp NumericVector x(v.begin(), v.end()) ; // Rcpp11 NumericVector x = import(begin(v), end(v)) ; NumericVector x = import(v) ; Vector( InputIterator first, InputIterator last) -> import
  • 13. NumericVector ctors // C++ uniform initialization NumericVector x = {1.0, 2.0, 3.0} ; ! // init with given size NumericVector y( 2 ) ; // data is not initialized NumericVector y( 2, 3.0 ) ; // initialize all to 3.0 ! // fuse several vectors (similar to c in R) NumericVector z = fuse(x, y) ; NumericVector z = fuse(x, y, 3.0) ;
  • 14. create // old school NumericVector::create (Rcpp style). NumericVector x = NumericVector::create(1.0, 2.0, 3.0) ; NumericVector x = NumericVector::create( _["a"] = 1.0, _["b"] = 2.0, _["c"] = 3.0 ) ; ! ! // create as a free function. Rcpp11 style NumericVector x = create(1.0, 2.0, 3.0) ; NumericVector x = create( _["a"] = 1.0, _["b"] = 2.0, _["c"] = 3.0 ) ;
  • 16. sapply + lambda #include <Rcpp11> ! // [[export]] NumericVector foo( NumericVector x ){ return sapply(x, [](double d){ return exp(d * 2) ; }); } x <- 1:3 sapply( x, function(d){ exp(d*2) ; })
  • 17. Rcpp11 release cycle • Available from CRAN: ! • Evolves quickly. Get it from github ! • Next Release: 3.1.1 (same time as R 3.1.1) > install.packages( "Rcpp11" ) > install_github( "Rcpp11/Rcpp11" )
  • 18. attributes companion package • Standalone impl of Rcpp attributes [[Rcpp::export]], sourceCpp, compileAttributes ! • Only available from github: > install_github( "Rcpp11/attributes" )
  • 19. Use Rcpp11 in your package • Write your .cpp files #include <Rcpp11> ! // [[export]] void foo( … ) { … } // your code SystemRequirements: C++11 LinkingTo: Rcpp11 library(attributes) compileAttributes( "mypkg" ) • Express dep on C++11 and Rcpp11 headers • Generate the boiler plate
  • 20. Header only • No runtime dependency ! • Snapshot the code base ! • Better control for package authors
  • 22. Internal C level try catch • Problem: evaluate an R call that might error (long jump) ! • Rcpp solution: wrap the call in R's tryCatch ! • Rcpp11 hack solution: • Leverage R_ToplevelExec / mess with the context • New problem. R_ToplevelExec expectations
  • 23. Internal C level try catch SEXP res ; try_catch( [&](){ // some unsafe C code that might JUMP res = Rf_eval(expr, env) ; }) ; return res ;
  • 24. Internal C level try catch /* R_ToplevelExec - call fun(data) within a top level context to insure that this functin cannot be left by a LONGJMP. R errors in the call to fun will result in a jump to top level. The return value is TRUE if fun returns normally, FALSE if it results in a jump to top level. */ ! Rboolean R_ToplevelExec(void (*fun)(void *), void *data) pointer to a function taking data as void* Data
  • 25. Internal C level try catch template <typename Fun> void try_catch( Fun fun ) { typedef std::pair<Fun*, SEXP&> Pair ; ! SEXP return_value ; ! Pair pair = std::make_pair(&fun, std::ref(return_value)) ; ! bool ok = R_ToplevelExec( &internal::try_catch_helper<Fun>, &pair ) ; ! if( !ok ){ ! SEXP condition = VECTOR_ELT(return_value,0) ; ! if( Rf_isNull(condition) ){ stop("eval error : %s", R_curErrorBuf()) ; } else { Shield<SEXP> msg = Rf_eval( Rf_lang2( Rf_install( "conditionMessage"), condition ), R_GlobalEnv ) ; stop("eval error : %s", CHAR(STRING_ELT(msg, 0)) ) ; } } } The function templated by the real function to call Data, also parameterise by Fun
  • 26. Internal C level try catch template <typename Fun> void try_catch_helper( void* data ){ typedef std::pair<Fun*, SEXP&> Pair ; Pair* pair = reinterpret_cast<Pair*>(data) ; RCNTXT* ctx = (RCNTXT*) R_GlobalContext ; ctx->callflag = CTXT_FUNCTION ; // first call to .addCondHands to add a handler SEXP args = pairlist( Rf_mkString("error"), Rf_allocVector(VECSXP,1), ctx->cloenv, ctx->cloenv, R_FalseValue ) ; SEXP symb = Rf_install(".addCondHands") ; SEXP ifun = INTERNAL( symb ) ; PRIMFUN(ifun)(symb, ifun, args, R_GlobalEnv ); // call it a second time to get the current R_HandlerStack CAR(args) = R_NilValue ; SEXP value = PRIMFUN(ifun)(symb, ifun, args, R_GlobalEnv ) ; pair->second = VECTOR_ELT(CAR(value),4) ; Fun& fun = *reinterpret_cast<Fun*>(pair->first) ; fun() ; } the actual function passed to R_ToplevelExec hack the contexts Finally calling the real function
  • 27. Internal C level try catch SEXP res ; try_catch( [&](){ // some unsafe C code that might JUMP res = Rf_eval(expr, env) ; }) ; return res ; Nice syntax : Better performance than Rcpp's solution Rcpp Rcpp11 0 1 2 3 4 5 6 7 8 9 10 11 12 overhead of safely calling a function (microseconds)
  • 28. Internal C level try catch • Problem: evaluate an R call that might error • Rcpp solution: wrap the call in R's tryCatch • Rcpp11 hack: leverage R_ToplevelExec / mess with the context • Question: Can you help ? Please.
  • 30. /* This code keeps a list of objects which are not assigned to variables but which are required to persist across garbage collections. The objects are registered with R_PreserveObject and deregistered with R_ReleaseObject. */ ! void R_PreserveObject(SEXP object) { R_PreciousList = CONS(object, R_PreciousList); } ! static SEXP RecursiveRelease(SEXP object, SEXP list) { if (!isNull(list)) { if (object == CAR(list)) return CDR(list); else CDR(list) = RecursiveRelease(object, CDR(list)); } return list; } ! void R_ReleaseObject(SEXP object) { R_PreciousList = RecursiveRelease(object, R_PreciousList); } ! R_PreserveObject / R_ReleaseObject