File size: 14,218 Bytes
884dabc
 
 
8cdbe7c
884dabc
 
71df3b8
 
884dabc
 
71df3b8
884dabc
 
8cdbe7c
 
 
 
 
 
884dabc
 
 
 
 
 
 
8cdbe7c
884dabc
 
 
 
 
71df3b8
 
884dabc
 
219b90b
 
884dabc
 
 
 
 
8cdbe7c
 
 
 
71df3b8
219b90b
71df3b8
 
 
 
 
8cdbe7c
 
 
 
 
 
 
 
 
71df3b8
 
 
884dabc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cdbe7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
884dabc
 
 
219b90b
884dabc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71df3b8
884dabc
 
 
 
 
 
 
 
 
71df3b8
884dabc
 
 
 
71df3b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cdbe7c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71df3b8
8cdbe7c
 
71df3b8
 
 
 
 
8cdbe7c
 
71df3b8
 
 
 
 
 
8cdbe7c
 
71df3b8
 
8cdbe7c
 
 
 
71df3b8
 
 
 
 
884dabc
71df3b8
219b90b
884dabc
 
 
 
 
 
 
 
 
 
8cdbe7c
884dabc
71df3b8
884dabc
8cdbe7c
884dabc
71df3b8
884dabc
8cdbe7c
884dabc
 
 
71df3b8
 
 
 
 
 
 
 
 
884dabc
 
 
 
 
 
71df3b8
884dabc
 
219b90b
884dabc
 
 
 
 
71df3b8
884dabc
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
#!/usr/bin/env python3
"""Build the `ticks` config: one row per 10 Hz telemetry tick per build.

Reads upstream flat exports from the containing recorder repo:
  builds.jsonl, telemetry/{build_id}.parquet, frames.jsonl, position_hf/{build_id}.parquet

For each build with telemetry, emits `data/ticks/{build_id:03d}.parquet`
(zero-padded so lexical sort matches numeric build_id):
  - One row per unique telemetry timestamp (the 10 Hz tick from /state/snapshot)
  - Wide-format sensor columns named "{sensor_id}.{kind}" (~64 columns)
  - Denormalized build context (build_id, job_name, ..., print_profile_name)
  - frame_chamber / frame_galvo / frame_thermal: nearest frame path in
    [tick_ts - 100ms, tick_ts], null when no frame fell in that window
    (frame_thermal is the legacy bedmatrix GIF heatmap; recorder stopped
    producing it after 2026-07-12, so it is null for builds captured since)
  - bedmatrix: nearest IR temperature matrix in the same 100ms window, as a
    struct {width, height, values (row-major °C), path}; null when none.
    This is the raw 32x24 bed-surface temperature grid the recorder now streams
    as JSON in place of the old rendered frame_thermal heatmap.
  - position_hf_burst: list of {ts_offset_ms, x, y, z1, z2, r, has_homed}
    for all position_hf events in the same 100ms window

Usage:
    uv run scripts/ticks/01_extract.py            # all builds with telemetry
    uv run scripts/ticks/01_extract.py 13 26      # specific build ids
"""
import json
import sys
from datetime import timedelta
from pathlib import Path

import polars as pl
import pyarrow as pa
import pyarrow.parquet as pq

sys.path.insert(0, str(Path(__file__).parent.parent))
from _lib import (EXPORTS_DIR, DATA_DIR, TELEMETRY_DIR, POSITION_DIR,
                  FRAMES_BUFFER, iter_jsonl, load_build_to_profile_name)


