Esempio n. 1
0
def main():
    plot_data_score = []
    plot_data_nrj = []
    plot_data_range = []
    plot_data_variance = []
    population = generate_population(N)
    generation = [Individu(element_str) for element_str in population]
    for g in range(GENERATIONS):
        # On monitor notre génération avant de la renouveller
        totalscore = 0
        generation = [Individu(element_str) for element_str in population]
        max_nrj = maxnrj(generation)
        for element in generation:
            totalscore += evaluate(element, max_nrj)
        plot_data_score.append(totalscore / len(generation))
        plot_data_nrj.append(avgnrj(generation))
        plot_data_range.append(avgrange(generation))
        plot_data_variance.append(variance(generation, max_nrj))
        # Puis on renouvelle une generation
        population = new_generation(generation)
        print('\r' + str(int(g / GENERATIONS * 100)) + "% done", end='')

    max_nrj = maxnrj(generation)
    major = best(generation)
    # Debug
    print("BEST ELEMENT : ")
    print_element(major, max_nrj)
    # End debug
    plot.figure(1)
    plot.subplot(221)
    plot.plot(plot_data_score)
    plot.xlabel("Generation")
    plot.ylabel("Fitness Score /100")
    plot.subplot(222)
    plot.plot(plot_data_nrj)
    plot.xlabel("Generation")
    plot.ylabel("Energy: TNT")
    plot.subplot(223)
    plot.plot(plot_data_range)
    plot.xlabel("Generation")
    plot.ylabel("Range: m")
    plot.subplot(224)
    plot.plot(plot_data_variance)
    plot.xlabel("Generation")
    plot.ylabel("Fitness variance")

    plot.subplots_adjust(top=0.97, bottom=0.12,
                         left=0.14, right=0.92, hspace=0.25,
                         wspace=0.61)
    plot.show()
    return 0
Esempio n. 2
0
    def run(self):
        generation = 0
        fitness_max = 0
        populations = []

        for i in range(self.population_number):
            new_pop = self.initialize_population()
            populations.append(new_pop)

        while generation <= self.merge:
            index = 0
            for i in populations:
                for j in i:
                    j.compute_fitness()
                best_pop = self.selection(i)
                cross_pop = self.cross_over(best_pop)
                new_generation = []
                for k in cross_pop:
                    phenotype = self.adn.update_phenotype(k)
                    individu = Individu(k, phenotype)
                    new_generation.append(individu)
                populations[index] = new_generation
                index += 1
            generation += 1

        for i in populations:
            self.individus += i

        print("Merged")
        while fitness_max != 1:
            self.compute_fitness_pop_final()
            fitness_max, best_phenotype, best_genotype = self.fitness_max()
            best = self.selection(self.individus)
            new_genotypes = self.cross_over(best)
            self.individus.clear()
            for i in new_genotypes:
                phenotype = self.adn.update_phenotype(i)
                individu = Individu(i, phenotype)
                self.individus.append(individu)
            generation += 1
            if generation == 1000:
                break
        if fitness_max == 1:
            print('Solution found after ', generation, ' generations')
            return 1, generation
        else:
            print('No solution found before 1000 generations, max fitness : ',
                  fitness_max)
            return -1, -1
Esempio n. 3
0
 def _first_generation(self):
     generation = []
     for i in range(0, self._nb_individus):
         generation.append(Individu())
     # Tri des individues, le meilleur fitness en haut
     generation.sort(key=lambda individu: individu.fitness, reverse=True)
     return generation
Esempio n. 4
0
 def initialize_population(self):
     population = []
     for i in range(self.pop):
         phenotype = self.adn.generate_phenotype()
         genotype = self.adn.generate_genotype(phenotype)
         individu = Individu(genotype, phenotype)
         population.append(individu)
     return population
Esempio n. 5
0
def initPopulation():
	individu = []

	for i in range(c.jml_individu):
		value = Individu(randomizerKromosom())
		individu.append(value)

	return individu
