I couldn't find any complete implementation of the 2-opt algorithm in Python so I am trying to add the missing parts in the this project..I want to get best solution.But in this project gives final route with cross path. To fix this I implement two opt algorithm to this code. But after all ,final route again with cross.It is two opt algorithm that i added to this source
I get this function from here:two-opt
def two_optt(self, route):
best = route
improved = True
while improved:
improved = False
for i in range(1, len(route.route) - 2):
for j in range(i + 1, len(route.route)):
if j - i == 1: continue
new_route=Route()
new_route.route = route.route[:]
new_route.recalc_rt_len()
new_route.route[i:j] = route.route[j-1:i - 1:-1] # this is the 2woptSwap
new_route.recalc_rt_len()
if new_route.length < best.length:
best = new_route
improved = True
route=best
best.recalc_rt_len()
return best
I added this function into class GA and i called this function after mutate calling.I called it, like this in code part:`
for route in descendant_pop.rt_pop:
if random.random() < 0.3:
self.mutate(route)
self.two_optt(route) `
Again i get a solution with cross path. What should i do ? Is it where I add two opt function wrong, or where I call wrong?