charts.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. """报告图表生成(matplotlib,本地渲染)。"""
  2. from __future__ import annotations
  3. import os
  4. from typing import Any, Dict, List, Optional
  5. import matplotlib
  6. matplotlib.use("Agg")
  7. import matplotlib.pyplot as plt
  8. from matplotlib import font_manager
  9. # 中文字体:优先 Windows 自带字体
  10. _FONT_CANDIDATES = [
  11. r"C:\Windows\Fonts\msyh.ttc",
  12. r"C:\Windows\Fonts\msyhbd.ttc",
  13. r"C:\Windows\Fonts\simhei.ttf",
  14. r"C:\Windows\Fonts\simsun.ttc",
  15. ]
  16. for _p in _FONT_CANDIDATES:
  17. if os.path.exists(_p):
  18. try:
  19. font_manager.fontManager.addfont(_p)
  20. except Exception:
  21. pass
  22. plt.rcParams["font.sans-serif"] = ["Microsoft YaHei", "SimHei", "SimSun", "DejaVu Sans"]
  23. plt.rcParams["axes.unicode_minus"] = False
  24. COLORS = ["#1a3b7f", "#2f80ed", "#27ae60", "#f2994a", "#eb5757", "#9b51e0", "#56ccf2"]
  25. def _new(figsize=(8.2, 4.2)):
  26. fig, ax = plt.subplots(figsize=figsize, dpi=160)
  27. ax.spines["top"].set_visible(False)
  28. ax.spines["right"].set_visible(False)
  29. ax.grid(axis="y", linestyle="--", alpha=0.25)
  30. return fig, ax
  31. def _save(fig, path: str):
  32. fig.tight_layout()
  33. fig.savefig(path, bbox_inches="tight", facecolor="white")
  34. plt.close(fig)
  35. return path
  36. def monthly_generation(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
  37. rows = [m for m in monthly if m.get("gen_mwh") is not None]
  38. if not rows:
  39. return None
  40. fig, ax = _new()
  41. x = [m["month"] for m in rows]
  42. y = [m["gen_mwh"] for m in rows]
  43. bars = ax.bar(x, y, color=COLORS[1], width=0.58, label="发电量")
  44. ax.set_ylabel("发电量(MWh)")
  45. ax.set_title("月度发电量", fontsize=13, fontweight="bold")
  46. ax.tick_params(axis="x", rotation=35)
  47. for b, v in zip(bars, y):
  48. ax.text(b.get_x() + b.get_width() / 2, v, f"{v:,.0f}", ha="center", va="bottom", fontsize=8)
  49. ax2 = ax.twinx()
  50. ax2.plot(x, [m.get("avg_wind") or 0 for m in rows], color=COLORS[3], marker="o", label="平均风速")
  51. ax2.set_ylabel("平均风速(m/s)")
  52. lines1, labels1 = ax.get_legend_handles_labels()
  53. lines2, labels2 = ax2.get_legend_handles_labels()
  54. ax.legend(lines1 + lines2, labels1 + labels2, loc="upper left", fontsize=8)
  55. return _save(fig, path)
  56. def turbine_generation(turbines: List[Dict[str, Any]], path: str, top: int = 15) -> Optional[str]:
  57. rows = [t for t in turbines if t.get("gen_mwh") is not None]
  58. if not rows:
  59. return None
  60. rows = rows[:top]
  61. fig, ax = _new((8.2, 4.8))
  62. names = [str(t.get("name") or t.get("code")) for t in rows]
  63. vals = [t["gen_mwh"] for t in rows]
  64. bars = ax.barh(names[::-1], vals[::-1], color=COLORS[0])
  65. ax.set_xlabel("发电量(MWh)")
  66. ax.set_title("机组发电量排名(前 %d 台)" % len(rows), fontsize=13, fontweight="bold")
  67. for b, v in zip(bars, vals[::-1]):
  68. ax.text(v, b.get_y() + b.get_height() / 2, f" {v:,.0f}", va="center", fontsize=8)
  69. return _save(fig, path)
  70. def health_distribution(dist: Dict[str, int], path: str) -> Optional[str]:
  71. if not dist:
  72. return None
  73. labels_map = {
  74. "healthy": ("健康", "#27ae60"),
  75. "subhealthy": ("亚健康", "#f2c94c"),
  76. "normal": ("一般", "#f2994a"),
  77. "fault": ("故障", "#eb5757"),
  78. "nodata": ("无数据", "#bdbdbd"),
  79. }
  80. labels, values, colors = [], [], []
  81. for key in ["healthy", "subhealthy", "normal", "fault", "nodata"]:
  82. v = int(dist.get(key, 0) or 0)
  83. if v > 0:
  84. labels.append(f"{labels_map[key][0]} {v}台")
  85. values.append(v)
  86. colors.append(labels_map[key][1])
  87. if not values:
  88. return None
  89. fig, ax = plt.subplots(figsize=(6.4, 4.2), dpi=160)
  90. wedges, texts, autotexts = ax.pie(
  91. values,
  92. labels=labels,
  93. colors=colors,
  94. autopct="%1.1f%%",
  95. startangle=100,
  96. textprops={"fontsize": 9},
  97. wedgeprops={"width": 0.42, "edgecolor": "white"},
  98. )
  99. ax.set_title("机组健康等级分布", fontsize=13, fontweight="bold")
  100. ax.axis("equal")
  101. return _save(fig, path)
  102. def health_ranking(turbines: List[Dict[str, Any]], path: str, limit: int = 20) -> Optional[str]:
  103. rows = [t for t in turbines if t.get("score") is not None and t["score"] >= 0]
  104. if not rows:
  105. return None
  106. rows = rows[:limit]
  107. fig, ax = _new((8.2, 4.6))
  108. names = [str(t.get("name") or t.get("code")) for t in rows]
  109. vals = [t["score"] for t in rows]
  110. colors = ["#eb5757" if v < 55 else "#f2994a" if v < 70 else "#f2c94c" if v < 85 else "#27ae60" for v in vals]
  111. bars = ax.barh(names[::-1], vals[::-1], color=colors[::-1])
  112. ax.set_xlim(0, 100)
  113. ax.set_xlabel("健康得分")
  114. ax.set_title("机组健康得分(低分优先展示)", fontsize=13, fontweight="bold")
  115. for b, v in zip(bars, vals[::-1]):
  116. ax.text(v + 1, b.get_y() + b.get_height() / 2, f"{v:.1f}", va="center", fontsize=8)
  117. return _save(fig, path)
  118. def health_subsystems(subsystems: Dict[str, Any], path: str) -> Optional[str]:
  119. if not subsystems:
  120. return None
  121. label_map = {
  122. "generator": "发电机组",
  123. "nacelle": "机舱系统",
  124. "grid": "电网环境",
  125. "drive_train": "传动系统",
  126. }
  127. labels = [label_map.get(k, k) for k in ["generator", "nacelle", "grid", "drive_train"]]
  128. vals = [subsystems.get(k) or 0 for k in ["generator", "nacelle", "grid", "drive_train"]]
  129. if not any(vals):
  130. return None
  131. fig, ax = _new((7.2, 4.0))
  132. bars = ax.bar(labels, vals, color=COLORS[:4], width=0.55)
  133. ax.set_ylim(0, 100)
  134. ax.set_ylabel("平均健康得分")
  135. ax.set_title("子系统平均健康得分", fontsize=13, fontweight="bold")
  136. for b, v in zip(bars, vals):
  137. ax.text(b.get_x() + b.get_width() / 2, v + 1, f"{v:.1f}", ha="center", fontsize=9)
  138. return _save(fig, path)
  139. def fault_monthly(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
  140. if not monthly:
  141. return None
  142. fig, ax = _new((8.2, 4.0))
  143. x = [m["month"] for m in monthly]
  144. y = [int(m.get("count") or 0) for m in monthly]
  145. bars = ax.bar(x, y, color=COLORS[4], width=0.55)
  146. ax.set_ylabel("故障次数")
  147. ax.set_title("月度故障次数", fontsize=13, fontweight="bold")
  148. ax.tick_params(axis="x", rotation=35)
  149. for b, v in zip(bars, y):
  150. ax.text(b.get_x() + b.get_width() / 2, v, str(v), ha="center", va="bottom", fontsize=8)
  151. return _save(fig, path)
  152. def fault_top(codes: List[Dict[str, Any]], path: str) -> Optional[str]:
  153. if not codes:
  154. return None
  155. rows = codes[:10]
  156. fig, ax = _new((8.2, 4.2))
  157. labels = [str(c.get("code"))[:22] for c in rows]
  158. vals = [int(c.get("count") or 0) for c in rows]
  159. bars = ax.barh(labels[::-1], vals[::-1], color=COLORS[4])
  160. ax.set_xlabel("发生次数")
  161. ax.set_title("高频故障码(前 %d 项)" % len(rows), fontsize=13, fontweight="bold")
  162. for b, v in zip(bars, vals[::-1]):
  163. ax.text(v, b.get_y() + b.get_height() / 2, f" {v}", va="center", fontsize=8)
  164. return _save(fig, path)
  165. def vibration_spectrum(spectrum: Dict[str, Any], path: str) -> Optional[str]:
  166. if not spectrum or not spectrum.get("freq"):
  167. return None
  168. freq = spectrum["freq"]
  169. amp = spectrum["amp"]
  170. fig, ax = _new((8.2, 4.2))
  171. ax.plot(freq, amp, color=COLORS[5], linewidth=0.9)
  172. ax.set_xlabel("频率(Hz)")
  173. ax.set_ylabel("幅值")
  174. ax.set_title(
  175. f"振动频谱示例 · {spectrum.get('point', '')} · {spectrum.get('time', '')}",
  176. fontsize=11,
  177. fontweight="bold",
  178. )
  179. return _save(fig, path)
  180. def vibration_monthly(monthly: List[Dict[str, Any]], path: str) -> Optional[str]:
  181. if not monthly:
  182. return None
  183. fig, ax = _new((8.2, 4.0))
  184. x = [m["month"] for m in monthly]
  185. y = [int(m.get("count") or 0) for m in monthly]
  186. bars = ax.bar(x, y, color=COLORS[6], width=0.55)
  187. ax.set_ylabel("波形记录数")
  188. ax.set_title("月度振动波形记录量", fontsize=13, fontweight="bold")
  189. ax.tick_params(axis="x", rotation=35)
  190. for b, v in zip(bars, y):
  191. ax.text(b.get_x() + b.get_width() / 2, v, str(v), ha="center", va="bottom", fontsize=8)
  192. return _save(fig, path)