def swap_Mutation(mutationRate: float, tour: Tour) -> Tour: for i, city in enumerate(tour.tour): if random() <= mutationRate: # Getting second random city randomId = randrange(0, tour.getSize()) other_city = tour.getCity(randomId) # Swapping the Route tour.setCity(i, other_city) tour.setCity(randomId, city) return tour
def moveCloser(self, blackHole, star): min_possible = star.getDistance() min_tour = star for i in range(7): # New Child newStar = Tour() # Getting Sub-tour startpos = randrange(0, blackHole.getSize()) endpos = randrange(0, blackHole.getSize()) if (startpos > endpos): startpos, endpos = endpos, startpos for i in range(newStar.getSize()): if i > startpos and i < endpos: newStar.setCity(i, blackHole.getCity(i)) else: newStar.setCity(i, None) for i in range(newStar.getSize()): if not newStar.containsCity(star.getCity(i)): for j in range(0, newStar.getSize()): if newStar.getCity(j) == None: newStar.setCity(j, star.getCity(i)) break if (newStar.getDistance(True) < min_possible): return newStar return min_tour
def ordered_crossover(parent_a: Tour, parent_b: Tour) -> Tour: # New Child offspring = Tour() # Getting Sub-tour startpos = randrange(0, parent_a.getSize()) endpos = randrange(0, parent_a.getSize()) if(startpos > endpos): startpos, endpos = endpos, startpos for i in range(offspring.getSize()): if i > startpos and i < endpos: offspring.setCity(i, parent_a.getCity(i)) else: offspring.setCity(i, None) for i in range(offspring.getSize()): if not offspring.containsCity(parent_b.getCity(i)): for j in range(0, offspring.getSize()): if offspring.getCity(j) == None: offspring.setCity(j, parent_b.getCity(i)) break return offspring