MS6021 Scientific Computing. TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Similar documents
Python for Scientists

Numerical Calculations

PYTHON NUMPY TUTORIAL CIS 581

Introduction to Python Practical 1

Ch.5: Array computing and curve plotting (Part 1)

User-Defined Function

Introduction to Scientific Computing with Python, part two.

MS6021 Scientific Computing. MatLab and Python for Mathematical Modelling. Aimed at the absolute beginner.

Numerical Methods. Centre for Mathematical Sciences Lund University. Spring 2015

ENGR (Socolofsky) Week 07 Python scripts

Python Crash Course Numpy, Scipy, Matplotlib

Part VI. Scientific Computing in Python. Alfredo Parra : Scripting with Python Compact Max-PlanckMarch 6-10,

Bi 1x Spring 2014: Plotting and linear regression

Introduction to Matlab

ERTH3021 Exploration and Mining Geophysics

Programming for Engineers in Python

python 01 September 16, 2016

Introduction to Python

STAT/MATH 395 A - PROBABILITY II UW Winter Quarter Matlab Tutorial

MATPLOTLIB. Python for computational science November 2012 CINECA.

Scientific Programming. Lecture A08 Numpy

ARTIFICIAL INTELLIGENCE AND PYTHON

Introduction to Programming with Python 3, Ami Gates. Chapter 1: Creating a Programming Environment

Introductory Scientific Computing with Python

python numpy tensorflow tutorial

1 Introduction to Matlab

A. Python Crash Course

ERTH2020 Introduction to Geophysics

Scientific Computing: Lecture 1

MO101: Python for Engineering Vladimir Paun ENSTA ParisTech

Introduction to Python Part 2

10.4 Linear interpolation method Newton s method

Grace days can not be used for this assignment

HW0 v3. October 2, CSE 252A Computer Vision I Fall Assignment 0

Week Two. Arrays, packages, and writing programs

Introduction to. The Help System. Variable and Memory Management. Matrices Generation. Interactive Calculations. Vectors and Matrices

Tutorial 2 PHY409 Anadi Canepa Office, TRIUMF MOB 92 B ( )

MATH (CRN 13695) Lab 1: Basics for Linear Algebra and Matlab

Implement NN using NumPy

Effective Programming Practices for Economists. 10. Some scientific tools for Python

Eric W. Hansen. The basic data type is a matrix This is the basic paradigm for computation with MATLAB, and the key to its power. Here s an example:

INTRODUCTION TO MATLAB, SIMULINK, AND THE COMMUNICATION TOOLBOX

Part VI. Scientific Computing in Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

MATLAB Tutorial. Mohammad Motamed 1. August 28, generates a 3 3 matrix.

Sunpy Python for Solar Physics Juan Carlos Martínez Oliveros

Introduction to Octave/Matlab. Deployment of Telecommunication Infrastructures

Defining Functions. turning expressions into functions. writing a function definition defining and using modules

Python Compact. 1 Python Compact. 2 What do we cover in this introduction lecture? February 7, What is also interesting to know?

F21SC Industrial Programming: Python: Python Libraries

Interactive Mode Python Pylab

An Introduction to Numerical Methods

LECTURE 19. Numerical and Scientific Packages

Chapter 2. MathScript

MLCV 182: Practical session 1 Ron Shapira Weber Computer Science, Ben-Gurion University

Introduction to Machine Learning. Useful tools: Python, NumPy, scikit-learn

Image Processing (1) Basic Concepts and Introduction of OpenCV

Getting Started with MATLAB

AMath 483/583 Lecture 28 June 1, Notes: Notes: Python scripting for Fortran codes. Python scripting for Fortran codes.

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Introduction to MATLAB LAB 1

CME 193: Introduction to Scientific Python Lecture 6: Numpy, Scipy, Matplotlib

A Guide to Using Some Basic MATLAB Functions

Episode 1 Using the Interpreter

Numerical Integration

Phys Techniques of Radio Astronomy Part 1: Python Programming LECTURE 3

MATLAB Basics. Configure a MATLAB Package 6/7/2017. Stanley Liang, PhD York University. Get a MATLAB Student License on Matworks

IAP Python - Lecture 4

Euler s Method with Python

Datenanalyse (PHY231) Herbstsemester 2017

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

