Overview
You build a local Python pipeline that trains a PyTorch forward-kinematics regressor on ABB IRB 120 samples against a ridge baseline before replaying ten six-DOF trajectories in MuJoCo. The scripts write four local outputs: a contact summary CSV, a cross-referenced anomaly CSV, a JSON evaluation report, and an offline Rerun archive opened with telemetry disabled.
- Train a CPU PyTorch multilayer perceptron on 80 percent of the IRB 120 samples and benchmark its held-out RMSE and 95th-percentile position error against scikit-learn Ridge regression.
- Replay five smooth interpolated trajectories and five perturbed trajectories through a six-DOF MuJoCo IRB 120 scene without solver instability and record every joint-limit breach or physical contact.
- Cross-reference every trajectory step exceeding the held-out 95th-percentile residual threshold or triggering a MuJoCo contact event in an anomaly CSV and evaluation summary JSON.
- Stream synchronized 3D arm motion alongside residual curves and warning logs into a local
.rrdrecording inspected with analytics disabled. - Verify deterministic physics replay across repeated runs and document required Kaggle CC BY 4.0 attribution in the repository README.
Tools
- PyTorch
PyTorch source is free under its BSD-style license. Hardware, cloud compute and third-party components can have separate costs or terms.
- MuJoCo
MuJoCo uses Apache-2.0 and supplies free local binaries and Python bindings. Compute and separately sourced model assets remain outside the engine license.
- Rerun
The SDK is free under Apache-2.0/MIT; managed Hub has separate contact-based pricing. The native agent panel documents using an installed Codex client with its subscription and no extra API key. A direct provider API connection requires its own key and billing.
Datasets
- Robot Kinematics Dataset Kaggle
Provides generated six-joint ABB IRB 120 forward-kinematics samples mapping joint angles to tool-space coordinates for PyTorch training and MuJoCo trajectory checks.
Before you begin
Python 3.11 or 3.12
Install CPython 3.11 or 3.12 with venv and pip available on your shell PATH, as rerun-sdk 0.44 requires Python 3.11+ and NumPy 2.0+. Prebuilt CPU wheels cover Windows, Linux, and Apple Silicon (arm64) macOS.
Free Kaggle account
Create a Kaggle account to download sandibaressiegota/robot-kinematics-dataset via the web UI or a KAGGLE_API_TOKEN environment variable. Keep all credentials outside your project repository.
2 GB of free disk space
PyTorch CPU wheels, MuJoCo binaries, the Rerun viewer binary, and the saved .rrd archive fit comfortably inside 2 GB of local storage.
Git and a terminal
Use PowerShell on Windows or Bash on macOS and Linux to run Python scripts and open the local Rerun viewer.
Stage 01 · setup45 minutes
Workspace Setup and Telemetry Opt-Out
Create an isolated Python 3.11+ environment, install the core packages, switch off Rerun analytics, and record dataset attribution.
Every package in this project runs locally on a standard CPU without cloud accounts or paid API keys. Separating the project into dedicated folders for raw data, processed splits, XML assets, source scripts, and generated reports keeps deterministic runs reproducible.
irb120-kinematics-audit/ # repository root
README.md # dataset attribution and tool licenses
requirements.txt # pinned Python dependencies
data/
raw/ # Kaggle CSV download
processed/ # train/test splits and trajectories
models/ # MuJoCo MJCF XML and trained weights
src/ # training, replay, logging, and audit scripts
outputs/ # CSVs, JSON summaries, and .rrd archivemkdir -p irb120-kinematics-audit/{data/raw,data/processed,models,src,outputs}
cd irb120-kinematics-audit
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pipNew-Item -ItemType Directory -Force irb120-kinematics-audit/data/raw,irb120-kinematics-audit/data/processed,irb120-kinematics-audit/models,irb120-kinematics-audit/src,irb120-kinematics-audit/outputs | Out-Null
Set-Location irb120-kinematics-audit
py -3.11 -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade piptorch>=2.2
mujoco>=3.1
rerun-sdk>=0.44
scikit-learn>=1.4
numpy>=2.0
pandas>=2.2
kagglehub>=0.3pip install -r requirements.txt
rerun analytics disable
rerun analytics config# IRB 120 Kinematics Audit
Train a PyTorch forward-kinematics regressor on ABB IRB 120 joint samples,
replay smooth and perturbed six-DOF trajectories in MuJoCo, and inspect
synchronized 3D motion and error logs offline in Rerun.
## Dataset Attribution
This project uses the "Robot Kinematics Dataset" by Sandi Baressi Segota et al.
from Kaggle (`sandibaressiegota/robot-kinematics-dataset`), licensed under
Creative Commons Attribution 4.0 International (CC BY 4.0).
Citations (dataset authors request citing at least one paper):
- Baressi Segota S, Andjelic N, Mrzljak V, Lorencin I, Kuric I, Car Z.
Utilization of multilayer perceptron for determining the inverse kinematics
of an industrial robotic manipulator. International Journal of Advanced
Robotic Systems. 2021 Aug 13;18(4):1729881420925283.
- Car Z, Baressi Segota S, Andjelic N, Lorencin I, Musulin J, Stifanic D,
Mrzljak V. Determining Inverse Kinematics of a Serial Robotic Manipulator
Through the Use of Genetic Programming Algorithm. 8th International
Congress of the Serbian Society of Mechanics. 2021 July 21.
## Tool Licenses
- PyTorch: BSD-style license (local CPU training, free).
- MuJoCo: Apache-2.0 license (local physics engine and Python bindings, free).
- Rerun SDK and native viewer: Apache-2.0 / MIT (local offline .rrd workflow,
free; managed Rerun Hub is a separate commercial service not used here).python -c "import torch, mujoco, rerun, sklearn, numpy, pandas; print('torch:', torch.__version__, 'mujoco:', mujoco.__version__, 'rerun:', rerun.__version__, 'numpy:', numpy.__version__)"torch: <torch_version> mujoco: <mujoco_version> rerun: <rerun_version> numpy: <numpy_version>
The virtual environment activates without errors and rerun analytics config reports analytics disabled. Your README.md holds the exact Kaggle CC BY 4.0 citations, and the import check prints versions for torch, mujoco, rerun, and numpy.
Stage 02 · data45 minutes
Download and Partition the IRB 120 Kinematics Dataset
Download the Kaggle dataset, verify headers and units, create a seeded 80/20 split, and save training-only normalization stats.
The Kaggle Robot Kinematics Dataset stores 15,000 generated forward-kinematics poses for a six-DOF ABB IRB 120 manipulator in robot_inverse_kinematics_dataset.csv. Inspecting column headers and numeric ranges before modeling prevents silent unit mismatches between radians, degrees, meters, and millimeters.
| Columns | Role | Expected Units |
|---|---|---|
q1 to q6 | Six revolute joint angles (q3 spans +1.22 to +1.92 rad) | Radians |
x, y, z | Tool-space coordinates from robot base | Meters or millimeters (checked by script) |
export KAGGLE_API_TOKEN="your_kaggle_token"
python -c "import shutil, pathlib, kagglehub; src = pathlib.Path(kagglehub.dataset_download('sandibaressiegota/robot-kinematics-dataset')); [shutil.copy2(p, pathlib.Path('data/raw') / p.name) for p in src.glob('*.csv')]; print('Copied CSV files to data/raw')"$env:KAGGLE_API_TOKEN = "your_kaggle_token"
python -c "import shutil, pathlib, kagglehub; src = pathlib.Path(kagglehub.dataset_download('sandibaressiegota/robot-kinematics-dataset')); [shutil.copy2(p, pathlib.Path('data/raw') / p.name) for p in src.glob('*.csv')]; print('Copied CSV files to data/raw')"Computing mean and standard deviation across the full table leaks held-out distribution information into training. The script below shuffles row indices with fixed seed 42 and reserves 20 percent for evaluation. It calculates normalization stats plus observed per-joint bounds (q_min, q_max) on the 80 percent training split alone.
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
RAW_DIR = Path("data/raw")
OUT_DIR = Path("data/processed")
SEED = 42
TEST_FRACTION = 0.20
JOINT_COLS = ["q1", "q2", "q3", "q4", "q5", "q6"]
TARGET_COLS = ["x", "y", "z"]
def find_csv(raw_dir: Path) -> Path:
candidates = sorted(raw_dir.rglob("*.csv"))
if not candidates:
raise FileNotFoundError(
"No CSV file found under data/raw. Download the Kaggle dataset first."
)
for path in candidates:
if "kinematics" in path.name.lower():
return path
return candidates[0]
def main() -> None:
OUT_DIR.mkdir(parents=True, exist_ok=True)
csv_path = find_csv(RAW_DIR)
df = pd.read_csv(csv_path)
print(f"Loaded: {csv_path.name}")
print(f"Shape: {df.shape[0]} rows x {df.shape[1]} columns")
print(f"Columns: {list(df.columns)}")
missing_cols = [c for c in JOINT_COLS + TARGET_COLS if c not in df.columns]
if missing_cols:
raise ValueError(f"Missing expected columns: {missing_cols}")
null_total = int(df[JOINT_COLS + TARGET_COLS].isna().sum().sum())
print(f"Null entries in selected columns: {null_total}")
df = df.dropna(subset=JOINT_COLS + TARGET_COLS).reset_index(drop=True)
for col in JOINT_COLS + TARGET_COLS:
col_min = float(df[col].min())
col_max = float(df[col].max())
print(f" {col}: min={col_min:.4f}, max={col_max:.4f}")
max_abs_xyz = float(df[TARGET_COLS].abs().to_numpy().max())
position_scale = 0.001 if max_abs_xyz > 10.0 else 1.0
unit_label = "millimeters (scaled to meters)" if position_scale != 1.0 else "meters"
print(f"Detected tool-space units: {unit_label}")
q_all = df[JOINT_COLS].to_numpy(dtype=np.float32)
xyz_all = df[TARGET_COLS].to_numpy(dtype=np.float32) * np.float32(position_scale)
rng = np.random.default_rng(SEED)
indices = rng.permutation(len(q_all))
n_test = int(round(len(q_all) * TEST_FRACTION))
test_idx = indices[:n_test]
train_idx = indices[n_test:]
q_train, xyz_train = q_all[train_idx], xyz_all[train_idx]
q_test, xyz_test = q_all[test_idx], xyz_all[test_idx]
q_mean = q_train.mean(axis=0)
q_std = np.where(q_train.std(axis=0) > 1e-8, q_train.std(axis=0), 1.0)
q_min = q_train.min(axis=0)
q_max = q_train.max(axis=0)
np.savez(OUT_DIR / "train.npz", q=q_train, xyz=xyz_train, indices=train_idx)
np.savez(OUT_DIR / "test.npz", q=q_test, xyz=xyz_test, indices=test_idx)
stats = {
"seed": SEED,
"test_fraction": TEST_FRACTION,
"n_train": int(len(train_idx)),
"n_test": int(len(test_idx)),
"position_scale_to_meters": position_scale,
"joint_cols": JOINT_COLS,
"target_cols": TARGET_COLS,
"q_mean": q_mean.tolist(),
"q_std": q_std.tolist(),
"q_min": q_min.tolist(),
"q_max": q_max.tolist(),
}
(OUT_DIR / "norm_stats.json").write_text(
json.dumps(stats, indent=2), encoding="utf-8"
)
print(f"Saved train ({len(train_idx)}) and test ({len(test_idx)}) splits.")
if __name__ == "__main__":
main()python src/inspect_data.pyLoaded: robot_inverse_kinematics_dataset.csv Shape: 15000 rows x 9 columns Columns: ['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'x', 'y', 'z'] Null entries in selected columns: 0 q1: min=<q1_min>, max=<q1_max> q3: min=<q3_min>, max=<q3_max> ... Detected tool-space units: <detected_units> Saved train (12000) and test (3000) splits.
data/processed/ holds train.npz, test.npz, and norm_stats.json with n_train: 12000, n_test: 3000, and per-joint q_min/q_max arrays. The printed joint angles sit in radians, including the dataset's positive q3 span near 1.22 to 1.92 radians.
Stage 03 · build1 hour 15 minutes
Train the PyTorch MLP and Ridge Baseline
Train a compact CPU multilayer perceptron mapping six joint angles to tool coordinates alongside a scikit-learn Ridge baseline.
Forward kinematics is a smooth nonlinear map built from chained sine and cosine rotations across six axes. A compact multilayer perceptron with three hidden layers (128, 128, and 64 units) learns that nonlinear mapping on CPU in under a minute.
Training a linear Ridge model on the identical normalized training split gives a concrete lower bound. Because a linear map cannot capture chained trigonometric rotations, the neural network should beat the ridge baseline by a wide margin.
from __future__ import annotations
import json
import random
from pathlib import Path
import joblib
import numpy as np
import torch
from sklearn.linear_model import Ridge
from torch import nn
from torch.utils.data import DataLoader, TensorDataset
PROC_DIR = Path("data/processed")
MODEL_DIR = Path("models")
OUT_DIR = Path("outputs")
SEED = 42
EPOCHS = 80
BATCH_SIZE = 128
LR = 1e-3
VAL_FRACTION = 0.10
def set_seed(seed: int) -> None:
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.use_deterministic_algorithms(True)
class ForwardKinematicsMLP(nn.Module):
def __init__(self) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(6, 128),
nn.ReLU(),
nn.Linear(128, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 3),
)
def forward(self, x: torch.Tensor) -> torch.Tensor:
return self.net(x)
def main() -> None:
set_seed(SEED)
MODEL_DIR.mkdir(parents=True, exist_ok=True)
OUT_DIR.mkdir(parents=True, exist_ok=True)
stats = json.loads((PROC_DIR / "norm_stats.json").read_text(encoding="utf-8"))
q_mean = np.asarray(stats["q_mean"], dtype=np.float32)
q_std = np.asarray(stats["q_std"], dtype=np.float32)
train_data = np.load(PROC_DIR / "train.npz")
q_train_norm = (train_data["q"] - q_mean) / q_std
xyz_train = train_data["xyz"]
n_val = int(round(len(q_train_norm) * VAL_FRACTION))
q_val, xyz_val = q_train_norm[:n_val], xyz_train[:n_val]
q_fit, xyz_fit = q_train_norm[n_val:], xyz_train[n_val:]
# Fit Ridge regression baseline on the same normalized training split.
ridge = Ridge(alpha=1.0)
ridge.fit(q_train_norm, xyz_train)
joblib.dump(ridge, MODEL_DIR / "ridge_baseline.joblib")
fit_ds = TensorDataset(torch.from_numpy(q_fit), torch.from_numpy(xyz_fit))
val_x = torch.from_numpy(q_val)
val_y = torch.from_numpy(xyz_val)
generator = torch.Generator().manual_seed(SEED)
loader = DataLoader(fit_ds, batch_size=BATCH_SIZE, shuffle=True, generator=generator)
model = ForwardKinematicsMLP()
optimizer = torch.optim.Adam(model.parameters(), lr=LR)
loss_fn = nn.MSELoss()
history = []
for epoch in range(1, EPOCHS + 1):
model.train()
running_loss = 0.0
for batch_x, batch_y in loader:
optimizer.zero_grad()
pred = model(batch_x)
loss = loss_fn(pred, batch_y)
loss.backward()
optimizer.step()
running_loss += float(loss.item()) * len(batch_x)
train_mse = running_loss / len(fit_ds)
model.eval()
with torch.no_grad():
val_mse = float(loss_fn(model(val_x), val_y).item())
history.append({"epoch": epoch, "train_mse": train_mse, "val_mse": val_mse})
if epoch == 1 or epoch % 10 == 0 or epoch == EPOCHS:
print(f"Epoch {epoch:03d}/{EPOCHS} | train_mse={train_mse:.6f} | val_mse={val_mse:.6f}")
torch.save(model.state_dict(), MODEL_DIR / "fk_mlp.pt")
(OUT_DIR / "training_history.json").write_text(
json.dumps(history, indent=2), encoding="utf-8"
)
print("Saved models/fk_mlp.pt and models/ridge_baseline.joblib.")
if __name__ == "__main__":
main()python src/train_fk.pyEpoch 001/80 | train_mse=<epoch1_train> | val_mse=<epoch1_val> Epoch 010/80 | train_mse=<epoch10_train> | val_mse=<epoch10_val> ... Epoch 080/80 | train_mse=<epoch80_train> | val_mse=<epoch80_val> Saved models/fk_mlp.pt and models/ridge_baseline.joblib.
Validation MSE drops across epochs while outputs/training_history.json records all 80 iterations. Both models/fk_mlp.pt and models/ridge_baseline.joblib exist on disk.
Stage 04 · test45 minutes
Evaluate Held-Out Errors and Set the Anomaly Threshold
Measure RMSE and 95th-percentile Euclidean position error on the reserved 20 percent split and store the residual threshold.
Single-axis MSE hides how far the predicted tool tip drifts in 3D space. Computing the Euclidean distance between predicted and ground-truth coordinates in meters turns model error into a physical tolerance that matches MuJoCo's world units.
The 95th-percentile held-out error becomes the anomaly cutoff for trajectory replay. Any replayed step whose predicted-versus-simulated residual exceeds that threshold gets flagged for inspection alongside MuJoCo contact and joint-limit checks.
from __future__ import annotations
import json
from pathlib import Path
import joblib
import numpy as np
import pandas as pd
import torch
from train_fk import ForwardKinematicsMLP
PROC_DIR = Path("data/processed")
MODEL_DIR = Path("models")
OUT_DIR = Path("outputs")
def position_metrics(pred: np.ndarray, truth: np.ndarray) -> tuple[float, float, np.ndarray]:
euclid = np.linalg.norm(pred - truth, axis=1)
rmse = float(np.sqrt(np.mean(euclid ** 2)))
p95 = float(np.percentile(euclid, 95))
return rmse, p95, euclid
def main() -> None:
OUT_DIR.mkdir(parents=True, exist_ok=True)
stats = json.loads((PROC_DIR / "norm_stats.json").read_text(encoding="utf-8"))
q_mean = np.asarray(stats["q_mean"], dtype=np.float32)
q_std = np.asarray(stats["q_std"], dtype=np.float32)
test_data = np.load(PROC_DIR / "test.npz")
q_test_norm = (test_data["q"] - q_mean) / q_std
xyz_test = test_data["xyz"]
model = ForwardKinematicsMLP()
model.load_state_dict(torch.load(MODEL_DIR / "fk_mlp.pt", map_location="cpu", weights_only=True))
model.eval()
with torch.no_grad():
mlp_pred = model(torch.from_numpy(q_test_norm)).numpy()
ridge = joblib.load(MODEL_DIR / "ridge_baseline.joblib")
ridge_pred = ridge.predict(q_test_norm).astype(np.float32)
mlp_rmse, mlp_p95, mlp_err = position_metrics(mlp_pred, xyz_test)
ridge_rmse, ridge_p95, ridge_err = position_metrics(ridge_pred, xyz_test)
print(f"MLP held-out RMSE: {mlp_rmse:.5f} m | p95 error: {mlp_p95:.5f} m")
print(f"Ridge held-out RMSE: {ridge_rmse:.5f} m | p95 error: {ridge_p95:.5f} m")
print(f"MLP beats Ridge baseline: {mlp_rmse < ridge_rmse}")
err_df = pd.DataFrame({
"sample_index": test_data["indices"],
"true_x": xyz_test[:, 0],
"true_y": xyz_test[:, 1],
"true_z": xyz_test[:, 2],
"mlp_x": mlp_pred[:, 0],
"mlp_y": mlp_pred[:, 1],
"mlp_z": mlp_pred[:, 2],
"mlp_euclid_m": mlp_err,
"ridge_euclid_m": ridge_err,
})
err_df.to_csv(OUT_DIR / "test_errors.csv", index=False)
summary = {
"n_test": int(len(xyz_test)),
"mlp_rmse_m": mlp_rmse,
"mlp_p95_m": mlp_p95,
"ridge_rmse_m": ridge_rmse,
"ridge_p95_m": ridge_p95,
"mlp_beats_ridge": bool(mlp_rmse < ridge_rmse),
"p95_residual_threshold_m": mlp_p95,
}
(OUT_DIR / "eval_summary.json").write_text(
json.dumps(summary, indent=2), encoding="utf-8"
)
print("Saved outputs/test_errors.csv and outputs/eval_summary.json.")
if __name__ == "__main__":
main()python src/evaluate_fk.pyMLP held-out RMSE: <your_mlp_rmse> m | p95 error: <your_mlp_p95> m Ridge held-out RMSE: <your_ridge_rmse> m | p95 error: <your_ridge_p95> m MLP beats Ridge baseline: True Saved outputs/test_errors.csv and outputs/eval_summary.json.
outputs/eval_summary.json records mlp_beats_ridge: true along with finite mlp_rmse_m, ridge_rmse_m, and p95_residual_threshold_m values. The exported outputs/test_errors.csv file contains 3,000 rows.
Stage 05 · build45 minutes
Synthesize Smooth and Perturbed Six-DOF Trajectories
Generate five smooth interpolated paths between held-out poses and five perturbed paths targeting joint limits or physical contact.
Testing a learned kinematics model on static test rows only checks poses drawn from the training distribution. Replaying continuous paths reveals whether smooth intermediate joints stay accurate and whether out-of-range or downward motions trigger physics warnings.
A cubic Hermite blend (3t^2 - 2t^3) starts and finishes with zero joint velocity so MuJoCo actuators track smoothly without sudden impulses. The Kaggle CSV samples q3 across +1.22 to +1.92 radians rather than the datasheet's -1.920 to +1.222 span. Reading observed q_min and q_max from norm_stats.json keeps smooth paths inside that active range.
| Joint | Axis Role | Active Range (Radians) |
|---|---|---|
joint1 | Base rotation | -2.880 to 2.880 |
joint2 | Shoulder pitch | -1.920 to 1.920 |
joint3 | Elbow pitch (dataset convention) | 1.220 to 1.920 (datasheet: -1.920 to 1.222) |
joint4 | Forearm roll | -2.793 to 2.793 |
joint5 | Wrist pitch | -2.094 to 2.094 |
joint6 | Flange roll | -6.981 to 6.981 |
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
PROC_DIR = Path("data/processed")
SEED = 42
STEPS_PER_TRAJ = 100
N_SMOOTH = 5
def cubic_interp(q_start: np.ndarray, q_end: np.ndarray, steps: int) -> np.ndarray:
t = np.linspace(0.0, 1.0, steps, dtype=np.float64)
s = 3.0 * t**2 - 2.0 * t**3
return q_start[None, :] + s[:, None] * (q_end - q_start)[None, :]
def main() -> None:
rng = np.random.default_rng(SEED)
stats = json.loads((PROC_DIR / "norm_stats.json").read_text(encoding="utf-8"))
q_low = np.asarray(stats["q_min"], dtype=np.float64)
q_high = np.asarray(stats["q_max"], dtype=np.float64)
inset = 0.05 * (q_high - q_low)
safe_low = q_low + inset
safe_high = q_high - inset
test_data = np.load(PROC_DIR / "test.npz")
q_test = test_data["q"].astype(np.float64)
trajectories, kinds, meta = [], [], []
# 1. Five smooth trajectories strictly inside observed training bounds.
for i in range(N_SMOOTH):
idx_a, idx_b = rng.choice(len(q_test), size=2, replace=False)
q_start = np.clip(q_test[idx_a], safe_low, safe_high)
q_end = np.clip(q_test[idx_b], safe_low, safe_high)
trajectories.append(cubic_interp(q_start, q_end, STEPS_PER_TRAJ))
kinds.append("smooth")
meta.append({"traj_id": i, "kind": "smooth", "perturbation": "none"})
# 2. Five perturbed trajectories pushing past active bounds or into contact.
perturb_modes = [
"j2_table_dip",
"j3_upper_bound",
"j1_limit_sweep",
"j2_j3_table_reach",
"j5_wrist_limit",
]
for offset, mode in enumerate(perturb_modes):
traj_id = N_SMOOTH + offset
idx_a, idx_b = rng.choice(len(q_test), size=2, replace=False)
q_start = np.clip(q_test[idx_a], safe_low, safe_high)
q_end = np.clip(q_test[idx_b], safe_low, safe_high)
path = cubic_interp(q_start, q_end, STEPS_PER_TRAJ)
bump = np.sin(np.linspace(0.0, np.pi, STEPS_PER_TRAJ))
if mode == "j2_table_dip":
# Stays within active joint bounds while folding downward to trigger contact.
path[:, 1] = path[:, 1] * (1.0 - bump) + min(1.85, q_high[1] - 0.04) * bump
path[:, 2] = path[:, 2] * (1.0 - bump) + (q_low[2] + 0.04) * bump
path[:, 4] = path[:, 4] * (1.0 - bump) + (-1.55) * bump
elif mode == "j3_upper_bound":
path[:, 2] = path[:, 2] * (1.0 - bump) + (q_high[2] + 0.30) * bump
elif mode == "j1_limit_sweep":
path[:, 0] = path[:, 0] * (1.0 - bump) + (q_high[0] + 0.30) * bump
elif mode == "j2_j3_table_reach":
path[:, 1] = path[:, 1] * (1.0 - bump) + (q_high[1] + 0.18) * bump
path[:, 2] = path[:, 2] * (1.0 - bump) + (q_low[2] - 0.25) * bump
path[:, 4] = path[:, 4] * (1.0 - bump) + (-1.50) * bump
elif mode == "j5_wrist_limit":
path[:, 4] = path[:, 4] * (1.0 - bump) + (q_low[4] - 0.30) * bump
trajectories.append(path)
kinds.append("perturbed")
meta.append({"traj_id": traj_id, "kind": "perturbed", "perturbation": mode})
traj_array = np.stack(trajectories, axis=0)
np.savez(
PROC_DIR / "trajectories.npz",
trajectories=traj_array,
kinds=np.array(kinds),
)
(PROC_DIR / "trajectories_meta.json").write_text(
json.dumps(meta, indent=2), encoding="utf-8"
)
print(f"Saved {traj_array.shape[0]} trajectories of {traj_array.shape[1]} steps each.")
if __name__ == "__main__":
main()python src/generate_trajectories.pySaved 10 trajectories of 100 steps each.
data/processed/trajectories.npz stores an array of shape (10, 100, 6) whose five smooth paths stay strictly inside [q_min, q_max]. The companion data/processed/trajectories_meta.json lists five smooth and five perturbed entries.
Stage 06 · build1 hour 45 minutes
Build the MuJoCo IRB 120 Scene and Replay Trajectories
Author a six-DOF MJCF arm model with matched joint limits and a workbench, then replay all ten trajectories to export contact and anomaly logs.
MuJoCo compiles robot geometry, inertia, joint limits, and contact rules from an MJCF XML file via mujoco.MjModel.from_xml_path. Trimming each link capsule away from its pivots and adding exclude pairs for adjacent bodies plus elbow and wrist housings stops false self-collisions while keeping real workbench contacts.
<mujoco model="abb_irb120">
<compiler angle="radian" autolimits="true"/>
<option timestep="0.002" gravity="0 0 -9.81" integrator="implicitfast"/>
<default>
<joint type="hinge" damping="2.0" armature="0.05" limited="true"/>
<geom contype="1" conaffinity="1" rgba="0.82 0.35 0.16 1"/>
<position kp="300" kv="30"/>
</default>
<worldbody>
<light pos="0.8 -0.8 1.5" dir="-0.5 0.5 -1"/>
<geom name="workbench" type="box" pos="0 0 -0.025" size="0.8 0.8 0.025"
rgba="0.22 0.24 0.28 1"/>
<body name="base_link" pos="0 0 0">
<geom name="base_geom" type="cylinder" pos="0 0 0.08" size="0.085 0.08"
rgba="0.35 0.35 0.38 1"/>
<body name="link1" pos="0 0 0.16">
<joint name="joint1" axis="0 0 1" range="-2.880 2.880"/>
<inertial pos="0 0 0.065" mass="3.0" diaginertia="0.015 0.015 0.015"/>
<geom name="link1_geom" type="capsule" fromto="0 0 0.020 0 0 0.105" size="0.048"/>
<body name="link2" pos="0 0 0.130">
<joint name="joint2" axis="0 1 0" range="-1.920 1.920"/>
<inertial pos="0 0 0.135" mass="3.5" diaginertia="0.03 0.03 0.01"/>
<geom name="link2_geom" type="capsule" fromto="0 0 0.055 0 0 0.215" size="0.042"/>
<body name="link3" pos="0 0 0.270">
<!-- Matches Kaggle IRB 120 dataset q3 range [1.22, 1.92] rad -->
<joint name="joint3" axis="0 1 0" range="1.220 1.920"/>
<inertial pos="0.04 0 0.035" mass="2.5" diaginertia="0.015 0.015 0.01"/>
<geom name="link3_geom" type="capsule" fromto="0 0 0.015 0 0 0.055" size="0.036"/>
<body name="link4" pos="0 0 0.070">
<joint name="joint4" axis="1 0 0" range="-2.793 2.793"/>
<inertial pos="0.151 0 0" mass="1.8" diaginertia="0.008 0.02 0.02"/>
<geom name="link4_geom" type="capsule" fromto="0.050 0 0 0.250 0 0" size="0.034"/>
<body name="link5" pos="0.302 0 0">
<joint name="joint5" axis="0 1 0" range="-2.094 2.094"/>
<inertial pos="0.036 0 0" mass="0.8" diaginertia="0.003 0.003 0.003"/>
<geom name="link5_geom" type="capsule" fromto="0.015 0 0 0.058 0 0" size="0.024"/>
<body name="link6" pos="0.072 0 0">
<joint name="joint6" axis="1 0 0" range="-6.981 6.981"/>
<inertial pos="0.01 0 0" mass="0.4" diaginertia="0.001 0.001 0.001"/>
<geom name="flange_geom" type="cylinder" pos="0.012 0 0"
quat="0.7071 0 0.7071 0" size="0.026 0.008"
rgba="0.15 0.55 0.85 1"/>
<site name="ee_site" pos="0.02 0 0" size="0.012" rgba="0.1 0.9 0.3 1"/>
</body>
</body>
</body>
</body>
</body>
</body>
</body>
</worldbody>
<contact>
<exclude body1="base_link" body2="link1"/>
<exclude body1="link1" body2="link2"/>
<exclude body1="link2" body2="link3"/>
<exclude body1="link3" body2="link4"/>
<exclude body1="link4" body2="link5"/>
<exclude body1="link5" body2="link6"/>
<exclude body1="link2" body2="link4"/>
<exclude body1="link4" body2="link6"/>
</contact>
<actuator>
<position name="act1" joint="joint1" ctrlrange="-2.880 2.880"/>
<position name="act2" joint="joint2" ctrlrange="-1.920 1.920"/>
<position name="act3" joint="joint3" ctrlrange="1.220 1.920"/>
<position name="act4" joint="joint4" ctrlrange="-2.793 2.793"/>
<position name="act5" joint="joint5" ctrlrange="-2.094 2.094"/>
<position name="act6" joint="joint6" ctrlrange="-6.981 6.981"/>
</actuator>
</mujoco>from __future__ import annotations
import json
from pathlib import Path
import mujoco
import numpy as np
import pandas as pd
import torch
from train_fk import ForwardKinematicsMLP
PROC_DIR, MODEL_DIR, OUT_DIR = Path("data/processed"), Path("models"), Path("outputs")
SUBSTEPS, LIMIT_MARGIN = 8, 1e-3
def fit_frame_alignment(model: mujoco.MjModel, q_train: np.ndarray, xyz_train: np.ndarray):
data = mujoco.MjData(model)
n = min(1000, len(q_train))
sim = np.zeros((n, 3), dtype=np.float64)
for i in range(n):
mujoco.mj_resetData(model, data)
data.qpos[:6] = q_train[i]
mujoco.mj_forward(model, data)
sim[i] = data.site("ee_site").xpos
ref = xyz_train[:n].astype(np.float64)
sm, rm = sim.mean(axis=0), ref.mean(axis=0)
u, _, vt = np.linalg.svd((sim - sm).T @ (ref - rm))
rot = vt.T @ u.T
if np.linalg.det(rot) < 0:
vt[-1, :] *= -1.0
rot = vt.T @ u.T
trans = rm - sm @ rot.T
rmse = float(np.sqrt(np.mean(np.sum((sim @ rot.T + trans - ref) ** 2, axis=1))))
return rot, trans, rmse
def replay_all(
xml_path: Path, trajectories: np.ndarray, kinds: np.ndarray,
mlp: ForwardKinematicsMLP, q_mean: np.ndarray, q_std: np.ndarray,
p95: float, rot: np.ndarray, trans: np.ndarray,
) -> tuple[pd.DataFrame, np.ndarray]:
model = mujoco.MjModel.from_xml_path(str(xml_path))
data = mujoco.MjData(model)
lo, hi = model.jnt_range[:6, 0].copy(), model.jnt_range[:6, 1].copy()
rows, chains = [], []
for tid in range(trajectories.shape[0]):
kind, path = str(kinds[tid]), trajectories[tid]
mujoco.mj_resetData(model, data)
q0 = np.clip(path[0], lo, hi)
data.qpos[:6], data.qvel[:], data.ctrl[:6] = q0, 0.0, q0
mujoco.mj_forward(model, data)
for step in range(path.shape[0]):
q_cmd = path[step]
breached = bool(np.any(q_cmd < lo - LIMIT_MARGIN) or np.any(q_cmd > hi + LIMIT_MARGIN))
data.ctrl[:6] = np.clip(q_cmd, lo, hi)
for _ in range(SUBSTEPS):
mujoco.mj_step(model, data)
if not np.all(np.isfinite(data.qpos)):
raise RuntimeError(f"Non-finite state at traj={tid}, step={step}")
sim_raw = data.site("ee_site").xpos.copy()
sim_xyz = sim_raw @ rot.T + trans
qn = ((q_cmd.astype(np.float32) - q_mean) / q_std)[None, :]
with torch.no_grad():
pred_xyz = mlp(torch.from_numpy(qn)).numpy()[0].astype(np.float64)
residual = float(np.linalg.norm(pred_xyz - sim_xyz))
pairs = []
for ci in range(data.ncon):
c = data.contact[ci]
g1 = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, int(c.geom1)) or str(c.geom1)
g2 = mujoco.mj_id2name(model, mujoco.mjtObj.mjOBJ_GEOM, int(c.geom2)) or str(c.geom2)
if {g1, g2} != {"base_geom", "workbench"}:
pairs.append(f"{g1}:{g2}")
n_con = len(pairs)
m_flag = residual > p95
p_flag = breached or (n_con > 0)
chains.append(np.vstack([data.xpos[1:8], sim_raw[None, :]]))
rows.append({
"traj_id": tid, "kind": kind, "step": step,
"sim_x": sim_xyz[0], "sim_y": sim_xyz[1], "sim_z": sim_xyz[2],
"pred_x": pred_xyz[0], "pred_y": pred_xyz[1], "pred_z": pred_xyz[2],
"residual_m": residual, "n_contacts": n_con,
"contact_pairs": ";".join(pairs), "limit_breach": breached,
"model_flag": m_flag, "physics_flag": p_flag,
"agree": m_flag == p_flag,
})
return pd.DataFrame(rows), np.stack(chains, axis=0)
def main() -> None:
OUT_DIR.mkdir(parents=True, exist_ok=True)
stats = json.loads((PROC_DIR / "norm_stats.json").read_text(encoding="utf-8"))
ev = json.loads((OUT_DIR / "eval_summary.json").read_text(encoding="utf-8"))
q_mean = np.asarray(stats["q_mean"], dtype=np.float32)
q_std = np.asarray(stats["q_std"], dtype=np.float32)
p95 = float(ev["p95_residual_threshold_m"])
tr = np.load(PROC_DIR / "train.npz")
tj = np.load(PROC_DIR / "trajectories.npz")
xml_path = MODEL_DIR / "irb120.xml"
model = mujoco.MjModel.from_xml_path(str(xml_path))
rot, trans, align_rmse = fit_frame_alignment(model, tr["q"], tr["xyz"])
print(f"Training-split rigid frame alignment RMSE: {align_rmse:.5f} m")
mlp = ForwardKinematicsMLP()
mlp.load_state_dict(torch.load(MODEL_DIR / "fk_mlp.pt", map_location="cpu", weights_only=True))
mlp.eval()
df, chains = replay_all(
xml_path, tj["trajectories"], tj["kinds"], mlp, q_mean, q_std, p95, rot, trans
)
df.to_csv(OUT_DIR / "contact_summary.csv", index=False)
anom = df[df["model_flag"] | df["physics_flag"]].copy()
anom.to_csv(OUT_DIR / "anomalies.csv", index=False)
np.savez(OUT_DIR / "replay_geometry.npz", chains=chains, rot=rot, trans=trans)
metrics = {
"total_steps": int(len(df)),
"total_contacts": int(df["n_contacts"].sum()),
"physics_flagged_fraction": float(df["physics_flag"].mean()),
"model_flagged_fraction": float(df["model_flag"].mean()),
"mean_agreement": float(df["agree"].mean()),
"anomaly_row_count": int(len(anom)),
"frame_align_rmse_m": align_rmse,
}
(OUT_DIR / "replay_metrics.json").write_text(json.dumps(metrics, indent=2), encoding="utf-8")
print(json.dumps(metrics, indent=2))
if __name__ == "__main__":
main()python src/replay_mujoco.pyTraining-split rigid frame alignment RMSE: <your_align_rmse> m
{
"total_steps": 1000,
"total_contacts": <your_contact_count>,
"physics_flagged_fraction": <your_physics_frac>,
"model_flagged_fraction": <your_model_frac>,
"mean_agreement": <your_agreement>,
"anomaly_row_count": <your_anomaly_rows>,
"frame_align_rmse_m": <your_align_rmse>
}MuJoCo completes all 1,000 steps without non-finite states or crashes, and outputs/contact_summary.csv holds 1,000 rows. Flagged steps appear in outputs/anomalies.csv by (traj_id, step), while outputs/replay_metrics.json reports the physics-flagged fraction and mean agreement.
Stage 07 · build1 hour
Stream 3D Poses and Error Plots into a Rerun Archive
Log synchronized 3D arm links, predicted versus simulated tool positions, scalar residuals, and anomaly text entries into a local .rrd file.
Rerun stores every entity under a hierarchical path and indexes updates on explicit timelines. Calling rr.save writes the entire recording directly to disk without needing a live network socket or viewer process during batch replay.
At every integer index on the step timeline, the logger records the arm chain with rr.LineStrips3D and both tool tips with rr.Points3D. Error curves use rr.Scalars, while flagged events write warning entries through rr.TextLog. Scrubbing any spike on the scalar chart moves the 3D arm straight to that exact configuration.
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
import rerun as rr
OUT_DIR = Path("outputs")
def main() -> None:
summary_df = pd.read_csv(OUT_DIR / "contact_summary.csv")
eval_summary = json.loads((OUT_DIR / "eval_summary.json").read_text(encoding="utf-8"))
geom = np.load(OUT_DIR / "replay_geometry.npz")
chains = geom["chains"]
rot = geom["rot"]
trans = geom["trans"]
p95_threshold = float(eval_summary["p95_residual_threshold_m"])
rrd_path = OUT_DIR / "irb120_replay.rrd"
rr.init("irb120_kinematics_audit")
rr.save(str(rrd_path))
# Log a static workbench reference square on z = 0.
table_outline = np.array([
[-0.8, -0.8, 0.0],
[0.8, -0.8, 0.0],
[0.8, 0.8, 0.0],
[-0.8, 0.8, 0.0],
[-0.8, -0.8, 0.0],
])
rr.log(
"world/workbench",
rr.LineStrips3D([table_outline], colors=[[90, 96, 110]]),
static=True,
)
for global_step, row in enumerate(summary_df.itertuples(index=False)):
rr.set_time("step", sequence=global_step)
chain = chains[global_step]
sim_world = chain[-1]
pred_dataset = np.array([row.pred_x, row.pred_y, row.pred_z], dtype=np.float64)
pred_world = (pred_dataset - trans) @ rot
is_alert = bool(row.model_flag or row.physics_flag)
arm_color = [225, 65, 55] if is_alert else [55, 160, 230]
rr.log(
"world/arm/links",
rr.LineStrips3D([chain], colors=[arm_color], radii=0.012),
)
rr.log(
"world/arm/joints",
rr.Points3D(chain[:-1], colors=[[240, 240, 245]], radii=0.018),
)
rr.log(
"world/ee/simulated",
rr.Points3D([sim_world], colors=[[35, 200, 110]], radii=0.022),
)
rr.log(
"world/ee/predicted",
rr.Points3D([pred_world], colors=[[245, 175, 40]], radii=0.020),
)
rr.log("metrics/residual_m", rr.Scalars(float(row.residual_m)))
rr.log("metrics/p95_threshold_m", rr.Scalars(p95_threshold))
rr.log("metrics/contact_count", rr.Scalars(float(row.n_contacts)))
rr.log("metrics/limit_breach", rr.Scalars(1.0 if row.limit_breach else 0.0))
if is_alert:
msg = (
f"traj={row.traj_id} ({row.kind}) step={row.step} "
f"residual={row.residual_m:.4f}m contacts={row.n_contacts} "
f"limit_breach={row.limit_breach}"
)
rr.log("logs/anomalies", rr.TextLog(msg, level=rr.TextLogLevel.WARN))
print(f"Wrote Rerun archive to {rrd_path} ({len(summary_df)} steps).")
if __name__ == "__main__":
main()python src/log_rerun.pyWrote Rerun archive to outputs/irb120_replay.rrd (1000 steps).
outputs/irb120_replay.rrd exists with non-zero file size and the script prints confirmation for all 1,000 logged steps.
Stage 08 · ship1 hour
Verify Determinism and Inspect Offline in Rerun
Confirm identical replay metrics across repeated runs while exporting the highest-error step report and inspecting the .rrd archive with analytics disabled.
Before inspecting plots, verify that running the MuJoCo replay twice on the same trajectory yields bit-identical contact counts and position residuals. The audit script checks repeatability and exports the 25 highest-error step indices into outputs/highest_error_steps.csv while merging replay metrics into outputs/eval_summary.json.
from __future__ import annotations
import json
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from replay_mujoco import replay_all
from train_fk import ForwardKinematicsMLP
PROC_DIR = Path("data/processed")
MODEL_DIR = Path("models")
OUT_DIR = Path("outputs")
def main() -> None:
stats = json.loads((PROC_DIR / "norm_stats.json").read_text(encoding="utf-8"))
eval_summary = json.loads((OUT_DIR / "eval_summary.json").read_text(encoding="utf-8"))
replay_metrics = json.loads((OUT_DIR / "replay_metrics.json").read_text(encoding="utf-8"))
geom = np.load(OUT_DIR / "replay_geometry.npz")
traj_data = np.load(PROC_DIR / "trajectories.npz")
mlp = ForwardKinematicsMLP()
mlp.load_state_dict(torch.load(MODEL_DIR / "fk_mlp.pt", map_location="cpu", weights_only=True))
mlp.eval()
# Run MuJoCo replay twice on trajectory 0 and verify identical outputs.
single_traj = traj_data["trajectories"][:1]
single_kind = traj_data["kinds"][:1]
q_mean = np.asarray(stats["q_mean"], dtype=np.float32)
q_std = np.asarray(stats["q_std"], dtype=np.float32)
p95 = float(eval_summary["p95_residual_threshold_m"])
run_a, _ = replay_all(
MODEL_DIR / "irb120.xml", single_traj, single_kind,
mlp, q_mean, q_std, p95, geom["rot"], geom["trans"],
)
run_b, _ = replay_all(
MODEL_DIR / "irb120.xml", single_traj, single_kind,
mlp, q_mean, q_std, p95, geom["rot"], geom["trans"],
)
contacts_match = bool((run_a["n_contacts"].to_numpy() == run_b["n_contacts"].to_numpy()).all())
residuals_match = bool(np.array_equal(run_a["residual_m"].to_numpy(), run_b["residual_m"].to_numpy()))
if not (contacts_match and residuals_match):
raise AssertionError("Replay determinism check failed between consecutive runs.")
summary_df = pd.read_csv(OUT_DIR / "contact_summary.csv")
top_df = summary_df.sort_values("residual_m", ascending=False).head(25)
top_df.to_csv(OUT_DIR / "highest_error_steps.csv", index=False)
eval_summary["replay"] = replay_metrics
eval_summary["determinism_verified"] = True
eval_summary["highest_error_top_steps"] = [
{
"traj_id": int(r.traj_id),
"step": int(r.step),
"residual_m": float(r.residual_m),
"n_contacts": int(r.n_contacts),
"limit_breach": bool(r.limit_breach),
}
for r in top_df.head(5).itertuples(index=False)
]
(OUT_DIR / "eval_summary.json").write_text(
json.dumps(eval_summary, indent=2), encoding="utf-8"
)
print("Determinism verified: identical contact counts and residuals across two runs.")
print("Exported outputs/highest_error_steps.csv and updated outputs/eval_summary.json.")
if __name__ == "__main__":
main()python src/audit_report.pyDeterminism verified: identical contact counts and residuals across two runs. Exported outputs/highest_error_steps.csv and updated outputs/eval_summary.json.
rerun analytics config
rerun outputs/irb120_replay.rrd
# Or open in your local browser instead of the native window:
# rerun --web-viewer outputs/irb120_replay.rrd- Confirm the 3D viewport renders
world/workbench,world/arm/links,world/ee/simulated(green), andworld/ee/predicted(amber). - Open the time-series panel showing
metrics/residual_m,metrics/p95_threshold_m,metrics/contact_count, andmetrics/limit_breachon thesteptimeline. - Click a peak where
metrics/residual_mrises abovemetrics/p95_threshold_mor where the arm links turn red, then verify the matchinglogs/anomaliesentry. - Cross-check the top five step indices in
outputs/highest_error_steps.csvagainstoutputs/anomalies.csvandoutputs/eval_summary.json.
| Artifact | Format | Contents |
|---|---|---|
src/ and models/irb120.xml | Python and MJCF | Training, evaluation, trajectory, MuJoCo replay, and Rerun scripts |
README.md | Markdown | Kaggle CC BY 4.0 citations and local tool license notes |
outputs/irb120_replay.rrd | Rerun archive | Ten replayed six-DOF trajectories with 3D arm links, tool points, error curves, and warnings |
outputs/eval_summary.json | JSON | Held-out MLP vs Ridge RMSE, p95 threshold, agreement, and determinism flag |
outputs/anomalies.csv | CSV | All steps exceeding p95 residual or triggering contacts or limit breaches |
outputs/highest_error_steps.csv | CSV | Top 25 trajectory steps ranked by Euclidean residual error |
src/audit_report.py exits with status 0 confirming deterministic replay, and outputs/irb120_replay.rrd opens locally with analytics disabled beside the scalar error plots. Every deliverable listed in the table above exists on disk and contains non-empty output.
Troubleshooting
kagglehub.dataset_download raises an authentication error or returns HTTP 401.
Confirm KAGGLE_API_TOKEN is exported in the same shell session, or place your legacy kaggle.json file in your user .kaggle directory with owner-only permissions. Manual download from Kaggle works as a fallback: grab the zip archive and extract the CSV into data/raw/.
frame_align_rmse_m stays above 0.10 meters even after SVD alignment.
Check whether the Kaggle CSV tool coordinates use millimeters (max_abs_xyz > 10) or rotated zero-angle joint conventions. Print q = 0 poses or inspect two single-joint sweeps in MuJoCo, then flip the matching hinge axis sign in models/irb120.xml until the training alignment error drops.
MuJoCo reports contacts on every step including upright smooth poses.
Verify the exclude pairs in the MJCF contact block cover adjacent links plus link2/link4 and link4/link6. Confirm capsule fromto endpoints sit clear of joint pivots and base_geom:workbench mounting contact is filtered.
The PyTorch MLP error is close to or worse than the Ridge baseline.
Verify inspect_data.py saved non-zero q_std values and that train_fk.py normalizes inputs before passing tensors to ForwardKinematicsMLP. Increasing EPOCHS to 120 or checking that xyz units were scaled consistently usually resolves underfitting.
rerun outputs/irb120_replay.rrd fails to open a native window on a headless or older GPU machine.
Launch the local browser viewer with rerun --web-viewer outputs/irb120_replay.rrd, which still respects rerun analytics disable. If port 9876 is busy, pass --port auto so Rerun picks a free local port.
PowerShell blocks .\.venv\Scripts\Activate.ps1 with an execution policy error.
Run Set-ExecutionPolicy -Scope CurrentUser RemoteSigned once in PowerShell, or invoke .\.venv\Scripts\python.exe directly without activating the shell wrapper.
Done when
- The PyTorch training script converges on CPU and prints root-mean-square position error across the 20 percent held-out IRB 120 split.
- MuJoCo replays all ten six-joint interpolated and perturbed trajectories without solver crashes and outputs a per-step contact summary CSV.
- A saved Rerun recording file opens locally and displays synchronized 3D six-joint motion beside residual error plots.
- Every trajectory step exceeding the 95th-percentile residual threshold or triggering a MuJoCo contact event is cross-referenced by step index in the exported anomaly log.
- Running the replay script twice on the same trajectory produces identical contact counts and position error metrics.
Deliverables
- Python project containing the PyTorch kinematics trainer paired with the MuJoCo six-joint replay and Rerun logging scripts, with required Kaggle dataset attribution in the README.
- Offline Rerun archive (.rrd) capturing all ten replayed six-joint trajectories with synchronized error plots and contact markers.
- Evaluation summary JSON and anomaly CSV detailing held-out position error plus all flagged trajectory step indices.
How to measure it
Report root-mean-square error and 95th-percentile Euclidean position error on the reserved fifth of IRB 120 records, checking whether the PyTorch regressor beats a ridge-regression baseline. Across the ten replayed trajectories, measure the fraction of steps flagged for joint-bound breaches or physical contacts and report mean agreement between high-residual model flags and MuJoCo physics checks.
Going further
- Encode each joint angle as
(sin(q), cos(q))(12 input features) and re-runsrc/evaluate_fk.pyto measure whether periodic features lower 95th-percentile wrist error. - Add a cylindrical fixture geom on the MuJoCo
workbenchand log minimum link-to-obstacle clearance distances as a newrr.Scalarsseries in Rerun. - Break down held-out residuals by octant of the IRB 120 workspace to see whether errors cluster near full reach or shoulder singularities.
- Profile CPU inference latency of
ForwardKinematicsMLPacrosstorch.set_num_threadssettings to check whether anomaly scoring fits inside a 500 Hz control tick.
Bounty stretch goals
- Train an inverse-kinematics PyTorch model that predicts all six joint angles from target coordinates and test whether MuJoCo reaches each pose without collision.
- Embed Rerun's browser viewer inside a small local HTML page with the explicit telemetry opt-out flag configured in code.
- Add synthetic Gaussian sensor noise to the six joint angles and measure how quickly position error degrades across five noise levels.
References
- Kaggle: Robot Kinematics Dataset (ABB IRB 120, CC BY 4.0)
- kagglehub README and Authentication Guide
- PyTorch README and License Overview
- scikit-learn Ridge Regression API Reference
- MuJoCo Python Bindings Documentation
- MuJoCo Modeling and MJCF Reference
- Rerun Python SDK Installation and Platform Requirements
- Rerun Python Quickstart (Points3D and LineStrips3D)
- Rerun Timelines and Sequence Indexing
- Rerun Sinks and FileSink Documentation
- Rerun Scalars Archetype Reference
- Rerun TextLog Archetype Reference
- Rerun CLI Reference (analytics and --web-viewer)
- Rerun 0.44 Changelog (Web Viewer Analytics Opt-Out)
Reporting behind this quest
- Rerun 0.44 puts a new telemetry choice in the web viewer 2026-11-26 · source
- Rerun keeps robot recordings on a shared timeline 2026-11-25 · source
- PyTorch gives experiments a programmable training loop 2026-11-25 · source
- MuJoCo makes contact dynamics available to a small experiment 2026-11-25 · source
An AI guide writer drafted this walkthrough against the official documentation above, automated template and style checks validated every block, and an independent AI reviewer verified commands, flags and claims before publication.
