intermediate python: using numpy, scipy and matplotlib

30
Intermediate Python: Using NumPy, SciPy and Matplotlib Lesson 19 Odds and Ends 1

Upload: others

Post on 12-Sep-2021

41 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Intermediate Python: Using NumPy, SciPy and Matplotlib

Intermediate Python: Using NumPy, SciPy and Matplotlib

Lesson 19 – Odds and Ends

1

Page 2: Intermediate Python: Using NumPy, SciPy and Matplotlib

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.

2

>>> 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

Page 3: Intermediate Python: Using NumPy, SciPy and Matplotlib

Physical Constants

• The scipy.constants module contains many physical constants!

3

Page 4: Intermediate Python: Using NumPy, SciPy and Matplotlib

Physical Constants

4

R molar gas constant

alpha fine-structure constant

N_A Avogadro constant

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

c speed of light in vacuum

mu_0 the magnetic 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

Always verify that they are in the correct units!!!

Page 5: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

5

>>> 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

Page 6: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 7: Intermediate Python: Using NumPy, SciPy and Matplotlib

Constants Database Example

>>> sc.value('Rydberg constant')

10973731.568539

>>> sc.unit('Rydberg constant')

'm^-1'

>>> sc.precision('Rydberg constant')

5.011968778030033e-12

7

Page 8: Intermediate Python: Using NumPy, SciPy and Matplotlib

Metric Prefixes

>>> sc.yotta

1e+24

>>> sc.mega

1000000.0

>>> sc.nano

1e-09

8

Page 9: Intermediate Python: Using NumPy, SciPy and Matplotlib

Conversions • There are conversion factors to MKS units.

9

>>> 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

Page 10: Intermediate Python: Using NumPy, SciPy and Matplotlib

Temperature Conversions

10

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

Page 11: Intermediate Python: Using NumPy, SciPy and Matplotlib

Special Functions

• The scipy.special module contains many special functions, such as Bessel functions, Legendre Polynomials, etc.

11

Page 12: Intermediate Python: Using NumPy, SciPy and Matplotlib

Interpolation

• The scipy.interpolate module contains functions for interpolating 1D and 2D data.

12

Page 13: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 14: Intermediate Python: Using NumPy, SciPy and Matplotlib

interp1d() Example

14

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')

xint = 3.5

yint = f(xint)

plt.plot(x, y, 'o', c = 'b')

plt.plot(xint, yint, 's', c = 'r')

plt.show()

Cubic Spline

Interpolated Point

Page 15: Intermediate Python: Using NumPy, SciPy and Matplotlib

Results

15

Interpolated Point

Page 16: Intermediate Python: Using NumPy, SciPy and Matplotlib

interp1d() Example

16

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')

xint = np.arange(0, 9.01, 0.01)

yint = f(xint)

plt.plot(x, y, 'o', c = 'b')

plt.plot(xint, yint, '-r')

plt.show()

Cubic Spline

Interpolated Points

Page 17: Intermediate Python: Using NumPy, SciPy and Matplotlib

Results

17

Interpolated Curve

Page 18: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 19: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 20: Intermediate Python: Using NumPy, SciPy and Matplotlib

Derivatives Example

from scipy.misc import derivative import numpy as np import matplotlib.pyplot as plt …… 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$') plt.show()

20

f = lambda x : np.exp(-x)*np.sin(x)

x = np.arange(0,10, 0.1)

first = derivative(f,x,dx=1,n=1)

second = derivative(f,x,dx=1,n=2)

Page 21: Intermediate Python: Using NumPy, SciPy and Matplotlib

Derivatives Results

21

Page 22: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 23: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 24: Intermediate Python: Using NumPy, SciPy and Matplotlib

Integration Example

• Suppose we want to evaluate the integral.

24

2

0

sinxe xdx

Page 25: Intermediate Python: Using NumPy, SciPy and Matplotlib

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)

25

Value of integral. Estimate of absolute error.

Page 26: Intermediate Python: Using NumPy, SciPy and Matplotlib

Can Even Do Infinite Bounds

• Suppose we want to evaluate the integral.

26

0

sinxe xdx

Page 27: Intermediate Python: Using NumPy, SciPy and Matplotlib

Infinite Integration Example

>>> I = integrate.quad(f, 0, float('inf'))

>>> print(I)

(0.5000000000000002, 1.4875911858955308e-08)

27

Note: The exact value of the integral is 0.5.

Page 28: Intermediate Python: Using NumPy, SciPy and Matplotlib

Double and Triple Integrals

• There are also functions for doing double and triple integrals.

28

Page 29: Intermediate Python: Using NumPy, SciPy and Matplotlib

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

Page 30: Intermediate Python: Using NumPy, SciPy and Matplotlib

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)

30

• Note that I is an array with one less element than y.