enrich_report_extra.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. """为报告补充模板要求但尚未使用的分析图(一次性脚本)。
  2. 从七台河分钟/CMS 数据生成偏航、完整度、风资源、温度、变桨/转速/功率、Cp/TSR、
  3. 环境温度、最小桨距角、振动时域/包络等图,并追加到报告 docx。
  4. """
  5. from __future__ import annotations
  6. import json
  7. import math
  8. import os
  9. from pathlib import Path
  10. import matplotlib
  11. matplotlib.use("Agg")
  12. import matplotlib.pyplot as plt
  13. import numpy as np
  14. import pymysql
  15. from docx import Document
  16. from docx.shared import Inches, Pt
  17. from docx.enum.text import WD_ALIGN_PARAGRAPH
  18. plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial Unicode MS"]
  19. plt.rcParams["axes.unicode_minus"] = False
  20. DATA = dict(host="106.120.102.238", port=10336, user="root", password="admin123456",
  21. database="energy_data_prod", charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor)
  22. WIND = "WOF046400029"
  23. TABLE = f"`{WIND}_minute`"
  24. OUT = Path(r"E:\WorkSpace\SourceCode\algorithm_ai\Analysis_Multi\output\reports\extra_charts")
  25. OUT.mkdir(parents=True, exist_ok=True)
  26. def q(sql, args=None):
  27. con = pymysql.connect(**DATA)
  28. try:
  29. with con.cursor() as cur:
  30. cur.execute(sql, args or ())
  31. return cur.fetchall()
  32. finally:
  33. con.close()
  34. def save(fig, name):
  35. p = OUT / f"{name}.png"
  36. fig.tight_layout()
  37. fig.savefig(p, dpi=150)
  38. plt.close(fig)
  39. return str(p)
  40. def chart_yaw():
  41. rows = q(f"SELECT yaw_error1 y FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND yaw_error1 IS NOT NULL LIMIT 200000")
  42. y = np.array([float(r["y"]) for r in rows])
  43. fig, ax = plt.subplots(figsize=(7, 3.6))
  44. ax.hist(y, bins=60, range=(-30, 30), color="#3d7bd6", edgecolor="white")
  45. ax.axvline(-3, color="orange", ls="--", lw=1)
  46. ax.axvline(3, color="orange", ls="--", lw=1)
  47. ax.set_title("静态偏航误差分布(±3° 为可接受范围)")
  48. ax.set_xlabel("偏航误差(°)")
  49. ax.set_ylabel("记录数")
  50. p1 = save(fig, "yaw_hist")
  51. over3 = float(np.mean(np.abs(y) > 3) * 100)
  52. over5 = float(np.mean(np.abs(y) > 5) * 100)
  53. fig, ax = plt.subplots(figsize=(5.5, 3.2))
  54. ax.bar(["|误差|≤3°", "3°<|误差|≤5°", "|误差|>5°"],
  55. [100 - over3, max(0, over3 - over5), over5],
  56. color=["#2e8b57", "#f0ad4e", "#d9534f"])
  57. ax.set_ylabel("记录占比(%)")
  58. ax.set_title("偏航误差绝对值区间占比")
  59. p2 = save(fig, "yaw_bins")
  60. return p1, p2, over3, over5
  61. def chart_integrity():
  62. rows = q(f"SELECT `year_month` ym, COUNT(*) n FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 GROUP BY `year_month` ORDER BY ym")
  63. labels, vals = [], []
  64. for r in rows:
  65. ym = str(r["ym"]); y, m = int(ym[:4]), int(ym[4:])
  66. import calendar
  67. exp = calendar.monthrange(y, m)[1] * 1440 * 33
  68. labels.append(f"{y}-{m:02d}")
  69. vals.append(round(r["n"] / exp * 100, 2))
  70. fig, ax = plt.subplots(figsize=(7, 3.4))
  71. ax.bar(labels, vals, color="#3d7bd6")
  72. ax.set_ylabel("分钟数据完整率(%)")
  73. ax.set_title("月度分钟级数据完整率")
  74. ax.tick_params(axis="x", rotation=45)
  75. return save(fig, "integrity")
  76. def chart_wind():
  77. rows = q(f"SELECT wind_velocity v, true_wind_direction d FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND wind_velocity IS NOT NULL AND true_wind_direction IS NOT NULL LIMIT 200000")
  78. v = np.array([float(r["v"]) for r in rows])
  79. d = np.radians(np.array([float(r["d"]) for r in rows]))
  80. fig, ax = plt.subplots(figsize=(6.2, 3.4))
  81. ax.hist(v, bins=40, color="#2e8b57", edgecolor="white")
  82. ax.set_xlabel("风速(m/s)")
  83. ax.set_ylabel("记录数")
  84. ax.set_title("风速频率分布")
  85. p1 = save(fig, "wind_freq")
  86. fig = plt.figure(figsize=(5, 5))
  87. ax = fig.add_subplot(111, projection="polar")
  88. ax.hist(d, bins=36, color="#3d7bd6", alpha=0.8)
  89. ax.set_title("风向玫瑰图")
  90. p2 = save(fig, "wind_rose")
  91. return p1, p2
  92. def chart_temp_power():
  93. rows = q(f"""SELECT active_power p, gearbox_high_speed_shaft_bearing_temperature t1,
  94. generatordrive_end_bearing_temperature t2, generatornon_drive_end_bearing_temperature t3
  95. FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>0
  96. AND gearbox_high_speed_shaft_bearing_temperature IS NOT NULL LIMIT 30000""")
  97. p = np.array([float(r["p"]) for r in rows])
  98. t1 = np.array([float(r["t1"]) for r in rows])
  99. t2 = np.array([float(r["t2"]) for r in rows])
  100. t3 = np.array([float(r["t3"]) for r in rows])
  101. fig, ax = plt.subplots(figsize=(6.2, 3.4))
  102. ax.scatter(p, t1, s=3, alpha=0.25, color="#d9534f")
  103. ax.set_xlabel("有功功率(kW)")
  104. ax.set_ylabel("齿轮箱高速轴轴承温度(℃)")
  105. ax.set_title("齿轮箱高速轴轴承温度 vs 功率")
  106. p1 = save(fig, "gearbox_temp_power")
  107. fig, axs = plt.subplots(1, 2, figsize=(9, 3.4))
  108. axs[0].scatter(p, t2, s=3, alpha=0.25, color="#3d7bd6")
  109. axs[0].set_title("发电机驱动端轴承温度 vs 功率")
  110. axs[0].set_xlabel("功率(kW)"); axs[0].set_ylabel("温度(℃)")
  111. axs[1].scatter(p, t3, s=3, alpha=0.25, color="#2e8b57")
  112. axs[1].set_title("发电机非驱动端轴承温度 vs 功率")
  113. axs[1].set_xlabel("功率(kW)"); axs[1].set_ylabel("温度(℃)")
  114. p2 = save(fig, "gen_temp_power")
  115. return p1, p2
  116. def chart_pitch_speed_power():
  117. rows = q(f"""SELECT active_power p, generator_speed s,
  118. (pitch_angle_blade_1+pitch_angle_blade_2+pitch_angle_blade_3)/3 pitch
  119. FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>=0
  120. AND generator_speed IS NOT NULL LIMIT 30000""")
  121. p = np.array([float(r["p"]) for r in rows])
  122. s = np.array([float(r["s"]) for r in rows])
  123. pitch = np.array([float(r["pitch"]) for r in rows])
  124. fig, axs = plt.subplots(1, 3, figsize=(12, 3.4))
  125. axs[0].scatter(pitch, s, s=3, alpha=0.2); axs[0].set_title("变桨-转速协调"); axs[0].set_xlabel("桨距角(°)"); axs[0].set_ylabel("发电机转速(rpm)")
  126. axs[1].scatter(pitch, p, s=3, alpha=0.2); axs[1].set_title("变桨-功率协调"); axs[1].set_xlabel("桨距角(°)"); axs[1].set_ylabel("功率(kW)")
  127. axs[2].scatter(s, p, s=3, alpha=0.2); axs[2].set_title("转速-功率协调"); axs[2].set_xlabel("发电机转速(rpm)"); axs[2].set_ylabel("功率(kW)")
  128. return save(fig, "pitch_speed_power")
  129. def chart_cp_tsr():
  130. rows = q(f"""SELECT active_power p, wind_velocity v, rotor_speed r
  131. FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>0
  132. AND wind_velocity BETWEEN 3 AND 20 AND rotor_speed>0 LIMIT 30000""")
  133. p = np.array([float(r["p"]) for r in rows]) * 1000
  134. v = np.array([float(r["v"]) for r in rows])
  135. r = np.array([float(r["r"]) for r in rows])
  136. cp = p / (0.5 * 1.225 * math.pi * 60 ** 2 * v ** 3)
  137. tsr = (r * 2 * math.pi / 60) * 60 / v
  138. fig, axs = plt.subplots(1, 2, figsize=(9, 3.4))
  139. axs[0].hist(np.clip(cp, 0, 0.6), bins=50, color="#3d7bd6")
  140. axs[0].set_title("Cp 分布(按 R=60m 估算)"); axs[0].set_xlabel("Cp")
  141. axs[1].hist(np.clip(tsr, 0, 15), bins=50, color="#2e8b57")
  142. axs[1].set_title("TSR 分布(按 R=60m 估算)"); axs[1].set_xlabel("TSR")
  143. return save(fig, "cp_tsr")
  144. def chart_ambient_pitch():
  145. rows = q(f"""SELECT `year_month` ym, AVG(outside_cabin_temperature) out_t, AVG(cabin_temperature) cab_t,
  146. AVG(LEAST(pitch_angle_blade_1,pitch_angle_blade_2,pitch_angle_blade_3)) min_pitch
  147. FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 GROUP BY `year_month` ORDER BY ym""")
  148. labels = [f"{str(r['ym'])[:4]}-{str(r['ym'])[4:]}" for r in rows]
  149. out_t = [float(r["out_t"] or 0) for r in rows]
  150. cab_t = [float(r["cab_t"] or 0) for r in rows]
  151. mp = [float(r["min_pitch"] or 0) for r in rows]
  152. fig, ax = plt.subplots(figsize=(7, 3.2))
  153. ax.plot(labels, out_t, marker="o", label="环境温度")
  154. ax.plot(labels, cab_t, marker="s", label="机舱温度")
  155. ax.set_ylabel("温度(℃)"); ax.set_title("环境/机舱温度月度趋势"); ax.legend()
  156. ax.tick_params(axis="x", rotation=45)
  157. p1 = save(fig, "ambient_cabin")
  158. fig, ax = plt.subplots(figsize=(6.2, 3.2))
  159. ax.hist(mp, bins=30, color="#f0ad4e", edgecolor="white")
  160. ax.set_xlabel("最小桨距角(°)均值"); ax.set_ylabel("月份数"); ax.set_title("最小桨距角分布")
  161. p2 = save(fig, "min_pitch")
  162. return p1, p2
  163. def chart_vibration():
  164. rows = q(f"SELECT id,time_stamp,mesure_data,sampling_frequency,rotational_speed FROM `{WIND}_wave` WHERE mesure_point_name LIKE '%%main_bearing%%' AND rotational_speed>0 AND sampling_frequency>=12800 ORDER BY time_stamp DESC LIMIT 1")
  165. if not rows:
  166. return None, None
  167. r = rows[0]
  168. raw = r["mesure_data"]
  169. try:
  170. data = json.loads(raw)
  171. if isinstance(data, dict):
  172. data = data.get("data") or data.get("values") or []
  173. arr = np.asarray(data, dtype=float)
  174. except Exception:
  175. arr = np.asarray([float(x) for x in str(raw).strip().strip("[]").split(",") if x.strip()])
  176. arr = arr[np.isfinite(arr)]
  177. fs = float(r["sampling_frequency"] or 1)
  178. t = np.arange(arr.size) / fs
  179. fig, ax = plt.subplots(figsize=(7, 3.2))
  180. ax.plot(t[: min(5000, arr.size)], arr[: min(5000, arr.size)], lw=0.6)
  181. ax.set_xlabel("时间(s)"); ax.set_ylabel("加速度"); ax.set_title("主轴承振动时域波形")
  182. p1 = save(fig, "vib_time")
  183. from scipy.signal import hilbert
  184. env = np.abs(hilbert(arr - arr.mean()))
  185. fig, ax = plt.subplots(figsize=(7, 3.2))
  186. ax.plot(t[: min(5000, env.size)], env[: min(5000, env.size)], lw=0.8, color="#d9534f")
  187. ax.set_xlabel("时间(s)"); ax.set_ylabel("包络幅值"); ax.set_title("主轴承振动包络谱(时域包络)")
  188. p2 = save(fig, "vib_envelope")
  189. return p1, p2
  190. def add_report(path, charts):
  191. doc = Document(path)
  192. doc.add_page_break()
  193. doc.add_heading("附录 补充分析图", level=1)
  194. doc.add_paragraph("以下图表基于平台分钟级 SCADA 与 CMS 波形数据生成,用于补充模板要求的专项分析。")
  195. sections = [
  196. ("9.1 偏航误差专项", [
  197. ("图 9-1 静态偏航误差分布", charts["yaw_hist"], "偏航误差主要分布在 ±3° 以外,说明机组对风偏差较大,建议按模板判据优先校正 >3° 机组。"),
  198. ("图 9-2 偏航误差绝对值区间占比", charts["yaw_bins"], "统计显示超过 3° 与超过 5° 的记录占比较高,偏航控制策略或风向仪安装偏差需复核。"),
  199. ]),
  200. ("9.2 数据完整度", [
  201. ("图 9-3 月度分钟级数据完整率", charts["integrity"], "各月完整率差异明显,完整性不足会直接影响能效与可靠性结论的可信度。"),
  202. ]),
  203. ("9.3 风资源", [
  204. ("图 9-4 风速频率分布", charts["wind_freq"], "风速集中在低风速区间,等效满负荷小时偏低与风资源条件相关。"),
  205. ("图 9-5 风向玫瑰图", charts["wind_rose"], "主导风向集中,偏航误差对发电量的影响在该风向下更敏感。"),
  206. ]),
  207. ("9.4 大部件温度", [
  208. ("图 9-6 齿轮箱高速轴轴承温度 vs 功率", charts["gearbox_temp_power"], "高温区随功率上升明显,需关注齿轮箱冷却与润滑状态。"),
  209. ("图 9-7 发电机驱动/非驱动端轴承温度 vs 功率", charts["gen_temp_power"], "两端轴承温度随功率变化趋势用于判断传感器偏差与轴承异常。"),
  210. ]),
  211. ("9.5 变桨/转速/功率协调", [
  212. ("图 9-8 变桨-转速、变桨-功率、转速-功率协调", charts["pitch_speed_power"], "散点离散度反映控制协调性;明显离群点需核查变桨控制与功率曲线。"),
  213. ]),
  214. ("9.6 Cp/TSR", [
  215. ("图 9-9 Cp/TSR 分布", charts["cp_tsr"], "Cp/TSR 按 R=60m 估算,用于相对比较;绝对值需结合机型参数复核。"),
  216. ]),
  217. ("9.7 环境温度与最小桨距角", [
  218. ("图 9-10 环境/机舱温度月度趋势", charts["ambient_cabin"], "环境温度与机舱温度差异反映机舱散热与传感器状态。"),
  219. ("图 9-11 最小桨距角分布", charts["min_pitch"], "最小桨距角异常偏大可能影响低风速段捕风能力。"),
  220. ]),
  221. ("9.8 振动时域/包络", [
  222. ("图 9-12 主轴承振动时域波形", charts["vib_time"], "时域波形用于观察冲击与调制特征,需结合频谱和特征频率复核。"),
  223. ("图 9-13 主轴承振动包络谱", charts["vib_envelope"], "包络谱对轴承早期故障敏感,建议对异常测点开展离线检测。"),
  224. ]),
  225. ]
  226. for title, items in sections:
  227. doc.add_heading(title, level=2)
  228. for caption, img_path, analysis in items:
  229. if img_path and os.path.exists(img_path):
  230. p = doc.add_paragraph(); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
  231. p.add_run().add_picture(img_path, width=Inches(6.1))
  232. cap = doc.add_paragraph(); cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
  233. run = cap.add_run(caption); run.font.size = Pt(9)
  234. doc.add_paragraph(analysis)
  235. doc.save(path)
  236. def main():
  237. yaw_hist, yaw_bins, over3, over5 = chart_yaw()
  238. integrity = chart_integrity()
  239. wind_freq, wind_rose = chart_wind()
  240. gearbox, gen = chart_temp_power()
  241. pitch = chart_pitch_speed_power()
  242. cp = chart_cp_tsr()
  243. ambient, min_pitch = chart_ambient_pitch()
  244. vib_t, vib_e = chart_vibration()
  245. charts = dict(yaw_hist=yaw_hist, yaw_bins=yaw_bins, integrity=integrity,
  246. wind_freq=wind_freq, wind_rose=wind_rose,
  247. gearbox_temp_power=gearbox, gen_temp_power=gen,
  248. pitch_speed_power=pitch, cp_tsr=cp,
  249. ambient_cabin=ambient, min_pitch=min_pitch,
  250. vib_time=vib_t, vib_envelope=vib_e)
  251. report = r"E:\WorkSpace\SourceCode\algorithm_ai\Analysis_Multi\output\reports\七台河风电场_2024-01_2024-12_可靠性和能效双提升数据分析报告_20261118_171622.docx"
  252. add_report(report, charts)
  253. print("done", len([v for v in charts.values() if v]))
  254. if __name__ == "__main__":
  255. main()