An Introduction to Python for Scientists Hands-On Tutorial Ahmed - - PowerPoint PPT Presentation

an introduction to python for scientists
SMART_READER_LITE
LIVE PREVIEW

An Introduction to Python for Scientists Hands-On Tutorial Ahmed - - PowerPoint PPT Presentation

An Introduction to Python for Scientists Hands-On Tutorial Ahmed Attia Statistical and Applied Mathematical Science Institute (SAMSI) 19 TW Alexander Dr, Durham, NC 27703 attia@ { samsi.info || vt.edu } Department of Mathematics, North Carolina


slide-1
SLIDE 1

An Introduction to Python for Scientists

Hands-On Tutorial Ahmed Attia

Statistical and Applied Mathematical Science Institute (SAMSI) 19 TW Alexander Dr, Durham, NC 27703 attia@ {samsi.info || vt.edu} Department of Mathematics, North Carolina State University, amttia2@ncsu.edu SAMSI SAMSI/NCSU Undergraduate Workshop; May 16, 2017

Hands-On Tutorial [1/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-2
SLIDE 2

Outline

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial [2/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-3
SLIDE 3

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Getting Started with Python [3/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-4
SLIDE 4

Getting Started with Python

◮ According to (Python.org ),

“Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together.”

◮ Why Python:

  • 1. https://www.continuum.io/why-python
  • 2. https://www.python.org/doc/essays/comparisons/
  • 3. http://www.bestprogramminglanguagefor.me/why-learn-python
  • 4. https://www.codefellows.org/blog/

5-reasons-why-python-is-powerful-enough-for-google/

Hands-On Tutorial Getting Started with Python [4/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-5
SLIDE 5

Learn Python: where should I start?

◮ Textbooks (for Scientists):

  • 1. Python for Scientists
  • 2. A Primer on Scientific Programming with Python
  • 3. Python Scripting for Computational Science

◮ Phone/Tablet Apps: Learn Python

  • Android:

https://play.google.com/store/apps/details?id=com.sololearn.python&hl=en

  • IPhone/IPad:

https://itunes.apple.com/us/app/learn-python-pro/id953972812?mt=8

◮ Python online Documentation: https://docs.python.org/2/ ◮ Practice, Practice, Practice,

Hands-On Tutorial Getting Started with Python [5/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-6
SLIDE 6

Basic Concepts

◮ Python script files have extension (.py), and compiled code files

(executables) have extension (.pyc).

◮ Python scripts can be written using any plain text editor. ◮ Avoid using SOLID Tabs.

Make sure Tabs are converted to SPACES (check your editor settings).

◮ INDENTATION is Extremely important. (For now, make sure all script line

start at the beginning of the line.)

◮ Python is CASE-SENSITIVE.

Hands-On Tutorial Getting Started with Python [6/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-7
SLIDE 7

Running Python code

◮ IPython : is an interactive command shell originally developed for Python,

that supports tab completion, and history amongst other features. This makes working with Python very similar to working with MATLAB .

◮ To run a Python script:

  • 1. from a terminal using the command: $ python [script-name.py]
  • 2. from IPython: $ run [script-name.py]

◮ Task:

  • 1. Slides & Code →

http://people.cs.vt.edu/~attia/Files/Classes/PythonIntro/SAMSI_NCSU_May_17/

  • 2. write a “Hello World” program in:

I a python script and run it, II in IPython shell,

Hands-On Tutorial Getting Started with Python [7/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-8
SLIDE 8

Terminal output; print

◮ Now, given the last task, you know that to print anything to the screen, we

will need to use the “print” function (or statement)

◮ Python’s ‘‘print’’ function can be used to print a “string representation”

  • f an ‘‘object’’ , e.g. string, number, etc.:

print(<object>)

  • r

print <object>

◮ The most obvious object to be printed to a screen is a String; one of the

main datatypes in Python is str . (Next)

◮ IF you like to complicate things, check:

print(str([object])), vs. print([object]. str ())

◮ Task: open the script lesson0 terminal output.py

Hands-On Tutorial Getting Started with Python [8/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-9
SLIDE 9

Data types, and variable assignment I

◮ Python supports a variety of data types, including:

  • 1. Strings: str
  • 2. Numerical types: int, long, float, complex
  • 3. Boolean: bool
  • 4. None/Null: None

◮ To check/view the data type of an object, you can use:

type([object name])

◮ Python, by default, allocates memory dynamically, and does not require

data type declaration; unlike Fortran, C, etc.

◮ Variables are created with dynamic binding; assignment is done using

assignment operator ‘‘=’’. variable-name = variable value

◮ Multiple assignment (with dynamic binding) is allowed , e.g. x = y = 3.

Hands-On Tutorial Getting Started with Python [9/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-10
SLIDE 10

Data types, and variable assignment II

◮ Variable naming rules:

  • 1. Variables names must start with a letter or an underscore,
  • 2. the remainder of the name may consist of letters, numbers, or underscores,
  • 3. variable name is case sensitive.
  • 4. variable name (identifier) length can be one character or more, and should be

meaningful.

◮ Examples:

Correct Incorrect x, i, 1x , x , radius, radius, radius, radi us, radi − us par 1, peremeter0 2 , etc. x$, s #, etc.

◮ Variable names starting with underscore will play vital role when we learn

how to import data from Python modules.

◮ Task: open the script lesson1 datatypes.py

Hands-On Tutorial Getting Started with Python [10/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-11
SLIDE 11

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Basic numerical, string, and boolean operations [11/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-12
SLIDE 12

Numerical arithmetics

◮ Python can apply one or more numerical arithmetic operations, to integers,

real numbers, or both.

  • 1. Addition, subtraction: [+, −]
  • 2. Multiplication, division, quotient, remainder(modulo): [∗, /, //, %]
  • 3. Unitary: [+, −]
  • 4. Exponentiation: [**]

Priority (precedence) is from “lowest” to “highest”. Override, and arrange

  • perations using round braces ( ).

◮ Question: What is the result of the following operation:

−3 ∗ ∗2 + 24//12%4/3 − 5 ∗ (2/3) ∗ (1/4.) Try by hand, then use IPython, and check your answer!

Hands-On Tutorial Basic numerical, string, and boolean operations [12/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-13
SLIDE 13

String operations

◮ You should know by now, that strings are defined, using single, double, or

triple-double quotes (“docstring”).

◮ Strings are saved into variables of “str” data type. Try the following:

x = ’this is a string’ print(type(x))

◮ Simple string operations:

◮ You can use addition ’+’ to add two strings, ◮ you can replicate a string using ’*’ (multiply a string by an INTEGER)

◮ A string can be formatted easily using escape characters, e.g. \n, \r, \t.

You can also use %[datatype] to insert something in a string,

◮ Task:

What is the result of the following expression? " Lesson%d \n is \t pointless%s " % (0, ’: ’*2)

Hands-On Tutorial Basic numerical, string, and boolean operations [13/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-14
SLIDE 14

Boolean (logical) operations

◮ Logical operations include:

>, < , ==, >=, <=, != in, not in, is, is not not, and, or

◮ You can also use double expressions such as: a < x < b. ◮ The priority of all these is less than arithmetics, and is ranked from highest to

lowest as follows:

  • 1. >, < , ==, >=, <=, !=, in, not in, is, is not
  • 2. not
  • 3. and
  • 4. or

◮ For full operator precedence, check:

https://docs.python.org/2/reference/expressions.html

Hands-On Tutorial Basic numerical, string, and boolean operations [14/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-15
SLIDE 15

Basic numerical, string, and boolean operations

Task:

  • 1. Open the script lesson2 numbers arithmetics.py
  • 2. Open the script lesson2 string operations.py
  • 3. Open the script lesson2 boolean expressions.py

Hands-On Tutorial Basic numerical, string, and boolean operations [15/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-16
SLIDE 16

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Iterables, and basic data structures [16/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-17
SLIDE 17

Iterables, and basic data structures

◮ An “iterable” is a Pythonic term, refers to any object capable of returning its

members one at a time.

◮ Basic examples include:

  • 1. lists,
  • 2. tuples,
  • 3. dictionaries,
  • 4. sets,
  • 5. strings.

◮ Task:

To learn how to create, access, or modify these objects:

  • 1. Open the script lesson3 lists.py
  • 2. Open the script lesson3 tuples.py
  • 3. Open the script lesson3 dictionaries.py

Hands-On Tutorial Iterables, and basic data structures [17/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-18
SLIDE 18

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Branching, and Looping [18/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-19
SLIDE 19

Branching, and Looping: if, for, while

◮ We will learn this lesson directly from the code examples. ◮ Task:

  • 1. Open the script lesson4 if statement.py
  • 2. Open the script lesson4 loops.py

Hands-On Tutorial Branching, and Looping [19/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-20
SLIDE 20

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Functions [20/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-21
SLIDE 21

Functions

◮ We will learn this lesson directly from the code examples. ◮ Task:

Open the script lesson5 functions.py

Hands-On Tutorial Functions [21/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-22
SLIDE 22

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Python Modules and Packages [22/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-23
SLIDE 23

Using Python Modules

◮ The components of a Python module, or a (.py) file can be imported into

the current working space, using the ’import’ statement. Examples (discussed further in class)

  • 1. import [module name]
  • 2. import module1, module2
  • 3. import module1 as alias
  • 4. from [module name] import

[variable, function, class, submodule] <as alias>

◮ Once a module is imported, its contents can be accessed using the [.]

  • perator

◮ The following statement imports everything(ish) from a module:

from [module name] import *

◮ Popular packages for scientific computing: math, numpy, scipy, matplotlib,

statsmodel, re, etc.

◮ Check this:

https://pythontips.com/2013/07/30/ 20-python-libraries-you-cant-live-without/

◮ Task: Open the script lesson6 modules.py

Hands-On Tutorial Python Modules and Packages [23/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-24
SLIDE 24

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Scientific Packages: Numpy & Scipy [24/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-25
SLIDE 25

Numpy

◮ According to (http://www.numpy.org/):

NumPy is the fundamental package for scientific computing with Python.

◮ Numpy contains, among other things:

  • 1. a powerful N-dimensional array object
  • 2. sophisticated “broadcasting” functions
  • 3. tools for integrating C/C++ and Fortran code
  • 4. useful linear algebra, Fourier transform, and random number capabilities

◮ Task: Open the script lesson7 numpy intro.py

Hands-On Tutorial Scientific Packages: Numpy & Scipy [25/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-26
SLIDE 26

Scipy: sparsity and more!

◮ Once you become familiar with Numpy, you will realize that some linear

algebra and statistical tools are not provided.

◮ Amongst others, Numpy does not provide sparse linear algebra functionalities.

This is the time to start learning/using Scipy

◮ According to (https://docs.scipy.org/doc/scipy/reference/),

SciPy (pronounced Sigh Pie) open-source software for mathematics, science, and engineering.

◮ Task: Open the script lesson8 scipy intro.py

Hands-On Tutorial Scientific Packages: Numpy & Scipy [26/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-27
SLIDE 27

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial File I/O [27/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-28
SLIDE 28

Files, input, and output operations

◮ You can open a file, to read ’r’, write ’w’, modify ’r+’, or append ’a’ .

file id = open([file name or path], mode=’r’) <Do stuff with the file> file id.method() <Do stuff with the file> file id.close()

◮ A better approach:

with open([file name or path]) as file id: Do stuff with the file> file id.method() <Do stuff with the file>

◮ Matlab (.mat) files:

import scipy.io as file io file contents = file io.loadmat([matlab mat file name or path])

◮ Task: Open the script lesson9 fileIO.py

Hands-On Tutorial File I/O [28/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-29
SLIDE 29

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial Plotting: matplotlib [29/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-30
SLIDE 30

Plotting: matplotlib

◮ According to (http://matplotlib.org/):

Matplotlib is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across

  • platforms. Matplotlib can be used in Python scripts, the Python and

IPython shell, the jupyter notebook, web application servers, and four graphical user interface toolkits.

◮ Task: Open the script lesson10 matplotlib.py

Hands-On Tutorial Plotting: matplotlib [30/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-31
SLIDE 31

Getting Started with Python Basic numerical, string, and boolean operations Iterables, and basic data structures Branching, and Looping Functions Python Modules and Packages Scientific Packages: Numpy & Scipy File I/O Plotting: matplotlib OOP: Python Classes

Hands-On Tutorial OOP: Python Classes [31/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)

slide-32
SLIDE 32

OOP: Python Classes

◮ Task:

Open the script lesson11 classes intro.py

Hands-On Tutorial OOP: Python Classes [32/32] May 16, 2017: An Introduction to Scientific Python, Ahmed Attia. (http://samsi.info)