You are on page 1of 32

Master 1 – Géoénergies

Outils Numériques pour les


Géosciences

TP2
Interaction avec le système d’exploitation (Linux et Python os),
introduction aux librairies NumPy et Matplotlib
INTERACTING WITH THE OPERATING SYSTEM
(LINUX COMMANDS AND OS PYTHON PACKAGE)

2022-2023 2
Linux Commands
Command Desciption
pwd Print working directory
ls List files and subdirectories
cd name_directory Change directory (to name_directory)
cd .. Move up one level of directory
mkdir Make new directory
rmdir Remove directory
rm Remove file
cp Copy file
mv Move file
These commands will be used in the Seismic courses of next semester.

2022-2023 3
os functions
Method Description Linux equivalent
os.chdir(path) Changes the current directory to path cd
os.getcwd() Returns the current working directory pwd
as a string
os.listdir(path) Returns a list of files and subdirectories ls
in path, which
defaults to the current directory
os.mkdir(dirname) Creates a directory named dirname. mkdir
Errors if directory already exists.
os.remove(path) Deletes file at path. Errors if path points rm
to a directory or does not exist.
os.rmdir(path) Deletes directory at path. Errors if rmdir
directory is not empty or does not exist.

2022-2023 4
os functions

 Les applications premières de ces commandes (dans le cadre


des TP) seront de:
• Pourvoir naviguer dans les différents répertoires afin d’accéder à des
fichiers pour charger des données (et éventuellement des fonctions
d’un fichier .py) ;
• Pouvoir naviguer et créer des répertoires afin d’exporter des fichiers
de résultats.

2022-2023 5
Based on Python Data Science Handbook

INTRODUCTION TO NUMPY

2022-2023 6
Introduction to NumPy

 NumPy (short name for Numerical Python)


• Provides an efficient interface to store and operate on data
• Based on C ➔ Much faster than Python lists
• Must be of single type e.g. numeric, str, bool (unlike lists, which can
have mixed types)
• Includes mathematical functions (e.g. trigonometric, statistical…),
linear algebra routines, Fourier transforms, random number
capabilities

 To use NumPy, you must import it (usually imported using the


alias name np) : import numpy as np

2022-2023 7
Getting started with NumPy
 Importing the package :

 Checking the version :

 Access built-in documentation :


• To see the list of NumPy functions, type np.<TAB>
• In Jupyter, press SHIFT + TAB to access the docstring of a function
(the cursor must be on the function name) or type
np.namefunction? (e.g. np.arange?)
• To display the help below the input cell, type
help(np.namefunction) (e.g. help(np.namefunction))

2022-2023 8
Creating arrays in NumPy
import numpy as np

Function Example TP
2
np.array(list) [In] np.array([3,4,7,2,-1])
[Out] array([ 3, 4, 7, 2, -1])
2
np.arange(start,stop,step) [In] np.arange(0,8,2)
[Out] array([0, 2, 4, 6])
2
np.linspace(start,stop,num) [In] np.linspace(0,6,4)
[Out] array([0., 2., 4., 6.])
np.logspace(start,stop,num) [In] np.logspace(-1,2,4)
[Out] array([ 0.1, 1. , 10. , 100. ])
2
np.zeros(shape) [In] np.zeros((3,2))
[Out] array([[0., 0.], [0., 0.], [0., 0.]])
2
np.ones(shape) [In] np.ones((3,2))
[Out] array([[1., 1.], [1., 1.], [1., 1.]])
np.full(shape,fill_value) [In] np.full((3,2),3.1)
[Out] array([[3.1, 3.1], [3.1, 3.1], [3.1, 3.1]])

2022-2023 9
Array manipulation in NumPy
 Attributes of arrays : determine the dimension, size and shape
of arrays
import numpy as np
x = np.full((3,2),3.1)

Method Example TP
Note : The function len(x) used for Python
ndim [In] x.ndim
lists can be used for arrays; it returns
[Out] 2
2
• The size of the array if the array is one
shape [In] x.shape dimensional;
[Out] (3, 2)
2
• The number of dimensions if the arrays
size [In] x.size has more than one dimension.
[Out] 6

2022-2023 10
Array manipulation in NumPy
 Array Indexing : Get and set the value of individual elements
