page_source.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. url = f"{MINIO_ENDPOINT}/{MINIO_BUCKET}/{file_addr}"
  75. try:
  76. r = requests.get(url, timeout=timeout)
  77. r.raise_for_status()
  78. return r.text
  79. except Exception:
  80. return None
  81. def _csv_rows(text: str) -> List[Dict[str, str]]:
  82. text = (text or "").lstrip("\ufeff")
  83. reader = csv.DictReader(io.StringIO(text))
  84. return [row for row in reader]
  85. def collect_overview_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  86. """分析概览页面数据:从平台分析批次文件读取,不直接查分钟表。"""
  87. code = wind["code"]
  88. start, end = months[0], months[-1]
  89. batch = resolve_analysis_batch(code, start, end)
  90. if not batch:
  91. return {"available": False, "error": "分析概览页面无覆盖所选时间段的已完成分析批次", "monthly": [], "turbines": [], "batch_code": None}
  92. files = analysis_general_files(batch["batch_code"], list(OVERVIEW_TYPES))
  93. prod_files = files.get("production_indicator", [])
  94. integ_files = files.get("data_integrity_minute", []) + files.get("data_integrity_second", [])
  95. if not prod_files:
  96. return {"available": False, "error": "分析概览页面该批次无生产指标结果文件", "monthly": [], "turbines": [], "batch_code": batch["batch_code"]}
  97. monthly_map: Dict[str, Dict[str, Any]] = {}
  98. turbine_map: Dict[str, Dict[str, Any]] = {}
  99. total_kwh = 0.0
  100. total_points = 0
  101. weighted_wind = 0.0
  102. for file_addr in prod_files:
  103. text = fetch_minio_text(file_addr)
  104. if not text:
  105. continue
  106. for row in _csv_rows(text):
  107. month = (row.get("year_month") or row.get("month") or "").strip()
  108. if len(month) == 6:
  109. month = f"{month[:4]}-{month[4:]}"
  110. if month and month not in months:
  111. continue
  112. name = row.get("wind_turbine_name") or row.get("engine_name") or row.get("wind_turbine_number") or ""
  113. gen_kwh = _f(row.get("gen_kwh") or row.get("generation") or row.get("energy") or 0)
  114. avg_power = _f(row.get("avg_power") or row.get("active_power_avg") or 0)
  115. avg_wind = _f(row.get("avg_wind") or row.get("wind_velocity") or None)
  116. points = int(_f(row.get("points") or row.get("record_count") or 0) or 0)
  117. if not name and not month:
  118. continue
  119. total_kwh += gen_kwh
  120. total_points += points
  121. if avg_wind is not None:
  122. weighted_wind += avg_wind * max(points, 1)
  123. if month:
  124. m = monthly_map.setdefault(month, {"month": month, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
  125. m["gen_kwh"] += gen_kwh
  126. m["points"] += points
  127. if avg_wind is not None:
  128. m["wind_sum"] += avg_wind * max(points, 1)
  129. m["wind_points"] += max(points, 1)
  130. if name:
  131. t = turbine_map.setdefault(name, {"name": name, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
  132. t["gen_kwh"] += gen_kwh
  133. t["points"] += points
  134. if avg_wind is not None:
  135. t["wind_sum"] += avg_wind * max(points, 1)
  136. t["wind_points"] += max(points, 1)
  137. monthly = []
  138. for m in monthly_map.values():
  139. m["gen_mwh"] = round(m["gen_kwh"] / 1000, 2)
  140. m["avg_wind"] = round(m["wind_sum"] / m["wind_points"], 2) if m["wind_points"] else None
  141. m["completeness"] = None
  142. monthly.append(m)
  143. monthly.sort(key=lambda x: x["month"])
  144. turbines = []
  145. for t in turbine_map.values():
  146. turbines.append({
  147. "name": t["name"],
  148. "gen_mwh": round(t["gen_kwh"] / 1000, 2),
  149. "avg_power": round(t["gen_kwh"] / t["points"], 2) if t["points"] else None,
  150. "avg_wind": round(t["wind_sum"] / t["wind_points"], 2) if t["wind_points"] else None,
  151. "points": t["points"],
  152. })
  153. turbines.sort(key=lambda x: x["gen_mwh"] or 0, reverse=True)
  154. for i, t in enumerate(turbines):
  155. t["rank"] = i + 1
  156. capacity = float(wind.get("capacity_kw") or 0)
  157. total_mwh = total_kwh / 1000
  158. return {
  159. "available": True,
  160. "batch_code": batch["batch_code"],
  161. "monthly": monthly,
  162. "turbines": turbines,
  163. "total_mwh": round(total_mwh, 2),
  164. "equivalent_hours": round(total_kwh / capacity, 1) if capacity else None,
  165. "avg_wind": round(weighted_wind / total_points, 2) if total_points else None,
  166. "capacity_factor": None,
  167. "completeness": None,
  168. "integrity_files": integ_files,
  169. }
  170. def collect_fault_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  171. """故障诊断页面数据:读取 autodiag 保存结果(vibration_diagnosis_result),不查故障日志表。"""
  172. code = wind["code"]
  173. start = datetime.fromisoformat(f"{months[0]}-01")
  174. y, m = map(int, months[-1].split("-"))
  175. end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
  176. conn = platform_conn()
  177. try:
  178. with conn.cursor() as cur:
  179. cur.execute(
  180. """
  181. SELECT wind_code, engine_code, point_name, diagnosis_type, max_status,
  182. component_type, create_time
  183. FROM vibration_diagnosis_result
  184. WHERE wind_code=%s AND create_time >= %s AND create_time < %s
  185. ORDER BY create_time
  186. """,
  187. (code, start, end),
  188. )
  189. rows = cur.fetchall() or []
  190. finally:
  191. conn.close()
  192. if not rows:
  193. return {"available": False, "error": "故障诊断页面无覆盖所选时间段的诊断结果", "monthly": [], "top_codes": [], "turbines": [], "total": 0, "affected_turbines": 0}
  194. monthly_map: Dict[str, Dict[str, Any]] = {}
  195. turbine_map: Dict[str, int] = {}
  196. type_map: Dict[str, int] = {}
  197. for row in rows:
  198. month = row["create_time"].strftime("%Y-%m")
  199. m = monthly_map.setdefault(month, {"month": month, "count": 0})
  200. m["count"] += 1
  201. eng = row["engine_code"] or row["point_name"]
  202. if eng:
  203. turbine_map[eng] = turbine_map.get(eng, 0) + 1
  204. key = row["diagnosis_type"] or row["component_type"] or "未分类"
  205. type_map[key] = type_map.get(key, 0) + 1
  206. return {
  207. "available": True,
  208. "total": len(rows),
  209. "affected_turbines": len(turbine_map),
  210. "monthly": sorted(monthly_map.values(), key=lambda x: x["month"]),
  211. "top_codes": sorted([{"code": k, "count": v} for k, v in type_map.items()], key=lambda x: x["count"], reverse=True),
  212. "turbines": sorted([{"name": k, "count": v} for k, v in turbine_map.items()], key=lambda x: x["count"], reverse=True),
  213. }
  214. def collect_algorithm_health_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
  215. """算法健康评估页面数据:/AnalysisMulti/health-assessment/detail。"""
  216. code = wind["code"]
  217. month = None
  218. # 在所选时间段内取页面最新可用期次(例如选择 2024-12 时回退到 2024-11)
  219. try:
  220. pr = requests.get(
  221. "http://127.0.0.1:8888/health-assessment/periods",
  222. params={"fieldCode": code},
  223. timeout=30,
  224. )
  225. pr.raise_for_status()
  226. periods = [x.get("period") for x in (pr.json().get("data") or [])]
  227. periods = [x for x in periods if x and months[0] <= x <= months[-1]]
  228. if periods:
  229. month = max(periods)
  230. except Exception:
  231. month = None
  232. if not month:
  233. return {"available": False, "error": "算法健康评估页面在所选时间段内无可用期次", "turbines": []}
  234. try:
  235. r = requests.get(
  236. "http://127.0.0.1:8888/health-assessment/detail",
  237. params={"fieldCode": code, "period": month},
  238. timeout=30,
  239. )
  240. r.raise_for_status()
  241. doc = (r.json() or {}).get("data") or {}
  242. except Exception as exc:
  243. return {"available": False, "error": f"算法健康评估页面无该期结果:{exc}", "turbines": []}
  244. turbines = doc.get("turbines") or []
  245. if not turbines:
  246. return {"available": False, "error": "算法健康评估页面无该期结果", "turbines": []}
  247. return {
  248. "available": True,
  249. "field_code": doc.get("field_code"),
  250. "period": doc.get("period"),
  251. "generated_at": doc.get("generated_at"),
  252. "grade_bands": doc.get("grade_bands") or [],
  253. "turbines": turbines,
  254. "treatment": doc.get("treatment") or {},
  255. }
  256. def _f(v):
  257. try:
  258. return float(v)
  259. except (TypeError, ValueError):
  260. return 0.0