Skip to content

Julia Aide-mémoire

Julia est un langage dynamique de haut niveau et haute performance pour le calcul scientifique.

01

Bases

Hello World

println ajoute un saut de ligne, print non

julia
println("Hello, World!")
print("No newline")

Commentaires

#= =# pour les commentaires multi-lignes

julia
# Single-line comment

#=
  Multi-line
  comment
=#

# Docstring
"""docstring"""

REPL

ans stocke le résultat précédent

julia
$ julia
julia> 1 + 1
2
julia> ans  # previous result
2

Interpolation de chaînes

$ pour les variables, $(expression) pour les expressions

julia
name = "Alice"
age = 30
println("$name is $age")
println("$(age * 2)")

Comparaisons chaînées

Julia prend en charge les comparaisons chaînées

julia
x = 5
1 < x < 10  # true
1 <= x <= 10  # true
02

Variables

Affectation de variables

Les noms de variables Unicode sont pris en charge

julia
x = 10
name = "Alice"
π = 3.14159  # supports Unicode
δ = 0.001

Constantes

const déclare une constante globale

julia
const PI = 3.14159
const MAX_SIZE = 100
# const declares a constant

Annotations de type

:: pour annoter les types

julia
x::Int = 10
y::Float64 = 3.14
function f(x::Int)::String
  string(x)
end

Affectation multiple

L'affectation multiple est prise en charge

julia
a, b, c = 1, 2, 3
x, y = y, x  # swap
(a, b) = (1, 2)
03

Types

Types de base

typeof donne le type

julia
typeof(42)       # Int64
typeof(3.14)     # Float64
typeof("hi")     # String
typeof(true)     # Bool
typeof('a')      # Char

Conversion de type

Utilisez le nom du type comme fonction de conversion

julia
Int(3.14)    # 3
Float64(3)   # 3.0
String(42)   # "42"
Char(65)     # 'A'

Types abstraits

abstract type définit un type abstrait

julia
abstract type Animal end
abstract type Dog <: Animal end
# <: denotes subtype relationship

Structs

struct est immuable

julia
struct Point
  x::Float64
  y::Float64
end

p = Point(1.0, 2.0)
p.x  # 1.0

Structs mutables

mutable struct autorise la modification des champs

julia
mutable struct Counter
  count::Int
end

c = Counter(0)
c.count += 1

Types paramétriques

T est un paramètre de type

julia
struct Point{T}
  x::T
  y::T
end

p = Point{Float64}(1.0, 2.0)
q = Point{Int}(1, 2)
04

Dispatch multiple

Surcharge de fonctions

Fonctionnalité centrale de Julia : le dispatch multiple

julia
function describe(x::Int)
  "integer: $x"
end

function describe(x::String)
  "string: $x"
end

describe(42)      # "integer: 42"
describe("hi")    # "string: hi"

Méthodes paramétriques

where spécifie les paramètres de type

julia
function norm(p::Point{T}) where T
  sqrt(p.x^2 + p.y^2)
end

# Works for all types T

Méthodes de repli

Une méthode sans annotation de type sert de valeur par défaut

julia
function describe(x)
  "unknown: $x"
end

# No type annotation, matches all arguments

Ambiguïté de méthodes

Attention à éviter toute ambiguïté entre méthodes

julia
f(x::Int, y) = 1
f(x, y::Int) = 2
# f(1, 1) raises an ambiguity error
# Need to define f(x::Int, y::Int) = 3
05

Fonctions

Définition de fonction

return est optionnel : la dernière expression est renvoyée

julia
function add(a, b)
  return a + b
end

# Shorthand
add(a, b) = a + b

Fonctions anonymes

-> définit une fonction anonyme

julia
f = x -> x^2
f(5)  # 25

map(x -> x * 2, [1, 2, 3])

Valeurs de retour multiples

Renvoie un tuple pour plusieurs valeurs

julia
function divrem2(a, b)
  return a ÷ b, a % b
end

q, r = divrem2(10, 3)

Arguments nommés

Après ; viennent les arguments nommés

julia
function plot(x, y; style="line", color="blue")
  # style and color are keyword arguments
end

plot(1:10, 1:10, color="red")

