InteligentnaSmieciarka2000/genetic.py

53 lines
1.3 KiB
Python
Raw Normal View History

2020-06-29 10:52:52 +02:00
from astar import Astar
import numpy as np
from DNA import DNA
import random
import copy
def genetic(goals, A):
recordDistance = 1000000000
#count = 0
generation = 0
totalPopulaton = 10
population = []
matingPool = []
mutationRate = 0.01
for i in range(totalPopulaton):
2020-06-29 11:09:03 +02:00
population.append(DNA(goals)
2020-06-29 10:52:52 +02:00
for j in range(totalPopulaton):
matingPool.clear()
generation = generation + 1
for i in range(totalPopulaton):
population[i].calcFitness(A)
if population[i].fitness < recordDistance:
recordDistance = population[i].fitness
best = copy.deepcopy(population[i])
bestGeneration = generation
for i in range(totalPopulaton):
n = population[i].fitness * 100
for j in range(int(n)):
matingPool.append(population[i])
for i in range(totalPopulaton):
if matingPool:
a = random.randint(0, len(matingPool) - 1)
b = random.randint(0, len(matingPool) - 1)
partnerA = matingPool[a]
partnerB = matingPool[b]
child = partnerA.crossover(partnerB)
child.mutate(mutationRate)
population[i] = child
return best