forked from HIT1190202126/EC_work
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutation.py
105 lines (93 loc) · 2.89 KB
/
mutation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import random
import Individual
import TSPProblem
class Mutation:
"""
The Class deal with mutation
"""
def __init__(self, size, tspproblem):
"""
Constructor
:param size :
:param tsp :A tspproblem object
"""
self.size = size
self.dim = tspproblem.DIMENSION
self.tspp = tspproblem
def getRand2(self):
"""
Helper function
get 2 randomly choose index
:return: idx1,idx2 two index in range [0,self.dim-1](idx1 < idx2)
"""
idx1 = 0
idx2 = 0
while idx2 == idx1:
idx1 = random.randint(0, self.dim - 1)
idx2 = random.randint(0, self.dim - 1)
if idx1 > idx2:
t = idx2
idx2 = idx1
idx1 = t
# print(idx1," ",idx2)
return idx1, idx2
def swapMutation(self, ind):
"""
Use swap to Mutate a new solution
:param ind:an individual object
:return:The SAME individual object which has been Mutated
"""
idx1, idx2 = self.getRand2()
# swap
t = ind.tour[idx1]
ind.tour[idx1] = ind.tour[idx2]
ind.tour[idx2] = t
return ind
def insertMutation(self, ind):
"""
Use insertion to Mutate a new solution
:param ind: an individual object
:return: The SAME individual object which has been Mutated
"""
idx1, idx2 = self.getRand2()
ind.tour.insert(idx1 + 1, ind.tour[idx2])
ind.tour.pop(idx2 + 1)
return ind
def invertionMutation(self, ind):
"""
Use invertion to Mutate a new solution
:param ind: an individual object
:return: The SAME individual object which has been Mutated
"""
idx1, idx2 = self.getRand2()
subList = ind.tour[idx1:idx2]
subList.reverse()
ind.tour[idx1:idx2] = subList
return ind
def scrambleMutation(self, ind):
"""
Use scramble to Mutate a new solution
:param ind: an individual object
:return: The SAME individual object which has been Mutated
"""
idx1, idx2 = self.getRand2()
subList = ind.tour[idx1:idx2]
random.shuffle(subList)
ind.tour[idx1:idx2] = subList
return ind
# Testing Correctness
if __name__ == "__main__":
location1 = "dataSet/eil51.tsp/eil51.tsp"
location2 = "dataSet/eil51.opt.tour/eil51.opt.tour"
TSP0 = TSPProblem.TSPProblem(location1, location2)
Ind = Individual.Individual(TSP0)
Ind.RandomTour()
print(Ind.tour)
Ind = Mutation(0, TSP0).swapMutation(Ind)
print("After SWAP", Ind.tour)
Ind = Mutation(0, TSP0).insertMutation(Ind)
print("After Insert", Ind.tour)
Ind = Mutation(0, TSP0).scrambleMutation(Ind)
print("After scramble", Ind.tour)
Ind = Mutation(0, TSP0).invertionMutation(Ind)
print("After invert", Ind.tour)