Intermediate Python: Using NumPy, SciPy and Matplotlib

advertisement
Intermediate Python: Using
NumPy, SciPy and Matplotlib
Lesson 19 – Odds and Ends
1
Lambda Operator
• Python also has a simple way of defining a one-line function.
• These are created using the Lambda operator.
• The code must be a single, valid Python statement.
• Looping, if-then constructs, and other control statements cannot be
use in Lambdas.
>>> bar = lambda x,y: x + y
>>> bar(2,3)
5
>>> cube_volume = lambda l, w, h: l*w*h
>>> cube_volume(2, 4.5, 7)
63.0
2
Physical Constants
• The scipy.constants module contains many
physical constants!
3
Physical Constants
R
molar gas constant
c
speed of light in vacuum
alpha
fine-structure constant
mu_0
the magnetic constant
N_A
Avogadro constant
epsilon_0
the electric constant (vacuum
permittivity),
h
the Planck constant
hbar
the Planck constant divided by 2.
G
Newtonian constant of gravitation
g
standard acceleration of gravity
e
elementary charge
k
Boltzmann constant
sigma
Stefan-Boltzmann constant
Wien
Wien displacement law constant
Rydberg Rydberg constant
m_e
electron mass
m_p
proton mass
m_n
neutron mass
Always verify that they are in the correct units!!!
4
Examples
>>> import scipy.constants as sc
>>> sc.c
299792458.0
>>> sc.h
6.62606957e-34
>>> sc.G
6.67384e-11
>>> sc.g
9.80665
>>> sc.e
1.602176565e-19
>>> sc.R
8.3144621
>>> sc.N_A
6.02214129e+23
>>> sc.k
1.3806488e-23
>>> sc.sigma
5.670373e-08
>>> sc.m_e
9.10938291e-31
5
Constants Database
• There are more constants in the constants database.
• These are accecces using dictionary keys.
• The methods available are:
– value() # the value of the constant
– unit() # the units of the contant
– precision() # the precision of the constant
• To see a list of available constants, go to:
http://docs.scipy.org/doc/scipy/reference/constants.html#
module-scipy.constants
6
Constants Database Example
>>> sc.value('Rydberg constant')
10973731.568539
>>> sc.unit('Rydberg constant')
'm^-1'
>>> sc.precision('Rydberg constant')
5.011968778030033e-12
7
Metric Prefixes
>>> sc.yotta
1e+24
>>> sc.mega
1000000.0
>>> sc.nano
1e-09
8
Conversions
• There are conversion factors to MKS units.
>>> sc.gram
0.001
>>> sc.lb
0.45359236999999997
>>> sc.mile
1609.3439999999998
>>> sc.foot
0.30479999999999996
>>> sc.atm
101325.0
>>> sc.psi
6894.757293168361
>>> sc.gallon
0.0037854117839999997
>>> sc.mph
0.44703999999999994
>>> sc.knot
0.5144444444444445
>>> sc.erg
1e-07
>>> sc.Btu
1055.05585262
9
Temperature Conversions
zero_Celsius
zero of Celsius scale in Kelvin
degree_Fahrenheit
one degree Fahrenheit difference in Kelvin
C2K(C)
Convert Celsius to Kelvin
K2C(K)
Convert Kelvin to Celsius
F2C(F)
Convert Fahrenheit to Celsius
C2F(C)
Convert Celsius to Fahrenheit
F2K(F)
Convert Fahrenheit to Kelvin
K2F(K)
Convert Kelvin to Fahrenheit
10
Special Functions
• The scipy.special module contains many
special functions, such as Bessel functions,
Legendre Polynomials, etc.
11
Interpolation
• The scipy.interpolate module contains
functions for interpolating 1D and 2D data.
12
scipy.interpolate.interp1d()
• This function takes an array of x values and an
array of y values, and then returns a function.
By passing an x value to the function the
function returns the interpolated y value.
• It uses linear interpolation as the default, but
also can use other forms of interpolation
including cubic splines or higher-order splines.
13
interp1d() Example
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10)
y = np.array([3.0, -4.0, -2.0, -1.0, 3.0, 6.0, 10.0, 8.0, 12.0, 20.0])
f = interp1d(x, y, kind = 'cubic')
Cubic Spline
xint = 3.5
yint = f(xint)
Interpolated Point
plt.plot(x, y, 'o', c = 'b')
plt.plot(xint, yint, 's', c = 'r')
plt.show()
14
Results
Interpolated Point
15
interp1d() Example
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 10)
y = np.array([3.0, -4.0, -2.0, -1.0, 3.0, 6.0, 10.0, 8.0, 12.0, 20.0])
f = interp1d(x, y, kind = 'cubic')
Cubic Spline
xint = np.arange(0, 9.01, 0.01)
yint = f(xint)
Interpolated Points
plt.plot(x, y, 'o', c = 'b')
plt.plot(xint, yint, '-r')
plt.show()
16
Results
Interpolated Curve
17
scipy.interpolate.interp2d()
• This function works similarly to interp1d(), but
can interpolate values on a 2D grid.
• The input values can be either regularly
spaced, or irregularly spaced.
18
Numerical Differentiation
• scipy.misc.derivative(f, x, dx=dx, n = n) is a
function to find the nth derivative of a
function f.
• The function can either be a lambda or a user
defined function.
19
Derivatives Example
from scipy.misc import derivative
import numpy as np
import matplotlib.pyplot as plt
……
f = lambda x : np.exp(-x)*np.sin(x)
x = np.arange(0,10, 0.1)
fig, ax = plt.subplots(3,1,sharex = True)
ax[0].plot(x,f(x))
ax[0].set_ylabel(r'$f(x)$')
ax[1].plot(x,first)
ax[1].set_ylabel(r'$f\/\prime(x)$')
ax[2].plot(x,second)
ax[2].set_ylabel(r'$f\/\prime\prime(x)$')
ax[2].set_xlabel(r'$x$')
first = derivative(f,x,dx=1,n=1)
second = derivative(f,x,dx=1,n=2)
plt.show()
20
Derivatives Results
21
Numerical Integration
• scipy.integrate is a module that contains
functions for integration.
• Integration can be performed on a function
defined by a lambda.
• Integration can also be performed given an
array of y values.
22
Numerical Integration
• scipy.integrate is a module that contains
functions for integration.
• Integration can be performed on a function
defined by a lambda.
• Integration can also be performed given an
array of y values.
23
Integration Example
• Suppose we want to evaluate the integral.
2
e
sin
xdx

