Python Crash Course Numpy, Scipy, Matplotlib

Similar documents
Part VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,

Part VI. Scientific Computing in Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

User-Defined Function

Bi 1x Spring 2014: Plotting and linear regression

Plotting With matplotlib

NumPy Primer. An introduction to numeric computing in Python

LECTURE 19. Numerical and Scientific Packages

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Image Processing in Python

Handling arrays in Python (numpy)

The Python interpreter

Effective Programming Practices for Economists. 10. Some scientific tools for Python

(DRAFT) PYTHON FUNDAMENTALS II: NUMPY & MATPLOTLIB

PYTHON NUMPY TUTORIAL CIS 581

NumPy and SciPy. Lab Objective: Create and manipulate NumPy arrays and learn features available in NumPy and SciPy.

PyPlot. The plotting library must be imported, and we will assume in these examples an import statement similar to those for numpy and math as

The SciPy Stack. Jay Summet

Numerical Calculations

LECTURE 22. Numerical and Scientific Packages

NumPy quick reference

MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

MO101: Python for Engineering Vladimir Paun ENSTA ParisTech

6. ADVANCED PLOTTING. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

ARTIFICIAL INTELLIGENCE AND PYTHON

Why NumPy / SciPy? NumPy / SciPy / Matplotlib. A Tour of NumPy. Initializing a NumPy array

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )

numpy-scipy February 11, 2015

Introduction to NumPy

Programming for Engineers in Python

CSC Advanced Scientific Computing, Fall Numpy

INTRODUCTION TO DATA VISUALIZATION WITH PYTHON. Working with 2D arrays

5 File I/O, Plotting with Matplotlib

NumPy. Daniël de Kok. May 4, 2017

Introductory Scientific Computing with Python

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3

Datenanalyse (PHY231) Herbstsemester 2017

Visualisation in python (with Matplotlib)

LECTURE 22. Numerical and Scientific Computing Part 2

Scientific Programming. Lecture A08 Numpy

python 01 September 16, 2016

Intro to Research Computing with Python: Visualization

Introduction to Scientific Computing with Python, part two.

2 Getting Started with Numerical Computations in Python

Python for Scientists

ENGR (Socolofsky) Week 07 Python scripts

Course May 18, Advanced Computational Physics. Course Hartmut Ruhl, LMU, Munich. People involved. SP in Python: 3 basic points

NumPy is suited to many applications Image processing Signal processing Linear algebra A plethora of others

Python for Data Analysis

Statistical Data Analysis: Python Tutorial

CME 193: Introduction to Scientific Python Lecture 5: Numpy, Scipy, Matplotlib

Problem Based Learning 2018

CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib

Exercise: Introduction to NumPy arrays

Episode 8 Matplotlib, SciPy, and Pandas. We will start with Matplotlib. The following code makes a sample plot.

NAVIGATING UNIX. Other useful commands, with more extensive documentation, are

IAP Python - Lecture 4

DSC 201: Data Analysis & Visualization

