small refractor and added comments in Population

This commit is contained in:
Konrad 2021-06-15 23:33:40 +02:00
parent 95c5a01749
commit b64cdb51d4

View File

@ -16,24 +16,24 @@ class Population:
return population
def createRoute(self, points):
route = random.sample(points, len(points))
route = random.sample(points, len(points)) #creating population (first generation)
return route
def rankRoutes(self, population):
fitnessResults = {}
for i in range(0, len(population)):
for i in range(0, len(population)): #creating whole population
fitnessResults[i] = Fitness(population[i], self.board, self.dTree).routeFitness()
return sorted(fitnessResults.items(), key=operator.itemgetter(1), reverse=True)
def selection(self, popRanked, eliteSize):
def selection(self, popRanked, eliteSize): #selecting mating pool
selectionResults = []
df = pd.DataFrame(np.array(popRanked), columns=["Index", "Fitness"])
df = pd.DataFrame(np.array(popRanked), columns=["Index", "Fitness"]) #roulette wheel selection
df['cum_sum'] = df.Fitness.cumsum()
df['cum_perc'] = 100 * df.cum_sum / df.Fitness.sum()
for i in range(0, eliteSize):
for i in range(0, eliteSize): #elitism
selectionResults.append(popRanked[i][0])
for i in range(0, len(popRanked) - eliteSize):
for i in range(0, len(popRanked) - eliteSize): #compare a randomly drawn number weights to select our mating pool
pick = 100 * random.random()
for i in range(0, len(popRanked)):
if pick <= df.iat[i, 3]:
@ -52,8 +52,10 @@ class Population:
child = []
childP1 = []
childP2 = []
print(parent1)
geneA = int(random.random() * len(parent1))
print(geneA)
geneB = int(random.random() * len(parent1))
startGene = min(geneA, geneB)
@ -67,16 +69,16 @@ class Population:
child = childP1 + childP2
return child
def mutate(self, individual, mutationRate):
def mutate(self, individual, mutationRate): # with specified low probability, two bombs will swap places in our route
for swapped in range(len(individual)):
if random.random() < mutationRate:
swapWith = int(random.random() * len(individual))
city1 = individual[swapped]
city2 = individual[swapWith]
bomb1 = individual[swapped]
bomb2 = individual[swapWith]
individual[swapped] = city2
individual[swapWith] = city1
individual[swapped] = bomb2
individual[swapWith] = bomb1
return individual
def mutatePopulation(self, population, mutationRate):
@ -88,8 +90,8 @@ class Population:
return mutatedPop
def nextGeneration(self, currentGen, eliteSize, mutationRate):
popRanked = self.rankRoutes(currentGen)
selectionResults = self.selection(popRanked, eliteSize)
popRanked = self.rankRoutes(currentGen) #rank the routes
selectionResults = self.selection(popRanked, eliteSize) #determine potential parents
matingpool = self.matingPool(currentGen, selectionResults)
children = self.breedPopulation(matingpool, eliteSize)
nextGeneration = self.mutatePopulation(children, mutationRate)