def mate(pop1,pop2,loci):
    #print "mating\n"
    offspring = Population(); 
    #fill in fields that identify the offspring's contributing ancestor populations. 
    offspring.contributors = [pop1,pop2]
    offspring.allancestors = pop1.allancestors + pop2.allancestors; 
    offspring.probs=dict() 
    prob1,prob2 = find_crossover_probs(pop1,pop2); 
    #print "prob1:" + str(prob1)+"\n" 
    #print "prob2: "+ str(prob2)+"\n" 
    #print "pop1 probs:"+str(len(pop1.probs)) 
    #print "pop2 probs:"+str(len(pop2.probs)) 
    for l in loci: 
        if (l not in pop1.probs.keys()) or (l not in pop2.probs.keys()): 
            continue
        randfloat = random(); 
        mutationprob=random(); 
        if randfloat < prob1:
            offspring.probs[l]=pop1.probs[l]; 
            if mutationprob < Params.mutation_rate: 
                offspring.probls[l]=1-offspring.probs[l] #mutate to the other allele 
        else: 
            offspring.probs[l]=pop2.probs[l]; 
            if mutationprob < Params.mutation_rate: 
                offspring.probs[l]=1-offspring.probls[l] 
    offspring.findFitness(); 
    #print "offspring: " +offspring.toString()+"\n" 
    #print "done mating" 
    return offspring; 
Example #2
0
def oneRun(constants, evaluation, sheet=None):
    """
	Performs one run of the experiment
	
	Parameters:
	
	-``constants``: Config settings for the EA from the config files specified at run time
	
	-``evaluation``: Fitness function.  From ``Fitness`` Module
	"""
    created = []
    if "popType" in constants:
        pop = Util.moduleClasses(Population)[constants["popType"]](constants)
    else:
        pop = Population.Population(constants)

    best, evals, lastImproved = Population.Individual(), 0, 0
    rowCounter = 0
    while evals < constants["evals"] and best.fitness < constants["maxFitness"]:
        try:
            child = pop.next()
        except StopIteration:
            break
        evaluation(child)
        evals += 1
        if best < child:
            lastImproved = evals
            created.append((evals, child.fitness, child))
            best = child
    print best.fitness
    return created
Example #3
0
def first_gen(possible_list, num_pop,goal):
    """

    :type possible_list: List of Integers
    """
    response = []
    ## This is done to resolve the scoping probles in Python
    for i in range(0,num_pop):
        response.append(Population([]))
    i = 0
    while i < num_pop:
        a_pop = []

        ## Create a population based off random numbers from the list
        for j in range(len(possible_list)):
            a_pop.append(possible_list[randint(0,len(possible_list)-1)])

        ## If the population is an 'unfit' population, e.g. it's greater than the goal
        ## Discard it and start anew.
        test = Population(a_pop)
        test.evalPop(fge,goal)

        if (test.getRatings() == 0):
            continue
        else:

            response[i].children=a_pop
        i = i+1

    return response
Example #4
0
 def __init__(self, screen):
     self.goal = [400, 10]
     self.boxSize = [800, 800]
     self.dotSize = 4
     self.screen = screen
     self.test = Population(100, self.dotSize, self.boxSize, self.screen,
                            self.goal)
Example #5
0
 def evolve_Population(self,myPop):
     
     newPopulation = Population(myPop.get_size(),False,"2")
     #Saving the most fittest from old population
     newPopulation.save_individual(0,myPop.get_Fittest())
     print(newPopulation.individuals)
     #selecting two random individual
     crossover_List = list(combinations(Population.individuals, 2))
     
     #checking crossover probability and generating cross over population
     for pair in crossover_List: 
         i=1
         test = random.randint(0,100)
         if(test<=75):
             print("CrossOVer positive")
             (indiv1, indiv2) = pair
             self.crossover(indiv1,indiv2,newPopulation)
             i +=1   
     
     print("Generation 1 :")
     print(newPopulation.individuals,len(newPopulation.individuals))
     #removing Duplicates using dictionary
     print(newPopulation.dict_pop,len(newPopulation.dict_pop))
     print(newPopulation.dict_fitness,len(newPopulation.dict_fitness))
     print(newPopulation.get_Fittest())
def selection(aPopulation, distanceArr):

    newPopulation = Population()
    aPopulation.calAllScores()
    mean = aPopulation.getAverage()
    print("average = ", mean)
    selected = 0

    sum = 0
    for x in aPopulation.getPopulation():
        if x[1] <= mean:
            print("rate = ", mean / x[1])
            sum += mean / x[1]
    print("sum = ", sum)

    for x in aPopulation.getPopulation():
        if x[1] <= mean:
            rate = mean / x[1]
            print("weight = ", rate / sum)
            weight_int = int(round(rate * 100 / sum))
            print("acutal weight = ", weight_int)
            selected += 1
            for y in range(weight_int):
                copy = list(x[0].getSeq())
                cities = CitySeq(copy)
                cities.calDistance(distanceArr)
                print("adding: ", cities, "\nsequence: ", cities.getSeq(),
                      "\ndistance: ", cities.getDistance())
                newPopulation.addIndividuals(cities)
    newPopulation.setSelected(selected)
    print("\ndone with selection\n")
    newPopulation.printPopulation()
    print("\ntotal individuals = ", len(newPopulation.individuals))
    newPopulation.calAllScores()
    return newPopulation
