"""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 (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 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 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 Inova-Mk1-Database.""" 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" {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")), } 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). Cols A-B carry the raw load/extension curve; cols D-F carry whatever scalar metrics that particular export included. Metrics/curves not present in the export (full strain/stress arrays, modulus, yield, etc. — they require the support span, which isn't surfaced here) 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}") metrics = { "modulus_pa": None, "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": [convert_unit(v, curve["col_a_unit"], _LENGTH_TO_M) for v in curve["col_a"]], "load_n": [convert_unit(v, curve["col_b_unit"], _FORCE_TO_N) for v in curve["col_b"]], "strain": [], "stress_pa": [], }, "notes": session.get("notes", "") or ( "Raw persistent.h5/DAQ h5 unavailable for this specimen; curve and " "metrics extracted from the TestWorks xlsx export only. Full " "strain/stress arrays and modulus/yield metrics are null because " "they require the support span, which this export doesn't surface." ), "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)}/")