x
0
24
Integration Example
>>> import scipy.integrate as integrate
>>> import numpy as np
>>> f = lambda x : np.exp(-x)*np.sin(x)
>>> I = integrate.quad(f, 0, 2*np.pi)
>>> print(I)
(0.49906627863414593, 6.023731631928322e-15)
Value of integral.
Estimate of absolute error.
25
Can Even Do Infinite Bounds
• Suppose we want to evaluate the integral.

e
sin
xdx

x
0
26
Infinite Integration Example
>>> I = integrate.quad(f, 0, float('inf'))
>>> print(I)
(0.5000000000000002, 1.4875911858955308e-08)
Note: The exact value of the integral is 0.5.
27
Double and Triple Integrals
• There are also functions for doing double and
triple integrals.
28
Integration of Array Data
• If you only have an array of y values, without
knowing the functional dependence of x and
y, you can still integrate.
• For this, use the scipy.integrate.simps()
function, which uses Simpson’s rule.
• You can either specify the x values, or just give
the x increment, dx.
29
Example of Cumulative Integration
import scipy.integrate as integrate
import numpy as np
x = np.arange(0, 20, 2)
y = np.array([0, 3, 5, 2, 8, 9, 0, -3, 4, 9], dtype = float)
I = integrate.simps(y,x)
print(I)
• Note that I is an array with one less element
than y.
30
Download