SlideShare une entreprise Scribd logo
1  sur  70
Extend R with Rcpp!!!
     2010/09/19 Tsukuba.R#8
           id:mickey24
id: mickey24 (@mickey24)
Tsukuba.R
Tsukuba.R#4
   •R           Brainf*ck
     •   Brainf*ck

> hello <- "+++++++++[>++++++++>++++++++++
+>+++++<<<-]>.>++.+++++++..++
+.>-.------------.<++++++++.--------.++
+.------.--------.>+."
> brainfxxk(hello)
[1] "Hello, world!"

                        http://www.slideshare.net/mickey24/rbrainfck-1085191
Tsukuba.R#5
• Animation with R
 • library(animation)




                        http://d.hatena.ne.jp/mickey24/20090614
Tsukuba.R#6
• Extend R with C!!!
 •   C   R             (C             OpenCV                 )




                 http://d.hatena.ne.jp/mickey24/20091123/r_de_extension
Tsukuba.R#7
• Parallel Conputing in R
  •   snow




                    http://d.hatena.ne.jp/mickey24/20100510/tsukuba_r7
Tsukuba.R#8


Rcpp R
Outline
•        R    (C++)

• Rcpp
•
R   (C++)
C++ R
• C++         R
        (C/FORTRAN OK)

• C++              R
1.
     •
     •          C   R                     (40   50   )   www
         - Seeking for my unique color.
         http://d.hatena.ne.jp/syou6162/20090117/1232120983

2. R           C
C++ R
• C++   R                 API




extern "C" SEXP foo(SEXP x) {
  ...
}
C++ R
    1. C++ R
    2.                  .so
    3. R       .so
    4. .Call   .so


R                              C++
                     1. add_vector
                     2. cat_string
add_vector.cc
#include <R.h>
#include <Rdefines.h>

extern "C" SEXP add_vector(SEXP x, SEXP y) {
  PROTECT(x = AS_NUMERIC(x));
  PROTECT(y = AS_NUMERIC(y));

    const int n = LENGTH(x);
    SEXP z;
    PROTECT(z = allocVector(REALSXP, n));

    for (int i = 0; i < n; ++i) {
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];
    }

    UNPROTECT(3);
    return z;
}
add_vector.cc
•
$ R CMD SHLIB add_vector.cc


• .so
$ ls
add_vector.cc
add_vector.o
add_vector.so
add_vector.cc
•R    .so
> dyn.load("add_vector.so")



•
> .Call("add_vector", 1:3, 4:6)
[1] 5 7 9


                                  OK!
cat_string.cc
#include <R.h>
#include <Rdefines.h>
#include <string>

extern "C" SEXP cat_string(SEXP x, SEXP y) {
  PROTECT(x = AS_CHARACTER(x));
  PROTECT(y = AS_CHARACTER(y));

    SEXP z;
    PROTECT(z = allocVector(STRSXP, 1));

    std::string str(CHAR(STRING_ELT(x, 0)));
    str += CHAR(STRING_ELT(y, 0));

    SET_STRING_ELT(z, 0, mkChar(str.c_str()));

    UNPROTECT(3);
    return z;
}
cat_string.cc
•
$ R CMD SHLIB cat_string.cc


•R
> dyn.load("cat_string.so")
> .Call("cat_string", "foo", "bar")
[1] "foobar"

                                      OK!
R
•   PROTECT / UNPROTECT
    •
    •   UNPROTECT(n) →        n
                     …

    •                    GC

•   SEXP C++

•
    •   REAL(x)
    •   C++
Outline
•        R    (C++)

• Rcpp
•
Rcpp
Rcpp
•R          C++


 •
• C++   R
•
> install.packages("Rcpp")



•   Rcpp
Overview
•
> vignette("Rcpp-introduction")




•
OK
• Rcpp                    R




         add_vector.cc Rcpp
add_vector.cc (                          )
#include <R.h>
#include <Rdefines.h>

