Python Crash Course Numpy & MatplotLib Sterrenkundig Practicum 2 V1.0 dd 07-01-2015 Hour 3.

Slides:



Advertisements
Similar presentations
MATLAB – A Computational Methods By Rohit Khokher Department of Computer Science, Sharda University, Greater Noida, India MATLAB – A Computational Methods.
Advertisements

Computation for Physics 計算物理概論
Introduction to MATLAB The language of Technical Computing.
Introduction to M ATLAB Programming Ian Brooks Institute for Climate & Atmospheric Science School of Earth & Environment
Introduction to Matlab
Matrix Manipulation and 2D Plotting
MATLAB – What is it? Computing environment / programming language Tool for manipulating matrices Many applications, you just need to get some numbers in.
Recitation 7 Programming for Engineers in Python.
Python Crash Course Numpy Bachelors V1.0 dd Hour 1.
Lecture 4 Sept 7 Chapter 4. Chapter 4 – arrays, collections and indexing This chapter discusses the basic calculations involving rectangular collections.
Lecture 2 MATLAB fundamentals Variables, Naming Rules, Arrays (numbers, scalars, vectors, matrices), Arithmetical Operations, Defining and manipulating.
Introduction to Matlab Jianguo Wang CSSCR September 2009.
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.
Engineering Analysis ENG 3420 Fall 2009 Dan C. Marinescu Office: HEC 439 B Office hours: Tu-Th 11:00-12:00.
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
Introduction to MATLAB January 18, 2008 Steve Gu Reference: Eta Kappa Nu, UCLA Iota Gamma Chapter, Introduction to MATLAB,
MATLAB Tutorials Session I Introduction to MATLAB Rajeev Madazhy Dept of Mechanical Engineering LSU.
Computation for Physics 計算物理概論
Introduction to Python Session 2: Beginning Numerical Python and Visualization Jeremy Chen.
418512: Computer Programming Languages Lecture 7 Pramook Khungurn TexPoint fonts used in EMF. Read the TexPoint manual before you delete this box.: A AAAA.
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.
Eng Ship Structures 1 Introduction to Matlab.
MAE 1202: AEROSPACE PRACTICUM An Introduction to MATLAB: Part 2 Mechanical and Aerospace Engineering Department Florida Institute of Technology Developed.
Introduction to MATLAB adapted from Dr. Rolf Lakaemper.
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.
Python Mini-Course University of Oklahoma Department of Psychology Lesson 21 NumPy 6/11/09 Python Mini-Course: Lesson 21 1.
Introduction to Matlab  Matlab is a software package for technical computation.  Matlab allows you to solve many numerical problems including - arrays.
Basics Copyright © Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See
INTRODUCTION TO MATLAB DAVID COOPER SUMMER Course Layout SundayMondayTuesdayWednesdayThursdayFridaySaturday 67 Intro 89 Scripts 1011 Work
INTRODUCTION TO MATLAB Dr. Hugh Blanton ENTC 4347.
CIS 601 Fall 2003 Introduction to MATLAB Longin Jan Latecki Based on the lectures of Rolf Lakaemper and David Young.
Postgraduate Computing Lectures PAW 1 PAW: Physicist Analysis Workstation What is PAW? –A tool to display and manipulate data. Learning PAW –See ref. in.
Matplotlib SANTHOSH Boggarapu.
Python & NetworkX Youn-Hee Han
Math 252: Math Modeling Eli Goldwyn Introduction to MATLAB.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
Computer Science 121 Scientific Computing Winter 2016 Chapter 3 Simple Types: Numbers, Text, Booleans.
CIS 595 MATLAB First Impressions. MATLAB This introduction will give Some basic ideas Main advantages and drawbacks compared to other languages.
CS100A, Fall 1998, Lecture 191 CS100A, Fall 1998 Lecture 19, Thursday Nov 05 Matlab Concepts: Matlab arrays Matlab subscripting Matlab plotting.
How to use MATLAB (using M-files) Double click this icon To start Matlab 6.5.
Python Scripting for Computational Science CPS 5401 Fall 2014 Shirley Moore, Instructor October 6,
Introducing Tim Sheerman-Chase This work is licensed under a Creative Commons Attribution 3.0 Unported License 28 th Sept 2011.
Numerical and Scientific Computing Part 2
PH2150 Scientific Computing Skills
Numpy (Numerical Python)
IPYTHON AND MATPLOTLIB Python for computational science
Python NumPy AILab Batselem Jagvaral 2016 March.
INTRODUCTION TO BASIC MATLAB
PH2150 Scientific Computing Skills
Introduction to MATLAB
Numerical Computing in Python
Matlab tutorial course
Python plotting curves chapter 10_5
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.
Python Crash Course Numpy
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.
Simulation And Modeling
Dr. Sampath Jayarathna Cal Poly Pomona
Dr. Sampath Jayarathna Old Dominion University
Python for Data Analysis
Matplotlib and Pandas
Presentation transcript:

