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
8cdbe7c
7615f9a
 
 
09206c3
 
8cdbe7c
09206c3
 
 
 
7615f9a
 
 
 
 
09206c3
 
 
 
 
 
 
 
 
8cdbe7c
09206c3
7615f9a
09206c3
 
7615f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8cdbe7c
 
 
7615f9a
 
 
 
 
8cdbe7c
7615f9a
 
 
 
 
 
8cdbe7c
7615f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#!/usr/bin/env python3
"""Render per-layer timelapse GIFs for each build.

Reads data/ticks/{build_id:03d}.parquet and writes:
  previews/{build_id:03d}/timelapse_chamber.gif
  previews/{build_id:03d}/timelapse_thermal.gif
  previews/{build_id:03d}/timelapse_galvo.gif
  previews/{build_id:03d}/timelapse_composite.gif  (1×3 panel: chamber | thermal | galvo)

Layer detection: positions.position.z2 is quantized in 100 µm buckets.
Only z2 > 0 rows are used — z2 stays at 0 during pre-print heating so this
naturally excludes the heating phase without needing to inspect the phase column.
The *last* non-null frame within each z2 bucket is the representative — that's
the most-recent view of the layer just before recoating begins.

Null-frame levels are forward-filled from the most recent non-null level of the
same kind, so the GIF never shows a blank panel mid-timelapse.

The thermal panel is rendered from the raw `bedmatrix` IR grid (inferno colormap
over a fixed absolute °C range; see _thermal.py) whenever it's present — builds
013+. The three earliest builds (001/002/012) predate the bedmatrix stream and
fall back to the legacy pre-rendered `frame_thermal` GIF.

Subsampled to at most MAX_FRAMES (default 300). At GIF_FPS=25 that gives
a max 12-second GIF. Builds with fewer detected layers are not padded.

Canvas is scaled to GIF_PANEL_HEIGHT=240 px (half the MP4 panel height) to
keep file sizes web-friendly for README embedding.

Usage:
    uv run scripts/previews/02_timelapse.py            # all builds in data/ticks/
    uv run scripts/previews/02_timelapse.py 26 28      # specific build ids
    uv run scripts/previews/02_timelapse.py 26 --kinds chamber,composite
"""
import io
import sys
from pathlib import Path

import pyarrow.parquet as pq
from PIL import Image, ImageStat

sys.path.insert(0, str(Path(__file__).parent.parent))
sys.path.insert(0, str(Path(__file__).parent))
from _lib import DATA_DIR
from _thermal import bedmatrix_to_image

OUTPUT_DIR = DATA_DIR.parent / "previews"
TICKS_DIR  = DATA_DIR / "ticks"

FRAME_KINDS        = ("chamber", "thermal", "galvo")
KIND_ROTATION_CW   = {"chamber": 90}  # degrees; see _decode_raw
# The thermal panel renders from the raw `bedmatrix` IR grid when present
# (builds 013+), falling back to the legacy `frame_thermal` GIF for the three
# earliest builds (001/002/012) that predate the bedmatrix stream.

GIF_FPS            = 25
GIF_DURATION_MS    = int(1000 / GIF_FPS)   # 40 ms per frame
MAX_FRAMES         = 300                    # subsample cap → max 12 s GIF
LAYER_QUANTIZE_UM  = 100                    # z2 bucket size in microns
GIF_PANEL_HEIGHT   = 240                    # panel height in pixels for GIF canvas
BATCH_ROWS         = 1000                   # pyarrow streaming batch size

# Halogen brightness filter — applies to chamber frames only.
# The halogens pulse on/off throughout a build; dark frames (halogens off) are
# uninformative for viewing. A frame is kept if its mean grayscale brightness is
# at least this fraction of the brightest frame seen in the same build.
# For the individual chamber GIF dark frames are dropped entirely; for the
# composite they are forward-filled from the last bright frame so thermal/galvo
# stay in layer-sync.
CHAMBER_BRIGHTNESS_RATIO = 0.5


# ---------------------------------------------------------------------------
# Image helpers (mirrors 01_render.py exactly)
# ---------------------------------------------------------------------------

def _decode_raw(b: bytes, kind: str) -> Image.Image | None:
    """Decode raw image bytes to PIL RGB with orientation correction."""
    if not b:
        return None
    try:
        img = Image.open(io.BytesIO(b)).convert("RGB")
    except Exception:
        return None
    rot = KIND_ROTATION_CW.get(kind, 0)
    if rot == 90:
        img = img.transpose(Image.Transpose.ROTATE_270)
    elif rot == 180:
        img = img.transpose(Image.Transpose.ROTATE_180)
    elif rot == 270:
        img = img.transpose(Image.Transpose.ROTATE_90)
    return img


