Julia

Multiple dispatch

Author

David Gómez-Castro

Plots.jl

Tutorial básico

Creando animaciones

using Plots 
anim = @animate for n=1:20
    plot( x-> sin(n*x) , label="")
end;

gif(anim, "animation.gif",  fps = 30)

mp4(anim, "video.mp4",  fps = 30)

En un notebook se puede hacer

using Plots
@gif for n=1:20
    plot( x-> sin(n*x) , label="" )
end
[ Info: Saved animation to /Users/david/Library/Mobile Documents/com~apple~CloudDocs/Universidad/Docencia/Julia Compumates/Github/04-PaquetesHabituales/tmp.gif

Otras librerías de representación

Input Output (IO)

Hay múltiples paquetes dentro de JuliaIO

Dictionarios

Para sacar datos a un archivo, es habitual crear un Dictionary

dict = Dict("mivariable" => 1, "b" => 2, "unvector" => [1,2,3], 1=>"mi variable aquí")
Dict{Any, Any} with 4 entries:
  "unvector"   => [1, 2, 3]
  "b"          => 2
  "mivariable" => 1
  1            => "mi variable aquí"

Se puede acceder al contenido como si fuese un vector

@show dict["unvector"]
dict["unvector"] = [1, 2, 3]
3-element Vector{Int64}:
 1
 2
 3

Variables de fecha y hora

Dates.jl es parte de Standard Library

TimeZones.jl

El problema de zonas horarias es muy difícil Vídeo de Computerphile

FileIO.jl

FileIO aims to provide a common framework for detecting file formats and dispatching to appropriate readers/writers. The two core functions in this package are called load and save, and offer high-level support for formatted files (in contrast with julia’s low-level read and write). To avoid name conflicts, packages that provide support for standard file formats through functions named load and save are encouraged to register with FileIO.

JLD2.jl

JLD2 saves and loads Julia data structures in a format comprising a subset of HDF5, without any dependency on the HDF5 C library. JLD2 is able to read most HDF5 files created by other HDF5 implementations supporting HDF5 File Format Specification Version 3.0 (i.e. libhdf5 1.10 or later) and similarly those should be able to read the files that JLD2 produces. JLD2 provides read-only support for files created with the JLD package.

JSON.jl

Para gestionar archivos JSON.

MAT.jl

Para leer archivos de MATLAB.

JuliaData

Data manipulation, storage, and I/O in Julia

DataFrames.jl

DataFrames.jl provides a set of tools for working with tabular data in Julia. Its design and functionality are similar to those of pandas (in Python) and data.frame, data.table and dplyr (in R), making it a great general purpose data science tool.

DataFrames.jl plays a central role in the Julia Data ecosystem, and has tight integrations with a range of different libraries. DataFrames.jl isn’t the only tool for working with tabular data in Julia – as noted below, there are some other great libraries for certain use-cases – but it provides great data wrangling functionality through a familiar interface.


using DataFrames
DataFrame()
0×0 DataFrame
DataFrame(A=1:3, B=5:7, fixed=1)
3×3 DataFrame
RowABfixed
Int64Int64Int64
1151
2261
3371
DataFrame("customer age" => [15, 20, 25],
                 "first name" => ["Rohit", "Rahul", "Akshat"])
3×2 DataFrame
Rowcustomer agefirst name
Int64String
115Rohit
220Rahul
325Akshat
dict = Dict("customer age" => [15, 20, 25],
                   "first name" => ["Rohit", "Rahul", "Akshat"])
Dict{String, Vector} with 2 entries:
  "first name"   => ["Rohit", "Rahul", "Akshat"]
  "customer age" => [15, 20, 25]

Más ejemplos

Otros paquetes

Tables.jl

CSV.jl

IndexedTables.jl

RData.jl

LinearAlgebra.jl

Es parte de Standard Library

Operaciones básicas

using LinearAlgebra
A = [1 2 3; 4 1 6; 7 8 1]
3×3 Matrix{Int64}:
 1  2  3
 4  1  6
 7  8  1
@show tr(A)
@show det(A)
println("inv(A) = ")
inv(A)
tr(A) = 3
det(A) = 104.0
inv(A) = 
3×3 Matrix{Float64}:
 -0.451923   0.211538    0.0865385
  0.365385  -0.192308    0.0576923
  0.240385   0.0576923  -0.0673077

La sintaxis para sistemas es la habitual

b = [1,2,3]
A \ b 
3-element Vector{Float64}:
 0.2307692307692308
 0.15384615384615383
 0.15384615384615385

Y las descomposiciones

eigvals(A) 
3-element Vector{Float64}:
 -6.214612641961068
 -1.554026596484783
 10.768639238445848

Factorizaciones

LU permite exportar L, U y vector de permutaciones, o matriz de permutaciones

lu(A)
LU{Float64, Matrix{Float64}, Vector{Int64}}
L factor:
3×3 Matrix{Float64}:
 1.0        0.0   0.0
 0.571429   1.0   0.0
 0.142857  -0.24  1.0
U factor:
3×3 Matrix{Float64}:
 7.0   8.0      1.0
 0.0  -3.57143  5.42857
 0.0   0.0      4.16

SVD

svd(A)
SVD{Float64, Float64, Matrix{Float64}, Vector{Float64}}
U factor:
3×3 Matrix{Float64}:
 -0.254232  -0.28571   -0.923978
 -0.458299  -0.805704   0.375238
 -0.851662   0.518856   0.0738954
singular values:
3-element Vector{Float64}:
 12.015096056147224
  5.870562197511579
  1.4744376035300788
Vt factor:
3×3 Matrix{Float64}:
 -0.669912   -0.647524  -0.363223
  0.0210319   0.472481  -0.88109
  0.742142   -0.597892  -0.302902

Matrices especiales

Type   Description
Symmetric Symmetric matrix
Hermitian Hermitian matrix
UpperTriangular Upper triangular matrix
UnitUpperTriangular Upper triangular matrix with unit diagonal
LowerTriangular Lower triangular matrix
UnitLowerTriangular Lower triangular matrix with unit diagonal
UpperHessenberg Upper Hessenberg matrix
Tridiagonal Tridiagonal matrix
SymTridiagonal Symmetric tridiagonal matrix
Bidiagonal Upper/lower bidiagonal matrix
Diagonal Diagonal matrix
UniformScaling Uniform scaling operator

A = UnitUpperTriangular( [ 1 2 3 ; 1 2 3 ; 1 2 3 ] )
3×3 UnitUpperTriangular{Int64, Matrix{Int64}}:
 1  2  3
 ⋅  1  3
 ⋅  ⋅  1

Más sobre matrices especiales

Estadística y teoría de la medida

Random.jl es parte de Standard Library

using Random 
@show rand()
@show rand( (-1,2) )
@show rand(5:10);
rand() = 0.8486290357514211
rand((-1, 2)) = -1
rand(5:10) = 9

Statistics.jl es parte de Standard Library.

Es reseñable la familia JuliaStats: DataFrames, Distributions, HypothesisTests, TimeSeries, …

Distributions.jl

The Distributions package provides a large collection of probabilistic distributions and related functions. Particularly, Distributions implements:

  • Sampling from distributions
  • Moments (e.g mean, variance, skewness, and kurtosis), entropy, and other properties
  • Probability density/mass functions (pdf) and their logarithm (logpdf)
  • Moment-generating functions and characteristic functions
  • Maximum likelihood estimation
  • Distribution composition and derived distributions (Cartesian product of distributions, truncated distributions, censored distributions)

using Random, Distributions
d = Normal()
d + 1.0
Normal{Float64}(μ=1.0, σ=1.0)
@show mean(d)
@show rand(d, 3)
mean(d) = 0.0
rand(d, 3) = [0.9226994090969068, -1.112146849970671, -0.4728081168414128]
3-element Vector{Float64}:
  0.9226994090969068
 -1.112146849970671
 -0.4728081168414128
x = [0, 0.4, -0.4] 
fit(Normal, x)
Normal{Float64}(μ=0.0, σ=0.32659863237109044)

Ver también MeasureTheory.jl

Turing.jl

Turing is a general-purpose probabilistic programming language for robust, efficient Bayesian inference and decision making. Current features include:

  * General-purpose probabilistic programming with an intuitive modelling interface;
  * Robust, efficient Hamiltonian Monte Carlo (HMC) sampling for differentiable posterior distributions;
  * Particle MCMC sampling for complex posterior distributions involving discrete variables and stochastic control flow; and
  * Compositional inference via Gibbs sampling that combines particle MCMC, HMC and random-walk MH (RWMH).

Un ejemplo sencillo

Cálculo paralelo

En este curso no haremos hincapié en las capacidades y técnicas de Julia para hacer cálculo en paralelo.

Para el cálculo paralelo en CPU se cuenta con Distributed en la Standard Library. Véase este Tutorial.

Para cálculo paralelo en GPU hay un conjunto de paquetes llamados JuliaGPU: Cuda.jl, AMDGPU.jl, Metal.jl, OpenCL.jl, …

Barras de progreso con ProgressMeter

using ProgressMeter

@showprogress 1 "Computing..." for i in 1:50
    sleep(0.1)
end
Computing...  20%|███████▊                               |  ETA: 0:00:04
Computing...  40%|███████████████▋                       |  ETA: 0:00:03
Computing...  60%|███████████████████████▍               |  ETA: 0:00:02
Computing...  80%|███████████████████████████████▎       |  ETA: 0:00:01
Computing... 100%|███████████████████████████████████████| Time: 0:00:05
using Distributed
using ProgressMeter

@showprogress @distributed for i in 1:10
    sleep(0.1)
end
Progress:  20%|████████▎                                |  ETA: 0:00:01
Progress:  30%|████████████▎                            |  ETA: 0:00:01
Progress:  40%|████████████████▍                        |  ETA: 0:00:01
Progress:  60%|████████████████████████▋                |  ETA: 0:00:00
Progress:  80%|████████████████████████████████▊        |  ETA: 0:00:00
Progress: 100%|█████████████████████████████████████████| Time: 0:00:01

DrWatson.jl

Es un paquete de gestión de investigación científica.

Permite organizar la versión de los paquetes, llevar orden de los casos simulados, y nombrar archivos de forma automática.