Last active
January 25, 2016 22:22
-
-
Save naranjja/0578a7b0f216dfc11c74 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
import random, math | |
def decimal(binary): | |
inverse = [0] * len(binary) | |
decimal = [0] * len(binary) | |
value = 0 | |
for i in range(len(binary)): | |
inverse[i] = binary[len(binary)-1-i] | |
for i in range(len(inverse)): | |
if inverse[i] == 1: decimal[i] = (2 ** i) | |
if inverse[i] == 0: decimal[i] = 0 | |
for i in range(len(decimal)): | |
value = value + decimal[i] | |
return value | |
def fitness(x): | |
y = x * x | |
return y | |
def randomChromosome(genes): | |
chromosome = [0] * genes | |
chromosome = [random.randint(0, 1) for i in range(genes)] | |
return chromosome | |
def stochasticSelect(chromosomes, genes): | |
genome = [[] for i in range(chromosomes)] | |
decimal_list = [0] * chromosomes | |
fitness_list = [0] * chromosomes | |
expected_list = [0] * chromosomes | |
probability_list = [0] * chromosomes | |
total = 0 | |
partsum = 0 | |
expected_total = 0 | |
fathers = [] | |
mothers = [] | |
mothers_index = [] | |
fathers_index = [] | |
for i in range(chromosomes): | |
genome[i] = randomChromosome(genes) | |
decimal_list[i] = decimal(genome[i]) | |
fitness_list[i] = fitness(decimal_list[i]) | |
total = total + fitness_list[i] | |
if total == 0: | |
print "Genoma incompleto" | |
return 0 | |
average = round(float(total)/chromosomes, 2) | |
for i in range(chromosomes): | |
expected_list[i] = round(fitness_list[i]/float(average), 2) | |
if int(math.floor(expected_list[i])) > 0: | |
fathers.append(genome[i]) | |
fathers_index.append(i+1) | |
expected_list[i] = round(abs(math.floor(expected_list[i])-expected_list[i]),2) | |
expected_total = expected_total + expected_list[i] | |
for i in range(chromosomes): | |
probability_list[i] = round(expected_list[i]/float(expected_total), 2) | |
for i in range(chromosomes-len(fathers)): | |
rand = random.uniform(0,1) * expected_total | |
j = 0 | |
while True: | |
partsum = partsum + expected_list[j] | |
j = j + 1 | |
if (partsum > rand) or (j == genes): | |
break | |
mothers.append(genome[j-1]) | |
mothers_index.append(j) | |
print "" | |
print "Genoma:", genome | |
print "Valores:", decimal_list | |
print "Fitness:", fitness_list | |
print "Total:", total | |
print "Promedio:", average | |
print "" | |
print "Valores esperados:", expected_list | |
print "Total esperado:", expected_total | |
print "Probabilidad:", probability_list | |
print "" | |
print "Padres:", fathers_index | |
print "Madres:", mothers_index | |
print "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment