-
Notifications
You must be signed in to change notification settings - Fork 0
/
evolver.py
38 lines (29 loc) · 910 Bytes
/
evolver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# coding: utf-8
#
# Copyright (c) 2019 Zoltán Máté
# All Rights Reserved.
#
# Author: Zoltán Máté <[email protected]>
#
"""
Simple evolutionary algorithm with asexual breeding
"""
from multiprocessing import Pool
class Evolver(object):
@classmethod
def evolve(cls, population):
population += cls.breed(population)
population_sorted_by_fitness = cls.sort_by_fitness(population)
return cls.select_high_fitness_entities(population_sorted_by_fitness)
@staticmethod
def breed(population):
with Pool() as pool:
return pool.map(breed, population)
@staticmethod
def sort_by_fitness(population):
return sorted(population, key=lambda x: x.fitness, reverse=True)
@staticmethod
def select_high_fitness_entities(population):
return population[:len(population) >> 1]
def breed(entity):
return entity.breed()