"""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 and the C5 SEM/BSE observables and milled-feedstock density layer: declared, uncalibrated hooks the fit never reached) posterior - .npz of thinned posterior and prior draws + metadata microstructure.py - C6 microstructure layer: declared link and measurement functions of the SEM grain and feature size, SEM porosity and Nd-rich phase outputs, and the descriptive SPS trace (pure numpy) coercivity_link.py - optional (C6 work package 1): the coercivity link; without it the link outputs are omitted manifest - TOOL_MANIFEST.json with the sha256 of this module and the files above (verified on load) C6 (physics tool C6, microstructure layer): every C5 output is computed exactly as in C5 for the same seed; the new outputs (grain_sem_dist, fracture_intercept_um, porosity_area_fraction_sem, the Nd-rich phase outputs, sps_log and the coercivity link) use their own generators and the per-draw parameters c6_* stored next to the C5 coercivity draws. C7 (material lab, 2026-10-23; README.md in this package lists every change and its evidence): - density: the C5.0 SPS density draws reweighted on #7 (7.01, Archimedes) and #8 as sintered (7.07, method not stated), one shared 850 C batch PREP-C850 (posterior_tool.npz; build/c7_density_update.py) - anneal: a load-free anneal can densify a body (anneal.py, anneal_posterior.npz; four mechanisms calibrated on #8's one paired return, build/c7_anneal_fit.py). Every annealed stage carries its own density: route-level density_rel, C5 remanence (relative to historical E's own anneal), the coercivity link's Br, the fracture-intercept feature factor. The 900 C hold is a route key (anneal_hold_h, default 2 h = the planned program, or "as_#8" for the same unconfirmed program as #8); the C5 grain law's 900 C growth follows the hold - inputs: unknown route keys raise with suggestions; degassing_completeness is an echoed alias of degas_completeness; alignment_cos and alignment_cos_theta are one physical feeding both magnetic paths (a conflict raises); predict() reports route_resolution - joint_target(): both magnetic paths (C5 and the coercivity link) on one set of draws, with the boundary-film magnetization and every epistemic quantity shared by the bodies of one preparation, body scatter from C5, the same declared temperature scenario, and the structural Br^2/4 bound reported - everything not named above is computed exactly as in C6 for the same seed, posterior and route C7.1 (2026-10-23, corrective; README.md "C7.1"): - anneal.py: CAPACITY's removable porosity is a state of the whole executed sequence (segmenting one program no longer removes more); CLOSED is integrated on a fixed largest dose step (segmentation-independent); the tool evaluates every stage from the as-sintered body through its whole sequence - one physical dependence on the 900 C hold on both magnetic paths: the hold-scaled C5 grain now also enters C5's grain-size mechanism H4 (Kronmueller term), as it enters the link's N_eff; every non-grain magnetic anneal term (C5's fitted factors, the link's re-wetting and 520 C gain) is historical E's 2 h response on both paths (declared) - polished-section planarity and SEM porosity read the body's density at the route's stage, as in the twin - eig() refuses what its latents cannot represent (annealed-stage density, Br and grain; annealed goals); anneal_eig() and condition_anneal() select and update anneal experiments on the same layer, readings and nuisances as predict() and the twin 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, microstructure=raw + MICROSTRUCTURE_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-20261023.8.2" 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"} OBJECTIVE_SPEC = {"Hci_kOe_min": 20.0, "BHmax_MGOe_min": 45.0} # C7 joint_target default (room temperature) RHO_TD = 7.62 HERE = Path(__file__).resolve().parent _PKG = "ndfeb_physics_model_c71" # distinct from C6's and C7's synthetic packages, so every version loads in one process 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") # C5 (declared, uncalibrated): SEM/BSE outputs of predict(), observables of condition(), and the milled-feedstock density # layer. Per-draw parameters c5_* are stored prior draws (forward.py, "C5 SEM/BSE observables"); the package's status # strings for them come from its posterior metadata (meta["c5"]["status"]). SEM_STAGES = ("as_sintered", "after_900_520") # both stages of one piece (SEM grain size and polished-section BSE) STAGE_ALIASES = {"900+520": "after_900_520"} # accepted on input SEM_OUTPUTS = ("grain_size_sem_um", "anneal_grain_change", "gb_phase_bse") BSE_CLASSES = ("spread", "pooled", "unreadable") C5_SEM_PARAMS = ("c5_cm", "c5_zeta", "c5_kox", "c5_Wstar", "c5_tau", "c5_rann") C5_DENSITY_PARAMS = ("c5_nD", "c5_gam", "c5_cox", "c5_dox", "c5_zfd") STATUS_MODELLED_PAIR = "modelled_pair" GRAIN_FIELD_LOG_SD = 0.15 # declared: field sampling of a reported mean grain size (log-sd), as forward.py E_RHO_PLACEHOLDER = 0.9738 # density passed for SEM/BSE-only observations in condition(); grain and W ignore it # C6 (microstructure layer; declared link functions in microstructure.py, per-draw parameters c6_* stored next to the # C5 coercivity draws, statuses from the package's posterior metadata meta["c6"]["status"]). New outputs draw from # their own generators (seed, 61 / 67), so every C5 array of a call is unchanged. C6_STAGES = ("as_sintered", "after_900", "after_900_520") C6_OUTPUTS = ("grain_sem_dist", "fracture_intercept_um", "porosity_area_fraction_sem", "nd_rich_area_fraction", "pocket_ecd_um", "pocket_share", "elongated_share", "faint_line_coverage", "sps_log", "coercivity_link") ALIGN_KEY = "alignment_cos_theta" # A6: grain alignment for the coercivity link only (C5 ignores it) ALIGN_DEFAULT = 0.5 # isotropic: every record to date ALIGN_RANGE = (0.5, 0.95) J_GB_POSTERIOR_T = {"0.0": 0.26, "0.6": 0.65, "1.2": 0.08} # Phase 2a D/E posterior of the film magnetization (never drawn) LINK_STATUS_MISSING = "link module not installed" LINK_STATE_KEYS = ("n", "route", "alignment_cos_theta", "alignment_declared", "stages", "rho_rel", "grain_model_um", "grain_sigma_ln", "grain_sem_median_um", "fracture_intercept_um", "nd_rich", "W", "c5", "J_GB_posterior_T", "ln_hci_chem_offset", "rho_rel_by_stage") # requests no C6 instrument answers (for the campaign twin, C6_SPEC C): key -> reason REFUSALS = {"powder_icp_oes": "no model of powder chemistry by ICP-OES", "film_magnetization": "the 2-3 nm boundary film's magnetization is not observable by any measurement in " "this window (STEM-EDS or atom-probe tomography can constrain chemistry, not directly measure film magnetization)", "stem_eds": "no STEM or atom-probe instrument is simulated in this window"} PRESSURE_MODES = ("heating", "cooling", "dwell") ANNEALS = ("none", "900", "900+520") # C7 route input handling: every key must be a route key, an accepted alias (applied and echoed) or informational ANNEAL_HOLD_KEY = "anneal_hold_h" # hold of the 900 C step (h); "as_#8" = the same unconfirmed program as #8 ANNEAL_HOLD_DEFAULT = 2.0 # the September timeline's planned 900 C / 2 h (not confirmed for #8) ANNEAL_HOLD_RANGE = (0.5, 4.0) ANNEAL_HOLD_AS8 = "as_#8" SECOND_STEP = (520.0, 2.0) # the planned 520 C / 2 h step (below the Nd-rich eutectic: no densification) ROUTE_ALIASES = {"degassing_completeness": "degas_completeness"} # the campaign twin's preparation key INFORMATIONAL_KEYS = ("label", "body_id", "note") # echoed, never read E_ROUTE_ANNEAL_RHO = 0.9738 # historical E's as-sintered relative density (7.42): C5's anneal factors are E's C7_STAGE_DENSITY_NOTE = ("C7: a load-free anneal can densify a body (anneal.py). density_rel is the body's density at " "the route's stage; density_rel_as_sintered is the same body before the anneal. Br at an " "annealed stage is C5's (whose anneal factor was fitted on historical E) times the body's " "density gain over E's gain under the same anneal draw; ln Hci keeps C5's as-sintered " "porosity (declared: porosity damage is set at sintering)") 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, microstructure=None, coercivity_link=None, anneal=None, anneal_posterior=None): """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. C6: microstructure (default microstructure.py next to this file) carries the C6 link functions; coercivity_link (default coercivity_link.py next to this file, when it exists) is the coercivity link of work package 1. A manifest that lists either file binds it too; without the link module the link outputs are omitted with status "link module not installed". C7: anneal (default anneal.py) and anneal_posterior (default anneal_posterior.npz) carry the anneal layer; both are required together, and a manifest that lists them binds them. Without them annealed stages keep the as-sintered density, as in C6, and every output says so.""" physics = physics or HERE / "physics.py" forward = forward or HERE / "forward.py" posterior = posterior or HERE / "posterior_tool.npz" if microstructure is None and (HERE / "microstructure.py").exists(): microstructure = HERE / "microstructure.py" if coercivity_link is False: # explicit opt-out: load without the link even when coercivity_link.py exists coercivity_link = None elif coercivity_link is None and (HERE / "coercivity_link.py").exists(): coercivity_link = HERE / "coercivity_link.py" if anneal is False: # explicit opt-out of the C7 anneal layer (C6 behaviour for annealed stages) anneal, anneal_posterior = None, None else: if anneal is None and (HERE / "anneal.py").exists(): anneal = HERE / "anneal.py" if anneal_posterior is None and anneal is not None and (HERE / "anneal_posterior.npz").exists(): anneal_posterior = HERE / "anneal_posterior.npz" if (anneal is None) != (anneal_posterior is None): raise ValueError("the C7 anneal layer needs both anneal.py and anneal_posterior.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__))} if microstructure is not None: hashes["microstructure"] = _sha256(microstructure) if coercivity_link is not None: hashes["coercivity_link"] = _sha256(coercivity_link) if anneal is not None: hashes["anneal"] = _sha256(anneal) hashes["anneal_posterior"] = _sha256(anneal_posterior) 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}") opt = ("microstructure", "coercivity_link", "anneal", "anneal_posterior") absent = [k for k in opt if k in man["files"] and k not in hashes] if absent: raise ValueError(f"the manifest lists {absent}: pass the file(s) to load()") unbound = [k for k in opt if k in hashes and k not in man["files"]] if unbound: raise ValueError(f"{unbound} loaded but not listed in the manifest (a C7 manifest binds every module)") keys = ("physics", "forward", "posterior", "tool") + tuple(k for k in opt if k in hashes) want = {k: man["files"][k]["sha256"] for k in keys} 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) ms = _load_module(_PKG + ".microstructure", microstructure) if microstructure is not None else None link = _load_module(_PKG + ".coercivity_link", coercivity_link) if coercivity_link is not None else None an = _load_module(_PKG + ".anneal", anneal) if anneal is not None else None return PhysicsModel(ph, fw, posterior, hashes, verified=verified, ms=ms, link=link, an=an, anneal_posterior=anneal_posterior) 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), density (a declared size, " "packing and oxide layer on the densification rates and green density), the SEM/BSE " "outputs and the flags change"), "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 _std_normal_cdf(z): """Phi(z), accurate in both tails (numpy has no erfc).""" z = np.asarray(z, float) return 0.5 * np.frompyfunc(math.erfc, 1, 1)(-z / math.sqrt(2.0)).astype(float) 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, ms=None, link=None, an=None, anneal_posterior=None): self.ph, self.fw, self.hashes, self.verified = ph, fw, hashes, verified self.ms, self.link = ms, link # C6: microstructure link functions; coercivity link (work package 1) or None # C7 anneal layer: mechanism weights and stored draws (posterior and prior) per mechanism, kept apart from # every C5/C6 array; drawn with their own generator so no C5/C6 draw of a call changes self.an, self.an_post, self.an_prior, self.an_meta, self.an_dw = an, {}, {}, None, {} if an is not None: za = np.load(anneal_posterior, allow_pickle=False) self.an_meta = json.loads(str(za["__meta__"])) for key in za.files: if key == "__meta__": continue grp, mech, par = key.split("__", 2) (self.an_post if grp == "post" else self.an_prior).setdefault(mech, {})[par] = np.asarray(za[key], float) z = np.load(posterior_path, allow_pickle=False) self.meta = json.loads(str(z["__meta__"])) self.post, self.prior = {}, {} # C6: the c6_* per-draw parameters are kept apart from the C5 parameters, so every C5 computation (draw # assignment, copies of resampled draws, conditioning) sees exactly the C5 arrays self.c6post, self.c6prior = {}, {} for key in z.files: if key == "__meta__": continue grp, mech, par = key.split("__", 2) if par.startswith("c6_"): tgt = self.c6post if grp == "post" else self.c6prior else: 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_