Python for Science Shane Grigsby. What is python? Why python? Interpreted, object oriented language Free and open source Focus is on readability Fast.

Slides:



Advertisements
Similar presentations
Guy Griffiths. General purpose interpreted programming language Widely used by scientists and programmers of all stripes Supported by many 3 rd -party.
Advertisements

Introduction to R Brody Sandel. Topics Approaching your analysis Basic structure of R Basic programming Plotting Spatial data.
R for Macroecology Aarhus University, Spring 2011.
Matlab Intro Simple introduction to some basic Matlab syntax. Declaration of a variable [ ] Matrices or vectors Some special (useful) syntax. Control statements.
Python tutorial for scientific computing Steve Byrnes 16 March 2012.
Python: Your new best friend print “Adam Avison”.
Python Basics: Statements Expressions Loops Strings Functions.
Introduction to Matlab Workshop Matthew Johnson, Economics October 17, /13/20151.
XP 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties Tutorial 10.
By. What advantages has it? The Reasons for Choosing Python  Python is free  It is object-oriented  It is interpreted  It is operating-system independent.
Python plotting for lab folk Only the stuff you need to know to make publishable figures of your data. For all else: ask Sourish.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
EPSII 59:006 Spring Topics Using TextPad If Statements Relational Operators Nested If Statements Else and Elseif Clauses Logical Functions For Loops.
732A44 Programming in R.  Self-studies of the course book  2 Lectures (1 in the beginning, 1 in the end)  Labs (computer). Compulsory submission of.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Introduction to Programming Workshop 1 PHYS1101 Discovery Skills in Physics Dr. Nigel Dipper Room 125d
HTML, MATLAB & Delphi Aleksey Charapko 11/3/13. HTML Markup Language  Created at CERN for scientific purposes  No executable code  Controls the “look”
Introduction to PythonIntroduction to Python SPARCS `08 서우석 (pipoket) `09 Summer SP ARCS Seminar`09 Summer SP ARCS Seminar.
How to think through your program [ principles of good program design ] Rachel Denison MATLAB for Cognitive Neuroscience ICN, 13 December 2007.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room A, Chris Hill, Room ,
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
MATLAB Tutorial EE 327 Signals and Systems 1. What is MATLAB? MATLAB – Matrix Laboratory The premier number-crunching software Extremely useful for signal.
Computer Science 101 Introduction to Programming.
What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation tools. Others include Maple Mathematica MathCad.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Introduction to Information Security Python. Python motivation Python is to a Hacker what Matlab is to an engineer Lots of built-in modules Lots of 3.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
You Need an Interpreter!. Closing the GAP Thus far, we’ve been struggling to speak to computers in “their” language, maybe its time we spoke to them in.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Lecture 20: Choosing the Right Tool for the Job. What is MATLAB? MATLAB is one of a number of commercially available, sophisticated mathematical computation.
A (VERY) SHORT INTRODUCTION TO MATLAB J.A. MARR George Mason University School of Physics, Astronomy and Computational Sciences.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Practical Kinetics Exercise 0: Getting Started Objectives: 1.Install Python and IPython Notebook 2.print “Hello World!”
Python & NetworkX Youn-Hee Han
Scion Macros How to make macros for Scion The Fast and Easy Guide.
Xi Wang Yang Zhang. 1. Easy to learn 2. Clean and readable codes 3. A lot of useful packages, especially for web scraping and text mining 4. Growing popularity.
Python 1 SIGCS 1 Intro to Python March 7, 2012 Presented by Pamela A Moore & Zenia C Bahorski 1.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
PROGRAMMING USING PYTHON LANGUAGE ASSIGNMENT 1. INSTALLATION OF RASPBERRY NOOB First prepare the SD card provided in the kit by loading an Operating System.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Python – It's great By J J M Kilner. Introduction to Python.
PH2150 Scientific Computing Skills
Module 5 Working with Data
CSC 458– Predictive Analytics I, Fall 2017, Intro. To Python
Pamela Moore & Zenia Bahorski
Intro To Pete Alonzi University of Virginia Library
IPYTHON AND MATPLOTLIB Python for computational science
DATA MINING Python.
Python in astronomy + Monte-Carlo techniques
Functions CIS 40 – Introduction to Programming in Python
Scripts & Functions Scripts and functions are contained in .m-files
Prepared by Kimberly Sayre and Jinbo Bi
PH2150 Scientific Computing Skills
Python Primer 2: Functions and Control Flow
Matlab review Matlab is a numerical analysis system
MATLAB Tutorial Dr. David W. Graham.
CSC 458– Predictive Analytics I, Fall 2018, Intro. To Python
Communication and Coding Theory Lab(CS491)
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
CIS 136 Building Mobile Apps
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Python for Science Shane Grigsby

What is python? Why python? Interpreted, object oriented language Free and open source Focus is on readability Fast to write and debug code Large community – Lots of documentation – Lots of packages… General purpose language

The python scientific stack:

Python: Fast to write, slow to run? Depends on how you use it– if something is slow there is probably a faster way to do it! Are you using a numeric library? Are you slicing through arrays, or looping lists? Is your code vectorized? Numpy calls fortran code to do array operations Many other libraries call C for operations… …or have functions written in both C and python e.g., scipy.spatial.kdtree vs. scipy.spatial.cKDTree

How is python different from MATLAB? Indexing starts at 0 Space delimited Default behavior is element-by-element when dealing with arrays Functions use ()’s, indexes use []’s, tuples and dictionaries use {}’s You don’t have to use a ‘;’ on every command Object oriented See also:

Today’s tutorial Intro to the scientific stack Importing modules Intro to the development environments: – Spyder – iPython Indexing Defining functions Plotting and graphics Intro to data structures Basic looping (maybe…) Additional pandas – data import from clipboard – time series (on your own) Notebooks: SARP python tutorial Prism Data Regression loops Files: Leaf_Angles.csv good_12_leafangle.h5 monthly.nc # Optional *_spec.txt

Terminals and Prompts We’ll use python and python tools from three different ‘prompts’: – The system prompt (i.e., cmd) – From spyder – From the iPython Notebook Note that these will all run the same version of python, but with slightly different behaviors

Notebooks: SARP python tutorial Prism Data Regression loops Files: Leaf_Angles.csv good_12_leafangle.h5 monthly.nc # Optional

Imports Basic python is sparse… …but we can import! import tables import numpy as np from pylab import * From scipy import ones, array

Example time: Using the iPython notebook Notes: – ‘%’s are specific to the iPython NB’s; they won’t work in your terminal – We’ll use: %pylab inline This doesn’t work for 3D or interactive plots (yet) Use spyder or ipython (without the notebook) to access interactive graphics.

Imports Pull from the python install directory first – i.e., lib/python2.7/site-packages Pull from the current directory second Conflicting imports are replaced with the last import

Defining a function Multiline comment Keyword arguments – can use default values Definition syntax – return is optional Constants defined at the top of the script Top line brings in physical constants, so we don’t have to define them ourselves… from scipy.constants import * def Xwave(wavelength, temp, unit=1): X_wave = (h*c)/(k*(wavelength*unit)*temp) return X_wave def Lwave(wavelength, temp, unit=1): """Calculates L given wavelength and Temp To get M, multiply by pi Note that units are: W * m**-2 * sr**-1 * m**-1 I.e, units are given in meter of spectrum multiply by nm to get: W * m**-2 *sr**-1 nm**-1""” X_funct= Xwave(wavelength, temp, unit) L=(2*h*(c**2))/(((wavelength*unit)**5)*(exp(X_funct)-1)) return L ang = 1E-10 nm = 1E-9 um = 1E-6 Cm = 1E-2 hH = 1.0 kH = 1E3 mH = 1E6 gH = 1E9 tH = 1E12

Defining Functions Functions are defined using ‘def’, function name, ‘()’’s with parameters, and an ending ‘:’ The function body is demarcated using white space (as in for loops) Functions are called using the function name, ‘()’’s, and input parameters – Note that the input parameters don’t have to match the names that requested…

Looping in python for item in list: print item ‘item’ is a variable name; it is not declared in advance; it is arbitrary (i.e., could be ‘i’, ‘point’, or some other label). There could also be more them one variable here—see next slide… ‘for’ and ‘in’ are syntactically required; they bracket our variables. ‘list’ could be another data structure (dictionary, array, etc.), or could be a function in advanced use. Note: else and elseif are not required, but can be used Note: the white space is required—either a tab or four spaces Note: we don’t need to know how many items are in the data structure for i in range(len(list)): #  NO… print list[i] # executes, but is wrong

A more advanced loop: from liblas import file import scipy f = file.File('/Users/grigsbye/Downloads/Alameda_park_trees_pts.las',mode='r') treeData = scipy.ones((len(f),3)) for i, p in enumerate(f): treeData[i,0], treeData[i,1], treeData[i,2] = p.x,p.y,p.z First line imports a special module to read.las files Third line reads a.las file into a python object we can loop over Fourth line creates a scipy/numpy array to hold our data ‘Enumerate’ returns an index number for each point that we are looping over The last line assigns the x, y, and z values to our array, incrementing the index by one with each loop For a more complete guide to looping, see: