| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565 |
- """报告数据采集:平台库(台账/健康) + 业务库(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]:
- # 健康评估为逐机组模型推理,耗时较长;报告取时间段内最近 1 个月,
- # 其余维度(概览/故障/振动)仍覆盖完整时间段。
- assess_months = months[-1:]
- 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,
- }
- )
- if month == assess_months[-1]:
- latest_turbines = items
- except Exception as exc:
- errors.append(f"{month}: {exc}")
- 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]["distribution"] if monthly else {}
- 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:
- arr = _parse_wave(sample.get("mesure_data"))
- fs = float(sample.get("sampling_frequency") or 0)
- if arr is not None and fs > 0:
- arr = arr - float(np.mean(arr))
- n = arr.size
- win = np.hanning(n)
- amp = np.abs(np.fft.rfft(arr * win)) * 2 / max(n, 1)
- freq = np.fft.rfftfreq(n, d=1 / fs)
- keep = freq <= fs / 2.56
- freq, amp = freq[keep], amp[keep]
- if freq.size > 1500:
- idx = np.linspace(0, freq.size - 1, 1500).astype(int)
- freq, amp = freq[idx], amp[idx]
- spectrum = {
- "freq": [round(float(x), 3) for x in freq],
- "amp": [round(float(x), 6) for x in amp],
- "fs": fs,
- "rms": round(float(np.sqrt(np.mean(arr ** 2))), 4),
- "point": sample.get("mesure_point_name"),
- "time": str(sample.get("time_stamp")),
- "rpm": sample.get("rotational_speed"),
- }
- 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]:
- 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": collect_overview(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": "未勾选健康评估章节"},
- "fault": collect_fault(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(台账/健康)",
- },
- }
- return data
|