Code should execute sequentially if run in a Jupyter notebook

# Setting up Your Julia Environment¶

## Overview¶

In this lecture we will cover how to get up and running with Julia

Topics:

1. Installation
2. Interactive Julia sessions
3. Running sample programs
4. Installation of libraries, including the Julia code that underpins these lectures

## First Steps¶

### Installation¶

Note: In these lectures we assume you have version 0.6 or later

Unless you have good reason to do otherwise, choose

• The current release rather than nightly build
• The platform specific binary rather than source

Assuming there were no problems, you should now be able to start Julia either by

• Navigating to Julia through your menus or desktop icons (Windows, OSX), or
• Opening a terminal and typing julia (Linux)

Either way you should now be looking at something like this (modulo your operating system — this is a Linux machine)

### The REPL¶

The program that’s running here is called the Julia REPL (Read Eval Print Loop) or Julia interpreter

Let’s try some basic commands

The Julia interpreter has the kind of nice features you expect from a modern REPL

For example,

• Pushing the up arrow key retrieves the previously typed command
• If you type ? the prompt will change to help?> and give you access to online documentation

You can also type ; to get a shell prompt, at which you can enter shell commands

(Here ls is a UNIX style command that lists directory contents — your shell commands depend on your operating system)

Below we’ll often show interactions with the interpreter as follows

x = 10

10

2 * x

20


## Installing Packages¶

In these lectures you’ll often see statements such as

using Plots


or

using QuantEcon


These commands pull in code from some of Julia’s many external Julia code libraries

For the code to run, you need to install the corresponding package first

Fortunately this is easy using Julia’s package management system

For example, let’s install DataFrames, which provides useful functions and data types for manipulating data sets

Pkg.add("DataFrames")


Assuming you have a working Internet connection this should install the DataFrames package

Here’s how it looks on our machine (which already has this package installed)

If you now type Pkg.status() you’ll see DataFrames and its version number

To pull the functionality from DataFrames into the current session we type

using DataFrames


Now its functions are accessible

df = DataFrame(x1=[1, 2], x2=["foo", "bar"])

2x2 DataFrame
| Row | x1 | x2    |
|-----|----|-------|
| 1   | 1  | "foo" |
| 2   | 2  | "bar" |


### Keeping your Packages up to Date¶

Running

Pkg.update()


will update your installed packages and also update local information on the set of available packages

### QuantEcon¶

QuantEcon is an organization that facilitates development of open source code for economic modeling

As well as these lectures, it supports QuantEcon.jl, a library for quantitative economic modeling in Julia

The installation method is standard

Pkg.add("QuantEcon")


Here’s an example, which creates a discrete approximation to an AR(1) process

using QuantEcon: tauchen

tauchen(4, 0.9, 1.0)

Discrete Markov Chain
stochastic matrix of type Array{Float64,2}:
[0.945853 0.0541468 2.92863e-10 0.0; 0.00580845 0.974718 0.0194737 1.43534e-11; 1.43534e-11 0.0194737 0.974718 0.00580845; 2.08117e-27 2.92863e-10 0.0541468 0.945853]


## Jupyter¶

To work with Julia in a scientific context we need at a minimum

1. An environment for editing and running Julia code
2. The ability to generate figures and graphics

One option that provides these features is Jupyter

As a bonus, Jupyter also provides

• Nicely formatted output in the browser, including tables, figures, animation, video, etc.
• The ability to mix in formatted text and mathematical expressions between cells
• Functions to generate PDF slides, static HTML, etc.

Whether you end up using Jupyter as your primary work environment or not, you’ll find learning about it an excellent investment

### Installing Jupyter¶

There are two steps here:

1. Installing Jupyter itself
2. Installing IJulia, which serves as an interface between Jupyter notebooks and Julia

In fact you can get both by installing IJulia

However, if you have the bandwidth, we recommend that you

1. Do the two steps separately
2. In the first step, when installing Jupyter, do this by installing the larger package Anaconda Python

The advantage of this approach is that Anaconda gives you not just Jupyter but the whole scientific Python ecosystem

This includes things like plotting tools we’ll make use of later

#### Installing Anaconda¶

If you are asked during the installation process whether you’d like to make Anaconda your default Python installation, say yes — you can always remove it later

Otherwise you can accept all of the defaults

Note that the packages in Anaconda update regularly — you can keep up to date by typing conda update anaconda in a terminal

#### Installing IJulia¶

Now open up a Julia terminal and type

Pkg.add("IJulia")


If you have problems, consult the installation instructions

#### Other Requirements¶

Since IJulia runs in the browser it might be a good time to update your browser

One good option is to install a free modern browser such as Chrome or Firefox

In our experience Chrome plays well with IJulia

### Getting Started¶

Now either

1. search for and start the Jupyter notebook application on your machine or
2. open up a terminal (or cmd in Windows) and type jupyter notebook

You should see something (not exactly) like this

The page you are looking at is called the “dashboard”

The address localhost:8888/tree you see in the image indicates that the browser is communicating with a Julia session via port 8888 of the local machine

If you click on “New” you should have the option to start a Julia notebook

Here’s what your Julia notebook should look like

The notebook displays an active cell, into which you can type Julia commands

### Notebook Basics¶

Notice that in the previous figure the cell is surrounded by a green border

This means that the cell is in edit mode

As a result, you can type in Julia code and it will appear in the cell

When you’re ready to execute these commands, hit Shift-Enter instead of the usual Enter

#### Switching modes¶

