Friday, April 29, 2011

Plotting p-norm unit circles with matplotlib

A unit circle is a circle with a radius of one, this concept is different in different vectorial norms. The following script will show the shape of the unit circle using differents p-norm.
import pylab
from numpy import array, linalg, random, sqrt, inf

def plotUnitCircle(p):
 """ plot some 2D vectors with p-norm < 1 """
 for i in range(5000):
  x = array([random.rand()*2-1,random.rand()*2-1])
  if linalg.norm(x,p) < 1:
   pylab.plot(x[0],x[1],'bo')
 pylab.axis([-1.5, 1.5, -1.5, 1.5])
 pylab.show()
And now we can plot the unit circles:
plotUnitCircle(1)
plotUnitCircle(2)
plotUnitCircle(5)
plotUnitCircle(inf)

Wednesday, April 27, 2011

How to find the minimum of a function using fmin from scipy

In this example we will see how to use the function fmin to minimize a function. The function fmin is contained in the optimize module of the scipy library. It uses the downhill simplex algorithm to find the minimum of an objective function starting from a guessing point given by the user. In the example we will start from two different guessing points to compare the results. Here's the code:
import numpy
import pylab
from scipy.optimize import fmin

# objective function
rsinc = lambda x: -1 * numpy.sin(x)/x

x0 = -5 # start from x = -5
xmin0 = fmin(rsinc,x0)

x1 = -4 # start from x = -4
xmin1 = fmin(rsinc,x1)

# plot the function
x = numpy.linspace(-15,15,100)
y = rsinc(x)
pylab.plot(x,y)
# plot of x0 and the minimum found startin from x0
pylab.plot(x0,rsinc(x0),'bd',xmin0,rsinc(xmin0),'bo')
# plot of x1 and the minimum found startin from x1
pylab.plot(x1,rsinc(x1),'rd',xmin1,rsinc(xmin1),'ro')
pylab.axis([-15,15,-1.3,0.3])
pylab.show()
The function fmin will print some detail about the iterative process performed:
Optimization terminated successfully.
         Current function value: -0.128375
         Iterations: 18
         Function evaluations: 36
Optimization terminated successfully.
         Current function value: -1.000000
         Iterations: 19
         Function evaluations: 38

And the graphical result should be as follows:


The blue dot is the minimum found starting from the blue diamond (x=-5) and the red dot is the minimum found starting from the red diamond (x=-4). In this case, when we start from x=-5 fmin get stuck in a local minum and when we start from x=-4 fmin reaches the global minimum.

Tuesday, April 26, 2011

How to plot a function using matplotlib

We will see how to evaluate a function using numpy and how to plot the result.
import pylab
import numpy

x = numpy.linspace(-15,15,100) # 100 linearly spaced numbers
y = numpy.sin(x)/x # computing the values of sin(x)/x

# compose plot
pylab.plot(x,y) # sin(x)/x
pylab.plot(x,y,'co') # same function with cyan dots
pylab.plot(x,2*y,x,3*y) # 2*sin(x)/x and 3*sin(x)/x
pylab.show() # show the plot
The command pylab.show() will open a window with the following plot:

Monday, April 25, 2011

How to use twitter search api

The example show how to search in twitter without using third party libraries. We will use the json data-interchange format provided by twitter.
import urllib
import simplejson

def searchTweets(query):
 search = urllib.urlopen("http://search.twitter.com/search.json?q="+query)
 dict = simplejson.loads(search.read())
 for result in dict["results"]: # result is a list of dictionaries
  print "*",result["text"],"\n"

# we will search tweets about "fc liverpool" football team
searchTweets("fc+liverpool")
The program will print the most popular tweets about fc liverpool
* Poulsen set for return home? http://tinyurl.com/3vnyc9r 

* Now: Watch live press conf - Liverpool FC http://lfc.tv/GYb 

* Who wants 20 percent off a Liverpool fc stuff 

* Liverpool FC manager Gerard Houllier in Birmingham hospital after health s... http://bit.ly/glcgxJ #LFC 

* RT @darsh710: Liverpool Echo: Kenny: Alberto Aquilani welcome back at LFC after Juve loan ends http://bit.ly/emp5QZ  #LFC @ShilChandi @KaushP @BolaAnt 

* RT @empireofthekop: Liverpool Echo : News: Kenny Dalglish: Alberto Aquilani welcome back at Liverpool FC after Juventus loan ends http://bit.ly/emp5QZ #LFC #fb 

Friday, April 22, 2011

How to delete all the files in a directory

import os

dirPath = "/home/giu/pyExperiments/toRemove"
fileList = os.listdir(dirPath)
for fileName in fileList:
 os.remove(dirPath+"/"+fileName)

How to implement a multithread echo server

The example implement a multithread echo server. Every incoming request is handed off to a worker thread that will process the request.
import socket
import thread

def handle(client_socket, address):
 while True:
  data = client_socket.recv(512)
  if data.startswith("exit"): # if data start with "exit"
   client_socket.close() # close the connection with the client
   break
  client_socket.send(data) # echo the received string

# opening the port 1075
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((socket.gethostname(),1075))
server.listen(2)