Example #7
0
def main_2():
    iter_max = 30

    Pop = Population(
        "AAAGGATCTTCTTGAGATCCTTTTTTTCTGCGCGTAATCTGCTGCCAGTAAACGAAAAAACCGCCTGGGGAGGCGGTTTAGTCGAAGGTTAAGTCAG"
    )
    Pop.evolve(iter_max, "Tournoi")
    def ButOptimizeClick(self):
        self.GetOptions()
#        self.PrintOptions()
        
        # Интерпретация пользовательского ввода.
        if self.nOfFunction == 1:
            self.OptFunction = QuadraticFunction
            self.toleranceRange = [[self.a1, self.b1]]
        elif self.nOfFunction == 2:
            self.OptFunction = RosenbrokFunction
            self.toleranceRange = [[self.a1, self.b1], [self.a2, self.b2]]
        elif self.nOfFunction == 3:
            self.OptFunction = MatyasFunction
            self.toleranceRange = [[self.a1, self.b1], [self.a2, self.b2]]
        
        self.FitnessFunction = FitnessFunction1
        if self.nOfCodingProcedure == 0:
            self.Encode = Dec2Gray
            self.Decode = Gray2Dec
        elif self.nOfCodingProcedure == 1:
            self.Encode = Dec2Bin
            self.Decode = Bin2Dec
        
        # Настраиваем класс Organism методом его метакласса Configure.
        Organism.Configure(self.OptFunction,                         # Оптимизируемая функция;
                           self.toleranceRange,                 # Ее ОДЗ;
                           self.nOfGenes,                       # Число генов организма;
                           self.FitnessFunction,                # Его фитнес-функция;
                           self.Encode,                         # Функция кодирования признака;
                           self.Decode,                         # Функция декодирования признака;
                           self.areCrossoverPointsDiffer,       # Различны ли точки кроссовера?;
                           self.areMutationPointsDiffer)        # Различны ли точки мутации?
       
       # Создаем популяцию организмов.
        pop = Population(Organism,                  # Класс организмов, населяющих популяцию;
                         self.nOfOrganisms,         # Число организмов, , населяющих популяцию;
                         self.crossoverProbability, # Вероятность кроссовера;
                         self.nOfCrossoverPoints,   # Число точек кроссовера;
                         self.mutationProbability,  # Вероятность мутации;
                         self.nOfMutatingPoints)    # Число точек мутации.
        
        
        
        
#        self.progressGeneration.setModal(True)
#        self.progressGeneration.show()
        self.progressGeneration.setMaximum(self.nOfGenerations-1)
        
        for i in range(self.nOfGenerations):
            pop.Generate()
            self.progressGeneration.setValue(i)
        
        self.lblx.setText('x* = ' + str(pop[0].argopt()))
        self.lblfx.setText('f(x*) = ' + str(pop[0].opt()))
        
        pop.listInfo.append(['x* =' , pop[0].argopt()])
        pop.listInfo.append(['f(x*) = ', pop[0].opt()])
        
        self.SaveIntegralInfoToFile('SystemInfo.txt', pop.listInfo)
Example #9
0
def main_4():
    lineList = [line.rstrip('\n') for line in open("./Data/plasmid_8k.fasta")]
    seq = ''.join(lineList[1:])
    pop_size = 20
    nb_gen = 4

    pop = Population(seq, pop_size)
    pop.evolve(nb_gen, selection_method="Tournoi", alpha=0.593879313130056)
Example #10
0
def test_draw_traited_2(file_name, methode_sele, nbiter, nbindiv):
    lineList = [line.rstrip('\n') for line in open(file_name)]
    seq = ''.join(lineList[1:])
    Pop = Population(seq, n=nbindiv)
    Pop.evolve(nbiter, selection_method=methode_sele)
    traj = Traj3D()
    traj.compute(seq, Pop._Get_Current_Best()[0])
    return traj
def train(population: Population, epochCount, input, output):
    """
        For a certain number of epochs, perform the following:
            1. Get the current best chromosome.
            2. Select 2 random parent chromosomes.
            3. Create an offspring(child) of those two selected.
            4. Perform a random mutation on the child.
            5. Replace the least fit member of the population with the child resulted above.
    :param population: The initial population
    :param epochCount: How many epochs to run the algorithms
    :param input: the x variables
    :param output: the y variables to predict, based on the input
    :return: None
    """
    population.eval(input, output)

    for epoch in range(epochCount):
        if epoch % FEEDBACK_EPOCH == 0:
            best = population.getBest()
            print("Epoch " + str(epoch) + " genotype: " + str(best.genotype) +
                  " loss: " + str(best.phenotype))
            if best.phenotype == 0:
                break

        male = population.selection()
        female = population.selection()
        off = population.XO(male, female)
        offM = population.mutation(off)

        offM.eval(input, output)
        population.replaceWorst(offM)
Example #12
0
 def test_set_get_pop(self):
     coils = GAutils.get_coils_from_excel()
     population1 = Population.Population(coils)
     population1.createInitial(GAutils.CONST_POPULATION_SIZE)
     pop1 = population1.getPop()
     population2 = Population.Population(coils)
     population2.createInitial(GAutils.CONST_POPULATION_SIZE)
     pop2 = population2.getPop()
     self.assertNotEqual(pop1, pop2)
     population2.setPop(pop1)
     pop2 = population2.getPop()
     self.assertEqual(pop1, pop2)
 def runCoexistence(self, N, r, d, K, b1, b2):
     timeUntilDeath = 0 
     survivor = 0
     population = Population(0, mutationON=False)
     population.addIndividual(r, d, N, b1, K, resident=True)
     population.addIndividual(r, d, N, b2, K, resident=False)
     while population.residentinvaderPresent():
         population.updatePopulation(1)
         timeUntilDeath += 1
     if population.residentPresent(): survivor = 1
     if population.invaderPresent(): survivor = 2
     return ma.log10(timeUntilDeath), survivor