OUTPUT_DIR = DATA_DIR / "ticks"
WINDOW = timedelta(milliseconds=100)  # 10 Hz tick interval
FRAME_KINDS = ("chamber", "galvo", "thermal")
# The IR temperature matrix. Same underlying sensor the legacy frame_thermal GIF
# was rendered from, but streamed as a raw {width, height, values} JSON grid.
# Attached like a frame (nearest-before-tick), embedded as a numeric struct.
BEDMATRIX_KIND = "bedmatrix"
# frame_* path strings are relative to this directory in the upstream recorder repo.
FRAMES_DIR = FRAMES_BUFFER  # loose frames for builds not yet zip-delivered
# HF Image feature wire format. Both fields nullable; the struct itself is null when no frame.
IMAGE_STRUCT_TYPE = pa.struct([
    pa.field("bytes", pa.binary()),
    pa.field("path",  pa.string()),
])
# Bedmatrix numeric struct. `values` is row-major, length width*height (32*24=768),
# temperatures in °C as float32 (firmware sends ~0.01°C resolution; f32 is ample).
# The whole struct is null when no matrix fell in the tick window.
BEDMATRIX_STRUCT_TYPE = pa.struct([
    pa.field("width",  pa.int32()),
    pa.field("height", pa.int32()),
    pa.field("values", pa.list_(pa.float32())),
    pa.field("path",   pa.string()),
])
# Streaming chunk size in rows. Tuned so peak embedded payload per chunk stays
# under ~1 GB (thermal frames dominate at ~315 KB each).
CHUNK_ROWS = 2_000


def load_builds_index() -> dict[int, dict]:
    rows = list(iter_jsonl(EXPORTS_DIR / "builds.jsonl"))
    return {r["id"]: r for r in rows}


def load_frames_for_build(build_id: int) -> pl.DataFrame:
    """Read just the frame rows for one build out of the upstream frames.jsonl."""
    rows = [r for r in iter_jsonl(EXPORTS_DIR / "frames.jsonl")
            if r.get("build_id") == build_id]
    if not rows:
        return pl.DataFrame(schema={"ts": pl.Datetime("us", "UTC"),
                                    "kind": pl.String, "path": pl.String})
    df = pl.DataFrame(rows).select(
        pl.col("ts").str.to_datetime(time_unit="us", time_zone="UTC"),
        pl.col("kind"),
        pl.col("path"),
    )
    return df


def pivot_telemetry(tel: pl.DataFrame) -> pl.DataFrame:
    """Wide-pivot (ts, sensor_id, kind, value) → one row per ts with
    {sensor_id}.{kind} columns. Duplicate samples within a tick collapse via first."""
    tel = tel.with_columns(
        col_name=pl.col("sensor_id") + "." + pl.col("kind")
    )
    return tel.pivot(
        on="col_name", index="ts", values="value", aggregate_function="first"
    ).sort("ts")


def attach_frames(wide: pl.DataFrame, frames: pl.DataFrame) -> pl.DataFrame:
    """For each frame kind, attach the nearest path within WINDOW prior to tick_ts."""
    for kind in FRAME_KINDS:
        f = (
            frames.filter(pl.col("kind") == kind)
            .select(pl.col("ts"), pl.col("path").alias(f"frame_{kind}"))
            .sort("ts")
        )
        if f.height == 0:
            wide = wide.with_columns(pl.lit(None, dtype=pl.String).alias(f"frame_{kind}"))
            continue
        wide = wide.sort("ts").join_asof(
            f, on="ts", strategy="backward", tolerance=WINDOW
        )
    return wide


def attach_bedmatrix(wide: pl.DataFrame, frames: pl.DataFrame) -> pl.DataFrame:
    """Attach the nearest bedmatrix path within WINDOW prior to tick_ts as a
    string column `bedmatrix` (parsed into a numeric struct at write time,
    exactly like the frame_* path columns)."""
    f = (
        frames.filter(pl.col("kind") == BEDMATRIX_KIND)
        .select(pl.col("ts"), pl.col("path").alias("bedmatrix"))
        .sort("ts")
    )
    if f.height == 0:
        return wide.with_columns(pl.lit(None, dtype=pl.String).alias("bedmatrix"))
    return wide.sort("ts").join_asof(
        f, on="ts", strategy="backward", tolerance=WINDOW
    )


