"""统计分析:蒙特卡洛重复、参数扫描、置信区间、失败率(仅依赖 numpy/scipy)。 对应 docs/实现方案.md §7.6 与 §8。 gen_fn 为可调用对象:gen_fn(seed, **params) -> tau_hat(float), 由调用方(pipeline)注入,保证本模块与具体模型解耦(Pyodide 兼容)。 """ import numpy as np def failure_rate(tau_hats, tau_true, tol=0.05): """失败率:|τ̂−τ|/τ > tol 的比例。""" arr = np.asarray(tau_hats, dtype=float) if tau_true is None or tau_true == 0 or len(arr) == 0: return 0.0 rel = np.abs(arr - tau_true) / tau_true return float(np.mean(rel > tol)) def confidence_interval(tau_hats, level=0.95): """正态近似置信区间(大样本/教学用);附标准差。""" arr = np.asarray(tau_hats, dtype=float) n = len(arr) if n < 2: return {"mean": None, "std": None, "ci_lo": None, "ci_hi": None} mean = float(np.mean(arr)) std = float(np.std(arr, ddof=1)) z = 1.96 if level >= 0.95 else 1.645 return { "mean": mean, "std": std, "ci_lo": float(mean - z * std / np.sqrt(n)), "ci_hi": float(mean + z * std / np.sqrt(n)), "level": level, } def monte_carlo(gen_fn, repeats=200, seed=0, tau_true=None, tol=0.05): """蒙特卡洛重复:不同种子运行 repeats 次,统计 τ̂ 分布。 gen_fn 返回 None 表示本次拟合失败(欠采样/不收敛),计入 n_failed 跳过。 """ tau_hats = [] n_failed = 0 for i in range(int(repeats)): v = gen_fn(seed + i) if v is None: n_failed += 1 else: tau_hats.append(float(v)) n_ok = len(tau_hats) result = { "n": int(repeats), "n_ok": n_ok, "n_failed": n_failed, "failure_rate_fit": n_failed / int(repeats) if repeats else 0.0, "tau_hats": tau_hats, "tau_true": tau_true, } if n_ok >= 2: ci = confidence_interval(tau_hats) result.update({ "mean": ci["mean"], "std": ci["std"], "rel_std": (ci["std"] / ci["mean"]) if ci["mean"] else None, "ci_lo": ci["ci_lo"], "ci_hi": ci["ci_hi"], }) if tau_true is not None: result["bias"] = (result["mean"] - tau_true) / tau_true result["failure_rate"] = failure_rate(tau_hats, tau_true, tol) return result def sweep(gen_fn, param_name, values, repeats=20, seed=0, tau_true=None, tol=0.05): """参数扫描:对每个参数值做蒙特卡洛(小样本),输出趋势表。 返回 [{param, mean, std, rel_std, bias, failure_rate}, ...]。 """ rows = [] for i, v in enumerate(values): st = monte_carlo(gen_fn, repeats=repeats, seed=seed + i * 1000, tau_true=tau_true, tol=tol) row = {param: float(v)} for key in ("mean", "std", "rel_std", "bias", "failure_rate", "tau_true"): row[key] = st.get(key) rows.append(row) return {"param": param, "values": [float(v) for v in values], "rows": rows}