Introduction to Scientific Computing with Python, part two.

Similar documents
LECTURE 19. Numerical and Scientific Packages

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

Scientific Computing: Lecture 1

Numerical Calculations

LECTURE 22. Numerical and Scientific Packages

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

Symbolic and Automatic Di erentiation in Python

Python for Scientists

MPI: the Message Passing Interface

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

Scientific Python. 1 of 10 23/11/ :00

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

Numerical Integration

User-Defined Function

Computational Programming with Python

Scientific computing platforms at PGI / JCNS

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Cosmology with python: Beginner to Advanced in one week. Tiago Batalha de Castro

Python Crash Course Numpy, Scipy, Matplotlib

HANDS ON DATA MINING. By Amit Somech. Workshop in Data-science, March 2016

David J. Pine. Introduction to Python for Science & Engineering

PYTHON NUMPY TUTORIAL CIS 581

ARTIFICIAL INTELLIGENCE AND PYTHON

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

Plotting With matplotlib

Scientific Computing with Python. Quick Introduction

Python Programming. Hans-Petter Halvorsen.

The Python interpreter

CME 193: Introduction to Scientific Python Lecture 1: Introduction

Introduction to Python

Interactive Mode Python Pylab

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

Introductory Scientific Computing with Python

Research Computing with Python, Lecture 1

Arbitrary Precision and Symbolic Calculations

List Comprehensions and Simulations

Scientific Computing with Python and CUDA

4. Modules and Functions

Scientific Computing Using. Atriya Sen

Computational Finance

Image Processing in Python

Day 15: Science Code in Python

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

Introduction to Python for Scientific Computing

10.4 Linear interpolation method Newton s method

pandas: Rich Data Analysis Tools for Quant Finance

Homework 11 - Debugging

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

