introductory scientific computing with python

37
Introductory Scientific Computing with Python Numpy arrays FOSSEE Department of Aerospace Engineering IIT Bombay Mumbai, India FOSSEE (FOSSEE – IITB) Interactive Plotting 1 / 33

Upload: others

Post on 24-May-2022

12 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Introductory Scientific Computing with Python

Introductory Scientific Computingwith Python

Numpy arrays

FOSSEE

Department of Aerospace EngineeringIIT Bombay

Mumbai, India

FOSSEE (FOSSEE – IITB) Interactive Plotting 1 / 33

Page 2: Introductory Scientific Computing with Python

Outline

1 numpy arraysSlicing arraysArray creationExample: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 2 / 33

Page 3: Introductory Scientific Computing with Python

numpy arrays

Outline

1 numpy arraysSlicing arraysArray creationExample: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 3 / 33

Page 4: Introductory Scientific Computing with Python

numpy arrays

The numpy module

Efficient, powerful array typeAbstracts out standard operations on arraysConvenience functionsipython --pylab imports part of numpy

FOSSEE (FOSSEE – IITB) Interactive Plotting 4 / 33

Page 5: Introductory Scientific Computing with Python

numpy arrays

Without Pylab

In []: from numpy import *In []: x = linspace(0, 1)

Note that we had done this “import” earlier!

# Can also do this:In []: import numpyIn []: x = numpy.linspace(0, 1)# orIn []: import numpy as npIn []: x = np.linspace(0, 1)

Note the use of numpy.linspace

FOSSEE (FOSSEE – IITB) Interactive Plotting 5 / 33

Page 6: Introductory Scientific Computing with Python

numpy arrays

numpy arrays

Fixed size (arr.size)Same type (arr.dtype)Arbitrary dimensionality: arr.shapeshape: extent (size) along each dimensionarr.itemsize: number of bytes per elementNote: shape can change so long as the size isconstantIndices start from 0Negative indices work like lists

FOSSEE (FOSSEE – IITB) Interactive Plotting 6 / 33

Page 7: Introductory Scientific Computing with Python

numpy arrays

numpy arrays

In []: a = array([1,2,3,4])In []: b = array([2,3,4,5])

In []: print(a[0], a[-1])(1, 4)

In []: a[0] = -1In []: a[0] = 1

Operations are elementwise

FOSSEE (FOSSEE – IITB) Interactive Plotting 7 / 33

Page 8: Introductory Scientific Computing with Python

numpy arrays

Simple operations

In []: a + bOut[]: array([3, 5, 7, 9])In []: a*bOut[]: array([2, 6, 12, 20])In []: a/bOut[]: array([0, 0, 0, 0])

Operations are element-wiseTypes matter

10 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 8 / 33

Page 9: Introductory Scientific Computing with Python

numpy arrays

Data type matters

Try again with this:

In []: a = array([1.,2,3,4])In []: a/b

FOSSEE (FOSSEE – IITB) Interactive Plotting 9 / 33

Page 10: Introductory Scientific Computing with Python

numpy arrays

Examples

pi and e are defined.

In []: x = linspace(0.0, 10.0, 200)In []: x *= 2*pi/10# apply functions to array.In []: y = sin(x)In []: y = cos(x)In []: x[0] = -1In []: print(x[0], x[-1])(-1.0, 10.0)

FOSSEE (FOSSEE – IITB) Interactive Plotting 10 / 33

Page 11: Introductory Scientific Computing with Python

numpy arrays

size, shape, rank etc.

In []: x = array([1., 2, 3, 4])In []: size(x)Out[]: 4In []: x.dtypedtype(’float64’)In []: x.shapeOut[] (4,)In []: rank(x)Out[]: 1In []: x.itemsizeOut[]: 8

FOSSEE (FOSSEE – IITB) Interactive Plotting 11 / 33

Page 12: Introductory Scientific Computing with Python

