File size: 24,004 Bytes
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3742261
0f6d5bb
 
 
 
 
 
 
 
 
 
a196ec9
 
 
 
 
 
0f6d5bb
 
 
a196ec9
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
0f6d5bb
 
 
82ea559
0f6d5bb
 
 
 
 
82ea559
0f6d5bb
 
 
82ea559
0f6d5bb
82ea559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f49758
 
 
 
82ea559
 
 
 
 
 
 
 
 
 
 
 
a196ec9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f49758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
 
3742261
82ea559
 
 
a196ec9
 
 
 
 
 
 
 
 
82ea559
 
 
 
 
 
 
 
 
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
0f6d5bb
 
 
 
82ea559
 
 
 
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
 
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
a196ec9
 
 
 
0f6d5bb
 
 
 
82ea559
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c5ff6e
0f6d5bb
 
 
 
 
 
 
 
 
82ea559
 
 
 
 
 
2f49758
 
 
 
 
 
 
 
 
 
 
82ea559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2f49758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a196ec9
82ea559
2f49758
82ea559
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a196ec9
 
2f49758
 
82ea559
 
2f49758
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
 
 
 
 
 
 
 
 
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ea559
 
0f6d5bb
 
 
 
 
 
 
 
 
82ea559
 
0f6d5bb
 
 
 
 
 
 
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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
"""Shared helpers for the per-session specimen extract scripts.

Each `scripts/specimens/{NN}_*.py` declares one TestWorks session as a SESSION
dict, then calls `process_session(SESSION)`. Output: one JSONL file per
specimen under `data/{standard}/`.

A session dict looks like:
    SESSION = {
        "session_folder": "2026_05_26",          # relative to source/
        "test_folder":    "TST1.Test",           # almost always this
        "xlsx_name":      "tensile_testing_5.26.xlsx",
        "astm":           {"standard": "D638", "type": "Type I", "year": "2022"},
        "batch_label":    "A",
        "test_runs":      [(tsr_idx, material_class, db_print_date_or_None), ...],
    }
"""
import json
import logging
import re
from pathlib import Path

import h5py
import openpyxl

ROOT = Path(__file__).parent.parent.parent
SOURCE_DIR = ROOT / "source"
DATA_DIR = ROOT / "data"

DATABASE_ROOT = ROOT.parent / "Agentic-SLS-Database"
DATABASE_JOBS = DATABASE_ROOT / "data" / "jobs.jsonl"
DATABASE_PROFILES_DIR = DATABASE_ROOT / "source" / "PrintProfiles"

# Substring that identifies the matching STL object in a Database job, by standard.
STANDARD_TO_STL_NEEDLE = {"D638": "d638", "D790": "d790"}

logging.basicConfig(level=logging.INFO, format="%(message)s")
log = logging.getLogger("specimens")


def load_database_jobs() -> dict[str, list[dict]]:
    """Index Database jobs.jsonl by print_date. A single date can have multiple
    jobs (e.g. 2026-06-27 has both `D790 and D638 and other objects` and
    `Hex Coasters and Nameplates and Benchies`), so values are lists —
    resolve_database_fk() picks the one containing the standard's STL."""
    jobs: dict[str, list[dict]] = {}
    with DATABASE_JOBS.open() as f:
        for line in f:
            row = json.loads(line)
            jobs.setdefault(row["print_date"], []).append(row)
    return jobs


def find_print_profile(profile_id: str) -> dict | None:
    for p in DATABASE_PROFILES_DIR.glob(f"*{profile_id}*.json"):
        with p.open() as f:
            return json.load(f)
    return None


def pick_object(job_row: dict, standard: str) -> dict | None:
    needle = STANDARD_TO_STL_NEEDLE[standard]
    for obj in job_row["objects"]:
        if needle in obj["name"].lower():
            return obj
    return None


def safe_float(x):
    """Coerce to float and turn NaN/inf into None for JSON safety."""
    if x is None:
        return None
    try:
        v = float(x)
    except (TypeError, ValueError):
        return None
    if v != v or v in (float("inf"), float("-inf")):
        return None
    return v


def get_either(d: dict, *keys):
    """Return the first key from `keys` present in `d`, or None.

    Tensile and flex persistent.h5 spell the same concept differently
    (e.g. StrnAtPeak vs StrainAtPeak)."""
    for k in keys:
        if k in d:
            return d[k]
    return None


def read_xlsx_scalars(xlsx_path: Path, sheet_index: int) -> dict:
    """Pull {DisplayName: Value} pairs (plus their units) from cols D-F of a
    TestWorks export sheet."""
    wb = openpyxl.load_workbook(xlsx_path, data_only=True, read_only=True)
    sheet_name = wb.sheetnames[sheet_index]
    ws = wb[sheet_name]
    scalars, units = {}, {}
    for i, row in enumerate(ws.iter_rows(values_only=True)):
        if i < 2:
            continue
        name = row[3] if len(row) > 3 else None
        value = row[4] if len(row) > 4 else None
        unit = row[5] if len(row) > 5 else None
        if name is None:
            continue
        scalars[str(name)] = value
        units[str(name)] = unit
    wb.close()
    return {"scalars": scalars, "units": units, "sheet_name": sheet_name}


def read_xlsx_curve(xlsx_path: Path, sheet_index: int) -> dict:
    """Pull the raw (col A, col B) curve embedded in a TestWorks export sheet,
    for sessions where no persistent.h5/DAQ h5 survived (see Dataset H flex).
    Row 2 (0-indexed) holds the units for these two columns."""
    wb = openpyxl.load_workbook(xlsx_path, data_only=True, read_only=True)
    ws = wb[wb.sheetnames[sheet_index]]
    a_unit = b_unit = None
    a_vals, b_vals = [], []
    for i, row in enumerate(ws.iter_rows(values_only=True)):
        if i == 1:
            a_unit, b_unit = row[0], row[1]
            continue
        if i < 2:
            continue
        a, b = row[0], row[1]
        if a is None or b is None:
            continue
        a_vals.append(a)
        b_vals.append(b)
    wb.close()
    return {"col_a": a_vals, "col_a_unit": a_unit, "col_b": b_vals, "col_b_unit": b_unit}


_LENGTH_TO_M = {"mm": 1e-3, "m": 1.0, "cm": 1e-2, "in": 0.0254}
_FORCE_TO_N = {"n": 1.0, "kn": 1e3, "lbf": 4.4482216153}
_STRESS_TO_PA = {
    "pa": 1.0, "kpa": 1e3, "mpa": 1e6, "gpa": 1e9,
    "n/mm2": 1e6, "kn/mm2": 1e9, "psi": 6894.757,
}


def _normalize_unit(unit) -> str | None:
    if unit is None:
        return None
    return str(unit).strip().lower().replace("²", "2").replace(" ", "")


def _is_stress_unit(unit) -> bool:
    return _normalize_unit(unit) in _STRESS_TO_PA


def convert_unit(value, unit, table: dict) -> float | None:
    """Convert `value` from its xlsx-reported `unit` to the SI unit `table` maps to."""
    v = safe_float(value)
    if v is None:
        return None
    factor = table.get(_normalize_unit(unit))
    if factor is None:
        log.warning(f"  unrecognized unit {unit!r} for value {value}")
        return None
    return v * factor


def flexural_modulus_pa(width_mm, thickness_mm, extension_m, load_n):
    """ASTM D790 chord flexural modulus from the load-deflection curve.

    TestWorks' D790 method exported a Modulus scalar computed from a
    mis-zeroed strain channel (20-150 GPa on SLS specimens — physically
    impossible; PA12-GF TDS flexural modulus is 2.4 GPa), so D790 modulus
    is recomputed here: E = L^3 m / (4 b d^3) with support span L = 16 d
    (span-to-depth 16:1 — confirmed against the export's own stress
    channel, which matches sigma = 3FL/(2 b d^2) with this L exactly),
    where m is the least-squares slope of load vs crosshead deflection
    over the 10-40%-of-peak-load window (chord through the linear region,
    above the seating toe). Validated: batch H recomputes to 2.0-2.6 GPa,
    at the TDS value. Crosshead-based deflection understates E for very
    compliant specimens, so treat low-density batches' values as lower
    bounds.
    """
    if not width_mm or not thickness_mm or not extension_m or not load_n:
        return None
    b, d = width_mm / 1000.0, thickness_mm / 1000.0
    span = 16.0 * d
    peak = max(load_n)
    if peak <= 0:
        return None
    peak_i = load_n.index(peak)
    pts = [(e, l) for e, l in zip(extension_m[:peak_i], load_n[:peak_i])
           if e is not None and l is not None and 0.10 * peak <= l <= 0.40 * peak]
    if len(pts) < 5:
        return None
    n = len(pts)
    sx = sum(p[0] for p in pts)
    sy = sum(p[1] for p in pts)
    sxx = sum(p[0] * p[0] for p in pts)
    sxy = sum(p[0] * p[1] for p in pts)
    denom = n * sxx - sx * sx
    if denom == 0:
        return None
    slope = (n * sxy - sx * sy) / denom
    if slope <= 0:
        return None
    return span ** 3 * slope / (4.0 * b * d ** 3)


def flexural_stress_strain_pa(width_mm, thickness_mm, extension_m, load_n):
    """ASTM D790 chord stress/strain arrays derived from a raw load-deflection
    curve, for xlsx_only D790 sessions whose export has no analyzed
    StressArray/StrainArray to fall back on (e.g. Batch H, K, L flex).

    Same span assumption as flexural_modulus_pa (L = 16*d, validated against
    TestWorks' own stress channel): sigma = 3*P*L / (2*b*d^2),
    epsilon = 6*D*d / L^2, where D is crosshead deflection (extension_m).
    """
    if not width_mm or not thickness_mm:
        return [], []
    b, d = width_mm / 1000.0, thickness_mm / 1000.0
    span = 16.0 * d
    strain, stress_pa = [], []
    for e, l in zip(extension_m, load_n):
        if e is None or l is None:
            continue
        strain.append(6.0 * e * d / span ** 2)
        stress_pa.append(3.0 * l * span / (2.0 * b * d ** 2))
    return strain, stress_pa


def resolve_database_fk(material_class: str, db_print_date: str | None, standard: str,
                         jobs_by_date: dict, log_ctx: str):
    """Look up the Database job/print-profile FKs for an SLS specimen, if the
    print job has been backfilled into Agentic-SLS-Database."""
    job_id = print_profile_id = object_hash = None
    print_profile_snapshot = None
    if material_class == "SLS" and db_print_date:
        candidates = jobs_by_date.get(db_print_date, [])
        # Prefer a job that actually contains the standard's STL — this
        # disambiguates dates with multiple prints (e.g. 2026-06-27).
        job = next((c for c in candidates if pick_object(c, standard)), None)
        if job is None and candidates:
            log.warning(f"  {log_ctx}: {len(candidates)} Database job(s) on "
                        f"{db_print_date} but none contain a {standard} STL; "
                        f"falling back to first")
            job = candidates[0]
        if job is None:
            log.warning(f"  {log_ctx}: no Database job for {db_print_date}")
        else:
            job_id = job["metadata"]["AutomaticJob"]["Id"]
            print_profile_id = job["print_profile_id"]
            obj = pick_object(job, standard)
            object_hash = obj["hash"] if obj else None
            print_profile_snapshot = find_print_profile(print_profile_id)
    return job_id, print_profile_id, object_hash, print_profile_snapshot


def _h5_array_to_list(arr) -> list:
    return [safe_float(v) for v in arr]


def read_persistent_h5(path: Path) -> dict:
    """Return analyzed scalars + curve arrays from an AnalysisRun."""
    with h5py.File(path, "r") as f:
        v = f["Values"][0]
        scalars, arrays = {}, {}
        for name in v.dtype.names:
            val = v[name]
            if isinstance(val, (bytes, str)):
                continue
            if hasattr(val, "__len__"):
                arrays[name] = _h5_array_to_list(val)
            else:
                scalars[name] = safe_float(val) if isinstance(val, float) else val
    return {"scalars": scalars, "arrays": arrays}


def read_daq_h5(path: Path) -> dict:
    """Return raw DAQ scans (extension_m, load_N, time_s).

    Both tensile and flex DAQs store SI units per the Signals dataset
    (Crosshead=m, Load=N, Time=s)."""
    with h5py.File(path, "r") as f:
        g = f["Session0000000000000000"]
        scans = g["Scans"][...]
    return {
        "extension_m": [float(v) for v in scans[:, 0]],
        "load_n":      [float(v) for v in scans[:, 1]],
        "time_s":      [float(v) for v in scans[:, 2]],
    }


def build_row(session: dict, tsr_idx: int, material_class: str,
              db_print_date: str | None, sample_id: str | None,
              jobs_by_date: dict) -> dict:
    session_folder = session["session_folder"]
    test_folder = session["test_folder"]
    base = SOURCE_DIR / session_folder / test_folder
    tsr_dir = base / "TestRuns" / f"TSR{tsr_idx}.TestRun"
    persistent_path = tsr_dir / "AnalysisRuns" / "ANR1.AnalysisRun" / "persistent.h5"
    daq_path = tsr_dir / "Data" / "DaqTaskActivity1.h5"
    xlsx_path = SOURCE_DIR / session_folder / session["xlsx_name"]
    # Disambiguate sessions where more than one Test project (TST1.Test,
    # TST2.Test, ...) shares a session_folder — e.g. Batch H/I tensile, both
    # under source/2026_06_30/Tensile/.
    specimen_path = session_folder if test_folder == "TST1.Test" else f"{session_folder}/{test_folder}"

    persistent = read_persistent_h5(persistent_path)
    daq = read_daq_h5(daq_path)
    xlsx = read_xlsx_scalars(xlsx_path, sheet_index=tsr_idx - 1)
    x_scalars = xlsx["scalars"]
    ps = persistent["scalars"]

    width_mm = safe_float(x_scalars.get("Width"))
    thickness_mm = safe_float(x_scalars.get("Thickness"))
    area_mm2 = (width_mm * thickness_mm) if (width_mm and thickness_mm) else None
    # Gauge length only exists for tensile (D638). Flex (D790) uses support span,
    # which is not surfaced by TestWorks here.
    adj_gage = ps.get("AdjGage")
    gauge_length_mm = round(adj_gage * 1000, 4) if adj_gage else None

    job_id, print_profile_id, object_hash, print_profile_snapshot = resolve_database_fk(
        material_class, db_print_date, session["astm"]["standard"], jobs_by_date,
        f"{session_folder}/TSR{tsr_idx}")

    metrics = {
        "modulus_pa":         safe_float(ps.get("Modulus")),
        "peak_load_n":        safe_float(ps.get("PeakLoad")),
        "peak_stress_pa":     safe_float(ps.get("PeakStress")),
        "strain_at_peak":     safe_float(get_either(ps, "StrnAtPeak", "StrainAtPeak")),
        "load_at_break_n":    safe_float(ps.get("LoadAtBreak")),
        "stress_at_break_pa": safe_float(ps.get("StressAtBreak")),
        "strain_at_break":    safe_float(get_either(ps, "StrnAtBreak", "BreakStrain")),
        "energy_to_break_j":  safe_float(ps.get("EnergyToBreak")),
        "yield_stress_pa":    safe_float(ps.get("StressAtYield")),
        "strain_at_yield":    safe_float(get_either(ps, "StrnAtYield", "StrainAtYield")),
    }
    if session["astm"]["standard"] == "D790":
        # TestWorks' D790 Modulus scalar is unusable — see flexural_modulus_pa.
        metrics["modulus_pa"] = flexural_modulus_pa(
            width_mm, thickness_mm, daq["extension_m"], daq["load_n"])

    return {
        "sample_id":        sample_id,
        "batch_label":      session["batch_label"] if material_class == "SLS" else None,
        "specimen_id":      f"{specimen_path}/TSR{tsr_idx}",
        "test_date":        session_folder.split("/")[0].replace("_", "-"),
        "session_folder":   session_folder,
        "test_run_name":    f"TSR{tsr_idx}",
        "specimen_index":   tsr_idx,
        "material_class":   material_class,
        "astm":             session["astm"],
        "test_end_reason":  x_scalars.get("Test Run End Reason"),
        "geometry": {
            "width_mm":         width_mm,
            "thickness_mm":     thickness_mm,
            "area_mm2":         area_mm2,
            "gauge_length_mm":  gauge_length_mm,
        },
        "job_id":           job_id,
        "print_date":       db_print_date,
        "print_profile_id": print_profile_id,
        "object_hash":      object_hash,
        "session_id":       None,
        "print_profile_snapshot": print_profile_snapshot,
        "metrics":          metrics,
        "curves": {
            "time_s":      daq["time_s"],
            "extension_m": daq["extension_m"],
            "load_n":      daq["load_n"],
            "strain":      persistent["arrays"].get("StrainArray", []),
            "stress_pa":   persistent["arrays"].get("StressArray", []),
        },
        "notes": session.get("notes", ""),
        "source_paths": {
            "persistent_h5": str(persistent_path.relative_to(ROOT)),
            "daq_h5":        str(daq_path.relative_to(ROOT)),
            "xlsx":          str(xlsx_path.relative_to(ROOT)),
            "xlsx_sheet":    xlsx["sheet_name"],
        },
    }


def build_row_from_xlsx(session: dict, sheet_idx: int, material_class: str,
                         db_print_date: str | None, sample_id: str | None,
                         jobs_by_date: dict) -> dict:
    """Build a specimen row from a TestWorks xlsx export only, for sessions
    whose persistent.h5/DAQ h5 files did not survive (Dataset H flex: its
    TestRuns folder was overwritten when a later TestWorks project reused the
    same default TST1.Test name) or were never captured to begin with (Batch
    K/L, 2026-07-15: only the xlsx exports were handed off). Cols A-B carry
    a curve whose columns vary by export: some sessions (e.g. Batch H flex)
    export the raw load/extension trace (col A in mm, col B in N); others
    (e.g. Batch K/L) export the already-analyzed strain/stress trace (col A
    dimensionless mm/mm, col B in a stress unit like kN/mm²). Which one we
    got is detected from col B's unit rather than assumed, and only the
    matching curve field gets populated — the other stays empty rather than
    being derived. Cols D-F carry whatever scalar metrics that particular
    export included. Metrics/curves not present in the export (yield, full
    raw DAQ trace, etc.) stay null/empty rather than being approximated."""
    session_folder = session["session_folder"]
    xlsx_path = SOURCE_DIR / session_folder / session["xlsx_name"]

    xlsx = read_xlsx_scalars(xlsx_path, sheet_index=sheet_idx - 1)
    curve = read_xlsx_curve(xlsx_path, sheet_index=sheet_idx - 1)
    x_scalars, x_units = xlsx["scalars"], xlsx["units"]

    width_mm = safe_float(x_scalars.get("Width"))
    thickness_mm = safe_float(x_scalars.get("Thickness"))
    area_mm2 = (width_mm * thickness_mm) if (width_mm and thickness_mm) else None

    job_id, print_profile_id, object_hash, print_profile_snapshot = resolve_database_fk(
        material_class, db_print_date, session["astm"]["standard"], jobs_by_date,
        f"{session_folder}/Sheet{sheet_idx}")

    curve_is_analyzed = _is_stress_unit(curve["col_b_unit"])
    if curve_is_analyzed:
        curve_ext_m, curve_load_n = [], []
        curve_strain = [safe_float(v) for v in curve["col_a"]]
        curve_stress_pa = [convert_unit(v, curve["col_b_unit"], _STRESS_TO_PA) for v in curve["col_b"]]
    else:
        curve_ext_m = [convert_unit(v, curve["col_a_unit"], _LENGTH_TO_M) for v in curve["col_a"]]
        curve_load_n = [convert_unit(v, curve["col_b_unit"], _FORCE_TO_N) for v in curve["col_b"]]
        curve_strain, curve_stress_pa = [], []
        if session["astm"]["standard"] == "D790":
            # Derive the analyzed curve via the same chord formulas/span
            # assumption as flexural_modulus_pa, so raw-curve D790 exports
            # (no StressArray/StrainArray to fall back on) still plot.
            curve_strain, curve_stress_pa = flexural_stress_strain_pa(
                width_mm, thickness_mm, curve_ext_m, curve_load_n)

    if session["astm"]["standard"] == "D790":
        # flexural_modulus_pa needs the raw load-deflection trace; an
        # already-analyzed strain/stress export doesn't carry deflection, so
        # there's nothing to recompute from — leave modulus null.
        modulus_pa = (flexural_modulus_pa(width_mm, thickness_mm, curve_ext_m, curve_load_n)
                      if not curve_is_analyzed else None)
    else:
        # Tensile Modulus, when the export includes it, is a direct TestWorks
        # scalar (not the mis-zeroed-channel D790 case) — use it as-is.
        modulus_pa = convert_unit(x_scalars.get("Modulus"), x_units.get("Modulus"), _STRESS_TO_PA)

    metrics = {
        "modulus_pa":         modulus_pa,
        "peak_load_n":        convert_unit(x_scalars.get("Peak Load"), x_units.get("Peak Load"), _FORCE_TO_N),
        "peak_stress_pa":     convert_unit(x_scalars.get("Peak Stress"), x_units.get("Peak Stress"), _STRESS_TO_PA),
        "strain_at_peak":     None,
        "load_at_break_n":    None,
        "stress_at_break_pa": convert_unit(x_scalars.get("Stress at Break"), x_units.get("Stress at Break"), _STRESS_TO_PA),
        "strain_at_break":    safe_float(x_scalars.get("Strain at Break")),
        "energy_to_break_j":  None,
        "yield_stress_pa":    None,
        "strain_at_yield":    None,
    }

    return {
        "sample_id":        sample_id,
        "batch_label":      session["batch_label"] if material_class == "SLS" else None,
        "specimen_id":      f"{session_folder}/Sheet{sheet_idx}",
        "test_date":        session_folder.split("/")[0].replace("_", "-"),
        "session_folder":   session_folder,
        "test_run_name":    f"Sheet{sheet_idx}",
        "specimen_index":   sheet_idx,
        "material_class":   material_class,
        "astm":             session["astm"],
        "test_end_reason":  x_scalars.get("Test Run End Reason"),
        "geometry": {
            "width_mm":         width_mm,
            "thickness_mm":     thickness_mm,
            "area_mm2":         area_mm2,
            "gauge_length_mm":  None,
        },
        "job_id":           job_id,
        "print_date":       db_print_date,
        "print_profile_id": print_profile_id,
        "object_hash":      object_hash,
        "session_id":       None,
        "print_profile_snapshot": print_profile_snapshot,
        "metrics":          metrics,
        "curves": {
            "time_s":      [],
            "extension_m": curve_ext_m,
            "load_n":      curve_load_n,
            "strain":      curve_strain,
            "stress_pa":   curve_stress_pa,
        },
        "notes": session.get("notes", "") or (
            (
                "Raw persistent.h5/DAQ h5 unavailable for this specimen; strain/"
                "stress curve and metrics extracted from the TestWorks xlsx "
                "export only (already analyzed — no raw load/extension trace to "
                "derive it from). Yield metrics are null; D790 modulus is null "
                "since it needs the raw load-deflection trace to recompute (see "
                "flexural_modulus_pa)."
            ) if curve_is_analyzed else (
                (
                    "Raw persistent.h5/DAQ h5 unavailable for this specimen; curve "
                    "and metrics extracted from the TestWorks xlsx export only. "
                    "Strain/stress curve and modulus are both derived from the raw "
                    "load-deflection trace via the D790 chord formulas with span = "
                    "16*depth (see flexural_stress_strain_pa / flexural_modulus_pa) "
                    "rather than TestWorks' own analysis. Yield metrics are null."
                ) if session["astm"]["standard"] == "D790" else (
                    "Raw persistent.h5/DAQ h5 unavailable for this specimen; curve "
                    "and metrics extracted from the TestWorks xlsx export only. "
                    "Strain/stress arrays and yield metrics are null."
                )
            )
        ),
        "source_paths": {
            "persistent_h5": None,
            "daq_h5":        None,
            "xlsx":          str(xlsx_path.relative_to(ROOT)),
            "xlsx_sheet":    xlsx["sheet_name"],
        },
    }


