Compare commits

5 Commits

Author SHA1 Message Date
xxh
6ab356a947 improve train speed and add speed constrain 2026-03-13 08:51:49 -04:00
3a42120857 Revert "improve training speed and add speed constrain"
This reverts commit 648cf32e9c.
2026-03-13 08:43:28 -04:00
648cf32e9c improve training speed and add speed constrain 2026-03-13 08:40:50 -04:00
徐学颢
092fb521e1 fxxk the bahirt and the add Walk gym 2026-03-12 19:59:07 +08:00
徐学颢
0e402c2b4c train base and gitignore files 2026-03-11 09:54:29 +08:00
8 changed files with 930 additions and 155 deletions

6
.gitignore vendored
View File

@@ -10,9 +10,3 @@ poetry.toml
**/log/ **/log/
*.spec *.spec
dist/ dist/
*.zip
*.csv
*.json
*.xml
*.npz
*.pkl

View File

@@ -98,8 +98,12 @@ class Walk(Behavior):
velocity[0] = np.clip(velocity[0], -0.5, 0.5) velocity[0] = np.clip(velocity[0], -0.5, 0.5)
velocity[1] = np.clip(velocity[1], -0.25, 0.25) velocity[1] = np.clip(velocity[1], -0.25, 0.25)
radian_joint_positions = np.deg2rad(list(robot.motor_positions.values())) radian_joint_positions = np.deg2rad(
radian_joint_speeds = np.deg2rad(list(robot.motor_speeds.values())) [robot.motor_positions[motor] for motor in robot.ROBOT_MOTORS]
)
radian_joint_speeds = np.deg2rad(
[robot.motor_speeds[motor] for motor in robot.ROBOT_MOTORS]
)
qpos_qvel_previous_action = np.vstack( qpos_qvel_previous_action = np.vstack(
( (

View File

@@ -1,7 +1,5 @@
import logging import logging
import os
import socket import socket
import time
from select import select from select import select
from communication.world_parser import WorldParser from communication.world_parser import WorldParser
@@ -12,32 +10,15 @@ class Server:
def __init__(self, host: str, port: int, world_parser: WorldParser): def __init__(self, host: str, port: int, world_parser: WorldParser):
self.world_parser: WorldParser = world_parser self.world_parser: WorldParser = world_parser
self.__host: str = host self.__host: str = host
self.__port: int = port self.__port: str = port
self.__socket: socket.socket = self._create_socket() self.__socket: socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.__socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
self.__send_buff = [] self.__send_buff = []
self.__rcv_buffer_size = 1024 self.__rcv_buffer_size = 1024
self.__rcv_buffer_default_size = 1024
self.__max_msg_size = 1048576
self.__shrink_threshold = 8192
self.__shrink_after_msgs = 200
self.__small_msg_streak = 0
self.__rcv_buffer = bytearray(self.__rcv_buffer_size) self.__rcv_buffer = bytearray(self.__rcv_buffer_size)
def _create_socket(self) -> socket.socket:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
return sock
def connect(self) -> None: def connect(self) -> None:
logger.info("Connecting to server at %s:%d...", self.__host, self.__port) logger.info("Connecting to server at %s:%d...", self.__host, self.__port)
# Always reconnect with a fresh socket object.
try:
self.__socket.close()
except OSError:
pass
self.__socket = self._create_socket()
while True: while True:
try: try:
self.__socket.connect((self.__host, self.__port)) self.__socket.connect((self.__host, self.__port))
@@ -46,19 +27,12 @@ class Server:
logger.error( logger.error(
"Connection refused. Make sure the server is running and listening on {self.__host}:{self.__port}." "Connection refused. Make sure the server is running and listening on {self.__host}:{self.__port}."
) )
time.sleep(0.05)
logger.info(f"Server connection established to {self.__host}:{self.__port}.") logger.info(f"Server connection established to {self.__host}:{self.__port}.")
def shutdown(self) -> None: def shutdown(self) -> None:
try:
self.__socket.shutdown(socket.SHUT_RDWR)
except OSError:
pass
try:
self.__socket.close() self.__socket.close()
except OSError: self.__socket.shutdown(socket.SHUT_RDWR)
pass
def send_immediate(self, msg: str) -> None: def send_immediate(self, msg: str) -> None:
""" """
@@ -111,10 +85,6 @@ class Server:
msg_size = int.from_bytes(self.__rcv_buffer[:4], byteorder="big", signed=False) msg_size = int.from_bytes(self.__rcv_buffer[:4], byteorder="big", signed=False)
# Guard against corrupted frame lengths that would trigger huge allocations.
if msg_size <= 0 or msg_size > self.__max_msg_size:
raise ConnectionResetError
if msg_size > self.__rcv_buffer_size: if msg_size > self.__rcv_buffer_size:
self.__rcv_buffer_size = msg_size self.__rcv_buffer_size = msg_size
self.__rcv_buffer = bytearray(self.__rcv_buffer_size) self.__rcv_buffer = bytearray(self.__rcv_buffer_size)
@@ -130,15 +100,6 @@ class Server:
message=self.__rcv_buffer[:msg_size].decode() message=self.__rcv_buffer[:msg_size].decode()
) )
if msg_size <= self.__shrink_threshold and self.__rcv_buffer_size > self.__rcv_buffer_default_size:
self.__small_msg_streak += 1
if self.__small_msg_streak >= self.__shrink_after_msgs:
self.__rcv_buffer_size = self.__rcv_buffer_default_size
self.__rcv_buffer = bytearray(self.__rcv_buffer_size)
self.__small_msg_streak = 0
else:
self.__small_msg_streak = 0
# 如果socket没有更多数据就退出 # 如果socket没有更多数据就退出
if len(select([self.__socket], [], [], 0.0)[0]) == 0: if len(select([self.__socket], [], [], 0.0)[0]) == 0:
break break

View File

@@ -74,21 +74,6 @@ poetry run ./build_binary.sh <team-name>
Once binary generation is finished, the result will be inside the build folder, as ```<team-name>.tar.gz``` Once binary generation is finished, the result will be inside the build folder, as ```<team-name>.tar.gz```
### GYM
To use the gym, you need to install the following dependencies:
```bash
pip install gymnasium
pip install psutil
pip install stable-baselines3
```
Then, you can run gym examples under the ```GYM_CPU``` folder:
```bash
python3 -m scripts.gyms.Walk # Run the Walk gym example
# of course, you can run other gym examples
```
### Authors and acknowledgment ### Authors and acknowledgment
This project was developed and contributed by: This project was developed and contributed by:
- **Chenxi Liu** - **Chenxi Liu**

View File

@@ -1,15 +1,9 @@
import subprocess import subprocess
import os import os
import time
import threading
class Server(): class Server():
WATCHDOG_ENABLED = True def __init__(self, first_server_p, first_monitor_p, n_servers) -> None:
WATCHDOG_INTERVAL_SEC = 30.0
WATCHDOG_RSS_MB_LIMIT = 2000.0
def __init__(self, first_server_p, first_monitor_p, n_servers, no_render=True, no_realtime=True) -> None:
try: try:
import psutil import psutil
self.check_running_servers(psutil, first_server_p, first_monitor_p, n_servers) self.check_running_servers(psutil, first_server_p, first_monitor_p, n_servers)
@@ -19,93 +13,25 @@ class Server():
self.first_server_p = first_server_p self.first_server_p = first_server_p
self.n_servers = n_servers self.n_servers = n_servers
self.rcss_processes = [] self.rcss_processes = []
self._server_specs = []
self._watchdog_stop = threading.Event()
self._watchdog_lock = threading.Lock()
self._watchdog_thread = None
first_monitor_p = first_monitor_p + 100 first_monitor_p = first_monitor_p + 100
# makes it easier to kill test servers without affecting train servers # makes it easier to kill test servers without affecting train servers
cmd = "rcssservermj" cmd = "rcssservermj"
render_arg = "--no-render" if no_render else ""
realtime_arg = "--no-realtime" if no_realtime else ""
for i in range(n_servers): for i in range(n_servers):
port = first_server_p + i port = first_server_p + i
mport = first_monitor_p + i mport = first_monitor_p + i
self._server_specs.append((port, mport, cmd, render_arg, realtime_arg))
proc = self._spawn_server(port, mport, cmd, render_arg, realtime_arg)
self.rcss_processes.append(proc)
if self.WATCHDOG_ENABLED: server_cmd = f"{cmd} --aport {port} --mport {mport} --no-render --no-realtime"
self._watchdog_thread = threading.Thread(target=self._watchdog_loop, daemon=True)
self._watchdog_thread.start()
def _spawn_server(self, port, mport, cmd, render_arg, realtime_arg): self.rcss_processes.append(
server_cmd = f"{cmd} -c {port} -m {mport} {render_arg} {realtime_arg}".strip() subprocess.Popen(
proc = subprocess.Popen(
server_cmd.split(), server_cmd.split(),
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT, stderr=subprocess.STDOUT,
start_new_session=True start_new_session=True
) )
# Avoid startup storm when launching many servers at once.
time.sleep(0.03)
rc = proc.poll()
if rc is not None:
raise RuntimeError(
f"rcssservermj exited early (code={rc}) on server port {port}, monitor port {mport}"
) )
return proc
@staticmethod
def _pid_rss_mb(pid):
try:
with open(f"/proc/{pid}/status", "r", encoding="utf-8") as f:
for line in f:
if line.startswith("VmRSS:"):
parts = line.split()
if len(parts) >= 2:
# VmRSS is kB
return float(parts[1]) / 1024.0
except (FileNotFoundError, ProcessLookupError, PermissionError, OSError):
return 0.0
return 0.0
def _restart_server_at_index(self, idx, reason):
port, mport, cmd, render_arg, realtime_arg = self._server_specs[idx]
old_proc = self.rcss_processes[idx]
try:
old_proc.terminate()
old_proc.wait(timeout=1.0)
except Exception:
try:
old_proc.kill()
except Exception:
pass
new_proc = self._spawn_server(port, mport, cmd, render_arg, realtime_arg)
self.rcss_processes[idx] = new_proc
print(
f"[ServerWatchdog] Restarted server idx={idx} port={port} monitor={mport} reason={reason}"
)
def _watchdog_loop(self):
while not self._watchdog_stop.wait(self.WATCHDOG_INTERVAL_SEC):
with self._watchdog_lock:
for i, proc in enumerate(self.rcss_processes):
rc = proc.poll()
if rc is not None:
self._restart_server_at_index(i, f"exited:{rc}")
continue
rss_mb = self._pid_rss_mb(proc.pid)
if rss_mb > self.WATCHDOG_RSS_MB_LIMIT:
self._restart_server_at_index(i, f"rss_mb:{rss_mb:.1f}")
def check_running_servers(self, psutil, first_server_p, first_monitor_p, n_servers): def check_running_servers(self, psutil, first_server_p, first_monitor_p, n_servers):
''' Check if any server is running on chosen ports ''' ''' Check if any server is running on chosen ports '''
found = False found = False
@@ -140,9 +66,6 @@ class Server():
return return
def kill(self): def kill(self):
self._watchdog_stop.set()
if self._watchdog_thread is not None:
self._watchdog_thread.join(timeout=1.0)
for p in self.rcss_processes: for p in self.rcss_processes:
p.kill() p.kill()
print(f"Killed {self.n_servers} rcssservermj processes starting at {self.first_server_p}") print(f"Killed {self.n_servers} rcssservermj processes starting at {self.first_server_p}")

View File

@@ -171,8 +171,8 @@ class Train_Base():
ep_reward += reward ep_reward += reward
ep_length += 1 ep_length += 1
# if enable_FPS_control: # control simulation speed (using non blocking user input) if enable_FPS_control: # control simulation speed (using non blocking user input)
# self.control_fps(select.select([sys.stdin], [], [], 0)[0]) self.control_fps(select.select([sys.stdin], [], [], 0)[0])
if done: if done:
obs, _ = env.reset() obs, _ = env.reset()

302
scripts/commons/UI.py Normal file
View File

@@ -0,0 +1,302 @@
from itertools import zip_longest
from math import inf
import math
import numpy as np
import shutil
class UI():
console_width = 80
console_height = 24
@staticmethod
def read_particle(prompt, str_options, dtype=str, interval=[-inf,inf]):
'''
Read particle from user from a given dtype or from a str_options list
Parameters
----------
prompt : `str`
prompt to show user before reading input
str_options : `list`
list of str options (in addition to dtype if dtype is not str)
dtype : `class`
if dtype is str, then user must choose a value from str_options, otherwise it can also send a dtype value
interval : `list`
[>=min,<max] interval for numeric dtypes
Returns
-------
choice : `int` or dtype
index of str_options (int) or value (dtype)
is_str_option : `bool`
True if `choice` is an index from str_options
'''
# Check if user has no choice
if dtype is str and len(str_options) == 1:
print(prompt, str_options[0], sep="")
return 0, True
elif dtype is int and interval[0] == interval[1]-1:
print(prompt, interval[0], sep="")
return interval[0], False
while True:
inp = input(prompt)
if inp in str_options:
return str_options.index(inp), True
if dtype is not str:
try:
inp = dtype(inp)
if inp >= interval[0] and inp < interval[1]:
return inp, False
except:
pass
print("Error: illegal input! Options:", str_options, f" or {dtype}" if dtype != str else "")
@staticmethod
def read_int(prompt, min, max):
'''
Read int from user in a given interval
:param prompt: prompt to show user before reading input
:param min: minimum input (inclusive)
:param max: maximum input (exclusive)
:return: choice
'''
while True:
inp = input(prompt)
try:
inp = int(inp)
assert inp >= min and inp < max
return inp
except:
print(f"Error: illegal input! Choose number between {min} and {max-1}")
@staticmethod
def print_table(data, titles=None, alignment=None, cols_width=None, cols_per_title=None, margins=None, numbering=None, prompt=None):
'''
Print table
Parameters
----------
data : `list`
list of columns, where each column is a list of items
titles : `list`
list of titles for each column, default is `None` (no titles)
alignment : `list`
list of alignments per column (excluding titles), default is `None` (left alignment for all cols)
cols_width : `list`
list of widths per column, default is `None` (fit to content)
Positive values indicate a fixed column width
Zero indicates that the column will fit its content
cols_per_title : `list`
maximum number of subcolumns per title, default is `None` (1 subcolumn per title)
margins : `list`
number of added leading and trailing spaces per column, default is `None` (margin=2 for all columns)
numbering : `list`
list of booleans per columns, indicating whether to assign numbers to each option
prompt : `str`
the prompt string, if given, is printed after the table before reading input
Returns
-------
index : `int`
returns global index of selected item (relative to table)
col_index : `int`
returns local index of selected item (relative to column)
column : `int`
returns number of column of selected item (starts at 0)
* if `numbering` or `prompt` are `None`, `None` is returned
Example
-------
titles = ["Name","Age"]
data = [[John,Graciete], [30,50]]
alignment = ["<","^"] # 1st column is left-aligned, 2nd is centered
cols_width = [10,5] # 1st column's width=10, 2nd column's width=5
margins = [3,3]
numbering = [True,False] # prints: [0-John,1-Graciete][30,50]
prompt = "Choose a person:"
'''
#--------------------------------------------- parameters
cols_no = len(data)
if alignment is None:
alignment = ["<"]*cols_no
if cols_width is None:
cols_width = [0]*cols_no
if numbering is None:
numbering = [False]*cols_no
any_numbering = False
else:
any_numbering = True
if margins is None:
margins = [2]*cols_no
# Fit column to content + margin, if required
subcol = [] # subcolumn length and widths
for i in range(cols_no):
subcol.append([[],[]])
if cols_width[i] == 0:
numbering_width = 4 if numbering[i] else 0
if cols_per_title is None or cols_per_title[i] < 2:
cols_width[i] = max([len(str(item))+numbering_width for item in data[i]]) + margins[i]*2
else:
subcol[i][0] = math.ceil(len(data[i])/cols_per_title[i]) # subcolumn maximum length
cols_per_title[i] = math.ceil(len(data[i])/subcol[i][0]) # reduce number of columns as needed
cols_width[i] = margins[i]*(1+cols_per_title[i]) - (1 if numbering[i] else 0) # remove one if numbering, same as when printing
for j in range(cols_per_title[i]):
subcol_data_width = max([len(str(item))+numbering_width for item in data[i][j*subcol[i][0]:j*subcol[i][0]+subcol[i][0]]])
cols_width[i] += subcol_data_width # add subcolumn data width to column width
subcol[i][1].append(subcol_data_width) # save subcolumn data width
if titles is not None: # expand to acomodate titles if needed
cols_width[i] = max(cols_width[i], len(titles[i]) + margins[i]*2 )
if any_numbering:
no_of_items=0
cumulative_item_per_col=[0] # useful for getting the local index
for i in range(cols_no):
assert type(data[i]) == list, "In function 'print_table', 'data' must be a list of lists!"
if numbering[i]:
data[i] = [f"{n+no_of_items:3}-{d}" for n,d in enumerate(data[i])]
no_of_items+=len(data[i])
cumulative_item_per_col.append(no_of_items)
table_width = sum(cols_width)+cols_no-1
#--------------------------------------------- col titles
print(f'{"="*table_width}')
if titles is not None:
for i in range(cols_no):
print(f'{titles[i]:^{cols_width[i]}}', end='|' if i < cols_no - 1 else '')
print()
for i in range(cols_no):
print(f'{"-"*cols_width[i]}', end='+' if i < cols_no - 1 else '')
print()
#--------------------------------------------- merge subcolumns
if cols_per_title is not None:
for i,col in enumerate(data):
if cols_per_title[i] < 2:
continue
for k in range(subcol[i][0]): # create merged items
col[k] = (" "*margins[i]).join( f'{col[item]:{alignment[i]}{subcol[i][1][subcol_idx]}}'
for subcol_idx, item in enumerate(range(k,len(col),subcol[i][0])) )
del col[subcol[i][0]:] # delete repeated items
#--------------------------------------------- col items
for line in zip_longest(*data):
for i,item in enumerate(line):
l_margin = margins[i]-1 if numbering[i] else margins[i] # adjust margins when there are numbered options
item = "" if item is None else f'{" "*l_margin}{item}{" "*margins[i]}' # add margins
print(f'{item:{alignment[i]}{cols_width[i]}}', end='')
if i < cols_no - 1:
print(end='|')
print(end="\n")
print(f'{"="*table_width}')
#--------------------------------------------- prompt
if prompt is None:
return None
if not any_numbering:
print(prompt)
return None
index = UI.read_int(prompt, 0, no_of_items)
for i,n in enumerate(cumulative_item_per_col):
if index < n:
return index, index-cumulative_item_per_col[i-1], i-1
raise ValueError('Failed to catch illegal input')
@staticmethod
def print_list(data, numbering=True, prompt=None, divider=" | ", alignment="<", min_per_col=6):
'''
Print list - prints list, using as many columns as possible
Parameters
----------
data : `list`
list of items
numbering : `bool`
assigns number to each option
prompt : `str`
the prompt string, if given, is printed after the table before reading input
divider : `str`
string that divides columns
alignment : `str`
f-string style alignment ( '<', '>', '^' )
min_per_col : int
avoid splitting columns with fewer items
Returns
-------
item : `int`, item
returns tuple with global index of selected item and the item object,
or `None` (if `numbering` or `prompt` are `None`)
'''
WIDTH = shutil.get_terminal_size()[0]
data_size = len(data)
items = []
items_len = []
#--------------------------------------------- Add numbers, margins and divider
for i in range(data_size):
number = f"{i}-" if numbering else ""
items.append( f"{divider}{number}{data[i]}" )
items_len.append( len(items[-1]) )
max_cols = np.clip((WIDTH+len(divider)) // min(items_len),1,math.ceil(data_size/max(min_per_col,1))) # width + len(divider) because it is not needed in last col
#--------------------------------------------- Check maximum number of columns, considering content width (min:1)
for i in range(max_cols,0,-1):
cols_width = []
cols_items = []
table_width = 0
a,b = divmod(data_size,i)
for col in range(i):
start = a*col + min(b,col)
end = start+a+(1 if col<b else 0)
cols_items.append( items[start:end] )
col_width = max(items_len[start:end])
cols_width.append( col_width )
table_width += col_width
if table_width <= WIDTH+len(divider):
break
table_width -= len(divider)
#--------------------------------------------- Print columns
print("="*table_width)
for row in range(math.ceil(data_size / i)):
for col in range(i):
content = cols_items[col][row] if len(cols_items[col]) > row else divider # print divider when there are no items
if col == 0:
l = len(divider)
print(end=f"{content[l:]:{alignment}{cols_width[col]-l}}") # remove divider from 1st col
else:
print(end=f"{content :{alignment}{cols_width[col] }}")
print()
print("="*table_width)
#--------------------------------------------- Prompt
if prompt is None:
return None
if numbering is None:
return None
else:
idx = UI.read_int( prompt, 0, data_size )
return idx, data[idx]

606
scripts/gyms/Walk.py Normal file
View File

@@ -0,0 +1,606 @@
import os
import numpy as np
import math
import time
from time import sleep
from random import random
from random import uniform
from stable_baselines3 import PPO
from stable_baselines3.common.vec_env import SubprocVecEnv
import gymnasium as gym
from gymnasium import spaces
from scripts.commons.Train_Base import Train_Base
from scripts.commons.Server import Server as Train_Server
from agent.base_agent import Base_Agent
from utils.math_ops import MathOps
from scipy.spatial.transform import Rotation as R
'''
Objective:
Learn how to run forward using step primitive
----------
- class Basic_Run: implements an OpenAI custom gym
- class Train: implements algorithms to train a new model or test an existing model
'''
class WalkEnv(gym.Env):
def __init__(self, ip, server_p) -> None:
# Args: Server IP, Agent Port, Monitor Port, Uniform No., Robot Type, Team Name, Enable Log, Enable Draw
self.Player = player = Base_Agent(
team_name="Gym",
number=1,
host=ip,
port=server_p
)
self.robot_type = self.Player.robot
self.step_counter = 0 # to limit episode size
self.force_play_on = True
self.target_position = np.array([0.0, 0.0]) # target position in the x-y plane
self.initial_position = np.array([0.0, 0.0]) # initial position in the x-y plane
self.target_direction = 0.0 # target direction in the x-y plane (relative to the robot's orientation)
self.isfallen = False
self.waypoint_index = 0
self.route_completed = False
self.debug_every_n_steps = 5
self.calibrate_nominal_from_neutral = True
self.auto_calibrate_train_sim_flip = True
self.nominal_calibrated_once = False
self.flip_calibrated_once = False
self._target_hz = 0.0
self._target_dt = 0.0
self._last_sync_time = None
target_hz_env = 24
if target_hz_env:
try:
self._target_hz = float(target_hz_env)
except ValueError:
self._target_hz = 0.0
if self._target_hz > 0.0:
self._target_dt = 1.0 / self._target_hz
# State space
# 原始观测大小: 78
obs_size = 78
self.obs = np.zeros(obs_size, np.float32)
self.observation_space = spaces.Box(
low=-10.0,
high=10.0,
shape=(obs_size,),
dtype=np.float32
)
action_dim = len(self.Player.robot.ROBOT_MOTORS)
self.no_of_actions = action_dim
self.action_space = spaces.Box(
low=-1.0,
high=1.0,
shape=(action_dim,),
dtype=np.float32
)
# 中立姿态
self.joint_nominal_position = np.array(
[
0.0,
0.0,
0.0,
1.4,
0.0,
-0.4,
0.0,
-1.4,
0.0,
0.4,
0.0,
-0.4,
0.0,
0.0,
0.8,
-0.4,
0.0,
0.4,
0.0,
0.0,
-0.8,
0.4,
0.0,
]
)
self.reference_joint_nominal_position = self.joint_nominal_position.copy()
self.train_sim_flip = np.array(
[
1.0, # 0: Head_yaw (he1)
-1.0, # 1: Head_pitch (he2)
1.0, # 2: Left_Shoulder_Pitch (lae1)
-1.0, # 3: Left_Shoulder_Roll (lae2)
1.0, # 4: Left_Elbow_Pitch (lae3)
1.0, # 5: Left_Elbow_Yaw (lae4)
-1.0, # 6: Right_Shoulder_Pitch (rae1)
1.0, # 7: Right_Shoulder_Roll (rae2)
1.0, # 8: Right_Elbow_Pitch (rae3)
1.0, # 9: Right_Elbow_Yaw (rae4)
1.0, # 10: Waist (te1)
1.0, # 11: Left_Hip_Pitch (lle1)
-1.0, # 12: Left_Hip_Roll (lle2)
-1.0, # 13: Left_Hip_Yaw (lle3)
1.0, # 14: Left_Knee_Pitch (lle4)
1.0, # 15: Left_Ankle_Pitch (lle5)
-1.0, # 16: Left_Ankle_Roll (lle6)
-1.0, # 17: Right_Hip_Pitch (rle1)
-1.0, # 18: Right_Hip_Roll (rle2)
-1.0, # 19: Right_Hip_Yaw (rle3)
-1.0, # 20: Right_Knee_Pitch (rle4)
-1.0, # 21: Right_Ankle_Pitch (rle5)
-1.0, # 22: Right_Ankle_Roll (rle6)
]
)
self.scaling_factor = 0.5
self.previous_action = np.zeros(len(self.Player.robot.ROBOT_MOTORS))
self.previous_pos = np.array([0.0, 0.0]) # Track previous position
self.Player.server.connect()
# sleep(2.0) # Longer wait for connection to establish completely
self.Player.server.send_immediate(
f"(init {self.Player.robot.name} {self.Player.world.team_name} {self.Player.world.number})"
)
def debug_log(self, message):
print(message)
try:
log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), "comm_debug.log")
with open(log_path, "a", encoding="utf-8") as f:
f.write(message + "\n")
except OSError:
pass
def calibrate_train_sim_flip_from_neutral(self, neutral_joint_positions):
updated_flip = self.train_sim_flip.copy()
changed = []
for idx, (reference_value, observed_value) in enumerate(
zip(self.reference_joint_nominal_position, neutral_joint_positions)
):
if idx >= 10:
continue
if abs(reference_value) < 0.15 or abs(observed_value) < 0.15:
continue
inferred_flip = 1.0 if np.sign(reference_value) == np.sign(observed_value) else -1.0
if updated_flip[idx] != inferred_flip:
changed.append((idx, updated_flip[idx], inferred_flip))
updated_flip[idx] = inferred_flip
self.train_sim_flip = updated_flip
if changed:
self.debug_log(
"[FlipDebug] "
f"changes={[(idx, old, new) for idx, old, new in changed]}"
)
def is_reliable_neutral_pose(self, neutral_joint_positions):
leg_positions = neutral_joint_positions[11:]
leg_norm = float(np.linalg.norm(leg_positions))
leg_max = float(np.max(np.abs(leg_positions)))
height = float(self.Player.world.global_position[2])
reliable = (
leg_norm > 0.8
and leg_max > 0.35
and 0.12 < height < 0.8
)
return reliable, leg_norm, leg_max, height
def observe(self, init=False):
"""获取当前观测值"""
robot = self.Player.robot
world = self.Player.world
# Safety check: ensure data is available
# 计算目标速度
raw_target = self.target_position - world.global_position[:2]
velocity = MathOps.rotate_2d_vec(
raw_target,
-robot.global_orientation_euler[2],
is_rad=False
)
# 计算相对方向
rel_orientation = MathOps.vector_angle(velocity) * 0.3
rel_orientation = np.clip(rel_orientation, -0.25, 0.25)
velocity = np.concatenate([velocity, np.array([rel_orientation])])
velocity[0] = np.clip(velocity[0], -0.5, 0.5)
velocity[1] = np.clip(velocity[1], -0.25, 0.25)
# 关节状态
radian_joint_positions = np.deg2rad(
[robot.motor_positions[motor] for motor in robot.ROBOT_MOTORS]
)
radian_joint_speeds = np.deg2rad(
[robot.motor_speeds[motor] for motor in robot.ROBOT_MOTORS]
)
qpos_qvel_previous_action = np.concatenate([
(radian_joint_positions * self.train_sim_flip - self.joint_nominal_position) / 4.6,
radian_joint_speeds / 110.0 * self.train_sim_flip,
self.previous_action / 10.0,
])
# 角速度
ang_vel = np.clip(np.deg2rad(robot.gyroscope) / 50.0, -1.0, 1.0)
# 投影的重力方向
orientation_quat_inv = R.from_quat(robot._global_cheat_orientation).inv()
projected_gravity = orientation_quat_inv.apply(np.array([0.0, 0.0, -1.0]))
# 组合观测
observation = np.concatenate([
qpos_qvel_previous_action,
ang_vel,
velocity,
projected_gravity,
])
observation = np.clip(observation, -10.0, 10.0)
return observation.astype(np.float32)
def sync(self):
''' Run a single simulation step '''
self.Player.server.receive()
self.Player.world.update()
self.Player.robot.commit_motor_targets_pd()
self.Player.server.send()
if self._target_dt > 0.0:
now = time.time()
if self._last_sync_time is None:
self._last_sync_time = now
return
elapsed = now - self._last_sync_time
remaining = self._target_dt - elapsed
if remaining > 0.0:
time.sleep(remaining)
now = time.time()
self._last_sync_time = now
def debug_joint_status(self):
robot = self.Player.robot
actual_joint_positions = np.deg2rad(
[robot.motor_positions[motor] for motor in robot.ROBOT_MOTORS]
)
target_joint_positions = getattr(
self,
'target_joint_positions',
np.zeros(len(robot.ROBOT_MOTORS), dtype=np.float32)
)
joint_error = actual_joint_positions - target_joint_positions
leg_slice = slice(11, None)
self.debug_log(
"[WalkDebug] "
f"step={self.step_counter} "
f"pos={np.round(self.Player.world.global_position, 3).tolist()} "
f"target_xy={np.round(self.target_position, 3).tolist()} "
f"target_leg={np.round(target_joint_positions[leg_slice], 3).tolist()} "
f"actual_leg={np.round(actual_joint_positions[leg_slice], 3).tolist()} "
f"err_norm={float(np.linalg.norm(joint_error)):.4f} "
f"fallen={self.Player.world.global_position[2] < 0.3}"
)
def reset(self, seed=None, options=None):
'''
Reset and stabilize the robot
Note: for some behaviors it would be better to reduce stabilization or add noise
'''
r = self.Player.robot
super().reset(seed=seed)
if seed is not None:
np.random.seed(seed)
length1 = np.random.uniform(10, 20) # randomize target distance
length2 = np.random.uniform(10, 20) # randomize target distance
length3 = np.random.uniform(10, 20) # randomize target distance
angle2 = np.random.uniform(-30, 30) # randomize initial orientation
angle3 = np.random.uniform(-30, 30) # randomize target direction
self.step_counter = 0
self.waypoint_index = 0
self.route_completed = False
self.previous_action = np.zeros(len(self.Player.robot.ROBOT_MOTORS))
self.previous_pos = np.array([0.0, 0.0]) # Initialize for first step
self.walk_cycle_step = 0
# 随机 beam 目标位置和朝向,增加训练多样性
beam_x = (random() - 0.5) * 10
beam_y = (random() - 0.5) * 10
for _ in range(5):
self.Player.server.receive()
self.Player.world.update()
self.Player.robot.commit_motor_targets_pd()
self.Player.server.commit_beam(pos2d=(beam_x, beam_y), rotation=0)
self.Player.server.send()
# 执行 Neutral 技能直到完成,给机器人足够时间在 beam 位置稳定站立
finished_count = 0
for _ in range(10):
finished = self.Player.skills_manager.execute("Neutral")
self.sync()
if finished:
finished_count += 1
if finished_count >= 3: # 假设需要连续3次完成才算成功
break
# neutral_joint_positions = np.deg2rad(
# [self.Player.robot.motor_positions[motor] for motor in self.Player.robot.ROBOT_MOTORS]
# )
# reliable_neutral, neutral_leg_norm, neutral_leg_max, neutral_height = self.is_reliable_neutral_pose(neutral_joint_positions)
# if self.auto_calibrate_train_sim_flip and reliable_neutral and not self.flip_calibrated_once:
# self.calibrate_train_sim_flip_from_neutral(neutral_joint_positions)
# self.flip_calibrated_once = True
# if self.calibrate_nominal_from_neutral and reliable_neutral and not self.nominal_calibrated_once:
# self.joint_nominal_position = neutral_joint_positions * self.train_sim_flip
# self.nominal_calibrated_once = True
# self.debug_log(
# "[ResetDebug] "
# f"neutral_pos={np.round(self.Player.world.global_position, 3).tolist()} "
# f"shoulders={np.round(neutral_joint_positions[2:10], 3).tolist()} "
# f"legs={np.round(neutral_joint_positions[11:], 3).tolist()} "
# f"flip={self.train_sim_flip.tolist()} "
# f"nominal_legs={np.round(self.joint_nominal_position[11:], 3).tolist()} "
# f"calibrated_once={(self.flip_calibrated_once, self.nominal_calibrated_once)} "
# f"reliable_neutral={reliable_neutral} "
# f"leg_norm={neutral_leg_norm:.3f} leg_max={neutral_leg_max:.3f} height={neutral_height:.3f}"
# )
# reset_action_noise = np.random.uniform(-0.015, 0.015, size=(len(self.Player.robot.ROBOT_MOTORS),))
# self.target_joint_positions = (self.joint_nominal_position + reset_action_noise) * self.train_sim_flip
# for idx, target in enumerate(self.target_joint_positions):
# r.set_motor_target_position(
# r.ROBOT_MOTORS[idx], target*180/math.pi, kp=25, kd=0.6
# )
# memory variables
self.initial_position = np.array(self.Player.world.global_position[:2])
self.previous_pos = self.initial_position.copy() # Critical: set to actual position
self.act = np.zeros(self.no_of_actions, np.float32)
point1 = self.initial_position + np.array([length1, 0])
point2 = point1 + MathOps.rotate_2d_vec(np.array([length2, 0]), angle2, is_rad=False)
point3 = point2 + MathOps.rotate_2d_vec(np.array([length3, 0]), angle3, is_rad=False)
self.point_list = [point1, point2, point3]
self.target_position = self.point_list[self.waypoint_index]
return self.observe(True), {}
def render(self, mode='human', close=False):
return
def compute_reward(self, previous_pos, current_pos, action):
velocity = current_pos - previous_pos
velocity_magnitude = np.linalg.norm(velocity)
direction_to_target = self.target_position - current_pos
prev_direction_to_target = self.target_position - previous_pos
distance_to_target = np.linalg.norm(direction_to_target)
prev_distance_to_target = np.linalg.norm(prev_direction_to_target)
progress_reward = np.clip((prev_distance_to_target - distance_to_target) * 30.0, -2.0, 4.0)
velocity_in_m_per_sec = velocity_magnitude / 0.05
speed_reward = np.clip(velocity_in_m_per_sec * 1.5, 0.0, 1.5)
if velocity_magnitude > 1e-4 and distance_to_target > 1e-4:
directional_alignment = np.dot(velocity, direction_to_target) / (velocity_magnitude * distance_to_target)
directional_alignment = np.clip(directional_alignment, -1.0, 1.0)
direction_reward = max(0.0, directional_alignment)
else:
direction_reward = 0.0
alive_bonus = 0.05
height = self.Player.world.global_position[2]
if 0.45 <= height <= 1.2:
height_reward = 1.5
else:
height_reward = -6.0
motionless_penalty = -1.5 if velocity_magnitude < 0.003 else 0.0
waypoint_bonus = 0.0
if distance_to_target < 0.5:
waypoint_bonus = 25.0
if self.waypoint_index < len(self.point_list) - 1:
self.waypoint_index += 1
self.target_position = self.point_list[self.waypoint_index]
else:
waypoint_bonus = 100.0
self.route_completed = True
action_magnitude = np.linalg.norm(action[11:])
action_penalty = -0.08 * action_magnitude
tilt_penalty = -0.2 * np.linalg.norm(self.Player.robot.gyroscope[:2]) / 100.0
return (
progress_reward
+ speed_reward
+ direction_reward
+ alive_bonus
+ height_reward
+ motionless_penalty
+ waypoint_bonus
+ action_penalty
+ tilt_penalty
)
def step(self, action):
r = self.Player.robot
self.previous_action = action
self.target_joint_positions = (
self.joint_nominal_position
+ self.scaling_factor * action
)
self.target_joint_positions *= self.train_sim_flip
for idx, target in enumerate(self.target_joint_positions):
r.set_motor_target_position(
r.ROBOT_MOTORS[idx], target * 180 / math.pi, kp=25, kd=0.6
)
self.sync() # run simulation step
self.step_counter += 1
# if self.step_counter % self.debug_every_n_steps == 0:
# self.debug_joint_status()
current_pos = np.array(self.Player.world.global_position[:2], dtype=np.float32)
# Compute reward based on movement from previous step
reward = self.compute_reward(self.previous_pos, current_pos, action)
# Update previous position
self.previous_pos = current_pos.copy()
# Fall detection and penalty
is_fallen = self.Player.world.global_position[2] < 0.3
# terminal state: the robot is falling or timeout
terminated = is_fallen or self.step_counter > 800 or self.route_completed
truncated = False
return self.observe(), reward, terminated, truncated, {}
class Train(Train_Base):
def __init__(self, script) -> None:
super().__init__(script)
def train(self, args):
# --------------------------------------- Learning parameters
n_envs = 8 # Reduced from 8 to decrease CPU/network pressure during init
if n_envs < 1:
raise ValueError("GYM_CPU_N_ENVS must be >= 1")
n_steps_per_env = 512 # RolloutBuffer is of size (n_steps_per_env * n_envs)
minibatch_size = 128 # should be a factor of (n_steps_per_env * n_envs)
total_steps = 30000000
learning_rate = 3e-4
folder_name = f'Walk_R{self.robot_type}'
model_path = f'./scripts/gyms/logs/{folder_name}/'
print(f"Model path: {model_path}")
print(f"Using {n_envs} parallel environments")
# --------------------------------------- Run algorithm
def init_env(i_env):
def thunk():
return WalkEnv(self.ip, self.server_p + i_env)
return thunk
server_log_dir = os.path.join(model_path, "server_logs")
os.makedirs(server_log_dir, exist_ok=True)
servers = Train_Server(self.server_p, self.monitor_p_1000, n_envs + 1) # include 1 extra server for testing
# Wait for servers to start
print(f"Starting {n_envs + 1} rcssservermj servers...")
print("Servers started, creating environments...")
env = SubprocVecEnv([init_env(i) for i in range(n_envs)])
eval_env = SubprocVecEnv([init_env(n_envs)])
try:
# Custom policy network architecture
policy_kwargs = dict(
net_arch=dict(
pi=[256, 256, 128], # Policy network: 3 layers
vf=[256, 256, 128] # Value network: 3 layers
),
activation_fn=__import__('torch.nn', fromlist=['ReLU']).ReLU,
)
if "model_file" in args: # retrain
model = PPO.load(args["model_file"], env=env, device="cpu", n_envs=n_envs, n_steps=n_steps_per_env,
batch_size=minibatch_size, learning_rate=learning_rate)
else: # train new model
model = PPO(
"MlpPolicy",
env=env,
verbose=1,
n_steps=n_steps_per_env,
batch_size=minibatch_size,
learning_rate=learning_rate,
device="cpu",
policy_kwargs=policy_kwargs,
ent_coef=0.01, # Entropy coefficient for exploration
clip_range=0.2, # PPO clipping parameter
gae_lambda=0.95, # GAE lambda
gamma=0.99 # Discount factor
)
model_path = self.learn_model(model, total_steps, model_path, eval_env=eval_env,
eval_freq=n_steps_per_env * 10, save_freq=n_steps_per_env * 10,
backup_env_file=__file__)
except KeyboardInterrupt:
sleep(1) # wait for child processes
print("\nctrl+c pressed, aborting...\n")
servers.kill()
return
env.close()
eval_env.close()
servers.kill()
def test(self, args):
# Uses different server and monitor ports
server_log_dir = os.path.join(args["folder_dir"], "server_logs")
os.makedirs(server_log_dir, exist_ok=True)
server = Train_Server(self.server_p - 1, self.monitor_p, 1, log_dir=server_log_dir)
env = WalkEnv(self.ip, self.server_p - 1)
model = PPO.load(args["model_file"], env=env)
try:
self.export_model(args["model_file"], args["model_file"] + ".pkl",
False) # Export to pkl to create custom behavior
self.test_model(model, env, log_path=args["folder_dir"], model_path=args["folder_dir"])
except KeyboardInterrupt:
print()
env.close()
server.kill()
if __name__ == "__main__":
from types import SimpleNamespace
# 创建默认参数
script_args = SimpleNamespace(
args=SimpleNamespace(
i='127.0.0.1', # Server IP
p=3100, # Server port
m=3200, # Monitor port
r=0, # Robot type
t='Gym', # Team name
u=1 # Uniform number
)
)
trainer = Train(script_args)
trainer.train({"model_file": "scripts/gyms/logs/Walk_R0_000/model_245760_steps.zip"})