Advertisement
Jann24

gen_alg_new

Nov 26th, 2024
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 KB | None | 0 0
  1. import random
  2. import scipy.io
  3. import matplotlib.pyplot as plt
  4. import numpy as np
  5.  
  6. classroom_width = 7
  7. classroom_length = 5
  8.  
  9. num_app = 5
  10.  
  11. population_size = 12
  12.  
  13. generations = 10
  14.  
  15. mutation_rate = 0.1
  16.  
  17.  
  18. def calculate_signal_strength(ap_x, ap_y, point_x, point_y):
  19.     distance = np.sqrt((ap_x - point_x)**2 + (ap_y - point_y)**2)
  20.     return 1/(distance+1)
  21.  
  22. def visualize_initial_and_final(classroom_width, classroom_length, initial_population, final_population):
  23.     plt.figure(figsize=(15,6))
  24.  
  25.     for i, (x, y) in enumerate(initial_population):
  26.         plt.text(x, y, str(i+1), color='black', fontsize=8, ha='center', va='center')
  27.     plt.scatter(*zip(*initial_population), color="red", marker="o", label="Начална позиция на точките за дотъп до WI-FI")
  28.  
  29.     for i, (x,y) in enumerate(final_population):
  30.         plt.text(x, y, str(i+1), color='black', fontsize=8, ha='center', va='center')
  31.     plt.scatter(*zip(*final_population), color="blue", marker="o", label="Финална позиция на точките за дотъп до WI-FI")
  32.  
  33.     plt.xlabel("Ширина на учебна зала (М)")
  34.     plt.ylabel("Дължина на учебна зала (М)")
  35.     plt.title("Начало и крайно разпределение на точките за достъп")
  36.     plt.legend()
  37.     plt.show()
  38.  
  39. def visualize_dynamic_changes(classroom_width, classroom_length, population, fitness_scores):
  40.     for generation in range(generations):
  41.         plt.figure(figsize=(15,6))
  42.  
  43.         plt.subplot(1, 2, 1)
  44.         ap_placements = population[generation]
  45.  
  46.         x = np.linspace(0, classroom_width, 100)
  47.         y = np.linspace(0, classroom_length, 100)
  48.         X, Y = np.meshgrid(x, y)
  49.         Z = np.zeros_like(X)
  50.         for ap_x, ap_y in ap_placements:
  51.             Z += calculate_signal_strength(ap_x, ap_y, X, Y)
  52.         plt.pcolormesh(X, Y, Z, shading='auto', cmap='viridis')
  53.         plt.colorbar(label="СИла на сигнала")
  54.         for i, (x, y) in enumerate(ap_placements):
  55.             plt.text(x, y, str(i+1), color="black", fontsize=8, ha="center", va="center")
  56.         plt.scatter(*zip(*ap_placements), color="red", marker="o", label="Разпределение на точките за достъп")
  57.         plt.xlabel("Ширина на учебна зала (м)")
  58.         plt.ylabel("Дължина на учебната зала (м)")
  59.         plt.title(f'Сила на Wi-Fi сигнала и разпределение на точките за достъп (Поколение {generation + 1})')
  60.         plt.legend()
  61.  
  62.  
  63.  
  64.  
  65.         plt.subplot(1, 2, 2)
  66.         plt.plot(range(1, generation + 2), fitness_scores[:generation + 1], marker = 'o')
  67.         plt.xlabel("Поколение")
  68.         plt.ylabel("Резултат от фитнеса")
  69.         plt.title("Резултат от фитнеса за различните поколения")
  70.  
  71.         plt.tight_layout()
  72.         plt.show()
  73.  
  74.  
  75. initial_population = [(random.uniform(0, classroom_width), random.uniform(0, classroom_length)) for _ in range(population_size)]
  76. population = [initial_population.copy()]
  77.  
  78. best_solution = None
  79. best_fitness = float('-inf')
  80. all_fitness_scores = []
  81.  
  82.  
  83. for generation in range(generations):
  84.     fitness_scores = []
  85.     for ap_x, ap_y in population[generation]:
  86.         coverage = 0
  87.         for point_x in range(classroom_width):
  88.             for point_y in range(classroom_length):
  89.                 coverage += calculate_signal_strength(ap_x, ap_y, point_x, point_y)
  90.         fitness_scores.append(coverage)
  91.  
  92.     if(max(fitness_scores)) > best_fitness:
  93.         best_solution = population[generation][fitness_scores.index(max(fitness_scores))]
  94.         best_fitness = max(fitness_scores)
  95.    
  96.     all_fitness_scores.append(max(fitness_scores))
  97.     selected_parents = random.choices(population[generation], weights=fitness_scores, k=population_size)
  98.  
  99.     offspring = []
  100.     for _ in range(population_size):
  101.         parent1, parent2 = random.sample(selected_parents,2)
  102.         crossover_x = random.uniform(parent1[0], parent2[0])
  103.         crossover_y = random.uniform(parent1[1], parent2[1])
  104.         offspring.append((crossover_x, crossover_y))
  105.  
  106.     for i in range(len(offspring)):
  107.         if random.random() < mutation_rate:
  108.             offspring[i] = (random.uniform(0, classroom_width), random.uniform(0, classroom_length))
  109.     population.append(offspring)
  110.  
  111.  
  112. #visualize_initial_and_final(classroom_width, classroom_length, initial_population, population[-1])
  113.  
  114. #visualize_dynamic_changes(classroom_width, classroom_length, population, all_fitness_scores)
  115.  
  116.  
  117. print(f"Най-доброто разпределение на точките за дотъп: {best_solution}")
  118. print(f"Най-доброто покритие: {best_fitness}")
  119.  
  120. #Траектория на популация
  121. trajectory_scores = []
  122. for generation in range(generations + 1):
  123.     distances = [np.linalg.norm(np.array(point) - np.array(best_solution)) for point in population[generation]]
  124.     trajectory_scores.append(np.mean(distances))
  125.  
  126. plt.figure(figsize=(10,6))
  127. plt.plot(range(generation + 1), trajectory_scores, marker="o")
  128. plt.xlabel("Поколение")
  129. plt.ylabel("Средно разстояние до най-добро решение")
  130. plt.title('Траектория на популация')
  131. plt.show()
  132.  
  133.  
  134. # Графика на сходство
  135. plt.figure()
  136. plt.plot(range(1, generations + 1), all_fitness_scores, marker="o")
  137. plt.xlabel('Поколение')
  138. plt.ylabel('Най-добър фитнес резултат')
  139. plt.title("Графика на сходство")
  140. plt.show()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement