eduzrh commited on
Commit
ec1317f
·
verified ·
1 Parent(s): 63ccb7e

sync scripts

Browse files
Files changed (2) hide show
  1. scripts/best_tables.py +110 -0
  2. scripts/build_report.py +165 -0
scripts/best_tables.py ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Summarise the performance-first (``best_*``) runs.
2
+
3
+ Produces ``results/tables/tab_best.csv`` with, per architecture:
4
+
5
+ * per-fold stress R2 averaged over seeds (mean +- sd over folds/seeds)
6
+ * pooled out-of-fold stress / shape / primary R2 for seed 0 and for the
7
+ seed-averaged predictions (all seeds share one fold split by construction)
8
+
9
+ and prints the markdown table used in the report.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ sys.path.insert(0, str(ROOT / "code"))
22
+
23
+ from pimamba.data import TARGETS, TARGET_KEYS # noqa: E402
24
+ from pimamba.metrics import PRIMARY, _r2, regression_metrics # noqa: E402
25
+
26
+ RUNS = ROOT / "results" / "runs"
27
+ TABLES = ROOT / "results" / "tables"
28
+
29
+
30
+ def runs_of(prefix: str):
31
+ out = {}
32
+ for d in RUNS.glob(f"{prefix}_*_f*_s*"):
33
+ try:
34
+ m, f, s = d.name[len(prefix) + 1:].rsplit("_", 2)
35
+ f = int(f[1:]); s = int(s[1:])
36
+ except ValueError:
37
+ continue
38
+ if (d / "metrics.json").exists():
39
+ out.setdefault(m, {}).setdefault(s, {})[f] = d
40
+ return out
41
+
42
+
43
+ def pooled(tags: dict, seeds: list[int]):
44
+ """Pool the predictions of one model over the given seeds."""
45
+ P, Y, M = [], [], []
46
+ for f in sorted(tags[seeds[0]]):
47
+ arrs = [np.load(tags[s][f] / "predictions.npz", allow_pickle=True)
48
+ for s in seeds if f in tags.get(s, {})]
49
+ if not arrs:
50
+ continue
51
+ P.append(np.mean([a["pred"] for a in arrs], 0))
52
+ Y.append(arrs[0]["true"]); M.append(arrs[0]["mask"])
53
+ if not P:
54
+ return None
55
+ return (np.concatenate(P), np.concatenate(Y), np.concatenate(M))
56
+
57
+
58
+ def score(P, Y, M):
59
+ pt = regression_metrics(Y.reshape(-1, len(TARGETS)), P.reshape(-1, len(TARGETS)),
60
+ M.reshape(-1, len(TARGETS)))
61
+ j = TARGET_KEYS.index("sigma")
62
+ mm = M[:, :, j] > 0
63
+ sig = _r2(Y[:, :, j][mm], P[:, :, j][mm])
64
+ ys, ps = [], []
65
+ for i in range(P.shape[0]):
66
+ k = M[i, :, j] > 0
67
+ if k.sum() < 4:
68
+ continue
69
+ ys.append(Y[i, k, j] - Y[i, k, j].mean())
70
+ ps.append(P[i, k, j] - P[i, k, j].mean())
71
+ shape = _r2(np.concatenate(ys), np.concatenate(ps))
72
+ prim = [pt[k]["r2"] for k in PRIMARY if np.isfinite(pt[k]["r2"])]
73
+ return dict(sigma=sig, shape=shape, primary=float(np.mean(prim)))
74
+
75
+
76
+ def main(prefix="best"):
77
+ found = runs_of(prefix)
78
+ rows = []
79
+ for m, per_seed in sorted(found.items()):
80
+ seeds = sorted(per_seed)
81
+ folds = sorted(per_seed[seeds[0]])
82
+ nparams = json.loads((per_seed[seeds[0]][folds[0]] / "metrics.json").read_text())["n_params"]
83
+ fold_r2 = []
84
+ for s in seeds:
85
+ for f, d in per_seed[s].items():
86
+ r = json.loads((d / "metrics.json").read_text())
87
+ fold_r2.append(r["per_target"]["sigma"]["r2"])
88
+ row = {"model": m, "seeds": len(seeds), "folds": len(folds),
89
+ "params": nparams,
90
+ "fold_r2_mean": float(np.mean(fold_r2)),
91
+ "fold_r2_sd": float(np.std(fold_r2)),
92
+ "n_runs": sum(len(v) for v in per_seed.values())}
93
+ full = all(len(per_seed[s]) == 5 for s in seeds)
94
+ if full:
95
+ for tag, ss in (("seed0", [seeds[0]]), ("seedavg", seeds)):
96
+ g = pooled(per_seed, ss)
97
+ sc = score(*g)
98
+ row[f"{tag}_sigma"] = round(sc["sigma"], 3)
99
+ row[f"{tag}_shape"] = round(sc["shape"], 3)
100
+ row[f"{tag}_primary"] = round(sc["primary"], 3)
101
+ rows.append(row)
102
+ df = pd.DataFrame(rows)
103
+ TABLES.mkdir(parents=True, exist_ok=True)
104
+ df.to_csv(TABLES / f"tab_{prefix}.csv", index=False)
105
+ print(df.to_string(index=False))
106
+ return df
107
+
108
+
109
+ if __name__ == "__main__":
110
+ main(sys.argv[1] if len(sys.argv) > 1 else "best")
scripts/build_report.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Build the HTML and PDF versions of the report from ``report/paper.md``.
2
+
3
+ Run on a machine that has WeasyPrint and a CJK font installed::
4
+
5
+ python scripts/build_report.py
6
+
7
+ The HTML is self-contained apart from the figure files (``report/figures/``),
8
+ so it can be opened directly in a browser or printed to PDF by hand.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import shutil
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import markdown
17
+ from weasyprint import CSS, HTML
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+ REPORT = ROOT / "report"
21
+ SRC = REPORT / "paper.md"
22
+ OUT_HTML = REPORT / "paper.html"
23
+ OUT_PDF = REPORT / "paper.pdf"
24
+ FIG_SRC = ROOT / "results" / "figures"
25
+ FIG_DST = REPORT / "figures"
26
+
27
+ # The text uses LaTeX only inside the first sections; converting those few
28
+ # expressions to Unicode keeps the PDF readable without a JS math renderer.
29
+ MATH = {
30
+ r"$\mathrm{m^{-2}}$": "m⁻²",
31
+ r"$10^{16}\,\mathrm{m^{-2}}$": "10¹⁶ m⁻²",
32
+ r"$5\times10^{-4}$": "5×10⁻⁴",
33
+ r"$33\times401=13233$": "33 × 401 = 13233",
34
+ r"$T=401$": "T = 401",
35
+ r"$R^2=1$": "R² = 1",
36
+ r"$R^2=0$": "R² = 0",
37
+ r"$R^2<0$": "R² < 0",
38
+ r"$\sigma$": "σ",
39
+ r"$c$": "c",
40
+ r"$\delta$": "δ",
41
+ r"$\chi$": "χ",
42
+ r"$\Delta H_{\mathrm{mix}}$": "ΔH_mix",
43
+ r"$\Delta S_{\mathrm{mix}}$": "ΔS_mix",
44
+ r"$\rho_{\mathrm{total}}$": "ρ_total",
45
+ r"$\rho_{\mathrm{twin}}$": "ρ_twin",
46
+ r"$\varepsilon_{1:T}$": "ε(1..T)",
47
+ r"$\xi_{\mathrm{BCC}}, \xi_{\mathrm{FCC}}, \xi_{\mathrm{HCP}}, \xi_{\mathrm{other}}$":
48
+ "ξ_BCC, ξ_FCC, ξ_HCP, ξ_other",
49
+ r"$\rho_{1/2},\rho_{a/2},\rho_{a/3},\rho_{\mathrm{edge}},\rho_{\mathrm{screw}},\rho_{\mathrm{perfect}},\rho_{\mathrm{other}}$":
50
+ "ρ_1/2, ρ_a/2, ρ_a/3, ρ_edge, ρ_screw, ρ_perfect, ρ_other",
51
+ }
52
+
53
+ CSS_TEXT = r"""
54
+ @page {
55
+ size: A4;
56
+ margin: 20mm 18mm 18mm 18mm;
57
+ @bottom-center {
58
+ content: counter(page);
59
+ font-family: "Noto Serif CJK SC", serif;
60
+ font-size: 9pt;
61
+ color: #555;
62
+ }
63
+ @top-center {
64
+ content: string(doctitle);
65
+ font-family: "Noto Serif CJK SC", serif;
66
+ font-size: 8.5pt;
67
+ color: #777;
68
+ }
69
+ }
70
+ @page :first { @top-center { content: none; } }
71
+
72
+ html { font-size: 10.5pt; }
73
+ body {
74
+ font-family: "Noto Serif CJK SC", "Songti SC", serif;
75
+ line-height: 1.78;
76
+ color: #111;
77
+ text-align: left;
78
+ max-width: 820px;
79
+ margin: 0 auto;
80
+ padding: 0 8px;
81
+ }
82
+ h1 {
83
+ font-size: 19pt; line-height: 1.45; text-align: center;
84
+ margin: 0 0 6px 0; font-weight: 700; string-set: doctitle content();
85
+ }
86
+ h2 {
87
+ font-size: 13.5pt; margin: 22px 0 8px 0; font-weight: 700;
88
+ border-bottom: 1.2px solid #333; padding-bottom: 3px;
89
+ page-break-after: avoid;
90
+ }
91
+ h3 { font-size: 11.5pt; margin: 16px 0 6px 0; font-weight: 700; page-break-after: avoid; }
92
+ p { margin: 0 0 8px 0; text-indent: 2em; }
93
+ p.eq { text-align: center; text-indent: 0; margin: 9px 0 11px 0; }
94
+ p.eq sub, td sub { font-size: 68%; }
95
+ p:has(> img) { text-indent: 0; text-align: center; margin: 12px 0 4px 0; }
96
+ img { max-width: 96%; height: auto; }
97
+ table {
98
+ border-collapse: collapse; width: 100%; margin: 10px 0 6px 0;
99
+ font-size: 8.6pt; line-height: 1.45; page-break-inside: avoid;
100
+ break-before: avoid; /* keep the caption above the table on the same page */
101
+ }
102
+ th, td { border: 0.5pt solid #999; padding: 3px 5px; text-align: center; vertical-align: middle; }
103
+ th { background: #f0f0f0; font-weight: 700; }
104
+ td:first-child, th:first-child { text-align: left; }
105
+ tr:nth-child(even) td { background: #fafafa; }
106
+ code { font-family: "DejaVu Sans Mono", monospace; font-size: 8.6pt; background: #f4f4f4; padding: 0 2px; }
107
+ pre {
108
+ background: #f6f6f6; border: 0.5pt solid #ddd; padding: 6px 8px;
109
+ font-size: 8.2pt; line-height: 1.4; white-space: pre-wrap; page-break-inside: avoid;
110
+ }
111
+ pre code { background: none; }
112
+ blockquote { margin: 8px 0; padding-left: 10px; border-left: 3px solid #ccc; color: #444; }
113
+ hr { border: none; border-top: 0.6pt solid #ccc; margin: 16px 0; }
114
+ strong { font-weight: 700; }
115
+ #TOC { background: #f7f7f7; border: 0.5pt solid #ddd; padding: 8px 14px; margin: 14px 0 18px 0; }
116
+ #TOC ul { margin: 2px 0; padding-left: 18px; }
117
+ #TOC li { margin: 1px 0; font-size: 9.2pt; }
118
+ #TOC a { color: #111; text-decoration: none; }
119
+ a { color: #1a4f8b; text-decoration: none; }
120
+ """
121
+
122
+ TEMPLATE = """<!DOCTYPE html>
123
+ <html lang="zh-CN">
124
+ <head>
125
+ <meta charset="utf-8">
126
+ <title>{title}</title>
127
+ <style>{css}</style>
128
+ </head>
129
+ <body>
130
+ {body}
131
+ </body>
132
+ </html>
133
+ """
134
+
135
+
136
+ def main() -> int:
137
+ if not SRC.exists():
138
+ print(f"missing {SRC}")
139
+ return 1
140
+ text = SRC.read_text(encoding="utf-8")
141
+ for k, v in MATH.items():
142
+ text = text.replace(k, v)
143
+ left = text.count("$")
144
+ if left:
145
+ print(f"warning: {left} '$' characters remain (unconverted LaTeX?)")
146
+ body = markdown.markdown(
147
+ text, extensions=["tables", "fenced_code", "toc", "sane_lists"],
148
+ extension_configs={"toc": {"title": "目录", "toc_depth": "2-2"}})
149
+ doc = TEMPLATE.format(title="多���金 MD 轨迹的应力–应变预测", css=CSS_TEXT, body=body)
150
+ OUT_HTML.write_text(doc, encoding="utf-8")
151
+
152
+ if FIG_SRC.exists():
153
+ FIG_DST.mkdir(exist_ok=True)
154
+ for f in FIG_SRC.glob("*.png"):
155
+ shutil.copy2(f, FIG_DST / f.name)
156
+
157
+ HTML(string=doc, base_url=str(REPORT)).write_pdf(
158
+ str(OUT_PDF), stylesheets=[CSS(string=CSS_TEXT)])
159
+ print(f"html {OUT_HTML.stat().st_size/1024:.0f} KB, "
160
+ f"pdf {OUT_PDF.stat().st_size/1024:.0f} KB")
161
+ return 0
162
+
163
+
164
+ if __name__ == "__main__":
165
+ sys.exit(main())