├── .Rbuildignore ├── .gitignore ├── Contributors ├── NAMESPACE ├── demo ├── testNAtypeMatrix.R ├── 00Index ├── testmdarray.R ├── testmatrix.R ├── testNAtype.R ├── testdataframe.R ├── testtuple.R ├── testcode.R ├── testParallel.R └── testtype.R ├── src ├── Julia_R.h ├── Makevars ├── dataframe.h ├── R_Julia.h ├── Makevars.win ├── dataframe.c ├── embedding.c ├── R_Julia.c └── Julia_R.c ├── RJulia.Rproj ├── R ├── zzz.R └── rjulia.R ├── todo.txt ├── DESCRIPTION ├── tests ├── run_unit_tests.R ├── unit │ └── test_roundtrip.R └── stresstest.R ├── man ├── julia_eval.Rd ├── julia_init.Rd ├── jloaddf.Rd ├── r_julia.Rd ├── julia_BigintToDouble.Rd └── rjulia-package.Rd ├── README.md └── LICENSE /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | todo[.]txt 4 | Contributors 5 | 6 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.dll 3 | *.o 4 | *.exe 5 | *.a 6 | *.lib 7 | *.so 8 | .Rhistory 9 | .Rbuildignore 10 | .Rdata 11 | .Rproj.user 12 | -------------------------------------------------------------------------------- /Contributors: -------------------------------------------------------------------------------- 1 | who contributed by donating code, bug fixes and documentation 2 | Oliver Keyes, Martin Maechler, Sam Lendle and Daniel Gromer 3 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | export(julia_init, 2 | ## short, long : 3 | j2r, julia_eval, 4 | jDo, julia_void_eval, 5 | r2j, r_julia, 6 | jloaddf, julia_LoadDataArrayFrame, 7 | jdfinited, julia_DataArrayFrameInited 8 | ) 9 | useDynLib(rjulia) 10 | -------------------------------------------------------------------------------- /demo/testNAtypeMatrix.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | julia_init() 3 | julia_LoadDataArrayFrame() 4 | x <- matrix(1:9, 3,3) 5 | x[c(1,5,8)] <- NA 6 | x 7 | r2j(x,"xy") 8 | str( j2r("xy") ) 9 | str( j2r("length(xy)") ) 10 | str( j2r("length(xy.na)") ) 11 | str( j2r("length(xy.data)") ) 12 | -------------------------------------------------------------------------------- /demo/00Index: -------------------------------------------------------------------------------- 1 | testNAtype test NA type 2 | testNAtypeMatrix test NA type matrix 3 | testParallel test parallel 4 | testcode test code 5 | testdataframe test data frame 6 | testmatrix test matrix 7 | testmdarray test "md"array 8 | testtuple test tuple 9 | testtype test type 10 | 11 | -------------------------------------------------------------------------------- /src/Julia_R.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | #ifndef JULIA_R_H 5 | #define JULIA_R_H 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #include 12 | #include 13 | 14 | SEXP Julia_R(jl_value_t* Var); 15 | SEXP Julia_BigintToDouble(SEXP Var); 16 | #ifdef __cplusplus 17 | } 18 | #endif 19 | #endif 20 | -------------------------------------------------------------------------------- /RJulia.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: Default 4 | SaveWorkspace: Default 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: Sweave 13 | LaTeX: pdfLaTeX 14 | 15 | BuildType: Package 16 | PackageUseDevtools: Yes 17 | PackageInstallArgs: --no-multiarch --with-keep.source 18 | -------------------------------------------------------------------------------- /src/Makevars: -------------------------------------------------------------------------------- 1 | # Emacs: treat me as -*- Makefile -*- 2 | # CRAN checks want non-GNU Makefiles 3 | # but MM cannot see a direct way -- we would need Makevars.in 4 | 5 | JL_SHARE = $(shell julia -e 'print(joinpath(JULIA_HOME,Base.DATAROOTDIR,"julia"))') 6 | PKG_CFLAGS += $(shell $(JL_SHARE)/julia-config.jl --cflags) 7 | PKG_LIBS += $(shell $(JL_SHARE)/julia-config.jl --ldlibs --ldflags) 8 | -------------------------------------------------------------------------------- /src/dataframe.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | #ifndef DATAFRAME_H 5 | #define DATAFRAME_H 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | #define eltsize 1024 10 | #define evalsize 4096 11 | #include 12 | SEXP Julia_LoadDataArrayFrame(); 13 | SEXP Julia_DataArrayFrameInited(); 14 | bool LoadDF(); 15 | #ifdef __cplusplus 16 | } 17 | #endif 18 | #endif 19 | -------------------------------------------------------------------------------- /R/zzz.R: -------------------------------------------------------------------------------- 1 | .juliaLib <- function() 2 | gsub("\"", "", 3 | system('julia -E "abspath(Libdl.dlpath(\\\"libjulia\\\"))"', 4 | intern = TRUE)) 5 | 6 | .onLoad <- function(libname, pkgname) 7 | { 8 | .ldjulia <<- .juliaLib() 9 | dyn.load(.ldjulia, local = FALSE) 10 | } 11 | 12 | .onUnload <- function(libpath) 13 | { 14 | if(!exists(".ldjulia")) .ldjulia <- .juliaLib() 15 | dyn.unload(.ldjulia) 16 | } 17 | -------------------------------------------------------------------------------- /todo.txt: -------------------------------------------------------------------------------- 1 | 1 verify R STRSXP to julia array is correct(done) 2 | 2 R array to Julia array (done) 3 | 3 R matrix to Julia matrix(done matrix is 2d array) 4 | 4 R dataframe to Julia dataframe(DataArray already done,Dataframe done,factor also done) 5 | 5 write more samples and docs (done by Martin Maechler) 6 | 6 R long vector to Julia array(long term becasue this need modify code heavily) 7 | 7 julia tuple to R list and R list to Julia tuple(done) 8 | 9 | 10 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: rjulia 2 | Type: Package 3 | Title: Integrating R and Julia -- Calling Julia from R 4 | Version: 0.9-4 5 | Date: 2015-08-01 6 | Author: Yu Gong [aut, cre], Oliver Keys [ctb], Martin Maechler [ctb] 7 | Maintainer: Yu Gong 8 | Description: An interface between R and Julia. It allows to run a script 9 | in julia from R, i.e., call Julia on R objects and provides object type 10 | mapping between R and Julia. 11 | SystemRequirements: Julia (including C headers [pkgs julia-dev (deb) / julia-devel (rpm)]), 12 | GNU make 13 | License: GPL-2 14 | Suggests: 15 | RUnit 16 | -------------------------------------------------------------------------------- /demo/testmdarray.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | 5 | f <- function(n) { 6 | stopifnot( n >= 1) 7 | for (i in 1:n) { 8 | ## pass R array to Julia 9 | x <- array(1.01:18.01, c(3,3,2)) 10 | 11 | st <- system.time({ 12 | ## pass R matrix to Julia 13 | r2j(x,"tt") 14 | ## and get it passed back from Julia 15 | y <- j2r("tt") 16 | }) 17 | cat("MD array (rank 3) passed to julia and back: ") 18 | stopifnot(identical(y, x)) 19 | cat(sprintf("[Ok]. Elapsed system.time(): %g\n", st[["elapsed"]])) 20 | } 21 | } 22 | 23 | f(1) 24 | #f(10) 25 | #xdd <- f(10000) 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/R_Julia.h: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | #ifndef JULIA_R_H 5 | #define JULIA_R_H 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #include 12 | #include 13 | 14 | //Convert R Type To Julia,which not contain NA 15 | SEXP R_Julia(SEXP Var, SEXP VarNam); 16 | //Convert R Type To Julia,which contain NA 17 | SEXP R_Julia_NA(SEXP Var, SEXP na, SEXP VarNam); 18 | //Convert R Type To Julia,which contain NA 19 | SEXP R_Julia_NA_Factor(SEXP Var, SEXP VarNam); 20 | //Convert R data frame To Julia 21 | SEXP R_Julia_NA_DataFrame(SEXP Var, SEXP na, SEXP VarNam); 22 | 23 | #ifdef __cplusplus 24 | } 25 | #endif 26 | #endif 27 | -------------------------------------------------------------------------------- /tests/run_unit_tests.R: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env Rscript 2 | ##### 3 | ##### A script to run tests on the rjulia package 4 | 5 | suppressMessages(library(rjulia)) 6 | suppressMessages(library(RUnit)) 7 | julia_init() 8 | 9 | testsuite.rjulia <- defineTestSuite("rjulia.test.suite", 10 | dirs = "unit", 11 | testFileRegexp = "^test_.+\\.R", 12 | testFuncRegexp = "^test_.+", 13 | rngKind = "default", 14 | rngNormalKind = "default") 15 | 16 | results <- capture.output(runTestSuite(testsuite.rjulia)) 17 | 18 | ## Finish up 19 | quit(runLast=FALSE) 20 | -------------------------------------------------------------------------------- /demo/testmatrix.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | julia_init() 3 | 4 | f <- function(n) { 5 | stopifnot(n >= 1) 6 | for (i in 1:n) { 7 | ## pass R double vector to Julia 8 | x <- matrix(1.01:6.01,3,2) 9 | r2j(x,"tt") 10 | y <- j2r("tt") 11 | cat("i=",i,"; Matrix, passed to Julia and back to R:\n", sep="") 12 | print(y) 13 | ## cat("run time is:",i,"\n") 14 | cat(" is equal to original R? ", paste(all.equal(x,y), collapse="\n "), "\n") 15 | } 16 | 17 | ## create 2d array in julia,get from R 18 | julia_void_eval("x = rand(2,2)") 19 | yy <- j2r("x") 20 | cat("Matrix from Julia's rand(2,2):\n") 21 | print(yy) 22 | } 23 | 24 | f(1) 25 | #f(10) 26 | #xdd <- f(10000) 27 | -------------------------------------------------------------------------------- /demo/testNAtype.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | ## needed for NA's (!) 5 | julia_void_eval("using DataArrays") 6 | ## ?? julia_void_eval("using DataArrays, DataFrames") 7 | 8 | x <- 1:10 9 | x[2] <- NA 10 | r2j(x,"ttt") 11 | y <- j2r("ttt[10]") 12 | y 13 | y <- j2r("ttt[2]") 14 | y 15 | y <- j2r("ttt") 16 | y 17 | 18 | x <- c(TRUE, NA, TRUE,TRUE,FALSE,FALSE,FALSE) 19 | r2j(x,"ttt") 20 | y <- j2r("ttt[3]") 21 | y 22 | y <- j2r("ttt[2]") 23 | y 24 | y <- j2r("ttt") 25 | y 26 | 27 | x <- 1.1:10.1 28 | x[2] <- NA 29 | r2j(x,"ttt") 30 | y <- j2r("ttt[10]") 31 | y 32 | y <- j2r("ttt[2]") 33 | y 34 | y <- j2r("ttt") 35 | y 36 | 37 | x <- c("x", NA, "z","u","v","w","a") 38 | r2j(x,"ttt") 39 | y <- j2r("ttt[3]") 40 | y 41 | y <- j2r("ttt[2]") 42 | y 43 | y <- j2r("ttt") 44 | y 45 | -------------------------------------------------------------------------------- /demo/testdataframe.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | 5 | jloaddf() 6 | 7 | y <- j2r('df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])') 8 | typeof(y) 9 | is.data.frame(y) 10 | y 11 | ## because julia data frame don't allow column name like R,so need change iris column name 12 | names(iris) <- c("sl","sw","pl","wl","speics") 13 | r2j(iris,"xx") 14 | y <- j2r("xx") 15 | y 16 | ## todo factor and pooldataarray 17 | 18 | y <- j2r('pdv = @pdata(["Group A", "Group A", "Group A","Group B", "Group B", "Group B"])') 19 | y 20 | y <- j2r('levels(pdv)') 21 | y 22 | y <- j2r('df = DataFrame(A = [1, 1, 1, 2, 2, 2],B = ["X", "X", "X", "Y", "Y", "Y"])') 23 | y 24 | y <- j2r('pool!(df, [:A, :B])') 25 | y <- j2r('df') 26 | y 27 | 28 | ## xx=DataFrame(Ssl =xxdfelt1,sw =xxdfelt2,pl =xxdfelt3,wl =xxdfelt4,NA =xxdfelt5) 29 | -------------------------------------------------------------------------------- /demo/testtuple.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | 5 | x <- 1:3 6 | x1 <- c("hello","world") 7 | y <- matrix(1:12,c(3,4)) 8 | z <- list(x,x1,y) 9 | 10 | r2j(z,"tupletest") 11 | y <- j2r("tupletest") 12 | y 13 | if(FALSE) ## FAILS, as y has 1d-arrays instead of vectors 14 | stopifnot(identical(y, z)) 15 | 16 | arr1d2vec <- function(a) { 17 | if(is.atomic(a)) { 18 | if(length(dim(a)) == 1) 19 | dim(a) <- NULL 20 | a 21 | } else if(is.list(a)) { 22 | lapply(a, arr1d2vec) 23 | } else 24 | stop("'a' not atomic or list, not yet supported") 25 | } 26 | stopifnot(identical(z, arr1d2vec(y))) 27 | 28 | zz <- list(x,x1,z, arr1d2vec(y)) 29 | r2j(zz,"tupletst2") 30 | yy <- j2r("tupletst2") 31 | stopifnot(identical(zz, arr1d2vec(yy))) 32 | 33 | #Julia Tuple to R list 34 | julia_eval("(3,)") 35 | julia_eval("(3,5)") 36 | 37 | ### List with *names* 38 | str(nz <- list(x=x, x1=x1, m = matrix(1:12, 3,4), A = array(1:24, dim=2:4))) 39 | r2j(nz, jnm <- "nmd_tupletst") 40 | nz2 <- j2r(jnm) 41 | str(nz2) ## list names are lost -- FIXME 42 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | # Emacs: treat me as -*- Makefile -*- 2 | # CRAN checks want non-GNU Makefiles 3 | # but MM cannot see a direct way -- we would need Makevars.in 4 | 5 | #julia -E find include file 6 | myjuliahome="abspath(JULIA_HOME)" 7 | ## Fails: it is not expanded at all when passed to gcc ! 8 | # juliabinpath=`julia -E $(myjuliahome)` 9 | # juliabinpath ::= $(juliabinpath) 10 | juliabinpath=$(shell julia -E $(myjuliahome)) 11 | juliabinpath:=$(strip $(juliabinpath)) 12 | 13 | 14 | #dev julia 15 | PKG_CPPFLAGS= -I$(juliabinpath)/../../src 16 | PKG_CPPFLAGS+= -I$(juliabinpath)/../../src/support 17 | #release julia 18 | PKG_CPPFLAGS+= -I$(juliabinpath)/../include 19 | PKG_CPPFLAGS+= -I$(juliabinpath)/../include/julia 20 | 21 | #define SWRLOCK 22 | PKG_CPPFLAGS+= -D_WIN32_WINNT=0x0600 23 | 24 | 25 | #use julia -E find libjulia.so path 26 | Libjulia="abspath(dirname(Libdl.dlpath(\"libjulia\")))" 27 | libjuliapath=$(shell julia -E $(Libjulia)) 28 | libjuliapath:=$(strip $(libjuliapath)) 29 | # libjuliapath = `julia -E $(Libjulia)` 30 | # libjuliapath ::= $(libjuliapath) 31 | # 32 | PKG_LIBS=-L$(libjuliapath) -ljulia 33 | 34 | -------------------------------------------------------------------------------- /src/dataframe.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "dataframe.h" 10 | 11 | //whether DataArrays and DataFrames packages loaded 12 | static int DataArrayFrameInited = 0; 13 | 14 | //try load julia DataArrays and DataFrames packages 15 | SEXP Julia_LoadDataArrayFrame() 16 | { 17 | jl_eval_string("using DataArrays,DataFrames"); 18 | if (jl_exception_occurred()) 19 | { 20 | jl_show(jl_stderr_obj(), jl_exception_occurred()); 21 | Rprintf("\n"); 22 | jl_exception_clear(); 23 | } 24 | else 25 | DataArrayFrameInited = 1; 26 | return R_NilValue; 27 | } 28 | 29 | //whether DataArrays and DataFrames packages loaded 30 | SEXP Julia_DataArrayFrameInited() 31 | { 32 | return ScalarLogical(DataArrayFrameInited); 33 | } 34 | 35 | //real function for load julia DataArrays and DataFrames packages 36 | bool LoadDF() 37 | { 38 | if (DataArrayFrameInited) 39 | return true; 40 | 41 | Julia_LoadDataArrayFrame(); 42 | if (!DataArrayFrameInited) 43 | { 44 | error("DataArrays and DataFrames can't be loaded correctly into Julia, please check this"); 45 | return false; 46 | } 47 | return true; 48 | } 49 | -------------------------------------------------------------------------------- /man/julia_eval.Rd: -------------------------------------------------------------------------------- 1 | \name{julia_eval} 2 | \title{Evaluate Julia Code or Get a Julia Variable} 3 | \alias{j2r} 4 | \alias{julia_eval} 5 | \alias{jDo} 6 | \alias{julia_void_eval} 7 | \description{ 8 | Evaluate Julia code from \R, or simply get a Julia variable into \R. 9 | 10 | Whereas \code{j2r()} is currently \emph{identical} to 11 | \code{julia_eval()}, 12 | \code{julia_void_eval()} will evaluate code in the running julia 13 | process \emph{without} returning a value. 14 | } 15 | \usage{ 16 | j2r (expression) # short for 17 | julia_eval (expression) 18 | 19 | jDo (expression) # short for 20 | julia_void_eval(expression) 21 | } 22 | \arguments{ 23 | \item{expression}{a \code{\link{character}} string.} 24 | } 25 | %% \details{ 26 | %% %% ~~ If necessary, more details than the description above ~~ 27 | %% } 28 | \value{ 29 | an \R object, translated from the corresponding Julia object to which 30 | \code{expression} evaluated. 31 | } 32 | %% \references{ 33 | %% } 34 | \seealso{ 35 | \code{\link{r2j}()} to \dQuote{send} \R objects to Julia. 36 | } 37 | \examples{ 38 | j2r("cos(pi * (1:7))") 39 | 40 | j2r("map(x -> x^2, (7,17,47))") # tuple in Julia ==> list (with no names!) in R 41 | 42 | j2r("rand(2,3)")# or rather use R's RNG 43 | } 44 | \keyword{interface} 45 | -------------------------------------------------------------------------------- /man/julia_init.Rd: -------------------------------------------------------------------------------- 1 | \name{julia_init} 2 | \title{Start Julia from R, properly initializing the R--Julia Interface} 3 | \alias{julia_init} 4 | \alias{isJuliaOk} 5 | \description{ 6 | Start Julia from \R, properly initializing the \R--Julia interface. 7 | } 8 | \usage{ 9 | julia_init(juliahome = "", disablegc = FALSE, parallel = TRUE) 10 | 11 | isJuliaOk() 12 | } 13 | \arguments{ 14 | \item{juliahome}{the home directory of the julia installation; should 15 | rarely be needed.} 16 | \item{disablegc}{logical indicating if garbage collection is 17 | % .... 18 | disabled.} 19 | \item{parallel}{logical indicating if Julia should be initialized to 20 | run several parallel processes.} 21 | } 22 | %% \details{ 23 | %% %% ~~ If necessary, more details than the description above ~~ 24 | %% } 25 | \value{ 26 | \code{julia_init()} returns \code{\link{NULL}} if successful, an error 27 | otherwise 28 | 29 | \code{isJuliaOk()} returns \code{\link{TRUE}} or \code{\link{FALSE}} 30 | (and should never give an error). 31 | } 32 | \seealso{ 33 | \code{\link{r2j}}, \code{\link{j2r}}, \code{\link{julia_eval}}. 34 | } 35 | \examples{ 36 | isJuliaOk() # TRUE, (almost ?) always if the 'rjulia' package has been loaded properly 37 | try( julia_init() ) # should work if julia is properly installed 38 | } 39 | \keyword{interface} 40 | -------------------------------------------------------------------------------- /man/jloaddf.Rd: -------------------------------------------------------------------------------- 1 | \name{jloaddf} 2 | \title{Loads the DataArray and DataFrame Julia Packages or Checks them} 3 | \alias{julia_LoadDataArrayFrame} 4 | \alias{julia_DataArrayFrameInited} 5 | \alias{jloaddf} 6 | \alias{jdfinited} 7 | \description{ 8 | \code{julia_LoadDataArrayFrame()} loads the \code{DataArray} and 9 | \code{DataFrames} julia packages, 10 | and 11 | \code{julia_DataArrayFrameInited()} checks if they have been loaded 12 | and work. 13 | 14 | \code{jloaddf} is identical to \code{julia_LoadDataArrayFrame}, and 15 | \code{jdfinited} is identical to \code{julia_DataArrayFrameInited}, 16 | just short forms for convenience. 17 | } 18 | \usage{ 19 | julia_LoadDataArrayFrame() 20 | jloaddf() 21 | 22 | julia_DataArrayFrameInited() 23 | jdfinited() 24 | } 25 | %% \details{ 26 | %% %% ~~ If necessary, more details than the description above ~~ 27 | %% } 28 | \value{ 29 | \code{julia_DataArrayFrameInited()} (and hence \code{jdfinited()}) 30 | return a \code{\link{logical}}, \code{TRUE} if the julia packages are there. 31 | 32 | %% FIXME the other: none (?) 33 | 34 | } 35 | \seealso{ 36 | \code{\link{julia_init}} 37 | } 38 | \examples{ 39 | julia_DataArrayFrameInited() # TRUE or FALSE in any case 40 | 41 | if(julia_DataArrayFrameInited()) 42 | julia_LoadDataArrayFrame() 43 | ## ^^^^^^^^^^^^^^^^^^^^^^^^^^ fails if not installed in Julia 44 | } 45 | \keyword{interface} 46 | -------------------------------------------------------------------------------- /demo/testcode.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | 5 | f <- function(n) { 6 | stopifnot( n >= 1 ) 7 | for (i in 1:n) 8 | { 9 | ## pass R double vector to Julia 10 | x <- 1.01:5.01 11 | r2j(x,"tt") 12 | ## get passed vector from Julia 13 | y <- j2r("tt") 14 | cat("float vector:",y,"\n") 15 | 16 | 17 | ## pass R int vector to Julia 18 | x <- 1:5 19 | r2j(x,"tt") 20 | ## get passed vector from Julia 21 | y <- j2r("tt") 22 | cat("int vector:",y,"\n") 23 | 24 | ## pass R int vector to Julia 25 | x <- c(TRUE,FALSE,TRUE) 26 | r2j(x,"ttt") 27 | yy <- j2r("ttt") 28 | cat("bool vector:",yy,"\n") 29 | 30 | 31 | x <- 1 32 | r2j(x,"ss") 33 | yy <- j2r("ss") 34 | cat("int :",yy,"\n") 35 | 36 | 37 | 38 | x <- 1.1 39 | r2j(x,"ss") 40 | yy <- j2r("ss") 41 | cat("float :",yy,"\n") 42 | 43 | 44 | x <- TRUE 45 | r2j(x,"ss") 46 | yy <- j2r("ss") 47 | cat("bool :",yy,"\n") 48 | 49 | 50 | ## pass string vector to julia,need to verify 51 | x <- c("tttt","xxxx") 52 | r2j(x,"sss") 53 | yy <- j2r("sss") 54 | cat("string vector :",yy,"\n") 55 | yy <- j2r("sss[1]") 56 | cat("string :",yy,"\n") 57 | 58 | ## pass string vector to julia,need to verify 59 | julia_void_eval('xx=["ttt","xxxx"]') 60 | y <- j2r("xx") 61 | cat("string vector:",y,"\n") 62 | y <- j2r("xx[1]") 63 | cat("string:",y,"\n") 64 | cat("run time is:",i,"\n") 65 | } 66 | } 67 | 68 | f(1) 69 | #f(10) 70 | #xdd <- f(10000) 71 | -------------------------------------------------------------------------------- /demo/testParallel.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | ## warning due to https://github.com/JuliaLang/julia/issues/10085, the rjulia master branch may crash when calling julia parallel functions on Julia 0.3.x. 5 | ## warning don't add too much procs in test 6 | ## otherwise it will crash on low end machine 7 | julia_eval("addprocs(3)") 8 | 9 | #julia 0.4 move distributed array from base library, so DistributedArrays need to be installed and loaded 10 | julia_void_eval("@everywhere using DistributedArrays") 11 | 12 | #demo rand on remote 13 | julia_void_eval(paste("r=remotecall(",2,", rand, 2, 2)",sep = "")) 14 | y <- j2r("fetch(r)") 15 | cat("\n") 16 | cat("process", 2, "got value:\n"); print(y) 17 | 18 | #simple distribute 19 | julia_void_eval('x=drand((100,100));') 20 | julia_void_eval('println(x.chunks); println(x.indexes)') 21 | julia_void_eval('println(typeof(x))') 22 | julia_void_eval('y=convert(Array,x);') 23 | y1<-j2r("y") 24 | y1[1:4] 25 | 26 | #demo DArray 27 | julia_void_eval('x=drand((100,100));') 28 | julia_void_eval('println(x.chunks); println(x.indexes)') 29 | julia_void_eval('println(typeof(x))') 30 | julia_void_eval('y=convert(Array,x);') 31 | y1<-j2r("y") 32 | y1[1:4] 33 | 34 | #demo PMAP 35 | julia_void_eval('x=[rand(100,100) for i=1:4];') 36 | julia_void_eval('z=pmap(sum, x)') 37 | julia_void_eval('println(typeof(z))') 38 | julia_void_eval('y=convert(Array{Float64},z);') 39 | y2<-j2r('y') 40 | y2 41 | 42 | #close workers 43 | julia_void_eval("rmprocs(workers())") 44 | -------------------------------------------------------------------------------- /man/r_julia.Rd: -------------------------------------------------------------------------------- 1 | \name{r_julia} 2 | \alias{r2j} 3 | \alias{r_julia} 4 | \title{Send R Objects to Julia} 5 | \description{ 6 | Send \R object \code{x} to julia, i.e., translate it to a corresponding julia 7 | object, and store that as \code{y}. 8 | } 9 | \usage{ 10 | r_julia(x, y) # or shorter 11 | r2j(x, y) 12 | } 13 | \arguments{ 14 | \item{x}{an \R object. Currently must fulfill certain properties to 15 | be translatable to Julia.} 16 | \item{y}{a \code{\link{character}} string; the variable name on the 17 | Julia side.} 18 | } 19 | %% \details{ 20 | %% %% ~~ If necessary, more details than the description above ~~ 21 | %% } 22 | \value{ 23 | on success, \code{\link{NULL}}, invisibly. 24 | } 25 | \seealso{ 26 | \code{\link{j2r}} aka \code{\link{julia_eval}} for the reverse of this. 27 | } 28 | \examples{ 29 | ## assign R's pi to Julia, as "Rpi" 30 | r2j(pi, "Rpi") 31 | j2r("pi") # Julia's builtin pi 32 | ## is there a difference 33 | j2r("Rpi - pi") # typically 0 34 | 35 | ## integer vector: 36 | r2j(1:10, "i10") 37 | j2r("i10") ; stopifnot(identical(1:10, j2r("i10"))) 38 | 39 | ## matrix, passed to Julia and got back 40 | m <- matrix(exp(-5:6), 3,4) 41 | r2j(m, "m") 42 | stopifnot(identical(m, j2r("m"))) 43 | 44 | ## complex -- not yet _FIXME_ 45 | z <- complex(modulus = 4, argument = pi*(0:16)/8) 46 | r2j(z, "z") # does *not* work ! but gives no error 47 | if(FALSE) 48 | stopifnot(identical(z, j2r("z"))) 49 | try( j2r( "z" ) )# -> "... undefined" 50 | } 51 | \keyword{interface} 52 | -------------------------------------------------------------------------------- /demo/testtype.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | ## uint 8 5 | y <- j2r("x=convert(Uint8,1)") 6 | y 7 | ## uint 16 8 | y <- j2r("x=convert(Uint16,1)") 9 | y 10 | ## uint 32 11 | y <- j2r("x=convert(Uint32,1)") 12 | y 13 | ## uint 64 14 | y <- j2r("x=convert(Uint64,1)") 15 | y 16 | ## int 8 17 | y <- j2r("x=convert(Int8,1)") 18 | y 19 | ## int 16 20 | y <- j2r("x=convert(Int16,1)") 21 | y 22 | ## int 32 23 | y <- j2r("x=convert(Int32,1)") 24 | y 25 | ## int 64 26 | y <- j2r("x=convert(Int64,1)") 27 | y 28 | ## float32 29 | y <- j2r("x=convert(Float32,1.01)") 30 | y 31 | ## float64 32 | y <- j2r("x=convert(Float64,1.01)") 33 | y 34 | 35 | ## vector 36 | ## uint 8 37 | x <- 1:10 38 | r2j(x,"tt") 39 | y <- j2r("x1=convert(Uint8,tt[1])") 40 | y <- j2r("x2=convert(Uint8,tt[2])") 41 | y <- j2r("x=[x1,x2]") 42 | y 43 | ## uint16 44 | y <- j2r("x1=convert(Uint16,tt[1])") 45 | y <- j2r("x2=convert(Uint16,tt[2])") 46 | y <- j2r("x=[x1,x2]") 47 | y 48 | ## uint 32 49 | y <- j2r("x1=convert(Uint32,tt[1])") 50 | y <- j2r("x2=convert(Uint32,tt[2])") 51 | y <- j2r("x=[x1,x2]") 52 | y 53 | ## uint 64 54 | y <- j2r("x1=convert(Uint64,tt[1])") 55 | y <- j2r("x2=convert(Uint64,tt[2])") 56 | y <- j2r("x=[x1,x2]") 57 | y 58 | ## int 8 59 | y <- j2r("x1=convert(Int8,tt[1])") 60 | y <- j2r("x2=convert(Int8,tt[2])") 61 | y <- j2r("x=[x1,x2]") 62 | y 63 | ## int 16 64 | y <- j2r("x1=convert(Int16,tt[1])") 65 | y <- j2r("x2=convert(Int16,tt[2])") 66 | y <- j2r("x=[x1,x2]") 67 | y 68 | ## int 32 69 | y <- j2r("x1=convert(Int32,tt[1])") 70 | y <- j2r("x2=convert(Int32,tt[2])") 71 | y <- j2r("x=[x1,x2]") 72 | y 73 | ## int 64 74 | y <- j2r("x1=convert(Int64,tt[1])") 75 | y <- j2r("x2=convert(Int64,tt[2])") 76 | y <- j2r("x=[x1,x2]") 77 | y 78 | 79 | x <- 1.1:10.1 80 | ## float32 81 | r2j(x,"tt") 82 | y <- j2r("x1=convert(Float32,tt[1])") 83 | y <- j2r("x2=convert(Float32,tt[2])") 84 | y <- j2r("x=[x1,x2]") 85 | y 86 | ## float64 87 | y <- j2r("x1=convert(Float64,tt[1])") 88 | y <- j2r("x2=convert(Float64,tt[2])") 89 | y <- j2r("x=[x1,x2]") 90 | y 91 | -------------------------------------------------------------------------------- /man/julia_BigintToDouble.Rd: -------------------------------------------------------------------------------- 1 | \name{julia_BigintToDouble} 2 | \alias{julia_BigintToDouble} 3 | \title{Option for Converting Julia Types Uint32, Int64, and Uint64 to R} 4 | \description{ 5 | We need to pay attention on the julia types \code{UInt32}, \code{Int64} 6 | and \code{UInt64} are mapped to \R. As the \code{\link{integer}} type 7 | in \R is (only) signed 32 bit, the above three types contain values out 8 | of \R's integer range. 9 | \code{julia_BigintToDouble()} allows to determine what happens when 10 | such variables are converted to \R objects. 11 | } 12 | \usage{ 13 | julia_BigintToDouble(mode = FALSE) 14 | } 15 | \arguments{ 16 | \item{mode}{\code{\link{logical}} indicating how to convert Uint32, 17 | Int64 and Uint64 julia objects to \R. If \code{mode} is true, convert to 18 | double. If it is false, the julia object will be converted to 19 | integer or double depending on the object's value. If all values of 20 | the object stay within the range of signed int32, then the object will be 21 | converted to integer, otherwise to double. The default \code{mode} 22 | is \code{FALSE}.} 23 | } 24 | %% \details{ 25 | %% %% ~~ If necessary, more details than the description above ~~ 26 | %% } 27 | %% \value{ 28 | %% } 29 | %% \references{ 30 | %% %% ~put references to the literature/web site here ~ 31 | %% } 32 | \seealso{ 33 | \code{\link{r2j}}, 34 | \code{\link{julia_eval}}. 35 | } 36 | \examples{ 37 | julia_BigintToDouble(TRUE) 38 | y <- j2r("jvar=convert(Uint64, 12)") 39 | julia_void_eval("println(typeof(jvar))") # UInt64 40 | str(y) # num 12 -- double ("TRUE" above) 41 | 42 | julia_BigintToDouble(FALSE) 43 | y <- j2r("jvar=convert(Uint64, 31)") 44 | julia_void_eval("println(typeof(jvar))") # UInt64 45 | str(y) # int 31 -- integer, not double ("FALSE" above) 46 | 47 | ## Show maximal values of the 64-bit integer types: 48 | y[1] <- j2r("jvar= convert(Uint64, typemax(Uint64))") 49 | y[2] <- j2r("jv2 = convert(Int64, typemax( Int64))") 50 | julia_void_eval("println(typeof(jvar),' ', typeof(jv2))") 51 | str(y) # num 1.84e+19 9.22e+18 52 | ## they are 2^64 and 2^63 respectively: 53 | stopifnot(log2(y) == 64:63) 54 | } 55 | \keyword{interface} 56 | -------------------------------------------------------------------------------- /src/embedding.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | //this file is for embeded julia to R 5 | #include 6 | #include 7 | #include 8 | #include "dataframe.h" 9 | #include "Julia_R.h" 10 | #include "R_Julia.h" 11 | 12 | #ifdef __cplusplus 13 | extern "C" { 14 | #endif 15 | 16 | static int jlrunning = 0; 17 | 18 | //function about whether embeded Julia is started 19 | //use static to avoid create many small object 20 | SEXP Julia_is_running() 21 | { 22 | static SEXP ans; 23 | if (ans==NULL) 24 | { 25 | ans = allocVector(LGLSXP, 1); 26 | R_PreserveObject(ans); 27 | } 28 | LOGICAL(ans)[0] = jlrunning; 29 | return ans; 30 | } 31 | 32 | //function about init embeded Julia instance 33 | //julia_home shoud be the directy of julia execute file 34 | //DisableGC determine whether the Julia garbage collector is to be enabled or not 35 | SEXP initJulia(SEXP julia_home, SEXP DisableGC) 36 | { 37 | if (jl_is_initialized()) 38 | return R_NilValue; 39 | const char *s = CHAR(asChar(julia_home)); 40 | if (strlen((char *)s) == 0) 41 | jl_init(NULL); 42 | else 43 | jl_init((char *)s); 44 | 45 | jlrunning = 1; 46 | if (jl_exception_occurred()) 47 | { 48 | error("Julia not initialized"); 49 | jlrunning = 0; 50 | return R_NilValue; 51 | } 52 | if (asLogical(DisableGC)) 53 | jl_gc_enable(0); 54 | return R_NilValue; 55 | } 56 | 57 | //eval julia srcipt, but not return val 58 | SEXP jl_void_eval(SEXP cmd) 59 | { 60 | const char *s = CHAR(asChar(cmd)); 61 | jl_eval_string((char *)s); 62 | if (jl_exception_occurred()) 63 | { 64 | jl_show(jl_stderr_obj(), jl_exception_occurred()); 65 | Rprintf("\n"); 66 | jl_exception_clear(); 67 | } 68 | return R_NilValue; 69 | } 70 | 71 | //eval julia script and return 72 | SEXP jl_eval(SEXP cmd) 73 | { 74 | const char *s = CHAR(asChar(cmd)); 75 | jl_value_t *ret = jl_eval_string((char *)s); 76 | if (jl_exception_occurred()) 77 | { 78 | jl_show(jl_stderr_obj(), jl_exception_occurred()); 79 | Rprintf("\n"); 80 | jl_exception_clear(); 81 | return R_NilValue; 82 | } 83 | return Julia_R(ret); 84 | } 85 | 86 | #ifdef __cplusplus 87 | } 88 | #endif 89 | -------------------------------------------------------------------------------- /man/rjulia-package.Rd: -------------------------------------------------------------------------------- 1 | \name{rjulia-package} 2 | \alias{rjulia-package} 3 | \alias{rjulia} 4 | \docType{package} 5 | \title{rjulia helps integrating R and Julia by calling Julia from R} 6 | \description{ 7 | RJulia (R package name \pkg{rjulia}) provides an interface between \R 8 | and Julia by converting \R and Julia objects mutually, and running 9 | Julia scripts from \R. 10 | 11 | \R is a sophisticated feature-rich statistical software but a bit 12 | slow, julia is new advanced computing language which is fast and 13 | LLVM-based JIT. So, combining \R and julia will allow us to do better 14 | statistical computing. 15 | } 16 | \details{ 17 | \tabular{ll}{ 18 | Package: \tab rjulia\cr 19 | Type: \tab Package\cr 20 | Version: \tab 1.0\cr 21 | %% Date: \tab 2015-07-02\cr -- don't want to update all the time 22 | License: \tab GPL 2\cr 23 | } 24 | 25 | TODO: 26 | An overview of how to use the package, including the most important functions. 27 | } 28 | \author{Yu Gong \email{armgong@yahoo.com} 29 | } 30 | \references{ 31 | Online Julia Documentation, at \url{http://docs.julialang.org}. 32 | } 33 | \seealso{ 34 | \code{\link{j2r}}, \code{\link{r2j}}; further 35 | \code{\link{julia_init}}, \code{\link{julia_eval}}, 36 | } 37 | \examples{ 38 | (cc <- j2r( "cos(pi * (0 : 0.5 : 4))")) 39 | all.equal(cc, cos(pi * seq(0,4, by=0.5))) # TRUE indeed 40 | 41 | j2r("float(1//2 + 2//3)") # Julia knows rationals numbers, i.e., ratios of integers 42 | 43 | ## Julia has builtin "Bigfloat" data type with 256 bits precision: 44 | (pi. <- j2r("string(big(pi))")) 45 | 46 | ## if you really have problems getting R to call Julia, try ... 47 | 48 | if(is(T1 <- tryCatch(julia_init(), error=function(e)e), "error")) { 49 | ## try harder 50 | juliaDIR <- dirname(system("which julia", intern=TRUE)) 51 | message("Trying Julia directory ", juliaDIR) 52 | if(is(T2 <- tryCatch(julia_init(juliaDIR), error=function(e)e), "error")) { 53 | ## TODO: show error messages of T1 and T2 54 | warning("Did not succeed to initialize Rjulia with correct julia directory yet") 55 | } 56 | else { 57 | message(" Success !!") 58 | julia_eval("1+1") 59 | ## julia_eval("2^20") 60 | } 61 | } 62 | } 63 | \keyword{package} 64 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | rjulia 2 | =============== 3 | 4 | rjulia provides an interface between R and Julia. It allows a user to run a script in Julia from R, and maps objects between the two languages. 5 | 6 | It currently supports use on Linux and Windows (both R and RGUI), but build on Windows only for advance users. 7 | 8 | Installing 9 | ------------- 10 | 11 | 1. Install julia v0.5 and R version >=3.1.0. 12 | 13 | 2. Add `/bin` to your system PATH variable if needed. 14 | 15 | 3. Install the rjulia package. If you're using the v0.4 branch of julia, use the "julia0.4" branch of rjulia. 16 | 17 | You can install rjulia on Linux using the devtools package: 18 | 19 | ```r 20 | install.packages("devtools") #if not already installed 21 | devtools::install_github("armgong/rjulia", ref="julia0.5")# or ref="julia0.4" if using Julia v0.5 22 | ``` 23 | You can install rjulia on Windows using the Rtools and devtools package : 24 | 25 | ```r 26 | install.packages("devtools") #if not already installed 27 | devtools::install_github("armgong/rjulia", ref="master", args = "--no-multiarch")# or ref="0.3" if using Julia v0.3 28 | ``` 29 | 30 | 4. If you want to be able to use R or Julia objects that contain NA values or factors or data frames, the Julia packages `DataArrays` and `DataFrames` must be installed. 31 | 32 | Simple example 33 | ------------- 34 | 35 | ```r 36 | library(rjulia) 37 | julia_init() #**(will auto find your julia home)** 38 | julia_eval("1+1") 39 | ``` 40 | 41 | Demo 42 | ------------- 43 | 44 | Please see the `*.R` files in the `demo/` directory, or use 45 | ```r 46 | demo(package = "rjulia") 47 | ``` 48 | 49 | 50 | Docs 51 | ------------- 52 | Help files are now done, mostly with examples. 53 | 54 | 55 | Know Problems 56 | ------------- 57 | * The Julia api rapidly changes between releases. Each time you upgrade or downgrade Julia, rjulia needs to be recompiled and reinstalled, e.g. with `devtools::install_github`. 58 | 59 | * Due to RStudio issue (https://github.com/armgong/rjulia/issues/16), when using rjulia on Windows 64bit, RStudio-0.98.1103 is recommended http://download1.rstudio.org/RStudio-0.98.1103.zip . 60 | * Due to gcc toolchain issue , when using rjulia on Windows, it will crash R, to solve this, download unoffical build julia from https://github.com/armgong/julia-64-build-with-mingw-builds-for-R . 61 | 62 | 63 | 64 | -------------------------------------------------------------------------------- /tests/unit/test_roundtrip.R: -------------------------------------------------------------------------------- 1 | 2 | ### Test sending data from R to julia and back again 3 | 4 | library(RUnit) 5 | library(rjulia) 6 | julia_init(disablegc=FALSE) 7 | 8 | ## logical, numeric, and character with "e" fails 9 | ## logical or character with "f" fails. Logical or character have loop rather than memcpy in R_Julia_MD. 10 | 11 | ## Send data of each atomic type to julia and back again 12 | ## With and without NAs 13 | ## Test that the roundtrip returns the same value 14 | test_roundtrip <- function() { 15 | test.list = list( 16 | a = 0:5, 17 | b = matrix(0:5, ncol=2), 18 | c = array( c(0:8), dim=c(2, 2, 2)), 19 | d = c(NA_integer_, 0:4), 20 | e = matrix(c(0:4, NA_integer_), ncol=2), 21 | f = array( c(0:7, NA_integer_), dim=c(2, 2, 2)) 22 | ) 23 | 24 | types = c("integer", "logical", "numeric", "character") 25 | 26 | ## Vectors, matrices and arrays 27 | mapply( 28 | names(test.list), test.list, 29 | FUN=function(k, v) { 30 | lapply( 31 | types, 32 | function(x) { 33 | message(x, ": ", k) 34 | newv = as(v, x) 35 | r2j(newv, k) 36 | checkIdentical( newv, j2r(k) ) 37 | }) 38 | }) 39 | ## Factors 40 | mapply( 41 | names(test.list), test.list, 42 | FUN=function(k, v) { 43 | message("factor: ", k) 44 | newv = as.factor(v) 45 | r2j(newv, k) 46 | checkIdentical( newv, j2r(k) ) 47 | }) 48 | 49 | ## Lists and data.frames 50 | lists = list( 51 | h = list( 1:5, letters[1:5] ), 52 | j = list( c(NA, 2:5), letters[1:5] ) 53 | ) 54 | mapply(names(lists), lists, 55 | FUN=function(k, v) { 56 | message("list: ", k) 57 | r2j(v, k) 58 | checkIdentical( v, j2r(k) ) 59 | message("data.frame w.o. factors: ", k) 60 | names(v) = letters[1:length(v)] 61 | newv = as.data.frame(v, stringsAsFactors=FALSE) 62 | r2j(newv, k) 63 | checkIdentical( newv, j2r(k) ) 64 | message("data.frame w. factors: ", k) 65 | names(v) = letters[1:length(k)] 66 | newv = as.data.frame(v, stringsAsFactors=TRUE) 67 | r2j(newv, k) 68 | checkIdentical( newv, j2r(k) ) 69 | }) 70 | 71 | } 72 | 73 | ## Repeated run r2j and j2r, can detect 'random' segfaults 74 | test_stress_roundtrip <- function() { 75 | for (i in 1:100) { 76 | test_roundtrip() 77 | } 78 | TRUE 79 | } 80 | -------------------------------------------------------------------------------- /R/rjulia.R: -------------------------------------------------------------------------------- 1 | ## Initialise Julia 2 | julia_init <- function(juliahome="", disablegc = FALSE, parallel = TRUE) 3 | { 4 | ## Check Julia exists on the system. If it doesn't, stop immediately. 5 | juliabindir <- if (nzchar(juliahome)) juliahome else { 6 | gsub("\"", "", system('julia -E JULIA_HOME', intern=TRUE)) 7 | } 8 | ## Otherwise, initialise Julia using the provided home directory. 9 | .Call("initJulia", juliabindir, disablegc, PACKAGE = "rjulia") 10 | 11 | ## If on Windows, run a specific push to compensate for R not handling pkg.dir() correctly. 12 | julia_void_eval('@static if is_windows() push!(LOAD_PATH,joinpath(string(ENV["HOMEDRIVE"],ENV["HOMEPATH"]),".julia",string("v",VERSION.major,".",VERSION.minor))) end') 13 | julia_void_eval('@static if is_windows() ENV["HOME"]=joinpath(string(ENV["HOMEDRIVE"],ENV["HOMEPATH"])) end') 14 | 15 | jloaddf() 16 | 17 | if (julia_eval('VERSION < v"0.5.0"')) 18 | stop("Julia version must be 0.5 or higher.") 19 | 20 | return(invisible(TRUE)) 21 | } 22 | 23 | ######### From: rjulia2 24 | 25 | cstrnull<-function(orgstr) 26 | { 27 | return (c(charToRaw(orgstr),as.raw(0))) 28 | } 29 | 30 | ccall<-function(fname,cmdstr) 31 | { 32 | functionsym<-getNativeSymbolInfo(fname) 33 | invisible(.C(functionsym,cstrnull(cmdstr))) 34 | } 35 | 36 | 37 | .julia_init_if_necessary <- function() { 38 | if (!.isJuliaOk) { 39 | message("Julia not yet running. Calling julia_init() ...") 40 | julia_init() 41 | if (!.isJuliaOk) 42 | stop("Julia *still* not running. Giving up.") 43 | else 44 | message("julia_init complete successfully") 45 | } 46 | } 47 | 48 | jDo<-julia_void_eval<-julia_eval<-function(cmdstr) { 49 | .julia_init_if_necessary() 50 | #first clear julia exception 51 | ccall("jl_eval_string",'ccall(:jl_exception_clear,Void,());') 52 | #second eval julia expression 53 | ccall("jl_eval_string",cmdstr) 54 | #then,try catch and show julia execption 55 | ccall("jl_eval_string", 56 | 'if ccall(:jl_exception_occurred,Ptr{Void},())!=C_NULL 57 | rjuliaexception=ccall(:jl_exception_occurred,Any,()); 58 | showerror(STDERR,rjuliaexception); 59 | println(""); 60 | ccall(:jl_exception_clear,Void,()); 61 | end') 62 | } 63 | 64 | Init<-julia_init <- function(juliahome="") 65 | { 66 | ##force change HOME env variable in R, R change HOME to c:\user\username\Documents 67 | ##but on window 7+ this should be c:\user\username, and it not change it, julia could not 68 | ##find its package and compiled package, so let us change it 69 | if (Sys.info()[['sysname']]=="Windows") 70 | { 71 | Sys.setenv(HOME=paste0(Sys.getenv("HOMEDRIVE"),Sys.getenv("HOMEPATH"))) 72 | } 73 | 74 | juliabindir <- if (nchar(juliahome) > 0) juliahome else { 75 | gsub("\"", "", 76 | system('julia -E JULIA_HOME', 77 | intern=TRUE)) 78 | } 79 | ccall("jl_init",juliabindir) 80 | .isJuliaOk<<-T 81 | ## If on Windows, run a specific push to compensate for R not handling pkg.dir() correctly. 82 | ##jDo('@windows_only 83 | ##push!(LOAD_PATH,joinpath(string(ENV["HOMEDRIVE"],ENV["HOMEPATH"]),".julia",string("v",VERSION.major,".",VERSION.minor)))') 84 | ##jDo('@windows_only ENV["HOME"]=joinpath(string(ENV["HOMEDRIVE"],ENV["HOMEPATH"]))') 85 | ## Loading julia packages 86 | jDo("using DataFrames") 87 | jDo("using RCall") 88 | } 89 | 90 | 91 | ########## End: from rjulia2 92 | 93 | j2r <- julia_eval <- function(expression) 94 | { 95 | .julia_init_if_necessary() 96 | ## Evaluate the expression and return the results of that evaluation. 97 | .Call("jl_eval", expression, PACKAGE="rjulia") 98 | } 99 | 100 | r2j <- r_julia <- function(x,y) 101 | { 102 | .julia_init_if_necessary() 103 | 104 | if (is.vector(x) || is.array(x)) { # Covers list and matrix too 105 | 106 | if (anyNA(x)) { 107 | na = is.na(x) 108 | invisible(.Call("R_Julia_NA", x, na, y, PACKAGE="rjulia")) 109 | } else { 110 | invisible(.Call("R_Julia", x, y, PACKAGE="rjulia")) 111 | } 112 | } else if (is.data.frame(x)) { 113 | na = lapply(x, is.na) 114 | if (is.null(names(x))) { 115 | names(x) = as.character(seq_len(length(x))) 116 | } 117 | invisible(.Call("R_Julia_NA_DataFrame", x, na, y, PACKAGE="rjulia")) 118 | } else if (is.factor(x)) { 119 | invisible(.Call("R_Julia_NA_Factor", x, y, PACKAGE="rjulia")) 120 | } else { 121 | warning("rjulia supports only vector, matrix, array, list(withoug NAs), factor and data frames (with simple string, int, float, logical) classes") 122 | } 123 | } 124 | 125 | jdfinited <- julia_DataArrayFrameInited <- function() 126 | { 127 | .Call("Julia_DataArrayFrameInited", PACKAGE="rjulia") 128 | } 129 | 130 | jloaddf <- julia_LoadDataArrayFrame <- function() 131 | { 132 | .julia_init_if_necessary() 133 | 134 | invisible(.Call("Julia_LoadDataArrayFrame", PACKAGE="rjulia")) 135 | if (!julia_DataArrayFrameInited()) warning( 136 | "DataArray and DataFrame Julia packages have not been loaded. 137 | Please install or check installation directory.") 138 | } 139 | 140 | 141 | julia_BigintToDouble <- function(mode = FALSE) 142 | { 143 | invisible(.Call("Julia_BigintToDouble", mode, PACKAGE="rjulia")) 144 | } 145 | 146 | ### MM: (ess-set-style 'DEFAULT) ==> only indent by 2 147 | ## Local Variables: 148 | ## eval: (ess-set-style 'DEFAULT 'quiet) 149 | ## delete-old-versions: never 150 | ## End: 151 | -------------------------------------------------------------------------------- /tests/stresstest.R: -------------------------------------------------------------------------------- 1 | library(rjulia) 2 | 3 | julia_init() 4 | ## ## init embedding julia,paraments are julia_home and disable_gc 5 | ## if(.Platform$OS.type == "unix") julia_init("/usr/bin",F,T) else 6 | ## { 7 | ## if (.Platform$r_arch=="x64") 8 | ## {julia_init("c:/julia/64/bin",F,T)} 9 | ## else 10 | ## {julia_init("c:/julia/32/bin",F,T)} 11 | ## } 12 | 13 | ## load Julia DataFrames and DataArrays -- with care 14 | T <- tryCatch(julia_void_eval("using DataArrays,DataFrames"), 15 | error = function(e) e) 16 | ## MM [2015-02-04, lynne]: 17 | ## LoadError("/u/maechler/.julia/v0.3/DataArrays/src/DataArrays.jl",59,LoadError("/u/maechler/.julia/v0.3/DataArrays/src/abstractdataarray.jl",5,UndefVarError(:StoredArray))) 18 | okDF <- !inherits(T, "error") 19 | 20 | 21 | f <- function(n) 22 | { 23 | stopifnot(n >= 1) 24 | for (i in 1:n) { 25 | ## pass R double vector to Julia 26 | x <- 1.01:5.01 27 | r2j(x,"tt") 28 | ## get passed vector from Julia 29 | y <- j2r("tt") 30 | cat("float vector:",y,"\n") 31 | 32 | 33 | ## pass R int vector to Julia 34 | x <- 1:5 35 | r2j(x,"tt") 36 | ## get passed vector from Julia 37 | y <- j2r("tt") 38 | cat("int vector:",y,"\n") 39 | 40 | ## pass R int vector to Julia 41 | x <- c(TRUE,FALSE,TRUE) 42 | r2j(x,"ttt") 43 | yy <- j2r("ttt") 44 | cat("bool vector:",yy,"\n") 45 | 46 | x <- 1 47 | r2j(x,"ss") 48 | yy <- j2r("ss") 49 | cat("int :",yy,"\n") 50 | 51 | x <- 1.1 52 | r2j(x,"ss") 53 | yy <- j2r("ss") 54 | cat("float :",yy,"\n") 55 | 56 | x <- TRUE 57 | r2j(x,"ss") 58 | yy <- j2r("ss") 59 | cat("bool :",yy,"\n") 60 | 61 | ## pass string vector to julia,need to verify 62 | x <- c("tttt","xxxx") 63 | r2j(x,"sss") 64 | yy <- j2r("sss") 65 | cat("string vector :",yy,"\n") 66 | yy <- j2r("sss[1]") 67 | cat("string :",yy,"\n") 68 | 69 | ## pass string vector to julia,need to verify 70 | julia_void_eval('xx=["ttt","xxxx"]') 71 | y <- j2r("xx") 72 | cat("string vector:",y,"\n") 73 | y <- j2r("xx[1]") 74 | cat("string:",y,"\n") 75 | cat("run time is:",i,"\n") 76 | } 77 | } 78 | f(1) 79 | f(10) 80 | xdd <- f(10000) 81 | 82 | f2 <- function(n) 83 | { 84 | stopifnot(n >= 1) 85 | for (i in 1:n) { 86 | x <- matrix(1.01:6.01, 3,2) 87 | st <- system.time({ 88 | ## pass R matrix to Julia 89 | r2j(x,"tt") 90 | ## and get it passed back from Julia 91 | y <- j2r("tt") 92 | }) 93 | cat("Matrix passed to julia and back: ") 94 | stopifnot(identical(y, x)) 95 | cat(sprintf("[Ok]. Elapsed system.time(): %g\n", st[["elapsed"]])) 96 | } 97 | ## 98 | ## create 2d array in julia,get from R 99 | julia_void_eval("x = rand(2,2)") 100 | yy <- j2r("x") 101 | cat("rand(2,2) matrix:\n") 102 | print(yy) 103 | } ## end{f2} 104 | 105 | f2(1) 106 | f2(10) 107 | ## !!!! If I interrupt the following, R is taken down !!! BUG !!! 108 | xdd <- f2(10000) 109 | 110 | f3 <- function(n) { 111 | stopifnot(n >= 1) 112 | for (i in 1:n) 113 | { 114 | ## pass R double vector to Julia 115 | x <- array(1.01:18.01,c(3,3,2)) 116 | r2j(x,"tt") 117 | y <- j2r("tt") 118 | cat("MD array:","\n") 119 | print(y) 120 | cat("run times is:",i,"\n") 121 | } 122 | } 123 | f3(1) 124 | f3(10) 125 | xdd <- f3(10000) 126 | cat("clear R Object begin\n") 127 | rm(list = ls()) 128 | cat("clear R Object Finish\n") 129 | 130 | for (i in 1:1) 131 | { 132 | x <- 1:10 133 | x[2] <- NA 134 | r2j(x,"ttt") 135 | y <- j2r("ttt[10]") 136 | 137 | y <- j2r("ttt[2]") 138 | 139 | y <- j2r("ttt") 140 | 141 | x <- c(TRUE,FALSE,TRUE,TRUE,FALSE,FALSE,FALSE) 142 | x[2] <- NA 143 | r2j(x,"ttt") 144 | y <- j2r("ttt[3]") 145 | 146 | y <- j2r("ttt[2]") 147 | 148 | y <- j2r("ttt") 149 | 150 | 151 | 152 | x <- 1.1:10.1 153 | x[2] <- NA 154 | r2j(x,"ttt") 155 | y <- j2r("ttt[10]") 156 | y <- j2r("ttt[2]") 157 | y <- j2r("ttt") 158 | 159 | 160 | x <- c("x", NA, "z","u","v","w","a") 161 | r2j(x,"ttt") 162 | y <- j2r("ttt[3]") 163 | 164 | y <- j2r("ttt[2]") 165 | 166 | y <- j2r("ttt") 167 | 168 | x <- matrix(1:9, 3,3) 169 | x[c(1,5,8)] <- NA 170 | x 171 | r2j(x,"xy") 172 | y <- j2r("xy") 173 | 174 | y <- j2r("length(xy)") 175 | 176 | y <- j2r("length(xy.na)") 177 | 178 | y <- j2r("length(xy.data)") 179 | 180 | 181 | x <- 1:3 182 | x1 <- c("hello","world") 183 | y <- matrix(1:12, 3,4) 184 | z <- list(x,x1,y) 185 | r2j(z,"tupletest") 186 | y <- j2r("tupletest") 187 | 188 | 189 | zz <- list(x,x1,y,z) 190 | r2j(zz,"tupletest") 191 | y <- j2r("tupletest") 192 | 193 | ## uint 8 194 | y <- j2r("x=convert(Uint8,1)") 195 | 196 | ## uint 16 197 | y <- j2r("x=convert(Uint16,1)") 198 | 199 | ## uint 32 200 | y <- j2r("x=convert(Uint32,1)") 201 | 202 | ## uint 64 203 | y <- j2r("x=convert(Uint64,1)") 204 | 205 | ## int 8 206 | y <- j2r("x=convert(Int8,1)") 207 | 208 | ## int 16 209 | y <- j2r("x=convert(Int16,1)") 210 | 211 | ## int 32 212 | y <- j2r("x=convert(Int32,1)") 213 | 214 | ## int 64 215 | y <- j2r("x=convert(Int64,1)") 216 | 217 | ## float32 218 | y <- j2r("x=convert(Float32,1.01)") 219 | 220 | ## float64 221 | y <- j2r("x=convert(Float64,1.01)") 222 | 223 | 224 | ## vector 225 | ## uint 8 226 | x <- 1:10 227 | r2j(x,"tt") 228 | y <- j2r("x1=convert(Uint8,tt[1])") 229 | y <- j2r("x2=convert(Uint8,tt[2])") 230 | y <- j2r("x=[x1,x2]") 231 | ## uint16 232 | y <- j2r("x1=convert(Uint16,tt[1])") 233 | y <- j2r("x2=convert(Uint16,tt[2])") 234 | y <- j2r("x=[x1,x2]") 235 | 236 | ## uint 32 237 | y <- j2r("x1=convert(Uint32,tt[1])") 238 | y <- j2r("x2=convert(Uint32,tt[2])") 239 | y <- j2r("x=[x1,x2]") 240 | 241 | ## uint 64 242 | y <- j2r("x1=convert(Uint64,tt[1])") 243 | y <- j2r("x2=convert(Uint64,tt[2])") 244 | y <- j2r("x=[x1,x2]") 245 | ## int 8 246 | y <- j2r("x1=convert(Int8,tt[1])") 247 | y <- j2r("x2=convert(Int8,tt[2])") 248 | y <- j2r("x=[x1,x2]") 249 | 250 | ## int 16 251 | y <- j2r("x1=convert(Int16,tt[1])") 252 | y <- j2r("x2=convert(Int16,tt[2])") 253 | y <- j2r("x=[x1,x2]") 254 | 255 | ## int 32 256 | y <- j2r("x1=convert(Int32,tt[1])") 257 | y <- j2r("x2=convert(Int32,tt[2])") 258 | y <- j2r("x=[x1,x2]") 259 | 260 | ## int 64 261 | y <- j2r("x1=convert(Int64,tt[1])") 262 | y <- j2r("x2=convert(Int64,tt[2])") 263 | y <- j2r("x=[x1,x2]") 264 | 265 | 266 | x <- 1.1:10.1 267 | ## float32 268 | r2j(x,"tt") 269 | y <- j2r("x1=convert(Float32,tt[1])") 270 | y <- j2r("x2=convert(Float32,tt[2])") 271 | y <- j2r("x=[x1,x2]") 272 | 273 | ## float64 274 | y <- j2r("x1=convert(Float64,tt[1])") 275 | y <- j2r("x2=convert(Float64,tt[2])") 276 | y <- j2r("x=[x1,x2]") 277 | 278 | y <- j2r('df = DataFrame(A = 1:4, B = ["M", "F", "F", "M"])') 279 | typeof(y) 280 | is.data.frame(y) 281 | ## todo factor and pooldataarray 282 | 283 | y <- j2r('pdv = @pdata(["Group A", "Group A", "Group A","Group B", "Group B", "Group B"])') 284 | y <- j2r('levels(pdv)') 285 | y <- j2r('df = DataFrame(A = [1, 1, 1, 2, 2, 2],B = ["X", "X", "X", "Y", "Y", "Y"])') 286 | y <- j2r('pool!(df, [:A, :B])') 287 | y <- j2r('df') 288 | julia_void_eval("df=0;") 289 | names(iris) <- c("sl","sw","pl","wl","speics") 290 | r2j(iris,"xx") 291 | y <- j2r("xx") 292 | julia_void_eval("xx=0;") 293 | 294 | cat("run time is:",i,"\n") 295 | 296 | cat("clear R Object begin\n") 297 | rm(list = ls()) 298 | cat("clear R Object Finish\n") 299 | } 300 | 301 | ## warning don't add too much procs in test 302 | ## otherwise it will crash on low end machine 303 | ## warning due to https://github.com/JuliaLang/julia/issues/10085, the rjulia master branch may crash when calling julia parallel functions on Julia 0.3.x. 304 | 305 | julia_void_eval("addprocs(1)") 306 | 307 | julia_void_eval(paste("r=remotecall(",2,", rand, 2, 2)",sep = "")) 308 | y <- j2r(" fetch(r)") 309 | cat("\n") 310 | cat(paste("process ",2," get value:\n",sep = "")) 311 | print(y) 312 | 313 | julia_void_eval("rmprocs(workers())") 314 | 315 | -------------------------------------------------------------------------------- /src/R_Julia.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | 5 | //this file is for conver R object to julia 6 | #include 7 | #include 8 | #include 9 | #include 10 | #define USE_RINTERNALS 11 | #include 12 | #include 13 | #include 14 | #include "dataframe.h" 15 | #include "R_Julia.h" 16 | #define pkgdebug 17 | 18 | // Handle and report exception 19 | static int rjulia_exception_occurred() { 20 | if (jl_exception_occurred()) { 21 | jl_show(jl_stderr_obj(), jl_exception_occurred()); 22 | Rprintf("\n"); 23 | jl_exception_clear(); 24 | return(1); 25 | } else { 26 | return(0); 27 | } 28 | } 29 | 30 | //convert R SEXP dims to julia tuple 31 | static jl_value_t *RDims_JuliaTuple(SEXP Var) 32 | { 33 | SEXP dims = getAttrib(Var, R_DimSymbol); 34 | char evalcmd[evalsize]; 35 | char eltcmd[eltsize]; 36 | snprintf(evalcmd, evalsize, "%s","("); 37 | int ndims = LENGTH(dims); 38 | for (size_t i = 0; i < ndims; i++) 39 | { 40 | snprintf(eltcmd,eltsize,"%d,",INTEGER(dims)[i]); 41 | strcat(evalcmd,eltcmd); 42 | } 43 | strcat(evalcmd,")"); 44 | return jl_eval_string(evalcmd); 45 | } 46 | 47 | //create an Array in julia 48 | static jl_array_t* CreateArray(jl_datatype_t *type, size_t ndim, jl_value_t *dims) 49 | { 50 | return jl_new_array(jl_apply_array_type(type, ndim), dims);; 51 | } 52 | 53 | // Pick type for array element 54 | static jl_datatype_t* ElementType(SEXP Var) { 55 | jl_datatype_t *eltype = jl_any_type; 56 | switch (TYPEOF(Var)) 57 | { 58 | case LGLSXP: 59 | { 60 | eltype = jl_bool_type; 61 | break; 62 | }; 63 | case INTSXP: 64 | { 65 | eltype = jl_int32_type; 66 | break; 67 | } 68 | case REALSXP: 69 | { 70 | eltype = jl_float64_type; 71 | break; 72 | } 73 | case STRSXP: 74 | { 75 | eltype = jl_string_type; 76 | } 77 | } 78 | return(eltype); 79 | } 80 | 81 | // Alternate array creator starting from R SEXP 82 | static jl_array_t* NewArray(SEXP Var) { 83 | jl_datatype_t *eltype = ElementType(Var); 84 | if (isMatrix(Var)) { 85 | jl_value_t* array_type = jl_apply_array_type(eltype, 2); 86 | return jl_alloc_array_2d(array_type, nrows(Var), ncols(Var)); 87 | } else if (isArray(Var)) { 88 | jl_value_t *dims = RDims_JuliaTuple(Var); 89 | return CreateArray(eltype, jl_nfields(dims), dims); 90 | } else { // isVector and isVectorAtomic do not mean what one would expect 91 | jl_value_t* array_type = jl_apply_array_type(eltype, 1); 92 | return jl_alloc_array_1d(array_type, LENGTH(Var)); 93 | } 94 | } 95 | 96 | //convert R object to julia object 97 | //Var is R object 98 | static jl_array_t *R_Julia_MD(SEXP Var) 99 | { 100 | jl_array_t *ret = NewArray(Var); 101 | JL_GC_PUSH1(&ret); 102 | switch (TYPEOF(Var)) 103 | { 104 | case LGLSXP: 105 | { 106 | char *retData = (char *)jl_array_data(ret); 107 | int *var_p = LOGICAL(Var); 108 | for (size_t i = 0; i < jl_array_len(ret); i++) // Can not be memcpy because we need to cast from int32 to int8 109 | retData[i] = (char)var_p[i]; // No write barrier, right? 110 | break; 111 | }; 112 | case INTSXP: 113 | { 114 | int *retData = (int *)jl_array_data(ret); 115 | memcpy(retData, INTEGER(Var), jl_array_len(ret) * sizeof(int)); 116 | break; 117 | } 118 | case REALSXP: 119 | { 120 | double *retData = (double *)jl_array_data(ret); 121 | memcpy(retData, REAL(Var), jl_array_len(ret) * sizeof(double)); 122 | break; 123 | } 124 | case STRSXP: 125 | { 126 | jl_value_t **retData = jl_array_data(ret); 127 | for (size_t i = 0; i < jl_array_len(ret); i++) { 128 | retData[i] = (jl_value_t *)jl_cstr_to_string(translateCharUTF8(STRING_ELT(Var, i))); 129 | jl_gc_wb(ret, retData[i]); // I'm not sure this is right 130 | } 131 | break; 132 | } 133 | case VECSXP: 134 | { 135 | jl_value_t **retData = jl_array_data(ret); 136 | for (int i = 0; i < jl_array_len(ret); i++) { 137 | retData[i] = (jl_value_t *)R_Julia_MD(VECTOR_ELT(Var,i)); 138 | jl_gc_wb(ret, retData[i]); 139 | } 140 | break; 141 | } 142 | default: 143 | { 144 | jl_error("Invalid array type. rjulia supports the array types LGLSXP, INTSXP, REALSXP, STRSXP and VECSXP.\n"); 145 | } 146 | } 147 | JL_GC_POP(); 148 | return ret; 149 | } 150 | 151 | //convert R object contain NA value to Julia DataArrays 152 | static jl_value_t *R_Julia_MD_NA(SEXP Var, SEXP na) 153 | { 154 | jl_function_t *func = jl_get_function(jl_main_module, "DataArray"); 155 | jl_array_t *ret1 = NULL; 156 | jl_array_t *ret2 = NULL; 157 | jl_value_t *ans = NULL; 158 | JL_GC_PUSH3(&ret1, &ret2, &ans); 159 | ret1 = R_Julia_MD(Var); 160 | ret2 = R_Julia_MD(na); 161 | ans = jl_call2(func, (jl_value_t *)ret1, (jl_value_t *)ret2); 162 | if (rjulia_exception_occurred()) 163 | ans = (jl_value_t *) jl_nothing; 164 | JL_GC_POP(); 165 | return ans; 166 | } 167 | 168 | //convert R factor to Julia PooledDataArray 169 | static jl_value_t *R_Julia_MD_NA_Factor(SEXP Var) 170 | { 171 | SEXP levels = getAttrib(Var, R_LevelsSymbol); 172 | size_t nlevels = LENGTH(levels); 173 | size_t len = LENGTH(Var); 174 | if (len == 0 || TYPEOF(Var) != INTSXP || levels == R_NilValue) 175 | return (jl_value_t *) jl_nothing; 176 | 177 | //create string array for levels in julia 178 | jl_value_t *ans=(jl_value_t *) jl_nothing; 179 | jl_array_t *ret=NULL; 180 | jl_array_t *new_levels=NULL; 181 | jl_array_t *na_vec=NULL; 182 | JL_GC_PUSH4(&ret, &new_levels, &ans, &na_vec); 183 | ret = jl_alloc_array_1d(jl_apply_array_type(jl_string_type, 1), len); 184 | new_levels = jl_alloc_array_1d(jl_apply_array_type(jl_string_type,1), nlevels); 185 | 186 | // Collect levels 187 | jl_value_t **retData1 = jl_array_data(new_levels); 188 | for (size_t i = 0; i < nlevels; i++) { 189 | retData1[i] = jl_cstr_to_string(translateCharUTF8(STRING_ELT(levels, i))); 190 | jl_gc_wb(retData1, retData1[i]); 191 | } 192 | 193 | // Collect string vector 194 | na_vec = jl_alloc_array_1d( jl_apply_array_type(jl_bool_type,1), LENGTH(Var)); 195 | char *na_data = (char *)jl_array_data(na_vec); 196 | int level_index; 197 | 198 | for (size_t i = 0; i < jl_array_len(ret); i++) 199 | { 200 | level_index = INTEGER(Var)[i]; 201 | if (INTEGER(Var)[i] == NA_INTEGER) { 202 | jl_arrayset(ret, retData1[0], i); // Will get wiped out by NA 203 | na_data[i] = 1; 204 | jl_gc_wb(ret,retData1[0]); 205 | } else { 206 | jl_arrayset(ret, retData1[level_index - 1], i); 207 | na_data[i] = 0; 208 | jl_gc_wb(ret,retData1[level_index - 1]); 209 | } 210 | } 211 | 212 | // Make DataArray 213 | jl_function_t *func = jl_get_function(jl_main_module, "DataArray"); 214 | ans = jl_call2(func, (jl_value_t *)ret, (jl_value_t *)na_vec); 215 | 216 | // Make PooledDataArray using DataArray and levels 217 | func = jl_get_function(jl_main_module, "PooledDataArray"); 218 | ans = jl_call2(func, (jl_value_t *)ans, (jl_value_t *)new_levels); 219 | 220 | if (rjulia_exception_occurred()) 221 | ans = (jl_value_t *) jl_nothing; 222 | 223 | JL_GC_POP(); 224 | return ans; 225 | } 226 | 227 | //convert R DataFrame to Julia DataFrame in DataFrames package 228 | static jl_value_t *R_Julia_MD_NA_DataFrame(SEXP Var, SEXP na, const char *VarName) 229 | { 230 | SEXP names = getAttrib(Var, R_NamesSymbol); 231 | size_t len = LENGTH(Var); 232 | if (TYPEOF(Var) != VECSXP || len == 0 || names == R_NilValue) 233 | return (jl_value_t *) jl_nothing; 234 | char evalcmd[evalsize]; 235 | char eltcmd[eltsize]; 236 | const char *onename; 237 | 238 | SEXP elt; 239 | jl_value_t *temp; 240 | for (size_t i = 0; i < len; i++) 241 | { 242 | elt = VECTOR_ELT(Var, i); 243 | snprintf(eltcmd, eltsize, "%sdfelt%lu", VarName, i + 1); 244 | //vector is factor or not 245 | if (getAttrib(elt, R_LevelsSymbol) != R_NilValue) { 246 | temp = R_Julia_MD_NA_Factor(elt); 247 | } else { 248 | temp = R_Julia_MD_NA(elt, VECTOR_ELT(na,i)); 249 | } 250 | jl_set_global(jl_main_module, jl_symbol(eltcmd), (jl_value_t *)temp); 251 | onename = CHAR(STRING_ELT(names, i)); 252 | if (i == 0) { 253 | snprintf(evalcmd, evalsize, "%s=DataFrame(%s = %s)", VarName, onename, eltcmd); 254 | } else { 255 | snprintf(evalcmd, evalsize, "%s[Symbol(\"%s\")] = %s", VarName, onename, eltcmd); 256 | } 257 | jl_eval_string(evalcmd); 258 | 259 | //clear 260 | snprintf(eltcmd, eltsize, "%sdfelt%lu=0;", VarName, i + 1); 261 | jl_eval_string(eltcmd); 262 | 263 | if (jl_exception_occurred()) 264 | { 265 | jl_show(jl_stderr_obj(), jl_exception_occurred()); 266 | Rprintf("\n"); 267 | jl_exception_clear(); 268 | return (jl_value_t *) jl_nothing; 269 | } 270 | } 271 | return (jl_value_t *) jl_nothing; 272 | } 273 | 274 | //Convert R Type To Julia,which not contain NA 275 | SEXP R_Julia(SEXP Var, SEXP VarName) 276 | { 277 | jl_array_t *ans = R_Julia_MD(Var); 278 | JL_GC_PUSH1(&ans); 279 | jl_set_global(jl_main_module, jl_symbol(CHAR(STRING_ELT(VarName, 0))), (jl_value_t *)ans); 280 | JL_GC_POP(); 281 | return R_NilValue; 282 | } 283 | 284 | //Convert R Type To Julia,which contain NA 285 | SEXP R_Julia_NA(SEXP Var, SEXP na, SEXP VarName) 286 | { 287 | jl_value_t *ans = R_Julia_MD_NA(Var, na); 288 | JL_GC_PUSH1(&ans); 289 | jl_set_global(jl_main_module, jl_symbol(CHAR(STRING_ELT(VarName, 0))), ans); 290 | JL_GC_POP(); 291 | return R_NilValue; 292 | } 293 | //Convert R factor To Julia, which contain NA 294 | SEXP R_Julia_NA_Factor(SEXP Var, SEXP VarName) 295 | { 296 | LoadDF(); 297 | jl_value_t *ans = R_Julia_MD_NA_Factor(Var); 298 | JL_GC_PUSH1(&ans); 299 | jl_set_global(jl_main_module, jl_symbol(CHAR(STRING_ELT(VarName, 0))), ans); 300 | JL_GC_POP(); 301 | return R_NilValue; 302 | } 303 | //Convert R data frame To Julia 304 | SEXP R_Julia_NA_DataFrame(SEXP Var, SEXP na, SEXP VarName) 305 | { 306 | LoadDF(); 307 | R_Julia_MD_NA_DataFrame(Var, na, CHAR(STRING_ELT(VarName, 0))); 308 | return R_NilValue; 309 | } 310 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /src/Julia_R.c: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright (C) 2014, 2015 by Yu Gong 3 | */ 4 | 5 | //this file is for convert julia object to R 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include "dataframe.h" 15 | #include "Julia_R.h" 16 | #define pkgdebug 17 | 18 | 19 | // Translate julia eltype to R type 20 | SEXP juliaArrayToSEXP(jl_value_t *Var) { 21 | int nprot = 0; 22 | SEXPTYPE type; 23 | SEXP ans = R_NilValue; 24 | jl_datatype_t *vartype = jl_array_eltype(Var); 25 | if (vartype == jl_string_type) 26 | type = STRSXP; 27 | else if (vartype == jl_bool_type) 28 | type = LGLSXP; 29 | else if (vartype == jl_any_type) 30 | type = VECSXP; 31 | else if (vartype == jl_float64_type || vartype == jl_float32_type || vartype == jl_int64_type || vartype == jl_uint64_type || vartype== jl_uint32_type) 32 | type = REALSXP; 33 | else if (vartype == jl_int32_type || vartype == jl_int16_type || vartype == jl_uint16_type || vartype == jl_int8_type || vartype == jl_uint8_type) 34 | type = INTSXP; 35 | int rank = jl_array_rank(Var); 36 | if (rank > 1) { 37 | //get Julia dims and set R array Dims 38 | int ndims = jl_array_ndims(Var); 39 | SEXP dims = PROTECT(allocVector(INTSXP, ndims)); nprot++; 40 | int *p = INTEGER(dims); 41 | for (size_t i = 0; i < ndims; i++) 42 | p[i] = jl_array_dim(Var, i); 43 | PROTECT(ans = allocArray(type, dims)); nprot++; 44 | } else { 45 | PROTECT(ans = allocVector(type, jl_array_len(Var))); nprot++; 46 | } 47 | UNPROTECT(nprot); 48 | return(ans); 49 | } 50 | 51 | // Macros for julia type to r, for shorter code 52 | // NOTE: You must UNPROTECT at the very end !! 53 | 54 | #define jlint_to_r \ 55 | int *res = INTEGER(ans); \ 56 | for (size_t i = 0; i < len; i++) \ 57 | res[i] = p[i] 58 | 59 | 60 | #define jlfloat_to_r \ 61 | double *res = REAL(ans); \ 62 | for (size_t i = 0; i < len; i++) \ 63 | res[i] = p[i] 64 | 65 | 66 | #define jlbigint_to_r bool isInt32=true; \ 67 | for (size_t ii=0; iiINT32_MAX || p[ii]INT32_MAX || p[ii]