Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions Lab2/backend/geneticsAlgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
#arr-points - массив пар точек x и y

import random

# Определение функции Розенброка
def rosenbrock(x, y):
return (1 - x) ** 2 + 100 * (y - x ** 2) ** 2

# Создание начальной популяции
def create_population(population_size):
return [(random.uniform(-5, 5), random.uniform(-5, 5)) for _ in range(population_size)]

# Вычисление пригодности (fitness) для каждой особи в популяции
def compute_fitness(population,rosenbrock):
fitness_scores = []
for ind in population:
x, y = ind
fitness_scores.append(rosenbrock(x, y))
return fitness_scores

# Селекция (выбор лучших особей)
def select_best_individuals(population, fitness_scores, num_parents):
selected_indices = sorted(range(len(fitness_scores)), key=lambda i: fitness_scores[i])[:num_parents]
return [population[i] for i in selected_indices]

# Скрещивание (кроссовер)
def crossover(parents, offspring_size):
offspring = []
while len(offspring) < offspring_size:
parent1, parent2 = random.sample(parents, 2)
crossover_point = random.randint(1, len(parent1) - 1)
child = parent1[:crossover_point] + parent2[crossover_point:]
offspring.append(child)
return offspring

# Мутация
def mutate(offspring):
mutated_offspring = []
for child in offspring:
x, y = child
if random.random() < 0.1: # Вероятность мутации
x += random.uniform(-0.5, 0.5)
y += random.uniform(-0.5, 0.5)
mutated_offspring.append((x, y))
return mutated_offspring

# Генетический алгоритм
def genetic_algorithm(population_size, num_generations,rosenbrock):
population = create_population(population_size)
arr_points = []
for generation in range(num_generations):
fitness_scores = compute_fitness(population,rosenbrock)
parents = select_best_individuals(population, fitness_scores, population_size // 2)
offspring = crossover(parents, population_size - len(parents))
mutated_offspring = mutate(offspring)
population = parents + mutated_offspring
best_fitness = min(fitness_scores)
#print(f"Поколение {generation + 1}: Лучшее значение функции Розенброка = {best_fitness}")
arr_points.append(population[fitness_scores.index(min(fitness_scores))])


best_solution = population[fitness_scores.index(min(fitness_scores))]
return best_solution, min(fitness_scores),arr_points

# Запуск генетического алгоритма
#population_size = 50
#num_generations = 100
#best_solution, best_fitness,arr_points = genetic_algorithm(population_size, num_generations,rosenbrock)
#print("Оптимальное значение функции Розенброка:", best_fitness)
#print("Оптимальные значения переменных:")
#print("x =", best_solution[0])
#print("y =", best_solution[1])
#print(arr_points)
91 changes: 91 additions & 0 deletions Lab2/backend/simplexMethod.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import numpy as np

def get_index(func, elem):
for i in range(len(func)):
if func[i] == elem:
return i
return 0


def simplex_method(x1, x2,f):
triangle = []
x0 = float(x1)
z0 = float(x2)
e = 5
alpha = 2
points = [[x0 - alpha / 2, z0 - 0.29 * alpha],
[x0 + alpha / 2, z0 - 0.29 * alpha],
[x0, z0 + 0.58 * alpha]]
func = [f(points[0][0], points[0][1]),
f(points[1][0], points[1][1]),
f(points[2][0], points[2][1])]
triangle.append(list(points))
x_min = x0
z_min = z0
y_min = f(x0, z0)
flag = 0
x_max = x0
z_max = z0
while abs(f(x_max, z_max) - min(func)) > e:
if flag:
flag = 0
x0, z0 = points[get_index(func, min(func))]
x0 += points[get_index(func, max(func))][0]
z0 += points[get_index(func, max(func))][1]
x0 /= 2
z0 /= 2
points.remove(points[get_index(func, max(func))])
func.remove(max(func))
x1, z1 = points[get_index(func, min(func))]
x1 += points[get_index(func, max(func))][0]
z1 += points[get_index(func, max(func))][1]
x1 /= 2
z1 /= 2
points.remove(points[get_index(func, max(func))])
func.remove(max(func))
func.append(f(x0, z0))
points.append([x0, z0])
func.append(f(x1, z1))
points.append([x1, z1])
else:
x_max, z_max = points[get_index(func, max(func))]
points.remove(points[get_index(func, max(func))])
func.remove(max(func))
x0 = 0 - x_max
z0 = 0 - z_max
for value in points:
x0 += value[0]
z0 += value[1]
if f(x0, z0) > max(func):
func.append(f(x_max, z_max))
points.append([x_max, z_max])
flag = 1
else:
func.append(f(x0, z0))
points.append([x0, z0])

if f(x_min, z_min) > min(func):
x_min, z_min = points[get_index(func, min(func))]
y_min = min(func)

triangle.append(list(points))

x_min = round(x_min, 2)
z_min = round(z_min, 2)
y_min = round(y_min, 2)
return triangle, x_min, y_min, z_min

def get_points(start_x,start_y,function):
triangle, x_min, z_min,y_min = simplex_method(start_x,start_y,function)
points = []
for tr in triangle:
if min(tr)[1] >y_min:
point = [tr[0][0], tr[0][1], min(tr)[1]]
points.append(point)
else:
points.append([x_min, y_min,z_min])
break
return points

#points = get_points(10,2,f)
#print(points)
10 changes: 10 additions & 0 deletions Lab2/frontshow/placement_elements.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import tkinter as tk
from tkinter import ttk
ttk = tk
class createLabel:

@staticmethod
def placement_label(root,text,row,column,padx,rowspan,columnspan,pady):
label = ttk.Label(root, text=text)
label.grid(row=row, column=column, padx=padx, rowspan=rowspan, columnspan=columnspan, pady=pady)
return label
20 changes: 20 additions & 0 deletions Lab2/global_variable.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
START = -5
END = 5
STEP = 0.5

SPEED = 100
SIZE_POINT = 50

current_function = None
x_data = []
y_data = []

scatter_points = []

canvas_3d = None
canvas_3d_widget = None

textReachGradientPoint = None
textReachQuadPoint = None
textReachGeneraticPoints = None

Loading