def generate_new_population(fitness_values, previous_population):
	new_population = []
	
	# for each child of our new population
	for i in range(POPULATION_SIZE-1):
		
		# selection
		parents = selection(fitness_values)
				
		# crossover
		chromosome = crossover(population, parents)

		# mutation
		chromosome = mutation(chromosome)
		
		# accept
		new_population.append(chromosome)
	
	
	"""
	Perform hybrid elitist selection. Carry the best chromosome over to the new population, unmutated.
	"""
	chromosome = population[listtools.max_index_in_list(fitness_values)]
	new_population.append(chromosome)
	
	return new_population
コード例 #2
0
ファイル: application.py プロジェクト: barthap/GA_PID_Tuner
    def run_sim(self):
        simulation = self.simulation
        cfg = self.controller.global_params['cfg']
        MAX_RUNS = cfg['max_runs']
        status: SimulationStatus = self.controller.global_params['status']
        status.running = True

        dt_start = datetime.timestamp(datetime.now())

        simulation.generate_initial_population()

        # symulujemy kolejne iteracje, zapisując wyniki każdej z nich
        for i in range(MAX_RUNS):

            if status.kill is True:
                #status.running = False
                return

            # populacja i fitness z aktualnego pokolenia
            population = simulation.population
            fitness_values = simulation.fitness_values

            # może już przetwarzać sobie następne, jeśli to nie było ostatnie
            if i < MAX_RUNS - 1:
                simulation.next_generation()

            std = np.std(fitness_values)

            # add the champion chromosome to a list of champions for plotting
            index_of_champion = listtools.max_index_in_list(fitness_values)
            status.champion_chromosomes.append(population[index_of_champion])

            # add the max/average values to lists for plotting
            status.max_values.append(
                listtools.max_value_in_list(fitness_values))
            status.avg_values.append(listtools.avgList(fitness_values))
            status.stds.append(std)

            status.current_population = population
            status.drawEvent = True
            status.iteration = i
            self.after(
                0,
                self.update_label(i, status.max_values[i],
                                  status.avg_values[i], std))

            if status.kill is True:
                #status.running = False
                return

        dt_end = datetime.timestamp(datetime.now())
        status.totalTime = dt_end - dt_start

        status.running = False
    def run(self) -> AlgorithmResult:
        MAX_RUNS = self.config['max_runs']
        result = AlgorithmResult()
        result.gene_names = self.params.gene_names

        dt_start = datetime.timestamp(datetime.now())

        self.generate_initial_population()

        # symulujemy kolejne iteracje, zapisując wyniki każdej z nich
        for i in range(MAX_RUNS):

            # może już przetwarzać sobie następne, jeśli to nie było ostatnie
            if i < MAX_RUNS - 1:
                self.next_generation()

            std = np.std(self.fitness_values)

            # add the champion chromosome to a list of champions for plotting
            index_of_champion = listtools.max_index_in_list(
                self.fitness_values)
            result.champion_chromosomes.append(
                self.population[index_of_champion])

            # add the max/average values to lists for plotting
            result.max_values.append(
                listtools.max_value_in_list(self.fitness_values))
            result.avg_values.append(listtools.avgList(self.fitness_values))
            result.stds.append(std)

            result.current_population = self.population
            result.iteration = i

        dt_end = datetime.timestamp(datetime.now())
        result.totalTime = dt_end - dt_start

        return result
コード例 #4
0
def generate_new_population(fitness_values, previous_population):
    new_population = []

    # for each child of our new population
    for i in range(POPULATION_SIZE - 1):

        # selection
        parents = selection(fitness_values)

        # crossover
        chromosome = crossover(population, parents)

        # mutation
        chromosome = mutation(chromosome)

        # accept
        new_population.append(chromosome)
    """
	Perform hybrid elitist selection. Carry the best chromosome over to the new population, unmutated.
	"""
    chromosome = population[listtools.max_index_in_list(fitness_values)]
    new_population.append(chromosome)

    return new_population
 def best_iteration(self) -> int:
     """
     :return: zero-based best generation index
     """
     return listtools.max_index_in_list(self.max_values)
コード例 #6
0
ファイル: main.py プロジェクト: piLigrym/genetic-pid
max_values = []
avg_values = []
kp_values = []
kd_values = []
ki_values = []

# perform simulation

for i in range(config['max_runs']):

    simulation.generate_new_population()
    fitness_values = simulation.fitness_values
    population = simulation.population

    # add the champion chromosome to a list of champions for plotting
    index_of_champion = listtools.max_index_in_list(fitness_values)
    kp_values.append(population[index_of_champion].kp)
    kd_values.append(population[index_of_champion].kd)
    ki_values.append(population[index_of_champion].ki)

    # add the max/average values to lists for plotting
    max_values.append(listtools.max_value_in_list(fitness_values))
    avg_values.append(listtools.avgList(fitness_values))

    print("Run " + str(i) + ": max value " + str(max_values[i]) +
          ", avg value " + str(avg_values[i]))
    print(population[index_of_champion].kp, population[index_of_champion].kd,
          population[index_of_champion].ki)
    print('\n')

plt.figure()
コード例 #7
0
ファイル: application.py プロジェクト: barthap/GA_PID_Tuner
    def do_show(self):
        results: SimulationStatus = self.controller.global_params['status']
        cfg = self.controller.global_params['cfg']
        MAX_RUNS = cfg['max_runs']

        tk.Label(self,
                 text="Algorithm total time: {:.2f}s".format(
                     results.totalTime)).grid(row=2, column=0, sticky='w')

        best_index = listtools.max_index_in_list(results.max_values)
        best_chromosome = results.champion_chromosomes[best_index]
        tk.Label(self,
                 text="Starting result: {:.4f}, Starting values: "
                 .format(results.max_values[0]) + str(results.champion_chromosomes[0]))\
            .grid(row=3, column=0, sticky='w')
        tk.Label(self, text="Best generation: " + str(best_index + 1)).grid(
            row=4, column=0, sticky='sw')
        tk.Label(self, text="Best result: {:.4f}, Reduced ISE: {:.4f}"
                 .format(results.max_values[best_index], 1.0 / results.max_values[best_index]))\
            .grid(row=5, column=0, sticky='nw')
        tk.Label(self, text="Calculated PID values: " +
                 str(best_chromosome)).grid(row=6, column=0, sticky='sw')

        tk.Label(self, text="Population size: {}\t Generations count: {}".format(cfg['population_size'], cfg['max_runs']))\
            .grid(row=3, column=1,sticky='we')

        p = plt.figure()
        canvas = FigureCanvasTkAgg(p, self)
        canvas.get_tk_widget().grid(row=0, column=0, sticky="we")

        plt.title("Generation fitness value")
        plt.plot(range(1, MAX_RUNS + 1),
                 results.max_values,
                 marker='.',
                 label=r"Best")
        plt.plot(range(1, MAX_RUNS + 1),
                 results.avg_values,
                 marker='.',
                 label=r"Average")
        plt.plot([best_index + 1],
                 results.max_values[best_index],
                 marker='o',
                 color='r')
        plt.legend(loc='lower right')
        plt.grid()
        plt.xlabel("Generation")
        plt.ylabel("Fitness")
        plt.tight_layout()
        plt.gcf().subplots_adjust(bottom=0.3)
        self.p1 = p

        # plot values of parameters for each run
        # plt.subplot(2,1,2)
        p2 = plt.figure()
        canvas2 = FigureCanvasTkAgg(p2, self)
        canvas2.get_tk_widget().grid(row=0, column=1, sticky="we")

        plt.title("Generation best PID values")
        plt.plot(range(1, MAX_RUNS + 1),
                 [x.kp for x in results.champion_chromosomes],
                 marker='.',
                 label=r"Kp")
        plt.plot(range(1, MAX_RUNS + 1),
                 [x.Ti for x in results.champion_chromosomes],
                 marker='.',
                 label=r"Ti")
        plt.plot(range(1, MAX_RUNS + 1),
                 [x.Td for x in results.champion_chromosomes],
                 marker='.',
                 label=r"Td")
        plt.legend(loc='center right')
        plt.grid()
        plt.xlabel("Generation")
        plt.ylabel("Value")
        plt.tight_layout()
        plt.subplots_adjust(bottom=0.3)
        self.p2 = p2

        fit, t, y = self.controller.global_params[
            'sim'].sim_model.simulate_for_fitness(best_chromosome)

        tk.Label(self,
                 text="Integral Square Error (ISE): {:.4f}".format(fit)).grid(
                     row=7, column=0, sticky='nw')
        p3 = plt.figure(figsize=(6.4, 3.6))
        canvas3 = FigureCanvasTkAgg(p3, self)
        canvas3.get_tk_widget().grid(row=1, column=0, sticky="we")
        plt.plot(t, y, 'b')
        plt.xlabel('t [s]')
        plt.ylabel('Step response')
        plt.grid(True)
        plt.title('PID tuning result')
        plt.tight_layout()
        plt.gcf().subplots_adjust(bottom=0.25)
        self.p3 = p3

        p4 = plt.figure(figsize=(6.4, 2.4))
        canvas4 = FigureCanvasTkAgg(p4, self)
        canvas4.get_tk_widget().grid(row=1, column=1, sticky="wens")
        plt.plot(range(MAX_RUNS), results.stds)
        plt.title("Fitness standard deviation")
        plt.grid()
        plt.xlabel("Generation")
        plt.tight_layout()
        self.p4 = p4

        dummy = plt.figure()
        new_manager = dummy.canvas.manager
        # create a dummy figure and use its
        new_manager.canvas.figure = p4
        p4.set_canvas(new_manager.canvas)
コード例 #8
0
 def test_max_index_in_list(self):
     lista = [1, 2, 5, 2]
     idx = listtools.max_index_in_list(lista)
     self.assertEqual(idx, 2)
max_values = []
avg_values = []
kp_values = []
kd_values = []
ki_values = []

# perform simulation

for i in range(MAX_RUNS):

	# generate population and run the simulation
	population = generate_new_population(fitness_values, population)
	fitness_values = run_simulation(map, population)
	
	# add the champion chromosome to a list of champions for plotting
	index_of_champion = listtools.max_index_in_list(fitness_values)
	kp_values.append(population[index_of_champion].kp)
	kd_values.append(population[index_of_champion].kd)
	ki_values.append(population[index_of_champion].ki)
	

	# add the max/average values to lists for plotting
	max_values.append(listtools.max_value_in_list(fitness_values))
	avg_values.append(listtools.avgList(fitness_values))
	
	
	# every RUNS_PER_SCREENSHOT runs, do a plot of the champion chromosome
	if i % RUNS_PER_SCREENSHOT == 0:
		# run the simulation for the first selected parent
		run_simulation_for_champion(map, population, index_of_champion, i, listtools.max_value_in_list(fitness_values))