ppak10 commited on
Commit
8cdbe7c
·
1 Parent(s): b200cc9

Adds rerun and reformatted parquet files.

Browse files
CLAUDE.md CHANGED
@@ -8,7 +8,7 @@ Context for continuing work on this dataset. Captures the design decisions, conv
8
 
9
  It is the **third leaf** in the Inova Mk1 dataset ecosystem alongside `Inova-Mk1-Database` (canonical printer entities) and `Inova-Mk1-ASTM` (mechanical-test specimens).
10
 
11
- Unlike the other two, this dataset has **no local `source/` directory** — its raw inputs are the flat exports written by a sibling Git repo (`Agentic-Additive-Manufacturing-Process-Optimization`, "the recorder"). The ETL here reshapes those flat exports into one parquet file per build.
12
 
13
  ## Data lineage — printer to row
14
 
@@ -69,11 +69,11 @@ End-to-end, before this dataset's ETL touches anything:
69
  ┌────────────────────────────┐
70
  │ This dataset │ Per-build wide parquet, one row per 10 Hz tick.
71
  │ data/ticks/{NNN}.parquet │ Embedded image bytes, denormalized build
72
- │ │ context, ~78 columns including position burst.
73
  └────────────────────────────┘
74
  ```
75
 
76
- The two **sidecar CSVs** at the recorder layer (`build_to_inova_session.csv`, `sensors.csv`) are hand-annotated by a human, not generated. They're checked into the recorder repo and read by this dataset's ETL via the sibling-folder path.
77
 
78
  ## How the data is captured
79
 
@@ -91,10 +91,12 @@ The recorder also pins **`sls4all/SLS4All.Compact`** as a submodule at tag `publ
91
  Submodule layout inside the recorder repo:
92
  ```
93
  sls4all/
94
- Inova-API-Plugin/ # the C# plugin (our code; editable)
95
- SLS4All.Compact/ # firmware (vendor; pinned)
 
96
  datasets/
97
- Agentic-SLS/ # legacy submodule, predates the HF dataset layout
 
98
  ```
99
 
100
  ### How the recorder runs
@@ -134,7 +136,11 @@ Only needed if you're rebuilding the recorder side — this dataset's ETL doesn'
134
 
