lolamontes69

Ch5 Ex6-Programming Collective Intelligence

Jul 7th, 2013
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.01 KB | None | 0 0
  1. """ Chapter 5 Exercise 6: Line angle penalization.
  2.  
  3.    Add an additional cost to the network layout algorithm cost function when the angle between two lines attached to the same person is very small. (Hint: you can use the vector cross-product.)
  4.  
  5.    Here's the basic line angle penalization to add.
  6. """
  7.  
  8. def crosscount1(v):
  9.     total = 0
  10.     res = 0
  11.     def calculate_angle(centre,line1,line2):
  12.         # Calculate the angles created.
  13.         delta_x = float(line1[0] - centre[0])
  14.         delta_y = float(line1[1] - centre[1])
  15.         answer = atan2(delta_y, delta_x)*180.0/pi
  16.  
  17.         delta_x = float(line2[0] - centre[0])
  18.         delta_y = float(line2[1] - centre[1])
  19.         answer1 = atan2(delta_y, delta_x)*180.0/pi
  20.  
  21.         # Get the answer
  22.         if answer > answer1: return answer-answer1
  23.         else: return answer1-answer
  24.  
  25.     # Convert the number list t a dictionary of person/ (x,y)
  26.     loc=dict([(people[i],(v[i*2],v[i*2+1])) for i in range(0,len(people))])
  27.     total=0
  28.  
  29.     # Loop through every pair of links
  30.     for i in range(len(links)):
  31.         for j in range(i+1,len(links)):
  32.  
  33.             # Get the locations                                                - first get the locations
  34.             (x1,y1),(x2,y2)=loc[links[i][0]],loc[links[i][1]]
  35.             (x3,y3),(x4,y4)=loc[links[j][0]],loc[links[j][1]]
  36.  
  37.             # Find nodes then calculate angle between lines
  38.             if (x1,y1)==(x3,y3): res = calculate_angle((x1,y1),(x2,y2),(x4,y4))                      
  39.             elif (x1,y1)==(x4,y4): res = calculate_angle((x1,y1),(x2,y2),(x3,y3))
  40.             elif (x2,y2)==(x3,y3): res = calculate_angle((x2,y2),(x1,y1),(x4,y4))
  41.             elif (x2,y2)==(x4,y4): res = calculate_angle((x2,y2),(x1,y1),(x3,y3))
  42.             # Find the smallest of the two angles between the lines
  43.             if res>180: res1 = 360-res
  44.             else: res1=res
  45.             # If the angle is less than 30 add to cost
  46.             if res1<30:
  47.                 total+=(1-(res1/30.0))
  48.     return total
Advertisement
Add Comment
Please, Sign In to add comment