• To switch to command mode from edit mode, hit the Esc key
• To switch to edit mode from command mode, hit Enter or click in a cell

The modal behavior of the Jupyter notebook is a little tricky at first but very efficient when you get used to it

#### Working with Files¶

To run an existing Julia file using the notebook you can copy and paste the contents into a cell in the notebook

If it’s a long file, however, you have the alternative of

1. Saving the file in your present working directory
2. Executing include("filename") in a cell

The present working directory can be found by executing the command pwd()

#### Plots¶

Let’s generate some plots

There are several options we’ll discuss in detail later

For now lets start with Plots.jl

Pkg.add("Plots")


Now try copying the following into a notebook cell and hit Shift-Enter

using Plots
plot(sin, -2pi, pi, label="sine function")


You’ll see something like this (although the style of plot depends on your installation — more on this later)

### Working with the Notebook¶

Let’s go over some more Jupyter notebook features — enough so that we can press ahead with programming

#### Tab Completion¶

A simple but useful feature of IJulia is tab completion

For example if you type rep and hit the tab key you’ll get a list of all commands that start with rep

IJulia offers up the possible completions

This helps remind you of what’s available and saves a bit of typing

To get help on the Julia function such as repmat, enter ?repmat

Documentation should now appear in the browser

#### Other Content¶

In addition to executing code, the Jupyter notebook allows you to embed text, equations, figures and even videos in the page

For example, here we enter a mixture of plain text and LaTeX instead of code

Next we Esc to enter command mode and then type m to indicate that we are writing Markdown, a mark-up language similar to (but simpler than) LaTeX

(You can also use your mouse to select Markdown from the Code drop-down box just below the list of menu items)

Now we Shift + Enter to produce this

#### Inserting unicode (e.g., Greek letters)¶

Julia supports the use of unicode characters such as α and β in your code

Unicode characters can be typed quickly in Jupyter using the tab key

Try creating a new code cell and typing \alpha, then hitting the tab key on your keyboard

#### Shell Commands¶

You can execute shell commands (system commands) in IJulia by prepending a semicolon

For example, ;ls will execute the UNIX style shell command ls, which — at least for UNIX style operating systems — lists the contents of the current working directory

These shell commands are handled by your default system shell and hence are platform specific

### Sharing Notebooks¶

Notebook files are just text files structured in JSON and typically end with .ipynb

A notebook can easily be saved and shared between users — you just need to pass around the ipynb file

To open an existing ipynb file, import it from the dashboard (the first browser page that opens when you start Jupyter notebook) and run the cells or edit as discussed above

#### nbviewer¶

The Jupyter organization has a site for sharing notebooks called nbviewer

The notebooks you see there are static HTML representations of notebooks

However, each notebook can be downloaded as an ipynb file by clicking on the download icon at the top right of its page

Once downloaded you can open it as a notebook, as we discussed just above

## Alternatives to Jupyter¶

In this lecture series we’ll assume that you’re using Jupyter

Doing so allows us to make sure that everything works in at least one sensible environment

But as you work more with Julia you will want to explore other environments as well

Here are some notes on working with the REPL, text editors and other alternatives

### Editing Julia Scripts¶

You can run Julia scripts from the REPL using the include("filename") syntax

The file needs to be in the present working directory, which you can determine by typing pwd()

You also need to know how to edit them — let’s discuss how to do this without Jupyter

#### IDEs¶

IDEs (Integrated Development Environments) combine an interpreter and text editing facilities in the one application

For Julia one nice option is Juno

#### Text Editors¶

The beauty of text editors is that if you master one of them, you can use it for every coding task you come across, regardless of the language

At a minimum, a text editor for coding should provide

• Syntax highlighting for the languages you want to work with
• Automatic indentation
• Efficient text manipulation (search and replace, copy and paste, etc.)

There are many text editors that speak Julia, and a lot of them are free

Suggestions:

• Atom is a popular open source next generation text editor
• Sublime Text is a modern, popular and highly regarded text editor with a relatively moderate learning curve (not free but trial period is unlimited)
• Emacs is a high quality free editor with a sharper learning curve

Finally, if you want an outstanding free text editor and don’t mind a seemingly vertical learning curve plus long days of pain and suffering while all your neural pathways are rewired, try Vim

## Exercises¶

### Exercise 1¶

If Jupyter is still running, quit by using Ctrl-C at the terminal where you started it

Now launch again, but this time using jupyter notebook --no-browser

This should start the kernel without launching the browser

Note also the startup message: It should give you a URL such as http://localhost:8888 where the notebook is running

Now

1. Start your browser — or open a new tab if it’s already running
2. Enter the URL from above (e.g. http://localhost:8888) in the address bar at the top

You should now be able to run a standard Jupyter notebook session

This is an alternative way to start the notebook that can also be handy

### Exercise 2¶

This exercise will familiarize you with git and GitHub

Git is a version control system — a piece of software used to manage digital projects such as code libraries

In many cases the associated collections of files — called repositories — are stored on GitHub

GitHub is a wonderland of collaborative coding projects

Git is an extremely powerful tool for distributed collaboration — for example, we use it to share and synchronize all the source files for these lectures

There are two main flavors of Git

1. The plain vanilla command line Git version

2. The various point-and-click GUI versions

As an exercise, try

1. Installing Git
2. Getting a copy of QuantEcon.jl using Git

For example, if you’ve installed the command line version, open up a terminal and enter

git clone https://github.com/QuantEcon/QuantEcon.jl


(This is just git clone in front of the URL for the repository)

Even better,