Spaces:
Sleeping
Sleeping
Upload folder using huggingface_hub
Browse filesFiles changed (13)
- READ_ME.txtAdded+45
- __pycache__/car_game_classes_gradio.cpython-312.pycAdded
- __pycache__/ppo_agent_gradio.cpython-312.pycAdded
- app copy 2.pyAdded+400
- app copy 3.pyAdded+401
- app copy.pyAdded+270
- app.pyAdded+401
- assets/car_transparent.pngAdded
- car_game_classes_gradio.pyAdded+378
- car_model_epoch_270_lvl3_final_gradio.pthAdded+3
- model/18.6_car_model_epoch_270_lvl3_final.pthAdded+3
- ppo_agent_gradio.pyAdded+268
- requirements.txtAdded+4
123456789101112131415161718192021222324252627282930313233343536373839404142434445# 🏎️ PPO Car Racing Agent Demo
This is an interactive demo of a reinforcement learning agent trained using PPO (Proximal Policy Optimization) to navigate racing tracks autonomously.
## 🎮 How to Use
1. **Select Difficulty**: Choose between simple (1) or complex (2) track layouts
2. **Toggle Ray Casting**: Enable to see the agent's vision sensors
3. **Start Demo**: Click to begin the autonomous driving demonstration
4. **Generate New Tracks**: Create different track layouts to test the agent
## 🤖 About the Agent
The PPO agent features:
- **7 ray-casting sensors** for environmental perception
- **Deep neural network** policy (512→256→128 layers)
- **8 discrete actions** including acceleration, steering, and braking
- **Trained on thousands of episodes** using reinforcement learning
## 🏁 Game Mechanics
- **Blue lines**: Goals to reach in sequence
- **Yellow lines**: Current target goal
- **Green lines**: Completed goals
- **Red car**: The autonomous agent
- **Yellow rays**: Agent's vision sensors (when enabled)
## 📊 Performance Metrics
The interface displays real-time statistics including:
- Current velocity and distance traveled
- Goals completed vs. total goals
- Step count and simulation status
## 🛠️ Technical Details
Built with:
- **PyTorch** for the neural network
- **Pygame** for game simulation
- **Gradio** for the web interface
- **PPO algorithm** for training
---
*This demo showcases the capabilities of modern reinforcement learning in autonomous navigation tasks.*123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400import gradio as gr
import numpy as np
import pygame
import threading
import queue
from PIL import Image
from car_game_classes_gradio import Car, RayCasting, MapGenerator
from ppo_agent_gradio import PPOAgent
from collections import deque
# Initialize Pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 1600, 900
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
# Define constants
ACTION_SPACE = 8
state_size = 22
LOADED_MODEL = "model/18.6_car_model_epoch_270_lvl3_final.pth"
SIMULATION_FPS = 120 # Fixed simulation FPS, matching training
DT = 1.0 / SIMULATION_FPS # Fixed time step
# Frame queue for Gradio
frame_queue = queue.Queue(maxsize=1)
def point_to_line_distance(point, line_p0, line_p1):
p = pygame.math.Vector2(point)
a = pygame.math.Vector2(line_p0)
b = pygame.math.Vector2(line_p1)
ap = p - a
ab = b - a
magnitude_ab = ab.length_squared()
if magnitude_ab == 0:
return ap.length()
projection = ap.dot(ab) / magnitude_ab
projection = max(0, min(1, projection))
closest = a + projection * ab
return p.distance_to(closest)
class TrainingEnvironment:
def __init__(self, action_space=8):
self.action_space = action_space
self.map_generator = MapGenerator(SCREEN_WIDTH, SCREEN_HEIGHT, 2, 18) # Difficulty 2 = lvl 3 in training
car_surf = pygame.image.load("assets/car_transparent.png").convert_alpha()
w, h = car_surf.get_size()
self.car_image = pygame.transform.scale(car_surf, (w//18, h//18))
self.start_pos = None
self.start_dir = None
self.previous_speed = 0.0
self.speed_history = deque(maxlen=5)
self.steering_history = deque(maxlen=10)
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.prev_pos = None
self.passed_goals = []
self.last_action = 0
self.reset()
def generate_new_map(self):
start_pos, start_dir = self.map_generator.update()
self.start_pos = pygame.math.Vector2(start_pos)
self.start_dir = pygame.math.Vector2(start_dir).normalize()
def reset_car(self):
if self.start_pos is None or self.start_dir is None:
raise ValueError("Map not generated yet")
self.car = Car(self.car_image, self.start_pos)
self.car.direction = self.start_dir
self.rays = RayCasting(
self.car.pos, self.car.direction, self.map_generator.surface,
[-60, -30, -15, 0, 15, 30, 60],
[14, 22, 27, 26, 27, 22, 14],
draw_rays=False)
self.current_goal_index = 0
self.passed_goals = []
self.prev_pos = self.car.pos.copy()
self.previous_speed = 0.0
self.speed_history.clear()
self.steering_history.clear()
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.last_action = 0
def reset(self):
self.map_generator.difficulty = 2 # Ensure difficulty matches training
self.generate_new_map()
self.reset_car()
def detect_steering_need(self, ray_distances):
norm_distances = [min(d / self.rays.max_distance, 1.0) for d in ray_distances]
left_rays = norm_distances[0:3]
center_ray = norm_distances[3]
right_rays = norm_distances[4:7]
left_avg = sum(left_rays) / len(left_rays)
right_avg = sum(right_rays) / len(right_rays)
space_difference = right_avg - left_avg
steering_needed = False
preferred_direction = 0
urgency = 0.0
min_side_distance = min(min(left_rays), min(right_rays))
if min_side_distance < 0.3:
steering_needed = True
urgency = 1.0 - min_side_distance
preferred_direction = 1 if left_avg < right_avg else -1
elif abs(space_difference) > 0.15:
steering_needed = True
urgency = min(abs(space_difference), 1.0)
preferred_direction = 1 if space_difference > 0 else -1
elif center_ray < 0.4:
steering_needed = True
urgency = 1.0 - center_ray
preferred_direction = 1 if left_avg < right_avg else -1
return {
'needed': steering_needed,
'direction': preferred_direction,
'urgency': urgency,
'space_diff': space_difference,
'left_space': left_avg,
'right_space': right_avg,
'center_distance': center_ray
}
def get_state(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
steering_info = self.detect_steering_need(ray_distances)
state = [
self.car.velocity / self.car.max_velocity,
self.car.direction.x,
self.car.direction.y,
int(self.car.is_braking),
]
state.extend(normalized_ray_distances)
state.extend([
float(steering_info['needed']),
steering_info['direction'],
steering_info['urgency'],
steering_info['space_diff'],
steering_info['left_space'],
steering_info['right_space'],
steering_info['center_distance']
])
total_goals = len(self.map_generator.goals)
progress = self.current_goal_index / max(total_goals, 1)
state.append(progress)
state.append(self.last_action / 4.0)
speed_change = self.car.velocity - self.previous_speed
self.speed_history.append(speed_change)
avg_speed_change = sum(self.speed_history) / max(len(self.speed_history), 1)
state.extend([speed_change / 100.0, avg_speed_change / 100.0])
self.previous_speed = self.car.velocity
return np.array(state, dtype=np.float32)
def execute_action_dispatch(self, action, dt):
action_int = int(action)
self.last_action = action_int
keys = {'w': False, 'a': False, 'd': False, 's': False}
steer_factor = 1.0
if action_int == 0:
keys['w'] = True
elif action_int == 1:
keys['a'] = True
steer_factor = 1.0
elif action_int == 2:
keys['d'] = True
steer_factor = 1.0
elif action_int == 3:
keys['w'] = True
keys['a'] = True
steer_factor = 0.8
elif action_int == 4:
keys['w'] = True
keys['d'] = True
steer_factor = 0.8
elif action_int == 5:
keys['s'] = True
original_brake = self.car.brake_deceleration
self.car.brake_deceleration *= 0.6
self.car.update(dt, keys, steer_factor)
self.car.brake_deceleration = original_brake
return
elif action_int == 6:
keys['s'] = True
keys['a'] = True
steer_factor = 1.2
elif action_int == 7:
keys['s'] = True
keys['d'] = True
steer_factor = 1.2
self.car.update(dt, keys, steer_factor)
def detect_curve_severity(self, ray_distances, steering_info):
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
longest_distance = max(normalized_ray_distances)
longest_index = normalized_ray_distances.index(longest_distance)
main_ray_index = 3
if longest_index == main_ray_index:
return 0.0
left_adjacent_index = max(0, longest_index - 1)
right_adjacent_index = min(len(normalized_ray_distances) - 1, longest_index + 1)
left_adjacent_distance = normalized_ray_distances[left_adjacent_index]
right_adjacent_distance = normalized_ray_distances[right_adjacent_index]
if left_adjacent_distance > right_adjacent_distance:
longer_adjacent_index = left_adjacent_index
longer_adjacent_distance = left_adjacent_distance
else:
longer_adjacent_index = right_adjacent_index
longer_adjacent_distance = right_adjacent_distance
weight = longer_adjacent_distance / longest_distance
ray_angles = [-60, -30, -15, 0, 15, 30, 60]
longest_ray_angle = ray_angles[longest_index]
longer_adjacent_angle = ray_angles[longer_adjacent_index]
longest_pos_angle = longest_ray_angle + weight * (longer_adjacent_angle - longest_ray_angle)
front_ray_angle = ray_angles[main_ray_index]
angle_difference = abs(longest_pos_angle - front_ray_angle)
if angle_difference >= 50:
curve_severity = 1.0
else:
curve_severity = angle_difference / 40.0
return curve_severity
def calculate_reward(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
collision = self.rays.has_zero_length_ray()
if collision:
return -100.0, collision, False
steering_info = self.detect_steering_need(ray_distances)
reward = 0.0
curve_severity = self.detect_curve_severity(ray_distances, steering_info)
center_distance = ray_distances[3] / self.rays.max_distance
if center_distance > 0.25:
reward += 0.25 * self.car.velocity - 6
if curve_severity > 0.1:
if curve_severity > 0.5:
if 0.125 < self.car.velocity < 0.25:
reward += self.car.velocity / 10
else:
reward += -2
elif curve_severity > 0.25:
if 0.15 < self.car.velocity < 0.35:
reward += self.car.velocity / 12
else:
reward += -2
else:
if 0.35 < self.car.velocity < 0.7:
reward += self.car.velocity / 10
else:
reward += -2
else:
if self.car.velocity > 40:
reward += self.car.velocity / 20
elif self.car.velocity < 25:
reward += -0.5
if hasattr(self, 'speed_consistency_tracker'):
self.speed_consistency_tracker = {'appropriate': False, 'count': 0}
if steering_info['needed']:
steering_urgency = steering_info['urgency']
base_steering_reward = 5.0 + (steering_urgency * 4.0)
correct_action = False
if steering_info['direction'] == -1:
if self.last_action in [1, 3, 6]:
correct_action = True
if self.steering_persistence['direction'] == -1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': -1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 6:
base_steering_reward += 5.0
elif steering_info['direction'] == 1:
if self.last_action in [2, 4, 7]:
correct_action = True
if self.steering_persistence['direction'] == 1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.0)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': 1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 7:
base_steering_reward += 5.0
if correct_action:
reward += base_steering_reward
else:
self.steering_persistence = {'direction': 0, 'count': 0}
if steering_urgency > 0.6:
penalty = -4.0 * steering_urgency
reward += penalty
else:
self.steering_persistence = {'direction': 0, 'count': 0}
speed_factor = self.car.velocity / self.car.max_velocity
min_side_distance = min([ray_distances[i] for i in [0, 1, 2, 4, 5, 6]]) / self.rays.max_distance
center_distance = ray_distances[3] / self.rays.max_distance
if min_side_distance < 0.01:
danger_penalty = -5.0 * (1.0 - min_side_distance * 12.5) * (0.5 + speed_factor * 0.5)
reward += danger_penalty
elif min_side_distance < 0.0166:
if speed_factor > 0.7:
minor_penalty = -2 * (1.0 - min_side_distance * 6.67)
reward += minor_penalty
if 0.01666 <= min_side_distance and center_distance > 0.2:
safety_efficiency_bonus = 0.3
if 0.3 <= speed_factor <= 0.8:
safety_efficiency_bonus += 0.2
reward += safety_efficiency_bonus
total_goals = len(self.map_generator.goals)
if self.current_goal_index < total_goals:
goal = self.map_generator.goals[self.current_goal_index]
dist = point_to_line_distance(self.car.pos, goal[0], goal[1])
if dist < 8:
reward += 7.5
self.passed_goals.append(self.current_goal_index)
self.current_goal_index += 1
all_goals_completed = self.current_goal_index >= total_goals
if all_goals_completed:
reward += 20.0
reward = max(-15.0, min(reward, 12.0))
self.prev_pos = pygame.math.Vector2(self.car.pos)
self.last_steering_reward = reward
return reward, collision, all_goals_completed
def game_loop():
try:
pygame.init()
pygame.display.set_mode((1, 1), pygame.NOFRAME)
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
env = TrainingEnvironment(ACTION_SPACE)
env.reset()
agent = PPOAgent(state_size, ACTION_SPACE)
agent.load(LOADED_MODEL)
steps = 0
action_counts = [0] * ACTION_SPACE
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
state = env.get_state()
action, _ = agent.select_action(state)
action_int = int(action)
action_counts[action_int] += 1
env.execute_action_dispatch(action_int, DT)
reward, collision, all_goals_completed = env.calculate_reward()
env.rays.update(env.car.pos, env.car.direction)
if collision or all_goals_completed:
env.reset()
steps += 1
screen.fill((255, 255,255))
env.map_generator.draw(screen)
env.car.draw(screen)
for i, (angle, offset) in enumerate(zip([-60, -30, -15, 0, 15, 30, 60], [14, 22, 27, 26, 27, 22, 14])):
if i < len(env.rays.last_collisions):
ray_dir = env.car.direction.rotate(angle).normalize()
origin = env.car.pos + ray_dir * offset
end_point = env.rays.last_collisions[i]
pygame.draw.line(screen, (255, 255, 0),
(int(origin.x), int(origin.y)),
(int(end_point.x), int(end_point.y)),
width=2)
frame_array = pygame.surfarray.array3d(screen)
frame_array = np.transpose(frame_array, (1, 0, 2))
pil_image = Image.fromarray(frame_array)
pil_image = pil_image.resize((SCREEN_WIDTH, SCREEN_HEIGHT))
try:
frame_queue.put(pil_image, block=False)
except queue.Full:
pass
clock.tick(SIMULATION_FPS)
except Exception as e:
print(f"Error in game loop: {e}")
def get_frame():
try:
return frame_queue.get_nowait()
except queue.Empty:
return Image.new('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), (0, 0, 0))
css = """#game-image {
height: calc(100vw * 9 / 16) !important;
object-fit: contain;
margin: 0 auto;
display: block;
}"""
def execute_interference():
game_thread = threading.Thread(target=game_loop)
game_thread.daemon = True
game_thread.start()
with gr.Blocks(css=css) as demo:
with gr.Column():
img = gr.Image(type="pil", label="Game Stream", elem_id="game-image", scale=1, min_width=0)
timer = gr.Timer(value=0.00833)
timer.tick(fn=get_frame, inputs=None, outputs=img)
demo.launch()
if __name__ == "__main__":
execute_interference()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401import gradio as gr
import numpy as np
import pygame
import threading
import queue
from PIL import Image
from car_game_classes_gradio import Car, RayCasting, MapGenerator
from ppo_agent_gradio import PPOAgent
from collections import deque
# Initialize Pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 1600, 900
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
# Define constants
ACTION_SPACE = 8
state_size = 22
LOADED_MODEL = "model/18.6_car_model_epoch_270_lvl3_final.pth"
SIMULATION_FPS = 120 # Fixed simulation FPS, matching training
DT = 1.0 / SIMULATION_FPS # Fixed time step
# Frame queue for Gradio
frame_queue = queue.Queue(maxsize=1)
def point_to_line_distance(point, line_p0, line_p1):
p = pygame.math.Vector2(point)
a = pygame.math.Vector2(line_p0)
b = pygame.math.Vector2(line_p1)
ap = p - a
ab = b - a
magnitude_ab = ab.length_squared()
if magnitude_ab == 0:
return ap.length()
projection = ap.dot(ab) / magnitude_ab
projection = max(0, min(1, projection))
closest = a + projection * ab
return p.distance_to(closest)
class TrainingEnvironment:
def __init__(self, action_space=8):
self.action_space = action_space
self.map_generator = MapGenerator(SCREEN_WIDTH, SCREEN_HEIGHT, 2, 18) # Difficulty 2 = lvl 3 in training
car_surf = pygame.image.load("assets/car_transparent.png").convert_alpha()
w, h = car_surf.get_size()
self.car_image = pygame.transform.scale(car_surf, (w//18, h//18))
self.start_pos = None
self.start_dir = None
self.previous_speed = 0.0
self.speed_history = deque(maxlen=5)
self.steering_history = deque(maxlen=10)
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.prev_pos = None
self.passed_goals = []
self.last_action = 0
self.reset()
def generate_new_map(self):
start_pos, start_dir = self.map_generator.update()
self.start_pos = pygame.math.Vector2(start_pos)
self.start_dir = pygame.math.Vector2(start_dir).normalize()
def reset_car(self):
if self.start_pos is None or self.start_dir is None:
raise ValueError("Map not generated yet")
self.car = Car(self.car_image, self.start_pos)
self.car.direction = self.start_dir
self.rays = RayCasting(
self.car.pos, self.car.direction, self.map_generator.surface,
[-60, -30, -15, 0, 15, 30, 60],
[14, 22, 27, 26, 27, 22, 14],
draw_rays=False)
self.current_goal_index = 0
self.passed_goals = []
self.prev_pos = self.car.pos.copy()
self.previous_speed = 0.0
self.speed_history.clear()
self.steering_history.clear()
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.last_action = 0
def reset(self):
self.map_generator.difficulty = 2 # Ensure difficulty matches training
self.generate_new_map()
self.reset_car()
def detect_steering_need(self, ray_distances):
norm_distances = [min(d / self.rays.max_distance, 1.0) for d in ray_distances]
left_rays = norm_distances[0:3]
center_ray = norm_distances[3]
right_rays = norm_distances[4:7]
left_avg = sum(left_rays) / len(left_rays)
right_avg = sum(right_rays) / len(right_rays)
space_difference = right_avg - left_avg
steering_needed = False
preferred_direction = 0
urgency = 0.0
min_side_distance = min(min(left_rays), min(right_rays))
if min_side_distance < 0.3:
steering_needed = True
urgency = 1.0 - min_side_distance
preferred_direction = 1 if left_avg < right_avg else -1
elif abs(space_difference) > 0.15:
steering_needed = True
urgency = min(abs(space_difference), 1.0)
preferred_direction = 1 if space_difference > 0 else -1
elif center_ray < 0.4:
steering_needed = True
urgency = 1.0 - center_ray
preferred_direction = 1 if left_avg < right_avg else -1
return {
'needed': steering_needed,
'direction': preferred_direction,
'urgency': urgency,
'space_diff': space_difference,
'left_space': left_avg,
'right_space': right_avg,
'center_distance': center_ray
}
def get_state(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
steering_info = self.detect_steering_need(ray_distances)
state = [
self.car.velocity / self.car.max_velocity,
self.car.direction.x,
self.car.direction.y,
int(self.car.is_braking),
]
state.extend(normalized_ray_distances)
state.extend([
float(steering_info['needed']),
steering_info['direction'],
steering_info['urgency'],
steering_info['space_diff'],
steering_info['left_space'],
steering_info['right_space'],
steering_info['center_distance']
])
total_goals = len(self.map_generator.goals)
progress = self.current_goal_index / max(total_goals, 1)
state.append(progress)
state.append(self.last_action / 4.0)
speed_change = self.car.velocity - self.previous_speed
self.speed_history.append(speed_change)
avg_speed_change = sum(self.speed_history) / max(len(self.speed_history), 1)
state.extend([speed_change / 100.0, avg_speed_change / 100.0])
self.previous_speed = self.car.velocity
return np.array(state, dtype=np.float32)
def execute_action_dispatch(self, action, dt):
action_int = int(action)
self.last_action = action_int
keys = {'w': False, 'a': False, 'd': False, 's': False}
steer_factor = 1.0
if action_int == 0:
keys['w'] = True
elif action_int == 1:
keys['a'] = True
steer_factor = 1.0
elif action_int == 2:
keys['d'] = True
steer_factor = 1.0
elif action_int == 3:
keys['w'] = True
keys['a'] = True
steer_factor = 0.8
elif action_int == 4:
keys['w'] = True
keys['d'] = True
steer_factor = 0.8
elif action_int == 5:
keys['s'] = True
original_brake = self.car.brake_deceleration
self.car.brake_deceleration *= 0.6
self.car.update(dt, keys, steer_factor)
self.car.brake_deceleration = original_brake
return
elif action_int == 6:
keys['s'] = True
keys['a'] = True
steer_factor = 1.2
elif action_int == 7:
keys['s'] = True
keys['d'] = True
steer_factor = 1.2
self.car.update(dt, keys, steer_factor)
def detect_curve_severity(self, ray_distances, steering_info):
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
longest_distance = max(normalized_ray_distances)
longest_index = normalized_ray_distances.index(longest_distance)
main_ray_index = 3
if longest_index == main_ray_index:
return 0.0
left_adjacent_index = max(0, longest_index - 1)
right_adjacent_index = min(len(normalized_ray_distances) - 1, longest_index + 1)
left_adjacent_distance = normalized_ray_distances[left_adjacent_index]
right_adjacent_distance = normalized_ray_distances[right_adjacent_index]
if left_adjacent_distance > right_adjacent_distance:
longer_adjacent_index = left_adjacent_index
longer_adjacent_distance = left_adjacent_distance
else:
longer_adjacent_index = right_adjacent_index
longer_adjacent_distance = right_adjacent_distance
weight = longer_adjacent_distance / longest_distance
ray_angles = [-60, -30, -15, 0, 15, 30, 60]
longest_ray_angle = ray_angles[longest_index]
longer_adjacent_angle = ray_angles[longer_adjacent_index]
longest_pos_angle = longest_ray_angle + weight * (longer_adjacent_angle - longest_ray_angle)
front_ray_angle = ray_angles[main_ray_index]
angle_difference = abs(longest_pos_angle - front_ray_angle)
if angle_difference >= 50:
curve_severity = 1.0
else:
curve_severity = angle_difference / 40.0
return curve_severity
def calculate_reward(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
collision = self.rays.has_zero_length_ray()
if collision:
return -100.0, collision, False
steering_info = self.detect_steering_need(ray_distances)
reward = 0.0
curve_severity = self.detect_curve_severity(ray_distances, steering_info)
center_distance = ray_distances[3] / self.rays.max_distance
if center_distance > 0.25:
reward += 0.25 * self.car.velocity - 6
if curve_severity > 0.1:
if curve_severity > 0.5:
if 0.125 < self.car.velocity < 0.25:
reward += self.car.velocity / 10
else:
reward += -2
elif curve_severity > 0.25:
if 0.15 < self.car.velocity < 0.35:
reward += self.car.velocity / 12
else:
reward += -2
else:
if 0.35 < self.car.velocity < 0.7:
reward += self.car.velocity / 10
else:
reward += -2
else:
if self.car.velocity > 40:
reward += self.car.velocity / 20
elif self.car.velocity < 25:
reward += -0.5
if hasattr(self, 'speed_consistency_tracker'):
self.speed_consistency_tracker = {'appropriate': False, 'count': 0}
if steering_info['needed']:
steering_urgency = steering_info['urgency']
base_steering_reward = 5.0 + (steering_urgency * 4.0)
correct_action = False
if steering_info['direction'] == -1:
if self.last_action in [1, 3, 6]:
correct_action = True
if self.steering_persistence['direction'] == -1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': -1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 6:
base_steering_reward += 5.0
elif steering_info['direction'] == 1:
if self.last_action in [2, 4, 7]:
correct_action = True
if self.steering_persistence['direction'] == 1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': 1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 7:
base_steering_reward += 5.0
if correct_action:
reward += base_steering_reward
else:
self.steering_persistence = {'direction': 0, 'count': 0}
if steering_urgency > 0.6:
penalty = -4.0 * steering_urgency
reward += penalty
else:
self.steering_persistence = {'direction': 0, 'count': 0}
speed_factor = self.car.velocity / self.car.max_velocity
min_side_distance = min([ray_distances[i] for i in [0, 1, 2, 4, 5, 6]]) / self.rays.max_distance
center_distance = ray_distances[3] / self.rays.max_distance
if min_side_distance < 0.01:
danger_penalty = -5.0 * (1.0 - min_side_distance * 12.5) * (0.5 + speed_factor * 0.5)
reward += danger_penalty
elif min_side_distance < 0.0166:
if speed_factor > 0.7:
minor_penalty = -2 * (1.0 - min_side_distance * 6.67)
reward += minor_penalty
if 0.01666 <= min_side_distance and center_distance > 0.2:
safety_efficiency_bonus = 0.3
if 0.3 <= speed_factor <= 0.8:
safety_efficiency_bonus += 0.2
reward += safety_efficiency_bonus
total_goals = len(self.map_generator.goals)
if self.current_goal_index < total_goals:
goal = self.map_generator.goals[self.current_goal_index]
dist = point_to_line_distance(self.car.pos, goal[0], goal[1])
if dist < 8:
reward += 7.5
self.passed_goals.append(self.current_goal_index)
self.current_goal_index += 1
all_goals_completed = self.current_goal_index >= total_goals
if all_goals_completed:
reward += 20.0
reward = max(-15.0, min(reward, 12.0))
self.prev_pos = pygame.math.Vector2(self.car.pos)
self.last_steering_reward = reward
return reward, collision, all_goals_completed
def game_loop():
try:
pygame.init()
pygame.display.set_mode((1, 1), pygame.NOFRAME)
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
env = TrainingEnvironment(ACTION_SPACE)
env.reset()
agent = PPOAgent(state_size, ACTION_SPACE)
agent.load(LOADED_MODEL)
steps = 0
action_counts = [0] * ACTION_SPACE
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
state = env.get_state()
action, _ = agent.select_action(state)
action_int = int(action)
action_counts[action_int] += 1
env.execute_action_dispatch(action_int, DT)
reward, collision, all_goals_completed = env.calculate_reward()
env.rays.update(env.car.pos, env.car.direction)
if collision or all_goals_completed:
env.reset()
steps += 1
screen.fill((255, 255, 255))
env.map_generator.draw(screen)
env.car.draw(screen)
for i, (angle, offset) in enumerate(zip([-60, -30, -15, 0, 15, 30, 60], [14, 22, 27, 26, 27, 22, 14])):
if i < len(env.rays.last_collisions):
ray_dir = env.car.direction.rotate(angle).normalize()
origin = env.car.pos + ray_dir * offset
end_point = env.rays.last_collisions[i]
pygame.draw.line(screen, (255, 255, 0),
(int(origin.x), int(origin.y)),
(int(end_point.x), int(end_point.y)),
width=2)
# Optimized frame generation
raw_str = pygame.image.tostring(screen, 'RGB')
pil_image = Image.frombytes('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), raw_str)
try:
frame_queue.put(pil_image, block=False)
except queue.Full:
pass
clock.tick(SIMULATION_FPS)
if steps % 120 == 0:
print(f"Actual FPS: {clock.get_fps():.2f}")
except Exception as e:
print(f"Error in game loop: {e}")
def get_frame():
try:
return frame_queue.get_nowait()
except queue.Empty:
return Image.new('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), (0, 0, 0))
css = """#game-image {
height: calc(100vw * 9 / 16) !important;
object-fit: contain;
margin: 0 auto;
display: block;
}"""
def execute_interference():
game_thread = threading.Thread(target=game_loop)
game_thread.daemon = True
game_thread.start()
with gr.Blocks(css=css) as demo:
with gr.Column():
img = gr.Image(type="pil", label="Game Stream", elem_id="game-image", scale=1, min_width=0)
timer = gr.Timer(value=0.00833)
timer.tick(fn=get_frame, inputs=None, outputs=img)
demo.launch()
if __name__ == "__main__":
execute_interference()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270import gradio as gr
import numpy as np
import pygame
import threading
import time
import queue
from PIL import Image
from car_game_classes_gradio import Car, RayCasting, MapGenerator
from ppo_agent_gradio import PPOAgent
# Initialize Pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 1600, 900
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
# Define constants
DIFF_LVL = 2
ACTION_SPACE = 8
state_size = 22 # Based on TrainingEnvironment's get_state output
LOADED_MODEL = "model/18.6_car_model_epoch_270_lvl3_final.pth"
# Frame queue to hold the latest game frame
frame_queue = queue.Queue(maxsize=1)
class TrainingEnvironment:
def __init__(self, action_space=8):
self.action_space = action_space
self.map_generator = MapGenerator(SCREEN_WIDTH, SCREEN_HEIGHT, DIFF_LVL, 18)
car_surf = pygame.image.load("assets/car_transparent.png").convert_alpha()
w, h = car_surf.get_size()
self.car_image = pygame.transform.scale(car_surf, (w//18, h//18))
self.start_pos = None
self.start_dir = None
self.previous_speed = 0.0
self.speed_history = []
self.last_action = 0
self.reset()
def generate_new_map(self):
start_pos, start_dir = self.map_generator.update()
self.start_pos = pygame.math.Vector2(start_pos)
self.start_dir = pygame.math.Vector2(start_dir).normalize()
def reset_car(self):
if self.start_pos is None or self.start_dir is None:
raise ValueError("Map not generated yet")
self.car = Car(self.car_image, self.start_pos)
self.car.direction = self.start_dir
self.rays = RayCasting(
self.car.pos, self.car.direction, self.map_generator.surface,
[-60, -30, -15, 0, 15, 30, 60],
[14, 22, 27, 26, 27, 22, 14],
draw_rays=False)
self.current_goal_index = 0
self.previous_speed = 0.0
self.speed_history = []
self.last_action = 0
def reset(self):
self.generate_new_map()
self.reset_car()
def detect_steering_need(self, ray_distances):
norm_distances = [min(d / self.rays.max_distance, 1.0) for d in ray_distances]
left_rays = norm_distances[0:3]
center_ray = norm_distances[3]
right_rays = norm_distances[4:7]
left_avg = sum(left_rays) / len(left_rays)
right_avg = sum(right_rays) / len(right_rays)
space_difference = right_avg - left_avg
steering_needed = False
preferred_direction = 0
urgency = 0.0
min_side_distance = min(min(left_rays), min(right_rays))
if min_side_distance < 0.3:
steering_needed = True
urgency = 1.0 - min_side_distance
preferred_direction = 1 if left_avg < right_avg else -1
elif abs(space_difference) > 0.15:
steering_needed = True
urgency = min(abs(space_difference), 1.0)
preferred_direction = 1 if space_difference > 0 else -1
elif center_ray < 0.4:
steering_needed = True
urgency = 1.0 - center_ray
preferred_direction = 1 if left_avg < right_avg else -1
return {
'needed': steering_needed,
'direction': preferred_direction,
'urgency': urgency,
'space_diff': space_difference,
'left_space': left_avg,
'right_space': right_avg,
'center_distance': center_ray
}
def get_state(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
steering_info = self.detect_steering_need(ray_distances)
state = [
self.car.velocity / self.car.max_velocity,
self.car.direction.x,
self.car.direction.y,
int(self.car.is_braking),
]
state.extend(normalized_ray_distances)
state.extend([
float(steering_info['needed']),
steering_info['direction'],
steering_info['urgency'],
steering_info['space_diff'],
steering_info['left_space'],
steering_info['right_space'],
steering_info['center_distance']
])
total_goals = len(self.map_generator.goals)
progress = self.current_goal_index / max(total_goals, 1)
state.append(progress)
state.append(self.last_action / 4.0)
speed_change = self.car.velocity - self.previous_speed
self.speed_history.append(speed_change)
if len(self.speed_history) > 5:
self.speed_history.pop(0)
avg_speed_change = sum(self.speed_history) / max(len(self.speed_history), 1)
state.extend([speed_change / 100.0, avg_speed_change / 100.0])
self.previous_speed = self.car.velocity
return np.array(state, dtype=np.float32)
def execute_action_dispatch(self, action, dt):
action_int = int(action)
self.last_action = action_int
keys = {'w': False, 'a': False, 'd': False, 's': False}
steer_factor = 1.0
if action_int == 0:
keys['w'] = True
elif action_int == 1:
keys['a'] = True
steer_factor = 1.0
elif action_int == 2:
keys['d'] = True
steer_factor = 1.0
elif action_int == 3:
keys['w'] = True
keys['a'] = True
steer_factor = 0.8
elif action_int == 4:
keys['w'] = True
keys['d'] = True
steer_factor = 0.8
elif action_int == 5:
keys['s'] = True
original_brake = self.car.brake_deceleration
self.car.brake_deceleration *= 0.6
self.car.update(dt, keys, steer_factor)
self.car.brake_deceleration = original_brake
return
elif action_int == 6:
keys['s'] = True
keys['a'] = True
steer_factor = 1.2
elif action_int == 7:
keys['s'] = True
keys['d'] = True
steer_factor = 1.2
self.car.update(dt, keys, steer_factor)
def game_loop():
try:
# Initialize Pygame
pygame.init()
# Set a dummy display mode to satisfy Pygame's requirement
pygame.display.set_mode((1, 1), pygame.NOFRAME)
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
# Example environment and agent setup (replace with your actual classes)
env = TrainingEnvironment(ACTION_SPACE)
env.reset()
agent = PPOAgent(state_size, ACTION_SPACE)
agent.load(LOADED_MODEL) # Ensure LOADED_MODEL is defined
# Simulation and rendering settings
simulation_fps = 120
render_fps = 30
render_interval = simulation_fps // render_fps # 4
dt = 1.0 / simulation_fps
steps = 0
while True:
# Game logic
state = env.get_state()
action, _ = agent.select_action(state)
env.execute_action_dispatch(action, dt)
env.rays.update(env.car.pos, env.car.direction)
if env.rays.has_zero_length_ray():
env.reset()
steps += 1
# Render at specified intervals
if steps % render_interval == 0:
screen.fill((255, 255, 255)) # White background
env.map_generator.draw(screen)
env.car.draw(screen)
# Draw rays (example implementation)
for i, (angle, offset) in enumerate(zip([-60, -30, -15, 0, 15, 30, 60], [14, 22, 27, 26, 27, 22, 14])):
if i < len(env.rays.last_collisions):
ray_dir = env.car.direction.rotate(angle).normalize()
origin = env.car.pos + ray_dir * offset
end_point = env.rays.last_collisions[i]
pygame.draw.line(screen, (255, 255, 0),
(int(origin.x), int(origin.y)),
(int(end_point.x), int(end_point.y)),
width=2)
# Convert surface to array and then to PIL image for Gradio
frame_array = pygame.surfarray.array3d(screen)
frame_array = np.transpose(frame_array, (1, 0, 2)) # Swap axes for correct orientation
pil_image = Image.fromarray(frame_array)
pil_image = pil_image.resize((SCREEN_WIDTH, SCREEN_HEIGHT)) # Adjust size as needed
# Send to Gradio queue (ensure frame_queue is defined in your code)
try:
frame_queue.put(pil_image, block=False)
except queue.Full:
pass
time.sleep(dt) # Control simulation speed
except Exception as e:
print(f"Error in game loop: {e}")
def get_frame():
try:
return frame_queue.get_nowait()
except queue.Empty:
return Image.new('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), (0, 0, 0))
css="""#game-image {
height: calc(100vw * 9 / 16) !important;
object-fit: contain;
margin: 0 auto;
display: block;
}"""
def execute_interference():
game_thread = threading.Thread(target=game_loop)
game_thread.start()
with gr.Blocks(css=css) as demo:
with gr.Column():
img = gr.Image(
type="pil",
label="Game Stream",
elem_id="game-image",
scale=1,
min_width=0
)
with gr.Column():
with gr.Row():
simulation_speed = gr.Slider(30, 300, 120, step=10.0, label="Simulation_Speed")
difficulty_lvl = gr.Slider(1, 2, 2, step=1, label="Difficulty of Street")
fps = gr.Slider(24, 120, 30, step=1, label="FPS")
timer = gr.Timer(value=0.033) # Approximately 30 FPS
timer.tick(fn=get_frame, inputs=None, outputs=img)
demo.launch()
if __name__ == "__main__":
execute_interference()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401import gradio as gr
import numpy as np
import pygame
import threading
import queue
from PIL import Image
from car_game_classes_gradio import Car, RayCasting, MapGenerator
from ppo_agent_gradio import PPOAgent
from collections import deque
# Initialize Pygame
pygame.init()
SCREEN_WIDTH, SCREEN_HEIGHT = 1600, 900
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
clock = pygame.time.Clock()
# Define constants
ACTION_SPACE = 8
state_size = 22
LOADED_MODEL = "model/18.6_car_model_epoch_270_lvl3_final.pth"
SIMULATION_FPS = 120 # Fixed simulation FPS, matching training
DT = 1.0 / SIMULATION_FPS # Fixed time step
# Frame queue for Gradio
frame_queue = queue.Queue(maxsize=1)
def point_to_line_distance(point, line_p0, line_p1):
p = pygame.math.Vector2(point)
a = pygame.math.Vector2(line_p0)
b = pygame.math.Vector2(line_p1)
ap = p - a
ab = b - a
magnitude_ab = ab.length_squared()
if magnitude_ab == 0:
return ap.length()
projection = ap.dot(ab) / magnitude_ab
projection = max(0, min(1, projection))
closest = a + projection * ab
return p.distance_to(closest)
class TrainingEnvironment:
def __init__(self, action_space=8):
self.action_space = action_space
self.map_generator = MapGenerator(SCREEN_WIDTH, SCREEN_HEIGHT, 2, 18) # Difficulty 2 = lvl 3 in training
car_surf = pygame.image.load("assets/car_transparent.png").convert_alpha()
w, h = car_surf.get_size()
self.car_image = pygame.transform.scale(car_surf, (w//18, h//18))
self.start_pos = None
self.start_dir = None
self.previous_speed = 0.0
self.speed_history = deque(maxlen=5)
self.steering_history = deque(maxlen=10)
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.prev_pos = None
self.passed_goals = []
self.last_action = 0
self.reset()
def generate_new_map(self):
start_pos, start_dir = self.map_generator.update()
self.start_pos = pygame.math.Vector2(start_pos)
self.start_dir = pygame.math.Vector2(start_dir).normalize()
def reset_car(self):
if self.start_pos is None or self.start_dir is None:
raise ValueError("Map not generated yet")
self.car = Car(self.car_image, self.start_pos)
self.car.direction = self.start_dir
self.rays = RayCasting(
self.car.pos, self.car.direction, self.map_generator.surface,
[-60, -30, -15, 0, 15, 30, 60],
[14, 22, 27, 26, 27, 22, 14],
draw_rays=False)
self.current_goal_index = 0
self.passed_goals = []
self.prev_pos = self.car.pos.copy()
self.previous_speed = 0.0
self.speed_history.clear()
self.steering_history.clear()
self.steering_persistence = {'direction': 0, 'count': 0}
self.last_steering_reward = 0.0
self.last_action = 0
def reset(self):
self.map_generator.difficulty = 2 # Ensure difficulty matches training
self.generate_new_map()
self.reset_car()
def detect_steering_need(self, ray_distances):
norm_distances = [min(d / self.rays.max_distance, 1.0) for d in ray_distances]
left_rays = norm_distances[0:3]
center_ray = norm_distances[3]
right_rays = norm_distances[4:7]
left_avg = sum(left_rays) / len(left_rays)
right_avg = sum(right_rays) / len(right_rays)
space_difference = right_avg - left_avg
steering_needed = False
preferred_direction = 0
urgency = 0.0
min_side_distance = min(min(left_rays), min(right_rays))
if min_side_distance < 0.3:
steering_needed = True
urgency = 1.0 - min_side_distance
preferred_direction = 1 if left_avg < right_avg else -1
elif abs(space_difference) > 0.15:
steering_needed = True
urgency = min(abs(space_difference), 1.0)
preferred_direction = 1 if space_difference > 0 else -1
elif center_ray < 0.4:
steering_needed = True
urgency = 1.0 - center_ray
preferred_direction = 1 if left_avg < right_avg else -1
return {
'needed': steering_needed,
'direction': preferred_direction,
'urgency': urgency,
'space_diff': space_difference,
'left_space': left_avg,
'right_space': right_avg,
'center_distance': center_ray
}
def get_state(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
steering_info = self.detect_steering_need(ray_distances)
state = [
self.car.velocity / self.car.max_velocity,
self.car.direction.x,
self.car.direction.y,
int(self.car.is_braking),
]
state.extend(normalized_ray_distances)
state.extend([
float(steering_info['needed']),
steering_info['direction'],
steering_info['urgency'],
steering_info['space_diff'],
steering_info['left_space'],
steering_info['right_space'],
steering_info['center_distance']
])
total_goals = len(self.map_generator.goals)
progress = self.current_goal_index / max(total_goals, 1)
state.append(progress)
state.append(self.last_action / 4.0)
speed_change = self.car.velocity - self.previous_speed
self.speed_history.append(speed_change)
avg_speed_change = sum(self.speed_history) / max(len(self.speed_history), 1)
state.extend([speed_change / 100.0, avg_speed_change / 100.0])
self.previous_speed = self.car.velocity
return np.array(state, dtype=np.float32)
def execute_action_dispatch(self, action, dt):
action_int = int(action)
self.last_action = action_int
keys = {'w': False, 'a': False, 'd': False, 's': False}
steer_factor = 1.0
if action_int == 0:
keys['w'] = True
elif action_int == 1:
keys['a'] = True
steer_factor = 1.0
elif action_int == 2:
keys['d'] = True
steer_factor = 1.0
elif action_int == 3:
keys['w'] = True
keys['a'] = True
steer_factor = 0.8
elif action_int == 4:
keys['w'] = True
keys['d'] = True
steer_factor = 0.8
elif action_int == 5:
keys['s'] = True
original_brake = self.car.brake_deceleration
self.car.brake_deceleration *= 0.6
self.car.update(dt, keys, steer_factor)
self.car.brake_deceleration = original_brake
return
elif action_int == 6:
keys['s'] = True
keys['a'] = True
steer_factor = 1.2
elif action_int == 7:
keys['s'] = True
keys['d'] = True
steer_factor = 1.2
self.car.update(dt, keys, steer_factor)
def detect_curve_severity(self, ray_distances, steering_info):
normalized_ray_distances = [min(distance / self.rays.max_distance, 1.0) for distance in ray_distances]
longest_distance = max(normalized_ray_distances)
longest_index = normalized_ray_distances.index(longest_distance)
main_ray_index = 3
if longest_index == main_ray_index:
return 0.0
left_adjacent_index = max(0, longest_index - 1)
right_adjacent_index = min(len(normalized_ray_distances) - 1, longest_index + 1)
left_adjacent_distance = normalized_ray_distances[left_adjacent_index]
right_adjacent_distance = normalized_ray_distances[right_adjacent_index]
if left_adjacent_distance > right_adjacent_distance:
longer_adjacent_index = left_adjacent_index
longer_adjacent_distance = left_adjacent_distance
else:
longer_adjacent_index = right_adjacent_index
longer_adjacent_distance = right_adjacent_distance
weight = longer_adjacent_distance / longest_distance
ray_angles = [-60, -30, -15, 0, 15, 30, 60]
longest_ray_angle = ray_angles[longest_index]
longer_adjacent_angle = ray_angles[longer_adjacent_index]
longest_pos_angle = longest_ray_angle + weight * (longer_adjacent_angle - longest_ray_angle)
front_ray_angle = ray_angles[main_ray_index]
angle_difference = abs(longest_pos_angle - front_ray_angle)
if angle_difference >= 50:
curve_severity = 1.0
else:
curve_severity = angle_difference / 40.0
return curve_severity
def calculate_reward(self):
self.rays.update(self.car.pos, self.car.direction)
ray_distances = self.rays.get_ray_distances()
collision = self.rays.has_zero_length_ray()
if collision:
return -100.0, collision, False
steering_info = self.detect_steering_need(ray_distances)
reward = 0.0
curve_severity = self.detect_curve_severity(ray_distances, steering_info)
center_distance = ray_distances[3] / self.rays.max_distance
if center_distance > 0.25:
reward += 0.25 * self.car.velocity - 6
if curve_severity > 0.1:
if curve_severity > 0.5:
if 0.125 < self.car.velocity < 0.25:
reward += self.car.velocity / 10
else:
reward += -2
elif curve_severity > 0.25:
if 0.15 < self.car.velocity < 0.35:
reward += self.car.velocity / 12
else:
reward += -2
else:
if 0.35 < self.car.velocity < 0.7:
reward += self.car.velocity / 10
else:
reward += -2
else:
if self.car.velocity > 40:
reward += self.car.velocity / 20
elif self.car.velocity < 25:
reward += -0.5
if hasattr(self, 'speed_consistency_tracker'):
self.speed_consistency_tracker = {'appropriate': False, 'count': 0}
if steering_info['needed']:
steering_urgency = steering_info['urgency']
base_steering_reward = 5.0 + (steering_urgency * 4.0)
correct_action = False
if steering_info['direction'] == -1:
if self.last_action in [1, 3, 6]:
correct_action = True
if self.steering_persistence['direction'] == -1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': -1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 6:
base_steering_reward += 5.0
elif steering_info['direction'] == 1:
if self.last_action in [2, 4, 7]:
correct_action = True
if self.steering_persistence['direction'] == 1:
self.steering_persistence['count'] += 2
persistence_bonus = min(3.0, self.steering_persistence['count'] * 0.5)
base_steering_reward += persistence_bonus
else:
self.steering_persistence = {'direction': 1, 'count': 1}
if curve_severity > 0.4 and self.last_action == 7:
base_steering_reward += 5.0
if correct_action:
reward += base_steering_reward
else:
self.steering_persistence = {'direction': 0, 'count': 0}
if steering_urgency > 0.6:
penalty = -4.0 * steering_urgency
reward += penalty
else:
self.steering_persistence = {'direction': 0, 'count': 0}
speed_factor = self.car.velocity / self.car.max_velocity
min_side_distance = min([ray_distances[i] for i in [0, 1, 2, 4, 5, 6]]) / self.rays.max_distance
center_distance = ray_distances[3] / self.rays.max_distance
if min_side_distance < 0.01:
danger_penalty = -5.0 * (1.0 - min_side_distance * 12.5) * (0.5 + speed_factor * 0.5)
reward += danger_penalty
elif min_side_distance < 0.0166:
if speed_factor > 0.7:
minor_penalty = -2 * (1.0 - min_side_distance * 6.67)
reward += minor_penalty
if 0.01666 <= min_side_distance and center_distance > 0.2:
safety_efficiency_bonus = 0.3
if 0.3 <= speed_factor <= 0.8:
safety_efficiency_bonus += 0.2
reward += safety_efficiency_bonus
total_goals = len(self.map_generator.goals)
if self.current_goal_index < total_goals:
goal = self.map_generator.goals[self.current_goal_index]
dist = point_to_line_distance(self.car.pos, goal[0], goal[1])
if dist < 8:
reward += 7.5
self.passed_goals.append(self.current_goal_index)
self.current_goal_index += 1
all_goals_completed = self.current_goal_index >= total_goals
if all_goals_completed:
reward += 20.0
reward = max(-15.0, min(reward, 12.0))
self.prev_pos = pygame.math.Vector2(self.car.pos)
self.last_steering_reward = reward
return reward, collision, all_goals_completed
def game_loop():
try:
pygame.init()
pygame.display.set_mode((1, 1), pygame.NOFRAME)
screen = pygame.Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
env = TrainingEnvironment(ACTION_SPACE)
env.reset()
agent = PPOAgent(state_size, ACTION_SPACE)
agent.load(LOADED_MODEL)
steps = 0
action_counts = [0] * ACTION_SPACE
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
return
state = env.get_state()
action, _ = agent.select_action(state)
action_int = int(action)
action_counts[action_int] += 1
env.execute_action_dispatch(action_int, DT)
reward, collision, all_goals_completed = env.calculate_reward()
env.rays.update(env.car.pos, env.car.direction)
if collision or all_goals_completed:
env.reset()
steps += 1
screen.fill((255, 255, 255))
env.map_generator.draw(screen)
env.car.draw(screen)
for i, (angle, offset) in enumerate(zip([-60, -30, -15, 0, 15, 30, 60], [14, 22, 27, 26, 27, 22, 14])):
if i < len(env.rays.last_collisions):
ray_dir = env.car.direction.rotate(angle).normalize()
origin = env.car.pos + ray_dir * offset
end_point = env.rays.last_collisions[i]
pygame.draw.line(screen, (255, 255, 0),
(int(origin.x), int(origin.y)),
(int(end_point.x), int(end_point.y)),
width=2)
# Optimized frame generation
raw_str = pygame.image.tostring(screen, 'RGB')
pil_image = Image.frombytes('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), raw_str)
try:
frame_queue.put(pil_image, block=False)
except queue.Full:
pass
clock.tick(SIMULATION_FPS)
if steps % 120 == 0:
print(f"Actual FPS: {clock.get_fps():.2f}")
except Exception as e:
print(f"Error in game loop: {e}")
def get_frame():
try:
return frame_queue.get_nowait()
except queue.Empty:
return Image.new('RGB', (SCREEN_WIDTH, SCREEN_HEIGHT), (0, 0, 0))
css = """#game-image {
height: calc(100vw * 9 / 16) !important;
object-fit: contain;
margin: 0 auto;
display: block;
}"""
def execute_interference():
game_thread = threading.Thread(target=game_loop)
game_thread.daemon = True
game_thread.start()
with gr.Blocks(css=css) as demo:
with gr.Column():
img = gr.Image(type="pil", label="Game Stream", elem_id="game-image", scale=1, min_width=0)
timer = gr.Timer(value=0.00833)
timer.tick(fn=get_frame, inputs=None, outputs=img)
demo.launch()
if __name__ == "__main__":
execute_interference()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378import pygame
import math
import numpy as np
class MapGenerator:
def __init__(self, width, height, difficulty, goals):
self.surface = pygame.Surface((width, height))
self.width = width
self.height = height
self.difficulty = difficulty
self.goals = []
self.num_goals = goals if isinstance(goals, int) else len(goals) if goals else 12
self.curve_pts = [] # Added to store curve points
def update(self):
self.surface.fill((255, 255, 255))
if self.difficulty == 1:
border = 50
num_ctrl = 4
x_coords = [i * (self.width/(num_ctrl-1)) for i in range(num_ctrl)]
x_coords[0], x_coords[-1] = border*2, self.width-border*2
y_coords = np.random.randint(border*4, self.height-border*4, num_ctrl)
ctrl_pts = list(zip(x_coords, y_coords))
curve_pts = self.compute_catmull_rom(ctrl_pts, 800)
road_width = 100
if self.difficulty == 2:
border = 50
num_ctrl = 5
x_coords = [i * (self.width/(num_ctrl-1)) for i in range(num_ctrl)]
x_coords[0], x_coords[-1] = border*2, self.width-border*2
# Generate y coordinates with alternating high/low pattern
y_coords = []
# Define high and low ranges
high_range = (self.height//2 + 2*border, self.height - int(border*5.5))
low_range = (int(border*5.5), self.height//2 - 2*border)
# Generate first point randomly
first_y = np.random.randint(int(border*5.5), self.height-int(border*5.5))
y_coords.append(first_y)
# Determine if first point is high or low
is_first_high = first_y > self.height // 2
# Generate remaining points alternating between high and low
for i in range(1, num_ctrl):
index_prev = i-1
y_previous = y_coords[index_prev]
diff_min = 75
diff_max = 225
if is_first_high:
if (i - 1) % 2 == 0: # Previous was high (first point)
y = np.random.randint(y_previous-diff_max, y_previous-diff_min)
else: # Previous was low
y = np.random.randint(y_previous+diff_min, y_previous+diff_max)
else:
# If previous point was low, make this one high
if (i - 1) % 2 == 0: # Previous was low (first point)
y = np.random.randint(y_previous+diff_min, y_previous+diff_max)
else: # Previous was high
y = np.random.randint(y_previous-diff_max, y_previous-diff_min)
y_coords.append(y)
ctrl_pts = list(zip(x_coords, y_coords))
curve_pts = self.compute_catmull_rom(ctrl_pts, 50)
curve_pts = self.compute_catmull_rom(curve_pts, 800)
road_width = 100
self.curve_pts = curve_pts # Store curve points
# Create goals
goals_pts = self.create_goals(curve_pts)
self.goals = goals_pts
# Draw roads as connected segments
self.draw_road_segments(curve_pts, road_width)
# Draw goals
for goal_index in goals_pts:
pygame.draw.line(self.surface, (0,0,255), goal_index[0], goal_index[1], width=2)
# Get car start
if len(curve_pts) >= 2:
start_pos = curve_pts[0]
xs, ys = start_pos
xe, ye = curve_pts[1]
x = xe - xs
y = ye - ys
start_dir = (x, y)
else:
start_pos = (100, self.height//2)
start_dir = (1, 0)
return pygame.math.Vector2(start_pos), pygame.math.Vector2(start_dir)
def draw_road_segments(self, points, road_width):
if len(points) < 2:
return
for i in range(len(points) - 1):
start_pos = (int(points[i][0]), int(points[i][1]))
end_pos = (int(points[i+1][0]), int(points[i+1][1]))
pygame.draw.line(self.surface, (0, 0, 0), start_pos, end_pos, width=road_width)
cap_radius = road_width // 2
for point in points:
pygame.draw.circle(self.surface, (0, 0, 0), (int(point[0]), int(point[1])), cap_radius)
def compute_catmull_rom(self, control_points, steps_per_segment=20):
try:
is_loop = control_points[0] == control_points[-1]
if hasattr(is_loop, '__len__') and len(is_loop) > 1:
is_loop = np.allclose(control_points[0], control_points[-1])
except:
first = np.array(control_points[0])
last = np.array(control_points[-1])
is_loop = np.allclose(first, last)
pts = control_points[:-1] if is_loop else control_points
n = len(pts)
points = []
def get(idx):
if is_loop:
return pts[idx % n]
else:
return pts[min(max(idx, 0), n - 1)]
for i in range(n if is_loop else n - 1):
p0 = get(i - 1)
p1 = get(i)
p2 = get(i + 1)
p3 = get(i + 2)
for j in range(steps_per_segment):
t = j / steps_per_segment
t2 = t * t
t3 = t2 * t
f1 = -0.5 * t3 + t2 - 0.5 * t
f2 = 1.5 * t3 - 2.5 * t2 + 1.0
f3 = -1.5 * t3 + 2.0 * t2 + 0.5 * t
f4 = 0.5 * t3 - 0.5 * t2
x = f1 * p0[0] + f2 * p1[0] + f3 * p2[0] + f4 * p3[0]
y = f1 * p0[1] + f2 * p1[1] + f3 * p2[1] + f4 * p3[1]
points.append((x, y))
if not is_loop:
points.append(tuple(pts[-1]))
return points
def resample_by_distance(self, points, desired_spacing):
if len(points) < 2:
return points
dists = [0.0]
for i in range(1, len(points)):
prev, curr = np.array(points[i-1]), np.array(points[i])
dist = float(np.linalg.norm(curr - prev))
dists.append(dists[-1] + dist)
total_len = dists[-1]
if total_len == 0:
return points
n_points = int(total_len // desired_spacing)
new_pts = []
for k in range(n_points+1):
target = k * desired_spacing
for j in range(1, len(dists)):
if dists[j] >= target:
ratio = (target - dists[j-1])/(dists[j] - dists[j-1])
A, B = np.array(points[j-1]), np.array(points[j])
P = A + ratio*(B - A)
new_pts.append(tuple(P))
break
return new_pts if new_pts else points
def create_goals(self, pts, goal_number=None):
n_pts = len(pts)
if goal_number is not None:
num_goals = goal_number
else:
num_goals = self.num_goals
if n_pts == 0 or num_goals == 0:
return []
actual_goals = min(num_goals, n_pts // 10)
if actual_goals == 0:
actual_goals = 1
lines = []
last_dir = None
for k in range(actual_goals):
if actual_goals == 1:
idx = n_pts // 2
else:
idx = int((k * (n_pts - 1)) / (actual_goals - 1))
idx = max(0, min(idx, n_pts - 1))
idx2 = idx
look_ahead = 5
if idx + look_ahead < n_pts:
idx2 = idx + look_ahead
elif idx >= look_ahead:
idx2 = idx - look_ahead
elif idx + 1 < n_pts:
idx2 = idx + 1
elif idx > 0:
idx2 = idx - 1
x, y = pts[idx]
if idx2 != idx:
x1, y1 = pts[idx2]
dir_vec = pygame.math.Vector2(x1 - x, y1 - y)
if idx2 < idx:
dir_vec *= -1
else:
dir_vec = last_dir if last_dir else pygame.math.Vector2(0, -1)
if dir_vec.length_squared() < 1e-8:
dir_vec = pygame.math.Vector2(0, -1)
else:
dir_vec = dir_vec.normalize()
if last_dir and dir_vec.dot(last_dir) < -0.5:
dir_vec *= -1
last_dir = dir_vec
normal = dir_vec.rotate(90)
p0 = pygame.math.Vector2(x, y) + normal * 50
p1 = pygame.math.Vector2(x, y) - normal * 50
lines.append((p0, p1))
return lines
def draw(self, surface):
surface.blit(self.surface, (0,0))
class Car:
def __init__(self, image, pos, max_velocity=275, turn_speed=77.5):
self.original_image = image.convert_alpha()
self.image = self.original_image
self.pos = pygame.math.Vector2(pos)
self.velocity = 0.0
self.max_velocity = max_velocity
self.direction = pygame.math.Vector2(1, 0)
self.turn_speed = turn_speed
self.angle = 0.0
self.is_braking = False
self.acceleration = 55.0
self.deceleration = 16.0
self.brake_deceleration = 55.0
self.min_velocity_threshold = 5.0
def update(self, dt, keys=None, steer_factor=1.0):
if keys is None:
pressed = pygame.key.get_pressed()
keys = {
'w': pressed[pygame.K_w],
'a': pressed[pygame.K_a],
's': pressed[pygame.K_s],
'd': pressed[pygame.K_d]
}
self.is_braking = False
if keys.get('w', False):
acceleration_multiplier = 1.0
if self.velocity > 50:
acceleration_multiplier = 1.2
elif self.velocity < 20:
acceleration_multiplier = 1.5
if self.velocity < self.max_velocity:
self.velocity += self.acceleration * acceleration_multiplier * dt
if self.velocity > self.max_velocity:
self.velocity = self.max_velocity
if keys.get('s', False):
self.is_braking = True
if self.velocity > 0:
brake_multiplier = 1.0 + (self.velocity / self.max_velocity) * 0.5
self.velocity -= self.brake_deceleration * brake_multiplier * dt
if self.velocity < 0:
self.velocity = 0
else:
if not keys.get('w', False) and self.velocity > 0:
decel_rate = self.deceleration
if self.velocity > 100:
decel_rate *= 0.7
self.velocity -= decel_rate * dt
if self.velocity < self.min_velocity_threshold:
self.velocity = max(0, self.velocity - 2.0 * dt)
if self.velocity > 0:
self.pos += self.direction.normalize() * self.velocity * dt
if self.velocity > 10:
angular_velocity = 0
speed_factor = min(1.0, self.velocity / 200.0)
effective_turn_speed = self.turn_speed * (0.5 + 0.5 * speed_factor)
if keys.get('a', False):
angular_velocity = -effective_turn_speed * steer_factor
elif keys.get('d', False):
angular_velocity = effective_turn_speed * steer_factor
if angular_velocity != 0:
angle_change = angular_velocity * dt
target_direction = self.direction.rotate(angle_change)
base_drift = 0.15
velocity_factor = min(1.0, self.velocity / self.max_velocity)
drift_factor = base_drift * (0.5 + 0.5 * velocity_factor)
self.direction = (self.direction * drift_factor +
target_direction * (1 - drift_factor)).normalize()
self.angle = -math.degrees(math.atan2(self.direction.y, self.direction.x))
self.image = pygame.transform.rotate(self.original_image, self.angle)
def draw(self, surface):
rect = self.image.get_rect(center=self.pos)
surface.blit(self.image, rect.topleft)
def reset(self, pos, direction):
self.pos = pygame.math.Vector2(pos)
self.direction = pygame.math.Vector2(direction).normalize()
self.velocity = 0.0
self.angle = -math.degrees(math.atan2(self.direction.y, self.direction.x))
class RayCasting:
def __init__(self, car_pos, car_dir, track_surf,
ray_angles, ray_offsets, max_distance=1600, step_pixels=1, draw_rays=True):
self.car_pos = pygame.math.Vector2(car_pos)
self.car_dir = pygame.math.Vector2(car_dir).normalize()
self.track_surf = track_surf
self.ray_angles = list(ray_angles)
self.ray_offsets = list(ray_offsets)
self.max_distance = max_distance
self.step_pixels = step_pixels
self.last_collisions = [self.car_pos.copy()] * len(self.ray_angles)
self.ray_distances = [0.0] * len(self.ray_angles)
self.draw_rays = draw_rays
def cast_ray(self, start_pos, direction):
pos = pygame.math.Vector2(start_pos)
dir_norm = pygame.math.Vector2(direction).normalize()
inv = max(abs(dir_norm.x), abs(dir_norm.y))
step_size = (1.0 / inv) if inv != 0 else 1.0
traveled = 0.0
w, h = self.track_surf.get_size()
while traveled < self.max_distance:
ix, iy = int(pos.x), int(pos.y)
if 0 <= ix < w and 0 <= iy < h:
color = self.track_surf.get_at((ix, iy))
if color[:3] == (255, 255, 255):
return pos, traveled
pos += dir_norm * (step_size * self.step_pixels)
traveled += step_size * self.step_pixels
return pos, traveled
def draw_ray(self, start, end, color=(255, 255, 0)):
pygame.draw.line(self.track_surf, color,
(int(start.x), int(start.y)),
(int(end.x), int(end.y)),
width=2)
def update(self, car_pos, car_dir):
self.car_pos = pygame.math.Vector2(car_pos)
self.car_dir = pygame.math.Vector2(car_dir).normalize()
self.last_collisions = []
self.ray_distances = []
any_origin_in_white = False
for angle, offset in zip(self.ray_angles, self.ray_offsets):
ray_dir = self.car_dir.rotate(angle).normalize()
origin = self.car_pos + ray_dir * offset
ix, iy = int(origin.x), int(origin.y)
w, h = self.track_surf.get_size()
if 0 <= ix < w and 0 <= iy < h:
if self.track_surf.get_at((ix, iy))[:3] == (255, 255, 255):
any_origin_in_white = True
self.last_collisions.append(origin)
self.ray_distances.append(0.0)
continue
hit_pt, distance = self.cast_ray(origin, ray_dir)
self.last_collisions.append(hit_pt)
self.ray_distances.append(distance)
if self.draw_rays:
self.draw_ray(origin, hit_pt)
return not any_origin_in_white
def get_ray_distances(self):
return self.ray_distances.copy()
def has_zero_length_ray(self):
return any(distance <= 0.0 for distance in self.ray_distances)123version https://git-lfs.github.com/spec/v1oid sha256:9e6d5897b2d6c2f706fe892512c92f6be2e80620708a8733e8d078023bfc98c7size 4257707123version https://git-lfs.github.com/spec/v1oid sha256:9e6d5897b2d6c2f706fe892512c92f6be2e80620708a8733e8d078023bfc98c7size 4257707123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np
class PolicyNetwork(nn.Module):
def __init__(self, state_dim, action_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, action_dim)
)
for layer in self.net:
if isinstance(layer, nn.Linear):
nn.init.xavier_uniform_(layer.weight)
nn.init.constant_(layer.bias, 0)
def forward(self, state):
return self.net(state)
class ValueNetwork(nn.Module):
def __init__(self, state_dim):
super().__init__()
self.net = nn.Sequential(
nn.Linear(state_dim, 512),
nn.ReLU(),
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 1)
)
for layer in self.net:
if isinstance(layer, nn.Linear):
nn.init.xavier_uniform_(layer.weight)
nn.init.constant_(layer.bias, 0)
def forward(self, state):
return self.net(state)
class PPOAgent:
def __init__(self, state_dim, action_dim, lr=3e-4, gamma=0.99, clip_eps=0.2):
self.policy = PolicyNetwork(state_dim, action_dim)
self.value = ValueNetwork(state_dim)
self.optimizer = optim.Adam(
list(self.policy.parameters()) + list(self.value.parameters()),
lr=lr
)
self.memory = []
self.gamma = gamma
self.clip_eps = clip_eps
self.epsilon = 1.0
self.epsilon_decay = 0.995
self.epsilon_min = 0.1
self.mini_batch_size = 256
self.update_epochs = 4
def select_action(self, state):
state = torch.FloatTensor(state).unsqueeze(0)
# Add input validation
if torch.isnan(state).any() or torch.isinf(state).any():
print(f"Warning: Invalid state detected: {state}")
action = np.random.randint(0, 8)
log_prob = torch.log(torch.tensor(1/8))
return action, log_prob
with torch.no_grad():
logits = self.policy(state)
if torch.isnan(logits).any() or torch.isinf(logits).any():
print(f"Warning: Invalid logits detected: {logits}")
action = np.random.randint(0, 8)
log_prob = torch.log(torch.tensor(1/8))
return action, log_prob
# Apply temperature scaling
logits = logits / 1.0
probs = torch.softmax(logits, dim=-1)
# Add small epsilon to prevent zero probabilities
probs = probs + 1e-8
probs = probs / probs.sum(dim=-1, keepdim=True)
dist = Categorical(probs)
action = dist.sample()
return action.item(), dist.log_prob(action)
def store_experience(self, state, action, reward, next_state, done, log_prob):
# Validate inputs before storing
if not (torch.isnan(torch.FloatTensor(state)).any() or
torch.isnan(torch.FloatTensor(next_state)).any() or
torch.isnan(log_prob).any() or
np.isnan(reward)):
self.memory.append((state, action, reward, next_state, done, log_prob))
def calculate_returns_and_advantages_optimized(self, rewards, values, dones):
"""
Optimized O(n) calculation of returns and advantages using GAE
"""
returns = torch.zeros_like(rewards)
advantages = torch.zeros_like(rewards)
# GAE parameters
gae_lambda = 0.95
# Calculate advantages and returns in reverse order (O(n))
last_gae = 0
for i in reversed(range(len(rewards))):
if i == len(rewards) - 1:
next_value = 0 # Terminal state
else:
next_value = values[i + 1]
# TD error
delta = rewards[i] + self.gamma * next_value - values[i]
# GAE advantage
advantages[i] = last_gae = delta + self.gamma * gae_lambda * last_gae
# Returns = advantages + values
returns[i] = advantages[i] + values[i]
return returns, advantages
def update(self, epochs=None):
if len(self.memory) < 32: # Minimum batch size
return None
# Use instance variable if epochs not specified
if epochs is None:
epochs = self.update_epochs
# Convert experience buffer to tensors
states, actions, rewards, next_states, dones, old_log_probs = zip(*self.memory)
states = torch.FloatTensor(np.array(states))
actions = torch.LongTensor(actions)
rewards = torch.FloatTensor(rewards)
old_log_probs = torch.stack(old_log_probs)
# Validate tensors
if (torch.isnan(states).any() or torch.isnan(rewards).any() or
torch.isnan(old_log_probs).any()):
print("Warning: NaN detected in experience buffer, skipping update")
self.memory.clear()
return None
# Get values for all states at once
with torch.no_grad():
values = self.value(states).squeeze(-1)
# OPTIMIZED: O(n) returns and advantages calculation
returns, advantages = self.calculate_returns_and_advantages_optimized(
rewards, values, torch.zeros_like(rewards) # dones placeholder
)
# Normalize advantages
if len(advantages) > 1 and advantages.std() > 1e-8:
advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-8)
# Mini-batch training for large datasets
dataset_size = len(states)
indices = torch.randperm(dataset_size)
total_policy_loss = 0
total_value_loss = 0
total_entropy = 0
update_count = 0
for epoch in range(epochs):
# Process in mini-batches to avoid memory issues
for start_idx in range(0, dataset_size, self.mini_batch_size):
end_idx = min(start_idx + self.mini_batch_size, dataset_size)
batch_indices = indices[start_idx:end_idx]
# Get mini-batch
batch_states = states[batch_indices]
batch_actions = actions[batch_indices]
batch_advantages = advantages[batch_indices]
batch_returns = returns[batch_indices]
batch_old_log_probs = old_log_probs[batch_indices]
# Forward pass
logits = self.policy(batch_states)
probs = torch.softmax(logits, dim=-1) + 1e-8
probs = probs / probs.sum(dim=-1, keepdim=True)
dist = Categorical(probs)
new_log_probs = dist.log_prob(batch_actions)
# Policy loss
ratio = torch.exp(new_log_probs - batch_old_log_probs)
ratio = torch.clamp(ratio, 0.1, 10.0)
surr1 = ratio * batch_advantages
surr2 = torch.clamp(ratio, 1 - self.clip_eps, 1 + self.clip_eps) * batch_advantages
policy_loss = -torch.min(surr1, surr2).mean()
# Value loss
current_values = self.value(batch_states).squeeze(-1)
value_loss = nn.MSELoss()(current_values, batch_returns)
# Entropy
entropy = dist.entropy().mean()
# Total loss
total_loss = policy_loss + 0.5 * value_loss - 0.01 * entropy # Reduced entropy coefficient
# Check for NaN
if torch.isnan(total_loss) or torch.isinf(total_loss):
print("Warning: NaN/Inf loss detected, skipping batch")
continue
# Optimize
self.optimizer.zero_grad()
total_loss.backward()
# Gradient clipping
torch.nn.utils.clip_grad_norm_(self.policy.parameters(), 0.5)
torch.nn.utils.clip_grad_norm_(self.value.parameters(), 0.5)
self.optimizer.step()
# Accumulate losses
total_policy_loss += policy_loss.detach().item()
total_value_loss += value_loss.detach().item()
total_entropy += entropy.detach().item()
update_count += 1
# Clear memory
self.memory.clear()
if update_count == 0:
return None
return {
'policy_loss': total_policy_loss / update_count,
'value_loss': total_value_loss / update_count,
'entropy': total_entropy / update_count
}
def save(self, filepath):
"""Save the model"""
torch.save({
'policy_state_dict': self.policy.state_dict(),
'value_state_dict': self.value.state_dict(),
'optimizer_state_dict': self.optimizer.state_dict()
}, filepath)
def load(self, filepath):
"""Load the model"""
checkpoint = torch.load(filepath, map_location='cpu')
self.policy.load_state_dict(checkpoint['policy_state_dict'])
self.value.load_state_dict(checkpoint['value_state_dict'])
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])1234torch
numpy
pygame
pillowREAD_ME.txtAdded+45
__pycache__/car_game_classes_gradio.cpython-312.pycAdded
__pycache__/ppo_agent_gradio.cpython-312.pycAdded
app copy 2.pyAdded+400
app copy 3.pyAdded+401
app copy.pyAdded+270
app.pyAdded+401
assets/car_transparent.pngAdded

car_game_classes_gradio.pyAdded+378
car_model_epoch_270_lvl3_final_gradio.pthAdded+3
model/18.6_car_model_epoch_270_lvl3_final.pthAdded+3
ppo_agent_gradio.pyAdded+268
requirements.txtAdded+4