0

I am trying to visualize and solve the traveling salesperson problem with python and genetic algorithms, i was following one of Daniel Shiffman's coding challenge videos on youtube i don't know if i'm allowed to put a link here but here is the link (https://www.youtube.com/watch?v=M3KTWnTrU_c&list=PLRqwX-V7Uu6ZiZxtDDRCi6uhfTH4FilpH&index=42)

So the problem is , my genetic algorithm does not evolve. It gets stuck on just on first generation.I think i couldn't write the code that creates next generation like it's supposed to be due to my lack of knowledge on python, here is the code :

 import pygame
import random
import numpy as np
import sys

size=width,height=500,500
bgColor = (0,0,0)
screen = pygame.display.set_mode(size)
vertexArray = []
fitness = []
population = []
pygame.display.set_caption("Finding the Shortest path with Genetich Algorithm")
bestEver=[]
bestDistance = 999999

def shuffle(vertexArray):
    np.random.shuffle(vertexArray)
def swap(a,i,j):
    temp = a[i]
    a[i]=a[j]
    a[j]=temp
class Vertex:
    def __init__(self,x,y):
        self.color = (255,255,255)
        self.x = x
        self.y = y

    def display(self):
        pygame.draw.circle(screen,self.color,(self.x,self.y),4,4)

    def getPosition(self):
        return [self.x,self.y]

    def __str__(self):
        return str(self.x+", "+self.y)

def createVertexes(numOfVertexes):
    for i in range(numOfVertexes):
        vertexArray.append(Vertex(random.randint(0,width),random.randint(0,height)))
createVertexes(8)
def createPopulation():
    for i in range(300):
        population.append(vertexArray[:])
        for j in range(100):
            shuffle(population[i])
createPopulation()
def drawLines(vertexArray,color):
    for i in range(vertexArray.__len__()-1):
        pygame.draw.line(screen,color,vertexArray[i].getPosition(),vertexArray[i+1].getPosition(),1)
def calculateDistance(vertexArray):
    dist = 0
    for i in range(vertexArray.__len__()-1):
        dist += np.linalg.norm(np.asarray(vertexArray[i+1].getPosition())-np.asarray(vertexArray[i].getPosition()))
    return dist
def displayVertexes(vertexArray):
    for i in range(vertexArray.__len__()):
        vertexArray[i].display()
def calculateFitness():
    global bestDistance
    global bestEver
    for i in range(population.__len__()-1):
        d = calculateDistance(population[i])
        if d<bestDistance:
            bestDistance = d
            bestEver = population[i][:]
        fitness.append(1/d)
def getProbability(fitness,population):
    first = 0
    sum = 0
    for i in range(fitness.__len__() - 1):
        sum += fitness[i]
    r = random.uniform(0, sum)
    for i in range(fitness.__len__() - 1):
        if r<=fitness[i] and r>=first:
            return population[i]
        first = fitness[i]
    return population[random.randint(0,2)]

def pickOne(population,fitness):
    return getProbability(fitness,population)


def mutate(order):
    indexA = random.randint(0,order.__len__()-1)
    indexB = random.randint(0,order.__len__()-1)
    swap(order,indexA,indexB)

def nextGeneration():
    global population
    newPopulation=[]
    for i in range(population.__len__()-1):
        order = pickOne(population,fitness)
        mutate(order)
        newPopulation.append(order)
    population = newPopulation
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
    screen.fill(bgColor)
    displayVertexes(vertexArray)
    calculateFitness()
    print(fitness[2])
    nextGeneration()
    drawLines(bestEver,(255, 0, 0))
    pygame.display.flip()
lejlot
  • 64,777
  • 8
  • 131
  • 164
Tolga Oguz
  • 142
  • 1
  • 14
  • The last line of `getProbability` seems suspicious: `return population[random.randint(0,2)]` Why does it choosing from only the first two items in the population? – Elliot Godzich Sep 26 '17 at 21:13
  • @ElliotGodzich yea , i added that line of code because of a compiler error.It says `NoneType can't have the method : __len__()` when that function does not return anything.Actually i found out that my `getProbability` function is wrong .I just can't figure out how to give a higher probabilty to the fittest population while i'm selecting one of them randomly – Tolga Oguz Sep 26 '17 at 21:24

0 Answers0