Julia tutorial: Get started with the Julia language

Want the convenience of a dynamic language and the performance of a compiled statically typed language? Try Julia

As I discussed in “What is Julia?,” Julia is a free open source high-level, high-performance dynamic programming language for numerical computing that combines the development convenience of a dynamic language with the performance of a compiled statically typed language. It was designed to be good for scientific computing, machine learning, data mining, large-scale linear algebra, distributed computing, and parallel computing, and to have the ease of use of Python, R or even Matlab.

There are five major options for working with Julia: JuliaBox online; an installation of the Julia command line; an installation of JuliaPro; Visual Studio Code plus a plug-in and a Julia or JuliaPro installation; and Jupyter notebooks with IJulia. Let’s consider the pros and cons of each.

JuliaBox online requires no installation or maintenance, and you can use a free account to get started. It is set up for Jupyter notebooks, has more than 300 packages already added, and has dozens of tutorials in Jupyter notebook form. Many of the notebooks tie into the official Julia video tutorials. Jupyter notebooks are excellent for explaining your calculations, as you can see below.

juliabox linear algebra IDG

Jupyter notebooks make it easy to document as you go. 

On the down side, the free tier of JuliaBox can seem slow at times, although relatively inexpensive monthly paid subscriptions give you more cores, more RAM, and longer sessions. In addition, a Jupyter notebook is better for solving small problems than large ones, and is not as good as an IDE for actual programming.

As I discussed in “What is Julia?,” Julia is a free open source high-level, high-performance dynamic programming language for numerical computing that combines the development convenience of a dynamic language with the performance of a compiled statically typed language. It was designed to be good for scientific computing, machine learning, data mining, large-scale linear algebra, distributed computing, and parallel computing, and to have the ease of use of Python, R or even Matlab.

There are five major options for working with Julia: JuliaBox online; an installation of the Julia command line; an installation of JuliaPro; Visual Studio Code plus a plug-in and a Julia or JuliaPro installation; and Jupyter notebooks with IJulia. Let’s consider the pros and cons of each.

JuliaBox online requires no installation or maintenance, and you can use a free account to get started. It is set up for Jupyter notebooks, has more than 300 packages already added, and has dozens of tutorials in Jupyter notebook form. Many of the notebooks tie into the official Julia video tutorials. Jupyter notebooks are excellent for explaining your calculations, as you can see below.

juliabox linear algebra IDG

Jupyter notebooks make it easy to document as you go. 

On the down side, the free tier of JuliaBox can seem slow at times, although relatively inexpensive monthly paid subscriptions give you more cores, more RAM, and longer sessions. In addition, a Jupyter notebook is better for solving small problems than large ones, and is not as good as an IDE for actual programming.

If you install the open source Julia command line, you’ll need to add many packages to make it useful. On the plus side, the command line installs quickly; on the minus side, it can be annoying to interrupt your development flow to install missing packages.

julia command line IDG

The Julia command line.

JuliaPro gives you the Julia command line with many packages pre-installed (shown above), and adds the Juno IDE (shown below), which is based on the GitHub Atom editor. JuliaPro comes in free personal and paid enterprise versions. Juno is a nice multi-paned environment for Julia programming and debugging.

The JuliaPro Quick Start guide for your OS will include the location of the Julia command line; it varies from version to version. While you can install multiple versions of Julia side by side, there is no need to do so. When you update Julia, you should also update packages: Pkg.update().

julia juno ide IDG

The Juno IDE for Julia is based on Atom.

Another good alternative is to develop Julia programs using Visual Studio Code. You’ll need to have the Julia command line installed, and to add the Julia plug-in to Visual Studio Code. I had to close and restart Visual Studio Code before it would recognize the command line location. This configuration gives you functionality that is similar to Juno, including a Julia Plot pane, with the advantage of being able to program in other languages in addition to Julia.

julia visual studio code IDG

Julia in Visual Studio Code. 

IJulia for Jupyter notebooks gives you an environment similar to JuliaBox that you can run on your own computers if you wish. You’ll need to install Jupyter for Python 2 or Python 3, either by installing Anaconda or by using pip. Once that works, and you have IJulia installed from the Julia command line with Pkg.add("IJulia"), you can launch IJulia and notebook():

using IJulia
notebook()

If you want to fork a new process for the notebook server, you can use notebook(detached=true) from Julia. If you want to open the notebook in a specific directory from Julia, you can use the dir argument, notebook(dir="/some/path"). The default is your home directory.

According to the documentation, you should be able to also run jupyter notebook from a system command line and start a Julia kernel. Currently this causes kernel exceptions on my MacBook Pro when I try to execute a notebook code line, even though the same notebooks work just fine when launched from the Julia command line. I launched the notebook shown below from within Julia.

julia jupyter plot sin IDG

A sine plot using Gadfly in a Jupyter notebook. 

If you’d like to run the JuliaBox tutorials locally instead of online, you can clone the tutorial repository from GitHub. Then open a notebook in your local JuliaBoxTutorials directory, and run the Local_installations notebooks to install all of the packages used in the tutorials. Allow some time for this—it will take longer than you expect.

If you update Julia or JuliaPro after installing IJulia, you’ll need to rebuild IJulia from the Julia command line: Pkg.build("IJulia").

Julia basics

Now that you’ve set up Julia locally or decided to use JuliaBox, let’s go over how to use them, and run a few examples.

To start, open the Julia or JuliaPro REPL. Press ?, and notice how the prompt changes to help?>. Type help and press the Enter key, and you’ll see something like the screen below.

julia cli help 2 IDG

Julia command line help.

Now try one of the suggested help requests, such as ?@time, and press the Enter key. Go on to try evaluating some expressions interactively. In the screenshot below I took my cue from the help for @time, and also ran the test twice—the first time through there’s an overhead from just-in-time (JIT) compilation. I was able to copy and paste from the help; I was also able to scroll up the history in the terminal to re-run a previous command.

julia time rand 2 IDG

Playing in the Julia REPL. 

When you’re done playing with the Julia REPL, press Control-D or type exit().

Now let’s try JuliaBox. Browse to https://juliabox.com. You’ll be redirected to this webpage:

juliabox start IDG

The JuliaBox start page. 

I usually log in with my GitHub credentials, but feel free to log in with your Google or LinkedIn ID. I still use the free subscription. When I need more cores or longer sessions, I run the Jupyter notebooks locally with IJulia, as described above.

Once the notebook initializes, click into the tutorials folder, then the intro-to-julia folder, then short-version, and finally open 00.Jupyter_notebooks. Follow the instructions, navigating live through the notebook with Shift-Enter and reading every line. The completed notebook should look roughly like the screenshot below.

juliabox jupyter get started IDG

The completed Jupyter notebooks tutorial in Julia. 

You’ll notice that the ? notation for help is shared with the Julia REPL, even though the prompt doesn’t change in the notebook. The ; notation for shell commands also works in the REPL, and causes the prompt to change to shell>:

julia shell 2 IDG

The Julia shell. 

Exactly what the shell will do depends on the underlying OS; here I’m using MacOS with the default Bash shell. On Windows 10, from the Julia shell> prompt, I discovered that I have to pick an OS shell to run, whether the Command shell or PowerShell:

julia shell windows IDG

You can access both the Command shell and PowerShell from the Julia shell prompt on Windows 10.

Going back to JuliaBox, close the 00.Jupyter_notebooks notebook and open a 01.Getting_to_know_Julia notebook. Again, work through the notebook sequentially with Shift-Enter and read every line as you go.

Hint: the tab completion sequences for Unicode are described in the Interacting with Julia documentation, and the full list is in the Unicode Input documentation. Search for \:mahjong: to see the emoji glyphs, such as \:cat:<TAB> and \:dog:<TAB>. These work in the REPL as well as Julia notebooks. 

Pay attention to the data structures discussed. As a quick quiz for yourself, which data structures are mutable, and which are immutable? Which contain ordered sequences, and which are unordered?

When you get to functions, pay special attention. Note the three syntax styles for defining a function. Also note the meaning of ! at the end of a function name:

juliabox mutating functions IDG

The ! at the end of the name denotes a mutating function in Julia. 

If you keep going, you’ll see the use of the higher-order function map, which you may know from other languages, and broadcast, which is a generalization of map. Also note the dot syntax for broadcasting:

juliabox dot broadcast IDG

Note Julia’s dot syntax for broadcasting. 

Julia linear algebra operations

I strongly encourage you to continue with the 02.Linear_Algebra notebook and read the documentation on linear algebra. Assuming that you have taken college linear algebra and have done numerical computations with matrices, you have to be impressed by a language that has an operator that solves linear systems, knows how to represent symmetric tridiagonal and Hermitian matrices, has functions for eigenvalues and eigenvectors, and computes matrix factorizations.

juliabox linear algebra IDG

Julia has an impressive level of support for linear algebra operations. 

Julia benchmarks

In the notebook 05.Julia_is_fast, you can compare the speed of Julia with other languages for the simple problem of summing 10 million random numbers. If the answers you get are like mine, you’ll find that the built-in Julia sum() function is slightly faster than NumPy. A handwritten Julia loop is about half that speed, nearly the same as a handwritten C function. Plain Python without NumPy is an order of magnitude slower using the built-in Python sum() function, and another three times slower than that using handwritten Python.

julia benchmarks IDG

Some Julia benchmark results. 

Julia graphics and plotting

Julia has many ways to generate plots and display graphics. Three of the most popular plotting packages in Julia are Plots, PyPlot, and Gadfly.

