418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA.

Slides:



Advertisements
Similar presentations
Lecture 5.
Advertisements

Introduction to Matlab
Introduction to Graphing Using MATLAB. Line Graphs  Useful for graphing functions  Useful for displaying data trends over time  Useful for showing.
Matlab Graphics S. Awad, Ph.D. M. Corless, M.S.E.E. E.C.E. Department University of Michigan-Dearborn Introduction to Matlab: 2D Graphics.
Slide deck by Dr. Greg Reese Miami University MATLAB An Introduction With Applications, 5 th Edition Dr. Amos Gilat The Ohio State University Chapter 3.
Python Crash Course Scipy 3 rd year Bachelors V1.0 dd Hour 3.
Recitation 7 Programming for Engineers in Python.
Lecture 6 Sept 15, 09 Goals: two-dimensional arrays matrix operations circuit analysis using Matlab image processing – simple examples.
Python Crash Course Numpy Bachelors V1.0 dd Hour 1.
PYTHON PLOTTING CURVES CHAPTER 10_5 FROM THINK PYTHON HOW TO THINK LIKE A COMPUTER SCIENTIST.
MATLAB Fundamentals.
1 Introduction to MATLAB MATLAB is all of the following: 1.Computational environment 2.Plotting software 3.Programming language Typical applications: 1.Calculations.
Mathcad Variable Names A string of characters (including numbers and some “special” characters (e.g. #, %, _, and a few more) Cannot start with a number.
Chapter 10 Review: Matrix Algebra
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
Chapter 5. Loops are common in most programming languages Plus side: Are very fast (in other languages) & easy to understand Negative side: Require a.
MATLAB INTRO CONTROL LAB1  The Environment  The command prompt Getting Help : e.g help sin, lookfor cos Variables Vectors, Matrices, and Linear Algebra.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
REVIEW 2 Exam History of Computers 1. CPU stands for _______________________. a. Counter productive units b. Central processing unit c. Copper.
Computation for Physics 計算物理概論
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. A Concise Introduction to MATLAB ® William J. Palm III.
Introduction to Python Session 2: Beginning Numerical Python and Visualization Jeremy Chen.
ECE 1304 Introduction to Electrical and Computer Engineering Section 1.1 Introduction to MATLAB.
Scientific Computing with NumPy & SciPy NumPy Installation and Documentation  Not much on the home page—don’t buy the guide, it’s.
CDA6530: Performance Models of Computers and Networks Chapter 4: Using Matlab for Performance Analysis and Simulation TexPoint fonts used in EMF. Read.
Matlab 14.html Cost: $100 Available in labs on Windows and Unix machines.
ES 240: Scientific and Engineering Computation. Chapter 2 Chapter 2: MATLAB Fundamentals Uchechukwu Ofoegbu Temple University.
Python Crash Course Numpy 3 rd year Bachelors V1.0 dd Hour 5.
Matlab Screen  Command Window  type commands  Current Directory  View folders and m-files  Workspace  View program variables  Double click on a.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 21 NumPy 6/11/09 Python Mini-Course: Lesson 21 1.
UW CSE 190p Section 7/26, Summer 2012 Dun-Yu Hsiao.
Linear Algebra Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
Part 1 Chapter 2 MATLAB Fundamentals PowerPoints organized by Dr. Michael R. Gustafson II, Duke University and Prof. Steve Chapra, Tufts University All.
EGR 106 Lecture 6 2-D Plotting Graphical presentation has become the standard method to show technical information. Engineers use plots to analyze, visualize,
Matlab Introduction  Getting Around Matlab  Matrix Operations  Drawing Graphs  Calculating Statistics  (How to read data)
NumPy References The Numpy Example List   Tables of contents ordered.
Python Crash Course Numpy & MatplotLib Sterrenkundig Practicum 2 V1.0 dd Hour 3.
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
Python & NetworkX Youn-Hee Han
CS100A, Fall 1998, Lecture 191 CS100A, Fall 1998 Lecture 19, Thursday Nov 05 Matlab Concepts: Matlab arrays Matlab subscripting Matlab plotting.
CS100A, Fall 1998, Lecture 201 CS100A, Fall 1998 Lecture 20, Tuesday Nov 10 More Matlab Concepts: plotting (cont.) 2-D arrays Control structures: while,
An Introduction to Programming in Matlab Emily Blumenthal
Copyright © CRS Enterprises Ltd 1 Python for Scientists by Chris Seddon.
Python Scripting for Computational Science CPS 5401 Fall 2014 Shirley Moore, Instructor October 6,
Numerical and Scientific Computing Part 2
PH2150 Scientific Computing Skills
ECE 1304 Introduction to Electrical and Computer Engineering
Numpy (Numerical Python)
Introduction to Mat lab
IPYTHON AND MATPLOTLIB Python for computational science
TexPoint fonts used in EMF.
Matrices and Arrays.
Python NumPy AILab Batselem Jagvaral 2016 March.
Numerical Computing in Python
Python plotting curves chapter 10_5
Vectors and Matrices I.
Matplotlib.
Numpy (Numerical Python)
Notes on pyplot Professor Hugh C. Lauer CS-1004 — Introduction to Programming for Non-Majors (Slides include materials from Python Programming: An Introduction.
Plotting Signals in MATLAB
Python Crash Course Scipy
MATLAB Programming Basics Copyright © Software Carpentry 2011
Data Intensive and Cloud Computing Matrices and Arrays Lecture 9
Scipy 'Ecosystem' containing a variety of scientific packages including iPython, numpy, matplotlib, and pandas. numpy is both a system for constructing.
Announcements P3 due today
How to Use MATLAB A Brief Introduction.
Dr. Sampath Jayarathna Old Dominion University
Matplotlib and Pandas
Presentation transcript:

418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA A A

Python Mathematical Libraries NumPy SciPy matplotlib

NUMPY

Numpy Numpy manipulates homogeneous multidimensional array. – Table of same types of elements. – Indexed by tuple of positive integers. Example: – [1, 2, 1]  rank 1  1 axis – [[ 1., 0., 0.], [ 0., 1., 2.]]  rank 2  2 axis

ndarray ndarray = class for multidim array Properties – ndarray.ndim number of axes – ndarray.shape tuple of integers indicating sizes of array in each dim – ndarray.size total number of elements in an array

ndarray Properpies – ndarray.dtype type of elements in the array – ndarray.itemsize size in bytes of each element of the array – ndarray.data memory containing the actual elements don’t deal with this directly

ndarray >>> from numpy import * >>> a = arange(10).reshape(2,5) >>> a array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) >>> a.shape (2, 5) >>> a.size 10 >>> a.dtype dtype('int32') >>> a.itemsize 4

Array Creation Use the “array” function. >>> from numpy import * >>> a = array( [2,3,4] ) >>> a array([2, 3, 4]) >>> type(a) >>> b = array( [(1.5,2,3), (4,5,6)] ) >>> b array([[ 1.5, 2., 3. ], [ 4., 5., 6. ]])

dtype parameter >>> c = array( [ [1,2], [3,4] ], dtype=complex ) >>> c array([[ 1.+0.j, 2.+0.j], [ 3.+0.j, 4.+0.j]])

Array Creation zeros >>> zeros((3,4)) array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])

Array Creation ones >>> ones((2,3,4), dtype=int16) array([[[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]], [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]], dtype=int16)

Array Creation empty >>> empty((2,3)) array([[ e+161, e-096, e-057], [ e+277, e+214, e+000]])

Array Creation arange >>> arange( 10, 30, 5 ) array([10, 15, 20, 25]) >>> arange( 0, 2, 0.3 ) array([ 0., 0.3, 0.6, 0.9, 1.2, 1.5, 1.8])

Array Creation linspace – last argument = number of elements >>> linspace( 0, 2, 9 ) array([ 0., 0.25, 0.5, 0.75, 1., 1.25, 1.5, 1.75, 2. ])

Basic Operations Arithmetic operators apply elementwise. >>> a = array( [20, 30, 40, 50] ) >>> b = arange( 4 ) >>> c = a - b >>> c array([20, 29, 38, 47]) >>> b**2 array([0, 1, 4, 9]) >>> 10*sin(a) array([ , , , ]) >>> a < 35 array([ True, True, False, False], dtype=bool)

Multiplication * (multiplication) operates elementwise too. – Not matrix multiplication. >>> A = array( [[1,1], [0,1]] ) >>> B = array( [[2,0], [3,4]] ) >>> A * B array([[2, 0], [0, 4]])

Matrix Product Use the “dot” function. >>> A = array( [[1,1], [0,1]] ) >>> B = array( [[2,0], [3,4]] ) >>> dot(A,B) array([[5, 4], [3, 4]])

In-Place Operator Some operators do not create new arrays. >>> a = ones((2,3), dtype=int) >>> b = random.random((2,3)) >>> a *= 3 >>> a array([[3, 3, 3], [3, 3, 3]]) >>> b += a >>> b array([[ , , ], [ , , ]]) >>> a += b >>> a array([[6, 6, 6], [6, 6, 6]])

Unary Operators >>> a = random.random((2,3)) >>> a array([[ , , ], [ , , ]]) >>> a.sum() >>> a.min() >>> a.max()

axis parameter Supply the “axis” parameter to apply operators along a particular axis. >>> b = arange(12).reshape(3,4) >>> b array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> b.sum(axis=0) array([12, 15, 18, 21]) >>> b.min(axis=1) array([0, 4, 8]) >>> b.cumsum(axis=1) array([[ 0, 1, 3, 6], [ 4, 9, 15, 22], [ 8, 17, 27, 38]])

Universal Functions >>> B = arange(3) >>> B array([0, 1, 2]) >>> exp(B) array([ 1., , ]) >>> sqrt(B) array([ 0., 1., ])

Indexing, Slicing, and Iterating >>> a = arange(10)**3 >>> a array([ 0, 1, 8, 27, 64, 125, 216, 343, 512, 729]) >>> a[2] 8 >>> a[2:5] array([ 8, 27, 64]) >>> a[3] = >>> a array([0, 1, 8, -1000, 64, 125, 216, 343, 512, 729])

Indexing Multidimensional Array Indices are tuple separated by commas. >>> def f(x,y):... return 10*x+y... >>> b = fromfunction(f, (5,4), dtype=int) >>> b array([[ 0, 1, 2, 3], [10, 11, 12, 13], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43]]) >>> b[2,3] 23 >>> b[:,1] array([ 1, 11, 21, 31, 41]) >>> b[1:3,:] array([[10, 11, 12, 13], [20, 21, 22, 23]])

Iterating over Multidimensional Array You get the rows. >>> for row in b:... print row... [ ] [ ] [ ] [ ] [ ]

Flat Attribute Use “flat” attribute to get each element. >>> for element in b.flat:... print element,

Ravel and Transpose >>> a = floor(10*random.random((3,4))) >>> a array([[ 4., 0., 0., 0.], [ 7., 2., 1., 3.], [ 6., 9., 1., 1.]]) >>> a.ravel() array([ 4., 0., 0., 0., 7., 2., 1., 3., 6., 9., 1., 1.]) >>> a.transpose() array([[ 4., 7., 6.], [ 0., 2., 9.], [ 0., 1., 1.], [ 0., 3., 1.]])

Reshape and Resize Reshape returns a new array. >>> a = floor(10*random.random((3,4))) >>> a.reshape(6,2) array([[ 0., 7.], [ 6., 8.], [ 3., 5.], [ 3., 9.], [ 0., 7.], [ 4., 7.]]) >>> a.resize(2,6) >>> a array([[ 0., 7., 6., 8., 3., 5.], [ 3., 9., 0., 7., 4., 7.]])

Deep Copy Do deep copy with the “copy” method. >>> a = arange(12).reshape(3,4) >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> d = a.copy() >>> d is a False >>> d[0,0] = 9999 >>> a array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) >>> d array([[9999, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]])

Matrix Matrices are created by “matrix” function. Matrices are different from arrays that * is matrix multiplication. >>> A = matrix([[1,2,3], [4,5,6], [7,8,9]]) >>> A matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) >>> B = matrix([[2,0,0], [0,2,0], [0,0,2]]) >>> A * B matrix([[ 2, 4, 6], [ 8, 10, 12], [14, 16, 18]])

SCIPY

Scipy Scipy is for scientific computation. To use: import scipy Useful subpackages: – clusterclustering algorithms – fftpackfast fourier transform – integrateintegration – interpolateinterpolation and smoothing splines – linalglinear algebra – optimizeoptimization and root-finding – signalsignal processing – sparsesparse matrices – statsstatistical distribution and functions

Scipy Documentation Use “scipy.info” on packages or functions. >>> import scipy >>> from scipy import linalg >>> scipy.info(linalg) >>> scipy.info(linalg.det )

integrate.quad Use it to integrate a general function. For example, if you want to compute: >>> from scipy import integrate >>> integrate.quad(lambda x: x**2, 0, 4.5) (30.375, e-13) The first return value is the value of integration. The second is the upper bound on the error.

optimize.fmin Use it to find the argument that minimizes a function. For example, if you want to minimize: >>> def rosen(x):... return sum(100.0*(x[1:]-x[:-1]**2.0)**2.0 + (1-x[:-1])**2.0)... >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2] >>> xopt = fmin(rosen, x0, xtol=1e-8) >>> print xopt [ ]

