File size: 15,510 Bytes
239a1be | 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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 | """Dataset / normalisation / splitting utilities.
Everything the model sees is built here so that the *exact* same transform is
applied at train, validation and inference time (statistics are fitted on the
training split only and stored in a JSON file).
"""
from __future__ import annotations
import json
from dataclasses import dataclass, field
from pathlib import Path
from typing import Dict, List, Sequence, Tuple
import numpy as np
import pandas as pd
import torch
from torch.utils.data import Dataset
ROOT = Path(__file__).resolve().parents[2]
PROC = ROOT / "data" / "processed"
ELEMENTS = ["Al", "Ti", "Zr", "Nb", "Mo", "Ta", "V", "Cr", "Mn", "Fe",
"Co", "Ni", "Cu", "Hf", "W", "Re", "Sc", "Mg", "Si", "Sn"]
# ---------------------------------------------------------------------------
# target specification
# ---------------------------------------------------------------------------
@dataclass
class Target:
name: str # column in trajectories.csv
key: str # short key used in metrics / heads
unit: str
transform: str # "identity" | "asinh"
group: str # "macro" | "phase" | "dislocation" | "twin"
TARGETS: List[Target] = [
Target("sigma_GPa", "sigma", "GPa", "zscore", "macro"),
Target("xi_BCC", "xi_BCC", "vol.fr.", "fraction", "phase"),
Target("xi_FCC", "xi_FCC", "vol.fr.", "fraction", "phase"),
Target("xi_HCP", "xi_HCP", "vol.fr.", "fraction", "phase"),
Target("xi_other", "xi_other", "vol.fr.", "fraction", "phase"),
Target("rho_total", "rho_total", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_perfect", "rho_perfect", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_shockley", "rho_shockley", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_stairrod", "rho_stairrod", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_hirth", "rho_hirth", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_other_disl", "rho_other_disl", "1e19 m^-2", "asinh", "dislocation"),
Target("rho_112_111", "rho_112_111", "1e19 m^-2", "asinh", "dislocation"),
Target("twin_density_nm-1", "twin", "nm^-1", "asinh", "twin"),
]
TARGET_KEYS = [t.key for t in TARGETS]
# static numeric features (raw column -> transform)
NUMERIC_STATIC = [
("VEC", "identity"), ("delta", "identity"), ("rbar", "identity"),
("dHmix", "identity"), ("dSmix", "identity"), ("chi", "identity"),
("Mavg", "identity"), ("dmu", "identity"), ("Tm", "identity"),
("rhomass", "identity"), ("T0", "identity"), ("strain_rate", "log10"),
("eta", "identity"),
]
GEOM_STATIC = ["geom_L", "geom_W", "geom_H", "geom_D", "geom_AR", "geom_volume_nm3"]
GEOM_FLAGS = ["app_L", "app_W", "app_H", "app_D", "app_AR", "app_V"]
CATEGORICAL = {
"shape_type": ["prism", "cylinder"],
"crystalline": ["s", "p"],
"ensemble": ["NPT", "NVT", "NVE"],
"potential": ["EAM", "MEAM", "SNAP"],
"load_mode": ["T", "C", "S"],
}
INIT_PHASE = ["init_xi_BCC", "init_xi_FCC", "init_xi_HCP", "init_xi_other"]
INIT_RHO = ["init_d_perfect", "init_d_shockley", "init_d_stairrod",
"init_d_hirth", "init_d_oth", "init_d_112_111", "init_d_100"]
def build_static_frame(meta: pd.DataFrame) -> Tuple[np.ndarray, List[str], List[str]]:
"""Return (raw static matrix, feature names, feature kinds)."""
cols, names, kinds = [], [], []
for c in ELEMENTS:
cols.append(meta["at_" + c].to_numpy(float))
names.append("at_" + c)
kinds.append("composition")
for c, _ in NUMERIC_STATIC:
cols.append(meta[c].to_numpy(float))
names.append(c)
kinds.append("numeric")
for c in GEOM_STATIC:
cols.append(meta[c].to_numpy(float))
names.append(c)
kinds.append("geom")
for c in GEOM_FLAGS:
cols.append(meta[c].to_numpy(float))
names.append(c)
kinds.append("flag")
for c in INIT_PHASE:
cols.append(meta[c].to_numpy(float))
names.append(c)
kinds.append("init_phase")
for c in INIT_RHO:
cols.append(meta[c].to_numpy(float))
names.append(c)
kinds.append("init_rho")
cols.append(meta["orient_h"].to_numpy(float))
cols.append(meta["orient_k"].to_numpy(float))
cols.append(meta["orient_l"].to_numpy(float))
cols.append(meta["app_orient"].to_numpy(float))
names += ["orient_h", "orient_k", "orient_l", "app_orient"]
kinds += ["geom", "geom", "geom", "flag"]
for cat, levels in CATEGORICAL.items():
raw = meta[cat].astype(str).to_numpy()
for lv in levels:
cols.append((raw == lv).astype(float))
names.append(f"{cat}={lv}")
kinds.append("onehot")
X = np.stack(cols, axis=1)
return X, names, kinds
class Normalizer:
"""Train-split statistics for static features and targets.
* composition / phase fractions / one-hot / flags -> already dimensionless,
left untouched (step 2: 0-1 variables need no normalisation);
* physical quantities -> z-score;
* strain rate -> log10 then z-score (spans 1e8-5e11);
* geometry -> log10 then z-score, with a separate applicability flag so a
non-applicable dimension is encoded as "0 after normalisation" rather
than a fake physical zero;
* dislocation density / twin density -> asinh(x / s0) then z-score, which
is defined at exactly zero and ~log for large values.
"""
def __init__(self, mode: str = "full"):
self.mode = mode # "full" | "none" (ablation)
self.mu = None
self.sd = None
self.tgt_mu = np.zeros(len(TARGETS))
self.tgt_sd = np.ones(len(TARGETS))
self.tgt_s0 = np.ones(len(TARGETS))
self.loss_w = np.ones(len(TARGETS))
# -- static ------------------------------------------------------------
def fit_static(self, X: np.ndarray, names: Sequence[str], kinds: Sequence[str]):
n = X.shape[1]
self.mu = np.zeros(n)
self.sd = np.ones(n)
if self.mode == "none":
return self
for j, (nm, kd) in enumerate(zip(names, kinds)):
col = X[:, j].astype(float).copy()
if kd in ("composition", "flag", "onehot", "init_phase"):
self.mu[j], self.sd[j] = 0.0, 1.0
continue
if kd == "geom" and nm in ("geom_L", "geom_W", "geom_H", "geom_D",
"geom_AR", "geom_volume_nm3"):
col = np.log10(np.clip(col, 1e-6, None))
if kd == "init_rho":
col = np.arcsinh(col / 1.0)
m = np.nanmean(col)
s = np.nanstd(col)
if not np.isfinite(s) or s < 1e-9:
s = 1.0
self.mu[j], self.sd[j] = (0.0 if not np.isfinite(m) else m), s
return self
def transform_static(self, X: np.ndarray, names: Sequence[str],
kinds: Sequence[str]) -> np.ndarray:
if self.mode == "none":
return np.nan_to_num(X.astype(float), nan=0.0, posinf=0.0, neginf=0.0)
Z = X.astype(float).copy()
for j, (nm, kd) in enumerate(zip(names, kinds)):
col = Z[:, j]
if kd == "geom" and nm in ("geom_L", "geom_W", "geom_H", "geom_D",
"geom_AR", "geom_volume_nm3"):
col = np.log10(np.clip(col, 1e-6, None))
if kd == "init_rho":
col = np.arcsinh(col / 1.0)
Z[:, j] = (col - self.mu[j]) / self.sd[j]
Z = np.nan_to_num(Z, nan=0.0, posinf=0.0, neginf=0.0)
return Z
# -- targets -----------------------------------------------------------
def fit_targets(self, traj: pd.DataFrame):
if self.mode == "none":
return self
for i, t in enumerate(TARGETS):
v = traj[t.name].to_numpy(float)
v = v[np.isfinite(v)]
if t.transform == "fraction":
self.tgt_s0[i] = 1.0
self.tgt_mu[i] = 0.0
self.tgt_sd[i] = 1.0
continue
if t.transform == "asinh":
pos = v[v > 0]
s0 = float(np.median(pos)) if len(pos) else 1.0
if not np.isfinite(s0) or s0 <= 0:
s0 = 1.0
self.tgt_s0[i] = s0
z = np.arcsinh(v / s0)
else:
self.tgt_s0[i] = 1.0
z = v
self.tgt_mu[i] = float(np.mean(z)) if len(z) else 0.0
sd = float(np.std(z)) if len(z) else 1.0
self.tgt_sd[i] = sd if sd > 1e-9 else 1.0
# optimisation weights: equalise the variance each head sees, so a
# 0-1 phase fraction and a z-scored stress contribute comparably.
Y, M = self.transform_targets(traj)
for i in range(len(TARGETS)):
m = M[:, i] > 0
v = Y[m, i]
var = float(np.var(v)) if len(v) > 1 else 1.0
self.loss_w[i] = 1.0 / max(var, 0.05)
self.loss_w = self.loss_w / np.mean(self.loss_w)
return self
def transform_targets(self, traj: pd.DataFrame) -> Tuple[np.ndarray, np.ndarray]:
T = len(traj)
Y = np.full((T, len(TARGETS)), np.nan, dtype=np.float32)
M = np.zeros((T, len(TARGETS)), dtype=np.float32)
for i, t in enumerate(TARGETS):
v = traj[t.name].to_numpy(float).astype(np.float32)
obs = np.isfinite(v)
z = np.where(obs, v, 0.0)
if self.mode == "none":
Y[obs, i] = z[obs]
M[obs, i] = 1.0
continue
if t.transform == "asinh":
z = np.arcsinh(z / self.tgt_s0[i])
z = (z - self.tgt_mu[i]) / self.tgt_sd[i]
elif t.transform == "zscore":
z = (z - self.tgt_mu[i]) / self.tgt_sd[i]
Y[obs, i] = z[obs]
M[obs, i] = 1.0
Y = np.nan_to_num(Y, nan=0.0, posinf=0.0, neginf=0.0)
return Y, M
def inverse_targets(self, Z: np.ndarray) -> np.ndarray:
"""(..., n_targets) normalised -> raw physical units."""
Z = np.asarray(Z, dtype=np.float64)
out = np.empty_like(Z)
for i, t in enumerate(TARGETS):
v = Z[..., i] * self.tgt_sd[i] + self.tgt_mu[i]
if t.transform == "asinh":
v = np.sinh(v) * self.tgt_s0[i]
out[..., i] = v
return out
def to_json(self) -> dict:
return {"static_mu": self.mu.tolist(), "static_sd": self.sd.tolist(),
"target_mu": self.tgt_mu.tolist(), "target_sd": self.tgt_sd.tolist(),
"target_s0": self.tgt_s0.tolist(),
"target_keys": TARGET_KEYS, "loss_w": self.loss_w.tolist()}
@classmethod
def from_json(cls, d: dict):
z = cls()
z.mu = np.asarray(d["static_mu"], float)
z.sd = np.asarray(d["static_sd"], float)
z.tgt_mu = np.asarray(d["target_mu"], float)
z.tgt_sd = np.asarray(d["target_sd"], float)
z.tgt_s0 = np.asarray(d["target_s0"], float)
z.loss_w = np.asarray(d.get("loss_w", np.ones(len(TARGETS))), float)
return z
class PackedDataset(Dataset):
"""Packed tensors for a set of sample ids.
Returns (static, seq_input, Y, M, sample_id).
seq_input channels: [strain/0.2, dstrain/5e-4, log10(rate)/10, T0/1000, sign]
"""
def __init__(self, sids, meta: pd.DataFrame, traj: pd.DataFrame,
norm: Normalizer, names, kinds, keep_mask=None):
mm = meta.set_index("sample_id")
self.sids = list(sids)
idx = {int(s): i for i, s in enumerate(meta.sample_id)}
Xraw = np.stack([_static_row(meta, idx[s]) for s in self.sids])
Z = norm.transform_static(Xraw, names, kinds).astype(np.float32)
if keep_mask is not None:
# *select* the retained columns: dropping a feature must shrink the
# input width (train.py builds the encoder with n_static=km.sum()),
# not pad it with a constant zero.
Z = Z[:, np.asarray(keep_mask, dtype=bool)]
self.static = torch.from_numpy(Z)
xs, ys, ms = [], [], []
for s in self.sids:
sub = traj[traj.sample_id == s].sort_values("strain")
eps = sub.strain.to_numpy(np.float32)
de = np.zeros_like(eps)
de[1:] = np.diff(eps)
rate = np.log10(max(float(mm.loc[s, "strain_rate"]), 1.0)) / 10.0
T0 = float(mm.loc[s, "T0"]) / 1000.0
sign = 1.0 if str(mm.loc[s, "load_mode"]).upper().startswith("T") else -1.0
x = np.stack([eps / 0.2, de / 5e-4,
np.full_like(eps, rate), np.full_like(eps, T0),
np.full_like(eps, sign)], axis=1)
Y, M = norm.transform_targets(sub)
xs.append(torch.from_numpy(x.astype(np.float32)))
ys.append(torch.from_numpy(Y))
ms.append(torch.from_numpy(M))
self.x = xs
self.Y = ys
self.M = ms
def __len__(self):
return len(self.sids)
def __getitem__(self, i):
return self.static[i], self.x[i], self.Y[i], self.M[i], self.sids[i]
_STATIC_CACHE = {}
def _static_row(meta: pd.DataFrame, i: int):
key = id(meta)
if key not in _STATIC_CACHE:
_STATIC_CACHE[key] = build_static_frame(meta)[0]
return _STATIC_CACHE[key][i]
def collate(batch):
statics, xs, ys, ms, sids = zip(*batch)
return (torch.stack(statics), torch.stack(xs), torch.stack(ys),
torch.stack(ms), list(sids))
# ---------------------------------------------------------------------------
# splits
# ---------------------------------------------------------------------------
def random_split(alloys: List[str], meta: pd.DataFrame, seed: int,
test_frac: float = 0.2) -> Tuple[List[int], List[int]]:
"""Sample-level split stratified by alloy (a held-out alloy never appears)."""
rng = np.random.default_rng(seed)
sids = meta.sample_id.tolist()
by_alloy: Dict[str, List[int]] = {}
for sid, al in zip(sids, alloys):
by_alloy.setdefault(al, []).append(sid)
test = []
for al, ids in by_alloy.items():
k = max(1, int(round(len(ids) * test_frac))) if len(ids) > 1 else 0
if len(ids) == 1:
k = 1 if rng.random() < test_frac else 0
test += list(rng.choice(ids, size=k, replace=False))
test = sorted(set(int(x) for x in test))
train = sorted(set(sids) - set(test))
return train, test
def kfold_split(alloys: List[str], meta: pd.DataFrame, seed: int, k: int,
fold: int) -> Tuple[List[int], List[int]]:
"""Alloy-stratified K-fold over samples."""
rng = np.random.default_rng(seed)
by_alloy: Dict[str, List[int]] = {}
for sid, al in zip(meta.sample_id.tolist(), alloys):
by_alloy.setdefault(al, []).append(int(sid))
assign = {}
counter = 0
for al in sorted(by_alloy):
ids = list(by_alloy[al])
rng.shuffle(ids)
for sid in ids:
assign[sid] = counter % k
counter += 1
test = sorted(s for s, f in assign.items() if f == fold)
train = sorted(s for s, f in assign.items() if f != fold)
return train, test
def loao_split(alloys: List[str], meta: pd.DataFrame, held: str):
sids = meta.sample_id.tolist()
test = [int(s) for s, a in zip(sids, alloys) if a == held]
train = [int(s) for s in sids if s not in test]
return train, test |