collector.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  1. """报告数据采集:平台库(台账/健康) + 业务库(SCADA/故障/振动)。
  2. 所有查询只读取本机配置指定的数据库,不访问互联网。
  3. """
  4. from __future__ import annotations
  5. import calendar
  6. import json
  7. import math
  8. import os
  9. import re
  10. from datetime import datetime, timedelta
  11. from typing import Any, Dict, List, Optional, Tuple
  12. import numpy as np
  13. import pymysql
  14. import requests
  15. from pymysql.cursors import DictCursor
  16. from app.config import dataSettings, platformSettings
  17. HEALTH_API = os.getenv("HEALTH_API", "http://127.0.0.1:8888/health_assess")
  18. def _split_host(value: str) -> Tuple[str, int]:
  19. if ":" in value:
  20. host, port = value.rsplit(":", 1)
  21. return host, int(port)
  22. return value, 3306
  23. def _connect(settings, database: str):
  24. host, port = _split_host(settings.db_host)
  25. return pymysql.connect(
  26. host=host,
  27. port=port,
  28. user=settings.db_user,
  29. password=settings.db_password,
  30. database=database,
  31. charset="utf8mb4",
  32. cursorclass=DictCursor,
  33. connect_timeout=15,
  34. read_timeout=600,
  35. write_timeout=600,
  36. autocommit=True,
  37. )
  38. def platform_conn():
  39. return _connect(platformSettings, platformSettings.db_name)
  40. def business_conn():
  41. return _connect(dataSettings, dataSettings.db_name)
  42. def safe_code(code: str) -> str:
  43. if not re.fullmatch(r"[A-Za-z0-9_]+", code or ""):
  44. raise ValueError("非法的风场编号")
  45. return code
  46. def month_list(start_month: str, end_month: str) -> List[str]:
  47. sy, sm = map(int, start_month.split("-"))
  48. ey, em = map(int, end_month.split("-"))
  49. if (sy, sm) > (ey, em):
  50. raise ValueError("开始月份不能晚于结束月份")
  51. out = []
  52. y, m = sy, sm
  53. while (y, m) <= (ey, em):
  54. out.append(f"{y:04d}-{m:02d}")
  55. m += 1
  56. if m > 12:
  57. y += 1
  58. m = 1
  59. return out
  60. def _month_bounds(month: str) -> Tuple[datetime, datetime]:
  61. y, m = map(int, month.split("-"))
  62. start = datetime(y, m, 1)
  63. end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
  64. return start, end
  65. def _table_exists(conn, table: str) -> bool:
  66. with conn.cursor() as cur:
  67. cur.execute(
  68. "SELECT COUNT(*) AS c FROM information_schema.tables "
  69. "WHERE table_schema = DATABASE() AND table_name = %s",
  70. (table,),
  71. )
  72. return cur.fetchone()["c"] > 0
  73. def get_wind_info(wind_code: str) -> Dict[str, Any]:
  74. wind_code = safe_code(wind_code)
  75. conn = platform_conn()
  76. try:
  77. with conn.cursor() as cur:
  78. cur.execute(
  79. "SELECT field_code, field_name, company_code, rated_capacity_number "
  80. "FROM wind_field WHERE field_code=%s",
  81. (wind_code,),
  82. )
  83. field = cur.fetchone() or {}
  84. cur.execute(
  85. "SELECT engine_code, engine_name, mill_type_code, rated_capacity "
  86. "FROM wind_engine_group WHERE field_code=%s AND del_state=0 "
  87. "ORDER BY engine_name",
  88. (wind_code,),
  89. )
  90. turbines = cur.fetchall() or []
  91. cur.execute(
  92. "SELECT company_name FROM wind_company WHERE company_code=%s",
  93. (field.get("company_code"),),
  94. )
  95. company = cur.fetchone() or {}
  96. finally:
  97. conn.close()
  98. capacity = float(field.get("rated_capacity_number") or 0)
  99. if capacity <= 0:
  100. capacity = sum(float(t.get("rated_capacity") or 0) for t in turbines)
  101. return {
  102. "code": wind_code,
  103. "name": field.get("field_name") or wind_code,
  104. "company": company.get("company_name") or field.get("company_code") or "",
  105. "capacity_kw": capacity,
  106. "turbine_count": len(turbines),
  107. "turbines": turbines,
  108. }
  109. def collect_overview(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  110. try:
  111. code = wind["code"]
  112. table = f"`{safe_code(code)}_minute`"
  113. start_ym = int(months[0].replace("-", ""))
  114. end_ym = int(months[-1].replace("-", ""))
  115. conn = business_conn()
  116. try:
  117. if not _table_exists(conn, f"{code}_minute"):
  118. return {"available": False, "error": f"未找到 {code}_minute 表", "monthly": [], "turbines": []}
  119. with conn.cursor() as cur:
  120. cur.execute(
  121. f"""
  122. SELECT `year_month`, `wind_turbine_number`,
  123. MAX(wind_turbine_name) AS turbine_name,
  124. COUNT(*) AS points,
  125. AVG(active_power) AS avg_power,
  126. AVG(wind_velocity) AS avg_wind,
  127. SUM(active_power) / 60.0 AS gen_kwh
  128. FROM {table}
  129. WHERE `year_month` BETWEEN %s AND %s
  130. GROUP BY `year_month`, `wind_turbine_number`
  131. """,
  132. (start_ym, end_ym),
  133. )
  134. rows = cur.fetchall() or []
  135. finally:
  136. conn.close()
  137. if not rows:
  138. return {"available": False, "error": "所选时间段内无分钟级 SCADA 数据", "monthly": [], "turbines": []}
  139. monthly_map: Dict[str, Dict[str, Any]] = {}
  140. turbine_map: Dict[str, Dict[str, Any]] = {}
  141. total_kwh = 0.0
  142. total_points = 0
  143. weighted_wind = 0.0
  144. for row in rows:
  145. ym = int(row["year_month"])
  146. month = f"{ym // 100:04d}-{ym % 100:02d}"
  147. points = int(row["points"] or 0)
  148. gen_kwh = float(row["gen_kwh"] or 0)
  149. avg_power = float(row["avg_power"] or 0)
  150. avg_wind = float(row["avg_wind"] or 0) if row["avg_wind"] is not None else None
  151. code_t = row["wind_turbine_number"]
  152. name_t = row["turbine_name"] or code_t
  153. m = monthly_map.setdefault(
  154. month,
  155. {"month": month, "gen_kwh": 0.0, "points": 0, "wind_points": 0, "wind_sum": 0.0, "turbines": 0},
  156. )
  157. m["gen_kwh"] += gen_kwh
  158. m["points"] += points
  159. m["turbines"] += 1
  160. if avg_wind is not None:
  161. m["wind_sum"] += avg_wind * points
  162. m["wind_points"] += points
  163. t = turbine_map.setdefault(
  164. code_t,
  165. {
  166. "code": code_t,
  167. "name": name_t,
  168. "gen_kwh": 0.0,
  169. "points": 0,
  170. "wind_points": 0,
  171. "wind_sum": 0.0,
  172. "power_weighted": 0.0,
  173. },
  174. )
  175. t["gen_kwh"] += gen_kwh
  176. t["points"] += points
  177. t["power_weighted"] += avg_power * points
  178. if avg_wind is not None:
  179. t["wind_sum"] += avg_wind * points
  180. t["wind_points"] += points
  181. total_kwh += gen_kwh
  182. total_points += points
  183. if avg_wind is not None:
  184. weighted_wind += avg_wind * points
  185. # 完整率:按月内应有分钟数计算
  186. for month, m in monthly_map.items():
  187. days = calendar.monthrange(int(month[:4]), int(month[5:]))[1]
  188. expected = days * 1440 * max(m["turbines"], 1)
  189. m["completeness"] = round(min(1.0, m["points"] / expected) * 100, 2) if expected else 0.0
  190. m["gen_mwh"] = round(m["gen_kwh"] / 1000, 2)
  191. m["avg_wind"] = round(m["wind_sum"] / m["wind_points"], 2) if m["wind_points"] else None
  192. turbines = []
  193. for t in turbine_map.values():
  194. turbines.append(
  195. {
  196. "code": t["code"],
  197. "name": t["name"],
  198. "gen_mwh": round(t["gen_kwh"] / 1000, 2),
  199. "avg_power": round(t["power_weighted"] / t["points"], 2) if t["points"] else 0,
  200. "avg_wind": round(t["wind_sum"] / t["wind_points"], 2) if t["wind_points"] else None,
  201. "points": t["points"],
  202. }
  203. )
  204. turbines.sort(key=lambda x: x["gen_mwh"], reverse=True)
  205. for i, t in enumerate(turbines):
  206. t["rank"] = i + 1
  207. capacity = float(wind.get("capacity_kw") or 0)
  208. total_mwh = total_kwh / 1000
  209. total_hours = sum(
  210. (calendar.monthrange(int(m[:4]), int(m[5:]))[1]) * 24 for m in months
  211. )
  212. return {
  213. "available": True,
  214. "monthly": sorted(monthly_map.values(), key=lambda x: x["month"]),
  215. "turbines": turbines,
  216. "total_mwh": round(total_mwh, 2),
  217. "equivalent_hours": round(total_kwh / capacity, 1) if capacity else None,
  218. "avg_wind": round(weighted_wind / total_points, 2) if total_points else None,
  219. "capacity_factor": round(total_kwh / (capacity * total_hours) * 100, 2) if capacity and total_hours else None,
  220. "completeness": round(
  221. sum(m["completeness"] for m in monthly_map.values()) / len(monthly_map), 2
  222. )
  223. if monthly_map
  224. else None,
  225. "best": turbines[:3],
  226. "worst": list(reversed(turbines[-3:])) if len(turbines) >= 3 else list(reversed(turbines)),
  227. }
  228. except Exception as exc:
  229. return {"available": False, "error": str(exc), "monthly": [], "turbines": []}
  230. def _call_health(wind_code: str, month: str) -> List[Dict[str, Any]]:
  231. resp = requests.post(
  232. HEALTH_API,
  233. json={"windcode": wind_code, "month": month},
  234. timeout=900,
  235. )
  236. resp.raise_for_status()
  237. data = resp.json()
  238. if isinstance(data, dict) and data.get("detail"):
  239. raise RuntimeError(str(data.get("detail")))
  240. if not isinstance(data, list):
  241. raise RuntimeError("健康评估返回格式异常")
  242. return data
  243. def collect_health(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  244. # 健康评估为逐机组模型推理,耗时较长;报告取时间段内最近 1 个月,
  245. # 其余维度(概览/故障/振动)仍覆盖完整时间段。
  246. assess_months = months[-1:]
  247. monthly = []
  248. latest_turbines: List[Dict[str, Any]] = []
  249. errors = []
  250. for month in assess_months:
  251. try:
  252. items = _call_health(wind["code"], month)
  253. scores = [float(x.get("total_health_score", -1)) for x in items]
  254. valid = [s for s in scores if s >= 0]
  255. dist = {"healthy": 0, "subhealthy": 0, "normal": 0, "fault": 0, "nodata": 0}
  256. for s in scores:
  257. if s < 0:
  258. dist["nodata"] += 1
  259. elif s >= 85:
  260. dist["healthy"] += 1
  261. elif s >= 70:
  262. dist["subhealthy"] += 1
  263. elif s >= 55:
  264. dist["normal"] += 1
  265. else:
  266. dist["fault"] += 1
  267. monthly.append(
  268. {
  269. "month": month,
  270. "count": len(items),
  271. "avg_score": round(sum(valid) / len(valid), 2) if valid else None,
  272. "min_score": round(min(valid), 2) if valid else None,
  273. "max_score": round(max(valid), 2) if valid else None,
  274. "distribution": dist,
  275. }
  276. )
  277. if month == assess_months[-1]:
  278. latest_turbines = items
  279. except Exception as exc:
  280. errors.append(f"{month}: {exc}")
  281. turbines = []
  282. for x in latest_turbines:
  283. subsystems = x.get("subsystems") or {}
  284. turbines.append(
  285. {
  286. "code": x.get("engine_code"),
  287. "name": x.get("wind_turbine_name"),
  288. "score": x.get("total_health_score", -1),
  289. "generator": (subsystems.get("generator") or {}).get("health_score", -1),
  290. "nacelle": (subsystems.get("nacelle") or {}).get("health_score", -1),
  291. "grid": (subsystems.get("grid") or {}).get("health_score", -1),
  292. "drive_train": (subsystems.get("drive_train") or {}).get("health_score", -1),
  293. }
  294. )
  295. turbines.sort(key=lambda x: (x["score"] < 0, -(x["score"] if x["score"] >= 0 else -1)))
  296. valid_turbines = [t for t in turbines if t["score"] >= 0]
  297. subsys_avg = {}
  298. for key in ["generator", "nacelle", "grid", "drive_train"]:
  299. vals = [t[key] for t in valid_turbines if t[key] is not None and t[key] >= 0]
  300. subsys_avg[key] = round(sum(vals) / len(vals), 2) if vals else None
  301. latest_dist = monthly[-1]["distribution"] if monthly else {}
  302. return {
  303. "available": bool(monthly) and bool(valid_turbines),
  304. "months": monthly,
  305. "turbines": turbines,
  306. "avg_score": round(sum(t["score"] for t in valid_turbines) / len(valid_turbines), 2)
  307. if valid_turbines
  308. else None,
  309. "distribution": latest_dist,
  310. "subsystems": subsys_avg,
  311. "low_turbines": [t for t in valid_turbines if t["score"] < 70][:10],
  312. "errors": errors,
  313. "assessed_months": assess_months,
  314. }
  315. def collect_fault(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  316. code = wind["code"]
  317. table_name = f"{code}_fault"
  318. start, _ = _month_bounds(months[0])
  319. _, end = _month_bounds(months[-1])
  320. try:
  321. conn = business_conn()
  322. try:
  323. if not _table_exists(conn, table_name):
  324. return {
  325. "available": False,
  326. "error": f"未找到 {table_name} 故障表(该风场可能未接入故障日志)",
  327. "monthly": [],
  328. "top_codes": [],
  329. }
  330. with conn.cursor() as cur:
  331. cur.execute(
  332. f"""
  333. SELECT DATE_FORMAT(begin_time, '%%Y-%%m') AS month,
  334. COUNT(*) AS count,
  335. COUNT(DISTINCT wind_turbine_number) AS turbines
  336. FROM `{table_name}`
  337. WHERE begin_time >= %s AND begin_time < %s
  338. GROUP BY month ORDER BY month
  339. """,
  340. (start, end),
  341. )
  342. monthly = cur.fetchall() or []
  343. cur.execute(
  344. f"""
  345. SELECT COALESCE(NULLIF(fault_code, ''), '未编码') AS code,
  346. COUNT(*) AS count,
  347. COUNT(DISTINCT wind_turbine_number) AS turbines
  348. FROM `{table_name}`
  349. WHERE begin_time >= %s AND begin_time < %s
  350. GROUP BY code ORDER BY count DESC LIMIT 10
  351. """,
  352. (start, end),
  353. )
  354. top_codes = cur.fetchall() or []
  355. cur.execute(
  356. f"""
  357. SELECT wind_turbine_name AS name, COUNT(*) AS count
  358. FROM `{table_name}`
  359. WHERE begin_time >= %s AND begin_time < %s
  360. GROUP BY wind_turbine_name ORDER BY count DESC LIMIT 10
  361. """,
  362. (start, end),
  363. )
  364. turbines = cur.fetchall() or []
  365. cur.execute(
  366. f"SELECT COUNT(*) AS c, COUNT(DISTINCT wind_turbine_number) AS t "
  367. f"FROM `{table_name}` WHERE begin_time >= %s AND begin_time < %s",
  368. (start, end),
  369. )
  370. summary = cur.fetchone() or {}
  371. finally:
  372. conn.close()
  373. for row in top_codes:
  374. row["code"] = str(row["code"])[:40]
  375. return {
  376. "available": summary.get("c", 0) > 0,
  377. "total": int(summary.get("c", 0) or 0),
  378. "affected_turbines": int(summary.get("t", 0) or 0),
  379. "monthly": monthly,
  380. "top_codes": top_codes,
  381. "turbines": turbines,
  382. }
  383. except Exception as exc:
  384. return {"available": False, "error": str(exc), "monthly": [], "top_codes": []}
  385. def _parse_wave(raw: str) -> Optional[np.ndarray]:
  386. try:
  387. data = json.loads(raw)
  388. if isinstance(data, dict):
  389. data = data.get("data") or data.get("values") or []
  390. arr = np.asarray(data, dtype=float)
  391. arr = arr[np.isfinite(arr)]
  392. return arr if arr.size else None
  393. except Exception:
  394. try:
  395. cleaned = str(raw).strip().strip("[]")
  396. arr = np.asarray([float(x) for x in cleaned.split(",") if x.strip()], dtype=float)
  397. return arr if arr.size else None
  398. except Exception:
  399. return None
  400. def collect_vibration(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  401. code = wind["code"]
  402. table_name = f"{code}_wave"
  403. start, _ = _month_bounds(months[0])
  404. _, end = _month_bounds(months[-1])
  405. try:
  406. conn = business_conn()
  407. try:
  408. if not _table_exists(conn, table_name):
  409. return {
  410. "available": False,
  411. "error": f"未找到 {table_name} 振动波形表",
  412. "points": [],
  413. "monthly": [],
  414. }
  415. with conn.cursor() as cur:
  416. cur.execute(
  417. f"SELECT COUNT(*) AS c, COUNT(DISTINCT wind_turbine_number) AS t, "
  418. f"COUNT(DISTINCT mesure_point_name) AS p, MIN(time_stamp) AS mn, MAX(time_stamp) AS mx "
  419. f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s",
  420. (start, end),
  421. )
  422. summary = cur.fetchone() or {}
  423. cur.execute(
  424. f"SELECT mesure_point_name AS point, COUNT(*) AS count, "
  425. f"ROUND(AVG(sampling_frequency),0) AS fs "
  426. f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s "
  427. f"GROUP BY point ORDER BY count DESC LIMIT 12",
  428. (start, end),
  429. )
  430. points = cur.fetchall() or []
  431. for p in points:
  432. p["fs"] = float(p["fs"]) if p.get("fs") is not None else None
  433. cur.execute(
  434. f"SELECT DATE_FORMAT(time_stamp, '%%Y-%%m') AS month, COUNT(*) AS count "
  435. f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s "
  436. f"GROUP BY month ORDER BY month",
  437. (start, end),
  438. )
  439. monthly = cur.fetchall() or []
  440. cur.execute(
  441. f"SELECT id, time_stamp, sampling_frequency, mesure_point_name, "
  442. f"rotational_speed, mesure_data FROM `{table_name}` "
  443. f"WHERE time_stamp >= %s AND time_stamp < %s "
  444. f"AND mesure_point_name LIKE '%%main_bearing%%' "
  445. f"ORDER BY time_stamp DESC LIMIT 1",
  446. (start, end),
  447. )
  448. sample = cur.fetchone()
  449. if not sample:
  450. cur.execute(
  451. f"SELECT id, time_stamp, sampling_frequency, mesure_point_name, "
  452. f"rotational_speed, mesure_data FROM `{table_name}` "
  453. f"WHERE time_stamp >= %s AND time_stamp < %s "
  454. f"ORDER BY time_stamp DESC LIMIT 1",
  455. (start, end),
  456. )
  457. sample = cur.fetchone()
  458. finally:
  459. conn.close()
  460. spectrum = None
  461. if sample:
  462. arr = _parse_wave(sample.get("mesure_data"))
  463. fs = float(sample.get("sampling_frequency") or 0)
  464. if arr is not None and fs > 0:
  465. arr = arr - float(np.mean(arr))
  466. n = arr.size
  467. win = np.hanning(n)
  468. amp = np.abs(np.fft.rfft(arr * win)) * 2 / max(n, 1)
  469. freq = np.fft.rfftfreq(n, d=1 / fs)
  470. keep = freq <= fs / 2.56
  471. freq, amp = freq[keep], amp[keep]
  472. if freq.size > 1500:
  473. idx = np.linspace(0, freq.size - 1, 1500).astype(int)
  474. freq, amp = freq[idx], amp[idx]
  475. spectrum = {
  476. "freq": [round(float(x), 3) for x in freq],
  477. "amp": [round(float(x), 6) for x in amp],
  478. "fs": fs,
  479. "rms": round(float(np.sqrt(np.mean(arr ** 2))), 4),
  480. "point": sample.get("mesure_point_name"),
  481. "time": str(sample.get("time_stamp")),
  482. "rpm": sample.get("rotational_speed"),
  483. }
  484. return {
  485. "available": (summary.get("c", 0) or 0) > 0,
  486. "total": int(summary.get("c", 0) or 0),
  487. "turbine_count": int(summary.get("t", 0) or 0),
  488. "point_count": int(summary.get("p", 0) or 0),
  489. "min_time": str(summary.get("mn")) if summary.get("mn") else None,
  490. "max_time": str(summary.get("mx")) if summary.get("mx") else None,
  491. "points": points,
  492. "monthly": monthly,
  493. "spectrum": spectrum,
  494. }
  495. except Exception as exc:
  496. return {"available": False, "error": str(exc), "points": [], "monthly": []}
  497. def collect_all(wind_code: str, start_month: str, end_month: str, sections=None) -> Dict[str, Any]:
  498. months = month_list(start_month, end_month)
  499. wind = get_wind_info(wind_code)
  500. selected = set(sections or ["overview", "health", "fault", "vibration"])
  501. data = {
  502. "wind": wind,
  503. "period": {"start": start_month, "end": end_month, "months": months, "month_count": len(months)},
  504. "overview": collect_overview(wind, months) if "overview" in selected else {"available": False, "error": "未勾选分析概览章节", "monthly": [], "turbines": []},
  505. "health": collect_health(wind, months) if "health" in selected else {"available": False, "error": "未勾选健康评估章节"},
  506. "fault": collect_fault(wind, months) if "fault" in selected else {"available": False, "error": "未勾选故障诊断章节", "monthly": [], "top_codes": []},
  507. "vibration": collect_vibration(wind, months) if "vibration" in selected else {"available": False, "error": "未勾选振动分析章节", "points": [], "monthly": []},
  508. "meta": {
  509. "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
  510. "data_source": "energy_data_prod(SCADA/故障/振动) + energy_prod(台账/健康)",
  511. },
  512. }
  513. return data