File size: 10,185 Bytes
0f6d5bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c5ff6e
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
"""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 / "Inova-Mk1-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, dict]:
    """Index Database jobs.jsonl by print_date."""
    jobs = {}
    with DATABASE_JOBS.open() as f:
        for line in f:
            row = json.loads(line)
            jobs[row["print_date"]] = 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 from cols D-E 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 = {}
    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
        if name is None:
            continue
        scalars[str(name)] = value
    wb.close()
    return {"scalars": scalars, "sheet_name": sheet_name}


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"]
    base = SOURCE_DIR / session_folder / session["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"]

    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 = None
    print_profile_snapshot = None
    if material_class == "SLS" and db_print_date:
        job = jobs_by_date.get(db_print_date)
        if job is None:
            log.warning(f"  {session_folder}/TSR{tsr_idx}: 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, session["astm"]["standard"])
            object_hash = obj["hash"] if obj else None
            print_profile_snapshot = find_print_profile(print_profile_id)

    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")),
    }

    return {
        "sample_id":        sample_id,
        "batch_label":      session["batch_label"] if material_class == "SLS" else None,
        "specimen_id":      f"{session_folder}/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"],
        },
    }


_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']})")

    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 = build_row(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)}/")