Created
March 25, 2014 19:14
-
-
Save luizirber/9769068 to your computer and use it in GitHub Desktop.
Fluctuating environment
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
import random | |
RESOURCES = [0, 1] | |
GENE_MUTATION_RATE = .05 | |
POPULATION_SIZE = 20 | |
NUMBER_OF_GENERATIONS = 100 | |
class Org(object): | |
def __init__(self, genes): | |
self.genes = genes | |
def __repr__(self): | |
return "Org(" + str(self.genes) + ")" | |
def replicate(self): | |
return Org(list(self.genes)) | |
def mutate(self): | |
self.mutate_genes() | |
def mutate_genes(self): | |
for i in range(len(self.genes)): | |
if random.random() < GENE_MUTATION_RATE: | |
self.genes[i] = random.choice([0, 1]) | |
def selection(pop, environment): | |
survivors = [] | |
for org in pop: | |
if any(o == e for (o, e) in zip(org.genes, environment) if e == 1): | |
survivors.append(Org(org.genes[:])) | |
if not survivors: | |
print 'DEAD!' | |
return survivors | |
def fill_in_population(pop): | |
while len(pop) < POPULATION_SIZE: | |
lucky = random.choice(pop) | |
pop.append(lucky) | |
def mutate_population(pop): | |
for org in pop: | |
org.mutate() | |
initial_genes = [0, 1] | |
org = Org(initial_genes) | |
pop = [org] | |
fill_in_population(pop) | |
env = [1, 0] | |
for gen in range(NUMBER_OF_GENERATIONS): | |
if gen % 50 == 0: | |
env[0], env[1] = env[1], env[0] | |
print [p.genes[0] == p.genes[1] for p in pop].count(True) | |
print env | |
pop = selection(pop, env) | |
fill_in_population(pop) | |
mutate_population(pop) | |
from pprint import pprint | |
pprint(pop) | |
print [p.genes[0] == p.genes[1] for p in pop].count(True) | |
print env |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment