import random import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation import gradio as gr class Robot: def __init__(self, x, y, role): self.x = x self.y = y self.role = role self.resource = False self.energy = 100 self.communication_range = 2 def move(self, dx, dy): self.x += dx self.y += dy self.energy -= 0.1 self.x = max(-10, min(10, self.x)) self.y = max(-10, min(10, self.y)) def sense_nearby_robots(self, robots, radius): return [robot for robot in robots if robot != self and self.distance(robot) <= radius] def distance(self, other): if isinstance(other, Robot): return np.hypot(self.x - other.x, self.y - other.y) else: return np.hypot(self.x - other[0], self.y - other[1]) def communicate(self, robots, resources): for robot in robots: if self.distance(robot) <= self.communication_range: if self.role == 'explorer' and robot.role == 'explorer': if resources and not robot.resource: closest_resource = min(resources, key=lambda r: self.distance(r)) return closest_resource return None class Swarm: def __init__(self, num_robots, sensing_radius, num_resources, num_obstacles): self.num_robots = num_robots self.sensing_radius = sensing_radius self.robots = [Robot(random.uniform(-10, 10), random.uniform(-10, 10), 'explorer') for _ in range(num_robots)] self.resources = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(num_resources)] self.obstacles = [(random.uniform(-10, 10), random.uniform(-10, 10)) for _ in range(num_obstacles)] self.charging_stations = [(8, 8), (-8, -8)] def update(self): for robot in self.robots: nearby_robots = robot.sense_nearby_robots(self.robots, self.sensing_radius) if robot.energy < 20: self.seek_charging_station(robot) elif robot.energy > 80 and robot.role != 'explorer': robot.role = 'explorer' if robot.role == 'explorer': shared_resource = robot.communicate(nearby_robots, self.resources) if shared_resource: dx = shared_resource[0] - robot.x dy = shared_resource[1] - robot.y robot.move(0.05 * dx, 0.05 * dy) elif nearby_robots: avg_x = sum(r.x for r in nearby_robots) / len(nearby_robots) avg_y = sum(r.y for r in nearby_robots) / len(nearby_robots) robot.move(0.01 * (avg_x - robot.x), 0.01 * (avg_y - robot.y)) else: robot.move(random.uniform(-0.1, 0.1), random.uniform(-0.1, 0.1)) self.avoid_obstacles(robot) for resource in self.resources: if robot.distance(resource) < 0.5: robot.resource = True robot.role = 'transporter' self.resources.remove(resource) break elif robot.role == 'transporter': if robot.x > 9: robot.resource = False robot.role = 'explorer' else: robot.move(0.1, 0) self.assemble_pattern() def avoid_obstacles(self, robot): for obstacle in self.obstacles: if robot.distance(obstacle) < 1: dx = robot.x - obstacle[0] dy = robot.y - obstacle[1] dist = max(np.hypot(dx, dy), 0.1) robot.move(0.1 * dx / dist, 0.1 * dy / dist) def seek_charging_station(self, robot): nearest_station = min(self.charging_stations, key=lambda s: robot.distance(s)) dx = nearest_station[0] - robot.x dy = nearest_station[1] - robot.y robot.move(0.05 * dx, 0.05 * dy) if robot.distance(nearest_station) < 0.5: robot.energy = min(robot.energy + 5, 100) robot.role = 'charging' else: robot.role = 'returning' def assemble_pattern(self): if len(self.resources) == 0: centers = [(0, 0), (5, 5), (-5, 5), (5, -5), (-5, -5)] for robot, center in zip(self.robots, centers * (len(self.robots) // 5 + 1)): dx = center[0] - robot.x dy = center[1] - robot.y robot.move(0.01 * dx, 0.01 * dy) def simulate_swarm(num_robots, sensing_radius, num_resources, num_obstacles, num_frames): swarm = Swarm(num_robots, sensing_radius, num_resources, num_obstacles) fig, ax = plt.subplots(figsize=(8, 8)) ax.set_xlim(-11, 11) ax.set_ylim(-11, 11) robot_scatter = ax.scatter([], [], c=[], cmap='viridis', vmin=0, vmax=100) resource_scatter = ax.scatter([], [], c='green', marker='s') obstacle_scatter = ax.scatter([], [], c='red', marker='^') station_scatter = ax.scatter([s[0] for s in swarm.charging_stations], [s[1] for s in swarm.charging_stations], c='yellow', marker='*', s=200) def animate(frame): swarm.update() x = [robot.x for robot in swarm.robots] y = [robot.y for robot in swarm.robots] c = [robot.energy for robot in swarm.robots] robot_scatter.set_offsets(np.c_[x, y]) robot_scatter.set_array(np.array(c)) resource_scatter.set_offsets(swarm.resources) obstacle_scatter.set_offsets(swarm.obstacles) ax.set_title(f'Frame: {frame}, Resources left: {len(swarm.resources)}') return robot_scatter, resource_scatter, obstacle_scatter, station_scatter ani = FuncAnimation(fig, animate, frames=num_frames, interval=50, blit=True) plt.close(fig) return ani def launch_demo(num_robots, sensing_radius, num_resources, num_obstacles, num_frames): ani = simulate_swarm(num_robots, sensing_radius, num_resources, num_obstacles, num_frames) return gr.Plot(ani) with gr.Blocks() as demo: gr.Markdown("# Enhanced Swarm Intelligence Demo") gr.Markdown("Interactive demo showcasing advanced swarm intelligence behaviors including energy management, obstacle avoidance, and improved communication.") with gr.Row(): num_robots = gr.Slider(minimum=1, maximum=50, step=1, value=20, label="Number of Robots") sensing_radius = gr.Slider(minimum=1, maximum=10, step=0.5, value=3, label="Sensing Radius") num_resources = gr.Slider(minimum=1, maximum=30, step=1, value=15, label="Number of Resources") num_obstacles = gr.Slider(minimum=0, maximum=20, step=1, value=10, label="Number of Obstacles") num_frames = gr.Slider(minimum=100, maximum=1000, step=50, value=500, label="Number of Frames") output = gr.Plot(label="Swarm Intelligence Demo") inputs = [num_robots, sensing_radius, num_resources, num_obstacles, num_frames] run_button = gr.Button("Run Simulation") run_button.click(fn=launch_demo, inputs=inputs, outputs=output) demo.launch()