Пример #1
0
    def test_leniency(self):
        level = []
        level.append('X---------------')
        level.append('X---------------')
        level.append('X---------------')
        self.assertEqual(0, Fitness.leniency(level))

        level.append('X---------------')
        level.append('XE--------------')
        level.append('X---------------')
        self.assertEqual(0.5, Fitness.leniency(level))

        level.append('X---------------')
        level.append('X---------------')
        level.append('----------------')
        self.assertEqual(1.0, Fitness.leniency(level))

        level.append('X----------------')
        level.append('----XE-----------')
        level.append('X----------------')
        self.assertEqual(2.0, Fitness.leniency(level))

        level.append('X----------------')
        level.append('bBE--------------')
        level.append('X----------------')
        self.assertEqual(2.5, Fitness.leniency(level))
Пример #2
0
    def test_linearity(self):
        level = []
        level.append('X---------------')
        level.append('X---------------')
        level.append('X---------------')
        self.assertEqual(0, Fitness.linearity(level))

        level.append('X---------------')
        level.append('XE--------------')
        level.append('X---------------')
        self.assertEqual(0, Fitness.linearity(level))

        level = []
        level.append('B------')
        level.append('-S-----')
        level.append('XXX----')
        level.append('-------')
        level.append(']]]>E--')
        level.append('[[[>X--')
        level.append('-----Q-')
        level.append('------]')
        level.append('-------')
        self.assertEqual(0, Fitness.linearity(level))

        level.append('-------')
        level.append('--QE---')
        self.assertNotEqual(0, Fitness.linearity(level))
Пример #3
0
def get_inf_ind(horario, dic_notas, dic_horarios):
    value = Fitness.schdl_value(horario, dic_notas, dic_horarios)
    teacher_value = Fitness.schedule_teacher_score(horario, dic_notas,
                                                   dic_horarios)
    closeness = Fitness.closeness_score(horario)
    gap_value = closeness[0]
    conflict = closeness[1]
    dishom = -Fitness.dis_homogen_score(horario)
    return value, teacher_value, gap_value, conflict, dishom
Пример #4
0
def tournament_select(generation, pop_size):
    new_generation = []
    while pop_size > len(new_generation):
        individuals = []
        for _ in range(2):
            individuals.append(random.choice(generation))
        if (fit.individual_fitness_func(individuals[0]) >
                fit.individual_fitness_func(individuals[1])):
            new_generation.append(individuals[0])
        else:
            new_generation.append(individuals[1])
    return new_generation
Пример #5
0
    def evaluate_fitness(self, X_Data, Y_Data, Weights=None):

        # X_Data: np-array. Shape = (num_features, n_samples). Specifies the features of the samples.
        # Y_Data: np-array. Shape = (n_samples). These are the target values of n_samples.
        # Weights: np-array. Shape = (n_sample). Weights applied to individual sample

        Y_Pred = self.evaluate(X_Data)
        # Predicted values from the tree.
        fitness_function = Fitness.get_fitness_metric(self.fitness_metric)
        fitness = fitness_function(Y_Data, Y_Pred, Weights)
        self.fitness = Fitness.get_fitness_sign(self.fitness_metric) * fitness

        return self.fitness
Пример #6
0
    def main(self, option):
        overall_bestfit = []
        print("Please enter the  maximum number of runs:")
        maxruns = int(input())
        print("Please enter desired number of generations: ")
        gens = int(input())
        print("Enter Population size")
        self.population_size = int(input())
        capacity = 30
        run_fitnesses = []
        best_ind = []
        ks_run_values = []
        ks_run_weights = []
        ks_run_fitness = []
        for run in range(int(maxruns)):
            # print("Run Number %i" % run)
            generation = self.createPopulation(self.population_size,
                                               self.len_of_ind)
            #print(generation)
            run_fitnesses.clear()
            ks_weights, ks_values = self.initKnapSackVals()
            ks_run_weights += [ks_weights]
            ks_run_values += [ks_values]
            ks_final_fitness = []
            for gen in range(int(gens)):
                #print("---------------------------------------------------------------")
                fitness_values = fit.generation_fitness_func(generation)

                # KnapSack part of the problem
                ks_fitness = Knapsack.calc_fitness_dynamic(
                    ks_weights, ks_values, generation, self.population_size,
                    capacity)
                if option == "tournament":
                    generation = select.tournament_select(
                        generation, self.population_size)
                if option == "linear":
                    generation = select.linear_rank_select(
                        generation, fitness_values, self.population_size)
                if option == 'proportionate':
                    generation = select.proportionate_selection(
                        generation, fitness_values, self.population_size)
                generation = Crossover.random_crossover(
                    generation, self.len_of_ind, self.population_size)
                generation = self.mutation(generation, self.pm)
                ks_fitness = Knapsack.calc_fitness_dynamic(
                    ks_weights, ks_values, generation, self.population_size)
                ks_final_fitness = ks_fitness
                #print("Knapsack Fitness Values : \n{0}".format(ks_final_fitness))
            ks_run_fitness += [ks_final_fitness]
        print("-----------------------------------")
        print("Knapsack Capacity is {}".format(capacity))
        print("Weights over {} runs".format(maxruns))
        for i in range(len(ks_run_weights)):
            print(ks_run_weights[i])
        print("Values over {} runs".format(maxruns))
        for i in range(len(ks_run_values)):
            print(ks_run_values[i])
        print("Fitness over {} runs".format(maxruns))
        for i in range(len(ks_run_fitness)):
            print(ks_run_fitness[i])
Пример #7
0
def refinarRotas(population):
    fitnessResults = {}
    for i in range(0, len(population)):
        fitnessResults[i] = f.Fitness(population[i]).fitCalc(
        )  #para cada rota dentro da nossa população, calculamos o fitness
    return sorted(
        fitnessResults.items(), key=operator.itemgetter(1), reverse=True
    )  #retorna uma array com o ID da rota e o valor de Fitness da mesma, por ondem descrescente
Пример #8
0
def proportionate_selection(generation, fitness_values, pop_size):
    generation, fitness_values = Sort.sort(generation, fitness_values)
    new_generation = []
    max = 0
    fitness_values = fit.generation_fitness_func(generation)
    for value in fitness_values:
        max += value
    current = 0
    pick = random.uniform(0, max)
    while pop_size > len(new_generation):
        for individual in range(len(generation)):

            fitness = fit.countOnes(
                generation[individual]
            )  # countOnes function can calculate fitness for an individual
            current += fitness
            if current > pick:
                new_generation.append(generation[individual])
    return new_generation
Пример #9
0
def selection(pool, dic_notas, dic_horarios):
    values = []
    probs = []
    for horario in pool:
        value = Fitness.schdl_value(horario, dic_notas, dic_horarios)
        values.append(value)
    values = (np.array(displace_values(values)) + 0.001).tolist()
    tot_val = sum(values)
    for value in values:
        prob = value / tot_val
        probs.append(prob)
    rd_indv = pick_one(probs, pool)
    return rd_indv
Пример #10
0
def produceGeneration(population=Classes.Population()):

    new_population = Classes.Population()

    for x in range(population.populationLimit):

        newChild = CrossOverAndMutation.crossOver(population)

        Fit = Fitness.CalculateFitness(newChild)
        newChild.fitness = (Fit[0] + Fit[1] + Fit[2]) * -1

        new_population.chromosomeList.append(newChild)

    return new_population
Пример #11
0
def GenerateChromosome(Time_List):
    # create a chromosome consisting of multiple genes

    chromosome1 = Classes.Chromosome()

    CodeList.Time = Time_List

    for x in CodeList.course_database:

        timeList = []
        del timeList

        if (CodeList.course_database[x][2] == 0):

            timeList = SetTime.set_timing_for_class()

            chromosome1.geneList.append(
                Classes.ChromosomeGene(CodeList.course_database[x][0],
                                       CodeList.course_database[x][1],
                                       CodeList.course_database[x][3],
                                       CodeList.course_database[x][2],
                                       CodeList.course_database[x][4],
                                       random.randint(2, 7), timeList[0],
                                       timeList[1], random.randint(0, 4)))

        elif (CodeList.course_database[x][2] == 1):

            timeList = SetTime.set_timing_for_lab()
            chromosome1.geneList.append(
                Classes.ChromosomeGene(CodeList.course_database[x][0],
                                       CodeList.course_database[x][1],
                                       CodeList.course_database[x][3],
                                       CodeList.course_database[x][2],
                                       CodeList.course_database[x][4],
                                       random.randint(0, 1), timeList[0],
                                       timeList[1], random.randint(0, 4)))

    Clash_List = Fitness.CalculateFitness(chromosome1)
    chromosome1.fitness = (Clash_List[0] + Clash_List[1] + Clash_List[2]) * -1
    return chromosome1
Пример #12
0
def rerun(new_population, sol_per_pop, maximum_tank_mass, coeff_FL_it,
          coeff_FL_cost, coeff_FL_er, coeff_FL_m_dot, num_genes):

    # Defining the population size
    pop_size = (sol_per_pop, num_genes)
    num_parents_mating = 4
    toll = 2
    generation = 0
    condition1 = True
    Best_solution_size = (1, num_genes)
    Queens = numpy.zeros(Best_solution_size)
    Queens_add = numpy.zeros(Best_solution_size)
    colomn_size = (sol_per_pop)

    while 1:
        if toll == 0:
            condition1 = False
        if condition1 == True:
            zn = Data.parameters(new_population, colomn_size, sol_per_pop)
            V = Fitness.tank(new_population, zn)
            t = Fitness.tank_design(V, sol_per_pop, new_population, zn)
            empty_tank_mass = Fitness.empty_tank_mass(t, sol_per_pop,
                                                      new_population, zn)
            gas_size = (sol_per_pop, 1)
            gas_mass = numpy.zeros(gas_size)
            gas_mass[0:, 0] = new_population[0:, 3]
            full_tank_mass = empty_tank_mass + gas_mass
            m_diff = maximum_tank_mass - full_tank_mass
            parents_num = int(0.2 * sol_per_pop)
            performance_size = [sol_per_pop, 16]
            performance_matrix = numpy.zeros(shape=performance_size)
            EngineParameters = namedtuple('EngineParameters',
                                          'Tc Pc molar_m gamma Re er Ps')
            for j in range(0, sol_per_pop):
                T = new_population[j, 4]
                p_chamber = new_population[j, 5]
                p_storage = new_population[j, 2]
                Re = new_population[j, 6]
                er = new_population[j, 7]
                molar_mass = gas_mass[j] * 1000 / zn[j, 1]
                params = EngineParameters(Tc=T,
                                          Pc=p_chamber,
                                          molar_m=molar_mass,
                                          gamma=1.27,
                                          Re=Re,
                                          er=er,
                                          Ps=p_storage)
                performance = aero_solver.aerosolver(params)
                performance_matrix[j, 0] = performance.delta
                performance_matrix[j, 1] = performance.Re
                performance_matrix[j, 2] = performance.ht
                performance_matrix[j, 3] = performance.At
                performance_matrix[j, 4] = performance.er
                performance_matrix[j, 5] = performance.Pc
                performance_matrix[j, 6] = performance.Tc
                performance_matrix[j, 7] = performance.m_dot
                performance_matrix[j, 8] = performance.F
                performance_matrix[j, 9] = performance.Isp[-1]
                performance_matrix[j, 10] = performance.Pe
                performance_matrix[j, 11] = performance.Te
                performance_matrix[j, 12] = performance.Me
                performance_matrix[j, 13] = performance.Cf
                performance_matrix[j, 14] = performance.Ps
                performance_matrix[j, 15] = full_tank_mass[j]
            FL = Fitness.FL_calc_rerun(new_population, m_diff, sol_per_pop,
                                       parents_num, performance_matrix,
                                       coeff_FL_it, coeff_FL_cost, coeff_FL_er,
                                       coeff_FL_m_dot, coeff_FL_epsilon)
            fl = FL[:, 0] + FL[:, 1] + FL[:, 2]
            old_pop = numpy.copy(new_population)
            fl_max = numpy.where(fl == numpy.max(fl))
            fl_max_idx = fl_max[0][0]
            Queens[generation, :] = old_pop[fl_max_idx, :]
            Queens = numpy.r_[Queens, Queens_add]
            parents = GA.select_mating_pool(fl, sol_per_pop, parents_num,
                                            new_population, num_genes)
            offspring_size = [pop_size[0] - parents.shape[0], num_genes]
            offspring_crossover_rerun = GA.crossover(parents, offspring_size)
            new_population[0:parents.shape[0], :] = parents
            new_population[
                parents.shape[0]:sol_per_pop, :] = offspring_crossover_rerun
            numpy.random.shuffle(new_population)
            generation = generation + 1

            if generation > 10:
                toll1 = 0
                for i in range(2, 20):
                    toll_v = (Queens[Queens.shape[0] - i, :] -
                              Queens[Queens.shape[0] - (i + 1), :])
                    toll1 = toll1 + numpy.sum(toll_v)
                toll = toll1
        else:
            break

    fl_max = numpy.where(fl == numpy.max(fl))
    fl_max_idx = fl_max[0][0]
    Best_solution = old_pop[fl_max_idx]
    Best_performance = performance_matrix[fl_max_idx, :]

    Results = namedtuple(
        'Results',
        'Idx fl FL Propellant_Type Tank_Type Tank_material Tank_Dimensions Storage_Pressure gass_mass full_tank_mass Tank_temperature Chamber_Pressure delta Re ht At er Pc Tc m_dot F Isp Pe Te Me Cf Ps'
    )
    Final_results = Results(Idx=fl_max_idx,
                            fl=fl[fl_max_idx],
                            FL=FL[fl_max_idx],
                            Propellant_Type=Best_solution[0],
                            Tank_Type=Best_solution[1],
                            Tank_material=Best_solution[8],
                            Tank_Dimensions=t[fl_max_idx, :],
                            Storage_Pressure=Best_solution[2],
                            gass_mass=Best_solution[3],
                            full_tank_mass=Best_performance[15],
                            Tank_temperature=Best_solution[4],
                            Chamber_Pressure=Best_solution[5],
                            delta=Best_performance[0],
                            Re=Best_performance[1],
                            ht=Best_performance[2],
                            At=Best_performance[3],
                            er=Best_performance[4],
                            Pc=Best_performance[5],
                            Tc=Best_performance[6],
                            m_dot=Best_performance[7],
                            F=Best_performance[8],
                            Isp=Best_performance[9],
                            Pe=Best_performance[10],
                            Te=Best_performance[11],
                            Me=Best_performance[12],
                            Cf=Best_performance[13],
                            Ps=Best_performance[14])
    return Final_results
Пример #13
0
 new_population[0:,7] = numpy.random.randint(low=er_min,high=er_max, size=colomn_size)                   # Expansion Ratio
 new_population[0:,8] = numpy.random.randint(low=0,high=2, size=colomn_size)                             # Tank material:0=aluminum,1=stainless steel
 
 # The following lines are the initialization of the termination criterion, when the last n best solution are the same, toll = 0
 toll = 2
 generation=0
 condition1=True
 Best_solution_size = (1,num_genes)
 Queens = numpy.zeros(Best_solution_size)
 Queens_add = numpy.zeros(Best_solution_size)
 while 1:
     if toll==0:
         condition1=False       
     if condition1==True: 
         zn = Data.parameters (new_population,colomn_size,sol_per_pop)                                   # Matrix contaiing gas parameters R,M,Z
         V = Fitness.tank (new_population,zn)                                                            # Volume of the tank
         t = Fitness.tank_design(V,sol_per_pop,new_population,zn)                                        # Include both width and radii
         empty_tank_mass = Fitness.empty_tank_mass (t,sol_per_pop,new_population,zn)                     # Empty tank mass
         gas_size = (sol_per_pop,1)
         gas_mass=numpy.zeros(gas_size)
         gas_mass [0:,0] = new_population[0:,3]                                                          # Gas mass
         full_tank_mass = empty_tank_mass + gas_mass                                                     # Full tank mass
         m_diff= maximum_tank_mass - full_tank_mass
         
         # Initialization of the vectors for : performance evaluation and creation of the new generation
         
         parents_num = int(0.2*sol_per_pop)
         random_solutions = int(0.2*sol_per_pop)                                                         # 20% random solutions
         random_sol_shape = (random_solutions,num_genes)
         performance_size=[sol_per_pop,16]
         performance_matrix = numpy.zeros(shape=performance_size)
Пример #14
0
import GeneticAlgorithm as GA
import Fitness
import Ordenation
import Graphic

time = 720
chromosomeSize = time/10
generations = 50
mutationPercentage = 40
populationSize = 20
numberOfSelectedIndividuals = 12
pltBestFitness = []
pltFitnessAverage = []

# Main
population = GA.initialize_population(populationSize,chromosomeSize)
for i in range(generations):
    print "Generation: "+ str(i)
    fitnessvalues = Fitness.fitness(population,time)
    fitnessvalues,population = Ordenation.selectionsort(fitnessvalues,population)
    print "     Best fitness: "+str(fitnessvalues[0])
    print "     Fitness average: "+str(sum(fitnessvalues)/len(fitnessvalues))
    pltBestFitness.append(fitnessvalues[0])
    pltFitnessAverage.append(sum(fitnessvalues)/len(fitnessvalues))
    population = GA.selection(population, numberOfSelectedIndividuals)
    population = GA.uniformCrossover(population, populationSize, chromosomeSize)
    population = GA.mutation(population, mutationPercentage)

Graphic.printGraphic(pltBestFitness,pltFitnessAverage,generations)
Пример #15
0
    def main(self, option):
        overall_bestfit = []
        print("Please enter the  maximum number of runs:")
        maxruns = int(input())
        print("Please enter desired number of generations: ")
        gens = int(input())
        print("Enter Population size")
        self.population_size = int(input())

        run_fitnesses = []
        best_ind = []
        for run in range(int(maxruns)):
            # print("Run Number %i" % run)
            generation = self.createPopulation(self.population_size,
                                               self.len_of_ind)
            print(generation)
            run_fitnesses.clear()
            for gen in range(int(gens)):
                print(
                    "---------------------------------------------------------------"
                )

                #Genetic Algorithm part
                x1, x2, x3 = self.extract_genes(generation)
                fit_value = fit.calc_fitness_value(x1, x2, x3)
                run_fitnesses.append(fit_value)
                fitness_values = fit.generation_fitness_func(generation)

                if option == "tournament":
                    generation = select.tournament_select(
                        generation, self.population_size)
                if option == "linear":
                    generation = select.linear_rank_select(
                        generation, fitness_values, self.population_size)
                if option == 'proportionate':
                    generation = select.proportionate_selection(
                        generation, fitness_values, self.population_size)
                generation = Crossover.random_crossover(
                    generation, self.len_of_ind, self.population_size)
                generation = self.mutation(generation, self.pm)

            bor, vector = analyze.best_of_run(generation, run_fitnesses)
            self.best_of_runs += [bor]
            self.best_individuals += vector

            print("Best of run is %i" % bor)
            if self.exec_start == 0:
                overall_bestfit = bor
                self.exec_start = 1
            if bor < overall_bestfit:
                overall_bestfit = bor

        print("Best fitness over all runs is %i" % overall_bestfit)
        avg = analyze.mean(run_fitnesses)
        print("Average of all runs is %f" % avg)
        print("Best of run values:")
        print(self.best_of_runs)
        print("Standard deviation from {0} independent runs is {1}".format(
            maxruns, np.std(self.best_of_runs)))
        print("Best individuals: ")
        for each in range(len(self.best_individuals)):
            print(self.best_individuals[each])
