chore: 初始化 MCM/ICM Toolkit 仓库骨架

审查并精简 ChatGPT 的建库建议后落地的第一版骨架,只定接口不写实现。

- 建议审查:14 个包 → 7 个;约 250 个函数 → 约 40 个;5 个 Result 类 → 1 个
  (docs/01-suggestion-review.md)
- docs/:架构、路线图(含永久不做清单)、环境、Git 工作流、函数卡片模板
- src/mcm_toolkit/:core / data / stats / models / solve / decision / viz
  共 23 个模块,均为签名 + docstring + NotImplementedError
- tests/:9 个文件,其中 test_api_surface.py 已通过(20 passed)
- examples/ problems/ notebooks/ figures/ tables/ 骨架
- pyproject.toml(核心依赖 4 个 + 6 组 extras)、environment.yml
- scripts/:setup-venv.ps1(ASCII + LF)、setup-conda.ps1、doctor.ps1
- 环境:.venv(system-site-packages)与 conda 环境 mcm-toolkit 均已建好,
  数值栈版本与 base 完全对齐(numpy 2.4.6 / scipy 1.18.1 / pandas 3.0.6,MKL 后端)
This commit is contained in:
guzhujushi committed 2026-10-01 17:43:48 +08:00
commit 5319589dfd
76 files changed
+6812

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
"""端到端最小流程:读数据 → 清洗 → 描述 → bootstrap → 出图。
体量刻意压到最小,只用来确认"环境 + 包 + 出图"这条链路是通的。
"""
from __future__ import annotations
import numpy as np
import mcm_toolkit as mcm
def main() -> None:
mcm.set_seed(20260101)
# 1) 造一份带缺失和离群点的数据(真实赛题里这步是 load_table)
rng = np.random.default_rng(20260101)
heights = rng.normal(170, 8, size=300)
heights[[3, 77]] = [260.0, -10.0] # 两个录入错误
# 2) 找出离群点(约定:只标不删,删不删是人来决定)
mask = np.asarray(mcm.data.detect_outliers(heights, method="iqr"))
print(f"检出离群点 {mask.sum()} 个")
clean = heights[~mask]
# 3) 描述统计
print(mcm.stats.describe(clean))
# 4) 中位数的 bootstrap 置信区间(统计量没有解析分布时的通用答案)
ci = mcm.bootstrap_ci(clean, statistic=np.median, n_resamples=10000, random_state=20260101)
print(f"中位数 = {np.median(clean):.2f}, 95% CI = [{ci.params['low']:.2f}, {ci.params['high']:.2f}]")
# 5) 出图(默认同时写 png + pdf,300 dpi)
mcm.viz.mcm_style()
fig, ax = mcm.viz.plot(clean, kind="hist", title="身高分布", xlabel="cm")
paths = mcm.viz.save_figure(fig, "figures/quickstart_hist")
print("已写出:", [str(p) for p in paths])
if __name__ == "__main__":
main()
+48
View File
@@ -0,0 +1,48 @@
"""蒙特卡洛:估计 π、积 x²、算概率,并画收敛曲线。
三个例子覆盖 MC 的三种典型用法:
积分(几何量)、概率估计、以及"n 要取多大才够"的收敛性验证。
"""
from __future__ import annotations
import numpy as np
from mcm_toolkit.solve import monte_carlo_integral, monte_carlo_probability
from mcm_toolkit.viz import mcm_style, plot_convergence, save_figure
def main() -> None:
mcm_style()
# --- 1) 估 π:单位正方形内落入四分之一圆的比例 × 4 ---
def in_circle(X: np.ndarray) -> np.ndarray:
return (X**2).sum(axis=1) <= 1.0
r = monte_carlo_probability(in_circle, lambda rng, **k: rng.uniform(-1, 1, size=(1, 2)), n=200_000, random_state=1)
print(f"π ≈ {4 * r.metrics['probability']:.5f} (真值 3.14159)")
# --- 2) 积分 ∫₀¹ x² dx = 1/3 ---
r2 = monte_carlo_integral(lambda X: X[:, 0] ** 2, bounds=[(0, 1)], n=200_000, random_state=2)
print(f"∫₀¹x²dx ≈ {r2.data:.5f} (真值 0.33333)")
# --- 3) 收敛性:MC 误差是 O(1/√n),论文里要给这张图证明 n 选得够 ---
ns = np.unique(np.round(np.logspace(2, 6, 40)).astype(int))
errors = []
for n in ns:
est = monte_carlo_integral(lambda X: X[:, 0] ** 2, bounds=[(0, 1)], n=int(n), random_state=7)
errors.append(abs(est.data - 1 / 3))
fig, _ = plot_convergence(
np.column_stack([ns, errors]),
log=True,
reference=None,
title="Monte Carlo 误差随样本量收敛",
xlabel="样本量 n",
ylabel="绝对误差",
)
save_figure(fig, "figures/mc_convergence")
if __name__ == "__main__":
main()
+45
View File
@@ -0,0 +1,45 @@
"""评价类题目的标准流程:无量纲化 → 赋权 → TOPSIS 排序 → 敏感性。
这是中文建模赛出现频率最高的题型之一。
关键点(也是最容易翻车的地方):**指标方向必须显式声明**。
"""
from __future__ import annotations
import numpy as np
from mcm_toolkit.decision import entropy_weights, topsis
from mcm_toolkit.solve import robustness_test
def main() -> None:
# 3 个城市 × 4 个指标
# 人均GDP(效益) 空气PM2.5(成本) 绿化率(效益) 通勤时间(成本)
X = np.array(
[
[120.0, 35.0, 42.0, 38.0],
[95.0, 55.0, 36.0, 29.0],
[140.0, 28.0, 45.0, 47.0],
]
)
labels = ["城市A", "城市B", "城市C"]
benefit = [0, 2] # 只有第 0、2 列是"越大越好"
# 1) 客观赋权
w = entropy_weights(X, benefit_columns=benefit)
print("熵权:", np.round(w.params["weights"], 4))
# 2) TOPSIS 排序
result = topsis(X, weights=w.params["weights"], benefit_columns=benefit, labels=labels)
print(result.data)
# 3) 鲁棒性:权重扰动 ±10% 后排名还稳不稳?(论文里必须回答这个问题)
def model(**kw):
return topsis(X, weights=kw["weights"], benefit_columns=benefit).data["rank"].tolist()
rob = robustness_test(model, params={"weights": w.params["weights"]}, perturbation=0.1, n_samples=500, random_state=0)
print("排名稳定性:", rob.metrics)
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
# 例子
每个模块一个能直接跑的最小例子。
> **当前状态**:这些脚本是**用法规格**,函数实现填好之前跑不通
> (会抛 `NotImplementedError`)。实现顺序见 `docs/03-roadmap.md`。
| 文件 | 对应模块 | 覆盖的 L 档 |
|---|---|---|
| `00_quickstart.py` | 全流程 | L0 |
| `01_clean_and_describe.py` | `data` + `stats` | L0 |
| `02_regression_compare.py` | `models` | L1 |
| `03_monte_carlo.py` | `solve/simulate` | L0 |
| `04_decision_topsis.py` | `decision` | L1 |
| `05_sensitivity.py` | `solve/sensitivity` | L1 |
跑法:
```powershell
.\.venv\Scripts\python.exe examples\03_monte_carlo.py
```