"""报告数据采集:平台库(台账/健康) + 业务库(SCADA/故障/振动)。 所有查询只读取本机配置指定的数据库,不访问互联网。 """ from __future__ import annotations import calendar import json import math import os import re from datetime import datetime, timedelta from typing import Any, Dict, List, Optional, Tuple import numpy as np import pymysql import requests from pymysql.cursors import DictCursor from app.config import dataSettings, platformSettings HEALTH_API = os.getenv("HEALTH_API", "http://127.0.0.1:8888/health_assess") def _split_host(value: str) -> Tuple[str, int]: if ":" in value: host, port = value.rsplit(":", 1) return host, int(port) return value, 3306 def _connect(settings, database: str): host, port = _split_host(settings.db_host) return pymysql.connect( host=host, port=port, user=settings.db_user, password=settings.db_password, database=database, charset="utf8mb4", cursorclass=DictCursor, connect_timeout=15, read_timeout=600, write_timeout=600, autocommit=True, ) def platform_conn(): return _connect(platformSettings, platformSettings.db_name) def business_conn(): return _connect(dataSettings, dataSettings.db_name) def safe_code(code: str) -> str: if not re.fullmatch(r"[A-Za-z0-9_]+", code or ""): raise ValueError("非法的风场编号") return code def month_list(start_month: str, end_month: str) -> List[str]: sy, sm = map(int, start_month.split("-")) ey, em = map(int, end_month.split("-")) if (sy, sm) > (ey, em): raise ValueError("开始月份不能晚于结束月份") out = [] y, m = sy, sm while (y, m) <= (ey, em): out.append(f"{y:04d}-{m:02d}") m += 1 if m > 12: y += 1 m = 1 return out def _month_bounds(month: str) -> Tuple[datetime, datetime]: y, m = map(int, month.split("-")) start = datetime(y, m, 1) end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1) return start, end def _table_exists(conn, table: str) -> bool: with conn.cursor() as cur: cur.execute( "SELECT COUNT(*) AS c FROM information_schema.tables " "WHERE table_schema = DATABASE() AND table_name = %s", (table,), ) return cur.fetchone()["c"] > 0 def get_wind_info(wind_code: str) -> Dict[str, Any]: wind_code = safe_code(wind_code) conn = platform_conn() try: with conn.cursor() as cur: cur.execute( "SELECT field_code, field_name, company_code, rated_capacity_number " "FROM wind_field WHERE field_code=%s", (wind_code,), ) field = cur.fetchone() or {} cur.execute( "SELECT engine_code, engine_name, mill_type_code, rated_capacity " "FROM wind_engine_group WHERE field_code=%s AND del_state=0 " "ORDER BY engine_name", (wind_code,), ) turbines = cur.fetchall() or [] cur.execute( "SELECT company_name FROM wind_company WHERE company_code=%s", (field.get("company_code"),), ) company = cur.fetchone() or {} finally: conn.close() capacity = float(field.get("rated_capacity_number") or 0) if capacity <= 0: capacity = sum(float(t.get("rated_capacity") or 0) for t in turbines) return { "code": wind_code, "name": field.get("field_name") or wind_code, "company": company.get("company_name") or field.get("company_code") or "", "capacity_kw": capacity, "turbine_count": len(turbines), "turbines": turbines, } def collect_overview(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]: try: code = wind["code"] table = f"`{safe_code(code)}_minute`" start_ym = int(months[0].replace("-", "")) end_ym = int(months[-1].replace("-", "")) conn = business_conn() try: if not _table_exists(conn, f"{code}_minute"): return {"available": False, "error": f"未找到 {code}_minute 表", "monthly": [], "turbines": []} with conn.cursor() as cur: cur.execute( f""" SELECT `year_month`, `wind_turbine_number`, MAX(wind_turbine_name) AS turbine_name, COUNT(*) AS points, AVG(active_power) AS avg_power, AVG(wind_velocity) AS avg_wind, SUM(active_power) / 60.0 AS gen_kwh FROM {table} WHERE `year_month` BETWEEN %s AND %s GROUP BY `year_month`, `wind_turbine_number` """, (start_ym, end_ym), ) rows = cur.fetchall() or [] finally: conn.close() if not rows: return {"available": False, "error": "所选时间段内无分钟级 SCADA 数据", "monthly": [], "turbines": []} monthly_map: Dict[str, Dict[str, Any]] = {} turbine_map: Dict[str, Dict[str, Any]] = {} total_kwh = 0.0 total_points = 0 weighted_wind = 0.0 for row in rows: ym = int(row["year_month"]) month = f"{ym // 100:04d}-{ym % 100:02d}" points = int(row["points"] or 0) gen_kwh = float(row["gen_kwh"] or 0) avg_power = float(row["avg_power"] or 0) avg_wind = float(row["avg_wind"] or 0) if row["avg_wind"] is not None else None code_t = row["wind_turbine_number"] name_t = row["turbine_name"] or code_t m = monthly_map.setdefault( month, {"month": month, "gen_kwh": 0.0, "points": 0, "wind_points": 0, "wind_sum": 0.0, "turbines": 0}, ) m["gen_kwh"] += gen_kwh m["points"] += points m["turbines"] += 1 if avg_wind is not None: m["wind_sum"] += avg_wind * points m["wind_points"] += points t = turbine_map.setdefault( code_t, { "code": code_t, "name": name_t, "gen_kwh": 0.0, "points": 0, "wind_points": 0, "wind_sum": 0.0, "power_weighted": 0.0, }, ) t["gen_kwh"] += gen_kwh t["points"] += points t["power_weighted"] += avg_power * points if avg_wind is not None: t["wind_sum"] += avg_wind * points t["wind_points"] += points total_kwh += gen_kwh total_points += points if avg_wind is not None: weighted_wind += avg_wind * points # 完整率:按月内应有分钟数计算 for month, m in monthly_map.items(): days = calendar.monthrange(int(month[:4]), int(month[5:]))[1] expected = days * 1440 * max(m["turbines"], 1) m["completeness"] = round(min(1.0, m["points"] / expected) * 100, 2) if expected else 0.0 m["gen_mwh"] = round(m["gen_kwh"] / 1000, 2) m["avg_wind"] = round(m["wind_sum"] / m["wind_points"], 2) if m["wind_points"] else None turbines = [] for t in turbine_map.values(): turbines.append( { "code": t["code"], "name": t["name"], "gen_mwh": round(t["gen_kwh"] / 1000, 2), "avg_power": round(t["power_weighted"] / t["points"], 2) if t["points"] else 0, "avg_wind": round(t["wind_sum"] / t["wind_points"], 2) if t["wind_points"] else None, "points": t["points"], } ) turbines.sort(key=lambda x: x["gen_mwh"], reverse=True) for i, t in enumerate(turbines): t["rank"] = i + 1 capacity = float(wind.get("capacity_kw") or 0) total_mwh = total_kwh / 1000 total_hours = sum( (calendar.monthrange(int(m[:4]), int(m[5:]))[1]) * 24 for m in months ) return { "available": True, "monthly": sorted(monthly_map.values(), key=lambda x: x["month"]), "turbines": turbines, "total_mwh": round(total_mwh, 2), "equivalent_hours": round(total_kwh / capacity, 1) if capacity else None, "avg_wind": round(weighted_wind / total_points, 2) if total_points else None, "capacity_factor": round(total_kwh / (capacity * total_hours) * 100, 2) if capacity and total_hours else None, "completeness": round( sum(m["completeness"] for m in monthly_map.values()) / len(monthly_map), 2 ) if monthly_map else None, "best": turbines[:3], "worst": list(reversed(turbines[-3:])) if len(turbines) >= 3 else list(reversed(turbines)), } except Exception as exc: return {"available": False, "error": str(exc), "monthly": [], "turbines": []} def _call_health(wind_code: str, month: str) -> List[Dict[str, Any]]: resp = requests.post( HEALTH_API, json={"windcode": wind_code, "month": month}, timeout=900, ) resp.raise_for_status() data = resp.json() if isinstance(data, dict) and data.get("detail"): raise RuntimeError(str(data.get("detail"))) if not isinstance(data, list): raise RuntimeError("健康评估返回格式异常") return data def collect_health(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]: # 报告与健康评估页同源:按所选时间段逐月调用健康评估页接口。 assess_months = list(months) monthly = [] latest_turbines: List[Dict[str, Any]] = [] errors = [] for month in assess_months: try: items = _call_health(wind["code"], month) scores = [float(x.get("total_health_score", -1)) for x in items] valid = [s for s in scores if s >= 0] dist = {"healthy": 0, "subhealthy": 0, "normal": 0, "fault": 0, "nodata": 0} for s in scores: if s < 0: dist["nodata"] += 1 elif s >= 85: dist["healthy"] += 1 elif s >= 70: dist["subhealthy"] += 1 elif s >= 55: dist["normal"] += 1 else: dist["fault"] += 1 monthly.append( { "month": month, "count": len(items), "avg_score": round(sum(valid) / len(valid), 2) if valid else None, "min_score": round(min(valid), 2) if valid else None, "max_score": round(max(valid), 2) if valid else None, "distribution": dist, "turbines": items, "valid_count": len(valid), } ) except Exception as exc: errors.append(f"{month}: {exc}") # 年度区间下,健康评估页面可能只有部分月份有有效结果; # 取最后一个月有有效结果的月份作为单机明细(总分布按所有月份汇总)。 last_valid_month = None for m in reversed(monthly): if m.get("valid_count"): last_valid_month = m.get("month") break latest_turbines = [] for m in monthly: if m.get("month") == last_valid_month: latest_turbines = m.get("turbines") or [] break turbines = [] for x in latest_turbines: subsystems = x.get("subsystems") or {} turbines.append( { "code": x.get("engine_code"), "name": x.get("wind_turbine_name"), "score": x.get("total_health_score", -1), "generator": (subsystems.get("generator") or {}).get("health_score", -1), "nacelle": (subsystems.get("nacelle") or {}).get("health_score", -1), "grid": (subsystems.get("grid") or {}).get("health_score", -1), "drive_train": (subsystems.get("drive_train") or {}).get("health_score", -1), } ) turbines.sort(key=lambda x: (x["score"] < 0, -(x["score"] if x["score"] >= 0 else -1))) valid_turbines = [t for t in turbines if t["score"] >= 0] subsys_avg = {} for key in ["generator", "nacelle", "grid", "drive_train"]: vals = [t[key] for t in valid_turbines if t[key] is not None and t[key] >= 0] subsys_avg[key] = round(sum(vals) / len(vals), 2) if vals else None latest_dist = (monthly[-1] if monthly else {}).get("distribution") or {} return { "available": bool(monthly) and bool(valid_turbines), "months": monthly, "turbines": turbines, "avg_score": round(sum(t["score"] for t in valid_turbines) / len(valid_turbines), 2) if valid_turbines else None, "distribution": latest_dist, "subsystems": subsys_avg, "low_turbines": [t for t in valid_turbines if t["score"] < 70][:10], "errors": errors, "assessed_months": assess_months, } def collect_fault(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]: code = wind["code"] table_name = f"{code}_fault" start, _ = _month_bounds(months[0]) _, end = _month_bounds(months[-1]) try: conn = business_conn() try: if not _table_exists(conn, table_name): return { "available": False, "error": f"未找到 {table_name} 故障表(该风场可能未接入故障日志)", "monthly": [], "top_codes": [], } with conn.cursor() as cur: cur.execute( f""" SELECT DATE_FORMAT(begin_time, '%%Y-%%m') AS month, COUNT(*) AS count, COUNT(DISTINCT wind_turbine_number) AS turbines FROM `{table_name}` WHERE begin_time >= %s AND begin_time < %s GROUP BY month ORDER BY month """, (start, end), ) monthly = cur.fetchall() or [] cur.execute( f""" SELECT COALESCE(NULLIF(fault_code, ''), '未编码') AS code, COUNT(*) AS count, COUNT(DISTINCT wind_turbine_number) AS turbines FROM `{table_name}` WHERE begin_time >= %s AND begin_time < %s GROUP BY code ORDER BY count DESC LIMIT 10 """, (start, end), ) top_codes = cur.fetchall() or [] cur.execute( f""" SELECT wind_turbine_name AS name, COUNT(*) AS count FROM `{table_name}` WHERE begin_time >= %s AND begin_time < %s GROUP BY wind_turbine_name ORDER BY count DESC LIMIT 10 """, (start, end), ) turbines = cur.fetchall() or [] cur.execute( f"SELECT COUNT(*) AS c, COUNT(DISTINCT wind_turbine_number) AS t " f"FROM `{table_name}` WHERE begin_time >= %s AND begin_time < %s", (start, end), ) summary = cur.fetchone() or {} finally: conn.close() for row in top_codes: row["code"] = str(row["code"])[:40] return { "available": summary.get("c", 0) > 0, "total": int(summary.get("c", 0) or 0), "affected_turbines": int(summary.get("t", 0) or 0), "monthly": monthly, "top_codes": top_codes, "turbines": turbines, } except Exception as exc: return {"available": False, "error": str(exc), "monthly": [], "top_codes": []} def _parse_wave(raw: str) -> Optional[np.ndarray]: try: data = json.loads(raw) if isinstance(data, dict): data = data.get("data") or data.get("values") or [] arr = np.asarray(data, dtype=float) arr = arr[np.isfinite(arr)] return arr if arr.size else None except Exception: try: cleaned = str(raw).strip().strip("[]") arr = np.asarray([float(x) for x in cleaned.split(",") if x.strip()], dtype=float) return arr if arr.size else None except Exception: return None def collect_vibration(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]: code = wind["code"] table_name = f"{code}_wave" start, _ = _month_bounds(months[0]) _, end = _month_bounds(months[-1]) try: conn = business_conn() try: if not _table_exists(conn, table_name): return { "available": False, "error": f"未找到 {table_name} 振动波形表", "points": [], "monthly": [], } with conn.cursor() as cur: cur.execute( f"SELECT COUNT(*) AS c, COUNT(DISTINCT wind_turbine_number) AS t, " f"COUNT(DISTINCT mesure_point_name) AS p, MIN(time_stamp) AS mn, MAX(time_stamp) AS mx " f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s", (start, end), ) summary = cur.fetchone() or {} cur.execute( f"SELECT mesure_point_name AS point, COUNT(*) AS count, " f"ROUND(AVG(sampling_frequency),0) AS fs " f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s " f"GROUP BY point ORDER BY count DESC LIMIT 12", (start, end), ) points = cur.fetchall() or [] for p in points: p["fs"] = float(p["fs"]) if p.get("fs") is not None else None cur.execute( f"SELECT DATE_FORMAT(time_stamp, '%%Y-%%m') AS month, COUNT(*) AS count " f"FROM `{table_name}` WHERE time_stamp >= %s AND time_stamp < %s " f"GROUP BY month ORDER BY month", (start, end), ) monthly = cur.fetchall() or [] cur.execute( f"SELECT id, time_stamp, sampling_frequency, mesure_point_name, " f"rotational_speed, mesure_data FROM `{table_name}` " f"WHERE time_stamp >= %s AND time_stamp < %s " f"AND mesure_point_name LIKE '%%main_bearing%%' " f"ORDER BY time_stamp DESC LIMIT 1", (start, end), ) sample = cur.fetchone() if not sample: cur.execute( f"SELECT id, time_stamp, sampling_frequency, mesure_point_name, " f"rotational_speed, mesure_data FROM `{table_name}` " f"WHERE time_stamp >= %s AND time_stamp < %s " f"ORDER BY time_stamp DESC LIMIT 1", (start, end), ) sample = cur.fetchone() finally: conn.close() spectrum = None if sample: # 与振动分析页面同源:调用 CMSAnalyst 生成频域图 try: from app.services.CMSAnalyst import CMSAnalyst cms = CMSAnalyst(0, None, code, [int(sample.get("id"))], light=False) freq = json.loads(cms.frequency_domain()) spectrum = { "freq": [round(float(x), 3) for x in freq.get("x", [])], "amp": [round(float(x), 6) for x in freq.get("y", [])], "fs": freq.get("fs"), "rms": freq.get("Xrms"), "point": sample.get("mesure_point_name"), "time": str(sample.get("time_stamp")), "rpm": sample.get("rotational_speed"), "source": "CMSAnalyst", } except Exception: spectrum = None return { "available": (summary.get("c", 0) or 0) > 0, "total": int(summary.get("c", 0) or 0), "turbine_count": int(summary.get("t", 0) or 0), "point_count": int(summary.get("p", 0) or 0), "min_time": str(summary.get("mn")) if summary.get("mn") else None, "max_time": str(summary.get("mx")) if summary.get("mx") else None, "points": points, "monthly": monthly, "spectrum": spectrum, } except Exception as exc: return {"available": False, "error": str(exc), "points": [], "monthly": []} def collect_all(wind_code: str, start_month: str, end_month: str, sections=None) -> Dict[str, Any]: from app.report import page_source months = month_list(start_month, end_month) wind = get_wind_info(wind_code) selected = set(sections or ["overview", "health", "fault", "vibration"]) data = { "wind": wind, "period": {"start": start_month, "end": end_month, "months": months, "month_count": len(months)}, "overview": page_source.collect_overview_from_page(wind, months) if "overview" in selected else {"available": False, "error": "未勾选分析概览章节", "monthly": [], "turbines": []}, "health": collect_health(wind, months) if "health" in selected else {"available": False, "error": "未勾选健康评估章节"}, "algorithm_health": page_source.collect_algorithm_health_from_page(wind, months), "yaw": page_source.collect_yaw_from_page(wind, months), "fault": page_source.collect_fault_from_page(wind, months) if "fault" in selected else {"available": False, "error": "未勾选故障诊断章节", "monthly": [], "top_codes": []}, "vibration": collect_vibration(wind, months) if "vibration" in selected else {"available": False, "error": "未勾选振动分析章节", "points": [], "monthly": []}, "meta": { "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "data_source": "energy_data_prod(SCADA/故障/振动) + energy_prod(台账/健康)", }, "provenance": { "overview": { "page": "分析概览", "source": "platform.analysis_result / analysis_general_file(页面 analysisDetail 同源)", "period": [start_month, end_month], "filter": "分析批次文件", }, "algorithm_health": { "page": "算法健康评估", "source": "http://127.0.0.1:8888/health-assessment/detail", "period": months, "filter": "fieldCode + period,读取 health.json", }, "yaw": { "page": "偏航误差分析", "source": "platform.analysis_general_file(yaw_error)", "period": [start_month, end_month], "filter": "静态偏航误差分析文件", }, "health": { "page": "健康评估", "source": HEALTH_API, "period": months, "filter": "windcode + month,逐月调用页面接口", }, "fault": { "page": "故障诊断", "source": "platform.vibration_diagnosis_result(页面 autodiag 结果)", "period": [start_month, end_month], "filter": "create_time 月区间", }, "vibration": { "page": "振动分析", "source": "CMSAnalyst(振动分析页面 CMS 波形)", "period": [start_month, end_month], "filter": "time_stamp 月区间 + CMS 频域分析", }, }, } return data