Example #14
0
def grasp(a, n, pop):
    Cmin = pop.getMinModularity()
    Cmax = pop.getMaxModularity()
    Sol = Population(pop.graph, [])
    while (n > 0):
        RCL = calculRCL(pop, Cmin, Cmax, a)
        index_S = randRCL(RCL)
        if index_S == -1:
            index_S = random.randint(0, len(pop) - 1)
        Sol.addPartition(pop.partitionList[index_S])
        n -= 1
    return Sol
 def runInvasion(self, repetitions, delay, dataTime, N1, N2, r, d, K, b1, b2):
 #: Function for running the invasion 
 #: @param repetitions: repetitions
 #: @return: returns the fraction of runs  in which  the invader was successful
     invasion = 0
     for rep in range(0,repetitions):
         population = Population(0, mutationON=False)
         population.addIndividual(r, d, N1, b1, K, resident=True)
         population.updatePopulation(delay)
         population.addIndividual(r, d, N2, b2, K, resident=False)
         population.updatePopulation(dataTime)
         if population.invaderPresent(): invasion += 1.0
     return invasion / repetitions
Example #16
0
def main_6():
    lineList = [line.rstrip('\n') for line in open("./Data/plasmid_8k.fasta")]
    seq = ''.join(lineList[1:])
    pop_size = 30
    nb_gen = 20

    pop = Population(
        "AAAGGATCTTCTTGAGATCCTTTTTTTCTGCGCGTAATCTGCTGCCAGTAAACGAAAAAACCGCCTGGGGAGGCGGTTTAGTCGAAGGTTAAGTCAG",
        pop_size)
    pop.evolve_and_graph(nb_gen,
                         scaling=False,
                         alpha=0.593879313130056,
                         selection_method="Tournoi")
Example #17
0
class MonoObjectiveGA(Optimizer):

	def __init__(self, chromosome, resEval, penEval, fitnessEval, popSize, elitism):

		Optimizer.__init__(self)

		self.Chromosome = chromosome
		self.ResEval = resEval
		self.PenEval = penEval
		self.FitnessEval = fitnessEval
		self.PopulationSize = popSize
		self.Elitism = elitism
		self.SelectionOp = TournamentSelectionOperator(2, 2)
		self.RecombinationOp = DrunkRecombinationOperator()
		self.MutationOp = None
		self.Population = None

		self.PenEval.ConstraintPenalties.append(Penalty("LOWER_BOUND", "__SUCCESS__", 1.0, 1.0, 0.5))

	def Start(self, maxIter = 50):

		self.Population = Population()
		for i in range(self.PopulationSize):
			indi = self.Chromosome.Clone()
			indi.Randomize()
			self.Population.append(indi)

		self.ResEval.Evaluate(self.Population)
		self.PenEval.Evaluate(self.Population)
		self.FitnessEval.Evaluate(self.Population)
		self.Population.SortByFitness()

		for gen in range(maxIter):
			newPop = Population()
			newPop.extend(self.Population[:self.Elitism])
			for i in range(self.Elitism, len(self.Population)):
				selected = self.SelectionOp.Select(self.Population)
				offspring = self.RecombinationOp.Combine(selected)
				# FIXME: mutation?
				#self.MutationOp.Mutate(offspring)
				offspring.ClipWithinBounds()
				newPop.append(offspring)
			self.Population = newPop
			self.ResEval.Evaluate(self.Population)
			self.PenEval.Evaluate(self.Population)
			self.FitnessEval.Evaluate(self.Population)
			self.Population.SortByFitness()
			print "Generation %d" % (gen + 1)
			print self.Population[0]
			if self.PostIterationCallback != None:
				self.PostIterationCallback(gen, self.Population)
Example #18
0
def draw_traited(file_name, scaling, methode_sele, nbiter, nbindiv, Luck,
                 Puiss):
    """ Permet de tracer le brain d'adn avec la table des angles optimisée à partir d'un fichier fasta, mais également la convergence au fil des générations"""
    lineList = [line.rstrip('\n') for line in open(file_name)]
    traj = Traj3D()
    seq = ''.join(lineList[1:])
    Pop = Population(seq, n=nbindiv)
    Pop.evolve(nbiter,
               scaling=scaling,
               selection_method=methode_sele,
               luck_prob=Luck,
               puissance=Puiss)
    traj.compute(seq, Pop._Get_Current_Best()[0])
    traj.draw("sample.png")