def attach_position_hf(wide: pl.DataFrame, build_id: int) -> pl.DataFrame:
    """Append a `position_hf_burst` column: list of structs of position_hf events
    in (tick_ts - WINDOW, tick_ts]. Empty list when no events in window or no parquet."""
    pos_path = POSITION_DIR / f"{build_id:03d}.parquet"
    burst_dtype = pl.List(
        pl.Struct({
            "ts_offset_ms": pl.Float64,
            "x":  pl.Float64, "y":  pl.Float64,
            "z1": pl.Float64, "z2": pl.Float64,
            "r":  pl.Float64, "has_homed": pl.Boolean,
        })
    )
    if not pos_path.exists():
        return wide.with_columns(pl.lit([], dtype=burst_dtype).alias("position_hf_burst"))

    pos = pl.read_parquet(pos_path).sort("ts")
    pos_records = pos.to_dicts()
    ticks = wide["ts"].to_list()

    bursts: list[list[dict]] = []
    pos_lo = 0
    for tick_ts in ticks:
        t_start = tick_ts - WINDOW
        while pos_lo < len(pos_records) and pos_records[pos_lo]["ts"] <= t_start:
            pos_lo += 1
        j = pos_lo
        burst: list[dict] = []
        while j < len(pos_records) and pos_records[j]["ts"] <= tick_ts:
            rec = pos_records[j]
            burst.append({
                "ts_offset_ms": (rec["ts"] - tick_ts).total_seconds() * 1000.0,
                "x":  rec.get("x"),  "y":  rec.get("y"),
                "z1": rec.get("z1"), "z2": rec.get("z2"),
                "r":  rec.get("r"),  "has_homed": rec.get("has_homed"),
            })
            j += 1
        bursts.append(burst)

    return wide.with_columns(pl.Series("position_hf_burst", bursts, dtype=burst_dtype))


def denormalize_build(wide: pl.DataFrame, build_row: dict,
                      profile_name_lookup: dict[int, str]) -> pl.DataFrame:
    """Prepend build-context columns to every row. Cheap in parquet thanks to
    dictionary encoding (every row in this file has the same value)."""
    bid = build_row["id"]
    return wide.with_columns(
        pl.lit(bid).alias("build_id"),
        pl.lit(build_row.get("job_name")).alias("job_name"),
        pl.lit(build_row.get("started_at")).alias("started_at"),
        pl.lit(build_row.get("ended_at")).alias("ended_at"),
        pl.lit(build_row.get("phase")).alias("phase"),
        pl.lit(profile_name_lookup.get(bid)).alias("print_profile_name"),
        pl.lit(None, dtype=pl.String).alias("inova_session_id"),
    )


def _embed_frame_column(paths: list[str | None]) -> pa.Array:
    """For one chunk's worth of paths, read the image bytes from disk and
    return a StructArray with HF Image shape. Missing path → null struct;
    missing-on-disk → null struct (warn-and-continue)."""
    raw_bytes: list[bytes | None] = []
    for p in paths:
        if p is None:
            raw_bytes.append(None)
            continue
        try:
            raw_bytes.append((FRAMES_DIR / p).read_bytes())
        except FileNotFoundError:
            raw_bytes.append(None)
    bytes_array = pa.array(raw_bytes, type=pa.binary())
    path_array  = pa.array(paths,     type=pa.string())
    # Mask the whole struct as null when there is no path. Children stay null too.
    mask = pa.array([p is None for p in paths], type=pa.bool_())
    return pa.StructArray.from_arrays(
        [bytes_array, path_array],
        fields=[pa.field("bytes", pa.binary()), pa.field("path", pa.string())],
        mask=mask,
    )


def _embed_bedmatrix_column(paths: list[str | None]) -> pa.Array:
    """For one chunk's paths, read each bedmatrix JSON from disk and return a
    StructArray of {width, height, values, path}. Missing path, missing-on-disk,
    or unparseable JSON → null struct (warn-free continue, same as frames)."""
    widths:  list[int | None]         = []
    heights: list[int | None]         = []
    values:  list[list[float] | None] = []
    kept:    list[str | None]         = []
    for p in paths:
        if p is None:
            widths.append(None); heights.append(None); values.append(None); kept.append(None)
            continue
        try:
            d = json.loads((FRAMES_DIR / p).read_bytes())
            widths.append(d.get("width"))
            heights.append(d.get("height"))
            values.append([float(v) for v in d["values"]])
            kept.append(p)
        except (FileNotFoundError, KeyError, ValueError, TypeError):
            widths.append(None); heights.append(None); values.append(None); kept.append(None)
    mask = pa.array([p is None for p in kept], type=pa.bool_())
    return pa.StructArray.from_arrays(
        [
            pa.array(widths,  type=pa.int32()),
            pa.array(heights, type=pa.int32()),
            pa.array(values,  type=pa.list_(pa.float32())),
            pa.array(kept,    type=pa.string()),
        ],
        fields=list(BEDMATRIX_STRUCT_TYPE),
        mask=mask,
    )


