Python. Python. 1 Python. M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 1 / 25



Similar documents
Advanced Functions and Modules

Exercise 0. Although Python(x,y) comes already with a great variety of scientic Python packages, we might have to install additional dependencies:

Intro to scientific programming (with Python) Pietro Berkes, Brandeis University

Computational Mathematics with Python

ANSA and μeta as a CAE Software Development Platform

CIS 192: Lecture 13 Scientific Computing and Unit Testing

Computational Mathematics with Python

Computational Mathematics with Python

We will learn the Python programming language. Why? Because it is easy to learn and many people write programs in Python so we can share.

Scientific Programming in Python

Assignment 2: Option Pricing and the Black-Scholes formula The University of British Columbia Science One CS Instructor: Michael Gelbart

PSTricks. pst-ode. A PSTricks package for solving initial value problems for sets of Ordinary Differential Equations (ODE), v0.7.

Part VI. Scientific Computing in Python

The NumPy array: a structure for efficient numerical computation

Postprocessing with Python

Python for Scientific Computing.

Simulation Tools. Python for MATLAB Users I. Claus Führer. Automn Claus Führer Simulation Tools Automn / 65

Material for tutorial. Twitter: prabhu_r. Slides: Demos:

Modeling with Python

Introduction to Python

Computer Science 1 CSci 1100 Lecture 3 Python Functions

Nicolas P. Rougier PyConFr Conference 2014 Lyon, October 24 25

3D Data visualization with Mayavi

FEEG Applied Programming 5 - Tutorial Session

Maple Quick Start. Introduction. Talking to Maple. Using [ENTER] 3 (2.1)

Introduction to Python

From mathematics to a nice figure in a LaTeX document

CRASH COURSE PYTHON. Het begint met een idee

AMATH 352 Lecture 3 MATLAB Tutorial Starting MATLAB Entering Variables

Exercise 4 Learning Python language fundamentals

CUDAMat: a CUDA-based matrix class for Python

from ztf_summerschool import source_lightcurve, barycenter_times %matplotlib inline

Modelling cellular processes with Python and Scipy

Chemical and Biological Engineering Calculations using Python 3. Jeffrey J. Heys

CS Software Engineering for Scientific Computing. Lecture 16: Particle Methods; Homework #4

Profiling, debugging and testing with Python. Jonathan Bollback, Georg Rieckh and Jose Guzman

Scientific Programming, Analysis, and Visualization with Python. Mteor 227 Fall 2015

Data Visualization. Christopher Simpkins

Introduction to Matlab

Scientific Programming with Python. Randy M. Wadkins, Ph.D. Asst. Prof. of Chemistry & Biochem.

Introduction to Python

Vector Spaces; the Space R n

Financial Econometrics MFE MATLAB Introduction. Kevin Sheppard University of Oxford

Lecture 2 Mathcad Basics

Python programming guide for Earth Scientists. Maarten J. Waterloo and Vincent E.A. Post

An introduction to Python Programming for Research

