""" Example 2 — Classification: Keyhole vs Conduction Mode Binary classifier predicting melting regime from four process parameters. Labels are derived automatically from melt-pool depth (zmax − zmin) in monitor/position-bounds_melt.dat: experiments whose steady-state depth exceeds the dataset median are labeled Keyhole (1), the rest Conduction (0). Rows with sentinel values (|val| > 1e30) are tagged "Initial Emptiness" and excluded from depth computation. The dataset is then balanced via random undersampling of the majority class before any ML step. Three models evaluated via leave-one-out cross-validation: 1. Logistic Regression 2. Random Forest 3. SVM (RBF kernel) Set N_SUBSET to a small number (e.g. 30) so a reviewer can run this quickly. Set N_SUBSET = None to use the full balanced dataset. Outputs saved to runs/classification_/: classification_diagnostics.png — LOO confusion matrices + feature relevance run.log — full training log This is a proof-of-concept, not a benchmark. """ import logging import random import sys from datetime import datetime from pathlib import Path import numpy as np from sklearn.base import clone from sklearn.ensemble import RandomForestClassifier from sklearn.inspection import permutation_importance from sklearn.linear_model import LogisticRegression from sklearn.metrics import ConfusionMatrixDisplay from sklearn.model_selection import LeaveOneOut from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC import matplotlib.pyplot as plt # ------------------------------------------------------------------ # Config ← edit DATA_DIRS to point at your data directories # ------------------------------------------------------------------ DATA_DIRS = [ Path(__file__).parent.parent / "rnl" / "final_data_processed", Path(__file__).parent.parent / "rnl" / "lrz_data_new_format", ] OUT_ROOT = Path(__file__).parent.parent / "runs" N_SUBSET = 30 # reviewer-friendly subset size (None = full dataset) N_STABLE = 50 # last N valid timesteps for steady-state depth estimate RANDOM_SEED = 42 INPUT_PARAMS = ["laser_power", "scan_speed", "laser_spot_size", "substrate_temp"] MODEL_NAMES = ["LogReg", "RandomForest", "SVM-RBF"] # ------------------------------------------------------------------ # Logger # ------------------------------------------------------------------ class _ColorFormatter(logging.Formatter): _COLORS = {logging.DEBUG: "\033[37m", logging.INFO: "\033[32m", logging.WARNING: "\033[33m", logging.ERROR: "\033[31m"} _RESET = "\033[0m"; _BOLD = "\033[1m" def format(self, record): color = self._COLORS.get(record.levelno, self._RESET) t = self.formatTime(record, "%H:%M:%S") return f"{self._BOLD}{t}{self._RESET} {color}{record.levelname:<8}{self._RESET} {record.getMessage()}" run_id = datetime.now().strftime("%Y%m%d_%H%M%S") out_dir = OUT_ROOT / f"classification_{run_id}" out_dir.mkdir(parents=True, exist_ok=True) _log = logging.getLogger("clf") _log.setLevel(logging.DEBUG) _h = logging.StreamHandler(sys.stdout); _h.setFormatter(_ColorFormatter()); _log.addHandler(_h) _f = logging.FileHandler(out_dir / "run.log") _f.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S")) _log.addHandler(_f) _log.info("=" * 60) _log.info(f"Run ID : {run_id}") _log.info(f"Results : {out_dir}") _log.info("=" * 60) # ------------------------------------------------------------------ # 1. Load experiments and auto-label # ------------------------------------------------------------------ def load_params(sim_dir: Path) -> dict | None: """Read process parameters from parameters.json.""" pjson = sim_dir / "parameters.json" if not pjson.exists(): return None try: raw = __import__("json").loads(pjson.read_text()) return { "laser_power": float(raw["laser_power"]["value"]), "scan_speed": float(raw["scan_speed_x"]["value"]), "laser_spot_size": float(raw["laser_spot_size"]["value"]), "substrate_temperature": float(raw["substrate_temperature"]["value"]), } except Exception: return None def melt_depth(sim_dir: Path, n_stable: int) -> float | None: """Mean melt-pool depth (zmax − zmin) over the last n_stable valid rows. Rows where any value |v| > 1e30 are Initial Emptiness sentinels → excluded. """ dat = sim_dir / "monitor" / "position-bounds_melt.dat" if not dat.exists(): return None try: b = np.loadtxt(dat, delimiter=",") if b.ndim == 1: b = b.reshape(1, -1) b = b[~np.any(np.abs(b) > 1e30, axis=1)] # drop Initial Emptiness rows if len(b) < 10: return None depth = (b[-n_stable:, 5] - b[-n_stable:, 4]).mean() # zmax - zmin return depth if depth > 0 else None except Exception: return None all_sims = [] for data_dir in DATA_DIRS: sims = sorted(data_dir.iterdir()) if data_dir.is_dir() else [] _log.info(f"Scanning {data_dir} → {len(sims)} dirs") all_sims.extend(sims) _log.info(f"Total simulation directories: {len(all_sims)}") X_list, depth_list, names = [], [], [] skipped = 0 for sim_dir in all_sims: if not sim_dir.is_dir(): continue params = load_params(sim_dir) if params is None: skipped += 1; continue d = melt_depth(sim_dir, N_STABLE) if d is None: skipped += 1; continue X_list.append(list(params.values())) depth_list.append(d) names.append(sim_dir.name) _log.info(f"Valid experiments: {len(X_list)} (skipped {skipped})") X_all = np.array(X_list) depths_all = np.array(depth_list) median_depth = np.median(depths_all) y_all = (depths_all > median_depth).astype(int) _log.info(f"Depth threshold (median): {median_depth*1e6:.2f} µm") _log.info(f"Keyhole: {y_all.sum()} Conduction: {(y_all==0).sum()}") # ------------------------------------------------------------------ # 2. Balance classes (undersample majority) then optionally subset # ------------------------------------------------------------------ rng = random.Random(RANDOM_SEED) kh_idx = np.where(y_all == 1)[0].tolist() cd_idx = np.where(y_all == 0)[0].tolist() n_bal = min(len(kh_idx), len(cd_idx)) rng.shuffle(kh_idx); rng.shuffle(cd_idx) balanced_idx = sorted(kh_idx[:n_bal] + cd_idx[:n_bal]) X_bal = X_all[balanced_idx] y_bal = y_all[balanced_idx] _log.info(f"After balancing: {len(y_bal)} experiments ({n_bal} Keyhole + {n_bal} Conduction)") if N_SUBSET is not None and N_SUBSET < len(y_bal): # Stratified subsample: N_SUBSET/2 from each class n_each = N_SUBSET // 2 kh_sub = [i for i in balanced_idx if y_all[i] == 1][:n_each] cd_sub = [i for i in balanced_idx if y_all[i] == 0][:n_each] sub_idx = sorted(kh_sub + cd_sub) X = X_all[sub_idx] y = y_all[sub_idx] _log.info(f"Reviewer subset: {len(y)} experiments ({n_each} Keyhole + {n_each} Conduction)") else: X, y = X_bal, y_bal _log.info("Using full balanced dataset") # ------------------------------------------------------------------ # 3. Model definitions # ------------------------------------------------------------------ def make_models(): return [ make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)), make_pipeline(StandardScaler(), RandomForestClassifier(n_estimators=200, random_state=RANDOM_SEED)), make_pipeline(StandardScaler(), SVC(kernel="rbf", probability=True, random_state=RANDOM_SEED)), ] # ------------------------------------------------------------------ # 4. LOO cross-validation # ------------------------------------------------------------------ splits = list(LeaveOneOut().split(X)) n_folds = len(splits) y_preds = {} for name, base_pipe in zip(MODEL_NAMES, make_models()): preds = np.empty(n_folds, dtype=int) correct = 0 _log.info(f"[{name}] LOO CV ({n_folds} folds)") for fold, (train_idx, test_idx) in enumerate(splits): pipe = clone(base_pipe) pipe.fit(X[train_idx], y[train_idx]) preds[test_idx] = pipe.predict(X[test_idx]) correct += int(preds[test_idx[0]] == y[test_idx[0]]) if (fold + 1) % 10 == 0 or fold == n_folds - 1: _log.info(f" fold {fold+1:3d}/{n_folds} running acc = {correct/(fold+1):.3f}") _log.info(f"[{name}] Final LOO accuracy: {(preds==y).mean():.3f}") y_preds[name] = preds # ------------------------------------------------------------------ # 5. Fit on full subset for importance plots # ------------------------------------------------------------------ _log.info("Fitting on full subset for feature importance ...") fitted = {} for name, pipe in zip(MODEL_NAMES, make_models()): pipe.fit(X, y) fitted[name] = pipe def feature_importances(name, pipe): if name == "LogReg": return pipe.named_steps["logisticregression"].coef_[0] if name == "RandomForest": return pipe.named_steps["randomforestclassifier"].feature_importances_ res = permutation_importance(pipe, X, y, n_repeats=30, random_state=0, scoring="accuracy") imp = res.importances_mean return imp / (np.abs(imp).max() or 1) # ------------------------------------------------------------------ # 6. Plots — 2 rows × 3 columns # ------------------------------------------------------------------ _log.info("Generating plots ...") fig, axes = plt.subplots(2, 3, figsize=(13, 8)) for col, name in enumerate(MODEL_NAMES): acc = (y_preds[name] == y).mean() ConfusionMatrixDisplay.from_predictions( y, y_preds[name], display_labels=["Conduction", "Keyhole"], cmap="Blues", ax=axes[0, col], colorbar=False, ) axes[0, col].set_title(f"{name} (LOO acc={acc:.3f})") imp = feature_importances(name, fitted[name]) colors = ["#e06c75" if v < 0 else "#61afef" for v in imp] axes[1, col].barh(INPUT_PARAMS, imp, color=colors) axes[1, col].axvline(0, color="k", lw=0.6) xlabel = ("Standardised coef. (+ → Keyhole)" if name == "LogReg" else "Mean decrease in impurity" if name == "RandomForest" else "Permutation importance (norm.)") axes[1, col].set_xlabel(xlabel) axes[1, col].set_title(f"{name} — input relevance") subset_note = f"N={len(y)} (reviewer subset)" if N_SUBSET else f"N={len(y)} (full balanced)" plt.suptitle( f"LOO confusion matrices and input relevance — Keyhole vs Conduction [{subset_note}]", y=1.01, ) plt.tight_layout() plot_path = out_dir / "classification_diagnostics.png" plt.savefig(plot_path, dpi=150, bbox_inches="tight") _log.info(f"Plot saved → {plot_path}") plt.show() _log.info("Done.")