extern "C" SEXP add_vector(SEXP x, SEXP y) {
  PROTECT(x = AS_NUMERIC(x));
  PROTECT(y = AS_NUMERIC(y));

    const int n = LENGTH(x);
    SEXP z;
    PROTECT(z = allocVector(REALSXP, n));

    for (int i = 0; i < n; ++i) {
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];
    }

    UNPROTECT(3);
    return z;
}
add_vector_rcpp.cc
#include <Rcpp.h>

RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) {
  Rcpp::NumericVector x(xx);
  Rcpp::NumericVector y(yy);

    int n = x.length();
    Rcpp::NumericVector z(n);

    for (int i = 0; i < n; ++i) {
      z[i] = x[i] + y[i];
    }

    return z;
}
1. PROTECT / UNPROTECT
     •                    Rcpp


     •   UNPROTECT
2.
     REAL(x)
     •               []

     •      C++
                                 COOL!!!
#include <R.h>                                 #include <Rcpp.h>
#include <Rdefines.h>
                                               RcppExport SEXP add_vector_rcpp(SEXP xx,
extern "C" SEXP add_vector(SEXP x, SEXP y) {                                   SEXP yy) {
  PROTECT(x = AS_NUMERIC(x));                    Rcpp::NumericVector x(xx);
  PROTECT(y = AS_NUMERIC(y));                    Rcpp::NumericVector y(yy);

    const int n = LENGTH(x);                       const int n = x.length();
    SEXP z;                                        Rcpp::NumericVector z(n);
    PROTECT(z = allocVector(REALSXP, n));
                                                   for (int i = 0; i < n; ++i) {
    for (int i = 0; i < n; ++i) {                    z[i] = x[i] + y[i];
      REAL(z)[i] = REAL(x)[i] + REAL(y)[i];        }
    }
                                                   return z;
    UNPROTECT(3);                              }
    return z;
}
                                                         1. PROTECT / UNPROTECT
                                                         2. REAL(x)
Rcpp

   •            Makevars
       •   Rcpp.h

PKG_CXXFLAGS=$(shell Rscript -e "Rcpp:::CxxFlags()")
PKG_LIBS=$(shell Rscript -e "Rcpp:::LdFlags()")
Rcpp

•
$ R CMD SHLIB add_vector_rcpp.cc



> dyn.load("add_vector_rcpp.so")
> .Call("add_vector_rcpp", 1:3, 4:6)
[1] 5 7 9
NumericVector
• Rcpp::NumericVector
#include <Rcpp.h>

RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) {
  Rcpp::NumericVector x(xx);
  Rcpp::NumericVector y(yy);
  Rcpp::NumericVector z(x + y);

    return z;
}
C++
• SEXP        C++


#include <Rcpp.h>
#include <string>

RcppExport SEXP cat_string_rcpp(SEXP xx, SEXP yy) {
  std::string x(Rcpp::as<std::string>(xx));
  std::string y(Rcpp::as<std::string>(yy));
  std::string z(x + y);

    return Rcpp::wrap(z);
}
as wrap
• SEXP                      C++
 1. primitive       int, double, etc.
 2.             std::string, const char*
 3.               std::vector<T>, std::list<T>
 4.               std::map<string, T>
 5. SEXP
 6. wrap
Rcpp

    PROTECT
   UNPROTECT

                REAL(x), CHAR(x),
                                    [] (                )
               STRING_ELT(x, i)
SEXP C++
                                           (as, wrap)

                                       Makervars
                                    Rcpp
Outline
•        R    (C++)

• Rcpp
•
• Rcpp

•    Rcpp
•             0.7                           n


    1. r2norm_for : R   for             (syou6162 )
    2. r2norm_cpp :           C++            (syou6162 )
    3. r2norm_rcpp : Rcpp


    > x <- r2norm_cpp(1000)
    > cor(x[,1], x[,2])
    [1] 0.7144986
    > plot(x)
                               http://d.hatena.ne.jp/syou6162/20090117/1232120983
