Getting Started With Julia - Sample Chapter
Getting Started With Julia - Sample Chapter
ee
C o m m u n i t y
E x p e r i e n c e
D i s t i l l e d
$ 29.99 US
18.99 UK
P U B L I S H I N G
pl
Sa
m
Ivo Balbaert
Chapter 8, I/O, Networking, and Parallel Computing, shows how to work with data in
files and databases using DataFrames. We can explore the networking capabilities, and
shows how to set up a parallel computing environment with Julia.
Chapter 9, Running External Programs, looks at how Julia interacts with the command
line and other languages and also discusses performance tips.
Chapter 10, The Standard Library and Packages, digs deeper into the standard library
and demonstrates the important packages for visualization of data.
Appendix, List of Macros and Packages, provides you with handy reference lists of the
macros and packages used in this book.
Installing Julia
Packages
Installing Sublime-IJulia
Installing Juno
Working of Julia
By the end of this chapter, you will have a running Julia platform. Moreover,
you will be able to work with Julia's shell as well as with editors or integrated
development environments with a lot of built-in features to make development
more comfortable.
Installing Julia
The Julia platform in binary (that is, executable) form can be downloaded from
http://julialang.org/downloads/. It exists for three major platforms (Windows,
Linux, and OS X) in 32- and 64-bit format, and is delivered as a package or in
an archive format. You should use the current official stable release when doing
serious professional work with Julia (at the time of writing, this is Version 0.3). If
you would like to investigate the latest developments, install the upcoming version
(which is now Version 0.4). The previous link contains detailed and platformspecific instructions for the installation. We will not repeat these instructions here
completely, but we will summarize some important points.
[ 16 ]
Chapter 1
4. A menu shortcut will be created which, when clicked, starts the Julia
command-line version or Read Evaluate Print Loop (REPL), as shown
in the following screenshot:
[ 17 ]
Ubuntu version
For Ubuntu systems (Version 12.04 or later), there is a Personal
Package Archive (PPA) for Julia (can be found at https://launchpad.
net/~staticfloat/+archive/ubuntu/juliareleases) that makes the installation
painless. All you need to do to get the stable version is to issue the following
commands in a terminal session:
sudo add-apt-repository ppa:staticfloat/juliareleases
sudo add-apt-repository ppa:staticfloat/julia-deps
sudo apt-get update
sudo apt-get install julia
If you want to be at the bleeding edge of development, you can download the nightly
builds instead of the stable releases. The nightly builds are generally less stable,
but will contain the most recent features. To do so, replace the first of the preceding
commands with:
sudo add-apt-repository ppa:staticfloat/julianightlies
This way, you can always upgrade to a more recent version by issuing the following
commands:
sudo apt-get update
sudo apt-get upgrade
[ 18 ]
Chapter 1
OS X
Installation for OS X is straightforwardusing the standard software installation
tools for the platform. Add /Applications/Julia-n.m.app/Contents/Resources/
julia/bin/Julia to make Julia available everywhere on your computer.
If you want code to be run whenever you start a Julia session, put it in /home/.
juliarc.jl on Ubuntu, ~/.juliarc.jl on OS X, or c:\Users\username\.
juliarc.jl on Windows. For instance, if this file contains the following code:
println("Greetings! ! ?")
Then, Julia starts up in its shell (or REPL as it is usually called) with the following
text in the screenshot, which shows its character representation capabilities:
Using .juliarc.jl
[ 19 ]
3. Make sure you have git installed; if not, issue the command:
sudo apt-get -f install git
This will download the Julia source code into a julia directory in the
current folder.
5. The Julia building process needs the GNU compilation tools g++, gfortran,
and m4, so make sure that you have installed them with the following
command:
sudo apt-get install gfortran g++ m4
6. Now go to the Julia folder and start the compilation process as follows:
cd julia
make
For more information on how to build Julia on Windows, OS X, and other systems,
refer to https://github.com/JuliaLang/julia/.
Using parallelization
If you want Julia to use n concurrent processes, compile the source
with make -j n.
There are two ways of using Julia. As described in the previous section, we can
use the Julia shell for interactive work. Alternatively, we can write programs in a
text file, save them with a .jl extension, and let Julia execute the whole program
sequentially.
[ 20 ]
Chapter 1
If, for some reason, you don't need to see the result, end the expression with a
; (semicolon) such as 6 * 7. In both the cases, the resulting value is stored, for
convenience, in a variable named ans that can be used in expressions, but only
inside the REPL. You can bind a value to a variable by entering an assignment as
a = 3. Julia is dynamic, and we don't need to enter a type for a, but we do need to
enter a value for the variable, so that Julia can infer its type. Using a variable b that
is not bound to the a value, results in the ERROR: b not defined message. Strings
are delineated by double quotes (""), as in b = "Julia". The following screenshot
illustrates these workings with the REPL:
[ 21 ]
Previous expressions can be retrieved in the same session by working with the
up and down arrow keys. The following key bindings are also handy:
To clear the screen (but variables are kept in memory), press CTRL + L
To reset the session so that variables are cleared, enter the command
Commands from the previous sessions can still be retrieved, because they are stored
(with a timestamp) in a.julia_history file (in /home/$USER on Ubuntu, c:\Users\
username on Windows, or ~/.julia_history on OS X). Ctrl + R (produces a
(reverse-i-search) ': prompt) searches through these commands.
Typing ? starts up the help mode (help?>) to give quick access to Julia's
documentation. Information on function names, types, macros, and so on, is given
when typing in their name. Alternatively, to get more information on a variable
a, type help(a), and to get more information on a function such as sort, type
help(sort). To find all the places where a function such as println is defined or
used, type apropos("println"), which gives the following output:
Base.println(x)
Base.enumerate(iter)
Base.cartesianmap(f, dims)
Thus, we can see that it is defined in the Base module, and is used in two other
functions. Different complete expressions on the same line have to be separated by a
; (semicolon) and only the last result is shown. You can enter multi-line expressions
as shown in the following screenshot. If the shell detects that the statement is
syntactically incomplete, it will not attempt to evaluate it. Rather, it will wait for the
user to enter additional lines until the multi-line statement can be evaluated.
[ 22 ]
Chapter 1
A handy autocomplete feature also exists. Type one or more letters, press the Tab key
twice, and then a list of functions starting with these letters appears. For example:
type so, press the Tab key twice, and then you get the list as: sort sort! sortby
sortby! sortcols sortperm sortrows.
If you start a line with ;, the rest of the line is interpreted as a system shell command
(try for example, ls, cd, mkdir, whoami, and so on). The Backspace key returns to the
Julia prompt.
A Julia script can be executed in the REPL by calling it with include. For example,
for hello.jl, which contains the println("Hello, Julia World!") command,
the command is as follows:
julia> include("hello.jl")
Experiment a bit with different expressions to get some feeling for this environment.
You can get more information at http://docs.julialang.org/en/
latest/manual/interacting-with-julia/#key-bindings.
The preceding commands print out 42 (on Windows, use " instead of the '
character).
Some other options useful for parallel processing will be discussed in Chapter 9,
Running External Programs. Type julia h for a list of all options.
[ 23 ]
A script.jl file with Julia source code can be started from the command line with
the following command:
julia script.jl arg1 arg2 arg3
Here arg1, arg2, and arg3 are optional arguments to be used in the script's code.
They are available from the global constant ARGS. Take a look at the args.jl file
as follows:
for arg in ARGS
println(arg)
end
The julia args.jl 1 Dart C command prints out 1, Dart, and C on consecutive
lines.
A script file also can execute other source files by including them in the REPL; for
example, main.jl contains include("hello.jl") that will execute the code from
hello.jl when called with julia main.jl.
Downloading the example code
You can download the example code files from your account at
http://www.packtpub.com for all the Packt Publishing books you
have purchased. If you purchased this book elsewhere, you can visit
http://www.packtpub.com/support and register to have the files
e-mailed directly to you.
Packages
Most of the standard library in Julia (can be found in /share/julia/base relative
to where Julia was installed) is written in Julia itself. The rest of Julia's code
ecosystem is contained in packages that are simply Git repositories. They are most
often authored by external contributors, and already provide functionality for such
diverse disciplines such as bioinformatics, chemistry, cosmology, finance, linguistics,
machine learning, mathematics, statistics, and high-performance computing. A
searchable package list can be found at http://pkg.julialang.org/. Official Julia
packages are registered in the METADATA.jl file in the Julia Git repository, available
on GitHub at https://github.com/JuliaLang/METADATA.jl.
[ 24 ]
Chapter 1
Julia's installation contains a built-in package manager Pkg for installing additional
Julia packages written in Julia. The downloaded packages are stored in a cache ready
to be used by Julia given by Pkg.dir(), which are located at c:\users\username\.
julia\vn.m\.cache, /home/$USER/.julia/vn.m/.cache, or ~/.julia/vn.m/.
cache. If you want to check which packages are installed, run the Pkg.status()
command in the Julia REPL, to get a list of packages with their versions, as shown in
the following screenshot:
Packages list
The Pkg.installed() command gives you the same information, but in a dictionary
form and is usable in code. Version and dependency management is handled
automatically by Pkg. Different versions of Julia can coexist with incompatible
packages, each version has its own package cache.
If you get an error with Pkg.status() such as
ErrorException("Unable to read directory METADATA."),
issue a Pkg.init() command to create the package repository folders,
and clone METADATA from Git. If the problem is not easy to find or the
cache becomes corrupted somehow, you can just delete the .julia
folder, enter Pkg.init(), and start with an empty cache. Then, add
the packages you need.
[ 25 ]
The rand(100) function is an array with 100 random numbers. This produces the
following output:
After installing a new Julia version, update all the installed packages by running
Pkg.update() in the REPL. For more detailed information, you can refer to
http://docs.julialang.org/en/latest/manual/packages/.
[ 26 ]
Chapter 1
Julia Studio
[ 27 ]
Notice the # sign that indicates the beginning of comments, the elegant and familiar
for loop and if elseif construct, and how they are closed with end. The 1:100
range is a range; mod returns the remainder of the division; the function mod(i, n)
can also be written as an i % n operator. Using four spaces for indentation is a
convention. Recently, Forio also developed Epicenter, a computational platform for
hosting the server-side models (also in Julia), and building interactive web interfaces
for these models.
[ 28 ]
Chapter 1
Verify that you have started IJulia. You must see IJ and the Julia logo in the upperleft corner of the browser window. Julia code is entered in the input cells (input can
be multiline) and then executed with Shift + Enter. Here is a small example:
[ 29 ]
In the second input cell, we use PyPlot (this requires the installation of matplotlib;
for example, on Linux, this is done by sudo apt-get install pythonmatplotlib).
The linspace(0, 5) command defines an array of 100 equally spaced values
between 0 and 5, y is defined as a function of x and is then shown graphically
with the plot as follows:
using PyPlot
x = linspace(0, 5)
y = cos(2x + 5)
plot(x, y, linewidth=2.0, linestyle="--")
title("a nice cosinus")
xlabel("x axis")
ylabel("y axis")
Save a notebook in file format (with the extension .ipynb) by downloading it from
the menu. If working in an IPython notebook is new for you, you can take a look at
the demo at http://ipython.org/notebook.html to get started. After installing a
new Julia version, always run Pkg.build("IJulia") in the REPL in order to rebuild
the IJulia package with this new version.
Installing Sublime-IJulia
The popular Sublime Text editor (http://www.sublimetext.com/3) now has a
plugin based on IJulia (https://github.com/quinnj/Sublime-IJulia) authored
by Jacob Quinn. It gives you syntax highlighting, autocompletion, and an in-editor
REPL, which you basically just open like any other text file, but it runs Julia code for
you. You can also select some code from a code file and send it to the REPL with the
shortcut CTRL + B, or send the entire file there. Sublime-IJulia provides a frontend to
the IJulia backend kernel, so that you can start an IJulia frontend in a Sublime view
and interact with the kernel. Here is a summary of the installation, for details you
can refer to the preceding URL:
1. From within the Julia REPL, install the ZMQ and IJulia packages.
2. From within Sublime Text, install the Package Control package
(https://sublime.wbond.net/installation).
[ 30 ]
Chapter 1
3. From within Sublime Text, install the IJulia package from the Sublime
command palette.
4. Ctrl + Shift + P opens up a new IJulia console. Start entering commands,
and press Shift + Enter to execute them. The Tab key provides
command completion.
Installing Juno
Another promising IDE for Julia and a work in progress by Mike Innes and Keno
Fisher is Juno, which is based on the Light Table environment. The docs at http://
junolab.org/docs/installing.html provides detailed instructions for installing
and configuring Juno. Here is a summary of the steps:
1. Get LightTable from http://lighttable.com.
2. Start LightTable, install the Juno plugin through its plugin manager, and
restart LightTable.
Light Table works extensively with a command palette that you can open by
typing Ctrl + SPACE, entering a command, and then selecting it. Juno provides
an integrated console, and you can evaluate single expressions in the code editor
directly by typing Ctrl + Enter at the end of the line. A complete script is evaluated
by typing Ctrl + Shift + Enter.
On Linux, gedit is very good. The Julia plugin works well and provides
autocompletion. Notepad++ also has Julia support from the contrib directory
mentioned earlier.
The SageMath project (https://cloud.sagemath.com/) runs Julia in the cloud
within a terminal and lets you work with IPython notebooks. You can also work and
teach with Julia in the cloud using the JuliaBox platform (https://juliabox.org/).
[ 31 ]
The code_native function can be used to see the assembly code generated for the
same type of x:
julia> code_native(f, (Int64,))
.text
Filename: none
Source line: 1
push
RBP
mov
RBP, RSP
Source line: 1
lea
RAX, QWORD PTR [RCX + RCX + 5]
pop
RBP
ret
[ 32 ]
Chapter 1
Julia code is fast because it generates specialized versions of functions for each data
type. Julia implements automatic memory management. The user doesn't have
to worry about allocating and keeping track of the memory for specific objects.
Automatic deletion of objects that are not needed any more (and hence, reclamation
of the memory associated with those objects) is done using a garbage collector (GC).
The garbage collector runs at the same time as your program. Exactly when a specific
object is garbage collected is unpredictable. In Version 0.3, the GC is a simple markand-sweep garbage collector; this will change to an incremental mark-and-sweep GC
in Version 0.4. You can start garbage collection yourself by calling gc(), or if it runs
in the way you can disable it by calling gc_disable().
The standard library is implemented in Julia itself. The I/O functions rely on the libuv
library for efficient, platform-independent I/O. The standard library is also contained
in a package called Base, which is automatically imported when starting Julia.
Summary
By now, you should have been able to install Julia in a working environment you
prefer. You should also have some experience with working in the REPL. We will
put this to good use starting in the next chapter, where we will meet the basic data
types in Julia, by testing out everything in the REPL.
[ 33 ]
www.PacktPub.com
Stay Connected: