File size: 9,868 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
"""
Example 1 — Regression: Process Parameters → Steady-State Melt-Pool Width

Three models compared via leave-one-out cross-validation:
  1. Ridge          (linear baseline)
  2. PolyRidge-2    (degree-2 polynomial features + Ridge)
  3. GPR            (RBF + white-noise kernel, uncertainty-aware)

Target: mean melt-pool width (ymax − ymin) over the last N_STABLE valid
timesteps of monitor/position-bounds_melt.dat.
Rows with sentinel values (|val| > 1e30) are excluded (Initial Emptiness).

Set N_SUBSET to a small number (e.g. 30) for a quick reviewer run.
Set N_SUBSET = None to use the full dataset.

Outputs saved to runs/regression_<timestamp>/:
  regression_diagnostics.png   — LOO parity plots + feature relevance
  run.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.gaussian_process import GaussianProcessRegressor
from sklearn.gaussian_process.kernels import RBF, WhiteKernel
from sklearn.inspection import permutation_importance
from sklearn.linear_model import Ridge
from sklearn.metrics import r2_score
from sklearn.model_selection import LeaveOneOut
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
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 width estimate
RANDOM_SEED = 42
INPUT_PARAMS = ["laser_power", "scan_speed", "laser_spot_size", "substrate_temp"]
MODEL_NAMES  = ["Ridge", "PolyRidge-2", "GPR"]

# ------------------------------------------------------------------
# Logger
# ------------------------------------------------------------------

class _ColorFormatter(logging.Formatter):
    _COLORS = {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"regression_{run_id}"
out_dir.mkdir(parents=True, exist_ok=True)

log = logging.getLogger("reg")
log.setLevel(logging.DEBUG)
_ch = logging.StreamHandler(sys.stdout); _ch.setFormatter(_ColorFormatter()); log.addHandler(_ch)
_fh = logging.FileHandler(out_dir / "run.log")
_fh.setFormatter(logging.Formatter("%(asctime)s  %(levelname)-8s  %(message)s", datefmt="%H:%M:%S"))
log.addHandler(_fh)

log.info("=" * 60)
log.info(f"Run ID  : {run_id}")
log.info(f"Results : {out_dir}")
log.info("=" * 60)

# ------------------------------------------------------------------
# 1. Load experiments
# ------------------------------------------------------------------

def load_params(sim_dir: Path) -> dict | None:
    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_width(sim_dir: Path, n_stable: int) -> float | None:
    """Mean melt-pool width (ymax − ymin) over the last n_stable valid rows.
    Rows where any |value| > 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
        width = (b[-n_stable:, 3] - b[-n_stable:, 2]).mean()   # ymax - ymin
        return width if width > 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, y_list, 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
    w = melt_width(sim_dir, N_STABLE)
    if w is None:
        skipped += 1; continue
    X_list.append(list(params.values()))
    y_list.append(w)

log.info(f"Valid experiments: {len(X_list)}  (skipped {skipped})")

X_all = np.array(X_list)
y_all = np.array(y_list)
log.info(f"Width range: [{y_all.min()*1e6:.1f}, {y_all.max()*1e6:.1f}] µm")

# ------------------------------------------------------------------
# 2. Optional subset for reviewer
# ------------------------------------------------------------------

if N_SUBSET is not None and N_SUBSET < len(X_all):
    rng = random.Random(RANDOM_SEED)
    idx = list(range(len(X_all)))
    rng.shuffle(idx)
    idx = sorted(idx[:N_SUBSET])
    X, y = X_all[idx], y_all[idx]
    log.info(f"Reviewer subset: {len(y)} experiments")
else:
    X, y = X_all, y_all
    log.info("Using full dataset")

# ------------------------------------------------------------------
# 3. Models
# ------------------------------------------------------------------

def make_models():
    return [
        make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
        make_pipeline(PolynomialFeatures(degree=2, include_bias=False),
                      StandardScaler(), Ridge(alpha=1.0)),
        make_pipeline(StandardScaler(), GaussianProcessRegressor(
            kernel=RBF() + WhiteKernel(), normalize_y=True, n_restarts_optimizer=5,
        )),
    ]

# ------------------------------------------------------------------
# 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)
    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])
        if (fold + 1) % 10 == 0 or fold == n_folds - 1:
            running_r2 = r2_score(y[:fold+1], preds[:fold+1])
            log.info(f"  fold {fold+1:3d}/{n_folds}  running R² = {running_r2:.3f}")

    log.info(f"[{name}] Final LOO R²: {r2_score(y, preds):.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 == "Ridge":
        return pipe.named_steps["ridge"].coef_
    if name == "PolyRidge-2":
        poly   = pipe.named_steps["polynomialfeatures"]
        coef   = pipe.named_steps["ridge"].coef_
        powers = poly.powers_
        imp = np.array([np.sum(np.abs(coef[powers[:, i] > 0])) for i in range(X.shape[1])])
        return imp / imp.max()
    result = permutation_importance(pipe, X, y, n_repeats=30, random_state=0)
    imp = result.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))
colors = [plt.get_cmap("tab20")(i / len(y)) for i in range(len(y))]

for col, name in enumerate(MODEL_NAMES):
    yt, yp = y * 1e6, y_preds[name] * 1e6
    r2 = r2_score(y, y_preds[name])

    ax = axes[0, col]
    ax.scatter(yt, yp, s=35, alpha=0.85, color=colors)
    lo, hi = min(yt.min(), yp.min()), max(yt.max(), yp.max())
    ax.plot([lo, hi], [lo, hi], "k--", lw=0.8)
    ax.set_title(f"{name}  (R²={r2:.3f})")
    ax.set_xlabel("True width (µm)")
    if col == 0:
        ax.set_ylabel("Predicted width (µm)")

    ax = axes[1, col]
    imp = feature_importances(name, fitted[name])
    bar_colors = ["#e06c75" if v < 0 else "#61afef" for v in imp]
    ax.barh(INPUT_PARAMS, imp, color=bar_colors)
    ax.axvline(0, color="k", lw=0.6)
    ax.set_xlabel("Standardised coef." if name != "GPR" else "Permutation importance (norm.)")
    ax.set_title(f"{name} — input relevance")

subset_note = f"N={len(y)} (reviewer subset)" if N_SUBSET else f"N={len(y)} (full)"
plt.suptitle(
    f"LOO parity and input relevance — steady-state melt-pool width  [{subset_note}]",
    y=1.01,
)
plt.tight_layout()

plot_path = out_dir / "regression_diagnostics.png"
plt.savefig(plot_path, dpi=150, bbox_inches="tight")
log.info(f"Plot saved → {plot_path}")
plt.show()
log.info("Done.")