(Ca...

Using the Matplotlib Library in Python 3

ENGR (Socolofsky) Week 07 Python scripts

Contents Computing with Formulas

SECTION 1: INTRODUCTION. ENGR 112 Introduction to Engineering Computing

Introduction to Python Part 2

Pandas and Friends. Austin Godber Mail: Source:

Getting along and working together. Fortran-Python Interoperability Jacob Wilkins

Intro to scientific Python in 45'

An interesting related problem is Buffon s Needle which was first proposed in the mid-1700 s.

NumPy quick reference

What advantages has it?

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

Python for Data Analysis

Matlab Tutorial. The value assigned to a variable can be checked by simply typing in the variable name:

Data Science with Python Course Catalog

Introduction to Engineering gii

Doing a li6le astronomy with. Python. Ryan Cooke (K16) These slides & examples:

Monte Carlo Integration

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

LECTURE 0: Introduction and Background

Skills Quiz - Python Edition Solutions

Algorithms and Programming I. Lecture#12 Spring 2015

ERTH3021 Exploration and Mining Geophysics

AUTHORS: FERNANDO PEREZ BRIAN E GRANGER (IEEE 2007) PRESENTED BY: RASHMISNATA ACHARYYA

Introduction to MATLAB

Scientific Programming. Lecture A08 Numpy

MO101: Python for Engineering Vladimir Paun ENSTA ParisTech

Introduction to Python and NumPy I

Python Scripting for Computational Science

A. Python Crash Course

Derek Bridge School of Computer Science and Information Technology University College Cork

Certified Data Science with Python Professional VS-1442

debugging, hexadecimals, tuples

Computer Programming in MATLAB

1. BASICS OF PYTHON. JHU Physics & Astronomy Python Workshop Lecturer: Mubdi Rahman

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

Computational Physics

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

STATS 507 Data Analysis in Python. Lecture 2: Functions, Conditionals, Recursion and Iteration

Outline. CSE 1570 Interacting with MATLAB. Outline. Starting MATLAB. MATLAB Windows. MATLAB Desktop Window. Instructor: Aijun An.

This Worksheet shows you several ways to start using Enthought s distribution of Python!

F21SC Industrial Programming: Python: Python Libraries

Intelligente Datenanalyse Intelligent Data Analysis

Appendix A. Introduction to MATLAB. A.1 What Is MATLAB?

AMS 27L LAB #1 Winter 2009

The SciPy Stack. Jay Summet

: Intro Programming for Scientists and Engineers Final Exam

Python Scripting for Computational Science

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Transcription:

Introduction to Scientific Computing with Python, part two. M. Emmett Department of Mathematics University of North Carolina at Chapel Hill June 20 2012

The Zen of Python zen of python... fire up python and run: import this these slides are in the public domain

How I use Python Experimenting with complex algorithms: it s quick and relatively easy to try new things in Python vs C or Fortran 90. Debugging: interactively drawing things mid-algorithm is helpful for debugging. Analysis: loading and working with data, computing errors, drawing graphs, and making movies is relatively painless. Deployment: building and launching many jobs/experiments on KillDevil is very convenient (ie, control everything from your desktop).

Resources for scientific computing with Python NumPy and SciPy: http://scipy.org Large collection of packages for: low-level numerical arrays (C/Fortran), sparse and dense linear algebra, FFTs, statistics etc... PyPI: http://pypi.python.org The Python Package Index is a central place for authors to distribute Python packages Software Carpentry: http://software-carpentry.org Lectures/videos about scientific programming. Books by Prof. Langtangen: http://folk.uio.no/hpl Prof. Langtangen has two great books on scientific computing with Python.

Python Packages Python has a batteries included philosophy. A standard Python installation contains many helpful packages. If the standard libraries don t have what you are looking for, there is a rich and growing collection of Python packages for many applications: system interaction, graphics, user interfaces, web programming, scientific computing, etc etc. Installing Python packages is relatively easy with pip: http://www.pip-installer.org

ipython - Interactive Python Fire up ipython. It s an interactive Python prompt. I find it helpful for looking up documentation and experimenting with Python. A few helpful things: tab completion is your friend shell commands like cd and ls work?command shows help for a given command??command shows the source code for a given command run script.py runs the script script.py, and shows traces nicely

numpy - Numerical Python NumPy is the fundamental package for scientific computing with Python low-level (C/Fortran) N-dimensional arrays broadcasting, dot/matrix products linear algebra (LAPACK), FFTs etc Compare the following # using python lists and a for loop y = [] for k in range ( 10 ): x = k * 2* math. pi / 10 y. append ( math. sin (x)) # using numpy broadcasting x = np. arange (0.0, 2*np.pi, 2*np.pi/10) y = np.sin (x)

scipy - Scientific Python SciPy is a large collection of packages for more general scientific computing. ODE solvers and quadrature routines optimization and root finding signal processing sparse linear algebra statistics, distributions, random numbers masked arrays much more...

sympy - Symbolic Python SymPy is a package for performing symbolic calculations. import sympy x = sympy. var ( 'x ') p = x**2 + 5*x + 2 print p. diff (x) # 2* x + 5 SymPy also contains multi-precision math routines from sympy. mpmath import * print quad ( lambda x: 4* sqrt (1-x**2), [0, 1]) # 3. 1415926535897932384626433832795028841971693993751

matplotlib - Plotting (similar in style to MATLAB) Matplotlib is a 2D plotting library that will be familiar to MATLAB users. import numpy as np import matplotlib. pylab as plt x = np. arange (0.0, 2*np.pi, 2*np.pi/20) y = np.sin (x) plt. plot (x, y, '-ok ') plt. show ()

fabric - Remote execution/deployment Fabric is a tool for executing commands on remote hosts. from fabric. api import * @task def build (): with cd(env. work ): run ( 'make ') Then, on the command line I could run: $ fab -H killdevil build

h5py and pytables - HDF5 storage The HDF5 file format is a great way to store data and move it around (ie, platform independent storage). I like to think of it as a filesystem within a file. There are two Python packages that can read and write HDF5 files: h5py and pytables. For example import h5py output = h5py. File ( ' results.h5 ', 'w ') output. create_dataset ( ' pressure ', data = pressure ) output. create_dataset ( ' temperature ', data = temperature ) output. close () results = h5py. File ( ' results.h5 ', 'r ') pressure = results [ ' pressure '] temperatute = results [ ' temperature '] # do something with pressure, temperature results. close ()

mpi4py - Parallel computing (MPI) for Python There are many ways to do parallel computing. One of them is with a Message Passing Interface (MPI) library (of which there are several implementations). The mpi4py package provides a nice wrapper to the MPI routines: from mpi4py import MPI import numpy as np comm = MPI. COMM_ WORLD if comm. rank == 0: x = np. array ([1.0, 2.0, 3.0, 4.0]) else : x = np. zeros (4) comm. Bcast (x) print 'i am %d of %d ' % ( comm.rank, comm. size ), x

Other useful packages MMMMMOOORE! While creating this presentation I kept thinking of more cool packages that I have used... some of them include Mayavi - 3d graphics with OpenGL rendering Pandas - data analysis similar in style to R PyMC - Markov-Chain Monte-Carlo simulations many, many more...

Defining functions To define a function in Python, use the def keyword def f(x): """ Return cos (x) - x**3. This is an extended docstring. """ return np.cos (x) - x**3 Then, one can call the function by y = f(0.2) Note that documentation is, in some sense, part of the language.

Defining functions Default arguments def error (a, b, order = 'inf '): """ Compute the error between * a* and * b*. The * order * can be ' inf ' or 2. """ if order == 'inf ': return np.max ( abs (a-b)) elif order == 2: return np. sqrt (np.sum ((a-b )** 2)) raise ValueError ( ' invalid order ') Now you can call this as: err_def = error (a, b) err_inf = error (a, b, order = 'inf ') err_2 = error (a, b, order =2) err_ reorder = error ( b=x, a=y)

Defining functions Lambda forms Small throw-away functions can be created using the lambda keyword: square = lambda x: x** 2 print square ( 2) # 4 This is especially useful for functional programming x = [ 1, 2, 3, 4 ] y = map ( lambda x: x**2, x) print y # [ 1, 4, 9, 16 ]

List comprehensions Python has some nice language constructs to make programming look more mathematical. Consider the following statement Let Ω = { x 2 x N, x < 100, and x is prime } In Python, this is omega = [ x** 2 for x in range ( 100 ) if is_ prime ( x) ] A similar construct exists for creating dictionaries.

Map and reduce Functional programming The map routine applies a function to each element of a list. The following are equivalent y = [ math. sin ( x) for x in X ] y = map ( math.sin, X) The reduce routine applies a function in an aggregate manner to reduce lists. To compute the factorial of 10, one could f = reduce ( lambda x, y: x * y, range (1, 11 ))

NumPy: vector programming When working with NumPy arrays, one can # do scalar / vector multiplication a = 2.0 x = np. asarray ([1.0, 2.0, 3.0]) y = a * x # [ 2.0, 4.0, 6. 0 ] # do elementwise multiplication z = x * y # [ 2.0, 8.0, 18.0 ] # do matrix / vector multiplication A = np. asarray ([ [ 1.0, 2.0, 1.0 ], [ 2.0, -1.0, 1.0 ] ]) z = np.dot (A, x) Recall the broadcasting rules too (y = np.sin(x)).

Computing π There are many ways to numerically compute an approximate value of π. One way is to note that π 4 = arctan 1 2 + arctan 1 3 and use the Taylor expansion of arctan x about 0, which is arctan x x x 3 3 + x 5 5 + = k=0 ( 1) k x 1+2k 1 + 2k

Computing π Try it! Here is a start... x2, x3 = 1.0/2.0, 1.0/3.0 atan2, atan3 = 0.0, 0. 0 for k in range (5): atan2 +=... atan3 +=... print ' pi = ', 4. 0 * ( atan2 + atan3 ) Warning: Be careful when dividing integers in Python: sometimes 1/2 0.5 That s why I wrote 1.0/2.0 instead of 1/2. Challenge: can you use the sympy.mpmath module to go beyond 14 digits?

Spectral analysis Sometimes we want to know about the frequencies that exist in a signal. Consider the following signal (contain in y) import numpy as np x = np. arange (0.0, 2*np.pi, 2*np.pi/100 ) y = ( 1.0 + 0.5*np.sin (x) + 0.3*np.sin (5*x) + 0.1*np.sin (8*x) ) Can you plot the spectrum of this signal, with the zero frequency in the center?