Arguments variadiques

... collecte les arguments variadiques

julia
function sumall(args...)
  sum(args)
end

sumall(1, 2, 3, 4)  # 10

Bloc do

Le bloc do transmet une fonction anonyme

julia
map([1, 2, 3]) do x
  x ^ 2
end
# Equivalent to map(x -> x^2, [1,2,3])
06

Flux de contrôle

if-elseif-else

Expression conditionnelle

julia
if x > 0
  println("positive")
elseif x < 0
  println("negative")
else
  println("zero")
end

Opérateur ternaire

Opérateur ternaire : condition ? true_value : false_value

julia
result = x > 0 ? "pos" : "neg"

# Chained
result = x > 0 ? "pos" : x < 0 ? "neg" : "zero"

Boucle for

Itération avec for in

julia
for i in 1:5
  println(i)
end

for (i, v) in enumerate(arr)
  println(i, v)
end

Boucle while

Boucle while

julia
i = 1
while i <= 5
  println(i)
  i += 1
end

break et continue

&& évalue en court-circuit pour les conditions

julia
for i in 1:10
  i == 5 && break
  i % 2 == 0 && continue
  println(i)
end
07

Tableaux

Créer des tableaux

Les tableaux sont stockés en column-major

julia
a = [1, 2, 3, 4, 5]
b = [1 2 3; 4 5 6]  # 2x3 matrix
c = zeros(3, 3)
d = ones(5)
e = rand(2, 2)

Indexation des tableaux

Les indices commencent à 1

julia
a = [10, 20, 30, 40, 50]
a[1]      # 10 (1-based)
a[end]    # 50
a[2:4]    # [20, 30, 40]
a[[1, 3]] # [10, 30]

Opérations sur les tableaux

Le suffixe ! signifie une modification en place

julia
push!(a, 60)    # add to end
pop!(a)          # remove from end
append!(a, b)    # concatenate
sort(a)          # sort (returns new array)
sort!(a)         # in-place sort

Compréhension de tableaux

Similaire aux compréhensions de listes

julia
[x^2 for x in 1:5]
# [1, 4, 9, 16, 25]

[x^2 for x in 1:10 if x % 2 == 0]
# [4, 16, 36, 64, 100]

Broadcasting

L'opérateur . effectue le broadcasting

julia
a = [1, 2, 3]
a .^ 2       # [1, 4, 9]
f.(a)        # apply f to each element
a .+ 10      # [11, 12, 13]
08

Tuples

Tuples

Les tuples sont immuables

julia
t = (1, 2, 3)
t[1]  # 1
t[2]  # 2

# Named tuple
nt = (name="Alice", age=30)
nt.name  # "Alice"

Destructuring

Affectation par destructuration de tuple

julia
a, b, c = (1, 2, 3)
(first, second) = (10, 20)

# Ignore
_, y = (1, 2)
09

Dictionnaires

Créer des dictionnaires

Dict crée un dictionnaire

julia
d = Dict("a" => 1, "b" => 2)
d2 = Dict(:name => "Alice", :age => 30)
d["c"] = 3  # add

Accès et modification

[] pour accéder et modifier

julia
d = Dict("a" => 1, "b" => 2)
d["a"]      # 1
d["a"] = 10 # modify
delete!(d, "b")  # delete

Itération

Itérez sur les paires clé-valeur

julia
for (k, v) in d
  println(k, " => ", v)
end

keys(d)    # all keys
values(d)  # all values

Opérations sur les dictionnaires

Fonctions courantes des dictionnaires

julia
haskey(d, "a")    # true
get(d, "x", 0)     # default value 0
get!(d, "x", 0)    # add if missing
merge(d1, d2)      # merge
10

Chaînes

Bases des chaînes

Les indices des chaînes peuvent être non contigus (UTF-8)

julia
s = "Hello World"
length(s)    # 11
s[1]         # 'H'
s[1:5]       # "Hello"
lastindex(s) # 11

Opérations sur les chaînes

Fonctions de chaînes courantes

julia
uppercase("hi")    # "HI"
lowercase("HI")    # "hi"
reverse("hello")   # "olleh"
strip("  hi  ")     # "hi"

Recherche et remplacement

Rechercher et remplacer

julia
s = "Hello World"
findfirst("World", s)  # 7:11
occursin("World", s)   # true
replace(s, "World" => "Julia")  # "Hello Julia"

Split et Join

split et join

julia
split("a,b,c", ",")   # ["a", "b", "c"]
join(["a", "b"], "-")  # "a-b"
split("hello", "")     # ['h','e','l','l','o']
11

Fonctions mathématiques

Maths de base

Fonctions mathématiques intégrées

julia
abs(-5)      # 5
sqrt(16)    # 4.0
cbrt(27)    # 3.0
sign(-5)    # -1
floor(3.7)  # 3.0
ceil(3.2)   # 4.0

Fonctions trigonométriques

En radians

julia
sin(π/2)   # 1.0
cos(0)     # 1.0
tan(π/4)  # 1.0
asin(1)   # 1.5707... (π/2)

Logarithme et exponentielle

log est le logarithme naturel

julia
log(ℯ)      # 1.0 (natural log)
log2(8)    # 3.0
log10(100) # 2.0
exp(1)     # 2.718... (ℯ)

Valeurs spéciales

Constantes mathématiques et valeurs spéciales

julia
π     # 3.14159...
ℯ     # 2.71828...
Inf   # positive infinity
NaN   # not a number
im    # imaginary unit
12

Algèbre linéaire

Opérations matricielles

Bibliothèque standard LinearAlgebra

julia
using LinearAlgebra

A = [1 2; 3 4]
A'        # transpose
inv(A)    # inverse matrix
det(A)    # determinant
rank(A)   # rank

Décomposition matricielle

Diverses décompositions de matrices

julia
A = [1.0 2.0; 3.0 4.0]
F = lu(A)    # LU decomposition
F = qr(A)    # QR decomposition
F = svd(A)   # SVD decomposition
F = eigen(A) # eigendecomposition

Opérations vectorielles

Opérations sur les vecteurs

julia
v1 = [1, 2, 3]
v2 = [4, 5, 6]
dot(v1, v2)    # dot product
cross(v1, v2)  # cross product
norm(v1)       # norm
v1 ⋅ v2       # dot product (Unicode)
13

Statistiques

Statistiques de base

Bibliothèque standard Statistics

julia
using Statistics

data = [1, 2, 3, 4, 5]
mean(data)    # 3.0
median(data)  # 3.0
std(data)     # standard deviation
var(data)     # variance

Quantiles

Calcul de quantiles

julia
using Statistics

data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
quantile(data, 0.25)  # 3.25
quantile(data, 0.5)   # 5.5
quantile(data, 0.75)  # 7.75

Corrélation et covariance

Coefficient de corrélation et covariance

julia
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
cor(x, y)    # 1.0 (correlation coefficient)
cov(x, y)    # covariance
14

Tracé de graphiques

Tracé de base

Plots.jl est la bibliothèque de tracé principale

julia
using Plots

x = 1:10
y = x .^ 2
plot(x, y, title="Quadratic", label="x^2")

Nuage de points

scatter dessine un nuage de points

julia
using Plots

x = rand(50)
y = rand(50)
scatter(x, y, markersize=5, color=:red)

Sous-graphiques

layout contrôle la disposition des sous-graphiques

julia
using Plots

p1 = plot(1:10, 1:10)
p2 = plot(1:10, (1:10).^2)
plot(p1, p2, layout=(2, 1))

Sauvegarde d'image

savefig enregistre l'image

julia
using Plots

p = plot(sin, 0, 2π)
savefig(p, "sine.png")
15

DataFrames

Créer un DataFrame

DataFrames.jl est similaire à pandas

julia
using DataFrames

df = DataFrame(
  name = ["Alice", "Bob", "Carol"],
  age = [25, 30, 35],
  city = ["NYC", "LA", "SF"]
)

Accéder aux données

Accès par lignes et colonnes

julia
df.name      # column
df[1, :]     # first row
df[:, :age]  # age column
df[1:2, :]   # first two rows

Filtrer et trier

Filtrage et tri

julia
using DataFrames

filter(:age => >(28), df)  # age > 28
sort(df, :age)            # sort by age
sort(df, :age, rev=true)  # descending

