Compare commits
13 Commits
f9a3e8ddba
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| a649865643 | |||
| b6cb5bb6a1 | |||
| 5a1ac694e0 | |||
| 14251aa415 | |||
| 0fe0a8697f | |||
| 7b9c52955b | |||
| 4cc2d37d94 | |||
| cd870a4afc | |||
| f5c07edc0a | |||
| 12b8f80002 | |||
| 3e6e40f0c5 | |||
| a1eb7b8573 | |||
| 7200531af3 |
+6
-2
@@ -3,8 +3,12 @@ node_modules/
|
||||
.venv/
|
||||
.vscode/
|
||||
__pycache__/
|
||||
ml/checkpoints/
|
||||
ml/logs/
|
||||
ml/checkpoints/*
|
||||
!ml/checkpoints/jackbot_kinematics_base.zip
|
||||
!ml/checkpoints/jackbot_ppo6_149994_steps.zip
|
||||
!ml/checkpoints/jackbot_ppo6_199992_steps.zip
|
||||
!ml/checkpoints/jackbot_ppo6_499980_steps.zip
|
||||
#ml/logs/
|
||||
|
||||
# Ignore environment files with private passwords/keys
|
||||
.env
|
||||
|
||||
+13
-3
@@ -11,7 +11,7 @@ class ArduinoCommunication(Thread):
|
||||
def __init__(self, port=cfg.port, baudrate=cfg.baudrate, timeout=cfg.comm_timeout):
|
||||
super().__init__()
|
||||
self.daemon = True # Thread schlie�t sich beim Programmende
|
||||
self.serial_conn = serial.Serial(port, baudrate, timeout=timeout)
|
||||
self.serial_conn = serial.Serial(port, baudrate, timeout=timeout)
|
||||
time.sleep(2) # Warten bis Arduino ready
|
||||
|
||||
self.command_queue = Queue()
|
||||
@@ -19,6 +19,9 @@ class ArduinoCommunication(Thread):
|
||||
self.running = Event()
|
||||
self.running.set()
|
||||
|
||||
def send_motion(self, radial_array):
|
||||
self.write(radial_array)
|
||||
|
||||
def run(self):
|
||||
while self.running.is_set():
|
||||
# 1. Befehle senden
|
||||
@@ -70,5 +73,12 @@ class ArduinoCommunication(Thread):
|
||||
|
||||
def stop(self):
|
||||
self.running.clear()
|
||||
self.join()
|
||||
self.serial_conn.close()
|
||||
try:
|
||||
self.join(timeout=0.5)
|
||||
except RuntimeError:
|
||||
pass
|
||||
if self.serial_conn and self.serial_conn.is_open:
|
||||
self.serial_conn.close()
|
||||
|
||||
def close(self):
|
||||
self.stop()
|
||||
+13
-3
@@ -25,10 +25,14 @@ HEADER_FMT = "<B B H I" # ID, Ver, Len, Timestamp
|
||||
TLV_FMT = "<B H"
|
||||
|
||||
class ESP32Communication(Thread):
|
||||
def __init__(self, host=cfg.esp32_ip, port=cfg.esp32_port):
|
||||
def __init__(self, host=None, port=None, ip=None):
|
||||
super().__init__(daemon=True)
|
||||
if ip is not None:
|
||||
host = ip
|
||||
host = cfg.esp32_ip if host is None else host
|
||||
port = cfg.esp32_port if port is None else port
|
||||
self.addr = (host, port)
|
||||
|
||||
|
||||
# UDP Socket - Zero Lag
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||
|
||||
@@ -126,4 +130,10 @@ class ESP32Communication(Thread):
|
||||
|
||||
def stop(self):
|
||||
self.running.clear()
|
||||
self.sock.close()
|
||||
try:
|
||||
self.sock.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def close(self):
|
||||
self.stop()
|
||||
@@ -1,48 +1,50 @@
|
||||
# JackBot — Hexapod Control, Simulation & RL Framework
|
||||
|
||||
JackBot is a modular 3D hexapod robot control and machine learning framework built in Python. It supports real-time kinematics, multi-input options (GUI, gamepads), hardware streaming (ESP32 / Arduino), and vectorized Reinforcement Learning (PPO) using PyBullet and Gymnasium.
|
||||
JackBot is a modular Python framework for controlling a six-legged robot in simulation or on hardware. The current workspace reflects a matured control stack with a PyBullet-based simulator, a GUI-driven manual runtime, and a reinforcement-learning pipeline for PPO training and evaluation.
|
||||
|
||||
---
|
||||
|
||||
## What JackBot Is
|
||||
|
||||
JackBot is a Python-based hexapod robot project that combines:
|
||||
JackBot is a Python-based hexapod project that combines:
|
||||
|
||||
* a robot control stack for a six-legged walking robot,
|
||||
* a physics simulator for testing in software before using real hardware, and
|
||||
* a reinforcement learning pipeline that teaches the robot how to move through trial and error.
|
||||
* a physics simulator (`simulation.py`) for testing in software before using real hardware,
|
||||
* a reinforcement learning pipeline that trains locomotion policies with PPO and behavioral cloning,
|
||||
* and a GUI/gamepad input layer for manual operation.
|
||||
|
||||
The project is not just one script or one model. It is a full control system that can:
|
||||
The project can currently:
|
||||
|
||||
* run the robot in a PyBullet simulation,
|
||||
* accept human commands from a GUI or gamepad,
|
||||
* stream target joint positions to physical hardware, and
|
||||
* train a policy using PPO so the robot can learn locomotion automatically.
|
||||
* accept commands from a GUI or gamepad,
|
||||
* stream target joint positions to physical hardware (ESP32 / Arduino),
|
||||
* train PPO models and evaluate saved checkpoints,
|
||||
* generate kinematics-based teacher data for behavioral cloning.
|
||||
|
||||
---
|
||||
|
||||
## Why the Project Exists
|
||||
|
||||
A hexapod is hard to control manually because each leg has several joints and the robot has to maintain balance while moving. Instead of hard-coding every motion rule, this project uses the robot model and physics simulation as a testbed to learn walking behavior.
|
||||
A hexapod is hard to control manually because each leg has multiple joints and the robot must maintain balance while moving. The project uses a robot model and physics simulation as a testbed for learning motion strategies, refining kinematic control, and validating behavior before applying commands to real hardware.
|
||||
|
||||
In practice, the workflow looks like this:
|
||||
In the current codebase, the practical workflow is:
|
||||
|
||||
1. The robot starts from a standing pose.
|
||||
2. The policy receives sensory information from the simulation.
|
||||
3. The policy chooses new joint target motions.
|
||||
4. The simulation updates the physics.
|
||||
5. The policy receives a reward for surviving and moving in the right direction.
|
||||
6. Over many iterations, PPO improves the controller.
|
||||
1. Start the robot in either simulation or hardware mode.
|
||||
2. Feed motion commands from GUI/gamepad or a training environment.
|
||||
3. Convert target foot positions into joint targets using inverse kinematics.
|
||||
4. Apply these targets to the active backend.
|
||||
5. Train or evaluate PPO policies against the simulated robot.
|
||||
|
||||
---
|
||||
|
||||
## Key Components
|
||||
|
||||
* **Robot abstraction (`Robot.py`)**: wraps the robot body, robot state, and joint control API.
|
||||
* **Kinematics (`kinematics.py`)**: turns target leg poses into actual joint angles through inverse kinematics.
|
||||
* **Simulation (`simulation.py`)**: creates and updates the PyBullet world where the robot can be tested safely.
|
||||
* **Inputs (`inputs/`)**: lets the robot be controlled from either a GUI, a gamepad, or a generated target command.
|
||||
* **ML environment (`ml/env.py`)**: provides the Gymnasium environment that the policy interacts with.
|
||||
* **PPO training (`ml/train.py`)**: trains a policy using stable-baselines3.
|
||||
* **Evaluation (`ml/evaluate.py`)**: loads a saved model and runs policy rollouts to inspect performance.
|
||||
* **Robot abstraction (`Robot.py`)**: Central handler for the active backend, current joint state, IK/FK helpers, gait handling, and RL action application.
|
||||
* **Kinematics (`kinematics.py`)**: Converts target foot positions into joint angles using IKPy chains for each leg.
|
||||
* **Simulation (`simulation.py`)**: Manages PyBullet scene loading, stepping, joint actuation, base pose queries, and physics telemetry.
|
||||
* **Inputs (`inputs/`)**: Receives commands from GUI sliders, Pygame gamepads, and random command generation.
|
||||
* **ML Subsystem (`ml/`)**: Contains the Gymnasium environment (`env.py`), PPO training (`run_train.py`), evaluation (`run_eval.py`), BC pretraining (`pretrain_bc.py`), callbacks, and metrics overlays.
|
||||
* **States (`states/`)**: Contains additional state-machine classes such as `IdleState`, `WalkingState`, and `WaveState`. These exist in the repository, but the current active runtime in `main.py` does not currently drive them through `Robot.tick()`.
|
||||
|
||||
---
|
||||
|
||||
@@ -50,49 +52,68 @@ In practice, the workflow looks like this:
|
||||
|
||||
```text
|
||||
JackBot/
|
||||
├── main.py # manual control and hardware streaming entry point
|
||||
├── Robot.py # robot wrapper and backend abstraction
|
||||
├── config.py # global settings and communication configuration
|
||||
├── kinematics.py # inverse kinematics used to map motion commands to joints
|
||||
├── simulation.py # PyBullet simulation shell for the robot
|
||||
├── robot_init.py # neutral standing pose and initial joint values
|
||||
├── DataTypes.py # typed data structures for positions and joint angles
|
||||
├── main.py # Manual runtime entry point
|
||||
├── Robot.py # Unified robot wrapper + backend selection
|
||||
├── config.py # Central runtime configuration
|
||||
├── kinematics.py # IK/FK helpers
|
||||
├── simulation.py # PyBullet scene / physics manager
|
||||
├── robot_init.py # Initial joint definitions and center points
|
||||
├── DataTypes.py # Typed arrays for positions / angles
|
||||
├── JackBotUrdf.urdf # Robot URDF
|
||||
│
|
||||
├── states/ # gait/state-machine behavior logic
|
||||
├── states/ # State classes present in the project
|
||||
│ ├── State.py
|
||||
│ ├── IdleState.py
|
||||
│ ├── WalkingState.py
|
||||
│ └── WaveState.py
|
||||
│ ├── WaveState.py
|
||||
│ ├── ml_walking.py
|
||||
│ └── __init__.py
|
||||
│
|
||||
├── inputs/ # command sources for the robot
|
||||
├── inputs/ # Command input providers
|
||||
│ ├── InputProvider.py
|
||||
│ ├── PygameController.py
|
||||
│ └── RandomeInputProvider.py
|
||||
│ ├── RandomeInputProvider.py
|
||||
│ └── RandomInputProvider.py
|
||||
│
|
||||
├── gui/ # visual control frontend
|
||||
├── gui/ # GUI/dashboard control layer
|
||||
│ └── MainWindow.py
|
||||
│
|
||||
├── EspCommunication.py # ESP32 communication layer
|
||||
├── ArduinoCommunication.py # Arduino serial communication layer
|
||||
├── JackBotUrdf.urdf # robot mesh and joint definition
|
||||
├── ml/ # Gymnasium RL training + evaluation stack
|
||||
│ ├── env.py # RL environment + reward logic
|
||||
│ ├── callbacks.py # SB3 callbacks for logs/curriculum
|
||||
│ ├── pretrain_bc.py # Behavior cloning pretraining
|
||||
│ ├── run_train.py # PPO training entry point
|
||||
│ ├── run_eval.py # Evaluation of saved checkpoints
|
||||
│ ├── run_eval_training.py # Kinematics-mode benchmark script
|
||||
│ ├── MetricsOverlay.py # 3D in-scene metrics HUD
|
||||
│ └── checkpoints/ # Model checkpoints + saved runs
|
||||
│
|
||||
└── ml/ # reinforcement learning subsystem
|
||||
├── env.py # Gymnasium environment used by PPO
|
||||
├── SimManager.py # PyBullet scene setup and stepping
|
||||
├── MetricsOverlay.py # HUD and visual overlays
|
||||
├── train.py # PPO training entry point
|
||||
├── run_train.py # command-line training launcher
|
||||
├── evaluate.py # policy evaluation loop
|
||||
└── run_eval.py # CLI wrapper for evaluation
|
||||
├── EspCommunication.py # ESP32 UDP communication layer
|
||||
├── ArduinoCommunication.py # Arduino serial communication layer
|
||||
├── Helper Scripts/ # Utility scripts
|
||||
│ ├── FindCenterPoints.py
|
||||
│ └── torqueCalc.py
|
||||
│
|
||||
├── requirements.txt
|
||||
├── README.md
|
||||
└── ...
|
||||
```
|
||||
|
||||
### Important current-state note
|
||||
|
||||
The repository contains a few pieces that are still present but not fully connected to the current runtime:
|
||||
|
||||
* `states/WalkingState.py`, `states/WaveState.py`, and `states/ml_walking.py` exist, but `main.py` currently drives `Robot.tick()` directly instead of routing through the active `STATE_REGISTRY`.
|
||||
* `inputs/RandomeInputProvider.py` exists, but the active runtime does not currently use it directly. The GUI resolves random walking behavior in `gui/MainWindow.py`.
|
||||
* `WaveEmoteState` / `LaolaWaveEmoteState` are defined in `states/WaveState.py`, but they are not currently registered in `states/__init__.py`.
|
||||
|
||||
---
|
||||
|
||||
## System Requirements
|
||||
|
||||
* **Python 3.12** (Recommended)
|
||||
* **OS:** Linux (Ubuntu/Debian) or Windows 10/11
|
||||
* **Dependencies:** `pybullet`, `gymnasium`, `stable-baselines3`, `torch`, `numpy`, `pygame`, `ikpy`, `pyserial`, `matplotlib`
|
||||
* **Python:** 3.12 recommended
|
||||
* **OS:** Windows 10/11 or Linux
|
||||
* **Dependencies:** `pybullet`, `gymnasium`, `stable-baselines3`, `torch`, `numpy`, `pygame`, `ikpy`, `pyserial`, `matplotlib`, `dearpygui`
|
||||
|
||||
---
|
||||
|
||||
@@ -110,7 +131,8 @@ pip install -r requirements.txt
|
||||
### Windows (PowerShell)
|
||||
|
||||
```powershell
|
||||
python3.12 -m venv .venv
|
||||
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope Process
|
||||
python -m venv .venv
|
||||
.\.venv\Scripts\Activate.ps1
|
||||
python -m pip install --upgrade pip setuptools wheel
|
||||
pip install -r requirements.txt
|
||||
@@ -120,144 +142,267 @@ pip install -r requirements.txt
|
||||
|
||||
## Usage Guide
|
||||
|
||||
### 1. Manual Control & Hardware Streaming (`main.py`)
|
||||
## Manual Control & Hardware Streaming (`main.py`)
|
||||
|
||||
`main.py` is the operational entry point for driving the robot manually via GUI sliders or a gamepad, running either in 3D PyBullet simulation or connected to physical hardware.
|
||||
`main.py` is the main operational entry point for driving the robot manually through the GUI or a connected gamepad.
|
||||
|
||||
To launch:
|
||||
|
||||
```bash
|
||||
python main.py
|
||||
```
|
||||
|
||||
#### Configuration (`config.py`)
|
||||
Edit `config.py` prior to launching `main.py` to configure execution mode and connections:
|
||||
### Configuration (`config.py`)
|
||||
|
||||
* **Backend Selection (`cfg.backend`):**
|
||||
* `BackendType.SIMULATION`: Executes motion inside a 3D PyBullet window.
|
||||
* `BackendType.ESP32`: Streams target joint angles over WiFi sockets to an ESP32 micro-controller (`cfg.esp32_ip`, `cfg.esp32_port`).
|
||||
* `BackendType.ARDUINO`: Streams target joint angles over Serial to an Arduino (`cfg.port`, `cfg.baudrate`).
|
||||
Before launching `main.py`, edit `config.py` to select the backend and connection targets.
|
||||
|
||||
* **Backend Selection (`cfg.backend`)**:
|
||||
* `BackendType.SIMULATION`: run inside a PyBullet window
|
||||
* `BackendType.ESP32`: stream motion over UDP to an ESP32
|
||||
* `BackendType.ARDUINO`: stream motion over serial to an Arduino
|
||||
|
||||
Supported configuration values in the current code include:
|
||||
|
||||
* `backend`
|
||||
* `urdf_path`
|
||||
* `port`, `baudrate`
|
||||
* `esp32_ip`, `esp32_port`
|
||||
* `tick_rate_hz`, `step_duration`
|
||||
* `step_height`, `step_length`
|
||||
|
||||
### GUI input sources
|
||||
|
||||
The current GUI (`gui/MainWindow.py`) exposes these input sources:
|
||||
|
||||
* `Gamepad`
|
||||
* `GUI Sliders`
|
||||
* `Random Walk`
|
||||
|
||||
The active `main.py` runtime resolves commands through `resolve_active_command(...)` and then passes the resulting `vector_dirmov` directly to `Robot.tick()`.
|
||||
|
||||
---
|
||||
|
||||
### 2. How the Machine Learning System Works
|
||||
## Machine Learning Pipeline (`ml/`)
|
||||
|
||||
The machine learning subsystem teaches the robot to move by interacting with a simulation environment instead of relying on a manually written gait controller.
|
||||
The ML subsystem currently uses:
|
||||
|
||||
At a high level:
|
||||
* **Gymnasium** as the environment API
|
||||
* **PyBullet** as the physics engine
|
||||
* **Stable-Baselines3 PPO** as the learning algorithm
|
||||
* **Curriculum phases** to gradually expose more difficult command spaces
|
||||
|
||||
* The policy receives a vector of observations from the simulator.
|
||||
* The policy outputs a set of continuous joint deltas.
|
||||
* Those outputs are applied to the robot in the physics simulation.
|
||||
* The environment computes a reward based on survival, movement, stability, and command-following quality.
|
||||
* PPO updates the policy over many training iterations to improve the controller.
|
||||
### Current ML scripts
|
||||
|
||||
#### What the policy sees and does
|
||||
* `ml/run_train.py` — PPO training entry point
|
||||
* `ml/run_eval.py` — phase-based model evaluation
|
||||
* `ml/run_eval_training.py` — reward benchmark for kinematics mode
|
||||
* `ml/pretrain_bc.py` — collect teacher data from the kinematics solver and pretrain a base policy
|
||||
* `ml/env.py` — environment definition and reward logic
|
||||
* `ml/callbacks.py` — reward logging and curriculum callbacks
|
||||
|
||||
The policy input contains:
|
||||
### Training flow
|
||||
|
||||
* 18 joint angles from the robot, and
|
||||
* 4 command dimensions describing the desired motion direction and yaw rate.
|
||||
Training is launched with:
|
||||
|
||||
The policy output is:
|
||||
|
||||
* 18 continuous values, one per joint, describing how much each joint should change.
|
||||
|
||||
This means the learning method is not controlling a discrete gait state directly. Instead, it learns a continuous control policy for the whole body.
|
||||
|
||||
#### Methods implemented
|
||||
|
||||
The current ML stack uses:
|
||||
|
||||
* **Gymnasium** as the environment API.
|
||||
* **PyBullet** as the physics engine.
|
||||
* **Stable-Baselines3 PPO** as the learning algorithm.
|
||||
* **Curriculum learning** to gradually unlock harder command regimes.
|
||||
|
||||
The key ideas are:
|
||||
|
||||
1. **Standing first**: the robot must stay upright and stable.
|
||||
2. **Forward motion second**: the robot must learn to move in a commanded direction.
|
||||
3. **Turning next**: after forward command-following is stable, the policy gets a yaw/turning challenge.
|
||||
4. **Omni-direction later**: the full command space is gradually exposed only once the simpler skills are reliable.
|
||||
|
||||
This staged approach is important because learning to balance and walk all at once is difficult for a real hexapod.
|
||||
|
||||
#### Training flow
|
||||
|
||||
Training is launched through `ml/run_train.py` and hands off to `ml/train.py`.
|
||||
|
||||
Typical training starts as:
|
||||
```bash
|
||||
python ml/run_train.py --timesteps 100000 --model ml/checkpoints/ppo_joint_command
|
||||
python ml/run_train.py --total-timesteps 1500000 --gui
|
||||
```
|
||||
|
||||
Training uses the simulator as the environment, runs PPO updates, and periodically saves checkpoint models.
|
||||
The current training script creates a vectorized PPO environment, optionally loads a pre-trained checkpoint, and saves results into `ml/checkpoints/` and `ml/logs/`.
|
||||
|
||||
#### Evaluation flow
|
||||
### Evaluation flow
|
||||
|
||||
Evaluation uses `ml/run_eval.py` and `ml/evaluate.py`.
|
||||
Evaluation is launched with:
|
||||
|
||||
A saved PPO model is loaded and run in deterministic evaluation mode. This is used to answer questions like:
|
||||
|
||||
* Does the policy actually move?
|
||||
* Does it survive longer than before?
|
||||
* Does it remain stable under the commanded motion?
|
||||
|
||||
Example:
|
||||
```bash
|
||||
python ml/run_eval.py --model ml/checkpoints/ppo_joint_command.zip --episodes 5 --gui
|
||||
python ml/run_eval.py --model ml/checkpoints/jackbot_kinematics_base.zip --episodes-per-phase 5 --gui
|
||||
```
|
||||
|
||||
This script runs a multi-phase deterministic evaluation suite with fixed command vectors for:
|
||||
|
||||
* `FORWARD`
|
||||
* `TURN_AND_DIRECTION`
|
||||
* `OMNI_DIRECTION`
|
||||
* `FULL_COMMAND`
|
||||
|
||||
### Behavioral cloning pretraining
|
||||
|
||||
The repository also contains a behavioral cloning route:
|
||||
|
||||
```bash
|
||||
python ml/pretrain_bc.py --num-samples 100000 --epochs 15 --save-path ml/checkpoints/jackbot_kinematics_base.zip
|
||||
```
|
||||
|
||||
This script gathers `(observation, action)` data from the kinematics teacher and trains a PPO policy to act as a learned base model.
|
||||
|
||||
---
|
||||
|
||||
## What the Reward Is Trying to Teach
|
||||
|
||||
The reward function is not a single number with one purpose. It combines several terms so the policy learns to:
|
||||
The reward function in `ml/env.py` is designed to teach several things at once:
|
||||
|
||||
* survive in the environment,
|
||||
* move in the commanded direction,
|
||||
* avoid unwanted sideways drift,
|
||||
* stay upright without excessive tilt,
|
||||
* avoid giant control jumps,
|
||||
* keep the robot away from a low collapsed posture.
|
||||
* survival and stability,
|
||||
* following the commanded direction,
|
||||
* avoiding lateral drift,
|
||||
* maintaining base height,
|
||||
* reducing abrupt control changes,
|
||||
* staying close to a stable stance when the command is zero.
|
||||
|
||||
The main ideas are:
|
||||
The environment uses several reward components, including:
|
||||
|
||||
* a small alive bonus for staying upright,
|
||||
* directional movement rewards,
|
||||
* penalties for drifting or standing still when a command is active,
|
||||
* penalties for excessive tilt or collapse,
|
||||
* a penalty for large abrupt control changes.
|
||||
* height reward,
|
||||
* stability reward,
|
||||
* pose closeness reward,
|
||||
* smoothness reward,
|
||||
* linear velocity tracking,
|
||||
* angular velocity tracking,
|
||||
* jitter penalty,
|
||||
* stand-by penalty when the command is zero.
|
||||
|
||||
This style of reward shaping encourages the policy to learn real locomotion rather than just freezing in place.
|
||||
### Detailed reward structure
|
||||
|
||||
### Curriculum / phase progression
|
||||
The reward is built step by step inside `JackBotEnv._compute_reward()` in `ml/env.py`. It is not a single binary success signal; it is a dense shaping signal that rewards good behavior continuously throughout the episode.
|
||||
|
||||
The environment uses a staged curriculum to expose command complexity gradually.
|
||||
At each control step, the environment measures:
|
||||
|
||||
* **Phase 0**: basic standing / forward-focused behavior
|
||||
* **Phase 1**: turning and directional regularization
|
||||
* **Phase 2**: omni-directional movement
|
||||
* **Phase 3**: full-command challenge
|
||||
* current body height,
|
||||
* roll and pitch angles,
|
||||
* current joint configuration,
|
||||
* measured linear and angular velocities,
|
||||
* the active command vector `[vx, vy, omega]`,
|
||||
* the difference between the current action and the previous actions.
|
||||
|
||||
The goal is to prevent the learner from being asked to master all difficult motion goals at once.
|
||||
From these values, it computes a set of sub-rewards:
|
||||
|
||||
* `height reward`: a Gaussian-style reward based on how close the robot body is to the target height.
|
||||
* `stability reward`: a reward for keeping roll/pitch low and the body well balanced.
|
||||
* `pose closeness reward`: rewards staying near the default standing joint posture.
|
||||
* `smoothness reward`: rewards actions that change gradually instead of abruptly.
|
||||
* `linear velocity reward`: encourages the robot to move in the commanded direction and speed.
|
||||
* `angular velocity reward`: rewards matching the commanded turning rate.
|
||||
|
||||
The environment then adds two kinds of correction terms:
|
||||
|
||||
* `jitter penalty`: subtracts a small amount when action changes are noisy or jerky.
|
||||
* `stand_penalty`: when the command is effectively zero, penalizes unintended movement and yaw drift.
|
||||
|
||||
This makes the reward function behave as a soft guidance system: the agent gets a steady gradient that says “this is closer to what we want” or “this is worse than the desired behavior.”
|
||||
|
||||
### Standing mode vs. walking mode
|
||||
|
||||
The reward code handles two cases differently:
|
||||
|
||||
#### 1. Standing mode
|
||||
When the command vector is close to zero (`cmd_norm < 0.05` and `abs(cmd_yaw) < 0.05`), the agent is not supposed to move much. In that case the reward focuses on:
|
||||
|
||||
* keeping the body at the correct height,
|
||||
* staying stable,
|
||||
* maintaining a clean posture,
|
||||
* staying smooth.
|
||||
|
||||
A small `stand_penalty` is then applied to discourage unintended speed and yaw drift while the robot is supposed to hold position.
|
||||
|
||||
#### 2. Walking mode
|
||||
When a non-zero command is active, the robot is rewarded for moving in the intended direction and turning at the requested rate. The reward then emphasizes:
|
||||
|
||||
* matching the commanded linear velocity,
|
||||
* matching the commanded yaw rate,
|
||||
* continuing to maintain height and stability,
|
||||
* staying smooth in its control inputs.
|
||||
|
||||
If the command expects movement but the robot is effectively still, the code now applies a stronger `stillness_penalty` instead of a neutral reward. This means standing while the command says to move is explicitly discouraged.
|
||||
|
||||
### Why the reward is shaped this way
|
||||
|
||||
The goal is not just to teach the robot to stay alive. The reward is designed so that a PPO agent learns multiple useful habits at once:
|
||||
|
||||
* do not collapse or tip over,
|
||||
* keep the body at a sensible height,
|
||||
* follow directional commands,
|
||||
* avoid unstable oscillations,
|
||||
* avoid overreactive control jumps,
|
||||
* stay near a normal standing pose when no motion is requested.
|
||||
|
||||
This is why the environment is not based on a single sparse reward such as “+1 for success, 0 otherwise.” Instead, it uses dense reward shaping so the policy receives useful feedback on every step.
|
||||
|
||||
### Are the penalties real penalties?
|
||||
|
||||
Yes — in the reward function they are real negative contributions. For example:
|
||||
|
||||
* `jitter_penalty` subtracts from the step reward when action changes are too abrupt,
|
||||
* `stand_penalty` subtracts when the robot moves unnecessarily while standing,
|
||||
* `stillness_penalty` subtracts when movement is commanded but the robot remains essentially frozen.
|
||||
|
||||
In the current implementation, a non-zero command that is not followed by meaningful motion now yields an explicit penalty instead of a neutral reward. This is the main behavior change requested for the training setup: standing while the command says to move is now actively discouraged.
|
||||
|
||||
The code does this:
|
||||
|
||||
```python
|
||||
final_reward = step_reward + jitter_penalty + alive_bonus
|
||||
```
|
||||
|
||||
That means:
|
||||
|
||||
* negative penalty terms can now reduce the reward below zero,
|
||||
* the reward is no longer clipped to zero in this path,
|
||||
* and the episode is still only ended by the separate failure check in `_update_robot_failure()`.
|
||||
|
||||
So the answer is:
|
||||
|
||||
* the penalties are real reward penalties,
|
||||
* they are now strong enough to discourage command-mismatch behavior,
|
||||
* and the actual terminal condition remains the failure check in `_update_robot_failure()`.
|
||||
|
||||
### What actually ends an episode?
|
||||
|
||||
The episode ends when the robot is considered failed, not when a reward penalty is applied. In `ml/env.py`, the environment marks the robot as failed if:
|
||||
|
||||
* it is too tilted (`roll` or `pitch` exceed the configured failure threshold), or
|
||||
* it has collapsed below a minimum body-height threshold.
|
||||
|
||||
That is a hard termination condition. In other words:
|
||||
|
||||
* reward penalties discourage bad behavior,
|
||||
* failure conditions stop the episode when the robot is clearly unstable or collapsed.
|
||||
|
||||
### Practical interpretation
|
||||
|
||||
A good mental model is:
|
||||
|
||||
* the reward function teaches the robot what “good locomotion” looks like,
|
||||
* the failure check prevents the robot from continuing when it is physically broken or unstable,
|
||||
* and the curriculum gradually increases the difficulty of the commands as the robot becomes more capable.
|
||||
|
||||
This combination is a common reinforcement-learning setup for locomotion: dense rewards shape the desired behavior, while hard failure conditions protect the training process from degenerate states.
|
||||
|
||||
This reward shaping encourages the robot to learn locomotion patterns rather than simply freezing in place.
|
||||
|
||||
---
|
||||
|
||||
## Curriculum / Phase Progression
|
||||
|
||||
The environment currently uses the following curriculum stages:
|
||||
|
||||
* **STAND_ONLY**
|
||||
* **FORWARD**
|
||||
* **TURN_AND_DIRECTION**
|
||||
* **OMNI_DIRECTION**
|
||||
* **FULL_COMMAND**
|
||||
|
||||
The training environment gradually advances phase complexity based on survival, stability, and movement metrics. `ml/callbacks.py` includes custom curriculum-handling logic for the online learning loop.
|
||||
|
||||
---
|
||||
|
||||
## How the Control Loop Works in Practice
|
||||
|
||||
A simple, human-readable pipeline is:
|
||||
A simplified view of the current runtime is:
|
||||
|
||||
1. `main.py` or the training/evaluation wrapper creates the robot environment.
|
||||
2. The simulation runs the robot in PyBullet.
|
||||
3. The policy observes the latest joint states and command vectors.
|
||||
4. PPO predicts a new action.
|
||||
5. The action is applied to the robot joints.
|
||||
6. The simulator steps forward one frame.
|
||||
7. The reward is computed from the new state.
|
||||
8. The policy improves based on that reward.
|
||||
|
||||
That loop is the essence of the machine learning part of the project.
|
||||
1. `main.py` starts the joystick controller process and opens the GUI.
|
||||
2. The GUI resolves active commands (`Gamepad`, slider, or random walk).
|
||||
3. `Robot.tick()` receives the current motion vector and applies it through the active backend.
|
||||
4. In simulation mode, `Simulation.step()` advances the PyBullet world.
|
||||
5. In training/evaluation mode, `JackBotEnv.step()` computes reward, updates curriculum, and returns observations.
|
||||
6. PPO uses the observation/action loop to improve the policy.
|
||||
|
||||
---
|
||||
|
||||
@@ -266,55 +411,73 @@ That loop is the essence of the machine learning part of the project.
|
||||
This repository is useful because it combines several layers that are often separate:
|
||||
|
||||
* robot control and kinematics,
|
||||
* physical simulation,
|
||||
* physics simulation,
|
||||
* command input sources,
|
||||
* RL environment construction,
|
||||
* PPO training and evaluation.
|
||||
* PPO training and evaluation,
|
||||
* hardware communication layers.
|
||||
|
||||
For a beginner, the easiest way to think about the repo is:
|
||||
For a newcomer, the easiest way to think about the project is:
|
||||
|
||||
- `main.py` is for direct manual control,
|
||||
- `ml/env.py` is the simulator-to-policy interface,
|
||||
- `ml/train.py` is where training happens,
|
||||
- `ml/evaluate.py` is where you check whether the learned policy is actually good.
|
||||
- `main.py` is the manual control entry point,
|
||||
- `Robot.py` is the core robot wrapper,
|
||||
- `simulation.py` is the physics layer,
|
||||
- `ml/env.py` is the environment interface for RL,
|
||||
- `ml/run_train.py`, `ml/run_eval.py`, and `ml/pretrain_bc.py` are the main ML workflows.
|
||||
|
||||
---
|
||||
|
||||
## Reward Function & Termination Mechanics (`ml/env.py`)
|
||||
## Current runtime notes and caveats
|
||||
|
||||
### 1. Reward Function Formulation
|
||||
### State system status
|
||||
|
||||
The per-robot step reward ($R_{\text{step}}$) is shaped to reward tracked motion and survival while strongly discouraging stillness once a command is present. The current implementation uses the following structure:
|
||||
The state classes are present in the repository, but the current runtime path is not using them as the main control loop:
|
||||
|
||||
$$R_{\text{step}} = R_{\text{alive}} + R_{\text{tracking}} + R_{\text{rotation}} - P_{\text{drift}} - P_{\text{still}}(t) - P_{\text{height}} - P_{\text{stability}} - P_{\text{large-delta}}$$
|
||||
* `Robot.tick()` currently updates the robot directly from `vector_dirmov`
|
||||
* the `STATE_REGISTRY` exists, but it is not the path used by the current `main.py` execution flow
|
||||
* the state subsystem remains partially implemented and should be treated as a legacy or optional extension
|
||||
|
||||
* **Alive Bonus ($R_{\text{alive}} \approx +0.02$):** A small positive baseline awarded every timestep the robot remains upright.
|
||||
* **Velocity Tracking ($R_{\text{tracking}}$):** Rewards linear movement aligned with the commanded direction vector.
|
||||
* **Yaw Rotation Tracking ($R_{\text{rotation}}$):** Rewards turning in the commanded yaw direction.
|
||||
* **Drift Penalty ($P_{\text{drift}}$):** Penalizes lateral motion that does not align with the commanded direction.
|
||||
* **Age-Ramped Stillness Penalty ($P_{\text{still}}(t)$):** Penalizes remaining stationary when a command is active; the penalty ramps up as the episode gets older so the policy cannot settle into a frozen local optimum.
|
||||
* **Height Penalty ($P_{\text{height}}$):** Penalizes falling below the measured post-settle standing height.
|
||||
* **Body Stability Penalty ($P_{\text{stability}}$):** Penalizes roll and pitch tilt.
|
||||
* **Large-Delta Penalty ($P_{\text{large-delta}}$):** Penalizes only large joint-control jumps, not normal continuous command usage, so the robot is free to use its joints continuously.
|
||||
### Input source status
|
||||
|
||||
The repository currently includes both:
|
||||
|
||||
* `inputs/PygameController.py` for gamepad input
|
||||
* `gui/MainWindow.py` for selecting `Gamepad`, `GUI Sliders`, and `Random Walk`
|
||||
|
||||
The standalone random input provider file is present, but it is not the path currently used by `main.py`.
|
||||
|
||||
### Hardware communication status
|
||||
|
||||
The hardware communication classes still exist:
|
||||
|
||||
* `EspCommunication.py` for ESP32 UDP
|
||||
* `ArduinoCommunication.py` for Arduino serial
|
||||
|
||||
They are available via `cfg.backend`, but they are not the primary path in the current example workflows shown here.
|
||||
|
||||
---
|
||||
|
||||
### 2. Failure Detection & Termination Logic
|
||||
## Helper Scripts
|
||||
|
||||
In multi-robot vectorized training (`JackBotEnv`), individual robot failures are handled independently to allow maximum simulation efficiency:
|
||||
### `Helper Scripts/FindCenterPoints.py`
|
||||
|
||||
* **Individual Failure Masking:** A robot is flagged as failed (`failed_robots_mask[idx] = True`) if either condition is met:
|
||||
* **Severe Tilt:** Base roll or pitch orientation exceeds $0.9\text{ radians}$.
|
||||
* **Base Collapse:** Base height drops below a relative threshold derived from the measured settled standing height.
|
||||
* **Visual Failure Feedback:** When a robot fails during GUI execution (`--gui`), its 3D URDF mesh immediately updates to a **semi-transparent dark gray** visual state (`COLOR_FAILED = [0.3, 0.3, 0.3, 0.6]`) to distinguish it from active learners.
|
||||
* **Environment Termination (`terminated=True`):** The environment as a whole is marked as terminated when the failure ratio reaches the configured threshold.
|
||||
* **Environment Truncation (`truncated=True`):** Occurs when the episode reaches the maximum allowable step budget (`max_episode_steps`).
|
||||
This script appears to be a utility for analyzing kinematic center point data and related foot-placement experiments. It is not part of the active runtime path.
|
||||
|
||||
### `Helper Scripts/torqueCalc.py`
|
||||
|
||||
This is a stand-alone Tkinter utility for estimating servo torque requirements based on robot mass, leg dimensions, and safety factor. It is a design/support script rather than part of the main robot runtime.
|
||||
|
||||
---
|
||||
|
||||
## Environment Mechanics & Telemetry (`ml/env.py`)
|
||||
## Bottom Line
|
||||
|
||||
When training with `--gui`, `JackBotEnv` includes dynamic visual feedback mechanisms:
|
||||
The current codebase is a working hybrid of:
|
||||
|
||||
* **Metrics HUD:** A live on-screen text overlay tracking active episode count, total step rate (FPS), average base height, roll/pitch angles, and cumulative per-robot rewards.
|
||||
* **Leader Crown ($\text{👑}$):** A floating crown debug indicator tracks and positions itself directly above the base of whichever robot is achieving the highest cumulative reward in the multi-robot grid.
|
||||
* real-time robot control,
|
||||
* PyBullet simulation,
|
||||
* GUI/manual input,
|
||||
* PPO-based RL training and evaluation,
|
||||
* partial state-machine scaffolding,
|
||||
* hardware communication support.
|
||||
|
||||
The information in this README has been updated to match the current files in the workspace, especially around the true ML entry points, active runtime flow, and the fact that some older state-helper modules are present but not currently wired into the main execution path.
|
||||
|
||||
@@ -59,8 +59,11 @@ class HardwareBackend:
|
||||
return [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]
|
||||
|
||||
def cleanup(self) -> None:
|
||||
if self.comm_channel and hasattr(self.comm_channel, 'close'):
|
||||
self.comm_channel.close()
|
||||
if self.comm_channel:
|
||||
if hasattr(self.comm_channel, 'stop'):
|
||||
self.comm_channel.stop()
|
||||
elif hasattr(self.comm_channel, 'close'):
|
||||
self.comm_channel.close()
|
||||
|
||||
|
||||
class PyBulletBackend:
|
||||
@@ -123,9 +126,11 @@ class Robot:
|
||||
self.backend: RobotBackend = PyBulletBackend(sim_instance)
|
||||
elif backend_type == BackendType.ESP32:
|
||||
comm = ESP32Communication(ip=cfg.esp32_ip, port=cfg.esp32_port)
|
||||
comm.start()
|
||||
self.backend = HardwareBackend(comm)
|
||||
elif backend_type == BackendType.ARDUINO:
|
||||
comm = ArduinoCommunication(port=cfg.port, baudrate=cfg.baudrate)
|
||||
comm.start()
|
||||
self.backend = HardwareBackend(comm)
|
||||
else:
|
||||
self.backend = backend_type
|
||||
@@ -220,8 +225,8 @@ class Robot:
|
||||
return
|
||||
|
||||
self.gait_phase = (self.gait_phase + 0.22) % (2.0 * math.pi)
|
||||
stride_len = 0.045
|
||||
step_height = 0.035
|
||||
stride_len = cfg.step_length
|
||||
step_height = cfg.step_height
|
||||
|
||||
center_data = (
|
||||
self.center_points.data if hasattr(self.center_points, 'data') else np.array(self.center_points)
|
||||
|
||||
@@ -38,6 +38,14 @@ class RobotConfig:
|
||||
tick_rate_hz: float = 25.0 # Motion loop execution rate [ticks/sec]
|
||||
step_duration: float = 0.8 # Time to complete full gait stride [s]
|
||||
|
||||
@property
|
||||
def standard_tickpersec(self) -> float:
|
||||
return self.tick_rate_hz
|
||||
|
||||
@standard_tickpersec.setter
|
||||
def standard_tickpersec(self, value: float) -> None:
|
||||
self.tick_rate_hz = value
|
||||
|
||||
@property
|
||||
def tick_duration(self) -> float:
|
||||
return 1.0 / self.tick_rate_hz
|
||||
|
||||
+44
-26
@@ -1,7 +1,11 @@
|
||||
"""
|
||||
ml/MetricsOverlay.py - Camera-Facing (Billboard) 3D Floating Text Overlay
|
||||
ml/MetricsOverlay.py - 3D HUD overlay for live simulation telemetry.
|
||||
|
||||
This file provides a small PyBullet HUD renderer that draws live robot metrics in the
|
||||
simulation scene. It is used during GUI runs to show the current phase, command vector,
|
||||
reward information, and basic motion statistics without leaving the 3D view.
|
||||
"""
|
||||
from typing import List, Tuple, Optional
|
||||
from typing import List, Tuple, Optional, Dict
|
||||
import numpy as np
|
||||
import pybullet as p
|
||||
|
||||
@@ -21,20 +25,15 @@ class MetricsHUD:
|
||||
yaw = cam_info[8]
|
||||
pitch = cam_info[9]
|
||||
|
||||
# Orient the text normal toward the camera view direction
|
||||
# PyBullet text default faces local +Z/-Y depending on roll,
|
||||
# converting visualizer yaw/pitch to Euler angles (roll, pitch, yaw in radians)
|
||||
roll_rad = 0.0
|
||||
pitch_rad = np.radians(pitch + 90.0)
|
||||
yaw_rad = np.radians(yaw)
|
||||
|
||||
text_orientation = p.getQuaternionFromEuler(
|
||||
[pitch_rad, roll_rad, yaw_rad],
|
||||
[pitch_rad, 0.0, yaw_rad],
|
||||
physicsClientId=self.client_id
|
||||
)
|
||||
return text_orientation
|
||||
except Exception:
|
||||
# Fallback default orientation if camera info call fails
|
||||
return [0.0, 0.0, 0.0, 1.0]
|
||||
|
||||
def update(
|
||||
@@ -45,29 +44,48 @@ class MetricsHUD:
|
||||
cmd_vel: np.ndarray,
|
||||
fps: float = 0.0,
|
||||
height: float = 0.0,
|
||||
roll_pitch: Tuple[float, float] = (0.0, 0.0)
|
||||
roll_pitch: Tuple[float, float] = (0.0, 0.0),
|
||||
mode: str = "direct",
|
||||
phase: str = "STAND_ONLY",
|
||||
distance: float = 0.0,
|
||||
status: str = "ALIVE",
|
||||
reward_components: Optional[Dict[str, float]] = None,
|
||||
ep_step: int = 0,
|
||||
) -> None:
|
||||
"""Updates floating black text block in 3D space with billboarding."""
|
||||
"""Updates floating text block in 3D space with expanded telemetry."""
|
||||
sorted_rewards = sorted(robot_rewards, reverse=True)
|
||||
top1 = f"{sorted_rewards[0]:+.2f}" if len(sorted_rewards) > 0 else "0.00"
|
||||
top2 = f"{sorted_rewards[1]:+.2f}" if len(sorted_rewards) > 1 else "0.00"
|
||||
top3 = f"{sorted_rewards[2]:+.2f}" if len(sorted_rewards) > 2 else "0.00"
|
||||
|
||||
vx = cmd_vel[0] if len(cmd_vel) > 0 else 0.0
|
||||
vy = cmd_vel[1] if len(cmd_vel) > 1 else 0.0
|
||||
omega = cmd_vel[3] if len(cmd_vel) > 3 else 0.0
|
||||
omega = cmd_vel[2] if len(cmd_vel) > 2 else 0.0
|
||||
|
||||
hud_text = (
|
||||
f"=== JACKBOT METRICS ===\n"
|
||||
f"Episode: {episode}\n"
|
||||
f"Global Step: {step}\n"
|
||||
f"FPS: {fps:.1f}\n"
|
||||
f"----------------------\n"
|
||||
f"Top Rewards: [{top1}, {top2}, {top3}]\n"
|
||||
f"Cmd (X,Y,W): [{vx:+.2f}, {vy:+.2f}, {omega:+.2f}]\n"
|
||||
f"Height: {height:.3f} m\n"
|
||||
f"Roll/Pitch: {roll_pitch[0]:+.1f}° / {roll_pitch[1]:+.1f}°"
|
||||
)
|
||||
lines = [
|
||||
"=== JACKBOT TELEMETRY ===",
|
||||
f"Mode: {mode.upper()}",
|
||||
f"Curriculum: {phase}",
|
||||
f"Status: {status}",
|
||||
f"Episode: {episode} (Step {ep_step})",
|
||||
f"Global Step: {step}",
|
||||
f"FPS: {fps:.1f}",
|
||||
"-------------------------",
|
||||
f"Episode Rew: {top1}",
|
||||
f"Cmd (X,Y,W): [{vx:+.2f}, {vy:+.2f}, {omega:+.2f}]",
|
||||
f"Height: {height:.3f} m",
|
||||
f"Roll/Pitch: {roll_pitch[0]:+.1f}° / {roll_pitch[1]:+.1f}°",
|
||||
f"Max Dist: {distance:.2f} m",
|
||||
]
|
||||
|
||||
if reward_components:
|
||||
lin_v = reward_components.get("lin_vel", 0.0)
|
||||
stab = reward_components.get("stability", 0.0)
|
||||
h_rew = reward_components.get("height", 0.0)
|
||||
jit = reward_components.get("jitter_penalty", 0.0)
|
||||
lines.append("--- Reward Components ---")
|
||||
lines.append(f"LinVel: {lin_v:.2f} | Stab: {stab:.2f}")
|
||||
lines.append(f"Height: {h_rew:.2f} | Jitter: {jit:+.3f}")
|
||||
|
||||
hud_text = "\n".join(lines)
|
||||
|
||||
# Position above origin in simulation world
|
||||
text_position = [-0.8, -0.8, 1.2]
|
||||
@@ -76,7 +94,7 @@ class MetricsHUD:
|
||||
# Calculate dynamic orientation to align text flat against camera plane
|
||||
text_orientation = self._get_camera_facing_orientation()
|
||||
|
||||
# Safely remove the old text to prevent PyBullet ghosting/overlapping
|
||||
# Safely remove old text to prevent PyBullet ghosting/overlapping
|
||||
if self._text_id is not None:
|
||||
try:
|
||||
p.removeUserDebugItem(self._text_id, physicsClientId=self.client_id)
|
||||
@@ -88,7 +106,7 @@ class MetricsHUD:
|
||||
text=hud_text,
|
||||
textPosition=text_position,
|
||||
textColorRGB=text_color,
|
||||
textSize=0.1,
|
||||
textSize=0.085,
|
||||
textOrientation=text_orientation,
|
||||
physicsClientId=self.client_id
|
||||
)
|
||||
|
||||
+2
-3
@@ -1,4 +1,3 @@
|
||||
from .env import JackBotEnv
|
||||
from .model import ActorCritic
|
||||
from .env import JackBotEnv, CurriculumPhase
|
||||
|
||||
__all__ = ["JackBotEnv", "ActorCritic"]
|
||||
__all__ = ["JackBotEnv", "CurriculumPhase"]
|
||||
|
||||
+5
-2
@@ -1,6 +1,9 @@
|
||||
"""
|
||||
ml/callbacks.py - Stable-Baselines3 Custom Callbacks for Logging & Curriculum Advancement
|
||||
Fully compatible with SubprocVecEnv and DummyVecEnv.
|
||||
ml/callbacks.py - Stable-Baselines3 callbacks for training diagnostics.
|
||||
|
||||
These callbacks extend SB3 training with two responsibilities: logging reward-component
|
||||
statistics for TensorBoard/console output, and checking whether the curriculum should
|
||||
advance to a harder set of commands based on recent training performance.
|
||||
"""
|
||||
|
||||
import numpy as np
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,5 +1,10 @@
|
||||
"""
|
||||
ml/env.py - Gymnasium Environment for JackBot Hexapod RL Training
|
||||
ml/env.py - Gymnasium environment for JackBot RL training and evaluation.
|
||||
|
||||
This file defines JackBotEnv, the main training/evaluation environment used by PPO.
|
||||
It wraps the PyBullet simulation and Robot interfaces into a Gymnasium-compatible
|
||||
step/reset loop, manages command sampling, curriculum progression, and reward
|
||||
calculation, and exposes metrics that the training callbacks can log.
|
||||
"""
|
||||
import time
|
||||
import math
|
||||
@@ -16,8 +21,6 @@ from simulation import Simulation
|
||||
from Robot import Robot, PyBulletBackend
|
||||
from ml.MetricsOverlay import MetricsHUD
|
||||
|
||||
COLOR_FAILED = [0.3, 0.3, 0.3, 0.6]
|
||||
|
||||
|
||||
class CurriculumPhase(IntEnum):
|
||||
STAND_ONLY = 0
|
||||
@@ -154,9 +157,6 @@ class JackBotEnv(gym.Env):
|
||||
# 2. Reset internal kinematics & hard reset joints in PyBullet
|
||||
self.robot.reset_to_init()
|
||||
|
||||
if self.use_gui:
|
||||
self.sim.set_robot_color([1.0, 1.0, 1.0, 1.0])
|
||||
|
||||
action_dim = self.action_space.shape[0]
|
||||
self.last_action = np.zeros(action_dim, dtype=np.float32)
|
||||
self.last_last_action = np.zeros(action_dim, dtype=np.float32)
|
||||
@@ -189,7 +189,19 @@ class JackBotEnv(gym.Env):
|
||||
return self._get_obs(), {}
|
||||
|
||||
def _get_obs(self) -> np.ndarray:
|
||||
return self.robot.get_observation(command=self.command)
|
||||
# Read raw joint angles from backend
|
||||
raw_angles = np.asarray(self.robot.backend.get_joint_angles(), dtype=np.float32).flatten()
|
||||
|
||||
min_lim = self.min_joint_limits.flatten()
|
||||
max_lim = self.max_joint_limits.flatten()
|
||||
|
||||
# Map raw joint radians [min, max] -> normalized [-1, 1]
|
||||
normalized_joints = 2.0 * (raw_angles - min_lim) / (max_lim - min_lim) - 1.0
|
||||
normalized_joints = np.clip(normalized_joints, -1.0, 1.0)
|
||||
|
||||
# Concatenate normalized joints with active command vector
|
||||
obs = np.concatenate([normalized_joints, self.command]).astype(np.float32)
|
||||
return obs
|
||||
|
||||
def step(self, action: np.ndarray) -> Tuple[np.ndarray, float, bool, bool, Dict[str, Any]]:
|
||||
previous_action = self.last_action.copy()
|
||||
@@ -199,26 +211,36 @@ class JackBotEnv(gym.Env):
|
||||
self.last_last_action = self.last_action.copy()
|
||||
self.last_action = action.copy()
|
||||
|
||||
# Command resampling
|
||||
if self.random_command and (self.step_count >= self.next_cmd_resample_step or self._curriculum_advanced):
|
||||
# Command resampling ONLY if random_command is True
|
||||
if self.random_command and (
|
||||
self.step_count >= self.next_cmd_resample_step or self._curriculum_advanced):
|
||||
self.command = self.sample_command()
|
||||
random_interval = np.random.randint(self.min_cmd_hold_steps, self.max_cmd_hold_steps + 1)
|
||||
self.next_cmd_resample_step = self.step_count + random_interval
|
||||
|
||||
# Extract [vx, vy, omega]
|
||||
# Extract active [vx, vy, omega]
|
||||
cmd_vx, cmd_vy, cmd_omega = self.command
|
||||
|
||||
# Mirror main.py input resolution logic: update robot_state and vector_dirmov directly
|
||||
# Mirror input resolution logic to keep robot state synchronized
|
||||
self.robot.robot_state = "walking" if (abs(cmd_vx) > 0.01 or abs(cmd_vy) > 0.01 or abs(cmd_omega) > 0.01) else "idle"
|
||||
self.robot.vector_dirmov = [float(cmd_vx), float(cmd_vy), float(cmd_omega)]
|
||||
|
||||
# Delegate execution tick to Robot instance
|
||||
target_angles = np.where(
|
||||
action < 0.0,
|
||||
self.default_joint_angles + action * (self.default_joint_angles - self.min_joint_limits),
|
||||
self.default_joint_angles + action * (self.max_joint_limits - self.default_joint_angles)
|
||||
)
|
||||
self.robot.tick(action=target_angles)
|
||||
|
||||
# Direct Mode: Target joint scaling
|
||||
action_flat = np.asarray(action, dtype=np.float32).flatten()
|
||||
action_clipped = np.clip(action_flat, -1.0, 1.0)
|
||||
|
||||
if self.robot_mode == "direct":
|
||||
# Map [-1, 1] linearly to physical joint limits [min, max]
|
||||
min_lim = self.min_joint_limits.flatten()
|
||||
max_lim = self.max_joint_limits.flatten()
|
||||
|
||||
target_angles = min_lim + (action_clipped + 1.0) * 0.5 * (max_lim - min_lim)
|
||||
else:
|
||||
# Residual mode mapping logic
|
||||
target_angles = self.default_joint_angles.flatten() + action_clipped * 0.20
|
||||
|
||||
# Apply target joint angles to physics engine
|
||||
self.robot.tick(action=target_angles, physics_substeps=4)
|
||||
|
||||
if self.robot_mode != "kinematics" and self.step_count % 60 == 0:
|
||||
random_force = np.random.uniform(-2.0, 2.0, size=2)
|
||||
@@ -228,8 +250,9 @@ class JackBotEnv(gym.Env):
|
||||
self._update_distance_metrics()
|
||||
self._update_curriculum()
|
||||
|
||||
# Build next observation preserving active command
|
||||
obs = self._get_obs()
|
||||
reward = self._compute_reward(action, previous_action)
|
||||
reward = self._compute_reward(action_flat, previous_action)
|
||||
|
||||
self.cumulative_reward += reward
|
||||
self.robot_reward += reward
|
||||
@@ -241,6 +264,9 @@ class JackBotEnv(gym.Env):
|
||||
if self.step_count % 120 == 0 and self.use_gui:
|
||||
self._update_hud()
|
||||
|
||||
if self.use_gui:
|
||||
time.sleep(1.0 / self.control_freq)
|
||||
|
||||
return obs, reward, terminated, truncated, info
|
||||
|
||||
def _update_distance_metrics(self):
|
||||
@@ -342,7 +368,10 @@ class JackBotEnv(gym.Env):
|
||||
target_speed = math.hypot(target_vx, target_vy)
|
||||
|
||||
if not is_moving:
|
||||
total_reward = 0.0
|
||||
# If the command says move but the robot stays effectively still,
|
||||
# give a real penalty instead of a neutral reward.
|
||||
stillness_penalty = -0.10
|
||||
total_reward = stillness_penalty
|
||||
else:
|
||||
lin_vel_error = (filtered_vx - target_vx)**2 + (filtered_vy - target_vy)**2
|
||||
r_lin_vel = math.exp(-25.0 * lin_vel_error)
|
||||
@@ -350,7 +379,7 @@ class JackBotEnv(gym.Env):
|
||||
|
||||
if target_speed > 0.08 and raw_speed < 0.03:
|
||||
r_lin_vel = 0.0
|
||||
stillness_penalty = -0.1 # Softened from -0.25
|
||||
stillness_penalty = -0.05
|
||||
|
||||
w_lin_vel, w_ang_vel, w_height, w_stability, w_smoothness = 0.55, 0.15, 0.10, 0.12, 0.08
|
||||
total_reward = (
|
||||
@@ -360,7 +389,7 @@ class JackBotEnv(gym.Env):
|
||||
|
||||
step_reward = float(total_reward / 10.0)
|
||||
alive_bonus = 0.01
|
||||
final_reward = max(0.0, step_reward + jitter_penalty + alive_bonus)
|
||||
final_reward = step_reward + jitter_penalty + alive_bonus
|
||||
|
||||
self.last_reward_components = {
|
||||
"height": float(r_height),
|
||||
@@ -371,6 +400,7 @@ class JackBotEnv(gym.Env):
|
||||
"ang_vel": float(r_ang_vel),
|
||||
"jitter_penalty": float(jitter_penalty),
|
||||
"stand_penalty": float(stand_penalty),
|
||||
"stillness_penalty": float(stillness_penalty),
|
||||
"total": final_reward,
|
||||
}
|
||||
for k, v in self.last_reward_components.items():
|
||||
@@ -421,8 +451,6 @@ class JackBotEnv(gym.Env):
|
||||
|
||||
if is_tilted or is_collapsed:
|
||||
self.is_failed = True
|
||||
if self.use_gui:
|
||||
self.sim.set_robot_color(COLOR_FAILED)
|
||||
|
||||
def close(self):
|
||||
self.sim.disconnect()
|
||||
Binary file not shown.
Binary file not shown.
-49
@@ -1,49 +0,0 @@
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.distributions import Normal
|
||||
|
||||
|
||||
class ActorCritic(nn.Module):
|
||||
def __init__(self, obs_dim: int, action_dim: int, hidden_sizes=(256, 256)):
|
||||
super().__init__()
|
||||
self.backbone = nn.Sequential(
|
||||
nn.Linear(obs_dim, hidden_sizes[0]),
|
||||
nn.ReLU(),
|
||||
nn.Linear(hidden_sizes[0], hidden_sizes[1]),
|
||||
nn.ReLU(),
|
||||
)
|
||||
|
||||
self.mean_head = nn.Linear(hidden_sizes[1], action_dim)
|
||||
self.value_head = nn.Linear(hidden_sizes[1], 1)
|
||||
self.log_std = nn.Parameter(torch.zeros(action_dim, dtype=torch.float32))
|
||||
|
||||
def forward(self, obs: torch.Tensor):
|
||||
x = self.backbone(obs)
|
||||
mean = self.mean_head(x)
|
||||
std = self.log_std.exp()
|
||||
value = self.value_head(x).squeeze(-1)
|
||||
return mean, std, value
|
||||
|
||||
def get_action(self, obs: torch.Tensor):
|
||||
mean, std, value = self.forward(obs)
|
||||
dist = Normal(mean, std)
|
||||
action = dist.sample()
|
||||
log_prob = dist.log_prob(action).sum(-1)
|
||||
return action, log_prob, value
|
||||
|
||||
def evaluate_actions(self, obs: torch.Tensor, actions: torch.Tensor):
|
||||
mean, std, value = self.forward(obs)
|
||||
dist = Normal(mean, std)
|
||||
log_prob = dist.log_prob(actions).sum(-1)
|
||||
entropy = dist.entropy().sum(-1)
|
||||
return value, log_prob, entropy
|
||||
|
||||
def save(self, path: str):
|
||||
torch.save(self.state_dict(), path)
|
||||
|
||||
@classmethod
|
||||
def load(cls, path: str, obs_dim: int, action_dim: int, hidden_sizes=(256, 256)):
|
||||
model = cls(obs_dim, action_dim, hidden_sizes)
|
||||
model.load_state_dict(torch.load(path, map_location=torch.device("cpu")))
|
||||
model.eval()
|
||||
return model
|
||||
@@ -0,0 +1,155 @@
|
||||
"""
|
||||
ml/pretrain_bc.py - Behavioral Cloning teacher-data pipeline.
|
||||
|
||||
This script collects observation/action pairs from the kinematics solver, then uses
|
||||
those pairs as training data for a PPO policy. In practice it serves as a teacher-
|
||||
student pretraining step: the kinematics controller generates sample trajectories, and
|
||||
this file teaches the policy to imitate those behavior patterns before PPO training.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils.data import DataLoader, TensorDataset
|
||||
from stable_baselines3 import PPO
|
||||
from tqdm import tqdm # <--- Progress Bar Support
|
||||
|
||||
# Ensure project root is in sys.path
|
||||
sys.path.append(str(Path(__file__).resolve().parent.parent))
|
||||
from ml.env import JackBotEnv, CurriculumPhase
|
||||
|
||||
|
||||
def collect_kinematics_dataset(num_samples: int = 100_000, use_gui: bool = False):
|
||||
"""Collects (Observation, Action) pairs directly from Kinematics Teacher."""
|
||||
print(f"\n[Pretrain] Collecting {num_samples} samples from Kinematics Teacher (GUI={use_gui})...")
|
||||
|
||||
# Disable random command resampling inside env.step so manual command locks persist
|
||||
env = JackBotEnv(use_gui=use_gui, robot_mode="kinematics", random_command=False)
|
||||
env.curriculum_phase = CurriculumPhase.FULL_COMMAND
|
||||
|
||||
observations = []
|
||||
actions = []
|
||||
|
||||
obs, _ = env.reset()
|
||||
|
||||
# --- PROGRESS BAR: Data Collection ---
|
||||
pbar = tqdm(range(num_samples), desc=" Collecting Data", unit="step")
|
||||
for i in pbar:
|
||||
# 1. Update command and vector targets every 120 steps
|
||||
if i % 120 == 0:
|
||||
env.command = env.sample_command()
|
||||
cmd_vx, cmd_vy, cmd_omega = env.command
|
||||
env.robot.robot_state = (
|
||||
"walking"
|
||||
if (abs(cmd_vx) > 0.01 or abs(cmd_vy) > 0.01 or abs(cmd_omega) > 0.01)
|
||||
else "idle"
|
||||
)
|
||||
env.robot.vector_dirmov = [float(cmd_vx), float(cmd_vy), float(cmd_omega)]
|
||||
|
||||
# 2. Capture observation BEFORE stepping environment
|
||||
current_obs = env._get_obs()
|
||||
|
||||
# 3. Step environment ONCE (updates kinematics solver, PyBullet physics, and computes IK)
|
||||
obs, _, terminated, truncated, _ = env.step(np.zeros(18, dtype=np.float32))
|
||||
|
||||
# 4. Extract procedural IK joint targets computed during this step
|
||||
target_ik_rad = env.robot.current_rad.data.flatten().copy()
|
||||
|
||||
# Step 5: Convert target radians directly to [-1, 1] relative to joint limits
|
||||
min_lim = env.min_joint_limits.flatten()
|
||||
max_lim = env.max_joint_limits.flatten()
|
||||
|
||||
normalized_action = 2.0 * (target_ik_rad - min_lim) / (max_lim - min_lim) - 1.0
|
||||
normalized_action = np.clip(normalized_action, -1.0, 1.0)
|
||||
|
||||
# Step 6: Store matching input (obs) and target ground truth (normalized_action)
|
||||
observations.append(current_obs.copy())
|
||||
actions.append(normalized_action.copy())
|
||||
|
||||
if use_gui:
|
||||
time.sleep(1.0 / 60.0)
|
||||
|
||||
# 7. Handle episode boundaries using terminated and truncated
|
||||
if terminated or truncated:
|
||||
obs, _ = env.reset()
|
||||
|
||||
env.close()
|
||||
print("[Pretrain] Data collection complete!\n")
|
||||
return np.array(observations, dtype=np.float32), np.array(actions, dtype=np.float32)
|
||||
|
||||
|
||||
def pretrain_policy(
|
||||
save_path: str = "ml/checkpoints/jackbot_kinematics_base.zip",
|
||||
epochs: int = 15,
|
||||
batch_size: int = 256,
|
||||
num_samples: int = 100_000,
|
||||
use_gui: bool = False
|
||||
):
|
||||
# Collect dataset from Kinematics teacher
|
||||
obs_data, action_data = collect_kinematics_dataset(num_samples=num_samples, use_gui=use_gui)
|
||||
|
||||
# Initialize Dummy Env & Fresh SB3 PPO Model
|
||||
dummy_env = JackBotEnv(use_gui=False, robot_mode="direct")
|
||||
model = PPO("MlpPolicy", dummy_env, learning_rate=5e-4, verbose=0, device="cpu")
|
||||
|
||||
# Extract PyTorch Policy Network & Optimizer
|
||||
policy = model.policy
|
||||
optimizer = torch.optim.Adam(policy.parameters(), lr=5e-4)
|
||||
loss_fn = nn.MSELoss()
|
||||
|
||||
# Convert to PyTorch Dataloader
|
||||
dataset = TensorDataset(torch.tensor(obs_data), torch.tensor(action_data))
|
||||
loader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
|
||||
|
||||
print(f"[Pretrain] Pre-training Policy Network ({epochs} Epochs)...")
|
||||
policy.train()
|
||||
|
||||
# --- PROGRESS BAR: Epoch Training ---
|
||||
for epoch in range(epochs):
|
||||
epoch_loss = 0.0
|
||||
|
||||
batch_pbar = tqdm(loader, desc=f" Epoch {epoch + 1:02d}/{epochs:02d}", leave=True, unit="batch")
|
||||
for batch_obs, batch_actions in batch_pbar:
|
||||
optimizer.zero_grad()
|
||||
|
||||
distribution = policy.get_distribution(batch_obs)
|
||||
predicted_actions = distribution.distribution.mean
|
||||
|
||||
loss = loss_fn(predicted_actions, batch_actions)
|
||||
loss.backward()
|
||||
optimizer.step()
|
||||
|
||||
current_loss = loss.item()
|
||||
epoch_loss += current_loss * len(batch_obs)
|
||||
|
||||
# Dynamic loss update in progress bar tail
|
||||
batch_pbar.set_postfix({"loss": f"{current_loss:.6f}"})
|
||||
|
||||
avg_loss = epoch_loss / len(dataset)
|
||||
tqdm.write(f" └─ Epoch {epoch + 1:02d}/{epochs:02d} Complete | Mean MSE Loss: {avg_loss:.6f}")
|
||||
|
||||
# Save SB3 Model Checkpoint
|
||||
out_file = Path(save_path)
|
||||
out_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
model.save(out_file)
|
||||
dummy_env.close()
|
||||
print(f"\n[Pretrain] Successfully saved pre-trained base model to: {out_file.resolve()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description="JackBot Behavioral Cloning Pre-trainer")
|
||||
parser.add_argument("--gui", action="store_true", help="Enable PyBullet 3D visual GUI rendering during collection")
|
||||
parser.add_argument("--num-samples", type=int, default=100_000, help="Number of dataset samples to collect")
|
||||
parser.add_argument("--epochs", type=int, default=15, help="Number of BC training epochs")
|
||||
parser.add_argument("--save-path", type=str, default="ml/checkpoints/jackbot_kinematics_base.zip", help="Output path for pre-trained model .zip")
|
||||
args = parser.parse_args()
|
||||
|
||||
pretrain_policy(
|
||||
save_path=args.save_path,
|
||||
epochs=args.epochs,
|
||||
num_samples=args.num_samples,
|
||||
use_gui=args.gui
|
||||
)
|
||||
+107
-67
@@ -1,7 +1,10 @@
|
||||
"""Run a trained policy in the PyBullet sim with full curriculum progression.
|
||||
"""
|
||||
ml/run_eval.py - Evaluate a saved JackBot policy across fixed command phases.
|
||||
|
||||
Usage:
|
||||
python ml/run_eval.py --model ml/checkpoints/ppo_joint_command.zip --episodes 5 --gui
|
||||
This script loads a trained PPO checkpoint, instantiates the Gymnasium environment in
|
||||
non-random mode, and runs deterministic evaluation episodes for several command
|
||||
regimes. It is used to measure whether a policy can survive, move, and maintain
|
||||
stability under forward, turning, lateral, and omni-direction commands.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
@@ -11,102 +14,139 @@ import sys
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
from stable_baselines3 import PPO
|
||||
|
||||
# Ensure project root is in sys.path
|
||||
sys.path.append(str(Path(__file__).resolve().parent.parent))
|
||||
from ml.env import JackBotEnv
|
||||
from ml.env import JackBotEnv, CurriculumPhase
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="JackBot Policy Evaluator")
|
||||
parser = argparse.ArgumentParser(description="JackBot Phase-by-Phase Policy Evaluator")
|
||||
parser.add_argument("--model", type=str, required=True, help="Path to trained model checkpoint (.zip)")
|
||||
parser.add_argument("--episodes", type=int, default=5, help="Number of evaluation episodes to run")
|
||||
parser.add_argument("--episodes-per-phase", type=int, default=1, help="Number of test episodes per phase")
|
||||
parser.add_argument("--max-steps-per-episode", type=int, default=600, help="Max simulation steps per episode")
|
||||
parser.add_argument("--gui", action="store_true", help="Enable PyBullet 3D visual GUI rendering")
|
||||
parser.add_argument("--no-random-command", dest="random_command", action="store_false", help="Lock commands to zero (disable random command sampling)")
|
||||
parser.set_defaults(random_command=True)
|
||||
parser.add_argument("--save-metrics", type=str, default=None, help="Optional JSON path to output evaluation summary")
|
||||
parser.add_argument("--save-metrics", type=str, default=None, help="Optional JSON path to save evaluation summary")
|
||||
args = parser.parse_args()
|
||||
|
||||
print(f"[Eval] Loading policy model from: {args.model}")
|
||||
model = PPO.load(args.model, device="cpu")
|
||||
|
||||
# Instantiate single evaluation environment matching train setup
|
||||
# Instantiate environment with random_command disabled so our test command stays locked
|
||||
env = JackBotEnv(
|
||||
use_gui=args.gui,
|
||||
random_command=args.random_command,
|
||||
random_command=False,
|
||||
max_episode_steps=args.max_steps_per_episode,
|
||||
robot_mode="direct"
|
||||
)
|
||||
|
||||
episode_rewards = []
|
||||
episode_lengths = []
|
||||
episode_phases = []
|
||||
# Multi-Phase Configurations Suite
|
||||
phase_configs = [
|
||||
#(CurriculumPhase.STAND_ONLY, "STAND", np.array([0.0, 0.0, 0.0], dtype=np.float32)),
|
||||
(CurriculumPhase.FORWARD, "FORWARD GAIT", np.array([1.0, 0.0, 0.0], dtype=np.float32)),
|
||||
(CurriculumPhase.TURN_AND_DIRECTION, "FORWARD + YAW TURN", np.array([0.5, 0.0, 0.4], dtype=np.float32)),
|
||||
(CurriculumPhase.OMNI_DIRECTION, "STRIDE LATERAL", np.array([0.5, 0.5, 0.0], dtype=np.float32)),
|
||||
(CurriculumPhase.FULL_COMMAND, "FULL OMNI COMBINATION", np.array([0.3, 0.2, 0.3], dtype=np.float32)),
|
||||
]
|
||||
|
||||
phase_summary = []
|
||||
|
||||
try:
|
||||
for ep in range(args.episodes):
|
||||
obs, _ = env.reset()
|
||||
done = False
|
||||
total_reward = 0.0
|
||||
steps = 0
|
||||
initial_phase = env.curriculum_phase.name
|
||||
print("\n" + "=" * 75)
|
||||
print(" STARTING MULTI-PHASE EVALUATION SUITE")
|
||||
print("=" * 75)
|
||||
|
||||
print(f"\n--- Starting Evaluation Episode {ep + 1}/{args.episodes} [Phase: {initial_phase}] ---")
|
||||
for phase_enum, phase_name, test_cmd in phase_configs:
|
||||
print(f"\n▶ Testing Phase [{phase_enum.value}]: {phase_enum.name} ({phase_name})")
|
||||
print(f" Target Command Vector [vx, vy, omega]: {test_cmd.tolist()}")
|
||||
|
||||
while not done:
|
||||
# Deterministic prediction matches evaluation standards
|
||||
action, _ = model.predict(obs, deterministic=True)
|
||||
|
||||
prev_phase = env.curriculum_phase
|
||||
obs, reward, terminated, truncated, _ = env.step(action)
|
||||
done = terminated or truncated
|
||||
ep_rewards = []
|
||||
ep_steps = []
|
||||
ep_distances = []
|
||||
|
||||
total_reward += float(reward)
|
||||
steps += 1
|
||||
for ep in range(args.episodes_per_phase):
|
||||
obs, _ = env.reset()
|
||||
|
||||
if env.curriculum_phase != prev_phase:
|
||||
print(f" └─ [Eval Milestone] Reached {env.curriculum_phase.name} at step {steps}!")
|
||||
# Force environment into active curriculum phase and lock command BEFORE getting obs
|
||||
env.curriculum_phase = phase_enum
|
||||
env.command = test_cmd.copy()
|
||||
cmd_vx, cmd_vy, cmd_omega = test_cmd
|
||||
env.robot.robot_state = (
|
||||
"walking"
|
||||
if (abs(cmd_vx) > 0.01 or abs(cmd_vy) > 0.01 or abs(cmd_omega) > 0.01)
|
||||
else "idle"
|
||||
)
|
||||
env.robot.vector_dirmov = [float(cmd_vx), float(cmd_vy), float(cmd_omega)]
|
||||
|
||||
if args.gui:
|
||||
time.sleep(1.0 / 240.0)
|
||||
# Get correct observation with test_cmd attached
|
||||
obs = env._get_obs()
|
||||
|
||||
status_str = "FAILED (Terminated)" if terminated else "COMPLETED (Truncated)"
|
||||
final_phase = env.curriculum_phase.name
|
||||
|
||||
episode_rewards.append(total_reward)
|
||||
episode_lengths.append(steps)
|
||||
episode_phases.append(final_phase)
|
||||
done = False
|
||||
total_reward = 0.0
|
||||
steps = 0
|
||||
|
||||
print(
|
||||
f"Episode {ep + 1} Finished [{status_str}]: "
|
||||
f"Phase = {final_phase} | Total Reward = {total_reward:.2f} | Steps = {steps}"
|
||||
)
|
||||
while not done:
|
||||
# Predict deterministic action from policy
|
||||
action, _ = model.predict(obs, deterministic=True)
|
||||
|
||||
# Step environment
|
||||
obs, reward, terminated, truncated, _ = env.step(action)
|
||||
done = terminated or truncated
|
||||
|
||||
total_reward += float(reward)
|
||||
steps += 1
|
||||
|
||||
if args.gui:
|
||||
time.sleep(1.0 / 60.0)
|
||||
|
||||
status_str = "FAILED (Collapsed)" if terminated else "SUCCESS (Completed)"
|
||||
dist = float(env.max_distance_from_start)
|
||||
print(
|
||||
f" └─ Ep {ep + 1}/{args.episodes_per_phase}: {status_str:<19} | "
|
||||
f"Steps: {steps:<4} | Reward: {total_reward:+.2f} | Max Dist: {dist:.2f}m"
|
||||
)
|
||||
|
||||
ep_rewards.append(total_reward)
|
||||
ep_steps.append(steps)
|
||||
ep_distances.append(dist)
|
||||
|
||||
phase_summary.append({
|
||||
"phase_id": phase_enum.value,
|
||||
"phase_name": phase_enum.name,
|
||||
"label": phase_name,
|
||||
"command": test_cmd.tolist(),
|
||||
"mean_reward": float(np.mean(ep_rewards)),
|
||||
"mean_steps": float(np.mean(ep_steps)),
|
||||
"mean_distance": float(np.mean(ep_distances)),
|
||||
})
|
||||
|
||||
finally:
|
||||
env.close()
|
||||
|
||||
# Calculate metrics report
|
||||
mean_reward = float(np.mean(episode_rewards))
|
||||
std_reward = float(np.std(episode_rewards))
|
||||
mean_length = float(np.mean(episode_lengths))
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print(f"EVALUATION COMPLETE ({args.episodes} Episodes)")
|
||||
print(f"Final Reached Phase: {env.curriculum_phase.name}")
|
||||
print(f"Mean Reward: {mean_reward:.2f} ± {std_reward:.2f}")
|
||||
print(f"Mean Episode Length: {mean_length:.1f} steps")
|
||||
print("=" * 60)
|
||||
# Print Summary Table
|
||||
print("\n" + "=" * 80)
|
||||
print(" EVALUATION SUMMARY REPORT")
|
||||
print("=" * 80)
|
||||
print(f"{'Phase ID & Name':<25} | {'Label':<22} | {'Reward':<8} | {'Steps':<6} | {'Max Dist':<8}")
|
||||
print("-" * 80)
|
||||
for res in phase_summary:
|
||||
phase_str = f"[{res['phase_id']}] {res['phase_name']}"
|
||||
print(
|
||||
f"{phase_str:<25} | "
|
||||
f"{res['label']:<22} | "
|
||||
f"{res['mean_reward']:<+8.2f} | "
|
||||
f"{res['mean_steps']:<6.0f} | "
|
||||
f"{res['mean_distance']:<8.2f}m"
|
||||
)
|
||||
print("=" * 80)
|
||||
|
||||
# Save JSON Report if requested
|
||||
if args.save_metrics:
|
||||
metrics = {
|
||||
"model_path": str(args.model),
|
||||
"episodes_evaluated": args.episodes,
|
||||
"final_curriculum_phase": env.curriculum_phase.name,
|
||||
"mean_reward": mean_reward,
|
||||
"std_reward": std_reward,
|
||||
"mean_episode_length": mean_length,
|
||||
"raw_rewards": episode_rewards,
|
||||
"episode_phases": episode_phases,
|
||||
}
|
||||
out_path = Path(args.save_metrics)
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(out_path, "w") as f:
|
||||
json.dump(metrics, f, indent=4)
|
||||
print(f"[Eval] Saved evaluation report to: {out_path.resolve()}")
|
||||
json.dump({"model_path": str(args.model), "summary": phase_summary}, f, indent=4)
|
||||
print(f"\n[Eval] Saved report to: {out_path.resolve()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
"""
|
||||
ml/run_eval_training.py - Benchmark reward system across all curriculum phases.
|
||||
ml/run_eval_training.py - Run a kinematics-mode reward benchmark.
|
||||
|
||||
This script repeatedly resets the JackBot environment in kinematics mode and applies
|
||||
fixed command vectors for each curriculum phase. It is intended as a lightweight
|
||||
benchmark to inspect reward components, movement quality, and survival behavior without
|
||||
requiring an already-trained PPO model.
|
||||
"""
|
||||
import time
|
||||
import numpy as np
|
||||
from ml.env import JackBotEnv, CurriculumPhase
|
||||
import sys
|
||||
from pathlib import Path
|
||||
sys.path.append(str(Path(__file__).resolve().parent.parent))
|
||||
from ml.env import JackBotEnv, CurriculumPhase
|
||||
|
||||
def evaluate_kinematics(episode_length: int = 1000):
|
||||
env = JackBotEnv(
|
||||
@@ -21,6 +26,7 @@ def evaluate_kinematics(episode_length: int = 1000):
|
||||
print("=" * 70 + "\n")
|
||||
|
||||
phase_configs = [
|
||||
(CurriculumPhase.STAND_ONLY, "STAND", np.array([1.0, 0.0, 0.0], dtype=np.float32)),
|
||||
(CurriculumPhase.FORWARD, "FORWARD GAIT", np.array([1.0, 0.0, 0.0], dtype=np.float32)),
|
||||
(CurriculumPhase.TURN_AND_DIRECTION, "FORWARD + YAW TURN", np.array([0.5, 0.0, 0.4], dtype=np.float32)),
|
||||
(CurriculumPhase.OMNI_DIRECTION, "STRIDE LATERAL", np.array([0.5, 0.5, 0.0], dtype=np.float32)),
|
||||
|
||||
+49
-22
@@ -1,4 +1,9 @@
|
||||
"""Minimal training launcher for quick experiments.
|
||||
"""PPO training launcher for JackBot.
|
||||
|
||||
This script is the main entry point for training a policy in the JackBot Gymnasium
|
||||
environment. It creates a vectorized environment, optionally loads a pretrained base
|
||||
model, runs Stable-Baselines3 PPO for a configured number of timesteps, and saves
|
||||
checkpoints plus evaluation artifacts during training.
|
||||
|
||||
Usage:
|
||||
python ml/run_train.py --total-timesteps 1500000 --gui
|
||||
@@ -57,6 +62,12 @@ def main():
|
||||
parser.add_argument("--save-dir", type=str, default="ml/checkpoints", help="Directory for model checkpoints")
|
||||
parser.add_argument("--save-freq", type=int, default=50_000, help="Checkpoint save frequency (steps)")
|
||||
parser.add_argument("--gui", action="store_true", help="Enable PyBullet 3D visual GUI rendering")
|
||||
parser.add_argument(
|
||||
"--pretrained-model",
|
||||
type=str,
|
||||
default=None,
|
||||
help="Path to pre-trained base model checkpoint (.zip) to start PPO training from"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
os.makedirs(args.log_dir, exist_ok=True)
|
||||
@@ -74,26 +85,42 @@ def main():
|
||||
]
|
||||
vec_env = SubprocVecEnv(env_fns)
|
||||
|
||||
# Initialize PPO Policy Hyperparameters
|
||||
model = PPO(
|
||||
policy="MlpPolicy",
|
||||
env=vec_env,
|
||||
learning_rate=1e-4,
|
||||
n_steps=256,
|
||||
batch_size=256,
|
||||
n_epochs=10,
|
||||
gamma=0.99,
|
||||
gae_lambda=0.95,
|
||||
clip_range=0.2,
|
||||
ent_coef=0.03,
|
||||
target_kl=0.05,
|
||||
vf_coef=0.5,
|
||||
max_grad_norm=0.5,
|
||||
verbose=1,
|
||||
tensorboard_log=args.log_dir,
|
||||
device="cpu",
|
||||
)
|
||||
|
||||
# Initialize or Load PPO Policy Model
|
||||
if args.pretrained_model and os.path.exists(args.pretrained_model):
|
||||
print(f"[Train] Loading pre-trained base knowledge from: {args.pretrained_model}")
|
||||
model = PPO.load(
|
||||
args.pretrained_model,
|
||||
env=vec_env,
|
||||
learning_rate=5e-5, # Lower learning rate so RL fine-tunes without destroying base gait
|
||||
ent_coef=0.0,
|
||||
target_kl=0.05,
|
||||
vf_coef=0.5,
|
||||
max_grad_norm=0.5,
|
||||
verbose=2,
|
||||
tensorboard_log=args.log_dir,
|
||||
device="cpu",
|
||||
)
|
||||
else:
|
||||
print("[Train] No base model provided. Starting training from scratch...")
|
||||
model = PPO(
|
||||
policy="MlpPolicy",
|
||||
env=vec_env,
|
||||
learning_rate=5e-5,
|
||||
n_steps=256,
|
||||
batch_size=256,
|
||||
n_epochs=10,
|
||||
gamma=0.99,
|
||||
gae_lambda=0.95,
|
||||
clip_range=0.2,
|
||||
ent_coef=0.0,
|
||||
target_kl=0.05,
|
||||
vf_coef=0.5,
|
||||
max_grad_norm=0.5,
|
||||
verbose=2,
|
||||
tensorboard_log=args.log_dir,
|
||||
device="cpu",
|
||||
)
|
||||
model.policy.log_std.data.fill_(-2.0)
|
||||
# Setup Callbacks with ppo<number> naming
|
||||
checkpoint_callback = CheckpointCallback(
|
||||
save_freq=max(1, args.save_freq // args.num_workers),
|
||||
@@ -110,7 +137,7 @@ def main():
|
||||
eval_env,
|
||||
best_model_save_path=best_model_path,
|
||||
log_path="ml/logs/results",
|
||||
eval_freq=max(1, 20_000 // args.num_workers),
|
||||
eval_freq=max(1, 50_000 // args.num_workers),
|
||||
deterministic=True,
|
||||
render=False,
|
||||
)
|
||||
|
||||
@@ -4,6 +4,7 @@ ikpy
|
||||
pybullet
|
||||
pyserial
|
||||
matplotlib
|
||||
dearpygui
|
||||
|
||||
# Deep learning / RL
|
||||
torch
|
||||
|
||||
+1
-7
@@ -85,7 +85,7 @@ class Simulation:
|
||||
force=30,
|
||||
physicsClientId=self.physics_client
|
||||
)
|
||||
|
||||
|
||||
def hard_reset_joint_angles(self, target_angles: Union[np.ndarray, dt.RadArray]) -> None:
|
||||
"""Instantly teleports joint angles to target positions, clearing velocity state."""
|
||||
radflat = target_angles.data.flatten() if isinstance(target_angles, dt.RadArray) else target_angles.flatten()
|
||||
@@ -164,12 +164,6 @@ class Simulation:
|
||||
"""Advances physics simulation by 1 time step."""
|
||||
p.stepSimulation(physicsClientId=self.physics_client)
|
||||
|
||||
def set_robot_color(self, rgba: List[float]) -> None:
|
||||
num_joints = p.getNumJoints(self.robot_id, physicsClientId=self.physics_client)
|
||||
p.changeVisualShape(self.robot_id, -1, rgbaColor=rgba, physicsClientId=self.physics_client)
|
||||
for j in range(num_joints):
|
||||
p.changeVisualShape(self.robot_id, j, rgbaColor=rgba, physicsClientId=self.physics_client)
|
||||
|
||||
def settle_and_measure_height(
|
||||
self, target_angles: Optional[np.ndarray] = None, steps: int = 100, fallback_height: float = 0.122
|
||||
) -> float:
|
||||
|
||||
Reference in New Issue
Block a user