Esempio n. 6
0
def get_fields():
    """retrieves the fields from tkinter to store them"""
    firstname = widgets_entry["firstname"].get()
    firstname = Individu(widgets_entry["name"].get(),
                         widgets_entry["firstname"].get(),
                         widgets_entry["phone"].get(),
                         widgets_entry["adress"].get(),
                         widgets_entry["city"].get())
    if firstname not in individuals:
        individuals.append(firstname)
    def crossover(self, ind1, ind2):
        fils = Individu(self.nb_e, self.nb_s, self.lastIndId)
        self.lastIndId += 1
        #On fait le croisement des genomes dans un premier temps
        plusGrdInnov = max(max(ind1.genome.connexions), max(ind2.genome.connexions))
        plusFort = ind1.sharedFitness > ind2.sharedFitness
        if plusFort:
            champ = deepcopy(ind1)
        else:
            champ = deepcopy(ind2)
        fils.phenotype = champ.phenotype
        fils.idToPos = champ.idToPos
        
        for i in range(plusGrdInnov+1):
            ind1con = ind1.genome.connexions.get(i, None)
            ind2con = ind2.genome.connexions.get(i, None)
            if ind1con == None and ind2con == None:
                pass
            elif ind1con != None and ind2con != None:
                c = copy(ut.randomPick([ind1con, ind2con]))
                #Ici on dans le cadre de deux connexions de meme indice d'innov
                if not(ind1con.activation) or not(ind2con.activation) : 
                    #On a une probabilité "prob.crossover.activation" d'activer
                    #les connexions désactivés dans les parents
                    if rand.random() < prob.crossover.activation:
                        c.activer()
                    else : 
                        c.desactiver()
                        
                fils.genome.connexions[i] = c
                fils.phenotype.modifierConnexion(c.entree, c.sortie, champ.idToPos, c.poids)
            #Les cas ici traitent les genes disjoints ou en excès
            elif ind1con == None:
                if not(plusFort):
                    fils.genome.connexions[i] = ind2con
                    fils.phenotype.modifierConnexion(ind2con.entree, ind2con.sortie, ind2.idToPos, ind2con.poids)
            elif ind2con == None:
                if plusFort:
                    fils.genome.connexions[i] = ind1con
                    fils.phenotype.modifierConnexion(ind1con.entree, ind1con.sortie, ind1.idToPos, ind1con.poids)

        fils.phenotype.reinit()
        return fils
    def crossover(self, ind1, ind2):
        fils = Individu(self.nb_e, self.nb_s, self.lastIndId)
        self.lastIndId += 1
        #On fait le croisement des genomes dans un premier temps
        plusGrdInnov = max(max(ind1.genome.connexions), max(ind2.genome.connexions))
        plusFort = ind1.sharedFitness > ind2.sharedFitness
        if plusFort:
            champ = deepcopy(ind1)
        else:
            champ = deepcopy(ind2)
        fils.phenotype = champ.phenotype
        fils.idToPos = champ.idToPos
        
        for i in range(plusGrdInnov+1):
            ind1con = ind1.genome.connexions.get(i, None)
            ind2con = ind2.genome.connexions.get(i, None)
            if ind1con == None and ind2con == None:
                pass
            elif ind1con != None and ind2con != None:
                c = copy(ut.randomPick([ind1con, ind2con]))
                #Ici on dans le cadre de deux connexions de meme indice d'innov
                if not(ind1con.activation) or not(ind2con.activation) : 
                    #On a une probabilité "prob.crossover.activation" d'activer
                    #les connexions désactivés dans les parents
                    if rand.random() < prob.crossover.activation:
                        c.activer()
                    else : 
                        c.desactiver()
                        
                fils.genome.connexions[i] = c
                fils.phenotype.modifierConnexion(c.entree, c.sortie, champ.idToPos, c.poids)
            #Les cas ici traitent les genes disjoints ou en excès
            elif ind1con == None:
                if not(plusFort):
                    fils.genome.connexions[i] = ind2con
                    fils.phenotype.modifierConnexion(ind2con.entree, ind2con.sortie, ind2.idToPos, ind2con.poids)
            elif ind2con == None:
                if plusFort:
                    fils.genome.connexions[i] = ind1con
                    fils.phenotype.modifierConnexion(ind1con.entree, ind1con.sortie, ind1.idToPos, ind1con.poids)

        fils.phenotype.reinit()
        return fils
