From 789331ebd1c48f103db8b14fa79da1aafb5ad860 Mon Sep 17 00:00:00 2001 From: JackM323 Date: Thu, 5 Nov 2026 10:22:12 +0100 Subject: [PATCH] Readme seperated into Sub-Readme's --- BoardCode/README.md | 66 +++++++++++++ README.md | 232 +++----------------------------------------- ml/README.md | 105 ++++++++++++++++++++ 3 files changed, 187 insertions(+), 216 deletions(-) create mode 100644 BoardCode/README.md create mode 100644 ml/README.md diff --git a/BoardCode/README.md b/BoardCode/README.md new file mode 100644 index 0000000..1fafa3a --- /dev/null +++ b/BoardCode/README.md @@ -0,0 +1,66 @@ +# JackBot Board Firmware + +`BoardCode/` contains the firmware sketches for running JackBot on microcontroller +boards. The Python simulator, manual-control application, and host-side communication +configuration are documented in the [main README](../README.md). + +## Sketches + +| Sketch | Purpose | +| --- | --- | +| [`JackBotEsp32/JackBotEsp32.ino`](JackBotEsp32/JackBotEsp32.ino) | ESP32 firmware using the shared JackBot library and UDP networking. | +| [`JackBotEsp32C3/JackBotEsp32C3.ino`](JackBotEsp32C3/JackBotEsp32C3.ino) | ESP32-C3 variant of the networked firmware. It initializes I2C on GPIO 6 and 7. | +| [`JackBotArd/JackBotArd.ino`](JackBotArd/JackBotArd.ino) | Separate Arduino sketch using Bluetooth serial and PCA9685 servo boards. | + +The ESP32 sketches use [`libaries/JackBot/`](libaries/JackBot/) (the directory name is +spelled `libaries` in this repository). That library contains: + +* `BotNetwork` for Wi-Fi/UDP packet handling; +* `MotionController` for PCA9685 servo output and motion interpolation; +* `DisplayManager` for the ST7789 display; and +* `Protocol.h` for packet type and header definitions. + +The `JackBotArd` sketch is a separate, older implementation; it does not use this +shared ESP32 library. + +## Build and upload + +1. Install the Arduino IDE or Arduino CLI and the Espressif ESP32 board support + package. +2. Install the libraries required by the selected sketch. The ESP32 sketches use + Adafruit PWM Servo Driver, Adafruit GFX, and Adafruit ST7735 and ST7789. The + classic `JackBotArd` sketch uses Adafruit PWM Servo Driver and additionally + includes `JackBotEmotes.h`; that dependency is not present in the shared + `libaries/JackBot` library. +3. Add `libaries/JackBot` as a local Arduino library (or copy it into your Arduino + libraries directory) before building either ESP32 sketch. +4. Open the desired `.ino` file, select the matching ESP32 board and serial port, + then build and upload it. + +Check the pin assignments in the selected sketch and the board's wiring before +powering servos or displays. The ESP32-C3 sketch explicitly sets I2C to GPIO 6/7; +the classic ESP32 sketch uses the board's default `Wire` pins. Display pins are +specified when `DisplayManager` is constructed in each sketch. + +## Network connection + +The ESP32 sketches listen for UDP packets on port `3323` through `BotNetwork`. The +network library is configured in the sketch constructor with Wi-Fi and fallback +access-point settings. Set these to the values for your installation before upload; +do not commit real network passwords to source control. + +For host-side use, set `cfg.backend` to `BackendType.ESP32` and configure the ESP32 +address and port in the root project's `config.py`. The host communication layer +and heartbeat behavior are described in the [main README](../README.md). + +## Protocol and runtime notes + +`Protocol.h` defines versioned packet types for motion commands, configuration, +display messages, and ping/pong packets. `BotNetwork` parses received packets and +passes motion/configuration/display updates to the sketch. The ESP32 sketches use +FreeRTOS tasks and queues so servo updates and display updates run separately from +packet reception. + +The classic Arduino sketch instead reads framed Bluetooth serial input and drives +two PCA9685 boards. It has a different transport and firmware path from the ESP32 +UDP implementation. diff --git a/README.md b/README.md index 167e3da..494cb03 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,8 @@ In the current codebase, the practical workflow is: * **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. +* **ML Subsystem (`ml/`)**: Gymnasium/PyBullet environment and learning workflows; see the [ML README](ml/README.md). +* **Board firmware (`BoardCode/`)**: Arduino and ESP32 sketches with a shared ESP32 library; see the [BoardCode README](BoardCode/README.md). * **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()`. --- @@ -77,16 +78,13 @@ JackBot/ │ ├── gui/ # GUI/dashboard control layer │ └── MainWindow.py +├── BoardCode/ # Arduino and ESP32 firmware +│ ├── JackBotArd/ +│ ├── JackBotEsp32/ +│ ├── JackBotEsp32C3/ +│ └── libaries/JackBot/ # Shared ESP32 Arduino library │ -├── 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/ # RL environment and workflows; see ml/README.md │ ├── EspCommunication.py # ESP32 UDP communication layer ├── ArduinoCommunication.py # Arduino serial communication layer @@ -180,6 +178,11 @@ Supported configuration values in the current code include: * `tick_rate_hz`, `step_duration` * `step_height`, `step_length` +In ESP32 mode, the GUI uses UDP heartbeat replies to show the robot connection +state. If the connection is lost, it retries for up to 30 seconds and then +shows **Robot Disconnected**; press **STOP ROBOT** to end the active session. +The ESP32 must run firmware containing the heartbeat reply support. + ### GUI input sources The current GUI (`gui/MainWindow.py`) exposes these input sources: @@ -194,212 +197,9 @@ The active `main.py` runtime resolves commands through `resolve_active_command(. ## Machine Learning Pipeline (`ml/`) -The ML subsystem currently uses: - -* **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 - -### Current ML scripts - -* `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 - -### Training flow - -Training is launched with: - -```bash -python ml/run_train.py --total-timesteps 1500000 --gui -``` - -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 is launched with: - -```bash -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 in `ml/env.py` is designed to teach several things at once: - -* 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 environment uses several reward components, including: - -* 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. - -### Detailed reward structure - -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. - -At each control step, the environment measures: - -* 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. - -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. +The ML project has its own guide covering environment behavior, reward and curriculum +design, setup, training, pretraining, evaluation, and generated outputs: +[ml/README.md](ml/README.md). --- diff --git a/ml/README.md b/ml/README.md new file mode 100644 index 0000000..70af64c --- /dev/null +++ b/ml/README.md @@ -0,0 +1,105 @@ +# JackBot Machine Learning + +This folder contains the Gymnasium/PyBullet environment and the scripts for +behavioral-cloning pretraining, PPO training, and policy evaluation. For the +robot's manual-control application, simulator setup, and project overview, see the +[main README](../README.md). + +## Setup + +Install the project's Python dependencies from the repository root, following the +[main setup instructions](../README.md#installation--setup): + +```bash +python -m pip install -r requirements.txt +``` + +Run the commands below from the repository root. The environment loads the robot +model and runs a PyBullet simulation; `--gui` opens the PyBullet window where that +option is available. + +## Workflows + +### Behavioral-cloning pretraining + +`pretrain_bc.py` collects observation/action examples from the kinematics controller +and trains an initial PPO policy to imitate those actions: + +```bash +python ml/pretrain_bc.py --num-samples 100000 --epochs 15 \ + --save-path ml/checkpoints/jackbot_kinematics_base.zip +``` + +Use `--gui` to visualize data collection. Defaults are 100,000 samples, 15 epochs, +and the checkpoint path shown above. + +### PPO training + +`run_train.py` trains a PPO policy in parallel environments and saves checkpoints: + +```bash +python ml/run_train.py --total-timesteps 1500000 +``` + +Useful options include `--num-workers`, `--save-freq`, `--log-dir`, `--save-dir`, +`--pretrained-model`, and `--gui`. By default, the script uses 16 workers, saves +checkpoints under `ml/checkpoints/`, and writes TensorBoard logs under `ml/logs/`. +To continue from a pretraining or previous checkpoint, pass its `.zip` path with +`--pretrained-model`. + +### Policy evaluation + +`run_eval.py` runs deterministic episodes for fixed movement commands and reports +mean reward, steps survived, and maximum distance for each phase: + +```bash +python ml/run_eval.py \ + --model ml/checkpoints/jackbot_kinematics_base.zip \ + --episodes-per-phase 5 +``` + +The model path is required. Other options include `--max-steps-per-episode`, +`--gui`, and `--save-metrics path/to/report.json`. + +### Kinematics benchmark + +`run_eval_training.py` benchmarks the kinematics controller against fixed commands +and prints reward-component averages and movement metrics. It currently has no +command-line options and enables the PyBullet GUI: + +```bash +python ml/run_eval_training.py +``` + +## Environment and training concepts + +[`env.py`](env.py) defines `JackBotEnv`. Each observation contains 18 joint angles +and a three-value movement command `[vx, vy, omega]`; the policy outputs 18 +normalized joint actions. The environment can use direct policy actions or the +kinematics controller, and provides reward and robot metrics to the training and +evaluation scripts. + +The reward is shaped to encourage survival, body height and stability, following +the requested linear and angular motion, smooth actions, and a stable stance when +the command is zero. It also discourages unintended movement while standing and +remaining still when movement is requested. Negative reward contributions are +not the same as episode termination: an episode ends on a failure condition (such +as excessive tilt or a collapsed body) or when the configured step limit is +reached. + +The curriculum in `env.py` progresses through these command stages: + +1. `STAND_ONLY` +2. `FORWARD` +3. `TURN_AND_DIRECTION` +4. `OMNI_DIRECTION` +5. `FULL_COMMAND` + +`callbacks.py` contains reward logging and curriculum callbacks. `MetricsOverlay.py` +displays simulation metrics when the GUI is in use. + +## Outputs + +Training checkpoints are written to `ml/checkpoints/` and TensorBoard logs and +evaluation results to `ml/logs/` by default. These directories can also contain +large generated artifacts; keep or remove them according to your experiment needs.