import numpy as np
import [Link] as plt
import pygame
from [Link] import *
import time
from io import BytesIO
[Link]()
class Fish:
def __init__(self, dimension, bounds):
[Link] = [Link](bounds[0], bounds[1], dimension)
[Link] = [Link](-1, 1, dimension)
self.best_position = [Link]([Link])
self.best_value = float('inf')
def food_function(x):
return [Link]((x - [Link]([5, 5])) ** 2)
def PSO_fish(num_fish, dimension, bounds, max_iterations, w=0.7, c1=0.01, c2=0.01):
swarm = [Fish(dimension, bounds) for _ in range(num_fish)]
global_best_position = [Link]([5, 5])
global_best_value = float('inf')
history = []
positions = []
for iteration in range(max_iterations):
current_positions = []
all_reached = True
for fish in swarm:
[Link] = (w * [Link] +
c1 * [Link]() * (fish.best_position -
[Link]) +
c2 * [Link]() * (global_best_position -
[Link]))
[Link] += [Link]
value = food_function([Link])
if value < fish.best_value:
fish.best_value = value
fish.best_position = [Link]
if value < global_best_value:
global_best_value = value
current_positions.append([Link])
if [Link]([Link] - global_best_position) > 0.1:
all_reached = False
[Link]([Link](current_positions))
[Link](global_best_value)
print(f"Iteration {iteration+1}: Best Value = {global_best_value}")
if all_reached:
print("All fish have reached the food!")
break
return global_best_position, global_best_value, history, positions
def visualize_combined(positions, history, screen_size=600, bounds=(-10, 10)):
screen = [Link].set_mode((screen_size, screen_size))
[Link].set_caption("Fish Movement & Optimization Progress")
clock = [Link]()
running = True
font = [Link](None, 24)
for i, pos in enumerate(positions):
[Link]((255, 255, 255))
# Draw fish
for fish in pos:
x = int((fish[0] - bounds[0]) / (bounds[1] - bounds[0]) * screen_size)
y = int((fish[1] - bounds[0]) / (bounds[1] - bounds[0]) * screen_size)
[Link](screen, (0, 0, 255), (x, y), 7) # Blue fish
# Draw food
food_x = int((5 - bounds[0]) / (bounds[1] - bounds[0]) * screen_size)
food_y = int((5 - bounds[0]) / (bounds[1] - bounds[0]) * screen_size)
[Link](screen, (255, 0, 0), (food_x, food_y), 10) # Red food
# Render optimization progress plot
fig, ax = [Link]()
[Link](history[:i+1], marker='o', linestyle='-', color='b')
ax.set_xlabel('Iteration')
ax.set_ylabel('Best Value Found')
ax.set_title('Optimization Progress')
[Link]()
# Convert Matplotlib figure to Pygame surface
buf = BytesIO()
[Link](buf, format="PNG")
[Link](0)
plot_surface = [Link](buf)
[Link]()
plot_surface = [Link](plot_surface, (300, 200))
[Link](plot_surface, (screen_size - 310, 10))
[Link](fig)
# Display iteration info
text = [Link](f"Iteration: {i+1}/{len(positions)}", True, (0, 0, 0))
[Link](text, (10, 10))
[Link]()
[Link](5)
for event in [Link]():
if [Link] == [Link]:
running = False
break
[Link]()
if __name__ == "__main__":
num_fish = 30
dimension = 2
bounds = (-10, 10)
max_iterations = 1000
best_position, best_value, history, positions = PSO_fish(num_fish, dimension,
bounds, max_iterations)
print(f"Best Position: {best_position}")
print(f"Best Value: {best_value}")
visualize_combined(positions, history)