135
  ```sh
136
  # In the recorder repo:
137
- git clone --recurse-submodules git@github.com:ppak10/Agentic-Additive-Manufacturing-Process-Optimization.git
 
 
 
 
138
  cp .env.example .env # then fill in printer IP
139
  docker compose up -d # brings up Postgres
140
  cd server && npm install # then run the Fastify server in dev/prod mode
@@ -148,15 +154,15 @@ Assuming you're working on this machine (`/mnt/storage2`):
148
 
149
  | Repo | Filesystem path | Role |
150
  |---|---|---|
151
- | This dataset | `/mnt/storage2/HuggingFace/Datasets/Inova-Mk1-Telemetry/` | Where you are now. ETL reads sibling exports; writes `data/ticks/`. |
152
- | Recorder repo | `/mnt/storage2/GitHub/Agentic-Additive-Manufacturing-Process-Optimization/` | Owns the live DB + export script. **The only sibling repo this dataset depends on.** This ETL reads `data/exports/`. |
153
  | Sibling Database dataset | `/mnt/storage2/HuggingFace/Datasets/Inova-Mk1-Database/` | Informational only — *not* a dependency. Consumers can join `print_profile_name` against `source/PrintProfiles/*.json` themselves to recover the UUID; see "Joining back to Inova-Mk1-Database" in the README. |
154
  | Sibling ASTM dataset | `/mnt/storage2/HuggingFace/Datasets/Inova-Mk1-ASTM/` | Independent leaf; no direct dependency. |
155
 
156
  `scripts/_lib.py` resolves the recorder path relative to its own location: `ROOT` is the repo root (`_lib.py` → two `.parent`s up), and then:
157
- - **Recorder** (`AGENTIC_ROOT`): `ROOT.parent.parent.parent / "GitHub" / "Agentic-Additive-Manufacturing-Process-Optimization"` — three climbs from `ROOT` to reach `/mnt/storage2`, then descend.
158
 
159
- If you move the repo out of `/mnt/storage2/HuggingFace/Datasets/`, that climb needs updating.
160
 
161
  **Authoritative references** for sensor semantics in the recorder repo:
162
  - `sls4all/Inova-API-Plugin/InovaApiPlugin.cs` — `/state/snapshot` returns `{ position, lights, power, temperature }`. Lines 85–213 are the endpoint definitions; lines 495–507 are the `CaptureSnapshot` shape.
@@ -254,9 +260,10 @@ Neither blocks the ETL. They improve dataset metadata.
254
 
255
  - **One config, not four.** Early iteration had separate `builds`, `telemetry`, `position_hf`, and `frames` configs. Replaced with a single `ticks` config because ML consumers almost always want the joined view: state + frame + position at one moment in time. The four-silo version pushed the join cost onto every downstream user.
256
  - **Anchor on the 10 Hz telemetry tick, not strict outer join.** The recorder's `/state/snapshot` poll fires at 10 Hz and `expand()` emits a deterministic ~64-row burst into the `telemetry` table — so a tick already represents a full state snapshot. Anchoring on ticks gives every row densely populated columns; frames and `position_hf` attach to the tick they're closest to. A strict outer join across all stream timestamps gave ~3M mostly-sparse rows for less ML value.
257
- - **Wide format, dotted column names matching upstream.** Sensor columns are named exactly `{sensor_id}.{kind}` — e.g. `powderBed.temp.current`, `laser.power`, `positions.position.x`. This matches the upstream `sensors.csv` glossary 1:1 so unit annotations land where consumers will look. ~64 sensor columns + build context + frame paths + position burst = 78 columns total.
258
  - **Frames attach by nearest-before-tick within a 100 ms window** and **the image bytes are embedded inline**. Frame timestamps don't align with telemetry ticks (chamber 5 Hz, thermal 2 Hz, galvo varies). For each tick we look back 100 ms and grab the most recent frame of each kind; nulls when nothing landed. Each `frame_*` column is a struct of `{bytes: binary, path: string}` matching HF's `Image` feature wire format — declared as `dtype: image` in the README so `datasets` decodes to `PIL.Image` on access. The `path` field inside the struct is the original relative filename (`"26/1780265532038_chamber.jpg"`) preserved for traceability back to the recorder repo.
259
  - **Null is preserved when no frame attaches** — we explicitly did **not** forward-fill the latest captured frame. Reason: shuffled training with forward-fill would pair the same image with widely varying telemetry rows (e.g. one chamber jpg stamped onto thousands of consecutive ticks during a 30-min heating phase), teaching the model spurious associations. Filtering null-frame rows at consume time is a one-liner; recovering "this image is stale" from a forward-filled column is impossible.
 
260
  - **`position_hf` preserved as per-tick bursts.** The firmware emits `PositionChangedHighFrequency` event-driven, not at fixed 1 kHz — so it bursts during motion and is empty during heating. We keep the full burst inside each tick's window as `position_hf_burst: list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. Empty list when no motion. Lossless within the 100 ms window; the raw `position_hf/{build_id}.parquet` upstream is the fallback if you need motion data between ticks.
261
  - **Build context denormalized into every row.** `build_id`, `job_name`, `started_at`, `ended_at`, `phase`, `print_profile_name`, `inova_session_id` repeat on every row. Parquet dictionary encoding makes this essentially free (~1 byte per row regardless of value).
262
  - **`print_profile_name` only, no `print_profile_id`.** The recorder's `events.jsonl` carries the *name* a build started with; the UUID lives in `Inova-Mk1-Database/source/PrintProfiles/*.json`. Earlier versions of the ETL cached the name→UUID lookup into a `print_profile_id` column, but doing that turned `Inova-Mk1-Database` into an ETL-time dependency for a one-line consumer join. We dropped the column so this dataset stands on its own with only the recorder repo. Consumers who want the UUID can join externally — see the README section "Joining back to Inova-Mk1-Database."
@@ -272,7 +279,7 @@ pyproject.toml # pyarrow, polars, imageio[ffmpeg], pillow, numpy
272
  .gitattributes # *.parquet, *.mp4, *.gif → LFS
273
 
274
  scripts/
275
- _lib.py # sibling-repo paths + JSONL streaming
276
  ticks/
277
  00_recover_spool41.py # one-off: recover build 41 from NVMe spool (DB was wiped)
278
  00_export_new_db.py # one-off: export DB builds with ID remap (old_id:new_id; identity N:N since 2026-07-13)
@@ -296,21 +303,22 @@ previews/
296
  timelapse_composite.gif # LFS; 1×3 panel GIF
297
  ```
298
 
299
- There is no `source/` (raw data lives in the sibling recorder repo's `data/exports/`).
300
 
301
  `scripts/ticks/01_extract.py` is organized as:
302
  1. `load_builds_index()` / `load_frames_for_build()` — load upstream JSONL
303
  2. `pivot_telemetry()` — long-to-wide on `(sensor_id, kind)`
304
  3. `attach_frames()` — three `join_asof(strategy='backward', tolerance=100ms)` calls
305
- 4. `attach_position_hf()` — manual sorted-merge to build the burst lists
306
- 5. `denormalize_build()` — `pl.lit()` columns for build context
307
- 6. `_embed_frame_column()` / `_embed_chunk()` / `process_build()` chunked write with pyarrow `ParquetWriter`
308
- 7. `main()` iterate target build IDs, call `process_build()` per build
 
309
 
310
  ## Row shape
311
 
312
  ```python
313
- # per row, ~78 columns:
314
  {
315
  # Build context (denormalized; same on every row of a given file)
316
  "build_id": 26,
@@ -346,7 +354,12 @@ There is no `source/` (raw data lives in the sibling recorder repo's `data/expor
346
  # Frames — embedded HF Image structs (PIL.Image on load) or None
347
  "frame_chamber": {"bytes": b"\xff\xd8...", "path": "26/1780265532038_chamber.jpg"},
348
  "frame_galvo": {"bytes": b"\x89PNG...", "path": "26/1780265532040_galvo.png"},
349
- "frame_thermal": None, # nothing in window
 
 
 
 
 
350
 
351
  # 1 kHz position-stream burst within (tick_ts - 100ms, tick_ts]
352
  "position_hf_burst": [
@@ -372,6 +385,7 @@ If `expand()` in the recorder ever changes, all of those column names change wit
372
  ## Important gotchas
373
 
374
  - **`frame_*` bytes are embedded; `path` inside the struct is recorder-relative.** Each non-null frame column carries the actual image bytes plus the original relative path (`"26/1780265532038_chamber.jpg"`, meaning `Agentic-Additive-Manufacturing-Process-Optimization/data/frames/...`). The path is for traceability only — consumers don't need the recorder repo to access the image. The unattached frames (~half of the 1.27 M captured) still live only in the recorder repo; this dataset only carries the per-tick attached subset.
 
375
  - **`positions.position.*` columns are 10 Hz**, not 1 kHz. They come from the snapshot's `position` field. For 1 kHz fidelity during motion, read `position_hf_burst`.
376
  - **`inova_session_id` is always null** until someone curates `build_to_inova_session.csv` in the recorder repo. Consumers who need an entity-graph link can fall back to joining on `print_profile_name` against `Inova-Mk1-Database` meanwhile.
377
  - **`build_id` is a Postgres BIGSERIAL**, not a UUID. One Database `PrintSession` may have many `build_id`s (one per recorder restart / attempt). That's why session-id mapping must be hand-authored.
 
8
 
9
  It is the **third leaf** in the Inova Mk1 dataset ecosystem alongside `Inova-Mk1-Database` (canonical printer entities) and `Inova-Mk1-ASTM` (mechanical-test specimens).
10
 
11
+ Unlike the other two, this dataset has **no local `source/` directory** — its raw inputs are the flat exports written by the recorder repo (`Agentic-Additive-Manufacturing-Process-Optimization`), which contains this dataset as a submodule at `datasets/Inova-Mk1-Telemetry`. The ETL here reshapes those flat exports into one parquet file per build.
12
 
13
  ## Data lineage — printer to row
14
 
 
69
  ┌────────────────────────────┐
70
  │ This dataset │ Per-build wide parquet, one row per 10 Hz tick.
71
  │ data/ticks/{NNN}.parquet │ Embedded image bytes, denormalized build
72
+ │ │ context, ~79 columns including position burst.
73
  └────────────────────────────┘
74
  ```
75
 
76
+ The two **sidecar CSVs** at the recorder layer (`build_to_inova_session.csv`, `sensors.csv`) are hand-annotated by a human, not generated. They're checked into the recorder repo and read by this dataset's ETL via the containing-repo path.
77
 
78
  ## How the data is captured
79
 
 
91
  Submodule layout inside the recorder repo:
92
  ```
93
  sls4all/
94
+ Inova-API-Plugin/ # the C# plugin (our code; editable)
95
+ SLS4All.Compact/ # firmware (vendor; pinned)
96
+ Inova-Defect-Detection-Model/# layer-wise defect detection model
97
  datasets/
98
+ Agentic-SLS/ # legacy submodule, predates the HF dataset layout
99
+ Inova-Mk1-Telemetry/ # THIS repo (update=none — never blanket --recurse-submodules; 566 GB)
100
  ```
101
 
102
  ### How the recorder runs
 
136
 
137
  ```sh
138
  # In the recorder repo:
139
+ # Don't use blanket --recurse-submodules: this dataset (566 GB) is itself a
140
+ # submodule at datasets/Inova-Mk1-Telemetry (guarded by update=none). Init
141
+ # the submodules you need explicitly instead.
142
+ git clone git@github.com:ppak10/Agentic-Additive-Manufacturing-Process-Optimization.git
143
+ git submodule update --init sls4all/Inova-API-Plugin sls4all/SLS4All.Compact
144
  cp .env.example .env # then fill in printer IP
145
  docker compose up -d # brings up Postgres
146
  cd server && npm install # then run the Fastify server in dev/prod mode
 
154
 
155
  | Repo | Filesystem path | Role |
156
  |---|---|---|
157
+ | This dataset | `/mnt/storage2/GitHub/Agentic-Additive-Manufacturing-Process-Optimization/datasets/Inova-Mk1-Telemetry/` | Where you are now. A submodule of the recorder repo. ETL reads the containing repo's exports; writes `data/ticks/`. |
158
+ | Recorder repo | `/mnt/storage2/GitHub/Agentic-Additive-Manufacturing-Process-Optimization/` | Owns the live DB + export script and contains this dataset as a submodule. **The only repo this dataset depends on.** This ETL reads `data/exports/`. |
159
  | Sibling Database dataset | `/mnt/storage2/HuggingFace/Datasets/Inova-Mk1-Database/` | Informational only — *not* a dependency. Consumers can join `print_profile_name` against `source/PrintProfiles/*.json` themselves to recover the UUID; see "Joining back to Inova-Mk1-Database" in the README. |
160
  | Sibling ASTM dataset | `/mnt/storage2/HuggingFace/Datasets/Inova-Mk1-ASTM/` | Independent leaf; no direct dependency. |
161
 
162
  `scripts/_lib.py` resolves the recorder path relative to its own location: `ROOT` is the repo root (`_lib.py` → two `.parent`s up), and then:
163
+ - **Recorder** (`AGENTIC_ROOT`): `ROOT.parent.parent` — two climbs from `ROOT` (`datasets/Inova-Mk1-Telemetry` `datasets` recorder root).
164
 
165
+ If you move the repo out of the recorder's `datasets/` folder, that climb needs updating.
166
 
167
  **Authoritative references** for sensor semantics in the recorder repo:
168
  - `sls4all/Inova-API-Plugin/InovaApiPlugin.cs` — `/state/snapshot` returns `{ position, lights, power, temperature }`. Lines 85–213 are the endpoint definitions; lines 495–507 are the `CaptureSnapshot` shape.
 
260
 
261
  - **One config, not four.** Early iteration had separate `builds`, `telemetry`, `position_hf`, and `frames` configs. Replaced with a single `ticks` config because ML consumers almost always want the joined view: state + frame + position at one moment in time. The four-silo version pushed the join cost onto every downstream user.
262
  - **Anchor on the 10 Hz telemetry tick, not strict outer join.** The recorder's `/state/snapshot` poll fires at 10 Hz and `expand()` emits a deterministic ~64-row burst into the `telemetry` table — so a tick already represents a full state snapshot. Anchoring on ticks gives every row densely populated columns; frames and `position_hf` attach to the tick they're closest to. A strict outer join across all stream timestamps gave ~3M mostly-sparse rows for less ML value.
263
+ - **Wide format, dotted column names matching upstream.** Sensor columns are named exactly `{sensor_id}.{kind}` — e.g. `powderBed.temp.current`, `laser.power`, `positions.position.x`. This matches the upstream `sensors.csv` glossary 1:1 so unit annotations land where consumers will look. ~64 sensor columns + build context + frame paths + bedmatrix + position burst = 79 columns total.
264
  - **Frames attach by nearest-before-tick within a 100 ms window** and **the image bytes are embedded inline**. Frame timestamps don't align with telemetry ticks (chamber 5 Hz, thermal 2 Hz, galvo varies). For each tick we look back 100 ms and grab the most recent frame of each kind; nulls when nothing landed. Each `frame_*` column is a struct of `{bytes: binary, path: string}` matching HF's `Image` feature wire format — declared as `dtype: image` in the README so `datasets` decodes to `PIL.Image` on access. The `path` field inside the struct is the original relative filename (`"26/1780265532038_chamber.jpg"`) preserved for traceability back to the recorder repo.
265
  - **Null is preserved when no frame attaches** — we explicitly did **not** forward-fill the latest captured frame. Reason: shuffled training with forward-fill would pair the same image with widely varying telemetry rows (e.g. one chamber jpg stamped onto thousands of consecutive ticks during a 30-min heating phase), teaching the model spurious associations. Filtering null-frame rows at consume time is a one-liner; recovering "this image is stale" from a forward-filled column is impossible.
266
+ - **`bedmatrix` is the IR temperature matrix as raw numbers, not a rendered image.** It attaches nearest-before-tick within the same 100 ms window as frames, but embeds as a numeric struct `{width: int32, height: int32, values: list<float32> (row-major °C), path: string}` — a 32×24 = 768-cell bed-surface temperature grid, null when nothing landed. **History:** through 2026-07-12 the same sensor was captured as a pre-rendered GIF heatmap under frame kind `thermal` (the source of `frame_thermal`, HTTP-polled from `/api/bedmatrix/image/`). Recorder commit `8d98e0c` dropped that poll; the dedicated `bedmatrix.ts` WS recorder (`/temperature/bedmatrix/stream`) now streams the raw matrix as JSON under kind `bedmatrix`. That JSON stream has actually run since build 13, so `bedmatrix` backfills across the whole dataset and is strictly richer than the old heatmap. Consequence: **`frame_thermal` is null for builds captured after 2026-07-12** (044 is the last with it; 046 has none) — use `bedmatrix` for thermal from there on. To recover a heatmap image, colormap `values` reshaped to `height × width`.
267
  - **`position_hf` preserved as per-tick bursts.** The firmware emits `PositionChangedHighFrequency` event-driven, not at fixed 1 kHz — so it bursts during motion and is empty during heating. We keep the full burst inside each tick's window as `position_hf_burst: list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. Empty list when no motion. Lossless within the 100 ms window; the raw `position_hf/{build_id}.parquet` upstream is the fallback if you need motion data between ticks.
268
  - **Build context denormalized into every row.** `build_id`, `job_name`, `started_at`, `ended_at`, `phase`, `print_profile_name`, `inova_session_id` repeat on every row. Parquet dictionary encoding makes this essentially free (~1 byte per row regardless of value).
269
  - **`print_profile_name` only, no `print_profile_id`.** The recorder's `events.jsonl` carries the *name* a build started with; the UUID lives in `Inova-Mk1-Database/source/PrintProfiles/*.json`. Earlier versions of the ETL cached the name→UUID lookup into a `print_profile_id` column, but doing that turned `Inova-Mk1-Database` into an ETL-time dependency for a one-line consumer join. We dropped the column so this dataset stands on its own with only the recorder repo. Consumers who want the UUID can join externally — see the README section "Joining back to Inova-Mk1-Database."
 
279
  .gitattributes # *.parquet, *.mp4, *.gif → LFS
280
 
281
  scripts/
282
+ _lib.py # recorder-repo paths + JSONL streaming
283
  ticks/
284
  00_recover_spool41.py # one-off: recover build 41 from NVMe spool (DB was wiped)
285
  00_export_new_db.py # one-off: export DB builds with ID remap (old_id:new_id; identity N:N since 2026-07-13)
 
303
  timelapse_composite.gif # LFS; 1×3 panel GIF
304
  ```
305
 
306
+ There is no `source/` (raw data lives in the containing recorder repo's `data/exports/`).
307
 
308
  `scripts/ticks/01_extract.py` is organized as:
309
  1. `load_builds_index()` / `load_frames_for_build()` — load upstream JSONL
310
  2. `pivot_telemetry()` — long-to-wide on `(sensor_id, kind)`
311
  3. `attach_frames()` — three `join_asof(strategy='backward', tolerance=100ms)` calls
312
+ 4. `attach_bedmatrix()` — one more `join_asof` for the IR matrix JSON path
313
+ 5. `attach_position_hf()` — manual sorted-merge to build the burst lists
314
+ 6. `denormalize_build()` `pl.lit()` columns for build context
315
+ 7. `_embed_frame_column()` / `_embed_bedmatrix_column()` / `_embed_chunk()` / `process_build()` chunked write with pyarrow `ParquetWriter`
316
+ 8. `main()` — iterate target build IDs, call `process_build()` per build
317
 
318
  ## Row shape
319
 
320
  ```python
321
+ # per row, ~79 columns:
322
  {
323
  # Build context (denormalized; same on every row of a given file)
324
  "build_id": 26,
 
354
  # Frames — embedded HF Image structs (PIL.Image on load) or None
355
  "frame_chamber": {"bytes": b"\xff\xd8...", "path": "26/1780265532038_chamber.jpg"},
356
  "frame_galvo": {"bytes": b"\x89PNG...", "path": "26/1780265532040_galvo.png"},
357
+ "frame_thermal": None, # legacy GIF heatmap; null for builds after 2026-07-12
358
+
359
+ # IR temperature matrix (raw numbers, replaces frame_thermal) — struct or None
360
+ "bedmatrix": {"width": 32, "height": 24,
361
+ "values": [97.3, 97.1, ...], # 768 floats, row-major °C
362
+ "path": "26/1780433796515_bedmatrix.json"},
363
 
364
  # 1 kHz position-stream burst within (tick_ts - 100ms, tick_ts]
365
  "position_hf_burst": [
 
385
  ## Important gotchas
386
 
387
  - **`frame_*` bytes are embedded; `path` inside the struct is recorder-relative.** Each non-null frame column carries the actual image bytes plus the original relative path (`"26/1780265532038_chamber.jpg"`, meaning `Agentic-Additive-Manufacturing-Process-Optimization/data/frames/...`). The path is for traceability only — consumers don't need the recorder repo to access the image. The unattached frames (~half of the 1.27 M captured) still live only in the recorder repo; this dataset only carries the per-tick attached subset.
388
+ - **`frame_thermal` is legacy and null for builds captured after 2026-07-12; use `bedmatrix` instead.** The recorder stopped polling the pre-rendered IR heatmap GIF (commit `8d98e0c`) and now streams the raw 32×24 temperature matrix as JSON under kind `bedmatrix`. Build 044 is the last with `frame_thermal`; 046 onward has none. `bedmatrix` is a numeric struct (`{width, height, values: list<float32> row-major °C, path}`), backfilled across the whole dataset (the JSON stream has run since build 13), and strictly richer — colormap `values` reshaped to `height × width` to recover a heatmap. The preview renderers now do exactly this: `previews/*/thermal.mp4`, `composite.mp4`, `timelapse_thermal.gif`, and `timelapse_composite.gif` render the thermal panel from `bedmatrix` (inferno colormap over a fixed 20–200 °C range; see `scripts/previews/_thermal.py`), falling back to `frame_thermal` only for the three earliest builds (001/002/012) that predate the stream. So thermal previews exist for all builds, including post-2026-07-12 ones.
389
  - **`positions.position.*` columns are 10 Hz**, not 1 kHz. They come from the snapshot's `position` field. For 1 kHz fidelity during motion, read `position_hf_burst`.
390
  - **`inova_session_id` is always null** until someone curates `build_to_inova_session.csv` in the recorder repo. Consumers who need an entity-graph link can fall back to joining on `print_profile_name` against `Inova-Mk1-Database` meanwhile.
391
  - **`build_id` is a Postgres BIGSERIAL**, not a UUID. One Database `PrintSession` may have many `build_id`s (one per recorder restart / attempt). That's why session-id mapping must be hand-authored.
README.md CHANGED
@@ -34,7 +34,7 @@ from datasets import load_dataset
34
  ds = load_dataset("ppak10/Inova-Mk1-Telemetry", split="train")
35
  row = ds[0]
36
  # row["frame_chamber"] → PIL.Image.Image (or None)
37
- # row["frame_thermal"] PIL.Image.Image (or None)
38
  # row["powderBed.temp.current"] → float (°C)
39
  # row["positions.position.z2"] → float (µm)
40
  # row["position_hf_burst"] → list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
@@ -72,7 +72,8 @@ Each row is one moment in time (a single 10 Hz tick). ~80 columns:
72
  | **Lights** | `lights.lights.{enabled,count}` | |
73
  | **Power (W)** | `{laser,fanGalvo,buzzer,laserSafety,io-en,wd-en,wd-in}.power`, `powerman.power.{current,required,max}` | Per-component draw and manager state. |
74
  | **Temperature (°C)** | `{powderBed,printBed}.temp.{current,average,target}`, `{powderChamber1..4,printChamber1..4}.temp.{current,average,target}`, `{quadrant1..4,surface,surfaceAvg,surfaceMin,surfaceMax,testTemp1}.temp.{current,average}` | ~51 columns. |
75
- | **Frame images** | `frame_chamber`, `frame_galvo`, `frame_thermal` | HF `Image` feature (struct of `{bytes, path}`). Null when no frame of that kind was captured in the 100 ms window. Loads as `PIL.Image` via `datasets`. `path` preserves the original filename for traceability. |
 
76
  | **Position burst** | `position_hf_burst` | `list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. 1 kHz position events that fell in `(tick_ts − 100 ms, tick_ts]`. Empty list during heating/idle. |
