{ "cells": [ { "cell_type": "markdown", "metadata": { "toc": "true" }, "source": [ "# Table of Contents\n", "

1  Sommaire
1.1  Introduction
1.1.1  ipython
1.1.2  Coding rules
1.1.3  Documentation
1.2  More of python
1.2.1  Lists indexing
1.2.2  List comprehension and lambda function
1.2.3  filter and map
1.3  Numpy
1.3.1  Introduction
1.3.2  Type
1.3.3  Some attributes
1.3.4  Indexing/Slicing
1.3.5  Reference/Copy
1.3.6  Constructors and IO
1.3.7  Manipulation
1.4  SciPy
1.5  Matplotlib
1.5.1  Introduction
1.5.2  Plot
1.5.3  Some commands
1.5.4  Axes
1.5.5  Text and Annotate
1.5.6  Figure and Subplot
1.6  Compiled code
" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Sommaire #\n", "\n", "* Introduction\n", "\n", "* More of python\n", " \n", "* Numpy\n", "\n", "* Scipy\n", "\n", "* Matplotlib\n", "\n", "* Compiled code" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Introduction ##\n", "\n", " * Ipython\n", " * Coding rules\n", " * Existing documentation" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### ipython ###\n", "\n", " * Interactive python\n", " * Overlay on the classic python interpretor\n", " * Automatic completion\n", " * Interactive help\n", " * Support shell commands (for Unixians)\n", " * Better management of the commands history" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "import math\n", "math?\n", "!ls -l" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "\n", "### Coding rules ###\n", "\n", "* Python offers much freedom\n", "* Maybe sometime too much freedom!\n", "* Important to decide on rules\n", " * Naming conventions\n", " * Always document functions/classes (docstring)\n", " * Tests\n", "\n", "Official advice: http://legacy.python.org/dev/peps/pep-0008/\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "import this" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Documentation ###\n", "\n", "* Plenty of on-line documentation : https://docs.python.org/3/\n", " * Tutorials\n", " * Documentation of modules/functions\n", " * Source code of modules\n", "* Internet search\n", " * Of existing module\n", " * Of problem solving on forums\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## More of python ##\n", "\n", " * List indexing\n", " * List comprehension and lambda functions\n", " * Filter, map, reduce\n", " * Eval (maybe)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Lists indexing ###\n", "\n", "* indices begin at 0\n", "* indexing operator *[begin:end:step]*\n", "* can also be used with *range*\n", "* *end* is excluded of the selection\n", "* if the index *i* is negative, it is interpreted like *n+j* (where *n* is the size)\n", "* if the integer between the *:* is omitted, the default values are *0*, *size* and *1*\n", "\n", "Exercise: \n", "\n", "* Generate a list going from 0 to 9 (with range function and the list constructor)\n", " * Display the first, last, one before last elements\n", "* From this list generate a new one:\n", " * going from 0 to 4\n", " * going from 4 to 9\n", " * with the even numbers\n", " * with the odd number in decreasing order until 3\n", " * Generate a list of even number going from 2 to 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "#python 2\n", "#l = range(10)\n", "\n", "#python 3\n", "l = list(range(10))\n", "print(l[0]); print(l[-1]); print(l[-2])\n", "a = l[:]; print(a)\n", "a = l[:5]; print(a)\n", "b = l[4:]; print(b)\n", "c = l[::2]; print(c)\n", "d = l[9:2:-2]; print(d)\n", "l2= list(range(10,1,-2)); print(l2)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### List comprehension and lambda function ###\n", "\n", " * Classic method to create a list: with a *for* loop and the *append* method\n", " * List comprehension : compact syntax allowing to generate list with a single line\n", " * Use a sequence or an iterator\n", " * Syntax: *[ ]* with inside it an expression followed of 0 or more *for* ol *if* statements\n", " \n", " * Lambda function : compact syntax allowing to write unnamed function in one line\n", " (useful when a function is a parameter of another one)\n", " * Syntax : *lambda args : expression(args)*\n", "\n", "Exercise:\n", "\n", " * Create, with a loop, a list with $sin(x)$ for values of $x$ going from 0 to 1 by 0.1 step\n", " * Create the same function in one line\n", " * Create a *f* function referencing a *lambda function* doing $sin(x^2)$\n", " * Create a list with $sin(x^2)$ for values of $x$ going from 0 to 1 by 0.1 step using *f*\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "import math\n", "s = []\n", "for x in range(11):\n", " s.append(math.sin(x*0.1))\n", "s2 = [math.sin(x*0.1) for x in range(11)]\n", "print(s == s2)\n", "\n", "f = lambda x : math.sin(x*x)\n", "s3 = [f(x*0.1) for x in range(11)]" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### filter and map ###\n", "\n", "2 functions using as input argument a function and a list.\n", "Python 3, the return value is an object allowing to create lists.\n", "Python 2, the return value is a list object.\n", "\n", "* Filter : returns the elements of the input list for which the evaluation of the input function returns `true`\n", " -> the result of the input function is interpreted as boolean\n", "* Map : returns for each elements of the input list, the evaluation return by the input function.\n", " \n", "*Note : Generally, when there are two possibles syntax, the list comprehension is faster than,\n", "filter/map function, which are faster than the loops*\n", "\n", "Exercise: Test the 2 functions\n", "\n", "* get a list of integer all multiples of 3\n", "* get a list corresponding to $sin(x)$ where x is an other list." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "l1 = list(filter(lambda x: x%3==0, range(15)))\n", "print(l1)\n", "l2 = list(map(math.sin,l1))\n", "print(l2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Zip ?\n", "No !" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Numpy ##\n", " * Introduction\n", " * Arrays: type, attributes, memory\n", " * Indexing/Slicing\n", " * View: reference/copy\n", " * Constructors, IO\n", " * Manipulation" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Introduction ###\n", "\n", "* Package to use n-dimension array\n", "* Designed for scientific computation\n", "* Efficient\n", "\n", "\n", "__Restrictions__ :\n", "\n", "* Total size of the array is constant
\n", "* Elements type is homogeneous
\n", "* Static type
\n", "\n", "Official site (with documentation and tutorials) : http://docs.scipy.org/doc/numpy/user/\n", "\n", "Exercises: Use the array constructor to create some arrays. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Type ###\n", "\n", "Numpy arrays are optimized for numerical data (boolean, un/signed integer, reals and complex number on 32 or 64 bits).\n", "When an array is create, the type may be inferred by the constructor or specified. The *dtype* attribute of the *array*\n", "class store the type.\n", "\n", "Exercises: Use the *array* class constructor to create a vector or integers, of reals.\n", "Check the type of the data held in each array with de *dtype* attribute." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "import numpy as np\n", "np?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "a = np.array([1,2,3])\n", "print(a)\n", "print(a.dtype)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "b = np.array((1.2,3.4,5.6))\n", "print(b)\n", "print(b.dtype)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "c = np.array([1,2,3],dtype='float')\n", "print(c.dtype)\n", "print(c)\n", "a[0] = 0.6\n", "c[0] = 0.6\n", "print(a)\n", "print(c)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Some attributes ###\n", "\n", "* dtype : the type of the elements of the array\n", "* size : integer corresponding to the total number of elements in the array\n", "* shape : tuple with the number of elements in each dimensions\n", "* data : object corresponding to the allocated memory referenced by the array\n", "\n", "Exercise: Create an array with 9 elements. Check its size, shape and what the data attribute is.\n", "Try to change the number of elements in the array. Try to change the shape of the array to make it a 3x3 matrix." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "d = np.array(range(9))\n", "print(d.size); print(d.shape); print(d.data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "d.size = 10" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "d.shape = [3,3]\n", "print(d)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Indexing/Slicing ###\n", "\n", "* Indexing similar to lists\n", "* Same syntax for each index (commas separated)\n", "* Selection\n", "\n", "Exercise: Play with the previous array to select subsets of the array." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "e = d[1,:]\n", "print(e)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "f = d[1:2,::2]\n", "print(f)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(e.data)\n", "print(f.data)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "g = d[d>4]\n", "print(g)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Reference/Copy ###\n", "\n", "* Numpy, when possible, makes *MemoryView* instead of copies. They really are *view* of the same memory.\n", " Thus in the previous examples, changing the content of the view change all the other views.\n", "* To be sure to make a copy (and not a view) the *copy* function of the NumPy module must be used.\n", "* The documentation states if a function/method returns a *view* or a *copy*.\n", "\n", "Exercise: \n", "\n", "* Create an array of size 9.\n", "* Make a view of shape 3x3.\n", "* Make a copy of the second line.\n", "* Read the documentation of the *reshape* function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "a = np.array(range(9))\n", "b = a\n", "b.shape = [3,3]" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(b);\n", "b[1,1] = 12\n", "print(a);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "c = np.copy(b[:,1])\n", "print(c);" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "c[2] = 14\n", "print(c);\n", "print(b)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "np.reshape?" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "A = a\n", "B = np.reshape(A,[3,3]) # makes a view\n", "B[0,0] = 1\n", "print(A)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "C = B.T\n", "D = np.reshape(C,9) # makes a copy\n", "D[0] = 100\n", "print(C)\n", "print(D)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Constructors and IO ###\n", "\n", "A list of constructors:\n", "* For a given shape: *empty*, *zeros*, *ones* (and not anymore!)\n", "* For vectors: *arange*, *linspace*\n", "* For matrices: *eye*, *diag*\n", "* For grids: *meshgrid*\n", "* For random numbers: le sub-module *random*\n", "\n", "For file reading/writing:\n", "* ASCII: *savetxt* and *loadtxt*\n", "* Binary: *save* and *load*\n", "\n", "Exercises: Try some." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(np.empty([2,2]))\n", "print(np.zeros([2,2]))\n", "print(np.ones([2,2]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(np.arange(3))\n", "print(np.arange(1.,2.,0.1))\n", "print(np.linspace(1.,2.,10))\n", "print(np.random.random([2,2]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(np.eye(2))\n", "print(np.diag(b[0:2]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "plop = np.meshgrid(np.linspace(0.,1.,2),np.linspace(0.,1.,3))\n", "print(plop[0].shape); print(plop[1].shape)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "print(np.random.random([2,2]))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Manipulation ###\n", "\n", "Operators works element-wise:\n", "* Classical arithmetic operators are supported: ```python +,-,*,/``` and ```**``` (for power)\n", "* When possible, it is better to use the ```python +=, -=, *=``` and ```/=``` operators.\n", "\n", "Useful methods and functions:\n", "* Methods : *min, max, argmin, argmax, sort, etc*\n", "* Functions : *dot* and *tensordot* for matrix/tensor products, every functions of math module\n", " also exist in NumPy to work with NumPy arrays.\n", "* Module: *linalg* for linear algebra (system resolution, etc)\n", "\n", "Exercise: Compute the value of a polynom on hundred points. Do the same with the *sinux*. Compute a matrix/matrix product." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "x = np.linspace(-1.,1.,500)\n", "%timeit p = x**5-4*x**4+3*x**3-2*x+1\n", "%timeit s = np.sin(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "import math\n", "xl = list(x)\n", "%timeit [l**5-4*l**4+3*l**3-2*l+1 for l in xl]\n", "%timeit map(math.sin,xl)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "A = np.array( [[1,1],\n", " [0,1]] )\n", "B = np.array( [[2,0],\n", " [3,4]] )\n", "print(A*B) # element wise product\n", "print(np.dot(A,B)) # matrix product" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## SciPy ##\n", "\n", "The SciPy module is based on NumPy to provide numerous algorithms use in scientific computations.\n", "It is made of several sub-modules:\n", "\n", "\n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "\n", " \n", "
scipy.cluster Vector quantization / Kmeans
scipy.constants Mathematical and physics constants
scipy.fftpack Fourier Transformed
scipy.integrate Integrals
scipy.interpolate Interpolation
scipy.io Input/Output
scipy.linalg Linear Algebra
scipy.ndimage Image filtering (n dimension)
scipy.odr Orthogonal distance regression
scipy.optimize Optimization
scipy.signal Signal processing
scipy.sparse Sparse matrix
scipy.spatial Algorithm and space data structure
scipy.special Special mathematical functions
scipy.stats Statistics
\n", "\n", "Providing details on each would be long and boring.\n", "Free period: test a function of a particularly interesting module to you.\n", "\n", "Proposed exercise: \n", "\n", "* Use the *integrate* module to compute the sum of the previously created polynom.\n", "* Use the *interpolate* module to compute the linear, quadratic, cubic interpolations of the sinus\n", "function on some points between $[0,2\\pi]$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "from scipy import integrate\n", "integrate.quad(lambda x: x**5-4*x**4+3*x**3-2*x+1, -1.,1.)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "from scipy import interpolate\n", "x = np.linspace(0.,2*math.pi,5)\n", "s = np.sin(x)\n", "lin = interpolate.interp1d(x,s)\n", "qua = interpolate.interp1d(x,s,'quadratic')\n", "cub = interpolate.interp1d(x,s,'cubic')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Matplotlib ##\n", "\n", "* Introduction\n", "* Plot\n", "* Some commands\n", "* Axis\n", "* Text and Annotations\n", "* Figure and Subplot\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Introduction ###\n", "\n", "* Uses NumPy arrays (or lists) to create graphics.\n", "* Convenient to represent 1/2D data.\n", "* For 3D representations it is advised to use other modules(vtk, mayavi, etc).\n", "\n", "Official documentation: http://matplotlib.org/1.4.0/contents.html\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Plot ###\n", "\n", "Matplotlib module implicitly works on its own objects. *plot* commands will create new objects that the\n", "user may not see.\n", "\n", "Once the objects created, the figure can be generated with the *show* command.\n", "\n", "Exercise: \n", "\n", "* Plot the $sin(2\\pi x)$ function between $[-1,1]$ with the commands *plot* et *show* of the *matplotlib.pyplot* module.\n", "*plot* may be use with a single array as an input.\n", "* Change the value of abcisses axis by adding the evaluation points of the functions.\n", "* Change the display style with the string `'ro'` as the third argument.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "%matplotlib inline\n", "from matplotlib import pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "plt.plot(s)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "plt.plot(x,s,'ro')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "* Colors can be defined by:\n", " * a predefined letter (b: blue, g: green, r: red, c: cyan, m: magenta y: yellow, k: black, w: white)\n", " * a value between 0 and 1 for a level of grey\n", " * a tuple of 3 values between 0 and 1 for a RGB\n", " * an htmo marker in hexadecimal (#eeefff)\n", " \n", "* Line styles (which link points) :\n", " * '-' \tsolid\n", " * '--' dashed\n", " * '-.' dash_dot\n", " * ':' \tdotted\n", " * '' or ' ' or None for nothing\n", " \n", "* Point marker styles:\n", " * '.' point\n", " * ',' pixel\n", " * 'o' circle\n", " * 'v' triangle_down\n", " * '^' triangle_up\n", " * 's' square\n", " * '*' star\n", " * for others: http://matplotlib.org/api/markers_api.html#module-matplotlib.markers" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "\n", "### Some commands ###\n", "\n", "Some simple functions to improve the final graphics:\n", "\n", "* *title* to give a title to the figure\n", "* *xlabel* to add a label on abscesses axes\n", "* *ylabel* to add a label on the ordinates axes\n", "\n", "These command all return a *text* object which can referenced in order to change the properties afterward\n", "(size of letters, orientation, http://matplotlib.org/api/text_api.html#matplotlib.text.Text)\n", "\n", "* *grid* allow to add/remove the background grid\n", "* *legend* display the legend (use the *label* parameter of a plot)\n", "\n", "* *setp* set the property of an object" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "lx = np.linspace(0.,2*math.pi,1000)\n", "si = plt.plot(lx,np.sin(lx),label='numpy function')\n", "plt.xlabel('x')\n", "plt.ylabel('y')\n", "plt.title(\"$sin(2\\pi x)$\")\n", "plt.legend(loc='upper right')\n", "\n", "plt.grid(True)\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "To display several graphs on a same figure:\n", "\n", "* Either give the data of each curve one after the other in one *plot*.\n", "* Or call *plot* once per curve before the call to *show*\n", "\n", "Exercise: Plot, on a single figure, the sinus functions, the interpolations points with only 'o' and the different interpolations." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "ll = plt.plot(lx,np.sin(lx),'b-',x,s,'o',label='numpy function')\n", "plt.setp(ll[1],label='interpolation points')\n", "plt.plot(lx,lin(lx),'r',label='linear interpolation')\n", "plt.plot(lx,qua(lx),'g',label='quadratic interpolation')\n", "plt.plot(lx,cub(lx),'b',label='cubic interpolation')\n", "\n", "plt.title(\"$sin(2\\pi x)$\")\n", "plt.legend(loc='upper right')\n", "\n", "plt.grid(True)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Axes ###\n", "\n", "Some commands act on the axes:\n", "\n", "* Size: *xlim*, *ylim* or *axis*\n", "* Scale: *xticks*, *yticks*\n", " * Allow to choose the scale\n", " * Also allow to choose what will be display on the axes\n", "\n", "Exercise: Adjust the axes on the previous figure to display $[0,\\frac{\\pi}{2},\\pi,\\frac{3\\pi}{2},2\\pi]$." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "ll = plt.plot(lx,np.sin(lx),'b-',x,s,'o',label='numpy function')\n", "plt.setp(ll[1],label='interpolation points')\n", "\n", "plt.plot(lx,lin(lx),'r',label='linear interpolation')\n", "plt.plot(lx,qua(lx),'g',label='quadratic interpolation')\n", "plt.plot(lx,cub(lx),'b',label='cubic interpolation')\n", "\n", "plt.title(\"$sin(2\\pi x)$\")\n", "plt.legend(loc='upper right')\n", "\n", "plt.ylim([-1.1,1.1])\n", "plt.yticks([-1,0,1])\n", "plt.xticks([0,math.pi/2.,math.pi,3*math.pi/2.,2*math.pi], [r\"$0$\",r\"$\\frac{\\pi}{2}$\",r\"$\\pi$\",r\"$\\frac{3\\pi}{2}$\",r\"$2\\pi$\"])\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Text and Annotate ###\n", "\n", "Functions allowing to add text on a figure:\n", "\n", "* *text* : wherever on the figure\n", "* *annotate* : text pointing to a pixel\n", "\n", "Each of these functions return an object, which properties can be modified with the `setp` function. Interesting properties are:\n", "\n", " * color\n", " * backgroundcolor\n", " * size\n", " * style\n", " \n", "Exercise: Add a text (for example the approximation of $\\pi$, and an annotation on the value of $sinus$ at $\\frac{3\\pi}{4}$" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "ll = plt.plot(lx,np.sin(lx),'b-',x,s,'o',label='numpy function')\n", "plt.setp(ll[1],label='interpolation points')\n", "\n", "plt.plot(lx,lin(lx),'r',label='linear interpolation')\n", "plt.plot(lx,qua(lx),'g',label='quadratic interpolation')\n", "plt.plot(lx,cub(lx),'b',label='cubic interpolation')\n", "\n", "plt.title(\"$sin(2\\pi x)$\")\n", "plt.legend(loc='upper right')\n", "\n", "plt.ylim([-1.1,1.1])\n", "plt.yticks([-1,0,1])\n", "plt.xticks([0,math.pi/2.,math.pi,3*math.pi/2.,2*math.pi], [r\"$0$\",r\"$\\frac{\\pi}{2}$\",r\"$\\pi$\",r\"$\\frac{3\\pi}{2}$\",r\"$2\\pi$\"])\n", "\n", "t = plt.text(0.5,-0.5,\"$\\pi \\simeq 3.14156$\")\n", "plt.setp(t,color='c',fontsize=14)\n", "t = plt.annotate(r'$\\frac{3\\pi}{4}$',xy=(3*math.pi/4,math.sqrt(2)/2.),xytext=(2.,-0.2),arrowprops=dict(facecolor='black', shrink=0.05))" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Figure and Subplot ###\n", "\n", "It is possible to generate several figures. By default every commands presented here work on the current figure.\n", "By calling the *figure* command (with an integer as input parameter) to create a new figure.\n", "\n", "In a single figure, several panels can be displayed with each its own axes with the *subplot* command.\n", "Three arguments are needed: the number of rows, the number of columns, the index of the graph.\n", "\n", "Exercise: Generate two figures, one with the sinus and one with interpolation points and the interpolated functions on\n", "different panels." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "slideshow": { "slide_type": "notes" } }, "outputs": [], "source": [ "\n", "plt.plot(lx,np.sin(lx),'b-',label='numpy function')\n", "plt.figure(2)\n", "plt.subplot(221)\n", "plt.plot(x,s,'o',label='interpolation points')\n", "plt.subplot(222)\n", "plt.plot(lx,lin(lx),'r',label='linear interpolation')\n", "plt.subplot(223)\n", "plt.plot(lx,qua(lx),'g',label='quadratic interpolation')\n", "plt.subplot(224)\n", "plt.plot(lx,cub(lx),'b',label='cubic interpolation')\n" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "## Compiled code ##\n", "\n", "* Python is slower than compiled code. To improve the efficiency:\n", " * Either to write thing so that Python code becomes compilable.\n", " * Or to call within Python functions of a compiled library.\n", " \n", "* The favorite compiled language to link with Python is C/C++\n", "\n", "* To (more or less) automatically convert Python code into C:\n", " * Cython\n", " * Pythran\n", " * Julia\n", "* To call a library inside Python:\n", " * Cython for C\n", " * f2py for Fortran (or use `iso_c_binding` Fortran2003 module to make the Fortran library callable as a C library)\n" ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" }, "latex_envs": { "bibliofile": "biblio.bib", "cite_by": "apalike", "current_citInitial": 1, "eqLabelWithNumbers": true, "eqNumInitial": 0 }, "toc": { "toc_cell": true, "toc_number_sections": true, "toc_threshold": "3", "toc_window_display": false } }, "nbformat": 4, "nbformat_minor": 1 }