Esempio n. 9
0
 def copulage(phrase1, phrase2):
     child_individu = None
     if len(phrase1) == len(phrase2):
         len_portion_left = int(random.randrange(len(phrase1)))
         new_phrase = phrase1[:len_portion_left -
                              1] + phrase2[len_portion_left - 1:]
         child_individu = Individu(proba_mutation, new_phrase)
     else:
         print("error: copulage(), not same length")
     return child_individu
Esempio n. 10
0
    def croisement(self):
        while not len(self._pop) == self._popSize:
            pat1 = self._selectRandomIndividu().patrimoine
            pat2 = self._selectRandomIndividu().patrimoine

            crossPoint = randint(1, 7)
            pat = pat1[:crossPoint] + pat2[crossPoint:]

            self._pop.append(deepcopy(Individu(pat, False)))
            self.noteIndi()
Esempio n. 11
0
def cloning(individu):
	newIndividu = []

	for i in range(len(individu)):
		kromosom = []

		for j in range(len(individu[i].kromosom)):
			temp_x = individu[i].kromosom[j].x
			temp_y = individu[i].kromosom[j].y
			valueKrom = Kromosom(temp_x,temp_y)
			kromosom.append(valueKrom)

		valueInd = Individu(kromosom)
		newIndividu.append(valueInd)

	return newIndividu
    def __init__(self, length, nb_e, nb_s):
        self.length = length
        self.contenu = [Individu(nb_e,nb_s, i) for i in range(length)]
        self.oldGen = []
        self.nb_e = nb_e
        self.nb_s = nb_s
        self.noeuds = [Noeud(i, "entree") for i in range(nb_e)]
        self.noeuds.extend([Noeud(i,"sortie") for i in range(nb_e, nb_e + nb_s)])
        self.generationCount = 0
        self.indiceInnovation = 0
        self.lastIndId = length
        self.lastEspId = 0
        self.averageFitness = None
        self.averageRawFitness = None
        self.historique = []
        self.especes = []
        self.histEspeces = []
        self.bestDisplay = 10
        self.best = []
#        self.especesFig, self.especesAx = plt.subplots(figsize=(20, 20*500/860))
        """Cette liste contiendra les différentes opérations génétiques structurelles
Esempio n. 13
0
def openfile():
    """opens a file and stores the elements in order to be accessed later"""
    filename = askopenfilename(parent=root)
    file = open(filename)
    lines = file.readlines()
    for line in lines:
        persons = line.split(":")

        for person in persons:
            if person == '':
                break

            characteristics = person.split(",")
            characteristics[1] = Individu(characteristics[0],
                                          characteristics[1],
                                          characteristics[2],
                                          characteristics[3],
                                          characteristics[4])

            if characteristics[1] not in individuals:
                individuals.append(characteristics[1])
Esempio n. 14
0
 def run(self):
     generation = 0
     fitness_max = 0
     self.initialize_population()
     while fitness_max != 1:
         self.compute_fitness()
         fitness_max, best_phenotype, best_genotype = self.fitness_max()
         print("Generation ", generation, "| Best fitness : ",
               fitness_max, " | Password : ",
               self.display_password(best_phenotype), ' | Size : ',
               len(best_phenotype))
         best = self.roulette_wheel_exponential()
         new_genotypes = self.cross_over(best)
         self.individus.clear()
         for i in new_genotypes:
             phenotype = self.adn.update_phenotype(i)
             individu = Individu(i, phenotype)
             self.individus.append(individu)
         self.x.append(fitness_max)
         self.plot_evolution(self.x)
         generation += 1
Esempio n. 15
0
def main():
    Individu().do_something()
    IndividuItineraire().do_something()
    Generation(500, proportion_elu=0.1).find_master_race(proba_mutation=0.9)
Esempio n. 16
0
 def initialize_population(self):
     for i in range(self.pop):
         phenotype = self.adn.generate_phenotype()
         genotype = self.adn.generate_genotype(phenotype)
         individu = Individu(genotype, phenotype)
         self.individus.append(individu)
Esempio n. 17
0
    def initGeneration(self, genes, rd=True):
        self._pop.clear()

        for a in range(self._popSize):
            self._pop.append(deepcopy(Individu(genes, rd)))
            self.noteIndi()