import random import string from astar import Astar from random import shuffle import numpy as np class DNA: def __init__(self, target): 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): child = DNA(self.genes) 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]