r2norm_cpp.cc                                     r2norm_rcpp.cc
#include <R.h>                                   #include <Rcpp.h>
#include <Rdefines.h>
                                                 RcppExport SEXP r2norm_rcpp(SEXP num) {
extern "C" SEXP r2norm_cpp(SEXP num) {             const int n = Rcpp::as<int>(num);
  PROTECT(num = AS_INTEGER(num));                  Rcpp::NumericMatrix ans(n, 2);
  const int n = INTEGER(num)[0];
                                                     GetRNGstate();
    SEXP ans;
    PROTECT(ans = allocMatrix(REALSXP, n, 2));       double prevX1 = 2.0;
                                                     double prevX2 = 1.0;
    GetRNGstate();                                   for (int i = 0; i < n; ++i) {
                                                       prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) +
    double prevX1 = 2.0;                                 (norm_rand() * (1.0 - 0.7 * 0.7));
    double prevX2 = 1.0;                               ans(i, 0) = prevX1;
    for (int i = 0; i < n; ++i) {                      prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) +
      prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) +              (norm_rand() * (1.0 - 0.7 * 0.7));
        (norm_rand() * (1.0 - 0.7 * 0.7));             ans(i, 1) = prevX2;
      REAL(ans)[i] = prevX1;                         }
      prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) +          PutRNGstate();
        (norm_rand() * (1.0 - 0.7 * 0.7));
      REAL(ans)[i+n] = prevX2;                       return ans;
    }                                            }
    PutRNGstate();

    UNPROTECT(2);
    return ans;
}
n = 1,000 n = 10^4 n = 10^5 n = 10^6

R    for      0.035     0.330    3.372    33.982

       C++    0.001     0.003    0.028    0.312

    Rcpp      0.001     0.005    0.050    0.507

                                               sec
R    for            C++       Rcpp
sec
40.00


30.00


20.00


10.00


      0
           n=1000   n=10^4         n=10^5         n=10^6


      R   for                      67
(        vs Rcpp)
                                         C++       Rcpp
sec
 0.60


 0.45


 0.30


 0.15


      0
          n=1000   n=10^4       n=10^5         n=10^6
•   Rcpp       C++      R


•   R
           (PROTECT / UNPROTECT   )

•   SEXP C++

•
•   C++    R


•         R API         C++


•
                  C++         R
•   Rcpp: Seamless R and C++ Integration
    http://dirk.eddelbuettel.com/code/rcpp.html

•   Rcpp                  - Seeking for my unique color.
    http://d.hatena.ne.jp/syou6162/20100316/1268734140

•   C   R                          (40   50   )       www
    - Seeking for my unique color.
    http://d.hatena.ne.jp/syou6162/20090117/1232120983

•   Writing R Extensions
    http://cran.r-project.org/doc/contrib/manuals-jp/R-exts.jp.pdf
Tsukuba.R#7
RTetris
2010/09/19 Tsukuba.R#8
      id:mickey24
RTetris
•   R(                   C++)
    •   Tsukuba.R#7 (           )

    •   tetris                      C++
        •            R

    •                ncurses


•                R
         R
RTetris                   R
•                 C++(Rcpp)
    •   ncurses       C++

•                      R
    •
• Tsukuba.R#8
…
•
1.
2.
3.
4.
•
•   ncurses

•   C++                 ncurses
           (             )

      RcppExport SEXP ncurses_initialize() {
        initscr();
        noecho();
        nodelay(stdscr, true);
        curs_set(0);

          return R_NilValue;
      }
