#!/usr/bin/env python3 """Build the `ticks` config: one row per 10 Hz telemetry tick per build. Reads upstream flat exports from the sibling 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 - 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 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, 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") # frame_* path strings are relative to this directory in the upstream recorder repo. FRAMES_DIR = EXPORTS_DIR.parent / "frames" # 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()), ]) # 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_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 = EXPORTS_DIR / "position_hf" / f"{build_id}.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 _make_output_schema(wide_arrow_schema: pa.Schema) -> pa.Schema: """Replace frame_* string fields with HF Image struct fields.""" 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)) else: new_fields.append(field) return pa.schema(new_fields) def _embed_chunk(chunk: pa.Table, output_schema: pa.Schema) -> pa.Table: """Swap frame_* string columns for embedded image structs in this chunk.""" arrays = [] for field in output_schema: if field.name in {f"frame_{k}" for k in FRAME_KINDS}: paths = chunk[field.name].to_pylist() arrays.append(_embed_frame_column(paths)) 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 = EXPORTS_DIR / "telemetry" / f"{build_id}.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_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 + 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 + ["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 (EXPORTS_DIR / "telemetry").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()