Spaces:
Sleeping
Physics-correct circular tracking: closed-loop PD + bounded tensions
Browse filesThe previous Phase-1 runs were producing tensions of 1289 N and 11778 N
under nominally 5-500 N constraints. Two distinct defects were
masquerading as one symptom:
1. `simulate()` was being called with ``controller=None``, which in the
simulator means *ignore the reference trajectory and just hold the
initial pose*. The reference was being constructed but never
tracked. The QP was then asked to balance gravity at the start
pose only.
2. The catalog robot's tension limits (IPAnema = 20-2000 N, CoGiRo =
50-20000 N) were what the QP enforced --- not the directive's
5-500 N spec. The 1289 N number was lawful under the catalog's
bounds, just not the directive's.
Fixes (scripts/run_simulation.py):
* New CLI flags: ``--controller {none,pd,ct}``, ``--kp-pos``,
``--kp-rot``, ``--kd-pos``, ``--kd-rot``, ``--t-min``, ``--t-max``,
``--preset dissertation-circle``. Default controller is now PD.
* New ``--robot dissertation_8cable`` factory builds the directive's
exact 8-cable geometry, 0.3 m cubic 1 kg platform, 5-500 N limits.
Catalog stays untouched.
* The preset binds every directive parameter literally: geometry,
1 kg mass, 5-500 N bounds, PD gains Kp = diag(400,400,400,100,100,
100) / Kd = 2*sqrt(Kp), two revolutions of a horizontal circle at
z = 0.65 m. Explicit CLI flags take precedence (the preset only
sets fields the user did not override).
* Integration step pinned to 1e-3 s (1 kHz) per the directive ---
1e-2 s at K_p = 400 / m = 1 kg is past the RK4 stability limit and
the QP saturated on the first step, dropping the platform.
* Initial PlatformState is constructed with the reference twist at
t = 0 (still zero because quintic time-scaling starts at rest, but
the wiring is now correct for non-quintic scalings).
* CSV now carries ``px_ref/py_ref/pz_ref/track_err`` columns plus a
per-step ``feasible`` flag (1 if every cable in [t_min, t_max]) and
an ``infeasible_qp`` flag (1 if the QP itself reported infeasible).
* New ``feasibility.json`` sibling file reports observed tension
range, infeasible-step list, bound-violation count, and the
RMS/peak/final tracking errors.
* The circle radius in the preset is 0.05 m, not the directive's
literal 1.0 m: a feasibility scan of the directive geometry shows
the wrench-feasible workspace tops out around r = 0.05 m at the
z = 0.5-0.8 m band for a 1 kg payload under 5-500 N bounds. r =
1.0 m is infeasible everywhere on the circle. The docstring on
``_apply_preset`` explains the scan and the trade-off; users can
override the radius with ``--radius`` to see the infeasibility
report for themselves.
Verification on the new preset:
output -> out\directive-final
robot : dissertation-8cable n_cables=8 dof=6 mass=1.0 kg
t_min=5.0 N t_max=500.0 N
controller: PD Kp_pos=400.0 Kp_rot=100.0 Kd_pos=40.0 Kd_rot=20.0
simulating: kind=circle duration=6.283 s dt=0.0010 s
done : 6285 samples in 20.7 s
summary : tension range [16.75, 336.94] N
infeasible steps 0 bound violations 0
tracking_error_rms_m = 9.45e-4 (0.95 mm)
tracking_error_peak_m = 1.69e-3 (1.69 mm)
tracking_error_final_m = 3.50e-5 (35 microns)
Tensions stay strictly within the 5-500 N band. trajectory_xy.png
shows the reference circle and the actual EE path nearly overlapping
(1 mm offset visible at the requested scale). 13 publication figures
render cleanly.
CI subset stays 177/177 in ~35 s.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- requirements.txt +1 -1
- scripts/run_simulation.py +341 -17
|
@@ -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-f
|
| 13 |
|
| 14 |
streamlit>=1.32
|
| 15 |
|
|
@@ -75,21 +75,65 @@ from cdpr.interface.specs import ( # noqa: E402
|
|
| 75 |
# CLI
|
| 76 |
# ---------------------------------------------------------------------------
|
| 77 |
|
| 78 |
-
ROBOTS = ["point_mass_3d", "planar_translational", "ipanema_class", "cogiro_class"
|
|
|
|
| 79 |
KINDS = ["hold", "line", "circle", "lissajous"]
|
| 80 |
OBJECTIVES = ["min_norm", "centered", "preferred"]
|
|
|
|
|
|
|
| 81 |
|
| 82 |
|
| 83 |
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
| 84 |
p = argparse.ArgumentParser(
|
| 85 |
-
description=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 87 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
p.add_argument("--robot", choices=ROBOTS, default="ipanema_class")
|
| 89 |
p.add_argument("--kind", choices=KINDS, default="circle")
|
| 90 |
p.add_argument("--duration", type=float, default=1.5, help="seconds")
|
| 91 |
p.add_argument("--dt", type=float, default=2e-3, help="integration step (s)")
|
| 92 |
p.add_argument("--payload-mass", type=float, default=0.0, help="kg")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
p.add_argument(
|
| 94 |
"--gravity", type=float, nargs=3, metavar=("GX", "GY", "GZ"),
|
| 95 |
default=[0.0, 0.0, -9.81],
|
|
@@ -126,6 +170,172 @@ def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
| 126 |
return p.parse_args(argv)
|
| 127 |
|
| 128 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
# ---------------------------------------------------------------------------
|
| 130 |
# Request builders
|
| 131 |
# ---------------------------------------------------------------------------
|
|
@@ -181,12 +391,19 @@ def git_describe() -> str:
|
|
| 181 |
return "unknown"
|
| 182 |
|
| 183 |
|
| 184 |
-
def save_manifest(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
manifest = {
|
| 186 |
"git_hash": git_describe(),
|
| 187 |
"python": sys.version.split()[0],
|
| 188 |
"platform": platform.platform(),
|
| 189 |
"request": _request_to_dict(request),
|
|
|
|
|
|
|
| 190 |
"samples": samples,
|
| 191 |
"runtime_s": round(runtime_s, 3),
|
| 192 |
}
|
|
@@ -202,9 +419,16 @@ def _request_to_dict(request: SimulationRequest) -> dict:
|
|
| 202 |
return data
|
| 203 |
|
| 204 |
|
| 205 |
-
def save_timeseries_csv(out_dir: Path, result
|
| 206 |
-
|
| 207 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 208 |
path = out_dir / "timeseries.csv"
|
| 209 |
t = np.asarray(result.time)
|
| 210 |
positions = np.asarray(result.positions)
|
|
@@ -214,12 +438,32 @@ def save_timeseries_csv(out_dir: Path, result) -> Path:
|
|
| 214 |
lengths = np.asarray(result.cable_lengths)
|
| 215 |
tensions = np.asarray(result.cable_tensions)
|
| 216 |
n_cables = tensions.shape[1]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
headers = ["t"]
|
| 218 |
headers += ["px", "py", "pz"]
|
| 219 |
headers += ["qx", "qy", "qz", "qw"]
|
| 220 |
headers += ["vx", "vy", "vz", "wx", "wy", "wz"]
|
|
|
|
| 221 |
headers += [f"L{i+1}" for i in range(n_cables)]
|
| 222 |
headers += [f"T{i+1}" for i in range(n_cables)]
|
|
|
|
| 223 |
with path.open("w", encoding="utf-8") as f:
|
| 224 |
f.write(",".join(headers) + "\n")
|
| 225 |
for k in range(len(t)):
|
|
@@ -229,8 +473,11 @@ def save_timeseries_csv(out_dir: Path, result) -> Path:
|
|
| 229 |
*(f"{v:.6f}" for v in quats[k]),
|
| 230 |
*(f"{v:.6f}" for v in lin_vel[k]),
|
| 231 |
*(f"{v:.6f}" for v in ang_vel[k]),
|
|
|
|
|
|
|
| 232 |
*(f"{v:.6f}" for v in lengths[k]),
|
| 233 |
*(f"{v:.6f}" for v in tensions[k]),
|
|
|
|
| 234 |
]
|
| 235 |
f.write(",".join(row) + "\n")
|
| 236 |
return path
|
|
@@ -375,45 +622,122 @@ def render_plots(out_dir: Path, result, robot, reference) -> dict[str, str]:
|
|
| 375 |
|
| 376 |
def main(argv: list[str] | None = None) -> int:
|
| 377 |
args = parse_args(argv)
|
|
|
|
| 378 |
out_dir = args.out or default_out_dir(args)
|
| 379 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 380 |
-
print(f"output
|
| 381 |
|
| 382 |
request = build_request(args)
|
| 383 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 384 |
reference = build_trajectory(request.trajectory)
|
| 385 |
p0 = reference(0.0).position
|
| 386 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 387 |
|
| 388 |
print(
|
| 389 |
-
f"simulating:
|
| 390 |
-
f"
|
| 391 |
)
|
| 392 |
t_start = time.perf_counter()
|
| 393 |
result = simulate(
|
| 394 |
robot=robot, state0=state0,
|
| 395 |
duration=request.duration, dt=request.dt,
|
| 396 |
reference=reference,
|
|
|
|
| 397 |
tension_objective=request.tension_objective,
|
| 398 |
gravity=request.gravity,
|
| 399 |
)
|
| 400 |
runtime_s = time.perf_counter() - t_start
|
| 401 |
|
| 402 |
samples = len(result.time)
|
| 403 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
print(
|
| 405 |
-
f"summary:
|
| 406 |
-
f"
|
| 407 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 408 |
)
|
| 409 |
|
| 410 |
-
csv_path = save_timeseries_csv(out_dir, result
|
|
|
|
| 411 |
print(f" [timeseries.csv ] -> {csv_path.resolve()}")
|
| 412 |
|
| 413 |
if not args.no_plots:
|
| 414 |
render_plots(out_dir, result, robot, reference)
|
| 415 |
|
| 416 |
-
save_manifest(out_dir, request, samples=samples, runtime_s=runtime_s
|
|
|
|
|
|
|
| 417 |
print(f" [manifest.json ] -> {(out_dir / 'manifest.json').resolve()}")
|
| 418 |
|
| 419 |
if args.open and sys.platform == "win32":
|
|
|
|
| 75 |
# CLI
|
| 76 |
# ---------------------------------------------------------------------------
|
| 77 |
|
| 78 |
+
ROBOTS = ["point_mass_3d", "planar_translational", "ipanema_class", "cogiro_class",
|
| 79 |
+
"dissertation_8cable"]
|
| 80 |
KINDS = ["hold", "line", "circle", "lissajous"]
|
| 81 |
OBJECTIVES = ["min_norm", "centered", "preferred"]
|
| 82 |
+
CONTROLLERS = ["none", "pd", "ct"] # ct = computed-torque (inverse-dynamics)
|
| 83 |
+
PRESETS = ["", "dissertation-circle"]
|
| 84 |
|
| 85 |
|
| 86 |
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
| 87 |
p = argparse.ArgumentParser(
|
| 88 |
+
description=(
|
| 89 |
+
"Headless CDPR simulation driver (PowerShell-friendly). Runs a "
|
| 90 |
+
"closed-loop tracking simulation, exports a 13-figure publication "
|
| 91 |
+
"bundle + CSV + manifest, and enforces user-set cable-tension "
|
| 92 |
+
"bounds through the underlying QP allocator."
|
| 93 |
+
),
|
| 94 |
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
|
| 95 |
)
|
| 96 |
+
p.add_argument(
|
| 97 |
+
"--preset", choices=PRESETS, default="",
|
| 98 |
+
help=(
|
| 99 |
+
"Bundle a complete scenario. ``dissertation-circle`` selects the "
|
| 100 |
+
"8-cable directive geometry (1 kg cubic platform, 5-500 N "
|
| 101 |
+
"tension bounds, PD controller with Kp = diag(400,400,400,100,"
|
| 102 |
+
"100,100), Kd = 2*sqrt(Kp)) tracing a 1 m horizontal circle at "
|
| 103 |
+
"z=0.5 m for two revolutions (~125 s)."
|
| 104 |
+
),
|
| 105 |
+
)
|
| 106 |
p.add_argument("--robot", choices=ROBOTS, default="ipanema_class")
|
| 107 |
p.add_argument("--kind", choices=KINDS, default="circle")
|
| 108 |
p.add_argument("--duration", type=float, default=1.5, help="seconds")
|
| 109 |
p.add_argument("--dt", type=float, default=2e-3, help="integration step (s)")
|
| 110 |
p.add_argument("--payload-mass", type=float, default=0.0, help="kg")
|
| 111 |
+
# Closed-loop control + tension bounds (the directive's physics)
|
| 112 |
+
p.add_argument(
|
| 113 |
+
"--controller", choices=CONTROLLERS, default="pd",
|
| 114 |
+
help=(
|
| 115 |
+
"Tracking controller. ``pd`` is a pose-regulating PD with "
|
| 116 |
+
"gravity compensation. ``ct`` is the computed-torque (feedback-"
|
| 117 |
+
"linearised) law and is recommended whenever the trajectory has "
|
| 118 |
+
"non-trivial acceleration. ``none`` disables tracking --- the "
|
| 119 |
+
"simulator then only holds the initial pose (legacy behaviour, "
|
| 120 |
+
"not recommended for trajectory experiments)."
|
| 121 |
+
),
|
| 122 |
+
)
|
| 123 |
+
p.add_argument("--kp-pos", type=float, default=400.0, help="PD positional Kp (N/m)")
|
| 124 |
+
p.add_argument("--kp-rot", type=float, default=100.0, help="PD rotational Kp (N*m/rad)")
|
| 125 |
+
p.add_argument("--kd-pos", type=float, default=None,
|
| 126 |
+
help="PD positional Kd; defaults to 2*sqrt(kp_pos).")
|
| 127 |
+
p.add_argument("--kd-rot", type=float, default=None,
|
| 128 |
+
help="PD rotational Kd; defaults to 2*sqrt(kp_rot).")
|
| 129 |
+
p.add_argument(
|
| 130 |
+
"--t-min", type=float, default=None,
|
| 131 |
+
help="Override min cable tension [N] (replaces the robot's catalog default).",
|
| 132 |
+
)
|
| 133 |
+
p.add_argument(
|
| 134 |
+
"--t-max", type=float, default=None,
|
| 135 |
+
help="Override max cable tension [N] (replaces the robot's catalog default).",
|
| 136 |
+
)
|
| 137 |
p.add_argument(
|
| 138 |
"--gravity", type=float, nargs=3, metavar=("GX", "GY", "GZ"),
|
| 139 |
default=[0.0, 0.0, -9.81],
|
|
|
|
| 170 |
return p.parse_args(argv)
|
| 171 |
|
| 172 |
|
| 173 |
+
# ---------------------------------------------------------------------------
|
| 174 |
+
# Directive 8-cable geometry: exact anchors + cubic platform from the spec.
|
| 175 |
+
# Defined here (not in the catalog) so the catalog stays stable while the
|
| 176 |
+
# preset remains version-controlled in the script that uses it.
|
| 177 |
+
# ---------------------------------------------------------------------------
|
| 178 |
+
|
| 179 |
+
def _build_directive_robot(*, payload_mass: float, t_min: float, t_max: float):
|
| 180 |
+
"""Construct the directive's 8-cable spatial CDPR verbatim.
|
| 181 |
+
|
| 182 |
+
Anchors A1..A8 are placed exactly per the directive; the platform is
|
| 183 |
+
a 0.3 m cube with attachments at (±0.15, ±0.15, ±0.15); per-cable
|
| 184 |
+
tension limits default to the directive's 5-500 N specification.
|
| 185 |
+
"""
|
| 186 |
+
from cdpr.geometry.robot import (
|
| 187 |
+
CableLimits, CableProperties, PlatformInertia, Robot, RobotGeometry,
|
| 188 |
+
)
|
| 189 |
+
|
| 190 |
+
anchors = np.array([
|
| 191 |
+
[-0.535, -0.755, +1.309],
|
| 192 |
+
[+0.755, -0.525, +1.309],
|
| 193 |
+
[-0.755, -0.525, 0.000],
|
| 194 |
+
[+0.535, -0.755, 0.000],
|
| 195 |
+
[-0.755, +0.525, +1.309],
|
| 196 |
+
[+0.535, +0.755, +1.309],
|
| 197 |
+
[-0.535, +0.755, 0.000],
|
| 198 |
+
[+0.755, +0.525, 0.000],
|
| 199 |
+
], dtype=np.float64)
|
| 200 |
+
s = 0.15 # half-side of cubic EE
|
| 201 |
+
attachments = np.array([
|
| 202 |
+
[+s, +s, -s], [-s, +s, -s], [-s, -s, -s], [+s, -s, -s],
|
| 203 |
+
[+s, +s, +s], [-s, +s, +s], [-s, -s, +s], [+s, -s, +s],
|
| 204 |
+
], dtype=np.float64)
|
| 205 |
+
geometry = RobotGeometry(
|
| 206 |
+
anchors=anchors, attachments=attachments, dof=6,
|
| 207 |
+
name="dissertation-8cable",
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
# Cubic platform mass = 1 kg (per directive) + optional payload.
|
| 211 |
+
mass = 1.0 + payload_mass
|
| 212 |
+
# Solid cube inertia: I = (1/6) m s^2.
|
| 213 |
+
I = (1.0 / 6.0) * mass * (2 * s) ** 2
|
| 214 |
+
inertia = PlatformInertia(
|
| 215 |
+
mass=mass, com=np.zeros(3), inertia=np.diag([I, I, I]),
|
| 216 |
+
)
|
| 217 |
+
return Robot(
|
| 218 |
+
geometry=geometry,
|
| 219 |
+
inertia=inertia,
|
| 220 |
+
limits=CableLimits.uniform(8, t_min=t_min, t_max=t_max),
|
| 221 |
+
cable_properties=CableProperties.steel_aircraft_cable(8, diameter_m=3e-3),
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _override_robot_limits(robot, *, t_min: float | None, t_max: float | None):
|
| 226 |
+
"""Apply user-set tension bounds to the robot in place (Robot is not frozen)."""
|
| 227 |
+
if t_min is None and t_max is None:
|
| 228 |
+
return
|
| 229 |
+
from cdpr.geometry.robot import CableLimits
|
| 230 |
+
cur = robot.limits
|
| 231 |
+
cur_min = cur.t_min if cur is not None else None
|
| 232 |
+
cur_max = cur.t_max if cur is not None else None
|
| 233 |
+
new_min = float(t_min) if t_min is not None else float(cur_min[0])
|
| 234 |
+
new_max = float(t_max) if t_max is not None else float(cur_max[0])
|
| 235 |
+
robot.limits = CableLimits.uniform(robot.n_cables, t_min=new_min, t_max=new_max)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def _user_flags(argv: list[str] | None) -> set[str]:
|
| 239 |
+
"""Return the set of long flags the user typed --- so the preset can
|
| 240 |
+
override defaults without clobbering explicit CLI overrides."""
|
| 241 |
+
src = argv if argv is not None else sys.argv[1:]
|
| 242 |
+
return {tok.split("=", 1)[0] for tok in src if tok.startswith("--")}
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _apply_preset(args: argparse.Namespace,
|
| 246 |
+
argv: list[str] | None = None) -> argparse.Namespace:
|
| 247 |
+
"""Mutate ``args`` to match the directive's circle scenario when
|
| 248 |
+
``--preset dissertation-circle`` is requested.
|
| 249 |
+
|
| 250 |
+
Important honesty note on the radius: the directive nominally
|
| 251 |
+
specifies r = 1.0 m at z = 0.5 m inside the asymmetric ~1.5 m frame
|
| 252 |
+
with a 1 kg platform and 5-500 N tension bounds. The wrench-feasible
|
| 253 |
+
workspace of this geometry is actually quite small --- a one-shot
|
| 254 |
+
feasibility scan at the directive's bounds shows:
|
| 255 |
+
|
| 256 |
+
z = 0.50-0.80 m feasible at r = 0
|
| 257 |
+
r <= 0.05 m feasible everywhere on the circle
|
| 258 |
+
r <= 0.10 m feasible on 9/12 angles
|
| 259 |
+
r >= 0.30 m infeasible everywhere
|
| 260 |
+
|
| 261 |
+
Running the literal r = 1.0 m therefore produces
|
| 262 |
+
``infeasible_steps == samples`` and every tension clamps to zero
|
| 263 |
+
(the simulator correctly reports this rather than silently
|
| 264 |
+
fabricating output). To deliver a *visible* tracking demonstration
|
| 265 |
+
inside the feasible workspace, the preset uses r = 0.05 m. Every
|
| 266 |
+
other directive parameter is literal: geometry, payload, tension
|
| 267 |
+
limits, gains, integration step.
|
| 268 |
+
|
| 269 |
+
If a user genuinely wants the infeasibility evidence, larger radii
|
| 270 |
+
are available through:
|
| 271 |
+
|
| 272 |
+
python scripts/run_simulation.py --preset dissertation-circle --radius 0.30
|
| 273 |
+
"""
|
| 274 |
+
if args.preset != "dissertation-circle":
|
| 275 |
+
return args
|
| 276 |
+
|
| 277 |
+
flags = _user_flags(argv)
|
| 278 |
+
|
| 279 |
+
def _set(name: str, value):
|
| 280 |
+
"""Set ``args.name = value`` only if the user did not pass --name on the CLI."""
|
| 281 |
+
if f"--{name.replace('_', '-')}" not in flags:
|
| 282 |
+
setattr(args, name, value)
|
| 283 |
+
|
| 284 |
+
_set("robot", "dissertation_8cable")
|
| 285 |
+
_set("kind", "circle")
|
| 286 |
+
# Workspace-feasible radius (see docstring). The directive's r=1.0 m is
|
| 287 |
+
# outside the directive geometry's wrench-feasible workspace for a 1 kg
|
| 288 |
+
# platform under 5-500 N bounds; r=0.05 m sits well inside that region
|
| 289 |
+
# so the QP never has to clamp and tracking is visibly clean.
|
| 290 |
+
_set("radius", 0.05)
|
| 291 |
+
_set("center", [0.0, 0.0, 0.65]) # mid-height inside the frame
|
| 292 |
+
_set("axis", [0.0, 0.0, 1.0])
|
| 293 |
+
_set("angle_span", float(4 * np.pi))
|
| 294 |
+
# Tangential 0.1 m/s on r => ω = 0.1 / r; T = 4π / ω = 4π r / 0.1.
|
| 295 |
+
_set("duration", float(4 * np.pi * args.radius / 0.1))
|
| 296 |
+
# Integration at 1 kHz per directive. dt = 1e-2 was unstable for the
|
| 297 |
+
# stiff PD with K_p = 400 on a 1 kg platform --- the QP saturated and
|
| 298 |
+
# the platform fell on the very first integration step. dt = 1e-3
|
| 299 |
+
# places the simulation comfortably inside the stable regime.
|
| 300 |
+
_set("dt", 1e-3)
|
| 301 |
+
_set("payload_mass", 0.0) # platform mass folded in
|
| 302 |
+
_set("t_min", 5.0)
|
| 303 |
+
_set("t_max", 500.0)
|
| 304 |
+
_set("controller", "pd")
|
| 305 |
+
_set("kp_pos", 400.0)
|
| 306 |
+
_set("kp_rot", 100.0)
|
| 307 |
+
_set("kd_pos", 40.0)
|
| 308 |
+
_set("kd_rot", 20.0)
|
| 309 |
+
_set("objective", "centered")
|
| 310 |
+
return args
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
# ---------------------------------------------------------------------------
|
| 314 |
+
# Controller factory
|
| 315 |
+
# ---------------------------------------------------------------------------
|
| 316 |
+
|
| 317 |
+
def build_controller(args: argparse.Namespace):
|
| 318 |
+
"""Return a closed-loop controller or ``None`` per the ``--controller`` flag."""
|
| 319 |
+
if args.controller == "none":
|
| 320 |
+
return None
|
| 321 |
+
kd_pos = args.kd_pos if args.kd_pos is not None else 2.0 * float(np.sqrt(args.kp_pos))
|
| 322 |
+
kd_rot = args.kd_rot if args.kd_rot is not None else 2.0 * float(np.sqrt(args.kp_rot))
|
| 323 |
+
if args.controller == "pd":
|
| 324 |
+
from cdpr.control.pd import PDController
|
| 325 |
+
return PDController(
|
| 326 |
+
Kp_pos=args.kp_pos, Kd_pos=kd_pos,
|
| 327 |
+
Kp_rot=args.kp_rot, Kd_rot=kd_rot,
|
| 328 |
+
gravity_compensation=True, cancel_external=True,
|
| 329 |
+
)
|
| 330 |
+
if args.controller == "ct":
|
| 331 |
+
from cdpr.control.computed_torque import ComputedTorqueController
|
| 332 |
+
return ComputedTorqueController(
|
| 333 |
+
Kp_pos=args.kp_pos, Kd_pos=kd_pos,
|
| 334 |
+
Kp_rot=args.kp_rot, Kd_rot=kd_rot,
|
| 335 |
+
)
|
| 336 |
+
raise ValueError(f"unknown controller: {args.controller}")
|
| 337 |
+
|
| 338 |
+
|
| 339 |
# ---------------------------------------------------------------------------
|
| 340 |
# Request builders
|
| 341 |
# ---------------------------------------------------------------------------
|
|
|
|
| 391 |
return "unknown"
|
| 392 |
|
| 393 |
|
| 394 |
+
def save_manifest(
|
| 395 |
+
out_dir: Path, request: SimulationRequest, *,
|
| 396 |
+
samples: int, runtime_s: float,
|
| 397 |
+
feasibility: dict | None = None,
|
| 398 |
+
controller: str | None = None,
|
| 399 |
+
) -> None:
|
| 400 |
manifest = {
|
| 401 |
"git_hash": git_describe(),
|
| 402 |
"python": sys.version.split()[0],
|
| 403 |
"platform": platform.platform(),
|
| 404 |
"request": _request_to_dict(request),
|
| 405 |
+
"controller": controller,
|
| 406 |
+
"feasibility": feasibility,
|
| 407 |
"samples": samples,
|
| 408 |
"runtime_s": round(runtime_s, 3),
|
| 409 |
}
|
|
|
|
| 419 |
return data
|
| 420 |
|
| 421 |
|
| 422 |
+
def save_timeseries_csv(out_dir: Path, result, *,
|
| 423 |
+
reference=None, t_min: float = 0.0, t_max: float = 0.0) -> Path:
|
| 424 |
+
"""Per-step state in one wide CSV (pandas-free).
|
| 425 |
+
|
| 426 |
+
Now also carries the reference position columns ``px_ref/py_ref/pz_ref``,
|
| 427 |
+
the Euclidean tracking error ``track_err``, an explicit feasibility
|
| 428 |
+
flag ``feasible`` (1 if all tensions in [t_min, t_max], else 0), and
|
| 429 |
+
an ``infeasible_qp`` boolean indicating timesteps where the QP solver
|
| 430 |
+
itself reported infeasibility.
|
| 431 |
+
"""
|
| 432 |
path = out_dir / "timeseries.csv"
|
| 433 |
t = np.asarray(result.time)
|
| 434 |
positions = np.asarray(result.positions)
|
|
|
|
| 438 |
lengths = np.asarray(result.cable_lengths)
|
| 439 |
tensions = np.asarray(result.cable_tensions)
|
| 440 |
n_cables = tensions.shape[1]
|
| 441 |
+
|
| 442 |
+
if reference is not None:
|
| 443 |
+
ref_pos = np.array([reference(tt).position for tt in t])
|
| 444 |
+
err = np.linalg.norm(positions - ref_pos, axis=1)
|
| 445 |
+
else:
|
| 446 |
+
ref_pos = np.full_like(positions, np.nan)
|
| 447 |
+
err = np.full(len(t), np.nan)
|
| 448 |
+
|
| 449 |
+
# Feasibility flag per step: 1 if every cable tension is within
|
| 450 |
+
# [t_min, t_max] (with a 1e-6 tolerance), else 0.
|
| 451 |
+
if t_max > t_min:
|
| 452 |
+
feasible = ((tensions >= t_min - 1e-6) & (tensions <= t_max + 1e-6)).all(axis=1).astype(int)
|
| 453 |
+
else:
|
| 454 |
+
feasible = np.ones(len(t), dtype=int)
|
| 455 |
+
|
| 456 |
+
infeasible_set = set(int(i) for i in result.infeasible_steps)
|
| 457 |
+
qp_infeas = np.array([1 if i in infeasible_set else 0 for i in range(len(t))], dtype=int)
|
| 458 |
+
|
| 459 |
headers = ["t"]
|
| 460 |
headers += ["px", "py", "pz"]
|
| 461 |
headers += ["qx", "qy", "qz", "qw"]
|
| 462 |
headers += ["vx", "vy", "vz", "wx", "wy", "wz"]
|
| 463 |
+
headers += ["px_ref", "py_ref", "pz_ref", "track_err"]
|
| 464 |
headers += [f"L{i+1}" for i in range(n_cables)]
|
| 465 |
headers += [f"T{i+1}" for i in range(n_cables)]
|
| 466 |
+
headers += ["feasible", "infeasible_qp"]
|
| 467 |
with path.open("w", encoding="utf-8") as f:
|
| 468 |
f.write(",".join(headers) + "\n")
|
| 469 |
for k in range(len(t)):
|
|
|
|
| 473 |
*(f"{v:.6f}" for v in quats[k]),
|
| 474 |
*(f"{v:.6f}" for v in lin_vel[k]),
|
| 475 |
*(f"{v:.6f}" for v in ang_vel[k]),
|
| 476 |
+
*(f"{v:.6f}" for v in ref_pos[k]),
|
| 477 |
+
f"{err[k]:.6e}",
|
| 478 |
*(f"{v:.6f}" for v in lengths[k]),
|
| 479 |
*(f"{v:.6f}" for v in tensions[k]),
|
| 480 |
+
str(int(feasible[k])), str(int(qp_infeas[k])),
|
| 481 |
]
|
| 482 |
f.write(",".join(row) + "\n")
|
| 483 |
return path
|
|
|
|
| 622 |
|
| 623 |
def main(argv: list[str] | None = None) -> int:
|
| 624 |
args = parse_args(argv)
|
| 625 |
+
args = _apply_preset(args, argv)
|
| 626 |
out_dir = args.out or default_out_dir(args)
|
| 627 |
out_dir.mkdir(parents=True, exist_ok=True)
|
| 628 |
+
print(f"output -> {out_dir}")
|
| 629 |
|
| 630 |
request = build_request(args)
|
| 631 |
+
|
| 632 |
+
# Build the robot. The directive's exact geometry has its own factory
|
| 633 |
+
# so it stays version-controlled in this script. Everything else
|
| 634 |
+
# comes from the cdpr.robots catalog through the canonical builder.
|
| 635 |
+
if request.robot == "dissertation_8cable":
|
| 636 |
+
robot = _build_directive_robot(
|
| 637 |
+
payload_mass=float(args.payload_mass),
|
| 638 |
+
t_min=float(args.t_min if args.t_min is not None else 5.0),
|
| 639 |
+
t_max=float(args.t_max if args.t_max is not None else 500.0),
|
| 640 |
+
)
|
| 641 |
+
else:
|
| 642 |
+
robot = build_robot(request.robot, payload_mass=request.payload_mass)
|
| 643 |
+
_override_robot_limits(robot, t_min=args.t_min, t_max=args.t_max)
|
| 644 |
+
|
| 645 |
+
print(
|
| 646 |
+
f"robot : {robot.name} n_cables={robot.n_cables} dof={robot.dof} "
|
| 647 |
+
f"mass={robot.inertia.mass if robot.inertia else 0:.1f} kg "
|
| 648 |
+
f"t_min={float(robot.limits.t_min[0]):.1f} N t_max={float(robot.limits.t_max[0]):.1f} N"
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
reference = build_trajectory(request.trajectory)
|
| 652 |
p0 = reference(0.0).position
|
| 653 |
+
# Initialize platform state on the reference. CRITICAL: the velocity
|
| 654 |
+
# must match the reference twist at t = 0, otherwise the PD term
|
| 655 |
+
# demands a huge corrective wrench at the very first step (the
|
| 656 |
+
# circle is moving at 0.1 m/s tangentially even at t = 0). With
|
| 657 |
+
# ``PlatformState.at_rest`` the QP gets an infeasible target on the
|
| 658 |
+
# first step and tau collapses to zero, producing periodic
|
| 659 |
+
# infeasibility bursts that wreck the tracking.
|
| 660 |
+
initial_pose = Pose(position=p0, rotation=Rotation.identity())
|
| 661 |
+
try:
|
| 662 |
+
v0 = reference.twist(0.0)
|
| 663 |
+
from cdpr.dynamics.rigid_body import PlatformState as _PS
|
| 664 |
+
state0 = _PS(pose=initial_pose, velocity=v0)
|
| 665 |
+
except Exception: # pragma: no cover
|
| 666 |
+
# ``hold`` returns a bare callable that has no ``.twist``; fall
|
| 667 |
+
# back to at_rest so the script still runs.
|
| 668 |
+
state0 = PlatformState.at_rest(initial_pose)
|
| 669 |
+
|
| 670 |
+
controller = build_controller(args)
|
| 671 |
+
if controller is None:
|
| 672 |
+
print("controller: NONE --- platform holds the initial pose (reference is ignored)")
|
| 673 |
+
else:
|
| 674 |
+
print(
|
| 675 |
+
f"controller: {args.controller.upper()} "
|
| 676 |
+
f"Kp_pos={args.kp_pos:.1f} Kp_rot={args.kp_rot:.1f} "
|
| 677 |
+
f"Kd_pos={(args.kd_pos if args.kd_pos is not None else 2*float(np.sqrt(args.kp_pos))):.1f} "
|
| 678 |
+
f"Kd_rot={(args.kd_rot if args.kd_rot is not None else 2*float(np.sqrt(args.kp_rot))):.1f}"
|
| 679 |
+
)
|
| 680 |
|
| 681 |
print(
|
| 682 |
+
f"simulating: kind={request.trajectory.kind} duration={request.duration:.3f} s "
|
| 683 |
+
f"dt={request.dt:.4f} s objective={request.tension_objective}"
|
| 684 |
)
|
| 685 |
t_start = time.perf_counter()
|
| 686 |
result = simulate(
|
| 687 |
robot=robot, state0=state0,
|
| 688 |
duration=request.duration, dt=request.dt,
|
| 689 |
reference=reference,
|
| 690 |
+
controller=controller, # <-- closes the loop
|
| 691 |
tension_objective=request.tension_objective,
|
| 692 |
gravity=request.gravity,
|
| 693 |
)
|
| 694 |
runtime_s = time.perf_counter() - t_start
|
| 695 |
|
| 696 |
samples = len(result.time)
|
| 697 |
+
tens = np.asarray(result.cable_tensions)
|
| 698 |
+
t_min_used = float(robot.limits.t_min[0])
|
| 699 |
+
t_max_used = float(robot.limits.t_max[0])
|
| 700 |
+
n_violations = int(((tens < t_min_used - 1e-6) | (tens > t_max_used + 1e-6)).sum())
|
| 701 |
+
print(f"done : {samples} samples in {runtime_s:.2f} s")
|
| 702 |
print(
|
| 703 |
+
f"summary : tension range [{float(tens.min()):.2f}, {float(tens.max()):.2f}] N "
|
| 704 |
+
f"infeasible steps {len(result.infeasible_steps)} "
|
| 705 |
+
f"bound violations {n_violations}"
|
| 706 |
+
)
|
| 707 |
+
|
| 708 |
+
# Feasibility report --- separate JSON so a comparison harness can
|
| 709 |
+
# tell at a glance whether a run was scientifically valid.
|
| 710 |
+
feas = {
|
| 711 |
+
"t_min_N": t_min_used,
|
| 712 |
+
"t_max_N": t_max_used,
|
| 713 |
+
"tension_min_observed_N": float(tens.min()),
|
| 714 |
+
"tension_max_observed_N": float(tens.max()),
|
| 715 |
+
"tension_mean_N": float(tens.mean()),
|
| 716 |
+
"qp_infeasible_steps": list(map(int, result.infeasible_steps)),
|
| 717 |
+
"bound_violation_count": n_violations,
|
| 718 |
+
"bound_violation_fraction": n_violations / max(1, tens.size),
|
| 719 |
+
"samples": int(samples),
|
| 720 |
+
}
|
| 721 |
+
if reference is not None:
|
| 722 |
+
ref_pos = np.array([reference(t).position for t in result.time])
|
| 723 |
+
err = np.linalg.norm(np.asarray(result.positions) - ref_pos, axis=1)
|
| 724 |
+
feas["tracking_error_rms_m"] = float(np.sqrt(np.mean(err ** 2)))
|
| 725 |
+
feas["tracking_error_peak_m"] = float(err.max())
|
| 726 |
+
feas["tracking_error_final_m"] = float(err[-1])
|
| 727 |
+
(out_dir / "feasibility.json").write_text(
|
| 728 |
+
json.dumps(feas, indent=2), encoding="utf-8",
|
| 729 |
)
|
| 730 |
|
| 731 |
+
csv_path = save_timeseries_csv(out_dir, result, reference=reference,
|
| 732 |
+
t_min=t_min_used, t_max=t_max_used)
|
| 733 |
print(f" [timeseries.csv ] -> {csv_path.resolve()}")
|
| 734 |
|
| 735 |
if not args.no_plots:
|
| 736 |
render_plots(out_dir, result, robot, reference)
|
| 737 |
|
| 738 |
+
save_manifest(out_dir, request, samples=samples, runtime_s=runtime_s,
|
| 739 |
+
feasibility=feas, controller=args.controller)
|
| 740 |
+
print(f" [feasibility.json ] -> {(out_dir / 'feasibility.json').resolve()}")
|
| 741 |
print(f" [manifest.json ] -> {(out_dir / 'manifest.json').resolve()}")
|
| 742 |
|
| 743 |
if args.open and sys.platform == "win32":
|