Created
September 28, 2011 15:52
-
-
Save ulope/1248310 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from operator import attrgetter | |
import random | |
import string | |
import sys | |
# Evolutionary word finding. | |
# Inspired by: http://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/ | |
# | |
# | |
# Copyright (c) 2011, Ulrich Petri <[email protected]> | |
# All rights reserved. | |
# | |
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: | |
# | |
# Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. | |
# Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. | |
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
def levenshtein(s1, s2): | |
""" | |
Returns the Levenshtein distance (http://en.wikipedia.org/wiki/Levenshtein_distance) | |
of s1 to s2 | |
Taken from: http://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance | |
""" | |
if len(s1) < len(s2): | |
return levenshtein(s2, s1) | |
if not s1: | |
return len(s2) | |
previous_row = xrange(len(s2) + 1) | |
for i, c1 in enumerate(s1): | |
current_row = [i + 1] | |
for j, c2 in enumerate(s2): | |
insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer | |
deletions = current_row[j] + 1 # than s2 | |
substitutions = previous_row[j] + (c1 != c2) | |
current_row.append(min(insertions, deletions, substitutions)) | |
previous_row = current_row | |
return previous_row[-1] | |
# "A-Za-z " | |
BASE_ALPHABET = string.letters[:52] + " " | |
class Entity(object): | |
"""An entity in the population""" | |
def __init__(self, dna, fitness): | |
if hasattr(dna, "__iter__"): | |
dna = "".join(dna) | |
self.dna = dna | |
self.fitness = fitness | |
def __repr__(self): | |
return "<Entity DNA: '%s'>" % (self.dna,) | |
class Evlover(object): | |
def __init__(self, target, pop_size=20): | |
# Add possible target specific letters to alphabet | |
self.alphabet = BASE_ALPHABET + "".join(set(target) - set(BASE_ALPHABET)) | |
self.target = target | |
self.populate(pop_size) | |
def evolve(self): | |
generation = 0 | |
while True: | |
self.reproduce() | |
generation += 1 | |
fitness = self.evaluate_population_fitness() | |
if generation % 20 == 0: | |
sys.stdout.write(".") | |
sys.stdout.flush() | |
if fitness == 0: | |
break | |
return generation, self.population[0] | |
def update_fitness(self, entity): | |
entity.fitness = levenshtein(entity.dna, self.target) | |
def evaluate_population_fitness(self): | |
""" | |
Evaluate the fitness (levenshtein distance) for each member of the | |
population | |
""" | |
for entity in self.population: | |
self.update_fitness(entity) | |
self.population.sort(key=attrgetter("fitness")) | |
return self.population[0].fitness | |
def populate(self, pop_size): | |
"""Create a random population""" | |
self.population = [ | |
Entity((random.choice(self.alphabet) for i in xrange(len(self.target))), 0) | |
for j in xrange(pop_size) | |
] | |
def reproduce(self): | |
""" | |
Choose two parents (better fitness is weighted higher), combine their | |
DNA randomly and randomly mutate one gene. | |
""" | |
parent1 = self.get_random_entity() | |
parent2 = self.get_random_entity() | |
child_dna = [] | |
for genes in zip(parent1.dna, parent2.dna): | |
child_dna.append(random.choice(genes)) | |
child_dna[random.randint(0, len(child_dna) - 1)] = random.choice(self.alphabet) | |
child = Entity(child_dna, 0) | |
self.update_fitness(child) | |
if self.population[-1].fitness > child.fitness: | |
self.population[-1] = child | |
def get_random_entity(self): | |
return self.population[int(random.random() * random.random() * len(self.population))] | |
if __name__ == "__main__": | |
target = "Hello World" | |
pop_size = 20 | |
if len(sys.argv) >= 2: | |
target = sys.argv[1] | |
if len(sys.argv) >= 3: | |
pop_size = int(sys.argv[2]) | |
print "Evolving to '%s' with a population of %d" % (target, pop_size) | |
generation_count, entity = Evlover(target, pop_size).evolve() | |
print "Evolution done. Evolved to target '%s' in %d generations." % (entity.dna, generation_count,) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment