RでC言語のgslを利用することで数値積分を早くする

Windowsの場合です。

#gslの導入
コンパイルはうまくいなからgslのバイナリを
http://www.stats.ox.ac.uk/pub/Rtools/libs.html
wget local323.zip

#1. 準備GSLのセットアップ
##(1-1) GSLのバイナリをのダウンロード
ここからgslのバイナリをいただく http://www.stats.ox.ac.uk/pub/Rtools/libs.html
c/Rtoolsで作業
mkdir gsl
cd gsl
wget http://www.stats.ox.ac.uk/pub/Rtools/goodies/multilib/local323.zip
unzip local323.zip
これでgsl 導入完了。
c/Rtools/gsl/libとc/Rtools/gsl/include
##(1-2) パスがあるところにコピー
これはやらなくてよい。
cp lib/x64/libgsl.a ../mingw_64/lib
cp lib/x64/libgslcblas.a ../mingw_64/lib

#2. Rのセットアップ
##(2-1) Rでの導入
install.packages(Rcpp)
install.pakcages(RcppGSL)

##(2-2) 設定ファイルを作る
$ HOME/.R/Makevars.R を作成して,以下の内容を書き込む

    • -

PKG_CPPFLAGS=${PKG_CPPFLGS} -L"C:/Rtools/gsl/lib/x64" -lgsl -lgslcblas -I"C:/Rtools/gsl/include"

    • -
  • Rtools/gsl 等は適切な場所に
  • $HOMEは、デフォルトでRが起動する場所、ある関数でだせるけどやり方失念。

#3. 試す

  • まず、cpp ファイル
    • -

// Rcpp::depends(RcppGSL)
#include
#include
#include


// Rcpp::export
Rcpp::NumericVector colNorm(const RcppGSL::Matrix & G) {
int k = G.ncol();
Rcpp::NumericVector n(k);
for (int j = 0; j < k; j++) {
RcppGSL::VectorView colview = gsl_matrix_const_column(G, j);
n[j] = gsl_blas_dnrm2(colview);
}
return n;
}

    • -
  • 次に、Rファイル
    • -

library(Rcpp)
library(RcppGSL)

sourceCpp('test0.cpp')

set.seed(1234)
m <- matrix(rnorm(4), ncol=2)
print(colNorm(m))
#1.238537 2.584243

    • -

#4 .積分
#4.1 積分をRで
以下すべてコードは以下かのサイトから引用です。
{Rcpp}と{RcppGSL}を活用した数値積分の例
http://statmodeling.hatenablog.com/entry/numerical-integration-with-Rcpp-and-RcppGSL

        • -

sd <- 0.24
integrand <- function(x, mu) (0.2 + min(x, -0.3-x)) * dnorm(x, mean=mu, sd=sd)
g1 <- function(mu) integrate(integrand, mu-6*sd, mu+6*sd, mu)$value
g2 <- function(mu) pracma::romberg(integrand, a=mu-6*sd, b=mu+6*sd, mu=mu)$value

x <- seq(-3, 3, len=101)
m1 <- sapply(x, g1)
m2 <- sapply(x, g2)

#一番参考にさせていただいたサイト
{Rcpp}と{RcppGSL}を活用した数値積分の例
http://statmodeling.hatenablog.com/entry/numerical-integration-with-Rcpp-and-RcppGSL


#その他、参考にさせていただいたサイト
http://wildpie.hatenablog.com/entry/20151003/1443863102
RccpGSL, installing/using GSL from R on windows 7
https://stackoverflow.com/questions/29370005/rccpgsl-installing-using-gsl-from-r-on-windows-7
{Rcpp}と{RcppGSL}を活用した数値積分の例
http://statmodeling.hatenablog.com/entry/numerical-integration-with-Rcpp-and-RcppGSL

configureの設定を変更してみる
https://www.atmarkit.co.jp/ait/articles/1107/01/news139.html
Cygwin上でmingwでビルドしたい。
https://teratail.com/questions/168455

http://ja.uwenku.com/question/p-voevlzxo-oy.html
準備GSLのセットアップ
ーーーーーーーーーーーーーーーーーー


#参考(ソースから)
https://www.gnu.org/software/gsl/
c/Rtoolsで作業
mkdir gsl
cd gsl
wget http://ftp.jaist.ac.jp/pub/GNU/gsl/gsl-2.6.tar.gz
gzip -d gsl-2.6.tar
tar -xvf gsl-2.6.tar
cd gsl-2.6
./configure --host=x86_64-w64-mingw32