Example #19
0
	def Start(self, maxIter = 50):

		self.Population = Population()
		for i in range(self.PopulationSize):
			indi = self.Chromosome.Clone()
			indi.Randomize()
			self.Population.append(indi)

		self.ResEval.Evaluate(self.Population)
		self.PenEval.Evaluate(self.Population)
		self.FitnessEval.Evaluate(self.Population)
		self.Population.SortByFitness()

		for gen in range(maxIter):
			newPop = Population()
			newPop.extend(self.Population[:self.Elitism])
			for i in range(self.Elitism, len(self.Population)):
				selected = self.SelectionOp.Select(self.Population)
				offspring = self.RecombinationOp.Combine(selected)
				# FIXME: mutation?
				#self.MutationOp.Mutate(offspring)
				offspring.ClipWithinBounds()
				newPop.append(offspring)
			self.Population = newPop
			self.ResEval.Evaluate(self.Population)
			self.PenEval.Evaluate(self.Population)
			self.FitnessEval.Evaluate(self.Population)
			self.Population.SortByFitness()
			print "Generation %d" % (gen + 1)
			print self.Population[0]
			if self.PostIterationCallback != None:
				self.PostIterationCallback(gen, self.Population)
Example #20
0
    def statistics(self):
        bestfitnesses = []
        for i in range(TEST_RUNS):
            self.population = Population(no=TEST_POP)
            for j in range(TEST_ITER):
                self.iteration()
            bestfitnesses.append(self.population.v[0].fittness(self.problem))
        bf = np.array(bestfitnesses)
        mu = bf.mean()
        sigma = bf.std()

        textstr = '\n'.join(
            (r'$\mu=%.2f$' % (mu, ), r'$\sigma=%.2f$' % (sigma, )))

        f, axarr = plt.subplots(1, 2, figsize=(10, 5))

        axarr[0].set_title("Results of " + str(TEST_RUNS) +
                           " runs with a population of " + str(TEST_POP))
        axarr[0].plot(np.array(range(len(bestfitnesses))),
                      bf,
                      c='r',
                      label="Fitness")
        axarr[0].set_xlabel("Run")
        axarr[0].set_ylabel("Fitness")
        axarr[0].legend(loc='upper right')
        props = dict(boxstyle='round', facecolor='w', alpha=0.5)
        axarr[0].text(0.05,
                      0.95,
                      textstr,
                      transform=axarr[0].transAxes,
                      fontsize=14,
                      verticalalignment='top',
                      bbox=props)

        self.population = Population()

        fitnesses = []
        for i in range(NO_ITER):
            self.iteration()
            fitnesses.append(self.population.v[0].fittness(self.problem))

        axarr[1].set_title("Variation of fitness in one run")
        axarr[1].plot(np.array(range(len(fitnesses))),
                      np.array(fitnesses),
                      c='r',
                      label="Fitness")
        axarr[1].set_xlabel("Iteration")
        axarr[1].set_ylabel("Fitness")
        axarr[1].legend(loc='upper right')
def generateTable():
    global logGens
    logGens = ""
    generationNumber = 1
    logGens += "\n> Generation # " + str(generationNumber) + "\n"
    population = Population.Population(POPULATION_SIZE)
    population.get_schedules().sort(key=lambda x: x.get_fitness(),
                                    reverse=True)
    logGens += str(displayMgr.print_generation(population))
    logGens += str(
        displayMgr.print_schedule_as_table(population.get_schedules()[0]))
    geneticAlgorithm = GeneticAlgorithm.GeneticAlgorithm()
    while (population.get_schedules()[0].get_fitness() != 1.0):
        generationNumber += 1
        logGens += "\n> Generation # " + str(generationNumber) + "\n"
        population = geneticAlgorithm.evolve(population)
        population.get_schedules().sort(key=lambda x: x.get_fitness(),
                                        reverse=True)
        logGens += str(displayMgr.print_generation(population))
        logGens += str(
            displayMgr.print_schedule_as_table(population.get_schedules()[0]))
    print("\n\n")

    root.destroy()
    last_gen = displayMgr.get_generated(population.get_schedules()[0])
    Generated_Table(last_gen)
    def get_baseline_maxmean(self, run_minutes, num_to_avg):
        print('Recording baseline intensity...\n')
        self.reset_time()
        args0 = copy.copy(self.args)
        args0.zernike_coeffs = [0]
        args0.num_masks = 1
        uniform_pop = Population.Population(args0,base_mask=self.base_mask,uniform=True)

        frame = 0
        times = []
        end_time = datetime.datetime.now() + datetime.timedelta(0,int(run_minutes*60))
        while datetime.datetime.now() < end_time:
            self.interface.get_output_fields(uniform_pop,repeat=num_to_avg)
            self.update_metrics(uniform_pop, 'initial',save_mask=False)
            times.append(datetime.datetime.now())
            frame += num_to_avg
            print('Time left:', end_time-datetime.datetime.now())

        self.save_path += '/baseline'
        os.makedirs(self.save_path, exist_ok=True)
        self.save_checkpoint()
        np.savetxt(self.save_path+'/baseline_times.txt', np.asarray(times,dtype='datetime64[s]'), fmt='%s')
        self.save_plots()

        self.save_path = args0.save_path
        print('.....Done\n\n')
Example #23
0
def main(args):
    population_size = args.population
    inputs = [float(i) for i in args.inputs]
    output = [float(i) for i in args.output]
    mutation = args.mutation
    epochs = args.epochs

    population = pl.population_function_estimation(inputs, output, population_size, Mutation = mutation)
    if args.end_condition == 0:
        genetic_algorithm = gp.Genetic_programming(population, condition = gp.end_with_error_zero, iterations = epochs,
                                                iter_method = False)
    else:
        genetic_algorithm = gp.Genetic_programming(population, iterations = epochs, iter_method = True)

    best_fitness_per_epoch, average_fitness_per_epoch, best = genetic_algorithm.run()

    print("best error: ", best.get_fitness())
    print("average result: ", average_fitness_per_epoch[-1])
    time = [i for i in range(len(best_fitness_per_epoch))]
    plt.plot(time, best_fitness_per_epoch,label=  'best')
    plt.plot(time, average_fitness_per_epoch,label=  'average')
    plt.legend()
    plt.xlabel('Epochs')
    plt.ylabel('Fitness [Error]')
    plt.show()