(!' ) "' # "*# "!(!' +,

3.2 Sources, Sinks, Saddles, and Spirals

CASA. Nemesio Rodriguez-Fernandez (IRAM) Outline. - Status and Measurement Set. - Structure. - Tools. - Tasks. - Scripts.

Online Digitizing and Editing of GIS Layers (On-Screen or Head s Up Digitizing)

Introduction to Python

Python for Computational Science and Engineering

by Przemysław Króliszewski & Sebastian Korczak. itechnologie Sp. z o. o. p.kroliszewski@itechnologie.com.pl, s.korczak@itechnologie.com.

Numerical Solution of Differential Equations

MatLab Basics. Now, press return to see what Matlab has stored as your variable x. You should see:

G563 Quantitative Paleontology. SQL databases. An introduction. Department of Geological Sciences Indiana University. (c) 2012, P.

Sample Solutions for Assignment 2.

Microsoft Excel 2010 Linking Worksheets and Workbooks

Programming Languages & Tools

ESPResSo Summer School 2012

Online Appointments (Patients)

University of Hull Department of Computer Science. Wrestling with Python Week 01 Playing with Python

Optimizing and interfacing with Cython. Konrad HINSEN Centre de Biophysique Moléculaire (Orléans) and Synchrotron Soleil (St Aubin)

Classroom Tips and Techniques: The Student Precalculus Package - Commands and Tutors. Content of the Precalculus Subpackage

Tellurium and libroadrunner in a Nutshell

Display Format To change the exponential display format, press the [MODE] key 3 times.

MBA Jump Start Program

SAGE, the open source CAS to end all CASs?

NetworkX: Network Analysis with Python

mouse (or the option key on Macintosh) and move the mouse. You should see that you are able to zoom into and out of the scene.

Department of Chemical Engineering ChE-101: Approaches to Chemical Engineering Problem Solving MATLAB Tutorial VI

13-1. This chapter explains how to use different objects.

Analysis Programs DPDAK and DAWN

The C Programming Language course syllabus associate level

Big Data Paradigms in Python

CSE 6040 Computing for Data Analytics: Methods and Tools

Getting to know your TI-83

Setting up Python 3.4 and numpy and matplotlib on your own Windows PC or laptop

Python and Cython. a dynamic language. installing Cython factorization again. working with numpy

The Piranha computer algebra system. introduction and implementation details

Solving ODEs in Matlab. BP205 M.Tremont

NCSS Statistical Software Principal Components Regression. In ordinary least squares, the regression coefficients are estimated using the formula ( )

CSCE 110 Programming I Basics of Python: Variables, Expressions, and Input/Output

The Whys, Hows and Whats of the Noise Power Spectrum. Helge Pettersen, Haukeland University Hospital, NO

Athena Knowledge Base

ESCI 386 Scientific Programming, Analysis and Visualization with Python. Lesson 5 Program Control

Lecture Notes to Accompany. Scientific Computing An Introductory Survey. by Michael T. Heath. Chapter 10

Introduction. Chapter 1

Computación I: intro to Matlab. Francesca Maria Marchetti

Lecture 11: 0-1 Quadratic Program and Lower Bounds

Negative Exponents and Scientific Notation

Guide to Using the Ti-nspire for Methods - The simple and the overcomplicated Version 1.5

Tentative NumPy Tutorial

FX 115 MS Training guide. FX 115 MS Calculator. Applicable activities. Quick Reference Guide (inside the calculator cover)

a. all of the above b. none of the above c. B, C, D, and F d. C, D, F e. C only f. C and F

SAMPLE. Computer Algebra System (Classpad 330 using OS 3 or above) Application selector. Icolns that access working zones. Icon panel (Master toolbar)

Transcription:

Python 1 Python M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 1 / 25

Python makes you fly M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 2 / 25

Let s start ipython vs python ipython Note that you have an access to the OS shell ls pwd reverse search: ctrl + R Automatic completion works! use Tab Comments with # Great help use? or help help pow pow? M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 3 / 25

ipython II History arrow up (shows previous command in history) arrow down (shows next command in history) po arrow up (shows previous command starting with po) history # (prints the complete recorded history) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 4 / 25

Array basics You need numpy import numpy as np Alternatively, you can use (less safe) from numpy import * Several possibilities how to create an array x=np.zeros((20,30)) Creates a 20x30 array of zeros x=np.ones((20,30)) x=np.arange(10) Creates integer arrays with sequential values Starting with 0 x=np.arange(10.) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 5 / 25

Array basics II x=np.arange(3,10) x=np.arange(3.,10.,1.5) x=np.array([3.,1.,7.]) Creating arrays form literal arguments x=np.array([[3.,1.][1.,7.]]) Be careful about reals and integers! x=3 y=4 x/y x=3. y=4 x/y Array indexing starts from 0! x,x[0],x[1] M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 6 / 25

Array types Array numeric types The default for integer is usually 32-bit integers (in numpy called int32) The default for floats is 64-doubles (in numpy called float64) How to find out the type of an array x with dtype x=arange(4.) x.dtype Converting an array to a different type with adtype() y=x.astype(float32) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 7 / 25

Array operations x.max() x.min() x.std() x.mean() x1=x.copy() x-=x.mean() equivalent with x=x-x.mean() max(x) min(x) std(x) mean(x) x1=copy(x) x-=mean(x) equivalent with x=x-mean(x) First and last 10 entries of an array x = np.random.random(100) x[:10] x[-100:] x[2:5] M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 8 / 25

Multidimensional arrays Creating an N M array N = 5 M = 3 x2 = np.zeros((n,m)) Size and shape of an array size(x2) shape(x2) Reshaping of an array x3 = np.arange(10).reshape(2,5) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 9 / 25

Linear algebra import numpy.linalg as la An inverse of a matrix x = np.array([[1,1],[1,-1]]) la.inv(x) dot(x,la.inv(x)) Finding an eigenvalues and vectors x = np.array([[1,2],[2,1]]) val, vec = la.eig(x) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 10 / 25

Pyhton For statements for i in range(3): x=i*i print x Indentation determines a block of code (such as for) cycle In interactive mode starting a block causes the interpreter to prompt with... (typing an empty line with enter terminated the block) Tabs may be used for indentation, but their use is not recommended M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 11 / 25

Python If statements x=0 if x==0: print "x equals 0" elif x==1: print "x equals 1" else: print "x equals something else than 0 or 1" M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 12 / 25

Plotting - handled with matplotlib module import matplotlib.pyplot as plt import numpy as np Plotting random series of y values y = np.random.random(50) plt.figure() plt.plot(x) plt.show() M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 13 / 25

Plotting II Plotting x against y values t = np.arange(10) y1 = np.random.random(10) y2 = np.random.random(10) plt.figure() plt.plot(t,y1, r ) plt.plot(t,y2, go- ) plt.show() Clear figure plt.clf() Close all figures plt.close( all ) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 14 / 25

Other modules useful in Earth sciences For seismologist obspy module www.obspy.org M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 15 / 25

Geochemical systems - one reservoir The concentration C i of an element i must follow (in the simplest case) dc i dt = C i τ Concentration in the box is homogeneous Initial condition C i (t = 0) = C 0 M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 16 / 25

Ordinary differential equations (ODE) We will need SciPy (Scientific tools for Python) import scipy as sp from scipy.integrate import odeint The function odeint finds solution of equation dy dt = f(y, t) With initial conditions y(0) = y 0 Where y is a length N vector and f is a mapping from R N to R N M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 17 / 25

Make your first Python script touch box model single.py #!/bin/python import numpy as np from scipy.integrate import odeint import matplotlib as mpl import matplotlib.pylab as plt Parameters of the system tau=1 y0=1 # initial conditions M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 18 / 25

ODE II Define times when you want to find a solution t = np.arange(0,10., 1.) Right hand side of the equation def func(y,t): return -y/tau Solve the system yy=odeint(func,y0,t) # solution of dc/dt=... M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 19 / 25

ODE III We know analytical solution time = np.arange(0,10.,0.1) concentration=y0*np.exp(-time/tau) # analytical solution Plotting plt.figure() plt.title( Concentration time evolution ) plt.ylabel( Concentration ) plt.xlabel( Time ) plt.plot(t,yy, ro ) plt.plot(time,concentration) Run your script in ipython execfile( box model single.py ) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 20 / 25

Box model - n reservoirs with concentrations C i Coltice at al. (GRL, 2000) Transport of an inert gas in the mantle Reservoir 6 Reservoir 5 Degassing K_n=K_top The n equations to solve dc i dt = v zn L (K i 1C i 1 K i C i ) K i = 1 i 1 or n Reservoir 4 Reservoir 3 Reservoir 2 Reservoir 1 K_0 C_0=K_bot C_n Reinjection K 0 C 0 = K bot C n = 0.2C n K n = K top = 10 v z = 1 mm/y (vertical velocity) n number of boxes L size of the domain M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 21 / 25

Box model with Python touch box model.py #!/bin/ipython import numpy as np from scipy.integrate import odeint import matplotlib as mpl import matplotlib.pylab as plt Parameters of the system vz=0.001 # m/year ktop=10.0 kbot=0.2 nn=100 # number of boxes LL=3E6 # size of mantle [m] M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 22 / 25

Box model with Python II t = np.arange(0,1.8e9, 1E6) # times - min, max, step y0=np.ones(nn) # array of initial concentration ynew=np.zeros(nn) def func(y,time): for ii in range(nn): if ii==0: # bottom ynew[0]=kbot*y[nn-1]-y[0] elif ii==nn-1: # top ynew[nn-1]=y[nn-2]-ktop*y[nn-1] else: ynew[ii]=y[ii-1]-y[ii] alpha=vz*ll/nn return alpha*ynew yy=odeint(func,y0,t) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 23 / 25

Plotting the results zz=np.arange(0.,1.,1./nn) zz=np.append(zz,1.) ntime=size(t)-1 print plotting at time:, t[ntime] plt.figure() plt.title( Concentration profile ) plt.xlabel( Concentration ) plt.ylabel( Height ) plt.plot(np.append(yy[ntime],yy[ntime][nn-1]),zz,drawstyle= steps ) plt.axis([0,max(yy[ntime]),0,1]) plt.savefig( fig1.pdf ) M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 24 / 25

Plotting the results II: Animation files=[] fig=plt.figure(figsize=(5,5)) ax=fig.add subplot(111) jj=0 for ii in range(0,size(t),size(t)/20): # 20 frames jj=jj+1 ax.cla() ax.plot(np.append(yy[ii],yy[ii][nn-1]),zz,drawstyle= steps ) fname = fig%03d.png %jj print Saving frame, fname fig.savefig(fname) files.append(fname) os.system( mencoder mf: tmp*.png -mf type=png:fps=10 / -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o animation.mpg ) mplayer M.Ulvrova, L.Pouilloux (ENS LYON) Informatique L3 Automne 2011 25 / 25