2020-06-29 10:52:52 +02:00
|
|
|
import random
|
|
|
|
import string
|
|
|
|
from astar import Astar
|
|
|
|
from random import shuffle
|
|
|
|
import numpy as np
|
|
|
|
|
|
|
|
class DNA:
|
|
|
|
|
2020-06-29 11:08:09 +02:00
|
|
|
def __init__(self, target):
|
2020-06-29 10:52:52 +02:00
|
|
|
shuffle(target)
|
|
|
|
self.genes = target.copy()
|
|
|
|
self.fitness = 1.0
|
|
|
|
|
|
|
|
def calcFitness(self, A):
|
|
|
|
start = [0, 0]
|
|
|
|
sum = 1
|
|
|
|
|
|
|
|
for goal in self.genes:
|
|
|
|
path = Astar(A, start, goal)
|
|
|
|
sum = sum + len(path) - 1
|
|
|
|
start = goal
|
|
|
|
|
|
|
|
self.fitness = sum
|
|
|
|
|
|
|
|
def crossover(self, partner):
|
|
|
|
|
2020-06-29 11:08:09 +02:00
|
|
|
child = DNA(self.genes)
|
2020-06-29 10:52:52 +02:00
|
|
|
start = abs(random.randint(0, len(self.genes)) - 1)
|
|
|
|
end = abs(random.randint(start - 1, len(self.genes)))
|
|
|
|
|
|
|
|
child.genes = child.genes[start:end]
|
|
|
|
|
|
|
|
for i in range(len(self.genes)):
|
|
|
|
node = partner.genes[i]
|
|
|
|
|
|
|
|
if node not in child.genes:
|
|
|
|
child.genes.append(node)
|
|
|
|
|
|
|
|
return child
|
|
|
|
|
|
|
|
def mutate(self, mutationRate):
|
|
|
|
|
|
|
|
for i in range(len(self.genes)):
|
|
|
|
if random.random() < mutationRate:
|
|
|
|
indexA = abs(random.randint(0, len(self.genes)) - 1)
|
|
|
|
indexB = (indexA + 1) % len(self.genes)
|
|
|
|
self.genes[indexA], self.genes[indexB] = self.genes[indexB], self.genes[indexA]
|
|
|
|
|