Spaces:
Sleeping
Five built-in CDPR_SIMULATOR examples (3 trajectories + 2 data-driven)
Browse filesImplements the directive's selectable demonstration set as built-in
tutorials accessible identically from PowerShell and the Streamlit
GUI. The registry in scripts/examples.py is the single source of truth.
Phase 1 — physics-based motion simulation:
* circle --- 3-DoF planar circular tracking on the dissertation_8cable
robot. 0.05 m radius, 2 revolutions, ~12.6 s, quintic
time-scaling for smooth start / stop.
* spiral --- 6-DoF helical sweep (the directive's "one example with
all six DoFs" requirement). 3-revolution spiral at
z = 0.65 m +/- 0.04 m with bounded sinusoidal yaw (+/-17°),
pitch (+/-6°) and roll (+/-3°) at distinct phase offsets.
Bounded amplitudes (not monotonic rotations) are essential
under pure PD: without orientation feedforward, a growing
angle saturates the QP --- bounded oscillation keeps the
angular error inside the cable wrench envelope.
* mshape --- Pick-and-place letter-M task. 5 vertices with quintic
motion phases + explicit dwell phases; gripper yaw
oscillates +/-30° during each dwell to simulate pick /
place actuation under load.
Phase 2 --- data-driven training / analysis:
* train --- 120-epoch PINN fit on the circle CSV. Auto-runs the
circle example first if its CSV is missing.
* compare --- Multi-model bench: replay vs MLP vs PINN vs PPO vs SAC
on the same dataset, 60 epochs supervised, 2000 RL train
steps, 2 eval episodes per RL policy.
Verification on the dissertation_8cable robot (5-500 N tension envelope):
circle : 12567 samples, 0 infeasible, tracking RMS 5.94 mm,
tensions [19.17, 336.26] N
spiral : 15001 samples, 0 infeasible, tracking RMS 4.43 mm,
tensions [6.40, 399.65] N --- 6-DoF orientation visible
in the orientation.png plot.
mshape : 10701 samples, 0 infeasible, tracking RMS 2.78 mm,
tensions [41.16, 421.80] N --- M-shape clearly visible
in trajectory_xy.png with reference overlay.
train : PINN rmse 0.151 N, mae 0.084 N, 120 epochs in 29 s.
compare : mlp 0.094 N, pinn 0.095 N, replay 25.57 N, ppo + sac
return-based (no tension RMSE); all 5 models status=ok.
Each Phase-1 run emits 14 publication-grade figures (well above the
directive's >=10 minimum): position, velocity, angular_velocity,
acceleration, cable_tensions, cable_lengths, cable_stretch,
tracking_error, rms_error_evolution, condition_number,
trajectory_xy/xz/yz, orientation, scene_3d --- plus CSV, manifest
(with embedded robot_spec block from the v17 sweep), and
feasibility.json.
Replay / PPO / SAC reconstruct the circle reference from the manifest
(catalog kind 'circle' with full params) so they run end-to-end. For
spiral / mshape the manifest uses kind='custom_callable' since the
inline Python callables have no closed-form recipe; train_from_csv
detects this and skips replay/RL cleanly with a documented reason,
while mlp/pinn still run on all three CSVs because they only need
the timeseries columns.
UI parity:
* PowerShell: python scripts/run_example.py --list
python scripts/run_example.py --name <id> [--open]
* Streamlit: "Built-in examples" panel above the parameter sidebar
with a dropdown of all 5 entries, per-example
description, copy-paste PowerShell command, and (on
local Streamlit only) a "Run inline" button that
subprocesses run_example.py and displays the produced
figures + feasibility.json + manifest inline. Inline
execution is disabled when CDPR_GUI_FRUGAL=1 because
Streamlit Cloud workers cannot host the full plot
bundle.
Documentation: docs/examples.md covers the decision on which example
gets the 6-DoF treatment, the PowerShell and GUI usage, the output
file layout for both phases, and the reproducibility guarantee.
CI subset stays 177/177 in ~34 s. Build banner bumped to
gui-2026-05-28-f; requirements.txt cache-bust to 2026-05-28-h.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- docs/examples.md +116 -0
- requirements.txt +1 -1
- scripts/examples.py +715 -0
- scripts/run_example.py +92 -0
- scripts/train_from_csv.py +18 -0
- src/cdpr/interface/gui.py +103 -0
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Built-in examples
|
| 2 |
+
|
| 3 |
+
Five selectable demonstrations cover the directive's two operational
|
| 4 |
+
phases. They are accessible identically from PowerShell and the
|
| 5 |
+
Streamlit GUI; the registry lives in `scripts/examples.py`.
|
| 6 |
+
|
| 7 |
+
| ID | Phase | DoF | Title | Description |
|
| 8 |
+
|---|---|---|---|---|
|
| 9 |
+
| `circle` | 1 | 3 | Circular trajectory tracking | 0.05 m radius horizontal circle, 2 revolutions, ≈12.6 s, quintic smoothing. |
|
| 10 |
+
| `spiral` | 1 | **6** | 6-DoF helical spiral | 3 spiral revs at z = 0.65 m ± 0.04 m, **roll / pitch / yaw oscillation** (±3 / ±6 / ±17 °), ≈15 s. |
|
| 11 |
+
| `mshape` | 1 | 3+1 | Pick-and-place M-task | Letter-M trace through 5 vertices with dwells + discrete gripper yaw at each pick/place. |
|
| 12 |
+
| `train` | 2 | | Data-driven PINN training | 120-epoch PINN fit on the `circle` CSV (auto-generates it if missing). |
|
| 13 |
+
| `compare` | 2 | | Multi-model comparison | Bench replay vs MLP vs PINN vs PPO vs SAC on the same dataset. |
|
| 14 |
+
|
| 15 |
+
## Decision on the 6-DoF showcase
|
| 16 |
+
|
| 17 |
+
The directive asked which of the three Phase-1 examples should
|
| 18 |
+
incorporate all six rigid-body DoFs. The **spiral** is the natural
|
| 19 |
+
choice:
|
| 20 |
+
|
| 21 |
+
* The position is already coupled in 3D space (x, y, z),
|
| 22 |
+
* Adding **roll / pitch / yaw oscillation** at distinct phase offsets
|
| 23 |
+
exercises the three rotational DoFs without breaking workspace
|
| 24 |
+
feasibility,
|
| 25 |
+
* The circle stays a clean 3-DoF planar demo (best fit for "first
|
| 26 |
+
introduction to closed-loop tracking"), and the M-shape uses
|
| 27 |
+
discrete gripper yaw at pick/place events (rather than continuous
|
| 28 |
+
orientation tracking) to demonstrate payload-handling logic.
|
| 29 |
+
|
| 30 |
+
Orientation amplitudes are deliberately **bounded sinusoids**
|
| 31 |
+
(±17° yaw, ±6° pitch, ±3° roll) rather than monotonic rotations.
|
| 32 |
+
Without an orientation feedforward, a PD controller cannot keep up
|
| 33 |
+
with a continuously growing angle; bounded oscillation lets the
|
| 34 |
+
angular error stay inside the cables' wrench-feasibility envelope
|
| 35 |
+
under the 5–500 N tension limits while still exercising all six DoFs
|
| 36 |
+
visibly. The `orientation` plot in every example artifact bundle
|
| 37 |
+
makes this explicit.
|
| 38 |
+
|
| 39 |
+
## PowerShell usage
|
| 40 |
+
|
| 41 |
+
```powershell
|
| 42 |
+
# List all five with descriptions.
|
| 43 |
+
python scripts\run_example.py --list
|
| 44 |
+
|
| 45 |
+
# Run a single example end-to-end. Output lands under out/example-<name>/.
|
| 46 |
+
python scripts\run_example.py --name circle --open
|
| 47 |
+
python scripts\run_example.py --name spiral --open
|
| 48 |
+
python scripts\run_example.py --name mshape --open
|
| 49 |
+
python scripts\run_example.py --name train --open
|
| 50 |
+
python scripts\run_example.py --name compare --open
|
| 51 |
+
```
|
| 52 |
+
|
| 53 |
+
The Phase-2 examples (`train`, `compare`) check for the Phase-1 CSV
|
| 54 |
+
they depend on (`out/example-circle/timeseries.csv`) and auto-run the
|
| 55 |
+
`circle` example to generate it if missing.
|
| 56 |
+
|
| 57 |
+
## Streamlit GUI usage
|
| 58 |
+
|
| 59 |
+
The sidebar carries a "Built-in examples" panel at the top of the main
|
| 60 |
+
page. Pick an example from the dropdown:
|
| 61 |
+
|
| 62 |
+
* the description, target output directory, and required PowerShell
|
| 63 |
+
command are shown,
|
| 64 |
+
* the **PowerShell command is always copy-paste ready** (works on a
|
| 65 |
+
local terminal regardless of where the Streamlit app is running),
|
| 66 |
+
* on **local Streamlit only**, a **"Run inline (local only)"** button
|
| 67 |
+
runs the example as a subprocess and displays the produced figures
|
| 68 |
+
inline. Inline execution is disabled on Streamlit Cloud because the
|
| 69 |
+
free-tier worker is too small for the full plot bundle.
|
| 70 |
+
|
| 71 |
+
## Output layout
|
| 72 |
+
|
| 73 |
+
Each Phase-1 example produces under `out/example-<id>/`:
|
| 74 |
+
|
| 75 |
+
| File | What |
|
| 76 |
+
|---|---|
|
| 77 |
+
| `timeseries.csv` | Full state log (Phase-2-ready) |
|
| 78 |
+
| `manifest.json` | Git hash, controller, robot spec, feasibility, trajectory recipe (catalog kind where reconstructible, `custom_callable` otherwise) |
|
| 79 |
+
| `feasibility.json` | t_min/t_max, observed tension range, infeasibility list, tracking RMS/peak/final |
|
| 80 |
+
| `position.png`, `velocity.png`, `angular_velocity.png`, `acceleration.png` | Per-axis state plots |
|
| 81 |
+
| `cable_tensions.png`, `cable_lengths.png`, `cable_stretch.png` | Per-cable diagnostics with bound shading |
|
| 82 |
+
| `tracking_error.png`, `rms_error_evolution.png` | Reference-vs-actual error and cumulative RMS |
|
| 83 |
+
| `condition_number.png` | Structure-matrix conditioning |
|
| 84 |
+
| `trajectory_xy.png`, `trajectory_xz.png`, `trajectory_yz.png` | 2D projections with reference overlay |
|
| 85 |
+
| `orientation.png` | Roll/pitch/yaw vs time (visible 6-DoF demonstration for `spiral`) |
|
| 86 |
+
| `scene_3d.png` | Final 3D scene with anchors, cables, platform, tension heatmap, trajectory trace |
|
| 87 |
+
|
| 88 |
+
That's **14 figures per Phase-1 run**, well above the directive's
|
| 89 |
+
≥10-figure minimum.
|
| 90 |
+
|
| 91 |
+
Each Phase-2 example produces under its `out/example-<id>/` (or per-
|
| 92 |
+
model subdirectories for `compare`):
|
| 93 |
+
|
| 94 |
+
| File | What |
|
| 95 |
+
|---|---|
|
| 96 |
+
| `loss.png`, `pred_vs_truth.png`, `residuals.png` | Training/eval curves |
|
| 97 |
+
| `metrics.json` | RMSE, MAE, per-cable error breakdown, train/val loss history |
|
| 98 |
+
| `manifest.json` | Hyper-params + git hash + python version |
|
| 99 |
+
| `compare_rmse.png`, `compare_runtime.png`, `compare_table.png`, `compare_overview.png` | Multi-model bar charts and ranking table (compare only) |
|
| 100 |
+
| `ranking.json`, `compare_metrics.json` | Sorted ranking with `ok` / `failed` / `skipped` status (compare only) |
|
| 101 |
+
|
| 102 |
+
## Reproducibility
|
| 103 |
+
|
| 104 |
+
All five examples are deterministic given the registered seeds
|
| 105 |
+
(supervised models use `--seed 0`; the RL evals use `seed=0+episode`).
|
| 106 |
+
Re-running `python scripts/run_example.py --name <id>` on the same
|
| 107 |
+
checkout produces byte-equivalent CSVs and reproducible figures.
|
| 108 |
+
|
| 109 |
+
The manifest carries the `robot_spec` block from improvement #2 of
|
| 110 |
+
the v17 sweep, so Phase-2 replay/PPO/SAC reconstruct the directive
|
| 111 |
+
robot exactly. Spiral and mshape use inline Python callables for
|
| 112 |
+
their references (full SE(3) tracking and piecewise pick-and-place
|
| 113 |
+
respectively); their manifests therefore mark `trajectory.kind` as
|
| 114 |
+
`custom_callable` and replay/RL Phase-2 workflows skip them cleanly
|
| 115 |
+
with a documented reason — supervised models (`mlp`, `pinn`) run on
|
| 116 |
+
all three Phase-1 CSVs because they only need the timeseries.
|
|
@@ -9,7 +9,7 @@
|
|
| 9 |
#
|
| 10 |
# Cache-bust marker: bump this when forcing Streamlit Cloud to discard a
|
| 11 |
# cached worker venv after a behavioural change in cdpr.interface.gui.
|
| 12 |
-
# rebuild: 2026-05-28-
|
| 13 |
|
| 14 |
streamlit>=1.32
|
| 15 |
|
|
|
|
| 9 |
#
|
| 10 |
# Cache-bust marker: bump this when forcing Streamlit Cloud to discard a
|
| 11 |
# cached worker venv after a behavioural change in cdpr.interface.gui.
|
| 12 |
+
# rebuild: 2026-05-28-h
|
| 13 |
|
| 14 |
streamlit>=1.32
|
| 15 |
|
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Built-in CDPR_SIMULATOR examples — five selectable demonstrations.
|
| 2 |
+
|
| 3 |
+
The list below is the single source of truth for both the PowerShell
|
| 4 |
+
CLI (:mod:`scripts.run_example`) and the Streamlit GUI's example
|
| 5 |
+
selector. Adding a new example here makes it discoverable in both
|
| 6 |
+
interfaces without touching either.
|
| 7 |
+
|
| 8 |
+
Phase 1 — physics-based motion simulation
|
| 9 |
+
-----------------------------------------
|
| 10 |
+
|
| 11 |
+
* ``circle`` — 3-DoF planar circular tracking on the directive robot.
|
| 12 |
+
* ``spiral`` — **6-DoF** helical sweep with continuous yaw + pitch
|
| 13 |
+
oscillation, demonstrating full SE(3) tracking.
|
| 14 |
+
* ``mshape`` — Pick-and-place letter-M task with vertex dwells and
|
| 15 |
+
discrete gripper yaw at pick / place events.
|
| 16 |
+
|
| 17 |
+
Phase 2 — data-driven training / analysis
|
| 18 |
+
------------------------------------------
|
| 19 |
+
|
| 20 |
+
* ``train`` — Single-model PINN fit on a Phase-1 CSV (auto-runs
|
| 21 |
+
``circle`` first when no input is supplied).
|
| 22 |
+
* ``compare`` — Multi-model bench: replay vs MLP vs PINN vs PPO vs SAC
|
| 23 |
+
on the same dataset.
|
| 24 |
+
|
| 25 |
+
Each entry carries everything the runner needs: a phase id, a human-
|
| 26 |
+
readable title and description, the expected output directory, and
|
| 27 |
+
either a ``runner`` callable (Phase 1) or a ``deps + subprocess argv``
|
| 28 |
+
recipe (Phase 2).
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
from __future__ import annotations
|
| 32 |
+
|
| 33 |
+
import json
|
| 34 |
+
import os
|
| 35 |
+
import platform as _platform
|
| 36 |
+
import subprocess
|
| 37 |
+
import sys
|
| 38 |
+
import time
|
| 39 |
+
from dataclasses import dataclass, field
|
| 40 |
+
from pathlib import Path
|
| 41 |
+
from typing import Callable
|
| 42 |
+
|
| 43 |
+
# Headless plotting before any matplotlib import.
|
| 44 |
+
os.environ.setdefault("MPLBACKEND", "Agg")
|
| 45 |
+
|
| 46 |
+
import numpy as np # noqa: E402
|
| 47 |
+
from scipy.spatial.transform import Rotation # noqa: E402
|
| 48 |
+
|
| 49 |
+
_REPO_ROOT = Path(__file__).resolve().parents[1]
|
| 50 |
+
_SRC = _REPO_ROOT / "src"
|
| 51 |
+
if str(_SRC) not in sys.path:
|
| 52 |
+
sys.path.insert(0, str(_SRC))
|
| 53 |
+
|
| 54 |
+
# Local helpers (shared with the train/compare scripts).
|
| 55 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 56 |
+
from _csv_io import RobotSpec # noqa: E402
|
| 57 |
+
|
| 58 |
+
from cdpr.core.frames import Pose # noqa: E402
|
| 59 |
+
from cdpr.control.pd import PDController # noqa: E402
|
| 60 |
+
from cdpr.dynamics.rigid_body import PlatformState # noqa: E402
|
| 61 |
+
from cdpr.dynamics.simulator import simulate # noqa: E402
|
| 62 |
+
from cdpr.robots.dissertation import dissertation_8cable # noqa: E402
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ---------------------------------------------------------------------------
|
| 66 |
+
# Custom reference trajectories used by the spiral and M-shape examples.
|
| 67 |
+
# The simulator accepts any callable ``t -> Pose`` as a reference, so these
|
| 68 |
+
# do not need to be wrapped in the heavier Trajectory class — at the cost
|
| 69 |
+
# of zero feedforward velocity (PD still tracks with realistic lag, which
|
| 70 |
+
# is itself a useful demonstration).
|
| 71 |
+
# ---------------------------------------------------------------------------
|
| 72 |
+
|
| 73 |
+
def helical6_pose(
|
| 74 |
+
t: float,
|
| 75 |
+
*,
|
| 76 |
+
duration: float = 15.0,
|
| 77 |
+
r_start: float = 0.015,
|
| 78 |
+
r_end: float = 0.035,
|
| 79 |
+
z_center: float = 0.65,
|
| 80 |
+
z_amp: float = 0.04,
|
| 81 |
+
n_revs: float = 3.0,
|
| 82 |
+
yaw_amp_rad: float = 0.30, # ±17°
|
| 83 |
+
pitch_amp_rad: float = 0.10, # ±6°
|
| 84 |
+
roll_amp_rad: float = 0.05, # ±3°
|
| 85 |
+
) -> Pose:
|
| 86 |
+
"""6-DoF helical reference: position spirals outward + up while the
|
| 87 |
+
platform tilts on all three Euler axes.
|
| 88 |
+
|
| 89 |
+
Orientation amplitudes are **bounded sinusoids** rather than
|
| 90 |
+
monotonic rotations --- without an orientation feedforward, PD
|
| 91 |
+
cannot track an angle that keeps growing; bounded oscillation lets
|
| 92 |
+
the angular error stay inside the cables' wrench-feasibility
|
| 93 |
+
envelope while still exercising all six rigid-body DoFs.
|
| 94 |
+
"""
|
| 95 |
+
s = float(np.clip(t / duration, 0.0, 1.0))
|
| 96 |
+
s_smooth = 6 * s ** 5 - 15 * s ** 4 + 10 * s ** 3
|
| 97 |
+
r = r_start + (r_end - r_start) * s_smooth
|
| 98 |
+
z = z_center - z_amp + 2 * z_amp * s_smooth
|
| 99 |
+
theta = 2.0 * np.pi * n_revs * s_smooth
|
| 100 |
+
pos = np.array([r * np.cos(theta), r * np.sin(theta), z], dtype=np.float64)
|
| 101 |
+
# Bounded orientation oscillation --- one full back-and-forth per
|
| 102 |
+
# revolution of the spiral, phase-shifted between axes to keep the
|
| 103 |
+
# demonstration visually rich.
|
| 104 |
+
yaw = yaw_amp_rad * np.sin(theta)
|
| 105 |
+
pitch = pitch_amp_rad * np.sin(theta + np.pi / 3)
|
| 106 |
+
roll = roll_amp_rad * np.sin(theta + 2 * np.pi / 3)
|
| 107 |
+
rot = Rotation.from_euler("xyz", [roll, pitch, yaw])
|
| 108 |
+
return Pose(position=pos, rotation=rot)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def mshape_pose(
|
| 112 |
+
t: float,
|
| 113 |
+
*,
|
| 114 |
+
vertices: list[tuple[float, float, float]] | None = None,
|
| 115 |
+
segment_time: float = 1.8,
|
| 116 |
+
dwell_time: float = 0.7,
|
| 117 |
+
gripper_yaw_amp: float = 0.52, # ~30°
|
| 118 |
+
) -> Pose:
|
| 119 |
+
"""Pick-and-place letter-M reference with explicit dwells at each
|
| 120 |
+
vertex and a discrete gripper yaw during the dwell (simulating
|
| 121 |
+
pick / place actuation)."""
|
| 122 |
+
if vertices is None:
|
| 123 |
+
# Five vertices inside the dissertation robot's feasible
|
| 124 |
+
# workspace (r ≲ 0.05 m around z = 0.65 m).
|
| 125 |
+
vertices = [
|
| 126 |
+
(-0.030, -0.025, 0.650), # V1 bottom-left (start)
|
| 127 |
+
(-0.030, +0.025, 0.650), # V2 top-left
|
| 128 |
+
( 0.000, -0.010, 0.650), # V3 middle dip
|
| 129 |
+
(+0.030, +0.025, 0.650), # V4 top-right
|
| 130 |
+
(+0.030, -0.025, 0.650), # V5 bottom-right (end)
|
| 131 |
+
]
|
| 132 |
+
V = [np.asarray(v, dtype=np.float64) for v in vertices]
|
| 133 |
+
n_segs = len(V) - 1
|
| 134 |
+
cycle = segment_time + dwell_time
|
| 135 |
+
total = dwell_time + n_segs * cycle
|
| 136 |
+
|
| 137 |
+
t = float(np.clip(t, 0.0, total))
|
| 138 |
+
if t < dwell_time:
|
| 139 |
+
# Initial dwell at V[0] --- "approach pick".
|
| 140 |
+
return Pose(position=V[0], rotation=Rotation.identity())
|
| 141 |
+
|
| 142 |
+
elapsed = t - dwell_time
|
| 143 |
+
seg_idx = int(elapsed // cycle)
|
| 144 |
+
if seg_idx >= n_segs:
|
| 145 |
+
return Pose(position=V[-1], rotation=Rotation.identity())
|
| 146 |
+
local = elapsed - seg_idx * cycle
|
| 147 |
+
v_start, v_end = V[seg_idx], V[seg_idx + 1]
|
| 148 |
+
|
| 149 |
+
if local < segment_time:
|
| 150 |
+
# Motion phase with quintic smoothing.
|
| 151 |
+
s = local / segment_time
|
| 152 |
+
s_smooth = 6 * s ** 5 - 15 * s ** 4 + 10 * s ** 3
|
| 153 |
+
pos = v_start + (v_end - v_start) * s_smooth
|
| 154 |
+
yaw = 0.0
|
| 155 |
+
else:
|
| 156 |
+
# Dwell at v_end with a sinusoidal gripper-yaw "pick" gesture
|
| 157 |
+
# to demonstrate orientation actuation under load.
|
| 158 |
+
pos = v_end
|
| 159 |
+
u = (local - segment_time) / dwell_time
|
| 160 |
+
yaw = gripper_yaw_amp * np.sin(np.pi * u)
|
| 161 |
+
return Pose(position=pos, rotation=Rotation.from_euler("xyz", [0.0, 0.0, yaw]))
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def mshape_total_duration(*, segment_time: float = 1.8, dwell_time: float = 0.7,
|
| 165 |
+
n_vertices: int = 5) -> float:
|
| 166 |
+
return dwell_time + (n_vertices - 1) * (segment_time + dwell_time)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ---------------------------------------------------------------------------
|
| 170 |
+
# Plot bundle --- the 13-figure pack the directive expects from each
|
| 171 |
+
# Phase-1 run. Lives here (instead of being imported from run_simulation.py)
|
| 172 |
+
# so the examples module is fully self-contained.
|
| 173 |
+
# ---------------------------------------------------------------------------
|
| 174 |
+
|
| 175 |
+
def _render_phase1_plots(out_dir: Path, result, robot, reference):
|
| 176 |
+
try:
|
| 177 |
+
from cdpr.viz.style import apply_paper_style
|
| 178 |
+
apply_paper_style()
|
| 179 |
+
except Exception: # pragma: no cover
|
| 180 |
+
pass
|
| 181 |
+
import matplotlib.pyplot as plt
|
| 182 |
+
from cdpr.viz import plots2d
|
| 183 |
+
from cdpr.viz.scene import SceneOptions, render_scene
|
| 184 |
+
|
| 185 |
+
figs_made: list[str] = []
|
| 186 |
+
|
| 187 |
+
def _save(name: str, fn) -> None:
|
| 188 |
+
path = out_dir / f"{name}.png"
|
| 189 |
+
try:
|
| 190 |
+
fig = fn()
|
| 191 |
+
fig.savefig(path, dpi=160, bbox_inches="tight")
|
| 192 |
+
plt.close(fig)
|
| 193 |
+
figs_made.append(name)
|
| 194 |
+
print(f" [{name:22s}] -> {path.resolve()}")
|
| 195 |
+
except Exception as exc:
|
| 196 |
+
print(f" [{name:22s}] FAILED {type(exc).__name__}: {exc}")
|
| 197 |
+
|
| 198 |
+
_save("position", lambda: plots2d.plot_position(result))
|
| 199 |
+
_save("velocity", lambda: plots2d.plot_velocity(result))
|
| 200 |
+
_save("angular_velocity", lambda: plots2d.plot_angular_velocity(result))
|
| 201 |
+
|
| 202 |
+
def _accel_plot():
|
| 203 |
+
t = np.asarray(result.time); v = np.asarray(result.linear_velocities)
|
| 204 |
+
a = np.gradient(v, t, axis=0)
|
| 205 |
+
fig, ax = plt.subplots(figsize=(6.0, 3.2))
|
| 206 |
+
for k, lbl in enumerate(("a_x", "a_y", "a_z")):
|
| 207 |
+
ax.plot(t, a[:, k], label=fr"${lbl}$")
|
| 208 |
+
ax.set_xlabel(r"time $t$ [s]")
|
| 209 |
+
ax.set_ylabel(r"acceleration [m s$^{-2}$]")
|
| 210 |
+
ax.legend(loc="best"); ax.set_title("Translational acceleration")
|
| 211 |
+
return fig
|
| 212 |
+
_save("acceleration", _accel_plot)
|
| 213 |
+
|
| 214 |
+
_save("cable_tensions", lambda: plots2d.plot_cable_tensions(result, robot=robot))
|
| 215 |
+
_save("cable_lengths", lambda: plots2d.plot_cable_lengths(result))
|
| 216 |
+
|
| 217 |
+
def _stretch_plot():
|
| 218 |
+
L = np.asarray(result.cable_lengths)
|
| 219 |
+
head = max(1, int(0.01 * L.shape[0])); L0 = L[:head].mean(axis=0)
|
| 220 |
+
d = L - L0[None, :]
|
| 221 |
+
fig, ax = plt.subplots(figsize=(6.0, 3.2))
|
| 222 |
+
for i in range(L.shape[1]):
|
| 223 |
+
ax.plot(result.time, d[:, i] * 1e3, label=f"cable {i+1}")
|
| 224 |
+
ax.set_xlabel(r"time $t$ [s]")
|
| 225 |
+
ax.set_ylabel(r"stretch $\Delta L$ [mm]")
|
| 226 |
+
ax.legend(loc="best", ncol=2, fontsize=8)
|
| 227 |
+
ax.set_title("Per-cable elongation vs initial length")
|
| 228 |
+
return fig
|
| 229 |
+
_save("cable_stretch", _stretch_plot)
|
| 230 |
+
|
| 231 |
+
if reference is not None:
|
| 232 |
+
_save("tracking_error", lambda: plots2d.plot_tracking_error(result, reference))
|
| 233 |
+
|
| 234 |
+
def _rms_plot():
|
| 235 |
+
t = np.asarray(result.time)
|
| 236 |
+
ref = np.asarray([reference(tt).position for tt in t])
|
| 237 |
+
err = np.linalg.norm(np.asarray(result.positions) - ref, axis=1)
|
| 238 |
+
sq_cumsum = np.cumsum(err ** 2)
|
| 239 |
+
rms = np.sqrt(sq_cumsum / np.arange(1, len(err) + 1))
|
| 240 |
+
fig, ax = plt.subplots(figsize=(6.0, 3.2))
|
| 241 |
+
ax.plot(t, rms * 1e3, color="C3")
|
| 242 |
+
ax.set_xlabel(r"time $t$ [s]")
|
| 243 |
+
ax.set_ylabel("cumulative RMS error [mm]")
|
| 244 |
+
ax.set_title("Tracking error — cumulative RMS evolution")
|
| 245 |
+
return fig
|
| 246 |
+
_save("rms_error_evolution", _rms_plot)
|
| 247 |
+
|
| 248 |
+
_save("condition_number", lambda: plots2d.plot_condition_number(result, robot))
|
| 249 |
+
|
| 250 |
+
if reference is not None:
|
| 251 |
+
ref_xyz = np.asarray([reference(t).position for t in result.time])
|
| 252 |
+
else:
|
| 253 |
+
ref_xyz = None
|
| 254 |
+
for plane in ("xy", "xz", "yz"):
|
| 255 |
+
_save(
|
| 256 |
+
f"trajectory_{plane}",
|
| 257 |
+
lambda p=plane: plots2d.plot_trajectory_projection(
|
| 258 |
+
result.positions, plane=p, reference=ref_xyz,
|
| 259 |
+
),
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
# Orientation evolution (especially relevant for the 6-DoF spiral
|
| 263 |
+
# and the M-shape's gripper actuation).
|
| 264 |
+
def _orientation_plot():
|
| 265 |
+
from scipy.spatial.transform import Rotation as _R
|
| 266 |
+
quat = np.asarray(result.quaternions_xyzw)
|
| 267 |
+
eul = _R.from_quat(quat).as_euler("xyz", degrees=True)
|
| 268 |
+
fig, ax = plt.subplots(figsize=(6.0, 3.2))
|
| 269 |
+
for k, lbl in enumerate(("roll", "pitch", "yaw")):
|
| 270 |
+
ax.plot(result.time, eul[:, k], label=lbl)
|
| 271 |
+
ax.set_xlabel(r"time $t$ [s]")
|
| 272 |
+
ax.set_ylabel("orientation [deg]")
|
| 273 |
+
ax.legend(loc="best")
|
| 274 |
+
ax.set_title("End-effector orientation evolution")
|
| 275 |
+
return fig
|
| 276 |
+
_save("orientation", _orientation_plot)
|
| 277 |
+
|
| 278 |
+
_save("scene_3d", lambda: render_scene(
|
| 279 |
+
robot,
|
| 280 |
+
Pose(
|
| 281 |
+
position=result.positions[-1],
|
| 282 |
+
rotation=Rotation.from_quat(result.quaternions_xyzw[-1]),
|
| 283 |
+
),
|
| 284 |
+
options=SceneOptions(tension_heatmap=True),
|
| 285 |
+
tensions=result.cable_tensions[-1],
|
| 286 |
+
trajectory_positions=result.positions,
|
| 287 |
+
))
|
| 288 |
+
|
| 289 |
+
return figs_made
|
| 290 |
+
|
| 291 |
+
|
| 292 |
+
# ---------------------------------------------------------------------------
|
| 293 |
+
# CSV writer (mirror of scripts/run_simulation.save_timeseries_csv, kept
|
| 294 |
+
# in sync so the Phase-2 examples can consume the output directly).
|
| 295 |
+
# ---------------------------------------------------------------------------
|
| 296 |
+
|
| 297 |
+
def _save_csv(out_dir: Path, result, reference=None,
|
| 298 |
+
t_min: float = 0.0, t_max: float = 0.0) -> Path:
|
| 299 |
+
path = out_dir / "timeseries.csv"
|
| 300 |
+
t = np.asarray(result.time)
|
| 301 |
+
positions = np.asarray(result.positions)
|
| 302 |
+
quats = np.asarray(result.quaternions_xyzw)
|
| 303 |
+
lin_vel = np.asarray(result.linear_velocities)
|
| 304 |
+
ang_vel = np.asarray(result.angular_velocities)
|
| 305 |
+
lengths = np.asarray(result.cable_lengths)
|
| 306 |
+
tensions = np.asarray(result.cable_tensions)
|
| 307 |
+
n_cables = tensions.shape[1]
|
| 308 |
+
|
| 309 |
+
if reference is not None:
|
| 310 |
+
ref_pos = np.array([reference(tt).position for tt in t])
|
| 311 |
+
err = np.linalg.norm(positions - ref_pos, axis=1)
|
| 312 |
+
else:
|
| 313 |
+
ref_pos = np.full_like(positions, np.nan)
|
| 314 |
+
err = np.full(len(t), np.nan)
|
| 315 |
+
|
| 316 |
+
if t_max > t_min:
|
| 317 |
+
feasible = ((tensions >= t_min - 1e-6) & (tensions <= t_max + 1e-6)).all(axis=1).astype(int)
|
| 318 |
+
else:
|
| 319 |
+
feasible = np.ones(len(t), dtype=int)
|
| 320 |
+
infeasible_set = set(int(i) for i in result.infeasible_steps)
|
| 321 |
+
qp_infeas = np.array([1 if i in infeasible_set else 0 for i in range(len(t))], dtype=int)
|
| 322 |
+
|
| 323 |
+
headers = ["t"] + ["px", "py", "pz"] + ["qx", "qy", "qz", "qw"]
|
| 324 |
+
headers += ["vx", "vy", "vz", "wx", "wy", "wz"]
|
| 325 |
+
headers += ["px_ref", "py_ref", "pz_ref", "track_err"]
|
| 326 |
+
headers += [f"L{i+1}" for i in range(n_cables)]
|
| 327 |
+
headers += [f"T{i+1}" for i in range(n_cables)]
|
| 328 |
+
headers += ["feasible", "infeasible_qp"]
|
| 329 |
+
with path.open("w", encoding="utf-8") as f:
|
| 330 |
+
f.write(",".join(headers) + "\n")
|
| 331 |
+
for k in range(len(t)):
|
| 332 |
+
row = [
|
| 333 |
+
f"{t[k]:.6f}",
|
| 334 |
+
*(f"{v:.6f}" for v in positions[k]),
|
| 335 |
+
*(f"{v:.6f}" for v in quats[k]),
|
| 336 |
+
*(f"{v:.6f}" for v in lin_vel[k]),
|
| 337 |
+
*(f"{v:.6f}" for v in ang_vel[k]),
|
| 338 |
+
*(f"{v:.6f}" for v in ref_pos[k]),
|
| 339 |
+
f"{err[k]:.6e}",
|
| 340 |
+
*(f"{v:.6f}" for v in lengths[k]),
|
| 341 |
+
*(f"{v:.6f}" for v in tensions[k]),
|
| 342 |
+
str(int(feasible[k])), str(int(qp_infeas[k])),
|
| 343 |
+
]
|
| 344 |
+
f.write(",".join(row) + "\n")
|
| 345 |
+
return path
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# ---------------------------------------------------------------------------
|
| 349 |
+
# Phase-1 example runner: build robot + controller + reference, simulate,
|
| 350 |
+
# render the 13-figure pack, write CSV + manifest + feasibility report.
|
| 351 |
+
# ---------------------------------------------------------------------------
|
| 352 |
+
|
| 353 |
+
@dataclass
|
| 354 |
+
class Phase1Run:
|
| 355 |
+
name: str
|
| 356 |
+
title: str
|
| 357 |
+
description: str
|
| 358 |
+
out_dir: Path
|
| 359 |
+
samples: int = 0
|
| 360 |
+
runtime_s: float = 0.0
|
| 361 |
+
tension_range_N: tuple[float, float] = (0.0, 0.0)
|
| 362 |
+
tracking_rms_m: float = 0.0
|
| 363 |
+
figures: list[str] = field(default_factory=list)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
def _run_phase1(
|
| 367 |
+
*,
|
| 368 |
+
name: str,
|
| 369 |
+
title: str,
|
| 370 |
+
description: str,
|
| 371 |
+
reference: Callable[[float], Pose],
|
| 372 |
+
duration: float,
|
| 373 |
+
dt: float,
|
| 374 |
+
kp_pos: float,
|
| 375 |
+
kp_rot: float,
|
| 376 |
+
out_dir: Path,
|
| 377 |
+
trajectory_spec: dict | None = None,
|
| 378 |
+
) -> Phase1Run:
|
| 379 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 380 |
+
print(f"\n=== Phase-1 example: {name} ===")
|
| 381 |
+
print(f" title : {title}")
|
| 382 |
+
print(f" description : {description}")
|
| 383 |
+
print(f" out_dir : {out_dir.resolve()}")
|
| 384 |
+
robot = dissertation_8cable(payload_mass=0.0, t_min=5.0, t_max=500.0)
|
| 385 |
+
kd_pos = 2.0 * float(np.sqrt(kp_pos))
|
| 386 |
+
kd_rot = 2.0 * float(np.sqrt(kp_rot))
|
| 387 |
+
controller = PDController(
|
| 388 |
+
Kp_pos=kp_pos, Kd_pos=kd_pos, Kp_rot=kp_rot, Kd_rot=kd_rot,
|
| 389 |
+
gravity_compensation=True, cancel_external=True,
|
| 390 |
+
)
|
| 391 |
+
p0 = reference(0.0).position
|
| 392 |
+
state0 = PlatformState.at_rest(
|
| 393 |
+
Pose(position=p0, rotation=reference(0.0).rotation),
|
| 394 |
+
)
|
| 395 |
+
print(f" duration : {duration:.3f} s dt: {dt:.4f} s")
|
| 396 |
+
|
| 397 |
+
t_start = time.perf_counter()
|
| 398 |
+
result = simulate(
|
| 399 |
+
robot=robot, state0=state0,
|
| 400 |
+
duration=duration, dt=dt,
|
| 401 |
+
reference=reference, controller=controller,
|
| 402 |
+
tension_objective="centered", gravity=(0.0, 0.0, -9.81),
|
| 403 |
+
)
|
| 404 |
+
runtime_s = time.perf_counter() - t_start
|
| 405 |
+
samples = len(result.time)
|
| 406 |
+
tens = np.asarray(result.cable_tensions)
|
| 407 |
+
t_min, t_max = float(robot.limits.t_min[0]), float(robot.limits.t_max[0])
|
| 408 |
+
n_violations = int(((tens < t_min - 1e-6) | (tens > t_max + 1e-6)).sum())
|
| 409 |
+
print(
|
| 410 |
+
f" done : {samples} samples in {runtime_s:.2f} s, "
|
| 411 |
+
f"tensions [{float(tens.min()):.2f}, {float(tens.max()):.2f}] N, "
|
| 412 |
+
f"violations {n_violations}, infeasible {len(result.infeasible_steps)}"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
# Tracking error metrics.
|
| 416 |
+
ref_pos = np.array([reference(t).position for t in result.time])
|
| 417 |
+
err = np.linalg.norm(np.asarray(result.positions) - ref_pos, axis=1)
|
| 418 |
+
rms_track = float(np.sqrt(np.mean(err ** 2)))
|
| 419 |
+
|
| 420 |
+
# Feasibility report.
|
| 421 |
+
feas = {
|
| 422 |
+
"t_min_N": t_min, "t_max_N": t_max,
|
| 423 |
+
"tension_min_observed_N": float(tens.min()),
|
| 424 |
+
"tension_max_observed_N": float(tens.max()),
|
| 425 |
+
"tension_mean_N": float(tens.mean()),
|
| 426 |
+
"qp_infeasible_steps": list(map(int, result.infeasible_steps)),
|
| 427 |
+
"bound_violation_count": n_violations,
|
| 428 |
+
"samples": int(samples),
|
| 429 |
+
"tracking_error_rms_m": rms_track,
|
| 430 |
+
"tracking_error_peak_m": float(err.max()),
|
| 431 |
+
"tracking_error_final_m": float(err[-1]),
|
| 432 |
+
}
|
| 433 |
+
(out_dir / "feasibility.json").write_text(
|
| 434 |
+
json.dumps(feas, indent=2), encoding="utf-8",
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
csv_path = _save_csv(out_dir, result, reference=reference,
|
| 438 |
+
t_min=t_min, t_max=t_max)
|
| 439 |
+
print(f" [timeseries.csv ] -> {csv_path.resolve()}")
|
| 440 |
+
figs = _render_phase1_plots(out_dir, result, robot, reference)
|
| 441 |
+
|
| 442 |
+
# Manifest (compatible with the Phase-2 readers).
|
| 443 |
+
manifest = {
|
| 444 |
+
"example": name,
|
| 445 |
+
"title": title,
|
| 446 |
+
"description": description,
|
| 447 |
+
"git_hash": _git_describe(),
|
| 448 |
+
"python": sys.version.split()[0],
|
| 449 |
+
"platform": _platform.platform(),
|
| 450 |
+
"controller": "pd",
|
| 451 |
+
"controller_gains": {"kp_pos": kp_pos, "kp_rot": kp_rot,
|
| 452 |
+
"kd_pos": kd_pos, "kd_rot": kd_rot},
|
| 453 |
+
"feasibility": feas,
|
| 454 |
+
"robot_spec": RobotSpec.from_robot(robot).to_dict(),
|
| 455 |
+
# ``request`` block lets train_from_csv.run_replay rebuild the
|
| 456 |
+
# trajectory for catalog kinds (circle). For the custom
|
| 457 |
+
# callables used by spiral / mshape the trajectory_spec is
|
| 458 |
+
# marked ``custom_callable`` and replay/RL fall back to their
|
| 459 |
+
# "skip cleanly with reason" stub --- which is the honest
|
| 460 |
+
# behaviour since we cannot reconstruct a closed-form
|
| 461 |
+
# reference for the inline functions.
|
| 462 |
+
"request": {
|
| 463 |
+
"robot": "dissertation_8cable",
|
| 464 |
+
"payload_mass": 0.0,
|
| 465 |
+
"duration": duration, "dt": dt,
|
| 466 |
+
"tension_objective": "centered",
|
| 467 |
+
"gravity": [0.0, 0.0, -9.81],
|
| 468 |
+
"trajectory": trajectory_spec or {
|
| 469 |
+
"kind": "custom_callable",
|
| 470 |
+
"duration": duration, "params": {},
|
| 471 |
+
},
|
| 472 |
+
},
|
| 473 |
+
"samples": samples,
|
| 474 |
+
"runtime_s": round(runtime_s, 3),
|
| 475 |
+
}
|
| 476 |
+
(out_dir / "manifest.json").write_text(
|
| 477 |
+
json.dumps(manifest, indent=2, default=str), encoding="utf-8",
|
| 478 |
+
)
|
| 479 |
+
print(f" [feasibility.json ] -> {(out_dir / 'feasibility.json').resolve()}")
|
| 480 |
+
print(f" [manifest.json ] -> {(out_dir / 'manifest.json').resolve()}")
|
| 481 |
+
|
| 482 |
+
return Phase1Run(
|
| 483 |
+
name=name, title=title, description=description,
|
| 484 |
+
out_dir=out_dir, samples=samples, runtime_s=runtime_s,
|
| 485 |
+
tension_range_N=(float(tens.min()), float(tens.max())),
|
| 486 |
+
tracking_rms_m=rms_track, figures=figs,
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def _git_describe() -> str:
|
| 491 |
+
try:
|
| 492 |
+
return subprocess.check_output(
|
| 493 |
+
["git", "rev-parse", "--short", "HEAD"],
|
| 494 |
+
cwd=_REPO_ROOT, text=True,
|
| 495 |
+
).strip()
|
| 496 |
+
except Exception: # pragma: no cover
|
| 497 |
+
return "unknown"
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
# ---------------------------------------------------------------------------
|
| 501 |
+
# Phase-1 example builders
|
| 502 |
+
# ---------------------------------------------------------------------------
|
| 503 |
+
|
| 504 |
+
def example_circle(out_dir: Path) -> Phase1Run:
|
| 505 |
+
"""Example 1 — circular tracking, 3-DoF planar reference."""
|
| 506 |
+
# Reuse the proven dissertation-circle preset's trajectory analytically:
|
| 507 |
+
# quintic time-scaling for smooth start/stop over 2 revolutions of
|
| 508 |
+
# a 0.05 m horizontal circle at z = 0.65 m.
|
| 509 |
+
def _circle_pose(t: float, *, T: float = 12.566) -> Pose:
|
| 510 |
+
s = float(np.clip(t / T, 0.0, 1.0))
|
| 511 |
+
s_smooth = 6 * s ** 5 - 15 * s ** 4 + 10 * s ** 3
|
| 512 |
+
theta = 2.0 * np.pi * 2.0 * s_smooth
|
| 513 |
+
pos = np.array([0.05 * np.cos(theta), 0.05 * np.sin(theta), 0.65])
|
| 514 |
+
return Pose(position=pos, rotation=Rotation.identity())
|
| 515 |
+
return _run_phase1(
|
| 516 |
+
name="circle",
|
| 517 |
+
title="Circular trajectory tracking",
|
| 518 |
+
description="Horizontal 0.05 m radius circle traced twice. "
|
| 519 |
+
"Demonstrates closed-loop PD tracking with feasible "
|
| 520 |
+
"tensions inside the 5-500 N envelope.",
|
| 521 |
+
reference=_circle_pose,
|
| 522 |
+
duration=12.566, dt=1e-3, # 4π/(0.1/0.05) s for v=0.1 m/s tangential
|
| 523 |
+
kp_pos=400.0, kp_rot=100.0,
|
| 524 |
+
out_dir=out_dir,
|
| 525 |
+
# Catalog-recoverable: replay / PPO / SAC can rebuild this
|
| 526 |
+
# trajectory from the manifest alone.
|
| 527 |
+
trajectory_spec={
|
| 528 |
+
"kind": "circle",
|
| 529 |
+
"duration": 12.566,
|
| 530 |
+
"params": {
|
| 531 |
+
"center": [0.0, 0.0, 0.65],
|
| 532 |
+
"radius": 0.05,
|
| 533 |
+
"axis": [0.0, 0.0, 1.0],
|
| 534 |
+
"angle_span": float(4 * np.pi),
|
| 535 |
+
},
|
| 536 |
+
},
|
| 537 |
+
)
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def example_spiral(out_dir: Path) -> Phase1Run:
|
| 541 |
+
"""Example 2 — 6-DoF helical reference.
|
| 542 |
+
|
| 543 |
+
Yaw rotates 2 full turns over the run and pitch oscillates ±~9 deg
|
| 544 |
+
so all six rigid-body DoFs see non-trivial motion. The ``orientation``
|
| 545 |
+
plot in the artifact bundle makes this visually obvious.
|
| 546 |
+
"""
|
| 547 |
+
def _ref(t: float) -> Pose:
|
| 548 |
+
return helical6_pose(t) # uses module defaults
|
| 549 |
+
return _run_phase1(
|
| 550 |
+
name="spiral",
|
| 551 |
+
title="6-DoF helical spiral (full SE(3) tracking)",
|
| 552 |
+
description="3 spiral revolutions with bounded roll / pitch / yaw "
|
| 553 |
+
"oscillation (±3-17°); demonstrates orientation "
|
| 554 |
+
"tracking under closed-loop PD with 5-500 N bounds.",
|
| 555 |
+
reference=_ref,
|
| 556 |
+
duration=15.0, dt=1e-3,
|
| 557 |
+
kp_pos=300.0, kp_rot=80.0,
|
| 558 |
+
out_dir=out_dir,
|
| 559 |
+
)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def example_mshape(out_dir: Path) -> Phase1Run:
|
| 563 |
+
"""Example 3 — pick-and-place letter-M task with vertex dwells and
|
| 564 |
+
discrete gripper actuation at each pick / place event."""
|
| 565 |
+
duration = mshape_total_duration()
|
| 566 |
+
def _ref(t: float) -> Pose:
|
| 567 |
+
return mshape_pose(t)
|
| 568 |
+
return _run_phase1(
|
| 569 |
+
name="mshape",
|
| 570 |
+
title="Pick-and-place M-task",
|
| 571 |
+
description=f"Trace the letter 'M' through 5 vertices with "
|
| 572 |
+
f"{int(duration)} s total of motion + dwells. "
|
| 573 |
+
"Gripper yaw at each dwell simulates pick/place "
|
| 574 |
+
"actuation under load.",
|
| 575 |
+
reference=_ref,
|
| 576 |
+
duration=duration, dt=1e-3,
|
| 577 |
+
kp_pos=350.0, kp_rot=90.0,
|
| 578 |
+
out_dir=out_dir,
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
# ---------------------------------------------------------------------------
|
| 583 |
+
# Phase-2 example runner: invokes the existing train_from_csv / compare_models
|
| 584 |
+
# scripts as subprocesses with pre-baked argument lists.
|
| 585 |
+
# ---------------------------------------------------------------------------
|
| 586 |
+
|
| 587 |
+
def _phase2_input_csv(dependency: str, dep_out_root: Path) -> Path:
|
| 588 |
+
"""Locate the CSV produced by a Phase-1 dependency, generating it if
|
| 589 |
+
missing. Default dependency is the circle example."""
|
| 590 |
+
csv = dep_out_root / "timeseries.csv"
|
| 591 |
+
if csv.exists():
|
| 592 |
+
return csv
|
| 593 |
+
print(f"[phase2] dependency CSV missing: {csv}")
|
| 594 |
+
print(f"[phase2] auto-running Phase-1 example '{dependency}' to generate it…")
|
| 595 |
+
if dependency == "circle":
|
| 596 |
+
example_circle(dep_out_root)
|
| 597 |
+
elif dependency == "spiral":
|
| 598 |
+
example_spiral(dep_out_root)
|
| 599 |
+
elif dependency == "mshape":
|
| 600 |
+
example_mshape(dep_out_root)
|
| 601 |
+
else:
|
| 602 |
+
raise ValueError(f"Unknown Phase-1 dependency: {dependency!r}")
|
| 603 |
+
if not csv.exists():
|
| 604 |
+
raise FileNotFoundError(f"Phase-1 run did not produce {csv}")
|
| 605 |
+
return csv
|
| 606 |
+
|
| 607 |
+
|
| 608 |
+
def example_train(out_dir: Path, *, dependency: str = "circle",
|
| 609 |
+
dep_out_root: Path | None = None) -> dict:
|
| 610 |
+
"""Example 4 — single-model PINN training on a Phase-1 CSV."""
|
| 611 |
+
dep_out_root = dep_out_root or (_REPO_ROOT / "out" / "example-circle")
|
| 612 |
+
csv = _phase2_input_csv(dependency, dep_out_root)
|
| 613 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 614 |
+
print(f"\n=== Phase-2 example: train (PINN) ===")
|
| 615 |
+
print(f" input : {csv}")
|
| 616 |
+
print(f" out : {out_dir.resolve()}")
|
| 617 |
+
cmd = [
|
| 618 |
+
sys.executable, str(Path(__file__).parent / "train_from_csv.py"),
|
| 619 |
+
"--input", str(csv),
|
| 620 |
+
"--model", "pinn",
|
| 621 |
+
"--epochs", "120",
|
| 622 |
+
"--batch-size", "64",
|
| 623 |
+
"--learning-rate", "1e-3",
|
| 624 |
+
"--out", str(out_dir),
|
| 625 |
+
]
|
| 626 |
+
return _run_subprocess("train", cmd, out_dir)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def example_compare(out_dir: Path, *, dependency: str = "circle",
|
| 630 |
+
dep_out_root: Path | None = None) -> dict:
|
| 631 |
+
"""Example 5 — multi-model comparison on a Phase-1 CSV."""
|
| 632 |
+
dep_out_root = dep_out_root or (_REPO_ROOT / "out" / "example-circle")
|
| 633 |
+
csv = _phase2_input_csv(dependency, dep_out_root)
|
| 634 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 635 |
+
print(f"\n=== Phase-2 example: compare (replay/mlp/pinn/ppo/sac) ===")
|
| 636 |
+
print(f" input : {csv}")
|
| 637 |
+
print(f" out : {out_dir.resolve()}")
|
| 638 |
+
cmd = [
|
| 639 |
+
sys.executable, str(Path(__file__).parent / "compare_models.py"),
|
| 640 |
+
"--input", str(csv),
|
| 641 |
+
"--out", str(out_dir),
|
| 642 |
+
"--models", "replay", "mlp", "pinn", "ppo", "sac",
|
| 643 |
+
"--epochs", "60",
|
| 644 |
+
"--rl-steps", "2000",
|
| 645 |
+
"--eval-episodes", "2",
|
| 646 |
+
]
|
| 647 |
+
return _run_subprocess("compare", cmd, out_dir)
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def _run_subprocess(label: str, cmd: list[str], out_dir: Path) -> dict:
|
| 651 |
+
print(f" cmd : {' '.join(cmd)}")
|
| 652 |
+
t0 = time.perf_counter()
|
| 653 |
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
| 654 |
+
dt = time.perf_counter() - t0
|
| 655 |
+
(out_dir / f"{label}_stdout.txt").write_text(proc.stdout or "", encoding="utf-8")
|
| 656 |
+
(out_dir / f"{label}_stderr.txt").write_text(proc.stderr or "", encoding="utf-8")
|
| 657 |
+
print(f" done : exit {proc.returncode}, {dt:.1f} s")
|
| 658 |
+
return {"label": label, "returncode": proc.returncode, "wall_time_s": round(dt, 2)}
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
# ---------------------------------------------------------------------------
|
| 662 |
+
# Registry --- the single source of truth used by the CLI and the GUI.
|
| 663 |
+
# ---------------------------------------------------------------------------
|
| 664 |
+
|
| 665 |
+
EXAMPLES: dict[str, dict] = {
|
| 666 |
+
"circle": {
|
| 667 |
+
"phase": 1,
|
| 668 |
+
"title": "Circular trajectory tracking",
|
| 669 |
+
"description": ("3-DoF planar circle at z = 0.65 m, 0.05 m radius, "
|
| 670 |
+
"2 revolutions with smooth start/stop."),
|
| 671 |
+
"out_dir": "example-circle",
|
| 672 |
+
"runner": example_circle,
|
| 673 |
+
},
|
| 674 |
+
"spiral": {
|
| 675 |
+
"phase": 1,
|
| 676 |
+
"title": "6-DoF helical spiral",
|
| 677 |
+
"description": ("Full SE(3) tracking: 3-revolution spiral with "
|
| 678 |
+
"platform yaw and pitch oscillation."),
|
| 679 |
+
"out_dir": "example-spiral",
|
| 680 |
+
"runner": example_spiral,
|
| 681 |
+
},
|
| 682 |
+
"mshape": {
|
| 683 |
+
"phase": 1,
|
| 684 |
+
"title": "Pick-and-place M-task",
|
| 685 |
+
"description": ("Trace letter 'M' through 5 vertices with dwells "
|
| 686 |
+
"and discrete gripper actuation at each pick/place."),
|
| 687 |
+
"out_dir": "example-mshape",
|
| 688 |
+
"runner": example_mshape,
|
| 689 |
+
},
|
| 690 |
+
"train": {
|
| 691 |
+
"phase": 2,
|
| 692 |
+
"title": "Data-driven PINN training",
|
| 693 |
+
"description": ("Train PINN inverse-dynamics on the circle CSV; "
|
| 694 |
+
"if missing, runs the circle example first."),
|
| 695 |
+
"out_dir": "example-train",
|
| 696 |
+
"depends_on": "circle",
|
| 697 |
+
"runner": example_train,
|
| 698 |
+
},
|
| 699 |
+
"compare": {
|
| 700 |
+
"phase": 2,
|
| 701 |
+
"title": "Multi-model comparison",
|
| 702 |
+
"description": ("Bench replay / MLP / PINN / PPO / SAC on the "
|
| 703 |
+
"same dataset and rank by RMSE."),
|
| 704 |
+
"out_dir": "example-compare",
|
| 705 |
+
"depends_on": "circle",
|
| 706 |
+
"runner": example_compare,
|
| 707 |
+
},
|
| 708 |
+
}
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def list_examples() -> list[dict]:
|
| 712 |
+
return [
|
| 713 |
+
{"name": k, **{kk: vv for kk, vv in v.items() if kk != "runner"}}
|
| 714 |
+
for k, v in EXAMPLES.items()
|
| 715 |
+
]
|
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""Unified CLI driver for the built-in CDPR_SIMULATOR demonstrations.
|
| 2 |
+
|
| 3 |
+
Five examples are registered in :mod:`scripts.examples` and exposed
|
| 4 |
+
here through a single entry point so the directive's "selectable
|
| 5 |
+
tutorials" requirement is satisfied for the PowerShell workflow.
|
| 6 |
+
|
| 7 |
+
::
|
| 8 |
+
|
| 9 |
+
python scripts/run_example.py --list
|
| 10 |
+
python scripts/run_example.py --name circle
|
| 11 |
+
python scripts/run_example.py --name spiral --open
|
| 12 |
+
python scripts/run_example.py --name mshape
|
| 13 |
+
python scripts/run_example.py --name train
|
| 14 |
+
python scripts/run_example.py --name compare --open
|
| 15 |
+
|
| 16 |
+
For Phase-2 examples (``train``, ``compare``) the runner auto-checks
|
| 17 |
+
for the Phase-1 CSV they depend on and re-generates it if missing.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
from pathlib import Path
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
| 30 |
+
p = argparse.ArgumentParser(
|
| 31 |
+
description="Run one of the five built-in CDPR_SIMULATOR examples.",
|
| 32 |
+
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 33 |
+
)
|
| 34 |
+
p.add_argument("--name", type=str, default=None,
|
| 35 |
+
help="Example identifier: circle, spiral, mshape, train, compare.")
|
| 36 |
+
p.add_argument("--list", action="store_true",
|
| 37 |
+
help="List all available examples and exit.")
|
| 38 |
+
p.add_argument("--out", type=Path, default=None,
|
| 39 |
+
help="Override the per-example output directory.")
|
| 40 |
+
p.add_argument("--open", action="store_true",
|
| 41 |
+
help="Open the result folder in Explorer when done (Windows only).")
|
| 42 |
+
return p.parse_args(argv)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _print_list(examples) -> None:
|
| 46 |
+
print("Built-in CDPR_SIMULATOR examples")
|
| 47 |
+
print("================================")
|
| 48 |
+
print()
|
| 49 |
+
for e in examples:
|
| 50 |
+
print(f"[{e['name']}] {e['title']} (phase {e['phase']})")
|
| 51 |
+
for line in e["description"].splitlines():
|
| 52 |
+
print(f" {line}")
|
| 53 |
+
if "depends_on" in e:
|
| 54 |
+
print(f" depends on: example '{e['depends_on']}'")
|
| 55 |
+
print()
|
| 56 |
+
print("Run with: python scripts/run_example.py --name <id>")
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def main(argv: list[str] | None = None) -> int:
|
| 60 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 61 |
+
from examples import EXAMPLES, list_examples
|
| 62 |
+
|
| 63 |
+
args = parse_args(argv)
|
| 64 |
+
|
| 65 |
+
if args.list or args.name is None:
|
| 66 |
+
_print_list(list_examples())
|
| 67 |
+
return 0
|
| 68 |
+
|
| 69 |
+
if args.name not in EXAMPLES:
|
| 70 |
+
print(f"Unknown example: {args.name!r}", file=sys.stderr)
|
| 71 |
+
print(f"Available: {', '.join(EXAMPLES.keys())}", file=sys.stderr)
|
| 72 |
+
return 2
|
| 73 |
+
|
| 74 |
+
spec = EXAMPLES[args.name]
|
| 75 |
+
out_root = Path("out")
|
| 76 |
+
out_dir = args.out or (out_root / spec["out_dir"])
|
| 77 |
+
runner = spec["runner"]
|
| 78 |
+
t0 = time.perf_counter()
|
| 79 |
+
result = runner(out_dir)
|
| 80 |
+
dt = time.perf_counter() - t0
|
| 81 |
+
print(f"\n[done] {args.name} in {dt:.1f} s -> {Path(out_dir).resolve()}")
|
| 82 |
+
|
| 83 |
+
if args.open and sys.platform == "win32":
|
| 84 |
+
try:
|
| 85 |
+
os.startfile(str(Path(out_dir))) # type: ignore[attr-defined]
|
| 86 |
+
except Exception as exc: # pragma: no cover
|
| 87 |
+
print(f"could not open folder: {exc}", file=sys.stderr)
|
| 88 |
+
return 0
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
if __name__ == "__main__":
|
| 92 |
+
sys.exit(main())
|
|
@@ -393,6 +393,15 @@ def run_replay(args, blocks: dict[str, np.ndarray], out_dir: Path,
|
|
| 393 |
"scripts/run_simulation.py to generate one")
|
| 394 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 395 |
req_d = manifest["request"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 396 |
request = SimulationRequest(
|
| 397 |
robot=req_d["robot"],
|
| 398 |
payload_mass=req_d.get("payload_mass", 0.0),
|
|
@@ -501,6 +510,15 @@ def run_rl(args, blocks: dict[str, np.ndarray], out_dir: Path,
|
|
| 501 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 502 |
req_d = manifest["request"]
|
| 503 |
from cdpr.interface.specs import SimulationRequest, TrajectorySpec, build_trajectory
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 504 |
request = SimulationRequest(
|
| 505 |
robot=req_d["robot"],
|
| 506 |
payload_mass=req_d.get("payload_mass", 0.0),
|
|
|
|
| 393 |
"scripts/run_simulation.py to generate one")
|
| 394 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 395 |
req_d = manifest["request"]
|
| 396 |
+
if req_d["trajectory"]["kind"] == "custom_callable":
|
| 397 |
+
return _missing_manifest_stub(
|
| 398 |
+
args.model, out_dir,
|
| 399 |
+
"the source manifest uses an inline Python callable as its "
|
| 400 |
+
"reference (kind='custom_callable'), which the analytic "
|
| 401 |
+
"replay / RL paths cannot reconstruct from the manifest "
|
| 402 |
+
"alone. Use a CSV produced by run_simulation.py (catalog "
|
| 403 |
+
"kinds) for these workflows.",
|
| 404 |
+
)
|
| 405 |
request = SimulationRequest(
|
| 406 |
robot=req_d["robot"],
|
| 407 |
payload_mass=req_d.get("payload_mass", 0.0),
|
|
|
|
| 510 |
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
|
| 511 |
req_d = manifest["request"]
|
| 512 |
from cdpr.interface.specs import SimulationRequest, TrajectorySpec, build_trajectory
|
| 513 |
+
if req_d["trajectory"]["kind"] == "custom_callable":
|
| 514 |
+
return _missing_manifest_stub(
|
| 515 |
+
args.model, out_dir,
|
| 516 |
+
"the source manifest uses an inline Python callable as its "
|
| 517 |
+
"reference (kind='custom_callable'), which the analytic "
|
| 518 |
+
"replay / RL paths cannot reconstruct from the manifest "
|
| 519 |
+
"alone. Use a CSV produced by run_simulation.py (catalog "
|
| 520 |
+
"kinds) for these workflows.",
|
| 521 |
+
)
|
| 522 |
request = SimulationRequest(
|
| 523 |
robot=req_d["robot"],
|
| 524 |
payload_mass=req_d.get("payload_mass", 0.0),
|
|
@@ -58,6 +58,7 @@ import matplotlib # noqa: E402
|
|
| 58 |
matplotlib.use("Agg", force=True)
|
| 59 |
|
| 60 |
import io # noqa: E402
|
|
|
|
| 61 |
|
| 62 |
import numpy as np # noqa: E402
|
| 63 |
import pandas as pd # noqa: E402
|
|
@@ -190,6 +191,7 @@ def render() -> None:
|
|
| 190 |
del st.session_state[k]
|
| 191 |
st.rerun()
|
| 192 |
|
|
|
|
| 193 |
request = _request_sidebar()
|
| 194 |
_action_bar(request)
|
| 195 |
_results_panel()
|
|
@@ -510,6 +512,107 @@ def _plot_scene_3d(result, robot):
|
|
| 510 |
# CSV / XLSX peek
|
| 511 |
# ---------------------------------------------------------------------------
|
| 512 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 513 |
def _upload_panel() -> None:
|
| 514 |
"""Phase-2 surface: peek at an uploaded log, then optionally run a
|
| 515 |
quick analysis (replay / PINN) inline.
|
|
|
|
| 58 |
matplotlib.use("Agg", force=True)
|
| 59 |
|
| 60 |
import io # noqa: E402
|
| 61 |
+
import json # noqa: E402
|
| 62 |
|
| 63 |
import numpy as np # noqa: E402
|
| 64 |
import pandas as pd # noqa: E402
|
|
|
|
| 191 |
del st.session_state[k]
|
| 192 |
st.rerun()
|
| 193 |
|
| 194 |
+
_examples_panel()
|
| 195 |
request = _request_sidebar()
|
| 196 |
_action_bar(request)
|
| 197 |
_results_panel()
|
|
|
|
| 512 |
# CSV / XLSX peek
|
| 513 |
# ---------------------------------------------------------------------------
|
| 514 |
|
| 515 |
+
def _examples_panel() -> None:
|
| 516 |
+
"""Selectable built-in demonstrations (the directive's "tutorials").
|
| 517 |
+
|
| 518 |
+
Five examples are registered in :mod:`scripts.examples`; this panel
|
| 519 |
+
shows them in a dropdown with the per-example description, a copy-
|
| 520 |
+
paste-ready PowerShell command, and (for local Streamlit) a one-
|
| 521 |
+
click runner that shells out to ``scripts/run_example.py`` and
|
| 522 |
+
displays the resulting figures inline.
|
| 523 |
+
|
| 524 |
+
On Streamlit Cloud the one-click runner is hidden because each
|
| 525 |
+
Phase-1 example takes 30-300 s and several MB of plotting --- the
|
| 526 |
+
free-tier worker would OOM. The PowerShell command is always shown
|
| 527 |
+
so the user can drive it from a local terminal.
|
| 528 |
+
"""
|
| 529 |
+
st.divider()
|
| 530 |
+
st.subheader("Built-in examples")
|
| 531 |
+
|
| 532 |
+
# Lazy import the registry --- keeps the GUI module's import cost
|
| 533 |
+
# light, and the script's path resolution works even on Streamlit
|
| 534 |
+
# Cloud where ``scripts/`` is not on sys.path by default.
|
| 535 |
+
try:
|
| 536 |
+
import sys as _sys
|
| 537 |
+
from pathlib import Path as _Path
|
| 538 |
+
scripts_dir = _Path(__file__).resolve().parents[3] / "scripts"
|
| 539 |
+
if str(scripts_dir) not in _sys.path:
|
| 540 |
+
_sys.path.insert(0, str(scripts_dir))
|
| 541 |
+
from examples import list_examples # noqa: E402
|
| 542 |
+
catalog = list_examples()
|
| 543 |
+
except Exception as exc:
|
| 544 |
+
st.warning(f"Examples registry unavailable: {exc}")
|
| 545 |
+
return
|
| 546 |
+
|
| 547 |
+
label_for: dict[str, dict] = {f"[{e['name']}] {e['title']}": e for e in catalog}
|
| 548 |
+
label = st.selectbox(
|
| 549 |
+
"Select a built-in example",
|
| 550 |
+
list(label_for.keys()),
|
| 551 |
+
key="example_select",
|
| 552 |
+
help="Five demonstrations cover the directive's two phases.",
|
| 553 |
+
)
|
| 554 |
+
entry = label_for[label]
|
| 555 |
+
cols = st.columns([5, 1])
|
| 556 |
+
cols[0].markdown(f"**Description:** {entry['description']}")
|
| 557 |
+
cols[1].markdown(f"**Phase:** {entry['phase']}")
|
| 558 |
+
if entry.get("depends_on"):
|
| 559 |
+
st.caption(f"Depends on example `{entry['depends_on']}` "
|
| 560 |
+
"(auto-run if its CSV is missing).")
|
| 561 |
+
|
| 562 |
+
ps_cmd = f"python scripts\\run_example.py --name {entry['name']} --open"
|
| 563 |
+
st.code(ps_cmd, language="powershell")
|
| 564 |
+
st.caption(
|
| 565 |
+
"Copy the line above into a PowerShell terminal at the project "
|
| 566 |
+
"root. Output lands under `out/" + entry['out_dir'] + "/`."
|
| 567 |
+
)
|
| 568 |
+
|
| 569 |
+
# One-click in-app runner --- only enabled when we are NOT running
|
| 570 |
+
# on Streamlit Cloud (frugal-mode env var is the cloud signal).
|
| 571 |
+
if not FRUGAL:
|
| 572 |
+
if st.button(f"Run '{entry['name']}' inline (local only)",
|
| 573 |
+
key=f"btn_example_{entry['name']}"):
|
| 574 |
+
_run_example_inline(entry)
|
| 575 |
+
else:
|
| 576 |
+
st.caption(
|
| 577 |
+
"Inline execution disabled on Streamlit Cloud (workers are too "
|
| 578 |
+
"small for the full plot bundle). Use the PowerShell command "
|
| 579 |
+
"above on a local checkout."
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
def _run_example_inline(entry: dict) -> None:
|
| 584 |
+
import subprocess
|
| 585 |
+
import sys as _sys
|
| 586 |
+
from pathlib import Path as _Path
|
| 587 |
+
repo_root = _Path(__file__).resolve().parents[3]
|
| 588 |
+
cmd = [_sys.executable, str(repo_root / "scripts" / "run_example.py"),
|
| 589 |
+
"--name", entry["name"]]
|
| 590 |
+
with st.spinner(f"Running example '{entry['name']}' …"):
|
| 591 |
+
proc = subprocess.run(cmd, capture_output=True, text=True, cwd=str(repo_root))
|
| 592 |
+
if proc.returncode != 0:
|
| 593 |
+
st.error(f"Example failed (exit {proc.returncode})")
|
| 594 |
+
st.code(proc.stderr or "", language="text")
|
| 595 |
+
return
|
| 596 |
+
st.success(f"Example '{entry['name']}' completed.")
|
| 597 |
+
out_root = repo_root / "out" / entry["out_dir"]
|
| 598 |
+
if not out_root.exists():
|
| 599 |
+
st.info(f"Output directory not found at {out_root}; check the console log.")
|
| 600 |
+
return
|
| 601 |
+
# Display all PNGs the run produced.
|
| 602 |
+
pngs = sorted(out_root.glob("*.png"))
|
| 603 |
+
if pngs:
|
| 604 |
+
st.write(f"Produced {len(pngs)} figure(s):")
|
| 605 |
+
for png in pngs[:18]: # cap to keep page light
|
| 606 |
+
st.image(str(png), caption=png.name, use_container_width=True)
|
| 607 |
+
metrics = out_root / "feasibility.json"
|
| 608 |
+
if metrics.exists():
|
| 609 |
+
st.json(json.loads(metrics.read_text(encoding="utf-8")))
|
| 610 |
+
manifest = out_root / "manifest.json"
|
| 611 |
+
if manifest.exists():
|
| 612 |
+
with st.expander("manifest.json", expanded=False):
|
| 613 |
+
st.json(json.loads(manifest.read_text(encoding="utf-8")))
|
| 614 |
+
|
| 615 |
+
|
| 616 |
def _upload_panel() -> None:
|
| 617 |
"""Phase-2 surface: peek at an uploaded log, then optionally run a
|
| 618 |
quick analysis (replay / PINN) inline.
|