Spaces:
Running
Running
File size: 10,899 Bytes
6dd47af |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
#!/usr/bin/env python3
"""Interactive cartpole control via OpenEnv.
This example demonstrates using the dm_control OpenEnv client with
the cartpole environment. Use arrow keys to control the cart.
Controls:
LEFT/RIGHT arrows: Apply force to move cart
R: Reset environment
ESC or Q: Quit
Requirements:
pip install pygame
Usage:
1. Start the server: uvicorn server.app:app --host 0.0.0.0 --port 8000
2. Run this script: python examples/cartpole_control.py
For visual mode (requires working MuJoCo rendering):
python examples/cartpole_control.py --visual
"""
import argparse
import random
import sys
from pathlib import Path
# Add parent directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent))
from client import DMControlEnv
from models import DMControlAction
def run_headless(env: DMControlEnv, task: str = "balance", max_steps: int = 500):
"""Run cartpole control in headless mode."""
print("\n=== Headless Mode (OpenEnv Step/Observation Pattern) ===")
print("This mode demonstrates the OpenEnv API with the cartpole.\n")
# Reset environment using OpenEnv pattern
result = env.reset(domain_name="cartpole", task_name=task)
print(f"Initial observations: {list(result.observation.observations.keys())}")
print(f" position: {result.observation.observations.get('position', [])}")
print(f" velocity: {result.observation.observations.get('velocity', [])}")
total_reward = 0.0
step_count = 0
print("\nRunning with random actions to demonstrate step/observation pattern...\n")
while not result.done and step_count < max_steps:
# Random action in [-1, 1]
action_value = random.uniform(-1.0, 1.0)
# Step the environment using OpenEnv pattern
action = DMControlAction(values=[action_value])
result = env.step(action)
# Access observation and reward from result
total_reward += result.reward or 0.0
step_count += 1
# Print progress periodically
if step_count % 50 == 0:
pos = result.observation.observations.get("position", [])
vel = result.observation.observations.get("velocity", [])
print(
f"Step {step_count}: reward={result.reward:.3f}, "
f"total={total_reward:.2f}, done={result.done}"
)
print(f" position={pos}, velocity={vel}")
print(f"\nEpisode finished: {step_count} steps, total reward: {total_reward:.2f}")
def run_interactive(env: DMControlEnv, task: str = "balance"):
"""Run interactive control with keyboard input via pygame."""
import pygame
print("\n=== Interactive Mode (OpenEnv Step/Observation Pattern) ===")
print("Use LEFT/RIGHT arrows to control cart, R to reset, ESC to quit.\n")
# Reset environment using OpenEnv pattern
result = env.reset(domain_name="cartpole", task_name=task)
print(f"Initial observations: {list(result.observation.observations.keys())}")
# Initialize pygame for keyboard input (minimal window)
pygame.init()
screen = pygame.display.set_mode((400, 100))
pygame.display.set_caption("Cartpole Control - Arrow keys to move, R to reset")
clock = pygame.time.Clock()
# Font for display
font = pygame.font.Font(None, 24)
running = True
total_reward = 0.0
step_count = 0
print("\nControls:")
print(" LEFT/RIGHT arrows: Move cart")
print(" R: Reset environment")
print(" ESC or Q: Quit\n")
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_ESCAPE, pygame.K_q):
running = False
elif event.key == pygame.K_r:
result = env.reset(domain_name="cartpole", task_name=task)
total_reward = 0.0
step_count = 0
print("Environment reset")
# Check for held keys (for continuous control)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
action_value = -1.0
elif keys[pygame.K_RIGHT]:
action_value = 1.0
else:
action_value = 0.0
# Step the environment using OpenEnv pattern
action = DMControlAction(values=[action_value])
result = env.step(action)
# Track reward from result
total_reward += result.reward or 0.0
step_count += 1
# Check if episode is done
if result.done:
print(
f"Episode finished! Steps: {step_count}, "
f"Total reward: {total_reward:.2f}"
)
# Auto-reset on done
result = env.reset(domain_name="cartpole", task_name=task)
total_reward = 0.0
step_count = 0
# Update display
direction = (
"<--" if action_value < 0 else ("-->" if action_value > 0 else "---")
)
screen.fill((30, 30, 30))
text = font.render(
f"Step: {step_count} | Reward: {total_reward:.1f} | {direction}",
True,
(255, 255, 255),
)
screen.blit(text, (10, 40))
pygame.display.flip()
# Print progress periodically
if step_count % 200 == 0 and step_count > 0:
print(f"Step {step_count}: Total reward: {total_reward:.2f}")
# Cap at 30 FPS
clock.tick(30)
pygame.quit()
print(f"Session ended. Final reward: {total_reward:.2f}")
def run_visual(env: DMControlEnv, task: str = "balance"):
"""Run with pygame visualization showing rendered frames."""
import base64
import io
import pygame
print("\n=== Visual Mode (OpenEnv Step/Observation Pattern) ===")
# Reset environment with rendering enabled
result = env.reset(domain_name="cartpole", task_name=task, render=True)
print(f"Initial observations: {list(result.observation.observations.keys())}")
# Get first frame to determine window size
if result.observation.pixels is None:
print("Error: Server did not return rendered pixels.")
print("Make sure the server supports render=True")
print("\nTry running in interactive mode (default) instead.")
sys.exit(1)
# Decode base64 PNG to pygame surface
png_data = base64.b64decode(result.observation.pixels)
frame = pygame.image.load(io.BytesIO(png_data))
frame_size = frame.get_size()
# Initialize pygame
pygame.init()
screen = pygame.display.set_mode(frame_size)
pygame.display.set_caption(
"Cartpole (OpenEnv) - Arrow Keys to Move, R to Reset, ESC to Quit"
)
clock = pygame.time.Clock()
print("Controls:")
print(" LEFT/RIGHT arrows: Move cart")
print(" R: Reset environment")
print(" ESC or Q: Quit")
running = True
total_reward = 0.0
step_count = 0
while running:
# Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key in (pygame.K_ESCAPE, pygame.K_q):
running = False
elif event.key == pygame.K_r:
result = env.reset(
domain_name="cartpole", task_name=task, render=True
)
total_reward = 0.0
step_count = 0
print("Environment reset")
# Check for held keys (for continuous control)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
action_value = -1.0
elif keys[pygame.K_RIGHT]:
action_value = 1.0
else:
action_value = 0.0
# Step the environment using OpenEnv pattern
action = DMControlAction(values=[action_value])
result = env.step(action, render=True)
# Track reward from result
total_reward += result.reward or 0.0
step_count += 1
# Check if episode is done
if result.done:
print(
f"Episode finished! Steps: {step_count}, "
f"Total reward: {total_reward:.2f}"
)
result = env.reset(domain_name="cartpole", task_name=task, render=True)
total_reward = 0.0
step_count = 0
# Render the frame from observation pixels
if result.observation.pixels:
png_data = base64.b64decode(result.observation.pixels)
frame = pygame.image.load(io.BytesIO(png_data))
screen.blit(frame, (0, 0))
pygame.display.flip()
# Print progress periodically
if step_count % 200 == 0 and step_count > 0:
print(f"Step {step_count}: Total reward: {total_reward:.2f}")
# Cap at 30 FPS
clock.tick(30)
pygame.quit()
print(f"Session ended. Final reward: {total_reward:.2f}")
def main():
parser = argparse.ArgumentParser(
description="Interactive cartpole control via OpenEnv"
)
parser.add_argument(
"--visual",
action="store_true",
help="Enable pygame visualization with rendered frames",
)
parser.add_argument(
"--headless",
action="store_true",
help="Run in headless mode (no pygame, automated control)",
)
parser.add_argument(
"--max-steps",
type=int,
default=500,
help="Maximum steps for headless mode (default: 500)",
)
parser.add_argument(
"--task",
type=str,
default="balance",
choices=["balance", "balance_sparse", "swingup", "swingup_sparse"],
help="Cartpole task (default: balance)",
)
args = parser.parse_args()
server_url = "http://localhost:8000"
print(f"Connecting to {server_url}...")
try:
with DMControlEnv(base_url=server_url) as env:
print("Connected!")
# Get environment state
state = env.state()
print(f"Domain: {state.domain_name}, Task: {state.task_name}")
print(f"Action spec: {state.action_spec}")
if args.headless:
run_headless(env, task=args.task, max_steps=args.max_steps)
elif args.visual:
run_visual(env, task=args.task)
else:
run_interactive(env, task=args.task)
except ConnectionError as e:
print(f"Failed to connect: {e}")
print("\nMake sure the server is running:")
print(" cd OpenEnv")
print(
" PYTHONPATH=src:envs uvicorn envs.dm_control_env.server.app:app --port 8000"
)
sys.exit(1)
if __name__ == "__main__":
main()
|