Introduction Julia

Install Julia

Installation of Julia in Mac and Windows is very simple.

For linux, if we have a Ubuntu, we can go to https://julialang.org/downloads/ and download a version of "Generic Linux Binaries for x86". Then decompress it, you will see julia has been there (bin directory).

The usage of jupyter lab for Julia:

启动julia,然后在julia terminal中输入

using Pkg

Pkg.add("IJulia")

装完后退出,然后启动jupyter lab即可。

Basics of Julia

Note that the bacics of Julia was studied by following the chapter by Jesús Fernández-Villaverde (see Chapter_HPC_8_Julia.pdf)

For the sections begin with JFV (the first letters of the name of Jesús Fernández-Villaverde), that means those are from his chapter.

JFV-1.1 $\sim$ 1.2

The result from the last computation performed by Julia will always be stored in ans, see the example below


In [22]:
a = 1


Out[22]:
1

In [23]:
b = ans+2.
println(b)
print(ans)


3.0
1

When using new package in Julia, just use


In [25]:
using PyPlot


┌ Info: Precompiling PyPlot [d330b81b-6aea-500a-939a-2ce795aea3ee]
└ @ Base loading.jl:1260
┌ Info: Installing matplotlib via the Conda matplotlib package...
└ @ PyCall /Users/ywfang/.julia/packages/PyCall/zqDXB/src/PyCall.jl:697
┌ Info: Running `conda install -y matplotlib` in root environment
└ @ Conda /Users/ywfang/.julia/packages/Conda/3rPhK/src/Conda.jl:113
Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... done

## Package Plan ##

  environment location: /Users/ywfang/.julia/conda/3

  added / updated specs:
    - matplotlib


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    cycler-0.10.0              |           py37_0          14 KB  defaults
    freetype-2.10.2            |       ha233b18_0         570 KB  defaults
    kiwisolver-1.2.0           |   py37h04f5b5a_0          55 KB  defaults
    libpng-1.6.37              |       ha441bb4_0         262 KB  defaults
    matplotlib-3.2.1           |                0          21 KB  defaults
    matplotlib-base-3.2.1      |   py37h5670ca0_0         5.3 MB  defaults
    pyparsing-2.4.7            |             py_0          65 KB  defaults
    python-dateutil-2.8.1      |             py_0         215 KB  defaults
    tornado-6.0.4              |   py37h1de35cc_1         597 KB  defaults
    ------------------------------------------------------------
                                           Total:         7.1 MB

The following NEW packages will be INSTALLED:

  cycler             pkgs/main/osx-64::cycler-0.10.0-py37_0
  freetype           pkgs/main/osx-64::freetype-2.10.2-ha233b18_0
  kiwisolver         pkgs/main/osx-64::kiwisolver-1.2.0-py37h04f5b5a_0
  libpng             pkgs/main/osx-64::libpng-1.6.37-ha441bb4_0
  matplotlib         pkgs/main/osx-64::matplotlib-3.2.1-0
  matplotlib-base    pkgs/main/osx-64::matplotlib-base-3.2.1-py37h5670ca0_0
  pyparsing          pkgs/main/noarch::pyparsing-2.4.7-py_0
  python-dateutil    pkgs/main/noarch::python-dateutil-2.8.1-py_0
  tornado            pkgs/main/osx-64::tornado-6.0.4-py37h1de35cc_1



Downloading and Extracting Packages
tornado-6.0.4        | 597 KB    | ########## | 100% 
matplotlib-3.2.1     | 21 KB     | ########## | 100% 
pyparsing-2.4.7      | 65 KB     | ########## | 100% 
matplotlib-base-3.2. | 5.3 MB    | ########## | 100% 
cycler-0.10.0        | 14 KB     | ########## | 100% 
freetype-2.10.2      | 570 KB    | ########## | 100% 
kiwisolver-1.2.0     | 55 KB     | ########## | 100% 
python-dateutil-2.8. | 215 KB    | ########## | 100% 
libpng-1.6.37        | 262 KB    | ########## | 100% 
Preparing transaction: ...working... done
Verifying transaction: ...working... done
Executing transaction: ...working... done
┌ Warning: PyPlot is using tkagg backend, which is known to cause crashes on MacOS (#410); use the MPLBACKEND environment variable to request a different backend.
└ @ PyPlot /Users/ywfang/.julia/packages/PyPlot/XHEG0/src/init.jl:192

JFV-1.3 Packages

Recall that the first thing you need is to switch to the package manager mode with ]. After doing so, and to check the status of your packages, and to add, update, and remove additional packages, you can use:


In [ ]:
st # checks status
add IJulia # add package IJulia
up IJulia # update IJulia rm IJulia # remove package

