ioandanielc commited on
Commit
8550bd0
·
verified ·
1 Parent(s): fcb6b7f

Upload folder using huggingface_hub

Browse files
examples/README.md ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Running the Examples
2
+
3
+ **You do not need to download the full dataset.** Each script has a cap (`N_SUBSET` or
4
+ `MAX_IMAGES`) that limits how many simulations or images are loaded. Download any small
5
+ subset of simulation directories and point `DATA_DIRS` at them — the scripts will use only
6
+ what is available.
7
+
8
+ ## Requirements
9
+
10
+ ```bash
11
+ pip install numpy pillow scikit-learn matplotlib torch
12
+ ```
13
+
14
+ ## Expected data layout
15
+
16
+ Each simulation directory must contain:
17
+
18
+ ```
19
+ <sim_dir>/
20
+ parameters.json # process parameters
21
+ monitor/position-bounds_melt.dat # melt-pool bounds (regression + classification)
22
+ frames.csv # frame labels (generation only)
23
+ frames/side/<frame>.png # side-profile images (generation only)
24
+ ```
25
+
26
+ Point `DATA_DIRS` in each script at one or more parent directories that hold these
27
+ simulation folders.
28
+
29
+ ## Regression — Melt-Pool Width Prediction
30
+
31
+ ```bash
32
+ python example_regression.py
33
+ ```
34
+
35
+ - **Reviewer shortcut:** set `N_SUBSET = 30` (already the default) to use only the first
36
+ 30 simulations found — ~1 min on CPU. Set `None` to use all.
37
+ - Predicts steady-state melt-pool width from four process parameters.
38
+ - Results (parity plots + feature importance) are saved to `runs/regression_<timestamp>/`.
39
+
40
+ ## Classification — Keyhole vs Conduction
41
+
42
+ ```bash
43
+ python example_classification.py
44
+ ```
45
+
46
+ - **Reviewer shortcut:** set `N_SUBSET = 30` (already the default) to use only the first
47
+ 30 simulations found — ~1 min on CPU. Set `None` to use all.
48
+ - Labels are derived automatically from simulation output — no manual annotation needed.
49
+ - Results (confusion matrices + feature importance) are saved to `runs/classification_<timestamp>/`.
50
+
51
+ ## Generation — Unconditional VAE on Side Profiles
52
+
53
+ ```bash
54
+ python example_generation.py
55
+ ```
56
+
57
+ - **Reviewer shortcut:** set `MAX_IMAGES = 500` (already the default) to cap the number of
58
+ frames loaded — ~2 min on CPU. Set `None` to use all images.
59
+ - Only frames labeled Keyhole or Conduction are used; Initial Emptiness and Forming Phase are excluded.
60
+ - Results (sample grids, reconstructions, loss curve) are saved to `runs/generation_<timestamp>/`.
examples/example_classification.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example 2 — Classification: Keyhole vs Conduction Mode
3
+
4
+ Binary classifier predicting melting regime from four process parameters.
5
+
6
+ Labels are derived automatically from melt-pool depth (zmax − zmin) in
7
+ monitor/position-bounds_melt.dat: experiments whose steady-state depth
8
+ exceeds the dataset median are labeled Keyhole (1), the rest Conduction (0).
9
+ Rows with sentinel values (|val| > 1e30) are tagged "Initial Emptiness" and
10
+ excluded from depth computation. The dataset is then balanced via random
11
+ undersampling of the majority class before any ML step.
12
+
13
+ Three models evaluated via leave-one-out cross-validation:
14
+ 1. Logistic Regression
15
+ 2. Random Forest
16
+ 3. SVM (RBF kernel)
17
+
18
+ Set N_SUBSET to a small number (e.g. 30) so a reviewer can run this quickly.
19
+ Set N_SUBSET = None to use the full balanced dataset.
20
+
21
+ Outputs saved to runs/classification_<timestamp>/:
22
+ classification_diagnostics.png — LOO confusion matrices + feature relevance
23
+ run.log — full training log
24
+
25
+ This is a proof-of-concept, not a benchmark.
26
+ """
27
+
28
+ import logging
29
+ import random
30
+ import sys
31
+ from datetime import datetime
32
+ from pathlib import Path
33
+
34
+ import numpy as np
35
+ from sklearn.base import clone
36
+ from sklearn.ensemble import RandomForestClassifier
37
+ from sklearn.inspection import permutation_importance
38
+ from sklearn.linear_model import LogisticRegression
39
+ from sklearn.metrics import ConfusionMatrixDisplay
40
+ from sklearn.model_selection import LeaveOneOut
41
+ from sklearn.pipeline import make_pipeline
42
+ from sklearn.preprocessing import StandardScaler
43
+ from sklearn.svm import SVC
44
+ import matplotlib.pyplot as plt
45
+
46
+ # ------------------------------------------------------------------
47
+ # Config ← edit DATA_DIRS to point at your data directories
48
+ # ------------------------------------------------------------------
49
+
50
+ DATA_DIRS = [
51
+ Path(__file__).parent.parent / "rnl" / "final_data_processed",
52
+ Path(__file__).parent.parent / "rnl" / "lrz_data_new_format",
53
+ ]
54
+ OUT_ROOT = Path(__file__).parent.parent / "runs"
55
+
56
+ N_SUBSET = 30 # reviewer-friendly subset size (None = full dataset)
57
+ N_STABLE = 50 # last N valid timesteps for steady-state depth estimate
58
+ RANDOM_SEED = 42
59
+
60
+ INPUT_PARAMS = ["laser_power", "scan_speed", "laser_spot_size", "substrate_temp"]
61
+ MODEL_NAMES = ["LogReg", "RandomForest", "SVM-RBF"]
62
+
63
+ # ------------------------------------------------------------------
64
+ # Logger
65
+ # ------------------------------------------------------------------
66
+
67
+ class _ColorFormatter(logging.Formatter):
68
+ _COLORS = {logging.DEBUG: "\033[37m", logging.INFO: "\033[32m",
69
+ logging.WARNING: "\033[33m", logging.ERROR: "\033[31m"}
70
+ _RESET = "\033[0m"; _BOLD = "\033[1m"
71
+
72
+ def format(self, record):
73
+ color = self._COLORS.get(record.levelno, self._RESET)
74
+ t = self.formatTime(record, "%H:%M:%S")
75
+ return f"{self._BOLD}{t}{self._RESET} {color}{record.levelname:<8}{self._RESET} {record.getMessage()}"
76
+
77
+
78
+ run_id = datetime.now().strftime("%Y%m%d_%H%M%S")
79
+ out_dir = OUT_ROOT / f"classification_{run_id}"
80
+ out_dir.mkdir(parents=True, exist_ok=True)
81
+
82
+ _log = logging.getLogger("clf")
83
+ _log.setLevel(logging.DEBUG)
84
+ _h = logging.StreamHandler(sys.stdout); _h.setFormatter(_ColorFormatter()); _log.addHandler(_h)
85
+ _f = logging.FileHandler(out_dir / "run.log")
86
+ _f.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S"))
87
+ _log.addHandler(_f)
88
+
89
+ _log.info("=" * 60)
90
+ _log.info(f"Run ID : {run_id}")
91
+ _log.info(f"Results : {out_dir}")
92
+ _log.info("=" * 60)
93
+
94
+ # ------------------------------------------------------------------
95
+ # 1. Load experiments and auto-label
96
+ # ------------------------------------------------------------------
97
+
98
+ def load_params(sim_dir: Path) -> dict | None:
99
+ """Read process parameters from parameters.json."""
100
+ pjson = sim_dir / "parameters.json"
101
+ if not pjson.exists():
102
+ return None
103
+ try:
104
+ raw = __import__("json").loads(pjson.read_text())
105
+ return {
106
+ "laser_power": float(raw["laser_power"]["value"]),
107
+ "scan_speed": float(raw["scan_speed_x"]["value"]),
108
+ "laser_spot_size": float(raw["laser_spot_size"]["value"]),
109
+ "substrate_temperature": float(raw["substrate_temperature"]["value"]),
110
+ }
111
+ except Exception:
112
+ return None
113
+
114
+
115
+ def melt_depth(sim_dir: Path, n_stable: int) -> float | None:
116
+ """Mean melt-pool depth (zmax − zmin) over the last n_stable valid rows.
117
+ Rows where any value |v| > 1e30 are Initial Emptiness sentinels → excluded.
118
+ """
119
+ dat = sim_dir / "monitor" / "position-bounds_melt.dat"
120
+ if not dat.exists():
121
+ return None
122
+ try:
123
+ b = np.loadtxt(dat, delimiter=",")
124
+ if b.ndim == 1:
125
+ b = b.reshape(1, -1)
126
+ b = b[~np.any(np.abs(b) > 1e30, axis=1)] # drop Initial Emptiness rows
127
+ if len(b) < 10:
128
+ return None
129
+ depth = (b[-n_stable:, 5] - b[-n_stable:, 4]).mean() # zmax - zmin
130
+ return depth if depth > 0 else None
131
+ except Exception:
132
+ return None
133
+
134
+
135
+ all_sims = []
136
+ for data_dir in DATA_DIRS:
137
+ sims = sorted(data_dir.iterdir()) if data_dir.is_dir() else []
138
+ _log.info(f"Scanning {data_dir} → {len(sims)} dirs")
139
+ all_sims.extend(sims)
140
+ _log.info(f"Total simulation directories: {len(all_sims)}")
141
+
142
+ X_list, depth_list, names = [], [], []
143
+ skipped = 0
144
+ for sim_dir in all_sims:
145
+ if not sim_dir.is_dir():
146
+ continue
147
+ params = load_params(sim_dir)
148
+ if params is None:
149
+ skipped += 1; continue
150
+ d = melt_depth(sim_dir, N_STABLE)
151
+ if d is None:
152
+ skipped += 1; continue
153
+ X_list.append(list(params.values()))
154
+ depth_list.append(d)
155
+ names.append(sim_dir.name)
156
+
157
+ _log.info(f"Valid experiments: {len(X_list)} (skipped {skipped})")
158
+
159
+ X_all = np.array(X_list)
160
+ depths_all = np.array(depth_list)
161
+ median_depth = np.median(depths_all)
162
+ y_all = (depths_all > median_depth).astype(int)
163
+
164
+ _log.info(f"Depth threshold (median): {median_depth*1e6:.2f} µm")
165
+ _log.info(f"Keyhole: {y_all.sum()} Conduction: {(y_all==0).sum()}")
166
+
167
+ # ------------------------------------------------------------------
168
+ # 2. Balance classes (undersample majority) then optionally subset
169
+ # ------------------------------------------------------------------
170
+
171
+ rng = random.Random(RANDOM_SEED)
172
+
173
+ kh_idx = np.where(y_all == 1)[0].tolist()
174
+ cd_idx = np.where(y_all == 0)[0].tolist()
175
+ n_bal = min(len(kh_idx), len(cd_idx))
176
+
177
+ rng.shuffle(kh_idx); rng.shuffle(cd_idx)
178
+ balanced_idx = sorted(kh_idx[:n_bal] + cd_idx[:n_bal])
179
+
180
+ X_bal = X_all[balanced_idx]
181
+ y_bal = y_all[balanced_idx]
182
+ _log.info(f"After balancing: {len(y_bal)} experiments ({n_bal} Keyhole + {n_bal} Conduction)")
183
+
184
+ if N_SUBSET is not None and N_SUBSET < len(y_bal):
185
+ # Stratified subsample: N_SUBSET/2 from each class
186
+ n_each = N_SUBSET // 2
187
+ kh_sub = [i for i in balanced_idx if y_all[i] == 1][:n_each]
188
+ cd_sub = [i for i in balanced_idx if y_all[i] == 0][:n_each]
189
+ sub_idx = sorted(kh_sub + cd_sub)
190
+ X = X_all[sub_idx]
191
+ y = y_all[sub_idx]
192
+ _log.info(f"Reviewer subset: {len(y)} experiments ({n_each} Keyhole + {n_each} Conduction)")
193
+ else:
194
+ X, y = X_bal, y_bal
195
+ _log.info("Using full balanced dataset")
196
+
197
+ # ------------------------------------------------------------------
198
+ # 3. Model definitions
199
+ # ------------------------------------------------------------------
200
+
201
+ def make_models():
202
+ return [
203
+ make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
204
+ make_pipeline(StandardScaler(), RandomForestClassifier(n_estimators=200, random_state=RANDOM_SEED)),
205
+ make_pipeline(StandardScaler(), SVC(kernel="rbf", probability=True, random_state=RANDOM_SEED)),
206
+ ]
207
+
208
+ # ------------------------------------------------------------------
209
+ # 4. LOO cross-validation
210
+ # ------------------------------------------------------------------
211
+
212
+ splits = list(LeaveOneOut().split(X))
213
+ n_folds = len(splits)
214
+ y_preds = {}
215
+
216
+ for name, base_pipe in zip(MODEL_NAMES, make_models()):
217
+ preds = np.empty(n_folds, dtype=int)
218
+ correct = 0
219
+ _log.info(f"[{name}] LOO CV ({n_folds} folds)")
220
+
221
+ for fold, (train_idx, test_idx) in enumerate(splits):
222
+ pipe = clone(base_pipe)
223
+ pipe.fit(X[train_idx], y[train_idx])
224
+ preds[test_idx] = pipe.predict(X[test_idx])
225
+ correct += int(preds[test_idx[0]] == y[test_idx[0]])
226
+ if (fold + 1) % 10 == 0 or fold == n_folds - 1:
227
+ _log.info(f" fold {fold+1:3d}/{n_folds} running acc = {correct/(fold+1):.3f}")
228
+
229
+ _log.info(f"[{name}] Final LOO accuracy: {(preds==y).mean():.3f}")
230
+ y_preds[name] = preds
231
+
232
+ # ------------------------------------------------------------------
233
+ # 5. Fit on full subset for importance plots
234
+ # ------------------------------------------------------------------
235
+
236
+ _log.info("Fitting on full subset for feature importance ...")
237
+ fitted = {}
238
+ for name, pipe in zip(MODEL_NAMES, make_models()):
239
+ pipe.fit(X, y)
240
+ fitted[name] = pipe
241
+
242
+
243
+ def feature_importances(name, pipe):
244
+ if name == "LogReg":
245
+ return pipe.named_steps["logisticregression"].coef_[0]
246
+ if name == "RandomForest":
247
+ return pipe.named_steps["randomforestclassifier"].feature_importances_
248
+ res = permutation_importance(pipe, X, y, n_repeats=30, random_state=0, scoring="accuracy")
249
+ imp = res.importances_mean
250
+ return imp / (np.abs(imp).max() or 1)
251
+
252
+ # ------------------------------------------------------------------
253
+ # 6. Plots — 2 rows × 3 columns
254
+ # ------------------------------------------------------------------
255
+
256
+ _log.info("Generating plots ...")
257
+ fig, axes = plt.subplots(2, 3, figsize=(13, 8))
258
+
259
+ for col, name in enumerate(MODEL_NAMES):
260
+ acc = (y_preds[name] == y).mean()
261
+
262
+ ConfusionMatrixDisplay.from_predictions(
263
+ y, y_preds[name],
264
+ display_labels=["Conduction", "Keyhole"],
265
+ cmap="Blues", ax=axes[0, col], colorbar=False,
266
+ )
267
+ axes[0, col].set_title(f"{name} (LOO acc={acc:.3f})")
268
+
269
+ imp = feature_importances(name, fitted[name])
270
+ colors = ["#e06c75" if v < 0 else "#61afef" for v in imp]
271
+ axes[1, col].barh(INPUT_PARAMS, imp, color=colors)
272
+ axes[1, col].axvline(0, color="k", lw=0.6)
273
+ xlabel = ("Standardised coef. (+ → Keyhole)" if name == "LogReg" else
274
+ "Mean decrease in impurity" if name == "RandomForest" else
275
+ "Permutation importance (norm.)")
276
+ axes[1, col].set_xlabel(xlabel)
277
+ axes[1, col].set_title(f"{name} — input relevance")
278
+
279
+ subset_note = f"N={len(y)} (reviewer subset)" if N_SUBSET else f"N={len(y)} (full balanced)"
280
+ plt.suptitle(
281
+ f"LOO confusion matrices and input relevance — Keyhole vs Conduction [{subset_note}]",
282
+ y=1.01,
283
+ )
284
+ plt.tight_layout()
285
+
286
+ plot_path = out_dir / "classification_diagnostics.png"
287
+ plt.savefig(plot_path, dpi=150, bbox_inches="tight")
288
+ _log.info(f"Plot saved → {plot_path}")
289
+ plt.show()
290
+ _log.info("Done.")
examples/example_generation.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example 3 — Unconditional VAE: Melt-Pool Side Profiles
3
+
4
+ Trains a minimal convolutional VAE on side-profile images and generates
5
+ new samples. No conditioning on process parameters.
6
+
7
+ Images are loaded from frames/side/ — already border-recolored by the
8
+ dataset pipeline. Only frames labeled Keyhole or Conduction are used
9
+ (Initial Emptiness and Forming Phase are excluded).
10
+
11
+ Architecture: 3×32×64 → latent z (dim=16) → 3×32×64
12
+
13
+ Set MAX_IMAGES to limit dataset size for a quick reviewer run.
14
+ Set MAX_IMAGES = None to use all available images.
15
+
16
+ Outputs saved to runs/generation_<timestamp>/:
17
+ generation_epoch_NNN.png — sample grid every SAMPLE_EVERY epochs
18
+ generation_loss.png — training loss curve
19
+ generation_reconstructions.png
20
+ generation_samples.png
21
+ run.log
22
+
23
+ This is a proof-of-concept, not a benchmark.
24
+ """
25
+
26
+ import csv
27
+ import logging
28
+ import sys
29
+ from datetime import datetime
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import torch
34
+ import torch.nn as nn
35
+ from torch.utils.data import DataLoader, TensorDataset
36
+ from PIL import Image as PILImage
37
+ import matplotlib.pyplot as plt
38
+
39
+ # ------------------------------------------------------------------
40
+ # Config ← edit DATA_DIRS to point at your data directories
41
+ # ------------------------------------------------------------------
42
+
43
+ DATA_DIRS = [
44
+ Path(__file__).parent.parent / "rnl" / "final_data_processed",
45
+ Path(__file__).parent.parent / "rnl" / "lrz_data_new_format",
46
+ ]
47
+ OUT_ROOT = Path(__file__).parent.parent / "runs"
48
+
49
+ MAX_IMAGES = 500 # reviewer-friendly cap (None = all images)
50
+ IMG_W = 64
51
+ IMG_H = 32
52
+ LATENT_DIM = 16
53
+ BATCH_SIZE = 64
54
+ EPOCHS = 50
55
+ LR = 1e-3
56
+ SAMPLE_EVERY = 10
57
+ RED_WEIGHT = 50.0
58
+ RANDOM_SEED = 42
59
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
60
+
61
+ VALID_LABELS = {"Keyhole", "Conduction"}
62
+
63
+ # ------------------------------------------------------------------
64
+ # Logger
65
+ # ------------------------------------------------------------------
66
+
67
+ class _ColorFormatter(logging.Formatter):
68
+ _COLORS = {logging.INFO: "\033[32m", logging.WARNING: "\033[33m", logging.ERROR: "\033[31m"}
69
+ _RESET = "\033[0m"; _BOLD = "\033[1m"
70
+
71
+ def format(self, record):
72
+ color = self._COLORS.get(record.levelno, self._RESET)
73
+ t = self.formatTime(record, "%H:%M:%S")
74
+ return f"{self._BOLD}{t}{self._RESET} {color}{record.levelname:<8}{self._RESET} {record.getMessage()}"
75
+
76
+
77
+ run_id = datetime.now().strftime("%Y%m%d_%H%M%S")
78
+ out_dir = OUT_ROOT / f"generation_{run_id}"
79
+ out_dir.mkdir(parents=True, exist_ok=True)
80
+
81
+ log = logging.getLogger("vae")
82
+ log.setLevel(logging.DEBUG)
83
+ _ch = logging.StreamHandler(sys.stdout); _ch.setFormatter(_ColorFormatter()); log.addHandler(_ch)
84
+ _fh = logging.FileHandler(out_dir / "run.log")
85
+ _fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S"))
86
+ log.addHandler(_fh)
87
+
88
+ log.info("=" * 60)
89
+ log.info(f"Run ID : {run_id}")
90
+ log.info(f"Results : {out_dir}")
91
+ log.info(f"Device : {DEVICE}")
92
+ log.info(f"Resolution: {IMG_W}×{IMG_H}")
93
+ log.info("=" * 60)
94
+
95
+ # ------------------------------------------------------------------
96
+ # 1. Collect valid image paths from frames.csv
97
+ # ------------------------------------------------------------------
98
+
99
+ img_paths = []
100
+ for data_dir in DATA_DIRS:
101
+ if not data_dir.is_dir():
102
+ continue
103
+ for sim_dir in sorted(data_dir.iterdir()):
104
+ frames_csv = sim_dir / "frames.csv"
105
+ if not frames_csv.exists():
106
+ continue
107
+ for row in csv.DictReader(frames_csv.open()):
108
+ if row["label"] not in VALID_LABELS:
109
+ continue
110
+ path = sim_dir / row["side_filename"]
111
+ if path.exists():
112
+ img_paths.append(path)
113
+
114
+ import random
115
+ rng = random.Random(RANDOM_SEED)
116
+ rng.shuffle(img_paths)
117
+ if MAX_IMAGES is not None:
118
+ img_paths = img_paths[:MAX_IMAGES]
119
+
120
+ log.info(f"Found {len(img_paths)} valid side-profile frames")
121
+
122
+ # ------------------------------------------------------------------
123
+ # 2. Load images (already border-recolored — just resize)
124
+ # ------------------------------------------------------------------
125
+
126
+ log.info("Loading images ...")
127
+ imgs = []
128
+ for path in img_paths:
129
+ pil = PILImage.open(path).convert("RGB").resize((IMG_W, IMG_H), PILImage.Resampling.BILINEAR)
130
+ imgs.append(np.array(pil))
131
+
132
+ data = torch.from_numpy(
133
+ np.stack(imgs).astype(np.float32) / 255.0
134
+ ).permute(0, 3, 1, 2) # N×3×H×W
135
+
136
+ loader = DataLoader(TensorDataset(data), batch_size=BATCH_SIZE, shuffle=True, generator=torch.Generator().manual_seed(RANDOM_SEED))
137
+ log.info(f"Tensor shape: {tuple(data.shape)}")
138
+
139
+ # ------------------------------------------------------------------
140
+ # 3. Convolutional VAE (3×32×64 input)
141
+ #
142
+ # Encoder spatial progression (H×W):
143
+ # 3×32×64 → 32×16×32 → 64×8×16 → 128×4×8 → 256×2×4
144
+ # Flatten → 2048 → mu / logvar (dim=16)
145
+ # ------------------------------------------------------------------
146
+
147
+ class Encoder(nn.Module):
148
+ def __init__(self, latent_dim):
149
+ super().__init__()
150
+ self.conv = nn.Sequential(
151
+ nn.Conv2d(3, 32, 4, 2, 1), nn.ReLU(),
152
+ nn.Conv2d(32, 64, 4, 2, 1), nn.ReLU(),
153
+ nn.Conv2d(64, 128, 4, 2, 1), nn.ReLU(),
154
+ nn.Conv2d(128, 256, 4, 2, 1), nn.ReLU(),
155
+ )
156
+ self.fc_mu = nn.Linear(256 * 2 * 4, latent_dim)
157
+ self.fc_logvar = nn.Linear(256 * 2 * 4, latent_dim)
158
+
159
+ def forward(self, x):
160
+ h = self.conv(x).flatten(1)
161
+ return self.fc_mu(h), self.fc_logvar(h)
162
+
163
+
164
+ class Decoder(nn.Module):
165
+ def __init__(self, latent_dim):
166
+ super().__init__()
167
+ self.fc = nn.Linear(latent_dim, 256 * 2 * 4)
168
+ self.deconv = nn.Sequential(
169
+ nn.ConvTranspose2d(256, 128, 4, 2, 1), nn.ReLU(),
170
+ nn.ConvTranspose2d(128, 64, 4, 2, 1), nn.ReLU(),
171
+ nn.ConvTranspose2d(64, 32, 4, 2, 1), nn.ReLU(),
172
+ nn.ConvTranspose2d(32, 3, 4, 2, 1), nn.Sigmoid(),
173
+ )
174
+
175
+ def forward(self, z):
176
+ return self.deconv(self.fc(z).view(-1, 256, 2, 4))
177
+
178
+
179
+ class VAE(nn.Module):
180
+ def __init__(self, latent_dim):
181
+ super().__init__()
182
+ self.encoder = Encoder(latent_dim)
183
+ self.decoder = Decoder(latent_dim)
184
+
185
+ def reparameterise(self, mu, logvar):
186
+ return mu + (0.5 * logvar).exp() * torch.randn_like(mu)
187
+
188
+ def forward(self, x):
189
+ mu, logvar = self.encoder(x)
190
+ return self.decoder(self.reparameterise(mu, logvar)), mu, logvar
191
+
192
+
193
+ def vae_loss(recon, x, mu, logvar):
194
+ # Upweight melt-pool pixels (red channel dominant) so the VAE
195
+ # doesn't ignore the small pool region against the background.
196
+ mask = ((x[:, 0] > 0.5) & (x[:, 1] < 0.25) & (x[:, 2] < 0.25)).unsqueeze(1).float()
197
+ weights = 1.0 + (RED_WEIGHT - 1.0) * mask.expand_as(x)
198
+ recon_loss = (weights * (recon - x).pow(2)).sum()
199
+ kld = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp())
200
+ return recon_loss + kld
201
+
202
+ # ------------------------------------------------------------------
203
+ # 4. Train
204
+ # ------------------------------------------------------------------
205
+
206
+ torch.manual_seed(RANDOM_SEED)
207
+ model = VAE(LATENT_DIM).to(DEVICE)
208
+ opt = torch.optim.Adam(model.parameters(), lr=LR)
209
+ z_fixed = torch.randn(16, LATENT_DIM, device=DEVICE)
210
+ loss_log = []
211
+
212
+ log.info(f"Training VAE for {EPOCHS} epochs | {len(data)} images | batch={BATCH_SIZE}")
213
+
214
+ for epoch in range(1, EPOCHS + 1):
215
+ model.train()
216
+ total = 0.0
217
+ for (batch,) in loader:
218
+ batch = batch.to(DEVICE)
219
+ recon, mu, logvar = model(batch)
220
+ loss = vae_loss(recon, batch, mu, logvar)
221
+ opt.zero_grad(); loss.backward(); opt.step()
222
+ total += loss.item()
223
+
224
+ loss_per_img = total / len(data)
225
+ loss_log.append(loss_per_img)
226
+ log.info(f" epoch {epoch:3d}/{EPOCHS} loss/img: {loss_per_img:.4f}")
227
+
228
+ if epoch % SAMPLE_EVERY == 0:
229
+ model.eval()
230
+ with torch.no_grad():
231
+ samples = model.decoder(z_fixed).cpu().permute(0, 2, 3, 1).numpy()
232
+ fig, axes = plt.subplots(2, 8, figsize=(14, 4))
233
+ for i, ax in enumerate(axes.flat):
234
+ ax.imshow(samples[i]); ax.axis("off")
235
+ fig.suptitle(f"VAE samples — epoch {epoch}/{EPOCHS} (loss/img={loss_per_img:.4f})", fontsize=10)
236
+ plt.tight_layout()
237
+ path = out_dir / f"generation_epoch_{epoch:03d}.png"
238
+ plt.savefig(path, dpi=100); plt.close(fig)
239
+ log.info(f" → saved {path.name}")
240
+
241
+ # ------------------------------------------------------------------
242
+ # 5. Final plots
243
+ # ------------------------------------------------------------------
244
+
245
+ model.eval()
246
+ log.info("Generating final plots ...")
247
+
248
+ fig, ax = plt.subplots(figsize=(7, 3))
249
+ ax.plot(range(1, EPOCHS + 1), loss_log, lw=1.5)
250
+ ax.set_xlabel("Epoch"); ax.set_ylabel("Loss / image")
251
+ ax.set_title("VAE training loss")
252
+ plt.tight_layout()
253
+ plt.savefig(out_dir / "generation_loss.png", dpi=150); plt.close(fig)
254
+
255
+ N_SHOW = 8
256
+ with torch.no_grad():
257
+ originals = data[:N_SHOW].to(DEVICE)
258
+ recons, _, _ = model(originals)
259
+ originals = originals.cpu().permute(0, 2, 3, 1).numpy()
260
+ recons = recons.cpu().permute(0, 2, 3, 1).numpy()
261
+ samples = model.decoder(torch.randn(16, LATENT_DIM, device=DEVICE)).cpu().permute(0, 2, 3, 1).numpy()
262
+
263
+ fig, axes = plt.subplots(2, N_SHOW, figsize=(14, 3))
264
+ for i in range(N_SHOW):
265
+ axes[0, i].imshow(originals[i]); axes[0, i].axis("off")
266
+ axes[1, i].imshow(recons[i]); axes[1, i].axis("off")
267
+ axes[0, 0].set_ylabel("Real", rotation=0, labelpad=30, va="center")
268
+ axes[1, 0].set_ylabel("Recon", rotation=0, labelpad=30, va="center")
269
+ fig.suptitle("VAE reconstructions — melt-pool side profiles", fontsize=11)
270
+ plt.tight_layout()
271
+ plt.savefig(out_dir / "generation_reconstructions.png", dpi=150); plt.close(fig)
272
+
273
+ fig, axes = plt.subplots(2, 8, figsize=(14, 4))
274
+ for i, ax in enumerate(axes.flat):
275
+ ax.imshow(samples[i]); ax.axis("off")
276
+ fig.suptitle("Unconditional VAE samples — melt-pool side profiles", fontsize=11)
277
+ plt.tight_layout()
278
+ plt.savefig(out_dir / "generation_samples.png", dpi=150); plt.close(fig)
279
+
280
+ log.info(f"All outputs saved to {out_dir}")
281
+ log.info("Done.")
examples/example_regression.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Example 1 — Regression: Process Parameters → Steady-State Melt-Pool Width
3
+
4
+ Three models compared via leave-one-out cross-validation:
5
+ 1. Ridge (linear baseline)
6
+ 2. PolyRidge-2 (degree-2 polynomial features + Ridge)
7
+ 3. GPR (RBF + white-noise kernel, uncertainty-aware)
8
+
9
+ Target: mean melt-pool width (ymax − ymin) over the last N_STABLE valid
10
+ timesteps of monitor/position-bounds_melt.dat.
11
+ Rows with sentinel values (|val| > 1e30) are excluded (Initial Emptiness).
12
+
13
+ Set N_SUBSET to a small number (e.g. 30) for a quick reviewer run.
14
+ Set N_SUBSET = None to use the full dataset.
15
+
16
+ Outputs saved to runs/regression_<timestamp>/:
17
+ regression_diagnostics.png — LOO parity plots + feature relevance
18
+ run.log
19
+
20
+ This is a proof-of-concept, not a benchmark.
21
+ """
22
+
23
+ import logging
24
+ import random
25
+ import sys
26
+ from datetime import datetime
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ from sklearn.base import clone
31
+ from sklearn.gaussian_process import GaussianProcessRegressor
32
+ from sklearn.gaussian_process.kernels import RBF, WhiteKernel
33
+ from sklearn.inspection import permutation_importance
34
+ from sklearn.linear_model import Ridge
35
+ from sklearn.metrics import r2_score
36
+ from sklearn.model_selection import LeaveOneOut
37
+ from sklearn.pipeline import make_pipeline
38
+ from sklearn.preprocessing import PolynomialFeatures, StandardScaler
39
+ import matplotlib.pyplot as plt
40
+
41
+ # ------------------------------------------------------------------
42
+ # Config ← edit DATA_DIRS to point at your data directories
43
+ # ------------------------------------------------------------------
44
+
45
+ DATA_DIRS = [
46
+ Path(__file__).parent.parent / "rnl" / "final_data_processed",
47
+ Path(__file__).parent.parent / "rnl" / "lrz_data_new_format",
48
+ ]
49
+ OUT_ROOT = Path(__file__).parent.parent / "runs"
50
+
51
+ N_SUBSET = 30 # reviewer-friendly subset size (None = full dataset)
52
+ N_STABLE = 50 # last N valid timesteps for steady-state width estimate
53
+ RANDOM_SEED = 42
54
+ INPUT_PARAMS = ["laser_power", "scan_speed", "laser_spot_size", "substrate_temp"]
55
+ MODEL_NAMES = ["Ridge", "PolyRidge-2", "GPR"]
56
+
57
+ # ------------------------------------------------------------------
58
+ # Logger
59
+ # ------------------------------------------------------------------
60
+
61
+ class _ColorFormatter(logging.Formatter):
62
+ _COLORS = {logging.INFO: "\033[32m", logging.WARNING: "\033[33m", logging.ERROR: "\033[31m"}
63
+ _RESET = "\033[0m"; _BOLD = "\033[1m"
64
+
65
+ def format(self, record):
66
+ color = self._COLORS.get(record.levelno, self._RESET)
67
+ t = self.formatTime(record, "%H:%M:%S")
68
+ return f"{self._BOLD}{t}{self._RESET} {color}{record.levelname:<8}{self._RESET} {record.getMessage()}"
69
+
70
+
71
+ run_id = datetime.now().strftime("%Y%m%d_%H%M%S")
72
+ out_dir = OUT_ROOT / f"regression_{run_id}"
73
+ out_dir.mkdir(parents=True, exist_ok=True)
74
+
75
+ log = logging.getLogger("reg")
76
+ log.setLevel(logging.DEBUG)
77
+ _ch = logging.StreamHandler(sys.stdout); _ch.setFormatter(_ColorFormatter()); log.addHandler(_ch)
78
+ _fh = logging.FileHandler(out_dir / "run.log")
79
+ _fh.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s", datefmt="%H:%M:%S"))
80
+ log.addHandler(_fh)
81
+
82
+ log.info("=" * 60)
83
+ log.info(f"Run ID : {run_id}")
84
+ log.info(f"Results : {out_dir}")
85
+ log.info("=" * 60)
86
+
87
+ # ------------------------------------------------------------------
88
+ # 1. Load experiments
89
+ # ------------------------------------------------------------------
90
+
91
+ def load_params(sim_dir: Path) -> dict | None:
92
+ pjson = sim_dir / "parameters.json"
93
+ if not pjson.exists():
94
+ return None
95
+ try:
96
+ raw = __import__("json").loads(pjson.read_text())
97
+ return {
98
+ "laser_power": float(raw["laser_power"]["value"]),
99
+ "scan_speed": float(raw["scan_speed_x"]["value"]),
100
+ "laser_spot_size": float(raw["laser_spot_size"]["value"]),
101
+ "substrate_temperature": float(raw["substrate_temperature"]["value"]),
102
+ }
103
+ except Exception:
104
+ return None
105
+
106
+
107
+ def melt_width(sim_dir: Path, n_stable: int) -> float | None:
108
+ """Mean melt-pool width (ymax − ymin) over the last n_stable valid rows.
109
+ Rows where any |value| > 1e30 are Initial Emptiness sentinels → excluded.
110
+ """
111
+ dat = sim_dir / "monitor" / "position-bounds_melt.dat"
112
+ if not dat.exists():
113
+ return None
114
+ try:
115
+ b = np.loadtxt(dat, delimiter=",")
116
+ if b.ndim == 1:
117
+ b = b.reshape(1, -1)
118
+ b = b[~np.any(np.abs(b) > 1e30, axis=1)] # drop Initial Emptiness rows
119
+ if len(b) < 10:
120
+ return None
121
+ width = (b[-n_stable:, 3] - b[-n_stable:, 2]).mean() # ymax - ymin
122
+ return width if width > 0 else None
123
+ except Exception:
124
+ return None
125
+
126
+
127
+ all_sims = []
128
+ for data_dir in DATA_DIRS:
129
+ sims = sorted(data_dir.iterdir()) if data_dir.is_dir() else []
130
+ log.info(f"Scanning {data_dir} → {len(sims)} dirs")
131
+ all_sims.extend(sims)
132
+ log.info(f"Total simulation directories: {len(all_sims)}")
133
+
134
+ X_list, y_list, skipped = [], [], 0
135
+ for sim_dir in all_sims:
136
+ if not sim_dir.is_dir():
137
+ continue
138
+ params = load_params(sim_dir)
139
+ if params is None:
140
+ skipped += 1; continue
141
+ w = melt_width(sim_dir, N_STABLE)
142
+ if w is None:
143
+ skipped += 1; continue
144
+ X_list.append(list(params.values()))
145
+ y_list.append(w)
146
+
147
+ log.info(f"Valid experiments: {len(X_list)} (skipped {skipped})")
148
+
149
+ X_all = np.array(X_list)
150
+ y_all = np.array(y_list)
151
+ log.info(f"Width range: [{y_all.min()*1e6:.1f}, {y_all.max()*1e6:.1f}] µm")
152
+
153
+ # ------------------------------------------------------------------
154
+ # 2. Optional subset for reviewer
155
+ # ------------------------------------------------------------------
156
+
157
+ if N_SUBSET is not None and N_SUBSET < len(X_all):
158
+ rng = random.Random(RANDOM_SEED)
159
+ idx = list(range(len(X_all)))
160
+ rng.shuffle(idx)
161
+ idx = sorted(idx[:N_SUBSET])
162
+ X, y = X_all[idx], y_all[idx]
163
+ log.info(f"Reviewer subset: {len(y)} experiments")
164
+ else:
165
+ X, y = X_all, y_all
166
+ log.info("Using full dataset")
167
+
168
+ # ------------------------------------------------------------------
169
+ # 3. Models
170
+ # ------------------------------------------------------------------
171
+
172
+ def make_models():
173
+ return [
174
+ make_pipeline(StandardScaler(), Ridge(alpha=1.0)),
175
+ make_pipeline(PolynomialFeatures(degree=2, include_bias=False),
176
+ StandardScaler(), Ridge(alpha=1.0)),
177
+ make_pipeline(StandardScaler(), GaussianProcessRegressor(
178
+ kernel=RBF() + WhiteKernel(), normalize_y=True, n_restarts_optimizer=5,
179
+ )),
180
+ ]
181
+
182
+ # ------------------------------------------------------------------
183
+ # 4. LOO cross-validation
184
+ # ------------------------------------------------------------------
185
+
186
+ splits = list(LeaveOneOut().split(X))
187
+ n_folds = len(splits)
188
+ y_preds = {}
189
+
190
+ for name, base_pipe in zip(MODEL_NAMES, make_models()):
191
+ preds = np.empty(n_folds)
192
+ log.info(f"[{name}] LOO CV ({n_folds} folds)")
193
+
194
+ for fold, (train_idx, test_idx) in enumerate(splits):
195
+ pipe = clone(base_pipe)
196
+ pipe.fit(X[train_idx], y[train_idx])
197
+ preds[test_idx] = pipe.predict(X[test_idx])
198
+ if (fold + 1) % 10 == 0 or fold == n_folds - 1:
199
+ running_r2 = r2_score(y[:fold+1], preds[:fold+1])
200
+ log.info(f" fold {fold+1:3d}/{n_folds} running R² = {running_r2:.3f}")
201
+
202
+ log.info(f"[{name}] Final LOO R²: {r2_score(y, preds):.3f}")
203
+ y_preds[name] = preds
204
+
205
+ # ------------------------------------------------------------------
206
+ # 5. Fit on full subset for importance plots
207
+ # ------------------------------------------------------------------
208
+
209
+ log.info("Fitting on full subset for feature importance ...")
210
+ fitted = {}
211
+ for name, pipe in zip(MODEL_NAMES, make_models()):
212
+ pipe.fit(X, y)
213
+ fitted[name] = pipe
214
+
215
+
216
+ def feature_importances(name, pipe):
217
+ if name == "Ridge":
218
+ return pipe.named_steps["ridge"].coef_
219
+ if name == "PolyRidge-2":
220
+ poly = pipe.named_steps["polynomialfeatures"]
221
+ coef = pipe.named_steps["ridge"].coef_
222
+ powers = poly.powers_
223
+ imp = np.array([np.sum(np.abs(coef[powers[:, i] > 0])) for i in range(X.shape[1])])
224
+ return imp / imp.max()
225
+ result = permutation_importance(pipe, X, y, n_repeats=30, random_state=0)
226
+ imp = result.importances_mean
227
+ return imp / (np.abs(imp).max() or 1)
228
+
229
+ # ------------------------------------------------------------------
230
+ # 6. Plots — 2 rows × 3 columns
231
+ # ------------------------------------------------------------------
232
+
233
+ log.info("Generating plots ...")
234
+ fig, axes = plt.subplots(2, 3, figsize=(13, 8))
235
+ colors = [plt.get_cmap("tab20")(i / len(y)) for i in range(len(y))]
236
+
237
+ for col, name in enumerate(MODEL_NAMES):
238
+ yt, yp = y * 1e6, y_preds[name] * 1e6
239
+ r2 = r2_score(y, y_preds[name])
240
+
241
+ ax = axes[0, col]
242
+ ax.scatter(yt, yp, s=35, alpha=0.85, color=colors)
243
+ lo, hi = min(yt.min(), yp.min()), max(yt.max(), yp.max())
244
+ ax.plot([lo, hi], [lo, hi], "k--", lw=0.8)
245
+ ax.set_title(f"{name} (R²={r2:.3f})")
246
+ ax.set_xlabel("True width (µm)")
247
+ if col == 0:
248
+ ax.set_ylabel("Predicted width (µm)")
249
+
250
+ ax = axes[1, col]
251
+ imp = feature_importances(name, fitted[name])
252
+ bar_colors = ["#e06c75" if v < 0 else "#61afef" for v in imp]
253
+ ax.barh(INPUT_PARAMS, imp, color=bar_colors)
254
+ ax.axvline(0, color="k", lw=0.6)
255
+ ax.set_xlabel("Standardised coef." if name != "GPR" else "Permutation importance (norm.)")
256
+ ax.set_title(f"{name} — input relevance")
257
+
258
+ subset_note = f"N={len(y)} (reviewer subset)" if N_SUBSET else f"N={len(y)} (full)"
259
+ plt.suptitle(
260
+ f"LOO parity and input relevance — steady-state melt-pool width [{subset_note}]",
261
+ y=1.01,
262
+ )
263
+ plt.tight_layout()
264
+
265
+ plot_path = out_dir / "regression_diagnostics.png"
266
+ plt.savefig(plot_path, dpi=150, bbox_inches="tight")
267
+ log.info(f"Plot saved → {plot_path}")
268
+ plt.show()
269
+ log.info("Done.")