Exemple #1
0
 def __init__(self,num, max_population, mutationR):
     self.population=[dna(num) for i in range(max_population)]
     self.parents=[]
     self.generations=0
     self.finished=False
     self.mutation_rate=mutationR
     self.perfect_score=sum([i for i in range(num)])
     self.best=None
     self.calculate_fitness()
     self.mutations=0
    def __init__(self, p, m, num):
        self.population = []
        self.mating_pool = []
        self.target = p
        self.generations = 0
        self.finished = False
        self.mutation_rate = m
        self.perfect_score = 1
        self.best = ''

        for i in range(0, num):
            self.population.append(dna(len(self.target)))

        self.calc_fitness_population()
Exemple #3
0
 def breed(self):
     pool2 = np.array([dna(" ") for i in range(self.pop)])
     for i in range(0, self.pop, 2):
         # print(self.pool[i].SkiwFitness,end=",")
         p1 = random.random()
         p2 = random.random()
         while p1 == p2:
             p2 = random.random()
         p1 = self.selection(p1)
         p2 = self.selection(p2)
         h1 = p1.cross(p2)
         h2 = p2.cross(p1)
         mutchance = random.random()
         if mutchance <= self.rate:
             h1.mutate()
             h2.mutate()
         pool2[i] = h1
         pool2[i + 1] = h2
     self.pool = pool2
Exemple #4
0
    def advanceGeneration(self):
        matingPool = [
            p for p in self.phrases
            for _ in range(int(p.fitness(self.target) * 100))
        ]
        self.phrases = []
        for _ in range(self.populationSize):
            pA = random.choice(matingPool)
            pB = random.choice(matingPool)
            child = dna(self.size)
            child.crossover(pA, pB)
            child.mutate()
            self.phrases.append(child)

        goodGenes = [d for d in self.phrases if d.fitness(self.target) == 1]
        if (len(goodGenes) > 0):
            return True
        else:
            return False
    def mating_pool(self, mutation_rate):
        parents = []
        children = []
        length = len(self.target)
        count = 0
        i = 0

        # creating probability pool of highest ranking parents
        while(count < self.pop_size):
            if (self.pool[i].score == 0):
                parents.append(self.pool[i])
                count += 1
            else:
                for j in range(self.pool[i].score * 2):
                    parents.append(self.pool[i])
                    count += 1
            i += 1

        # take random parents and start creating children
        count = 0
        while (count < self.pop_size):
            choice_one = random.randint(0, self.pop_size-1)
            choice_two = random.randint(0, self.pop_size-1)
            child = dna(self.target)
            child.genes = parents[choice_one].genes[:length/2] + \
                parents[choice_two].genes[length/2:]

            # Add mutation rate
            mutate = random.randint(0, 9)
            if (mutate < mutation_rate * 10):
                # fill in random character
                child.genes[random.randint(0, length-1)] = chr(random.randint(32, 122))

            # add child to new generation
            children.append(child)
            count += 1

        return children
Exemple #6
0
if do("scroll"):
    GD.cold()
    scroll(GD)

if do("tiling"):
    GD.cold()
    tiling(GD)

if do("blocks"):
    GD.cold()
    blocks(GD)

if do("dna"):
    GD.cold()
    dna(GD)

if do("j1"):
    GD.cold()
    j1(GD)

if do("demos"):
    for d in ["ball", "chessboard", "asteroids", "manicminer"]:
        GD.cold()
        playback(GD, open("traces/" + d))
        GD.pause()

GD.cold()
GD.getbrush(Image.open("originals/atparty.png"))
GD.paint(0, 0)
cp = GD.charpal()
Exemple #7
0
 def randinit(self):
     temp = "".join(random.choices(char, k=self.length))
     return dna(temp)
 def generate_pool(self):
     population = []
     for i in range(self.pop_size):
         population.append(dna(self.target))
     return population
Exemple #9
0
import random
import math

from dna import dna


population = []
num_generations = 50
population_size = 20


# append the individuals for the initial population
for x in range(0, population_size):
	population.append(dna())

best = None

# iterates the number of generations
for x in range(0, num_generations):
	# iterates through the indvidiuals in population so that each goes through cross over
	# and mutation, creates a child population
    children_pop = []

    for individual in range(0, population_size):
        population[individual].evaluate()

        chance = random.random()

        if chance < .85:
		# cross over for parents
		    parent_one = random.choice(population)
Exemple #10
0
if do('scroll'):
    GD.cold()
    scroll(GD)

if do('tiling'):
    GD.cold()
    tiling(GD)

if do('blocks'):
    GD.cold()
    blocks(GD)

if do('dna'):
    GD.cold()
    dna(GD)

if do('j1'):
    GD.cold()
    j1(GD)

if do('demos'):
    for d in ['ball', 'chessboard', 'asteroids', 'manicminer']:
        GD.cold()
        playback(GD, open("traces/" + d))
        GD.pause()

GD.cold()
GD.getbrush(Image.open("originals/atparty.png"))
GD.paint(0, 0)
cp = GD.charpal()
Exemple #11
0
 def __init__(self, populationSize, target):
     self.populationSize = populationSize
     self.target = target.lower()
     self.size = len(target)
     self.phrases = [dna(self.size) for x in range(populationSize)]
# Read the dna sequence file-2 previously downloaded from NCBI.
dict_seq_2 = read_dna_seq('China_Seq_2019_Dec.txt')
# Modify the sequence with dummy 'N' nucleotide.
dict_seq_2 = gene_mod(dict_seq_2)

# Create matplotlib subplots for each gene.
f, ax = plt.subplots(nrows=11, ncols=3, figsize=(25, 30))
gene_name = list(numpy_image_dict.keys())
row = 0
col = 0
mut_dict = {}
for i in gene_name:
    G = i[5:]
    # Loop thru each gene in the Cornona Virus nucleotide sequence.
    gene_us = dna(dict_seq_1['gene=' + G][1])
    # Invoke the transcription method of the class dna
    gene_us.transcription()
    # Invoke the mothod that converts the gene sequence into a numpy array.
    numpfy_usa = gene_us.numpfy()
    # Reshape the numpy array with a predeifned shape from the numpy_image_dict dictionary.
    numpfy_usa = numpfy_usa.reshape(numpy_image_dict['gene=' + G][0])
    # sub-plot the numpy array with matplotlib pcolor method.
    ax[row][col].pcolor(numpfy_usa)
    ax[row][col].set_title(G + ' Gene - USA')
    col += 1
    gene_china = dna(dict_seq_2['gene=' + G][1])
    # Invoke the transcription method of the class dna
    gene_china.transcription()
    # Invoke the mothod that converts the gene sequence into a numpy array.
    numpfy_china = gene_china.numpfy()
Exemple #13
0
import random
import math

from dna import dna

population = []
num_generations = 50
population_size = 20

# append the individuals for the initial population
for x in range(0, population_size):
    population.append(dna())

best = None

# iterates the number of generations
for x in range(0, num_generations):
    # iterates through the indvidiuals in population so that each goes through cross over
    # and mutation, creates a child population
    children_pop = []

    for individual in range(0, population_size):
        population[individual].evaluate()

        chance = random.random()

        if chance < .85:
            # cross over for parents
            parent_one = random.choice(population)
            parent_two = random.choice(population)
            new_child = parent_one.crossover(parent_two)