optimize.fsolve Use it to find a zero of a function. Suppose you want to solve: >>> def func(x):... return x + 2*cos(x)... >>> from scipy.optimize import fsolve >>> x0 = fsolve(func, 0.3) >>> print x0 [ ]

optimize.fsolve You want to solve a system of equation >>> def func2(x):... out = [x[0]*cos(x[1])-4]... out.append(x[1]*x[0] - x[1] - 5)... return out... >>> x02 = fsolve(func2, [1,1]) >>> print x02 [ ]

linalg.inv Find the inverse of a matrix. >>> A = matrix([[1,3,5], [2,5,1], [2,3,8]]) >>> from scipy import linalg >>> linalg.inv(A) array([[-1.48, 0.36, 0.88], [ 0.56, 0.08, -0.36], [ 0.16, -0.12, 0.04]])

linalg.solve To solve the linear system: >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> b = mat('[10;8;3]') >>> linalg.solve(A,b) array([[-9.28], [ 5.16], [ 0.76]])

linalg.det Find the determinant. >>> A = mat('[1 3 5; 2 5 1; 2 3 8]') >>> linalg.det(A)

linalg.svd Find the singular value decomposition. >>> A = mat('[1 3 2; 1 2 3]') >>> U, s, Vh = linalg.svd(A) >>> U array([[ , ], [ , ]]) >>> s array([ , 1. ]) >>> Vh array([[ e-01, e-01, e-01], [ e-16, e-01, e-01], [ e-01, e-01, e-01]])

linalg.eig Find eigenvalues and eigenvectors. >>> A = mat('[1 5 2; 2 4 1; 3 6 2]') >>> la, v = linalg.eig(A) >>> v array([[ , , ], [ , , ], [ , , ]]) >>> la array([ j, j, j])

MATPLOTLIB

matplotlib.pyplot A package for plotting graphs. pyplot works like MATLAB. – Commands make changes a figure. – Stateful.

pyplot.plot >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3,4]) [ ] >>> plt.ylabel('some numbers') >>> plt.show()

pyplot.plot

Here’s how you plot x-vs-y.

pyplot.plot Third argument indicates the style of the graph. – Default value ‘b-’ is blue line. – Below: ‘ro’ is red dots. >>> plt.plot([1,2,3,4], [1,4,9,16], 'ro') [ ] >>> plt.show()

pyplot.plot

pyplot.axis axis() takes [xmin, xmax, ymin, ymax] >>> plt.plot([1,2,3,4], [1,4,9,16], 'ro') >>> plt.axis([0, 6, 0, 20]) >>> plt.show()

pyplot.axis

matplotlib and Numpy You can use Numpy arrays as arrays of x and y values. >>> import numpy as np >>> import matplotlib.pyplot as plt >>> t = np.arange(0., 5., 0.2) >>> plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') >>> plt.show()

matplotlib and Numpy

pyplot.subplot subplot(r, c, fignum) – Create a grid with r rows and c cols. – fignum ranges from 1 to r*c. – fignum selects which grid cell to draw to.

pyplot.subplot >>> import numpy as np >>> import matplotlib.pyplot as plt >>> def f(t):... return np.exp(-t) * np.cos(2*np.pi*t)... >>> t1 = np.arange(0.0, 5.0, 0.1) >>> t2 = np.arange(0.0, 5.0, 0.02) >>> plt.figure(1) >>> plt.subplot(2,1,1) >>> plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') >>> plt.subplot(2,1,2) >>> plt.plot(t2, np.cos(2*np.pi*t2), 'r--') >>> plt.show()

pyplot.subplot

Drawing Text text() – Add text at arbitrary location. xlabel(), ylabel(), title() – Add text at specified locations.

Drawing Text import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) n, bins, patches = plt.hist(x, 50, normed=1, facecolor='g', alpha=0.75) plt.xlabel('Smarts') plt.ylabel('Probability') plt.title('Histogram of IQ') plt.text(60,.025, r'$\mu=100,\ \sigma=15$') plt.axis([40, 160, 0, 0.03]) plt.grid(True)

Drawing Text

pyplot.annotate Makes it easy to annotate the graph. – xy: the location of to be annotated – xytext: the location of the text ax = plt.subplot(111) t = np.arange(0.0, 5.0, 0.01) s = np.cos(2*np.pi*t) line, = plt.plot(t, s, lw=2) plt.annotate('local max', xy=(2, 1), xytext=(3, 1.5), arrowprops=dict(facecolor='black', shrink=0.05), ) plt.ylim(-2,2) plt.show()

pyplot.annotate