| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219 |
- """报告图表生成(matplotlib,本地渲染)。"""
- from __future__ import annotations
- import os
- from typing import Any, Dict, List, Optional
- import matplotlib
- matplotlib.use("Agg")
- import matplotlib.pyplot as plt
- from matplotlib import font_manager
- # 中文字体:优先 Windows 自带字体
- _FONT_CANDIDATES = [
- r"C:\Windows\Fonts\msyh.ttc",
- r"C:\Windows\Fonts\msyhbd.ttc",
- r"C:\Windows\Fonts\simhei.ttf",
- r"C:\Windows\Fonts\simsun.ttc",
- ]
- for _p in _FONT_CANDIDATES:
- if os.path.exists(_p):
- try:
- font_manager.fontManager.addfont(_p)
- except Exception:
- pass
- plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "SimSun", "DejaVu Sans"]
- plt.rcParams["axes.unicode_minus"] = False
- COLORS = ["#1a3b7f", "#2f80ed", "#27ae60", "#f2994a", "#eb5757", "#9b51e0", "#56ccf2"]
- def _new(figsize=(8.2, 4.2)):
- fig, ax = plt.subplots(figsize=figsize, dpi=160)
- ax.spines["top"].set_visible(False)
- ax.spines["right"].set_visible(False)
- ax.grid(axis="y", linestyle="--", alpha=0.25)
- return fig, ax
- def _save(fig, path: str):
- fig.tight_layout()
- fig.savefig(path, bbox_inches="tight", facecolor="white")
- plt.close(fig)
- return path
- def monthly_generation(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
- rows = [m for m in monthly if m.get("gen_mwh") is not None]
- if not rows:
- return None
- fig, ax = _new()
- x = [m["month"] for m in rows]
- y = [m["gen_mwh"] for m in rows]
- bars = ax.bar(x, y, color=COLORS[1], width=0.58, label="发电量")
- ax.set_ylabel("发电量(MWh)")
- ax.set_title("月度发电量", fontsize=13, fontweight="bold")
- ax.tick_params(axis="x", rotation=35)
- for b, v in zip(bars, y):
- ax.text(b.get_x() + b.get_width() / 2, v, f"{v:,.0f}", ha="center", va="bottom", fontsize=8)
- ax2 = ax.twinx()
- ax2.plot(x, [m.get("avg_wind") or 0 for m in rows], color=COLORS[3], marker="o", label="平均风速")
- ax2.set_ylabel("平均风速(m/s)")
- lines1, labels1 = ax.get_legend_handles_labels()
- lines2, labels2 = ax2.get_legend_handles_labels()
- ax.legend(lines1 + lines2, labels1 + labels2, loc="upper left", fontsize=8)
- return _save(fig, path)
- def turbine_generation(turbines: List[Dict[str, Any]], path: str, top: int = 15) -> Optional[str]:
- rows = [t for t in turbines if t.get("gen_mwh") is not None]
- if not rows:
- return None
- rows = rows[:top]
- fig, ax = _new((8.2, 4.8))
- names = [str(t.get("name") or t.get("code")) for t in rows]
- vals = [t["gen_mwh"] for t in rows]
- bars = ax.barh(names[::-1], vals[::-1], color=COLORS[0])
- ax.set_xlabel("发电量(MWh)")
- ax.set_title("机组发电量排名(前 %d 台)" % len(rows), fontsize=13, fontweight="bold")
- for b, v in zip(bars, vals[::-1]):
- ax.text(v, b.get_y() + b.get_height() / 2, f" {v:,.0f}", va="center", fontsize=8)
- return _save(fig, path)
- def health_distribution(dist: Dict[str, int], path: str) -> Optional[str]:
- if not dist:
- return None
- labels_map = {
- "healthy": ("健康", "#27ae60"),
- "subhealthy": ("亚健康", "#f2c94c"),
- "normal": ("一般", "#f2994a"),
- "fault": ("故障", "#eb5757"),
- "nodata": ("无数据", "#bdbdbd"),
- }
- labels, values, colors = [], [], []
- for key in ["healthy", "subhealthy", "normal", "fault", "nodata"]:
- v = int(dist.get(key, 0) or 0)
- if v > 0:
- labels.append(f"{labels_map[key][0]} {v}台")
- values.append(v)
- colors.append(labels_map[key][1])
- if not values:
- return None
- fig, ax = plt.subplots(figsize=(6.4, 4.2), dpi=160)
- wedges, texts, autotexts = ax.pie(
- values,
- labels=labels,
- colors=colors,
- autopct="%1.1f%%",
- startangle=100,
- textprops={"fontsize": 9},
- wedgeprops={"width": 0.42, "edgecolor": "white"},
- )
- ax.set_title("机组健康等级分布", fontsize=13, fontweight="bold")
- ax.axis("equal")
- return _save(fig, path)
- def health_ranking(turbines: List[Dict[str, Any]], path: str, limit: int = 20) -> Optional[str]:
- rows = [t for t in turbines if t.get("score") is not None and t["score"] >= 0]
- if not rows:
- return None
- rows = rows[:limit]
- fig, ax = _new((8.2, 4.6))
- names = [str(t.get("name") or t.get("code")) for t in rows]
- vals = [t["score"] for t in rows]
- colors = ["#eb5757" if v < 55 else "#f2994a" if v < 70 else "#f2c94c" if v < 85 else "#27ae60" for v in vals]
- bars = ax.barh(names[::-1], vals[::-1], color=colors[::-1])
- ax.set_xlim(0, 100)
- ax.set_xlabel("健康得分")
- ax.set_title("机组健康得分(低分优先展示)", fontsize=13, fontweight="bold")
- for b, v in zip(bars, vals[::-1]):
- ax.text(v + 1, b.get_y() + b.get_height() / 2, f"{v:.1f}", va="center", fontsize=8)
- return _save(fig, path)
- def health_subsystems(subsystems: Dict[str, Any], path: str) -> Optional[str]:
- if not subsystems:
- return None
- label_map = {
- "generator": "发电机组",
- "nacelle": "机舱系统",
- "grid": "电网环境",
- "drive_train": "传动系统",
- }
- labels = [label_map.get(k, k) for k in ["generator", "nacelle", "grid", "drive_train"]]
- vals = [subsystems.get(k) or 0 for k in ["generator", "nacelle", "grid", "drive_train"]]
- if not any(vals):
- return None
- fig, ax = _new((7.2, 4.0))
- bars = ax.bar(labels, vals, color=COLORS[:4], width=0.55)
- ax.set_ylim(0, 100)
- ax.set_ylabel("平均健康得分")
- ax.set_title("子系统平均健康得分", fontsize=13, fontweight="bold")
- for b, v in zip(bars, vals):
- ax.text(b.get_x() + b.get_width() / 2, v + 1, f"{v:.1f}", ha="center", fontsize=9)
- return _save(fig, path)
- def fault_monthly(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
- if not monthly:
- return None
- fig, ax = _new((8.2, 4.0))
- x = [m["month"] for m in monthly]
- y = [int(m.get("count") or 0) for m in monthly]
- bars = ax.bar(x, y, color=COLORS[4], width=0.55)
- ax.set_ylabel("故障次数")
- ax.set_title("月度故障次数", fontsize=13, fontweight="bold")
- ax.tick_params(axis="x", rotation=35)
- for b, v in zip(bars, y):
- ax.text(b.get_x() + b.get_width() / 2, v, str(v), ha="center", va="bottom", fontsize=8)
- return _save(fig, path)
- def fault_top(codes: List[Dict[str, Any]], path: str) -> Optional[str]:
- if not codes:
- return None
- rows = codes[:10]
- fig, ax = _new((8.2, 4.2))
- labels = [str(c.get("code"))[:22] for c in rows]
- vals = [int(c.get("count") or 0) for c in rows]
- bars = ax.barh(labels[::-1], vals[::-1], color=COLORS[4])
- ax.set_xlabel("发生次数")
- ax.set_title("高频故障码(前 %d 项)" % len(rows), fontsize=13, fontweight="bold")
- for b, v in zip(bars, vals[::-1]):
- ax.text(v, b.get_y() + b.get_height() / 2, f" {v}", va="center", fontsize=8)
- return _save(fig, path)
- def vibration_spectrum(spectrum: Dict[str, Any], path: str) -> Optional[str]:
- if not spectrum or not spectrum.get("freq"):
- return None
- freq = spectrum["freq"]
- amp = spectrum["amp"]
- fig, ax = _new((8.2, 4.2))
- ax.plot(freq, amp, color=COLORS[5], linewidth=0.9)
- ax.set_xlabel("频率(Hz)")
- ax.set_ylabel("幅值")
- ax.set_title(
- f"振动频谱示例 · {spectrum.get('point', '')} · {spectrum.get('time', '')}",
- fontsize=11,
- fontweight="bold",
- )
- return _save(fig, path)
- def vibration_monthly(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
- if not monthly:
- return None
- fig, ax = _new((8.2, 4.0))
- x = [m["month"] for m in monthly]
- y = [int(m.get("count") or 0) for m in monthly]
- bars = ax.bar(x, y, color=COLORS[6], width=0.55)
- ax.set_ylabel("波形记录数")
- ax.set_title("月度振动波形记录量", fontsize=13, fontweight="bold")
- ax.tick_params(axis="x", rotation=35)
- for b, v in zip(bars, y):
- ax.text(b.get_x() + b.get_width() / 2, v, str(v), ha="center", va="bottom", fontsize=8)
- return _save(fig, path)
|