R
•
•         R               (ry



•   C++       & ncurses
•   ncurses getch
    •                     ASCII                 -1

        RcppExport SEXP ncurses_getch() {
          return wrap(getch());
        }



•   R

    •
    •   proc.time()
        while (running) {
          key = ncurses_getch()
          if (key != -1) {      }


            now = proc.time()
            if (now[3] >= next_time) {      }


            Sys.sleep(0.001)
        }
•

•
    •           all

    •
        all(field[i,] == BLOCK)
•
                                       
   a11   a12   a13   a14                 1
  a21   a22   a23   a24           1    
A=
  a31
                            R=          
         a32   a33   a34       1        
   a41   a42   a43   a44        1
(                       )

•
                                              
       a11   a12   a13   a14                 1
     a21    a22   a23   a24           1       
AR = 
     a31
                             ×                 
             a32   a33   a34       1           
       a41   a42   a43   a44    1
                            
      a14    a13   a12   a11
     a24    a23   a22   a21 
   =a34
                             
             a33   a32   a31 
      a44    a43   a42   a41
(            )

•
                                 T
            a14    a13   a12   a11
           a24    a23   a22   a21 
    (AR) = 
        T
           a34
                                   
                   a33   a32   a31 
            a44    a43   a42   a41
                                  
             a14   a24   a34   a44
           a13    a23   a33   a43 
          =
           a12
                                   
                   a22   a32   a42 
             a11   a21   a31   a41
(                )

   •
                                                      
   a11   a12   a13   a14            a41   a31   a21   a11
  a21   a22   a23   a24          a42   a32   a22   a12 
A=
  a31
                          (RA)T =                       
         a32   a33   a34          a43   a33   a23   a13 
   a41   a42   a43   a44            a44   a34   a24   a14
•
•   R


    •
    •
•
Extend R with Rcpp!!!

Contenu connexe

Tendances

Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
jeffz
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
jeffz
 
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
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
koji lin
 

Tendances (20)

响应式编程及框架
响应式编程及框架响应式编程及框架
响应式编程及框架
 
Jscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScriptJscex: Write Sexy JavaScript
Jscex: Write Sexy JavaScript
 
Javascript Uncommon Programming
Javascript Uncommon ProgrammingJavascript Uncommon Programming
Javascript Uncommon Programming
 
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)
 
The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184The Ring programming language version 1.5.3 book - Part 87 of 184
The Ring programming language version 1.5.3 book - Part 87 of 184
 
Coding in Style
Coding in StyleCoding in Style
Coding in Style
 
RuleML2015: GRAAL - a toolkit for query answering with existential rules
RuleML2015:  GRAAL - a toolkit for query answering with existential rulesRuleML2015:  GRAAL - a toolkit for query answering with existential rules
RuleML2015: GRAAL - a toolkit for query answering with existential rules
 
Java8 stream
Java8 streamJava8 stream
Java8 stream
 
Swift for tensorflow
Swift for tensorflowSwift for tensorflow
Swift for tensorflow
 
Struct examples
Struct examplesStruct examples
Struct examples
 
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...GECon2017_Cpp  a monster that no one likes but that will outlast them all _Ya...
GECon2017_Cpp a monster that no one likes but that will outlast them all _Ya...
 
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them allGECon 2017: C++ - a Monster that no one likes but that will outlast them all
GECon 2017: C++ - a Monster that no one likes but that will outlast them all
 
Brief intro to clojure
Brief intro to clojureBrief intro to clojure
Brief intro to clojure
 
Vectorization in ATLAS
Vectorization in ATLASVectorization in ATLAS
Vectorization in ATLAS
 
The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181The Ring programming language version 1.5.2 book - Part 78 of 181
The Ring programming language version 1.5.2 book - Part 78 of 181
 
Beyond tf idf why, what & how
Beyond tf idf why, what & howBeyond tf idf why, what & how
Beyond tf idf why, what & how
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
Anti patterns
Anti patternsAnti patterns
Anti patterns
 
Lec06
Lec06Lec06
Lec06
 
Modern c++ Memory Management
Modern c++ Memory ManagementModern c++ Memory Management
Modern c++ Memory Management
 

En vedette

ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33
horihorio
 
Extend R with C!!!
Extend R with C!!!Extend R with C!!!
Extend R with C!!!
mickey24
 
Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33
Nobuaki Oshiro
 
第31回TokyoR LT資料
第31回TokyoR LT資料第31回TokyoR LT資料
第31回TokyoR LT資料
tetsuro ito
 

En vedette (20)