Example #24
0
 def processPopulations(self):
     manager = mp.Manager()
     retDict = manager.dict()
     jobs = []
     for pop in self.populations:
         j = mp.Process(target=pop.processPopulation, args=(retDict, ))
         jobs.append(j)
         j.start()
     for j in jobs:
         j.join()
     self.newPopulations = []
     self.generationNumber += 1
     for pop in retDict.values():
         newPop = Population(pop.populationID, self.generationNumber,
                             cities_, pop.numberOfSpecimen, pop.type,
                             pop.tournamentSize, pop.p_m, pop.eliteSize,
                             pop.migrationSize, pop.specimen, pop.pmx,
                             pop.cx, pop.ox, pop.pmxEff, pop.cxEff,
                             pop.oxEff, pop.swap, pop.insert, pop.scramble,
                             pop.inversion, pop.swapEff, pop.insertEff,
                             pop.scrambleEff, pop.inversionEff)
         self.newPopulations.append(newPop)
     self.populations = self.newPopulations
     self.populations.sort(key=lambda x: x.populationID)
     pass
Example #25
0
 def encontrarSolucion(self):
     self.poblacion=Population.Population(POB_INICIAL)
     while((self.poblacion.getMejorIndividuo().getFitness() < sum(MAX_FITNESS)-ERROR_ACEPTABLE) and (self.poblacion.getNumeroGeneraciones()<MAX_GENERACIONES)):
         for x in self.poblacion.getGeneracionActual():
             print( x.getCromosomas(),x.getFitness())
             
         print('Fin GEN ',self.poblacion.getNumeroGeneraciones())
         #PARENT SELECION
         parents=self.poblacion.seleccionarParents()
         #CROSSOVER
         cruzar=random.random()
         offSprings=[]
         if(cruzar<PROB_CROSSOVER):
             offSprings=parents[0].crearOffSprings_UniformCrossOver(parents[1]) #dos nuevos miembros
             #offSprings=parents[0].crearOffSprings_OnePointCrossOver(parents[1]) #dos nuevos miembros
         #MUTATION
         #Se puede decidir si mutar todos los descendientes o toda la poblacion entera
         poblacionBase=self.poblacion.getGeneracionActual()
         for x in poblacionBase:
             x.mutar()
         #SURVIVOR SELECTION
         nuevaGen=self.seleccionarSobrevivientes(poblacionBase,offSprings)
         self.poblacion.actualizarGeneracion(nuevaGen)
         
 
 
 
     print('Fin en generacion numero:  ', self.poblacion.getNumeroGeneraciones())
     print('primer mejor individuo: ', self.poblacion.getPrimerMejorIndividuo().getCromosomas(),self.poblacion.getPrimerMejorIndividuo().getFitness())
  
     print(' mejor individuo: ', self.poblacion.getMejorIndividuo().getCromosomas(),self.poblacion.getMejorIndividuo().getFitness())
