"""NdFeB SPS physics-model tool: predict, p_meets_spec, eig, condition. Evidence class: owner-built conditional executable physics model (Dynamical's model fitted to RPI's released records and declared literature priors; not an RPI or collaborator model); not a physical observation; does not calibrate current-body coercivity. The fit's assumptions about those records are listed in the README ("Fitted assumptions"). Dependencies: Python standard library + numpy. No JAX. Loads hash-bound artifacts: physics.py - schedule discretisation and rate laws (identical bytes to the fitted model) forward.py - mechanism forward equations (the fitted model's, plus the C4 feedstock particle-size layer, a declared and uncalibrated hook that the fit never reached) posterior - .npz of thinned posterior and prior draws + metadata manifest - TOOL_MANIFEST.json with the sha256 of this module and the three files above (verified on load) Usage inside a science workspace (files are mounted by sha256, without names or extensions): import importlib.util from importlib.machinery import SourceFileLoader raw = '/workspace/raw/' loader = SourceFileLoader('ndfeb_physics_tool', raw + TOOL_SHA) spec = importlib.util.spec_from_loader('ndfeb_physics_tool', loader) tool = importlib.util.module_from_spec(spec); loader.exec_module(tool) pm = tool.load(physics=raw + PHYSICS_SHA, forward=raw + FORWARD_SHA, posterior=raw + POSTERIOR_SHA, manifest=raw + MANIFEST_SHA) pm.predict({'T_peak_C': 800, 'pressure_mode': 'cooling', 'P_MPa': 60}) Units: deg C, minutes, MPa, relative density (fraction of 7.62 g/cm3), kOe, kGs, MGOe, um. """ from __future__ import annotations import hashlib import importlib.util import json import math import sys import types from importlib.machinery import SourceFileLoader from pathlib import Path import numpy as np TOOL_VERSION = "ndfeb-sps-physics-tool-20261013.5.0" EVIDENCE_CLASS = ("owner-built conditional executable physics model (Dynamical's model fitted to RPI's released records " "and declared literature priors; not an RPI or collaborator model); not a physical observation; does " "not calibrate current-body coercivity") OBJECTIVE = {"Hci_kOe_min": 20.0, "BHmax_MGOe_min": 45.0, "note": "Dy/Tb-free, verified at operating temperature; " "10 kOe / 11 MGOe is a historical simulated benchmark from sample E, not the objective"} RHO_TD = 7.62 HERE = Path(__file__).resolve().parent _PKG = "ndfeb_physics_model" QUANTILE_LEVELS = (0.01, 0.025, 0.05, 0.10, 0.25, 0.50, 0.75, 0.90, 0.95, 0.975, 0.99) QUANTILE_KEYS = ("q01", "q025", "q05", "q10", "q25", "q50", "q75", "q90", "q95", "q975", "q99") H_MEASUREMENT_LOG_SD = 0.25 # declared, uncalibrated: hydrogen content vs the model's residual-hydrogen index H_DETECTION_INDEX = 0.01 # declared detection limit of a hydrogen measurement on the residual-hydrogen index scale # (1 = non-degassed powder); a body below it (e.g. degas_completeness "complete") reads at the limit # degas_completeness d is a declared, uncalibrated input (a number, a uniform or beta distribution, or "complete"). # The route defaults below are the v4 build defaults; a package may override them through meta["route_defaults"] # (each time slice states its own defaults from information released by its cutoff). ROUTE_DEFAULTS = dict(T_peak_C=None, heating_rate_C_per_min=10.0, dwell_min=5.0, P_MPa=60.0, pressure_mode="cooling", cooling_rate_C_per_min=100.0, load_ramp_min=0.3, degas=1.0, anneal="none", alignment_cos=0.5, T_measure_C=20.0, prep="new", degas_completeness=1.0, current_path="compact", feedstock_d50_um=4.0) # C4 feedstock particle-size layer (declared, uncalibrated): feedstock_d50_um = 4.0 is RPI's stated feedstock, the # feedstock of every fitted record; any other value is a declared extrapolation (forward.py, "C4 feedstock"). FEEDSTOCK_KEY = "feedstock_d50_um" FEEDSTOCK_REF_UM = 4.0 FEEDSTOCK_RANGE_UM = (0.5, 8.0) FEEDSTOCK_PARAMS = ("fd_beta", "fd_sg", "fd_dox", "fd_gox", "fd_kH") STATUS_FITTED = "fitted_feedstock" STATUS_DECLARED = "declared_extrapolation_uncalibrated" OUTPUTS = ("density_rel", "grain_um", "Hci_kOe", "Br_kGs", "Hk_over_Hci", "BHmax_MGOe") PRESSURE_MODES = ("heating", "cooling", "dwell") ANNEALS = ("none", "900", "900+520") CURRENT_PATHS = ("compact", "insulated") LT_LEVELS = ("trap", "load", "current") SPEC_KEYS = ("Hci_kOe_min", "BHmax_MGOe_min", "Br_kGs_min", "density_rel_min", "T_operating_C") def _validate_spec(spec): """Reject unknown or non-numeric spec keys (a misspelled key must not silently drop a requirement).""" if not isinstance(spec, dict) or not spec: raise ValueError(f"spec must be a non-empty dict with keys from {SPEC_KEYS}") bad = sorted(k for k in spec if k not in SPEC_KEYS) if bad: raise ValueError(f"unknown spec keys {bad}; allowed: {list(SPEC_KEYS)}") for k, v in spec.items(): if not _is_number(v): raise ValueError(f"spec[{k!r}] must be a number") return spec def _sha256(path) -> str: return hashlib.sha256(Path(path).read_bytes()).hexdigest() def _load_module(name, path): loader = SourceFileLoader(name, str(path)) spec = importlib.util.spec_from_loader(name, loader) mod = importlib.util.module_from_spec(spec) sys.modules[name] = mod loader.exec_module(mod) return mod def _compose(physics_path, forward_path): """Compose physics.py and forward.py into a synthetic package (forward does `from . import physics`).""" pkg = types.ModuleType(_PKG) pkg.__path__ = [] sys.modules[_PKG] = pkg ph = _load_module(_PKG + ".physics", physics_path) pkg.physics = ph fw = _load_module(_PKG + ".forward", forward_path) return ph, fw def load(physics=None, forward=None, posterior=None, manifest=None, verify=True): """Load the tool. With a manifest (default: TOOL_MANIFEST.json next to this file) every artifact's sha256 is checked and a mismatch raises. Without one the model loads with `verified = False`, reported in every output.""" physics = physics or HERE / "physics.py" forward = forward or HERE / "forward.py" posterior = posterior or HERE / "posterior_tool.npz" if manifest is None and (HERE / "TOOL_MANIFEST.json").exists(): manifest = HERE / "TOOL_MANIFEST.json" hashes = {"physics": _sha256(physics), "forward": _sha256(forward), "posterior": _sha256(posterior), "tool": _sha256(Path(__file__))} verified = False if verify and manifest is not None: man = json.loads(Path(manifest).read_text()) missing = [k for k in ("physics", "forward", "posterior", "tool") if k not in man.get("files", {})] if missing: raise ValueError(f"manifest lacks entries {missing}; a v3.1 manifest lists physics, forward, posterior and tool") if man.get("tool_version") != TOOL_VERSION: raise ValueError(f"manifest is for {man.get('tool_version')}, this module is {TOOL_VERSION}") want = {k: man["files"][k]["sha256"] for k in ("physics", "forward", "posterior", "tool")} bad = {k: (hashes[k], want[k]) for k in want if hashes[k] != want[k]} if bad: raise ValueError(f"artifact hashes differ from the manifest: {bad}") verified = True ph, fw = _compose(physics, forward) return PhysicsModel(ph, fw, posterior, hashes, verified=verified) def _n_logpdf(y, mu, s): return -0.5 * ((y - mu) / s) ** 2 - np.log(s) - 0.5 * math.log(2 * math.pi) def _t_logpdf(y, mu, s, nu=5.0): z = (y - mu) / s return (math.lgamma((nu + 1) / 2) - math.lgamma(nu / 2) - 0.5 * math.log(nu * math.pi) - np.log(s) - (nu + 1) / 2 * np.log1p(z ** 2 / nu)) def _lse(a, axis=None): a = np.asarray(a, float) m = np.max(a, axis=axis, keepdims=True) m = np.where(np.isfinite(m), m, 0.0) out = m + np.log(np.sum(np.exp(a - m), axis=axis, keepdims=True)) return np.squeeze(out, axis=axis) if axis is not None else float(np.squeeze(out)) def _lme(a, axis): a = np.asarray(a, float) return _lse(a, axis) - math.log(a.shape[axis]) def _iqr(x): q25, q75 = np.quantile(x, [0.25, 0.75]) return float(q75 - q25) def _distribution(x): """Quantiles (the primary summary) and a quantile-matched log-normal approximation of a predictive sample (mu_ln = ln median, sd_ln = half the 15.9-84.1 % log spread, over the positive draws), with its adequacy: lognormal_max_log_error is the largest |ln q - (mu_ln + z_q sd_ln)| over q05..q95, and lognormal_adequate is true when it is below 0.25. Mixtures over mechanisms and degassing states are often not log-normal.""" from statistics import NormalDist x = np.asarray(x, float) qs = np.quantile(x, QUANTILE_LEVELS) pos = x[x > 0] mu = sd = worst = None # JSON-safe: None where a log-normal summary is not computable (never NaN or inf) if len(pos) >= 10: # quantile-matched (robust): a few collapsed draws must not distort the summary l16, l50, l84 = np.log(np.quantile(pos, [0.158655, 0.5, 0.841345])) mu, sd = float(l50), float((l84 - l16) / 2.0) central = [(q, lv) for q, lv in zip(qs, QUANTILE_LEVELS) if 0.05 <= lv <= 0.95] if sd > 0 and all(q > 0 for q, _ in central): worst = float(max(abs(math.log(q) - (mu + NormalDist().inv_cdf(lv) * sd)) for q, lv in central)) return dict(quantiles={k: float(v) for k, v in zip(QUANTILE_KEYS, qs)}, mu_ln=mu, sd_ln=sd, lognormal_max_log_error=worst, lognormal_adequate=bool(worst is not None and worst < 0.25), frac_nonpositive=float(np.mean(x <= 0))) def _load_on_cooling(r): """Hull feature: 1 load on cooling, 0 load in heating, 0.5 load from the start of the dwell (declared scenario).""" return {"cooling": 1.0, "heating": 0.0, "dwell": 0.5}[r["pressure_mode"]] def _is_number(v): import numbers return isinstance(v, numbers.Real) and not isinstance(v, bool) def _check_prep_feedstock(seen, r, what="routes"): """Routes (or observations) sharing a preparation share one powder batch, hence one feedstock size.""" v = float(r.get(FEEDSTOCK_KEY, FEEDSTOCK_REF_UM)) if seen.setdefault(r["prep"], v) != v: raise ValueError(f"{what} sharing preparation {r['prep']!r} must share {FEEDSTOCK_KEY} (one powder batch)") def _scenarios(r): dc = r["degas_completeness"] dc_num = float(dc) if _is_number(dc) else None complete = dc == "complete" extrap = complete or (dc_num is not None and dc_num > 1.0) or (isinstance(dc, dict) and ( (dc.get("distribution") == "uniform" and float(dc.get("high", 0)) > 1.0))) calibrated = bool(abs(float(r["alignment_cos"]) - 0.5) < 1e-9 and abs(float(r["T_measure_C"]) - 20) < 1e-9 and dc_num is not None and dc_num in (0.0, 1.0) and r["current_path"] == "compact" and r["pressure_mode"] in ("heating", "cooling") and float(r.get(FEEDSTOCK_KEY, FEEDSTOCK_REF_UM)) == FEEDSTOCK_REF_UM) return {"alignment_cos": float(r["alignment_cos"]), "T_measure_C": float(r["T_measure_C"]), "degas_occurrence_probability": float(r["degas"]), "degas_completeness": dc, "degas_extrapolation_beyond_fitted_state": bool(extrap), "degas_complete_declared": bool(complete), "current_path": r["current_path"], "pressure_mode_dwell_declared": r["pressure_mode"] == "dwell", FEEDSTOCK_KEY: float(r.get(FEEDSTOCK_KEY, FEEDSTOCK_REF_UM)), "feedstock_declared": float(r.get(FEEDSTOCK_KEY, FEEDSTOCK_REF_UM)) != FEEDSTOCK_REF_UM, "feedstock_note": ("feedstock_d50_um other than 4 um (the feedstock of every fitted record) is a declared, " "uncalibrated extrapolation: grain size, coercivity (an empirical grain-size factor in " "every mechanism, an oxidation term and a hydrogen term) and the flags change; density " "is the current feedstock's density model, unchanged"), "calibrated": calibrated, "note": "model assumptions, not records: calibrated only at isotropic alignment, room temperature, the " "two degassing states the fit assigns (the model assumes A-C correspond to completeness 0 and D/E " "to completeness 1; RPI's record does not state A-C's dehydrogenation), a current-carrying compact " "(conductive graphite die) and load in heating or on cooling. Alignment, temperature, intermediate " "completeness (interpolated), completeness above 1 (extrapolated), complete degassing " "(no residual hydrogen; generic degassing terms held at the fitted D/E state), an insulated " "compact and load from the start of the dwell are declared scenarios; batch records or a hydrogen " "measurement would pin the completeness."} # ---------------------------------------------------------------------------------------------------- eig (v4) helpers EIG_METHOD_V4 = "bracketed-ba-v4" EIG_QUANTITIES = ("Hci", "Br", "sq", "density", "grain", "H_ppm", "Hci_ratio_T") EIG_EPS = 0.01 # every fitted posterior is mixed with the prior weights at this rate (bounds log q below) EIG_ESS_POOL = (20.0, 200.0) # pooling weight on the exact nested posterior: 0 below ESS 20, 1 above ESS 200 (log-linear) EIG_QUAD_DIMS = 36 # quadratic classifier terms use the leading principal components of the latent means GOAL_BODIES_POOL, GOAL_BODIES_OUTER = 4, 32 # simulated bodies per draw for the success probability p(goal | draw) GOAL_QUANTILES = (0.05, 0.25, 0.5, 0.75, 0.95) def _eig_spec_check(spec): """Same keys and checks as p_meets_spec; unknown keys raise (a misspelled key must not drop a requirement).""" v = globals().get("_validate_spec") if v is not None: return v(spec) allowed = ("Hci_kOe_min", "BHmax_MGOe_min", "Br_kGs_min", "density_rel_min", "T_operating_C") if not isinstance(spec, dict) or not spec: raise ValueError(f"spec must be a non-empty dict with keys from {allowed}") bad = sorted(k for k in spec if k not in allowed) if bad: raise ValueError(f"unknown spec keys {bad}; allowed: {list(allowed)}") for k, val in spec.items(): if not _is_number(val): raise ValueError(f"spec[{k!r}] must be a number") return spec def _lbfgs(fg, x0, iters=200, m=10, tol=1e-8): """Minimise a smooth convex f given fg(x) -> (f, grad): two-loop L-BFGS with a backtracking Armijo search.""" x = np.array(x0, float) f, g = fg(x) S, Y = [], [] for _ in range(iters): q = g.copy() hist = [] for s, y in reversed(list(zip(S, Y))): r = 1.0 / (y @ s) a = r * (s @ q) q -= a * y hist.append((r, a, s, y)) if S: q *= (S[-1] @ Y[-1]) / (Y[-1] @ Y[-1]) for r, a, s, y in reversed(hist): q += s * (a - r * (y @ q)) d = -q gd = g @ d if not gd < 0: d, gd, S, Y = -g, -(g @ g), [], [] t = 1.0 while True: xn = x + t * d fn, gn = fg(xn) if fn <= f + 1e-4 * t * gd or t < 1e-12: break t *= 0.5 s, y = xn - x, gn - g done = abs(f - fn) <= tol * max(1.0, abs(f)) if y @ s > 1e-14: S.append(s) Y.append(y) if len(S) > m: S.pop(0) Y.pop(0) x, f, g = xn, fn, gn if done: break return x class _Features: """Classifier / regression inputs: standardised summaries (clipped at 6 sd) and quadratic terms of the leading EIG_QUAD_DIMS principal components of the first n_quad columns (the per-latent means). Fitted on training rows.""" def __init__(self, X, n_quad): self.mu, self.sd = X.mean(0), X.std(0) + 1e-9 Z = np.clip((X - self.mu) / self.sd, -6.0, 6.0)[:, :n_quad] k = min(EIG_QUAD_DIMS, Z.shape[1]) if k: lam, V = np.linalg.eigh(np.cov(Z.T).reshape(Z.shape[1], Z.shape[1])) self.V = V[:, ::-1][:, :k] else: self.V = np.zeros((Z.shape[1], 0)) self.n_quad = n_quad def __call__(self, X): Z = np.clip((X - self.mu) / self.sd, -6.0, 6.0) P = Z[:, :self.n_quad] @ self.V k = P.shape[1] iu = np.triu_indices(k) quad = (P[:, :, None] * P[:, None, :])[:, iu[0], iu[1]] / math.sqrt(2.0) if k else np.zeros((len(Z), 0)) return np.concatenate([Z, np.clip(quad, -36.0, 36.0)], 1) class _Softmax: """Weighted multinomial logistic regression on _Features, fitted by L-BFGS with a small L2 penalty. Targets may be soft (rows of class probabilities).""" def __init__(self, X, T, sw, n_quad, l2=1e-4, iters=200): self.feat = _Features(X, n_quad) Phi = self.feat(X) n, p = Phi.shape K = T.shape[1] swn = sw / sw.sum() def fg(x): W, b = x[:p * K].reshape(p, K), x[p * K:] A = Phi @ W + b A -= A.max(1, keepdims=True) E = np.exp(A) Ssum = E.sum(1, keepdims=True) G = (E / Ssum - T) * swn[:, None] f = -float(np.sum(swn[:, None] * T * (A - np.log(Ssum)))) + 0.5 * l2 * float(np.sum(W * W)) return f, np.concatenate([(Phi.T @ G + l2 * W).ravel(), G.sum(0)]) x = _lbfgs(fg, np.zeros(p * K + K), iters=iters) self.W, self.b = x[:p * K].reshape(p, K), x[p * K:] def log_prob(self, X): A = self.feat(X) @ self.W + self.b return A - _lse(A, 1)[:, None] def _ridge(X, t, sw, Xnew, n_quad, l2=1e-3): """Weighted ridge regression of t on [1, _Features(X)]; returns predictions at Xnew.""" feat = _Features(X, n_quad) Phi = np.concatenate([np.ones((len(X), 1)), feat(X)], 1) w = sw / sw.sum() beta = np.linalg.solve(Phi.T @ (Phi * w[:, None]) + l2 * np.eye(Phi.shape[1]), Phi.T @ (w * t)) return np.concatenate([np.ones((len(Xnew), 1)), feat(Xnew)], 1) @ beta def _systematic(p, n, rng): """n indices drawn by systematic resampling with probabilities p (every index appears floor/ceil(n p) times).""" if n <= 0: return np.zeros(0, int) c = np.cumsum(p / p.sum()) u = (rng.random() + np.arange(n)) / n return np.minimum(np.searchsorted(c, u), len(p) - 1) def _alloc(w, n, balanced): """Label counts summing to n: equal shares (balanced) or proportional to w (largest remainder).""" k = len(w) if balanced: c = np.full(k, n // k) c[: n - c.sum()] += 1 return c raw = n * w / w.sum() c = np.floor(raw).astype(int) c[np.argsort(-(raw - c))[: n - c.sum()]] += 1 return c def _eig_halves(contrib, fold, offset): """Lower bound from each half of the simulated experiments and whether they agree within 2 combined SE.""" est, var = [], [] for f in (0, 1): c = contrib[fold == f] est.append(offset + float(c.mean())) var.append(float(c.var(ddof=1)) / len(c) if len(c) > 1 else float("inf")) return est, bool(abs(est[0] - est[1]) <= 2.0 * math.sqrt(var[0] + var[1])) def _bern_entropy(p): p = np.clip(np.asarray(p, float), 1e-12, 1 - 1e-12) return -(p * np.log(p) + (1 - p) * np.log1p(-p)) # ---------------------------------------------------------------------------------------------------------------- class PhysicsModel: def __init__(self, ph, fw, posterior_path, hashes, verified=False, weights=None): self.ph, self.fw, self.hashes, self.verified = ph, fw, hashes, verified z = np.load(posterior_path, allow_pickle=False) self.meta = json.loads(str(z["__meta__"])) self.post, self.prior = {}, {} for key in z.files: if key == "__meta__": continue grp, mech, par = key.split("__", 2) tgt = self.post if grp == "post" else self.prior tgt.setdefault(mech, {})[par] = np.asarray(z[key], dtype=float) # every indicator's weights (density, magnetic and, from v4, load_timing) self.w = {k: dict(v) for k, v in self.meta["weights"].items()} # per-draw load-timing probabilities (v4): stored as post____ltp_