R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦! R+pythonでKAGGLEの2値予測に挑戦!
R+pythonでKAGGLEの2値予測に挑戦!
 
今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門今日から使える! みんなのクラスタリング超入門
今日から使える! みんなのクラスタリング超入門
 
ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33ロジスティック回帰の考え方・使い方 - TokyoR #33
ロジスティック回帰の考え方・使い方 - TokyoR #33
 
Extend R with C!!!
Extend R with C!!!Extend R with C!!!
Extend R with C!!!
 
ESS
ESSESS
ESS
 
セイバーメトリクス
セイバーメトリクスセイバーメトリクス
セイバーメトリクス
 
RでAHP
RでAHPRでAHP
RでAHP
 
Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33Doradora09 lt tokyo_r33
Doradora09 lt tokyo_r33
 
ニコニコ動画タグネットワーク
ニコニコ動画タグネットワークニコニコ動画タグネットワーク
ニコニコ動画タグネットワーク
 
偽相関と偏相関係数
偽相関と偏相関係数偽相関と偏相関係数
偽相関と偏相関係数
 
Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境Fluentd,mongo db,rでお手軽ログ解析環境
Fluentd,mongo db,rでお手軽ログ解析環境
 
Collaborativefilteringwith r
Collaborativefilteringwith rCollaborativefilteringwith r
Collaborativefilteringwith r
 
rzmq
rzmqrzmq
rzmq
 
第31回TokyoR LT資料
第31回TokyoR LT資料第31回TokyoR LT資料
第31回TokyoR LT資料
 
中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側中の人が語る seekR.jp の裏側
中の人が語る seekR.jp の裏側
 
R3.0.0 is relased
R3.0.0 is relasedR3.0.0 is relased
R3.0.0 is relased
 
Tokyo r30 anova_part2
Tokyo r30 anova_part2Tokyo r30 anova_part2
Tokyo r30 anova_part2
 
第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション第32回Tokyo.R#初心者セッション
第32回Tokyo.R#初心者セッション
 
Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」Tokyo.R 白熱教室「これからのRcppの話をしよう」
Tokyo.R 白熱教室「これからのRcppの話をしよう」
 
Abテストと検定
Abテストと検定Abテストと検定
Abテストと検定
 

Similaire à Extend R with Rcpp!!!

Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
Romain Francois
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
Romain Francois
 
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdfImplement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
meerobertsonheyde608
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
Romain Francois
 
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdfTranslate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
fcsondhiindia
 

Similaire à Extend R with Rcpp!!! (20)

Rcpp11 genentech
Rcpp11 genentechRcpp11 genentech
Rcpp11 genentech
 
R and C++
R and C++R and C++
R and C++
 
R and cpp
R and cppR and cpp
R and cpp
 
Rcpp11 useR2014
Rcpp11 useR2014Rcpp11 useR2014
Rcpp11 useR2014
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014R/C++ talk at earl 2014
R/C++ talk at earl 2014
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Native interfaces for R
Native interfaces for RNative interfaces for R
Native interfaces for R
 
PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...PVS-Studio team experience: checking various open source projects, or mistake...
PVS-Studio team experience: checking various open source projects, or mistake...
 
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdfImplement an MPI program to perform matrix-matrix multiplication AB .pdf
Implement an MPI program to perform matrix-matrix multiplication AB .pdf
 
Rcpp11
Rcpp11Rcpp11
Rcpp11
 
Rcpp: Seemless R and C++
Rcpp: Seemless R and C++Rcpp: Seemless R and C++
Rcpp: Seemless R and C++
 
Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009Computer Vision using Ruby and libJIT - RubyConf 2009
Computer Vision using Ruby and libJIT - RubyConf 2009
 
Brief tour of psp-std
Brief tour of psp-stdBrief tour of psp-std
Brief tour of psp-std
 
Frsa
FrsaFrsa
Frsa
 
Sparse Matrix and Polynomial
Sparse Matrix and PolynomialSparse Matrix and Polynomial
Sparse Matrix and Polynomial
 
