10 KiB
Using other languages¶
Often, I hear that the biggest challenge of moving from another language to Julia is giving up all the codes you have written in other languages or your favorite packages from other languages. This notebook is not about data science, but it's about your next data science project (if you're working on a data science project in Julia and you want to use functionality from other langages). Here, we will specifically cover Python, R, and C.
⚫Python¶
using PyCall
You can import any python package...
math = pyimport("math")
math.sin(math.pi / 4) # returns ≈ 1/√2 = 0.70710678...
Hint: you may need to do:
julia> using Conda
julia> Conda.add("networkx")
for the line below to work.
python_networkx = pyimport("networkx")
You can also write your own Python code as follows
py"""
import numpy
def find_best_fit_python(xvals,yvals):
meanx = numpy.mean(xvals)
meany = numpy.mean(yvals)
stdx = numpy.std(xvals)
stdy = numpy.std(yvals)
r = numpy.corrcoef(xvals,yvals)[0][1]
a = r*stdy/stdx
b = meany - a*meanx
return a,b
"""
xvals = repeat(1:0.5:10, inner=2)
yvals = 3 .+ xvals .+ 2 .* rand(length(xvals)) .-1
find_best_fit_python = py"find_best_fit_python"
a,b = find_best_fit_python(xvals,yvals)
If the above python code was in a file called fit_linear.py, you can call it as follows:
python_linear_fit = pyimport("fit_linear")
python_linear_fit.find_best_fit_python(xvals,yvals)```
⚫R code¶
using RCall
$ can switch to an R REPL from julia's REPL. We'll take a look...
# we can use the rcall function
r = rcall(:sum, Float64[1.0, 4.0, 6.0])
typeof(r[1])
The @rput allows you to put julia variable in the R context.
z = 1
@rput z
r = R"z+z"
r[1]
x = randn(10)
You can apply R functions on julia variables
@rimport base as rbase
rbase.sum([1, 2, 3])
Hint: for the code below to work, you will need to type $ in the REPL followed by:
install.packages("boot")
the $ will enter you into the R REPL mode.
R"t.test($x)"
The equivalent in Julia would be
using HypothesisTests
OneSampleTTest(x)
⚫C code¶
Calling standard libraries is easy
t = ccall(:clock, Int32, ())
Can look at Python and C/C++ examples here: https://github.com/xorJane/Excelling-at-Julia-Basics-and-Beyond/blob/master/JuliaCon2019_Huda/Julia%20Wrappers.ipynb
ccall((:hello_world_repeated,"hello_world_lib.dylib"),
Int64,
(Int64,),
10)
```
Finally, I would say that this is the only off-topic notebook in this course, and it's a topic that can be covered on its own in a standalone tutorial... Nevertheless, the goal of this notebook is to tell you that porting your code from Python, R, and C should be easy and straight forward in Julia.
🥳 One cool finding¶
You can easily call Python, R, C, and Cpp code from Julia!