Пример #16
0
 def goFitness(self):
     self.window = QtWidgets.QWidget()
     self.ui = Fitness.Ui_Dialog()
     self.ui.setupUi(self.window)
     self.window.show()
Пример #17
0
    #<editor-fold desc="Selection based on Fitness">

    if supressConsole == 0:
        print("##################################################")
        print("########           SELECTION STEP       ##########")
        print("##################################################")

        print("########           Before      ##########")
    #Assist.populationfitnessprnt(population, fitnessFunc)
    prunedPop = []

    pool = []
    while len(prunedPop) < N / 2:
        if gen % 10 == 0:
            prunedPop.append(
                Fitness.tournamentprob(population, tournamentSize, N - 1,
                                       fitnessFunc))
        else:
            prunedPop.append(
                Fitness.tournamentprob(population, tournamentSize, N - 1,
                                       fitnessFunc))

    #prunedPop = Fitness.selTournament(population, round(N/2), tournamentSize, fitnessFunc )
    #prunedPop = Fitness.selRoulette(population, round(N/2), fitnessFunc )

    #input("Press Enter to continue...")
    if supressConsole == 0:
        print("########           After      ##########")
    population = prunedPop
    # population = population[:int(N * percentParent)]
    #Assist.populationfitnessprnt(population, fitnessFunc)
Пример #18
0
        if(x.fitness>10):

            chr = x
            PrintFunctions.printChromosome(chr)
            flag = True
            break

    i=i+1

    if(flag==True):

       break



fit = Fitness.CalculateFitness(chr)
'''
for x in population.chromosomeList:
    if(x.fitness==0):
        PrintFunctions.printChromosome(x)
        fit = Fitness.CalculateFitness(chr)

        print(x.fitness)
        print("\n\n\n")

'''