77
 
78
  ### Null frames
@@ -135,7 +136,7 @@ data/ticks/{build_id:03d}.parquet # one file per build, zero-padded (001–
135
 
136
  previews/{build_id:03d}/
137
  chamber.mp4 # optical — real-time 10 fps, forward-filled
138
- thermal.mp4 # IR matrix
139
  galvo.mp4 # scan-mirror trace
140
  composite.mp4 # 1×3 panel: chamber | thermal | galvo
141
  timelapse_chamber.gif # layer-by-layer, 25 fps, ≤ 12 s
@@ -163,7 +164,7 @@ Four animated GIFs per build sampled one frame per detected print layer:
163
  - **Playback**: 25 fps, capped at 300 frames (12 s max). Null-frame levels are forward-filled within the GIF.
164
  - **Canvas**: 240 px height (half the MP4 canvas) for web-friendly file sizes.
165
 
166
- Both previews are sourced from this dataset's own parquet (not the recorder's raw frame files), so they see only the per-tick-attached frame subset (~36% chamber, ~37% galvo, ~16% thermal attachment rate).
167
 
168
  ---
169
 
 
34
  ds = load_dataset("ppak10/Inova-Mk1-Telemetry", split="train")
35
  row = ds[0]
36
  # row["frame_chamber"] → PIL.Image.Image (or None)
37
+ # row["bedmatrix"] {width, height, values (768 °C floats), path} (or None)
38
  # row["powderBed.temp.current"] → float (°C)
39
  # row["positions.position.z2"] → float (µm)
40
  # row["position_hf_burst"] → list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
 
72
  | **Lights** | `lights.lights.{enabled,count}` | |
73
  | **Power (W)** | `{laser,fanGalvo,buzzer,laserSafety,io-en,wd-en,wd-in}.power`, `powerman.power.{current,required,max}` | Per-component draw and manager state. |
74
  | **Temperature (°C)** | `{powderBed,printBed}.temp.{current,average,target}`, `{powderChamber1..4,printChamber1..4}.temp.{current,average,target}`, `{quadrant1..4,surface,surfaceAvg,surfaceMin,surfaceMax,testTemp1}.temp.{current,average}` | ~51 columns. |
75
+ | **Frame images** | `frame_chamber`, `frame_galvo`, `frame_thermal` | HF `Image` feature (struct of `{bytes, path}`). Null when no frame of that kind was captured in the 100 ms window. Loads as `PIL.Image` via `datasets`. `path` preserves the original filename for traceability. **`frame_thermal` is a legacy pre-rendered IR heatmap GIF and is null for builds recorded after 2026-07-12 — use `bedmatrix` for thermal from there on** (see below). |
76
+ | **Bed temperature matrix** | `bedmatrix` | Struct `{width: int32, height: int32, values: list<float32>, path: string}`. The raw IR bed-surface temperature grid (32×24 = 768 cells, row-major, °C) attached nearest-before-tick in the same 100 ms window; null when none landed. Reshape `values` to `height × width` and colormap to render a heatmap. This supersedes `frame_thermal` and is available on all builds (the stream has run since build 013). |
77
  | **Position burst** | `position_hf_burst` | `list<struct<ts_offset_ms, x, y, z1, z2, r, has_homed>>`. 1 kHz position events that fell in `(tick_ts − 100 ms, tick_ts]`. Empty list during heating/idle. |
78
 
79
  ### Null frames
 
136
 
137
  previews/{build_id:03d}/
138
  chamber.mp4 # optical — real-time 10 fps, forward-filled
139
+ thermal.mp4 # IR bed heatmap (from bedmatrix; inferno, fixed 20–200 °C)
140
  galvo.mp4 # scan-mirror trace
141
  composite.mp4 # 1×3 panel: chamber | thermal | galvo
142
  timelapse_chamber.gif # layer-by-layer, 25 fps, ≤ 12 s
 
164
  - **Playback**: 25 fps, capped at 300 frames (12 s max). Null-frame levels are forward-filled within the GIF.
165
  - **Canvas**: 240 px height (half the MP4 canvas) for web-friendly file sizes.
166
 
167
+ Both previews are sourced from this dataset's own parquet (not the recorder's raw frame files), so they see only the per-tick-attached frame subset (~36% chamber, ~37% galvo attachment rate). The **thermal** panel is rendered from the numeric `bedmatrix` IR grid — inferno colormap over a fixed 20–200 °C range, so the same color means the same temperature across every build — rather than the legacy `frame_thermal` GIF. Builds 001/002/012 predate the bedmatrix stream and fall back to the old GIF.
168
 
169
  ---
170
 
data/ticks/001.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:f9218481ccf8ffa21212a3f2a1deb8400c2f1085fb2186c4fe2736a6040a916a
3
- size 3070050859
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5f7403410b9c4c4454ca2ad7996496f1f75d392436f3d35346f567d58e81a831
3
+ size 3070064819
data/ticks/002.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:56a9e8e9d263749b271bf8879737fa0aff761770ef4b6a854a3b1b594db4a474
3
- size 2509572
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:322538cc0188f75ffcfbbcec18bd24919e082a8ce016db2f8b6787b84845d7bf
3
+ size 2510220
data/ticks/012.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:251d4d7eda86545e5b4411a577d337e5c1da27047dfd7ce93627e9df765c08c1
3
- size 4928937483
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9170527116296e16c09801bae09afd7daafa3cdf9a636cc068ee16f081895a88
3
+ size 4928964220
data/ticks/013.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9698cf8e091ac9a13d7650995e4c9873c177d113cdc449949ac9a61a0b7c6753
3
- size 551842848
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0d09d2578cd171bb9c6acf010a3bcde3536cb494db75bad51265c66399fd7bf2
3
+ size 557525403
data/ticks/014.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:0c47665b6d90171a760ca5148a8975e5a8dd817172ea79de0913cb2475527c2d
3
- size 46213
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:80a0b811c8a9b912c062eac4c1d598542f8f47d283aa72958ffe7deaac5380e6
3
+ size 46831
data/ticks/016.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:907d7ac915aa74c995983b2b3292e95d3f507b9f7e047cf955fc62a707eecdab
3
- size 806791
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a6c0b6bad32633cfe8acd4b5ec4d08f66978765d7417c9c5e34cafa185386dc6
3
+ size 811333
data/ticks/017.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:c377a97cb77161b89c9a7ae3f9a3ecf20724cccf59b322ecda2eca5af2a5375d
3
- size 29798
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b4e1bec1f4a9e0fb00ddae496856a298b14139c5cc2fbdc597e1c50c389323fd
3
+ size 30416
data/ticks/025.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:100ae729c896b36fd1e42bb444d17990a1c3c87ec5cad350a32c26dee94e2e00
3
- size 1208604
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:68bcc513234d93bad405b1e0e1015573985eb69f2f449cd236ada2df16709aae
3
+ size 1216867
data/ticks/026.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:73954fc364fbd9557376b26f16b7ec082d443cd626cf799256025edb1e39593c
3
- size 11552611342
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:58fb99fe240e3176ef29113dbaa9eaceadc0d70aa56743cfec022fd19a7ce126
3
+ size 11667958845
data/ticks/028.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:44f6df8e1e1f67a4007da0b83314faf60a758e4994ff48274204f9bbcfc48762
3
- size 11436603086
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:93fdf48a3ea3c4def04132e62b55429821f1eed5b9728e4e69c90f840839f4ed
3
+ size 11549490145
data/ticks/029.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7984c30bae143e2dbd661485a3bf3c00b64f8dcf5c788268931d58f4d0035967
3
- size 9743021465
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c88515ead6ae3985780c7151b6d3b1d17dc5d0944a43485ed6913759f46781c7
3
+ size 9837883077
data/ticks/030.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:72fa46726514b3c98c4aa31eb255afb82469d5342d44f877a6c27b628395ad92
3
- size 7195639311
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5fe55e56eacc7909732ae3e701b480fb46f7277f0e1adb3390082e2de9ab80c5
3
+ size 7271463144
data/ticks/031.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:790000dd8b5928eddcac9684f133d060e8a72eedf537bd613f10f133967698d9
3
- size 5245032189
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:69469797ac695a0bb7df79ad63c002814cb42b8350c66f33ecb0acad8cbe0ed8
3
+ size 5297605879
data/ticks/032.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:2fa685a426e8ee02940f32785b15503a5140dd53ded250536f1e4af68c7ca9df
3
- size 684999581
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ce5ba49e1fcf1954478d3ca5c826465c34861e46c6d974180d58cc12ac8e002e
3
+ size 691454927
data/ticks/033.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:6011cf0ac654dc6dfa966426bfe5d31e334049304b8f9818742db4f00be0d958
3
- size 61512550
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b5eb26e407b43b9d65e7db5ec45b95b3827fe1344f0696543c765031692ddd9e
3
+ size 62132491
data/ticks/034.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ac5ba412a172eb64acb18994d5d9f6ee79c50a81bceb75a8cc5896556e0841b5
3
- size 676195678
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60bf42451327c0128a253e9ea8388d3fe446368ca170f7be89aac71a1f9f1f00
3
+ size 683238238
data/ticks/035.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:7437eb161a729ed7cf3eda5b92e9acdc2e48ace0c11678514b1a1fffb0ed259e
3
- size 13537250980
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e85af5d97a95c5906f5db62363c55fdc46bd8774d539fca037cebb73e24f2d2d
3
+ size 13674409754
data/ticks/036.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:dbd0a8bb72f28afec0a9b6b7f5a938ec2e3a758bf30fac205bf8e5ebae444af3
3
- size 23101901278
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1d592fa4682d13cee9e174856b3c4a2fe7937dba4375938f718bf162396c5056
3
+ size 23337459002
data/ticks/037.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:9a4388c3c1ce6cef5349768b0210360824d37824c8e5cf45fe8e70eb48bc45e6
3
- size 25359402
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:16fed17db954b8fca729be26e80f6cf10cd31e519cfe9c25d9732dfbfd1461c3
3
+ size 25640340
data/ticks/038.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:ad5da92e26ed5ade9ba6b5430d534e9feceb23679efe0211ebc51e15e7779623
3
- size 307246351
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c30e56ee16f3b8285cd7bc2b2c2c63c0a24a697a2ae6ccab073635be4ee59778
3
+ size 310532525
data/ticks/039.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:237f344a55b4bd3014c5502c177b07f8b4f4e463689b68df2bcf443d5fbed393
3
- size 10519582199
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cc971e8f869f3af6d9ff6b2923f45a36159541662acee703e8cd1dc2121df69
3
+ size 10630729356
data/ticks/040.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:574f079273d822fec27031f4d28d821b222398ded7ebbd4b937a902d62198702
3
- size 17473241885
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b8a29000eb5863a48f64c1a9b26ffce8799a4db05020ac928333475a029aa93c
3
+ size 17614067314
data/ticks/041.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:282deff9e2448ef9af7aa5226fb8b0ed29949d8d44609697bdc4454ade065f28
3
- size 6500208522
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:473fccdc7b8871ff5385b812439dd5887e85f5429624e49fe93f91eac7278b66
3
+ size 6547243758
data/ticks/042.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:78ea5cc388362fa1b52bac6c704a0427aeccf5943fef57bc77ac4accbc077f8f
3
- size 7825522339
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b2d098902b863dece24dd62a96265783298d0e9b93d9e7654b5360a634918912
3
+ size 7889765448
data/ticks/043.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:38d7090e54ce702c2d0d3d47406ad5467cfc3276fbd4bd92d43bcd3449256d56
3
- size 15964728527
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:780c3bfab099e7833269f4c906440a143d262958c95e2c81f86171c4f7a37eed
3
+ size 16087819174
data/ticks/044.parquet CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:99fbbd84b6865b68c91c65f4435eb620b35d34b9c4803a60e58abe909bf9caf4
3
- size 12351398426
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8f56132f2fc45c5bc318fde4aa9313386b01c1f525d91f48bdd7db5bd8a175f0
3
+ size 7716259964
previews/013/thermal.mp4 CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:84fb87117f04f930df5e8e308c56c372a72d45f27f62f3471ab5a90234719436
3
- size 55420929
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d394714e25951d74b837b619e856e2c44cd5c1495650483dd50c556e8ed73768
3
+ size 9736266
previews/032/timelapse_composite.gif CHANGED

Git LFS Details

  • SHA256: 06ffc6ab6d0af8fe22bdee8ee853c3f9cc2e48444e2a10f4565649fc3858bb31
  • Pointer size: 132 Bytes
  • Size of remote file: 6.26 MB

Git LFS Details

  • SHA256: c131d08a03ebe7e4bb4796c51146a0edd19d429a47c3ad07f92cbbcaa3eaf05e
  • Pointer size: 132 Bytes
  • Size of remote file: 5.13 MB
previews/032/timelapse_thermal.gif CHANGED

Git LFS Details

  • SHA256: ac0f2f3c6183cc2a27b44e1725d58b177e10eebc96a7c58b51f23b7a78dda5eb
  • Pointer size: 132 Bytes
  • Size of remote file: 4.81 MB

Git LFS Details

  • SHA256: 4fbc7ca9fc94b8d364eceff425da7eff8942b07e10961e4b6a945c3fcf7e3038
  • Pointer size: 132 Bytes
  • Size of remote file: 3.41 MB
scripts/_lib.py CHANGED
@@ -1,8 +1,8 @@
1
  """Shared paths and helpers for the extract scripts.
2
 
3
- The raw data lives in a sibling Git repo (the recorder). This dataset has no
4
- local source files; every extract script reads from `EXPORTS_DIR` and writes
5
- to `DATA_DIR`.
6
  """
7
  import json
8
  from pathlib import Path
@@ -10,11 +10,12 @@ from pathlib import Path
10
  ROOT = Path(__file__).parent.parent
11
  DATA_DIR = ROOT / "data"
12
 
13
- # Sibling-repo location. The Telemetry dataset has no local source/ tree;
14
  # its raw inputs are the flat exports written by
15
  # `Agentic-Additive-Manufacturing-Process-Optimization/scripts/export.py`.
16
- # /mnt/storage2/HuggingFace/Datasets/Inova-Mk1-Telemetry up three to /mnt/storage2.
17
- AGENTIC_ROOT = ROOT.parent.parent.parent / "GitHub" / "Agentic-Additive-Manufacturing-Process-Optimization"
 
18
  EXPORTS_DIR = AGENTIC_ROOT / "data" / "exports"
19
 
20
 
 
1
  """Shared paths and helpers for the extract scripts.
2
 
3
+ The raw data lives in the recorder repo, which contains this dataset as a
4
+ submodule (`datasets/Inova-Mk1-Telemetry`). This dataset has no local source
5
+ files; every extract script reads from `EXPORTS_DIR` and writes to `DATA_DIR`.
6
  """
7
  import json
8
  from pathlib import Path
 
10
  ROOT = Path(__file__).parent.parent
11
  DATA_DIR = ROOT / "data"
12
 
13
+ # Recorder-repo location. The Telemetry dataset has no local source/ tree;
14
  # its raw inputs are the flat exports written by
15
  # `Agentic-Additive-Manufacturing-Process-Optimization/scripts/export.py`.
16
+ # This repo is a submodule at `datasets/Inova-Mk1-Telemetry` inside the
17
+ # recorder repo → two climbs from ROOT reach the recorder root.
18
+ AGENTIC_ROOT = ROOT.parent.parent
19
  EXPORTS_DIR = AGENTIC_ROOT / "data" / "exports"
20
 
21
 
scripts/previews/01_render.py CHANGED
@@ -16,6 +16,11 @@ Source is the dataset's own parquet — no recorder repo needed. The trade-off
16
  is that ~half of upstream-captured frames don't survive the per-tick attach,
17
  so motion looks chunkier than playing the raw recorder frames would.
18
 
 
 
 
 
 
19
  Usage:
20
  uv run scripts/previews/01_render.py # all builds in data/ticks/
21
  uv run scripts/previews/01_render.py 13 26 # specific build ids
@@ -35,12 +40,17 @@ import pyarrow.parquet as pq
35
  from PIL import Image
36
 
37
  sys.path.insert(0, str(Path(__file__).parent.parent))
 
38
  from _lib import DATA_DIR
 
39
 
40
  OUTPUT_DIR = DATA_DIR.parent / "previews"
41
  TICKS_DIR = DATA_DIR / "ticks"
42
  # Order here = left-to-right order in the composite panel.
43
  FRAME_KINDS = ("chamber", "thermal", "galvo")
 
 
 
44
  # Per-kind rotation applied post-decode (degrees clockwise). The chamber camera
45
  # is mounted sideways on the printer, so its raw frames need a 90° CW correction
46
  # before rendering. Other kinds are captured already in display orientation.
@@ -78,6 +88,40 @@ def _decode_raw(frame_struct, kind: str) -> Image.Image | None:
78
  return img
79
 
80
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
81
  def _fit_to_canvas(img: Image.Image, canvas_w: int) -> np.ndarray:
82
  """Letterbox `img` into a (canvas_w × PANEL_HEIGHT) gray canvas, preserving aspect.
83
  Locking on the canvas dims is required because some builds have frames whose
@@ -129,23 +173,22 @@ def _open_writer(out_path: Path):
129
  )
130
 
131
 
132
- def _probe_first_frame_width(parquet_path: Path, kind: str) -> int | None:
133
- """Find the first non-null frame of `kind`, compute the locked canvas width
134
- from its post-rotation aspect ratio (height = PANEL_HEIGHT). Returns None if
135
  no frame of that kind ever appears."""
136
- for n_rows, cols in _iter_struct_batches(parquet_path, [f"frame_{kind}"]):
137
- for struct in cols[f"frame_{kind}"]:
138
- img = _decode_raw(struct, kind)
139
  if img is not None:
140
  sw, sh = img.size
141
  return _even(max(2, round(sw * PANEL_HEIGHT / sh)))
142
  return None
143
 
144
 
145
- def render_per_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
146
- """Write one MP4 of a single frame kind, forward-filled. Returns frame count."""
147
- col = f"frame_{kind}"
148
- width = _probe_first_frame_width(parquet_path, kind)
149
  if width is None:
150
  # No frames of this kind exist for this build; nothing meaningful to render.
151
  print(f" {kind:8s}: no frames of this kind, skipping")
@@ -155,7 +198,7 @@ def render_per_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
155
  with _open_writer(out_path) as writer:
156
  for n_rows, cols in _iter_struct_batches(parquet_path, [col]):
157
  for struct in cols[col]:
158
- img = _decode_raw(struct, kind)
159
  if img is not None:
160
  last = _fit_to_canvas(img, width)
161
  writer.append_data(last if last is not None else _placeholder(width))
@@ -163,19 +206,19 @@ def render_per_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
163
  return frames_written
164
 
165
 
166
- def render_composite(parquet_path: Path, out_path: Path) -> int:
167
  """Write the 1×3 composite. All three panels share the tick timeline."""
168
  # Lock canvas widths up front so all subsequent frames letterbox into a fixed shape.
169
- widths = {k: (_probe_first_frame_width(parquet_path, k) or PANEL_HEIGHT)
170
  for k in FRAME_KINDS}
171
- cols_to_read = [f"frame_{k}" for k in FRAME_KINDS]
172
  last: dict[str, np.ndarray | None] = {k: None for k in FRAME_KINDS}
173
  frames_written = 0
174
  with _open_writer(out_path) as writer:
175
  for n_rows, cols in _iter_struct_batches(parquet_path, cols_to_read):
176
  for i in range(n_rows):
177
  for k in FRAME_KINDS:
178
- img = _decode_raw(cols[f"frame_{k}"][i], k)
179
  if img is not None:
180
  last[k] = _fit_to_canvas(img, widths[k])
181
  panels = [
@@ -194,18 +237,21 @@ def process_build(build_id: int, kinds: set[str]) -> None:
194
  return
195
  build_dir = OUTPUT_DIR / f"{build_id:03d}"
196
  print(f"build {build_id:03d}: rendering → {build_dir.relative_to(Path.cwd())}/")
 
 
 
197
  for kind in FRAME_KINDS:
198
  if kind not in kinds:
199
  continue
200
  out = build_dir / f"{kind}.mp4"
201
- n = render_per_kind(parquet_path, kind, out)
202
  # render_per_kind skips writing entirely when no frames of this kind exist
203
  # (and prints its own "skipping" line). Guard stat to avoid FileNotFoundError.
204
  if out.exists():
205
  print(f" {kind:8s}: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)")
206
  if "composite" in kinds:
207
  out = build_dir / "composite.mp4"
208
- n = render_composite(parquet_path, out)
209
  if out.exists():
210
  print(f" composite: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)")
211
 
 
16
  is that ~half of upstream-captured frames don't survive the per-tick attach,
17
  so motion looks chunkier than playing the raw recorder frames would.
18
 
19
+ The thermal panel is rendered from the raw `bedmatrix` IR grid (inferno colormap
20
+ over a fixed absolute °C range; see _thermal.py) whenever it's present — builds
21
+ 013+. The three earliest builds (001/002/012) predate the bedmatrix stream and
22
+ fall back to the legacy pre-rendered `frame_thermal` GIF.
23
+
24
  Usage:
25
  uv run scripts/previews/01_render.py # all builds in data/ticks/
26
  uv run scripts/previews/01_render.py 13 26 # specific build ids
 
40
  from PIL import Image
41
 
42
  sys.path.insert(0, str(Path(__file__).parent.parent))
43
+ sys.path.insert(0, str(Path(__file__).parent))
44
  from _lib import DATA_DIR
45
+ from _thermal import bedmatrix_to_image
46
 
47
  OUTPUT_DIR = DATA_DIR.parent / "previews"
48
  TICKS_DIR = DATA_DIR / "ticks"
49
  # Order here = left-to-right order in the composite panel.
50
  FRAME_KINDS = ("chamber", "thermal", "galvo")
51
+ # The thermal panel is rendered from the raw `bedmatrix` IR grid when present
52
+ # (builds 013+), falling back to the legacy `frame_thermal` GIF for the three
53
+ # earliest builds (001/002/012) that predate the bedmatrix stream.
54
  # Per-kind rotation applied post-decode (degrees clockwise). The chamber camera
55
  # is mounted sideways on the printer, so its raw frames need a 90° CW correction
56
  # before rendering. Other kinds are captured already in display orientation.
 
88
  return img
89
 
90
 
91
+ def _decode_cell(cell, kind: str) -> Image.Image | None:
92
+ """Decode one struct cell to a PIL RGB image, dispatching on struct shape:
93
+ a `bedmatrix` struct (has 'values') renders as an inferno heatmap; a frame
94
+ Image struct (has 'bytes') decodes + orientation-corrects. None when missing."""
95
+ if cell is None:
96
+ return None
97
+ if "values" in cell:
98
+ return bedmatrix_to_image(cell)
99
+ return _decode_raw(cell, kind)
100
+
101
+
102
+ def _thermal_column(parquet_path: Path) -> str:
103
+ """Which column feeds the thermal panel for this build: 'bedmatrix' when the
104
+ raw IR matrix has any non-null cell, else the legacy 'frame_thermal'. The
105
+ bedmatrix stream started at build 013, so 001/002/012 fall back to the GIF."""
106
+ pf = pq.ParquetFile(parquet_path)
107
+ if "bedmatrix" not in {f.name for f in pf.schema_arrow}:
108
+ return "frame_thermal"
109
+ for batch in pf.iter_batches(columns=["bedmatrix"], batch_size=BATCH_ROWS):
110
+ for cell in batch.column("bedmatrix").to_pylist():
111
+ if cell is not None:
112
+ return "bedmatrix"
113
+ return "frame_thermal"
114
+
115
+
116
+ def _columns_for_build(parquet_path: Path) -> dict[str, str]:
117
+ """Map each panel kind → the parquet column that feeds it for this build."""
118
+ return {
119
+ "chamber": "frame_chamber",
120
+ "thermal": _thermal_column(parquet_path),
121
+ "galvo": "frame_galvo",
122
+ }
123
+
124
+
125
  def _fit_to_canvas(img: Image.Image, canvas_w: int) -> np.ndarray:
126
  """Letterbox `img` into a (canvas_w × PANEL_HEIGHT) gray canvas, preserving aspect.
127
  Locking on the canvas dims is required because some builds have frames whose
 
173
  )
174
 
175
 
176
+ def _probe_first_frame_width(parquet_path: Path, kind: str, col: str) -> int | None:
177
+ """Find the first non-null cell in `col`, compute the locked canvas width
178
+ from its post-decode aspect ratio (height = PANEL_HEIGHT). Returns None if
179
  no frame of that kind ever appears."""
180
+ for n_rows, cols in _iter_struct_batches(parquet_path, [col]):
181
+ for struct in cols[col]:
182
+ img = _decode_cell(struct, kind)
183
  if img is not None:
184
  sw, sh = img.size
185
  return _even(max(2, round(sw * PANEL_HEIGHT / sh)))
186
  return None
187
 
188
 
189
+ def render_per_kind(parquet_path: Path, kind: str, out_path: Path, col: str) -> int:
190
+ """Write one MP4 of a single panel kind, forward-filled. Returns frame count."""
191
+ width = _probe_first_frame_width(parquet_path, kind, col)
 
192
  if width is None:
193
  # No frames of this kind exist for this build; nothing meaningful to render.
194
  print(f" {kind:8s}: no frames of this kind, skipping")
 
198
  with _open_writer(out_path) as writer:
199
  for n_rows, cols in _iter_struct_batches(parquet_path, [col]):
200
  for struct in cols[col]:
201
+ img = _decode_cell(struct, kind)
202
  if img is not None:
203
  last = _fit_to_canvas(img, width)
204
  writer.append_data(last if last is not None else _placeholder(width))
 
206
  return frames_written
207
 
208
 
209
+ def render_composite(parquet_path: Path, out_path: Path, cols_map: dict[str, str]) -> int:
210
  """Write the 1×3 composite. All three panels share the tick timeline."""
211
  # Lock canvas widths up front so all subsequent frames letterbox into a fixed shape.
212
+ widths = {k: (_probe_first_frame_width(parquet_path, k, cols_map[k]) or PANEL_HEIGHT)
213
  for k in FRAME_KINDS}
214
+ cols_to_read = [cols_map[k] for k in FRAME_KINDS]
215
  last: dict[str, np.ndarray | None] = {k: None for k in FRAME_KINDS}
216
  frames_written = 0
217
  with _open_writer(out_path) as writer:
218
  for n_rows, cols in _iter_struct_batches(parquet_path, cols_to_read):
219
  for i in range(n_rows):
220
  for k in FRAME_KINDS:
221
+ img = _decode_cell(cols[cols_map[k]][i], k)
222
  if img is not None:
223
  last[k] = _fit_to_canvas(img, widths[k])