Genrally we can use a package in the julia shell mode by typing:


In [31]:
using PyPlot

or we can use a specified function of a package, say


In [32]:
import PyPlot: plot

In most occasions, however, importing the whole package will be the simplest approach and the recommended default. Some other useful packages:

  1. Plots : easy plots.
  2. Gadfly : another plotting package; it follows Hadley Wickhams’s ggplot2 for R and the ideas of Wilkinson (2005).
  3. Distributions : probability distributions and associated functions.
  4. DataFrames : to work with tabular data.
  5. Pandas : a front-end to work with Python’s Pandas.
  6. TensorFlow : a Julia wrapper for TensorFlow.

We can also install some other packages that can faciliate the interaction of Julia and other languages like python

  1. Pycall : call Python functions.
  2. JavaCall : call Java from Julia.
  3. RCall : embedded R within Julia.

JFV-1.4 Types

Julia has variables, values, and types. A variable is a name bound to a value. Julia is case sensitive, so "a" is a different variable than "A". A variable doesn't hve a type, but its value has the type which attributes the content. All the values in Julia are thus $objects$.

In the base implementation of Julia, there are 230 different methods for the function sum! You can list them with the command as in:


In [ ]:
method_list = methods(+) # list all the methods for sum

In [ ]:

There is a types tree, but we don't need keep it in mind because we can use the built-in funciton to check its spertype and subtypes


In [39]:
supertype(Float64)


Out[39]:
AbstractFloat

In [40]:
subtypes(Integer)


Out[40]:
3-element Array{Any,1}:
 Bool
 Signed
 Unsigned

In [41]:
supertype(Integer)


Out[41]:
Real

In [42]:
supertype(Real)


Out[42]:
Number

We can always check the type of a variable with


In [45]:
a=1
typeof(a)


Out[45]:
Int64

In [46]:
# determine type of elements in collection a
eltype(a)


Out[46]:
Int64

You can fix the type a variable with the operator :: (read as “is an instance of”):


In [58]:
a::Float64


Out[58]:
1.0

In [65]:
b::Int = 10


syntax: type declarations on global variables are not yet supported

Stacktrace:
 [1] top-level scope at /Users/ywfang/.julia/packages/IJulia/DrVMH/src/kernel.jl:52

In [66]:
sizeof(a) # check the memory size of the variable


Out[66]:
8

In [73]:
# If you want to know more about the state of your memory at any given time, you can
# check the workspace

varinfo()


Out[73]:
name size summary
Base Module
Core Module
Main Module
a 8 bytes Float64
b 8 bytes Int64
data 7.629 MiB 1000000-element Array{Float64,1}
method_list 296.392 KiB Base.MethodList

In [89]:
a=0


Out[89]:
0

In [90]:
varinfo()


Out[90]:
name size summary
Base Module
Core Module
Main Module
a 8 bytes Int64
b 8 bytes Int64
data 7.629 MiB 1000000-element Array{Float64,1}
method_list 296.556 KiB Base.MethodList

In [ ]:

Julia’s sophisticated type structure provides you with extraordinary capabilities. For instance, you can use a greek letter as a variable by typing its LATEX’s name plus pressing tab: \alpha (+ press Tab) You will get


In [91]:
α # The code will be much easier to read and maintain.


Out[91]:
1

You can extend this capability of to all Unicode characters and operate on exotic variables


In [93]:
α = 1
β = 2
sum = α + β
println(sum)


3

In [ ]:


In [ ]:


In [5]:
# Listing1.3

using Statistics

@time begin
    data = Float64[]
    for i in 1:10^6
        group = Float64[]
        for j in 1:5*10^2
            push!(group, rand())
        end
        push!(data, mean(group))
    end
    println("98% of the means lie in the estimated range:",
    (quantile(data, 0.01), quantile(data,0.99)))
    
    end;


98% of the means lie in the estimated range:(0.4699297053832717, 0.5301852200037569)
  7.718874 seconds (10.00 M allocations: 7.974 GiB, 15.64% gc time)

In [ ]:


In [ ]:


In [2]:
# Listing 1.4 Fast code example compared to Listing 1.3

using Statistics

@time begin
    data = [mean(rand(5*10^2)) for _ in 1:10^6]
    println("98% of the means lie in the estimated range: ", (
            quantile(data, 0.01), quantile(data,0.99)))
end


98% of the means lie in the estimated range: (0.46999055943827006, 0.5299175853053604)
  1.727430 seconds (1.14 M allocations: 3.904 GiB, 43.43% gc time)

In [6]:
;echo '1' # ";" can be used to activate the shell mode


1

In [8]:



UndefVarError: clearconsole not defined

Stacktrace:
 [1] top-level scope at In[8]:1

In [ ]: