Datasets:
Languages:
English
Size:
100K<n<1M
Tags:
additive-manufacturing
laser-powder-bed-fusion
smoothed-particle-hydrodynamics
melt-pool
keyhole
physics-simulation
DOI:
License:
| #!/usr/bin/env python3 | |
| """ | |
| refactor_and_label.py | |
| One-shot pipeline: refactor raw SPH experiment folders into the public release | |
| layout AND apply auto-labels using a per-experiment median-zmin threshold. | |
| LABELING RULE (per-frame): | |
| Initial Emptiness if the corresponding monitor row has any |value| > 1e30 | |
| Keyhole if zmin < 1.5 * per-experiment-median-zmin | |
| (pool bottom is deeper than 1.5x the typical pool bottom) | |
| Conduction otherwise | |
| The per-experiment median zmin is computed over valid (non-IE) rows of | |
| monitor/position-bounds_melt.dat for that experiment only --- no cross- | |
| experiment comparison. Both median_zmin and per-frame zmin are negative | |
| (pool extends below substrate surface at z=0); "zmin < 1.5*median_zmin" | |
| is equivalent to "|zmin| > 1.5*|median_zmin|". | |
| EXCLUSIONS (whole experiment skipped, label column left empty): | |
| - fewer than 10 valid (non-IE) rows | |
| - per-experiment median zmin >= 0 (pool not subsurface) | |
| ASSUMPTION: | |
| monitor/position-bounds_melt.dat has one row per simulation timestep, | |
| starting at timestep 0. PNG filenames use the simulation timestep number | |
| (e.g. ss_100069_*.png), so the monitor row at index i corresponds to | |
| simulation timestep i. PNG frames are mapped by: | |
| monitor_row = rows[png_timestep] | |
| PNG frames whose timestep exceeds the available monitor rows are left | |
| unlabeled (counted in n_frames_unmapped). | |
| USAGE: | |
| # Single experiment (testing or one-off): | |
| python refactor_and_label.py --mode single <P-...folder> <dest> | |
| # Whole dataset (batch): | |
| python refactor_and_label.py --mode set <parent_dir_of_P-folders> <output_parent> | |
| In set mode: source is a directory containing many P-...VX-...LS-... experiment | |
| folders; output receives sim_00001/, sim_00002/, ... in sorted order. | |
| In single mode: source is one P-...VX-... folder; output receives sim_00001/. | |
| """ | |
| import argparse | |
| import csv | |
| import json | |
| import re | |
| import shutil | |
| import statistics | |
| import sys | |
| import traceback | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| # ---- Constants ------------------------------------------------------------- | |
| PARAM_MAP = { | |
| "P": ("laser_power", "W"), | |
| "VX": ("scan_speed_x", "m/s"), | |
| "LS": ("laser_spot_size", "m"), | |
| "ST": ("substrate_temperature", "K"), | |
| } | |
| SENTINEL_THRESHOLD = 1e30 | |
| MIN_VALID_ROWS = 10 | |
| KEYHOLE_RATIO = 1.5 | |
| SCRIPT_VERSION = "refactor+label v0.2" | |
| # ---- Folder-name parsing --------------------------------------------------- | |
| def decode_value(raw): | |
| if re.fullmatch(r"[A-Z0-9]+", raw): | |
| return raw | |
| return float(raw.replace("p", ".")) | |
| def parse_folder_name(name): | |
| out = {} | |
| for token in name.split("_"): | |
| if "-" not in token: | |
| continue | |
| key, _, value = token.partition("-") | |
| out[key] = value | |
| return out | |
| # ---- Monitor-file parsing -------------------------------------------------- | |
| def parse_monitor_dat(path): | |
| rows = [] | |
| with open(path) as f: | |
| for line in f: | |
| line = line.strip() | |
| if not line or line.startswith("#"): | |
| continue | |
| parts = [p.strip() for p in line.split(",")] | |
| try: | |
| values = [float(p) for p in parts[:6]] | |
| except ValueError: | |
| continue | |
| if len(values) < 6: | |
| continue | |
| rows.append(values) | |
| return rows | |
| def is_initial_emptiness_row(row): | |
| return any(abs(v) > SENTINEL_THRESHOLD for v in row) | |
| # ---- Per-experiment processing -------------------------------------------- | |
| def process_one(src, dst, sim_id): | |
| """Refactor + label a single experiment. Returns a summary dict.""" | |
| raw = parse_folder_name(src.name) | |
| # 1) Parameters | |
| parameters = {} | |
| for letter, (canonical, unit) in PARAM_MAP.items(): | |
| if letter not in raw: | |
| return {"sim_id": sim_id, "src_name": src.name, | |
| "fatal_error": f"missing parameter '{letter}' in folder name"} | |
| parameters[canonical] = {"value": decode_value(raw[letter]), "unit": unit} | |
| material = raw.get("M", None) | |
| # 2) Locate inputs | |
| final_results = src / "final_results" | |
| if not final_results.is_dir(): | |
| return {"sim_id": sim_id, "src_name": src.name, "fatal_error": "missing final_results/"} | |
| details_candidates = list(final_results.glob("*.json")) | |
| if len(details_candidates) != 1: | |
| return {"sim_id": sim_id, "src_name": src.name, | |
| "fatal_error": f"expected 1 JSON in final_results/, found {len(details_candidates)}"} | |
| details_src = details_candidates[0] | |
| monitor_src = final_results / "monitor" | |
| if not monitor_src.is_dir(): | |
| return {"sim_id": sim_id, "src_name": src.name, "fatal_error": "missing final_results/monitor/"} | |
| png_dir = src / "png_files" | |
| if not png_dir.is_dir(): | |
| return {"sim_id": sim_id, "src_name": src.name, "fatal_error": "missing png_files/"} | |
| # 3) Build dest | |
| dst.mkdir(parents=True) | |
| for view in ("front", "side", "top"): | |
| (dst / "frames" / view).mkdir(parents=True) | |
| # 4) Copy details + monitor | |
| shutil.copy2(details_src, dst / "experiment_details.json") | |
| shutil.copytree(monitor_src, dst / "monitor") | |
| # 5) Process PNG frames | |
| pattern = re.compile(r"ss_(\d+)_(front|side|top)\.png") | |
| by_timestep = {} | |
| for p in png_dir.iterdir(): | |
| m = pattern.match(p.name) | |
| if not m: | |
| continue | |
| ts, view = int(m.group(1)), m.group(2) | |
| by_timestep.setdefault(ts, {})[view] = p | |
| complete = {ts: views for ts, views in by_timestep.items() if len(views) == 3} | |
| skipped = len(by_timestep) - len(complete) | |
| sorted_timesteps = sorted(complete.keys()) | |
| n_frames = len(sorted_timesteps) | |
| for idx, ts in enumerate(sorted_timesteps): | |
| new_name = f"frame_{idx:05d}.png" | |
| for view, src_path in complete[ts].items(): | |
| shutil.copy2(src_path, dst / "frames" / view / new_name) | |
| # 6) Auto-label using monitor file (per-experiment median zmin, 1.5x threshold) | |
| monitor_dat = dst / "monitor" / "position-bounds_melt.dat" | |
| rows = parse_monitor_dat(monitor_dat) if monitor_dat.is_file() else [] | |
| label_status = "labeled" | |
| exclusion_reason = None | |
| median_zmin = None | |
| n_ie_rows = 0 | |
| n_valid_rows = 0 | |
| n_unmapped = 0 | |
| labels = [""] * n_frames | |
| if not rows: | |
| label_status, exclusion_reason = "excluded", "missing or empty position-bounds_melt.dat" | |
| else: | |
| is_ie = [is_initial_emptiness_row(r) for r in rows] | |
| n_ie_rows = sum(is_ie) | |
| valid = [r for r, ie in zip(rows, is_ie) if not ie] | |
| n_valid_rows = len(valid) | |
| if n_valid_rows < MIN_VALID_ROWS: | |
| label_status = "excluded" | |
| exclusion_reason = f"only {n_valid_rows} valid rows (need >= {MIN_VALID_ROWS})" | |
| else: | |
| median_zmin = statistics.median(r[4] for r in valid) | |
| if median_zmin >= 0: | |
| label_status = "excluded" | |
| exclusion_reason = (f"per-experiment median zmin >= 0 " | |
| f"({median_zmin:.3e} m); pool not subsurface") | |
| else: | |
| # Map each PNG frame to its monitor row by simulation timestep: | |
| # the .dat file has one row per simulation timestep, starting at 0. | |
| # PNG filenames use the simulation timestep number (e.g. ss_100069_*.png), | |
| # so row index = png timestep. | |
| # | |
| # Both median_zmin and per-frame zmin are negative (pool extends | |
| # below substrate surface at z=0); keyhole = pool bottom deeper | |
| # than 1.5x the typical bottom, i.e. zmin < 1.5*median_zmin | |
| # (more negative than the threshold). | |
| threshold = KEYHOLE_RATIO * median_zmin # negative | |
| for frame_idx, ts in enumerate(sorted_timesteps): | |
| if ts >= len(rows): | |
| n_unmapped += 1 | |
| continue # leave label empty | |
| if is_ie[ts]: | |
| labels[frame_idx] = "Initial Emptiness" | |
| else: | |
| zmin = rows[ts][4] | |
| labels[frame_idx] = "Keyhole" if zmin < threshold else "Conduction" | |
| # 7) Write parameters.json | |
| with open(dst / "parameters.json", "w") as f: | |
| json.dump(parameters, f, indent=2) | |
| # 8) Write frames.csv (with labels) | |
| with open(dst / "frames.csv", "w", newline="") as f: | |
| writer = csv.writer(f) | |
| writer.writerow(["frame_idx", "timestep", "label", | |
| "front_filename", "side_filename", "top_filename"]) | |
| for idx, ts in enumerate(sorted_timesteps): | |
| new_name = f"frame_{idx:05d}.png" | |
| writer.writerow([idx, ts, labels[idx], | |
| f"frames/front/{new_name}", | |
| f"frames/side/{new_name}", | |
| f"frames/top/{new_name}"]) | |
| # 9) Write metadata.json | |
| with open(dst / "metadata.json", "w") as f: | |
| json.dump({ | |
| "sim_id": sim_id, | |
| "original_folder_name": src.name, | |
| "original_hash": raw.get("H", None), | |
| "material": material, | |
| "n_frames": n_frames, | |
| "n_skipped_incomplete": skipped, | |
| }, f, indent=2) | |
| # 10) Write labeling_provenance.json | |
| n_keyhole = sum(1 for l in labels if l == "Keyhole") | |
| n_conduction = sum(1 for l in labels if l == "Conduction") | |
| n_ie = sum(1 for l in labels if l == "Initial Emptiness") | |
| now = datetime.now(timezone.utc).isoformat() | |
| if label_status == "labeled": | |
| provenance = { | |
| "method": "automatic", | |
| "automatic_method": "per-experiment-median-zmin, threshold = 1.5x median", | |
| "n_frames_total": n_frames, | |
| "n_frames_auto_labeled": n_frames - n_unmapped, | |
| "n_frames_unmapped": n_unmapped, | |
| "n_frames_human_verified": 0, | |
| "n_keyhole": n_keyhole, | |
| "n_conduction": n_conduction, | |
| "n_initial_emptiness": n_ie, | |
| "median_zmin_m": median_zmin, | |
| "keyhole_threshold_m": KEYHOLE_RATIO * median_zmin, | |
| "n_monitor_rows_total": len(rows), | |
| "n_monitor_rows_ie": n_ie_rows, | |
| "n_monitor_rows_valid": n_valid_rows, | |
| "labeler_id": None, | |
| "labeled_at": now, | |
| "tool_version": SCRIPT_VERSION, | |
| } | |
| else: | |
| provenance = { | |
| "method": "excluded", | |
| "automatic_method": "per-experiment-median-zmin, threshold = 1.5x median", | |
| "n_frames_total": n_frames, | |
| "n_frames_auto_labeled": 0, | |
| "n_frames_human_verified": 0, | |
| "exclusion_reason": exclusion_reason, | |
| "n_monitor_rows_total": len(rows), | |
| "n_monitor_rows_ie": n_ie_rows, | |
| "n_monitor_rows_valid": n_valid_rows, | |
| "labeler_id": None, | |
| "labeled_at": now, | |
| "tool_version": SCRIPT_VERSION, | |
| } | |
| with open(dst / "labeling_provenance.json", "w") as f: | |
| json.dump(provenance, f, indent=2) | |
| return { | |
| "sim_id": sim_id, | |
| "src_name": src.name, | |
| "dst_name": dst.name, | |
| "n_frames": n_frames, | |
| "n_unmapped": n_unmapped, | |
| "label_status": label_status, | |
| "exclusion_reason": exclusion_reason, | |
| "median_zmin": median_zmin, | |
| "n_keyhole": n_keyhole, | |
| "n_conduction": n_conduction, | |
| "n_initial_emptiness": n_ie, | |
| } | |
| # ---- Driver ---------------------------------------------------------------- | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__, | |
| formatter_class=argparse.RawDescriptionHelpFormatter) | |
| ap.add_argument("source", type=Path, | |
| help="Source path. In --mode single: a single P-...VX-... folder. " | |
| "In --mode set: a parent directory containing many P-...VX-... folders.") | |
| ap.add_argument("dest", type=Path, | |
| help="Destination path. In --mode single: dest folder for sim_NNNNN/. " | |
| "In --mode set: parent directory; sim_NNNNN/ folders will be created here.") | |
| ap.add_argument("--mode", choices=["single", "set"], required=True, | |
| help="single: process one experiment folder. " | |
| "set: iterate over all P-* folders in source.") | |
| ap.add_argument("--start", type=int, default=1, | |
| help="Starting sim number (default: 1)") | |
| ap.add_argument("--prefix", default="P-", | |
| help="Source folder prefix to match in --mode set (default: 'P-')") | |
| args = ap.parse_args() | |
| src_root = args.source.resolve() | |
| dst_root = args.dest.resolve() | |
| if not src_root.is_dir(): | |
| sys.exit(f"ERROR: source not found: {src_root}") | |
| if args.mode == "single": | |
| if not src_root.name.startswith(args.prefix): | |
| sys.exit(f"ERROR: --mode single expects a folder whose name starts with " | |
| f"'{args.prefix}'. Got: {src_root.name}") | |
| raw = [src_root] | |
| print(f"Single-experiment mode: {src_root.name}") | |
| else: # set | |
| if src_root.name.startswith(args.prefix): | |
| sys.exit(f"ERROR: --mode set expects a parent directory, but you pointed at " | |
| f"a single experiment folder ({src_root.name}). " | |
| f"Either use --mode single, or pass the parent directory.") | |
| raw = sorted(p for p in src_root.iterdir() | |
| if p.is_dir() and p.name.startswith(args.prefix)) | |
| if not raw: | |
| sys.exit(f"ERROR: no '{args.prefix}*/' folders found in {src_root}") | |
| print(f"Batch mode: {len(raw)} raw experiments in {src_root}") | |
| dst_root.mkdir(parents=True, exist_ok=True) | |
| print(f"Output: {dst_root}\n") | |
| results = [] | |
| for i, src_folder in enumerate(raw): | |
| sim_id = args.start + i | |
| sim_name = f"sim_{sim_id:05d}" | |
| dst_folder = dst_root / sim_name | |
| if dst_folder.exists(): | |
| print(f" [SKIP] {sim_name}: destination already exists") | |
| continue | |
| try: | |
| r = process_one(src_folder, dst_folder, sim_id) | |
| except Exception as e: | |
| print(f" [ERROR] {sim_name}: {type(e).__name__}: {e}") | |
| traceback.print_exc() | |
| if dst_folder.exists(): | |
| shutil.rmtree(dst_folder) | |
| continue | |
| results.append(r) | |
| if "fatal_error" in r: | |
| print(f" [FATAL] {sim_name}: {r['fatal_error']}") | |
| if dst_folder.exists(): | |
| shutil.rmtree(dst_folder) | |
| elif r["label_status"] == "excluded": | |
| print(f" [EXCL] {sim_name}: {r['exclusion_reason']}") | |
| else: | |
| unmap_note = f" (UNMAPPED: {r.get('n_unmapped', 0)})" if r.get('n_unmapped', 0) else "" | |
| print(f" [OK] {sim_name}: {r['n_frames']:4d} frames | " | |
| f"K={r['n_keyhole']:4d} C={r['n_conduction']:4d} IE={r['n_initial_emptiness']:3d} | " | |
| f"median_zmin={r['median_zmin']:.3e} m{unmap_note}") | |
| # Summary | |
| n_ok = sum(1 for r in results if r.get("label_status") == "labeled") | |
| n_exc = sum(1 for r in results if r.get("label_status") == "excluded") | |
| n_fatal = sum(1 for r in results if "fatal_error" in r) | |
| tot_K = sum(r.get("n_keyhole", 0) for r in results) | |
| tot_C = sum(r.get("n_conduction", 0) for r in results) | |
| tot_IE = sum(r.get("n_initial_emptiness", 0) for r in results) | |
| tot_frames = tot_K + tot_C + tot_IE | |
| print("\n" + "=" * 70) | |
| print("SUMMARY") | |
| print("=" * 70) | |
| print(f"Experiments: {len(results)}") | |
| print(f" labeled: {n_ok}") | |
| print(f" excluded: {n_exc}") | |
| if n_fatal: | |
| print(f" fatal errors: {n_fatal}") | |
| print(f"\nLabeled frames: {tot_frames}") | |
| print(f" Keyhole: {tot_K}") | |
| print(f" Conduction: {tot_C}") | |
| print(f" Initial Emptiness: {tot_IE}") | |
| if __name__ == "__main__": | |
| main() |