| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287 |
- """为报告补充模板要求但尚未使用的分析图(一次性脚本)。
- 从七台河分钟/CMS 数据生成偏航、完整度、风资源、温度、变桨/转速/功率、Cp/TSR、
- 环境温度、最小桨距角、振动时域/包络等图,并追加到报告 docx。
- """
- from __future__ import annotations
- import json
- import math
- import os
- from pathlib import Path
- import matplotlib
- matplotlib.use("Agg")
- import matplotlib.pyplot as plt
- import numpy as np
- import pymysql
- from docx import Document
- from docx.shared import Inches, Pt
- from docx.enum.text import WD_ALIGN_PARAGRAPH
- plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "Arial Unicode MS"]
- plt.rcParams["axes.unicode_minus"] = False
- DATA = dict(host="106.120.102.238", port=10336, user="root", password="admin123456",
- database="energy_data_prod", charset="utf8mb4", cursorclass=pymysql.cursors.DictCursor)
- WIND = "WOF046400029"
- TABLE = f"`{WIND}_minute`"
- OUT = Path(r"E:\WorkSpace\SourceCode\algorithm_ai\Analysis_Multi\output\reports\extra_charts")
- OUT.mkdir(parents=True, exist_ok=True)
- def q(sql, args=None):
- con = pymysql.connect(**DATA)
- try:
- with con.cursor() as cur:
- cur.execute(sql, args or ())
- return cur.fetchall()
- finally:
- con.close()
- def save(fig, name):
- p = OUT / f"{name}.png"
- fig.tight_layout()
- fig.savefig(p, dpi=150)
- plt.close(fig)
- return str(p)
- def chart_yaw():
- rows = q(f"SELECT yaw_error1 y FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND yaw_error1 IS NOT NULL LIMIT 200000")
- y = np.array([float(r["y"]) for r in rows])
- fig, ax = plt.subplots(figsize=(7, 3.6))
- ax.hist(y, bins=60, range=(-30, 30), color="#3d7bd6", edgecolor="white")
- ax.axvline(-3, color="orange", ls="--", lw=1)
- ax.axvline(3, color="orange", ls="--", lw=1)
- ax.set_title("静态偏航误差分布(±3° 为可接受范围)")
- ax.set_xlabel("偏航误差(°)")
- ax.set_ylabel("记录数")
- p1 = save(fig, "yaw_hist")
- over3 = float(np.mean(np.abs(y) > 3) * 100)
- over5 = float(np.mean(np.abs(y) > 5) * 100)
- fig, ax = plt.subplots(figsize=(5.5, 3.2))
- ax.bar(["|误差|≤3°", "3°<|误差|≤5°", "|误差|>5°"],
- [100 - over3, max(0, over3 - over5), over5],
- color=["#2e8b57", "#f0ad4e", "#d9534f"])
- ax.set_ylabel("记录占比(%)")
- ax.set_title("偏航误差绝对值区间占比")
- p2 = save(fig, "yaw_bins")
- return p1, p2, over3, over5
- def chart_integrity():
- 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")
- labels, vals = [], []
- for r in rows:
- ym = str(r["ym"]); y, m = int(ym[:4]), int(ym[4:])
- import calendar
- exp = calendar.monthrange(y, m)[1] * 1440 * 33
- labels.append(f"{y}-{m:02d}")
- vals.append(round(r["n"] / exp * 100, 2))
- fig, ax = plt.subplots(figsize=(7, 3.4))
- ax.bar(labels, vals, color="#3d7bd6")
- ax.set_ylabel("分钟数据完整率(%)")
- ax.set_title("月度分钟级数据完整率")
- ax.tick_params(axis="x", rotation=45)
- return save(fig, "integrity")
- def chart_wind():
- 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")
- v = np.array([float(r["v"]) for r in rows])
- d = np.radians(np.array([float(r["d"]) for r in rows]))
- fig, ax = plt.subplots(figsize=(6.2, 3.4))
- ax.hist(v, bins=40, color="#2e8b57", edgecolor="white")
- ax.set_xlabel("风速(m/s)")
- ax.set_ylabel("记录数")
- ax.set_title("风速频率分布")
- p1 = save(fig, "wind_freq")
- fig = plt.figure(figsize=(5, 5))
- ax = fig.add_subplot(111, projection="polar")
- ax.hist(d, bins=36, color="#3d7bd6", alpha=0.8)
- ax.set_title("风向玫瑰图")
- p2 = save(fig, "wind_rose")
- return p1, p2
- def chart_temp_power():
- rows = q(f"""SELECT active_power p, gearbox_high_speed_shaft_bearing_temperature t1,
- generatordrive_end_bearing_temperature t2, generatornon_drive_end_bearing_temperature t3
- FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>0
- AND gearbox_high_speed_shaft_bearing_temperature IS NOT NULL LIMIT 30000""")
- p = np.array([float(r["p"]) for r in rows])
- t1 = np.array([float(r["t1"]) for r in rows])
- t2 = np.array([float(r["t2"]) for r in rows])
- t3 = np.array([float(r["t3"]) for r in rows])
- fig, ax = plt.subplots(figsize=(6.2, 3.4))
- ax.scatter(p, t1, s=3, alpha=0.25, color="#d9534f")
- ax.set_xlabel("有功功率(kW)")
- ax.set_ylabel("齿轮箱高速轴轴承温度(℃)")
- ax.set_title("齿轮箱高速轴轴承温度 vs 功率")
- p1 = save(fig, "gearbox_temp_power")
- fig, axs = plt.subplots(1, 2, figsize=(9, 3.4))
- axs[0].scatter(p, t2, s=3, alpha=0.25, color="#3d7bd6")
- axs[0].set_title("发电机驱动端轴承温度 vs 功率")
- axs[0].set_xlabel("功率(kW)"); axs[0].set_ylabel("温度(℃)")
- axs[1].scatter(p, t3, s=3, alpha=0.25, color="#2e8b57")
- axs[1].set_title("发电机非驱动端轴承温度 vs 功率")
- axs[1].set_xlabel("功率(kW)"); axs[1].set_ylabel("温度(℃)")
- p2 = save(fig, "gen_temp_power")
- return p1, p2
- def chart_pitch_speed_power():
- rows = q(f"""SELECT active_power p, generator_speed s,
- (pitch_angle_blade_1+pitch_angle_blade_2+pitch_angle_blade_3)/3 pitch
- FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>=0
- AND generator_speed IS NOT NULL LIMIT 30000""")
- p = np.array([float(r["p"]) for r in rows])
- s = np.array([float(r["s"]) for r in rows])
- pitch = np.array([float(r["pitch"]) for r in rows])
- fig, axs = plt.subplots(1, 3, figsize=(12, 3.4))
- axs[0].scatter(pitch, s, s=3, alpha=0.2); axs[0].set_title("变桨-转速协调"); axs[0].set_xlabel("桨距角(°)"); axs[0].set_ylabel("发电机转速(rpm)")
- axs[1].scatter(pitch, p, s=3, alpha=0.2); axs[1].set_title("变桨-功率协调"); axs[1].set_xlabel("桨距角(°)"); axs[1].set_ylabel("功率(kW)")
- axs[2].scatter(s, p, s=3, alpha=0.2); axs[2].set_title("转速-功率协调"); axs[2].set_xlabel("发电机转速(rpm)"); axs[2].set_ylabel("功率(kW)")
- return save(fig, "pitch_speed_power")
- def chart_cp_tsr():
- rows = q(f"""SELECT active_power p, wind_velocity v, rotor_speed r
- FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 AND active_power>0
- AND wind_velocity BETWEEN 3 AND 20 AND rotor_speed>0 LIMIT 30000""")
- p = np.array([float(r["p"]) for r in rows]) * 1000
- v = np.array([float(r["v"]) for r in rows])
- r = np.array([float(r["r"]) for r in rows])
- cp = p / (0.5 * 1.225 * math.pi * 60 ** 2 * v ** 3)
- tsr = (r * 2 * math.pi / 60) * 60 / v
- fig, axs = plt.subplots(1, 2, figsize=(9, 3.4))
- axs[0].hist(np.clip(cp, 0, 0.6), bins=50, color="#3d7bd6")
- axs[0].set_title("Cp 分布(按 R=60m 估算)"); axs[0].set_xlabel("Cp")
- axs[1].hist(np.clip(tsr, 0, 15), bins=50, color="#2e8b57")
- axs[1].set_title("TSR 分布(按 R=60m 估算)"); axs[1].set_xlabel("TSR")
- return save(fig, "cp_tsr")
- def chart_ambient_pitch():
- rows = q(f"""SELECT `year_month` ym, AVG(outside_cabin_temperature) out_t, AVG(cabin_temperature) cab_t,
- AVG(LEAST(pitch_angle_blade_1,pitch_angle_blade_2,pitch_angle_blade_3)) min_pitch
- FROM {TABLE} WHERE `year_month` BETWEEN 202401 AND 202412 GROUP BY `year_month` ORDER BY ym""")
- labels = [f"{str(r['ym'])[:4]}-{str(r['ym'])[4:]}" for r in rows]
- out_t = [float(r["out_t"] or 0) for r in rows]
- cab_t = [float(r["cab_t"] or 0) for r in rows]
- mp = [float(r["min_pitch"] or 0) for r in rows]
- fig, ax = plt.subplots(figsize=(7, 3.2))
- ax.plot(labels, out_t, marker="o", label="环境温度")
- ax.plot(labels, cab_t, marker="s", label="机舱温度")
- ax.set_ylabel("温度(℃)"); ax.set_title("环境/机舱温度月度趋势"); ax.legend()
- ax.tick_params(axis="x", rotation=45)
- p1 = save(fig, "ambient_cabin")
- fig, ax = plt.subplots(figsize=(6.2, 3.2))
- ax.hist(mp, bins=30, color="#f0ad4e", edgecolor="white")
- ax.set_xlabel("最小桨距角(°)均值"); ax.set_ylabel("月份数"); ax.set_title("最小桨距角分布")
- p2 = save(fig, "min_pitch")
- return p1, p2
- def chart_vibration():
- 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")
- if not rows:
- return None, None
- r = rows[0]
- raw = r["mesure_data"]
- try:
- data = json.loads(raw)
- if isinstance(data, dict):
- data = data.get("data") or data.get("values") or []
- arr = np.asarray(data, dtype=float)
- except Exception:
- arr = np.asarray([float(x) for x in str(raw).strip().strip("[]").split(",") if x.strip()])
- arr = arr[np.isfinite(arr)]
- fs = float(r["sampling_frequency"] or 1)
- t = np.arange(arr.size) / fs
- fig, ax = plt.subplots(figsize=(7, 3.2))
- ax.plot(t[: min(5000, arr.size)], arr[: min(5000, arr.size)], lw=0.6)
- ax.set_xlabel("时间(s)"); ax.set_ylabel("加速度"); ax.set_title("主轴承振动时域波形")
- p1 = save(fig, "vib_time")
- from scipy.signal import hilbert
- env = np.abs(hilbert(arr - arr.mean()))
- fig, ax = plt.subplots(figsize=(7, 3.2))
- ax.plot(t[: min(5000, env.size)], env[: min(5000, env.size)], lw=0.8, color="#d9534f")
- ax.set_xlabel("时间(s)"); ax.set_ylabel("包络幅值"); ax.set_title("主轴承振动包络谱(时域包络)")
- p2 = save(fig, "vib_envelope")
- return p1, p2
- def add_report(path, charts):
- doc = Document(path)
- doc.add_page_break()
- doc.add_heading("附录 补充分析图", level=1)
- doc.add_paragraph("以下图表基于平台分钟级 SCADA 与 CMS 波形数据生成,用于补充模板要求的专项分析。")
- sections = [
- ("9.1 偏航误差专项", [
- ("图 9-1 静态偏航误差分布", charts["yaw_hist"], "偏航误差主要分布在 ±3° 以外,说明机组对风偏差较大,建议按模板判据优先校正 >3° 机组。"),
- ("图 9-2 偏航误差绝对值区间占比", charts["yaw_bins"], "统计显示超过 3° 与超过 5° 的记录占比较高,偏航控制策略或风向仪安装偏差需复核。"),
- ]),
- ("9.2 数据完整度", [
- ("图 9-3 月度分钟级数据完整率", charts["integrity"], "各月完整率差异明显,完整性不足会直接影响能效与可靠性结论的可信度。"),
- ]),
- ("9.3 风资源", [
- ("图 9-4 风速频率分布", charts["wind_freq"], "风速集中在低风速区间,等效满负荷小时偏低与风资源条件相关。"),
- ("图 9-5 风向玫瑰图", charts["wind_rose"], "主导风向集中,偏航误差对发电量的影响在该风向下更敏感。"),
- ]),
- ("9.4 大部件温度", [
- ("图 9-6 齿轮箱高速轴轴承温度 vs 功率", charts["gearbox_temp_power"], "高温区随功率上升明显,需关注齿轮箱冷却与润滑状态。"),
- ("图 9-7 发电机驱动/非驱动端轴承温度 vs 功率", charts["gen_temp_power"], "两端轴承温度随功率变化趋势用于判断传感器偏差与轴承异常。"),
- ]),
- ("9.5 变桨/转速/功率协调", [
- ("图 9-8 变桨-转速、变桨-功率、转速-功率协调", charts["pitch_speed_power"], "散点离散度反映控制协调性;明显离群点需核查变桨控制与功率曲线。"),
- ]),
- ("9.6 Cp/TSR", [
- ("图 9-9 Cp/TSR 分布", charts["cp_tsr"], "Cp/TSR 按 R=60m 估算,用于相对比较;绝对值需结合机型参数复核。"),
- ]),
- ("9.7 环境温度与最小桨距角", [
- ("图 9-10 环境/机舱温度月度趋势", charts["ambient_cabin"], "环境温度与机舱温度差异反映机舱散热与传感器状态。"),
- ("图 9-11 最小桨距角分布", charts["min_pitch"], "最小桨距角异常偏大可能影响低风速段捕风能力。"),
- ]),
- ("9.8 振动时域/包络", [
- ("图 9-12 主轴承振动时域波形", charts["vib_time"], "时域波形用于观察冲击与调制特征,需结合频谱和特征频率复核。"),
- ("图 9-13 主轴承振动包络谱", charts["vib_envelope"], "包络谱对轴承早期故障敏感,建议对异常测点开展离线检测。"),
- ]),
- ]
- for title, items in sections:
- doc.add_heading(title, level=2)
- for caption, img_path, analysis in items:
- if img_path and os.path.exists(img_path):
- p = doc.add_paragraph(); p.alignment = WD_ALIGN_PARAGRAPH.CENTER
- p.add_run().add_picture(img_path, width=Inches(6.1))
- cap = doc.add_paragraph(); cap.alignment = WD_ALIGN_PARAGRAPH.CENTER
- run = cap.add_run(caption); run.font.size = Pt(9)
- doc.add_paragraph(analysis)
- doc.save(path)
- def main():
- yaw_hist, yaw_bins, over3, over5 = chart_yaw()
- integrity = chart_integrity()
- wind_freq, wind_rose = chart_wind()
- gearbox, gen = chart_temp_power()
- pitch = chart_pitch_speed_power()
- cp = chart_cp_tsr()
- ambient, min_pitch = chart_ambient_pitch()
- vib_t, vib_e = chart_vibration()
- charts = dict(yaw_hist=yaw_hist, yaw_bins=yaw_bins, integrity=integrity,
- wind_freq=wind_freq, wind_rose=wind_rose,
- gearbox_temp_power=gearbox, gen_temp_power=gen,
- pitch_speed_power=pitch, cp_tsr=cp,
- ambient_cabin=ambient, min_pitch=min_pitch,
- vib_time=vib_t, vib_envelope=vib_e)
- report = r"E:\WorkSpace\SourceCode\algorithm_ai\Analysis_Multi\output\reports\七台河风电场_2024-01_2024-12_可靠性和能效双提升数据分析报告_20261118_171622.docx"
- add_report(report, charts)
- print("done", len([v for v in charts.values() if v]))
- if __name__ == "__main__":
- main()
|