Python Advance Course via Astronomy street. Sérgio Sousa (CAUP) ExoEarths Team (

SciPy. scipy [ and links on course web page] scipy arrays

Python Matplotlib. MACbioIDi February March 2018

Implement NN using NumPy

windrose Documentation Lionel Roubeyrie & Sebastien Celles

Data Science with Python Course Catalog

UNIVERSITETET I OSLO

Intelligente Datenanalyse Intelligent Data Analysis

4. BASIC PLOTTING. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

Numpy fast array interface

AMath 483/583 Lecture 28 June 1, Notes: Notes: Python scripting for Fortran codes. Python scripting for Fortran codes.

Week Two. Arrays, packages, and writing programs

UNIVERSITETET I OSLO

Python in Economics and Finance

Practical Numpy and Matplotlib Intro

Symbols. Anscombe s quartet, antiderivative, 200. bar charts for exercise, for expenses, Barnsley fern, drawing,

#To import the whole library under a different name, so you can type "diff_name.f unc_name" import numpy as np import matplotlib.

2.1 Indefinite Loops. while <condition>: <body> rabbits = 3 while rabbits > 0: print rabbits rabbits -= 1

Short Introduction to Python Machine Learning Course Laboratory

Lezione 6. Installing NumPy. Contents

Introduction to MATLAB Practical 1

Python for Data Analysis. Prof.Sushila Aghav-Palwe Assistant Professor MIT

Introduction to Matplotlib: 3D Plotting and Animations

Partial Differential Equations II: 2D Laplace Equation on 5x5 grid

Introducing Python Pandas

2. For each of the regular expressions, give a string that will matches it:

Scientific Computing with Python. Quick Introduction

cosmos_python_ Python as calculator May 31, 2018

MATPLOTLIB. Python for computational science November 2012 CINECA.

Using the Matplotlib Library in Python 3

Lab 4 S Objectives. The string type. Exercise 0

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Sunpy Python for Solar Physics Juan Carlos Martínez Oliveros

Basic Beginners Introduction to plotting in Python

Interpolation and curve fitting

Introduction to Matlab. Summer School CEA-EDF-INRIA 2011 of Numerical Analysis

NumPy. Arno Proeme, ARCHER CSE Team Attributed to Jussi Enkovaara & Martti Louhivuori, CSC Helsinki

dicompyler-core Documentation

Chapter 5 : Informatics Practices. Class XII ( As per CBSE Board) Numpy - Array. New Syllabus Visit : python.mykvs.in for regular updates

Homework 11 - Debugging

NumPy. Computational Physics. NumPy

PART 1 PROGRAMMING WITH MATHLAB

Transcription:

Python Crash Course Numpy, Scipy, Matplotlib That is what learning is. You suddenly understand something you ve understood all your life, but in a new way. Doris Lessing Steffen Brinkmann Max-Planck-Institut für Astronomie, Heidelberg IMPRESS, 2016 1 / 44

The ingredients A working Python installation Internet connection Passion for Python If anything of the above is missing, please say so now! 2 / 44

Get help http://docs.scipy.org/doc/ http://www.numpy.org/ 3 / 44

Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 4 / 44

Motivation What and how? Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 5 / 44

Motivation What and how? What do you want to do? Create data or read data from disc Manipulate data Visualise data Write data back to disc 6 / 44

Motivation What and how? How do you want to do it? Create data or read data from disc (Python, numpy) Manipulate data (numpy, scipy) Visualise data (matplotlib) Write data back to disc (Python, numpy) 7 / 44

ndarray - the basics Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 8 / 44

ndarray - the basics import numpy import numpy as np 9 / 44

ndarray - the basics ndarray The basic data structure li = [1,2,3] a = np. array (li) An ndarray is a (usually fixed-size) multidimensional container of items of the same type and size. It is created (among others) by the function np.array http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html 10 / 44

ndarray - the basics ndarray The basic data structure >>> a. shape (3,) >>> a. dtype dtype ( int64 ) The number of dimensions and items in an array is defined by its shape, which is a tuple of N positive integers The type of items in the array is specified by a separate data-type object (dtype), one of which is associated with each ndarray. http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html 11 / 44

ndarray - the basics ndarray The basic data structure >>> a. sum () 6 >>> a [1:]. sum () 5 The contents of an ndarray can be accessed and modified by indexing or slicing the array, and via the methods and attributes of the ndarray and the np namespace. slicing generates a view on an array, not a new array. http://docs.scipy.org/doc/numpy/reference/arrays.ndarray.html 12 / 44

ndarray - the basics ndarray Empty ndarrays make no sense >>> python -m timeit -s\ " import numpy as np; a = np. array ([])"\ "[ np. append (a,x) for x in range ( int (1 e3 ))]" 100 loops, best of 3: 12.8 msec per loop >>> python -m timeit -s\ "a = []"\ "[a. append (x) for x in range ( int (1 e3 ))]" 10000 loops, best of 3: 186 usec per loop A python list is a C array of pointers to values. Therefore, appending a value is fast, but operating on every value is slow. A numpy array is a C array of values. Therefore, appending a value is slow (reallocating), but operating on every value is fast. 13 / 44

Creation Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 14 / 44

Creation Creation of ndarrays From Python list arr_1d = np. array ([1,2,3]) arr_2d = np. array ([[1,2,3], [11,22,33]]) 1D arrays are created from simple Python lists nd arrays are created from lists of lists [of lists...] 15 / 44

Creation Creation of ndarrays Filling with 0 s or 1 s >>> np. zeros (8) array ([ 0., 0., 0., 0., 0., 0., 0., 0.]) >>> np. ones ((2,3,5)) array ([[[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]], [[ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.], [ 1., 1., 1., 1., 1.]]]) np.zeros(<shape>) and np.ones(<shape>) return an array of shape <shape> filled with 0s (1s). 16 / 44

Creation Creation of ndarrays Ranges >>> np. arange (10) array ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> np. arange (3.5,10,2) array ([ 3.5, 5.5, 7.5, 9.5]) >>> np. linspace (1,3,5) array ([ 1., 1.5, 2., 2.5, 3. ]) >>> np. logspace (1,3,5) array ([10., 31.6227766, 100., 316.22776602, 1000.]) np.arange() works just like Python s range but takes floats and returns a np.array. np.linspace(<from>, <to>, <n>) and np.logspace(<from>, <to>, <n>) return ranges of <n> numbers including the boundaries. 17 / 44

Creation Reading from and Saving to Files np. save ( filename. npy,arr_1 ) arr_1_reborn = np. load ( filename. npy ) arr_2 = np. loadtxt (< table.dat >, usecols =(2,5)) np.save(<filename>, <array>) and np.load(<filename>) are the preferred ways to save and load single arrays. Use np.savez(<filename>, <array1>, <array2>,...) to save multiple arrays Use loadtxt(<filename>, <options>) to conveniently load data from text tables 18 / 44

Access and Modification Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 19 / 44

Access and Modification Working with ndarrays Operators >>> a,b = np. array ([1,2]), np. array ([11,22]) >>> a+b array ([12, 24]) >>> a*b array ([11, 44]) >>> a@b 55 Operators work element-wise Except @, which in Python 3.x abbreviates a.dot(b) 20 / 44

Access and Modification Working with ndarrays Comparison >>> a = np. linspace (0,5,10) >>> a < 2 array ([ True, True, True, True, False, False, False, False, False, False ], dtype = bool ) >>> np.all (a <2) False >>> np.any (a <2) True Also comparison operators work element-wise. To get a scalar boolean, use np.all or np.any. 21 / 44

Access and Modification Working with ndarrays Selection >>> a = np. linspace (0,5,11) >>> np. where (a <2) ( array ([0, 1, 2, 3]),) >>> a[np. where (a <2)] array ([ 0., 0.5, 1., 1.5]) >>> np. where (a <2,a,a *100) array ([ 0., 0.5, 1., 1.5, 200., 250., 300., 350., 400., 450., 500. ]) To choose some values from an array based on a boolean array, use np.where 22 / 44

Access and Modification Working with ndarrays Functions >>> np.sin (a) array ([ 0. 84147098, 0. 90929743]) >>> np.exp (a) array ([ 2. 71828183, 7. 3890561 ]) All functions and constants from math are present in numpy (or scipy). numpy functions work element-wise 23 / 44

Access and Modification From pure Python to import math def func (x): return math. sin (x) * math. exp ( -0.5* x) x = [0.1* i for i in xrange ( 10000001)] y = [ func ( ix) for ix in x] import numpy as np def func (x): return np.sin (x) * np.exp ( -0.5* x) x = np. linspace (0,10,10000001) y = func (x) convert loops to vectorised functions. 24 / 44

Access and Modification Exercises and Break 25 / 44

matplotlib Basic plotting Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 26 / 44

matplotlib Basic plotting Basic plotting plt.plot import numpy as np import matplotlib. pyplot as plt x = np. linspace (0, 10, 20) y = np.sin (x) plt. plot (x, y) plt. show () Use linspace to create x coordinates Use arithmetic expression to calculate y coordinates Plot with plt.plot(x,y) Show plot with plt.show() 27 / 44

matplotlib Basic plotting Basic plotting Colours, markers, line styles x = np. linspace (0, 10, 20) y = np.sin (x) plt. plot (x, y, plt. show () ro: ) Specify colours, markers and line style as third argument of plt.plot colours: r, g, b, c, m, y, k, w markers:., o v ^ < > * + x and more line style: - -- -. : line width (lw) and marker size (ms) as keyword arguments 28 / 44

matplotlib Basic plotting Basic plotting Multiple lines x = np. linspace (0, 10, 20) y = np.sin (x) plt. plot (x, y, g+--, x, 1e -2* x**2, m>-, lw =2, ms =10) plt. show () Repeat positional arguments for multiple lines per plot or... 29 / 44

matplotlib Basic plotting Basic plotting Multiple lines x = np. linspace (0, 10, 20) y = np.sin (x) plt. plot (x, y, cv ) plt. plot (x, y, y- ) plt. plot (x, 1e -2* x**2, plt. show () k. ) Repeat calls to plt.plot for multiple lines per plot. 30 / 44

matplotlib More plots Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 31 / 44

matplotlib More plots Scatter plots with plot x,y=np. random. normal (5,2,(2,100)) plt. plot (x,y, ko ) plt. show () Use np.random module to obtain all kind of randomly distributed data. Plot using plot without a line style. 32 / 44

matplotlib More plots Scatter plots with scatter x,y=np. random. normal (5,2,(2,100)) plt. scatter (x,y,c=x+y, s =10*x -10* y) plt. show () c sets the colour (like z value in colour maps) s sets the size of the marker 33 / 44

matplotlib More plots Histograms x,y=np. random. triangular (5,7,10,(2,1000)) n, bins, patches = plt. hist (x, 50, normed =1, facecolor = r ) plt. show () Use np.random module to obtain all kind of randomly distributed data. Generate and plot histogram by using plt.hist. The count and location of the bins are returned 34 / 44

matplotlib More plots Contour lines x = y = np. linspace ( -5,5) xx,yy = np. meshgrid (x,y) zz = np. fromfunction ( lambda i,j: np.cos (x[i ]**2+ y[j ]**2)* np.exp ( -(x[i ]**2+ y[j ]**2)/10),(50,50), dtype = int ) plt. contourf (xx,yy,zz) plt. show () Use np.meshgrid to generate grid coordinates for 2d plots. Use np.fromfunction to generate an array evaluating a function. Plot (filled) contour lines using plt.contour (plt.contourf) 35 / 44

matplotlib More plots Colour maps x = y = np. linspace ( -5,5) xx,yy = np. meshgrid (x,y) zz = np. fromfunction ( lambda i,j: np.cos (x[i ]**2+ y[j ]**2)* np.exp ( -(x[i ]**2+ y[j ]**2)/10),(50,50), dtype = int ) plt. imshow (zz, interpolation = nearest, origin = lower, extent =( -5,5, -5,5)) plt. show () Use plt.imshow to generate grid coordinates for 2d plots. Choose from a variety of interpolation methods set origin to lower for math plots set extent to limits of x and y 36 / 44

matplotlib More plots Labels x = np. linspace ( -5,5) y = np.exp (x) p1 = plt. plot (x,y) plt. yscale ( log ) plt. legend (( p1), (r some exp func,), loc = upper left ) plt. xlabel ( x[$\mu m$] ) plt. ylabel ( y[$\psi$ ] ) plt. title ( Some exponential function ) plt. text (-2, 10, nothing special ) plt. grid ( True ) plt. show () Use plt.yscale to set log or lin scale for x or y. Use plt.legend, plt.xlabel, plt.ylabel, plt.title, plt.text to set labels Use plt.grid to switch grid on an off 37 / 44

SciPy Overview Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 38 / 44

SciPy Overview Overview Many submodules for constants, FFT, integration, linear algebra, interpolation, Multi-dimensional image processing, Optimization and root finding, statistics, signal processing... There are many algorithms for each problems, make sure, you choose the right one for your problem. Usually you will need few functions. Import them directly from scipy. special import j0 from scipy. interpolate import interp1d 39 / 44

SciPy Fitting, Finding roots, Integration Outline Motivation What and how? ndarray - the basics Creation Access and Modification matplotlib Basic plotting More plots SciPy Overview Fitting, Finding roots, Integration 40 / 44

SciPy Fitting, Finding roots, Integration Fitting model to data def model (x, a, b, c): return a*x **2+ b*x + c xdata = linspace (0,10) ydata = model ( xdata, -0.3, 0.90, 8.0) + randn (50) popt, pcov = scipy. optimize. curve_fit ( func, xdata, ydata ) yfit = func ( xdata, * popt ) plot ( xdata, ydata, +, xdata, yfit, lw =2, ms =12) 41 / 44

SciPy Fitting, Finding roots, Integration Finding roots def model (x, a, b, c): return a*x **2+ b*x + c sol = scipy. optimize. fsolve ( model, [-1, 1], args = tuple ( popt )) print ( sol ) # prints : array ([ -4.30211097, 6. 83009459]) 42 / 44

SciPy Fitting, Finding roots, Integration Integration def model (x, a, b, c): return a*x **2+ b*x + c result = integrate. quad ( lambda x: model (x,* popt ), -4.3, 6.83) print ( result ) # prints : (65.43660782846362, 7.264922866452708 e -13) plt. plot ( xdata, ytest, linspace (0,10), ydata, + ) plt. fill ( xdata [np. where ( ytest >=0)], ytest [np. where ( ytest >=0)]) 43 / 44

Appendix For Further Reading For Further Reading I E. Bressert. SciPy and. O Reilly, 2012. Ivan Idris. Cookbook. O Reilly, 2012. 44 / 44