'''
print("\n\n\n\n")
Пример #19
0
 def test_max_linearity(self):
     self.assertEqual(8 * 10 + 7 * 10, Fitness.max_linearity(20, 16))
Пример #20
0
 def __init__(self, chromosome):
     self.chromosome = chromosome
     self.fitness = Fitness.cal_fitness(chromosome, constants.TARGET)
Пример #21
0
result_train = data.get_result(matches)
training = data.vector('matches_train_2.csv')

# training data and testing data
matches_test = data.vector('test111.csv')
result_test = data.get_result(matches_test)
testing = data.vector('test222.csv')

ran = 20
best_gamma = [0] * ran
best_c = [0] * ran
best_fitness = [0] * ran

for loop in range(ran):
    pop = Genetic.initialize(pop, chromNodes, chromRange)
    pop = Fitness.calFitness(training, result_train, testing, result_test, pop)
    bestChrom = Genetic.findBest(pop)
    bestFitnessList.append(bestChrom[1])  # now best fitness
    aveFitnessList.append(Genetic.calAveFitness(pop, N))  # ave fitness

    for t in range(iterNum):
        pop = Genetic.mutChrom(pop, mut, chromNodes, bestChrom, chromRange)
        pop = Genetic.acrChrom(pop, acr, chromNodes)
        nowBestChrom = Genetic.findBest(pop)
        bestChrom = Genetic.compareChrom(nowBestChrom, bestChrom)
        worseChrom = Genetic.findWorse(pop)
        pop[worseChrom[0]].chrom = pop[bestChrom[0]].chrom
        pop[worseChrom[0]].fitness = pop[bestChrom[0]].fitness
        bestFitnessList.append(bestChrom[1])
        aveFitnessList.append(Genetic.calAveFitness(pop, N))
Пример #22
0
    fitness = Fitness.Fitness('fitness_f_Tepl')
    mutation = Mutation.Mutation('mut_Tepl')
    populationGen = Population.Population('generate_new_population_Tepl')
    bga = BasicGeneticAlgorithm.BasicGeneticAlgorithm(generator=genPopulation_Tepl,
                                                      fitness=fitness,
                                                      mutation=mutation,
                                                      sizeOfPopulation=10,
                                                      genPopulation=populationGen,
                                                      numberChromosome=NN, epoche=100,
                                                      data=data)
    ans = bga.fit()
    print(ans)"""

    data = GenMtrx_NN()  # инициализация условий задачи (считывание матрицы расстояний)
    NN = len(data)  # считываем количество городов
    fitness = Fitness.Fitness('fitness_population_NN')
    crossover = Crossover.Crossover('crossover_NN')
    # Можно выбрать: inbreeding_NN,
    #                 outbreeding_NN
    #                 panmixia_NN
    #                 tournament_selection_NN
    #                 roulette_selection_NN
    selection = Selection.Selection('inbreeding_NN')
    mutation = Mutation.Mutation('insertion_deleting_mutation_NN')
    populationGen = Population.Population('elite_selection')
    bga = BasicGeneticAlgorithm.BasicGeneticAlgorithm(generator=genPopulation_NN,
                                                      fitness=fitness,
                                                      crossover=crossover,
                                                      selection=selection,
                                                      mutation=mutation,
                                                      sizeOfPopulation=100,
Пример #23
0
p = Population.Population(100)
population = p.getPopulations()

while (True):

    # for i in range(0, len(population)):
    #     combined = ""
    #     for j in range(0, len(target)):
    #         combined = combined.join(population[i])
    #         # print("COMBINED IS")
    #         # print(combined)
    #         if (combined == target):
    #             print("Its Done!")
    #             sys.exit()

    f = Fitness.Fitness(population)
    fitness = f.getFitness()

    s = Selection.Selection(fitness)
    firstChoice, secondChoice, maximum = s.selectFromPop()

    c = Crossover.Crossover(population, firstChoice, secondChoice)
    population = c.crossover()

    m = Mutation.Mutation(population, 10)
    population = m.mutate()

    if (catch == 1):

        print(
            "--------------------------------------------------------------------"
Пример #24
0
N = 200  #种群内个体数目
mut = 0.3  #突变概率
acr = 0.2  #交叉概率

pop = {}  #存储染色体的字典
for i in range(N):
    pop['chrom' + str(i)] = Chrom()
chromNodes = 4  #染色体节点数(变量个数)
iterNum = 10000  #迭代次数
chromRange = [[0, 10], [0, 10], [0, 10], [0, 10]]  #染色体范围
aveFitnessList = []  #平均适应度
bestFitnessList = []  #最优适应度

#初始染色体
pop = Genetic.initialize(pop, chromNodes, chromRange)
pop = Fitness.calFitness(pop)  #计算适应度
bestChrom = Genetic.findBest(pop)  #寻找最优染色体
bestFitnessList.append(bestChrom[1])  #将当前最优适应度压入列表中
aveFitnessList.append(Genetic.calAveFitness(pop, N))  #计算并存储平均适应度

#开始迭代
for t in range(iterNum):

    #print(bestChrom)
    #染色体突变
    pop = Genetic.mutChrom(pop, mut, chromNodes, bestChrom, chromRange)
    #染色体交换
    pop = Genetic.acrChrom(pop, acr, chromNodes)
    #寻找最优
    nowBestChrom = Genetic.findBest(pop)
    #比较前一个时间的最优和现在的最优
Пример #25
0
 def assignFitnesses(self, window):
     for x in self.genomes:
         x.prepareEvaluation()
         x.FI = Fitness.fitness(x, window) / self.counts[int(x.SP[4:])]
         self.fitnessSum += math.e ** (Settings.softmaxDilution * x.FI)