JoeTach Claude Opus 4.7 commited on
Commit
6045fb3
·
1 Parent(s): f2c274d

Add PowerShell CLI escape hatch + Streamlit diagnostic fallback

Browse files

The deployed Streamlit Cloud worker keeps blanking on every interaction
even after the GUI was reconciled with the real SimulationRequest /
TrajectorySpec contract --- the issue is now almost certainly in
Streamlit Cloud's runtime, not in the Python script. Render, Cloudflare
Pages, Supabase, and GitHub Actions are all green; only the Streamlit
worker is unreliable.

This commit lands two escape hatches plus one diagnostic toggle so the
user is not blocked by the Cloud-side flakiness:

scripts/run_simulation.py
PowerShell-friendly local driver:

python scripts/run_simulation.py --robot ipanema_class --kind circle

produces every plot the Streamlit GUI would have shown, plus a
timeseries CSV and a manifest with the git hash, into
./out/<robot>-<kind>-<timestamp>/. Each plot is wrapped in its own
try/except so a single render failure does not drop the others.

scripts/call_render.ps1
PowerShell wrapper around the live FastAPI on Render:

.\scripts\call_render.ps1 -Action health
.\scripts\call_render.ps1 -Action simulate -Kind circle
.\scripts\call_render.ps1 -Action plot -PlotKind cable_tensions -OpenPng

Honours the 180 s timeout for the ~50 s free-tier cold start, decodes
/plot responses to PNG on disk, opens them in the default viewer.

streamlit_app.py CDPR_GUI_DIAG=1 toggle
When the env var is set in the Streamlit Cloud Secrets tab, the
page swaps to a minimal one-button counter --- a clean A/B against
the full console. If even this page blanks on click, the Cloud
worker itself is unhealthy and the CLI / API escape hatches above
are the supported path forward until Cloud recovers.

Also fixed a pre-existing mathtext label that mathtext cannot parse
(`\lVert` / `\rVert` are amsmath, usetex-only); the tracking-error
y-axis label now uses `\|...\|` which works in mathtext's reduced
grammar. tests/test_viz_plots2d.py: 9 passed.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

.gitignore CHANGED
@@ -38,6 +38,7 @@ results/
38
  artifacts/
39
  runs/
40
  checkpoints/
 
41
  *.mp4
42
  *.gif
43
  *.h5
 
38
  artifacts/
39
  runs/
40
  checkpoints/
41
+ out/ # scripts/run_simulation.py output
42
  *.mp4
43
  *.gif
44
  *.h5
scripts/call_render.ps1 ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <#
2
+ .SYNOPSIS
3
+ Drive the live Render FastAPI from PowerShell --- run a simulation,
4
+ request a plot, save the PNG to disk, open it in the default viewer.
5
+
6
+ .DESCRIPTION
7
+ The deployed backend at https://cdpr-api.onrender.com exposes:
8
+ GET /health -- liveness check
9
+ GET /robots -- catalogue
10
+ POST /simulate -- forward integration (returns JSON timeseries)
11
+ POST /plot -- render a plot (returns {"png_base64": "..."})
12
+ POST /workspace -- WCW / WFW grid scan
13
+
14
+ The free tier sleeps after 15 min idle. The first request can take
15
+ ~50 s while the container wakes; later requests respond in under a
16
+ second. This script reuses the cached connection so the cold start
17
+ only happens once per PowerShell session.
18
+
19
+ .PARAMETER Action
20
+ One of: health, robots, simulate, plot, workspace.
21
+
22
+ .PARAMETER Robot
23
+ Reference robot name. Defaults to ipanema_class.
24
+
25
+ .PARAMETER Kind
26
+ Trajectory kind: hold, line, circle, lissajous. Default circle.
27
+
28
+ .PARAMETER Duration
29
+ Simulation length in seconds. Default 1.5.
30
+
31
+ .PARAMETER Dt
32
+ Integration step in seconds. Default 2e-3.
33
+
34
+ .PARAMETER PlotKind
35
+ For Action=plot: which plot to render (position, cable_tensions,
36
+ cable_lengths, tracking_error, condition_number,
37
+ trajectory_xy / xz / yz).
38
+
39
+ .PARAMETER OutDir
40
+ Where to drop response JSON / PNG. Defaults to ./out/render-<stamp>/.
41
+
42
+ .PARAMETER OpenPng
43
+ For Action=plot: open the saved PNG in the default viewer.
44
+
45
+ .PARAMETER BaseUrl
46
+ Override the API root. Defaults to the live Render URL.
47
+
48
+ .EXAMPLE
49
+ # Liveness check (also a good way to warm the worker before a big call).
50
+ .\scripts\call_render.ps1 -Action health
51
+
52
+ .EXAMPLE
53
+ # Run a circle and save the JSON response.
54
+ .\scripts\call_render.ps1 -Action simulate -Robot ipanema_class -Kind circle
55
+
56
+ .EXAMPLE
57
+ # Render a tension plot and pop it open.
58
+ .\scripts\call_render.ps1 -Action plot -PlotKind cable_tensions -OpenPng
59
+
60
+ #>
61
+
62
+ [CmdletBinding()]
63
+ param(
64
+ [Parameter(Mandatory=$true)]
65
+ [ValidateSet("health", "robots", "simulate", "plot", "workspace")]
66
+ [string]$Action,
67
+
68
+ [ValidateSet("point_mass_3d", "planar_translational", "ipanema_class", "cogiro_class")]
69
+ [string]$Robot = "ipanema_class",
70
+
71
+ [ValidateSet("hold", "line", "circle", "lissajous")]
72
+ [string]$Kind = "circle",
73
+
74
+ [double]$Duration = 1.5,
75
+ [double]$Dt = 2e-3,
76
+ [double]$PayloadMass = 0.0,
77
+
78
+ [ValidateSet("min_norm", "centered", "preferred")]
79
+ [string]$Objective = "centered",
80
+
81
+ [ValidateSet(
82
+ "position", "velocity", "angular_velocity",
83
+ "cable_lengths", "cable_tensions",
84
+ "tracking_error", "condition_number",
85
+ "trajectory_xy", "trajectory_xz", "trajectory_yz"
86
+ )]
87
+ [string]$PlotKind = "position",
88
+
89
+ [string]$OutDir = "",
90
+ [switch]$OpenPng,
91
+ [string]$BaseUrl = "https://cdpr-api.onrender.com"
92
+ )
93
+
94
+ $ErrorActionPreference = "Stop"
95
+
96
+ # Resolve output directory.
97
+ if (-not $OutDir) {
98
+ $stamp = Get-Date -Format "yyyyMMdd-HHmmss"
99
+ $OutDir = Join-Path -Path (Get-Location) -ChildPath "out\render-$stamp"
100
+ }
101
+ if (-not (Test-Path $OutDir)) {
102
+ New-Item -ItemType Directory -Force -Path $OutDir | Out-Null
103
+ }
104
+
105
+ Write-Host ("[call_render] base = {0}" -f $BaseUrl)
106
+ Write-Host ("[call_render] action = {0}" -f $Action)
107
+ Write-Host ("[call_render] outdir = {0}" -f $OutDir)
108
+
109
+ function Write-Json {
110
+ param([string]$Path, $Object)
111
+ $Object | ConvertTo-Json -Depth 12 | Out-File -FilePath $Path -Encoding utf8
112
+ Write-Host ("[call_render] wrote -> {0}" -f $Path)
113
+ }
114
+
115
+ # Build the per-action request body.
116
+ $body = $null
117
+ switch ($Action) {
118
+ "health" { $url = "$BaseUrl/health"; $method = "GET" }
119
+ "robots" { $url = "$BaseUrl/robots"; $method = "GET" }
120
+ "simulate" {
121
+ $url = "$BaseUrl/simulate"; $method = "POST"
122
+ $params = switch ($Kind) {
123
+ "line" {
124
+ @{ start = @(0.0, 0.0, 0.5); end = @(0.3, 0.0, 0.5) }
125
+ }
126
+ "circle" {
127
+ @{
128
+ center = @(0.0, 0.0, 0.5)
129
+ radius = 0.2
130
+ axis = @(0.0, 0.0, 1.0)
131
+ angle_span = [math]::PI * 2.0
132
+ }
133
+ }
134
+ "lissajous" {
135
+ @{
136
+ center = @(0.0, 0.0, 0.5)
137
+ amplitudes = @(0.2, 0.2, 0.0)
138
+ frequencies = @(1.0, 2.0, 0.0)
139
+ phases = @(0.0, [math]::PI / 2.0, 0.0)
140
+ }
141
+ }
142
+ default { @{} }
143
+ }
144
+ $body = @{
145
+ robot = $Robot
146
+ payload_mass = $PayloadMass
147
+ duration = $Duration
148
+ dt = $Dt
149
+ tension_objective = $Objective
150
+ gravity = @(0.0, 0.0, -9.81)
151
+ trajectory = @{ kind = $Kind; duration = $Duration; params = $params }
152
+ }
153
+ }
154
+ "plot" {
155
+ $url = "$BaseUrl/plot"; $method = "POST"
156
+ $body = @{
157
+ kind = $PlotKind
158
+ simulate = @{
159
+ robot = $Robot
160
+ payload_mass = $PayloadMass
161
+ duration = $Duration
162
+ dt = $Dt
163
+ tension_objective = $Objective
164
+ gravity = @(0.0, 0.0, -9.81)
165
+ trajectory = @{
166
+ kind = $Kind
167
+ duration = $Duration
168
+ params = @{
169
+ center = @(0.0, 0.0, 0.5)
170
+ radius = 0.2
171
+ axis = @(0.0, 0.0, 1.0)
172
+ angle_span = [math]::PI * 2.0
173
+ }
174
+ }
175
+ }
176
+ }
177
+ }
178
+ "workspace" {
179
+ $url = "$BaseUrl/workspace"; $method = "POST"
180
+ $body = @{
181
+ robot = $Robot
182
+ xlim = @(-0.6, 0.6); ylim = @(-0.4, 0.4); zlim = @(-0.4, 0.4)
183
+ resolution = 8
184
+ kind = "wcw"
185
+ }
186
+ }
187
+ }
188
+
189
+ # Invoke. Render's free tier cold-start can exceed PowerShell's default
190
+ # 100-s WebRequest timeout the first time you hit /simulate; bump it.
191
+ $invokeArgs = @{ Uri = $url; Method = $method; TimeoutSec = 180 }
192
+ if ($body) {
193
+ $invokeArgs.Body = ($body | ConvertTo-Json -Depth 12)
194
+ $invokeArgs.ContentType = "application/json"
195
+ }
196
+
197
+ Write-Host ("[call_render] {0} {1} (timeout 180s --- cold start can take ~50 s)" -f $method, $url)
198
+ $t0 = Get-Date
199
+ try {
200
+ $response = Invoke-RestMethod @invokeArgs
201
+ } catch {
202
+ Write-Host ("[call_render] HTTP error: {0}" -f $_.Exception.Message) -ForegroundColor Red
203
+ if ($_.Exception.Response) {
204
+ $stream = $_.Exception.Response.GetResponseStream()
205
+ $reader = New-Object System.IO.StreamReader($stream)
206
+ $errBody = $reader.ReadToEnd()
207
+ Write-Host ("[call_render] response body:`n{0}" -f $errBody) -ForegroundColor Red
208
+ }
209
+ exit 1
210
+ }
211
+ $elapsed = (Get-Date) - $t0
212
+ Write-Host ("[call_render] {0:N2} s" -f $elapsed.TotalSeconds)
213
+
214
+ # Persist the response.
215
+ $jsonPath = Join-Path $OutDir "$Action.json"
216
+ Write-Json -Path $jsonPath -Object $response
217
+
218
+ # Special handling for /plot: decode the base64 PNG to disk.
219
+ if ($Action -eq "plot" -and $response.png_base64) {
220
+ $pngPath = Join-Path $OutDir "$PlotKind.png"
221
+ $bytes = [Convert]::FromBase64String($response.png_base64)
222
+ [IO.File]::WriteAllBytes($pngPath, $bytes)
223
+ Write-Host ("[call_render] PNG -> {0}" -f $pngPath)
224
+ if ($OpenPng) {
225
+ Start-Process $pngPath
226
+ }
227
+ }
228
+
229
+ Write-Host "[call_render] done."
scripts/run_simulation.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""Headless CDPR simulation driver.
2
+
3
+ When the Streamlit Cloud GUI is uncooperative (or you just want a faster
4
+ loop on the dev machine) this script runs a full simulation, saves all
5
+ the plots the GUI would have shown, dumps the timeseries to CSV, and
6
+ writes a JSON manifest with the configuration + git hash. It is the
7
+ PowerShell escape hatch promised in the dissertation deployment plan.
8
+
9
+ Examples
10
+ --------
11
+
12
+ ::
13
+
14
+ # Defaults (IPAnema-class robot, circular trajectory, 1.5 s, 2 ms).
15
+ python scripts/run_simulation.py
16
+
17
+ # CoGiRo-class robot, larger circle, finer step, custom output dir.
18
+ python scripts/run_simulation.py ^
19
+ --robot cogiro_class ^
20
+ --kind circle ^
21
+ --radius 0.4 ^
22
+ --duration 2.0 ^
23
+ --dt 1e-3 ^
24
+ --out out/cogiro_circle
25
+
26
+ # Lissajous, more samples for the 3D scene.
27
+ python scripts/run_simulation.py --kind lissajous --duration 3.0
28
+
29
+ # Open the result folder in Explorer when done.
30
+ python scripts/run_simulation.py --open
31
+
32
+ The script never crashes on a single plot failure: each plot is wrapped
33
+ in its own try/except so the others still land on disk.
34
+ """
35
+
36
+ from __future__ import annotations
37
+
38
+ import argparse
39
+ import json
40
+ import os
41
+ import platform
42
+ import subprocess
43
+ import sys
44
+ import time
45
+ from dataclasses import asdict
46
+ from pathlib import Path
47
+
48
+ # Force headless matplotlib before any plotting import so this script
49
+ # runs cleanly in a PowerShell session without a display server.
50
+ os.environ.setdefault("MPLBACKEND", "Agg")
51
+
52
+ import numpy as np # noqa: E402
53
+ from scipy.spatial.transform import Rotation # noqa: E402
54
+
55
+ # When invoked from the repo root via `python scripts/run_simulation.py`
56
+ # the src/ layout is not yet on the path. Add it so this works on a
57
+ # fresh clone without `pip install -e .`.
58
+ _REPO_ROOT = Path(__file__).resolve().parents[1]
59
+ _SRC = _REPO_ROOT / "src"
60
+ if str(_SRC) not in sys.path:
61
+ sys.path.insert(0, str(_SRC))
62
+
63
+ from cdpr.core.frames import Pose # noqa: E402
64
+ from cdpr.dynamics.rigid_body import PlatformState # noqa: E402
65
+ from cdpr.dynamics.simulator import simulate # noqa: E402
66
+ from cdpr.interface.specs import ( # noqa: E402
67
+ SimulationRequest,
68
+ TrajectorySpec,
69
+ build_robot,
70
+ build_trajectory,
71
+ )
72
+
73
+
74
+ # ---------------------------------------------------------------------------
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="Headless CDPR simulation driver (PowerShell-friendly).",
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],
96
+ )
97
+ p.add_argument("--objective", choices=OBJECTIVES, default="centered")
98
+ # circle params
99
+ p.add_argument("--center", type=float, nargs=3, metavar=("CX", "CY", "CZ"),
100
+ default=[0.0, 0.0, 0.5])
101
+ p.add_argument("--radius", type=float, default=0.2)
102
+ p.add_argument("--axis", type=float, nargs=3, metavar=("AX", "AY", "AZ"),
103
+ default=[0.0, 0.0, 1.0])
104
+ p.add_argument("--angle-span", type=float, default=float(2 * np.pi))
105
+ # line params
106
+ p.add_argument("--start", type=float, nargs=3, metavar=("SX", "SY", "SZ"),
107
+ default=[0.0, 0.0, 0.5])
108
+ p.add_argument("--end", type=float, nargs=3, metavar=("EX", "EY", "EZ"),
109
+ default=[0.3, 0.0, 0.5])
110
+ # lissajous params
111
+ p.add_argument("--amplitudes", type=float, nargs=3,
112
+ metavar=("AX", "AY", "AZ"), default=[0.2, 0.2, 0.0])
113
+ p.add_argument("--frequencies", type=float, nargs=3,
114
+ metavar=("FX", "FY", "FZ"), default=[1.0, 2.0, 0.0])
115
+ p.add_argument("--phases", type=float, nargs=3,
116
+ metavar=("PX", "PY", "PZ"), default=[0.0, float(np.pi / 2), 0.0])
117
+ # output
118
+ p.add_argument(
119
+ "--out", type=Path, default=None,
120
+ help="output directory (default: out/<robot>-<kind>-<timestamp>/)",
121
+ )
122
+ p.add_argument("--no-plots", action="store_true",
123
+ help="skip plot rendering --- only save CSV + manifest")
124
+ p.add_argument("--open", action="store_true",
125
+ help="open the output folder in Explorer when done (Windows only)")
126
+ return p.parse_args(argv)
127
+
128
+
129
+ # ---------------------------------------------------------------------------
130
+ # Request builders
131
+ # ---------------------------------------------------------------------------
132
+
133
+ def build_request(args: argparse.Namespace) -> SimulationRequest:
134
+ if args.kind == "line":
135
+ params: dict = {"start": list(args.start), "end": list(args.end)}
136
+ elif args.kind == "circle":
137
+ params = {
138
+ "center": list(args.center),
139
+ "radius": float(args.radius),
140
+ "axis": list(args.axis),
141
+ "angle_span": float(args.angle_span),
142
+ }
143
+ elif args.kind == "lissajous":
144
+ params = {
145
+ "center": list(args.center),
146
+ "amplitudes": list(args.amplitudes),
147
+ "frequencies": list(args.frequencies),
148
+ "phases": list(args.phases),
149
+ }
150
+ else: # hold
151
+ params = {}
152
+ return SimulationRequest(
153
+ robot=args.robot,
154
+ payload_mass=float(args.payload_mass),
155
+ gravity=tuple(float(g) for g in args.gravity),
156
+ tension_objective=args.objective,
157
+ duration=float(args.duration),
158
+ dt=float(args.dt),
159
+ trajectory=TrajectorySpec(
160
+ kind=args.kind, duration=float(args.duration), params=params,
161
+ ),
162
+ )
163
+
164
+
165
+ # ---------------------------------------------------------------------------
166
+ # Output helpers
167
+ # ---------------------------------------------------------------------------
168
+
169
+ def default_out_dir(args: argparse.Namespace) -> Path:
170
+ stamp = time.strftime("%Y%m%d-%H%M%S")
171
+ return _REPO_ROOT / "out" / f"{args.robot}-{args.kind}-{stamp}"
172
+
173
+
174
+ def git_describe() -> str:
175
+ try:
176
+ return subprocess.check_output(
177
+ ["git", "rev-parse", "--short", "HEAD"],
178
+ cwd=_REPO_ROOT, text=True,
179
+ ).strip()
180
+ except Exception: # pragma: no cover
181
+ return "unknown"
182
+
183
+
184
+ def save_manifest(out_dir: Path, request: SimulationRequest, samples: int, runtime_s: float) -> None:
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
+ }
193
+ (out_dir / "manifest.json").write_text(
194
+ json.dumps(manifest, indent=2, default=str), encoding="utf-8",
195
+ )
196
+
197
+
198
+ def _request_to_dict(request: SimulationRequest) -> dict:
199
+ """SimulationRequest is a slots dataclass; ``asdict`` flattens its tuple
200
+ fields cleanly enough for the manifest."""
201
+ data = asdict(request)
202
+ return data
203
+
204
+
205
+ def save_timeseries_csv(out_dir: Path, result) -> Path:
206
+ """Per-step state in one wide CSV --- pandas-free so the script has
207
+ one less dependency on a fresh clone."""
208
+ path = out_dir / "timeseries.csv"
209
+ t = np.asarray(result.time)
210
+ positions = np.asarray(result.positions)
211
+ quats = np.asarray(result.quaternions_xyzw)
212
+ lin_vel = np.asarray(result.linear_velocities)
213
+ ang_vel = np.asarray(result.angular_velocities)
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)):
226
+ row = [
227
+ f"{t[k]:.6f}",
228
+ *(f"{v:.6f}" for v in positions[k]),
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
237
+
238
+
239
+ # ---------------------------------------------------------------------------
240
+ # Plot dispatch --- each plot wrapped in its own try/except so a single
241
+ # failing figure (e.g. tracking-error on a hold trajectory) does not
242
+ # prevent the others from landing on disk.
243
+ # ---------------------------------------------------------------------------
244
+
245
+ def render_plots(out_dir: Path, result, robot, reference) -> dict[str, str]:
246
+ try:
247
+ from cdpr.viz.style import apply_paper_style
248
+ apply_paper_style()
249
+ except Exception: # pragma: no cover
250
+ pass
251
+
252
+ from cdpr.viz import plots2d
253
+ from cdpr.viz.scene import SceneOptions, render_scene
254
+
255
+ outcomes: dict[str, str] = {}
256
+
257
+ def _save(name: str, fn) -> None:
258
+ path = out_dir / f"{name}.png"
259
+ try:
260
+ fig = fn()
261
+ fig.savefig(path, dpi=160, bbox_inches="tight")
262
+ outcomes[name] = "ok"
263
+ print(f" [{name:18s}] -> {path.resolve()}")
264
+ except Exception as exc:
265
+ outcomes[name] = f"failed: {type(exc).__name__}: {exc}"
266
+ print(f" [{name:18s}] FAILED {type(exc).__name__}: {exc}")
267
+
268
+ _save("position", lambda: plots2d.plot_position(result))
269
+ _save("cable_tensions", lambda: plots2d.plot_cable_tensions(result, robot=robot))
270
+ _save("cable_lengths", lambda: plots2d.plot_cable_lengths(result))
271
+ if reference is not None:
272
+ _save("tracking_error", lambda: plots2d.plot_tracking_error(result, reference))
273
+ _save("condition_number", lambda: plots2d.plot_condition_number(result, robot))
274
+ _save("scene_3d", lambda: render_scene(
275
+ robot,
276
+ Pose(
277
+ position=result.positions[-1],
278
+ rotation=Rotation.from_quat(result.quaternions_xyzw[-1]),
279
+ ),
280
+ options=SceneOptions(tension_heatmap=True),
281
+ tensions=result.cable_tensions[-1],
282
+ trajectory_positions=result.positions,
283
+ ))
284
+ return outcomes
285
+
286
+
287
+ # ---------------------------------------------------------------------------
288
+ # Entry point
289
+ # ---------------------------------------------------------------------------
290
+
291
+ def main(argv: list[str] | None = None) -> int:
292
+ args = parse_args(argv)
293
+ out_dir = args.out or default_out_dir(args)
294
+ out_dir.mkdir(parents=True, exist_ok=True)
295
+ print(f"output -> {out_dir}")
296
+
297
+ request = build_request(args)
298
+ robot = build_robot(request.robot, payload_mass=request.payload_mass)
299
+ reference = build_trajectory(request.trajectory)
300
+ p0 = reference(0.0).position
301
+ state0 = PlatformState.at_rest(Pose(position=p0, rotation=Rotation.identity()))
302
+
303
+ print(
304
+ f"simulating: robot={request.robot} kind={request.trajectory.kind} "
305
+ f"duration={request.duration}s dt={request.dt}s"
306
+ )
307
+ t_start = time.perf_counter()
308
+ result = simulate(
309
+ robot=robot, state0=state0,
310
+ duration=request.duration, dt=request.dt,
311
+ reference=reference,
312
+ tension_objective=request.tension_objective,
313
+ gravity=request.gravity,
314
+ )
315
+ runtime_s = time.perf_counter() - t_start
316
+
317
+ samples = len(result.time)
318
+ print(f"done : {samples} samples in {runtime_s:.2f} s")
319
+ print(
320
+ f"summary: max tension {float(np.max(result.cable_tensions)):.1f} N, "
321
+ f"min tension {float(np.min(result.cable_tensions)):.1f} N, "
322
+ f"infeasible steps {len(result.infeasible_steps)}"
323
+ )
324
+
325
+ csv_path = save_timeseries_csv(out_dir, result)
326
+ print(f" [timeseries.csv ] -> {csv_path.resolve()}")
327
+
328
+ if not args.no_plots:
329
+ render_plots(out_dir, result, robot, reference)
330
+
331
+ save_manifest(out_dir, request, samples=samples, runtime_s=runtime_s)
332
+ print(f" [manifest.json ] -> {(out_dir / 'manifest.json').resolve()}")
333
+
334
+ if args.open and sys.platform == "win32":
335
+ try:
336
+ os.startfile(str(out_dir)) # type: ignore[attr-defined]
337
+ except Exception as exc: # pragma: no cover
338
+ print(f"could not open folder: {exc}", file=sys.stderr)
339
+
340
+ return 0
341
+
342
+
343
+ if __name__ == "__main__":
344
+ sys.exit(main())
src/cdpr/viz/plots2d.py CHANGED
@@ -159,7 +159,10 @@ def plot_tracking_error(
159
  err = np.linalg.norm(result.positions - ref_positions, axis=1)
160
  ax.plot(result.time, err, color=CDPR_CABLE_COLORS[3])
161
  ax.set_xlabel(r"time $t$ [s]")
162
- ax.set_ylabel(r"$\lVert \mathbf{p}(t) - \mathbf{p}_\mathrm{ref}(t) \rVert$ [m]")
 
 
 
163
  ax.set_yscale("log")
164
  return fig
165
 
 
159
  err = np.linalg.norm(result.positions - ref_positions, axis=1)
160
  ax.plot(result.time, err, color=CDPR_CABLE_COLORS[3])
161
  ax.set_xlabel(r"time $t$ [s]")
162
+ # mathtext's reduced grammar does not understand \lVert / \rVert
163
+ # (those are amsmath, only available with usetex=True). Use the
164
+ # double-bar combination that mathtext parses everywhere.
165
+ ax.set_ylabel(r"$\|\mathbf{p}(t) - \mathbf{p}_\mathrm{ref}(t)\|$ [m]")
166
  ax.set_yscale("log")
167
  return fig
168
 
streamlit_app.py CHANGED
@@ -16,6 +16,18 @@ every later import sees it.
16
  If importing the GUI itself fails (a bad commit, a missing extra, a
17
  syntax error introduced upstream), we render the traceback in the page
18
  rather than letting Streamlit serve a blank tab.
 
 
 
 
 
 
 
 
 
 
 
 
19
  """
20
 
21
  from __future__ import annotations
@@ -44,28 +56,77 @@ os.environ.setdefault("CDPR_GUI_FRUGAL", "1")
44
  # 4) Default backend URL for the future variant of the GUI that talks
45
  # to the FastAPI service over HTTP. The current GUI embeds cdpr in
46
  # its own process and ignores this.
47
- os.environ.setdefault("CDPR_BACKEND_URL", "http://localhost:8000")
48
-
49
- # 5) Import & render. If anything raises (missing dep, syntax error,
50
- # config error), show the traceback in the page so the user can see
51
- # what the worker was unhappy about. Without this guard the worker
52
- # just dies and the browser shows a blank tab.
53
- try:
54
- from cdpr.interface import gui # noqa: F401, E402
55
- except Exception as exc: # pragma: no cover - last-resort surface
 
56
  import streamlit as st
57
 
58
- try:
59
- st.set_page_config(page_title="CDPR — load failure", layout="wide")
60
- except Exception:
61
- pass
62
- st.title("CDPR research console — failed to load")
63
- st.error(
64
- "The console failed to import. The traceback below tells you "
65
- "which module/line is at fault."
 
66
  )
67
- st.exception(exc)
68
- st.code(traceback.format_exc(), language="text")
69
- # Also write to stderr so the Streamlit Cloud "manage app" log
70
- # carries the same trace.
71
- print(traceback.format_exc(), file=sys.stderr, flush=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  If importing the GUI itself fails (a bad commit, a missing extra, a
17
  syntax error introduced upstream), we render the traceback in the page
18
  rather than letting Streamlit serve a blank tab.
19
+
20
+ Diagnostic fallback
21
+ -------------------
22
+
23
+ If the full console keeps blanking on Streamlit Cloud but the
24
+ Render-hosted FastAPI is reachable and the local CLI works, the issue
25
+ is almost certainly platform-side (worker resource limit, websocket
26
+ disconnect, install-cache desync). Set ``CDPR_GUI_DIAG=1`` in the
27
+ Streamlit Cloud "Secrets" tab to swap in a minimal one-button page:
28
+ if even that page blanks on the click, the platform itself is
29
+ unhealthy and the FastAPI / CLI escape hatches are the right paths
30
+ forward until the worker recovers.
31
  """
32
 
33
  from __future__ import annotations
 
56
  # 4) Default backend URL for the future variant of the GUI that talks
57
  # to the FastAPI service over HTTP. The current GUI embeds cdpr in
58
  # its own process and ignores this.
59
+ os.environ.setdefault("CDPR_BACKEND_URL", "https://cdpr-api.onrender.com")
60
+
61
+
62
+ def _run_diagnostic_page() -> None:
63
+ """A minimal Streamlit page used to isolate Cloud-side blanking.
64
+
65
+ If this page blanks on the click, the Streamlit Cloud worker itself
66
+ is unhealthy and the cdpr.interface.gui code cannot be at fault.
67
+ Useful as a one-button A/B against the full console.
68
+ """
69
  import streamlit as st
70
 
71
+ st.set_page_config(page_title="cdpr-diag", layout="centered")
72
+ st.title("cdpr diagnostic page")
73
+ st.write(
74
+ "If you can see this AND the click counter below increments when "
75
+ "you click the button, the Streamlit Cloud worker is healthy and "
76
+ "the issue is in `cdpr.interface.gui`. If the page goes blank on "
77
+ "the click, the worker itself is the problem --- use the "
78
+ "PowerShell CLI (`scripts/run_simulation.py`) or the FastAPI "
79
+ "backend (`scripts/call_render.ps1`) until Cloud recovers."
80
  )
81
+
82
+ n = st.session_state.get("clicks", 0)
83
+ st.metric("clicks", n)
84
+ if st.button("Click me"):
85
+ st.session_state["clicks"] = n + 1
86
+ st.toast(f"clicked {n + 1} times")
87
+ st.rerun()
88
+
89
+ with st.expander("Runtime"):
90
+ try:
91
+ import matplotlib # noqa: F401
92
+ mp_backend = matplotlib.get_backend()
93
+ except Exception:
94
+ mp_backend = "import failed"
95
+ st.write({
96
+ "python": sys.version.split()[0],
97
+ "platform": sys.platform,
98
+ "matplotlib_backend": mp_backend,
99
+ "CDPR_GUI_FRUGAL": os.environ.get("CDPR_GUI_FRUGAL"),
100
+ "CDPR_GUI_DIAG": os.environ.get("CDPR_GUI_DIAG"),
101
+ "CDPR_BACKEND_URL": os.environ.get("CDPR_BACKEND_URL"),
102
+ "session_state_keys": sorted(st.session_state.keys()),
103
+ })
104
+
105
+
106
+ if os.environ.get("CDPR_GUI_DIAG") in {"1", "true", "True"}:
107
+ _run_diagnostic_page()
108
+ else:
109
+ # 5) Import & render the full console. If anything raises (missing
110
+ # dep, syntax error, config error), show the traceback in the
111
+ # page so the user can see what the worker was unhappy about.
112
+ # Without this guard the worker just dies and the browser shows
113
+ # a blank tab.
114
+ try:
115
+ from cdpr.interface import gui # noqa: F401, E402
116
+ except Exception as exc: # pragma: no cover - last-resort surface
117
+ import streamlit as st
118
+
119
+ try:
120
+ st.set_page_config(page_title="CDPR — load failure", layout="wide")
121
+ except Exception:
122
+ pass
123
+ st.title("CDPR research console — failed to load")
124
+ st.error(
125
+ "The console failed to import. The traceback below tells you "
126
+ "which module/line is at fault."
127
+ )
128
+ st.exception(exc)
129
+ st.code(traceback.format_exc(), language="text")
130
+ # Also write to stderr so the Streamlit Cloud "manage app" log
131
+ # carries the same trace.
132
+ print(traceback.format_exc(), file=sys.stderr, flush=True)