One-dimensional array Multidimensional array
• Index starting at 0 • Use list [i,j] to access elements

• Negative indices to index elements


from the end

2022-2023 11
Array manipulation in NumPy
 Logical Indexing : Get elements that fulfills a given condition

2022-2023 12
Array manipulation in NumPy
 Array Slicing : Get and set subarrays [start:stop:step]
One-dimensional array

2022-2023 13
Array manipulation in NumPy
 Array Slicing : Get and set subarrays [start:stop:step]
Multidimensional array
Accessing rows and columns :

2022-2023 14
Array manipulation in NumPy
 Reshaping of arrays: Change the shape of a given array

2022-2023 15
Trigonometric functions

import numpy as np

Function Description
np.pi Pi value: 3.141592653589793
np.sin(x) Sinus
np.cos(x) Cosinus
np.tan(x) Tangent
np.arcsin(x) Arcsinus
np.arccos(x) Arccosinus
np.arctan(x) Arctangent

2022-2023 16
Statistical functions
import numpy as np

Function NaN-safe Function Description


np.sum(a) np.nansum(a) Compute sum of elements
np.prod(a) np.nanprod(a) Compute product of elements
np.max(a) np.nanmax(a) Find maximum value
np.min(a) np.nanmin(a) Find minimum value
np.argmax(a) np.nanargmax(a) Find index of maximum value
np.argmin(a) np.nanargmin(a) Find index of minimum value
np.mean(a) np.nanmean(a) Compute mean of elements
np.std(a) np.nanstd(a) Compute standard deviation
np.any Evaluate whether any elements are true
np.all Evaluate whether all elements are true

2022-2023 17
Based on Python Data Science Handbook
and Matplotlib documentation

INTRODUCTION TO MATPLOTLIB

2022-2023 18
Introduction to Matplotlib

 Matplotlib :
• Multiplatform data visualization built on NumPy arrays
• Similar to Matlab’s graphical plotting library
• Lots of controls and parameters, but can be tedious

 To use Matplotlib, you must import it. We usually only work


with the Pyplot module of Matplotlib (usually imported using
the alias name plt) :

import matplotlib.pyplot as plt

2022-2023 19
Plots in Matplotlib
Line Plots Scatter Plots

Pseudo color Plots Contour Plots 3D Plots

2022-2023 20
Plots in Matplotlib
Histograms Polar plots Image displays

Streamline Plots

2022-2023 21
Line plot

2022-2023 22
Line plot

2022-2023 23
Line plot

2022-2023 24
Matplotlib interfaces
Matplotlib has two interfaces (different syntaxes):
MATLAB-style interface Object-oriented interface
 Fast and convenient for simple  More powerful, especially when
plots you want more control on your
 “Historical” syntax : Matplotlib figure.
was originally written as a Python  More inline with the fact that
alternative to Matplotblib Python is object-oriented
 The plotting commands are  The plotting commands are
applied to the current figure and applied to explicit Figure and
axes. Axes objects, i.e. these objects
are specified prior to using the
plotting commands.

2022-2023 25
Matplotlib interfaces
MATLAB-style interface

Object-oriented interface

2022-2023 26
Object-oriented plotting

2022-2023 27
Matlab-style vs Object-oriented Plotting

 Most plt functions (Matlab-style interface) translate directly


to ax methods (object-oriented interface).
• e.g. plt.plot → ax.plot(), plt.legend()→ax.legend(), …
 BUT there are exceptions. For instance functions to set axes
limits or add labels and titles differ between the Matlab-style
and the object-oriented interfaces:
• plt.xlabel() → ax.set_xlabel()
• plt.ylabel() → ax.set_ylabel()
• plt.xlim() → ax.set_xlim()
• plt.ylim() → ax.set_ylim()
• plt.title() → ax.set_title()

2022-2023 28
Object-oriented Plotting

 In the object-oriented interface, we set these properties


simultaneously using the ax.set() method :

2022-2023 29
DATA

2022-2023 30
Experimental setup

Borgomano et al., 2017

2022-2023 31
Experimental setup
Channel 1 Channel 2

P S

P S

Channel 3 Channel 4

2022-2023 32

You might also like