Matlab Tutorial. Get familiar with MATLAB by using tutorials and demos found in MATLAB. You can click Start MATLAB Demos to start the help screen.

Matplotlib Python Plotting

MS&E351 Dynamic Programming and Stochastic Control Autumn 2016 Professor Benjamin Van Roy Python Tutorial

Python in Economics and Finance

A Brief Introduction to MATLAB

Introduction to MATLAB. Computational Probability and Statistics CIS 2033 Section 003

Lab 4: Structured Programming I

Matlab Introduction. Scalar Variables and Arithmetic Operators

Ch.1 Introduction. Why Machine Learning (ML)?

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

EE 350. Continuous-Time Linear Systems. Recitation 1. 1

UNIVERSITETET I OSLO

Python for Science and Engineering

Introduction to Matlab

Chapter 1 Introduction to MATLAB

Ch.1 Introduction. Why Machine Learning (ML)? manual designing of rules requires knowing how humans do it.

Python Programming. Hans-Petter Halvorsen.

Stokes Modelling Workshop

Python Scripting for Computational Science

Introduction to Scientific Computing with Matlab

Introduction to MATLAB

Mechanical Engineering Department Second Year (2015)

MATLAB. Input/Output. CS101 lec

Introduction to Engineering gii

PHY224 Practical Physics I. Lecture 2

MATLAB/Octave Tutorial

Ch.2: Loops and lists

Chapter 5 : Informatics Practices. Class XII ( As per CBSE Board) Numpy - Array. New Syllabus Visit : python.mykvs.in for regular updates

Lab 1 - Basic ipython Tutorial (EE 126 Fall 2014)

Introduction to MATLAB Practical 1

Transcription:

MS6021 Scientific Computing TOPICS: Python BASICS, INTRO to PYTHON for Scientific Computing

Preliminary Notes on Python (v MatLab + other languages) When you enter Spyder (available on installing Anaconda), you ll be able to (as in MatLab) use the Command Window, or create scripts (they will have an extension.py) Simplest commands (play with them): print("hello world!") x=3; print("x =", x) # comments 5/3 5./3 2**3 (NOTE that this is equivalent to 2^3 in MatLab!) 2

Basic Mathematical functions need to be imported (i.e. loaded)!!! sin(1) will produce an error, i.e. Python does not recognize mathematical functions such as sin. To get access to this function (and many other mathematical functions), we need to import them from a Python library, also called a module (such as math or numpy). A few approaches are available (one may employ all of them on different occasions): (a) import math math.sin(1) #. indicates that we use function sin from module math (b) from math import sin sin(1) (c) from math import * # here * means that ALL functions are imported from math sin(1), log(3) # we can use other math functions, such as log In the above (a)-(c), the module math can be replaced by a bigger module numpy (replace also sin by exp in your examples) Furthermore, a version of (a) with numpy can be replaced by (a ) import numpy as np # very typical abbreviation!! np.exp(1) # instead of numpy.exp(1) 3

COPYING complex data types (lists, arrays ) --- BEWARE!!! When you create x=5. and then y=x, then changing y does NOT change x For more complex data types, assignments in Python usually do not copy the actual objects (to achieve high performance): A = [1, 2, 3, 5] B = A B[0]=100 # now B is referring to the same list data as A # so changing B affects A (and visa versa) # print A and B to check this! If you want to really create a copy, instead of B=A, use B = A[:] Perform the above example with this replacement and see the difference! See also [Section 3.11, Python for Computational Science and Engineering ] (the link is given below) --- for similar examples with arrays 4

Instead of end to finish a loop, if statement, a function, program blocks are defined by their indentation level: Compare: PYTHON: if x>0: print ("x is positive") print("x =", x ) # end of indentation=end of loop if x>0: print ("x is positive") # end of indentation=end of loop print("x =", x ) def myfun(x,y): return x+y**3 # end of function print(myfun(1,4)) Link to further examples MATLAB if x>0 'x is positive x end if x>0 'x is positive end x function z = myfun(x,y) z=x+y.^3 end myfun(1,4) 5

