Download (some) Python for Crystallographers

Document related concepts
no text concepts found
Transcript
(some) Python for
Crystallographers
Fermin Otálora
[email protected]
Laboratorio de Estudios Cristalográficos
IACT, CSIC / U. Granada
CSDC / MCC M3-T09
Grenoble, Junio 2009
This presentation contains materials from a
presentation by Eric Jones and Travis
Oliphant. Original materials can be found at
http://nanohub.org/resources/99.
FORmula
TRANslation
A Ž B Ž C Ž C++
Monty Python
Flying Circus
What is Python
ten years ago. . .
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
In 1999, Van Rossum submitted a funding proposal
to DARPA called “Computer Programming for
Everybody”, in which he further defined his goals
for Python:
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
• an easy and intuitive language just as powerful
Assignment
as major competitors
Control Structures
Functions
• open source, so anyone can contribute to its
Modules
development
Classes
Misc
• code that is as understandable as plain English
ndarrays
• suitability for everyday tasks, allowing for short
development times
Guido van Rossum
What’s Python?
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• A interpreted, very high level, general purpose, portable languaje
with a focus on productivity via modularity, uniformity, simplicity,
pragmatism
•
•
•
•
clean, spare syntax
simple, regular, powerful semantics
object oriented, multiparadigm
easy modularity
• A rich standard library of modules
• A strong Open Source community
• Python Software Foundation
• many users (individuals and companies)
• lots of 3rd-party tools/add-ons
• sub-communities for special interests
• Several good implementations (CPython, PyPy, IronPython, Jython)
• Excellet for scripting, rapid prototyping and glueing external
libraries and applications
• Less lines to read makes code faster to write, less error prone and
easier to understand, maintain and debug
• A reduced number of keywords with only one meaning consistently
used in different contexts
• Syntax enforces structure and documentation
What’s Python?
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• A interpreted, very high level, general purpose, portable languaje
with a focus on productivity via modularity, uniformity, simplicity,
pragmatism
•
•
•
•
clean, spare syntax
simple, regular, powerful semantics
object oriented, multiparadigm
easy modularity
• A rich standard library of modules
• A strong Open Source community
• Python Software Foundation
• many users (individuals and companies)
• lots of 3rd-party tools/add-ons
• sub-communities for special interests
• Several good implementations (CPython, PyPy, IronPython, Jython)
• Excellet for scripting, rapid prototyping and glueing external
libraries and applications
• “Batteries Included”
• Second largest after Java
What’s Python?
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• A interpreted, very high level, general purpose, portable languaje
with a focus on productivity via modularity, uniformity, simplicity,
pragmatism
•
•
•
•
clean, spare syntax
simple, regular, powerful semantics
object oriented, multiparadigm
easy modularity
• A rich standard library of modules
• A strong Open Source community
• Python Software Foundation
• many users (individuals and companies)
• lots of 3rd-party tools/add-ons
• sub-communities for special interests
• Several good implementations (CPython, PyPy, IronPython, Jython)
• Excellet for scripting, rapid prototyping and glueing external
libraries and applications
What’s Python?
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• A interpreted, very high level, general purpose, portable languaje
with a focus on productivity via modularity, uniformity, simplicity,
pragmatism
•
•
•
•
clean, spare syntax
simple, regular, powerful semantics
object oriented, multiparadigm
easy modularity
• A rich standard library of modules
• A strong Open Source community
• Python Software Foundation
• many users (individuals and companies)
• lots of 3rd-party tools/add-ons
• sub-communities for special interests
• Several good implementations (CPython, PyPy, IronPython, Jython)
• Excellet for scripting, rapid prototyping and glueing external
libraries and applications
CPython http://www.python.org/
PyPy http://codespeak.net/pypy/dist/pypy/doc/
Jython http://www.jython.org/
IronPython
http://www.codeplex.com/Wiki/View.aspx?ProjectName=IronPy
What’s Python?
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• A interpreted, very high level, general purpose, portable languaje
with a focus on productivity via modularity, uniformity, simplicity,
pragmatism
•
•
•
•
clean, spare syntax
simple, regular, powerful semantics
object oriented, multiparadigm
easy modularity
• A rich standard library of modules
• A strong Open Source community
• Python Software Foundation
• many users (individuals and companies)
• lots of 3rd-party tools/add-ons
• sub-communities for special interests
• Several good implementations (CPython, PyPy, IronPython, Jython)
• Excellet for scripting, rapid prototyping and glueing external
libraries and applications
Bubblesort (Pseudocode)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
function bubblesort (A : l i s t [ 1 . . n ] )
var i n t i , j ;
f o r i from n downto 1
f o r j from 1 to i −1
i f (A[ j ] > A[ j +1])
swap (A[ j ] , A[ j +1])
Bubblesort (C)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
void bubbleSort ( i n t ∗ array , i n t length )
{
i n t i , j , temp ;
int test ;
f o r ( i = length − 1; i > 0; i −−)
{
t e s t =0;
f o r ( j = 0; j < i ; j ++)
{
i f ( array [ j ] > array [ j +1])
{
temp = array [ j ] ;
array [ j ] = array [ j +1];
array [ j +1] = temp ;
t e s t =1;
}
}
i f ( t e s t ==0) break ;
}
}
Bubblesort (Java)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
public s t a t i c void bubbleSort ( i n t [ ] data )
{
f o r ( i n t k = 0; k < data . length − 1; k++)
{
boolean isSorted = true ;
f o r ( i n t i = 1; i < data . length − k ; i ++)
{
i f ( data [ i ] < data [ i − 1 ] )
{
i n t tempVariable = data [ i ] ;
data [ i ] = data [ i − 1 ] ;
data [ i − 1] = tempVariable ;
isSorted = f a l s e ;
}
}
i f ( isSorted )
break ;
}
}
Bubblesort (Fortran 1/2)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
SUBROUTINE sort ( array_x , array_y , datasize )
REAL array_x ( ∗ )
REAL array_y ( ∗ )
INTEGER datasize
REAL x_temp
REAL y_temp
LOGICAL inorder
inorder = . f a l s e .
do 90 while ( inorder . eq . . f a l s e . )
inorder = . true .
do 91 i =1, datasize
i f ( array_x ( i ) . eq . array_x ( i +1) ) then
i f ( array_y ( i ) . l t . array_y ( i +1) ) then
x_temp = array_x ( i )
y_temp = array_y ( i )
array_x ( i ) = array_x ( i +1)
array_y ( i ) = array_y ( i +1)
array_x ( i +1) = x_temp
array_y ( i +1) = y_temp
inorder = . f a l s e .
endif
endif
Bubblesort (Fortran 2/2)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
91
90
i f ( array_x ( i ) . l t . array_x ( i +1) ) then
x_temp = array_x ( i )
y_temp = array_y ( i )
array_x ( i ) = array_x ( i +1)
array_y ( i ) = array_y ( i +1)
array_x ( i +1) = x_temp
array_y ( i +1) = y_temp
inorder = . f a l s e .
endif
continue
continue
END SUBROUTINE sort
Bubblesort (Pseudocode, Python)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
function bubblesort (A : l i s t [ 1 . . n ] )
var i n t i , j ;
f o r i from n downto 1
f o r j from 1 to i −1
i f (A[ j ] > A[ j +1])
swap (A[ j ] , A[ j +1])
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
def bubblesort ( l ) :
f o r passesLeft in range ( len ( l )−1, 0 , −1):
f o r index in range ( passesLeft ) :
i f l [ index ] < l [ index + 1 ] :
l [ index ] , l [ index + 1] = l [ index + 1 ] , l [ index ]
return l
Comparisons (Eficiency)
Python in
Crystallography
FORTRAN
C
C++
Java
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Perl
Python is interpreted
Execution in Python is slow
Comparisons (Eficiency)
Python in
Crystallography
FORTRAN
C
C++
Java
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Perl
Python is interpreted
Execution in Python is slow, but mumber
crunching is done in C or FORTRAN anyway
via extension libraries
Comparisons (Eficiency)
Python in
Crystallography
FORTRAN
C
C++
Java
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Perl
Python is “Programmer-Oriented”
Execution in Python is slow, but mumber
crunching is done in C or FORTRAN anyway
via extension libraries and development,
debuging and maintenance are very eficient and easy in Python.
Comparison (Programming paradigm)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• FORTRAN
• Application, scientific and engineering
• Imperative, procedural, object-oriented
• Medium/High (Compiler “extensions”)
• Medium
• Small
• C / C++
• System / Application, System
• Imperative / Imperative, object-oriented, generic
• Very high / Very high
• Medium / High
• Medium / Large
• Python
• Application, Scripting, Prototyping, Web
• Imperative, object-oriented, functional, aspect-oriented, reflective
• Almost complete
• Small
• Very Large
• Java
• Application, Web
• Imperative, procedural, reflective, functional, object-oriented, generic
• Complete
• Medium
• Huge
• Perl
• Application, Text processing, Scripting, Web
• Imperative, object-oriented, functional, reflective
• Almost complete
• High
• Large
Comparison (Portability)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• FORTRAN
• Application, scientific and engineering
• Imperative, procedural, object-oriented
• Medium/High (Compiler “extensions”)
• Medium
• Small
• C / C++
• System / Application, System
• Imperative / Imperative, object-oriented, generic
• Very high / Very high
• Medium / High
• Medium / Large
• Python
• Application, Scripting, Prototyping, Web
• Imperative, object-oriented, functional, aspect-oriented, reflective
• Almost complete
• Small
• Very Large
• Java
• Application, Web
• Imperative, procedural, reflective, functional, object-oriented, generic
• Complete
• Medium
• Huge
• Perl
• Application, Text processing, Scripting, Web
• Imperative, object-oriented, functional, reflective
• Almost complete
• High
• Large
Comparison (Complexity)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• FORTRAN
• Application, scientific and engineering
• Imperative, procedural, object-oriented
• Medium/High (Compiler “extensions”)
• Medium
• Small
• C / C++
• System / Application, System
• Imperative / Imperative, object-oriented, generic
• Very high / Very high
• Medium / High
• Medium / Large
• Python
• Application, Scripting, Prototyping, Web
• Imperative, object-oriented, functional, aspect-oriented, reflective
• Almost complete
• Small
• Very Large
• Java
• Application, Web
• Imperative, procedural, reflective, functional, object-oriented, generic
• Complete
• Medium
• Huge
• Perl
• Application, Text processing, Scripting, Web
• Imperative, object-oriented, functional, reflective
• Almost complete
• High
• Large
Comparison (Standard Library)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• FORTRAN
• Application, scientific and engineering
• Imperative, procedural, object-oriented
• Medium/High (Compiler “extensions”)
• Medium
• Small
• C / C++
• System / Application, System
• Imperative / Imperative, object-oriented, generic
• Very high / Very high
• Medium / High
• Medium / Large
• Python
• Application, Scripting, Prototyping, Web
• Imperative, object-oriented, functional, aspect-oriented, reflective
• Almost complete
• Small
• Very Large
• Java
• Application, Web
• Imperative, procedural, reflective, functional, object-oriented, generic
• Complete
• Medium
• Huge
• Perl
• Application, Text processing, Scripting, Web
• Imperative, object-oriented, functional, reflective
• Almost complete
• High
• Large
Comparison (Field of application)
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• FORTRAN
• Application, scientific and engineering
• Imperative, procedural, object-oriented
• Medium/High (Compiler “extensions”)
• Medium
• Small
• C / C++
• System / Application, System
• Imperative / Imperative, object-oriented, generic
• Very high / Very high
• Medium / High
• Medium / Large
• Python
• Application, Scripting, Prototyping, Web
• Imperative, object-oriented, functional, aspect-oriented, reflective
• Almost complete
• Small
• Very Large
• Java
• Application, Web
• Imperative, procedural, reflective, functional, object-oriented, generic
• Complete
• Medium
• Huge
• Perl
• Application, Text processing, Scripting, Web
• Imperative, object-oriented, functional, reflective
• Almost complete
• High
• Large
Using Python
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• Interactive interpreter
• Souce files (autocompilation)
• Interpreter + Editor
• Especialized editor or IDEs
Using Python
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• Interactive interpreter
• Souce files (autocompilation)
• Interpreter + Editor
• Especialized editor or IDEs
Using Python
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• Interactive interpreter
• Souce files (autocompilation)
• Interpreter + Editor
• Especialized editor or IDEs
Using Python
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• Interactive interpreter
• Souce files (autocompilation)
• Interpreter + Editor
• Especialized editor or IDEs
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
The Language
Interactive Calculator
Python in
Crystallography
enthought ®
Interactive Calculator
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# adding two values
>>> 1 + 1
2
# setting a variable
>>> a = 1
>>> a
1
# checking a variables type
>>> type(a)
<type 'int'>
# an arbitrarily long integer
>>> a = 1203405503201
>>> a
1203405503201L
>>> type(a)
<type 'long'>
# real numbers
>>> b = 1.2 + 3.1
>>> b
4.2999999999999998
>>> type(b)
<type 'float'>
# complex numbers
>>> c = 2+1.5j
>>> c
(2+1.5j)
The four numeric types in Python on
32-bit architectures are:
integer (4 byte)
long integer (any precision)
float (8 byte like C’s double)
complex (16 byte)
The Numeric module, which we will
see later, supports a larger number
of numeric types.
Strings
Python in
Crystallography
enthought ®
Strings
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
CREATING STRINGS
STRING LENGTH
# using double quotes
>>> s = “hello world”
>>> print s
hello world
# single quotes also work
>>> s = ‘hello world’
>>> print s
hello world
>>> s = “12345”
>>> len(s)
5
STRING OPERATIONS
# concatenating two strings
>>> “hello “ + “world”
‘hello world’
# repeating a string
>>> “hello “ * 3
‘hello hello hello ’
FORMAT STRINGS
# the % operator allows you
# to supply values to a
# format string. The format
# string follows
# C conventions.
>>> s = “some numbers:”
>>> x = 1.34
>>> y = 2
>>> s = “%s %f, %d” % (s,x,y)
>>> print s
some numbers: 1.34, 2
The string module
Python in
Crystallography
enthought ®
The string module
F. Otálora
Introduction
>>> import string
>>> s = “hello world”
What is Python
Comparisons
The Language
Numbers
Strings
Lists
# split space delimited words
>>> wrd_lst = string.split(s)
>>> print wrd_lst
[‘hello’, ‘world’]
Dictionaries
Tuples
Assignment
Control Structures
Functions
# python2.2 and higher
>>> s.split()
[‘hello’, ‘world’]
Modules
Classes
Misc
ndarrays
# join words back together
>>> string.join(wrd_lst)
hello world
# python2.2 and higher
>>> ‘ ‘.join(wrd_lst)
hello world
# replacing text in a string
>>> string.replace(s,’world’ \
... ,’Mars’)
‘hello Mars’
# python2.2 and higher
>>> s.replace(’world’ ,’Mars’)
‘hello Mars’
# strip whitespace from string
>>> s = “\t
hello
\n”
>>> string.strip(s)
‘hello’
# python2.2 and higher
>>> s.strip()
‘hello’
Multiline strings
Python in
Crystallography
Multi-line Strings
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
# triple quotes are used
# for mutli-line strings
>>> a = ”””hello
... world”””
>>> print a
hello
world
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# multi-line strings using
# “\” to indicate
continuation
>>> a = “hello ” \
...
“world”
>>> print a
hello world
# including the new line
>>> a = “hello\n” \
...
“world”
>>> print a
hello
world
enthought ®
List Objects
Python in
Crystallography
enthought ®
List objects
F. Otálora
Introduction
What is Python
Comparisons
The Language
LIST CREATION WITH BRACKETS
range( start, stop, step)
>>> l = [10,11,12,13,14]
>>> print l
[10, 11, 12, 13, 14]
# the range method is helpful
# for creating a sequence
>>> range(5)
[0, 1, 2, 3, 4]
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
CONCATENATING LIST
# simply use the + operator
>>> [10, 11] + [12,13]
[10, 11, 12, 13]
Functions
Modules
Classes
Misc
ndarrays
REPEATING ELEMENTS IN LISTS
# the multiply operator
# does the trick.
>>> [10, 11] * 3
[10, 11, 10, 11, 10, 11]
>>> range(2,7)
[2, 3, 4, 5, 6]
>>> range(2,7,2)
[2, 4, 6]
Indexing
Python in
Crystallography
enthought ®
Indexing
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
RETREIVING AN ELEMENT
NEGATIVE INDICES
# list
# indices: 0 1 2 3 4
>>> l = [10,11,12,13,14]
>>> l[0]
10
#
#
#
#
#
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
SETTING AN ELEMENT
>>> l[1] = 21
>>> print l
[10, 21, 12, 13, 14]
Classes
Misc
negative indices count
backward from the end of
the list.
indices: -5 -4 -3 -2 -1
>>>
l = [10,11,12,13,14]
>>> l[-1]
14
>>> l[-2]
13
OUT OF BOUNDS
ndarrays
>>> l[10]
Traceback (innermost last):
File "<interactive input>",line 1,in ?
IndexError: list index out of range
The first element in an
array has index=0 as
in C. Take note Fortran
programmers!
More on lists
Python in
Crystallography
enthought ®
More on list objects
F. Otálora
Introduction
What is Python
LIST CONTAINING MULTIPLE
TYPES
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
# list containing integer,
# string, and another list.
>>> l = [10,’eleven’,[12,13]]
>>> l[1]
‘eleven’
>>> l[2]
[12, 13]
Functions
Modules
Classes
Misc
ndarrays
# use multiple indices to
# retrieve elements from
# nested lists.
>>> l[2][0]
12
LENGTH OF A LIST
>>> len(l)
3
DELETING OBJECT FROM LIST
# use the del keyword
>>> del l[2]
>>> l
[10,’eleven’]
DOES THE LIST CONTAIN x ?
# use in or not in
>>> l = [10,11,12,13,14]
>>> 13 in l
1
>>> 13 not in l
0
Slicing
Python in
Crystallography
enthought ®
Slicing
F. Otálora
var[lower:upper]
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Slices extract a portion of a sequence by specifying a lower and upper
bound. The extracted elements start at lower and go up to, but do not
include, the upper element. Mathematically the range is [lower,upper).
SLICING LISTS
OMITTING INDICES
# indices: 0 1 2 3 4
>>> l = [10,11,12,13,14]
# [10,11,12,13,14]
>>> l[1:3]
[11, 12]
# omitted boundaries are
# assumed to be the beginning
# (or end) of the list.
# negative indices work also
>>> l[1:-2]
[11, 12]
>>> l[-4:3]
[11, 12]
# grab first three elements
>>> l[:3]
[10,11,12]
# grab last two elements
>>> l[-2:]
[13,14]
A few methods for list objects
Python in
Crystallography
enthought ®
A few methods for list objects
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
some_list.append( x )
some_list.remove( x )
Add the element x to the end
of the list, some_list.
Delete the first occurrence of x
from the list.
some_list.count( x )
some_list.reverse( )
Count the number of times x
occurs in the list.
Reverse the order of elements in
the list.
some_list.index( x )
some_list.sort( cmp )
Return the index of the first
occurrence of x in the list.
By default, sort the elements in
ascending order. If a compare
function is given, use it to sort
the list.
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
List methods in action
Python in
Crystallography
List methods in action
F. Otálora
Introduction
>>> l = [10,21,23,11,24]
What is Python
Comparisons
The Language
Numbers
Strings
Lists
# add an element to the list
>>> l.append(11)
>>> print l
[10,21,23,11,24,11]
# remove the first 11
>>> l.remove(11)
>>> print l
[10,21,23,24,11]
# how many 11s are there?
>>> l.count(11)
2
# sort the list
>>> l.sort()
>>> print l
[10,11,21,23,24]
# where does 11 first occur?
>>> l.index(11)
3
# reverse the list
>>> l.reverse()
>>> print l
[24,23,21,11,10]
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
enthought ®
Mutable vs. Inmutable
Python in
Crystallography
enthought ®
Mutable vs. Immutable
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
MUTABLE OBJECTS
IMMUTABLE OBJECTS
# Mutable objects, such as
# lists, can be changed
# in-place.
# Immutable objects, such as
# strings, cannot be changed
# in-place.
# insert new values into list
>>> l = [10,11,12,13,14]
>>> l[1:3] = [5,6]
>>> print l
[10, 5, 6, 13, 14]
# try inserting values into
# a string
>>> s = ‘abcde’
>>> s[1:3] = ‘xy’
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
The cStringIO module treats
strings like a file buffer
and allows insertions. It’s
useful when working with
large strings or when speed
is paramount.
Traceback (innermost last):
File "<interactive input>",line 1,in ?
TypeError: object doesn't support
slice assignment
# here’s how to do it
>>> s = s[:1] + ‘xy’ + s[3:]
>>> print s
'axyde'
Dictionaries
Python in
Crystallography
enthought ®
Dictionaries
F. Otálora
Introduction
What is Python
Comparisons
The Language
Dictionaries store key/value pairs. Indexing a dictionary by a key
returns the value associated with it.
DICTIONARY EXAMPLE
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# create an empty dictionary using curly brackets
>>> record = {}
>>> record[‘first’] = ‘Jmes’
>>> record[‘last’] = ‘Maxwell’
>>> record[‘born’] = 1831
>>> print record
{'first': 'Jmes', 'born': 1831, 'last': 'Maxwell'}
# create another dictionary with initial entries
>>> new_record = {‘first’: ‘James’, ‘middle’:‘Clerk’}
# now update the first dictionary with values from the new one
>>> record.update(new_record)
>>> print record
{'first': 'James', 'middle': 'Clerk', 'last':'Maxwell', 'born':
1831}
A few dictionary methods
enthought ®
Python in
Crystallography
F. Otálora
A few dictionary methods
Introduction
What is Python
some_dict.clear( )
some_dict.keys( )
Remove all key/value pairs from
the dictionary, some_dict.
Return a list of all the keys in the
dictionary.
some_dict.copy( )
some_dict.values( )
Create a copy of the dictionary
Return a list of all the values in
the dictionary.
some_dict.has_key( x )
some_dict.items( )
Test whether the dictionary
contains the key x.
Return a list of all the key/value
pairs in the dictionary.
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Dictionary methods in action
Python in
Crystallography
enthought ®
Dictionary methods in action
F. Otálora
Introduction
What is Python
>>> d = {‘cows’: 1,’dogs’:5,
...
‘cats’: 3}
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
# create a copy.
>>> dd = d.copy()
>>> print dd
{'dogs':5,'cats':3,'cows': 1}
# get a list of all values
>>> d.values()
[3, 5, 1]
# test for chickens.
>>> d.has_key(‘chickens’)
0
# return the key/value pairs
>>> d.items()
[('cats', 3), ('dogs', 5),
('cows', 1)]
# get a list of all keys
>>> d.keys()
[‘cats’,’dogs’,’cows’]
# clear the dictionary
>>> d.clear()
>>> print d
{}
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Tuples
Python in
Crystallography
enthought ®
Tuples
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Tuples are a sequence of objects just like lists. Unlike lists, tuples are
immutable objects. While there are some functions
and statements that require tuples, they are rare. A good rule of
thumb is to use lists whenever you need a generic sequence.
TUPLE EXAMPLE
# tuples are built from a comma separated list enclosed by ( )
>>> t = (1,’two’)
>>> print t
(1,‘two’)
>>> t[0]
1
# assignments to tuples fail
>>> t[0] = 2
Traceback (innermost last):
File "<interactive input>", line 1, in ?
TypeError: object doesn't support item assignment
Assignment
Python in
Crystallography
enthought ®
Assignment
F. Otálora
Introduction
What is Python
Assignment creates object references.
Comparisons
The Language
Numbers
Strings
>>> x = [0, 1, 2]
x
# y = x cause x and y to point
# at the same list
>>> y = x
y
0 1 2
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# changes to y also change x
>>> y[1] = 6
>>> print x
[0, 6, 2]
x
# re-assigning y to a new list
# decouples the two lists
>>> y = [3, 4]
x
0 6 2
y
3 4
y
0 6 2
Multiple Assignment
Python in
Crystallography
enthought ®
Multiple assignments
F. Otálora
Introduction
What is Python
Comparisons
The Language
# creating a tuple without ()
>>> d = 1,2,3
>>> d
(1, 2, 3)
Numbers
# multiple assignments from a
# tuple
>>> a,b,c = d
>>> print b
2
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# multiple assignments
>>> a,b,c = 1,2,3
>>> print b
2
# also works for lists
>>> a,b,c = [1,2,3]
>>> print b
2
If statements
Python in
Crystallography
enthought ®
If statements
F. Otálora
Introduction
What is Python
Comparisons
The Language
if/elif/else provide conditional execution of
code blocks.
Numbers
Strings
Lists
Dictionaries
Tuples
IF STATEMENT FORMAT
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
if <condition>:
<statements>
elif <condition>:
<statements>
else:
<statements>
IF EXAMPLE
# a
>>>
>>>
...
...
...
...
...
...
1
simple if statement
x = 10
if x > 0:
print 1
elif x == 0:
print 0
else:
print –1
< hit return >
Test values
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Test Values
• True means any non-zero number
or non-empty object
• False means not true: zero, empty object, or
None
Assignment
Control Structures
EMPTY OBJECTS
Functions
Modules
Classes
Misc
ndarrays
# empty objects evaluate false
>>> x = []
>>> if x:
...
print 1
... else:
...
print 0
... < hit return >
0
enthought ®
For Loops
Python in
Crystallography
F. Otálora
Introduction
enthought ®
For loops
For loops iterate over a sequence of objects.
What is Python
Comparisons
The Language
Numbers
for <loop_var> in <sequence>:
<statements>
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
TYPICAL SCENARIO
LOOPING OVER A LIST
>>> for i in range(5):
...
print i,
... < hit return >
0 1 2 3 4
>>> l=[‘dogs’,’cats’,’bears’]
>>> accum = ‘’
>>> for item in l:
...
accum = accum + item
...
accum = accum + ‘ ‘
... < hit return >
>>> print accum
dogs cats bears
Misc
ndarrays
LOOPING OVER A STRING
>>> for i in ‘abcde’:
...
print i,
... < hit return >
a b c d e
While loops
Python in
Crystallography
enthought ®
While loops
F. Otálora
Introduction
While loops iterate until a condition is met.
What is Python
Comparisons
while <condition>:
<statements>
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
WHILE LOOP
BREAKING OUT OF A LOOP
# the condition tested is
# whether lst is empty.
>>> lst = range(3)
>>> while lst:
...
print lst
...
lst = lst[1:]
... < hit return >
[0, 1, 2]
[1, 2]
[2]
# breaking from an infinite
# loop.
>>> i = 0
>>> while 1:
...
if i < 3:
...
print i,
...
else:
...
break
...
i = i + 1
... < hit return >
0 1 2
Anatomy of a function
Python in
Crystallography
enthought ®
Anatomy of a function
F. Otálora
Introduction
What is Python
Comparisons
The keyword def
indicates the start
of a function.
Function arguments are listed
separated by commas. They are passed
by assignment. More on this later.
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
Indentation is
used to indicate
the contents of
the function. It
is not optional,
but a part of the
syntax.
def add(arg0, arg1):
a = arg0 + arg1
return a
A colon ( : ) terminates
the function definition.
An optional return statement specifies
the value returned from the function. If
return is omitted, the function returns the
special value None.
Parameters can be positional or keyworded and can be optional with
default values.
Our new function in action
Python in
Crystallography
enthought ®
Our new function in action
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
# We’ll create our function
# on the fly in the
# interpreter.
>>> def add(x,y):
...
a = x + y
...
return a
# how about strings?
>>> x = ‘foo’
>>> y = ‘bar’
>>> add(x,y)
‘foobar’
# test it out with numbers
>>> x = 2
>>> y = 3
>>> add(x,y)
5
# functions can be assigned
# to variables
>>> func = add
>>> func(x,y)
‘foobar’
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# how about numbers and strings?
>>> add(‘abc',1)
Traceback (innermost last):
File "<interactive input>", line 1, in ?
File "<interactive input>", line 2, in add
TypeError: cannot add type "int" to string
Modules
Python in
Crystallography
enthought ®
Modules
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
EX1.PY
FROM SHELL
# ex1.py
[ej@bull ej]$ python ex1.py
6, 3.1416
PI = 3.1416
FROM INTERPRETER
def sum(lst):
tot = lst[0]
for value in lst[1:]:
tot = tot + value
return tot
# load and execute the module
>>> import ex1
6, 3.1416
# get/set a module variable.
>>> ex1.PI
3.1415999999999999
>>> ex1.PI = 3.14159
>>> ex1.PI
3.1415899999999999
# call a module variable.
>>> t = [2,3,4]
>>> ex1.sum(t)
9
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
l = [0,1,2,3]
print sum(l), PI
Modules
Python in
Crystallography
enthought ®
Modules cont.
F. Otálora
Introduction
INTERPRETER
EDITED EX1.PY
# load and execute the module
>>> import ex1
6, 3.1416
< edit file >
# import module again
>>> import ex1
# nothing happens!!!
# ex1.py version 2
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# use reload to force a
# previously imported library
# to be reloaded.
>>> reload(ex1)
10, 3.14159
PI = 3.14159
def sum(lst):
tot = 0
for value in lst:
tot = tot + value
return tot
l = [0,1,2,3,4]
print sum(l), PI
Modules
Python in
Crystallography
enthought ®
Modules cont. 2
F. Otálora
Introduction
Modules can be executable scripts or libraries or both.
What is Python
Comparisons
The Language
Numbers
EX2.PY
EX2.PY CONTINUED
“ An example module “
def add(x,y):
” Add two values.”
a = x + y
return a
Strings
Lists
Dictionaries
PI = 3.1416
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
def sum(lst):
””” Sum the values in a
list.
”””
tot = 0
for value in lst:
tot = tot + value
return tot
def test():
l = [0,1,2,3]
assert( sum(l) == 6)
print ‘test passed’
# this code runs only if this
# module is the main program
if __name__ == ‘__main__’:
test()
Setting up PYTHONPATH
Python in
Crystallography
enthought ®
Setting up PYTHONPATH
F. Otálora
Introduction
What is Python
PYTHONPATH is an environment variable (or set of registry entries on Windows) that
lists the directories Python searches for modules.
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
WINDOWS
The easiest way to set the search paths is
using PythonWin’s Tools->Edit Python Path
menu item. Restart PythonWin after
changing to insure changes take affect.
UNIX -- .cshrc
!! note: the following should !!
!! all be on one line
!!
setenv PYTHONPATH
$PYTHONPATH:$HOME/aces
Control Structures
Functions
Modules
Classes
Misc
ndarrays
UNIX -- .bashrc
PYTHONPATH=$PYTHONPATH:$HOME/aces
export PYTHONPATH
Classes
Python in
Crystallography
enthought ®
Classes
F. Otálora
SIMPLE PARTICLE CLASS
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> class particle:
...
# Constructor method
...
def __init__(self,mass, velocity):
...
# assign attribute values of new object
...
self.mass = mass
...
self.velocity = velocity
...
# method for calculating object momentum
...
def momentum(self):
...
return self.mass * self.velocity
...
# a “magic” method defines object’s string representation
...
def __repr__(self):
...
msg = "(m:%2.1f, v:%2.1f)" % (self.mass,self.velocity)
...
return msg
EXAMPLE
>>> a = particle(3.2,4.1)
>>> a
(m:3.2, v:4.1)
>>> a.momentum()
13.119999999999999
Reading files
Python in
Crystallography
enthought ®
Reading files
F. Otálora
Introduction
FILE INPUT EXAMPLE
PRINTING THE RESULTS
>>> results = []
>>> f = open(‘c:\\rcs.txt’,’r’)
>>> for i in results: print i
[100.0, -20.30…, -31.20…]
[200.0, -22.70…, -33.60…]
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
# read lines and discard header
>>> lines = f.readlines()[1:]
>>> f.close()
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> for l in lines:
...
# split line into fields
...
fields = line.split()
...
# convert text to numbers
...
freq = float(fields[0])
...
vv = float(fields[1])
...
hh = float(fields[2])
...
# group & append to results
...
all = [freq,vv,hh]
...
results.append(all)
... < hit return >
EXAMPLE FILE: RCS.TXT
#freq (MHz) vv (dB) hh (dB)
100
-20.3
-31.2
200
-22.7
-33.6
More compact version
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
More compact version
ITERATING ON A FILE AND LIST COMPREHENSIONS
>>> results = []
>>> f = open(‘c:\\rcs.txt’,’r’)
>>> f.readline()
‘#freq (MHz) vv (dB) hh (dB)\n'
>>> for l in f:
...
all = [float(val) for val in l.split()]
...
results.append(all)
... < hit return >
>>> for i in results:
...
print i
... < hit return >
ndarrays
EXAMPLE FILE: RCS.TXT
#freq (MHz)
100
200
vv (dB)
-20.3
-22.7
hh (dB)
-31.2
-33.6
enthought ®
One line
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Same thing, one line
OBFUSCATED PYTHON CONTEST…
>>> print [[float(val) for val in l.split()] for
...
l in open("c:\\temp\\rcs.txt","r")
...
if l[0] !="#"]
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
EXAMPLE FILE: RCS.TXT
#freq (MHz)
100
200
vv (dB)
-20.3
-22.7
hh (dB)
-31.2
-33.6
enthought ®
Data persistency
enthought ®
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Pickling and Shelves
Pickling is Python’s term for persistence. Pickling can write
arbitrarily complex objects to a file. The object can be
resurrected from the file at a later time for use in a program.
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> import shelve
>>> f = shelve.open(‘c:/temp/pickle’,’w’)
>>> import ex_material
>>> epoxy_gls = ex_material.constant_material(4.8,1)
>>> f[‘epoxy_glass’] = epoxy_gls
>>> f.close()
< kill interpreter and restart! >
>>> import shelve
>>> f = shelve.open(‘c:/temp/pickle’,’r’)
>>> epoxy_glass = f[‘epoxy_glass’]
>>> epoxy_glass.eps(100e6)
4.249e-11
Exception handling
Python in
Crystallography
enthought ®
Exception Handling
F. Otálora
ERROR ON LOG OF ZERO
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
import math
>>> math.log10(10.)
1.
>>> math.log10(0.)
Traceback (innermost last):
OverflowError: math range error
CATCHING ERROR AND CONTINUING
>>> a = 0.
>>> try:
...
r = math.log10(a)
... except OverflowError:
...
print ‘Warning: overflow occurred. Value set to 0.’
...
# set value to 0. and continue
...
r = 0.
Warning: overflow occurred. Value set to 0.
>>> print r
0.0
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
ndarray (numpy)
NumPy
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
• NumPy’s main object is the homogeneous multidimensional array
(ndarray). This is a table of elements (usually numbers), all of the
same type, indexed by a tuple of positive integers.
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> from numpy import ∗
# create an array out of a l i s t
>>> a = array ( [ 10, 20, 30, 40 ] )
>>> a
array ( [ 1 0 , 20, 30, 40])
# create an array of 4 integers , from 0 to 3
>>> b = arange ( 4 )
>>> b
array ( [ 0 , 1 , 2 , 3 ] )
# create an array of 3 evenly spaced samples from −pi to pi
>>> c = linspace (−pi , pi , 3 )
>>> c
array ([−3.14159265, 0.
, 3.14159265])
Python in
Crystallography
Multidimensional arrays. Placeholder
constructors
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
# A sequence of sequences produces a bidimensional array
>>> b = array ( [ ( 1 . 5 , 2 , 3 ) , ( 4 , 5 , 6 ) ] )
>>> b
array ( [ [ 1.5 , 2. , 3. ] ,
[ 4. , 5. , 6. ] ] )
# The shape can be s p e c i f i e d upon creation
>>> zeros ( ( 3 , 4 ) )
array ( [ [ 0 . , 0 . , 0 . , 0 . ] ,
[0. , 0. , 0. , 0.] ,
[0. , 0. , 0. , 0 . ] ] )
# the type can also be s p e c i f i e d
>>> 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 )
# L e f t values unspecified
>>> empty ( ( 2 , 3 ) )
array ( [ [ 3.73603959e−262,
6.02658058e−154,
6.55490914e−260],
[ 5.30498948e−313,
3.14673309e−307,
1.00000000e +000]])
ndarray objects
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
>>> a = arange ( 1 0 ) . reshape ( 2 , 5 )
>>> a
array ( [ [ 0 , 1 , 2 , 3 , 4 ] ,
[5 , 6, 7, 8, 9 ] ] )
>>> type ( a )
<type ’numpy. ndarray ’>
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
a.ndim Ž 2 the number of axes (dimensions) of the array
a.shape Ž (2,5) the dimensions of the array (a tuple of integers indicating
the size of the array in each dimension)
a.size Ž 10 the total number of elements of the array (product of the
elements of shape)
a.dtype Ž int32 an object describing the type of the elements in the array
(bool_, character, int_, int8, int16, int32, int64, float_,
float8, float16, float32, float64, complex_, complex64,
object_)
a.itemsize Ž 4 the size in bytes of each element of the array (equivalent
to ndarray.dtype.itemsize)
a.data the buffer containing the actual elements of the array
(seldomly used)
Ranges
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> arange ( 10, 30, 5 )
array ( [ 1 0 , 15, 20, 25])
# i t accepts f l o a t arguments
>>> arange ( 0 , 2 , 0.3 )
array ( [ 0. , 0.3 , 0.6 , 0.9 , 1.2 , 1.5 , 1 . 8 ] )
# 9 numbers from 0 to 2
>>> linspace ( 0 , 2 , 9 )
array ( [ 0. , 0.25 , 0.5 , 0.75 , 1. , 1.25 , 1.5 ,
# useful to evaluate function at l o t s of points
>>> x = linspace ( 0 , 2∗ pi , 100 )
1.75 ,
2.
])
Element-wise operations
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> a = array ( [20 ,30 ,40 ,50] )
>>> b = arange ( 4 )
>>> c = a−b
>>> c
array ( [ 2 0 , 29, 38, 47])
>>> b∗∗2
array ( [ 0 , 1 , 4 , 9 ] )
>>> 10∗ sin ( a )
array ( [ 9.12945251, −9.88031624, 7.4511316 , −2.62374854])
>>> a<35
array ( [ True , True , False , False ] , dtype=bool )
Common pitfall: Multiplication is also elementwise. Matrix product can be
performed using the dot function or creating matrix objects.
In-place operations
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• It is possible to perform some operations inplace so that no new array
is created.
>>> a = ones ( ( 2 , 3 ) , dtype= i n t )
>>> b = random . random ( ( 2 , 3 ) )
>>> a ∗= 3
>>> a
array ( [ [ 3 , 3 , 3 ] ,
[3 , 3, 3 ] ] )
>>> b += a
>>> b
array ( [ [ 3.69092703, 3.8324276 ,
[ 3.18679111, 3.3039349 ,
# b i s converted to integer type
>>> a += b
>>> a
array ( [ [ 6 , 6 , 6 ] ,
[6 , 6, 6 ] ] )
3.0114541 ] ,
3.37600289]])
Mixed-type operations
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• When operating with arrays of different types, the type of the resulting
array corresponds to the more general or precise one.
>>> a = ones ( 3 , dtype=int32 )
>>> b = linspace ( 0 , pi , 3 )
>>> b . dtype .name
’ float64 ’
>>> c = a+b
>>> c
array ( [ 1.
, 2.57079633, 4.14159265])
>>> c . dtype .name
’ float64 ’
>>> d = exp ( c ∗1 j )
>>> d
array ( [ 0.54030231+0.84147098j , −0.84147098+0.54030231j ,
−0.54030231−0.84147098 j ] )
>>> d . dtype .name
’complex128 ’
Unary operator methods
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> a = random . random ( ( 2 , 3 ) )
>>> a
array ( [ [ 0.6903007 , 0.39168346, 0.16524769],
[ 0.48819875, 0.77188505, 0.94792155]])
>>> a .sum ( )
3.4552372100521485
>>> a . min ( )
0.16524768654743593
>>> a .max ( )
0.9479215542670073
# specifying the axis parameter applies an operation along the s p e c i f i e d
>>> b = arange ( 1 2 ) . reshape ( 3 , 4 )
>>> b
array ( [ [ 0 , 1 , 2 , 3 ] ,
[ 4, 5, 6, 7] ,
[ 8 , 9 , 10, 1 1 ] ] )
>>>
# sum of each column
>>> b .sum( axis =0)
array ( [ 1 2 , 15, 18, 21])
>>>
# min of each row
>>> b . min ( axis =1)
array ( [ 0 , 4 , 8 ] )
>>>
# cumulative sum along the rows
>>> b .cumsum( axis =1)
array ( [ [ 0 , 1 , 3 , 6 ] ,
[ 4 , 9 , 15, 22] ,
[ 8 , 17, 27, 3 8 ] ] )
Indexing, Slicing, Iterating
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
• One dimensional arrays can be indexed, sliced and iterated over pretty
much like lists and other Python sequences.
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> 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 [ : 6 : 2 ] = −1000
# modify elements in a
>>> f o r i in a :
...
print i ∗∗(1/3.) ,
...
nan 1.0 nan 3.0 nan 5.0 6.0 7.0 8.0 9.0
Indexing, Slicing, Iterating
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
• Multidimensional arrays can be with one index per axis. These indices
are given in a tuple separated by comas
>>> def f ( x , y ) :
...
return 10∗x+y
...
>>> b = fromfunction ( f , ( 5 , 4 ) , dtype= i n t )
>>> b
array ( [ [ 0 , 1 , 2 , 3 ] ,
[10 , 11, 12, 13] ,
[20 , 21, 22, 23] ,
[30 , 31, 32, 33] ,
[40 , 41, 42, 4 3 ] ] )
>>> b[ 2 , 3 ]
23
>>> b [ : , 1 ]
# the second column of b
array ( [ 1 , 11, 21, 31, 41])
>>> b [ 1 : 3 , : ]
# the second and t h i r d row of b
array ( [ [ 1 0 , 11, 12, 13] ,
[20 , 21, 22, 2 3 ] ] )
• When fewer indices are provided than the number of axes, the missing
indices are supposed to be complete slices
>>> b[ −1]
array ( [ 4 0 , 41, 42, 43])
# the l a s t row . Equivalent to b[ −1 ,:]
Universal functions
Python in
Crystallography
F. Otálora
Introduction
What is Python
Comparisons
The Language
Numbers
Strings
Lists
Dictionaries
Tuples
Assignment
Control Structures
Functions
Modules
Classes
Misc
ndarrays
>>> p r i n t x
[0 1 2 3 4]
>>> p r i n t cos ( x )
[ 1. 0.54030231 −0.41614684 −0.9899925 −0.65364362]
>>> p r i n t arccos ( cos ( x ) )
[ 0. 1. 2. 3. 2.28318531]
# not a bug , but wraparound : 2∗ pi%4 i s 2.28318531
add
divide_safe
arccosh
arctanh
tanh
sqrt
ceil
conjugate
greater
less
logical_not
bitwise_not
subtract
remainder
arcsin
cos
log10
absolute
fmod
maximum
equal
less_equal
logical_and
bitwise_and
multiply
power
arcsinh
cosh
sin
fabs
exp
minimum
not_equal
logical_or
bitwise_or
divide
arccos
arctan
tan
sinh
floor
log
greater_equal
logical_xor
bitwise_xor
Related documents