Grouper et agréger

groupby + combine pour l'agrégation par groupes

julia
using DataFrames, Statistics

combine(groupby(df, :city), :age => mean => :avg_age)
16

E/S de fichiers

Lire et écrire du texte

Le bloc open do referme automatiquement le fichier

julia
# Write
open("output.txt", "w") do f
  write(f, "Hello World")
end

# Read
content = read("input.txt", String)

Lire ligne par ligne

eachline itère ligne par ligne

julia
for line in eachline("data.txt")
  println(line)
end

# Or
lines = readlines("data.txt")

Fichiers CSV

CSV.jl gère les fichiers CSV

julia
using CSV, DataFrames

df = CSV.read("data.csv", DataFrame)
CSV.write("output.csv", df)

Fichiers JSON

JSON.jl gère le JSON

julia
using JSON

data = JSON.parsefile("data.json")
JSON.print("output.json", data)
17

Modules

Définir un module

export déclare l'interface publique

julia
module MyModule

export greet, add

greet(name) = println("Hello $name")
add(a, b) = a + b

end  # module

Importer un module

Différence entre using et import

julia
using MyModule     # imports exported names
using MyModule: greet  # selective import
import MyModule        # needs MyModule.greet
import MyModule: add    # selective import

Modules standards

Modules de la bibliothèque standard

julia
using Dates        # date and time
using LinearAlgebra # linear algebra
using Statistics     # statistics
using Random         # random numbers
18

Macros

Définir une macro

Les macros opèrent sur l'AST à la compilation

julia
macro sayhi(name)
  return :(println("Hi, $name"))
end

@sayhi "Alice"  # Hi, Alice

Citation d'expressions

:() crée un objet expression

julia
ex = :(1 + 2)
# :(1 + 2)

dump(ex)
# Expr
#   head: Symbol call
#   args: Array[...]

Macros courantes

Macros courantes intégrées

julia
@time sleep(1)      # timing
@assert 1 == 1      # assertion
@show x              # print variable name and value
@elapsed sleep(0.1)  # return only time
@which sin(1)        # view method location
19

Métaprogrammation

Construction d'expressions

Expr construit un AST

julia
ex = Expr(:call, :+, 1, 2)
eval(ex)  # 3

# Equivalent to
eval(:(1 + 2))  # 3

Génération de code

Boucle pour générer du code

julia
for op in (:+, :-, :*, :/)
  eval(:(f($op, a, b) = $op(a, b)))
end

f(+, 1, 2)  # 3

Hygiène des macros

L'hygiène des macros évite les conflits de variables

julia
macro setx(val)
  return :(x = $val)
end

# Variables in macros are hygienic and won't pollute the caller's scope
20

Calcul parallèle

Multithreading

La macro @threads pour les boucles parallèles

julia
# Start: julia --threads=4
Threads.nthreads()  # 4

Threads.@threads for i in 1:100
  results[i] = compute(i)
end

Calcul distribué

Bibliothèque standard Distributed

julia
using Distributed
addprocs(4)  # add 4 worker processes

@everywhere function work(x)
  x ^ 2
end

pmap(work, 1:100)  # parallel map

Appel distant

Appel distant asynchrone

julia
using Distributed

ref = @spawnat :any sqrt(16)
fetch(ref)  # 4.0

# @spawnat executes on a specified process
21

Coroutines

Task

Task est la coroutine de Julia

julia
t = Task(() -> begin
  println("running")
  return 42
end)

schedule(t)
wait(t)

Channel

Channel permet la communication entre coroutines

julia
ch = Channel(32)

put!(ch, 1)
put!(ch, 2)
take!(ch)  # 1
take!(ch)  # 2

Producteur-consommateur

Les coroutines implémentent le modèle producteur-consommateur

julia
function producer(ch)
  for i in 1:5
    put!(ch, i)
  end
end

task = @task producer(Channel(10))
for val in task
  println(val)
end
22

Gestion des exceptions

try-catch

Structure try-catch-finally pour la gestion des exceptions.

julia
try
  risky()
catch e
  println("Error: $e")
finally
  cleanup()
end

Lever une exception

throw lève un objet exception

