File size: 10,884 Bytes
8550bd0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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_<timestamp>/:
  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.")