-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathInitMutFit.py
41 lines (33 loc) · 1.17 KB
/
InitMutFit.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
import numpy
import random
import copy
def InitializeSol(stops):
'''Random starting solution for optimization algorithm.'''
x = numpy.linspace(0, stops-1, stops)
random.shuffle(x)
return x
def Mutate(solution):
'''Mutate a solution by swapping the order of two locations.'''
solcopy = copy.deepcopy(solution)
stops = len(solcopy)
swap1 = random.randint(0, stops - 1)
swap2 = random.randint(0, stops - 1)
solcopy[swap1], solcopy[swap2] = solcopy[swap2], solcopy[swap1]
return solcopy
def Fitness(solution, distMat):
'''Calculate the fitness of a travel path as the total Euclidean
distance traveled.'''
stops = len(solution)
distance = 0.0
for i in range(1, stops):
distance += distMat[solution[i], solution[i - 1]]
return distance
def Select(fits, tournamentsize):
'''Choose an individual to reproduce by having them randomly
compete in a given size tournament.'''
stops = len(fits)
competitors = random.sample(range(stops), tournamentsize)
# who is the best of the competitors?
compFits = [fits[i] for i in competitors]
winner = competitors[compFits.index(min(compFits))]
return winner