Python Crash Course Numpy & MatplotLib Sterrenkundig Practicum 2 V1.0 dd Hour 3

Scientific Python? Extra features required: –fast, multidimensional arrays –libraries of reliable, tested scientific functions –plotting tools 2

Arrays – Numerical Python (Numpy) Lists ok for storing small amounts of one-dimensional data But, can’t use directly with arithmetical operators (+, -, *, /, …) Need efficient arrays with arithmetic and better multidimensional tools Numpy Similar to lists, but much more capable, except fixed size >>> a = [1,3,5,7,9] >>> print(a[2:4]) [5, 7] >>> b = [[1, 3, 5, 7, 9], [2, 4, 6, 8, 10]] >>> print(b[0]) [1, 3, 5, 7, 9] >>> print(b[1][2:4]) [6, 8] >>> import numpy >>> a = [1,3,5,7,9] >>> b = [3,5,6,7,9] >>> c = a + b >>> print c [1, 3, 5, 7, 9, 3, 5, 6, 7, 9]

Numpy – N-dimensional Array manpulations The fundamental library needed for scientific computing with Python is called NumPy. This Open Source library contains: a powerful N-dimensional array object advanced array slicing methods (to select array elements) convenient array reshaping methods and it even contains 3 libraries with numerical routines: basic linear algebra functions basic Fourier transforms sophisticated random number capabilities NumPy can be extended with C-code for functions where performance is highly time critical. In addition, tools are provided for integrating existing Fortran code. NumPy is a hybrid of the older NumArray and Numeric packages, and is meant to replace them both.

Numpy - ndarray NumPy's main object is the homogeneous multidimensional array called ndarray. –This is a table of elements (usually numbers), all of the same type, indexed by a tuple of positive integers. Typical examples of multidimensional arrays include vectors, matrices, images and spreadsheets. –Dimensions usually called axes, number of axes is the rank [7, 5, -1] An array of rank 1 i.e. It has 1 axis of length 3 [ [ 1.5, 0.2, -3.7], An array of rank 2 i.e. It has 2 axes, the first [ 0.1, 1.7, 2.9] ] length 3, the second of length 3 (a matrix with 2 rows and 3 columns >>> a = numpy.array([1,3,5,7,9]) >>> b = numpy.array([3,5,6,7,9]) >>> c = a + b >>> print c [4, 8, 11, 14, 18]

Numpy – ndarray attributes ndarray.ndim –the number of axes (dimensions) of the array i.e. the rank. ndarray.shape –the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim. ndarray.size –the total number of elements of the array, equal to the product of the elements of shape. ndarray.dtype –an object describing the type of the elements in the array. One can create or specify dtype's using standard Python types. NumPy provides many, for example bool_, character, int_, int8, int16, int32, int64, float_, float8, float16, float32, float64, complex_, complex64, object_. ndarray.itemsize –the size in bytes of each element of the array. E.g. for elements of type float64, itemsize is 8 (=64/8), while complex32 has itemsize 4 (=32/8) (equivalent to ndarray.dtype.itemsize). ndarray.data –the buffer containing the actual elements of the array. Normally, we won't need to use this attribute because we will access the elements in an array using indexing facilities.

Numpy – array creation and use >>> import numpy >>> l = [[1, 2, 3], [3, 6, 9], [2, 4, 6]] # create a list >>> a = numpy.array(l) # convert a list to an array >>> print(a) [[1 2 3] [3 6 9] [2 4 6]] >>> a.shape (3, 3) >>> print(a.dtype) # get type of an array int32 >>> print(a[0]) # this is just like a list of lists [1 2 3] >>> print(a[1, 2]) # arrays can be given comma separated indices 9 >>> print(a[1, 1:3]) # and slices [6 9] >>> print(a[:,1]) [2 6 4]

Numpy – array creation and use >>> a[1, 2] = 7 >>> print(a) [[1 2 3] [3 6 7] [2 4 6]] >>> a[:, 0] = [0, 9, 8] >>> print(a) [[0 2 3] [9 6 7] [8 4 6]] >>> b = numpy.zeros(5) >>> print(b) [ ] >>> b.dtype dtype(‘float64’) >>> n = 1000 >>> my_int_array = numpy.zeros(n, dtype=numpy.int) >>> my_int_array.dtype dtype(‘int32’)

