lolamontes69

socialnetwork.py for Ch5 Programming Collective Intelligence

Jul 5th, 2013
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.12 KB | None | 0 0
  1. import math
  2. from PIL import Image, ImageDraw
  3.  
  4. people=['Charlie','Augustus','Veruca','Violet','Mike','Joe','Willy','Miranda']
  5. links=[('Augustus', 'Willy'),
  6.        ('Mike', 'Joe'),
  7.        ('Miranda', 'Mike'),
  8.        ('Violet', 'Augustus'),
  9.        ('Miranda', 'Willy'),
  10.        ('Joe', 'Charlie'),
  11.        ('Veruca', 'Augustus'),
  12.        ('Miranda', 'Joe')]
  13.  
  14. def crosscount(v):
  15.     # Convert the number list t a dictionary of person/ (x,y)
  16.     loc=dict([(people[i],(v[i*2],v[i*2+1])) for i in range(0,len(people))])
  17.     total=0
  18.  
  19.     # Loop through every pair of links
  20.     for i in range(len(links)):
  21.         for j in range(i+1,len(links)):
  22.  
  23.             # Get the locations
  24.             (x1,y1),(x2,y2)=loc[links[i][0]],loc[links[i][1]]
  25.             (x3,y3),(x4,y4)=loc[links[j][0]],loc[links[j][1]]
  26.  
  27.             den=(y4-y3)*(x2-x1)-(x4-x3)*(y2-y1)
  28.  
  29.             # den=0 if lines are parallel
  30.             if den==0: continue
  31.  
  32.             # Otherwise ua and ab are a fraction of ithe line where they cross
  33.             ua=((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/float(den)              # Corrected for python 2x
  34.             ub=((x2-x1)*(y1-y3)-(y2-y1)*(x1-x3))/float(den)              # Corrected for python 2x
  35.  
  36.             # If the fraction for this total is between 0 and 1 for both lines then they cross each other
  37.             if ua>0 and ua<1 and ub>0 and ub<1:
  38.                 total+=1
  39.     print "total=",total
  40.     return total
  41.  
  42. def drawnetwork(sol):
  43.     jpeg='network_diagram.jpg'
  44.     # Create the image
  45.     img=Image.new('RGB',(400,400),(255,255,255))
  46.     draw=ImageDraw.Draw(img)
  47.  
  48.     # Create the position dict
  49.     pos=dict([(people[i],(sol[i*2],sol[i*2+1])) for i in range(0,len(people))])
  50.  
  51.     # Draw links
  52.     for (a,b) in links:
  53.         draw.line((pos[a],pos[b]),fill=(255,0,0))
  54.  
  55.     # draw people
  56.     for n,p in pos.items():
  57.         draw.text(p,n,(0,0,0))
  58.     img.save(jpeg,'JPEG')
  59.  
  60. domain=[(10,370)]*(len(people)*2)
  61.  
  62. """ Corrected drawnetwork() to print out result as a jpeg
  63.    Corrected crosscount to allow float division of ua and ub because Python 2x
  64.      defaulted to integer division during "../den"
  65. """
Advertisement
Add Comment
Please, Sign In to add comment