Example #26
0
def selection(popul, nb_best):
    """
    \Description : Select the best individuals of a population as well as random individuals from the rest of the population
    \Args : 
        popul   : the population of individual to evolve
        nb_best : number of best individuals to select
    \Outputs : 
        pop_next : The population of next generation
    """
    # Select the nb_best best individuals
    selected_indiv = popul.pop[0:nb_best]

    # Select 2/3 of the population so that the the last 1/3 is from the crossover
    nb_rand_indiv = (popul.size - len(selected_indiv)) - (popul.size // 3)

    # Select random individuals from the rest of the population
    selected_indiv.extend(sample(popul.pop[nb_best:], nb_rand_indiv))

    # Create the corresponding population
    pop_next = Pop.Population(dataset=popul.dataset,
                              size=len(selected_indiv),
                              NL_set=popul.NL_set,
                              NF_set=popul.NF_set,
                              lr_set=popul.lr_set,
                              mom_set=popul.mom_set,
                              indiv_list=selected_indiv,
                              train_loader=popul.train_loader,
                              test_loader=popul.test_loader,
                              train_batch_size=popul.train_batch_size,
                              test_batch_size=popul.test_batch_size)

    return pop_next
Example #27
0
    def __init__(self, numOfPointsVal, populationSizeVal, rootWindow,
                 controller):
        """Takes number of generations and Population() object"""
        self.pause = True
        self.stop = False
        # get random list
        listOfCities = rmg.genRandomListOfPoints(numOfPointsVal, 800, 400)
        # not use
        self.mutateRate = 0
        # how often will mutation occur
        self.mutateChance = 0.01
        self.populationSizeVal = populationSizeVal
        # population size must be even
        self.checkPopulationSize()

        self.population = population = Population.Population(
            self.populationSizeVal, listOfCities, self.mutateChance,
            self.mutateRate)
        self.event = mp.Event()
        controller.setEvent(self.event)
        controller.setForClossingEvent(self)
        pro = t.Thread(target=controller.genethicAlgorithmPart)
        pro.start()
        rootWindow.after(300, controller.addChangerListiner())
        controller.show_frame(CanvasFrame)
        controller.getCurrentTopFrame().updateFrame(
            self.population.bestSalesman.dna.getAsListOfTuple())
        print("After init EvolutionManager")
Example #28
0
    def run(self):
        # get user input before running program
        print(self.summary)
        self.num_cities = 10
        print(self.select_population_size)
        self.pop_size = int(input())
        print(self.select_mutation_rate)
        self.mutation_rate = float(input())
        print(self.generate_new_distances)
        self.generate = str(input())
        self.cities = Cities.Cities(self.num_cities)

        # use user input to create population object
        # and use them in the algorithm
        p = Population.Population(self.num_cities, self.pop_size,
                                  self.mutation_rate, self.cities)
        if self.generate == 'y':
            p.get_cities().generate_distances()
        else:
            p.get_cities().create_distances()

        for x in range(0, 1000):
            p.run_algorithm()
            # top = p.get_population()[0]
            # print("First place is: ", top, " with ", top.get_fitness())
        for x in range(0, self.pop_size - 1):
            print(p.get_population()[x], " with ",
                  p.get_population()[x].get_fitness())
Example #29
0
	def evolve_population(self, pop):
		new_population = Population.Population(pop.get_population_size(), False, self.tm)

		# Keep our best individual if elitism is enabled
		elitism_offset = 0
		if self.__elitism:
			new_population.save_tour(0, pop.get_fittest())
			elitism_offset = 1

		# Crossover population
		# Loop over new population's size and creates individuals from current population
		for i in range(elitism_offset, new_population.get_population_size()):
			# Select parents
			parent_1 = self.tournament_selection(pop)
			parent_2 = self.tournament_selection(pop)

			# Crossover parents
			child = self.crossover(parent_1, parent_2)

			# Add child to new population
			new_population.save_tour(i, child)

		# Mutate the new population a bit to add some new genetic material
		for i in range(elitism_offset, new_population.get_population_size()):
			self.mutate(new_population.get_tour(i))

		return new_population
 def test_Population_Constructor_Is_Valid(self):
     """
     Test the validity of the Population constructor
     """
     pops = p.Populations(self.__n_pop, self.__n_vars, self.__cost_func,
                          self.__domain_bounds)
     self.assertIsNotNone(pops, self.__test_msg)
Example #31
0
def testing_the_algorithm_total_and_best_improvement(coils):
    """
    This method used for research and debug purposes
    :param coils: the coils from the excel file
    :return: NONE
    """
    population = Population.Population(coils)
    population.createInitial(CONST_POPULATION_SIZE)
    best_improve = []
    total_improve = []
    for i in range(CONST_GENERATIONS):
        population.updateGenesRange()
        selected = rouletteSelection(population)
        offspring = crossover(selected[0], selected[1])
        c1 = offspring[0]
        c2 = offspring[1]
        c1 = mutate(c1)
        c2 = mutate(c2)
        c1.evaluate(c1.getSequence(), Steel.calculate_max_penalty(),
                    population.coils)
        c2.evaluate(c2.getSequence(), Steel.calculate_max_penalty(),
                    population.coils)
        population = replacement_elitism(population, offspring[0],
                                         offspring[1])
        population.update_fitness()
        best = population.get_best_solution()
        best_improve.append(best[1])
        total_improve.append(population.getFitness())
    save_data_to_excel_self_and_total_improve(best_improve, total_improve)
Example #32
0
 def create_initial_population(self):
     population = Population()
     for _ in range(self.num_of_individuals):
         individual = self.problem.generateIndividual()
         self.problem.calculate_objectives(individual)
         population.population.append(individual)
     return population
Example #33
0
File: App.py Project: pamhrituc/AI
def main():
    while True:
        prob = Problem()  #create problem
        size = prob.loadData(
            "data01.in")  #load data of problem, return board size
        x = Individ([0] * size)
        pop = Population(x)
        alg = Algorithm(pop)
        alg.readParameters("param.in")
        printMainMenu()
        x = input()
        if x == "1":
            bestX, sample = alg.run()
            print(bestX)
            print(bestX.fitness())
            plt.plot(sample)
            # function to show the plot
            plt.show()
        if x == "2":
            alg.run()
            sd, m = alg.statistics()
            print("Standard deviation " + str(sd))
            print("Mean " + str(m))
        if x == "0":
            return
Example #34
0
def main(args):
    if (args.resume) > 0:
        # print("loading file: population_{:d}.pickle".format(args.resume))
        population = load_element(args.output_dir,
                                  'population_{:d}.pickle'.format(args.resume))
    else:
        manager_BCCD = dm.Filter_processor()
        population = Population.population_filters(
            manager_BCCD,
            cg.filters_per_layers,
            n_population=int(args.population),
            Mutation=float(args.mutation))

    if int(args.samples_train) > -1:
        population.set_training_dataset_size(int(args.samples_train))
    if args.resume > 0:
        genetic_algorithm = Genetic_algotihm(population,
                                             iterations=args.epochs -
                                             args.resume,
                                             iter_method=True)
    else:
        genetic_algorithm = Genetic_algotihm(population,
                                             iterations=args.epochs,
                                             iter_method=True)

    best_samples, average, best = genetic_algorithm.run()
    save_element(args.output_dir,
                 'population_{:d}.pickle'.format(int(args.epochs)),
                 genetic_algorithm.population)
    print("best: ", best.get_fitness())
    print("averge result: ", average)
    for i in range(len(best_samples)):
        print("winner results is: ", best_samples[i].get_fitness())
    print("averge result: ", average)
def main(argv):
    filename = ''
    crossover_methods = []
    max_iterations = 1000
    pop_size = 500
    stop = False

    try:
        opts, args = getopt.getopt(argv, 'hf:i:p:t:s', [
        'help',
        'file=',
        'max-iterations',
        'population',
        'type=',
        's'
    ])
    except getopt.GetoptError:
        usage()
        sys.exit(2)
    for opt, arg in opts:
        if opt in ('-h', '--help'):
            usage()
            sys.exit()
        elif opt in ('-f', '--file'):
            filename = arg
            settings.init(filename)
        elif opt in ('-i', '--max-iterations'):
            max_iterations = int(arg)
        elif opt in ('-p', '--population'):
            pop_size = int(arg)
        elif opt in ('-t', '--type'):
            crossover_methods = arg.split(',')
        elif opt in ('-s', '--stop'):
            stop = True

    start_time = time.time()
    for method in crossover_methods:
        P = Population(pop_size)
        for i in range(max_iterations):
            try:
                P.evolve(method)
            except KeyError, e:
                usage()
                sys.exit()
            update_progress(i * 100 / max_iterations, P)
            if stop == True:
                if P.get_best_fitness() <= 0.001: break
        update_progress(100, P)
        print ''
        print 'processing time: {}'.format(time.time() - start_time)
        print ''
        P.result()
Example #36
0
File: Main.py Project: 17tangs/CPP
    def main(self):
        ##create a population class using Population.py
        #p = Population()
        ##generate the population based on the greedy algorithm
 ##       p.greedy(0)
        #for i in range(10):
            #p.greedy(i)
        ##generate a certain number of random solutions
        #p.add_random(950)
        ##call and print the statistics of the iteration
        #averages = []
        #bests = []
        #worsts = []
        #for i in range(CPP.I):
            #averages.append(p.average)
            #bests.append(p.best)
            ##worsts.append(p.worst)
            #p.breed(1)#wp1, wp2, ws1, ws2, rp, sp)
        size = [2,4,6,8,12,24]
        A = []
        B = []
        for j in range(1):
            p1 = Population()
            for i in range(10):
                p1.greedy(i)
            p1.add_random(950)
            a1 = []
            b1 = []
            for i in range(CPP.I):
                a1.append(p1.average)
                b1.append(p1.best)
                p1.breed(size[j])
            A.append(a1)
            B.append(b1)
            print p1.stat()
            self.stat(A,B,size)
            self.draw(p.pop)
 def runMutationdevelopment_independentPopulations(self, N, r, d, K, b1, b2, m):
     bValues = np.zeros((15000,3))
     time = 1
     resultPosition = 0
     population1 = Population(m, mutationON=False)
     population1.addIndividual(r, d, N, b1, K, resident=True)
     population2 = Population(m, mutationON=False)
     population2.addIndividual(r, d, N, b2, K, resident=True)
     while time <= 30000:
         population1.updatePopulation(1)
         population2.updatePopulation(1)
         if time % 100 == 1: 
             bValues[resultPosition] = [time, population1.getAverageB(), population2.getAverageB()]
             resultPosition += 1
         time += 1
     population1.mutationON = True
     population2.mutationON = True
     while time <= 150000:
         population1.updatePopulation(1)
         population2.updatePopulation(1)
         if time % 100 == 1: 
             bValues[resultPosition] = [time, population1.getAverageB(), population2.getAverageB()]
             resultPosition += 1
         time += 1
     return bValues
Example #38
0
print "Loading", sys.argv[1], "similarity matrix..."
cost_mat = load(sys.argv[1])
#cost_mat = genfromtxt(data_path + '/cost-matrices/' + sys.argv[1])

""" Compute the bullseye score.
    Assuming MPEG-7 data is loaded
"""
e = Evaluation(cost_mat, 20, 70)
print "Top 40 bullseye score: ", e.bullseye(40)

""" Compute a new similarity matrix using dice coefficient
    as a population cue
"""
#Geometric mean, to ensure symmetry
cost_mat = sqrt(cost_mat * cost_mat.transpose())
p = Population(cost_mat, 20, 70, verbose=True)
#Not setting k will attempt to automatically find it!
processed_matrix = p.generate_diff(k=13) 

e = Evaluation(processed_matrix, 20, 70)
print "Top 40 bullseye score using dice: ", e.bullseye(40)

""" Update the similarity matrix further using the previous
    matrix to build components 
"""
c = Components(processed_matrix)
c.get_components(0.3, strongly_connected=False)
comp_mat = c._expand_component_difference()

e = Evaluation(comp_mat, 20, 70)
print "Top 40 bullseye score after components: ", e.bullseye(40)
Example #39
0
File: LgpMain.py Project: nahu/lgp
def deme_evolve(population):
    """Se reinician los indices, para hacer coincidir cada individuo.index con su posicion en internal_pop"""
    population = resetIndex(population)
    for gen in range(Parameters.gen_to_migrate):
        to_tournament = []
        """Se seleccionan pool_size*2 diferentes posiciones en la poblacion para el torneo"""
        selected_indices = population.indices_selection(Parameters.pool_size * 2)

        to_tournament_indices = []
        to_tournament_indices.append(selected_indices[: Parameters.pool_size])
        to_tournament_indices.append(selected_indices[Parameters.pool_size :])
        to_tournament.append(population.selection_from_indices(to_tournament_indices[0]))
        to_tournament.append(population.selection_from_indices(to_tournament_indices[1]))

        # iter_result = population.pool.imap(Population.tournament_with_mutation, to_tournament, Parameters.chunk_size)
        winners = []
        """ ********************************* MUTACION  *********************************"""
        for i in range(2):
            """ Se retorna una lista de la siguiente forma: [modificado, no_modificado] """
            result = Population.tournament_with_mutation(to_tournament[i])
            winners.append(result)
            # winners.append(iter_result.next())

        """ ********************************* CROSSOVER *********************************"""
        if Util.random_flip_coin(Parameters.p_crossover):
            sister, brother = Population.crossover(winners[0][0], winners[1][0])
            Individual.check_destination_register(sister)
            Individual.check_destination_register(brother)

            if not sister.index == winners[0][0].index:
                winners[0][0] = brother
                winners[1][0] = sister

            if not Population.check_out_register(winners[0][0]) or not Population.check_out_register(winners[1][0]):
                print "ERROR: [LgpMain.deme_evolve]: El crossover dejo individuos sin registros de salida."

        for i in range(2):
            """ Se elimina de la lista de participantes del torneo al ganador, para remplazar a los perdedores"""
            try:
                del to_tournament_indices[i][to_tournament[i].index(winners[i][1])]
            except:
                print "ERROR: [LgpMain.deme_evolve]: Error al eliminar el indice del ganador del torneo " + str(i)

            """ best_replace = index_of_best([modificado, no_modificado])"""
            best_replace = 0 if Individual.compare(winners[i][0], winners[i][1]) == 1 else 1
            worst_replace = 1 if best_replace == 0 else 0

            """ Se remplaza los perdedores por el mejor entre (ganador modificado, ganador NO modificado)
            y se actualizan los indices dentro de la población """
            for l in to_tournament_indices[i]:
                indice = population.internal_pop[l].index
                population.internal_pop[l] = winners[i][best_replace].clone()
                population.internal_pop[l].index = indice
            """
            Como ya se remplazo a los perdedores por el mejor, se remplaza al ganador por el peor. Hay mas copias del mejor.
            """
            population.internal_pop[winners[i][0].index] = (
                winners[i][worst_replace].clone().set_index(winners[i][0].index)
            )

    """Se ordena la población de mayor a menor, según el error promedio o la desviación típica
    según una cierta probabilidad"""
    if Util.random_flip_coin(Parameters.p_migration_criteria):
        (population.internal_pop).sort(cmp=Individual.compare_error_prom, reverse=True)
    else:
        (population.internal_pop).sort(cmp=Individual.compare_deviation_in_error, reverse=True)

    for i in population.internal_pop:
        if not i.evaluated:
            print "ERROR: METODO DE ORDENACION FALLO."

    return population
 def runMutationdevelopment_coexistingCommunity(self, N, r, d, K, b1, b2, m):
     bValues = np.zeros((15000,3))
     time = 1
     resultPosition = 0
     population = Population(m, mutationON=False)
     population.addIndividual(r, d, N, b1, K, resident=True)
     population.addIndividual(r, d, N, b2, K, resident=False)
     while time <= 30000:
         population.updatePopulation(1)
         if time % 100 == 1: 
             bValues[resultPosition]= [time, population.getResidentAverageB(),population.getInvaderAverageB()]
             resultPosition += 1
         time += 1
     population.mutationON = True
     while time <= 150000:
         population.updatePopulation(1)
         if time % 100 == 1: 
             bValues[resultPosition] = [time, population.getResidentAverageB(),population.getInvaderAverageB()]
             resultPosition += 1
         time += 1
     return bValues
def main():
    
    # alphabet
    # first item of cities array is start and end point.
    cities = [ Gene("istanbul", 0, 0),
               Gene("ankara", 0, 1),
               Gene("izmir", 0, 2),
               Gene("antalya", 0, 3),
               Gene("erzurum", 0, 4),
               Gene("trabzon", 0, 5),
               Gene("gaziantep", 0, 6),
               Gene("bursa", 0, 7),
               Gene("artvin", 0, 8)]

    # keep bests
    ELITISM = True
    ELITISM_OFFSET = 3
    
    # other constants
    GENERATION = 50
    MUTATION_RATE = 0.05
    POPULATION_SIZE = 50
    CHROMOSOME_SIZE = len(cities) + 1

    # create population instance
    traveling_salesman = Population(cities)
    
    # create initial population
    traveling_salesman.populate(POPULATION_SIZE)

    # evolve
    generation_count = 0
    while generation_count < GENERATION:
      
      index = 0
      new_generation = []
      
      for individual in traveling_salesman.population:
        
        new_individual = crossover(individual)
        
        if random.uniform(0.0, 100.0) <= MUTATION_RATE:
          mutate(new_individual)
        
        new_generation.append(new_individual)

        index += 1
      
      # append new individuals to the population
      for x in new_generation:
        traveling_salesman.add_individual(x)

      traveling_salesman.order_by_fit()
      traveling_salesman.delete_unfit_individuals(POPULATION_SIZE)

      generation_count += 1
      print traveling_salesman.get_fittest().fitness

    best = traveling_salesman.get_fittest()

    for i in best.genes:
      print i.name

    print "Shortest path : " + str(best.fitness)