Indexing Range in a list (array) Indexing starts at 0! (while in MatLab from 1) Negative indices are possbile A=[8,4,3,5,9,12] print(a[0]) # prints the FIRST entry 8 print(a[2]) # prints the third entry 3 # here we have created a LIST A print(a[-1]) # prints the FINAL entry 12 # check A[-2], A[-3], A[-6] Note that A[7] and A[-7] will result in an error! List can be created and used in loops using range(start, stop) or range(start, stop, step) Try range(3, 12) and range(3, 15, 4) inside the following for loop. Note that in both cases, the final element is 11 (NOT 12 or 15!). for x in range(-3,3): print(x) We can extract a list part using [start : stop] or [:] or [: stop] or [start :] A[0:3] A[1:-1] A[1:6:2] # does NOT include A[3] # try to predict the output before running this command! # try to predict/explain the output of A[1:6:2] 6

lambda functions (similar to anonymous functions in MatLab) In Python we can define functions, using the lambda keyword: f1 = lambda x: x**2 # is equivalent to def f2(x): return x**2 To check this, evalute: f1(2), f2(2) Independently of how the function is defined, it can be used as an input for another function 7

MatLab-ish capabilities numpy multidimensional data arrays matplotlib 2d and 3d plotting scipy library of scientific algorithms builds on top of the low-level NumPy framework for multidimensional arrays provides a large number of higher-level scientific algorithms sparse matrices among other features will be skipped in this course 8

ARRAYs with numpy To use module numpy, you need to import the module functions, using for example: from numpy import * Now, to create new vector and matrix arrays, we can use the numpy.array function: M = array( [ [1, 2], [3, 4], [5, 6] ] ) # each interior [..] defines a row print (M) Try M[0,0], M[1,2], M[:,0], M[1,:], M[-1,:] etc, with various ranges Operations with arrays: try M*2+3 and M**2 and sin(m) ---all array operations are applied elementwise! Assignments B = M do not copy the actual array! B = M # now B is referring to the same list data as M B[0,0]=100 # so changing B affects M (and visa versa) # print M and B to check this! Replace B = M by B=M[:] or B=copy(M) to create an actual copy of M (check!) For linear systems, use numpy.linalg.solve(a,b) (similar to A\b in MatLab) 9

You may start with 2d plotting with matplotlib from matplotlib.pyplot import * from numpy import * # unless you already imported numpi Then we can plot almost like in MatLab x = linspace(0,1,20) # linspace is from module numpy plot(x, x**2) # graph of one function xlabel("text for x-axis") # plot, xlabel, ylabel are from matplotlib.pyplot ylabel("text for y-axis") plot(x, x**2, '-o', x, cos(x), '--*') # graph of two functions Alternative (and more preferable version of the above) import matplotlib.pyplot as plt from numpy import * x = linspace(0,1,20) # unless you already imported numpi # linspace is from module numpy plt.plot(x, x**2, '-o', x, cos(x), '--*') plt.xlabel("x-axis") plt.ylabel("x^2 and cos(x)") To add curves to the existing figure (from a script!) plt.plot(x, 1-x**3, '-o') 10

Further Reading Exercises As a crash course, you may look through the slides: http://www.seas.upenn.edu/~cis391/lectures/python-tutorial.pdf (Pp. 17-32, ignore tuples; pp. 50-61, 72-74, 76-79, 86-88) Main REF (may be of use in future as well): Python for Computational Science and Engineering (A beginner's guide), by Hans Fangohr http://www.southampton.ac.uk/~fangohr/training/python/pdfs/python-for- Computational-Science-and-Engineering.pdf (Sections 2.1, 2.3-2.5, 2.6.2, 2.7-2.9, 2.11 and beyond) NumPy for MatLab users notes: https://docs.scipy.org/doc/numpy-dev/user/numpy-for-matlab-users.html Also you may look into an open-source Springer book Programming for Computations Python by Svein Linge, Hans Petter Langtangen, http://link.springer.com/book/10.1007%2f978-3-319-32428-9 ---this is a Python version of the MatLab book you already know (Sections 1+2 and beyond) 11

Python Basics Worksheet Programming for Computations Python: Ex. 2.2, 2.4, 2.6 Rewrite your code(s) of Ass.#3, part II, into Python and reproduce the results obtained (excluding the use of the sophisticated MatLab build-in function quad). Rewrite your codes of Ass.#4 into Python and reproduce the results obtained (optional) 12