Pastebin
Paste #1239: differential simulated annealing
< previous paste - next paste>
Pasted by Verte
def d_neighbour(h, reservations):
"""Find a neighbour state.
Choose a reservation to move and the position it can be moved to."""
# Pick a random reservation
r = random.choice(reservations)
rsize = len(r.seats)
#print """We randomly selected reservation %s, with %s seats""" % (r.id, rsize)
#print r.pp()
# Pick random row with enough seats
row = None
while not row:
crow = random.choice(h.rows)
if len(crow.seats) >= rsize:
row = crow
# Pick a random start seat in this row
new_idx = int(rand() * (len(row.seats)-rsize))
# the unmodified reservation and the new seats
return reservation, row.seats[new_idx:new_idx+rsize]
def d_E(reservation, new_seats):
"""difference in energy. Given a reservation and a place it can be moved to,
calculate the difference between the energy of the original and the new state."""
return sum(r.seat.score for r in new_seats) - sum(r.seat.score for r in reservation)
def apply_diff(reservation, new_seats):
"""move a reservation to new seats."""
for seat in reservation.seats:
seat.sold -= 1
for seat in new_seats:
seat.sold += 1
reservation.seats = new_seats
# ...
e = E(sn)
hall, reservations = sn
i = 0
while k < kmax and e > emax: # While time remains & not good enough:
i+=1
# find a new state and the difference in energy created.
reservation, new_seats = neighbour(hall, reservations)
energy_diff = d_E(reservation, new_seats)
if P(e, e + energy_diff, temp(k/kmax)) > rand(): # Should we move to it?
apply_diff(reservation, new_seats) # move to the new state
e += energy_diff
if energy_diff < 0: # best we've seen- save it
en = e
sb = deepcopy((hall, reservations))
k = k + 1 # One more evaluation done
log("""Status: en: %s, eb: %s, e: %s""" % (en, eb, e), HINT)
New Paste
Go to most recent paste.