page_source.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. """报告页面数据源:只读取健康度检测平台各页面实际使用的数据。
  2. 对应关系:
  3. - 分析概览 -> platform.analysis_result / analysis_general_file(页面 analysisDetail 同源)
  4. - 健康评估 -> /AnalysisMulti/health_assess(页面同源)
  5. - 算法健康评估 -> /AnalysisMulti/health-assessment/detail(页面同源)
  6. - 故障诊断 -> platform.vibration_diagnosis_result(页面 autodiag 保存结果)
  7. - 振动分析 -> energy_data_prod.<场码>_wave(页面 CMS 分析底层数据源)
  8. 页面没有对应时间段的结果时,返回 unavailable + 说明,报告不得回退到底层表编造数据。
  9. """
  10. from __future__ import annotations
  11. import csv
  12. import io
  13. import os
  14. from datetime import datetime
  15. from typing import Any, Dict, List, Optional, Tuple
  16. import requests
  17. from app.report.collector import platform_conn, safe_code
  18. MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "http://127.0.0.1:9000")
  19. MINIO_BUCKET = os.getenv("MINIO_BUCKET", "bucket-zhzn")
  20. OVERVIEW_TYPES = {
  21. "production_indicator": "机组/全场生产指标",
  22. "data_integrity_minute": "分钟级数据完整度",
  23. "data_integrity_second": "秒级数据完整度",
  24. "yaw_error": "静态偏航误差",
  25. "power_curve": "有功功率曲线",
  26. }
  27. FAULT_TYPE = "fault"
  28. def resolve_analysis_batch(field_code: str, start_month: str, end_month: str) -> Optional[Dict[str, Any]]:
  29. """返回覆盖所选时间段、最近完成的平台分析批次(分析概览页面使用的批次)。"""
  30. field_code = safe_code(field_code)
  31. start = datetime.fromisoformat(f"{start_month}-01")
  32. y, m = map(int, end_month.split("-"))
  33. end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
  34. conn = platform_conn()
  35. try:
  36. with conn.cursor() as cur:
  37. cur.execute(
  38. """
  39. SELECT batch_code, field_code, analysis_name, data_start_time, data_end_time, analysis_state
  40. FROM analysis_result
  41. WHERE field_code=%s AND analysis_state=30
  42. AND (data_type_code IS NULL OR data_type_code <> 'health_assessment')
  43. AND data_start_time < %s AND data_end_time > %s
  44. ORDER BY data_start_time DESC, id DESC
  45. LIMIT 1
  46. """,
  47. (field_code, end, start),
  48. )
  49. return cur.fetchone()
  50. finally:
  51. conn.close()
  52. def analysis_general_files(batch_code: str, type_codes: List[str]) -> Dict[str, List[str]]:
  53. """按分析类型取页面 analysisDetail 使用的总文件地址。"""
  54. if not batch_code or not type_codes:
  55. return {}
  56. conn = platform_conn()
  57. try:
  58. placeholders = ",".join(["%s"] * len(type_codes))
  59. with conn.cursor() as cur:
  60. cur.execute(
  61. f"SELECT analysis_type_code, file_addr FROM analysis_general_file "
  62. f"WHERE batch_code=%s AND analysis_type_code IN ({placeholders}) "
  63. "ORDER BY id",
  64. (batch_code, *type_codes),
  65. )
  66. out: Dict[str, List[str]] = {}
  67. for row in cur.fetchall():
  68. out.setdefault(row["analysis_type_code"], []).append(row["file_addr"])
  69. return out
  70. finally:
  71. conn.close()
  72. def fetch_minio_text(file_addr: str, timeout: int = 60) -> Optional[str]:
  73. """读取 MinIO 对象文本(CSV/JSON),供报告复用页面文件。"""
  74. key = file_addr
  75. if key.startswith("/minio/"):
  76. key = key[len("/minio/"):]
  77. url = f"{MINIO_ENDPOINT}/{MINIO_BUCKET}/{key}"
  78. try:
  79. r = requests.get(url, timeout=timeout)
  80. r.raise_for_status()
  81. return r.content.decode("utf-8-sig", errors="replace")
  82. except Exception:
  83. return None
  84. def _csv_rows(text: str) -> List[Dict[str, str]]:
  85. text = (text or "").lstrip("\ufeff")
  86. reader = csv.DictReader(io.StringIO(text))
  87. return [row for row in reader]
  88. def collect_overview_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  89. """分析概览页面数据:从平台分析批次文件读取,不直接查分钟表。"""
  90. code = wind["code"]
  91. start, end = months[0], months[-1]
  92. batch = resolve_analysis_batch(code, start, end)
  93. if not batch:
  94. return {"available": False, "error": "分析概览页面无覆盖所选时间段的已完成分析批次", "monthly": [], "turbines": [], "batch_code": None}
  95. files = analysis_general_files(batch["batch_code"], list(OVERVIEW_TYPES))
  96. prod_files = files.get("production_indicator", [])
  97. integ_files = files.get("data_integrity_minute", []) + files.get("data_integrity_second", [])
  98. if not prod_files:
  99. return {"available": False, "error": "分析概览页面该批次无生产指标结果文件", "monthly": [], "turbines": [], "batch_code": batch["batch_code"]}
  100. monthly_map: Dict[str, Dict[str, Any]] = {}
  101. turbine_map: Dict[str, Dict[str, Any]] = {}
  102. total_kwh = 0.0
  103. total_points = 0
  104. weighted_wind = 0.0
  105. for file_addr in prod_files:
  106. text = fetch_minio_text(file_addr)
  107. if not text:
  108. continue
  109. for row in _csv_rows(text):
  110. month = (row.get("year_month") or row.get("month") or "").strip()
  111. if len(month) == 6:
  112. month = f"{month[:4]}-{month[4:]}"
  113. if month and month not in months:
  114. continue
  115. name = row.get("wind_turbine_name") or row.get("engine_name") or row.get("wind_turbine_number") or ""
  116. if name in ("全场", "场站"):
  117. continue
  118. if name == "":
  119. name = row.get("wind_turbine_number") or name
  120. gen_kwh = _f(row.get("gen_kwh") or row.get("EPActualTotal") or row.get("generation") or row.get("energy") or 0)
  121. avg_power = _f(row.get("avg_power") or row.get("active_power_avg") or 0)
  122. avg_wind = _f(row.get("avg_wind") or row.get("WindSpeedAvr") or row.get("wind_velocity") or None)
  123. points = int(_f(row.get("points") or row.get("record_count") or 0) or 0)
  124. if points <= 0 and avg_wind is not None:
  125. points = 1
  126. if not name and not month:
  127. continue
  128. total_kwh += gen_kwh
  129. total_points += points
  130. if avg_wind is not None:
  131. weighted_wind += avg_wind * max(points, 1)
  132. if month:
  133. m = monthly_map.setdefault(month, {"month": month, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
  134. m["gen_kwh"] += gen_kwh
  135. m["points"] += points
  136. if avg_wind is not None:
  137. m["wind_sum"] += avg_wind * max(points, 1)
  138. m["wind_points"] += max(points, 1)
  139. if name:
  140. t = turbine_map.setdefault(name, {"name": name, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
  141. t["gen_kwh"] += gen_kwh
  142. t["points"] += points
  143. if avg_wind is not None:
  144. t["wind_sum"] += avg_wind * max(points, 1)
  145. t["wind_points"] += max(points, 1)
  146. # 数据完整度(分钟级),读取页面同源 data_integrity_minute 文件
  147. comp_total_valid = 0
  148. comp_total_expected = 0
  149. comp_by_month: Dict[str, Any] = {}
  150. for file_addr in integ_files:
  151. text = fetch_minio_text(file_addr)
  152. if not text:
  153. continue
  154. for row in _csv_rows(text):
  155. month = (row.get("month") or "").strip()
  156. valid = int(_f(row.get("valid_count") or 0))
  157. expected = int(_f(row.get("expected_count") or 0))
  158. if expected <= 0:
  159. continue
  160. comp_total_valid += valid
  161. comp_total_expected += expected
  162. m = comp_by_month.setdefault(month, {"v": 0, "e": 0})
  163. m["v"] += valid
  164. m["e"] += expected
  165. monthly = []
  166. for m in monthly_map.values():
  167. m["gen_mwh"] = round(m["gen_kwh"] / 1000, 2)
  168. m["avg_wind"] = round(m["wind_sum"] / m["wind_points"], 2) if m["wind_points"] else None
  169. cm = comp_by_month.get(m["month"])
  170. m["completeness"] = round(cm["v"] / cm["e"] * 100, 2) if cm and cm["e"] else None
  171. monthly.append(m)
  172. monthly.sort(key=lambda x: x["month"])
  173. turbines = []
  174. for t in turbine_map.values():
  175. turbines.append({
  176. "name": t["name"],
  177. "gen_mwh": round(t["gen_kwh"] / 1000, 2),
  178. "avg_power": round(t["gen_kwh"] / t["points"], 2) if t["points"] else None,
  179. "avg_wind": round(t["wind_sum"] / t["wind_points"], 2) if t["wind_points"] else None,
  180. "points": t["points"],
  181. })
  182. turbines.sort(key=lambda x: x["gen_mwh"] or 0, reverse=True)
  183. for i, t in enumerate(turbines):
  184. t["rank"] = i + 1
  185. capacity = float(wind.get("capacity_kw") or 0)
  186. total_mwh = total_kwh / 1000
  187. return {
  188. "available": True,
  189. "batch_code": batch["batch_code"],
  190. "monthly": monthly,
  191. "turbines": turbines,
  192. "total_mwh": round(total_mwh, 2),
  193. "equivalent_hours": round(total_kwh / capacity, 1) if capacity else None,
  194. "avg_wind": round(weighted_wind / total_points, 2) if total_points else None,
  195. "capacity_factor": round(total_mwh * 1000 / (capacity * 24 * 30.4 * len(months)) * 100, 2)
  196. if capacity and months else None,
  197. "completeness": round(comp_total_valid / comp_total_expected * 100, 2) if comp_total_expected else None,
  198. "integrity_files": integ_files,
  199. }
  200. def collect_yaw_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  201. """静态偏航误差:读取页面同源 yaw_error 分析文件。"""
  202. code = wind["code"]
  203. start, end = months[0], months[-1]
  204. batch = resolve_analysis_batch(code, start, end)
  205. if not batch:
  206. return {"available": False, "error": "偏航误差页面无覆盖所选时间段的分析批次", "turbines": []}
  207. files = analysis_general_files(batch["batch_code"], ["yaw_error"]).get("yaw_error", [])
  208. rows = []
  209. for addr in files:
  210. text = fetch_minio_text(addr)
  211. if not text:
  212. continue
  213. rows.extend(_csv_rows(text))
  214. if not rows:
  215. return {"available": False, "error": "偏航误差页面无静态偏航结果", "turbines": []}
  216. turbines = []
  217. for r in rows:
  218. turbines.append({
  219. "name": r.get("wind_turbine_name") or r.get("wind_turbine_number"),
  220. "code": r.get("wind_turbine_number"),
  221. "avg": _f(r.get("avg_yaw_error")),
  222. "abs_avg": _f(r.get("avg_abs_yaw_error")),
  223. "abs_max": _f(r.get("max_abs_yaw_error")),
  224. "count": int(_f(r.get("valid_count") or 0)),
  225. })
  226. turbines.sort(key=lambda x: x["abs_avg"], reverse=True)
  227. over3 = [t for t in turbines if t["abs_avg"] > 3]
  228. over5 = [t for t in turbines if t["abs_avg"] > 5]
  229. return {
  230. "available": True,
  231. "turbines": turbines,
  232. "avg_abs": round(sum(t["abs_avg"] for t in turbines) / len(turbines), 2) if turbines else None,
  233. "over3": len(over3),
  234. "over5": len(over5),
  235. "over3_list": [t["name"] for t in over3],
  236. "over5_list": [t["name"] for t in over5],
  237. }
  238. def collect_fault_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  239. """故障诊断页面数据:读取 autodiag 保存结果(vibration_diagnosis_result),不查故障日志表。"""
  240. code = wind["code"]
  241. start = datetime.fromisoformat(f"{months[0]}-01")
  242. y, m = map(int, months[-1].split("-"))
  243. end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
  244. conn = platform_conn()
  245. try:
  246. with conn.cursor() as cur:
  247. cur.execute(
  248. """
  249. SELECT wind_code, engine_code, point_name, diagnosis_type, max_status,
  250. component_type, create_time,
  251. COALESCE(record_time, create_time) AS rec_time
  252. FROM vibration_diagnosis_result
  253. WHERE wind_code=%s
  254. AND COALESCE(record_time, create_time) >= %s
  255. AND COALESCE(record_time, create_time) < %s
  256. ORDER BY COALESCE(record_time, create_time)
  257. """,
  258. (code, start, end),
  259. )
  260. rows = cur.fetchall() or []
  261. finally:
  262. conn.close()
  263. if not rows:
  264. return {"available": False, "error": "故障诊断页面无覆盖所选时间段的诊断结果", "monthly": [], "top_codes": [], "turbines": [], "total": 0, "affected_turbines": 0}
  265. monthly_map: Dict[str, Dict[str, Any]] = {}
  266. turbine_map: Dict[str, int] = {}
  267. type_map: Dict[str, int] = {}
  268. for row in rows:
  269. month = row["rec_time"].strftime("%Y-%m")
  270. m = monthly_map.setdefault(month, {"month": month, "count": 0})
  271. m["count"] += 1
  272. eng = row["engine_code"] or row["point_name"]
  273. if eng:
  274. turbine_map[eng] = turbine_map.get(eng, 0) + 1
  275. key = row["diagnosis_type"] or row["component_type"] or "未分类"
  276. type_map[key] = type_map.get(key, 0) + 1
  277. return {
  278. "available": True,
  279. "total": len(rows),
  280. "affected_turbines": len(turbine_map),
  281. "monthly": sorted(monthly_map.values(), key=lambda x: x["month"]),
  282. "top_codes": sorted([{"code": k, "count": v} for k, v in type_map.items()], key=lambda x: x["count"], reverse=True),
  283. "turbines": sorted([{"name": k, "count": v} for k, v in turbine_map.items()], key=lambda x: x["count"], reverse=True),
  284. }
  285. def collect_algorithm_health_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  286. """算法健康评估页面数据:/AnalysisMulti/health-assessment/detail。"""
  287. code = wind["code"]
  288. month = None
  289. # 在所选时间段内取页面最新可用期次(例如选择 2024-12 时回退到 2024-11)
  290. try:
  291. pr = requests.get(
  292. "http://127.0.0.1:8888/health-assessment/periods",
  293. params={"fieldCode": code},
  294. timeout=30,
  295. )
  296. pr.raise_for_status()
  297. periods = [x.get("period") for x in (pr.json().get("data") or [])]
  298. periods = [x for x in periods if x and months[0] <= x <= months[-1]]
  299. if periods:
  300. month = max(periods)
  301. except Exception:
  302. month = None
  303. if not month:
  304. return {"available": False, "error": "算法健康评估页面在所选时间段内无可用期次", "turbines": []}
  305. try:
  306. r = requests.get(
  307. "http://127.0.0.1:8888/health-assessment/detail",
  308. params={"fieldCode": code, "period": month},
  309. timeout=30,
  310. )
  311. r.raise_for_status()
  312. doc = (r.json() or {}).get("data") or {}
  313. except Exception as exc:
  314. return {"available": False, "error": f"算法健康评估页面无该期结果:{exc}", "turbines": []}
  315. turbines = doc.get("turbines") or []
  316. if not turbines:
  317. return {"available": False, "error": "算法健康评估页面无该期结果", "turbines": []}
  318. return {
  319. "available": True,
  320. "field_code": doc.get("field_code"),
  321. "period": doc.get("period"),
  322. "generated_at": doc.get("generated_at"),
  323. "grade_bands": doc.get("grade_bands") or [],
  324. "turbines": turbines,
  325. "treatment": doc.get("treatment") or {},
  326. }
  327. def _f(v):
  328. try:
  329. return float(v)
  330. except (TypeError, ValueError):
  331. return 0.0