def _decode_cell(cell, kind: str) -> Image.Image | None:
    """Decode one struct cell to a PIL RGB image, dispatching on struct shape:
    a `bedmatrix` struct (has 'values') renders as an inferno heatmap; a frame
    Image struct (has 'bytes') decodes + orientation-corrects. None when missing."""
    if cell is None:
        return None
    if "values" in cell:
        return bedmatrix_to_image(cell)
    return _decode_raw(cell.get("bytes"), kind)


def _thermal_column(parquet_path: Path) -> str:
    """Which column feeds the thermal panel for this build: 'bedmatrix' when the
    raw IR matrix has any non-null cell, else the legacy 'frame_thermal'. The
    bedmatrix stream started at build 013, so 001/002/012 fall back to the GIF."""
    pf = pq.ParquetFile(parquet_path)
    if "bedmatrix" not in {f.name for f in pf.schema_arrow}:
        return "frame_thermal"
    for batch in pf.iter_batches(columns=["bedmatrix"], batch_size=BATCH_ROWS):
        for cell in batch.column("bedmatrix").to_pylist():
            if cell is not None:
                return "bedmatrix"
    return "frame_thermal"


def _columns_for_build(parquet_path: Path) -> dict[str, str]:
    """Map each panel kind → the parquet column that feeds it for this build."""
    return {
        "chamber": "frame_chamber",
        "thermal": _thermal_column(parquet_path),
        "galvo":   "frame_galvo",
    }


def _canvas_width(cell, kind: str) -> int:
    """Decode one cell to determine the locked canvas width for this kind."""
    img = _decode_cell(cell, kind)
    if img is None:
        return GIF_PANEL_HEIGHT  # square fallback
    sw, sh = img.size
    return max(2, round(sw * GIF_PANEL_HEIGHT / sh))


