lolamontes69

Ch 5 Collective Intelligence: Random-restart hillclimbing

Jun 30th, 2013
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.68 KB | None | 0 0
  1. """ This is optimization.py from the beginning of Chapter 5 in Programming Collective Intelligence
  2.    adapted to use a Random-restart hillclimbing method
  3.    Usage:
  4.         import optimization as optimization
  5.         s=optimization.randomoptimize(domain,optimization.schedulecost)
  6.         optimization.schedulecost(s)
  7.         optimization.printschedule(s)
  8. """
  9. import time as time
  10. import math
  11. import random as random
  12.  
  13. people = [('Seymour','BOS'),('Franny','DAL'),('Zooey','CAK'),('Walt','MIA'),('Buddy','ORD'),('Les','OMA')]
  14.  
  15. # LaGuardia airport in New York
  16. destination = 'LGA'
  17.  
  18. flights={}
  19. for line in file('schedule.txt'):
  20.     origin,dest,depart,arrive,price=line.strip().split(',')
  21.     flights.setdefault((origin,dest),[])
  22.  
  23.     # Add details to the list of possible flights
  24.     flights[(origin,dest)].append((depart,arrive,int(price)))
  25.  
  26. def getminutes(t):
  27.     x=time.strptime(t,'%H:%M')
  28.     return x[3]*60+x[4]
  29.  
  30. def printschedule(r):
  31.     for d in range(len(r)/2):
  32.         name=people[d][0]
  33.         origin=people[d][1]
  34.         out=flights[(origin,destination)][r[2*d]]              # Corrected for iterating wrongly
  35.         ret=flights[(origin,destination)][r[(2*d)+1]]          # Corrected for iterating wrongly
  36.         print '%10s%10s %5s-%5s $%3s %5s-%5s $%3s' % (name,origin,out[0],out[1],out[2],ret[0],ret[1],ret[2])
  37.  
  38. def schedulecost(sol):
  39.     totalprice=0
  40.     latestarrival=0
  41.     earliestdep=24*60
  42.     for d in range(len(sol)/2):
  43.         # Get the inbound and outbound flights
  44.         origin = people[d][1]
  45.         outbound = flights[(origin,destination)][int(sol[2*d])]    # Corrected for iterating wrongly
  46.         returnf = flights[(destination,origin)][int(sol[(2*d)+1])] # Corrected for iterating wrongly
  47.  
  48.         # Total price is the price of all outbound and return flights
  49.         totalprice+=outbound[2]
  50.         totalprice+=returnf[2]
  51.  
  52.         # Track the latest arrival and earliest departure
  53.         if latestarrival<getminutes(outbound[1]): latestarrival=getminutes(outbound[1])
  54.         if earliestdep>getminutes(returnf[0]): earliestdep=getminutes(returnf[0])
  55.  
  56.     # Every person must wait at the airport until the latest person arrives.
  57.     # They must also arrive at the same time and wait for their flights
  58.     totalwait=0
  59.     for d in range(len(sol)/2):
  60.         origin=people[d][1]
  61.         outbound=flights[(origin,destination)][int(sol[2*d])]    # Corrected for iterating wrongly
  62.         returnf=flights[(destination,origin)][int(sol[(2*d)+1])] # Corrected for iterating wrongly
  63.         totalwait+=latestarrival-getminutes(outbound[1])
  64.         totalwait+=getminutes(returnf[0])-earliestdep
  65.  
  66.     # Does this solution require an extra day of car rental? That'll be $50
  67.     if latestarrival<earliestdep: totalprice+=50  # Corrected
  68.  
  69.     return totalprice+totalwait
  70.  
  71. def randomoptimize(domain,costf):
  72.     best=999999999
  73.     bestr=None
  74.     for i in range(100):
  75.         # Create a random solution
  76.         r=[random.randint(domain[i][0],domain[i][1]) for i in range(len(domain))]
  77.         # Get the best solution from a hillclimb on the random solution.
  78.         r1 = hillclimb(domain,costf,r)
  79.         # Get the cost
  80.         cost=costf(r1)
  81.         # Compare it to the best one so far
  82.         if cost<best:
  83.             best=cost
  84.             bestr=r1
  85.  
  86.     return bestr                # Typo corrected 'bestr' for 'r'
  87.  
  88. def hillclimb(domain,costf,sol):
  89.     # Create a random solution
  90.     # Main loop
  91.     while 1:
  92.         #Create list of neighboring solutions
  93.         neighbors=[]
  94.         for j in range(len(domain)):
  95.             # One away in each direction
  96.             if sol[j] > domain[j][0] and sol[j] < domain[j][1]:
  97.                 neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:])
  98.                 neighbors.append(sol[0:j]+[sol[j]-1]+sol[j+1:])
  99.             if sol[j] == domain[j][0]:
  100.                 neighbors.append(sol[0:j]+[sol[j]+1]+sol[j+1:])
  101.             if sol[j] == domain[j][1]:
  102.                 neighbors.append(sol[0:j]+[sol[j]-1]+sol[j+1:])
  103.  
  104.         # See what the best solution amongst the neighbors is
  105.         current=costf(sol)
  106.         best=current
  107.         for j in range(len(neighbors)):
  108.             cost=costf(neighbors[j])
  109.             if cost<best:
  110.                 best=cost
  111.                 sol=neighbors[j]
  112.  
  113.         # If there's no improvement, then we've reached the top
  114.         if best==current:
  115.             break
  116.  
  117.     return sol
  118.  
  119. """ Corrections to printschedule() for wrong iterations through list r
  120.    Corrections to schedulecost() for wrong iterations through list r
  121.    Correction to randomoptimize() was returning r instead of bestr
  122.    Corrections in hillclimb to correct out of index errors when sol[j] is 0 or 1
  123. """
Advertisement
Add Comment
Please, Sign In to add comment