van boeren van boeren - 1 year ago 104
Python Question

I write this code of Simulated Annealing for TSP and I have been trying all day to debug it but something goes wrong

This code suppose to reduce the distance of initial tour: distan(initial_tour) < distan(best) . Can you help me plz? I 've been trying all day now. Do I need to change my swapping method?
Something goes wrong and the simulated annealing does'not work:

def prob(currentDistance,neighbourDistance,temp):

if neighbourDistance < currentDistance:
return 1.0

return math.exp( (currentDistance - neighbourDistance) / temp)

def distan(solution):

#gives the distance of solution

listax, listay = [], []
for i in range(len(solution)):


dists = np.linalg.norm(np.vstack([np.diff(np.array(listax)), np.diff(np.array(listay))]), axis=0)
cumsum_dist = np.cumsum(dists)

return cumsum_dist[-1]

#simulated annealing

temp = 1000000

#creating initial tour



print (distan(initial_tour))

current_best = initial_tour

best = current_best

while(temp >1 ):

#create new neighbour tour

new_solution= current_best

#Get a random positions in the neighbour tour

tourPos1=random.randrange(0, len(dfar))
tourPos2=random.randrange(0, len(dfar))



#get distance of both current_best and its neighbour

currentDistance = distan(current_best)

neighbourDistance = distan(new_solution)

# decide if we should accept the neighbour
# random.random() returns a number in [0,1)

if prob(currentDistance,neighbourDistance,temp) > random.random():

current_best = new_solution

# keep track of the best solution found

if distan(current_best) < distan(best):

best = current_best

#Cool system

temp = temp*0.99995


Answer Source

Your problem is in the first line of your while loop, where you write

new_solution= current_best 

What this does is puts a reference to the current_best list into new_solution. This means that when you change new_solution, you're actually changing current_best as well, which was not your intention.

The problem could be solved by replacing the problematic line with one that copies the list into a new list, like so:

new_solution = list(current_best)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download