_FILENAME_SAFE = re.compile(r"[^A-Za-z0-9_-]")


def _row_filename(row: dict) -> str:
    """Pick a per-specimen filename: sample_id for SLS rows,
    {material_class}_TSR{n} for non-SLS controls."""
    if row["sample_id"]:
        stem = row["sample_id"]
    else:
        stem = f"{row['material_class']}_{row['test_run_name']}"
    return _FILENAME_SAFE.sub("_", stem) + ".jsonl"


def process_session(session: dict) -> None:
    """Build per-specimen JSONL files for one TestWorks session."""
    standard = session["astm"]["standard"]
    out_dir = DATA_DIR / standard
    out_dir.mkdir(parents=True, exist_ok=True)

    jobs_by_date = load_database_jobs()

    log.info(f"== {session['session_folder']} ({standard}, batch {session['batch_label']})")

    builder = build_row_from_xlsx if session.get("xlsx_only") else build_row

    seq = 0
    written = 0
    for tsr_idx, material_class, db_print_date in session["test_runs"]:
        if material_class == "SLS":
            seq += 1
            sample_id = f"{session['batch_label']}{seq}"
        else:
            sample_id = None

        row = builder(session, tsr_idx, material_class, db_print_date,
                       sample_id, jobs_by_date)
        out_path = out_dir / _row_filename(row)
        with out_path.open("w", encoding="utf-8") as out:
            out.write(json.dumps(row, ensure_ascii=False) + "\n")
        written += 1
        log.info(f"  TSR{tsr_idx} [{sample_id or material_class}] -> {out_path.relative_to(ROOT)}")

    log.info(f"   wrote {written} specimens to {out_dir.relative_to(ROOT)}/")