while True: # listen for incoming connections
 client_socket, address = server.accept()
 print "request from the ip",address[0]
 # spawn a new thread that run the function handle()
 thread.start_new_thread(handle, (client_socket, address)) 
And now we can use telnet to communicate with the server application:
$ telnet localhost 1075
Trying ::1...
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
hi
hi
echo this!
echo this!
exit
Connection closed by foreign host.

Thursday, April 21, 2011

How to retrieve tweets from twitter

How to retrieve the most recent tweets of a twitter user without third party library. The example use the xml format provided by twitter to describe a user timeline.
import urllib
import xml.dom.minidom as minidom

def printTweets(username):
 timeline_xml = urllib.urlopen("http://twitter.com/statuses/user_timeline.xml?screen_name="+username)
 doc = minidom.parse(timeline_xml) # we're using the twitter xml format
 tweets = doc.getElementsByTagName("text") # tweet text is in ...
 
 for tweet in tweets:
  print "tweet:",tweet.childNodes[0].data,"\n"

## call the our function
printTweets("JustGlowing")
The function will print the 20 most recent JusetGlowing's tweet:
tweet: Security researchers find iPhones, 3G iPads track user location http://t.co/Fg9TIQy via @arstechnica 

tweet: White Blood Cells Solve Traveling-Salesman Problem http://zite.to/fMTv9J - RT @semanticvoid 

tweet: #IWouldTrade traffic in the city for a wonderful beach 

tweet: The time you enjoy wasting is not wasted time ~ Bertrand Russel 

tweet: numpy is a great tool, it make you feel like using matlab but you're using a free #python library #in

...

Wednesday, April 20, 2011

How to create threads

The example show how to define the behavior of a thread and run it.
import threading
import time
import random

class MyThread(threading.Thread):
 def __init__(self, myName):
  threading.Thread.__init__(self)
  self.myName = myName

 def run(self):
  while True:
   time.sleep(random.randint(0,3)) # wait a random time from 0 to 3 secs
   print "My name is",self.myName

thread1 = MyThread("1")
thread1.start() # the thread will run in background
thread2 = MyThread("2")
thread2.start()
My name is 1
My name is 1
My name is 2
My name is 2
My name is 1
...
The two threads will print in the console their attribute myName with random time interval.

Tuesday, April 19, 2011

How to work with exceptions

Here is:
  • How to define an exception
  • How to raise an exception
  • How to catch an exception

class MyException(Exception): # a custom exception
 """ My own exception class """
 def __init__(self,value):
  self.value = value
 def __str__(self):
  return repr(self.value)

def myFunction(): # this function will raise a exception
 print "The shuttle is landed"
 raise MyException("Huston, we have a problem")

def handleException(): # this function will handle the exception
 try:
  myFunction()
 except MyException, e:
  print "Something is going wrong:", e.value

## test the exception handling ##
handleException();
The shuttle is landed
Something is going wrong: Huston, we have a problem

Monday, April 18, 2011

How to define a class (using inheritance too)

The snippet contains:

  • How to declare and use a class with attributes and methods
  • How to declare a class using inheritance

class Point2D:
 """ a point in a 2D space """
 name = "A dummy name" # attribute

 def __init__(self,x,y): # constructor
  self.x = x
  self.y = y

 def product(self,p): # method
  """ product with another point """
  return self.x*p.x + self.y*p.y

 def print_2D(self):
  print "(",self.x,",",self.y,")"

class Point3D(Point2D): # Point3D inherit Point2D
 def __init__(self,x,y,z):
  self.x = x
  self.y = y
  self.z = z

 def print_3D(self):
  print "(",self.x,",",self.y,",",self.z,")"

## just test the our classes ##

p2 = Point2D(1,2)
p2.print_2D()
print p2.product(Point2D(2,1))

p3 = Point3D(5,4,3)
p3.print_2D()
p3.print_3D() # inherited method
print p3.name # inherited attribute
print dir(Point2D)
print dir(Point3D) # dir return a list with attribute and methods of the class
( 1 , 2 )
4
( 5 , 4 )
( 5 , 4 , 3 )
A dummy name
['__doc__', '__init__', '__module__', 'name', 'print_2D', 'product']
['__doc__', '__init__', '__module__', 'name', 'print_2D', 'print_3D', 'product']

How to list files in a directory

This code will print the content of the directory "/home/giu/Documents/secrets"
import os

fileList = os.listdir("/home/giu/Documents/secrets")
for fileName in fileList:
 print fileName
howtoconquertheworld.pdf
hellokitty.jpg
loveletter.txt
misterious_pictures

Variables and typing

Never forget, Python uses duck typing and has typed objects but untyped variable names.

lfc = "Liverpool" # this is a string
manc = "Manchester City"
l_score = 3 # this is a integer
m_score = 0
print "Result",lfc,l_score,"-",m_score,manc
Result Liverpool 1 - 0 Manchester City

How to know the type of variables:

type(lfc)
<type 'str'="">
type(l_score)
<type 'int'="">

Hello world

Just open a python interactive interpreter and type

print "Hello World! The glowing python is here!"

The output will be

Hello World! The glowing python is here!