numpy arrays

Multi-dimensional arrays

In []: a = array([[ 0, 1, 2, 3],...: [10,11,12,13]])

In []: a.shape # (rows, columns)Out[]: (2, 4)

In []: a[1,3]Out[]: 13

In []: a[1,3] = -1In []: a[1] # The second rowarray([10,11,12,-1])In []: a[1] = 0 # Entire row to zero.

20 mFOSSEE (FOSSEE – IITB) Interactive Plotting 12 / 33

Page 13: Introductory Scientific Computing with Python

numpy arrays Slicing arrays

Outline

1 numpy arraysSlicing arraysArray creationExample: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 13 / 33

Page 14: Introductory Scientific Computing with Python

Slicing arrays

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0,1:3]

Out[]: array([2, 3])

In []: a[1:,1:]

Out[]: array([[5, 6],[8, 9]])

In []: a[:,2]

Out[]: array([3, 6, 9])

Page 15: Introductory Scientific Computing with Python

Slicing arrays

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0,1:3]

Out[]: array([2, 3])

In []: a[1:,1:]

Out[]: array([[5, 6],[8, 9]])

In []: a[:,2]

Out[]: array([3, 6, 9])

Page 16: Introductory Scientific Computing with Python

Slicing arrays

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0,1:3]

Out[]: array([2, 3])

In []: a[1:,1:]

Out[]: array([[5, 6],[8, 9]])

In []: a[:,2]

Out[]: array([3, 6, 9])

Page 17: Introductory Scientific Computing with Python

Slicing arrays

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0,1:3]

Out[]: array([2, 3])

In []: a[1:,1:]

Out[]: array([[5, 6],[8, 9]])

In []: a[:,2]

Out[]: array([3, 6, 9])

Page 18: Introductory Scientific Computing with Python

Slicing arrays ...

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0::2,0::2] # Striding...

Out[]: array([[1, 3],[7, 9]])

# Slices refer to the same memory!

Page 19: Introductory Scientific Computing with Python

Slicing arrays ...

In []: a = array([[1,2,3], [4,5,6],...: [7,8,9]])

In []: a[0::2,0::2] # Striding...

Out[]: array([[1, 3],[7, 9]])

# Slices refer to the same memory!

Page 20: Introductory Scientific Computing with Python

numpy arrays Array creation

Outline

1 numpy arraysSlicing arraysArray creationExample: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 16 / 33

Page 21: Introductory Scientific Computing with Python

numpy arrays Array creation

Array creation functions

array(object)

linspace(start, stop, num=50)

ones(shape)

zeros((d1,...,dn))

empty((d1,...,dn))

identity(n)

ones_like(x), zeros_like(x),empty_like(x)

May pass an optional dtype= keyword argumentFor more dtypes see: numpy.typeDict

FOSSEE (FOSSEE – IITB) Interactive Plotting 17 / 33

Page 22: Introductory Scientific Computing with Python

numpy arrays Array creation

Creation examplesIn []: a = array([1,2,3], dtype=float)In []: ones_like(a)Out[]: array([ 1., 1., 1.])

In []: ones( (2, 3) )Out[]: array([[ 1., 1., 1.],

[ 1., 1., 1.]])

In []: identity(3)Out[]: array([[ 1., 0., 0.],

[ 0., 1., 0.],[ 0., 0., 1.]])

35 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 18 / 33

Page 23: Introductory Scientific Computing with Python

numpy arrays Array creation

Array math

Basic elementwise math (given two arrays a, b):a + b→ add(a, b)a - b, → subtract(a, b)a * b, → multiply(a, b)a / b, → divide(a, b)a % b, → remainder(a, b)a ** b, → power(a, b)

Inplace operators: a += b, or add(a, b, a)What happens if a is int and b is float?

FOSSEE (FOSSEE – IITB) Interactive Plotting 19 / 33

Page 24: Introductory Scientific Computing with Python