224
  panels = [
 
237
  return
238
  build_dir = OUTPUT_DIR / f"{build_id:03d}"
239
  print(f"build {build_id:03d}: rendering → {build_dir.relative_to(Path.cwd())}/")
240
+ cols_map = _columns_for_build(parquet_path)
241
+ if ("thermal" in kinds or "composite" in kinds):
242
+ print(f" thermal source: {cols_map['thermal']}")
243
  for kind in FRAME_KINDS:
244
  if kind not in kinds:
245
  continue
246
  out = build_dir / f"{kind}.mp4"
247
+ n = render_per_kind(parquet_path, kind, out, cols_map[kind])
248
  # render_per_kind skips writing entirely when no frames of this kind exist
249
  # (and prints its own "skipping" line). Guard stat to avoid FileNotFoundError.
250
  if out.exists():
251
  print(f" {kind:8s}: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)")
252
  if "composite" in kinds:
253
  out = build_dir / "composite.mp4"
254
+ n = render_composite(parquet_path, out, cols_map)
255
  if out.exists():
256
  print(f" composite: {n:>7,} frames → {out.name} ({out.stat().st_size:,} bytes)")
257
 
scripts/previews/02_timelapse.py CHANGED
@@ -16,6 +16,11 @@ the most-recent view of the layer just before recoating begins.
16
  Null-frame levels are forward-filled from the most recent non-null level of the
17
  same kind, so the GIF never shows a blank panel mid-timelapse.
18
 
 
 
 
 
 
19
  Subsampled to at most MAX_FRAMES (default 300). At GIF_FPS=25 that gives
20
  a max 12-second GIF. Builds with fewer detected layers are not padded.
21
 
@@ -35,13 +40,18 @@ import pyarrow.parquet as pq
35
  from PIL import Image, ImageStat
36
 
37
  sys.path.insert(0, str(Path(__file__).parent.parent))
 
38
  from _lib import DATA_DIR
 
39
 
40
  OUTPUT_DIR = DATA_DIR.parent / "previews"
41
  TICKS_DIR = DATA_DIR / "ticks"
42
 
43
  FRAME_KINDS = ("chamber", "thermal", "galvo")
44
  KIND_ROTATION_CW = {"chamber": 90} # degrees; see _decode_raw
 
 
 
45
 
46
  GIF_FPS = 25
47
  GIF_DURATION_MS = int(1000 / GIF_FPS) # 40 ms per frame
@@ -82,6 +92,49 @@ def _decode_raw(b: bytes, kind: str) -> Image.Image | None:
82
  return img
83
 
84
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
85
  def _fit_to_canvas(img: Image.Image, canvas_w: int) -> Image.Image:
86
  """Letterbox img into (canvas_w × GIF_PANEL_HEIGHT) with dark-gray fill."""
87
  sw, sh = img.size
@@ -110,78 +163,63 @@ def _chamber_threshold(decoded_frames: list[Image.Image | None]) -> float:
110
  return max(brightnesses) * CHAMBER_BRIGHTNESS_RATIO if brightnesses else 0.0
111
 
112
 
113
- def _canvas_width_from_bytes(b: bytes, kind: str) -> int:
114
- """Decode one frame to determine the locked canvas width for this kind."""
115
- img = _decode_raw(b, kind)
116
- if img is None:
117
- return GIF_PANEL_HEIGHT # square fallback
118
- sw, sh = img.size
119
- return max(2, round(sw * GIF_PANEL_HEIGHT / sh))
120
-
121
-
122
  # ---------------------------------------------------------------------------
123
  # Layer data collection
124
  # ---------------------------------------------------------------------------
125
 
126
- def collect_layer_bytes(parquet_path: Path, kind: str) -> dict[int, bytes]:
127
- """Single-pass stream → {z2_level: last_non_null_bytes}.
128
 
129
  Only z2 > 0 rows are included. The dict is keyed by int(z2 / LAYER_QUANTIZE_UM);
130
- each entry holds the bytes of the *last* non-null frame seen at that level.
131
- Reads only two parquet columns (z2 + one frame kind) for efficiency.
 
132
  """
133
- frame_col = f"frame_{kind}"
134
- z2_col = "positions.position.z2"
135
- pf = pq.ParquetFile(parquet_path)
136
- present = {f.name for f in pf.schema_arrow}
137
- if frame_col not in present or z2_col not in present:
138
  return {}
139
 
140
- layer_data: dict[int, bytes] = {}
141
- for batch in pf.iter_batches(columns=[z2_col, frame_col], batch_size=BATCH_ROWS):
142
- z2_list = batch.column(z2_col).to_pylist()
143
- frame_list = batch.column(frame_col).to_pylist()
144
- for z2, struct in zip(z2_list, frame_list):
145
  if z2 is None or z2 <= 0:
146
  continue
147
- level = int(z2 / LAYER_QUANTIZE_UM)
148
- if struct is not None:
149
- b = struct.get("bytes")
150
- if b:
151
- layer_data[level] = b
152
  return layer_data
153
 
154
 
155
- def collect_all_kinds(parquet_path: Path) -> dict[str, dict[int, bytes]]:
156
  """Single streaming pass collecting all three kinds simultaneously.
157
 
158
  Used by render_timelapse_composite so we don't make three separate passes
159
- through (potentially 17+ GB) parquet files. Reads four columns: z2 + the
160
- three frame columns. Each kind gets its own {z2_level: bytes} dict.
161
  """
162
  z2_col = "positions.position.z2"
163
  pf = pq.ParquetFile(parquet_path)
164
  present = {f.name for f in pf.schema_arrow}
165
- read_cols = [c for c in ([z2_col] + [f"frame_{k}" for k in FRAME_KINDS]) if c in present]
166
  if z2_col not in read_cols:
167
  return {k: {} for k in FRAME_KINDS}
168
 
169
- layer_data: dict[str, dict[int, bytes]] = {k: {} for k in FRAME_KINDS}
170
  for batch in pf.iter_batches(columns=read_cols, batch_size=BATCH_ROWS):
171
  z2_list = batch.column(z2_col).to_pylist()
172
  for kind in FRAME_KINDS:
173
- col = f"frame_{kind}"
174
  if col not in read_cols:
175
  continue
176
- frame_list = batch.column(col).to_pylist()
177
- for z2, struct in zip(z2_list, frame_list):
178
  if z2 is None or z2 <= 0:
179
  continue
180
- level = int(z2 / LAYER_QUANTIZE_UM)
181
- if struct is not None:
182
- b = struct.get("bytes")
183
- if b:
184
- layer_data[kind][level] = b
185
  return layer_data
186
 
187
 
@@ -238,25 +276,25 @@ def _write_gif(frames: list[Image.Image], out_path: Path) -> None:
238
  # Per-build renderers
239
  # ---------------------------------------------------------------------------
240
 
241
- def render_timelapse_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
242
  """Write timelapse_{kind}.gif. Returns number of GIF frames written.
243
 
244
  Chamber only: dark frames (halogens off) are dropped entirely so the GIF
245
  shows only moments where the part is visible. Thermal and galvo are
246
  unaffected — they don't depend on halogen lighting.
247
  """
248
- layer_bytes = collect_layer_bytes(parquet_path, kind)
249
- if not layer_bytes:
250
  print(f" {kind:8s}: no printing-phase frames (z2 > 0), skipping")
251
  return 0
252
 
253
- sorted_levels = sorted(layer_bytes)
254
  target_levels = _subsample(sorted_levels)
255
- fill_bytes = _forward_fill(layer_bytes, target_levels)
256
- canvas_w = _canvas_width_from_bytes(next(b for b in fill_bytes if b), kind)
257
 
258
  # Decode all selected frames up front (needed for brightness scan on chamber).
259
- decoded = [_decode_raw(b, kind) if b else None for b in fill_bytes]
260
 
261
  if kind == "chamber":
262
  # Compute brightness once per decoded frame, then threshold and filter.
@@ -289,7 +327,8 @@ def render_timelapse_kind(parquet_path: Path, kind: str, out_path: Path) -> int:
289
  return len(pil_frames)
290
 
291
 
292
- def render_timelapse_composite(parquet_path: Path, out_path: Path) -> int:
 
293
  """Write timelapse_composite.gif (1×3 panel). Single parquet pass.
294
 
295
  Thermal and galvo show the actual frame for every layer (unaffected by
@@ -297,28 +336,27 @@ def render_timelapse_composite(parquet_path: Path, out_path: Path) -> int:
297
  when the current layer's chamber frame is dark — this keeps all three
298
  panels in layer-sync while never displaying a dark chamber view.
299
  """
300
- all_bytes = collect_all_kinds(parquet_path)
301
 
302
- all_levels = sorted(set().union(*(set(d) for d in all_bytes.values())))
303
  if not all_levels:
304
  print(" composite: no printing-phase frames (z2 > 0), skipping")
305
  return 0
306
 
307
  target_levels = _subsample(all_levels)
308
- fill_per_kind = {k: _forward_fill(all_bytes[k], target_levels) for k in FRAME_KINDS}
309
 
310
  canvas_widths: dict[str, int] = {}
311
  for kind in FRAME_KINDS:
312
- first_b = next((b for b in fill_per_kind[kind] if b), None)
313
  canvas_widths[kind] = (
314
- _canvas_width_from_bytes(first_b, kind) if first_b else GIF_PANEL_HEIGHT
315
  )
316
  total_w = sum(canvas_widths.values())
317
 
318
  # Pre-decode chamber frames once; compute adaptive brightness threshold.
319
  chamber_decoded = [
320
- _decode_raw(b, "chamber") if b else None
321
- for b in fill_per_kind["chamber"]
322
  ]
323
  chamber_threshold = _chamber_threshold(chamber_decoded)
324
 
@@ -337,8 +375,7 @@ def render_timelapse_composite(parquet_path: Path, out_path: Path) -> int:
337
  # the first bright frame arrives.
338
  panel_img = last_bright_chamber
339
  else:
340
- b = fill_per_kind[kind][i]
341
- panel_img = _decode_raw(b, kind) if b else None
342
 
343
  panel = (
344
  _fit_to_canvas(panel_img, canvas_widths[kind])
@@ -360,19 +397,22 @@ def process_build(build_id: int, kinds: set[str]) -> None:
360
 
361
  build_dir = OUTPUT_DIR / f"{build_id:03d}"
362
  print(f"build {build_id:03d}: timelapse GIFs → {build_dir.relative_to(Path.cwd())}/")
 
 
 
363
 
364
  for kind in FRAME_KINDS:
365
  if kind not in kinds:
366
  continue
367
  out = build_dir / f"timelapse_{kind}.gif"
368
- n = render_timelapse_kind(parquet_path, kind, out)
369
  if out.exists():
370
  size = out.stat().st_size
371
  print(f" {kind:8s}: {n:>4} frames → {out.name} ({size:,} bytes)")
372
 
373
  if "composite" in kinds:
374
  out = build_dir / "timelapse_composite.gif"
375
- n = render_timelapse_composite(parquet_path, out)
376
  if out.exists():
377
  size = out.stat().st_size
378
  print(f" composite: {n:>4} frames → {out.name} ({size:,} bytes)")
 
16
  Null-frame levels are forward-filled from the most recent non-null level of the
17
  same kind, so the GIF never shows a blank panel mid-timelapse.
18
 
19
+ The thermal panel is rendered from the raw `bedmatrix` IR grid (inferno colormap
20
+ over a fixed absolute °C range; see _thermal.py) whenever it's present — builds
21
+ 013+. The three earliest builds (001/002/012) predate the bedmatrix stream and
22
+ fall back to the legacy pre-rendered `frame_thermal` GIF.
23
+
24
  Subsampled to at most MAX_FRAMES (default 300). At GIF_FPS=25 that gives
25
  a max 12-second GIF. Builds with fewer detected layers are not padded.
26
 
 
40
  from PIL import Image, ImageStat
41
 
42
  sys.path.insert(0, str(Path(__file__).parent.parent))
43
+ sys.path.insert(0, str(Path(__file__).parent))
44
  from _lib import DATA_DIR
45
+ from _thermal import bedmatrix_to_image
46
 
47
  OUTPUT_DIR = DATA_DIR.parent / "previews"
48
  TICKS_DIR = DATA_DIR / "ticks"
49
 
50
  FRAME_KINDS = ("chamber", "thermal", "galvo")
51
  KIND_ROTATION_CW = {"chamber": 90} # degrees; see _decode_raw
52
+ # The thermal panel renders from the raw `bedmatrix` IR grid when present
53
+ # (builds 013+), falling back to the legacy `frame_thermal` GIF for the three
54
+ # earliest builds (001/002/012) that predate the bedmatrix stream.
55
 
56
  GIF_FPS = 25
57
  GIF_DURATION_MS = int(1000 / GIF_FPS) # 40 ms per frame
 
92
  return img
93
 
94
 
95
+ def _decode_cell(cell, kind: str) -> Image.Image | None:
96
+ """Decode one struct cell to a PIL RGB image, dispatching on struct shape:
97
+ a `bedmatrix` struct (has 'values') renders as an inferno heatmap; a frame
98
+ Image struct (has 'bytes') decodes + orientation-corrects. None when missing."""
99
+ if cell is None:
100
+ return None
101
+ if "values" in cell:
102
+ return bedmatrix_to_image(cell)
103
+ return _decode_raw(cell.get("bytes"), kind)
104
+
105
+
106
+ def _thermal_column(parquet_path: Path) -> str:
107
+ """Which column feeds the thermal panel for this build: 'bedmatrix' when the
108
+ raw IR matrix has any non-null cell, else the legacy 'frame_thermal'. The
109
+ bedmatrix stream started at build 013, so 001/002/012 fall back to the GIF."""
110
+ pf = pq.ParquetFile(parquet_path)
111
+ if "bedmatrix" not in {f.name for f in pf.schema_arrow}:
112
+ return "frame_thermal"
113
+ for batch in pf.iter_batches(columns=["bedmatrix"], batch_size=BATCH_ROWS):
114
+ for cell in batch.column("bedmatrix").to_pylist():
115
+ if cell is not None:
116
+ return "bedmatrix"
117
+ return "frame_thermal"
118
+
119
+
120
+ def _columns_for_build(parquet_path: Path) -> dict[str, str]:
121
+ """Map each panel kind → the parquet column that feeds it for this build."""
122
+ return {
123
+ "chamber": "frame_chamber",
124
+ "thermal": _thermal_column(parquet_path),
125
+ "galvo": "frame_galvo",
126
+ }
127
+
128
+
129
+ def _canvas_width(cell, kind: str) -> int:
130
+ """Decode one cell to determine the locked canvas width for this kind."""
131
+ img = _decode_cell(cell, kind)
132
+ if img is None:
133
+ return GIF_PANEL_HEIGHT # square fallback
134
+ sw, sh = img.size
135
+ return max(2, round(sw * GIF_PANEL_HEIGHT / sh))
136
+
137
+
138
  def _fit_to_canvas(img: Image.Image, canvas_w: int) -> Image.Image:
139
  """Letterbox img into (canvas_w × GIF_PANEL_HEIGHT) with dark-gray fill."""
140
  sw, sh = img.size
 
163
  return max(brightnesses) * CHAMBER_BRIGHTNESS_RATIO if brightnesses else 0.0
164
 
165
 
 
 
 
 
 
 
 
 
 
166
  # ---------------------------------------------------------------------------
167
  # Layer data collection
168
  # ---------------------------------------------------------------------------
169
 
170
+ def collect_layer_cells(parquet_path: Path, kind: str, col: str) -> dict[int, dict]:
171
+ """Single-pass stream → {z2_level: last_non_null_struct}.
172
 
173
  Only z2 > 0 rows are included. The dict is keyed by int(z2 / LAYER_QUANTIZE_UM);
174
+ each entry holds the *last* non-null struct cell seen at that level (a frame
175
+ Image struct, or a bedmatrix struct for the thermal panel). Reads only two
176
+ parquet columns (z2 + the source column) for efficiency.
177
  """
178
+ z2_col = "positions.position.z2"
179
+ pf = pq.ParquetFile(parquet_path)
180
+ present = {f.name for f in pf.schema_arrow}
181
+ if col not in present or z2_col not in present:
 
182
  return {}
183
 
184
+ layer_data: dict[int, dict] = {}
185
+ for batch in pf.iter_batches(columns=[z2_col, col], batch_size=BATCH_ROWS):
186
+ z2_list = batch.column(z2_col).to_pylist()
187
+ cell_list = batch.column(col).to_pylist()
188
+ for z2, cell in zip(z2_list, cell_list):
189
  if z2 is None or z2 <= 0:
190
  continue
191
+ if cell is not None:
192
+ layer_data[int(z2 / LAYER_QUANTIZE_UM)] = cell
 
 
 
193
  return layer_data
194
 
195
 
196
+ def collect_all_kinds(parquet_path: Path, cols_map: dict[str, str]) -> dict[str, dict[int, dict]]:
197
  """Single streaming pass collecting all three kinds simultaneously.
198
 
199
  Used by render_timelapse_composite so we don't make three separate passes
200
+ through (potentially 17+ GB) parquet files. Reads four columns: z2 + each
201
+ kind's source column. Each kind gets its own {z2_level: struct} dict.
202
  """
203
  z2_col = "positions.position.z2"
204
  pf = pq.ParquetFile(parquet_path)
205
  present = {f.name for f in pf.schema_arrow}
206
+ read_cols = [c for c in ([z2_col] + [cols_map[k] for k in FRAME_KINDS]) if c in present]
207
  if z2_col not in read_cols:
208
  return {k: {} for k in FRAME_KINDS}
209
 
210
+ layer_data: dict[str, dict[int, dict]] = {k: {} for k in FRAME_KINDS}
211
  for batch in pf.iter_batches(columns=read_cols, batch_size=BATCH_ROWS):
212
  z2_list = batch.column(z2_col).to_pylist()
213
  for kind in FRAME_KINDS:
214
+ col = cols_map[kind]
215
  if col not in read_cols:
216
  continue
217
+ cell_list = batch.column(col).to_pylist()
218
+ for z2, cell in zip(z2_list, cell_list):
219
  if z2 is None or z2 <= 0:
220
  continue
221
+ if cell is not None:
222
+ layer_data[kind][int(z2 / LAYER_QUANTIZE_UM)] = cell
 
 
 
223
  return layer_data
224
 
225
 
 
276
  # Per-build renderers
277
  # ---------------------------------------------------------------------------
278
 
279
+ def render_timelapse_kind(parquet_path: Path, kind: str, out_path: Path, col: str) -> int:
280
  """Write timelapse_{kind}.gif. Returns number of GIF frames written.
281
 
282
  Chamber only: dark frames (halogens off) are dropped entirely so the GIF
283
  shows only moments where the part is visible. Thermal and galvo are
284
  unaffected — they don't depend on halogen lighting.
285
  """
286
+ layer_cells = collect_layer_cells(parquet_path, kind, col)
287
+ if not layer_cells:
288
  print(f" {kind:8s}: no printing-phase frames (z2 > 0), skipping")
289
  return 0
290
 
291
+ sorted_levels = sorted(layer_cells)
292
  target_levels = _subsample(sorted_levels)
293
+ fill_cells = _forward_fill(layer_cells, target_levels)
294
+ canvas_w = _canvas_width(next(c for c in fill_cells if c), kind)
295
 
296
  # Decode all selected frames up front (needed for brightness scan on chamber).
297
+ decoded = [_decode_cell(c, kind) for c in fill_cells]
298
 
299
  if kind == "chamber":
300
  # Compute brightness once per decoded frame, then threshold and filter.
 
327
  return len(pil_frames)
328
 
329
 
330
+ def render_timelapse_composite(parquet_path: Path, out_path: Path,
331
+ cols_map: dict[str, str]) -> int:
332
  """Write timelapse_composite.gif (1×3 panel). Single parquet pass.
333
 
334
  Thermal and galvo show the actual frame for every layer (unaffected by
 
336
  when the current layer's chamber frame is dark — this keeps all three
337
  panels in layer-sync while never displaying a dark chamber view.
338
  """
339
+ all_cells = collect_all_kinds(parquet_path, cols_map)
340
 
341
+ all_levels = sorted(set().union(*(set(d) for d in all_cells.values())))
342
  if not all_levels:
343
  print(" composite: no printing-phase frames (z2 > 0), skipping")
344
  return 0
345
 
346
  target_levels = _subsample(all_levels)
347
+ fill_per_kind = {k: _forward_fill(all_cells[k], target_levels) for k in FRAME_KINDS}
348
 
349
  canvas_widths: dict[str, int] = {}
350
  for kind in FRAME_KINDS:
351
+ first_c = next((c for c in fill_per_kind[kind] if c), None)
352
  canvas_widths[kind] = (
353
+ _canvas_width(first_c, kind) if first_c else GIF_PANEL_HEIGHT
354
  )
355
  total_w = sum(canvas_widths.values())
356
 
357
  # Pre-decode chamber frames once; compute adaptive brightness threshold.
358
  chamber_decoded = [
359
+ _decode_cell(c, "chamber") for c in fill_per_kind["chamber"]
 
360
  ]
361
  chamber_threshold = _chamber_threshold(chamber_decoded)
362
 
 
375
  # the first bright frame arrives.
376
  panel_img = last_bright_chamber
377
  else:
378
+ panel_img = _decode_cell(fill_per_kind[kind][i], kind)
 
379
 
380
  panel = (
381
  _fit_to_canvas(panel_img, canvas_widths[kind])
 
397
 
398
  build_dir = OUTPUT_DIR / f"{build_id:03d}"
399
  print(f"build {build_id:03d}: timelapse GIFs → {build_dir.relative_to(Path.cwd())}/")
400
+ cols_map = _columns_for_build(parquet_path)
401
+ if ("thermal" in kinds or "composite" in kinds):
402
+ print(f" thermal source: {cols_map['thermal']}")
403
 
404
  for kind in FRAME_KINDS:
405
  if kind not in kinds:
406
  continue
407
  out = build_dir / f"timelapse_{kind}.gif"
408
+ n = render_timelapse_kind(parquet_path, kind, out, cols_map[kind])
409
  if out.exists():
410
  size = out.stat().st_size
411
  print(f" {kind:8s}: {n:>4} frames → {out.name} ({size:,} bytes)")
412
 
413
  if "composite" in kinds:
414
  out = build_dir / "timelapse_composite.gif"
415
+ n = render_timelapse_composite(parquet_path, out, cols_map)
416
  if out.exists():
417
  size = out.stat().st_size
418
  print(f" composite: {n:>4} frames → {out.name} ({size:,} bytes)")
scripts/previews/_thermal.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared bedmatrix → thermal heatmap rendering for the preview scripts.
2
+
3
+ The `bedmatrix` column is the raw 32×24 IR bed-surface temperature grid
4
+ (row-major °C). We colormap it ourselves rather than reuse the legacy
5
+ `frame_thermal` GIF because:
6
+
7
+ * `frame_thermal` was a firmware-rendered heatmap whose colormap and scale we
8
+ never controlled and can't reproduce for new builds — and it's null for
9
+ builds recorded after 2026-07-12 (see CLAUDE.md).
10
+ * Rendering from `bedmatrix` gives one consistent look across every build and
11
+ a temperature scale we choose, so the thermal panel reads as an honest
12
+ temperature: the same color means the same °C in every build.
13
+
14
+ Colormap is an inferno approximation (11 anchor colors linearly interpolated to
15
+ 256 entries) — faithful enough for a preview without pulling in matplotlib.
16
+
17
+ Temperature → color uses a FIXED absolute range (`THERMAL_VMIN`..`THERMAL_VMAX`,
18
+ °C). The observed bedmatrix span across builds is ~51–191 °C during sintering;
19
+ the default 20–200 °C covers ambient through peak sinter with headroom and uses
20
+ the full colormap. Override via the THERMAL_VMIN / THERMAL_VMAX env vars.
21
+ """
22
+ import os
23
+
24
+ import numpy as np
25
+ from PIL import Image
26
+
27
+ THERMAL_VMIN = float(os.environ.get("THERMAL_VMIN", 20.0))
28
+ THERMAL_VMAX = float(os.environ.get("THERMAL_VMAX", 200.0))
29
+
30
+ # Inferno anchor colors at t = 0.0, 0.1, ... 1.0 (RGB 0–255). Sampled from
31
+ # matplotlib's inferno; linearly interpolated per channel to a 256-entry LUT.
32
+ _INFERNO_ANCHORS = np.array([
33
+ (0, 0, 4),
34
+ (20, 11, 52),
35
+ (57, 9, 98),
36
+ (100, 16, 108),
37
+ (143, 33, 102),
38
+ (186, 54, 85),
39
+ (221, 81, 58),
40
+ (243, 120, 25),
41
+ (252, 165, 10),
42
+ (246, 215, 70),
43
+ (252, 255, 164),
44
+ ], dtype=np.float64)
45
+
46
+ _LUT: np.ndarray | None = None
47
+
48
+
49
+ def _lut() -> np.ndarray:
50
+ """256×3 uint8 inferno LUT, built once."""
51
+ global _LUT
52
+ if _LUT is None:
53
+ xs = np.linspace(0.0, 1.0, len(_INFERNO_ANCHORS))
54
+ grid = np.linspace(0.0, 1.0, 256)
55
+ lut = np.empty((256, 3), dtype=np.uint8)
56
+ for c in range(3):
57
+ lut[:, c] = np.interp(grid, xs, _INFERNO_ANCHORS[:, c]).round().astype(np.uint8)
58
+ _LUT = lut
59
+ return _LUT
60
+
61
+
62
+ def bedmatrix_to_image(bm) -> Image.Image | None:
63
+ """Render a `bedmatrix` struct → PIL RGB heatmap at native grid resolution.
64
+
65
+ `bm` is the struct dict {width, height, values (row-major °C), path} or None.
66
+ Returns a (height × width) RGB image; the caller upscales / letterboxes it.
67
+ None when the struct is missing or malformed.
68
+ """
69
+ if bm is None:
70
+ return None
71
+ vals = bm.get("values")
72
+ w = bm.get("width")
73
+ h = bm.get("height")
74
+ if not vals or not w or not h or len(vals) != w * h:
75
+ return None
76
+ a = np.asarray(vals, dtype=np.float32).reshape(int(h), int(w))
77
+ a = np.nan_to_num(a, nan=THERMAL_VMIN)
78
+ t = (a - THERMAL_VMIN) / (THERMAL_VMAX - THERMAL_VMIN)
79
+ idx = np.clip(t, 0.0, 1.0)
80
+ idx = (idx * 255.0).round().astype(np.uint8)
81
+ rgb = _lut()[idx] # (h, w, 3)
82
+ return Image.fromarray(rgb, "RGB")
scripts/ticks/01_extract.py CHANGED
@@ -1,7 +1,7 @@
1
  #!/usr/bin/env python3
2
  """Build the `ticks` config: one row per 10 Hz telemetry tick per build.
3
 
4
- Reads upstream flat exports from the sibling recorder repo:
5
  builds.jsonl, telemetry/{build_id}.parquet, frames.jsonl, position_hf/{build_id}.parquet
6
 
7
  For each build with telemetry, emits `data/ticks/{build_id:03d}.parquet`
@@ -11,6 +11,12 @@ For each build with telemetry, emits `data/ticks/{build_id:03d}.parquet`
11
  - Denormalized build context (build_id, job_name, ..., print_profile_name)
12
  - frame_chamber / frame_galvo / frame_thermal: nearest frame path in
13
  [tick_ts - 100ms, tick_ts], null when no frame fell in that window
 
 
 
 
 
 
14
  - position_hf_burst: list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
15
  for all position_hf events in the same 100ms window
16
 
@@ -18,6 +24,7 @@ Usage:
18
  uv run scripts/ticks/01_extract.py # all builds with telemetry
19
  uv run scripts/ticks/01_extract.py 13 26 # specific build ids
20
  """
 
21
  import sys
22
  from datetime import timedelta
23
  from pathlib import Path
@@ -33,6 +40,10 @@ from _lib import EXPORTS_DIR, DATA_DIR, iter_jsonl, load_build_to_profile_name
33
  OUTPUT_DIR = DATA_DIR / "ticks"
34
  WINDOW = timedelta(milliseconds=100) # 10 Hz tick interval
35
  FRAME_KINDS = ("chamber", "galvo", "thermal")
 
 
 
 
36
  # frame_* path strings are relative to this directory in the upstream recorder repo.
37
  FRAMES_DIR = EXPORTS_DIR.parent / "frames"
38
  # HF Image feature wire format. Both fields nullable; the struct itself is null when no frame.
@@ -40,6 +51,15 @@ IMAGE_STRUCT_TYPE = pa.struct([
40
  pa.field("bytes", pa.binary()),
41
  pa.field("path", pa.string()),
42
  ])
 
 
 
 
 
 
 
 
 
43
  # Streaming chunk size in rows. Tuned so peak embedded payload per chunk stays
44
  # under ~1 GB (thermal frames dominate at ~315 KB each).
45
  CHUNK_ROWS = 2_000
@@ -93,6 +113,22 @@ def attach_frames(wide: pl.DataFrame, frames: pl.DataFrame) -> pl.DataFrame:
93
  return wide
94
 
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  def attach_position_hf(wide: pl.DataFrame, build_id: int) -> pl.DataFrame:
97
  """Append a `position_hf_burst` column: list of structs of position_hf events
98
  in (tick_ts - WINDOW, tick_ts]. Empty list when no events in window or no parquet."""
@@ -174,25 +210,63 @@ def _embed_frame_column(paths: list[str | None]) -> pa.Array:
174
  )
175
 
176
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
177
  def _make_output_schema(wide_arrow_schema: pa.Schema) -> pa.Schema:
178
- """Replace frame_* string fields with HF Image struct fields."""
 
179
  new_fields = []
180
  image_field_names = {f"frame_{k}" for k in FRAME_KINDS}
181
  for field in wide_arrow_schema:
182
  if field.name in image_field_names:
183
  new_fields.append(pa.field(field.name, IMAGE_STRUCT_TYPE))
 
 
184
  else:
185
  new_fields.append(field)
186
  return pa.schema(new_fields)
187
 
188
 
189
  def _embed_chunk(chunk: pa.Table, output_schema: pa.Schema) -> pa.Table:
190
- """Swap frame_* string columns for embedded image structs in this chunk."""
 
191
  arrays = []
192
  for field in output_schema:
193
- if field.name in {f"frame_{k}" for k in FRAME_KINDS}:
194
- paths = chunk[field.name].to_pylist()
195
- arrays.append(_embed_frame_column(paths))
 
196
  else:
197
  arrays.append(chunk[field.name].combine_chunks())
198
  return pa.Table.from_arrays(arrays, schema=output_schema)
@@ -211,14 +285,15 @@ def process_build(build_id: int, builds_index: dict[int, dict],
211
  wide = pivot_telemetry(tel)
212
  frames = load_frames_for_build(build_id)
213
  wide = attach_frames(wide, frames)
 
214
  wide = attach_position_hf(wide, build_id)
215
  wide = denormalize_build(wide, builds_index[build_id], profile_name_lookup)
216
 
217
- # Put build context + ts first, then sensors, then frames + burst.
218
  leading = ["build_id", "ts", "job_name", "started_at", "ended_at", "phase",
219
  "print_profile_name", "inova_session_id"]
220
  frame_cols = [f"frame_{k}" for k in FRAME_KINDS]
221
- trailing = frame_cols + ["position_hf_burst"]
222
  middle = [c for c in wide.columns if c not in leading and c not in trailing]
223
  wide = wide.select(leading + middle + trailing)
224
 
 
1
  #!/usr/bin/env python3
2
  """Build the `ticks` config: one row per 10 Hz telemetry tick per build.
3
 
4
+ Reads upstream flat exports from the containing recorder repo:
5
  builds.jsonl, telemetry/{build_id}.parquet, frames.jsonl, position_hf/{build_id}.parquet
6
 
7
  For each build with telemetry, emits `data/ticks/{build_id:03d}.parquet`
 
11
  - Denormalized build context (build_id, job_name, ..., print_profile_name)
12
  - frame_chamber / frame_galvo / frame_thermal: nearest frame path in
13
  [tick_ts - 100ms, tick_ts], null when no frame fell in that window
14
+ (frame_thermal is the legacy bedmatrix GIF heatmap; recorder stopped
15
+ producing it after 2026-07-12, so it is null for builds captured since)
16
+ - bedmatrix: nearest IR temperature matrix in the same 100ms window, as a
17
+ struct {width, height, values (row-major °C), path}; null when none.
18
+ This is the raw 32x24 bed-surface temperature grid the recorder now streams
19
+ as JSON in place of the old rendered frame_thermal heatmap.
20
  - position_hf_burst: list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
21
  for all position_hf events in the same 100ms window
22
 
 
24
  uv run scripts/ticks/01_extract.py # all builds with telemetry
25
  uv run scripts/ticks/01_extract.py 13 26 # specific build ids
26
  """
27
+ import json
28
  import sys
29
  from datetime import timedelta
30
  from pathlib import Path
 
40
  OUTPUT_DIR = DATA_DIR / "ticks"
41
  WINDOW = timedelta(milliseconds=100) # 10 Hz tick interval
42
  FRAME_KINDS = ("chamber", "galvo", "thermal")
43
+ # The IR temperature matrix. Same underlying sensor the legacy frame_thermal GIF
44
+ # was rendered from, but streamed as a raw {width, height, values} JSON grid.
45
+ # Attached like a frame (nearest-before-tick), embedded as a numeric struct.
46
+ BEDMATRIX_KIND = "bedmatrix"
47
  # frame_* path strings are relative to this directory in the upstream recorder repo.
48
  FRAMES_DIR = EXPORTS_DIR.parent / "frames"
49
  # HF Image feature wire format. Both fields nullable; the struct itself is null when no frame.
 
51
  pa.field("bytes", pa.binary()),
52
  pa.field("path", pa.string()),
53
  ])
54
+ # Bedmatrix numeric struct. `values` is row-major, length width*height (32*24=768),
55
+ # temperatures in °C as float32 (firmware sends ~0.01°C resolution; f32 is ample).
56
+ # The whole struct is null when no matrix fell in the tick window.
57
+ BEDMATRIX_STRUCT_TYPE = pa.struct([
58
+ pa.field("width", pa.int32()),
59
+ pa.field("height", pa.int32()),
60
+ pa.field("values", pa.list_(pa.float32())),
61
+ pa.field("path", pa.string()),
62
+ ])
63
  # Streaming chunk size in rows. Tuned so peak embedded payload per chunk stays
64
  # under ~1 GB (thermal frames dominate at ~315 KB each).
65
  CHUNK_ROWS = 2_000
 
113
  return wide
114
 
115
 
116
+ def attach_bedmatrix(wide: pl.DataFrame, frames: pl.DataFrame) -> pl.DataFrame:
117
+ """Attach the nearest bedmatrix path within WINDOW prior to tick_ts as a
118
+ string column `bedmatrix` (parsed into a numeric struct at write time,
119
+ exactly like the frame_* path columns)."""
120
+ f = (
121
+ frames.filter(pl.col("kind") == BEDMATRIX_KIND)
122
+ .select(pl.col("ts"), pl.col("path").alias("bedmatrix"))
123
+ .sort("ts")
124
+ )
125
+ if f.height == 0:
126
+ return wide.with_columns(pl.lit(None, dtype=pl.String).alias("bedmatrix"))
127
+ return wide.sort("ts").join_asof(
128
+ f, on="ts", strategy="backward", tolerance=WINDOW
129
+ )
130
+
131
+
132
  def attach_position_hf(wide: pl.DataFrame, build_id: int) -> pl.DataFrame:
133
  """Append a `position_hf_burst` column: list of structs of position_hf events
134
  in (tick_ts - WINDOW, tick_ts]. Empty list when no events in window or no parquet."""
 
210
  )
211
 
212
 
213
+ def _embed_bedmatrix_column(paths: list[str | None]) -> pa.Array:
214
+ """For one chunk's paths, read each bedmatrix JSON from disk and return a
215
+ StructArray of {width, height, values, path}. Missing path, missing-on-disk,
216
+ or unparseable JSON → null struct (warn-free continue, same as frames)."""
217
+ widths: list[int | None] = []
218
+ heights: list[int | None] = []
219
+ values: list[list[float] | None] = []
220
+ kept: list[str | None] = []
221
+ for p in paths:
222
+ if p is None:
223
+ widths.append(None); heights.append(None); values.append(None); kept.append(None)
224
+ continue
225
+ try:
226
+ d = json.loads((FRAMES_DIR / p).read_bytes())
227
+ widths.append(d.get("width"))
228
+ heights.append(d.get("height"))
229
+ values.append([float(v) for v in d["values"]])
230
+ kept.append(p)
231
+ except (FileNotFoundError, KeyError, ValueError, TypeError):
232
+ widths.append(None); heights.append(None); values.append(None); kept.append(None)
233
+ mask = pa.array([p is None for p in kept], type=pa.bool_())
234
+ return pa.StructArray.from_arrays(
235
+ [
236
+ pa.array(widths, type=pa.int32()),
237
+ pa.array(heights, type=pa.int32()),
238
+ pa.array(values, type=pa.list_(pa.float32())),
239
+ pa.array(kept, type=pa.string()),
240
+ ],
241
+ fields=list(BEDMATRIX_STRUCT_TYPE),
242
+ mask=mask,
243
+ )
244
+
245
+
246
  def _make_output_schema(wide_arrow_schema: pa.Schema) -> pa.Schema:
247
+ """Replace frame_* string fields with HF Image structs and the bedmatrix
248
+ path string with its numeric struct."""
249
  new_fields = []
250
  image_field_names = {f"frame_{k}" for k in FRAME_KINDS}
251
  for field in wide_arrow_schema:
252
  if field.name in image_field_names:
253
  new_fields.append(pa.field(field.name, IMAGE_STRUCT_TYPE))
254
+ elif field.name == "bedmatrix":
255
+ new_fields.append(pa.field("bedmatrix", BEDMATRIX_STRUCT_TYPE))
256
  else:
257
  new_fields.append(field)
258
  return pa.schema(new_fields)
259
 
260
 
261
  def _embed_chunk(chunk: pa.Table, output_schema: pa.Schema) -> pa.Table:
262
+ """Swap frame_* and bedmatrix string columns for embedded structs in this chunk."""
263
+ image_names = {f"frame_{k}" for k in FRAME_KINDS}
264
  arrays = []
265
  for field in output_schema:
266
+ if field.name in image_names:
267
+ arrays.append(_embed_frame_column(chunk[field.name].to_pylist()))
268
+ elif field.name == "bedmatrix":
269
+ arrays.append(_embed_bedmatrix_column(chunk[field.name].to_pylist()))
270
  else:
271
  arrays.append(chunk[field.name].combine_chunks())
272
  return pa.Table.from_arrays(arrays, schema=output_schema)
 
285
  wide = pivot_telemetry(tel)
286
  frames = load_frames_for_build(build_id)
287
  wide = attach_frames(wide, frames)
288
+ wide = attach_bedmatrix(wide, frames)
289
  wide = attach_position_hf(wide, build_id)
290
  wide = denormalize_build(wide, builds_index[build_id], profile_name_lookup)
291
 
292
+ # Put build context + ts first, then sensors, then frames + bedmatrix + burst.
293
  leading = ["build_id", "ts", "job_name", "started_at", "ended_at", "phase",
294
  "print_profile_name", "inova_session_id"]
295
  frame_cols = [f"frame_{k}" for k in FRAME_KINDS]
296
+ trailing = frame_cols + ["bedmatrix", "position_hf_burst"]
297
  middle = [c for c in wide.columns if c not in leading and c not in trailing]
298
  wide = wide.select(leading + middle + trailing)
299