Files
TIR_PROJ/tools/run_webots.sh
T
Johnny Fernandes d00da52c3c Portable Python env + 360° LiDAR ablation flag
Two small features.

(1) Portable interpreter
* `tools/setup_env.sh` exports HERDING_PYTHON (default points to the
  project's conda env; override in your shell to retarget).
* Both `controllers/*/runtime.ini` files now use Webots' env-var
  expansion: `COMMAND = $(HERDING_PYTHON)` so the Webots-launched
  controllers pick up the same interpreter as the bash scripts.
* `tools/run_webots.sh`, `tools/webots_sweep{,_gt}.sh` and
  `tools/calibrate_mecanum.sh` all source `setup_env.sh` at the top
  instead of hard-coding `/home/jalf/miniconda3/envs/tir/bin`.
The hard-coded conda path is now exactly one line in `setup_env.sh`'s
fallback default — a single place to edit on a new machine, or
override-once via `export HERDING_PYTHON=...`.

(2) 360° LiDAR FOV ablation
* New `LIDAR_WEBOTS_360` preset matches the existing
  `protos/ShepherdDog360.proto` (360 rays / 2π FOV / 15 m range).
* `tools/run_webots.sh` reads `HERDING_LIDAR=140|360` and swaps the
  diff-drive proto accordingly (mecanum keeps 140° — the
  ShepherdDogMecanum proto has its own LiDAR section). The variant
  is written into `herding_runtime.cfg` so the controller can read
  it even when Webots strips env vars.
* `controllers/shepherd_dog/shepherd_dog.py` picks the matching
  `lidar_cfg` (`HERDING_WEBOTS.lidar` for 140°, `LIDAR_WEBOTS_360`
  otherwise) and feeds it to `detections_from_scan` so the
  perception pipeline interprets ray angles + max range correctly.

Smoke test: `HERDING_LIDAR=360 tools/run_webots.sh 5 strombom
differential field` launches with `ShepherdDog360.proto`, the
controller logs the new mode/drive/world line, and the dog is
penning sheep through 360° perception (4/5 at step 19200 before I
killed the test). No retraining required because the gym already
trains under `LIDAR_FULL` (360° preset).

126 pytest cases still pass.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-17 02:19:15 +00:00

226 lines
7.9 KiB
Bash
Executable File

#!/bin/bash
# Launch Webots with N sheep enabled and the chosen controller mode.
# Generates a temporary world file in worlds/field_test.wbt with sheep
# beyond N commented out, sets the env vars the dog controller reads,
# then execs Webots on it.
#
# Usage:
# tools/run_webots.sh [N] [MODE] [DRIVE] [WORLD]
# N : number of active sheep (1..10), default 10
# MODE : "bc" | "rl" | "strombom" | "sequential", default "bc"
# DRIVE : "differential" | "mecanum", default "differential"
# WORLD : base world name (without .wbt), default "field"
# Supported: "field" (rectangular), "field_round" (circular)
#
# Examples:
# tools/run_webots.sh 10 bc # behaviour-cloned MLP, diff drive
# tools/run_webots.sh 10 rl mecanum # KL-PPO fine-tune, mecanum wheels
# tools/run_webots.sh 5 sequential field_round # analytic baseline, round field
# tools/run_webots.sh 3 strombom mecanum field_round # Strömbom, mecanum, round
#
# Notes:
# * bc loads training/runs/bc/policy.zip, rl loads training/runs/rl.
# Override via HERDING_POLICY_DIR=/path/to/run env var.
# * Conda env "tir" must be active (provides stable-baselines3 + torch).
#
# Headless-ish (no 3D view, fast sim, no modal dialogs):
# WEBOTS_HEADLESS=1 make webots N=10 MODE=rl DRIVE=mecanum
# WEBOTS_HEADLESS=1 tools/run_webots.sh 10 rl mecanum
# This passes --no-rendering --minimize --mode=fast --batch to webots.
# Webots still needs a display (Qt); on a machine without one use e.g.:
# xvfb-run -a env WEBOTS_HEADLESS=1 tools/run_webots.sh 10 rl mecanum
# Optional extra CLI tokens (space-separated):
# WEBOTS_EXTRA_ARGS="--stdout --stderr" WEBOTS_HEADLESS=1 tools/run_webots.sh 10 rl
set -e
# Make sure HERDING_PYTHON is resolved and on PATH so Webots inherits
# the right interpreter (controllers/{shepherd_dog,sheep}/runtime.ini
# both read $HERDING_PYTHON via env-var expansion).
source "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/setup_env.sh"
N=${1:-10}
MODE=${2:-bc}
DRIVE=${3:-differential}
WORLD=${4:-field}
if (( N < 0 || N > 10 )); then
echo "N must be 0..10, got $N" >&2; exit 1
fi
case "$MODE" in
bc|rl|strombom|sequential|universal|calibrate) ;;
*) echo "MODE must be bc|rl|strombom|sequential|universal|calibrate, got '$MODE'" >&2; exit 1 ;;
esac
case "$DRIVE" in
differential|mecanum) ;;
*) echo "DRIVE must be differential|mecanum, got '$DRIVE'" >&2; exit 1 ;;
esac
ROOT="$( cd "$( dirname "${BASH_SOURCE[0]}" )/.." && pwd )"
SRC="$ROOT/worlds/${WORLD}.wbt"
if [[ ! -f "$SRC" ]]; then
echo "World file not found: $SRC" >&2; exit 1
fi
DST="$ROOT/worlds/${WORLD}_test.wbt"
if [[ -n "${HERDING_POLICY_DIR:-}" ]]; then
RESOLVED_POLICY_DIR="$HERDING_POLICY_DIR"
else
# The training pipeline writes policies to:
# training/runs/{bc,rl}_<drive>_<world>
# Try that first; fall back to the drive-only and finally the
# bare-mode legacy paths so older policy checkouts still load.
if [[ "$MODE" == "rl" ]]; then
BASE="rl"
else
BASE="bc"
fi
for CAND in \
"$ROOT/training/runs/${BASE}_${DRIVE}_${WORLD}" \
"$ROOT/training/runs/${BASE}_${DRIVE}" \
"$ROOT/training/runs/${BASE}"
do
if [[ -d "$CAND" ]]; then
RESOLVED_POLICY_DIR="$CAND"
break
fi
done
: "${RESOLVED_POLICY_DIR:=$ROOT/training/runs/${BASE}_${DRIVE}_${WORLD}}"
fi
cp "$SRC" "$DST"
# LiDAR FOV variant: HERDING_LIDAR=140 (default) or 360 (ablation).
# 360° is only supported for differential drive; the mecanum proto
# always uses the 140° sensor matching ShepherdDog.proto.
LIDAR_VARIANT="${HERDING_LIDAR:-140}"
if [[ "$LIDAR_VARIANT" != "140" && "$LIDAR_VARIANT" != "360" ]]; then
echo "HERDING_LIDAR must be 140 or 360, got '$LIDAR_VARIANT'" >&2; exit 1
fi
if [[ "$LIDAR_VARIANT" == "360" && "$DRIVE" == "mecanum" ]]; then
echo "[run_webots] HERDING_LIDAR=360 not available for mecanum drive — falling back to 140." >&2
LIDAR_VARIANT="140"
fi
export HERDING_LIDAR="$LIDAR_VARIANT"
# Swap robot proto based on drive mode + LiDAR variant.
# Base worlds reference ShepherdDog (diff-drive 140°). For mecanum we
# swap in ShepherdDogMecanum; for the 360° ablation we swap in
# ShepherdDog360.
if [[ "$DRIVE" == "mecanum" ]]; then
sed -i 's|"../protos/ShepherdDog.proto"|"../protos/ShepherdDogMecanum.proto"|' "$DST"
sed -i 's|^ShepherdDog {|ShepherdDogMecanum {|' "$DST"
elif [[ "$LIDAR_VARIANT" == "360" ]]; then
sed -i 's|"../protos/ShepherdDog.proto"|"../protos/ShepherdDog360.proto"|' "$DST"
sed -i 's|^ShepherdDog {|ShepherdDog360 {|' "$DST"
fi
if [[ "$DRIVE" == "mecanum" ]]; then
# Inject mecanum roller contact properties. The proto's rollers are
# split into two contact materials so that we can keep the friction
# axes oriented along each roller's free-spin direction — but with
# physical roller hinges (no longer plain cylinder wheels) the
# ground contact is via the capsules and standard friction works.
# Slightly bumped coulombFriction keeps the rollers gripping during
# mecanum strafing.
python3 -c "
with open('$DST', 'r') as f:
txt = f.read()
mec = ''' ContactProperties {
material1 \"MecanumWheelA\"
coulombFriction [
2.0
]
bounce 0
forceDependentSlip [
0.005
]
softCFM 0.0001
}
ContactProperties {
material1 \"MecanumWheelB\"
coulombFriction [
2.0
]
bounce 0
forceDependentSlip [
0.005
]
softCFM 0.0001
}
'''
# The contactProperties array closes with ' ]\n}' (2-space indent ] then WorldInfo }).
# Insert the new block just before that closing ].
txt = txt.replace('\n ]\n}', '\n' + mec + ' ]\n}', 1)
with open('$DST', 'w') as f:
f.write(txt)
"
fi
# Comment out sheep N+1..10 by prefixing the matching Sheep { ... } line.
for i in $(seq $((N+1)) 10); do
sed -i "s|^Sheep .* \"sheep${i}\".*|# &|" "$DST"
done
active=$(grep -c '^Sheep' "$DST" || true)
echo "------------------------------------------------------------"
echo "World : $DST"
echo "Mode : $MODE"
echo "Drive : $DRIVE"
echo "Sheep : $active active"
echo "Policy dir : $RESOLVED_POLICY_DIR"
echo "------------------------------------------------------------"
# Webots strips HERDING_* env vars from controller subprocesses in some
# setups, so we also write a runtime config file the controller reads.
cat > "$ROOT/herding_runtime.cfg" <<EOF
HERDING_MODE=$MODE
HERDING_POLICY_DIR=$RESOLVED_POLICY_DIR
HERDING_DRIVE=$DRIVE
HERDING_WORLD=$WORLD
HERDING_LIDAR=$LIDAR_VARIANT
HERDING_USE_GT=${HERDING_USE_GT:-0}
EOF
export HERDING_MODE="$MODE"
export HERDING_POLICY_DIR="$RESOLVED_POLICY_DIR"
export HERDING_DRIVE="$DRIVE"
export HERDING_WORLD="$WORLD"
export HERDING_LIDAR="$LIDAR_VARIANT"
# The controller writes this sentinel when all GT sheep are penned. We
# poll for it and kill Webots so the run finishes cleanly instead of
# idling for minutes after the task is done.
DONE_FILE="$ROOT/training/.run_done"
mkdir -p "$(dirname "$DONE_FILE")"
rm -f "$DONE_FILE"
if [[ "${WEBOTS_HEADLESS:-}" == "1" ]]; then
echo "[run_webots] headless flags: --no-rendering --minimize --mode=fast --batch"
# shellcheck disable=SC2086
webots --no-rendering --minimize --mode=fast --batch ${WEBOTS_EXTRA_ARGS:-} "$DST" &
else
# shellcheck disable=SC2086
webots ${WEBOTS_EXTRA_ARGS:-} "$DST" &
fi
WEBOTS_PID=$!
cleanup() {
kill "$WEBOTS_PID" 2>/dev/null || true
wait "$WEBOTS_PID" 2>/dev/null || true
exit 0
}
trap cleanup INT TERM
# Poll for the sentinel; bail when Webots exits on its own or when the
# user closes the window.
while kill -0 "$WEBOTS_PID" 2>/dev/null; do
if [[ -f "$DONE_FILE" ]]; then
echo "[run_webots] all sheep penned — closing Webots"
sleep 1 # let the controller print its line
kill "$WEBOTS_PID" 2>/dev/null || true
break
fi
sleep 1
done
wait "$WEBOTS_PID" 2>/dev/null || true