julia
throw(ErrorException("something wrong"))
throw(DomainError(-1, "negative"))
error("generic error")

Exception personnalisée

Héritez du type Exception

julia
struct MyError <: Exception
  msg::String
end

throw(MyError("custom error"))

Assertion

La macro @assert

julia
@assert x > 0 "x must be positive"
# Throws AssertionError when condition is false
23

Regex

Expressions régulières

r"" crée une regex

julia
re = r"\d+"
occursin(re, "abc123")  # true
match(re, "abc123")     # RegexMatch

Match

match renvoie le résultat du premier match

julia
m = match(r"(\w+)@(\w+)", "user@host")
m.match   # "user@host"
m.captures  # ["user", "host"]
m[1]      # "user"

Trouver tout

eachmatch itère sur tous les matches

julia
for m in eachmatch(r"\d+", "a1b2c3")
  println(m.match)
end
# 1, 2, 3

Remplacement

replace prend en charge les regex

julia
replace("a1b2c3", r"\d" => "#")
# "a#b#c#"

replace("hello", r"l" => "L" => count=1)
# "heLlo"
24

DateTime

Créer une date

Bibliothèque standard Dates

julia
using Dates

now()                    # current time
Date(2024, 1, 15)       # date
DateTime(2024, 1, 15, 10, 30)  # datetime

Formatage

Formatage et parsing

julia
using Dates

dt = now()
Dates.format(dt, "yyyy-mm-dd HH:MM:SS")
Date("2024-01-15", "yyyy-mm-dd")

Arithmétique des dates

Types d'intervalles de temps

julia
using Dates

d1 = Date(2024, 1, 1)
d2 = d1 + Day(30)     # add 30 days
diff = d2 - d1        # 30 days
Day(1) + Hour(12)     # datetime arithmetic
25

Packages

Installer des packages

Pkg.add installe des packages

julia
using Pkg
Pkg.add("Plots")
Pkg.add(["DataFrames", "CSV"])
Pkg.rm("Plots")  # remove

Gestion des packages

Commandes Pkg courantes

julia
Pkg.status()    # view installed
Pkg.update()    # update all
Pkg.instantiate()  # install per Project.toml
Pkg.activate("env")  # activate environment

Environnements

Gestion des environnements de projet

julia
# Project.toml defines dependencies
# Manifest.toml locks versions

Pkg.activate("myproject")  # activate environment
Pkg.resolve()  # resolve dependencies
26

Gestionnaire Pkg

Mode Pkg du REPL

] entre en mode Pkg du REPL

julia
julia> ]
pkg> add Plots
pkg> rm Plots
pkg> status
pkg> update
pkg> test Plots

Créer un package

generate crée un squelette de package

julia
pkg> generate MyPackage

# Directory structure
# MyPackage/
#   Project.toml
#   src/MyPackage.jl

Mode développement

dev installe en mode développement

julia
pkg> dev ./MyPackage  # local development
pkg> dev MyPackage    # dev version from GitHub
pkg> free MyPackage   # exit development mode
27

Interopérabilité

Appeler du C

ccall appelle des fonctions C

julia
ccall((:sqrt, "libm"), Float64, (Float64,), 16.0)
# 4.0

Appeler du Python

PyCall.jl appelle Python

julia
using PyCall
np = pyimport("numpy")
np.array([1, 2, 3])
np.mean([1, 2, 3])

Appeler du R

RCall.jl appelle R

julia
using RCall
R"sd(c(1,2,3,4,5))"  # call R code
28

Calcul GPU

Tableaux CUDA

CUDA.jl prend en charge les GPU NVIDIA

julia
using CUDA

a = CUDA.ones(1000)
b = CUDA.zeros(1000)
c = a .+ b  # operations on GPU

Kernel GPU

@cuda lance un kernel GPU

julia
using CUDA

function kernel!(a)
  i = threadIdx().x
  if i <= length(a)
    @inbounds a[i] *= 2
  end
  return
end

@cuda threads=256 kernel!(a)

GPU AMD

AMDGPU.jl prend en charge les GPU AMD

julia
using AMDGPU

a = ROCArray(ones(100))
b = a .* 2  # operations on AMD GPU

Was this helpful?