In an earlier article, I had shown how it is possible to interact with Mathematica from Julia. In today’s article, I will share the details of how to interact with Julia from within Mathematica.
Why would somebody want to execute Julia code inside Mathematica? Although Mathematica is a great symbolic computing environment offering thousands of functions covering several areas, I might want to reuse some feature I have already implemented in Julia as part of some other project. Another reason is that sometimes implementing an algorithm in Julia to take advantage of multiple cores/GPU might give us better performance than implementing that algorithm in Mathematica. There could be other valid reasons.
In order to interact with Julia, first we must have installed Julia on our machine. In my case, I have Julia 1.8.2 running on my machine. In addition, Mathematica requires two packages “ZMQ” and “JSON” to be installed in Julia. So, I did that:
After installing the required packages, we can exit Julia. It need not be running in order to use from Mathematica.
Next we launch Mathematica. To check if Julia is accessible, we evaluate the function “FindExternalEvaluators[]”.
Mathematica responds with details of the Julia installation.
There are three ways to interact with Julia. The most general is to call “ExternalEvaluate[]” function.
The second way is to explicitly create a Julia session object using “StartExternalSession[]” function once and then pass the session object as an argument to “ExternalEvaluate[]” subsequently.
Notice that for calling a Julia function, we are using “[]” and not “()”.
The nice thing is that we can now mix Julia and Mathematica expressions:
Here we are calling the previously defined Julia function “factfn[]” inside the Mathematica function “Sort[]”. Also note that the function “DeleteObject[]” has to be called when the Julia session object is not needed anymore.
The third way to interact with Julia is through the “Julia Cell”. For this, type “>” in the Mathematica Notebook. This will bring up an evaluation Cell corresponding to the default language (in my case, “Python”). When you click on the Cell icon, a drop-down menu will appear. Select “Julia” from this list.
This will change the current Cell to Julia mode. You can now enter any Julia code in this Cell. Next time onward, when you type “>”, the Julia Cell comes up automatically.
This mode is convenient when your primary focus is Julia mode. Remember that in this mode, you cannot use non-Julia expressions/commands.
As shown above, interacting with Julia inside Mathematica is a simple process and is quite useful when you wish to take advantage of Julia’s special capabilities inside Mathematica.
About my test environment: I am using Julia 1.8.2 and Mathematica 13.1 on my iMac.
Have a great weekend!
Recent Comments