| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502 |
- """按《风电机组可靠性和能效双提升数据分析报告》模板重组 Word 报告。
- 现有 collector 已提供:概览(发电量/风速/完整率)、健康评估、故障、振动。
- 本构建器把这些数据映射到模板章节;模板中的偏航/功率曲线等专项数据若未接入,
- 明确写“本期未接入”,不编造结论。
- """
- from __future__ import annotations
- import os
- from typing import Any, Dict, List, Optional
- from docx import Document
- from docx.enum.text import WD_ALIGN_PARAGRAPH
- from docx.shared import Cm, Pt
- from app.report import docx_builder as L
- def _num(v, digits=2, suffix=""):
- if v is None:
- return "—"
- try:
- return f"{float(v):,.{digits}f}{suffix}"
- except (TypeError, ValueError):
- return f"{v}{suffix}"
- def _period_text(v):
- if isinstance(v, (list, tuple)):
- if len(v) == 1:
- return str(v[0])
- if len(v) >= 2:
- return f"{v[0]} 至 {v[-1]}"
- return str(v) if v not in (None, "") else "—"
- def _section_summary(doc, data: Dict[str, Any]):
- L._heading(doc, "摘 要", 1)
- w, ov = data["wind"], data.get("overview") or {}
- L._para(
- doc,
- f"本报告以{w.get('name')}为分析对象,分析时段为"
- f"{data['period']['start']} 至 {data['period']['end']}。"
- "报告围绕风资源与发电性能、设备可靠性、机组潜在风险及功率曲线等维度开展分析,"
- "识别影响机组可靠性和能效的主要问题,并提出针对性的检查与治理建议。",
- )
- h = data.get("health") or {}
- if h.get("available"):
- L._para(
- doc,
- f"健康评估覆盖 {len(h.get('turbines') or [])} 台机组,平均健康得分 "
- f"{_num(h.get('avg_score'), 2)}。报告对低分机组及其发电子系统、机舱系统、"
- "电网环境和传动系统进行了重点识别。",
- )
- f = data.get("fault") or {}
- if f.get("available"):
- L._para(
- doc,
- f"故障统计共记录 {f.get('total', 0)} 次,影响 {f.get('affected_turbines', 0)} 台机组;"
- "报告对高频故障码和故障集中机组进行了分析。",
- )
- L._para(
- doc,
- "本报告的数字、图表与统计结果由系统按既定口径计算;受数据接入范围、测点配置和现场记录完整性限制,"
- "结论应作为运维分析参考,需经专业技术人员复核后使用。",
- )
- def _section_preface(doc, data: Dict[str, Any]):
- w = data["wind"]
- L._heading(doc, "1 前言", 1)
- L._heading(doc, "1.1 风场情况", 2)
- L._table(
- doc,
- ["项目", "内容"],
- [
- ["风电场名称", w.get("name")],
- ["所属单位", w.get("company") or "—"],
- ["装机容量", _num((w.get("capacity_kw") or 0) / 1000, 2, " MW")],
- ["机组数量", f"{w.get('turbine_count', 0)} 台"],
- ["分析时段", f"{data['period']['start']} 至 {data['period']['end']}"],
- ],
- [4.0, 11.0],
- )
- L._para(
- doc,
- f"基于{w.get('name')}在平台四个页面展示的数据(分析概览、健康评估、算法健康评估、故障诊断、振动分析),"
- "对机位风资源、发电量、设备可靠性、机组潜在风险和功率曲线进行分析,"
- "为场站可靠性和能效提升提供数据依据。",
- )
- L._heading(doc, "1.2 分析思路", 2)
- L._para(doc, "风电场能效不及预期,可能存在的问题主要包括以下四个方面:")
- for t in (
- "一是风资源条件与可研设计存在偏差,通常需要较大投入的技改才能提升;",
- "二是限电比例较高,由当地电网及政策决定,不计入场站考核;",
- "三是设备可靠性不足,故障停机、亚健康限功率运行和隐性问题造成电量损失;",
- "四是机组功率曲线偏离设计水平,机组间一致性差,需要通过维护和整机优化改善。",
- ):
- L._para(doc, f"· {t}", indent=False, size=10)
- L._para(
- doc,
- "本报告结合平台页面同源数据,依次开展数据质量检查、"
- "能效分析、设备可靠性分析、潜在风险评估和功率曲线分析,并给出结论与建议。",
- )
- L._heading(doc, "1.3 相关说明", 2)
- L._para(
- doc,
- "本报告为场站级运行数据分析报告。报告只读取平台页面同源数据:分析概览读取分析批次文件,"
- "健康评估读取健康评估接口,算法健康评估读取算法健康评估接口,故障诊断读取诊断结果,振动分析读取 CMS 波形;未接入的专项数据在对应章节中明确标注,"
- "不以推测替代实测。",
- )
- def _section_standards(doc):
- L._heading(doc, "2 依据标准", 1)
- L._para(doc, "下列文件对于本报告的应用是必不可少的,但不限于这些。引用文件以最新版本适用于本报告。")
- standards = [
- "IEC 61400-12-1:2017《风力发电机组功率曲线测试》",
- "IEC 61400-12-2:2013《基于机舱风速计的风力发电机组功率曲线测试》",
- "IEC 61400-26-2:2014《基于发电量的可利用率》",
- "IEC 61400-1:2005《风力发电机组设计要求》",
- "GB/T 18451.2-2012《风力发电机组功率特性测试》",
- "GB/T 19960.2-2005《风力发电机组 第2部分:通用试验方法》",
- "GB/T 20319-2006《风力发电机组验收规范》",
- "GB/T 18710-2002《风电场风能资源评估方法》",
- "DL/T 793-2012《发电设备可靠性评价规程》",
- "NB/T 31045-2013《风电场运行指标与评价导则》",
- "《中国华电集团有限公司风电与光伏发电设备退出质保期管理办法》",
- "《中国华电集团有限公司防止风电机组重大设备事故技术要求》",
- ]
- for s in standards:
- L._para(doc, f"· {s}", indent=False, size=9.5)
- def _section_data_collection(doc, data: Dict[str, Any], tmp: str):
- w = data["wind"]
- ov = data.get("overview") or {}
- L._heading(doc, "3 数据收集", 1)
- L._heading(doc, "3.1 数据收集情况", 2)
- L._para(doc, f"{w.get('name')}提供的数据及接入情况汇总见表 3-1。")
- L._table(
- doc,
- ["数据类别", "来源/表", "本期状态", "用途"],
- [
- ["台账数据", "wind_field / wind_engine_group", "已接入", "风场、机组、机型与容量"],
- ["分钟级 SCADA", f"{w.get('code')}_minute", "已接入" if ov.get("available") else "不足", "发电量、风速、功率、完整率"],
- ["健康评估", "健康评估模型", "已接入" if (data.get("health") or {}).get("available") else "不足", "机组与子系统健康得分"],
- ["故障日志", f"{w.get('code')}_fault", "已接入" if (data.get("fault") or {}).get("available") else "不足", "故障次数、故障码与影响机组"],
- ["CMS 振动", f"{w.get('code')}_wave", "已接入" if (data.get("vibration") or {}).get("available") else "不足", "测点覆盖、采样频率与频谱"],
- ["秒级 SCADA", "标准秒级表", "按场站接入情况", "偏航/变桨/功率曲线专项分析"],
- ["偏航误差专项", "偏航误差计算结果", "本期未接入", "静态/动态偏航误差分析"],
- ],
- [3.8, 7.0, 2.8, 3.4],
- )
- prov = data.get("provenance") or {}
- if prov:
- L._para(
- doc,
- f"本报告只使用 {data['period']['start']} 至 {data['period']['end']} 的数据,"
- "四个数据页面与报告采用同一时间段口径,来源如下:",
- )
- rows = [
- [v.get("page"), v.get("source"), _period_text(v.get("period")), v.get("filter")]
- for v in prov.values()
- ]
- L._table(doc, ["数据页面", "来源", "时间段", "口径"], rows, [3.2, 7.2, 3.0, 5.0])
- L._heading(doc, "3.2 数据质量分析", 2)
- if ov.get("available"):
- L._para(doc, f"分钟级数据完整率约 {_num(ov.get('completeness'), 2, '%')}。各月数据质量见表 3-2。")
- rows = [
- [m.get("month"), _num(m.get("gen_mwh"), 2), _num(m.get("avg_wind"), 2), _num(m.get("completeness"), 2, "%")]
- for m in ov.get("monthly", [])
- ]
- if rows:
- L._table(doc, ["月份", "发电量(MWh)", "平均风速(m/s)", "完整率"], rows, [3.2, 4.2, 4.2, 3.4])
- else:
- L._para(doc, f"分钟级数据不足:{ov.get('error', '未取得有效记录')}。")
- for key, label in (("health", "健康评估"), ("fault", "故障日志"), ("vibration", "振动波形")):
- sec = data.get(key) or {}
- if not sec.get("available"):
- L._para(doc, f"· {label}:{sec.get('error', '未取得有效记录')}。", indent=False, size=10)
- def _render_yaw(doc, data: Dict[str, Any]):
- y = data.get("yaw") or {}
- L._heading(doc, "4.2 偏航误差分析", 2)
- if not y.get("available"):
- L._para(
- doc,
- "偏航误差包括静态偏航误差和动态偏航误差。本期页面无静态偏航误差专项结果,"
- "因此不对具体机组偏航误差数值作出判断。",
- )
- return
- L._para(
- doc,
- f"本期静态偏航误差按机组统计,平均绝对偏航误差 {_num(y.get('avg_abs'), 2, '°')};"
- f"绝对偏航误差 >3° 的机组 {y.get('over3', 0)} 台,>5° 的机组 {y.get('over5', 0)} 台。"
- f"按模板判据,±3° 以内为可接受范围,超过 3° 建议校正。",
- )
- rows = []
- for t in (y.get("turbines") or [])[:10]:
- rows.append([t.get("name"), _num(t.get("avg"), 2), _num(t.get("abs_avg"), 2), _num(t.get("abs_max"), 2)])
- if rows:
- L._table(doc, ["机组", "平均偏航误差(°)", "平均绝对误差(°)", "最大绝对误差(°)"], rows, [4.0, 3.6, 3.6, 3.6])
- if y.get("over3_list"):
- L._para(doc, f"绝对偏航误差 >3° 的机组:{'、'.join(y['over3_list'])}。", indent=False, size=10)
- if y.get("over5_list"):
- L._para(doc, f"绝对偏航误差 >5° 的机组:{'、'.join(y['over5_list'])};建议优先校正,校正后积累 2~3 周数据复核。", indent=False, size=10)
- def _section_energy(doc, data: Dict[str, Any], tmp: str):
- L._heading(doc, "4 能效分析", 1)
- L._para(doc, "本节通过偏航误差分析,对风电场的能效情况进行分析。")
- _render_yaw(doc, data)
- def _section_reliability(doc, data: Dict[str, Any], tmp: str):
- h = data.get("health") or {}
- f = data.get("fault") or {}
- L._heading(doc, "5 设备可靠性分析", 1)
- L._para(doc, "本节通过故障统计和健康评估结果,对风电场设备可靠性情况进行分析。")
- L._heading(doc, "5.1 故障分析", 2)
- if not f.get("available"):
- L._para(doc, f"故障日志数据不足:{f.get('error', '未取得有效记录')}。")
- else:
- L._table(doc, ["指标", "数值"], [["故障总次数", f.get("total")], ["影响机组数", f.get("affected_turbines")]], [5.0, 9.0])
- _page_image(doc, data, "fault", "图 5-1 故障诊断页面图")
- rows = [[c.get("code"), c.get("count"), c.get("turbines")] for c in f.get("top_codes", [])]
- if rows:
- L._table(doc, ["故障码", "次数", "影响机组数"], rows, [8.0, 3.0, 4.0])
- L._heading(doc, "5.2 大部件温度异常检测", 2)
- if not h.get("available"):
- L._para(doc, f"健康评估数据不足:{h.get('error', '未取得有效记录')}。")
- else:
- sub = h.get("subsystems") or {}
- L._table(
- doc,
- ["子系统", "平均得分", "关注点"],
- [
- ["发电机组", _num(sub.get("generator"), 2), "绕组、轴承温度与电气量"],
- ["机舱系统", _num(sub.get("nacelle"), 2), "机舱振动、温度与位置"],
- ["电网环境", _num(sub.get("grid"), 2), "电流、功率与并网质量"],
- ["传动系统", _num(sub.get("drive_train"), 2), "主轴承、齿轮箱温度"],
- ],
- [4.5, 4.0, 8.0],
- )
- L._para(
- doc,
- "大部件温度异常检测需要温度测点与工况数据的完整配对。本期健康评估已对发电机、机舱、"
- "电网环境和传动系统给出综合得分;具体温度偏差、温升趋势和传感器可信度仍需结合专项温度分析复核。",
- )
- L._heading(doc, "5.3 算法健康评估", 2)
- ah = data.get("algorithm_health") or {}
- if not ah.get("available"):
- L._para(doc, f"算法健康评估页面数据不足:{ah.get('error', '未取得有效结果')}。")
- else:
- L._para(
- doc,
- f"算法健康评估期次 {ah.get('period')},生成时间 {ah.get('generated_at')},"
- f"共评估 {len(ah.get('turbines') or [])} 台机组。总分按可评系统数是否达到适用系统半数决定;"
- "未达半数时总分显示为未评估。",
- )
- rows = []
- for t in (ah.get("turbines") or [])[:20]:
- ov = t.get("overall") or {}
- systems = t.get("systems") or []
- scored = sum(1 for s in systems if s.get("status") == "scored")
- applicable = sum(1 for s in systems if s.get("status") != "not_applicable")
- reason = (ov.get("reasons") or [{}])[0].get("text", "")
- rows.append([
- t.get("turbine_name") or t.get("turbine"),
- ov.get("score") if ov.get("status") == "scored" else "未评估",
- f"{scored}/{applicable}",
- reason,
- ])
- if rows:
- L._table(doc, ["机组", "总分", "可评分系统", "未评估原因"], rows, [4.0, 2.6, 3.4, 6.0])
- def _section_risk(doc, data: Dict[str, Any], tmp: str):
- h = data.get("health") or {}
- v = data.get("vibration") or {}
- L._heading(doc, "6 机组设备潜在风险评估", 1)
- L._para(doc, "本节结合健康评估、故障记录和振动波形,对机组潜在风险进行分析。")
- L._heading(doc, "6.1 主控系统分析", 2)
- L._para(
- doc,
- "主控系统风险应结合变桨-转速协调、转速-功率协调和控制参数一致性判断。"
- "本期报告已纳入健康评估中的电网环境与机舱系统得分,但未单独接入主控系统专项分析结果,"
- "相关结论需结合现场控制参数核查。",
- )
- L._heading(doc, "6.2 变桨系统分析", 2)
- L._para(
- doc,
- "变桨系统重点关注三叶桨距一致性、变桨速率、变桨电机温度及后备电源状态。"
- "本期数据未形成独立的变桨系统评分,暂不给出具体机组结论;建议补充变桨专项数据后开展。",
- )
- L._heading(doc, "6.3 偏航系统分析", 2)
- L._para(
- doc,
- "偏航系统重点关注静态/动态偏航误差、偏航频次、偏航刹车和扭缆状态。"
- "本期偏航误差专项结果未接入,暂不给出具体机组偏航误差数值,建议后续补充。",
- )
- L._heading(doc, "6.4 传动链分析", 2)
- if h.get("available"):
- sub = h.get("subsystems") or {}
- L._para(
- doc,
- f"传动系统平均健康得分 {_num(sub.get('drive_train'), 2)}。"
- "传动链风险需结合主轴承、齿轮箱温度、振动频谱和润滑状态综合判断。",
- )
- lows = [t for t in (h.get("low_turbines") or []) if (t.get("drive_train") or -1) >= 0][:8]
- if lows:
- rows = [[t.get("name"), _num(t.get("score"), 2), _num(t.get("drive_train"), 2)] for t in lows]
- L._table(doc, ["机组", "总分", "传动系统得分"], rows, [5.0, 4.0, 5.0])
- else:
- L._para(doc, "健康评估数据不足,暂不开展传动链风险排序。")
- L._heading(doc, "6.5 振动分析", 2)
- if not v.get("available"):
- L._para(doc, f"振动波形数据不足:{v.get('error', '未取得有效记录')}。")
- else:
- L._table(
- doc,
- ["指标", "数值"],
- [
- ["波形记录数", v.get("total")],
- ["覆盖机组数", v.get("turbine_count")],
- ["测点数", v.get("point_count")],
- ],
- [5.0, 9.0],
- )
- _page_image(doc, data, "vibration", "图 6-1 振动分析页面频谱图")
- L._para(
- doc,
- "上图为振动分析页面实际频谱图,报告不再使用重绘频谱,保证与页面展示一致。"
- "部件级诊断需结合轴承特征频率与历史趋势复核。",
- )
- def _section_power_curve(doc, data: Dict[str, Any]):
- L._heading(doc, "7 机组功率曲线分析", 1)
- L._para(
- doc,
- "功率曲线分析应基于机组风速-功率散点、合同功率曲线和机舱传递函数,对机组发电性能与一致性进行评价。"
- "本期报告使用分析概览页面有功功率曲线原图,确保与页面展示一致。",
- )
- _page_image(doc, data, "overview", "图 7-1 分析概览页面有功功率曲线")
- def _worst_subsystem(t: Dict[str, Any]) -> str:
- labels = {
- "generator": "发电机系统",
- "nacelle": "机舱系统",
- "grid": "电网环境",
- "drive_train": "传动系统",
- }
- vals = []
- for k, name in labels.items():
- v = t.get(k)
- try:
- v = float(v)
- except (TypeError, ValueError):
- v = None
- if v is not None and v >= 0:
- vals.append((v, name))
- if not vals:
- return "未评估"
- vals.sort(key=lambda x: x[0])
- return vals[0][1]
- def _section_conclusion(doc, data: Dict[str, Any]):
- from app.report import criteria
- L._heading(doc, "8 结论及建议", 1)
- cr = criteria.build_criteria(data)
- L._heading(doc, "8.1 判据", 2)
- L._table(
- doc,
- ["维度", "判据", "阈值", "本期值", "判定"],
- [[r["dim"], r["criterion"], r["threshold"], r["value"], r["verdict"]] for r in cr["rows"]],
- [2.4, 6.0, 2.4, 2.6, 2.0],
- )
- L._heading(doc, "8.2 结论", 2)
- for i, c in enumerate(cr["conclusions"], 1):
- L._para(doc, f"{i}. {c}", indent=False)
- # 重点机组与部件定位
- L._para(doc, "重点机组定位:", indent=False, bold=True)
- ov = data.get("overview") or {}
- h = data.get("health") or {}
- f = data.get("fault") or {}
- ah = data.get("algorithm_health") or {}
- if ov.get("available") and ov.get("turbines"):
- low_eff = sorted(ov["turbines"], key=lambda x: x.get("gen_mwh") or 0)[:5]
- names = "、".join(
- f"{t.get('name') or t.get('code')}({_num(t.get('gen_mwh'), 2, ' MWh')})" for t in low_eff
- )
- L._para(doc, f"· 能效低机组(发电量排名末 5):{names}。", indent=False, size=10)
- if h.get("available") and h.get("turbines"):
- ranked = sorted(
- [t for t in h["turbines"] if (t.get("score") or -1) >= 0],
- key=lambda x: x.get("score") or 0,
- )[:5]
- if ranked:
- items = []
- for t in ranked:
- items.append(f"{t.get('name') or t.get('code')}({_num(t.get('score'), 2, ' 分')},{_worst_subsystem(t)})")
- L._para(doc, f"· 健康重点关注机组(得分最低 5 台):{';'.join(items)}。", indent=False, size=10)
- if f.get("available") and f.get("turbines"):
- ft = sorted(f["turbines"], key=lambda x: x.get("count") or 0, reverse=True)[:8]
- names = "、".join(f"{t.get('name') or t.get('code')}({t.get('count', 0)} 次)" for t in ft)
- L._para(doc, f"· 故障集中机组:{names}。", indent=False, size=10)
- if ah.get("available"):
- unscored = [t for t in (ah.get("turbines") or []) if (t.get("overall") or {}).get("status") != "scored"]
- if unscored:
- names = "、".join(t.get("turbine_name") or t.get("turbine") or "" for t in unscored[:10])
- L._para(doc, f"· 算法健康评估未评总分机组:{names}。", indent=False, size=10)
- L._heading(doc, "8.3 建议", 2)
- for i, s in enumerate(cr["suggestions"], 1):
- L._para(doc, f"{i}. {s}", indent=False, size=10)
- summary = data.get("llm_conclusion") or " ".join(cr["conclusions"])
- L._heading(doc, "8.4 结论综述", 2)
- L._para(doc, summary, indent=False)
- def _page_image(doc, data: Dict[str, Any], key: str, caption: str):
- paths = (data.get("page_charts") or {}).get(key) or []
- for path in paths[:1]:
- L._image(doc, path, caption)
- def _section_page_images(doc, data: Dict[str, Any]):
- charts = data.get("page_charts") or {}
- labels = {
- "overview": "分析概览页面",
- "health": "健康评估页面",
- "algorithm_health": "算法健康评估页面",
- "fault": "故障诊断页面",
- "vibration": "振动分析页面",
- }
- if not charts:
- return
- L._heading(doc, "附录 页面原图", 1)
- L._para(doc, "以下为报告生成时从健康度检测平台五个功能页面抓取的原图,与报告数据同源。")
- for key, label in labels.items():
- for path in charts.get(key) or []:
- L._image(doc, path, f"{label} 原图")
- def build_template_report(data: Dict[str, Any], tmp_dir: str, output_path: str,
- title: Optional[str] = None, sections: Optional[List[str]] = None):
- os.makedirs(tmp_dir, exist_ok=True)
- os.makedirs(os.path.dirname(output_path), exist_ok=True)
- doc = Document()
- section = doc.sections[0]
- section.top_margin = Cm(2.2)
- section.bottom_margin = Cm(2.2)
- section.left_margin = Cm(2.6)
- section.right_margin = Cm(2.6)
- L._setup_header_footer(doc)
- normal = doc.styles["Normal"]
- normal.font.name = "微软雅黑"
- normal.font.size = Pt(10.5)
- normal._element.rPr.rFonts.set(L.qn("w:eastAsia"), "微软雅黑")
- report_title = title or f"{data['wind']['name']}风电机组可靠性和能效双提升数据分析报告"
- L._cover(doc, report_title, data)
- L._statement(doc)
- L._toc(doc, [
- "摘 要",
- "1 前言",
- "2 依据标准",
- "3 数据收集",
- "4 能效分析",
- "5 设备可靠性分析",
- "6 机组设备潜在风险评估",
- "7 机组功率曲线分析",
- "8 结论及建议",
- "附录 数据与模型说明",
- ])
- _section_summary(doc, data)
- _section_preface(doc, data)
- _section_standards(doc)
- _section_data_collection(doc, data, tmp_dir)
- _section_energy(doc, data, tmp_dir)
- _section_reliability(doc, data, tmp_dir)
- _section_risk(doc, data, tmp_dir)
- _section_power_curve(doc, data)
- _section_conclusion(doc, data)
- L._appendix(doc, data)
- doc.core_properties.title = report_title
- doc.core_properties.author = L.HEADER_TEXT
- doc.core_properties.subject = f"{data['wind']['name']} {data['period']['start']} 至 {data['period']['end']}"
- doc.save(output_path)
- return output_path
|