Compose Async with RxJS
Compose Async with RxJSCompose Async with RxJS
Compose Async with RxJS
 
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdfTranslate the following CC++ code into MIPS Assembly Codevoid ch.pdf
Translate the following CC++ code into MIPS Assembly Codevoid ch.pdf
 
Write Python for Speed
Write Python for SpeedWrite Python for Speed
Write Python for Speed
 
include.docx
include.docxinclude.docx
include.docx
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Dernier (20)

Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

Extend R with Rcpp!!!

  • 1. Extend R with Rcpp!!! 2010/09/19 Tsukuba.R#8 id:mickey24
  • 4. Tsukuba.R#4 •R Brainf*ck • Brainf*ck > hello <- "+++++++++[>++++++++>++++++++++ +>+++++<<<-]>.>++.+++++++..++ +.>-.------------.<++++++++.--------.++ +.------.--------.>+." > brainfxxk(hello) [1] "Hello, world!" http://www.slideshare.net/mickey24/rbrainfck-1085191
  • 5. Tsukuba.R#5 • Animation with R • library(animation) http://d.hatena.ne.jp/mickey24/20090614
  • 6. Tsukuba.R#6 • Extend R with C!!! • C R (C OpenCV ) http://d.hatena.ne.jp/mickey24/20091123/r_de_extension
  • 7. Tsukuba.R#7 • Parallel Conputing in R • snow http://d.hatena.ne.jp/mickey24/20100510/tsukuba_r7
  • 9. Outline • R (C++) • Rcpp •
  • 10. R (C++)
  • 11. C++ R • C++ R (C/FORTRAN OK) • C++ R
  • 12. 1. • • C R (40 50 ) www - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20090117/1232120983 2. R C
  • 13. C++ R • C++ R API extern "C" SEXP foo(SEXP x) { ... }
  • 14. C++ R 1. C++ R 2. .so 3. R .so 4. .Call .so R C++ 1. add_vector 2. cat_string
  • 15. add_vector.cc #include <R.h> #include <Rdefines.h> extern "C" SEXP add_vector(SEXP x, SEXP y) { PROTECT(x = AS_NUMERIC(x)); PROTECT(y = AS_NUMERIC(y)); const int n = LENGTH(x); SEXP z; PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } UNPROTECT(3); return z; }
  • 16. add_vector.cc • $ R CMD SHLIB add_vector.cc • .so $ ls add_vector.cc add_vector.o add_vector.so
  • 17. add_vector.cc •R .so > dyn.load("add_vector.so") • > .Call("add_vector", 1:3, 4:6) [1] 5 7 9 OK!
  • 18. cat_string.cc #include <R.h> #include <Rdefines.h> #include <string> extern "C" SEXP cat_string(SEXP x, SEXP y) { PROTECT(x = AS_CHARACTER(x)); PROTECT(y = AS_CHARACTER(y)); SEXP z; PROTECT(z = allocVector(STRSXP, 1)); std::string str(CHAR(STRING_ELT(x, 0))); str += CHAR(STRING_ELT(y, 0)); SET_STRING_ELT(z, 0, mkChar(str.c_str())); UNPROTECT(3); return z; }
  • 19. cat_string.cc • $ R CMD SHLIB cat_string.cc •R > dyn.load("cat_string.so") > .Call("cat_string", "foo", "bar") [1] "foobar" OK!
  • 20. R • PROTECT / UNPROTECT • • UNPROTECT(n) → n … • GC • SEXP C++ • • REAL(x) • C++
  • 21. Outline • R (C++) • Rcpp •
  • 22. Rcpp
  • 23. Rcpp •R C++ • • C++ R
  • 26. OK • Rcpp R add_vector.cc Rcpp
  • 27. add_vector.cc ( ) #include <R.h> #include <Rdefines.h> extern "C" SEXP add_vector(SEXP x, SEXP y) { PROTECT(x = AS_NUMERIC(x)); PROTECT(y = AS_NUMERIC(y)); const int n = LENGTH(x); SEXP z; PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } UNPROTECT(3); return z; }
  • 28. add_vector_rcpp.cc #include <Rcpp.h> RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) { Rcpp::NumericVector x(xx); Rcpp::NumericVector y(yy); int n = x.length(); Rcpp::NumericVector z(n); for (int i = 0; i < n; ++i) { z[i] = x[i] + y[i]; } return z; }
  • 29. 1. PROTECT / UNPROTECT • Rcpp • UNPROTECT 2. REAL(x) • [] • C++ COOL!!!
  • 30. #include <R.h> #include <Rcpp.h> #include <Rdefines.h> RcppExport SEXP add_vector_rcpp(SEXP xx, extern "C" SEXP add_vector(SEXP x, SEXP y) { SEXP yy) { PROTECT(x = AS_NUMERIC(x)); Rcpp::NumericVector x(xx); PROTECT(y = AS_NUMERIC(y)); Rcpp::NumericVector y(yy); const int n = LENGTH(x); const int n = x.length(); SEXP z; Rcpp::NumericVector z(n); PROTECT(z = allocVector(REALSXP, n)); for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) { z[i] = x[i] + y[i]; REAL(z)[i] = REAL(x)[i] + REAL(y)[i]; } } return z; UNPROTECT(3); } return z; } 1. PROTECT / UNPROTECT 2. REAL(x)
  • 31. Rcpp • Makevars • Rcpp.h PKG_CXXFLAGS=$(shell Rscript -e "Rcpp:::CxxFlags()") PKG_LIBS=$(shell Rscript -e "Rcpp:::LdFlags()")
  • 32. Rcpp • $ R CMD SHLIB add_vector_rcpp.cc > dyn.load("add_vector_rcpp.so") > .Call("add_vector_rcpp", 1:3, 4:6) [1] 5 7 9
  • 33. NumericVector • Rcpp::NumericVector #include <Rcpp.h> RcppExport SEXP add_vector_rcpp(SEXP xx, SEXP yy) { Rcpp::NumericVector x(xx); Rcpp::NumericVector y(yy); Rcpp::NumericVector z(x + y); return z; }
  • 34. C++ • SEXP C++ #include <Rcpp.h> #include <string> RcppExport SEXP cat_string_rcpp(SEXP xx, SEXP yy) { std::string x(Rcpp::as<std::string>(xx)); std::string y(Rcpp::as<std::string>(yy)); std::string z(x + y); return Rcpp::wrap(z); }
  • 35. as wrap • SEXP C++ 1. primitive int, double, etc. 2. std::string, const char* 3. std::vector<T>, std::list<T> 4. std::map<string, T> 5. SEXP 6. wrap
  • 36. Rcpp PROTECT UNPROTECT REAL(x), CHAR(x), [] ( ) STRING_ELT(x, i) SEXP C++ (as, wrap) Makervars Rcpp
  • 37. Outline • R (C++) • Rcpp •
  • 38.
  • 39. • Rcpp • Rcpp
  • 40.
  • 41. 0.7 n 1. r2norm_for : R for (syou6162 ) 2. r2norm_cpp : C++ (syou6162 ) 3. r2norm_rcpp : Rcpp > x <- r2norm_cpp(1000) > cor(x[,1], x[,2]) [1] 0.7144986 > plot(x) http://d.hatena.ne.jp/syou6162/20090117/1232120983
  • 42. r2norm_cpp.cc r2norm_rcpp.cc #include <R.h> #include <Rcpp.h> #include <Rdefines.h> RcppExport SEXP r2norm_rcpp(SEXP num) { extern "C" SEXP r2norm_cpp(SEXP num) { const int n = Rcpp::as<int>(num); PROTECT(num = AS_INTEGER(num)); Rcpp::NumericMatrix ans(n, 2); const int n = INTEGER(num)[0]; GetRNGstate(); SEXP ans; PROTECT(ans = allocMatrix(REALSXP, n, 2)); double prevX1 = 2.0; double prevX2 = 1.0; GetRNGstate(); for (int i = 0; i < n; ++i) { prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) + double prevX1 = 2.0; (norm_rand() * (1.0 - 0.7 * 0.7)); double prevX2 = 1.0; ans(i, 0) = prevX1; for (int i = 0; i < n; ++i) { prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) + prevX1 = 1.0 + 0.7 * (prevX2 - 2.0) + (norm_rand() * (1.0 - 0.7 * 0.7)); (norm_rand() * (1.0 - 0.7 * 0.7)); ans(i, 1) = prevX2; REAL(ans)[i] = prevX1; } prevX2 = 2.0 + 0.7 * (prevX1 - 1.0) + PutRNGstate(); (norm_rand() * (1.0 - 0.7 * 0.7)); REAL(ans)[i+n] = prevX2; return ans; } } PutRNGstate(); UNPROTECT(2); return ans; }
  • 43.
  • 44. n = 1,000 n = 10^4 n = 10^5 n = 10^6 R for 0.035 0.330 3.372 33.982 C++ 0.001 0.003 0.028 0.312 Rcpp 0.001 0.005 0.050 0.507 sec
  • 45. R for C++ Rcpp sec 40.00 30.00 20.00 10.00 0 n=1000 n=10^4 n=10^5 n=10^6 R for 67
  • 46. ( vs Rcpp) C++ Rcpp sec 0.60 0.45 0.30 0.15 0 n=1000 n=10^4 n=10^5 n=10^6
  • 47.
  • 48. Rcpp C++ R • R (PROTECT / UNPROTECT ) • SEXP C++ •
  • 49. C++ R • R API C++ • C++ R
  • 50. Rcpp: Seamless R and C++ Integration http://dirk.eddelbuettel.com/code/rcpp.html • Rcpp - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20100316/1268734140 • C R (40 50 ) www - Seeking for my unique color. http://d.hatena.ne.jp/syou6162/20090117/1232120983 • Writing R Extensions http://cran.r-project.org/doc/contrib/manuals-jp/R-exts.jp.pdf
  • 51.
  • 54. RTetris • R( C++) • Tsukuba.R#7 ( ) • tetris C++ • R • ncurses • R R
  • 55. RTetris R • C++(Rcpp) • ncurses C++ • R • • Tsukuba.R#8
  • 56.
  • 57.
  • 58.
  • 59.
  • 61. • • ncurses • C++ ncurses ( ) RcppExport SEXP ncurses_initialize() { initscr(); noecho(); nodelay(stdscr, true); curs_set(0); return R_NilValue; }
  • 62. R • • R (ry • C++ & ncurses
  • 63. ncurses getch • ASCII -1 RcppExport SEXP ncurses_getch() { return wrap(getch()); } • R • • proc.time() while (running) { key = ncurses_getch() if (key != -1) { } now = proc.time() if (now[3] >= next_time) { } Sys.sleep(0.001) }
  • 64. • • • all • all(field[i,] == BLOCK)
  • 65. •     a11 a12 a13 a14 1 a21 a22 a23 a24   1  A= a31  R=  a32 a33 a34   1  a41 a42 a43 a44 1
  • 66. ( ) •     a11 a12 a13 a14 1 a21 a22 a23 a24   1  AR =  a31 ×  a32 a33 a34   1  a41 a42 a43 a44 1   a14 a13 a12 a11 a24 a23 a22 a21  =a34  a33 a32 a31  a44 a43 a42 a41
  • 67. ( ) •  T a14 a13 a12 a11 a24 a23 a22 a21  (AR) =  T a34  a33 a32 a31  a44 a43 a42 a41   a14 a24 a34 a44 a13 a23 a33 a43  = a12  a22 a32 a42  a11 a21 a31 a41
  • 68. ( ) •     a11 a12 a13 a14 a41 a31 a21 a11 a21 a22 a23 a24  a42 a32 a22 a12  A= a31  (RA)T =   a32 a33 a34  a43 a33 a23 a13  a41 a42 a43 a44 a44 a34 a24 a14
  • 69. • • R • • •