mirror of
https://github.com/YuJunZhiXue/dsh-purge.git
synced 2026-12-06 17:40:22 +08:00
1.1.73: adapt DSH 0.2.1-rc.2, Apache-2.0, lab-only default-deny.
This commit is contained in:
1 parent
8df4406a7c
commit
1ea067189c
114 files changed
+21198
-5183
No files matched your search
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""为正文补充文献引用(一次性脚本)。
|
||||
|
||||
按"唯一匹配"原则替换:每个待插入位置的目标片段在文件中必须恰好出现一次,
|
||||
否则报错退出,避免误改。这样比逐条手工编辑更适合批量插入引用。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAN = ROOT / "manuscript"
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# (文件, 原文片段, 替换后片段)
|
||||
EDITS: list[tuple[str, str, str]] = [
|
||||
("part4_结果与分析.md",
|
||||
"这一形态与多孔材料压缩的经典响应一致,说明本文的三段式构造",
|
||||
"这一形态与多孔材料压缩的经典响应一致[31],也与其他增材制造点阵的压缩试验结果相符[16,38],说明本文的三段式构造"),
|
||||
("part4_结果与分析.md",
|
||||
"该判断将在 4.8 节通过不确定性分析进一步验证。",
|
||||
"这一排序与文献中关于点阵构型排序的一般性结论一致[32,34],其稳健性将在 4.8 节通过不确定性分析进一步检验。"),
|
||||
("part4_结果与分析.md",
|
||||
"但如 4.9 节所述,该对标只支持\"量级合理\",不支持\"数值准确\"。",
|
||||
"文献中同类 FDM PLA 点阵的实测比强度多集中在 5–15 kN·m/kg 区间[37,38,42],与本文输出范围吻合。但如 4.9 节所述,该对标只支持\"量级合理\",不支持\"数值准确\"。"),
|
||||
("part4_结果与分析.md",
|
||||
"工程含义是:打印角度在 0°–20° 范围内的波动对性能影响有限,但一旦超过 30°,性能损失迅速显现。这为工艺窗口的选择提供了定量依据。",
|
||||
"工程含义是:打印角度在 0°–20° 范围内的波动对性能影响有限,但一旦超过 30°,性能损失迅速显现。这与文献报道的打印角度—强度关系趋势一致[4,7,54]。这为工艺窗口的选择提供了定量依据。"),
|
||||
("part4_结果与分析.md",
|
||||
"这提示一个值得后续研究的方向:若能在保持 OCT 高平台应力的同时,通过梯度化设计延迟密实化,可望进一步提升吸能能力。",
|
||||
"这与文献报道的梯度化点阵能够同时改善刚度与吸能的结果方向一致[34,35]。这提示一个值得后续研究的方向:若能在保持 OCT 高平台应力的同时,通过梯度化设计延迟密实化,可望进一步提升吸能能力。"),
|
||||
("part4_结果与分析.md",
|
||||
"在全部交互项中,仅\"相对密度 × 打印角度\"显著(系数 −0.383,$p = 0.013$),符号为负,说明打印角度偏离 0° 造成的性能损失在高相对密度下更为严重。该结论提示结构设计与工艺参数不可独立优化,高相对密度点阵件对打印方向更为敏感。",
|
||||
"在全部交互项中,仅\"相对密度 × 打印角度\"显著(系数 −0.383,$p = 0.013$),符号为负,说明打印角度偏离 0° 造成的性能损失在高相对密度下更为严重。文献中关于填充率与打印角度存在交互作用的报道[7,54]与本文结果方向一致。该结论提示结构设计与工艺参数不可独立优化,高相对密度点阵件对打印方向更为敏感。"),
|
||||
("part4_结果与分析.md",
|
||||
"文献中关于梯度点阵能同时改善刚度与吸能的报道,其机理正在于此——通过拓扑的空间分布在不改变总相对密度的前提下重新分配承载路径。",
|
||||
"文献中关于梯度点阵能同时改善刚度与吸能的报道[34,35],其机理正在于此——通过拓扑的空间分布在不改变总相对密度的前提下重新分配承载路径。"),
|
||||
("part4_结果与分析.md",
|
||||
"文献中同类拓扑的模量前系数 $C_1$ 报道值通常在 ±20% 以内波动(主要差异来自节点质量集中程度与杆件截面形状的处理方式)。",
|
||||
"文献中同类拓扑的模量前系数 $C_1$ 报道值通常在 ±20% 以内波动(主要差异来自节点质量集中程度与杆件截面形状的处理方式)[31,32,39]。"),
|
||||
("part4_结果与分析.md",
|
||||
"**(3)几何模型为理想化模型,未计入 as-built 几何偏差。**",
|
||||
"**(3)几何模型为理想化模型,未计入 as-built 几何偏差。**"),
|
||||
("part4_结果与分析.md",
|
||||
"文献已指出这类偏差是仿真—实验系统性差异的主要来源。因此本文的偏差修正框架(式 2-4 至 2-6)只是对偏差效应的**宏观参数化**,不是对其几何成因的建模。",
|
||||
"文献已指出这类偏差是仿真—实验系统性差异的主要来源[21,33]。因此本文的偏差修正框架(式 2-4 至 2-6)只是对偏差效应的**宏观参数化**,不是对其几何成因的建模。"),
|
||||
("part4_结果与分析.md",
|
||||
"文献中同类 FDM PLA 点阵的实测比模量通常介于 100–350 kN·m/kg",
|
||||
"文献中同类 FDM PLA 点阵的实测比模量通常介于 100–350 kN·m/kg"),
|
||||
("part5_结论展望与附录.md",
|
||||
"论文的**相对结论**(如排序、因子贡献顺序、单调性)比绝对数值更可信",
|
||||
"论文的**相对结论**(如排序、因子贡献顺序、单调性)比绝对数值更可信"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
changed = 0
|
||||
for fname, old, new in EDITS:
|
||||
if old == new:
|
||||
continue
|
||||
p = MAN / fname
|
||||
t = p.read_text(encoding="utf-8")
|
||||
n = t.count(old)
|
||||
if n == 0:
|
||||
print(f"!! 未找到(跳过): {fname} :: {old[:44]}...")
|
||||
continue
|
||||
if n > 1:
|
||||
print(f"!! 匹配 {n} 处,拒绝替换: {fname} :: {old[:44]}...")
|
||||
continue
|
||||
p.write_text(t.replace(old, new), encoding="utf-8", newline="\n")
|
||||
changed += 1
|
||||
print(f"ok {fname} :: {old[:40]}...")
|
||||
print(f"\n共完成 {changed} 处替换")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,485 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把 manuscript/ 下的分章 md 编译为学位论文格式的 Word 文档(第 20 步交付构建)。
|
||||
|
||||
排版口径(按中文学位论文惯例):
|
||||
- A4 纸,上下 2.54 cm / 左右 2.8 cm 页边距
|
||||
- 一级标题(章):黑体 三号 居中,段前段后 12 pt
|
||||
- 二级标题(节):黑体 四号 左对齐
|
||||
- 三级标题:黑体 小四 左对齐
|
||||
- 正文:宋体/仿宋 小四,行距 22 pt,首行缩进 2 字符
|
||||
- 图表题注:宋体 五号 居中
|
||||
- 参考文献:宋体 五号,悬挂缩进
|
||||
|
||||
md 语法支持:# 标题、正文、- 列表、1. 有序列表、| 表格 |、```代码```、
|
||||
 图片、$公式$(原样保留为文本)、**粗体**。
|
||||
|
||||
用法:
|
||||
python code/build_docx.py
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from docx import Document
|
||||
from docx.enum.section import WD_SECTION
|
||||
from docx.enum.table import WD_TABLE_ALIGNMENT
|
||||
from docx.enum.text import WD_ALIGN_PARAGRAPH, WD_LINE_SPACING
|
||||
from docx.oxml import OxmlElement
|
||||
from docx.oxml.ns import qn
|
||||
from docx.shared import Cm, Pt, RGBColor
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAN = ROOT / "manuscript"
|
||||
FIG = ROOT / "figures"
|
||||
OUTDIR = ROOT / "deliverables"
|
||||
OUTDIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
from math2unicode import convert_text # noqa: E402 LaTeX -> Unicode 公式转换
|
||||
|
||||
ORDER = ["part0_摘要与目录.md",
|
||||
"part1_摘要与绪论.md", "part2_理论基础与模型.md",
|
||||
"part3_数值试验设计.md", "part4_结果与分析.md",
|
||||
"part5_结论展望与附录.md"]
|
||||
|
||||
# 字体(中文字体名 + 西文字体名)
|
||||
F_HEI = "黑体"
|
||||
F_SONG = "宋体"
|
||||
F_LATIN = "Times New Roman"
|
||||
|
||||
BLACK = RGBColor(0, 0, 0)
|
||||
GREY = RGBColor(0x59, 0x59, 0x59)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 底层工具
|
||||
# ---------------------------------------------------------------------------
|
||||
def set_font(run, cn=F_SONG, latin=F_LATIN, size=12, bold=False, color=BLACK):
|
||||
run.font.name = latin
|
||||
run.font.size = Pt(size)
|
||||
run.font.bold = bold
|
||||
run.font.color.rgb = color
|
||||
rPr = run._element.get_or_add_rPr()
|
||||
rFonts = rPr.find(qn("w:rFonts"))
|
||||
if rFonts is None:
|
||||
rFonts = OxmlElement("w:rFonts")
|
||||
rPr.append(rFonts)
|
||||
rFonts.set(qn("w:ascii"), latin)
|
||||
rFonts.set(qn("w:hAnsi"), latin)
|
||||
rFonts.set(qn("w:eastAsia"), cn)
|
||||
return run
|
||||
|
||||
|
||||
def para_fmt(p, first_indent_chars=0, line_pt=22, before=0, after=0,
|
||||
align=WD_ALIGN_PARAGRAPH.JUSTIFY, keep_next=False):
|
||||
pf = p.paragraph_format
|
||||
pf.line_spacing_rule = WD_LINE_SPACING.EXACTLY
|
||||
pf.line_spacing = Pt(line_pt)
|
||||
pf.space_before = Pt(before)
|
||||
pf.space_after = Pt(after)
|
||||
p.alignment = align
|
||||
if first_indent_chars:
|
||||
# 中文字符缩进必须用 w:firstLineChars(值为"百分之一字符")
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
ind = pPr.find(qn("w:ind"))
|
||||
if ind is None:
|
||||
ind = OxmlElement("w:ind")
|
||||
pPr.append(ind)
|
||||
ind.set(qn("w:firstLineChars"), str(int(first_indent_chars * 100)))
|
||||
ind.set(qn("w:firstLine"), str(int(first_indent_chars * 12 * 20)))
|
||||
if keep_next:
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
kn = OxmlElement("w:keepNext")
|
||||
pPr.append(kn)
|
||||
return p
|
||||
|
||||
|
||||
BOLD_RE = re.compile(r"\*\*(.+?)\*\*")
|
||||
|
||||
|
||||
def add_rich_text(p, text, cn=F_SONG, size=12, base_bold=False):
|
||||
"""处理 **粗体** 片段,其余按普通文本。"""
|
||||
pos = 0
|
||||
for m in BOLD_RE.finditer(text):
|
||||
if m.start() > pos:
|
||||
set_font(p.add_run(text[pos:m.start()]), cn=cn, size=size, bold=base_bold)
|
||||
set_font(p.add_run(m.group(1)), cn=cn, size=size, bold=True)
|
||||
pos = m.end()
|
||||
if pos < len(text):
|
||||
set_font(p.add_run(text[pos:]), cn=cn, size=size, bold=base_bold)
|
||||
if not text:
|
||||
set_font(p.add_run(""), cn=cn, size=size, bold=base_bold)
|
||||
return p
|
||||
|
||||
|
||||
TAG_RE = re.compile(r"^(.*?) ((\d+-\d+))$")
|
||||
|
||||
|
||||
def render_display_formula(doc, line: str):
|
||||
"""行间公式:公式居中,编号右对齐(用右对齐制表位,避免编号换行)。
|
||||
|
||||
版心宽度 = 21.0 - 2.8×2 = 15.4 cm;右制表位设在版心右边界,
|
||||
使编号紧贴右边距。
|
||||
"""
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=20, before=6, after=6, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
m = TAG_RE.match(line.strip())
|
||||
body = m.group(1).strip() if m else line.strip()
|
||||
tag = m.group(2) if m else ""
|
||||
|
||||
# 右对齐制表位。位置必须略小于版心宽度(15.4 cm)——恰好等于边界时
|
||||
# Word 会把制表符判为溢出而换行。实测 14.4 cm 可稳定同行。
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
tabs = OxmlElement("w:tabs")
|
||||
tab = OxmlElement("w:tab")
|
||||
tab.set(qn("w:val"), "right")
|
||||
tab.set(qn("w:pos"), str(int(14.4 * 567))) # 1 cm = 567 twips
|
||||
tabs.append(tab)
|
||||
pPr.append(tabs)
|
||||
|
||||
# 公式居中:左缩进取 1.2 cm,使公式视觉上接近居中
|
||||
p.paragraph_format.left_indent = Cm(2.4)
|
||||
set_font(p.add_run(body), cn=F_SONG, size=11.5)
|
||||
if tag:
|
||||
set_font(p.add_run("\t(" + tag + ")"), cn=F_SONG, size=11)
|
||||
return p
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 文档骨架
|
||||
# ---------------------------------------------------------------------------
|
||||
def new_doc() -> Document:
|
||||
doc = Document()
|
||||
st = doc.styles["Normal"]
|
||||
st.font.name = F_LATIN
|
||||
st.font.size = Pt(12)
|
||||
st.element.rPr.rFonts.set(qn("w:eastAsia"), F_SONG)
|
||||
|
||||
sec = doc.sections[0]
|
||||
sec.page_width, sec.page_height = Cm(21.0), Cm(29.7)
|
||||
sec.top_margin = sec.bottom_margin = Cm(2.54)
|
||||
sec.left_margin = sec.right_margin = Cm(2.8)
|
||||
return doc
|
||||
|
||||
|
||||
def add_page_number(doc):
|
||||
for sec in doc.sections:
|
||||
footer = sec.footer
|
||||
p = footer.paragraphs[0] if footer.paragraphs else footer.add_paragraph()
|
||||
p.alignment = WD_ALIGN_PARAGRAPH.CENTER
|
||||
run = p.add_run()
|
||||
set_font(run, cn=F_SONG, size=9, color=GREY)
|
||||
fld = OxmlElement("w:fldSimple")
|
||||
fld.set(qn("w:instr"), "PAGE")
|
||||
run._element.addnext(fld)
|
||||
|
||||
|
||||
def add_cover(doc):
|
||||
for _ in range(3):
|
||||
para_fmt(doc.add_paragraph(), line_pt=20)
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=40, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run("本科毕业论文"), cn=F_HEI, size=22, bold=True)
|
||||
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=40, before=24, after=6, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run("面向熔融沉积成形的点阵结构参数化建模"), cn=F_HEI, size=18, bold=True)
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=40, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run("与准静态压缩性能数值研究"), cn=F_HEI, size=18, bold=True)
|
||||
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=26, before=18, after=24, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run("Parametric Modeling and Numerical Study on the Quasi-Static\n"
|
||||
"Compressive Performance of Lattice Structures for\n"
|
||||
"Fused Deposition Modeling"),
|
||||
cn=F_SONG, size=11, color=GREY)
|
||||
|
||||
rows = [("作 者", "〔待填:姓名〕"), ("学 号", "〔待填:学号〕"),
|
||||
("专 业", "〔待填:专业〕"), ("指导教师", "〔待填:导师姓名 / 职称〕"),
|
||||
("学 院", "〔待填:学院名称〕"), ("完成日期", "〔待填:年 月 日〕")]
|
||||
tbl = doc.add_table(rows=len(rows), cols=2)
|
||||
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
for i, (k, v) in enumerate(rows):
|
||||
for j, txt in enumerate((k, v)):
|
||||
cell = tbl.cell(i, j)
|
||||
cell.text = ""
|
||||
p = cell.paragraphs[0]
|
||||
para_fmt(p, line_pt=26, align=WD_ALIGN_PARAGRAPH.LEFT if j else WD_ALIGN_PARAGRAPH.RIGHT)
|
||||
set_font(p.add_run(txt), cn=F_SONG, size=12)
|
||||
doc.add_page_break()
|
||||
|
||||
|
||||
def add_toc(doc, entries):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, before=6, after=14, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run("目 录"), cn=F_HEI, size=16, bold=True)
|
||||
for level, text in entries:
|
||||
p = doc.add_paragraph()
|
||||
indent = {1: 0, 2: 1.0, 3: 2.0}.get(level, 0)
|
||||
para_fmt(p, line_pt=22, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
if indent:
|
||||
p.paragraph_format.left_indent = Cm(indent)
|
||||
set_font(p.add_run(text), cn=F_HEI if level == 1 else F_SONG,
|
||||
size=12 if level == 1 else 11, bold=(level == 1))
|
||||
doc.add_page_break()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# markdown 渲染
|
||||
# ---------------------------------------------------------------------------
|
||||
def render_table(doc, rows: list[list[str]]):
|
||||
if not rows:
|
||||
return
|
||||
ncol = max(len(r) for r in rows)
|
||||
tbl = doc.add_table(rows=len(rows), cols=ncol)
|
||||
tbl.style = "Table Grid"
|
||||
tbl.alignment = WD_TABLE_ALIGNMENT.CENTER
|
||||
for i, row in enumerate(rows):
|
||||
for j in range(ncol):
|
||||
txt = row[j] if j < len(row) else ""
|
||||
txt = txt.replace("**", "").replace("$", "")
|
||||
cell = tbl.cell(i, j)
|
||||
cell.text = ""
|
||||
p = cell.paragraphs[0]
|
||||
para_fmt(p, line_pt=14,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER if i == 0 or j == 0 else WD_ALIGN_PARAGRAPH.LEFT)
|
||||
set_font(p.add_run(txt), cn=F_SONG, size=9, bold=(i == 0))
|
||||
# 表后空行
|
||||
para_fmt(doc.add_paragraph(), line_pt=6)
|
||||
|
||||
|
||||
def render_code(doc, lines: list[str]):
|
||||
for ln in lines:
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=12, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.6)
|
||||
set_font(p.add_run(ln if ln else " "), cn=F_SONG, latin="Consolas", size=9, color=RGBColor(0x1F, 0x3A, 0x5F))
|
||||
para_fmt(doc.add_paragraph(), line_pt=6)
|
||||
|
||||
|
||||
def render_image(doc, path: Path, caption: str):
|
||||
if not path.exists():
|
||||
print(f" !! 图片缺失,跳过:{path}")
|
||||
return
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=14, before=6, after=2, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
run = p.add_run()
|
||||
# 版心宽度约 15.4 cm,图宽限制在 14 cm
|
||||
run.add_picture(str(path), width=Cm(15.2))
|
||||
if caption:
|
||||
cp = doc.add_paragraph()
|
||||
para_fmt(cp, line_pt=16, after=10, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(cp.add_run(caption.replace("**", "")), cn=F_SONG, size=10.5)
|
||||
|
||||
|
||||
def render_markdown(doc, text: str, heading_offsets: dict[str, int]):
|
||||
lines = text.split("\n")
|
||||
i = 0
|
||||
while i < len(lines):
|
||||
ln = lines[i]
|
||||
s = ln.strip()
|
||||
|
||||
# 代码块
|
||||
if s.startswith("```"):
|
||||
i += 1
|
||||
buf = []
|
||||
while i < len(lines) and not lines[i].strip().startswith("```"):
|
||||
buf.append(lines[i])
|
||||
i += 1
|
||||
i += 1
|
||||
render_code(doc, buf)
|
||||
continue
|
||||
|
||||
# 表格
|
||||
if s.startswith("|") and i + 1 < len(lines) and re.match(r"^\|[\s:\-\|]+\|$", lines[i + 1].strip()):
|
||||
rows = []
|
||||
while i < len(lines) and lines[i].strip().startswith("|"):
|
||||
cells = [c.strip() for c in lines[i].strip().strip("|").split("|")]
|
||||
if not re.match(r"^[\s:\-]+$", "".join(cells)):
|
||||
rows.append(cells)
|
||||
i += 1
|
||||
render_table(doc, rows)
|
||||
continue
|
||||
|
||||
# 图片
|
||||
m = re.match(r"^!\[(.*?)\]\((.*?)\)$", s)
|
||||
if m:
|
||||
cap = m.group(1)
|
||||
render_image(doc, MAN.parent / m.group(2), cap)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 水平线
|
||||
if s in ("---", "***", "___"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=8, after=4)
|
||||
pPr = p._element.get_or_add_pPr()
|
||||
pbdr = OxmlElement("w:pBdr")
|
||||
bottom = OxmlElement("w:bottom")
|
||||
bottom.set(qn("w:val"), "single")
|
||||
bottom.set(qn("w:sz"), "6")
|
||||
bottom.set(qn("w:color"), "AAAAAA")
|
||||
pbdr.append(bottom)
|
||||
pPr.append(pbdr)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 标题
|
||||
m = re.match(r"^(#{2,4})\s+(.*)$", s)
|
||||
if m:
|
||||
level = len(m.group(1)) - 1 # ## -> 1
|
||||
txt = m.group(2).replace("**", "")
|
||||
p = doc.add_paragraph()
|
||||
if level == 1:
|
||||
para_fmt(p, line_pt=30, before=16, after=10,
|
||||
align=WD_ALIGN_PARAGRAPH.CENTER, keep_next=True)
|
||||
set_font(p.add_run(txt), cn=F_HEI, size=16, bold=True)
|
||||
elif level == 2:
|
||||
para_fmt(p, line_pt=26, before=12, after=6,
|
||||
align=WD_ALIGN_PARAGRAPH.LEFT, keep_next=True)
|
||||
set_font(p.add_run(txt), cn=F_HEI, size=14, bold=True)
|
||||
else:
|
||||
para_fmt(p, line_pt=24, before=8, after=4,
|
||||
align=WD_ALIGN_PARAGRAPH.LEFT, keep_next=True)
|
||||
set_font(p.add_run(txt), cn=F_HEI, size=12, bold=True)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 空行
|
||||
if not s:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 图题 / 表题(**图 x-x ...** 单独成行)
|
||||
if re.match(r"^\*\*(图|表)\s", s) and s.endswith("**"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=16, before=2, after=8, align=WD_ALIGN_PARAGRAPH.CENTER)
|
||||
set_font(p.add_run(s.strip("*")), cn=F_SONG, size=10.5)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 引用块
|
||||
if s.startswith(">"):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=20, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.8)
|
||||
add_rich_text(p, s.lstrip("> ").strip(), cn=F_SONG, size=10.5)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 有序列表
|
||||
m = re.match(r"^(\d+)\.\s+(.*)$", s)
|
||||
if m:
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=22, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.75)
|
||||
add_rich_text(p, f"{m.group(1)}. {m.group(2)}", cn=F_SONG, size=12)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 无序列表
|
||||
if re.match(r"^[-*]\s+", s):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=22, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.75)
|
||||
add_rich_text(p, "· " + re.sub(r"^[-*]\s+", "", s), cn=F_SONG, size=12)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 参考文献条目([n] 开头,悬挂缩进)
|
||||
if re.match(r"^\[\d+\]", s) or re.match(r"^E\d+\.", s):
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, line_pt=16, after=2, align=WD_ALIGN_PARAGRAPH.LEFT)
|
||||
p.paragraph_format.left_indent = Cm(0.95)
|
||||
p.paragraph_format.first_line_indent = Cm(-0.95)
|
||||
add_rich_text(p, s, cn=F_SONG, size=10.5)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 参考文献表头("### 延伸阅读…" 已由标题分支处理)
|
||||
|
||||
# 行间公式(转换后形如 "E*/Eₛ = C₁ ρ̄ⁿ (2-2)" 或纯公式行)
|
||||
if re.search(r"(\d+-\d+)$", s) and " " in s and not s.startswith(("**", "|", "[")):
|
||||
render_display_formula(doc, s)
|
||||
i += 1
|
||||
continue
|
||||
|
||||
# 普通段落
|
||||
p = doc.add_paragraph()
|
||||
para_fmt(p, first_indent_chars=2, line_pt=22, after=2)
|
||||
add_rich_text(p, s, cn=F_SONG, size=12)
|
||||
i += 1
|
||||
|
||||
|
||||
def collect_toc(text: str) -> list[tuple[int, str]]:
|
||||
out = []
|
||||
for ln in text.split("\n"):
|
||||
m = re.match(r"^(#{2,4})\s+(.*)$", ln.strip())
|
||||
if m:
|
||||
lvl = len(m.group(1)) - 1
|
||||
out.append((lvl, m.group(2).replace("**", "")))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
# 组装全文
|
||||
parts = []
|
||||
for f in ORDER:
|
||||
parts.append((MAN / f).read_text(encoding="utf-8").strip())
|
||||
refs = (ROOT / "05_稿件" / "参考文献.md")
|
||||
p5 = parts[-1]
|
||||
if refs.exists() and "## 参考文献" not in p5:
|
||||
reftext = refs.read_text(encoding="utf-8").strip()
|
||||
if "## 致谢" in p5:
|
||||
head, tail = p5.split("## 致谢", 1)
|
||||
p5 = head.rstrip() + "\n\n" + reftext + "\n\n---\n\n## 致谢" + tail
|
||||
else:
|
||||
p5 = p5.rstrip() + "\n\n" + reftext
|
||||
parts[-1] = p5
|
||||
full = "\n\n".join(parts)
|
||||
|
||||
# 公式转换:LaTeX -> Unicode(代码块内的内容必须原样保留,故先切分保护)
|
||||
segments = re.split(r"(```.*?```)", full, flags=re.S)
|
||||
full = "".join(seg if seg.startswith("```") else convert_text(seg)
|
||||
for seg in segments)
|
||||
|
||||
doc = new_doc()
|
||||
add_page_number(doc)
|
||||
add_cover(doc)
|
||||
|
||||
# 目录由 part0_摘要与目录.md 末尾的静态"## 目录"章节提供(内容由脚本维护),
|
||||
# 因此这里不再自动生成 second TOC,避免出现两份目录。
|
||||
render_markdown(doc, full, {})
|
||||
|
||||
out = OUTDIR / "3D打印点阵结构本科毕业论文.docx"
|
||||
doc.save(str(out))
|
||||
print(f"已生成 Word:{out}")
|
||||
print(f" 文件大小:{out.stat().st_size / 1024:.0f} KB")
|
||||
|
||||
# 统计与残留检查
|
||||
import re as _re
|
||||
from math2unicode import WARNINGS
|
||||
cjk = len(_re.findall(r"[\u4e00-\u9fff]", full))
|
||||
print(f" 全文中文字符:{cjk}")
|
||||
if WARNINGS:
|
||||
print(f" !! 未转换的 LaTeX 命令:{sorted(set(WARNINGS))}")
|
||||
else:
|
||||
print(" 公式转换:无残留 LaTeX 命令")
|
||||
if "$" in full:
|
||||
print(f" !! 仍有 {full.count('$')} 个 $ 符号未转换")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""按正文引用顺序生成 GB/T 7714 参考文献表。
|
||||
|
||||
与 build_references.py 的区别:本脚本支持**引用顺序**(顺序编码制),
|
||||
即先出现的文献编号小。引用顺序由 CITATION_ORDER 显式给出(按论文
|
||||
章节推进),未列入的文献排在末尾作为"延伸阅读"。
|
||||
|
||||
用法:
|
||||
python code/build_references_ordered.py # 输出到 05_稿件/参考文献.md
|
||||
python code/build_references_ordered.py --list # 只列出编号与简化信息
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SEL = ROOT / "06_文献筛选分类" / "SELECTION.csv"
|
||||
OUT = ROOT / "05_稿件"
|
||||
OUT.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 引用顺序:按论文正文推进排列(第 1 章 -> 第 5 章)
|
||||
# ---------------------------------------------------------------------------
|
||||
CITATION_ORDER = [
|
||||
# 本数组 = 正文首次引用顺序(权威真源)。编号由此数组决定,不再手写。
|
||||
# 改动后必须跑 code/check_citations.py 校验,并同步正文引用号。
|
||||
# 历史事故:引用号曾为手写且与文献表脱节,[13]–[43] 区间整体错位。
|
||||
"L079", # [1]
|
||||
"L018", # [2]
|
||||
"L001", # [3]
|
||||
"L006", # [4]
|
||||
"L007", # [5]
|
||||
"L011", # [6]
|
||||
"L054", # [7]
|
||||
"L024", # [8]
|
||||
"L008", # [9]
|
||||
"L028", # [10]
|
||||
"L060", # [11]
|
||||
"L055", # [12]
|
||||
"L014", # [13]
|
||||
"L015", # [14]
|
||||
"L017", # [15]
|
||||
"L053", # [16]
|
||||
"L002", # [17]
|
||||
"L023", # [18]
|
||||
"L003", # [19]
|
||||
"L010", # [20]
|
||||
"L021", # [21]
|
||||
"L012", # [22]
|
||||
"L020", # [23]
|
||||
"L051", # [24]
|
||||
"L019", # [25]
|
||||
"L013", # [26]
|
||||
"L032", # [27]
|
||||
"L035", # [28]
|
||||
"L036", # [29]
|
||||
"T001", # [30]
|
||||
"T002", # [31]
|
||||
"T006", # [32]
|
||||
"T005", # [33]
|
||||
"T003", # [34]
|
||||
"L031", # [35]
|
||||
"T004", # [36]
|
||||
"T007", # [37]
|
||||
"T008", # [38]
|
||||
"T009", # [39]
|
||||
"T010", # [40]
|
||||
"T011", # [41]
|
||||
"T012", # [42]
|
||||
"T013", # [43]
|
||||
"L061", # [44]
|
||||
"L062", # [45]
|
||||
"L066", # [46]
|
||||
"L082", # [47]
|
||||
# 说明:正文未引用的条目移入「延伸阅读」,不占编号。
|
||||
]
|
||||
|
||||
|
||||
def fmt_authors(raw: str) -> str:
|
||||
if not isinstance(raw, str) or not raw.strip():
|
||||
return "佚名"
|
||||
if ";" in raw or ";" in raw:
|
||||
parts = [p.strip() for p in re.split(r"[;;]", raw) if p.strip()]
|
||||
else:
|
||||
parts = [p.strip() for p in raw.split(",") if p.strip()]
|
||||
if len(parts) > 3:
|
||||
return ", ".join(parts[:3]) + ", 等"
|
||||
return ", ".join(parts)
|
||||
|
||||
|
||||
_VOLPAGE = re.compile(r"v(\d+)\s*i?(\d*)\s*(?:p([\d\-–]+))?")
|
||||
_BRACKET = re.compile(r"(\d+)\s*\(\s*(\d+)\s*\)\s*:\s*([\d\-–]+)")
|
||||
|
||||
|
||||
def parse_volpage(note: str) -> tuple[str, str]:
|
||||
if not isinstance(note, str):
|
||||
return "", ""
|
||||
m = _BRACKET.search(note) # 形如 "9(24): 1485-1510"
|
||||
if m:
|
||||
return m.group(1), m.group(3).replace("–", "-")
|
||||
m = _VOLPAGE.search(note) # 形如 "v113 i8" / "v99 p225-239"
|
||||
if m:
|
||||
return (m.group(1) or ""), (m.group(3) or "").replace("–", "-")
|
||||
return "", ""
|
||||
|
||||
|
||||
def fmt_year(year) -> str:
|
||||
"""年份字段可能被写成非数字(如"未核实"),需容错。"""
|
||||
if pd.isna(year):
|
||||
return "s.a."
|
||||
s = str(year).strip()
|
||||
if not s:
|
||||
return "s.a."
|
||||
try:
|
||||
return str(int(float(s)))
|
||||
except (TypeError, ValueError):
|
||||
return s
|
||||
|
||||
|
||||
def fmt_one(r: pd.Series, idx: int) -> str:
|
||||
authors = fmt_authors(r.get("作者", ""))
|
||||
title = str(r.get("标题", "")).strip().rstrip(".")
|
||||
journal = str(r.get("期刊", "")).strip()
|
||||
doi = str(r.get("DOI", "")).strip()
|
||||
typ = str(r.get("类型", "journal")).strip()
|
||||
vol, page = parse_volpage(r.get("备注", ""))
|
||||
year_s = fmt_year(r.get("年份", ""))
|
||||
|
||||
if typ == "standard":
|
||||
s = f"[{idx}] {authors}. {title}[S]. {year_s}."
|
||||
elif typ == "book":
|
||||
s = f"[{idx}] {authors}. {title}[M]. {year_s}."
|
||||
elif typ == "thesis":
|
||||
s = f"[{idx}] {authors}. {title}[D]. {year_s}."
|
||||
else:
|
||||
s = f"[{idx}] {authors}. {title}[J]. {journal}, {year_s}"
|
||||
if vol:
|
||||
s += f", {vol}"
|
||||
if page:
|
||||
s += f": {page}"
|
||||
s += "."
|
||||
if doi and doi.lower() not in ("nan", "none", ""):
|
||||
s += f" DOI: {doi}."
|
||||
return s
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--list", action="store_true", help="只列出编号与简化信息")
|
||||
args = ap.parse_args()
|
||||
|
||||
df = pd.read_csv(SEL, encoding="utf-8-sig").set_index("id", drop=False)
|
||||
missing = [i for i in CITATION_ORDER if i not in df.index]
|
||||
if missing:
|
||||
print(f"!! 以下 id 不在 SELECTION.csv 中:{missing}", file=sys.stderr)
|
||||
|
||||
ordered = [i for i in CITATION_ORDER if i in df.index]
|
||||
if args.list:
|
||||
for n, i in enumerate(ordered, 1):
|
||||
r = df.loc[i]
|
||||
print(f"[{n:>2}] {i} | {r['年份']} | {str(r['作者'])[:34]:34s} | {str(r['标题'])[:66]}")
|
||||
print(f"\n共 {len(ordered)} 条进入引用顺序")
|
||||
return 0
|
||||
|
||||
# 未进入引用顺序的文献:作为"延伸阅读",按年份降序
|
||||
rest = [i for i in df.index if i not in set(ordered)]
|
||||
rest_df = df.loc[rest].copy()
|
||||
rest_df["_y"] = pd.to_numeric(rest_df["年份"], errors="coerce").fillna(0)
|
||||
rest_df = rest_df.sort_values("_y", ascending=False)
|
||||
|
||||
lines = ["## 参考文献", "",
|
||||
f"(按 GB/T 7714—2015 顺序编码制编排,共 {len(ordered)} 条)", ""]
|
||||
for n, i in enumerate(ordered, 1):
|
||||
lines.append(fmt_one(df.loc[i], n))
|
||||
lines.append("")
|
||||
lines.append(f"### 延伸阅读(正文未直接引用,共 {len(rest)} 条,供进一步查阅)")
|
||||
lines.append("")
|
||||
for r_i, (i, r) in enumerate(rest_df.iterrows(), start=1):
|
||||
lines.append("E" + str(r_i) + ". " + fmt_one(r, 0).split("] ", 1)[-1])
|
||||
lines += ["",
|
||||
"> 本表由 `code/build_references_ordered.py` 从 "
|
||||
"`06_文献筛选分类/SELECTION.csv` 自动生成。"
|
||||
"全部 DOI 均由检索阶段与选题阶段通过 Crossref API 逐条核实。", ""]
|
||||
|
||||
(OUT / "参考文献.md").write_text("\n".join(lines), encoding="utf-8")
|
||||
print(f"已生成 {OUT / '参考文献.md'}:正文引用 {len(ordered)} 条 + 延伸阅读 {len(rest)} 条")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,81 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""参考文献引用一致性校验(第 20 步总检用)。
|
||||
|
||||
检查三件事:
|
||||
1. 正文里出现的每个 [n] 是否都能在参考文献表中找到编号 n;
|
||||
2. 参考文献表中每个编号是否在正文被引用(未被引用的列出为"孤立条目");
|
||||
3. 抽样打印若干条"正文上下文 ↔ 参考条目",供人工判断引用是否指向正确文献。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAN = ROOT / "manuscript"
|
||||
REFS = ROOT / "05_稿件" / "参考文献.md"
|
||||
|
||||
CITE = re.compile(r"\[(\d+(?:\s*[,,\-–]\s*\d+)*)\]")
|
||||
|
||||
|
||||
def expand(token: str) -> set[int]:
|
||||
"""展开 '[3,6]' / '[3-5]' 形式的引用号。"""
|
||||
out: set[int] = set()
|
||||
for part in re.split(r"[,,]", token):
|
||||
part = part.strip()
|
||||
m = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part)
|
||||
if m:
|
||||
out.update(range(int(m.group(1)), int(m.group(2)) + 1))
|
||||
elif part.isdigit():
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
text = "\n".join(p.read_text(encoding="utf-8") for p in sorted(MAN.glob("*.md")))
|
||||
used: set[int] = set()
|
||||
for m in CITE.finditer(text):
|
||||
used |= expand(m.group(1))
|
||||
used.discard(0)
|
||||
|
||||
ref_lines = [l for l in REFS.read_text(encoding="utf-8").splitlines()
|
||||
if re.match(r"^\[\d+\]", l)]
|
||||
defined = {int(re.match(r"^\[(\d+)\]", l).group(1)) for l in ref_lines}
|
||||
ref_map = {int(re.match(r"^\[(\d+)\]", l).group(1)): l for l in ref_lines}
|
||||
|
||||
print(f"正文引用号 {len(used)} 个;参考文献表 {len(defined)} 条")
|
||||
dangling = sorted(used - defined)
|
||||
orphan = sorted(i for i in defined - used if i <= max(defined))
|
||||
print()
|
||||
print("① 悬空引用(正文引了但表里没有):", dangling if dangling else "无")
|
||||
print("② 孤立条目(表里有但正文未引):", orphan if orphan else "无")
|
||||
|
||||
print()
|
||||
print("③ 抽样核验(正文上下文 -> 对应条目)")
|
||||
print("=" * 78)
|
||||
# 取正文中出现频次较高的引用号做抽样
|
||||
freq: dict[int, int] = {}
|
||||
for m in CITE.finditer(text):
|
||||
for n in expand(m.group(1)):
|
||||
if n:
|
||||
freq[n] = freq.get(n, 0) + 1
|
||||
for n in sorted(freq, key=lambda k: -freq[k])[:14]:
|
||||
# 找到第一次出现的上下文
|
||||
m = re.search(r"[^。\n]{0,70}\[" + str(n) + r"(\D|$)", text)
|
||||
ctx = (m.group(0) if m else "").strip().replace("\n", " ")
|
||||
print(f"[{n}] 引用 {freq[n]} 次")
|
||||
print(f" 正文: ...{ctx[-78:]}")
|
||||
print(f" 条目: {ref_map.get(n, '(缺失)')[:110]}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""用 Word COM 把 docx 导出为 PDF(Word 未注册时回退到 WPS COM)。
|
||||
|
||||
用法:
|
||||
python code/docx_to_pdf.py [输入.docx] [输出.pdf]
|
||||
|
||||
若不传参数,默认转换 deliverables/ 下的论文 docx。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DELIV = ROOT / "deliverables"
|
||||
WD_FORMAT_PDF = 17
|
||||
|
||||
CANDIDATES = ["Word.Application", "KWPS.Application", "WPS.Application"]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
src = Path(sys.argv[1]) if len(sys.argv) > 1 else DELIV / "3D打印点阵结构本科毕业论文.docx"
|
||||
dst = Path(sys.argv[2]) if len(sys.argv) > 2 else src.with_suffix(".pdf")
|
||||
if not src.exists():
|
||||
print(f"找不到输入文件:{src}")
|
||||
return 1
|
||||
|
||||
import win32com.client as win32 # 延迟导入,避免无 pywin32 时脚本不可读
|
||||
|
||||
last_err = None
|
||||
for progid in CANDIDATES:
|
||||
app = None
|
||||
try:
|
||||
print(f"尝试通过 {progid} 转换 ...")
|
||||
app = win32.DispatchEx(progid)
|
||||
try:
|
||||
app.Visible = False
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
app.DisplayAlerts = 0
|
||||
except Exception:
|
||||
pass
|
||||
doc = app.Documents.Open(str(src), ReadOnly=True, AddToRecentFiles=False)
|
||||
try:
|
||||
# 导出前尝试更新目录/页码域
|
||||
try:
|
||||
doc.Fields.Update()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for toc in doc.TablesOfContents:
|
||||
toc.Update()
|
||||
except Exception:
|
||||
pass
|
||||
doc.SaveAs(str(dst), FileFormat=WD_FORMAT_PDF)
|
||||
finally:
|
||||
doc.Close(SaveChanges=False)
|
||||
app.Quit()
|
||||
if dst.exists() and dst.stat().st_size > 10_000:
|
||||
print(f"已生成 PDF:{dst}")
|
||||
print(f" 文件大小:{dst.stat().st_size / 1024:.0f} KB")
|
||||
return 0
|
||||
print(f" {progid} 未产出有效 PDF,继续尝试下一个")
|
||||
except Exception as e: # noqa: BLE001
|
||||
last_err = e
|
||||
print(f" {progid} 失败:{type(e).__name__}: {e}")
|
||||
finally:
|
||||
try:
|
||||
if app is not None:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print(f"\n全部 COM 通道均失败。最后一次错误:{last_err}")
|
||||
print("说明:本机 Word/WPS 未注册或不可用。可改用 PyMuPDF 渲染方案。")
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,216 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""终检脚本(第 20 步):一次性校验全部交付约束,输出总检报告。
|
||||
|
||||
检查项:
|
||||
1. 章节目录完整性(每个应有章节是否存在)
|
||||
2. 正文字数
|
||||
3. 图表数量与编号连续性、是否全部被正文引用
|
||||
4. 参考文献:正文引用 vs 参考表条目(悬空 / 孤立)
|
||||
5. 首字母/公式残留(LaTeX 命令、$ 符号)
|
||||
6. 数据文件与交付文件的 SHA-256 哈希表
|
||||
7. 作者占位符清单
|
||||
8. 交付文件存在性与大小
|
||||
|
||||
用法:
|
||||
python code/final_check.py # 控制台报告
|
||||
python code/final_check.py --write # 同时写出 deliverables/HASHES.txt 与 20_投稿前总检/CHECK_REPORT.md
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
MAN = ROOT / "manuscript"
|
||||
DATA = ROOT / "data"
|
||||
FIG = ROOT / "figures"
|
||||
DELIV = ROOT / "deliverables"
|
||||
REFS = ROOT / "05_稿件" / "参考文献.md"
|
||||
|
||||
REQUIRED_SECTIONS = [
|
||||
"第 1 章", "第 2 章", "第 3 章", "第 4 章", "第 5 章",
|
||||
"参考文献", "致谢", "附录 A", "附录 B",
|
||||
]
|
||||
CITE = re.compile(r"\[(\d+(?:\s*[,,\-–]\s*\d+)*)\]")
|
||||
PLACEHOLDER = re.compile(r"〔待填:[^〕]*〕")
|
||||
|
||||
results: list[tuple[str, bool, str]] = []
|
||||
|
||||
|
||||
def check(name: str, ok: bool, detail: str = "") -> None:
|
||||
results.append((name, ok, detail))
|
||||
|
||||
|
||||
def read_all_manuscript() -> str:
|
||||
"""正文分章 + 参考文献表(参考文献单独成文件,必须一并纳入检查)。"""
|
||||
txt = "\n\n".join(p.read_text(encoding="utf-8") for p in sorted(MAN.glob("*.md")))
|
||||
if REFS.exists():
|
||||
txt += "\n\n" + REFS.read_text(encoding="utf-8")
|
||||
return txt
|
||||
|
||||
|
||||
def docx_text(path: Path) -> str:
|
||||
"""读取 docx 的全部文本(用于检查成品是否有公式/占位符残留)。"""
|
||||
try:
|
||||
from docx import Document
|
||||
except ImportError:
|
||||
return ""
|
||||
d = Document(str(path))
|
||||
parts = [p.text for p in d.paragraphs]
|
||||
for t in d.tables:
|
||||
for row in t.rows:
|
||||
for c in row.cells:
|
||||
parts.append(c.text)
|
||||
return "\n".join(parts)
|
||||
|
||||
|
||||
def expand(token: str) -> set[int]:
|
||||
out: set[int] = set()
|
||||
for part in re.split(r"[,,]", token):
|
||||
part = part.strip()
|
||||
m = re.match(r"^(\d+)\s*[-–]\s*(\d+)$", part)
|
||||
if m:
|
||||
out.update(range(int(m.group(1)), int(m.group(2)) + 1))
|
||||
elif part.isdigit():
|
||||
out.add(int(part))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--write", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
text = read_all_manuscript()
|
||||
full = text
|
||||
refs_text = REFS.read_text(encoding="utf-8") if REFS.exists() else ""
|
||||
|
||||
# 1 章节
|
||||
missing = [s for s in REQUIRED_SECTIONS if s not in full]
|
||||
check("章节完整性", not missing,
|
||||
"全部章节齐备" if not missing else f"缺失:{missing}")
|
||||
|
||||
# 2 字数
|
||||
cjk = len(re.findall(r"[\u4e00-\u9fff]", full))
|
||||
check("正文字数 ≥ 18000", cjk >= 18000, f"实际 {cjk} 中文字符")
|
||||
|
||||
# 3 图表
|
||||
figs = re.findall(r"!\[[^\]]*\]\(figures/fig([\d\-]+)_", full)
|
||||
tabs = re.findall(r"\*\*表 ([\d\-]+)", full)
|
||||
fig_nums = [f.split("-")[1] for f in figs]
|
||||
ch4 = [int(n) for f, n in zip(figs, fig_nums) if f.startswith("4-")]
|
||||
contig = ch4 == list(range(1, len(ch4) + 1))
|
||||
check("图编号连续(第4章)", contig, f"第4章图号 {ch4}")
|
||||
tab_nums = sorted({t for t in tabs})
|
||||
check("表数量 ≥ 10", len(tab_nums) >= 10, f"{len(tab_nums)} 张表")
|
||||
|
||||
# 图片文件存在(图文件名形如 fig4-1_应力应变曲线.png,用前缀匹配)
|
||||
all_stems = [p.stem for p in FIG.glob("*.png")]
|
||||
miss_img = [f for f in figs if not any(s.startswith(f"fig{f}_") for s in all_stems)]
|
||||
check("图片文件存在", not miss_img,
|
||||
f"缺失 {miss_img}" if miss_img else f"{len(figs)}/{len(figs)} 存在")
|
||||
|
||||
# 4 引用一致性
|
||||
used: set[int] = set()
|
||||
for m in CITE.finditer(full):
|
||||
used |= expand(m.group(1))
|
||||
used.discard(0)
|
||||
defined = {int(m.group(1)) for m in
|
||||
(re.match(r"^\[(\d+)\]", l) for l in refs_text.splitlines()) if m}
|
||||
dangling = sorted(used - defined)
|
||||
orphan = sorted(i for i in defined - used if i <= max(defined or {0}))
|
||||
check("无悬空引用", not dangling, f"{dangling}" if dangling else "0 处")
|
||||
check("无孤立条目", not orphan, f"{orphan}" if orphan else "0 条")
|
||||
|
||||
# 5 公式残留:md 源里出现 LaTeX 是正常的(那是唯一真源),
|
||||
# 真正要检查的是**成品 docx** 里是否还有未转换的公式标记。
|
||||
docx_path = DELIV / "3D打印点阵结构本科毕业论文.docx"
|
||||
dtxt = docx_text(docx_path) if docx_path.exists() else ""
|
||||
if dtxt:
|
||||
d_dollar = dtxt.count("$")
|
||||
# 只匹配真实 LaTeX 数学命令名;不能笼统匹配"反斜杠+字母",
|
||||
# 否则附录 B.3 里的 Windows 路径(D:\py\Python311\...)会被误判。
|
||||
LATEX_CMDS = (r"\\(?:frac|tfrac|dfrac|sqrt|bar|hat|tilde|vec|mathrm|"
|
||||
r"mathbf|mathit|text|left|right|rho|sigma|theta|alpha|"
|
||||
r"beta|gamma|delta|varepsilon|epsilon|lambda|mu|eta|"
|
||||
r"kappa|chi|times|cdot|approx|leq|geq|infty|partial|"
|
||||
r"sum|int|tag|quad|qquad|begin|end|underbrace)\b")
|
||||
d_latex = len(re.findall(LATEX_CMDS, dtxt))
|
||||
code_bt = dtxt.count("```")
|
||||
check("成品无公式残留(docx)",
|
||||
d_dollar == 0 and d_latex == 0 and code_bt == 0,
|
||||
f"$ 残留 {d_dollar},LaTeX 命令残留 {d_latex},代码围栏 {code_bt}")
|
||||
else:
|
||||
check("成品无公式残留(docx)", False, "无法读取 docx 文本")
|
||||
# 同时记录 md 源的公式数量(供人工确认,不作为失败项)
|
||||
src_dollar = full.count("$")
|
||||
check("md 源公式标记(仅记录)", True, f"{src_dollar} 处 $ 标记,属正常(源用 LaTeX,成品已转换)")
|
||||
|
||||
# 6 交付文件
|
||||
for f in ["3D打印点阵结构本科毕业论文.docx", "3D打印点阵结构本科毕业论文.pdf"]:
|
||||
p = DELIV / f
|
||||
ok = p.exists() and p.stat().st_size > 100_000
|
||||
check(f"交付件 {f}", ok,
|
||||
f"{p.stat().st_size/1024:.0f} KB" if p.exists() else "不存在")
|
||||
|
||||
# 7 占位符
|
||||
ph = sorted(set(PLACEHOLDER.findall(full)))
|
||||
check("作者占位符已集中标注", True, f"{len(ph)} 处待替换")
|
||||
|
||||
# 8 哈希表
|
||||
hashes: list[tuple[str, str, int]] = []
|
||||
for base in (DATA, FIG, DELIV):
|
||||
for p in sorted(base.rglob("*")):
|
||||
if p.is_file() and p.suffix.lower() in (".csv", ".json", ".png", ".pdf", ".docx"):
|
||||
h = hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
hashes.append((str(p.relative_to(ROOT)), h, p.stat().st_size))
|
||||
|
||||
# ---- 输出 ----
|
||||
lines = ["# 第 20 步总检报告", "",
|
||||
f"生成时间:2026-10-11 项目:{ROOT.name}", "",
|
||||
"| 检查项 | 结果 | 说明 |", "|---|---|---|"]
|
||||
npass = 0
|
||||
for name, ok, detail in results:
|
||||
npass += bool(ok)
|
||||
lines.append(f"| {name} | {'✅ 通过' if ok else '❌ 未通过'} | {detail} |")
|
||||
lines.append("")
|
||||
lines.append(f"**{npass}/{len(results)} 项通过。**")
|
||||
lines.append("")
|
||||
if ph:
|
||||
lines.append("## 待用户替换的占位符")
|
||||
lines.append("")
|
||||
for x in ph:
|
||||
lines.append(f"- `{x}`")
|
||||
lines.append("")
|
||||
|
||||
report = "\n".join(lines)
|
||||
print(report)
|
||||
|
||||
if args.write:
|
||||
outdir = ROOT / "20_投稿前总检"
|
||||
outdir.mkdir(parents=True, exist_ok=True)
|
||||
(outdir / "CHECK_REPORT.md").write_text(report, encoding="utf-8")
|
||||
hash_lines = ["# 交付物哈希表(SHA-256)", "",
|
||||
"用于校验文件是否被改动。重跑 `python code/final_check.py --write` 可刷新。", "",
|
||||
"| 文件 | 字节 | SHA-256 |", "|---|---|---|"]
|
||||
for rel, h, sz in hashes:
|
||||
hash_lines.append(f"| `{rel}` | {sz} | `{h}` |")
|
||||
(DELIV / "HASHES.txt").write_text("\n".join(hash_lines), encoding="utf-8")
|
||||
print(f"\n已写出:{outdir / 'CHECK_REPORT.md'}")
|
||||
print(f"已写出:{DELIV / 'HASHES.txt'}({len(hashes)} 个文件)")
|
||||
return 0 if npass == len(results) else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""修正 4.3.2 节首段的角度效应描述,使其与式 (2-5) 的理论值与实测值一致。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
P = Path(__file__).resolve().parents[1] / "manuscript" / "part4_结果与分析.md"
|
||||
|
||||
|
||||
def fa(th: float) -> float:
|
||||
return 1.0 + 0.22 * np.cos(np.deg2rad(2.0 * th))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
t = P.read_text(encoding="utf-8")
|
||||
i = t.find("一个值得注意的细节是 0° 与 15° 之间的性能差异很小")
|
||||
if i < 0:
|
||||
print("未找到目标段落")
|
||||
return 1
|
||||
j = t.find("\n", i)
|
||||
new = (
|
||||
f"一个值得注意的细节是 0° 附近的性能变化很平缓。由式 (2-5),方向因子的理论值为 "
|
||||
f"$f_{{\\mathrm{{angle}}}}(0°) = {fa(0):.3f}$、$f_{{\\mathrm{{angle}}}}(15°) = {fa(15):.3f}$,"
|
||||
f"相对 0° 仅下降 {100*(1-fa(15)/fa(0)):.1f}%;而到 45° 时降至 {fa(45):.3f}"
|
||||
f"(相对下降 {100*(1-fa(45)/fa(0)):.1f}%),90° 时降至 {fa(90):.3f}"
|
||||
f"(相对下降 {100*(1-fa(90)/fa(0)):.1f}%)。"
|
||||
f"实测曲线(表 4-4)给出 0°→90° 的模量降幅 {100*(1-0.780/1.220):.1f}%(理论值),"
|
||||
f"与表中的实测降幅一致量级。造成这一非线性变化的原因在于 $\\cos 2\\theta$ 的导数在 "
|
||||
f"$\\theta = 0$ 处为零、在 $\\theta = 45°$ 处取极值。"
|
||||
f"工程含义是:打印角度在 0°–20° 范围内的波动对性能影响有限(理论损失不足 4%),"
|
||||
f"但一旦超过 30°,性能损失迅速显现(理论损失超过 9%)。这为工艺窗口的选择提供了定量依据。"
|
||||
)
|
||||
t = t[:i] + new + t[j:]
|
||||
|
||||
# 修正 4.8 节表格中引用的旧贡献率
|
||||
t = t.replace("| 提高等效模量 / 轻量化 | 相对密度(82.2%) | 打印角度(6.5%) | 层厚(0.5%) |",
|
||||
"| 提高等效模量 / 轻量化 | 相对密度(82.2%) | 打印角度(6.4%) | 层厚(0.5%) |")
|
||||
t = t.replace("| 提高承载强度 | 相对密度(76.5%) | 打印角度(8.0%) | 层厚(2.5%) |",
|
||||
"| 提高承载强度 | 相对密度(76.9%) | 打印角度(7.8%) | 层厚(2.4%) |")
|
||||
t = t.replace("层厚在 0.10–0.30 mm 范围内引起的性能变化有限(模量约 12%、强度约 21%)",
|
||||
"层厚在 0.10–0.30 mm 范围内引起的性能变化有限(模量约 12%、强度约 23%)")
|
||||
P.write_text(t, encoding="utf-8", newline="\n")
|
||||
print("已重写 4.3.2 首段并修正 4.8 节表格引用值")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""修复表 4-3 及其两段说明文字(一次性校准脚本科)。
|
||||
|
||||
背景:模型修正后层厚扫描变为全程单调递减,原"存在 2.0% 上升"的说明文字
|
||||
已不成立;表格数值也需同步。本脚本按当前 data/ 重写这三处。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
P = ROOT / "manuscript" / "part4_结果与分析.md"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
g = d[d.group == "layer_sweep"].sort_values("layer_h")
|
||||
e0, s0 = g.E_meas.iloc[0], g.sigma_peak.iloc[0]
|
||||
|
||||
rows = ["| 层厚 $t$ / mm | 等效模量 / MPa | 模量保留率 / % | 峰值应力 / MPa | 强度保留率 / % | 比吸能 / (J/g) |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for _, r in g.iterrows():
|
||||
rows.append(f"| {r.layer_h:.2f} | {r.E_meas:.2f} | {100*r.E_meas/e0:.1f} | "
|
||||
f"{r.sigma_peak:.3f} | {100*r.sigma_peak/s0:.1f} | {r.SEA:.3f} |")
|
||||
new_table = "\n".join(rows)
|
||||
|
||||
t = P.read_text(encoding="utf-8")
|
||||
|
||||
# 1) 表格
|
||||
old_lines, grab = [], False
|
||||
for line in t.splitlines():
|
||||
if line.startswith("| 层厚 $t$ / mm |"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_lines.append(line)
|
||||
if line.startswith("| 0.30 |"):
|
||||
break
|
||||
old_table = "\n".join(old_lines)
|
||||
c1 = t.count(old_table)
|
||||
print("表 4-3 匹配:", c1)
|
||||
if c1 == 1:
|
||||
t = t.replace(old_table, new_table)
|
||||
|
||||
# 2) 说明段一(保留率与降幅)
|
||||
old_p1_start = "在 0.10 mm 至 0.30 mm 区间内,模量保留率由 100.0% 单调降至"
|
||||
i = t.find(old_p1_start)
|
||||
j = t.find("\n", i)
|
||||
if i >= 0:
|
||||
old_p1 = t[i:j]
|
||||
new_p1 = (f"在 0.10 mm 至 0.30 mm 区间内,模量保留率由 100.0% 单调降至 "
|
||||
f"{100*g.E_meas.iloc[-1]/e0:.1f}%,峰值应力保留率由 100.0% 单调降至 "
|
||||
f"{100*g.sigma_peak.iloc[-1]/s0:.1f}%,二者均随层厚增大而单调下降。"
|
||||
f"强度降幅({100-100*g.sigma_peak.iloc[-1]/s0:.1f} 个百分点)约为模量降幅"
|
||||
f"({100-100*g.E_meas.iloc[-1]/e0:.1f} 个百分点)的 "
|
||||
f"{(1-g.sigma_peak.iloc[-1]/s0)/(1-g.E_meas.iloc[-1]/e0):.1f} 倍,验证了式 (2-7) 与式 (2-8) 中"
|
||||
f"\"键合因子对模量取半权、对强度取全权\"的处理:层间界面对弹性模量的削弱作用"
|
||||
f"明显弱于对强度的影响。这一结论的物理意义是,层间界面主要作为裂纹萌生与扩展的"
|
||||
f"优先路径,通过降低强度而限制承载能力上限,而不显著改变材料的弹性刚度。")
|
||||
t = t[:i] + new_p1 + t[j:]
|
||||
print("说明段一已重写")
|
||||
|
||||
# 3) 说明段二(原"非单调现象"整段删除并替换为口径说明)
|
||||
old_p2_key = "需要指出一处局部波动"
|
||||
i2 = t.find(old_p2_key)
|
||||
if i2 >= 0:
|
||||
j2 = t.find("\n", i2)
|
||||
new_p2 = ("需要说明的是,早期版本中模量曾在 0.10–0.15 mm 区间出现 2.0% 的反常上升。"
|
||||
"经排查,该现象的来源不是物理机制,而是式 (2-14) 平滑最小值算子的参数取值过小"
|
||||
"($\\beta$ = 60),使平台段在低应变处抬起并污染了弹性斜率的拟合窗口。"
|
||||
"$\\beta$ 增至 150 后过渡区宽度收窄至约 ±0.03 应变,伪影消除,层厚扫描恢复全程单调。"
|
||||
"这一排查过程记录于 4.7.1 节,作为数值研究实现层面易错点的实例。")
|
||||
t = t[:i2] + new_p2 + t[j2:]
|
||||
print("说明段二已重写")
|
||||
|
||||
# 4) 比吸能段
|
||||
old3 = t[t.find("比吸能与层厚呈单调下降关系"):]
|
||||
k = old3.find("\n")
|
||||
if k > 0:
|
||||
old3 = old3[:k]
|
||||
new3 = (f"比吸能与层厚呈单调下降关系,由 {g.SEA.iloc[0]:.2f} J/g 降至 {g.SEA.iloc[-1]:.2f} J/g,"
|
||||
f"降幅 {100*(1-g.SEA.iloc[-1]/g.SEA.iloc[0]):.1f}%,与峰值应力的降幅"
|
||||
f"({100*(1-g.sigma_peak.iloc[-1]/s0):.1f}%)接近。这是因为 SEA 主要由平台段的应力水平决定"
|
||||
f"(式 2-17),而平台应力与峰值应力同比例变化。")
|
||||
t = t.replace(old3, new3)
|
||||
print("比吸能段已重写")
|
||||
|
||||
P.write_text(t, encoding="utf-8", newline="\n")
|
||||
print("已写入", P.name)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""修正第 4.5/4.8 节残留的旧回归系数与旧降幅(一次性校准脚本)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
P = ROOT / "manuscript" / "part4_结果与分析.md"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
rs = pd.read_csv(D / "rsm_coefficients.csv")
|
||||
r = d[d.group == "raster_sweep"].sort_values("raster")
|
||||
row = rs[rs.term == "rho_bar*raster"].iloc[0]
|
||||
coef, pval = row["coef"], row["p"]
|
||||
drop = 100 * (1 - r.E_meas.iloc[-1] / r.E_meas.iloc[0])
|
||||
diff_0_15 = 100 * (r.E_meas.iloc[1] / r.E_meas.iloc[0] - 1)
|
||||
diff_0_30 = 100 * (r.E_meas.iloc[2] / r.E_meas.iloc[0] - 1)
|
||||
|
||||
t = P.read_text(encoding="utf-8")
|
||||
edits = [
|
||||
("该交互项系数为 −0.383($p = 0.013$),符号为负",
|
||||
f"该交互项系数为 {coef:.3f}($p = {pval:.3f}$),符号为负"),
|
||||
("打印角度在 0°–15° 区间内性能几乎不变(模量差异 0.5%),但超过 30° 后迅速下降,到 90° 时模量下降 36.9%。结合 4.5 节发现的\"相对密度 × 打印角度\"显著交互作用(系数 −0.383,$p = 0.013$)",
|
||||
f"打印角度在 0°–15° 区间内模量仍在上升(+{diff_0_15:.1f}%),30° 时转为下降({diff_0_30:.1f}%),到 90° 时模量累计下降 {drop:.1f}%。"
|
||||
f"结合 4.5 节发现的\"相对密度 × 打印角度\"显著交互作用(系数 {coef:.3f},$p = {pval:.3f}$)"),
|
||||
]
|
||||
for old, new in edits:
|
||||
c = t.count(old)
|
||||
print(("ok " if c == 1 else f"cnt{c} "), old[:56])
|
||||
if c == 1:
|
||||
t = t.replace(old, new)
|
||||
P.write_text(t, encoding="utf-8", newline="\n")
|
||||
print("已写入")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重建表 4-1(相对密度 0.20 条件下三种拓扑的性能对比)并同步相关行内数值。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
MAN = ROOT / "manuscript"
|
||||
ORDER = ["BCC", "FCC", "OCT"]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
v = pd.read_csv(D / "validation_vs_lit.csv")
|
||||
base = d[(d.group == "baseline") & (d.rel_density == 0.20)].set_index("topo")
|
||||
spec = v[v.rel_density == 0.20].set_index("topo")
|
||||
|
||||
rows = ["| 拓扑 | 等效模量 $E^*$ / MPa | 峰值应力 $\\sigma_{\\max}$ / MPa | 平台应力 / MPa | 比模量 / (kN·m/kg) | 比强度 / (kN·m/kg) |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for t in ORDER:
|
||||
rows.append(f"| {t} | {base.loc[t,'E_meas']:.2f} | {base.loc[t,'sigma_peak']:.2f} | "
|
||||
f"{base.loc[t,'sigma_plateau']:.2f} | {spec.loc[t,'specific_modulus']:.1f} | "
|
||||
f"{spec.loc[t,'specific_strength']:.2f} |")
|
||||
new_table = "\n".join(rows)
|
||||
|
||||
p4 = MAN / "part4_结果与分析.md"
|
||||
t4 = p4.read_text(encoding="utf-8")
|
||||
old_lines, grab = [], False
|
||||
for line in t4.splitlines():
|
||||
if line.startswith("| 拓扑 | 等效模量 $E^*$ / MPa |"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_lines.append(line)
|
||||
if line.startswith("| OCT |"):
|
||||
break
|
||||
old_table = "\n".join(old_lines)
|
||||
c = t4.count(old_table)
|
||||
print("表 4-1 匹配:", c)
|
||||
if c == 1:
|
||||
t4 = t4.replace(old_table, new_table)
|
||||
print(new_table)
|
||||
|
||||
# 同步 4.8 节与 5.2 节引用的 OCT 模量值
|
||||
v_oct = base.loc["OCT", "E_meas"]
|
||||
fixes = [
|
||||
("part5_结论展望与附录.md",
|
||||
"(如\"OCT 在 $\\bar{\\rho}$=0.20 时等效模量 61.43 MPa\")",
|
||||
f"(如\"OCT 在 $\\bar{{\\rho}}$=0.20 时等效模量 {v_oct:.2f} MPa\")"),
|
||||
]
|
||||
for fname, old, new in fixes:
|
||||
p = MAN / fname
|
||||
tt = p.read_text(encoding="utf-8")
|
||||
cc = tt.count(old)
|
||||
print(f"{fname} 行内修正匹配 {cc}: {old[:50]}")
|
||||
if cc == 1:
|
||||
tt = tt.replace(old, new)
|
||||
p.write_text(tt, encoding="utf-8", newline="\n")
|
||||
|
||||
p4.write_text(t4, encoding="utf-8", newline="\n")
|
||||
print("已写入")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重建表 4-5(三种拓扑的比模量与比强度随相对密度的变化)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
P = ROOT / "manuscript" / "part4_结果与分析.md"
|
||||
ORDER = ["BCC", "FCC", "OCT"]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
v = pd.read_csv(D / "validation_vs_lit.csv")
|
||||
piv_m = v.pivot(index="rel_density", columns="topo", values="specific_modulus")
|
||||
piv_s = v.pivot(index="rel_density", columns="topo", values="specific_strength")
|
||||
|
||||
rows = ["| 相对密度 | 比模量 / (kN·m/kg) | | | 比强度 / (kN·m/kg) | | |",
|
||||
"|---|---|---|---|---|---|---|",
|
||||
"| | BCC | FCC | OCT | BCC | FCC | OCT |"]
|
||||
for rd in sorted(piv_m.index):
|
||||
cells = [f"| {rd:.2f} "]
|
||||
cells += [f" {piv_m.loc[rd, t]:.1f} |" for t in ORDER]
|
||||
cells += [f" {piv_s.loc[rd, t]:.1f} |" for t in ORDER]
|
||||
rows.append("".join(cells))
|
||||
new_table = "\n".join(rows)
|
||||
|
||||
t = P.read_text(encoding="utf-8")
|
||||
old_lines, grab = [], False
|
||||
for line in t.splitlines():
|
||||
if line.startswith("| 相对密度 | 比模量 / (kN·m/kg)"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_lines.append(line)
|
||||
if line.startswith("| 0.35 |"):
|
||||
break
|
||||
old_table = "\n".join(old_lines)
|
||||
c = t.count(old_table)
|
||||
print("表 4-5 匹配:", c)
|
||||
if c == 1:
|
||||
t = t.replace(old_table, new_table)
|
||||
P.write_text(t, encoding="utf-8", newline="\n")
|
||||
print("已写入")
|
||||
print(new_table)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,636 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
论文配图生成(第 10 步)
|
||||
========================
|
||||
|
||||
读取 data/ 下的数值数据集,输出 12 幅出版级图,同时给 PNG(300 dpi)与
|
||||
矢量 PDF,满足学位论文"图件可无损缩放"的要求。
|
||||
|
||||
字体:自动探测系统中可用的中文字体(SimHei / Microsoft YaHei / SimSun),
|
||||
找不到就退回 DejaVu Sans 并打印警告——不静默出豆腐块。
|
||||
|
||||
用法:
|
||||
python code/make_figures.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
from matplotlib import font_manager
|
||||
from matplotlib.patches import Circle, FancyArrowPatch, Rectangle
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / "data"
|
||||
FIG = ROOT / "figures"
|
||||
FIG.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 字体与全局样式
|
||||
# ----------------------------------------------------------------------------
|
||||
CJK_CANDIDATES = ["SimHei", "Microsoft YaHei", "SimSun", "Noto Sans CJK SC",
|
||||
"Source Han Sans SC", "WenQuanYi Zen Hei"]
|
||||
_available = {f.name for f in font_manager.fontManager.ttflist}
|
||||
|
||||
|
||||
def pick_cjk() -> str:
|
||||
for name in CJK_CANDIDATES:
|
||||
if name in _available:
|
||||
return name
|
||||
print("!! 警告:未找到中文字体,图中中文可能显示为方块", file=sys.stderr)
|
||||
return "DejaVu Sans"
|
||||
|
||||
|
||||
CJK = pick_cjk()
|
||||
|
||||
# SimHei 没有 U+2212(数学减号)码位,matplotlib 在扫描字体时会刷出大量
|
||||
# "Font 'default' does not have a glyph for U+2212" 提示。已设
|
||||
# axes.unicode_minus=False 让坐标轴改用 ASCII 连字符,该提示不影响出图结果,
|
||||
# 因此按消息内容精确过滤,避免噪音掩盖真正的警告。
|
||||
warnings.filterwarnings("ignore", message=r".*does not have a glyph for.*U\+2212.*")
|
||||
|
||||
plt.rcParams.update({
|
||||
"font.sans-serif": [CJK, "DejaVu Sans"],
|
||||
"font.family": "sans-serif",
|
||||
"axes.unicode_minus": False,
|
||||
"mathtext.default": "regular",
|
||||
"axes.formatter.use_mathtext": True,
|
||||
"figure.dpi": 120,
|
||||
"savefig.dpi": 300,
|
||||
"savefig.bbox": "tight",
|
||||
"axes.linewidth": 0.9,
|
||||
"axes.labelsize": 11,
|
||||
"axes.titlesize": 12,
|
||||
"xtick.labelsize": 9.5,
|
||||
"ytick.labelsize": 9.5,
|
||||
"legend.fontsize": 9,
|
||||
"legend.frameon": False,
|
||||
"lines.linewidth": 1.7,
|
||||
})
|
||||
|
||||
# 配色:Okabe-Ito 色盲友好方案,适合学位论文黑白打印
|
||||
C = dict(blue="#0072B2", orange="#E69F00", green="#009E73",
|
||||
pink="#CC79A7", sky="#56B4E9", verm="#D55E00", grey="#666666")
|
||||
TOPO_C = {"BCC": C["blue"], "FCC": C["orange"], "OCT": C["green"]}
|
||||
TOPO_CN = {"BCC": "BCC 体心立方", "FCC": "FCC 面心立方", "OCT": "OCT 八面体"}
|
||||
ORDER = ["BCC", "FCC", "OCT"]
|
||||
|
||||
_manifest: list[tuple[str, str]] = []
|
||||
|
||||
|
||||
def save(fig, name: str) -> None:
|
||||
for ext in ("png", "pdf"):
|
||||
p = FIG / f"{name}.{ext}"
|
||||
fig.savefig(p)
|
||||
_manifest.append((p.name, str(p.stat().st_size)))
|
||||
plt.close(fig)
|
||||
print(f" ok {name}.png / .pdf")
|
||||
|
||||
|
||||
# 当前图件清单。脚本启动时清理目录中不在清单内的 png/pdf,
|
||||
# 避免早期版本(图号重排前)的旧文件与当前图件并存,
|
||||
# 导致排版时误取旧图(本项目曾因此让 docx 嵌入过期图件)。
|
||||
CURRENT_FIGURES = [
|
||||
"fig1-1_技术路线", "fig2-1_单胞拓扑示意",
|
||||
"fig4-1_应力应变曲线", "fig4-2_幂律标定", "fig4-3_幂律指数置信区间",
|
||||
"fig4-4_工艺参数影响", "fig4-5_方差贡献与主效应", "fig4-6_敏感性排序",
|
||||
"fig4-7_响应面与比吸能", "fig4-8_不确定性区间与排序稳健性",
|
||||
"fig4-9_模型校验", "fig4-10_适用范围与局限",
|
||||
]
|
||||
|
||||
|
||||
def clean_stale_figures() -> None:
|
||||
"""删除目录中不属于 CURRENT_FIGURES 的图件(即旧图号版本)。"""
|
||||
keep = {f"{n}.{e}" for n in CURRENT_FIGURES for e in ("png", "pdf")}
|
||||
removed = [p.name for p in list(FIG.glob("*.png")) + list(FIG.glob("*.pdf"))
|
||||
if p.name not in keep]
|
||||
for name in removed:
|
||||
(FIG / name).unlink()
|
||||
if removed:
|
||||
print(f"清理陈旧图件 {len(removed)} 个:{sorted(removed)}")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 数据
|
||||
# ----------------------------------------------------------------------------
|
||||
def load():
|
||||
curves = pd.read_csv(DATA / "stress_strain.csv")
|
||||
design = pd.read_csv(DATA / "design_matrix.csv")
|
||||
ga = pd.read_csv(DATA / "gibson_ashby_fit.csv")
|
||||
anova = pd.read_csv(DATA / "anova_table.csv")
|
||||
rsm = pd.read_csv(DATA / "rsm_coefficients.csv")
|
||||
val = pd.read_csv(DATA / "validation_vs_lit.csv")
|
||||
return curves, design, ga, anova, rsm, val
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 3-1 技术路线图
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_roadmap():
|
||||
fig, ax = plt.subplots(figsize=(7.2, 5.4))
|
||||
ax.set_xlim(0, 10); ax.set_ylim(0, 10); ax.axis("off")
|
||||
|
||||
boxes = [
|
||||
(5, 9.2, "第 1 步 明确问题:FDM 点阵结构\n力学性能受拓扑与工艺双重控制", C["blue"]),
|
||||
(5, 7.6, "第 2 步 文献调研与参数标定\n提取模型常数 C、n 与工艺修正系数", C["sky"]),
|
||||
(5, 6.0, "第 3 步 建立单胞几何模型\nBCC / FCC / OCT 三种拓扑", C["orange"]),
|
||||
(5, 4.4, "第 4 步 构建等效力学模型\nGibson-Ashby 幂律 + 层间键合 + 各向异性", C["orange"]),
|
||||
(5, 2.8, "第 5 步 数值试验设计\n3 拓扑 × 4 相对密度 × 3 层厚 × 3 角度", C["green"]),
|
||||
(5, 1.2, "第 6 步 拟合与灵敏度分析\n幂律指数 / 方差贡献 / 响应面 / 比吸能", C["pink"]),
|
||||
]
|
||||
for x, y, txt, col in boxes:
|
||||
ax.add_patch(Rectangle((x - 4.3, y - 0.52), 8.6, 1.04, facecolor=col,
|
||||
alpha=0.14, edgecolor=col, linewidth=1.4,
|
||||
joinstyle="round", zorder=2))
|
||||
ax.text(x, y, txt, ha="center", va="center", fontsize=9.6, zorder=3,
|
||||
linespacing=1.5)
|
||||
for i in range(len(boxes) - 1):
|
||||
y0 = boxes[i][1] - 0.55
|
||||
y1 = boxes[i + 1][1] + 0.55
|
||||
ax.add_patch(FancyArrowPatch((5, y0), (5, y1), arrowstyle="-|>",
|
||||
mutation_scale=13, color=C["grey"],
|
||||
linewidth=1.3, zorder=1))
|
||||
# 反馈支路
|
||||
ax.add_patch(FancyArrowPatch((0.7, 1.2), (0.7, 7.6), arrowstyle="-|>",
|
||||
mutation_scale=12, color=C["verm"],
|
||||
linewidth=1.2, linestyle="--",
|
||||
connectionstyle="arc3,rad=0.35", zorder=1))
|
||||
ax.text(0.06, 4.4, "模型参数回标定", rotation=90, va="center",
|
||||
fontsize=8.6, color=C["verm"])
|
||||
ax.text(5, 0.25, "注:全流程为数值模拟,无实测环节", ha="center",
|
||||
fontsize=8.4, color=C["grey"], style="italic")
|
||||
fig.tight_layout()
|
||||
save(fig, "fig1-1_技术路线")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 3-2 三种单胞拓扑示意 + 相对密度-几何关系
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_unitcells():
|
||||
# 单胞示意图用 axis("off"),与 tight_layout 不兼容,故手工排布
|
||||
fig = plt.figure(figsize=(7.4, 2.9))
|
||||
gs = fig.add_gridspec(1, 3, left=0.02, right=0.98, top=0.84, bottom=0.02,
|
||||
wspace=0.10)
|
||||
|
||||
# 单胞二维投影示意
|
||||
for k, topo in enumerate(ORDER):
|
||||
ax = fig.add_subplot(gs[0, k])
|
||||
s = 1.0
|
||||
nodes = {"corner": [(0, 0), (s, 0), (s, s), (0, s)]}
|
||||
if topo == "BCC":
|
||||
nodes["center"] = [(0.5, 0.5)]
|
||||
edges = [((0, 0), (0.5, 0.5)), ((s, 0), (0.5, 0.5)),
|
||||
((s, s), (0.5, 0.5)), ((0, s), (0.5, 0.5)),
|
||||
((0, 0), (s, 0)), ((s, 0), (s, s)),
|
||||
((s, s), (0, s)), ((0, s), (0, 0))]
|
||||
elif topo == "FCC":
|
||||
nodes["face"] = [(0.5, 0), (1, 0.5), (0.5, 1), (0, 0.5)]
|
||||
edges = [((0, 0), (0.5, 0.5)), ((s, 0), (0.5, 0.5)),
|
||||
((s, s), (0.5, 0.5)), ((0, s), (0.5, 0.5))]
|
||||
edges += [((0, 0), (0.5, 0)), ((0.5, 0), (1, 0)),
|
||||
((1, 0), (1, 0.5)), ((1, 0.5), (1, 1)),
|
||||
((1, 1), (0.5, 1)), ((0.5, 1), (0, 1)),
|
||||
((0, 1), (0, 0.5)), ((0, 0.5), (0, 0))]
|
||||
else: # OCT
|
||||
nodes["face"] = [(0.5, 0), (1, 0.5), (0.5, 1), (0, 0.5)]
|
||||
edges = [((0, 0), (0.5, 0.5)), ((s, 0), (0.5, 0.5)),
|
||||
((s, s), (0.5, 0.5)), ((0, s), (0.5, 0.5)),
|
||||
((0, 0), (0.5, 0)), ((0.5, 0), (1, 0)),
|
||||
((1, 0), (1, 0.5)), ((1, 0.5), (1, 1)),
|
||||
((1, 1), (0.5, 1)), ((0.5, 1), (0, 1)),
|
||||
((0, 1), (0, 0.5)), ((0, 0.5), (0, 0)),
|
||||
((0, 0), (1, 1)), ((1, 0), (0, 1))]
|
||||
for (a, b) in edges:
|
||||
ax.plot([a[0], b[0]], [a[1], b[1]], color=TOPO_C[topo],
|
||||
lw=2.1, solid_capstyle="round", zorder=2)
|
||||
for pts in nodes.values():
|
||||
for (px, py) in pts:
|
||||
ax.add_patch(Circle((px, py), 0.042, color=TOPO_C[topo], zorder=3))
|
||||
ax.set_xlim(-0.12, 1.12); ax.set_ylim(-0.12, 1.12)
|
||||
ax.set_aspect("equal"); ax.axis("off")
|
||||
ax.set_title(f"({'abc'[k]}) {TOPO_CN[topo]}", fontsize=10)
|
||||
|
||||
save(fig, "fig2-1_单胞拓扑示意")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-1 应力-应变曲线族
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_curves(curves: pd.DataFrame):
|
||||
fig, axes = plt.subplots(1, 2, figsize=(7.6, 3.2))
|
||||
|
||||
# (a) 三拓扑对比(rd=0.20)
|
||||
ax = axes[0]
|
||||
sub = curves[(curves.group == "baseline") & (curves.rel_density == 0.20)]
|
||||
for topo in ORDER:
|
||||
g = sub[sub.topo == topo].sort_values("strain")
|
||||
ax.plot(g.strain, g.stress, color=TOPO_C[topo], label=TOPO_CN[topo])
|
||||
ax.set_xlabel("应变 ε"); ax.set_ylabel("应力 σ / MPa")
|
||||
ax.set_title("(a) 三种拓扑的压缩响应($\\bar{\\rho}$=0.20)", fontsize=10)
|
||||
ax.legend(loc="upper left"); ax.grid(alpha=0.25, lw=0.6)
|
||||
ax.set_xlim(0, 0.6)
|
||||
|
||||
# (b) 相对密度影响(FCC)
|
||||
ax = axes[1]
|
||||
sub = curves[(curves.group == "baseline") & (curves.topo == "FCC")]
|
||||
cmap = plt.get_cmap("viridis")
|
||||
rds = sorted(sub.rel_density.unique())
|
||||
for i, rd in enumerate(rds):
|
||||
g = sub[sub.rel_density == rd].sort_values("strain")
|
||||
ax.plot(g.strain, g.stress, color=cmap(i / max(len(rds) - 1, 1)),
|
||||
label=f"$\\bar{{\\rho}}$={rd:.2f}")
|
||||
ax.set_xlabel("应变 ε"); ax.set_ylabel("应力 σ / MPa")
|
||||
ax.set_title("(b) 相对密度的影响(FCC)", fontsize=10)
|
||||
ax.legend(loc="upper left", ncol=2); ax.grid(alpha=0.25, lw=0.6)
|
||||
ax.set_xlim(0, 0.6)
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-1_应力应变曲线")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-2 Gibson-Ashby 幂律标定
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_gibson(val: pd.DataFrame, ga: pd.DataFrame):
|
||||
fig, axes = plt.subplots(1, 2, figsize=(7.6, 3.2))
|
||||
|
||||
for ax, ycol, ylab, ttl in [
|
||||
(axes[0], "E_meas", "$E^*/E_s$", "(a) 等效模度的幂律关系"),
|
||||
(axes[1], "sigma_peak", "$\\sigma^*/\\sigma_{ys}$", "(b) 等效强度的幂律关系"),
|
||||
]:
|
||||
for topo in ORDER:
|
||||
g = val[val.topo == topo].sort_values("rel_density")
|
||||
y_over = (g[ycol] / (3500.0 if ycol == "E_meas" else 60.0)).to_numpy()
|
||||
fit = ga[ga.topo == topo].iloc[0]
|
||||
Cv = fit["C"] if ycol == "E_meas" else fit["C_sigma"]
|
||||
nv = fit["n"] if ycol == "E_meas" else fit["n_sigma"]
|
||||
x = g.rel_density.to_numpy()
|
||||
ax.loglog(x, y_over, "o", color=TOPO_C[topo], ms=5,
|
||||
label=f"{topo}(数据)")
|
||||
xs = np.linspace(x.min(), x.max(), 50)
|
||||
ax.loglog(xs, Cv * xs ** nv, "-", color=TOPO_C[topo], lw=1.5,
|
||||
label=f"{topo}: n={nv:.2f}, $R^2$={fit['r_squared']:.3f}")
|
||||
ax.set_xlabel("相对密度 $\\bar{\\rho}$"); ax.set_ylabel(ylab)
|
||||
ax.set_title(ttl, fontsize=10)
|
||||
ax.grid(alpha=0.25, which="both", lw=0.6)
|
||||
ax.legend(fontsize=7.4, loc="lower right")
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-2_幂律标定")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-3 层厚与打印角度的影响
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_process(design: pd.DataFrame, curves: pd.DataFrame):
|
||||
# 极坐标轴与 tight_layout 不兼容,故此处用 subplots_adjust 手工排布
|
||||
fig = plt.figure(figsize=(8.6, 2.9))
|
||||
gs = fig.add_gridspec(1, 3, left=0.065, right=0.985, top=0.86,
|
||||
bottom=0.17, wspace=0.34)
|
||||
|
||||
# (a) 层厚对模量/强度
|
||||
ax = fig.add_subplot(gs[0, 0])
|
||||
g = design[design.group == "layer_sweep"].sort_values("layer_h")
|
||||
e0 = g.E_meas.iloc[0]; s0 = g.sigma_peak.iloc[0]
|
||||
ax.plot(g.layer_h, 100 * g.E_meas / e0, "o-", color=C["blue"], label="等效模量 $E^*$")
|
||||
ax.plot(g.layer_h, 100 * g.sigma_peak / s0, "s-", color=C["verm"], label="峰值应力 $\\sigma_{max}$")
|
||||
ax.set_xlabel("层厚 $t$ / mm"); ax.set_ylabel("相对 0.10 mm 的保留率 / %")
|
||||
ax.set_title("(a) 层厚的影响", fontsize=10)
|
||||
ax.legend(); ax.grid(alpha=0.25, lw=0.6)
|
||||
|
||||
# (b) 打印角度各向异性(极坐标)
|
||||
ax = fig.add_subplot(gs[0, 1], projection="polar")
|
||||
g = design[design.group == "raster_sweep"].sort_values("raster")
|
||||
th = np.deg2rad(g.raster.to_numpy())
|
||||
th_c = np.concatenate([th, th[:1]])
|
||||
for col, lab, c in [("E_meas", "等效模量", C["blue"]),
|
||||
("sigma_peak", "峰值应力", C["verm"])]:
|
||||
v = g[col].to_numpy(); v = v / v[0]
|
||||
ax.plot(th_c, np.concatenate([v, v[:1]]), "-", color=c, label=lab)
|
||||
ax.plot(th, v, "o", color=c, ms=3.5)
|
||||
ax.set_theta_zero_location("N"); ax.set_theta_direction(-1)
|
||||
ax.set_title("(b) 打印角度的各向异性", fontsize=10, pad=12)
|
||||
ax.legend(loc="lower left", bbox_to_anchor=(-0.25, -0.18), fontsize=8)
|
||||
|
||||
# (c) 角度对曲线形状的影响
|
||||
ax = fig.add_subplot(gs[0, 2])
|
||||
# 用设计矩阵展示角度对应峰值应力
|
||||
g = design[design.group == "raster_sweep"].sort_values("raster")
|
||||
ax.bar(g.raster.astype(str), g.sigma_peak, color=C["green"], width=0.62,
|
||||
edgecolor="white")
|
||||
ax.set_xlabel("打印角度 / °"); ax.set_ylabel("峰值应力 / MPa")
|
||||
ax.set_title("(c) 峰值应力的角度依存", fontsize=10)
|
||||
ax.grid(alpha=0.25, axis="y", lw=0.6)
|
||||
|
||||
save(fig, "fig4-4_工艺参数影响")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-4 方差贡献与主效应
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_anova(anova: pd.DataFrame, design: pd.DataFrame):
|
||||
fig, axes = plt.subplots(1, 2, figsize=(7.8, 3.1))
|
||||
|
||||
fac_cn = {"topo_code": "拓扑", "rd_code": "相对密度",
|
||||
"t_code": "层厚", "a_code": "打印角度", "interaction": "交互(含三阶)"}
|
||||
resp_cn = {"E_meas": "等效模量", "sigma_peak": "峰值应力", "SEA": "比吸能"}
|
||||
|
||||
# (a) 堆叠贡献率
|
||||
ax = axes[0]
|
||||
resps = ["E_meas", "sigma_peak", "SEA"]
|
||||
facs = ["topo_code", "rd_code", "t_code", "a_code", "interaction"]
|
||||
colors = [C["blue"], C["orange"], C["green"], C["pink"], "#CCCCCC"]
|
||||
bottom = np.zeros(len(resps))
|
||||
for fac, col in zip(facs, colors):
|
||||
vals = []
|
||||
for r in resps:
|
||||
row = anova[(anova.response == r) & (anova.factor == fac)]
|
||||
vals.append(float(row.contribution.iloc[0]) * 100 if len(row) else 0.0)
|
||||
vals = np.array(vals)
|
||||
ax.bar([resp_cn[r] for r in resps], vals, bottom=bottom,
|
||||
color=col, label=fac_cn[fac], width=0.55, edgecolor="white", lw=0.8)
|
||||
bottom += vals
|
||||
ax.set_ylabel("平方和贡献率 / %"); ax.set_ylim(0, 100)
|
||||
ax.set_title("(a) 各因子对方差的贡献", fontsize=10)
|
||||
ax.legend(ncol=3, fontsize=7.6, loc="upper center", bbox_to_anchor=(0.5, -0.16))
|
||||
ax.grid(alpha=0.2, axis="y", lw=0.6)
|
||||
|
||||
# (b) 主效应图:相对密度
|
||||
ax = axes[1]
|
||||
full = design[design.group == "full_factorial"]
|
||||
for topo in ORDER:
|
||||
g = full[full.topo == topo].groupby("rel_density")["sigma_peak"].mean()
|
||||
ax.plot(g.index, g.values, "o-", color=TOPO_C[topo], label=TOPO_CN[topo])
|
||||
ax.set_xlabel("相对密度 $\\bar{\\rho}$"); ax.set_ylabel("平均峰值应力 / MPa")
|
||||
ax.set_title("(b) 相对密度主效应", fontsize=10)
|
||||
ax.legend(fontsize=8); ax.grid(alpha=0.25, lw=0.6)
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-5_方差贡献与主效应")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-5 响应面
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_rsm(design: pd.DataFrame):
|
||||
full = design[design.group == "full_factorial"].copy()
|
||||
full["rho_app"] = full.rel_density * 1240.0
|
||||
full["specific_strength"] = full.sigma_peak * 1e3 / full.rho_app
|
||||
full["specific_energy"] = full.SEA
|
||||
|
||||
fig, axes = plt.subplots(1, 3, figsize=(9.0, 2.9))
|
||||
|
||||
# (a)(b) 等值线:相对密度 × 层厚 / 打印角度
|
||||
for ax, xcol, ycol, xlab, ylab, ttl in [
|
||||
(axes[0], "rel_density", "layer_h", "相对密度 $\\bar{\\rho}$", "层厚 $t$ / mm",
|
||||
"(a) 比强度:$\\bar{\\rho}$ × $t$"),
|
||||
(axes[1], "rel_density", "raster", "相对密度 $\\bar{\\rho}$", "打印角度 / °",
|
||||
"(b) 比强度:$\\bar{\\rho}$ × 角度"),
|
||||
]:
|
||||
piv = full.pivot_table(index=ycol, columns=xcol, values="specific_strength",
|
||||
aggfunc="mean")
|
||||
X, Y = np.meshgrid(piv.columns.to_numpy(dtype=float),
|
||||
piv.index.to_numpy(dtype=float))
|
||||
cs = ax.contourf(X, Y, piv.to_numpy(dtype=float), levels=12, cmap="viridis")
|
||||
cl = ax.contour(X, Y, piv.to_numpy(dtype=float), levels=6,
|
||||
colors="white", linewidths=0.6, alpha=0.7)
|
||||
ax.clabel(cl, inline=True, fontsize=6.4, fmt=lambda v: f"{v:.1f}")
|
||||
cb = fig.colorbar(cs, ax=ax, pad=0.02)
|
||||
cb.set_label("比强度 / (kN·m/kg)", fontsize=8)
|
||||
cb.ax.tick_params(labelsize=7.5)
|
||||
ax.set_xlabel(xlab); ax.set_ylabel(ylab)
|
||||
ax.set_title(ttl, fontsize=10)
|
||||
|
||||
# (c) 比吸能柱状
|
||||
ax = axes[2]
|
||||
g = full.groupby("topo")["specific_energy"].agg(["mean", "std"]).reindex(ORDER)
|
||||
ax.bar([TOPO_CN[t].split()[0] for t in ORDER], g["mean"], yerr=g["std"],
|
||||
color=[TOPO_C[t] for t in ORDER], capsize=4, width=0.55,
|
||||
edgecolor="white", lw=0.8)
|
||||
ax.set_ylabel("比吸能 SEA / (J/g)")
|
||||
ax.set_title("(c) 三种拓扑的比吸能对比", fontsize=10)
|
||||
ax.grid(alpha=0.25, axis="y", lw=0.6)
|
||||
ax.text(0.5, 0.06, "误差棒为标准差", transform=ax.transAxes,
|
||||
fontsize=7.4, color=C["grey"], ha="center")
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-7_响应面与比吸能")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 4-6 模型校验
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_validation(val: pd.DataFrame, noise: float = 0.015):
|
||||
fig, axes = plt.subplots(1, 2, figsize=(7.6, 3.1))
|
||||
|
||||
# (a) 理论 vs 曲线反算
|
||||
ax = axes[0]
|
||||
for topo in ORDER:
|
||||
g = val[val.topo == topo]
|
||||
ax.plot(g.E_theory, g.E_meas, "o", color=TOPO_C[topo], ms=6,
|
||||
label=TOPO_CN[topo])
|
||||
lo = min(val.E_theory.min(), val.E_meas.min()) * 0.85
|
||||
hi = max(val.E_theory.max(), val.E_meas.max()) * 1.15
|
||||
ax.plot([lo, hi], [lo, hi], "--", color=C["grey"], lw=1.1, label="1:1 参考线")
|
||||
ax.fill_between([lo, hi], [lo * (1 - 3 * noise), hi * (1 - 3 * noise)],
|
||||
[lo * (1 + 3 * noise), hi * (1 + 3 * noise)],
|
||||
color=C["grey"], alpha=0.13, label="±3σ 带(σ=1.5%)")
|
||||
ax.set_xlabel("模型理论值 $E^*$ / MPa"); ax.set_ylabel("曲线反算值 $E_{meas}$ / MPa")
|
||||
ax.set_title("(a) 反算值与理论值一致性", fontsize=10)
|
||||
ax.legend(fontsize=7.4); ax.grid(alpha=0.25, lw=0.6)
|
||||
|
||||
# (b) 与文献量级区间对标
|
||||
ax = axes[1]
|
||||
val2 = val.copy()
|
||||
val2["rho_app"] = val2.rel_density * 1240.0
|
||||
val2["sm"] = val2.E_meas * 1e3 / val2.rho_app
|
||||
ax.axhspan(40, 420, color=C["green"], alpha=0.13, label="文献量级区间")
|
||||
for topo in ORDER:
|
||||
g = val2[val2.topo == topo].sort_values("rel_density")
|
||||
ax.semilogy(g.rel_density, g.sm, "o-", color=TOPO_C[topo], ms=5,
|
||||
label=TOPO_CN[topo])
|
||||
ax.set_xlabel("相对密度 $\\bar{\\rho}$"); ax.set_ylabel("比模量 / (kN·m/kg)")
|
||||
ax.set_title("(b) 比模量与文献量级对标", fontsize=10)
|
||||
ax.legend(fontsize=7.4, loc="lower right"); ax.grid(alpha=0.25, which="both", lw=0.6)
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-9_模型校验")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 5-1 敏感性排序(标准化回归系数)
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_sensitivity(rsm: pd.DataFrame):
|
||||
fig, ax = plt.subplots(figsize=(6.4, 3.2))
|
||||
d = rsm[rsm.term != "常数项"].copy()
|
||||
cn = {"rho_bar": "相对密度", "layer_h": "层厚", "raster": "打印角度",
|
||||
"rho_bar*layer_h": "相对密度×层厚", "rho_bar*raster": "相对密度×角度",
|
||||
"layer_h*raster": "层厚×角度", "rho_bar^2": "相对密度$^2$",
|
||||
"layer_h^2": "层厚$^2$", "raster^2": "打印角度$^2$"}
|
||||
d["label"] = d.term.map(cn)
|
||||
d = d.sort_values("coef")
|
||||
cols = [C["verm"] if p < 0.05 else "#BBBBBB" for p in d.p]
|
||||
ax.barh(d.label, d.coef, color=cols, height=0.62, edgecolor="white", lw=0.7)
|
||||
ax.axvline(0, color="black", lw=0.9)
|
||||
ax.set_xlabel("标准化回归系数")
|
||||
ax.set_title("比强度的响应面标准化系数(红=显著 p<0.05)", fontsize=10)
|
||||
ax.grid(alpha=0.22, axis="x", lw=0.6)
|
||||
r2 = rsm.r_squared.iloc[0]; ar2 = rsm.adj_r_squared.iloc[0]
|
||||
ax.text(0.98, 0.04, f"$R^2$={r2:.3f} 调整$R^2$={ar2:.3f}",
|
||||
transform=ax.transAxes, ha="right", fontsize=8.4, color=C["grey"])
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-6_敏感性排序")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 5-2 限制与适用范围示意
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_limits():
|
||||
fig, ax = plt.subplots(figsize=(6.6, 3.3))
|
||||
ax.set_xlim(0, 10); ax.set_ylim(0, 10); ax.axis("off")
|
||||
ax.text(5, 9.5, "模型适用范围与主要局限", ha="center", fontsize=11.5)
|
||||
|
||||
items = [
|
||||
("适用范围", 8.4, C["green"],
|
||||
"层厚 0.10–0.30 mm · 打印角度 0–90° · 相对密度 0.10–0.35\n"
|
||||
"准静态单轴压缩 · PLA 材料 · 无后处理(退火/浸渗)"),
|
||||
("外推风险", 5.9, C["orange"],
|
||||
"超出上述区间时幂律指数 n 不再稳定,\n"
|
||||
"高相对密度段丝材交叠使有效截面偏离几何估计"),
|
||||
("未纳入的机制", 4.1, C["orange"],
|
||||
"打印缺陷(欠挤出/翘曲) · 层间残余应力\n"
|
||||
"高温/湿热老化 · 多轴与冲击载荷"),
|
||||
("首要局限", 1.7, C["verm"],
|
||||
"全部数据来自文献标定的数值模型,未经实测验证;\n"
|
||||
"因此本文结论限于趋势与相对比较,不代表绝对性能预测"),
|
||||
]
|
||||
for title, y, col, body in items:
|
||||
ax.add_patch(Rectangle((0.5, y - 1.15), 9.0, 2.0, facecolor=col, alpha=0.10,
|
||||
edgecolor=col, lw=1.2))
|
||||
ax.text(0.85, y + 0.42, title, fontsize=10, color=col, va="center")
|
||||
ax.text(0.85, y - 0.38, body, fontsize=8.6, va="center", linespacing=1.55)
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-10_适用范围与局限")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 5-3 参数不确定性下的性能分布与排序稳健性
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_uncertainty():
|
||||
dist = pd.read_csv(DATA / "uncertainty_distribution.csv")
|
||||
consist = pd.read_csv(DATA / "uncertainty_consistency.csv", index_col=0)
|
||||
|
||||
fig, axes = plt.subplots(1, 2, figsize=(7.8, 3.1))
|
||||
|
||||
# (a) 区间条形图
|
||||
ax = axes[0]
|
||||
d = dist.set_index("topo").reindex(ORDER)
|
||||
ypos = np.arange(len(ORDER))[::-1]
|
||||
ax.barh(ypos + 0.17, d.ss_mean, xerr=[d.ss_mean - d.ss_lo, d.ss_hi - d.ss_mean],
|
||||
height=0.30, color=[TOPO_C[t] for t in ORDER], capsize=3,
|
||||
label="比强度")
|
||||
ax.barh(ypos - 0.17, d.sm_mean / 10.0,
|
||||
xerr=[(d.sm_mean - d.sm_lo) / 10.0, (d.sm_hi - d.sm_mean) / 10.0],
|
||||
height=0.30, color=[TOPO_C[t] for t in ORDER], alpha=0.45,
|
||||
capsize=3, label="比模量/10")
|
||||
ax.set_yticks(ypos); ax.set_yticklabels([TOPO_CN[t] for t in ORDER])
|
||||
ax.set_xlabel("性能指标(比强度 kN·m/kg;比模量已除以 10)")
|
||||
ax.set_title("(a) 参数抽样下的性能区间", fontsize=10)
|
||||
ax.legend(fontsize=8, loc="lower right")
|
||||
ax.grid(alpha=0.25, axis="x", lw=0.6)
|
||||
ax.text(0.02, 0.03, "误差棒为 2.5%–97.5% 分位区间", transform=ax.transAxes,
|
||||
fontsize=7.2, color=C["grey"])
|
||||
|
||||
# (b) 排序一致性热图
|
||||
ax = axes[1]
|
||||
M = consist.reindex(index=ORDER, columns=ORDER).to_numpy(dtype=float)
|
||||
im = ax.imshow(M, cmap="Blues", vmin=0, vmax=1)
|
||||
ax.set_xticks(range(3)); ax.set_yticks(range(3))
|
||||
ax.set_xticklabels([TOPO_CN[t].split()[0] for t in ORDER])
|
||||
ax.set_yticklabels([TOPO_CN[t].split()[0] for t in ORDER])
|
||||
for i in range(3):
|
||||
for j in range(3):
|
||||
ax.text(j, i, f"{M[i, j]:.2f}", ha="center", va="center",
|
||||
fontsize=9.5, color="white" if M[i, j] > 0.5 else "black")
|
||||
ax.set_xlabel("列拓扑"); ax.set_ylabel("行拓扑")
|
||||
ax.set_title("(b) 排序一致性 $P$(行优于列)", fontsize=10)
|
||||
cb = fig.colorbar(im, ax=ax, pad=0.03)
|
||||
cb.ax.tick_params(labelsize=7.5)
|
||||
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-8_不确定性区间与排序稳健性")
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 图 5-4 幂律指数置信区间
|
||||
# ----------------------------------------------------------------------------
|
||||
def fig_powerlaw_ci():
|
||||
ci = pd.read_csv(DATA / "powerlaw_ci.csv")
|
||||
ga = pd.read_csv(DATA / "gibson_ashby_fit.csv")
|
||||
|
||||
fig, ax = plt.subplots(figsize=(6.4, 3.0))
|
||||
x = np.arange(len(ORDER))
|
||||
ci = ci.set_index("topo").reindex(ORDER).reset_index()
|
||||
ax.errorbar(x - 0.10, ci.n, yerr=[ci.n - ci.n_lo, ci.n_hi - ci.n],
|
||||
fmt="o", color=C["blue"], capsize=5, ms=7,
|
||||
label="模量幂指数 $n$")
|
||||
ax.errorbar(x + 0.10, ci.n_sigma,
|
||||
yerr=[ci.n_sigma - ci.n_sigma_lo, ci.n_sigma_hi - ci.n_sigma],
|
||||
fmt="s", color=C["verm"], capsize=5, ms=6,
|
||||
label="强度幂指数 $n_\\sigma$")
|
||||
ax.axhline(2.0, ls="--", color=C["grey"], lw=1.1,
|
||||
label="开孔泡沫理论值 $n$=2")
|
||||
ax.axhline(1.5, ls=":", color=C["grey"], lw=1.1,
|
||||
label="强度理论值 $n_\\sigma$=1.5")
|
||||
ax.set_xticks(x); ax.set_xticklabels([TOPO_CN[t] for t in ORDER])
|
||||
ax.set_ylabel("幂律指数"); ax.set_ylim(1.2, 2.2)
|
||||
ax.set_title("幂律指数的 95% 置信区间(误差棒,df=4)", fontsize=10)
|
||||
ax.legend(fontsize=7.8, ncol=2, loc="lower right")
|
||||
ax.grid(alpha=0.25, axis="y", lw=0.6)
|
||||
fig.tight_layout()
|
||||
save(fig, "fig4-3_幂律指数置信区间")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
print(f"中文字体:{CJK}")
|
||||
clean_stale_figures()
|
||||
curves, design, ga, anova, rsm, val = load()
|
||||
print("生成配图 ...")
|
||||
fig_roadmap()
|
||||
fig_unitcells()
|
||||
fig_curves(curves)
|
||||
fig_gibson(val, ga)
|
||||
fig_process(design, curves)
|
||||
fig_anova(anova, design)
|
||||
fig_rsm(design)
|
||||
fig_validation(val)
|
||||
fig_sensitivity(rsm)
|
||||
fig_limits()
|
||||
fig_uncertainty()
|
||||
fig_powerlaw_ci()
|
||||
|
||||
# 图件清单
|
||||
lines = ["# 图件清单与哈希(第 10 步产出)", ""]
|
||||
lines.append("| 文件 | 字节 |")
|
||||
lines.append("|---|---|")
|
||||
import hashlib
|
||||
for name, size in sorted(_manifest):
|
||||
h = hashlib.sha256((FIG / name).read_bytes()).hexdigest()[:16]
|
||||
lines.append(f"| {name} | {size} |")
|
||||
lines.append("")
|
||||
lines.append("每幅图同时提供 PNG(300 dpi,用于 Word/PDF 排版)与 PDF(矢量,用于放大检查)。")
|
||||
(FIG / "FIGLIST.md").write_text("\n".join(lines), encoding="utf-8")
|
||||
print(f"\n完成:{len(_manifest)//2} 幅图,输出到 {FIG}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,315 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""LaTeX 数学式 -> Unicode 文本转换(供 docx 构建使用)。
|
||||
|
||||
学位论文正文需要人眼可读的公式。python-docx 无法排版真正的数学公式
|
||||
(OMML),因此本模块把 md 源中的 LaTeX 片段转换为 Unicode 字符表示,
|
||||
使其在 Word/WPS 中可直接阅读、可复制、可打印。
|
||||
|
||||
处理能力:
|
||||
- 希腊字母与常用算符:\\rho -> ρ,\\times -> ×,\\approx -> ≈ 等
|
||||
- 上标/下标:M^2 -> M²,C_1 -> C₁(无对应 Unicode 时用 ^(...) / _(...))
|
||||
- 常用修饰:\\bar{x} -> x̄,\\tilde{x} -> x̃,\\hat{x} -> x̂
|
||||
- 分数:\\frac{a}{b} -> (a)/(b);\\tfrac 同
|
||||
- 根号:\\sqrt{x} -> √(x)
|
||||
- 函数名与排版命令:\\mathrm/\\text/\\left/\\right/\\displaystyle/\\quad 等直接剥离
|
||||
- 行间公式的 \\tag{2-1} -> (2-1)
|
||||
|
||||
不支持任意嵌套的复杂公式(如多重分式嵌套、矩阵)。若遇到无法处理的结构,
|
||||
保留其原文并在控制台打印警告,由人工核对——不静默产生错误公式。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
GREEK = {
|
||||
"alpha": "α", "beta": "β", "gamma": "γ", "Gamma": "Γ", "delta": "δ",
|
||||
"Delta": "Δ", "epsilon": "ε", "varepsilon": "ε", "zeta": "ζ", "eta": "η",
|
||||
"theta": "θ", "Theta": "Θ", "iota": "ι", "kappa": "κ", "lambda": "λ",
|
||||
"Lambda": "Λ", "mu": "μ", "nu": "ν", "xi": "ξ", "Xi": "Ξ", "pi": "π",
|
||||
"Pi": "Π", "rho": "ρ", "sigma": "σ", "Sigma": "Σ", "tau": "τ",
|
||||
"upsilon": "υ", "phi": "φ", "varphi": "φ", "chi": "χ", "psi": "ψ",
|
||||
"Psi": "Ψ", "omega": "ω", "Omega": "Ω",
|
||||
}
|
||||
|
||||
OPS = {
|
||||
"times": "×", "cdot": "·", "pm": "±", "mp": "∓", "approx": "≈",
|
||||
"neq": "≠", "leq": "≤", "le": "≤", "geq": "≥", "ge": "≥",
|
||||
"ll": "≪", "gg": "≫", "sim": "~", "simeq": "≃", "equiv": "≡",
|
||||
"propto": "∝", "infty": "∞", "partial": "∂", "nabla": "∇",
|
||||
"rightarrow": "→", "to": "→", "leftarrow": "←", "Rightarrow": "⇒",
|
||||
"in": "∈", "notin": "∉", "subset": "⊂", "cup": "∪", "cap": "∩",
|
||||
"sum": "Σ", "prod": "Π", "int": "∫", "circ": "∘", "ast": "*",
|
||||
"sqrt": "√", "angle": "∠", "perp": "⊥", "parallel": "∥",
|
||||
"quad": " ", "qquad": " ", "enspace": " ", "qquad": " ",
|
||||
",": " ", ";": " ", "!": "", " ": " ",
|
||||
}
|
||||
|
||||
# 直接剥离的排版命令
|
||||
STRIP_CMDS = [
|
||||
"mathrm", "mathbf", "mathit", "mathsf", "mathtt", "text", "textrm",
|
||||
"operatorname", "mathcal", "mathbb", "mathfrak",
|
||||
"left", "right", "big", "Big", "bigg", "Bigg", "displaystyle",
|
||||
"textstyle", "limits", "nolimits", "mathstrut", "phantom",
|
||||
"underbrace", "overbrace", "underset", "overset",
|
||||
]
|
||||
|
||||
FUNCS = ["ln", "log", "exp", "sin", "cos", "tan", "max", "min", "clamp",
|
||||
"arccos", "arcsin", "arctan", "det", "dim"]
|
||||
|
||||
SUP = {"0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵",
|
||||
"6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹", "+": "⁺", "-": "⁻",
|
||||
"=": "⁼", "(": "⁽", ")": "⁾", "n": "ⁿ", "i": "ⁱ", "*": "*",
|
||||
"ε": "ᵋ", "β": "ᵝ", "γ": "ᵞ", "δ": "ᵟ", "φ": "ᵠ", "χ": "ᵡ",
|
||||
"a": "ᵃ", "b": "ᵇ", "c": "ᶜ", "d": "ᵈ", "e": "ᵉ", "f": "ᶠ",
|
||||
"g": "ᵍ", "h": "ʰ", "j": "ʲ", "k": "ᵏ", "l": "ˡ", "m": "ᵐ",
|
||||
"o": "ᵒ", "p": "ᵖ", "r": "ʳ", "s": "ˢ", "t": "ᵗ", "u": "ᵘ",
|
||||
"v": "ᵛ", "w": "ʷ", "x": "ˣ", "y": "ʸ", "z": "ᶻ"}
|
||||
|
||||
SUB = {"0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅",
|
||||
"6": "₆", "7": "₇", "8": "₈", "9": "₉", "+": "₊", "-": "₋",
|
||||
"=": "₌", "(": "₍", ")": "₎", "a": "ₐ", "e": "ₑ", "i": "ᵢ",
|
||||
"o": "ₒ", "r": "ᵣ", "s": "ₛ", "t": "ₜ", "x": "ₓ", "y": "ᵧ",
|
||||
"β": "ᵦ", "γ": "ᵧ", "ρ": "ᵨ", "φ": "ᵩ", "χ": "ᵪ"}
|
||||
|
||||
WARNINGS: list[str] = []
|
||||
|
||||
|
||||
def _script(ch: str, table: dict[str, str]) -> str | None:
|
||||
return table.get(ch)
|
||||
|
||||
|
||||
def _brace_group(s: str, i: int) -> tuple[str, int]:
|
||||
"""从 s[i] == '{' 开始取配对花括号内的内容。返回 (内容, 新位置)。"""
|
||||
if i >= len(s) or s[i] != "{":
|
||||
return "", i
|
||||
depth = 0
|
||||
for j in range(i, len(s)):
|
||||
if s[j] == "{":
|
||||
depth += 1
|
||||
elif s[j] == "}":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
return s[i + 1:j], j + 1
|
||||
return s[i + 1:], len(s)
|
||||
|
||||
|
||||
def _one_token(s: str, i: int) -> tuple[str, int]:
|
||||
"""取一个"原子":{...} 组、单个字符,或反斜杠命令。"""
|
||||
if i >= len(s):
|
||||
return "", i
|
||||
if s[i] == "{":
|
||||
return _brace_group(s, i)
|
||||
if s[i] == "\\":
|
||||
m = re.match(r"\\([a-zA-Z]+)", s[i:])
|
||||
if m:
|
||||
return "\\" + m.group(1), i + m.end()
|
||||
return s[i:i + 2], i + 2
|
||||
return s[i], i + 1
|
||||
|
||||
|
||||
def _to_script(content: str, table: dict[str, str], marker: str) -> str:
|
||||
"""把内容转成 Unicode 上下标。
|
||||
|
||||
优先整体转换;含无法映射的字符时,尝试"最内层可映射子串"策略:
|
||||
例如上标内容 "ε_D" 无法整体映射,但去掉 "_D" 后的 "ε" 也不可映射,
|
||||
此时退化为 marker(内容)。对下标内容 "bond",因字母 b/n/d 无下标
|
||||
字形,退化为 _(bond)。
|
||||
"""
|
||||
out = []
|
||||
content = content.strip()
|
||||
# _one_token 在解析 "^" / "_" 后可能返回带花括号的组(如 "{\mathrm{bond}}")
|
||||
# 或未配对的 "{bond}",这里统一剥掉最外层花括号,否则后续的
|
||||
# "纯字母" 判断会因存在 {} 而失败,退化成 _(bond) 形式。
|
||||
while len(content) >= 2 and content.startswith("{") and content.endswith("}"):
|
||||
content = content[1:-1].strip()
|
||||
# 仅当内容里确实还有未处理的 LaTeX 命令(反斜杠)时才递归展开,
|
||||
# 否则会把已解析的 "_σ" 再次映射成下标而导致信息丢失。
|
||||
if "\\" in content:
|
||||
content = latex_to_unicode(content)
|
||||
content = re.sub(r"\\[a-zA-Z]+", "", content)
|
||||
content = content.strip()
|
||||
if not content:
|
||||
return ""
|
||||
for ch in content:
|
||||
rep = _script(ch, table)
|
||||
if rep is None:
|
||||
# 尝试把内容里的 "^..." 或 "_..." 剥掉后重试(处理 ^{ n} 这类)
|
||||
cleaned = re.sub(r"[\^_]\s*\(?[^)]*\)?", "", content).strip()
|
||||
if cleaned and cleaned != content:
|
||||
return _to_script(cleaned, table, marker)
|
||||
# 纯字母或单个希腊字母内容:用 marker + 内容(如 _(bond) -> _bond、
|
||||
# _σ -> _σ)。Unicode 没有 σ/ε 的下标字形,加括号反而更差,故不加。
|
||||
if re.fullmatch(r"[a-zA-Z]+|[\u0370-\u03ff]", content):
|
||||
rep2 = table.get(content) or table.get(GREEK.get(content, ""))
|
||||
if rep2 is not None:
|
||||
return rep2
|
||||
return f"{marker}{content}"
|
||||
return f"{marker}({content})"
|
||||
out.append(rep)
|
||||
return "".join(out)
|
||||
|
||||
|
||||
def _simplify_frac(s: str) -> str:
|
||||
"""把 (a)/(b) 化简为 a/b —— 仅当 a、b 不含低优先运算符时。"""
|
||||
for _ in range(6):
|
||||
m = re.search(r"\(([^()]*)\)/\(([^()]*)\)", s)
|
||||
if not m:
|
||||
break
|
||||
a, b = m.group(1).strip(), m.group(2).strip()
|
||||
if any(op in a for op in "+- ") or any(op in b for op in "+- "):
|
||||
break
|
||||
s = s[:m.start()] + f"{a}/{b}" + s[m.end():]
|
||||
return s
|
||||
|
||||
|
||||
def latex_to_unicode(expr: str) -> str:
|
||||
"""把一段 LaTeX 数学式转换为 Unicode 文本。"""
|
||||
s = expr.strip()
|
||||
# 0a) 定积分上下限:先把 \int_a^b 展开成可读形式,避免上下标互相覆盖。
|
||||
# 例如 "\int_0^{\varepsilon_D}" -> "(从 0 到 ε_D 的积分)"
|
||||
def _int_limit(m):
|
||||
lo = m.group(1).strip()
|
||||
hi = m.group(2).strip()
|
||||
lo_t = latex_to_unicode(lo) if "\\" in lo else lo
|
||||
hi_t = latex_to_unicode(hi) if "\\" in hi else hi
|
||||
return f"(从 {lo_t} 到 {hi_t} 积分) "
|
||||
s = re.sub(r"\\int\s*_(\{[^}]*\}|[0-9a-zA-Z])\s*\^\s*(\{[^}]*\}|[0-9a-zA-Z])",
|
||||
_int_limit, s)
|
||||
|
||||
# 0b) 清除间距类命令(\, \; \! 等)——必须在上下标解析之前做,
|
||||
# 否则 "^{\,n}" 的内容会变成 "\,n",无法映射为上标。
|
||||
s = re.sub(r"\\[,;!>]", "", s)
|
||||
s = re.sub(r"\\(?:quad|qquad|enspace|thinspace|medspace|thickspace)\b", " ", s)
|
||||
|
||||
# 1) 处理 \frac{a}{b} / \tfrac / \dfrac(可能嵌套,循环到不动点)
|
||||
for _ in range(6):
|
||||
m = re.search(r"\\(?:dfrac|tfrac|frac)\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
start = m.start()
|
||||
a, p = _brace_group(s, s.index("{", m.start()))
|
||||
# 跳过空白后取第二个组
|
||||
while p < len(s) and s[p].isspace():
|
||||
p += 1
|
||||
if p >= len(s) or s[p] != "{":
|
||||
break
|
||||
b, p2 = _brace_group(s, p)
|
||||
s = s[:start] + f"({a})/({b})" + s[p2:]
|
||||
|
||||
# 2) 处理 \sqrt{x} -> √(x)
|
||||
for _ in range(4):
|
||||
m = re.search(r"\\sqrt\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
c, p = _brace_group(s, s.index("{", m.start()))
|
||||
s = s[:m.start()] + f"√({c})" + s[p:]
|
||||
|
||||
# 3) 剥离排版命令(保留其内容)
|
||||
for cmd in STRIP_CMDS:
|
||||
s = re.sub(r"\\" + cmd + r"\s*", "", s)
|
||||
s = re.sub(r"\\begin\{[^}]*\}|\\end\{[^}]*\}", "", s)
|
||||
|
||||
# 4) 修饰符:\bar{x} \tilde{x} \hat{x} \dot{x} \vec{x}
|
||||
marks = {"bar": "\u0304", "tilde": "\u0303", "hat": "\u0302",
|
||||
"dot": "\u0307", "vec": "\u20d7", "overline": "\u0305"}
|
||||
for _ in range(6):
|
||||
m = re.search(r"\\(bar|tilde|hat|dot|vec|overline)\s*\{", s)
|
||||
if not m:
|
||||
break
|
||||
c, p = _brace_group(s, s.index("{", m.start()))
|
||||
comb = marks[m.group(1)]
|
||||
s = s[:m.start()] + c + comb + s[p:]
|
||||
|
||||
# 5) 上下标
|
||||
out = []
|
||||
i = 0
|
||||
while i < len(s):
|
||||
ch = s[i]
|
||||
if ch in "^_":
|
||||
table = SUP if ch == "^" else SUB
|
||||
marker = "^" if ch == "^" else "_"
|
||||
nxt, i2 = _one_token(s, i + 1)
|
||||
if nxt.startswith("\\") and nxt[1:] in GREEK:
|
||||
nxt = GREEK[nxt[1:]]
|
||||
elif len(nxt) == 1 and nxt.isalpha() and nxt not in table:
|
||||
out.append(marker + nxt)
|
||||
i = i2
|
||||
continue
|
||||
out.append(_to_script(nxt, table, marker))
|
||||
i = i2
|
||||
continue
|
||||
out.append(ch)
|
||||
i += 1
|
||||
s = "".join(out)
|
||||
|
||||
# 6) 希腊字母
|
||||
for name, sym in GREEK.items():
|
||||
s = re.sub(r"\\" + name + r"(?![a-zA-Z])", sym, s)
|
||||
|
||||
# 7) 函数名:\ln -> ln,\max -> max
|
||||
for fn in FUNCS:
|
||||
s = re.sub(r"\\" + fn + r"\b", fn, s)
|
||||
|
||||
# 8) 算符与符号
|
||||
for name in sorted(OPS, key=len, reverse=True):
|
||||
s = re.sub(r"\\" + re.escape(name) + r"(?![a-zA-Z])", OPS[name], s)
|
||||
|
||||
# 9) 剩余未知命令:保留原名并告警
|
||||
for m in re.finditer(r"\\[a-zA-Z]+", s):
|
||||
if m.group(0) not in ("\\",):
|
||||
WARNINGS.append(m.group(0))
|
||||
s = re.sub(r"\\,|\\;|\\!|\\ ", " ", s)
|
||||
|
||||
# 10) 清理多余花括号与空白
|
||||
s = s.replace("{", "").replace("}", "")
|
||||
s = _simplify_frac(s)
|
||||
s = re.sub(r"[ \t]{2,}", " ", s).strip()
|
||||
return s
|
||||
|
||||
|
||||
_TAG = re.compile(r"\\tag\{([^}]*)\}")
|
||||
|
||||
|
||||
def convert_display(block: str) -> str:
|
||||
"""转换行间公式:\\tag{2-1} -> (2-1),其余转 Unicode。"""
|
||||
tags = _TAG.findall(block)
|
||||
body = _TAG.sub("", block)
|
||||
conv = latex_to_unicode(body)
|
||||
if tags:
|
||||
return f"{conv} ({tags[0].strip()})"
|
||||
return conv
|
||||
|
||||
|
||||
INLINE = re.compile(r"(?<!\$)\$([^$\n]+)\$(?!\$)")
|
||||
DISPLAY = re.compile(r"\$\$(.+?)\$\$", re.S)
|
||||
|
||||
|
||||
def convert_text(text: str) -> str:
|
||||
"""对整篇文本做公式转换(先处理 $$...$$,再处理 $...$)。"""
|
||||
text = DISPLAY.sub(lambda m: "\n" + convert_display(m.group(1)) + "\n", text)
|
||||
text = INLINE.sub(lambda m: latex_to_unicode(m.group(1)), text)
|
||||
return text
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
samples = [
|
||||
r"\bar{\rho} = \frac{\rho^*}{\rho_s} = \eta \, \left(\frac{d}{a}\right)^{2}",
|
||||
r"\frac{E^*}{E_s} = C_1 \, \bar{\rho}^{\,n}",
|
||||
r"\mathrm{SEA} = \frac{\displaystyle\int_0^{\varepsilon_D} \sigma \, \mathrm{d}\varepsilon}{\bar{\rho}\,\rho_s}",
|
||||
r"n \approx 2",
|
||||
r"30 \times 30 \times 30",
|
||||
r"f_{\mathrm{bond}}(t) = 1 - \kappa \, \frac{t - t_{\mathrm{ref}}}{t_{\mathrm{ref}}}",
|
||||
]
|
||||
for s in samples:
|
||||
print("IN :", s)
|
||||
print("OUT:", latex_to_unicode(s))
|
||||
print()
|
||||
if WARNINGS:
|
||||
print("未处理的命令:", sorted(set(WARNINGS)))
|
||||
@@ -0,0 +1,121 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""把 04_选题与空白识别/TOPIC.md 附录 A 的已核实文献并入 06_文献筛选分类/SELECTION.csv。
|
||||
|
||||
背景:选题阶段(第 04 步)与检索阶段(第 02/06 步)由不同环节完成,
|
||||
选题文档附录 A 中的 13 条文献(DOI 均经 Crossref 核实)未进入检索清单。
|
||||
若不并入,正文里对 Gonabadi、Utzeri、Maskery 等文献的引用将悬空。
|
||||
本脚本做一次幂等的合并:已存在的 DOI 跳过,不重复添加。
|
||||
|
||||
用法:
|
||||
python code/merge_topic_refs.py # 预览
|
||||
python code/merge_topic_refs.py --apply # 实际写入
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
for _s in (sys.stdout, sys.stderr):
|
||||
try:
|
||||
_s.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
SEL = ROOT / "06_文献筛选分类" / "SELECTION.csv"
|
||||
TOPIC = ROOT / "04_选题与空白识别" / "TOPIC.md"
|
||||
|
||||
# 从 TOPIC.md 附录 A 表格中逐行解析:| # | 作者(年份) | 题名 | 期刊 | 卷/页 | DOI | 核实状态 |
|
||||
ROW = re.compile(r"^\|\s*(\d+)\s*\|(.+?)\|(.+?)\|(.+?)\|(.+?)\|(.+?)\|(.+?)\|\s*$")
|
||||
DOI = re.compile(r"(10\.\d{4,9}/[^\s|]+)")
|
||||
|
||||
|
||||
def parse_topic() -> list[dict]:
|
||||
text = TOPIC.read_text(encoding="utf-8")
|
||||
# 只取附录 A 章节内的表格
|
||||
m = re.search(r"## 附录 A(.+?)## 附录 B", text, re.S)
|
||||
if not m:
|
||||
raise SystemExit("未在 TOPIC.md 中找到附录 A 表格")
|
||||
body = m.group(1)
|
||||
out = []
|
||||
for line in body.splitlines():
|
||||
mm = ROW.match(line.strip())
|
||||
if not mm:
|
||||
continue
|
||||
_, author, title, journal, volpage, doi_cell, status = mm.groups()
|
||||
d = DOI.search(doi_cell)
|
||||
if not d:
|
||||
continue
|
||||
author = author.strip()
|
||||
# "Gonabadi H., Chen Y., Yadav A., Bull S. (2021)" -> 作者 + 年份
|
||||
ym = re.search(r"\((\d{4})\)\s*$", author)
|
||||
year = ym.group(1) if ym else ""
|
||||
names = re.sub(r"\(\d{4}\)\s*$", "", author).strip()
|
||||
out.append(dict(
|
||||
author=re.sub(r"\s*,\s*", "; ", names).rstrip(";. "),
|
||||
year=year,
|
||||
title=title.strip(),
|
||||
journal=journal.strip(),
|
||||
volpage=volpage.strip(),
|
||||
doi=d.group(1).strip(),
|
||||
status=status.strip(),
|
||||
))
|
||||
return out
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--apply", action="store_true", help="实际写入 CSV")
|
||||
args = ap.parse_args()
|
||||
|
||||
df = pd.read_csv(SEL, encoding="utf-8-sig")
|
||||
have = set(df["DOI"].astype(str).str.strip().str.lower())
|
||||
|
||||
topic = parse_topic()
|
||||
print(f"TOPIC.md 附录 A 解析到 {len(topic)} 条")
|
||||
new_rows = []
|
||||
for r in topic:
|
||||
if r["doi"].lower() in have:
|
||||
print(f" 已存在,跳过: {r['doi']}")
|
||||
continue
|
||||
new_rows.append(r)
|
||||
print(f" 新增: {r['year']} {r['author'][:36]} | {r['title'][:52]} | {r['doi']}")
|
||||
|
||||
if not new_rows:
|
||||
print("无需合并。")
|
||||
return 0
|
||||
|
||||
max_id = max(int(str(x).lstrip("L")) for x in df["id"] if str(x).startswith("L"))
|
||||
add = []
|
||||
for i, r in enumerate(new_rows, start=1):
|
||||
add.append({
|
||||
"id": f"T{i:03d}",
|
||||
"作者": r["author"],
|
||||
"年份": int(r["year"]) if r["year"] else "",
|
||||
"标题": r["title"],
|
||||
"期刊": r["journal"],
|
||||
"DOI": r["doi"],
|
||||
"类型": "journal",
|
||||
"主题分类": "点阵结构",
|
||||
"是否核心": "是",
|
||||
"可获取性": "DOI 经 Crossref 核实",
|
||||
"备注": f"选题阶段(第04步)附录A并入;{r['status']};卷页 {r['volpage']}",
|
||||
})
|
||||
if not args.apply:
|
||||
print(f"\n预览模式:将新增 {len(add)} 行(未写入)。加 --apply 实际写入。")
|
||||
return 0
|
||||
|
||||
out = pd.concat([df, pd.DataFrame(add)], ignore_index=True)
|
||||
out.to_csv(SEL, index=False, encoding="utf-8-sig")
|
||||
print(f"\n已写入 {SEL},总计 {len(out)} 行(新增 {len(add)} 行)")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出正文引用的全部统计量(用于核对正文数字与数据文件是否一致)。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
D = Path(__file__).resolve().parents[1] / "data"
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ga = pd.read_csv(D / "gibson_ashby_fit.csv")
|
||||
ci = pd.read_csv(D / "powerlaw_ci.csv")
|
||||
rs = pd.read_csv(D / "rsm_coefficients.csv")
|
||||
v = pd.read_csv(D / "validation_vs_lit.csv")
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
a = pd.read_csv(D / "anova_table.csv")
|
||||
ss = pd.read_csv(D / "stress_strain.csv")
|
||||
ur = pd.read_csv(D / "uncertainty_ranking.csv")
|
||||
|
||||
print("== 数据集规模 ==")
|
||||
print(f" 设计点 {len(d)} | 曲线 {ss.groupby(['topo','rel_density']).ngroups}"
|
||||
f" | 每条曲线点数 {sorted(set(ss.groupby(['topo','rel_density']).size()))}"
|
||||
f" | 曲线总行数 {len(ss)}")
|
||||
|
||||
print("\n== 幂律拟合 ==")
|
||||
for _, r in ga.iterrows():
|
||||
print(f" {r['topo']}: C1={r['C']:.4f} n={r['n']:.4f} "
|
||||
f"C2={r['C_sigma']:.4f} n_sigma={r['n_sigma']:.4f} R2={r['r_squared']:.4f}")
|
||||
|
||||
print("\n== 幂指数 95% 置信区间 ==")
|
||||
for _, r in ci.iterrows():
|
||||
print(f" {r['topo']}: n [{r['n_lo']:.4f}, {r['n_hi']:.4f}] "
|
||||
f"n_sigma [{r['n_sigma_lo']:.4f}, {r['n_sigma_hi']:.4f}]")
|
||||
|
||||
print("\n== 方差贡献率 (%) ==")
|
||||
p = a.pivot(index="factor", columns="response", values="contribution") * 100
|
||||
print(p.round(1).to_string())
|
||||
print(" 合计:", (p.sum()).round(1).to_dict())
|
||||
for resp in ["E_meas", "sigma_peak", "SEA"]:
|
||||
col = p[resp]
|
||||
print(f" 最大/最小比({resp}): {col.max()/col.min():.1f}")
|
||||
|
||||
print("\n== 响应面 ==")
|
||||
print(f" R2 = {rs.r_squared.iloc[0]:.4f} | 调整 R2 = {rs.adj_r_squared.iloc[0]:.4f} | n = {int(rs.n.iloc[0])}")
|
||||
for _, r in rs.iterrows():
|
||||
flag = "显著" if r["p"] < 0.05 else "不显著"
|
||||
print(f" {r['term']:16s} coef={r['coef']:+.4f} t={r['t']:+.3f} p={r['p']:.4f} {flag}")
|
||||
|
||||
print("\n== 层厚扫描(保留率 %) ==")
|
||||
g = d[d.group == "layer_sweep"].sort_values("layer_h")
|
||||
print(" t :", g.layer_h.tolist())
|
||||
print(" E :", (100 * g.E_meas / g.E_meas.iloc[0]).round(1).tolist())
|
||||
print(" sigma :", (100 * g.sigma_peak / g.sigma_peak.iloc[0]).round(1).tolist())
|
||||
print(" SEA :", g.SEA.round(3).tolist())
|
||||
|
||||
print("\n== 打印角度扫描(保留率 %) ==")
|
||||
r = d[d.group == "raster_sweep"].sort_values("raster")
|
||||
print(" theta :", r.raster.tolist())
|
||||
print(" E :", (100 * r.E_meas / r.E_meas.iloc[0]).round(1).tolist())
|
||||
print(" sigma :", (100 * r.sigma_peak / r.sigma_peak.iloc[0]).round(1).tolist())
|
||||
print(f" 0->90 降幅: E {100*(1-r.E_meas.iloc[-1]/r.E_meas.iloc[0]):.1f}% "
|
||||
f"sigma {100*(1-r.sigma_peak.iloc[-1]/r.sigma_peak.iloc[0]):.1f}%")
|
||||
|
||||
print("\n== 文献对标 ==")
|
||||
print(f" 比模量 {v.specific_modulus.min():.1f}-{v.specific_modulus.max():.1f} kN·m/kg "
|
||||
f"落入 {int(v.modulus_in_range.sum())}/{len(v)}")
|
||||
print(f" 比强度 {v.specific_strength.min():.1f}-{v.specific_strength.max():.1f} kN·m/kg "
|
||||
f"落入 {int(v.strength_in_range.sum())}/{len(v)}")
|
||||
|
||||
print("\n== 一致性与排序 ==")
|
||||
err = float((d.E_meas / d.E_theory - 1).abs().max())
|
||||
print(f" 曲线反算 E 与理论值最大相对偏差: {err*100:.2f}%")
|
||||
print(f" SEA 范围: {d.SEA.min():.2f} - {d.SEA.max():.2f} J/g")
|
||||
print(" 排序最优概率:",
|
||||
ur.groupby("topology").p_best.first().round(4).to_dict())
|
||||
|
||||
print("\n== 全因子 SEA 按拓扑 ==")
|
||||
f = d[d.group == "full_factorial"]
|
||||
agg = f.groupby("topo").SEA.agg(["mean", "std"])
|
||||
agg["cv"] = agg["std"] / agg["mean"]
|
||||
print(agg.round(4).to_string())
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,512 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
FDM 点阵结构压缩性能 —— 数值模型与数据集生成
|
||||
================================================
|
||||
|
||||
本项目为 simulation-only 研究:本脚本用**文献标定的解析/半解析模型**生成
|
||||
应力-应变响应数据集,用于后续的幂律拟合、参数敏感性分析与响应面建模。
|
||||
|
||||
重要声明(会写进论文正文):
|
||||
本脚本产出的不是实测数据。模型参数取自公开发表的 PLA 与蜂窝/点阵
|
||||
力学文献,属于"文献标定 + 数值外推",因此论文中所有力学性能结论
|
||||
均限定在模型适用范围内,并以文献对标作为交叉验证。
|
||||
|
||||
数据流:
|
||||
code/sim_model.py -> data/stress_strain.csv 单元级应力-应变曲线
|
||||
-> data/design_matrix.csv 每条曲线的性能指标
|
||||
-> data/gibson_ashby_fit.csv 幂律拟合结果
|
||||
-> data/anova_table.csv 方差分析表
|
||||
-> data/rsm_coefficients.csv 响应面回归系数
|
||||
-> data/validation_vs_lit.csv 与文献对标
|
||||
|
||||
用法:
|
||||
python code/sim_model.py # 全量生成
|
||||
python code/sim_model.py --seed 7 # 换随机种子做稳健性复算
|
||||
|
||||
依赖:numpy, pandas, scipy
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import stats
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 路径:脚本自身定位项目根,保证仓库克隆到任何位置都能跑
|
||||
# ----------------------------------------------------------------------------
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / "data"
|
||||
DATA.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 1. 材料常数(PLA,取值来源见 manuscript 表 3-1 与 refs 中的材料文献)
|
||||
# ----------------------------------------------------------------------------
|
||||
PLA = dict(
|
||||
E_s=3500.0, # MPa 实体 PLA 弹性模量(文献区间 3.0-3.6 GPa)
|
||||
sigma_ys=60.0, # MPa 实体 PLA 屈服强度(文献区间 50-70 MPa)
|
||||
rho_s=1240.0, # kg/m3 实体 PLA 密度
|
||||
sigma_plat_ratio=0.30, # 平台应力/屈服强度比(蜂窝类材料经验值)
|
||||
)
|
||||
|
||||
# 单胞拓扑:参数化几何 + 相对密度系数 + 各向同性程度
|
||||
# eta 由胞元几何解析推导(struts 体积分数),数值与文献报道的 FDM 点阵相符
|
||||
TOPOLOGY = {
|
||||
"BCC": dict(eta=0.352, gamma=0.92, C1=0.24, C2=0.29, label="体心立方 BCC"),
|
||||
"FCC": dict(eta=0.500, gamma=0.78, C1=0.30, C2=0.36, label="面心立方 FCC"),
|
||||
"OCT": dict(eta=0.615, gamma=0.66, C1=0.36, C2=0.44, label="八面体 OCT"),
|
||||
}
|
||||
TOPOLOGY_ORDER = ["BCC", "FCC", "OCT"]
|
||||
|
||||
# 工艺参数水平
|
||||
LAYER_H = [0.10, 0.15, 0.20, 0.25, 0.30] # mm 层厚
|
||||
RASTER_A = [0.0, 15.0, 30.0, 45.0, 60.0, 75.0, 90.0] # deg 打印角度
|
||||
REL_DENS = [0.10, 0.15, 0.20, 0.25, 0.30, 0.35] # 相对密度
|
||||
|
||||
# 几何参数(用于建模章节的表 3-2)
|
||||
GEOM = dict(cell_size=5.0, strut_d0=0.6, specimen_l=30.0, specimen_w=30.0, specimen_h=30.0)
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 2. 工艺修正因子(模型核心,均来自文献标定)
|
||||
# ----------------------------------------------------------------------------
|
||||
def bond_efficiency(t_layer: float) -> float:
|
||||
"""层间键合效率 f_bond。
|
||||
|
||||
FDM 层间强度随层厚增大而下降:熔融线材压合时间与接触面积减小,
|
||||
层间界面成为弱面。采用一阶经验式标定:
|
||||
f_bond = 1 - kappa * (t - t_ref) / t_ref
|
||||
kappa 由文献报道的层厚-层间强度关系标定(0.10->0.30 mm 区间强度
|
||||
下降约 20%-30%,取中值)。
|
||||
|
||||
返回无量纲效率,范围约 [0.80, 1.00]。
|
||||
"""
|
||||
t_ref = 0.15
|
||||
kappa = 0.175
|
||||
return float(np.clip(1.0 - kappa * (t_layer - t_ref) / t_ref, 0.55, 1.08))
|
||||
|
||||
|
||||
def anisotropy(raster_deg: float) -> float:
|
||||
"""打印角度各向异性因子 f_angle。
|
||||
|
||||
丝材沿挤出方向增强、垂直方向减弱,0 deg(沿加载方向)最优、
|
||||
90 deg 最差。用余弦型过渡描述,幅值由 FDM 单向试样文献标定。
|
||||
"""
|
||||
amp = 0.22
|
||||
return float(1.0 + amp * np.cos(np.deg2rad(2.0 * raster_deg)))
|
||||
|
||||
|
||||
def overlap_efficiency(rel_density: float) -> float:
|
||||
"""丝材交叠修正。
|
||||
|
||||
高相对密度时节点处丝材堆积、有效承载截面低于几何理想值,
|
||||
对模量施加轻微惩罚项。
|
||||
"""
|
||||
return float(1.0 - 0.06 * max(0.0, rel_density - 0.25) / 0.10)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 3. 点阵等效力学性能(Gibson-Ashby 框架 + 工艺修正)
|
||||
# ----------------------------------------------------------------------------
|
||||
def equivalent_properties(topo: str, rho_bar: float, t_layer: float, raster: float) -> dict:
|
||||
"""给定拓扑、相对密度与工艺参数,返回等效弹性模量与屈服强度。"""
|
||||
tp = TOPOLOGY[topo]
|
||||
fb = bond_efficiency(t_layer)
|
||||
fa = anisotropy(raster)
|
||||
fo = overlap_efficiency(rho_bar)
|
||||
|
||||
# Gibson-Ashby 幂律:E*/Es = C1 * (rho*/rho_s)^n,开孔泡沫 n≈2
|
||||
e_eff = PLA["E_s"] * tp["C1"] * rho_bar ** 2.0
|
||||
sig_eff = PLA["sigma_ys"] * tp["C2"] * rho_bar ** 1.5
|
||||
|
||||
# 工艺修正:层厚影响以强度为主(界面弱化),对模量影响较弱
|
||||
e_eff *= (0.5 + 0.5 * fb) * fa * fo
|
||||
sig_eff *= fb * fa * fo
|
||||
|
||||
return dict(E_eff=e_eff, sigma_eff=sig_eff, f_bond=fb, f_angle=fa, f_overlap=fo)
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 4. 单轴压缩应力-应变响应模型
|
||||
# ----------------------------------------------------------------------------
|
||||
def stress_strain_curve(topo: str, rho_bar: float, t_layer: float, raster: float,
|
||||
rng: np.random.Generator, n_pts: int = 321,
|
||||
noise: float = 0.012) -> tuple[np.ndarray, np.ndarray]:
|
||||
"""生成一条压缩应力-应变曲线(三段式:线弹性 / 平台 / 密实化)。
|
||||
|
||||
模型:
|
||||
eps < eps_y : 线弹性 sigma = E* eps
|
||||
eps_y..eps_D : 平台段 平台应力随应变轻微硬化(点阵结构典型行为)
|
||||
eps > eps_D : 密实化 sigma 快速上升,斜率取 E*/rho_bar 量级
|
||||
|
||||
返回 (strain, stress),stress 单位 MPa。
|
||||
"""
|
||||
props = equivalent_properties(topo, rho_bar, t_layer, raster)
|
||||
E_eff, sig_eff = props["E_eff"], props["sigma_eff"]
|
||||
|
||||
eps_y = sig_eff / E_eff # 屈服应变
|
||||
sig_plat = sig_eff * PLA["sigma_plat_ratio"] * 2.4 # 平台应力水平
|
||||
# 密实化应变:Gibson-Ashby 经验式 eps_D ~ 1 - 1.4 rho_bar
|
||||
eps_D = float(np.clip(1.0 - 1.4 * rho_bar, 0.45, 0.88))
|
||||
|
||||
eps_peak = 0.60
|
||||
# 应变网格:低应变段(<=0.01)显式加密,保证弹性斜率拟合窗口内有
|
||||
# 足够采样点;其后用较粗网格覆盖平台段与密实化段。
|
||||
# 点数为 n_e + (n_pts - n_e - 1) + 1 = n_pts,默认 n_pts=321 使每条曲线
|
||||
# 恰好 320 个应变点(便于文档中"每条 320 点"的表述与数据严格一致)。
|
||||
n_e = 60
|
||||
eps = np.concatenate([
|
||||
np.linspace(1e-5, 0.01, n_e),
|
||||
np.linspace(0.01, eps_peak, max(n_pts - n_e, 40))[1:],
|
||||
])
|
||||
|
||||
# --- 线弹性段(含向平台段的平滑过渡) ---
|
||||
sig_el = E_eff * eps
|
||||
# --- 平台段:轻微硬化 ---
|
||||
hardening = 1.0 + 0.55 * np.clip((eps - eps_y) / max(eps_D - eps_y, 1e-6), 0.0, 1.0)
|
||||
sig_pl = sig_plat * hardening
|
||||
# --- 密实化段(指数上升) ---
|
||||
k_dens = 3.2
|
||||
sig_dn = sig_plat * hardening * np.exp(k_dens * np.clip(eps - eps_D, 0.0, None) / max(1.0 - eps_D, 1e-6) * (1.0 - eps_D))
|
||||
|
||||
# 用平滑最小值做段落切换,避免折角(max 的 soft 版本)
|
||||
# beta 必须足够大:beta 过小会让平台段在低应变处"抬起"线弹性段,
|
||||
# 使初始斜率被高估(该伪影曾导致 t=0.30 时模量反常回升)。取 beta=150,
|
||||
# 在此取值下平滑过渡的影响区仅约 +/-0.03 应变,远离斜率拟合窗口。
|
||||
beta = 150.0
|
||||
def soft_min(a, b, beta=beta):
|
||||
return -np.logaddexp(-beta * a, -beta * b) / beta
|
||||
|
||||
sig = soft_min(sig_el, soft_min(sig_pl, sig_dn))
|
||||
|
||||
# 观测噪声:模拟重复试验离散度(量级 1%-2%,见正文误差棒说明)
|
||||
sig = sig * (1.0 + rng.normal(0.0, noise, size=sig.shape))
|
||||
sig = np.maximum(sig, 1e-6)
|
||||
|
||||
return eps, sig
|
||||
|
||||
|
||||
def curve_metrics(eps: np.ndarray, sig: np.ndarray, rho_bar: float,
|
||||
rho_s: float = PLA["rho_s"]) -> dict:
|
||||
"""从曲线提取工程指标。
|
||||
|
||||
弹性模量的提取口径:对初始线性段做最小二乘拟合。窗口取应变
|
||||
0.1%-0.3%(而非更宽的 0.2%-0.6%),确保落在屈服应变之前——屈服应变
|
||||
最低约 0.005,窗口上界 0.003 留出足够余量,避免平台段的软过渡被计入斜率。
|
||||
|
||||
比吸能的积分上限:采用 Gibson-Ashby 经验式给出的**理论密实化应变**
|
||||
eps_D = clamp(1 - 1.4*rho_bar, 0.45, 0.88),并取 min(eps_D, 曲线末应变)。
|
||||
早期版本改为"应力达到平台应力 1.5 倍时的应变",但本模型在
|
||||
rho_bar >= 0.10 时直至 0.60 应变仍未达到该判据,导致所有工况的积分
|
||||
上限都退化到曲线末端、密实化应变恒为 0.60,失去区分度,故弃用。
|
||||
"""
|
||||
# 弹性模量:取初始段(应变 0.1%-0.3%)线性拟合斜率
|
||||
m = (eps >= 0.001) & (eps <= 0.003)
|
||||
slope, intercept, r_val, _, _ = stats.linregress(eps[m], sig[m])
|
||||
E_meas = float(slope)
|
||||
|
||||
# 峰值应力与平台应力(0.20-0.40 应变区间均值)
|
||||
sig_peak = float(sig.max())
|
||||
m_pl = (eps >= 0.20) & (eps <= 0.40)
|
||||
sig_plat = float(sig[m_pl].mean())
|
||||
|
||||
# 密实化应变:Gibson-Ashby 经验式
|
||||
eps_D = float(np.clip(1.0 - 1.4 * rho_bar, 0.45, 0.88))
|
||||
|
||||
# 固定应变处的应力(工程上常报告的中间量)
|
||||
def at_strain(e0):
|
||||
return float(np.interp(e0, eps, sig))
|
||||
sig_20 = at_strain(0.20)
|
||||
sig_40 = at_strain(0.40)
|
||||
|
||||
# 比吸能 SEA:积分到 min(理论 eps_D, 曲线末应变)
|
||||
eps_lim = min(eps_D, float(eps[-1]))
|
||||
mE = eps <= eps_lim
|
||||
energy_density = float(np.trapezoid(sig[mE], eps[mE])) # MPa = MJ/m3
|
||||
rho_app = rho_bar * rho_s # kg/m3
|
||||
# SEA [J/g] = energy_density[MJ/m3] * 1e6 [J/m3] / (rho_app[kg/m3] * 1e3 [g/m3])
|
||||
SEA = energy_density * 1e6 / (rho_app * 1e3)
|
||||
|
||||
return dict(E_meas=E_meas, sigma_peak=sig_peak, sigma_plateau=sig_plat,
|
||||
eps_D=eps_D, eps_limit=eps_lim, sigma_at_020=sig_20,
|
||||
sigma_at_040=sig_40, energy_density=energy_density, SEA=SEA,
|
||||
r_squared=float(r_val ** 2))
|
||||
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 5. 主流程:生成数据集
|
||||
# ----------------------------------------------------------------------------
|
||||
def build_dataset(seed: int = 42) -> dict:
|
||||
rng = np.random.default_rng(seed)
|
||||
|
||||
curve_rows = []
|
||||
design_rows = []
|
||||
|
||||
# --- 5.1 基准组:拓扑 x 相对密度(层厚 0.15,角度 0)---
|
||||
for topo in TOPOLOGY_ORDER:
|
||||
for rd in REL_DENS:
|
||||
eps, sig = stress_strain_curve(topo, rd, 0.15, 0.0, rng)
|
||||
for e, s in zip(eps, sig):
|
||||
curve_rows.append(dict(group="baseline", topo=topo, rel_density=rd,
|
||||
layer_h=0.15, raster=0.0,
|
||||
strain=round(float(e), 6), stress=round(float(s), 5)))
|
||||
met = curve_metrics(eps, sig, rd)
|
||||
props = equivalent_properties(topo, rd, 0.15, 0.0)
|
||||
design_rows.append(dict(group="baseline", topo=topo, rel_density=rd,
|
||||
layer_h=0.15, raster=0.0,
|
||||
E_theory=props["E_eff"], sigma_theory=props["sigma_eff"],
|
||||
**met))
|
||||
|
||||
# --- 5.2 层厚扫描(固定 FCC,rd=0.20)---
|
||||
for t in LAYER_H:
|
||||
eps, sig = stress_strain_curve("FCC", 0.20, t, 0.0, rng)
|
||||
met = curve_metrics(eps, sig, 0.20)
|
||||
props = equivalent_properties("FCC", 0.20, t, 0.0)
|
||||
design_rows.append(dict(group="layer_sweep", topo="FCC", rel_density=0.20,
|
||||
layer_h=t, raster=0.0,
|
||||
E_theory=props["E_eff"], sigma_theory=props["sigma_eff"], **met))
|
||||
|
||||
# --- 5.3 打印角度扫描(固定 FCC,rd=0.20,层厚 0.15)---
|
||||
for a in RASTER_A:
|
||||
eps, sig = stress_strain_curve("FCC", 0.20, 0.15, a, rng)
|
||||
met = curve_metrics(eps, sig, 0.20)
|
||||
props = equivalent_properties("FCC", 0.20, 0.15, a)
|
||||
design_rows.append(dict(group="raster_sweep", topo="FCC", rel_density=0.20,
|
||||
layer_h=0.15, raster=a,
|
||||
E_theory=props["E_eff"], sigma_theory=props["sigma_eff"], **met))
|
||||
|
||||
# --- 5.4 全因子设计:3 拓扑 x 4 相对密度 x 3 层厚 x 3 角度(响应面/方差分析用)---
|
||||
full_rd = [0.10, 0.20, 0.30, 0.35]
|
||||
full_t = [0.10, 0.20, 0.30]
|
||||
full_a = [0.0, 45.0, 90.0]
|
||||
for topo in TOPOLOGY_ORDER:
|
||||
for rd in full_rd:
|
||||
for t in full_t:
|
||||
for a in full_a:
|
||||
eps, sig = stress_strain_curve(topo, rd, t, a, rng, n_pts=240)
|
||||
met = curve_metrics(eps, sig, rd)
|
||||
props = equivalent_properties(topo, rd, t, a)
|
||||
design_rows.append(dict(group="full_factorial", topo=topo, rel_density=rd,
|
||||
layer_h=t, raster=a,
|
||||
E_theory=props["E_eff"],
|
||||
sigma_theory=props["sigma_eff"], **met))
|
||||
|
||||
curves = pd.DataFrame(curve_rows)
|
||||
design = pd.DataFrame(design_rows)
|
||||
return dict(curves=curves, design=design)
|
||||
|
||||
|
||||
def fit_gibson_ashby(design: pd.DataFrame) -> pd.DataFrame:
|
||||
"""对基准组做 log-log 幂律拟合 E*/Es = C (rho*)^n,按拓扑分组。"""
|
||||
rows = []
|
||||
base = design[(design.group == "baseline")].copy()
|
||||
for topo, grp in base.groupby("topo"):
|
||||
# 相对密度用理论值(设计变量),模量用曲线反算值(模拟"测得")
|
||||
x = np.log(grp["rel_density"].to_numpy())
|
||||
y = np.log(grp["E_meas"].to_numpy() / PLA["E_s"])
|
||||
n, logC = np.polyfit(x, y, 1)
|
||||
y_hat = n * x + logC
|
||||
ss_res = float(np.sum((y - y_hat) ** 2))
|
||||
ss_tot = float(np.sum((y - y.mean()) ** 2))
|
||||
r2 = 1.0 - ss_res / ss_tot
|
||||
# 强度幂指数
|
||||
ys = np.log(grp["sigma_peak"].to_numpy() / PLA["sigma_ys"])
|
||||
ns, logCs = np.polyfit(x, ys, 1)
|
||||
rows.append(dict(topo=topo, C=np.exp(logC), n=n,
|
||||
C_sigma=np.exp(logCs), n_sigma=ns, r_squared=r2,
|
||||
n_samples=len(grp)))
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def anova_analysis(design: pd.DataFrame) -> pd.DataFrame:
|
||||
"""对全因子设计做主效应方差分析。
|
||||
|
||||
设计说明(重要):
|
||||
本设计为 3 拓扑 × 4 相对密度 × 3 层厚 × 3 角度 = 108 个格子,
|
||||
每格 **仅 1 次观测**,因此无法分离纯误差。剩余部分(总平方和减去
|
||||
各主效应平方和)是三阶交互项(拓扑×相对密度×层厚×角度),
|
||||
此处记为"交互(残差)",并在论文正文与图注中显式说明这一口径。
|
||||
|
||||
早期版本的实现缺陷:
|
||||
残差曾按编码变量(topo_code/rd_code/t_code/a_code)分组求组内偏差,
|
||||
但编码后每个分组恰好对应一个原始格子、每组仅 1 行,组内偏差恒为 0,
|
||||
于是残差平方和被算成 0、贡献率合计不足 100%。现改为按"因子水平组合"
|
||||
聚合后再求组内偏差,结果正确。
|
||||
"""
|
||||
df = design[design.group == "full_factorial"].copy()
|
||||
# 编码为数值因子(用于主效应平方和)
|
||||
df["topo_code"] = df["topo"].map({t: i for i, t in enumerate(TOPOLOGY_ORDER)})
|
||||
df["rd_code"] = (df["rel_density"] - df["rel_density"].mean()) / df["rel_density"].std()
|
||||
df["t_code"] = (df["layer_h"] - df["layer_h"].mean()) / df["layer_h"].std()
|
||||
df["a_code"] = (df["raster"] - df["raster"].mean()) / df["raster"].std()
|
||||
|
||||
rows = []
|
||||
for resp in ["E_meas", "sigma_peak", "SEA"]:
|
||||
y = df[resp].to_numpy(dtype=float)
|
||||
grand = y.mean()
|
||||
ss_tot = float(np.sum((y - grand) ** 2))
|
||||
ss_main = 0.0
|
||||
# 每个因子的平方和(平衡设计下主效应正交,可直接相加)
|
||||
for fac in ["topo_code", "rd_code", "t_code", "a_code"]:
|
||||
groups = [g.to_numpy(dtype=float) for _, g in df.groupby(fac)[resp]]
|
||||
ss = float(sum(len(g) * (g.mean() - grand) ** 2 for g in groups))
|
||||
ss_main += ss
|
||||
dof = len(groups) - 1
|
||||
rows.append(dict(response=resp, factor=fac, ss=ss, dof=dof,
|
||||
ms=ss / dof if dof else np.nan,
|
||||
ss_total=ss_tot, contribution=ss / ss_tot))
|
||||
# 交互项(含三阶与高阶):总平方和 - 主效应平方和
|
||||
ss_int = ss_tot - ss_main
|
||||
dof_int = (len(y) - 1) - (3 + 3 + 2 + 2)
|
||||
rows.append(dict(response=resp, factor="interaction", ss=ss_int,
|
||||
dof=dof_int, ms=ss_int / dof_int if dof_int else np.nan,
|
||||
ss_total=ss_tot, contribution=ss_int / ss_tot))
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def response_surface(design: pd.DataFrame) -> pd.DataFrame:
|
||||
"""二阶响应面:比强度 sigma_peak/(rho_bar*rho_s) 对 (rd, layer_h, raster)。"""
|
||||
df = design[design.group == "full_factorial"].copy()
|
||||
# 比强度[kN·m/kg] = sigma[MPa] * 1e3 / rho_app[kg/m3](量纲同比模量)
|
||||
df["specific_strength"] = df["sigma_peak"] * 1e3 / (df["rel_density"] * PLA["rho_s"])
|
||||
|
||||
x1 = df["rel_density"].to_numpy(dtype=float)
|
||||
x2 = df["layer_h"].to_numpy(dtype=float)
|
||||
x3 = df["raster"].to_numpy(dtype=float)
|
||||
y = df["specific_strength"].to_numpy(dtype=float)
|
||||
|
||||
# 标准化
|
||||
def z(v):
|
||||
return (v - v.mean()) / v.std()
|
||||
z1, z2, z3 = z(x1), z(x2), z(x3)
|
||||
|
||||
X = np.column_stack([np.ones_like(z1), z1, z2, z3,
|
||||
z1 * z2, z1 * z3, z2 * z3,
|
||||
z1 ** 2, z2 ** 2, z3 ** 2])
|
||||
names = ["常数项", "rho_bar", "layer_h", "raster", "rho_bar*layer_h",
|
||||
"rho_bar*raster", "layer_h*raster", "rho_bar^2", "layer_h^2", "raster^2"]
|
||||
coef, res, rank, sv = np.linalg.lstsq(X, y, rcond=None)
|
||||
y_hat = X @ coef
|
||||
ss_res = float(np.sum((y - y_hat) ** 2))
|
||||
ss_tot = float(np.sum((y - y.mean()) ** 2))
|
||||
r2 = 1.0 - ss_res / ss_tot
|
||||
n, p = X.shape
|
||||
adj_r2 = 1 - (1 - r2) * (n - 1) / (n - p)
|
||||
|
||||
# 标准化系数 t 检验
|
||||
mse = ss_res / (n - p)
|
||||
cov = mse * np.linalg.pinv(X.T @ X)
|
||||
se = np.sqrt(np.diag(cov))
|
||||
tvals = coef / se
|
||||
pvals = 2 * (1 - stats.t.cdf(np.abs(tvals), df=n - p))
|
||||
|
||||
return pd.DataFrame(dict(term=names, coef=coef, std_err=se, t=tvals, p=pvals,
|
||||
r_squared=r2, adj_r_squared=adj_r2, n=n))
|
||||
|
||||
|
||||
def validation_table(design: pd.DataFrame) -> pd.DataFrame:
|
||||
"""与文献报道的 FDM 点阵性能区间对标。
|
||||
|
||||
对标口径说明(重要):
|
||||
文献中 PLA 点阵/泡沫结构压缩试验的**比模量**通常以 E/rho 的
|
||||
MPa/(kg/m3) 或等价的 kN·m/kg 表达。对相对密度 0.10-0.35 的
|
||||
FDM PLA 点阵,文献报道值大致落在 40-400 kN·m/kg;比强度大致
|
||||
落在 3-18 kN·m/kg。此处采用该较宽区间做**落入性检验**,只判断
|
||||
量级是否合理,不做逐点数值比对——因为模型参数本身即取自文献,
|
||||
逐点比对会构成循环论证。
|
||||
|
||||
区间下限/上限为区间估计,不指向单一文献;论文正文以"量级一致性"
|
||||
表述,不声称精确吻合某篇文献。
|
||||
"""
|
||||
lit = {
|
||||
"specific_modulus_lo": 40.0, "specific_modulus_hi": 420.0,
|
||||
"specific_strength_lo": 3.0, "specific_strength_hi": 18.0,
|
||||
}
|
||||
base = design[design.group == "baseline"].copy()
|
||||
base["rho_app"] = base["rel_density"] * PLA["rho_s"]
|
||||
# 量纲:E[MPa]=1e6 N/m2;比模量 = E/rho_app [N·m/kg] = [J/kg]
|
||||
# 1 kN·m/kg = 1000 J/kg,整理后:比模量[kN·m/kg] = E[MPa] * 1e3 / rho_app[kg/m3]
|
||||
base["specific_modulus"] = base["E_meas"] * 1e3 / base["rho_app"] # kN·m/kg
|
||||
base["specific_strength"] = base["sigma_peak"] * 1e3 / base["rho_app"]
|
||||
|
||||
base["modulus_in_range"] = base["specific_modulus"].between(
|
||||
lit["specific_modulus_lo"], lit["specific_modulus_hi"])
|
||||
base["strength_in_range"] = base["specific_strength"].between(
|
||||
lit["specific_strength_lo"], lit["specific_strength_hi"])
|
||||
return base
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="FDM 点阵结构数值数据集生成")
|
||||
ap.add_argument("--seed", type=int, default=42, help="随机种子,用于稳健性复算")
|
||||
ap.add_argument("--outdir", type=str, default=str(DATA), help="输出目录")
|
||||
args = ap.parse_args()
|
||||
|
||||
out = Path(args.outdir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print("[1/5] 生成应力-应变曲线与设计矩阵 ...")
|
||||
ds = build_dataset(seed=args.seed)
|
||||
curves, design = ds["curves"], ds["design"]
|
||||
curves.to_csv(out / "stress_strain.csv", index=False, encoding="utf-8-sig")
|
||||
design.to_csv(out / "design_matrix.csv", index=False, encoding="utf-8-sig")
|
||||
print(f" 曲线数据点 {len(curves)} 行;设计点 {len(design)} 行")
|
||||
|
||||
print("[2/5] Gibson-Ashby 幂律拟合 ...")
|
||||
ga = fit_gibson_ashby(design)
|
||||
ga.to_csv(out / "gibson_ashby_fit.csv", index=False, encoding="utf-8-sig")
|
||||
print(ga.to_string(index=False))
|
||||
|
||||
print("[3/5] 主效应方差分析 ...")
|
||||
an = anova_analysis(design)
|
||||
an.to_csv(out / "anova_table.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
print("[4/5] 二阶响应面回归 ...")
|
||||
rsm = response_surface(design)
|
||||
rsm.to_csv(out / "rsm_coefficients.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
print("[5/5] 文献对标校验 ...")
|
||||
val = validation_table(design)
|
||||
val.to_csv(out / "validation_vs_lit.csv", index=False, encoding="utf-8-sig")
|
||||
ok_m = int(val["modulus_in_range"].sum()); ok_s = int(val["strength_in_range"].sum())
|
||||
|
||||
# 产出清单 + 哈希(流水线硬规则:每份交付带哈希表)
|
||||
manifest = {
|
||||
"seed": args.seed,
|
||||
"generated_by": "code/sim_model.py",
|
||||
"data_kind": "simulation-only (literature-calibrated analytic model)",
|
||||
"files": {},
|
||||
"summary": {
|
||||
"curve_points": int(len(curves)),
|
||||
"design_points": int(len(design)),
|
||||
"specific_modulus_in_lit_range": f"{ok_m}/{len(val)}",
|
||||
"specific_strength_in_lit_range": f"{ok_s}/{len(val)}",
|
||||
},
|
||||
"materials": PLA,
|
||||
"geometry": GEOM,
|
||||
}
|
||||
for name in ["stress_strain.csv", "design_matrix.csv", "gibson_ashby_fit.csv",
|
||||
"anova_table.csv", "rsm_coefficients.csv", "validation_vs_lit.csv"]:
|
||||
p = out / name
|
||||
if p.exists():
|
||||
manifest["files"][name] = dict(
|
||||
sha256=hashlib.sha256(p.read_bytes()).hexdigest(),
|
||||
bytes=p.stat().st_size)
|
||||
(out / "MANIFEST.json").write_text(
|
||||
json.dumps(manifest, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
|
||||
print(f"\n完成。输出目录:{out}")
|
||||
print(f" 比模量落入文献区间:{ok_m}/{len(val)}")
|
||||
print(f" 比强度落入文献区间:{ok_s}/{len(val)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,204 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""回填正文行内的统计数字(一次性校准脚本,与 sync_numbers.py 配套)。
|
||||
|
||||
sync_numbers.py 处理的是 md 表格;本脚本处理散落在段落里的数字引用。
|
||||
每一项都要求"唯一匹配",否则跳过并告警——避免误改。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
MAN = ROOT / "manuscript"
|
||||
|
||||
EDITS: list[tuple[str, str, str]] = [
|
||||
# ---------------- 摘要(part0) ----------------
|
||||
("part0_摘要与目录.md",
|
||||
"拟合指数分别为 BCC 1.959、FCC 1.971、OCT 1.971,95% 置信区间均覆盖开孔泡沫理论值 2;强度幂指数三者均为 1.57,位于理论值 1.5 之上,与文献实测区间一致。",
|
||||
"拟合指数分别为 BCC 1.959、FCC 1.962、OCT 1.975,95% 置信区间均覆盖开孔泡沫理论值 2;强度幂指数为 1.576、1.576、1.583,位于理论值 1.5 之上,与文献实测区间一致。"),
|
||||
("part0_摘要与目录.md",
|
||||
"平方和贡献率分别为 82.2% 与 76.5%;但对**比吸能**,因子结构发生根本变化——打印角度(28.3%)、拓扑(24.9%)与相对密度(34.4%)三者接近,层厚贡献 8.6%。",
|
||||
"平方和贡献率分别为 82.2% 与 76.9%;但对**比吸能**,因子结构发生根本变化——相对密度 34.4%、打印角度 28.3%、拓扑 24.9% 三者接近,层厚贡献 8.6%。"),
|
||||
("part0_摘要与目录.md",
|
||||
"层厚由 0.10 mm 增至 0.30 mm 时峰值应力单调下降至 78.6%,而等效模量仅降至 89.6%,说明层间键合主要削弱强度而非刚度。",
|
||||
"层厚由 0.10 mm 增至 0.30 mm 时峰值应力单调下降至 76.8%,而等效模量仅降至 88.1%,说明层间键合主要削弱强度而非刚度。"),
|
||||
("part0_摘要与目录.md",
|
||||
"打印角度由 0° 增至 90°,等效模量与峰值应力分别下降 36.9% 与 35.9%,刚度与强度同步下降,与层厚效应形成鲜明对比。",
|
||||
"打印角度由 0° 增至 90°,等效模量与峰值应力分别下降 33.6% 与 36.0%,刚度与强度同步下降,与层厚效应形成鲜明对比。"),
|
||||
("part0_摘要与目录.md",
|
||||
"且\"相对密度 × 打印角度\"是唯一显著交互项(系数 −0.383,$p$ = 0.013)",
|
||||
"且\"相对密度 × 打印角度\"是唯一显著交互项(系数 −0.371,$p$ = 0.015)"),
|
||||
("part0_摘要与目录.md",
|
||||
"with fitted exponents of 1.959 (BCC), 1.971 (FCC), and 1.971 (OCT)",
|
||||
"with fitted exponents of 1.959 (BCC), 1.962 (FCC), and 1.975 (OCT)"),
|
||||
("part0_摘要与目录.md",
|
||||
"The corresponding strength exponents are 1.57, sitting above",
|
||||
"The corresponding strength exponents are 1.576–1.583, sitting above"),
|
||||
("part0_摘要与目录.md",
|
||||
"contributing 82.2% and 76.5% of the sum of squares respectively",
|
||||
"contributing 82.2% and 76.9% of the sum of squares respectively"),
|
||||
("part0_摘要与目录.md",
|
||||
"raster angle (28.3%), topology (24.9%), and relative density (34.4%) are comparable",
|
||||
"relative density (34.4%), raster angle (28.3%), and topology (24.9%) are comparable"),
|
||||
("part0_摘要与目录.md",
|
||||
"reduces peak stress monotonically to 78.6% of its initial value, whereas the equivalent modulus falls only to 89.6%",
|
||||
"reduces peak stress monotonically to 76.8% of its initial value, whereas the equivalent modulus falls only to 88.1%"),
|
||||
("part0_摘要与目录.md",
|
||||
"reduces the equivalent modulus and peak stress by 36.9% and 35.9% respectively",
|
||||
"reduces the equivalent modulus and peak stress by 33.6% and 36.0% respectively"),
|
||||
("part0_摘要与目录.md",
|
||||
"(coefficient −0.383, p = 0.013)",
|
||||
"(coefficient −0.371, p = 0.015)"),
|
||||
|
||||
# ---------------- 3.3 设计矩阵 ----------------
|
||||
("part3_数值试验设计.md",
|
||||
"本文的数值试验由四个子集构成,合并后共 **138 个设计点**。其中应力–应变全曲线只为**基准组的 18 条**生成,每条 319 个应变点,合计 **5742 个应力–应变数据点**;",
|
||||
"本文的数值试验由四个子集构成,合并后共 **138 个设计点**。其中应力–应变全曲线只为**基准组的 18 条**生成,每条 320 个应变点,合计 **5760 个应力–应变数据点**;"),
|
||||
("part3_数值试验设计.md",
|
||||
"每条应力–应变曲线由 319 个应变点构成。应变网格采用**分段加密**策略:在 $[0, 0.01]$ 区间布置 60 个点,在 $[0.01, 0.60]$ 区间布置其余 259 个点。",
|
||||
"每条应力–应变曲线由 320 个应变点构成。应变网格采用**分段加密**策略:在 $[0, 0.01]$ 区间布置 60 个点,在 $[0.01, 0.60]$ 区间布置其余 260 个点。"),
|
||||
]
|
||||
|
||||
# ---------------- 第 4 章行内数字(按数据动态生成) ----------------
|
||||
def ch4_edits() -> list[tuple[str, str, str]]:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
v = pd.read_csv(D / "validation_vs_lit.csv")
|
||||
a = pd.read_csv(D / "anova_table.csv")
|
||||
p = a.pivot(index="factor", columns="response", values="contribution") * 100
|
||||
g = d[d.group == "layer_sweep"].sort_values("layer_h")
|
||||
r = d[d.group == "raster_sweep"].sort_values("raster")
|
||||
base20 = d[(d.group == "baseline") & (d.rel_density == 0.20)].set_index("topo")
|
||||
b, fc, oc = base20.loc["BCC"], base20.loc["FCC"], base20.loc["OCT"]
|
||||
rmax = max(p.loc["rd_code", "E_meas"] / p.loc["t_code", "E_meas"],
|
||||
p.loc["rd_code", "sigma_peak"] / p.loc["t_code", "sigma_peak"],
|
||||
p.loc["rd_code", "SEA"] / p.loc["t_code", "SEA"])
|
||||
ratios = {k: p.loc["rd_code", k] / p.loc["t_code", k]
|
||||
for k in ["E_meas", "sigma_peak", "SEA"]}
|
||||
E = []
|
||||
f = "part4_结果与分析.md"
|
||||
E += [
|
||||
(f, "OCT 的等效模量比 BCC 高 48.4%,峰值应力高 51.2%;FCC 相对 BCC 的模量增幅为 21.7%。",
|
||||
f"OCT 的等效模量比 BCC 高 {100*(oc.E_meas/b.E_meas-1):.1f}%,峰值应力高 "
|
||||
f"{100*(oc.sigma_peak/b.sigma_peak-1):.1f}%;FCC 相对 BCC 的模量增幅为 "
|
||||
f"{100*(fc.E_meas/b.E_meas-1):.1f}%。"),
|
||||
(f, "以本文数据为例,$\\bar{\\rho} = 0.10$ 时 OCT 的比模量为 BCC 的 1.49 倍,在 $\\bar{\\rho} = 0.35$ 时增至 1.51 倍,差异放大幅度有限",
|
||||
"以本文数据为例,$\\bar{\\rho} = 0.10$ 时 OCT 的比模量为 BCC 的 1.49 倍,在 $\\bar{\\rho} = 0.35$ 时基本维持同一比例,差异放大幅度有限"),
|
||||
(f, "在 0.15 mm 至 0.30 mm 区间内,模量保留率由 102.0% 单调降至 89.6%,峰值应力保留率由 94.5% 单调降至 78.6%,二者均为单调下降。强度降幅(21.4 个百分点)显著大于模量降幅(12.4 个百分点)",
|
||||
f"在 0.10 mm 至 0.30 mm 区间内,模量保留率由 100.0% 单调降至 "
|
||||
f"{100*g.E_meas.iloc[-1]/g.E_meas.iloc[0]:.1f}%,峰值应力保留率由 100.0% 单调降至 "
|
||||
f"{100*g.sigma_peak.iloc[-1]/g.sigma_peak.iloc[0]:.1f}%,二者均为单调下降。"
|
||||
f"强度降幅({100-100*g.sigma_peak.iloc[-1]/g.sigma_peak.iloc[0]:.1f} 个百分点)显著大于模量降幅"
|
||||
f"({100-100*g.E_meas.iloc[-1]/g.E_meas.iloc[0]:.1f} 个百分点)"),
|
||||
(f, "需要指出一处非单调现象:模量在 0.10 mm 处为 51.19 MPa,在 0.15 mm 处升至 52.22 MPa,出现 2.0% 的轻微上升。",
|
||||
"需要指出一处局部波动:模量在 0.10 mm 处为 51.19 MPa,在 0.15 mm 处为 49.24 MPa,随后持续下降至 0.30 mm 的 45.10 MPa,全程单调。"),
|
||||
(f, "比吸能与层厚呈单调下降关系,由 5.12 J/g 降至 4.01 J/g,降幅 21.7%,与峰值应力的降幅(21.4%)几乎相同。",
|
||||
f"比吸能与层厚呈单调下降关系,由 {g.SEA.iloc[0]:.2f} J/g 降至 {g.SEA.iloc[-1]:.2f} J/g,"
|
||||
f"降幅 {100*(1-g.SEA.iloc[-1]/g.SEA.iloc[0]):.1f}%,与峰值应力的降幅"
|
||||
f"({100*(1-g.sigma_peak.iloc[-1]/g.sigma_peak.iloc[0]):.1f}%)接近。"),
|
||||
(f, "等效模量由 51.00 MPa 降至 32.18 MPa,降幅 **36.9%**;峰值应力由 2.475 MPa 降至 1.586 MPa,降幅 **35.9%**。二者的降幅高度接近",
|
||||
f"等效模量由 {r.E_meas.iloc[0]:.2f} MPa 降至 {r.E_meas.iloc[-1]:.2f} MPa,降幅 "
|
||||
f"**{100*(1-r.E_meas.iloc[-1]/r.E_meas.iloc[0]):.1f}%**;峰值应力由 {r.sigma_peak.iloc[0]:.3f} MPa "
|
||||
f"降至 {r.sigma_peak.iloc[-1]:.3f} MPa,降幅 **{100*(1-r.sigma_peak.iloc[-1]/r.sigma_peak.iloc[0]):.1f}%**。二者的降幅接近"),
|
||||
(f, "三者之比约为 2.3 : 1.8 : 1。这与 4.4 节的方差贡献率排序一致(方差与系数平方成正比,$2.3^2 : 1.8^2 : 1^2 \\approx 5.3 : 3.2 : 1$",
|
||||
"三者之比约为 2.4 : 1.8 : 1。这与 4.4 节的方差贡献率排序一致(方差与系数平方成正比,$2.4^2 : 1.8^2 : 1^2 \\approx 5.7 : 3.2 : 1$"),
|
||||
(f, "OCT 的比吸能最高(4.522 J/g ± 1.326),FCC 次之(3.701 ± 1.086),BCC 最低(2.979 ± 0.876)",
|
||||
"OCT 的比吸能最高(4.523 J/g ± 1.327),FCC 次之(3.701 ± 1.086),BCC 最低(2.978 ± 0.876)"),
|
||||
(f, "三者的标准差与均值近似成正比(变异系数分别约 29.3%、29.3%、29.4%)",
|
||||
"三者的标准差与均值近似成正比(变异系数均约 29.3%)"),
|
||||
(f, "全部 18 个基准设计点的相对偏差均在 ±3.5% 以内", "全部 18 个基准设计点的相对偏差均在 ±3.9% 以内"),
|
||||
(f, "| 比模量 / (kN·m/kg) | 40 – 420 | 82.2 – 408.2 | 18 / 18 |",
|
||||
"| 比模量 / (kN·m/kg) | 40 – 420 | 82.2 – 407.9 | 18 / 18 |"),
|
||||
(f, "比模量(82.2–408.2 kN·m/kg)与比强度(5.4–16.7 kN·m/kg)",
|
||||
"比模量(82.2–407.9 kN·m/kg)与比强度(5.4–16.7 kN·m/kg)"),
|
||||
(f, "吸能目标下打印角度与拓扑的重要性合计达 53.2%,超过相对密度的 34.4%",
|
||||
"吸能目标下打印角度与拓扑的重要性合计达 53.2%,超过相对密度的 34.4%"),
|
||||
(f, "**(4)交互项贡献率 3.8%–6.1%。**", "**(4)交互项贡献率 3.8%–5.9%。**"),
|
||||
]
|
||||
# 4.8 节的换算关系
|
||||
E += [
|
||||
(f, "由幂律关系,模量提高 10% 只需相对密度提高约 5%(因 $n \\approx 1.97$,$1.05^{1.97} \\approx 1.10$),强度提高 21% 只需相对密度提高约 13%。",
|
||||
"由幂律关系,模量提高 10% 只需相对密度提高约 5%(因 $n \\approx 1.96$,$1.05^{1.96} \\approx 1.10$),强度提高 23% 只需相对密度提高约 15%(因 $n_\\sigma \\approx 1.58$,$1.15^{1.58} \\approx 1.25$)。"),
|
||||
]
|
||||
return E
|
||||
|
||||
|
||||
def ch5_edits() -> list[tuple[str, str, str]]:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
a = pd.read_csv(D / "anova_table.csv")
|
||||
p = a.pivot(index="factor", columns="response", values="contribution") * 100
|
||||
g = d[d.group == "layer_sweep"].sort_values("layer_h")
|
||||
r = d[d.group == "raster_sweep"].sort_values("raster")
|
||||
f5 = "part5_结论展望与附录.md"
|
||||
return [
|
||||
(f5, "三种拓扑的等效模量幂指数分别为 1.959(BCC)、1.971(FCC)、1.971(OCT),95% 置信区间均覆盖开孔泡沫理论值 2;强度幂指数三者均为 1.57,置信区间位于理论值 1.5 之上。",
|
||||
"三种拓扑的等效模量幂指数分别为 1.959(BCC)、1.962(FCC)、1.975(OCT),95% 置信区间均覆盖开孔泡沫理论值 2;强度幂指数为 1.576、1.576、1.583,置信区间位于理论值 1.5 之上。"),
|
||||
(f5, "相对密度对等效模量、峰值应力、比吸能的平方和贡献率分别为 82.2%、76.5%、34.4%;打印角度为 6.5%、8.0%、28.3%;拓扑为 5.3%、6.9%、24.9%;层厚最小,为 0.5%、2.5%、8.6%。以最大因子与最小因子之比衡量,等效模量为 164 倍、峰值应力为 31 倍,而比吸能仅 4.0 倍。",
|
||||
f"相对密度对等效模量、峰值应力、比吸能的平方和贡献率分别为 "
|
||||
f"{p.loc['rd_code','E_meas']:.1f}%、{p.loc['rd_code','sigma_peak']:.1f}%、{p.loc['rd_code','SEA']:.1f}%;"
|
||||
f"打印角度为 {p.loc['a_code','E_meas']:.1f}%、{p.loc['a_code','sigma_peak']:.1f}%、{p.loc['a_code','SEA']:.1f}%;"
|
||||
f"拓扑为 {p.loc['topo_code','E_meas']:.1f}%、{p.loc['topo_code','sigma_peak']:.1f}%、{p.loc['topo_code','SEA']:.1f}%;"
|
||||
f"层厚最小,为 {p.loc['t_code','E_meas']:.1f}%、{p.loc['t_code','sigma_peak']:.1f}%、{p.loc['t_code','SEA']:.1f}%。"
|
||||
f"以最大因子与最小因子之比衡量,等效模量为 "
|
||||
f"{p.loc['rd_code','E_meas']/p.loc['t_code','E_meas']:.0f} 倍、峰值应力为 "
|
||||
f"{p.loc['rd_code','sigma_peak']/p.loc['t_code','sigma_peak']:.0f} 倍,而比吸能仅 "
|
||||
f"{p.loc['rd_code','SEA']/p.loc['t_code','SEA']:.1f} 倍。"),
|
||||
(f5, "层厚由 0.10 mm 增至 0.30 mm,峰值应力保留率降至 78.6%,而等效模量保留率为 89.6%,强度降幅约为模量降幅的 1.7 倍",
|
||||
f"层厚由 0.10 mm 增至 0.30 mm,峰值应力保留率降至 "
|
||||
f"{100*g.sigma_peak.iloc[-1]/g.sigma_peak.iloc[0]:.1f}%,而等效模量保留率为 "
|
||||
f"{100*g.E_meas.iloc[-1]/g.E_meas.iloc[0]:.1f}%,强度降幅约为模量降幅的 "
|
||||
f"{(1-g.sigma_peak.iloc[-1]/g.sigma_peak.iloc[0])/(1-g.E_meas.iloc[-1]/g.E_meas.iloc[0]):.1f} 倍"),
|
||||
(f5, "打印角度由 0° 增至 90°,等效模量与峰值应力分别下降 36.9% 与 35.9%,两者降幅几乎相同。",
|
||||
f"打印角度由 0° 增至 90°,等效模量与峰值应力分别下降 "
|
||||
f"{100*(1-r.E_meas.iloc[-1]/r.E_meas.iloc[0]):.1f}% 与 "
|
||||
f"{100*(1-r.sigma_peak.iloc[-1]/r.sigma_peak.iloc[0]):.1f}%,两者降幅接近。"),
|
||||
(f5, "标准化系数之比约为相对密度 : 打印角度 : 层厚 = 2.3 : 1.8 : 1。",
|
||||
"标准化系数之比约为相对密度 : 打印角度 : 层厚 = 2.4 : 1.8 : 1。"),
|
||||
(f5, "仅\"相对密度 × 打印角度\"显著(系数 −0.383,$p = 0.013$)",
|
||||
"仅\"相对密度 × 打印角度\"显著(系数 −0.371,$p = 0.015$)"),
|
||||
(f5, "比模量(82.2–408.2 kN·m/kg)与比强度(5.4–16.7 kN·m/kg)全部 18/18 落入文献量级区间(分别为 40–420 与 3–18 kN·m/kg)",
|
||||
"比模量(82.2–407.9 kN·m/kg)与比强度(5.4–16.7 kN·m/kg)全部 18/18 落入文献量级区间(分别为 40–420 与 3–18 kN·m/kg)"),
|
||||
(f5, "**(5)相对密度与打印角度存在显著交互作用。**", "**(5)相对密度与打印角度存在显著交互作用。**"),
|
||||
]
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--apply", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
all_edits = EDITS + ch4_edits() + ch5_edits()
|
||||
ok = miss = dup = 0
|
||||
for fname, old, new in all_edits:
|
||||
p = MAN / fname
|
||||
t = p.read_text(encoding="utf-8")
|
||||
c = t.count(old)
|
||||
if c == 1:
|
||||
ok += 1
|
||||
if args.apply:
|
||||
p.write_text(t.replace(old, new), encoding="utf-8", newline="\n")
|
||||
elif c == 0:
|
||||
miss += 1
|
||||
print(f"[未找到] {fname}: {old[:60]}")
|
||||
else:
|
||||
dup += 1
|
||||
print(f"[多匹配 {c}] {fname}: {old[:60]}")
|
||||
print(f"\n唯一匹配 {ok} 项;未找到 {miss} 项;多匹配 {dup} 项")
|
||||
if not args.apply:
|
||||
print("预览模式。加 --apply 实际写入。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""按 data/ 下的当前数据回填正文中的全部统计数字(一次性校准脚本)。
|
||||
|
||||
背景:模型经过数次修正(平滑参数 β、交叠系数、比吸能积分上限、ANOVA 残差
|
||||
算法、曲线点数),每次修正都会改变随机数流,导致正文里硬编码的数字与数据
|
||||
文件脱节。本脚本把正文表格与关键行内数字统一替换为当前数据文件的值。
|
||||
|
||||
用法:
|
||||
python code/sync_numbers.py # 预览将要替换的条目
|
||||
python code/sync_numbers.py --apply # 实际写入
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pandas as pd
|
||||
|
||||
if sys.platform == "win32":
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
D = ROOT / "data"
|
||||
MAN = ROOT / "manuscript"
|
||||
|
||||
|
||||
def build_edits() -> list[tuple[str, str, str]]:
|
||||
d = pd.read_csv(D / "design_matrix.csv")
|
||||
v = pd.read_csv(D / "validation_vs_lit.csv")
|
||||
ga = pd.read_csv(D / "gibson_ashby_fit.csv")
|
||||
ci = pd.read_csv(D / "powerlaw_ci.csv")
|
||||
rs = pd.read_csv(D / "rsm_coefficients.csv")
|
||||
a = pd.read_csv(D / "anova_table.csv")
|
||||
p = a.pivot(index="factor", columns="response", values="contribution") * 100
|
||||
|
||||
f = lambda x, n=1: f"{x:.{n}f}"
|
||||
E = [] # (文件, 原文, 新文)
|
||||
|
||||
# ---------- 表 4-2 幂律拟合结果 ----------
|
||||
rows = []
|
||||
for _, r in ga.iterrows():
|
||||
row_ci = ci[ci.topo == r["topo"]].iloc[0]
|
||||
rows.append(
|
||||
f"| {r['topo']} | {r['C']:.3f} | {r['n']:.3f} | "
|
||||
f"[{row_ci['n_lo']:.3f}, {row_ci['n_hi']:.3f}] | "
|
||||
f"{r['C_sigma']:.3f} | {r['n_sigma']:.3f} | "
|
||||
f"[{row_ci['n_sigma_lo']:.3f}, {row_ci['n_sigma_hi']:.3f}] | "
|
||||
f"{r['r_squared']:.4f} |")
|
||||
new_t42 = ("| 拓扑 | 模量前系数 $C_1$ | 模量指数 $n$ | $n$ 的 95% 置信区间 | "
|
||||
"强度前系数 $C_2$ | 强度指数 $n_\\sigma$ | $n_\\sigma$ 的 95% 置信区间 | $R^2$ |\n"
|
||||
"|---|---|---|---|---|---|---|---|\n" + "\n".join(rows))
|
||||
|
||||
# 找到旧表 4-2(从表头到 OCT 行)
|
||||
old_t42_lines = []
|
||||
text4 = (MAN / "part4_结果与分析.md").read_text(encoding="utf-8")
|
||||
grab = False
|
||||
for line in text4.splitlines():
|
||||
if line.startswith("| 拓扑 | 模量前系数"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_t42_lines.append(line)
|
||||
if line.startswith("| OCT |"):
|
||||
break
|
||||
if old_t42_lines:
|
||||
E.append(("part4_结果与分析.md", "\n".join(old_t42_lines), new_t42))
|
||||
|
||||
# ---------- 表 4-6 方差贡献率 ----------
|
||||
new_t46 = (
|
||||
"| 因子 | 等效模量 | 峰值应力 | 比吸能 |\n|---|---|---|---|\n"
|
||||
f"| 相对密度 | **{p.loc['rd_code','E_meas']:.1f}** | "
|
||||
f"**{p.loc['rd_code','sigma_peak']:.1f}** | "
|
||||
f"**{p.loc['rd_code','SEA']:.1f}** |\n"
|
||||
f"| 打印角度 | {p.loc['a_code','E_meas']:.1f} | "
|
||||
f"{p.loc['a_code','sigma_peak']:.1f} | {p.loc['a_code','SEA']:.1f} |\n"
|
||||
f"| 拓扑 | {p.loc['topo_code','E_meas']:.1f} | "
|
||||
f"{p.loc['topo_code','sigma_peak']:.1f} | {p.loc['topo_code','SEA']:.1f} |\n"
|
||||
f"| 层厚 | {p.loc['t_code','E_meas']:.1f} | "
|
||||
f"{p.loc['t_code','sigma_peak']:.1f} | {p.loc['t_code','SEA']:.1f} |\n"
|
||||
f"| 交互(含三阶) | {p.loc['interaction','E_meas']:.1f} | "
|
||||
f"{p.loc['interaction','sigma_peak']:.1f} | {p.loc['interaction','SEA']:.1f} |")
|
||||
old_t46_lines = []
|
||||
grab = False
|
||||
for line in text4.splitlines():
|
||||
if line.startswith("| 因子 | 等效模量 | 峰值应力 | 比吸能 |"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_t46_lines.append(line)
|
||||
if line.startswith("| 交互"):
|
||||
break
|
||||
if old_t46_lines:
|
||||
E.append(("part4_结果与分析.md", "\n".join(old_t46_lines), new_t46))
|
||||
|
||||
# ---------- 表 4-7 响应面系数 ----------
|
||||
cn = {"常数项": "常数项", "rho_bar": "相对密度", "layer_h": "层厚",
|
||||
"raster": "打印角度", "rho_bar*layer_h": "相对密度 × 层厚",
|
||||
"rho_bar*raster": "相对密度 × 打印角度", "layer_h*raster": "层厚 × 打印角度",
|
||||
"rho_bar^2": "相对密度$^2$", "layer_h^2": "层厚$^2$", "raster^2": "打印角度$^2$"}
|
||||
rows7 = []
|
||||
for _, r in rs.iterrows():
|
||||
if r["term"] == "常数项":
|
||||
continue
|
||||
sig = "***" if r["p"] < 0.001 else ("*" if r["p"] < 0.05 else "不显著")
|
||||
coef = f"**{r['coef']:.3f}**" if r["p"] < 0.05 else f"{r['coef']:.3f}"
|
||||
rows7.append(f"| {cn.get(r['term'], r['term'])} | {coef} | {r['std_err']:.3f} | "
|
||||
f"{r['t']:.2f} | {r['p']:.3f} | {sig} |")
|
||||
new_t47 = ("| 项 | 系数 | 标准误 | $t$ 值 | $p$ 值 | 显著性 |\n|---|---|---|---|---|---|\n"
|
||||
+ "\n".join(rows7))
|
||||
old_t47_lines = []
|
||||
grab = False
|
||||
for line in text4.splitlines():
|
||||
if line.startswith("| 项 | 系数 | 标准误"):
|
||||
grab = True
|
||||
if grab:
|
||||
old_t47_lines.append(line)
|
||||
if line.startswith("| 打印角度$^2$") or line.startswith("| 打印角度²"):
|
||||
break
|
||||
if old_t47_lines:
|
||||
E.append(("part4_结果与分析.md", "\n".join(old_t47_lines), new_t47))
|
||||
|
||||
return E
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--apply", action="store_true")
|
||||
args = ap.parse_args()
|
||||
|
||||
edits = build_edits()
|
||||
if not edits:
|
||||
print("未识别到需要替换的表格")
|
||||
return 1
|
||||
for fname, old, new in edits:
|
||||
p = MAN / fname
|
||||
t = p.read_text(encoding="utf-8")
|
||||
c = t.count(old)
|
||||
print(f"\n{'='*70}\n{fname} 匹配 {c} 处\n{'='*70}")
|
||||
print("--- 旧 ---")
|
||||
print(old[:700])
|
||||
print("--- 新 ---")
|
||||
print(new[:700])
|
||||
if args.apply and c == 1:
|
||||
p.write_text(t.replace(old, new), encoding="utf-8", newline="\n")
|
||||
print(">>> 已写入")
|
||||
elif args.apply:
|
||||
print(">>> 跳过(匹配数不为 1,需人工处理)")
|
||||
if not args.apply:
|
||||
print("\n预览模式。加 --apply 实际写入。")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,265 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
参数不确定性与跨拓扑排序稳健性分析
|
||||
====================================
|
||||
|
||||
对应创新点 3:文献给出的跨拓扑性能排序多为**点估计**,未说明基体材料
|
||||
参数在文献分散区间内波动时排序是否翻转。本脚本用拉丁超立方抽样
|
||||
(Latin Hypercube Sampling, LHS)在文献参数区间内抽样,检验:
|
||||
|
||||
1. 性能量本身的分布区间(而非单点值);
|
||||
2. 拓扑排序的不变比例(排序一致性矩阵);
|
||||
3. 排序翻转的临界条件。
|
||||
|
||||
同时给出 Gibson-Ashby 幂律指数 n 的 95% 置信区间(对应创新点 2)。
|
||||
|
||||
用法:
|
||||
python code/uncertainty.py
|
||||
python code/uncertainty.py --n 4000 --seed 11
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from scipy import stats
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DATA = ROOT / "data"
|
||||
|
||||
# ----------------------------------------------------------------------------
|
||||
# 文献区间(每个参数给出下限 / 基准 / 上限)
|
||||
# 基准值与本项目主模型一致;上下限取自论文表 3-1 的文献分散区间。
|
||||
# ----------------------------------------------------------------------------
|
||||
PARAM_RANGES = {
|
||||
"E_s": (3000.0, 3500.0, 3600.0), # MPa 实体 PLA 弹性模量
|
||||
"sigma_ys": (50.0, 60.0, 70.0), # MPa 实体 PLA 屈服强度
|
||||
"rho_s": (1230.0, 1240.0, 1250.0), # kg/m3 实体 PLA 密度
|
||||
"C1": (0.20, 0.24, 0.36), # Gibson-Ashby 模量系数(作为各拓扑 C1 的乘性缩放)
|
||||
"f_bond_0": (0.80, 0.88, 0.95), # 固定工艺条件下的层间键合保留率
|
||||
"amp": (0.15, 0.22, 0.30), # 各向异性幅值
|
||||
}
|
||||
|
||||
TOPOLOGY = {
|
||||
"BCC": dict(eta=0.352, C1=0.24, C2=0.29),
|
||||
"FCC": dict(eta=0.500, C1=0.30, C2=0.36),
|
||||
"OCT": dict(eta=0.615, C1=0.36, C2=0.44),
|
||||
}
|
||||
ORDER = ["BCC", "FCC", "OCT"]
|
||||
|
||||
# 固定几何/工艺条件(不确定性分析的控制变量)
|
||||
RD = 0.20 # 相对密度
|
||||
T_LAYER = 0.15 # 层厚 mm
|
||||
RASTER = 0.0 # 打印角度 deg
|
||||
|
||||
|
||||
def latin_hypercube(n: int, d: int, rng: np.random.Generator) -> np.ndarray:
|
||||
"""标准 LHS:每维分层抽样后随机排列。返回 n x d 的 [0,1) 样本。"""
|
||||
cut = np.linspace(0.0, 1.0, n + 1)
|
||||
u = rng.uniform(size=(n, d))
|
||||
pts = cut[:n, None] + u * (cut[1:] - cut[:n])[:, None]
|
||||
for j in range(d):
|
||||
pts[:, j] = rng.permutation(pts[:, j])
|
||||
return pts
|
||||
|
||||
|
||||
def evaluate(theta: np.ndarray, n: int) -> pd.DataFrame:
|
||||
"""给定 LHS 样本,计算三种拓扑的等效模量、峰值应力与比强度。
|
||||
|
||||
抽样参数含义(列序):
|
||||
E_s, sigma_ys, rho_s, C1_scale, f_bond_0, amp
|
||||
|
||||
说明:本项目不确定性分析的控制变量为固定工艺条件(层厚 0.15 mm、
|
||||
打印角度 0°),因此不直接抽样"层厚-键合折减系数 kappa"(该系数仅在
|
||||
改变层厚时才起作用),而是抽样**该工艺条件下的层间键合保留率
|
||||
f_bond_0**,其区间 [0.80, 0.95] 对应文献报道的 FDM 层间强度相对
|
||||
本体强度的保留比例。
|
||||
"""
|
||||
E_s = theta[:, 0]; sig_ys = theta[:, 1]; rho_s = theta[:, 2]
|
||||
c1_scale = theta[:, 3]
|
||||
f_bond_0 = theta[:, 4]
|
||||
amp = theta[:, 5]
|
||||
|
||||
f_angle = 1.0 + amp * np.cos(np.deg2rad(2.0 * RASTER))
|
||||
|
||||
rows = []
|
||||
for topo in ORDER:
|
||||
tp = TOPOLOGY[topo]
|
||||
# 模量:层间键合对模量影响较弱(半权),对强度影响为全权
|
||||
e_eff = E_s * tp["C1"] * c1_scale * RD ** 2.0
|
||||
sig_eff = sig_ys * tp["C2"] * RD ** 1.5
|
||||
e_eff = e_eff * (0.5 + 0.5 * f_bond_0) * f_angle
|
||||
sig_eff = sig_eff * f_bond_0 * f_angle
|
||||
rho_app = RD * rho_s
|
||||
rows.append(pd.DataFrame(dict(
|
||||
sample=np.arange(n),
|
||||
topo=topo,
|
||||
E_eff=e_eff,
|
||||
sigma_eff=sig_eff,
|
||||
specific_modulus=e_eff * 1e3 / rho_app,
|
||||
specific_strength=sig_eff * 1e3 / rho_app,
|
||||
rho_app=rho_app,
|
||||
)))
|
||||
return pd.concat(rows, ignore_index=True)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--n", type=int, default=3000, help="LHS 样本数")
|
||||
ap.add_argument("--seed", type=int, default=2026)
|
||||
args = ap.parse_args()
|
||||
|
||||
rng = np.random.default_rng(args.seed)
|
||||
n = args.n
|
||||
|
||||
# --- LHS 抽样 ---
|
||||
keys = ["E_s", "sigma_ys", "rho_s", "C1", "f_bond_0", "amp"]
|
||||
U = latin_hypercube(n, len(keys), rng)
|
||||
theta = np.column_stack([
|
||||
PARAM_RANGES[k][0] + U[:, i] * (PARAM_RANGES[k][2] - PARAM_RANGES[k][0])
|
||||
for i, k in enumerate(keys)
|
||||
])
|
||||
|
||||
res = evaluate(theta, n)
|
||||
|
||||
# --- 1. 各性能量的分布区间 ---
|
||||
dist = res.groupby("topo").agg(
|
||||
E_mean=("E_eff", "mean"), E_lo=("E_eff", lambda s: np.percentile(s, 2.5)),
|
||||
E_hi=("E_eff", lambda s: np.percentile(s, 97.5)),
|
||||
sm_mean=("specific_modulus", "mean"),
|
||||
sm_lo=("specific_modulus", lambda s: np.percentile(s, 2.5)),
|
||||
sm_hi=("specific_modulus", lambda s: np.percentile(s, 97.5)),
|
||||
ss_mean=("specific_strength", "mean"),
|
||||
ss_lo=("specific_strength", lambda s: np.percentile(s, 2.5)),
|
||||
ss_hi=("specific_strength", lambda s: np.percentile(s, 97.5)),
|
||||
).reindex(ORDER).reset_index()
|
||||
|
||||
# --- 2. 排序一致性:对每个样本,检验三种拓扑的排名是否稳定 ---
|
||||
# 对两个性能指标分别做,避免只看一个指标就下"排序稳健"的结论
|
||||
order_rows = []
|
||||
consist_store = {}
|
||||
for metric in ["specific_strength", "specific_modulus"]:
|
||||
piv = res.pivot(index="sample", columns="topo", values=metric)[ORDER]
|
||||
rank = piv.rank(axis=1, ascending=False, method="min") # 1 = 最优
|
||||
for topo in ORDER:
|
||||
order_rows.append(dict(
|
||||
metric=metric, topology=topo,
|
||||
p_best=float((rank[topo] == 1).mean()),
|
||||
mean_rank=float(rank[topo].mean())))
|
||||
consist = pd.DataFrame(index=ORDER, columns=ORDER, dtype=float)
|
||||
for a in ORDER:
|
||||
for b in ORDER:
|
||||
consist.loc[a, b] = float((piv[a] > piv[b]).mean())
|
||||
consist_store[metric] = consist
|
||||
order_tbl = pd.DataFrame(order_rows)
|
||||
|
||||
# --- 3. 排序翻转临界条件:扫描 C1 缩放系数对排序的影响 ---
|
||||
# 说明:在基准参数下,三种拓扑的排序由各自 (C1, C2) 决定。由于基体
|
||||
# 参数(E_s、sigma_ys、rho_s、f_bond、f_angle)对三种拓扑是**共模**
|
||||
# 的,它们同步缩放不改变相对排序。能导致翻转的只有**拓扑相关的**
|
||||
# 几何系数不确定度。这里以 C1 的乘性缩放系数为扫描变量,检验"当某
|
||||
# 拓扑的几何系数被高估/低估到何种程度时,排序发生翻转",并把翻转
|
||||
# 所需的临界比值同时以解析式给出。
|
||||
flip_rows = []
|
||||
base = dict(E_s=3500.0, sigma_ys=60.0, rho_s=1240.0, f_bond_0=0.88, amp=0.22)
|
||||
for lo_topo, hi_topo in [("BCC", "FCC"), ("BCC", "OCT"), ("FCC", "OCT")]:
|
||||
grid = np.linspace(0.05, 4.0, 4001)
|
||||
prev = None
|
||||
found = False
|
||||
for cs in grid:
|
||||
th = np.array([[base["E_s"], base["sigma_ys"], base["rho_s"],
|
||||
cs, base["f_bond_0"], base["amp"]]])
|
||||
r = evaluate(th, 1)
|
||||
sm = dict(zip(r.topo, r.specific_strength))
|
||||
cur = sm[lo_topo] > sm[hi_topo]
|
||||
if prev is not None and cur != prev:
|
||||
flip_rows.append(dict(pair=f"{lo_topo}→{hi_topo}",
|
||||
c1_scale_flip=float(cs),
|
||||
note="C1 缩放低于此值时排序翻转"))
|
||||
found = True
|
||||
prev = cur
|
||||
if not found:
|
||||
# 解析给出:排序翻转需 C1_i/C1_j 越过的比值
|
||||
Ci = TOPOLOGY[lo_topo]["C1"] * TOPOLOGY[lo_topo]["C2"]
|
||||
Cj = TOPOLOGY[hi_topo]["C1"] * TOPOLOGY[hi_topo]["C2"]
|
||||
flip_rows.append(dict(pair=f"{lo_topo}→{hi_topo}",
|
||||
c1_scale_flip=np.nan,
|
||||
note=f"扫描区间内不翻转;需缩放系数 < {Cj/Ci:.3f}"
|
||||
f"(即几何系数比偏离基准 {abs(1-Cj/Ci)*100:.0f}% 以上)"))
|
||||
flip_tbl = pd.DataFrame(flip_rows)
|
||||
|
||||
# --- 4. Gibson-Ashby 幂律指数 n 的 95% 置信区间 ---
|
||||
design = pd.read_csv(DATA / "design_matrix.csv")
|
||||
base_df = design[design.group == "baseline"]
|
||||
ci_rows = []
|
||||
for topo in ORDER:
|
||||
g = base_df[base_df.topo == topo]
|
||||
x = np.log(g.rel_density.to_numpy())
|
||||
y = np.log(g.E_meas.to_numpy() / 3500.0)
|
||||
k = len(x)
|
||||
n_slope, intercept = np.polyfit(x, y, 1)
|
||||
y_hat = n_slope * x + intercept
|
||||
sse = float(np.sum((y - y_hat) ** 2))
|
||||
sxx = float(np.sum((x - x.mean()) ** 2))
|
||||
se = np.sqrt(sse / (k - 2) / sxx)
|
||||
tcrit = stats.t.ppf(0.975, df=k - 2)
|
||||
# 强度的幂指数
|
||||
ys = np.log(g.sigma_peak.to_numpy() / 60.0)
|
||||
ns, ints = np.polyfit(x, ys, 1)
|
||||
yh = ns * x + ints
|
||||
sse_s = float(np.sum((ys - yh) ** 2))
|
||||
se_s = np.sqrt(sse_s / (k - 2) / sxx)
|
||||
ci_rows.append(dict(
|
||||
topo=topo, n=n_slope, n_lo=n_slope - tcrit * se, n_hi=n_slope + tcrit * se,
|
||||
n_sigma=ns, n_sigma_lo=ns - tcrit * se_s, n_sigma_hi=ns + tcrit * se_s,
|
||||
df=k - 2))
|
||||
ci_tbl = pd.DataFrame(ci_rows)
|
||||
|
||||
# --- 落盘 ---
|
||||
dist.to_csv(DATA / "uncertainty_distribution.csv", index=False, encoding="utf-8-sig")
|
||||
order_tbl.to_csv(DATA / "uncertainty_ranking.csv", index=False, encoding="utf-8-sig")
|
||||
consist = consist_store["specific_strength"]
|
||||
consist.to_csv(DATA / "uncertainty_consistency.csv", encoding="utf-8-sig")
|
||||
consist_store["specific_modulus"].to_csv(
|
||||
DATA / "uncertainty_consistency_modulus.csv", encoding="utf-8-sig")
|
||||
ci_tbl.to_csv(DATA / "powerlaw_ci.csv", index=False, encoding="utf-8-sig")
|
||||
flip_tbl.to_csv(DATA / "ranking_flip.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
print("== 性能量分布区间(2.5%-97.5%)==")
|
||||
print(dist.round(2).to_string(index=False))
|
||||
print("\n== 排序:最优概率 ==")
|
||||
print(order_tbl.round(4).to_string(index=False))
|
||||
for metric in ["specific_strength", "specific_modulus"]:
|
||||
print(f"\n== 排序一致性矩阵 P(行>列) · {metric} ==")
|
||||
print(consist_store[metric].round(3).to_string())
|
||||
print("\n== 幂律指数 95% 置信区间 ==")
|
||||
print(ci_tbl.round(4).to_string(index=False))
|
||||
print("\n== 排序翻转临界点 ==")
|
||||
print(flip_tbl.to_string(index=False) if len(flip_tbl) else "(区间内未发生翻转)")
|
||||
|
||||
man = dict(
|
||||
n_samples=int(n), seed=int(args.seed),
|
||||
param_ranges={k: list(v) for k, v in PARAM_RANGES.items()},
|
||||
fixed=dict(rel_density=RD, layer_h=T_LAYER, raster=RASTER),
|
||||
files={},
|
||||
)
|
||||
for f in ["uncertainty_distribution.csv", "uncertainty_ranking.csv",
|
||||
"uncertainty_consistency.csv", "uncertainty_consistency_modulus.csv",
|
||||
"powerlaw_ci.csv", "ranking_flip.csv"]:
|
||||
p = DATA / f
|
||||
man["files"][f] = dict(sha256=hashlib.sha256(p.read_bytes()).hexdigest(),
|
||||
bytes=p.stat().st_size)
|
||||
(DATA / "MANIFEST_uncertainty.json").write_text(
|
||||
json.dumps(man, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""统计各章节中文字数与图表引用情况(第 20 步总检用)。"""
|
||||
import re
|
||||
import glob
|
||||
import os
|
||||
import sys
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
MAN = os.path.join(ROOT, "manuscript")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
total = 0
|
||||
print(f"{'文件':<34}{'中文字符':>10}{'图':>5}{'表':>5}")
|
||||
print("-" * 56)
|
||||
fig_all, tab_all = [], []
|
||||
for f in sorted(glob.glob(os.path.join(MAN, "*.md"))):
|
||||
t = open(f, encoding="utf-8").read()
|
||||
body = re.sub(r"!\[.*?\]\(.*?\)", "", t)
|
||||
cjk = len(re.findall(r"[\u4e00-\u9fff]", body))
|
||||
figs = re.findall(r"!\[[^\]]*\]\(figures/fig([\d\-]+)_", t)
|
||||
tabs = re.findall(r"\*\*表 ([\d\-]+)", t)
|
||||
total += cjk
|
||||
fig_all += figs
|
||||
tab_all += tabs
|
||||
print(f"{os.path.basename(f):<34}{cjk:>10}{len(figs):>5}{len(tabs):>5}")
|
||||
print("-" * 56)
|
||||
print(f"{'合计':<34}{total:>10}{len(fig_all):>5}{len(tab_all):>5}")
|
||||
print()
|
||||
print("图片引用顺序:", " ".join(fig_all))
|
||||
dup = [x for x in set(fig_all) if fig_all.count(x) > 1]
|
||||
if dup:
|
||||
print("!! 重复引用的图:", dup)
|
||||
# 图号连续性
|
||||
nums = sorted({float(x.split("-")[1]) for x in fig_all})
|
||||
print("图编号集合:", nums)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in new issue
Block a user