def _make_output_schema(wide_arrow_schema: pa.Schema) -> pa.Schema:
    """Replace frame_* string fields with HF Image structs and the bedmatrix
    path string with its numeric struct."""
    new_fields = []
    image_field_names = {f"frame_{k}" for k in FRAME_KINDS}
    for field in wide_arrow_schema:
        if field.name in image_field_names:
            new_fields.append(pa.field(field.name, IMAGE_STRUCT_TYPE))
        elif field.name == "bedmatrix":
            new_fields.append(pa.field("bedmatrix", BEDMATRIX_STRUCT_TYPE))
        else:
            new_fields.append(field)
    return pa.schema(new_fields)


def _embed_chunk(chunk: pa.Table, output_schema: pa.Schema) -> pa.Table:
    """Swap frame_* and bedmatrix string columns for embedded structs in this chunk."""
    image_names = {f"frame_{k}" for k in FRAME_KINDS}
    arrays = []
    for field in output_schema:
        if field.name in image_names:
            arrays.append(_embed_frame_column(chunk[field.name].to_pylist()))
        elif field.name == "bedmatrix":
            arrays.append(_embed_bedmatrix_column(chunk[field.name].to_pylist()))
        else:
            arrays.append(chunk[field.name].combine_chunks())
    return pa.Table.from_arrays(arrays, schema=output_schema)


def process_build(build_id: int, builds_index: dict[int, dict],
                  profile_name_lookup: dict[int, str]) -> Path | None:
    tel_path = TELEMETRY_DIR / f"{build_id:03d}.parquet"
    if not tel_path.exists():
        return None

    tel = pl.read_parquet(tel_path)
    if tel.is_empty():
        return None

    wide = pivot_telemetry(tel)
    frames = load_frames_for_build(build_id)
    wide = attach_frames(wide, frames)
    wide = attach_bedmatrix(wide, frames)
    wide = attach_position_hf(wide, build_id)
    wide = denormalize_build(wide, builds_index[build_id], profile_name_lookup)

    # Put build context + ts first, then sensors, then frames + bedmatrix + burst.
    leading = ["build_id", "ts", "job_name", "started_at", "ended_at", "phase",
               "print_profile_name", "inova_session_id"]
    frame_cols = [f"frame_{k}" for k in FRAME_KINDS]
    trailing = frame_cols + ["bedmatrix", "position_hf_burst"]
    middle = [c for c in wide.columns if c not in leading and c not in trailing]
    wide = wide.select(leading + middle + trailing)

    # Stream-write: build target schema (with image structs), then iterate
    # CHUNK_ROWS-sized slices, embedding bytes per chunk to bound memory.
    base_table = wide.to_arrow()
    output_schema = _make_output_schema(base_table.schema)
    out_path = OUTPUT_DIR / f"{build_id:03d}.parquet"
    with pq.ParquetWriter(out_path, output_schema, compression="zstd") as writer:
        for i in range(0, base_table.num_rows, CHUNK_ROWS):
            chunk = base_table.slice(i, CHUNK_ROWS)
            writer.write_table(_embed_chunk(chunk, output_schema))
    return out_path


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    builds_index = load_builds_index()
    profile_name_lookup = load_build_to_profile_name()

    args = [int(a) for a in sys.argv[1:]]
    targets = args or sorted(int(p.stem) for p in TELEMETRY_DIR.glob("*.parquet"))

    for bid in targets:
        if bid not in builds_index:
            print(f"build {bid}: not in builds.jsonl, skipping")
            continue
        out = process_build(bid, builds_index, profile_name_lookup)
        if out is None:
            print(f"build {bid}: no telemetry parquet, skipping")
            continue
        rows = pl.scan_parquet(out).select(pl.len()).collect().item()
        size = out.stat().st_size
        print(f"build {bid}: wrote {rows:,} ticks → {out.relative_to(Path.cwd())}  ({size:,} bytes)")


if __name__ == "__main__":
    main()