Metadata-Version: 2.4
Name: armdoctor
Version: 0.1.0
Summary: Fault detection for MuJoCo-modelled robot arms: a self-test trajectory, residuals against a nominal twin, a health report (evaluated in simulation only)
Keywords: robotics,mujoco,fault-detection,diagnostics,digital-twin,robot-arm
Author: Sam Ko
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering
Requires-Dist: mjguard>=0.5.0
Requires-Dist: mujoco>=3.2
Requires-Dist: numpy>=2.0
Requires-Python: >=3.12
Project-URL: Repository, https://github.com/SamKo88927/armdoctor
Description-Content-Type: text/markdown

# armdoctor

armdoctor runs a short, safety-checked self-test on a robot arm and compares the reported joint positions and loads
with a nominal MuJoCo model of the arm. It reports whether the arm is healthy, which joint is affected, which of
five fault types is most likely, and how large the fault is.

> **Status: simulation only; not validated on hardware.** Every number in this repository comes from a synthetic
> plant (a perturbed MuJoCo model with sensor limits) checked against the nominal model. No real arm has been
> diagnosed with it yet. Treat the results as a statement about the method under stated assumptions, not about
> any real robot.

Full method, results and limitations: **[TECH_REPORT.md](TECH_REPORT.md)**.

armdoctor works with any MuJoCo arm that has position servos. [mjguard](https://pypi.org/project/mjguard/) checks
motions *before* they run; armdoctor looks at what happened *after* a known motion ran. It reuses mjguard's robot
configs and presets, and every self-test it generates must pass mjguard's checks.

## Results in simulation

Held-out test runs on two arms, the RoArm-M3 (5 joints, hobby servos) and the UR5e from MuJoCo Menagerie (6 joints).
The alarm threshold is set for 5% false alarms on 1000 healthy runs that were not used for fitting.

| | RoArm-M3 | UR5e |
|---|---|---|
| false alarms (2000 held-out healthy runs) | 4.7% (95% CI 3.9–5.7%) | 5.1% (4.2–6.1%) |
| fault type right / joint right (detected single faults) | 96.5% / 98.2% | 92.0% / 97.8% |
| payload, smallest reliably detected | ≤ 0.02 kg | 0.25 kg |
| zero offset | 1° on the shoulder; not seen on wrists or vertical axes | 1° on shoulder_lift; same limits |
| friction | ×2 to ×3 on 4 of 5 joints; not the shoulder | ×2 on all joints (assumed nominal friction) |
| weak gain | ×0.8 to ×0.9 | ×0.9 |
| backlash | 0.1° to 0.5° | 0.1° to 0.25° |
| magnitude error midway between training values, median (payload / backlash) | 0.003 kg / 0.05° | 0.02 kg / 0.03° |
| two simultaneous faults | always detected, one of the two named | always detected, one named in 98.8% |

![Detection vs false alarms](docs/figures/roc.png)

## Install

From a checkout (Python ≥ 3.12, [uv](https://docs.astral.sh/uv/)):

    uv sync

## Quickstart: a simulated demo on the UR5e

    uv run armdoctor robots                                    # bundled robots + mjguard presets
    uv run armdoctor selftest --robot ur5e -o selftest.json    # refuses to write a test mjguard rejects
    uv run armdoctor baseline --robot ur5e --selftest selftest.json --simulate 60 --classifier -o baseline.json
    uv run armdoctor simulate --robot ur5e --selftest selftest.json --seed 7 --fault friction:elbow_joint:2.5 -o ep.json
    uv run armdoctor check ep.json --robot ur5e --baseline baseline.json -o report   # report.json + report.html

The `simulate` step stands in for a real arm. It draws a synthetic episode from the perturbed plant. Repeat
`--fault` to inject several faults at once. `bash scripts/demo.sh` runs the whole chain on the RoArm-M3 and the
UR5e: one healthy and five faulty episodes each. Reports are written to `out/demo/<robot>/report_*.html`.

With recorded episodes of a real arm, fit the baseline from two disjoint sets of healthy runs. Use hundreds of
threshold runs if you can: with tens, the realised false-alarm rate varies by several points.

    uv run armdoctor baseline --robot ur5e --selftest selftest.json \
        --healthy fit/*.json --threshold-runs thr/*.json -o baseline.json

## What it does

1. **Self-test** (`armdoctor selftest`) generates a joint trajectory for your robot in two parts:
   - Eight dwell poses. They are chosen so that gravity loads separate a zero offset on each joint from link-mass
     and payload errors.
   - Then a slow sweep of each joint with two reversals, so that friction shows as a load step between the two
     directions.

   Every waypoint passes mjguard and stays within its step and speed limits. `armdoctor verify` re-checks a
   stored test.
2. **Baseline** (`armdoctor baseline`) learns what healthy looks like:
   - Healthy runs fix the normal spread of every residual feature.
   - A disjoint set of healthy runs sets the alarm threshold. It uses the ⌈(n+1)(1−α)⌉-th smallest score, a
     split-conformal rule.
   - Optionally, a k-nearest-neighbour classifier and continuous magnitude maps are trained on simulated faults.
3. **Check** (`armdoctor check`) takes one episode and writes a health report (JSON and a self-contained HTML
   page). The report contains:
   - an anomaly score and the status of each joint;
   - the features that moved;
   - physical estimates of zero offset (deg), sweep friction (N·m) and payload (kg);
   - the most likely fault, with its magnitude and the feature that magnitude was read from;
   - the nearest labelled examples, so the answer can be checked.

Fault types modelled: payload at the tool, encoder zero offset, joint friction, weak position gain, backlash.

**Robots.** `--robot` takes any of these:

- a bundled robot (`roarm_m3`);
- an mjguard preset (`ur5e`, `panda`, `fr3`, ...). Menagerie models are downloaded by `robot_descriptions` on
  first use;
- an mjguard TOML config;
- a bare MJCF file. In that case the arm joints are the hinge joints with position actuators, and the floor is the
  first plane geom.

An optional `[armdoctor.plant]` table in the TOML sets simulation-only plant options.

**Episode format** (`armdoctor-episode/1`, JSON):

- `planned` waypoints, `period_s`, `start`;
- `measured` rows `[t, q...]`;
- optional `loads` rows `[t, l...]`, in any consistent unit.

roarm-mcp episode files are accepted as well. An episode must come from the same self-test as the baseline;
armdoctor checks this by fingerprint and waypoints. Without loads, only position features are used, and the
report says so.

## Limitations (short version)

- **Simulation only.** Plant and twin share the MJCF geometry. The sensor, friction, backlash and gain-loss models
  are assumptions, not measurements of real servos.
- **Some faults cannot be seen with this test.** A zero offset on a vertical-axis joint changes no gravity load.
  Wrist offsets are below the load noise.
- **The classifier is trained on simulated single faults.** With two faults it names only one.
- **The false-alarm rate depends on the healthy population.** On a real arm it must be re-measured on that arm's
  own healthy runs.

See [TECH_REPORT.md](TECH_REPORT.md), Section 5.

## Development

    uv run pytest                 # fast tests (~1 min); `-m slow` for long sweeps
    uv run ruff check . && uv run ruff format --check .
    uv run pyright                # strict mode on src/
    uv run python scripts/run_study.py --robot roarm_m3   # the study behind TECH_REPORT.md (see its Section 6)

`src/armdoctor/robots/roarm_m3.xml` is generated from roarm-mcp's primitive RoArm-M3 model (Apache-2.0).

## License

Apache-2.0. See [LICENSE](LICENSE).