def _fit_to_canvas(img: Image.Image, canvas_w: int) -> Image.Image:
    """Letterbox img into (canvas_w × GIF_PANEL_HEIGHT) with dark-gray fill."""
    sw, sh = img.size
    scale  = min(canvas_w / sw, GIF_PANEL_HEIGHT / sh)
    nw     = max(1, round(sw * scale))
    nh     = max(1, round(sh * scale))
    fitted = img.resize((nw, nh), Image.BILINEAR)
    canvas = Image.new("RGB", (canvas_w, GIF_PANEL_HEIGHT), (20, 20, 20))
    canvas.paste(fitted, ((canvas_w - nw) // 2, (GIF_PANEL_HEIGHT - nh) // 2))
    return canvas


def _placeholder(canvas_w: int) -> Image.Image:
    return Image.new("RGB", (canvas_w, GIF_PANEL_HEIGHT), (20, 20, 20))


def _mean_brightness(img: Image.Image) -> float:
    """Mean grayscale pixel value 0–255 (uses PIL ImageStat, no numpy)."""
    return ImageStat.Stat(img.convert("L")).mean[0]


def _chamber_threshold(decoded_frames: list[Image.Image | None]) -> float:
    """Return the brightness threshold for a build's chamber frames.
    25 % of the brightest frame seen; 0 if no frames (no filtering applied)."""
    brightnesses = [_mean_brightness(f) for f in decoded_frames if f is not None]
    return max(brightnesses) * CHAMBER_BRIGHTNESS_RATIO if brightnesses else 0.0


# ---------------------------------------------------------------------------
# Layer data collection
# ---------------------------------------------------------------------------

def collect_layer_cells(parquet_path: Path, kind: str, col: str) -> dict[int, dict]:
    """Single-pass stream → {z2_level: last_non_null_struct}.

    Only z2 > 0 rows are included. The dict is keyed by int(z2 / LAYER_QUANTIZE_UM);
    each entry holds the *last* non-null struct cell seen at that level (a frame
    Image struct, or a bedmatrix struct for the thermal panel). Reads only two
    parquet columns (z2 + the source column) for efficiency.
    """
    z2_col  = "positions.position.z2"
    pf      = pq.ParquetFile(parquet_path)
    present = {f.name for f in pf.schema_arrow}
    if col not in present or z2_col not in present:
        return {}

    layer_data: dict[int, dict] = {}
    for batch in pf.iter_batches(columns=[z2_col, col], batch_size=BATCH_ROWS):
        z2_list   = batch.column(z2_col).to_pylist()
        cell_list = batch.column(col).to_pylist()
        for z2, cell in zip(z2_list, cell_list):
            if z2 is None or z2 <= 0:
                continue
            if cell is not None:
                layer_data[int(z2 / LAYER_QUANTIZE_UM)] = cell
    return layer_data


def collect_all_kinds(parquet_path: Path, cols_map: dict[str, str]) -> dict[str, dict[int, dict]]:
    """Single streaming pass collecting all three kinds simultaneously.

    Used by render_timelapse_composite so we don't make three separate passes
    through (potentially 17+ GB) parquet files. Reads four columns: z2 + each
    kind's source column. Each kind gets its own {z2_level: struct} dict.
    """
    z2_col    = "positions.position.z2"
    pf        = pq.ParquetFile(parquet_path)
    present   = {f.name for f in pf.schema_arrow}
    read_cols = [c for c in ([z2_col] + [cols_map[k] for k in FRAME_KINDS]) if c in present]
    if z2_col not in read_cols:
        return {k: {} for k in FRAME_KINDS}

    layer_data: dict[str, dict[int, dict]] = {k: {} for k in FRAME_KINDS}
    for batch in pf.iter_batches(columns=read_cols, batch_size=BATCH_ROWS):
        z2_list = batch.column(z2_col).to_pylist()
        for kind in FRAME_KINDS:
            col = cols_map[kind]
            if col not in read_cols:
                continue
            cell_list = batch.column(col).to_pylist()
            for z2, cell in zip(z2_list, cell_list):
                if z2 is None or z2 <= 0:
                    continue
                if cell is not None:
                    layer_data[kind][int(z2 / LAYER_QUANTIZE_UM)] = cell
    return layer_data


# ---------------------------------------------------------------------------
# Subsampling and forward-fill
# ---------------------------------------------------------------------------

def _subsample(levels: list[int]) -> list[int]:
    """Evenly subsample sorted levels down to at most MAX_FRAMES."""
    if len(levels) <= MAX_FRAMES:
        return levels
    step = len(levels) / MAX_FRAMES
    return [levels[round(i * step)] for i in range(MAX_FRAMES)]


def _forward_fill(layer_bytes: dict[int, bytes],
                  target_levels: list[int]) -> list[bytes | None]:
    """For each target level, return the bytes at that level or the most
    recent non-null bytes seen so far (forward-fill across gaps)."""
    out: list[bytes | None] = []
    last: bytes | None = None
    for lvl in target_levels:
        b = layer_bytes.get(lvl)
        if b is not None:
            last = b
        out.append(last)
    return out


# ---------------------------------------------------------------------------
# GIF writer
# ---------------------------------------------------------------------------

def _write_gif(frames: list[Image.Image], out_path: Path) -> None:
    """Palette-quantize and save frames as an animated GIF."""
    out_path.parent.mkdir(parents=True, exist_ok=True)
    palette_frames = [
        f.quantize(colors=256, method=Image.Quantize.MEDIANCUT,
                   dither=Image.Dither.FLOYDSTEINBERG)
        for f in frames
    ]
    palette_frames[0].save(
        out_path,
        format="GIF",
        save_all=True,
        append_images=palette_frames[1:],
        loop=0,
        duration=GIF_DURATION_MS,
        optimize=False,
    )


# ---------------------------------------------------------------------------
# Per-build renderers
# ---------------------------------------------------------------------------

def render_timelapse_kind(parquet_path: Path, kind: str, out_path: Path, col: str) -> int:
    """Write timelapse_{kind}.gif. Returns number of GIF frames written.

    Chamber only: dark frames (halogens off) are dropped entirely so the GIF
    shows only moments where the part is visible. Thermal and galvo are
    unaffected — they don't depend on halogen lighting.
    """
    layer_cells = collect_layer_cells(parquet_path, kind, col)
    if not layer_cells:
        print(f"  {kind:8s}: no printing-phase frames (z2 > 0), skipping")
        return 0

    sorted_levels = sorted(layer_cells)
    target_levels = _subsample(sorted_levels)
    fill_cells    = _forward_fill(layer_cells, target_levels)
    canvas_w      = _canvas_width(next(c for c in fill_cells if c), kind)

    # Decode all selected frames up front (needed for brightness scan on chamber).
    decoded = [_decode_cell(c, kind) for c in fill_cells]

    if kind == "chamber":
        # Compute brightness once per decoded frame, then threshold and filter.
        brightnesses = [_mean_brightness(img) if img is not None else None
                        for img in decoded]
        threshold = _chamber_threshold(decoded)
        pil_frames = [
            _fit_to_canvas(img, canvas_w)
            for img, b in zip(decoded, brightnesses)
            if img is not None and b is not None and b >= threshold
        ]
        dark_dropped = sum(
            1 for img, b in zip(decoded, brightnesses)
            if img is not None and b is not None and b < threshold
        )
        if dark_dropped:
            print(f"  {kind:8s}: dropped {dark_dropped} dark frames "
                  f"(threshold {threshold:.1f}/255)")
    else:
        pil_frames = [
            _fit_to_canvas(img, canvas_w) if img else _placeholder(canvas_w)
            for img in decoded
        ]

    if not pil_frames:
        print(f"  {kind:8s}: no frames survived brightness filter, skipping")
        return 0

    _write_gif(pil_frames, out_path)
    return len(pil_frames)


def render_timelapse_composite(parquet_path: Path, out_path: Path,
                               cols_map: dict[str, str]) -> int:
    """Write timelapse_composite.gif (1×3 panel). Single parquet pass.

    Thermal and galvo show the actual frame for every layer (unaffected by
    halogens). The chamber panel forward-fills from the last *bright* frame
    when the current layer's chamber frame is dark — this keeps all three
    panels in layer-sync while never displaying a dark chamber view.
    """
    all_cells = collect_all_kinds(parquet_path, cols_map)

    all_levels = sorted(set().union(*(set(d) for d in all_cells.values())))
    if not all_levels:
        print("  composite: no printing-phase frames (z2 > 0), skipping")
        return 0

    target_levels = _subsample(all_levels)
    fill_per_kind = {k: _forward_fill(all_cells[k], target_levels) for k in FRAME_KINDS}

    canvas_widths: dict[str, int] = {}
    for kind in FRAME_KINDS:
        first_c = next((c for c in fill_per_kind[kind] if c), None)
        canvas_widths[kind] = (
            _canvas_width(first_c, kind) if first_c else GIF_PANEL_HEIGHT
        )
    total_w = sum(canvas_widths.values())

    # Pre-decode chamber frames once; compute adaptive brightness threshold.
    chamber_decoded = [
        _decode_cell(c, "chamber") for c in fill_per_kind["chamber"]
    ]
    chamber_threshold = _chamber_threshold(chamber_decoded)

    last_bright_chamber: Image.Image | None = None
    pil_frames: list[Image.Image] = []
    for i in range(len(target_levels)):
        composite = Image.new("RGB", (total_w, GIF_PANEL_HEIGHT), (20, 20, 20))
        x = 0
        for kind in FRAME_KINDS:
            if kind == "chamber":
                img = chamber_decoded[i]
                # Update the running bright-chamber reference when this frame is bright.
                if img is not None and _mean_brightness(img) >= chamber_threshold:
                    last_bright_chamber = img
                # Always use the last bright frame (forward-fill); placeholder until
                # the first bright frame arrives.
                panel_img = last_bright_chamber
            else:
                panel_img = _decode_cell(fill_per_kind[kind][i], kind)

            panel = (
                _fit_to_canvas(panel_img, canvas_widths[kind])
                if panel_img else _placeholder(canvas_widths[kind])
            )
            composite.paste(panel, (x, 0))
            x += canvas_widths[kind]
        pil_frames.append(composite)

    _write_gif(pil_frames, out_path)
    return len(pil_frames)


def process_build(build_id: int, kinds: set[str]) -> None:
    parquet_path = TICKS_DIR / f"{build_id:03d}.parquet"
    if not parquet_path.exists():
        print(f"build {build_id:03d}: no parquet, skipping")
        return

    build_dir = OUTPUT_DIR / f"{build_id:03d}"
    print(f"build {build_id:03d}: timelapse GIFs → {build_dir.relative_to(Path.cwd())}/")
    cols_map = _columns_for_build(parquet_path)
    if ("thermal" in kinds or "composite" in kinds):
        print(f"  thermal source: {cols_map['thermal']}")

    for kind in FRAME_KINDS:
        if kind not in kinds:
            continue
        out = build_dir / f"timelapse_{kind}.gif"
        n = render_timelapse_kind(parquet_path, kind, out, cols_map[kind])
        if out.exists():
            size = out.stat().st_size
            print(f"  {kind:8s}: {n:>4} frames → {out.name}  ({size:,} bytes)")

    if "composite" in kinds:
        out = build_dir / "timelapse_composite.gif"
        n = render_timelapse_composite(parquet_path, out, cols_map)
        if out.exists():
            size = out.stat().st_size
            print(f"  composite: {n:>4} frames → {out.name}  ({size:,} bytes)")


def main():
    import argparse
    parser = argparse.ArgumentParser(
        description=__doc__,
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    parser.add_argument("build_ids", nargs="*", type=int,
                        help="Build IDs to render (default: all in data/ticks/)")
    parser.add_argument(
        "--kinds", default="chamber,thermal,galvo,composite",
        help="Comma-separated outputs to render. "
             "Valid: chamber, thermal, galvo, composite. Default: all four.",
    )
    args   = parser.parse_args()
    kinds  = set(args.kinds.split(","))
    unknown = kinds - (set(FRAME_KINDS) | {"composite"})
    if unknown:
        parser.error(f"unknown --kinds values: {sorted(unknown)}")

    targets = args.build_ids or sorted(int(p.stem) for p in TICKS_DIR.glob("*.parquet"))
    for bid in targets:
        process_build(bid, kinds)


if __name__ == "__main__":
    main()