1.1.73: adapt DSH 0.2.1-rc.2, Apache-2.0, lab-only default-deny.

This commit is contained in:
叫我小杨同学 committed 2026-10-23 11:50:42 +08:00
1 parent 8df4406a7c
commit 1ea067189c
114 files changed
+21198 -5183

No files matched your search

@@ -0,0 +1,435 @@
"""Cross-material transfer benchmark for L-PBF process->property surrogates.
Synthetic-data study of whether a single surrogate model can transfer across
alloy families (Ti-6Al-4V, SS316L, AlSi10Mg) when trained on all-but-one
materials and applied to the held-out family with or without fine-tuning.
Design notes (why every parameter is what it is)
-------------------------------------------------
* Process windows are literature-typical values declared as design choices;
nothing here is fitted to a target output.
* The latent physics per material is a *latent process* latent factor model:
density = base[m] + sum_k beta[m,k] * f_k(x) + eps
where f_k are shared kernels (dimensionless) and beta are per-material
weights. Because f_k is shared, transfer is possible in principle; because
beta differs strongly across families, pure zero-shot transfer is weak for
far families -- exactly the qualitative behaviour reported in the
benchmark literature this paper builds on (Xie 2021; Jiang 2022;
Akbari 2022/2024). This is a mechanism assumption, not a claim of physical
correctness: it lets the benchmark have a *known ground truth* so that
"where does error come from" is measurable instead of guessed.
* Noise sigma is declared as a fraction of each material's response range.
* Seed is fixed for reproducibility.
Units: x1 laser power P [W]; x2 scan speed v [mm/s]; x3 hatch spacing h
[mm]; x4 layer thickness t [um]. Outputs: relative density rho_rel [%],
defect probability p_def [-]. Both dimensionless-normalised in the kernel
space (see FEATURES below) which is the point of the feature-scale
sensitivity experiment.
"""
from __future__ import annotations
import math
import numpy as np
NAME = "lpbf_transfer_bench"
VERSION = "1.3.0"
DESCRIPTION = ("Leave-material-out cross-material transfer benchmark for L-PBF "
"process->density/defect surrogates across Ti6Al4V, SS316L, "
"AlSi10Mg; zero-shot vs 10% fine-tune; feature-scale and "
"capacity attribution.")
# --------------------------------------------------------------------------
# Materials. Each entry: base response level, per-kernel weights, response
# range (for metric scaling and noise floor), and label "family distance".
# Values are design choices at literature-reported magnitudes; they encode
# the known fact that density and porosity respond on different scales and
# with different sign structure per family.
# --------------------------------------------------------------------------
_MATERIALS = {
# x_scale (power W, speed mm/s, hatch mm, layer um)
"Ti6Al4V": {
"x_range": (180.0, 320.0, 150.0, 800.0, 0.025, 0.070, 25.0, 70.0), # P0,P1,v0,v1,h0,h1,t0,t1
"rho_base": 99.55, # % relative density base
"rho_amp": 0.75, # response swing across window
"p_base": 0.115, # defect probability base
"p_amp": 0.16,
"beta_rho": [0.90, -0.30, -0.42, -0.20], # over kernels f0..f3
"beta_p": [0.85, 0.55, 0.40, 0.10],
},
"SS316L": {
"x_range": (180.0, 320.0, 150.0, 800.0, 0.025, 0.070, 25.0, 70.0),
"rho_base": 98.90,
"rho_amp": 0.95,
"p_base": 0.075,
"p_amp": 0.20,
# Steel: opposite sign on speed kernel vs Ti -> source-target gap
"beta_rho": [-0.45, 0.75, -0.30, 0.15],
"beta_p": [ 0.60, -0.35, 0.55, 0.25],
},
"AlSi10Mg": {
"x_range": (160.0, 300.0, 150.0, 900.0, 0.025, 0.080, 25.0, 80.0),
"rho_base": 99.20,
"rho_amp": 0.60,
"p_base": 0.045,
"p_amp": 0.30,
# Al: largest swing on hatch kernel -> far family for density
"beta_rho": [ 0.25, -0.15, -0.85, 0.10],
"beta_p": [ 0.35, 0.70, 0.35, 0.30],
},
}
PARAMS = {
# --- sample sizes (design choices; benchmark-scale, not experiments) --
"n_train_per_mat": 900, # per material for source-pool training
"n_finetune_frac": 0.10, # fraction of target test set used to fine-tune
"n_test_per_mat": 600,
"seed": 20240611,
# --- noise floors (assumption: instrument/measurement floor) ---------
"rho_noise_frac": 0.02, # 2% of material response range
"p_noise_frac": 0.05, # 5% of material probability span
# --- model capacity ladder (Tab.4 ablation axis) ----------------------
"capacities": [16, 64], # MLP hidden units per layer (capacity ladder)
}
def _kernels(x: np.ndarray) -> np.ndarray:
"""Shared latent process kernels f_k: dimensionless smooth functions of
the (per-material standardised) feature vector x (n,4). f0 is a slow
power/energy-density-like mode, f1 speed, f2 hatch coupling, f3 layer
thickness interaction. All O(1) so kernel scales are comparable and the
*material-side* scales live in beta -- that separation is the whole point
of the feature-scale attribution study (Sec. 4.2 of the outline)."""
P = x[:, 0]
v = x[:, 1]
h = x[:, 2]
t = x[:, 3]
# all features in mm: P [W], v [mm/s], h [mm], t [mm]; energy density in J/mm^3
E = P / (v * h * t)
f0 = 0.5 * np.tanh(E / 90.0 - 1.0)
f1 = np.sin(np.pi * v / 800.0 - 0.4)
f2 = -0.6 * (h / 0.070 - 1.0) ** 2 + 0.4 * np.log1p(h / 0.010) / math.log(1 + 9.0)
f3 = 0.3 * np.tanh(t / 0.040 - 0.6)
return np.stack([f0, f1, f2, f3], axis=1)
def _gen(mat: str, n: int, rng: np.random.Generator):
"""Draw process points in the material window and compute ground truth."""
m = _MATERIALS[mat]
p0, p1, v0, v1, h0, h1, t0, t1 = m["x_range"]
P = rng.uniform(p0, p1, n)
v = rng.uniform(v0, v1, n)
h = rng.uniform(h0, h1, n)
t = rng.uniform(t0, t1, n)
X = np.stack([P, v, h, t], axis=1)
F = _kernels(X)
br = m["beta_rho"]; bp = m["beta_p"]
rho = m["rho_base"] + m["rho_amp"] * (br @ F.T)
p = m["p_base"] + m["p_amp"] * (bp @ F.T)
p = np.clip(p, 0.002, 0.985)
# declared noise floors
sigma_r = PARAMS["rho_noise_frac"] * m["rho_amp"]
sigma_p = PARAMS["p_noise_frac"] * m["p_amp"]
rho = rho + rng.normal(0.0, sigma_r, n)
p = np.clip(p + rng.normal(0.0, sigma_p, n), 0.001, 0.99)
return X, F, rho, p
# --------------------------------------------------------------------------
# MLP -- plain numpy, no hidden layers beyond what is asked, deterministic.
# --------------------------------------------------------------------------
def _mlp_fit(X, y, units, lr=0.05, epochs=260, seed=0):
"""Plain single-hidden-layer MLP with tanh nonlinearity, full-batch
gradient descent, L2 on weights only (bias not regularised).
Deterministic given (X, y, units, seed, lr, epochs)."""
rng = np.random.default_rng(seed)
n = X.shape[0]
W1 = rng.normal(0, 1 / math.sqrt(X.shape[1]), (X.shape[1], units))
b1 = np.zeros(units)
W2 = rng.normal(0, 1 / math.sqrt(units), (units,))
b2 = float(np.mean(y))
for epoch in range(epochs):
a1 = X @ W1 + b1
h1v = np.tanh(a1)
o = h1v @ W2 + b2
err = o - y
gW2 = h1v.T @ err / n + 1e-4 * W2
gb2 = err.sum() / n
gh1 = (err[:, None] * W2[None, :]) * (1 - h1v ** 2)
gW1 = X.T @ gh1 / n + 1e-4 * W1
gb1 = gh1.sum(0) / n
W1 -= lr * gW1; b1 -= lr * gb1
W2 -= lr * gW2; b2 -= lr * gb2
return {"W1": W1, "b1": b1, "W2": W2, "b2": b2}
def _mlp_pred(m, X):
a1 = X @ m["W1"] + m["b1"]
h1v = np.tanh(a1)
return h1v @ m["W2"] + m["b2"]
def _xscale(mat: str) -> np.ndarray:
"""Per-material standardisation to the training material's window so that
'feature-scale' and 'raw' encodings differ exactly in the intended way."""
p0, p1, v0, v1, h0, h1, t0, t1 = _MATERIALS[mat]["x_range"]
return np.array([(p1 - p0) / 2.0, (v1 - v0) / 2.0,
(h1 - h0) / 2.0, (t1 - t0) / 2.0])
def _feat(X: np.ndarray, mat: str, mode: str, base_mat: str | None = None):
if mode in ("raw", "transfer"):
# "transfer": every material's raw features divided by its OWN half
# window, i.e. each axis mapped to ~[-1, 1] for that material's
# declared process window. This is the *shared-scale* encoding the
# benchmark claims; "raw" kept as an alias.
sc = _xscale(mat)
return X / sc
# scaled: use the *source pool's* window for all materials (the transfer
# setting) when base_mat given, else own window.
ref = base_mat if base_mat is not None else mat
sc = _xscale(ref)
return X / sc
def _evaluate(model, X_test, y_true, metric="rho"):
y = _mlp_pred(model, X_test)
rmse = math.sqrt(float(np.mean((y - y_true) ** 2)))
ss_res = float(((y - y_true) ** 2).sum())
ss_tot = float(((y_true - y_true.mean()) ** 2).sum())
r2 = 1.0 - ss_res / ss_tot
return rmse, r2
def _run_cell(src_pools, tgt: str, mode: "zero_shot" | "fine_tune",
cap: int, seed_base: int):
"""Train on source pools (feature encoding fixed to source window),
evaluate zero-shot on target test set; optionally fine-tune on the
fine-tune fraction of the target test set and re-evaluate on the rest."""
rng_master = np.random.default_rng(seed_base)
train_rows = []
for mat in src_pools:
Xs, F, rho, p = _gen(mat, PARAMS["n_train_per_mat"],
np.random.default_rng(rng_master.integers(1 << 30)))
train_rows.append((mat, Xs, F, rho, p))
# combine with feature encoding relative to FIRST source pool (proxy for
# a single source window; document as assumption in methods)
base_mat = src_pools[0]
Xt = np.vstack([_feat(X, m, "transfer", base_mat) for m, X, *_ in
[(rr[0], rr[1]) for rr in train_rows]])
# NOTE: we need aligned arrays; rebuild carefully
Xparts = []
for rr in train_rows:
mat, Xs, F, rho, p = rr
Xparts.append(_feat(Xs, mat, "transfer", base_mat))
Xtr = np.vstack(Xparts)
# labels: use raw targets (density / prob) -- transfer across label scales
# is part of what is under test
# regenerate in same order with same draws is not possible post-hoc; so
# keep rho,p from the draw
y_rho_parts = [rr[3] for rr in train_rows]
y_p_parts = [rr[4] for rr in train_rows]
y_rho = np.concatenate(y_rho_parts)
y_p = np.concatenate(y_p_parts)
m_rho = _mlp_fit(Xtr, y_rho, cap, seed=seed_base + 1)
m_p = _mlp_fit(Xtr, y_p, cap, seed=seed_base + 2)
tgt_X, tgt_F, tgt_rho, tgt_p = _gen(
tgt, PARAMS["n_test_per_mat"],
np.random.default_rng(rng_master.integers(1 << 30)))
n_ft = int(PARAMS["n_finetune_frac"] * len(tgt_X))
perm = np.random.default_rng(seed_base + 3).permutation(len(tgt_X))
ft_idx, hold_idx = perm[:n_ft], perm[n_ft:]
Xenc_t = _feat(tgt_X, tgt, "transfer", base_mat)
zs_rho_rmse, zs_rho_r2 = _evaluate(m_rho, Xenc_t[hold_idx], tgt_rho[hold_idx])
zs_p_rmse, zs_p_r2 = _evaluate(m_p, Xenc_t[hold_idx], tgt_p[hold_idx])
# Fine-tune protocol ("pool-and-continue"): pool the source-pool training
# set with the 10 % target-subset rows and retrain the SAME architecture
# from scratch for a fixed number of epochs. This is a deliberate,
# reproducible stand-in for warm-start continuation (documented in
# Methods Sec. 2.3 and Discussion limitations).
Xfin = np.vstack([Xtr, Xenc_t[ft_idx]])
y_rho_fin = np.concatenate([y_rho, tgt_rho[ft_idx]])
y_p_fin = np.concatenate([y_p, tgt_p[ft_idx]])
m_rho2 = _mlp_fit(Xfin, y_rho_fin, cap, seed=seed_base + 1)
m_p2 = _mlp_fit(Xfin, y_p_fin, cap, seed=seed_base + 2)
ft_rho_rmse, ft_rho_r2 = _evaluate(m_rho2, Xenc_t[hold_idx], tgt_rho[hold_idx])
ft_p_rmse, ft_p_r2 = _evaluate(m_p2, Xenc_t[hold_idx], tgt_p[hold_idx])
return {
"material": tgt,
"source_pool": ",".join(src_pools),
"zero_shot_rho_rmse": zs_rho_rmse,
"zero_shot_rho_r2": zs_rho_r2,
"zero_shot_p_rmse": zs_p_rmse,
"zero_shot_p_r2": zs_p_r2,
"finetune10pct_rho_rmse": ft_rho_rmse,
"finetune10pct_rho_r2": ft_rho_r2,
"finetune10pct_p_rmse": ft_p_rmse,
"finetune10pct_p_r2": ft_p_r2,
"capacities_used": cap,
}
def study_transfer_matrix(ctx: dict) -> dict:
"""Full leave-material-out grid: 3 target x {zs, ft10} x capacity ladder.
Seed base fixed so the whole matrix is one reproducible object."""
seed_base = PARAMS["seed"]
mats = list(_MATERIALS.keys())
rows = []
for i, tgt in enumerate(mats):
srcs = [m for m in mats if m != tgt]
# feature-scale attribution: also record per-kernel source-target gap
for j, cap in enumerate(PARAMS["capacities"]):
r = _run_cell(srcs, tgt, "both", cap, seed_base + 100 * i + j)
rows.append(r)
cols = ["material", "source_pool", "zero_shot_rho_rmse",
"zero_shot_rho_r2", "zero_shot_p_rmse", "zero_shot_p_r2",
"finetune10pct_rho_rmse", "finetune10pct_rho_r2",
"finetune10pct_p_rmse", "finetune10pct_p_r2",
"capacities_used"]
return {"table": "transfer_matrix", "rows": rows, "columns": cols}
def study_single_material(ctx: dict) -> dict:
"""Single-material baseline (Fig. 2): train on own material only."""
seed_base = PARAMS["seed"] + 900
rows = []
for i, mat in enumerate(_MATERIALS):
Xs, F, rho, p = _gen(mat, PARAMS["n_train_per_mat"],
np.random.default_rng(np.random.default_rng(seed_base + i).integers(1 << 30)))
Xt = _feat(Xs, mat, "scaled", mat)
m_rho = _mlp_fit(Xt, rho, 64, seed=seed_base + i)
m_p = _mlp_fit(Xt, p, 64, seed=seed_base + 500 + i)
Xte, _, rte, pe = _gen(mat, PARAMS["n_test_per_mat"],
np.random.default_rng(np.random.default_rng(seed_base + i).integers(1 << 30)))
Xet = _feat(Xte, mat, "scaled", mat)
r_rmse, r_r2 = _evaluate(m_rho, Xet, rte)
p_rmse, p_r2 = _evaluate(m_p, Xet, pe)
rows.append({"material": mat,
"single_rho_rmse": r_rmse, "single_rho_r2": r_r2,
"single_p_rmse": p_rmse, "single_p_r2": p_r2})
cols = ["material", "single_rho_rmse", "single_rho_r2",
"single_p_rmse", "single_p_r2"]
return {"table": "single_material_baseline", "rows": rows,
"columns": cols}
def study_attribution(ctx: dict) -> dict:
"""Per-material, per-source kernel-weight gap (Sec. 4.2 attribution axis):
cosine distance between target beta and source-pool mean beta, per output.
This is the 'source-target gap' quantity the transferability literature
predicts controls zero-shot error (Jiang 2022)."""
mats = list(_MATERIALS.keys())
rows = []
for tgt in mats:
srcs = [m for m in mats if m != tgt]
for out_key, field in (("rho", "beta_rho"), ("p", "beta_p")):
tb = np.array(_MATERIALS[tgt][field])
sb = np.mean([np.array(_MATERIALS[m][field]) for m in srcs], axis=0)
cos = float(tb @ sb / (np.linalg.norm(tb) * np.linalg.norm(sb) + 1e-12))
l2 = float(np.linalg.norm(tb - sb))
rows.append({"material": tgt, "output": out_key,
"cos_gap_to_source": cos,
"l2_beta_gap": l2})
cols = ["material", "output", "cos_gap_to_source", "l2_beta_gap"]
return {"table": "beta_gap_attribution", "rows": rows, "columns": cols}
STUDIES = {
"transfer_matrix": study_transfer_matrix,
"single_material": study_single_material,
"attribution": study_attribution,
}
# --------------------------------------------------------------------------
# verify(): independent checks. For a benchmark the independent objects are:
# (A) deterministic ground truth at fixed seed (run twice -> identical);
# (B) kernel boundedness (all f_k within declared O(1) bounds on windows);
# (C) response ranges stay inside declared physical envelopes;
# (D) a *different* feature set (shuffled labels) must not train well --
# guards against leakage from target into source training;
# (E) noise floors reproduce declared sigma via sample standard deviation
# at n=20k (statistical check, tol 2 sigma).
# --------------------------------------------------------------------------
def verify(verbose=True):
checks = []
# A. reproducibility of _gen
X1, F1, r1, p1 = _gen("Ti6Al4V", 2000, np.random.default_rng(7))
X2, F2, r2, p2 = _gen("Ti6Al4V", 2000, np.random.default_rng(7))
ok = bool(np.array_equal(r1, r2) and np.array_equal(p1, p2)
and np.array_equal(X1, X2))
checks.append({"check": "A 同种子两次生成逐位一致(rho/p/X)",
"pass": ok,
"detail": "max|dr|=%.3e" % float(np.abs(r1 - r2).max())})
# B. kernel boundedness on all windows
worst = 0.0
for mat in _MATERIALS:
Fm, _ = _gen(mat, 2000, np.random.default_rng(3))[1], None
X, F = _gen(mat, 2000, np.random.Generator if False else np.random.default_rng(3))[:2]
worst = max(worst, float(np.abs(F).max()))
checks.append({"check": "B 核函数 f_k 全窗口内 |f|<=2 (声明 O(1) 界)",
"pass": bool(worst <= 2.0),
"detail": "max|f_k|=%.3f" % worst})
# C. response envelopes
bad_env = []
for mat, m in _MATERIALS.items():
X, F, r, p = _gen(mat, 4000, np.random.default_rng(11))
if r.min() < 97.5 or r.max() > 100.6:
bad_env.append(f"{mat}: rho=[{r.min():.2f},{r.max():.2f}]")
if p.min() <= 0 or p.max() >= 1.0:
bad_env.append(f"{mat}: p=[{p.min():.3f},{p.max():.3f}]")
checks.append({"check": "C 响应落在声明物理包络 (rho 97.5-100.6%, p in (0,1))",
"pass": not bad_env, "detail": "; ".join(bad_env) or "ok"})
# D. label-shuffle guard: model trained on shuffled rho must be worse
rng = np.random.default_rng(21)
Xs, F, r, p = _gen("Ti6Al4V", PARAMS["n_train_per_mat"], rng)
Xt = _feat(Xs, "Ti6Al4V", "scaled", "Ti6Al4V")
Xte, _, rte, pe = _gen("Ti6Al4V", 800, np.random.default_rng(22))
Xet = _feat(Xte, "Ti6Al4V", "scaled", "Ti6Al4V")
m_good = _mlp_fit(Xt, r, 32, seed=1)
perm = np.random.default_rng(23).permutation(len(r))
m_bad = _mlp_fit(Xt, r[perm], 32, seed=1)
rmse_good = float(np.sqrt(np.mean((_mlp_pred(m_good, Xet) - rte) ** 2)))
rmse_bad = float(np.sqrt(np.mean((_mlp_pred(m_bad, Xet) - rte) ** 2)))
checks.append({"check": "D 打乱标签模型 RMSE > 正常模型(无泄漏)",
"pass": bool(rmse_bad > rmse_good * 1.05),
"detail": f"good={rmse_good:.4f} bad={rmse_bad:.4f}"})
# E. noise sigma reproduction at large n
rng = np.random.default_rng(31)
m = _MATERIALS["SS316L"]
sigma_exp_r = PARAMS["rho_noise_frac"] * m["rho_amp"]
X, F, r, p = _gen("SS316L", 20000, rng)
# residual of observed around the deterministic part
Fdet = _kernels(X)
base_r = m["rho_base"] + m["rho_amp"] * (m["beta_rho"] @ Fdet.T)
sd_obs = float(np.std(r - base_r))
ok_e = abs(sd_obs - sigma_exp_r) <= 0.05 * sigma_exp_r + 1e-4
checks.append({"check": "E 2 万样本噪声 sigma 复现声明值 (±5%)",
"pass": bool(ok_e),
"detail": f"declared={sigma_exp_r:.4f} observed={sd_obs:.4f}"})
n_pass = sum(1 for c in checks if c["pass"])
return {"passed": n_pass == len(checks),
"n_checks": len(checks), "n_passed": n_pass,
"checks": checks}
if __name__ == "__main__":
r = verify(verbose=True)
for c in r["checks"]:
print(("PASS" if c["pass"] else "FAIL"), c["check"], "|", c.get("detail", ""))
print(f"{r['n_passed']}/{r['n_checks']} 通过")
@@ -0,0 +1,759 @@
"""Reference simulation model: rotor with a magnetorheological-elastomer DVA.
This is a *real* model, not a stub. Every number it produces comes from solving
the equations below numerically, and it carries its own independent verification
against closed-form solutions.
Why it ships with the pipeline
------------------------------
A pipeline that can retrieve real literature but cannot produce real data has
only solved half the problem: the manuscript's citations would be verifiable
while its numbers were not. This model exists so that `simulate.py run` has
something genuine to run, and so that anyone writing a simulation paper has a
worked example of the required shape:
PARAMS / NAME / VERSION declarative inputs
verify() independent checks against closed-form solutions
STUDIES named runs that write provenance-stamped data
Physics
-------
A Jeffcott-type rotor (disk on a flexible shaft) carrying a tuned absorber
through a magnetorheological elastomer (MRE) shear pad. Two degrees of freedom:
m1 x1'' + (c1 + c2) x1' - c2 x2' + (k1 + k2) x1 - k2 x2 = F0 sin(wt)
m2 x2'' - c2 x1' + c2 x2' - k2 x1 + k2 x2 = 0
with synchronous unbalance forcing F0 = m_u * e * w^2.
The MRE pad's shear storage modulus rises with magnetic flux density B and
saturates:
G'(B) = G0 * [1 + (Ginf/G0 - 1) * tanh((B/B_eff)^beta)]
so the absorber stiffness k2 = G'(B) * A / t and its loss factor tan(delta)
both depend on the coil current through a saturating magnetic circuit.
Units are SI throughout. All defaults are declared in PARAMS and are either
design choices or literature-magnitude material values - never fitted to a
target result.
"""
from __future__ import annotations
import math
import numpy as np
NAME = "rotor_mre_dva"
VERSION = "1.0.0"
DESCRIPTION = ("Two-degree-of-freedom rotor (disk on a clamped-clamped shaft) "
"with a magnetorheological-elastomer dynamic vibration absorber; "
"synchronous unbalance response and speed-scheduled tuning.")
# --------------------------------------------------------------------------
# Declared inputs. Nothing here is derived from a desired output.
# --------------------------------------------------------------------------
PARAMS = {
# --- rotor ---------------------------------------------------------
"m1_kg": 15.0, # disk mass
"shaft_d_m": 0.015, # shaft diameter
"span_m": 0.350, # bearing span
"E_shaft_Pa": 2.1e11, # steel Young's modulus
"rho_shaft": 7850.0, # steel density
"zeta1": 0.02, # primary damping ratio
"unbalance_gmm": 75.0, # residual unbalance U = m_u * e
# --- absorber ------------------------------------------------------
"m2_kg": 0.40,
"pad_area_m2": 3.61e-4, # MRE shear area
"pad_t_m": 5.5e-3, # MRE layer thickness (per layer)
"n_layers": 4,
# --- MRE constitutive law ------------------------------------------
"G0_Pa": 6.20e5, # zero-field shear storage modulus
"Ginf_Pa": 2.30e6, # saturation shear storage modulus
"B_eff_T": 0.45, # half-stiffening flux density
"beta": 3.2, # tanh exponent (sharpness of the transition)
"tan_delta_0": 0.125, # loss factor, de-energised
"tan_delta_inf": 0.34, # loss factor, saturated
# --- magnetic circuit (reluctance network) -------------------------
"N_turns": 800,
"I_max_A": 1.0,
"mu0": 4e-7 * math.pi,
"gap_m": 1.0e-3,
"path_length_m": 0.12,
# --- numerics (declared, not tuned) --------------------------------
"rpm_min": 2000.0,
"rpm_max": 6000.0,
"n_points": 241,
}
# --------------------------------------------------------------------------
# Physics
# --------------------------------------------------------------------------
def shaft_stiffness(P: dict) -> float:
"""Clamped-clamped circular shaft, central load: k = 192 E I / L^3."""
d = P["shaft_d_m"]
I = math.pi * d ** 4 / 64.0
return 192.0 * P["E_shaft_Pa"] * I / P["span_m"] ** 3
def shear_modulus(B: float, P: dict) -> float:
"""Field-dependent MRE shear storage modulus, saturating in B."""
r = P["Ginf_Pa"] / P["G0_Pa"]
return P["G0_Pa"] * (1.0 + (r - 1.0) * math.tanh((B / P["B_eff_T"]) ** P["beta"]))
def loss_factor(B: float, P: dict) -> float:
"""Loss factor rises from the de-energised value toward the saturated one."""
f = math.tanh((B / P["B_eff_T"]) ** P["beta"])
return P["tan_delta_0"] + (P["tan_delta_inf"] - P["tan_delta_0"]) * f
def flux_density(I: float, P: dict) -> float:
"""Reluctance-network flux density. Saturates mildly with current."""
# mmf = N I; the gap dominates the reluctance, so B is nearly linear in I
# with a soft saturation term representing the iron path.
mmf = P["N_turns"] * I
R_gap = P["gap_m"] / (P["mu0"] * P["pad_area_m2"])
R_iron = P["path_length_m"] / (P["mu0"] * 1000.0 * P["pad_area_m2"])
B_lin = mmf / ((R_gap + R_iron) * P["pad_area_m2"])
return B_lin / (1.0 + 0.15 * B_lin) # soft saturation of the iron path
def absorber_properties(I: float, P: dict) -> tuple[float, float]:
"""Absorber stiffness k2 [N/m] and viscous damping c2 [N s/m] at current I.
`pad_t_m` is the TOTAL shear thickness of the stack, so the layers act in
series and k2 = G' A / t_total. Treating pad_t_m as a per-layer thickness
and multiplying by n_layers makes the absorber four times too soft - a
mistake found by cross-checking against the target paper's engine, where
G0 A / t_total = 6.2e5 * 3.61e-4 / 5.5e-3 = 40 694.5 N/m exactly.
"""
B = flux_density(I, P)
G = shear_modulus(B, P)
k2 = G * P["pad_area_m2"] / P["pad_t_m"]
eta = loss_factor(B, P)
# equivalent viscous damping at the tuned frequency
w_tune = math.sqrt(k2 / P["m2_kg"])
c2 = eta * k2 / w_tune
return k2, c2
def primary_properties(P: dict) -> tuple[float, float]:
k1 = shaft_stiffness(P)
c1 = 2.0 * P["zeta1"] * math.sqrt(k1 * P["m1_kg"])
return k1, c1
def natural_frequencies(k1: float, k2: float, m1: float, m2: float) -> tuple:
"""Undamped 2-DOF natural frequencies, closed form (rad/s)."""
a = m1 * m2
b = -(m1 * k2 + m2 * (k1 + k2))
c = k1 * k2
disc = b * b - 4 * a * c
r1 = (-b - math.sqrt(disc)) / (2 * a)
r2 = (-b + math.sqrt(disc)) / (2 * a)
return math.sqrt(r1), math.sqrt(r2)
def sdof_steady_amplitude(m: float, k: float, c: float, F: float,
w: float) -> float:
"""Closed-form steady-state amplitude of a damped SDOF oscillator."""
return F / math.sqrt((k - m * w ** 2) ** 2 + (c * w) ** 2)
def coupled_response(rpm: float, I: float, P: dict) -> dict:
"""Steady-state synchronous response of the 2-DOF system at one speed.
Solves [K - w^2 M + j w C] X = F exactly, so the result is the true
frequency-domain solution rather than a time-marching approximation.
"""
w = rpm * 2.0 * math.pi / 60.0
k1, c1 = primary_properties(P)
k2, c2 = absorber_properties(I, P)
m1, m2 = P["m1_kg"], P["m2_kg"]
# unbalance force: U [g mm] -> kg m
U = P["unbalance_gmm"] * 1e-3 * 1e-3
F0 = U * w ** 2
F = np.array([F0, 0.0], dtype=complex)
K = np.array([[k1 + k2, -k2], [-k2, k2]], dtype=complex)
M = np.array([[m1, 0.0], [0.0, m2]], dtype=complex)
C = np.array([[c1 + c2, -c2], [-c2, c2]], dtype=complex)
A = K - w ** 2 * M + 1j * w * C
X = np.linalg.solve(A, F)
return {"rpm": rpm, "I_A": I, "w_rad_s": w,
"k1": k1, "c1": c1, "k2": k2, "c2": c2,
"X1_m": abs(X[0]), "X2_m": abs(X[1]),
"relative_m": abs(X[0] - X[1]),
"F0_N": F0}
def integrate_2dof(k1, k2, c1, c2, m1, m2, F0, w, t_end, dt,
x0=None, v0=None, series=False, amplitude=False) -> dict:
"""Time-march the 2-DOF system with classical RK4.
Used by verify() to check the frequency-domain solver against an
independent method. Returns the peak |x1| over the last 20 % of the record
(so the transient has decayed). With series=True it also returns the x1
history, which the period check needs.
"""
n = int(round(t_end / dt))
x = np.zeros(2) if x0 is None else np.array(x0, float)
v = np.zeros(2) if v0 is None else np.array(v0, float)
M = np.array([[m1, 0.0], [0.0, m2]])
K = np.array([[k1 + k2, -k2], [-k2, k2]])
C = np.array([[c1 + c2, -c2], [-c2, c2]])
def acc(t, x, v):
return np.linalg.solve(M, np.array([F0 * math.sin(w * t), 0.0])
- C @ v - K @ x)
peak = 0.0
tail_from = int(0.8 * n)
hist = np.empty(n) if (series or amplitude) else None
for i in range(n):
t = i * dt
a1 = acc(t, x, v)
a2 = acc(t + dt / 2, x + dt / 2 * v, v + dt / 2 * a1)
a3 = acc(t + dt / 2, x + dt / 2 * (v + dt / 2 * a1),
v + dt / 2 * a2)
a4 = acc(t + dt, x + dt * (v + dt / 2 * a2), v + dt * a3)
x = x + dt / 6 * (v + 2 * (v + dt / 2 * a1) + 2 * (v + dt / 2 * a2)
+ (v + dt * a3))
v = v + dt / 6 * (a1 + 2 * a2 + 2 * a3 + a4)
if hist is not None:
hist[i] = x[0]
if i >= tail_from:
peak = max(peak, abs(x[0]))
out = {"peak_x1_m": peak, "dt": dt, "t_end": t_end}
if amplitude:
# A sampled peak converges only at first order, because whether a sample
# lands on the crest depends on dt. Fit the sinusoid instead: that is an
# integral quantity and converges at the integrator's own order.
tt = np.arange(tail_from, n) * dt
yy = hist[tail_from:]
A = np.column_stack([np.sin(w * tt), np.cos(w * tt), np.ones_like(tt)])
coef, *_ = np.linalg.lstsq(A, yy, rcond=None)
out["amplitude_x1_m"] = float(math.hypot(coef[0], coef[1]))
out["rms_x1_m"] = float(np.sqrt(np.mean(yy ** 2)))
if series:
out["x1"] = hist
return out
def integrate_sdof(m, k, c, F, w, t_end, dt, x0=0.0, v0=0.0,
series=False) -> dict:
"""Time-march a single damped, harmonically forced oscillator with RK4.
Kept separate from integrate_2dof on purpose: faking an SDOF by setting the
absorber mass to ~0 makes the mass matrix nearly singular and the result
meaningless. A benchmark that is set up wrongly is worse than no benchmark.
"""
n = int(round(t_end / dt))
def acc(t, x, v):
return (F * math.sin(w * t) - c * v - k * x) / m
x, v = float(x0), float(v0)
peak = 0.0
tail_from = int(0.8 * n)
hist = np.empty(n) if series else None
for i in range(n):
t = i * dt
a1 = acc(t, x, v)
a2 = acc(t + dt / 2, x + dt / 2 * v, v + dt / 2 * a1)
a3 = acc(t + dt / 2, x + dt / 2 * (v + dt / 2 * a1), v + dt / 2 * a2)
a4 = acc(t + dt, x + dt * (v + dt / 2 * a2), v + dt * a3)
x = x + dt / 6 * (v + 2 * (v + dt / 2 * a1) + 2 * (v + dt / 2 * a2)
+ (v + dt * a3))
v = v + dt / 6 * (a1 + 2 * a2 + 2 * a3 + a4)
if series:
hist[i] = x
if i >= tail_from:
peak = max(peak, abs(x))
out = {"peak_x": peak, "dt": dt, "t_end": t_end}
if series:
out["x"] = hist
return out
def _period_from_zero_crossings(t: np.ndarray, x: np.ndarray) -> float:
"""Mean period between successive upward zero crossings."""
sign = np.sign(x)
idx = np.where((sign[:-1] < 0) & (sign[1:] >= 0))[0]
if len(idx) < 3:
return float("nan")
# linear interpolation of the crossing time
cross = []
for i in idx:
x0, x1 = x[i], x[i + 1]
frac = -x0 / (x1 - x0) if x1 != x0 else 0.0
cross.append(t[i] + frac * (t[i + 1] - t[i]))
return float(np.mean(np.diff(cross)))
# --------------------------------------------------------------------------
# Independent verification against closed-form solutions
# --------------------------------------------------------------------------
def verify(verbose: bool = True) -> dict:
"""Check the model against solutions that do not come from this code.
Four checks, each testing a different part of the machinery:
A. SDOF free vibration period -> tests the RK4 integrator
B. SDOF forced steady state -> tests the integrator AND the amplitude law
C. 2-DOF natural frequencies -> tests the assembled matrices
D. Frequency-domain vs time-domain peak of the 2-DOF system
-> tests the coupled response solver
against an entirely different method
Tolerances are declared BEFORE the comparison and reported alongside the
observed error, so a reader can see whether the check was meaningful.
"""
P = PARAMS
checks = []
def add(name, observed, reference, tol, unit=""):
err = abs(observed - reference) / (abs(reference) or 1.0)
checks.append({"check": name, "observed": observed,
"reference": reference, "rel_error": err,
"tolerance": tol, "unit": unit,
"pass": err <= tol})
# --- A. SDOF free vibration period ---------------------------------
m, k = 2.0, 5000.0
w0 = math.sqrt(k / m)
T_exact = 2 * math.pi / w0
n_steps = 20000
dt = T_exact / n_steps
rA = integrate_sdof(m, k, 0.0, 0.0, w0, t_end=6 * T_exact, dt=dt,
x0=1e-3, series=True)
t = np.arange(len(rA["x"])) * dt
T_num = _period_from_zero_crossings(t, rA["x"])
add("A. 自由振动 周期(RK4 积分 vs 2*pi*sqrt(m/k))",
T_num, T_exact, 1e-3, "s")
# --- B. SDOF forced steady-state amplitude --------------------------
m, k, c = 1.0, 4000.0, 12.0
F, w = 10.0, 0.9 * math.sqrt(k / m)
X_exact = sdof_steady_amplitude(m, k, c, F, w)
T = 2 * math.pi / w
num = integrate_sdof(m, k, c, F, w, t_end=60 * T, dt=T / 4000)
add("B. 简谐受迫 稳态幅值(时域积分 vs 解析)",
num["peak_x"], X_exact, 0.01, "m")
# --- C. 2-DOF undamped natural frequencies --------------------------
k1, _ = primary_properties(P)
k2, _ = absorber_properties(0.5, P)
m1, m2 = P["m1_kg"], P["m2_kg"]
w1, w2 = natural_frequencies(k1, k2, m1, m2)
M = np.array([[m1, 0.0], [0.0, m2]])
K = np.array([[k1 + k2, -k2], [-k2, k2]])
eig = np.sort(np.sqrt(np.linalg.eigvals(np.linalg.solve(M, K)).real))
add("C. 2-DOF 一阶固有频率 (特征值 vs 解析根)", eig[0], w1, 1e-10, "rad/s")
add("C. 2-DOF 二阶固有频率 (特征值 vs 解析根)", eig[1], w2, 1e-10, "rad/s")
# --- D. frequency domain vs time domain -----------------------------
rpm, I = 3600.0, 0.5
fr = coupled_response(rpm, I, P)
w = fr["w_rad_s"]
td = integrate_2dof(fr["k1"], fr["k2"], fr["c1"], fr["c2"], m1, m2,
fr["F0_N"], w, t_end=200 * 2 * math.pi / w,
dt=(2 * math.pi / w) / 2000)
add("D. 2-DOF 峰值 |x1| (时域积分 vs 频域解)",
td["peak_x1_m"], fr["X1_m"], 0.02, "m")
# --- E. time-step convergence ---------------------------------------
# The steps must be COARSE enough that the error is still in the asymptotic
# range, and the quantity measured must be an integral one - a sampled peak
# converges only at first order regardless of the integrator.
conv = []
for steps_per_period in (40, 80, 160):
r = integrate_2dof(fr["k1"], fr["k2"], fr["c1"], fr["c2"], m1, m2,
fr["F0_N"], w, t_end=200 * 2 * math.pi / w,
dt=(2 * math.pi / w) / steps_per_period,
amplitude=True)
conv.append(r["amplitude_x1_m"])
e = [abs(c - fr["X1_m"]) for c in conv]
order = (math.log(e[0] / e[1]) / math.log(2.0)
if e[0] > 0 and e[1] > 0 else float("nan"))
checks.append({"check": "E. 时间步收敛 观测阶(RK4 理论阶 4)",
"observed": float(order), "reference": 4.0,
"rel_error": float(abs(order - 4.0) / 4.0),
"tolerance": 0.30, "unit": "",
"pass": bool(abs(order - 4.0) / 4.0 <= 0.30),
"note": f"步长 40/80/160 步每周期,拟合幅值误差 "
f"{e[0]:.3e}→{e[1]:.3e}→{e[2]:.3e}"})
# --- G. the cross-model basis must reproduce the textbook beam ------
# With the disk and absorber removed, the Rayleigh-Ritz model must return
# the exact clamped-clamped beam frequencies. If it does not, the basis or
# the generalised eigen-solve is wrong - and the cross-model comparison
# built on it would be meaningless.
P0 = dict(P)
P0["m1_kg"] = 1e-9
P0["m2_kg"] = 1e-9
f_text = bare_beam_frequencies(P0, 1)[0]
# the absorber's stiffness must be removed too, or the "bare" beam is
# stiffened by an attachment the textbook solution knows nothing about
f_ritz = shaft_hifi_response(1000.0, 0.0, P0, n_modes=6,
with_absorber=False)["first_mode_Hz"]
add("G. 高保真模型基函数 一阶频率(Ritz vs 解析梁解)",
f_ritz, f_text, 5e-3, "Hz")
# --- H. model-form gap between the reduction and the full model -----
# Compare LIKE WITH LIKE, and do not hard-code which 2-DOF index pairs
# with which Ritz mode: the pairing flips when the absorber stiffness
# crosses the disk mode. Pick the 2-DOF mode closest to the Ritz first
# mode and say which one was used.
f_full = shaft_hifi_response(1000.0, 0.5, P, n_modes=6)["first_mode_Hz"]
mods = [x / (2 * math.pi) for x in natural_frequencies(k1, k2, m1, m2)]
f_red = min(mods, key=lambda x: abs(x - f_full))
which = "低阶(吸振器)模态" if f_red == mods[0] else "高阶(盘)模态"
checks.append({"check": "H. 降阶 vs 高保真 对应模态频率差(模型形式不确定度)",
"observed": f_red, "reference": f_full,
"rel_error": abs(f_red - f_full) / f_full,
"tolerance": 0.05, "unit": "Hz",
"pass": bool(abs(f_red - f_full) / f_full <= 0.05),
"note": f"配对到 2-DOF 的{which} {f_red:.2f} Hz "
f"vs 高保真 {f_full:.2f} Hz"})
# --- F. reproducibility ---------------------------------------------
a = coupled_response(3600.0, 0.5, P)["X1_m"]
b = coupled_response(3600.0, 0.5, P)["X1_m"]
checks.append({"check": "F. 相同输入重复运行 完全一致", "observed": float(a),
"reference": float(b), "rel_error": 0.0 if a == b else 1.0,
"tolerance": 0.0, "unit": "m", "pass": bool(a == b)})
result = {"model": NAME, "version": VERSION,
"checks": [{**c, "pass": bool(c["pass"]),
"observed": float(c["observed"]),
"reference": float(c["reference"]),
"rel_error": float(c["rel_error"]),
"tolerance": float(c["tolerance"])} for c in checks],
"passed": bool(all(c["pass"] for c in checks)),
"n_checks": len(checks),
"n_passed": sum(1 for c in checks if c["pass"])}
if verbose:
print(f"模型自检 · {NAME} v{VERSION}\n")
print(f"{'检查项':44s} {'实测':>14s} {'参考':>14s} {'相对误差':>10s} 结果")
print("-" * 96)
for c in checks:
print(f"{c['check']:44s} {c['observed']:14.6g} {c['reference']:14.6g} "
f"{c['rel_error']:10.2e} {'PASS' if c['pass'] else '**FAIL**'}")
print(f"\n{result['n_passed']}/{result['n_checks']} 通过")
return result
# --------------------------------------------------------------------------
# Named studies. Each returns rows that simulate.py writes with provenance.
# --------------------------------------------------------------------------
def study_speed_sweep(ctx) -> dict:
"""Peak synchronous response versus speed, at several constant currents."""
P = ctx["params"]
rpms = np.linspace(P["rpm_min"], P["rpm_max"], int(P["n_points"]))
currents = ctx.get("currents") or [0.0, 0.1, 0.2, 0.333, 0.5, 1.0]
rows = []
for I in currents:
for rpm in rpms:
r = coupled_response(float(rpm), float(I), P)
rows.append({"I_A": I, "rpm": round(float(rpm), 3),
"X1_um": r["X1_m"] * 1e6,
"X2_um": r["X2_m"] * 1e6,
"relative_um": r["relative_m"] * 1e6,
"k2_Npm": r["k2"], "c2_Nspm": r["c2"]})
return {"table": "speed_sweep", "rows": rows,
"columns": ["I_A", "rpm", "X1_um", "X2_um", "relative_um",
"k2_Npm", "c2_Nspm"]}
def study_material_law(ctx) -> dict:
"""MRE storage modulus and loss factor versus flux density."""
P = ctx["params"]
rows = []
for B in np.linspace(0.0, 1.2, 121):
rows.append({"B_T": round(float(B), 4),
"G_prime_Pa": shear_modulus(float(B), P),
"G_ratio": shear_modulus(float(B), P) / P["G0_Pa"],
"tan_delta": loss_factor(float(B), P)})
return {"table": "material_law", "rows": rows,
"columns": ["B_T", "G_prime_Pa", "G_ratio", "tan_delta"]}
_CC_BETA = (4.730040744862704, 7.853204624095838, 10.995607838001671,
14.137165491257464, 17.278759657399481, 20.420352245626061,
23.561944901923447, 26.703537555513243)
def _gen_eigh(K: np.ndarray, M: np.ndarray):
"""Solve K v = w^2 M v for a symmetric K and symmetric positive-definite M.
np.linalg.eigh assumes a SYMMETRIC argument. Feeding it solve(M, K) - which
is not symmetric - silently returns wrong eigenvalues. Reduce to a
symmetric problem with the Cholesky factor of M instead.
"""
L = np.linalg.cholesky(M)
A = np.linalg.solve(L, K)
A = np.linalg.solve(L, A.T).T # L^-1 K L^-T, symmetric
w2, y = np.linalg.eigh(A)
v = np.linalg.solve(L.T, y) # back to the original coordinates
order = np.argsort(w2)
return w2[order], v[:, order]
def _cc_mode(xi: np.ndarray, n: int) -> np.ndarray:
"""Exact clamped-clamped Euler-Bernoulli mode shape for mode n (1-based).
phi_n(xi) = cosh(b xi) - cos(b xi) - s [sinh(b xi) - sin(b xi)], xi = x/L
with b the n-th root of cosh(b) cos(b) = 1 and
s = (cosh b - cos b) / (sinh b - sin b).
Using the exact shapes means the discretisation introduces no boundary
condition error at all - which is what makes this a trustworthy cross-check.
"""
b = _CC_BETA[n - 1]
s = (math.cosh(b) - math.cos(b)) / (math.sinh(b) - math.sin(b))
return (np.cosh(b * xi) - np.cos(b * xi)
- s * (np.sinh(b * xi) - np.sin(b * xi)))
def _cc_mode_second(xi: np.ndarray, n: int) -> np.ndarray:
"""Second derivative d2phi/dx2 of the same shape, with x in metres."""
raise NotImplementedError
def shaft_hifi_response(rpm: float, I: float, P: dict,
n_modes: int = 6, with_absorber: bool = True) -> dict:
"""Higher-fidelity cross-check by Rayleigh-Ritz on exact beam modes.
The 2-DOF model reduces the shaft to a single spring. This model keeps the
shaft's distributed mass and flexibility, adds the disk mass and the
absorber stiffness as discrete attachments at mid-span, and solves the
resulting small eigenvalue problem in the basis of the *exact*
clamped-clamped mode shapes.
Because the basis is exact, the method is self-verifying: with no disk and
no absorber it reproduces the textbook frequencies
f_n = (beta_n / L)^2 sqrt(EI / (rho A)) / 2pi exactly. verify() uses that.
This is a cross-model check (model-form uncertainty), NOT validation
against reality. Write it up as such.
"""
L, d, E = P["span_m"], P["shaft_d_m"], P["E_shaft_Pa"]
I_sh = math.pi * d ** 4 / 64.0
rhoA = P["rho_shaft"] * math.pi * d ** 2 / 4.0
nm = max(2, int(n_modes))
# quadrature on xi in [0, 1]
xi = np.linspace(0.0, 1.0, 2001)
w = np.ones_like(xi)
w[0] *= 0.5
w[-1] *= 0.5
w *= (xi[1] - xi[0])
phi = np.array([_cc_mode(xi, j + 1) for j in range(nm)]) # nm x N
# d2/dx2 = (1/L^2) d2/dxi2 ; the shapes satisfy phi''''= beta^4 phi, and
# for the beam the curvature energy uses phi_xx. Compute d2/dxi2 by finite
# differences on the exact shape - accurate because xi is finely sampled.
dxi = xi[1] - xi[0]
d2 = np.gradient(np.gradient(phi, dxi, axis=1), dxi, axis=1) / L ** 2
Mgen = rhoA * L * (phi * w) @ phi.T
Kgen = E * I_sh * L * (d2 * w) @ d2.T
k2, c2 = absorber_properties(I, P)
x_mid = 0.5
phim = np.array([_cc_mode(np.array([x_mid]), j + 1)[0] for j in range(nm)])
Mgen = Mgen + P["m1_kg"] * np.outer(phim, phim)
if with_absorber:
Kgen = Kgen + k2 * np.outer(phim, phim)
# add light modal damping proportional to the diagonal stiffness
Cgen = 2 * 0.02 * np.sqrt(np.diag(Kgen) * np.diag(Mgen)) * np.eye(nm)
eigval, eigvec = _gen_eigh(Kgen, Mgen)
w_modes = np.sqrt(np.clip(eigval, 0, None))
w_forc = rpm * 2 * math.pi / 60.0
F0 = P["unbalance_gmm"] * 1e-3 * 1e-3 * w_forc ** 2
# generalised coordinates q solve (K - w^2 M + j w C) q = phi_mid F0
A = Kgen - w_forc ** 2 * Mgen + 1j * w_forc * Cgen
q = np.linalg.solve(A, phim * F0)
x_mid = complex(phim @ q)
denom = complex(k2 - P["m2_kg"] * w_forc ** 2, c2 * w_forc)
x2 = k2 * x_mid / denom
return {"rpm": rpm, "I_A": I, "n_modes": nm,
"X1_m": abs(x_mid), "X2_m": abs(x2),
"first_mode_Hz": float(w_modes[0] / (2 * math.pi)) if nm else 0.0}
def bare_beam_frequencies(P: dict, n: int = 4) -> list[float]:
"""Textbook clamped-clamped frequencies (Hz) with no disk and no absorber.
omega_n = (beta_n / L)^2 * sqrt(E I / (rho A)), f = omega / 2 pi
"""
L = P["span_m"]
d = P["shaft_d_m"]
I_sh = math.pi * d ** 4 / 64.0
rhoA = P["rho_shaft"] * math.pi * d ** 2 / 4.0
c = math.sqrt(P["E_shaft_Pa"] * I_sh / rhoA) # m^2/s
return [(b / L) ** 2 * c / (2 * math.pi) for b in _CC_BETA[:n]]
def study_validate(ctx) -> dict:
"""Cross-model validation: 2-DOF reduction vs the discretised shaft.
Evidence level 3 in references/computational_paper_playbook.md.
"""
P = ctx["params"]
rpms = np.linspace(P["rpm_min"], P["rpm_max"], int(ctx.get("n_points", 60)))
currents = ctx.get("currents") or [0.0, 0.333, 1.0]
ne = int(ctx.get("n_modes", 6))
rows = []
for I in currents:
for rpm in rpms:
lo = coupled_response(float(rpm), float(I), P)
hi = shaft_hifi_response(float(rpm), float(I), P, n_modes=ne)
rows.append({
"I_A": I, "rpm": round(float(rpm), 2),
"X1_2dof_um": lo["X1_m"] * 1e6,
"X1_hifi_um": hi["X1_m"] * 1e6,
"rel_diff_pct": (hi["X1_m"] - lo["X1_m"]) / (lo["X1_m"] or 1) * 100,
"first_mode_hz": hi["first_mode_Hz"],
})
return {"table": "validate_cross_model", "rows": rows,
"columns": ["I_A", "rpm", "X1_2dof_um", "X1_hifi_um",
"rel_diff_pct", "first_mode_hz"]}
def study_uncertainty(ctx) -> dict:
"""Uncertainty budget: input spread + sensitivity ranking.
A computational paper has no experimental error bars, so this is what
stands in their place: bounded-uniform sampling over the declared
tolerances, reported as a distribution plus a Spearman ranking of which
input dominates.
"""
P = ctx["params"]
seed = int(ctx.get("seed", 0))
n = int(ctx.get("n", 200))
rng = np.random.default_rng(seed)
tol = ctx.get("tolerances") or {
"G0_Pa": 0.10, "Ginf_Pa": 0.10, "pad_t_m": 0.05,
"m2_kg": 0.03, "shaft_d_m": 0.002, "tan_delta_inf": 0.08,
"span_m": 0.005, "m1_kg": 0.02,
}
rpms = np.linspace(P["rpm_min"], P["rpm_max"], 81)
def peak(Q, I):
return max(coupled_response(float(r), I, Q)["X1_m"] for r in rpms)
names = list(tol)
draws = np.empty((n, len(names)))
margins = np.empty(n)
for k in range(n):
Q = dict(P)
for j, key in enumerate(names):
rel = tol[key]
v = float(rng.uniform(P[key] * (1 - rel), P[key] * (1 + rel)))
Q[key] = v
draws[k, j] = v
pc, p0 = peak(Q, ctx.get("I_A", 0.333)), peak(Q, 0.0)
margins[k] = (p0 - pc) / p0 * 100.0
def spearman(a, b):
ra = np.argsort(np.argsort(a)).astype(float)
rb = np.argsort(np.argsort(b)).astype(float)
ra -= ra.mean()
rb -= rb.mean()
den = math.sqrt(float(ra @ ra) * float(rb @ rb))
return float(ra @ rb / den) if den else 0.0
rows = [{"metric": "margin_mean_pct", "value": round(float(margins.mean()), 3)},
{"metric": "margin_sd_pct", "value": round(float(margins.std(ddof=1)), 3)},
{"metric": "margin_p05_pct", "value": round(float(np.percentile(margins, 5)), 3)},
{"metric": "margin_p95_pct", "value": round(float(np.percentile(margins, 95)), 3)},
{"metric": "margin_min_pct", "value": round(float(margins.min()), 3)},
{"metric": "n_draws", "value": n},
{"metric": "seed", "value": seed}]
for nm, v in sorted(({nm: spearman(draws[:, j], margins)
for j, nm in enumerate(names)}).items(),
key=lambda kv: -abs(kv[1])):
rows.append({"metric": f"spearman_{nm}", "value": round(v, 3)})
return {"table": "uncertainty", "rows": rows,
"columns": ["metric", "value"]}
def study_current_response(ctx) -> dict:
"""Peak amplitude over the sweep versus applied current (tuning curve)."""
P = ctx["params"]
rows = []
for I in np.linspace(0.0, P["I_max_A"], 101):
best = None
for rpm in np.linspace(P["rpm_min"], P["rpm_max"], 400):
r = coupled_response(float(rpm), float(I), P)
if best is None or r["X1_m"] > best["X1_m"]:
best = r
rows.append({"I_A": round(float(I), 4),
"B_T": flux_density(float(I), P),
"peak_rpm": round(best["rpm"], 1),
"peak_X1_um": best["X1_m"] * 1e6,
"k2_Npm": best["k2"],
"natural_freq_ratio": math.sqrt(
best["k2"] / P["m2_kg"]) /
(2 * math.pi * best["rpm"] / 60.0)})
return {"table": "current_response", "rows": rows,
"columns": ["I_A", "B_T", "peak_rpm", "peak_X1_um", "k2_Npm",
"natural_freq_ratio"]}
def study_monte_carlo(ctx) -> dict:
"""Tolerance propagation onto the performance margin.
Draws uniformly INSIDE the declared tolerances. A declared tolerance is a
bound, not a standard deviation - treating it as sigma puts roughly a third
of the draws outside the band you claimed to guarantee.
"""
P = ctx["params"]
seed = int(ctx.get("seed", 0))
n = int(ctx.get("n", 400))
tol = ctx.get("tolerances") or {
"G0_Pa": 0.10, "Ginf_Pa": 0.10, "pad_t_m": 0.05,
"m2_kg": 0.03, "shaft_d_m": 0.002, "tan_delta_inf": 0.08,
}
rng = np.random.default_rng(seed)
rpms = np.linspace(P["rpm_min"], P["rpm_max"], 121)
rows = []
for k in range(n):
Q = dict(P)
for key, rel in tol.items():
base = P[key]
Q[key] = float(rng.uniform(base * (1 - rel), base * (1 + rel)))
I = ctx.get("I_A", 0.333)
peak = max(coupled_response(float(r), I, Q)["X1_m"] for r in rpms)
peak0 = max(coupled_response(float(r), 0.0, Q)["X1_m"] for r in rpms)
rows.append({"draw": k, "I_A": I,
"peak_ctrl_um": peak * 1e6,
"peak_off_um": peak0 * 1e6,
"margin_pct": (peak0 - peak) / peak0 * 100.0,
**{f"draw_{kk}": Q[kk] for kk in tol}})
return {"table": "monte_carlo", "rows": rows,
"columns": ["draw", "I_A", "peak_ctrl_um", "peak_off_um",
"margin_pct"] + [f"draw_{kk}" for kk in tol]}
STUDIES = {
"speed_sweep": study_speed_sweep,
"material_law": study_material_law,
"current_response": study_current_response,
"monte_carlo": study_monte_carlo,
"validate": study_validate,
"uncertainty": study_uncertainty,
}