numpy arrays Array creation

Array math

Logical operations: ==, !=, <, >, etc.sin(x), arcsin(x), sinh(x),exp(x), sqrt(x) etc.sum(x, axis=0), product(x, axis=0)

dot(a, b)

FOSSEE (FOSSEE – IITB) Interactive Plotting 20 / 33

Page 25: Introductory Scientific Computing with Python

numpy arrays Array creation

Convenience functions: loadtxt

loadtxt(file_name): loads a text fileloadtxt(file_name, unpack=True):loads a text file and unpacks columns

In []: x = loadtxt(’pendulum.txt’)In []: x.shapeOut[]: (90, 2)

In []: x, y = loadtxt(’pendulum.txt’,...: unpack=True)

In []: x.shapeOut[]: (90,)

45 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 21 / 33

Page 26: Introductory Scientific Computing with Python

numpy arrays Array creation

Advanced

Only scratched the surface of numpyreduce, outer

TypecastingMore functions: take, choose, where,compress, concatenate

Array broadcasting and NoneRecord arrays

FOSSEE (FOSSEE – IITB) Interactive Plotting 22 / 33

Page 27: Introductory Scientific Computing with Python

numpy arrays Array creation

Learn more

https://docs.scipy.org/doc/numpy-dev/user/quickstart.html

http://numpy.org

FOSSEE (FOSSEE – IITB) Interactive Plotting 23 / 33

Page 28: Introductory Scientific Computing with Python

numpy arrays Array creation

Recap

Basic concepts: creation, access, operations1D, multi-dimensionalSlicingArray creation, dtypesMathloadtxt

50 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 24 / 33

Page 29: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Outline

1 numpy arraysSlicing arraysArray creationExample: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 25 / 33

Page 30: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Example: plotting data from file

Data is usually present in a file!Lets look at the pendulum.txt file.

In []: cat pendulum.txt1.0000e-01 6.9004e-011.1000e-01 6.9497e-011.2000e-01 7.4252e-011.3000e-01 7.5360e-01

. . .

FOSSEE (FOSSEE – IITB) Interactive Plotting 26 / 33

Page 31: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Reading pendulum.txt

File contains L vs. T valuesFirst Column - L valuesSecond Column - T valuesLet us generate a plot from the data file

FOSSEE (FOSSEE – IITB) Interactive Plotting 27 / 33

Page 32: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Gotcha and an asideEnsure you are in the same directory aspendulum.txtif not, do the following on IPython:In []: %cd directory_containing_file# Check if pendulum.txt is there.In []: ls# Also tryIn []: !ls

Note: %cd is an IPython magic command. For moreinformation do:In []: ?In []: %cd?

FOSSEE (FOSSEE – IITB) Interactive Plotting 28 / 33

Page 33: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Exercise

Plot L versus T square with dotsNo line connecting points

60 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 29 / 33

Page 34: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Solution

In []: L, t = loadtxt(’pendulum.txt’,....: unpack=True)

In []: plot(L, t*t, ’.’)

or

In []: x = loadtxt(’pendulum.txt’)In []: L, t = x[:,0], x[:,1]In []: plot(L, t*t, ’.’)

FOSSEE (FOSSEE – IITB) Interactive Plotting 30 / 33

Page 35: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

FOSSEE (FOSSEE – IITB) Interactive Plotting 31 / 33

Page 36: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Odds and ends

In []: mean(L)Out[]: 0.54499999999999993

In []: std(L)Out[]: 0.25979158313283879

FOSSEE (FOSSEE – IITB) Interactive Plotting 32 / 33

Page 37: Introductory Scientific Computing with Python

numpy arrays Example: plotting data from file

Summary

Introduction to numpy arraysSlicing arraysMulti-dimensional arraysArray operationsCreating arraysLoading data from file

65 m

FOSSEE (FOSSEE – IITB) Interactive Plotting 33 / 33