Numpy – array creation and use >>> c = numpy.ones(4) >>> print(c) [ ] >>> d = numpy.arange(5) # just like range() >>> print(d) [ ] >>> d[1] = 9.7 >>> print(d) # arrays keep their type even if elements changed [ ] >>> print(d*0.4) # operations create a new array, with new type [ ] >>> d = numpy.arange(5, dtype=numpy.float) >>> print(d) [ ] >>> numpy.arange(3, 7, 0.5) # arbitrary start, stop and step array([ 3., 3.5, 4., 4.5, 5., 5.5, 6., 6.5])

Numpy – array methods >>> arr.sum() 45 >>> arr.mean() 4.5 >>> arr.std() >>> arr.max() 9 >>> arr.min() 0 >>> div_by_3.all() False >>> div_by_3.any() True >>> div_by_3.sum() 3 >>> div_by_3.nonzero() (array([2, 5, 8]),)

Numpy – array mathematics >>> a = np.array([1,2,3], float) >>> b = np.array([5,2,6], float) >>> a + b array([6., 4., 9.]) >>> a – b array([-4., 0., -3.]) >>> a * b array([5., 4., 18.]) >>> b / a array([5., 1., 2.]) >>> a % b array([1., 0., 3.]) >>> b**a array([5., 4., 216.]) >>> a = np.array([[1, 2], [3, 4], [5, 6]], float) >>> b = np.array([-1, 3], float) >>> a array([[ 1., 2.], [ 3., 4.], [ 5., 6.]]) >>> b array([-1., 3.]) >>> a + b array([[ 0., 5.], [ 2., 7.], [ 4., 9.]])

Numpy – array functions Most array methods have equivalent functions Ufuncs provide many element-by-element math, trig., etc. operations –e.g., add(x1, x2), absolute(x), log10(x), sin(x), logical_and(x1, x2) See >>> arr.sum() 45 >>> numpy.sum(arr) 45

Plotting - matplotlib User friendly, but powerful, plotting capabilites for python Once installed (default at Observatory) >>> import pylab Settings can be customised by editing ~/.matplotlib/matplotlibrc –default font, colours, layout, etc. Helpful website –many examples

Pylab and Pyplot $ python Python (default, Aug , 17:23:57) [GCC (Red Hat )] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3,4]) [ ] >>> plt.ylabel('some numbers') >>> plt.show() $ ipython –-pylab Python (default, Aug , 17:23:57) Type "copyright", "credits" or "license" for more information. IPython An enhanced Interactive Python. ? -> Introduction and overview of IPython's features. %quickref -> Quick reference. help -> Python's own help system. object? -> Details about 'object', use 'object??' for extra details. Welcome to pylab, a matplotlib-based Python environment [backen: GTKAgg]. For more information, type ‘help(pylab)’ In [1]: plot([1,2,3,4])

Matplotlib.pyplot basic example import matplotlib.pyplot as plt plt.plot([1,2,3,4]) plt.ylabel('some numbers') plt.show() matplotlib.pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot unction makes some change to a figure: eg, create a figure, create a plotting area in a figure, plot some lines in a plotting area, decorate the plot with labels, etc....

Matplotlib.pyplot basic example import numpy as np import matplotlib.pyplot as plt # evenly sampled time at 200ms intervals t = np.arange(0., 5., 0.2) # red dashes, blue squares and green triangles plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^') Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.

Matplotlib.pyplot example import numpy as np import matplotlib.pyplot as plt mu, sigma = 100, 15 x = mu + sigma * np.random.randn(10000) # the histogram of the data 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) Working with text. The text() command can be used to add text in an arbitrary location, and the xlabel(), ylabel() and title() are used to add text in the indicated locations.

Matplotlib.pyplot example from matplotlib import rc from matplotlib.numerix import arange, cos, pi from pylab import figure, axes, plot, xlabel, ylabel, title, grid, savefig, show rc('text', usetex=True) figure(1) ax = axes([0.1, 0.1, 0.8, 0.7]) t = arange(0.0, , 0.01) s = cos(2*2*pi*t)+2 plot(t, s) xlabel(r'\textbf{time (s)}') ylabel(r'\textit{voltage (mV)}',fontsize=16) title(r"\TeX\ is Number $\displaystyle\sum_{n=1}^\infty\frac{-e^{i\pi}}{2^n}$!", fontsize=16, color='r') grid(True) savefig('tex_demo') show() Using TeX.