mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-11-29 06:30:22 +08:00
308 lines
11 KiB
Python
308 lines
11 KiB
Python
#!/usr/bin/env python3
|
||
"""simulate — run real simulations and stamp their output with provenance.
|
||
|
||
This is the data half of the pipeline. Without it a manuscript's citations
|
||
could be verified while its numbers were not, because nothing forced the
|
||
numbers to come from an actual run.
|
||
|
||
python simulate.py list
|
||
python simulate.py check --model rotor_mre_dva
|
||
python simulate.py run --model rotor_mre_dva --study speed_sweep \
|
||
--out data/speed_sweep.csv
|
||
python simulate.py provenance --data data/
|
||
|
||
Every file written by `run` gets a sidecar `<file>.prov.json` recording the
|
||
model, its version, the exact parameter set, the random seed, the SHA-256 of
|
||
the model source at run time, and the verification report that was valid then.
|
||
`provenance` re-checks all of that, so data that was hand-edited, generated by
|
||
a superseded model, or never verified is caught rather than trusted.
|
||
|
||
Standard library plus numpy.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import hashlib
|
||
import io
|
||
import json
|
||
import os
|
||
import platform
|
||
import sys
|
||
import time
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
MODELS_DIR = os.path.join(os.path.dirname(HERE), "models")
|
||
sys.path.insert(0, MODELS_DIR)
|
||
|
||
try:
|
||
import numpy as np # noqa: F401
|
||
except ImportError: # pragma: no cover
|
||
print("simulate needs numpy: pip install numpy", file=sys.stderr)
|
||
raise SystemExit(1)
|
||
|
||
|
||
def _utf8() -> None:
|
||
for s in (sys.stdout, sys.stderr):
|
||
try:
|
||
s.reconfigure(encoding="utf-8") # type: ignore[attr-defined]
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _sha256(path: str) -> str:
|
||
h = hashlib.sha256()
|
||
with open(path, "rb") as fh:
|
||
for chunk in iter(lambda: fh.read(1 << 16), b""):
|
||
h.update(chunk)
|
||
return h.hexdigest()
|
||
|
||
|
||
def available_models() -> dict[str, str]:
|
||
if not os.path.isdir(MODELS_DIR):
|
||
return {}
|
||
out = {}
|
||
for f in sorted(os.listdir(MODELS_DIR)):
|
||
if f.endswith(".py") and not f.startswith("_"):
|
||
out[f[:-3]] = os.path.join(MODELS_DIR, f)
|
||
return out
|
||
|
||
|
||
def load_model(name: str):
|
||
models = available_models()
|
||
if name not in models:
|
||
raise SystemExit(f"[fail] 没有模型 {name!r};可用:{list(models)}")
|
||
sys.path.insert(0, MODELS_DIR)
|
||
mod = __import__(name)
|
||
for attr in ("NAME", "VERSION", "PARAMS", "STUDIES"):
|
||
if not hasattr(mod, attr):
|
||
raise SystemExit(
|
||
f"[fail] 模型 {name} 缺少必需属性 {attr},"
|
||
"写法见 models/README.md")
|
||
return mod, models[name]
|
||
|
||
|
||
# ----------------------------------------------------------------- commands
|
||
def cmd_list(a) -> int:
|
||
models = available_models()
|
||
if not models:
|
||
print(f"[fail] {MODELS_DIR} 下没有模型", file=sys.stderr)
|
||
return 1
|
||
print(f"可用模型({MODELS_DIR})\n")
|
||
for name, path in models.items():
|
||
try:
|
||
mod, _ = load_model(name)
|
||
print(f" {mod.NAME:18s} v{mod.VERSION:8s} {name}.py")
|
||
print(f" {getattr(mod, 'DESCRIPTION', '')}")
|
||
print(f" 研究:{', '.join(mod.STUDIES)}")
|
||
except SystemExit:
|
||
print(f" {name:18s} (加载失败)")
|
||
print()
|
||
return 0
|
||
|
||
|
||
def cmd_check(a) -> int:
|
||
mod, path = load_model(a.model)
|
||
print(f"模型:{mod.NAME} v{mod.VERSION}")
|
||
print(f"源码:{path}")
|
||
print(f"SHA-256:{_sha256(path)[:16]}…\n")
|
||
r = mod.verify(verbose=True)
|
||
if a.out:
|
||
os.makedirs(os.path.dirname(a.out) or ".", exist_ok=True)
|
||
payload = dict(r)
|
||
payload["source_path"] = path
|
||
payload["source_sha256"] = _sha256(path)
|
||
payload["checked_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||
with io.open(a.out, "w", encoding="utf-8") as fh:
|
||
json.dump(payload, fh, ensure_ascii=False, indent=1)
|
||
print(f"\n[ok] 自检报告:{a.out}")
|
||
if not r["passed"]:
|
||
print("\n[阻止] 模型自检未通过 —— 用它产生的数据不能写进论文。",
|
||
file=sys.stderr)
|
||
return 1
|
||
return 0
|
||
|
||
|
||
def cmd_run(a) -> int:
|
||
mod, path = load_model(a.model)
|
||
if a.study not in mod.STUDIES:
|
||
raise SystemExit(f"[fail] 模型没有研究 {a.study!r};"
|
||
f"可用:{list(mod.STUDIES)}")
|
||
|
||
# Refuse to produce data from a model that does not pass its own checks.
|
||
if not a.skip_verify:
|
||
r = mod.verify(verbose=False)
|
||
if not r["passed"]:
|
||
bad = [c["check"] for c in r["checks"] if not c["pass"]]
|
||
print("[阻止] 模型自检未通过,拒绝产生数据:", file=sys.stderr)
|
||
for b in bad:
|
||
print(f" - {b}", file=sys.stderr)
|
||
print("先修模型,或确认是有意为之再加 --skip-verify。",
|
||
file=sys.stderr)
|
||
return 1
|
||
verify_info = {"passed": True, "n_checks": r["n_checks"],
|
||
"n_passed": r["n_passed"]}
|
||
print(f"[ok] 模型自检 {r['n_passed']}/{r['n_checks']} 通过")
|
||
else:
|
||
verify_info = {"passed": None, "note": "自检被 --skip-verify 跳过"}
|
||
print("[warn] 跳过了模型自检 —— 这份数据不能直接进论文")
|
||
|
||
ctx = dict(mod.PARAMS)
|
||
ctx["params"] = dict(mod.PARAMS)
|
||
for kv in (a.set or []):
|
||
if "=" not in kv:
|
||
raise SystemExit(f"[fail] --set 需要 key=value,收到 {kv!r}")
|
||
k, v = kv.split("=", 1)
|
||
try:
|
||
ctx["params"][k] = float(v) if "." in v or "e" in v.lower() else int(v)
|
||
except ValueError:
|
||
ctx["params"][k] = v
|
||
if a.seed is not None:
|
||
ctx["seed"] = a.seed
|
||
if a.n is not None:
|
||
ctx["n"] = a.n
|
||
if a.current is not None:
|
||
ctx["I_A"] = a.current
|
||
|
||
t0 = time.time()
|
||
print(f"[run] {mod.NAME}.{a.study} …")
|
||
out = mod.STUDIES[a.study](ctx)
|
||
dt = time.time() - t0
|
||
rows, cols = out["rows"], out["columns"]
|
||
print(f"[ok] {len(rows)} 行,用时 {dt:.1f}s")
|
||
|
||
dest = a.out
|
||
os.makedirs(os.path.dirname(dest) or ".", exist_ok=True)
|
||
with io.open(dest, "w", encoding="utf-8", newline="") as fh:
|
||
w = csv.DictWriter(fh, fieldnames=cols, extrasaction="ignore")
|
||
w.writeheader()
|
||
for r in rows:
|
||
w.writerow(r)
|
||
print(f"[ok] {dest}")
|
||
|
||
prov = {
|
||
"schema": "paper-pipeline/provenance/1.0",
|
||
"file": os.path.basename(dest),
|
||
"file_sha256": _sha256(dest),
|
||
"model": mod.NAME,
|
||
"model_version": mod.VERSION,
|
||
"model_source": os.path.relpath(path, os.path.dirname(HERE)),
|
||
"model_sha256": _sha256(path),
|
||
"study": a.study,
|
||
"parameters": ctx["params"],
|
||
"seed": ctx.get("seed"),
|
||
"rows": len(rows),
|
||
"columns": cols,
|
||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||
"runtime_s": round(dt, 3),
|
||
"verification": verify_info,
|
||
"environment": {"python": sys.version.split()[0],
|
||
"platform": platform.platform(),
|
||
"numpy": __import__("numpy").__version__},
|
||
}
|
||
pp = dest + ".prov.json"
|
||
with io.open(pp, "w", encoding="utf-8") as fh:
|
||
json.dump(prov, fh, ensure_ascii=False, indent=1)
|
||
print(f"[ok] {pp}")
|
||
print(f" 文件指纹 {prov['file_sha256'][:16]}… "
|
||
f"模型指纹 {prov['model_sha256'][:16]}…")
|
||
return 0
|
||
|
||
|
||
def cmd_provenance(a) -> int:
|
||
roots = a.data if isinstance(a.data, list) else [a.data]
|
||
files = []
|
||
for r in roots:
|
||
if os.path.isdir(r):
|
||
for dp, _dn, fn in os.walk(r):
|
||
for f in fn:
|
||
if f.endswith((".csv", ".json")) and not f.endswith(".prov.json"):
|
||
files.append(os.path.join(dp, f))
|
||
elif os.path.isfile(r):
|
||
files.append(r)
|
||
print(f"检查 {len(files)} 个数据文件\n")
|
||
ok = warn = bad = 0
|
||
for f in sorted(files):
|
||
pp = f + ".prov.json"
|
||
if not os.path.isfile(pp):
|
||
print(f" [缺溯源] {os.path.relpath(f)} —— 没有 .prov.json,"
|
||
"无法证明这份数据是真跑出来的")
|
||
bad += 1
|
||
continue
|
||
try:
|
||
with io.open(pp, encoding="utf-8") as fh:
|
||
p = json.load(fh)
|
||
except ValueError:
|
||
print(f" [坏溯源] {os.path.relpath(f)} —— .prov.json 不是合法 JSON")
|
||
bad += 1
|
||
continue
|
||
problems = []
|
||
if p.get("file_sha256") and _sha256(f) != p["file_sha256"]:
|
||
problems.append("数据文件在生成之后被改动过(指纹不符)")
|
||
src = p.get("model_source")
|
||
if src:
|
||
# stored relative to the skill root (the parent of scripts/)
|
||
sp = os.path.join(os.path.dirname(HERE), src)
|
||
if os.path.isfile(sp):
|
||
if _sha256(sp) != p.get("model_sha256"):
|
||
problems.append("模型源码已改动,这份数据是用旧版本跑的,需要重跑")
|
||
else:
|
||
problems.append(f"找不到模型源码 {src}")
|
||
v = p.get("verification") or {}
|
||
if v.get("passed") is False:
|
||
problems.append("生成时模型自检未通过")
|
||
elif v.get("passed") is None:
|
||
problems.append("生成时跳过了模型自检")
|
||
if problems:
|
||
for x in problems:
|
||
print(f" [有问题] {os.path.relpath(f)} —— {x}")
|
||
bad += 1
|
||
else:
|
||
print(f" [ok ] {os.path.relpath(f)} "
|
||
f"({p.get('model')}.{p.get('study')}, {p.get('rows')} 行, "
|
||
f"{p.get('generated_at')})")
|
||
ok += 1
|
||
print(f"\n可溯源 {ok} · 有问题 {bad} · 警告 {warn}")
|
||
if bad:
|
||
print("**有数据无法证明是真跑出来的 —— 不能用来写论文。**")
|
||
return 1
|
||
return 0
|
||
|
||
|
||
def main() -> int:
|
||
_utf8()
|
||
ap = argparse.ArgumentParser(prog="simulate",
|
||
description="真实仿真与数据溯源")
|
||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||
|
||
sub.add_parser("list", help="列出可用模型").set_defaults(func=cmd_list)
|
||
|
||
c = sub.add_parser("check", help="跑模型自检(解析解对照 + 收敛性)")
|
||
c.add_argument("--model", required=True)
|
||
c.add_argument("--out", default="")
|
||
c.set_defaults(func=cmd_check)
|
||
|
||
r = sub.add_parser("run", help="跑一个研究并写带溯源的数据文件")
|
||
r.add_argument("--model", required=True)
|
||
r.add_argument("--study", required=True)
|
||
r.add_argument("--out", required=True)
|
||
r.add_argument("--set", action="append", default=[],
|
||
help="覆盖参数,可重复:--set m2_kg=0.5")
|
||
r.add_argument("--seed", type=int, default=None)
|
||
r.add_argument("--n", type=int, default=None)
|
||
r.add_argument("--current", type=float, default=None)
|
||
r.add_argument("--skip-verify", action="store_true",
|
||
help="跳过模型自检(产生警告,数据不可直接进论文)")
|
||
r.set_defaults(func=cmd_run)
|
||
|
||
p = sub.add_parser("provenance", help="核查数据文件的溯源信息")
|
||
p.add_argument("--data", nargs="+", required=True)
|
||
p.set_defaults(func=cmd_provenance)
|
||
|
||
a = ap.parse_args()
|
||
return a.func(a)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|