Plots is a plotting meta-package that brings many different plotting back-end packages under a single API, and is featured in the plotting tutorials on JuliaBox. PyPlot calls into the standard Python package Matplotlib, and is one of the preferred back ends to Plots. Gadfly is an implementation of a Wickham-Wilkinson style grammar of graphics, similar to the popular R package Ggplot2, and has been featured in several Julia publications, including the language speed comparison benchmarks.

Let’s try a very simple example for Plots, taken from the Plots tutorial. In your favorite Julia environment, run this program:

using Plots
x = 1:10; y = rand(10); # These are the plotting data
plot(x,y)

If you get an error telling you that Plots is not installed, fix that with Pkg.add("Plots") and then rerun the program.

In my installation, the first run showed me:

julia plots simple IDG

A simple plot using Julia’s Plot plotting meta-package. 

When I reran the program, the data was different, because it was generated randomly, so the line plot looked different.

As a more impressive demonstration of what Plots can do, consider this program from the Plots documentation:

using Plots, ProgressMeter
pyplot(leg=false, ticks=nothing)
x = y = linspace(-5, 5, 40)
zs = zeros(0,40)
n = 100

# create a progress bar for tracking the animation generation
prog = Progress(n,1)

@gif for i in linspace(0, 2π, n)
    f(x,y) = sin(x + 10sin(i)) + cos(y)

    # create a plot with 3 subplots and a custom layout
    l = @layout [a{0.7w} b; c{0.2h}]
    p = plot(x, y, f, st = [:surface, :contourf], layout=l)

    # induce a slight oscillating camera angle sweep, in degrees (azimuth, altitude)
    plot!(p[1],camera=(15*cos(i),40))

    # add a tracking line
    fixed_x = zeros(40)
    z = map(f,fixed_x,y)
    plot!(p[1], fixed_x, y, z, line = (:black, 5, 0.2))
    vline!(p[2], [0], line = (:black, 5))

    # add to and show the tracked values over time
    zs = vcat(zs, z’)
    plot!(p[3], zs, alpha = 0.2, palette = cgrad(:blues).colors)

    # increment the progress bar
    next!(prog)
end

The animated GIF produced by the program looks like this:

julia plot waves 2 IDG

Julia’s Plot package can produce fancy, 3D plots. 

The fancy 3D plot above was created using PyPlot as the back end to Plots. You can call PyPlot directly, assuming that you have it and the Matplotlib Python package installed. Drawing on the basic usage sample in the PyPlot README, we can run four lines of code in the REPL and get the plot in a separate window, as shown below:

julia pyplot plot IDG

You can call PyPlot directly from Julia.

In fact, everything that’s possible with Plots and the PyPlot back end is also possible using PyPlot directly. If you’re adapting Python code that calls matplotlib.pyplot for use in Julia, it might be quicker to call PyPlot than rewrite the code for Plots. If you’re starting from a green field, it might be easier to call Plots, and that will also give you the option to create interactive plots with another back end.

Gadfly has lots of features and no dependency on Python, but it is limited to 2D graphics. In addition, Gadfly takes awhile to emit its first plot, and has a lot of Julia dependencies. However, Gadfly is so similar to the R package Ggplot2 that I groked its grammer right away, so it’s the package I would use if I were adapting R plotting code. At its simplest, you can generate a plot with Gadfly with one line of code after the using statement:

using Gadfly
plot(sin,0,25)

If you get an error on the first line, then Pkg.add("Gadfly").

When I ran this code in the Julia REPL, it (eventually) opened a browser tab showing the graph:

julia gadfly sin 2 IDG

A sine plot produced by Julia’s Gadfly package. 

Gadfly plots can be quite complex. The benchmark notebook has a good example. It’s a little easier to follow the example in the Gadfly tutorial, which uses the standard R database for iris classification. Depending on where you are running this example, you may have first run Pkg.add("RDatasets"):

using RDatasets
iris = dataset("datasets", "iris")
plot(iris, x=:SepalLength, y=:SepalWidth, color=:Species,
         Geom.point)

This displays the iris sepal lengths versus sepal widths, color-coded by species, as shown below. You can actually see the clusters, and especially see the Setosa cluster in the upper left (short, wide sepals).

julia gadfly iris plot 2 IDG

Iris sepal lengths versus sepal widths by species, plotted with Julia’s Gadfly. 

At this point you should be ready to continue your Julia learning journey on your own. In addition to going through the rest of the tutorial notebooks on JuliaBox, and the full tutorials for the three plotting packages we discussed, you might like watching the saved webcasts by Jane Herriman and others. On the same page as the webcasts, you’ll also find references to a number of online tutorial documents, Julia resources, and additional Julia videos.

This story, "Julia tutorial: Get started with the Julia language" was originally published by InfoWorld.