Download The Random Grid Search: A simple way to find optmal cuts

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
An Introduction to
Python
Harrison B. Prosper
Florida State University
1
An Introduction to python, Harrison B. Prosper, 1997
Acknowledgements





I learnt a great deal by browsing the python web site and
its linked pages.
 http://www.python.org
 http://www.python.org/doc/tut/tut.html
Guido van Rossum (python author)
David Beazley (SWIG author, University of Utah)
Mark Lutz’s excellent book.
 Programming Python, O’Reilly Associates Inc.
Frederick Lundh’s Tkinter documentation is very helpful.
 http://www.pythonware.com/library.htm
2
An Introduction to python, Harrison B. Prosper, 1997
Outline


Part I
 What is python?
 Getting started
 Namespaces
 Sequences
 Functions
 Classes
 Odds and ends
Part 2
 Graphical User Interfaces
 A Simple GIF/JPEG/BMP Browser
3
An Introduction to python, Harrison B. Prosper, 1997
What is python?


Python is a scripting language, created by Guido van
Rossum ([email protected]), that is:
 interpreted
 object-oriented
 dynamically typed
 simple
 powerful and
 free
Python website:
 http://www.python.org
4
An Introduction to python, Harrison B. Prosper, 1997
Getting started


The python interpreter has been ported to all the
popular platforms, including Windows 95/NT.
Running python interactively:
 setup python
 python
 >>> print ‘Thou lump of foul deformity’
 Thou lump of foul deformity
 >>> x = 2; y = 5
 >>> z = x*y
 >>> z
 10
5
An Introduction to python, Harrison B. Prosper, 1997
Example 1 (from, import, for, in, if, else)
from string import atoi, split # Add atoi, split to global namespace.
import os
# Add os to global namespace.
f = os.popen(‘cd; ls -l’)
# Pipe command output to file.
s = f.read()
# Read into a single string.
l = split(s,’\n’)
# Split into a list of strings.
n = len(l)
# Get length of list.
for j in xrange(n):
# Iterate over a range object.
a = split(l[j])
# Split into a list of strings.
if (len(a) > 4):
# If length of list > 4 convert
size = atoi(a[4])
# string value into an integer.
print size, l[j]
else:
LOOK MA, NO BRACES BECAUSE
print l[j]
PYTHON USES INDENTATION!
6
An Introduction to python, Harrison B. Prosper, 1997
Namespaces
__builtins__
len, xrange, dir, open,...
Global (import)
os
popen, system,
listdir, environ,
path,...
__builtins__
f, s, atoi, split
l, n, j, a, size
7
An Introduction to python, Harrison B. Prosper, 1997
Looking at namespaces
l = dir()
for j in xrange(len(l)):
print l[j]
Create a list of the names
in the global namespace
l = dir(__builtins__)
Create a list of the names
in the namespace of the module
__builtins__
l = dir(os)
Do likewise for the module os
8
An Introduction to python, Harrison B. Prosper, 1997
Example 2 (map, lambda)
l = dir(__builtins__)
# List names in module __builtins__
o= map(lambda x: x+`\n’,l) # For every element x of list apply the
# one-line function f(x) = x+`\n’ and
# return the result in the list o.
f = open(‘builtins.txt’,’w’) # Open a file object f for output.
f.writelines(o)
# Write out list of newline-terminated
# strings.
f.close()
# Close file object.
from string import strip
g = open(‘builtins.txt’,’r’)
t = g.readlines()
t = map(strip,t)
# Add strip to global namespace.
# Open file for input.
# Read entire file into list t.
# Strip off whitespace (here newline).
9
An Introduction to python, Harrison B. Prosper, 1997
Example 3 (filter)
from string import strip, find
# Import strip and find
t = open(‘builtins.txt’).readlines() # Read entire file into list t.
t = map(strip,t)
# Strip off whitespace.
o = filter(lambda x: find(x,`Error’) > 0, t) # For every x in list t
# apply the one-line function
# f(x) = find(x,’Error’) > 0
# If f(x) is true (i.e., f(x)=1)
# copy x to output list o.
# Example of python error code: AttributeError
10
An Introduction to python, Harrison B. Prosper, 1997
Sequence types



Immutable types (can’t be changed)
 Strings
aString = ‘Go boil your head’
 Tuples
aTuple = (‘Bozo’,42,3.14,aString)
Mutable types (can be changed)
 Lists
aList = [aString, aTuple,1997]
 Dictionaries
aMap = {‘string’:aString,(1,2):aList}
General operators on sequence s
 len(s), min(s), max(s), s[i], s[i:j] (= s[i]..s[j-1])
 x [not] in s
1 if item x [not] in s, else 0
 s+t
concatenate sequences s and t
 n*s
n copies, concatenated
11
An Introduction to python, Harrison B. Prosper, 1997
Tuples (immutable; can’t be changed)
0
1
2
3
4 5
>>> IamAtuple = (‘The’,’time’,3.141,’has’,42,’come’)
>>> IamAtuple[0]; IamAtuple[5]
‘The’
‘come’
>>> IamAtupleSlice = IamAtuple[3:6]
>>> IamAtupleSlice
(‘has’,42,’come’)
>>> IamAtupleCopy = IamAtuple[:]
>>> len(IamAtupleCopy)
6
12
An Introduction to python, Harrison B. Prosper, 1997
Lists (mutable; can be changed)
>>> IamAlist = [‘The’,’time’,3.141,’has’,42,’come’]
>>> IamAlist[0]
‘The’
>>> IamAlist[2] = (1,2,3); IamAlist
[‘The’,’time’,(1,2,3),’has’,42,’come’]
>>> IamAlist.sort()
[42,’The’,’come’,’has’,’time’,(1,2,3)]
>>> IamAlist.append(1997); IamAlist
[42,’The’,’come’,’has’,’time’,(1,2,3),1997]
13
An Introduction to python, Harrison B. Prosper, 1997
Dictionaries, or mappings (mutable)
>>> IamAmap = {}
# An empty dictionary
>>> IamAmapAlso = {1:’one’,(2,’boo’):’two’}
>>> IamAmap[‘language’] = (‘python’,1997)
>>> IamAmap[‘comment’] = ‘Superb!’
>>> IamAmap[‘cost’] = 0
>>> IamAmap[‘map’] = IamAmapAlso
>>> IamAmap.keys()
[‘cost’,’language’,’comment’,’map’]
# Bind keys to
# values.
# Get list of keys
>>> IamAmap.values()
# Get list of values
[0,(‘python’,1997),’Superb!’,{1:’one’,(2,’boo’):’two’}]
14
An Introduction to python, Harrison B. Prosper, 1997
Functions (def, None, return)
def goofy(a, b=‘yahoo’,*t, **k):
r1 = r2 = None
if ( len(t) > 0 ):
r1 = t[0]
if ( k.has_key(‘title’) ):
r2 = k[‘title’]
return (r1,r2)
# a is a required arg.
# b is a req. arg. with a default.
# *t, **k are optional args.
# None is a python object.
# *t is a tuple of args.
# **k is a set of keyword args.
# Check if key ‘title’ exists.
# Get value for given key.
# Return as a tuple.
>>> a, b = goofy(1,’sucks’,1,2, title=‘2001’,author=’Clarke’)
>>> print a, b
1 2001
15
An Introduction to python, Harrison B. Prosper, 1997
Classes
class FourVector:
# Name of class
def __init__(self, px=0,py=0,pz=0,E=0): # Constructor
self.ok = 1
# Creation ok
if E >= 0:
self.px, self.py, self.pz, self.e = px,py,pz,E
else:
self.ok = 0
# Creation failed
def __del__(self):
pass
>>> p = FourVector(12,-14,13,80)
An Introduction to python, Harrison B. Prosper, 1997
# Destructor
16
Classes, __str__ method
def __str__(self):
# Used by print and str(*)
s=
‘px %d\n’ % self.px # Uses the C printf
s = s + ‘py %d\n’ % self.py # format strings
s = s + ‘pz %d\n’ % self.pz
s = s = ‘E %d’ % self.e
return s
# Return string
# Note: We could also have written the above
#
as s = ‘%s %d\n’ % (‘px’,self.px), etc..
>>> print p
px 12
py -14
pz 13
E 80
An Introduction to python, Harrison B. Prosper, 1997
17
Classes, __add__, __sub__ methods
def __add__(self, v):
# Implement +
u = FourVector()
u.px = self.px + v.px
u.py = self.py + v.py
u.pz = self.pz + v.pz
u.e = self.e + v.e
return u
def __sub__(self, v):
:
:
# Implement -
18
An Introduction to python, Harrison B. Prosper, 1997
Classes, __mul__ method
def __mul__(self, v):
# Implement *
u = self.px*v.px+self.py*v.py+self.pz*v.pz
return self.e*v.e - u
>>> p = FourVector(1,2,3,10)
>>> q = FourVector(0,0,-1,20)
>>> pq = p*q
19
An Introduction to python, Harrison B. Prosper, 1997
Classes, Inheritance
class Particle(FourVector):
def __init__(self, label=‘e-’,px=0,py=0,pz=0,E=0):
# Call FourVector constructor to initialize px, etc.
FourVector.__init__(self, px,py,pz,E)
if self.ok:
# Check for success
self.label = label # Create another attribute
else: return# NB: Constructor return value ignored
def __del__(self):
if self.ok: print ‘Goodbye cruel world!’
else: print ‘I never got properly made anyway!’
20
An Introduction to python, Harrison B. Prosper, 1997
Classes, dynamically created attributes
from math import *
# Import all math functions
class Particle(FourVector):
:
:
def __getattr__(self, attribute): # Method to get values
# of dynamic attributes
if attribute == ‘mass’:
x = sqrt(self.e**2
-(self.px**2+self.py**2+self.pz**2))
return x
else:
# Okay; have a tantrum!
raise AttributeError, attribute
21
An Introduction to python, Harrison B. Prosper, 1997
Setting dynamically created attributes
class Particle(FourVector):
:
:
def __setattr__(self, attribute, value): # Method to set
# values of dynamic attributes
if attribute == ‘version’:
#NB: Do not write self.version = value here because this
#
would create a statically defined attribute! Set using the
#
object’s dictionary attribute:
self.__dict__[attribute] = value
else:
raise AttributeError, attribute
22
An Introduction to python, Harrison B. Prosper, 1997
A simple Internet server
from socket import *
from os import *
def server(PORT=50000): # Choose any non-privileged port
HOST = ‘’
# Local host
s = socket(AF_INET, SOCK_STREAM) # Create socket
s.bind(HOST, PORT)
# Bind socket to local host
s.listen(1)
# Allow only a single queued connection
client, address = s.accept()
# Wait for a connection
while 1:
# Wait “forever”
data = client.recv(4096)
# Get up to 4k bytes
if data == ‘quit’: break
else: print data
print “Goodbye from server!”
23
An Introduction to python, Harrison B. Prosper, 1997
A simple internet client
from socket import *
from os import *
def client(HOST=gethostname(),
# Default is local server
PORT=50000):
# Server port
s = socket(AF_INET, SOCK_STREAM) # Create socket
s.connect(HOST, PORT)
# Connect to server
while 1:
data = raw_input(‘Client> ’)# Get keyboard input
if data == ‘quit’: break
else: s.send(data)
# Send to server
s.send(‘quit’)
s.shutdown(2)
# Terminate all pending I/O
s.close()
# Close connection
print “Goodbye from client!”
24
An Introduction to python, Harrison B. Prosper, 1997
And finally, a client/server session
Server:
>>> from server import server
>>> server()
Go Boil your head!
Goodbye from server!
>>>
Client:
>>> from client import client
>>> client(‘d02ka.fnal.gov’)
Client>> Go boil your head!
Client>> quit
Goodbye from client!
>>>
An Introduction to python, Harrison B. Prosper, 1997
25
Odds and ends
Changing the python search path on-the-fly
import sys
sys.path.append(‘~harry/python/tutorial’)
sys.path.append(‘~harry/python/examples’)
Spawning commands to the operating system
import os
os.system(‘cd; ls -la’)
Debugging python scripts (type h for help)
from pdb import run
run(‘p = FourVector(1,1,2,90)’)
26
An Introduction to python, Harrison B. Prosper, 1997
Odds and ends (eval, exec, try, except)
Evaluating strings and updating current namespace
p = eval(‘FourVector(1,1,2,90)’)
Executing statements and updating current namespace)
exec(‘p = FourVector(1,1,2,90)’)
Handling errors
>>> s = open(‘FourVector.txt’,’r’).read()
>>> try:
# Try following statements and
...
p = eval(s) # if an error (i.e., an exception) occurs
. . . except:
# execute these statements.
...
exec(s)
# Note: Can also catch specified
>>> print p
# exceptions with the except keyword.
27
An Introduction to python, Harrison B. Prosper, 1997
Graphical User Interfaces



Tk is a widely supported toolkit for building portable
Graphical User Interfaces (GUIs). Its purpose is to hide the
unbelievable horrors of X windows.
Tkinter is a python module that provides an object-oriented
wrapping of Tk. It is available with the standard distribution of
python on many different platforms, including Windows
NT/95.
 http://www.pythonware.com/downloads.htm
 download self-extracting archive (py15-980706.exe)
 double-click on file to install python
To load all of the Tkinter attributes and methods into the
global namespace do:
 from Tkinter import *
28
An Introduction to python, Harrison B. Prosper, 1997
Event-driven programs

A GUI application is an example of an event-driven
program. An application goes through two steps:
 Construct GUI layout and bind screen objects
(widgets) to functions (callbacks).
 Enter a wait loop and bind events to callbacks
Construct GUI layout
WaitForEvent
Decide which callbacks to call
Dispatch callbacks
29
An Introduction to python, Harrison B. Prosper, 1997
Anatomy of a simple GUI
Root
Entry
Scale
Frames are containers for Tk objects (widgets).
Gui layouts are created by using nested Frames into
which useful widgets are placed. The root widget provides
(platform-dependent) window management.
30
An Introduction to python, Harrison B. Prosper, 1997
GUI Example 1
from Tkinter import * # Add all names to global namespace
import os
class Gui(Frame): # Gui is an extended Frame
def __init__(self, parent=None): # Default parent is root
Frame.__init__(self, parent) # Initialize Frame
self.b = Button(self, text=‘List Directory’,
command=self.list,
fg=‘red’, bg=‘green’)
self.pack(side=TOP); self.b.pack(side=LEFT)
def list(self):
os.system(‘cd; ls -la’)
if __name__ == ‘__main__’: Gui.mainloop() # Run as script
31
An Introduction to python, Harrison B. Prosper, 1997
GUI Example 2
from Tkinter import *
#Add all names to global namespace
from ScrolledText import ScrolledText
class Gui(Frame):
def __init__(self, parent=None):
Frame.__init__(self, parent)
self.pack()
self.config(relief=GROOVE, bd=2)
self.master.title(‘Example 2’)
self.text = ScrolledText(self)
self.text.pack()
if __name__ == ‘__main__’: Gui.mainloop()
32
An Introduction to python, Harrison B. Prosper, 1997
A couple of other widgets
o is object, p is parent widget, v is value
o = Scale(p, orient=HORIZONTAL, from_= 0, to =1000)
v = o.get(), o.set(v)
o = Entry(p), x = StringVar(); o[‘textvariable’] = x
o.bind(‘<Key-Return>‘, callback); x.get(), x.set()
33
An Introduction to python, Harrison B. Prosper, 1997
Python Imaging Library



We shall use this extension (by Frederick Lundh) to
build a simple graphics browser (gbrowser.py)
Import modules
class Gui(Frame):
 Constructor
• Get a list of filenames
• Loop over filenames
– Create and store full graphics image in a dictionary
– Create a button, attach a thumbnail image to it and
bind button to the display method

Display
• Paste full image to a label in a separate window
34
An Introduction to python, Harrison B. Prosper, 1997
A Simple Graphics Browser
from Tkinter import *
import Image
# Load a couple of PIL
import ImageTk
# classes
import os, sys
from string import find, rfind, lower
FILETYPES = (‘.gif’,’.jpg’,’.bmp’)
BIG = (768,576); SMALL=(80,60)
# Handle different path delimiters between
# windows and UNIX
if sys.platform == 'win32':
DELIM = "\\" # ‘\’ is the python escape character
else:
DELIM = "/" # To make UNIX happy :-(
35
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part 1
class Gui(Frame): # Gui is an extended frame
def __init__(self, parent=None, path=('.',)):
# Try to get a listing of given path ( (‘.’,) -- syntax for 1-tuple)
try:
files = []
# Create an empty list
for d in path: # path is a tuple of directories
l = os.listdir(d)
f = map(lambda x,y=d:y+delim+x,l)
files = files + f # Concatenate lists
except:
# Come here if listing fails
print "**Errror**, bad directory: ", d
sys.exit(1)
36
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part 2
# Get list of graphics files.
# Extract the last 4 characters of each string x in the list files.
# Make lower case, then test if the 4-character string matches a
# string in the FILETYPES tuple.
gifs = filter(lambda x: lower(x[len(x)-4]) in FILETYPES, files)
# Initialize inherited frame
Frame.__init__(self, parent, relief=SUNKEN, bd=2)
self.pack()
self.image = {} # Dictionary for images
row = col = 0 # For use with grid method
# Next we shall loop over the GIF files and try to read each one
37
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part 3
for giffile in gifs:
# Loop over graphics files
# Extract file name
gif = giffile[rfind(giffile,DELIM)+1:] # Search from right
# Exclude duplicate images
if not self.image.has_key(gif):
print "Reading ", gif, # Note comma to suppress NL
# Read GIF file and create image
try:
ig = Image.open(giffile)
ig.thumbnail(BIG)
self.image[gif] = ImageTk.PhotoImage(ig)
38
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part 4
# Paste button b with a thumbnail version of image.
# Note the use of lambda to pass context information to
# the single callback self.display
:
:
ig.thumbnail(SMALL)
# 80 x 60 pixels
b = Button(self, image=ImageTk.PhotoImage(ig),
command=lambda s=self, x=gif: s.display(x))
:
:
39
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part 5
# Pack using grid method, which requires that we give the row
# and column numbers of a matrix. Make buttons expand in all
# directions (N+S+E+W) to fill available space.
b.grid(row=row, column=col, sticky=N+S+E+W)
col = col + 1
# Update column number
if col == 5:
row = row + 1
# Update row number
col = 0
print ""
# Complete print statement
except:
# associated with Try (see part 3)
print "*** FAILED *** "
# Here if we fail to read file
40
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, part6
# Method to display full image
def display(self, gif):
top = Toplevel() # Create a separate window
top.title(gif)
top.iconname(gif)
Label(top,image=self.image[gif]).pack()
# Note: Because we do not plan to do anything with the
# label other than display it, we don’t bother to create a
# reference (a name) for the label.
41
An Introduction to python, Harrison B. Prosper, 1997
Graphics Browser, running it
# Code added at the end to execute file if it is run as a script,
# that is: python gbrowser.py [dir1] [dir2] ...
if __name__ == '__main__':
if not sys.argv[1:]: # Check for NO arguments and, if
path = '.'
# none, default to working directory
else:
path = sys.argv[1:] # Get arguments
root = Tk()
# Create Tk root widget
root.title('Graphics Browser')
Gui(root, path).mainloop() # Enter event loop
42
An Introduction to python, Harrison B. Prosper, 1997
The End
Python in action!
43
An Introduction to python, Harrison B. Prosper, 1997