Download Interactive Computing - Mathematical, Statistical, and Scientific

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
MCS 507 Lecture 3
Mathematical, Statistical and Scientific Software
Jan Verschelde, 30 August 2013
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
1 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
2 / 33
running a script
We run the script hellothere.py
at the command line prompt $:
$ python hellothere.py
Welcome to our interactive Python script!
who is there ? me
How are you, me?
type some number : 3.4
-> your number 3.4 : <type ’float’>
$
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
3 / 33
input statements
Two ways to enter data:
1
raw_input() returns a string, example:
NAME = raw_input(’who is there ? ’)
After displaying who is there ?,
the characters typed in by the user are returned in a string are
assigned to the variable NAME.
2
input() interprets the input of the user, e.g.:
NUMB = input(’type some number : ’)
After displaying type a number :
and taking the user input, this input is interpreted
and, if successful, is then assigned to the variable NUMB.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
4 / 33
parsing input strings
The statement
x = input(’type some number : ’)
is equivalent to
s = raw_input(’type some number : ’)
x = eval(s)
Test in an interactive Python session:
>>> s = ’1.2’
>>> x = eval(s)
>>> type(x)
<type ’float’>
>>> x
1.2
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
5 / 33
output statements
The basic output is print ’some string’.
Some examples:
print ’How are you, ’ + NAME + ’?’
The + signs are for string concatenation.
First the strings ’How are you, ’, the string in NAME, and ’?’
are added to one string before printing.
print ’-> your number’, NUMB , ’:’, NUMBTYPE
What is printed is separated by commas.
The type of NUMB is not restricted to string.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
6 / 33
formatted output
Often we want to format the output of floats:
limit the number of decimal places
>>> import math
>>> print ’%.5f’ % math.pi
3.14159
display in scientific format
>>> print ’%.4e’ % (100*math.pi)
3.1416e+02
Observe that % is used twice differently:
The % inside the string defines the format.
The % after the format string is an operator.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
7 / 33
hellothere.py
# L-3 MCS 507 Fri 30 Aug 2013 : hellothere.py
"""
Execute this script by typing at the command prompt $:
python hellothere.py
"""
print ’Welcome to our interactive Python script!’
NAME = raw_input(’who is there ? ’)
print ’How are you, ’ + NAME + ’?’
NUMB = input(’type some number : ’)
NUMBTYPE = type(NUMB)
print ’-> your number’, NUMB , ’:’, NUMBTYPE
To explicitly check on the type, use isinstance.
For example, in an interactive Python session:
>>> x = 4.3
>>> isinstance(x,float)
True
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
8 / 33
an alternative way to run a script
#!/Library/Frameworks/Python.framework/Versions/2.7/bin/python
# L-3 MCS 507 Fri 30 Aug 2013 : hellothere2.py
"""
Execute this script by typing at the command prompt $:
hellothere2.py
"""
print ’Welcome to our interactive Python script!’
NAME = raw_input(’who is there ? ’)
print ’How are you, ’ + NAME + ’?’
NUMB = input(’type some number : ’)
NUMBTYPE = type(NUMB)
print ’-> your number’, NUMB , ’:’, NUMBTYPE
At the command prompt $, just type
$ ./hellothere2.py
Note that one must have permissions to execute the file, if necessary do
chmod +x hellothere2.py (on Unix-like systems).
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
9 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
10 / 33
math and cmath
The operations in math are restricted to floats:
>>> import math
>>> math.sqrt(-1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: math domain error
The c in cmath stands for complex:
>>> import cmath
>>> cmath.sqrt(-1)
1j
The imaginary unit
√
−1 is displayed as 1j.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
11 / 33
defining complex numbers
The type complex is a builtin Python type:
>>> z = complex(2,3)
>>> type(z)
<type ’complex’>
>>> z.real
2.0
>>> z.imag
3.0
>>> type(z.real)
<type ’float’>
>>> z.conjugate()
(2-3j)
Python is object oriented: z.conjugate() is the application of the
method conjugate to the object z.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
12 / 33
polar representation
Session continued, with z = 2 + 3j:
>>> import cmath
>>> cmath.polar(z)
(3.6055512754639891, 0.98279372324732905)
On returns is a tuple with absolute value and angle:
>>> abs(z)
3.6055512754639891
>>> cmath.phase(z)
0.98279372324732905
From polar to rectangular representation:
>>> (r,t) = cmath.polar(z)
>>> r*cmath.exp(t*complex(0,1))
(2+2.9999999999999996j)
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
13 / 33
unified treatment with numpy
>>> import cmath
>>> cmath.sqrt(2)
(1.4142135623730951+0j)
We want a floating-point approximation for
√
2.
>>> import numpy.lib
>>> numpy.lib.scimath.sqrt(2)
1.4142135623730951
>>> type(_)
<type ’numpy.float64’>
>>> numpy.lib.scimath.sqrt(-2)
1.4142135623730951j
>>> type(_)
<type ’numpy.complex128’>
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
14 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
15 / 33
Python coding style
PEP 8 – Style Guide for Python
PEP = Python Enhancement Proposal
available at http://www.python.org/dev/peps/pep-0008/
This document gives coding conventions for Python code.
The guidelines are intended to improve readability of the code.
For example in Names to Avoid:
Never use the characters ’l’ (lowercase letter el), ’O’ (uppercase letter
oh), or ’I’ (uppercase letter eye) as single character variable names.
In some fonts, these characters are indistinguishable from the
numerals one and zero. When tempted to use ’l’, use ’L’ instead.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
16 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
17 / 33
a Python code static checker
pylint 1.0.0 is a static checker of Python code.
Copied from www.pylint.org:
Pylint is a Python source code analyzer which looks for programming
errors, helps enforcing a coding standard and sniffs for some code
smells (as defined in Martin Fowler’s Refactoring book).
Pylint has many rules enabled by default, way too much to silence
them all on a minimally sized program. It’s highly configurable and
handle pragmas to control it from within your code. Additionally, it is
possible to write plugins to add your own checks.
It’s a free software distributed under the GNU Public Licence.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
18 / 33
running pylint
$ pylint hellothere.py
No config file found, using default configuration
************* Module hellothere
W: 11, 7: Used builtin function ’input’ (bad-builtin)
Report
======
7 statements analysed.
. . . output omitted . . .
Global evaluation
----------------Your code has been rated at 8.57/10 (previous run: 8.57/10,
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
19 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
20 / 33
modeling sound
A sound is a wave describe by sine function
s(t) = A sin(2πf t),
t is time in seconds,
where the amplitude A is the strength of the sound
and f is the frequency expressed in Hertz.
An f Hz tone lasting for m seconds with sample rate r is defined by the
sequence
n
sn = A sin 2πf
, n = 0, 1, . . . , m · r .
r
For CD quality, the rate r is 44100 samples per second.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
21 / 33
playing sounds
Sounds on a computer are stored in a WAV file.
The package scitools available from the web site of the text book
has a module sound.py.
The script playsounds.py contains
f = raw_input(’give file name : ’)
print ’playing’, f, ’...’
import scitools.sound
scitools.sound.play(f)
We run at the command prompt $ as
$ python playsounds.py
On MacOS X, scitools.sound.play(f) is equivalent to typing
open f at the command line prompt.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
22 / 33
playing a tone
We create a sound at 440 Hz for 6 seconds:
import numpy, scitools.sound
ATONE = scitools.sound.note(440, 6)
calling note() of the module sound in the package scitools;
note() returns a numpy array of floats
and we must convert this array to two bytes integers:
AMPLITUDE = 2**15-1
ATONE = AMPLITUDE*ATONE
ATONE = ATONE.astype(numpy.int16)
scitools.sound.write(ATONE, ’atone.wav’)
scitools.sound.play(’atone.wav’)
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
23 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
24 / 33
arrays in Python
Python has no array type, but there is numpy, an abbreviation for the
package Numerical Python.
>>> import numpy as np
>>> t = np.linspace(0,2*np.pi,5)
>>> t
array([ 0.
, 1.57079633, 3.14159265,
4.71238898, 6.28318531])
linspace(a,b,n) creates an array of n equidistant points in the
interval [a,b]. We sample at those points:
>>> s = np.sin(2*np.pi*t)
The array s contains the values of sin(2πt) at the points in the array of
5 equidistant points in t. No loop is needed!
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
25 / 33
vectorization
Difference between math.sin() and numpy.sin()?
numpy.sin() applies to numbers, arrays + is efficient
>>> import numpy
>>> x = numpy.linspace(0,1,100)
>>> y = numpy.sin(x)
the y = numpy.sin(x) is equivalent to
>>> y = numpy.zeros(len(x))
>>> for i in range(0,len(x)):
...
y[i] = math.sin(x[i])
...
but the loop is not efficient.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
26 / 33
computing a sound
Computing r = 44100 samples of a f = 440 Hz sound lasting for
m = 6 seconds of amplitude A = 1 via
n
, n = 0, 1, . . . , m · r .
sn = A sin 2πf
r
A couple of lines at the Python prompt:
>>>
>>>
>>>
>>>
import numpy as np
r = 44100; f = 440; m = 6; A = 1
t = np.linspace(0,m,m*r)
s = A*np.sin(2*np.pi*f*t)
Values for r, f, m, and A are the parameters for the note() in the
sound module of the package scitools.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
27 / 33
creating an echo
With a sound defined in the array s, we compute an echo:
with a delay of one second,
play a sound of half the original strength,
for half of the original length.
Using r as the sampling rate:
delay = np.zeros(r)
echo = 0.5*s[0:len(s)/2]
sound = np.concatenate((s,delay,echo))
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
28 / 33
the script compute_sound.py
# L-3 MCS 507 Fri 30 Aug 2013 : compute_sound.py
"""
This script creates a .wav file with a sound
at a prescribed frequency, using numpy and scitools.
"""
import numpy as np
RATE = 44100
FREQ = 440
RANGE = 6
TIME = np.linspace(0, RANGE, RANGE*RATE)
SINE = np.sin(2*np.pi*FREQ*TIME)
DELAY = np.zeros(RATE)
ECHO = 0.5*SINE[0:len(SINE)/2]
SOUND = np.concatenate((SINE, DELAY, ECHO))
AMPLITUDE = 2**15-1
SOUND = AMPLITUDE*SOUND
SOUND = SOUND.astype(np.int16)
import scitools.sound
scitools.sound.write(SOUND, ’atone.wav’)
scitools.sound.play(’atone.wav’)
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
29 / 33
Interactive Computing
1
Input/Output and Complex Arithmetic
interactive Python scripts
complex arithmetic
2
Python Coding Style and pylint
coding style
static code checking with pylint
3
Programming with Sound
sampling sine functions
numpy arrays in Python
PyAudio: PortAudio v19 Python Bindings
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
30 / 33
PyAudio
With PyAudio, you can use Python to play and record audio
on a variety of platforms.
Written by Hubert Phan, available at
http://people.csail.mit.edu/hubert/pyaudio.
Download the scripts record.py and play.py:
python record.py
→ records a few sounds and saves to output.wav.
python play.py output.wav
→ plays the recorded sounds in output.wav.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
31 / 33
Summary + Exercises
We covered chapter 1 of the text book.
Exercises: (1 is exercise 1.13 how to cook the perfect egg)
1
The time t in seconds it takes for the center of the yolk to reach
the temperature Ty in Celsius is given by the formula
To − Tw
M 2/3 cρ1/3
ln 0.76
t=
Ty − Tw
K π 2 (4π/3)2/3
where M is the mass, ρ the density, c is the specific heat capacity,
and K is the thermal conductivity of the egg. Typical values for a
large egg are M = 67 g, ρ = 1.038 g cm−3 , c = 3.7 J g−1 K−1 , and
K = 5.4 · 10−3 W cm−1 K−1 . The original temperature in Celsius
is To and Tw = 100 C is the temperature of the boiling water.
Write a script egg.py using the formula to compute the time t it
takes for Ty = 70 C. Prompt the user for the value of To , for
example: To = 4 C (fridge), To = 20 C (room temperature).
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
32 / 33
more exercises
2
3
√
−b± b 2 −4ac
for the roots of
Consider the quadratic formula x =
2a
ax 2 + bx + c. Write an interactive Python script that prompts the
user for a, b, c and prints the roots. Use numpy.lib.scimath to
compute the roots.
Make a sound composed of two frequencies, e.g.: one at 440 Hz
and the other at 300 Hz, where the first has twice the amplitude of
the other, lasting for ten seconds.
The first homework collection is on Monday 9 September, at 9AM.
Bring to class your answers to exercise 3 of Lecture 1;
exercises 1, 2 of Lecture 2; and exercises 1, 3 of Lecture 3.
Along with a paper version, also email me your scripts.
Scientific Software (MCS 507 L-3)
Interactive Computing
30 August 2013
33 / 33