File size: 11,039 Bytes
ae16a1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Build the `peregrine` config: one row per LABELED layer per build, shaped
like the ORNL Peregrine dataset (ppak10/Peregrine-Dataset-v2023-11).

Only layers that carry at least one *active* defect label are emitted — this is
the sparse, defect-focused counterpart to the dense `ticks` config, meant for
Peregrine-style transfer learning. Frames are recorded ONLY for labeled layers.

Per-build output `data/peregrine/{build_id:03d}.parquet` (zero-padded) so a new
build only writes its own file — existing builds are never rewritten.

Reads from this dataset's own source/ tree + built frame index:
  source/labels/{build}.parquet        curated active labels (sls-export-labels)
  data/frames_index/{build}.parquet    ts_ms -> (archive zip, member) per frame
  source/telemetry/{build}.parquet     z2 (recoat boundary) + process scalars
  source/recorder/builds.jsonl         build_name

Schema (Peregrine-aligned; images are raw JPEG bytes as `binary`, exactly like
Peregrine's image_after_* columns — decode with PIL.Image.open(io.BytesIO(x))):
  build, build_name, layer, ts
  image_after_powder   post-recoat chamber still (Peregrine after_powder)
  image_after_melt     post-scan   chamber still (Peregrine after_melt)
  part_mask            galvo scan mask           (Peregrine part_ids analog)
  labels               list<{class, bbox[x0,y0,x1,y1] normalized, polarity}>
  has_<class>          bool per PEREGRINE_ALL_CLASSES (12)
  <sensor>_temp / laser_power_w   process scalars nearest-before the layer ts

Frame selection per labeled layer (anchor = earliest label ts on the layer):
  after_melt   = chamber frame nearest the anchor ts (the detection frame)
  after_powder = first chamber frame after the recoat that precedes the anchor
                 (z2 returns to 0 = recoat complete); null if none resolved
  part_mask    = galvo frame nearest the anchor ts

Usage:
    uv run scripts/peregrine/01_extract.py            # all builds with labels
    uv run scripts/peregrine/01_extract.py 48         # specific build ids
"""
import io
import sys
import zipfile
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 DATA_DIR, SOURCE_DIR, TELEMETRY_DIR, EXPORTS_DIR, iter_jsonl

LABELS_DIR = SOURCE_DIR / "labels"
FRAMES_INDEX_DIR = DATA_DIR / "frames_index"
OUTPUT_DIR = DATA_DIR / "peregrine"

# Bit-position order shared with the defect model (runs/*/constants.py).
PEREGRINE_ALL_CLASSES = [
    "powder", "printed", "recoater_hopping", "recoater_streaking",
    "incomplete_spreading", "swelling", "debris", "super_elevation",
    "spatter", "misprint", "over_melting", "under_melting",
]

# Process scalars: (output column, telemetry kind, sensor_id | None for single-sensor).
SCALAR_SPECS = [
    ("printBed_temp",    "temp.current",  "printBed"),
    ("printChamber_temp", "temp.current", "printChamber1"),
    ("powderBed_temp",   "temp.current",  "powderBed"),
    ("surface_temp",     "temp.current",  "surface"),
    ("laser_power_w",    "power.current", None),
]

LABEL_STRUCT = pa.struct([
    pa.field("class", pa.string()),
    pa.field("bbox", pa.list_(pa.float64())),
    pa.field("polarity", pa.string()),
])

OUTPUT_SCHEMA = pa.schema(
    [
        pa.field("build", pa.int64()),
        pa.field("build_name", pa.string()),
        pa.field("layer", pa.int32()),
        pa.field("ts", pa.timestamp("us", tz="UTC")),
        pa.field("image_after_powder", pa.binary()),
        pa.field("image_after_melt", pa.binary()),
        pa.field("part_mask", pa.binary()),
        pa.field("labels", pa.list_(LABEL_STRUCT)),
    ]
    + [pa.field(f"has_{c}", pa.bool_()) for c in PEREGRINE_ALL_CLASSES]
    + [pa.field(name, pa.float64()) for name, _, _ in SCALAR_SPECS]
)


def _build_name(build_id: int) -> str | None:
    for r in iter_jsonl(EXPORTS_DIR / "builds.jsonl"):
        if r.get("id") == build_id:
            return r.get("job_name")
    return None


class FrameStore:
    """Resolve chamber/galvo JPEG bytes by nearest / first-after timestamp.

    Reads the built frame index (ts_ms -> archive zip + member) and lazily opens
    the store-mode zip chunks, caching handles (a labeled build touches only a
    handful of chunks).
    """

    def __init__(self, build_id: int):
        fi = pl.read_parquet(FRAMES_INDEX_DIR / f"{build_id:03d}.parquet")
        self._by_kind = {}
        for kind in ("chamber", "galvo"):
            k = fi.filter(pl.col("kind") == kind).sort("ts_ms")
            self._by_kind[kind] = {
                "ts": k["ts_ms"].to_numpy(),
                "archive": k["archive"].to_list(),
                "member": k["member"].to_list(),
            }
        self._zips: dict[str, zipfile.ZipFile] = {}

    def _read(self, kind: str, idx: int) -> bytes:
        k = self._by_kind[kind]
        archive = k["archive"][idx]
        zf = self._zips.get(archive)
        if zf is None:
            zf = self._zips[archive] = zipfile.ZipFile(archive)
        return zf.read(k["member"][idx])

    def nearest(self, kind: str, ts_ms: int) -> bytes | None:
        ts = self._by_kind[kind]["ts"]
        if len(ts) == 0:
            return None
        import numpy as np
        i = int(np.searchsorted(ts, ts_ms))
        cands = [j for j in (i - 1, i) if 0 <= j < len(ts)]
        best = min(cands, key=lambda j: abs(int(ts[j]) - ts_ms))
        return self._read(kind, best)

    def first_in(self, kind: str, lo_ms: int, hi_ms: int) -> bytes | None:
        """First frame with lo <= ts <= hi (chronological), else None."""
        ts = self._by_kind[kind]["ts"]
        if len(ts) == 0:
            return None
        import numpy as np
        i = int(np.searchsorted(ts, lo_ms, side="left"))
        if i < len(ts) and int(ts[i]) <= hi_ms:
            return self._read(kind, i)
        return None

    def close(self):
        for zf in self._zips.values():
            zf.close()


# z2 is the build piston: it steps once per deposited layer (Peregrine
# "z2 advances once per deposited layer") and ramps monotonically to ~29 mm over
# the build — it does NOT cycle back to 0 per recoat. A layer/recoat boundary is
# therefore a STEP in z2; the ts the step settles ~= the post-recoat moment.
Z2_STEP_MIN = 1.0  # ignore sub-unit sensor jitter


def _recoat_boundaries_ms(tel: pl.DataFrame):
    """ts_ms at each z2 step (recoat/layer boundary). Sorted ascending."""
    z2 = (
        tel.filter(pl.col("kind") == "position.z2")
        .select("ts", "value")
        .sort("ts")
        .with_columns(ts_ms=pl.col("ts").dt.epoch(time_unit="ms"))
    )
    if z2.is_empty():
        return []
    z2 = z2.with_columns(step=(pl.col("value") - pl.col("value").shift(1)).abs())
    steps = z2.filter(pl.col("step") >= Z2_STEP_MIN)
    return steps["ts_ms"].to_list()


def _scalar_series(tel: pl.DataFrame):
    """{output_col: (ts_ms ndarray, value ndarray)} for nearest-before lookup."""
    import numpy as np
    out = {}
    for name, kind, sensor in SCALAR_SPECS:
        sel = tel.filter(pl.col("kind") == kind)
        if sensor is not None:
            sel = sel.filter(pl.col("sensor_id") == sensor)
        sel = sel.select("ts", "value").sort("ts")
        out[name] = (
            sel["ts"].dt.epoch(time_unit="ms").to_numpy(),
            sel["value"].to_numpy(),
        ) if not sel.is_empty() else (np.array([]), np.array([]))
    return out


def _scalar_at(series, ts_ms: int) -> float | None:
    import numpy as np
    ts, val = series
    if len(ts) == 0:
        return None
    i = int(np.searchsorted(ts, ts_ms, side="right")) - 1  # nearest-before
    if i < 0:
        i = 0  # label before first sample: take earliest
    return float(val[i])


def process_build(build_id: int) -> Path | None:
    labels_path = LABELS_DIR / f"{build_id:03d}.parquet"
    fi_path = FRAMES_INDEX_DIR / f"{build_id:03d}.parquet"
    tel_path = TELEMETRY_DIR / f"{build_id:03d}.parquet"
    if not labels_path.exists():
        return None
    labels = pl.read_parquet(labels_path)
    if labels.is_empty():
        return None
    if not fi_path.exists() or not tel_path.exists():
        print(f"  build {build_id}: labels present but frames_index/telemetry "
              f"missing — run sls-deliver-frames + sls-export first; skipped")
        return None

    tel = pl.read_parquet(tel_path)
    frames = FrameStore(build_id)
    boundaries = _recoat_boundaries_ms(tel)
    scalars = _scalar_series(tel)
    build_name = _build_name(build_id)

    import numpy as np
    bnd = np.array(boundaries, dtype="int64")

    rows: list[dict] = []
    # One row per labeled layer; anchor = earliest label ts on that layer.
    for (layer,), grp in labels.sort("ts").group_by(["layer"], maintain_order=True):
        grp = grp.sort("ts")
        anchor_ts_ms = int(grp["ts"].dt.epoch(time_unit="ms")[0])

        label_list = [
            {"class": r["class"], "bbox": list(r["bbox"]), "polarity": r["polarity"]}
            for r in grp.iter_rows(named=True)
        ]
        present = {lbl["class"] for lbl in label_list}

        # after_powder: first chamber after the recoat that precedes the anchor.
        lo = int(bnd[np.searchsorted(bnd, anchor_ts_ms, side="right") - 1]) \
            if len(bnd) and bnd[0] <= anchor_ts_ms else None
        after_powder = frames.first_in("chamber", lo, anchor_ts_ms) if lo is not None else None

        row = {
            "build": build_id,
            "build_name": build_name,
            "layer": int(layer),
            "ts": grp["ts"][0],
            "image_after_powder": after_powder,
            "image_after_melt": frames.nearest("chamber", anchor_ts_ms),
            "part_mask": frames.nearest("galvo", anchor_ts_ms),
            "labels": label_list,
        }
        for c in PEREGRINE_ALL_CLASSES:
            row[f"has_{c}"] = c in present
        for name, _, _ in SCALAR_SPECS:
            row[name] = _scalar_at(scalars[name], anchor_ts_ms)
        rows.append(row)

    frames.close()
    rows.sort(key=lambda r: r["layer"])

    table = pa.Table.from_pylist(rows, schema=OUTPUT_SCHEMA)
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    out_path = OUTPUT_DIR / f"{build_id:03d}.parquet"
    pq.write_table(table, out_path, compression="zstd")
    print(f"  build {build_id}: {len(rows)} labeled layer(s) -> "
          f"{out_path.relative_to(DATA_DIR.parent)}")
    return out_path


def _builds_with_labels() -> list[int]:
    return sorted(int(p.stem) for p in LABELS_DIR.glob("*.parquet"))


def main():
    args = sys.argv[1:]
    builds = [int(a) for a in args] if args else _builds_with_labels()
    if not builds:
        print("no builds with source/labels/*.parquet found")
        return
    written = 0
    for b in builds:
        if process_build(b) is not None:
            written += 1
    print(f"done: {written} build(s) written to {OUTPUT_DIR.relative_to(DATA_DIR.parent)}")


if __name__ == "__main__":
    main()