| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358 |
- """报告页面数据源:只读取健康度检测平台各页面实际使用的数据。
- 对应关系:
- - 分析概览 -> platform.analysis_result / analysis_general_file(页面 analysisDetail 同源)
- - 健康评估 -> /AnalysisMulti/health_assess(页面同源)
- - 算法健康评估 -> /AnalysisMulti/health-assessment/detail(页面同源)
- - 故障诊断 -> platform.vibration_diagnosis_result(页面 autodiag 保存结果)
- - 振动分析 -> energy_data_prod.<场码>_wave(页面 CMS 分析底层数据源)
- 页面没有对应时间段的结果时,返回 unavailable + 说明,报告不得回退到底层表编造数据。
- """
- from __future__ import annotations
- import csv
- import io
- import os
- from datetime import datetime
- from typing import Any, Dict, List, Optional, Tuple
- import requests
- from app.report.collector import platform_conn, safe_code
- MINIO_ENDPOINT = os.getenv("MINIO_ENDPOINT", "http://127.0.0.1:9000")
- MINIO_BUCKET = os.getenv("MINIO_BUCKET", "bucket-zhzn")
- OVERVIEW_TYPES = {
- "production_indicator": "机组/全场生产指标",
- "data_integrity_minute": "分钟级数据完整度",
- "data_integrity_second": "秒级数据完整度",
- "yaw_error": "静态偏航误差",
- "power_curve": "有功功率曲线",
- }
- FAULT_TYPE = "fault"
- def resolve_analysis_batch(field_code: str, start_month: str, end_month: str) -> Optional[Dict[str, Any]]:
- """返回覆盖所选时间段、最近完成的平台分析批次(分析概览页面使用的批次)。"""
- field_code = safe_code(field_code)
- start = datetime.fromisoformat(f"{start_month}-01")
- y, m = map(int, end_month.split("-"))
- end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
- conn = platform_conn()
- try:
- with conn.cursor() as cur:
- cur.execute(
- """
- SELECT batch_code, field_code, analysis_name, data_start_time, data_end_time, analysis_state
- FROM analysis_result
- WHERE field_code=%s AND analysis_state=30
- AND (data_type_code IS NULL OR data_type_code <> 'health_assessment')
- AND data_start_time < %s AND data_end_time > %s
- ORDER BY data_start_time DESC, id DESC
- LIMIT 1
- """,
- (field_code, end, start),
- )
- return cur.fetchone()
- finally:
- conn.close()
- def analysis_general_files(batch_code: str, type_codes: List[str]) -> Dict[str, List[str]]:
- """按分析类型取页面 analysisDetail 使用的总文件地址。"""
- if not batch_code or not type_codes:
- return {}
- conn = platform_conn()
- try:
- placeholders = ",".join(["%s"] * len(type_codes))
- with conn.cursor() as cur:
- cur.execute(
- f"SELECT analysis_type_code, file_addr FROM analysis_general_file "
- f"WHERE batch_code=%s AND analysis_type_code IN ({placeholders}) "
- "ORDER BY id",
- (batch_code, *type_codes),
- )
- out: Dict[str, List[str]] = {}
- for row in cur.fetchall():
- out.setdefault(row["analysis_type_code"], []).append(row["file_addr"])
- return out
- finally:
- conn.close()
- def fetch_minio_text(file_addr: str, timeout: int = 60) -> Optional[str]:
- """读取 MinIO 对象文本(CSV/JSON),供报告复用页面文件。"""
- key = file_addr
- if key.startswith("/minio/"):
- key = key[len("/minio/"):]
- url = f"{MINIO_ENDPOINT}/{MINIO_BUCKET}/{key}"
- try:
- r = requests.get(url, timeout=timeout)
- r.raise_for_status()
- return r.content.decode("utf-8-sig", errors="replace")
- except Exception:
- return None
- def _csv_rows(text: str) -> List[Dict[str, str]]:
- text = (text or "").lstrip("\ufeff")
- reader = csv.DictReader(io.StringIO(text))
- return [row for row in reader]
- def collect_overview_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
- """分析概览页面数据:从平台分析批次文件读取,不直接查分钟表。"""
- code = wind["code"]
- start, end = months[0], months[-1]
- batch = resolve_analysis_batch(code, start, end)
- if not batch:
- return {"available": False, "error": "分析概览页面无覆盖所选时间段的已完成分析批次", "monthly": [], "turbines": [], "batch_code": None}
- files = analysis_general_files(batch["batch_code"], list(OVERVIEW_TYPES))
- prod_files = files.get("production_indicator", [])
- integ_files = files.get("data_integrity_minute", []) + files.get("data_integrity_second", [])
- if not prod_files:
- return {"available": False, "error": "分析概览页面该批次无生产指标结果文件", "monthly": [], "turbines": [], "batch_code": batch["batch_code"]}
- 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 file_addr in prod_files:
- text = fetch_minio_text(file_addr)
- if not text:
- continue
- for row in _csv_rows(text):
- month = (row.get("year_month") or row.get("month") or "").strip()
- if len(month) == 6:
- month = f"{month[:4]}-{month[4:]}"
- if month and month not in months:
- continue
- name = row.get("wind_turbine_name") or row.get("engine_name") or row.get("wind_turbine_number") or ""
- if name in ("全场", "场站"):
- continue
- if name == "":
- name = row.get("wind_turbine_number") or name
- gen_kwh = _f(row.get("gen_kwh") or row.get("EPActualTotal") or row.get("generation") or row.get("energy") or 0)
- avg_power = _f(row.get("avg_power") or row.get("active_power_avg") or 0)
- avg_wind = _f(row.get("avg_wind") or row.get("WindSpeedAvr") or row.get("wind_velocity") or None)
- points = int(_f(row.get("points") or row.get("record_count") or 0) or 0)
- if not name and not month:
- continue
- total_kwh += gen_kwh
- total_points += points
- if avg_wind is not None:
- weighted_wind += avg_wind * max(points, 1)
- if month:
- m = monthly_map.setdefault(month, {"month": month, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
- m["gen_kwh"] += gen_kwh
- m["points"] += points
- if avg_wind is not None:
- m["wind_sum"] += avg_wind * max(points, 1)
- m["wind_points"] += max(points, 1)
- if name:
- t = turbine_map.setdefault(name, {"name": name, "gen_kwh": 0.0, "points": 0, "wind_sum": 0.0, "wind_points": 0})
- t["gen_kwh"] += gen_kwh
- t["points"] += points
- if avg_wind is not None:
- t["wind_sum"] += avg_wind * max(points, 1)
- t["wind_points"] += max(points, 1)
- # 数据完整度(分钟级),读取页面同源 data_integrity_minute 文件
- comp_total_valid = 0
- comp_total_expected = 0
- comp_by_month: Dict[str, Any] = {}
- for file_addr in integ_files:
- text = fetch_minio_text(file_addr)
- if not text:
- continue
- for row in _csv_rows(text):
- month = (row.get("month") or "").strip()
- valid = int(_f(row.get("valid_count") or 0))
- expected = int(_f(row.get("expected_count") or 0))
- if expected <= 0:
- continue
- comp_total_valid += valid
- comp_total_expected += expected
- m = comp_by_month.setdefault(month, {"v": 0, "e": 0})
- m["v"] += valid
- m["e"] += expected
- monthly = []
- for m in monthly_map.values():
- 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
- cm = comp_by_month.get(m["month"])
- m["completeness"] = round(cm["v"] / cm["e"] * 100, 2) if cm and cm["e"] else None
- monthly.append(m)
- monthly.sort(key=lambda x: x["month"])
- turbines = []
- for t in turbine_map.values():
- turbines.append({
- "name": t["name"],
- "gen_mwh": round(t["gen_kwh"] / 1000, 2),
- "avg_power": round(t["gen_kwh"] / t["points"], 2) if t["points"] else None,
- "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"] or 0, 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
- return {
- "available": True,
- "batch_code": batch["batch_code"],
- "monthly": monthly,
- "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": None,
- "completeness": round(comp_total_valid / comp_total_expected * 100, 2) if comp_total_expected else None,
- "integrity_files": integ_files,
- }
- def collect_yaw_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
- """静态偏航误差:读取页面同源 yaw_error 分析文件。"""
- code = wind["code"]
- start, end = months[0], months[-1]
- batch = resolve_analysis_batch(code, start, end)
- if not batch:
- return {"available": False, "error": "偏航误差页面无覆盖所选时间段的分析批次", "turbines": []}
- files = analysis_general_files(batch["batch_code"], ["yaw_error"]).get("yaw_error", [])
- rows = []
- for addr in files:
- text = fetch_minio_text(addr)
- if not text:
- continue
- rows.extend(_csv_rows(text))
- if not rows:
- return {"available": False, "error": "偏航误差页面无静态偏航结果", "turbines": []}
- turbines = []
- for r in rows:
- turbines.append({
- "name": r.get("wind_turbine_name") or r.get("wind_turbine_number"),
- "code": r.get("wind_turbine_number"),
- "avg": _f(r.get("avg_yaw_error")),
- "abs_avg": _f(r.get("avg_abs_yaw_error")),
- "abs_max": _f(r.get("max_abs_yaw_error")),
- "count": int(_f(r.get("valid_count") or 0)),
- })
- turbines.sort(key=lambda x: x["abs_avg"], reverse=True)
- over3 = [t for t in turbines if t["abs_avg"] > 3]
- over5 = [t for t in turbines if t["abs_avg"] > 5]
- return {
- "available": True,
- "turbines": turbines,
- "avg_abs": round(sum(t["abs_avg"] for t in turbines) / len(turbines), 2) if turbines else None,
- "over3": len(over3),
- "over5": len(over5),
- "over3_list": [t["name"] for t in over3],
- "over5_list": [t["name"] for t in over5],
- }
- def collect_fault_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
- """故障诊断页面数据:读取 autodiag 保存结果(vibration_diagnosis_result),不查故障日志表。"""
- code = wind["code"]
- start = datetime.fromisoformat(f"{months[0]}-01")
- y, m = map(int, months[-1].split("-"))
- end = datetime(y + (1 if m == 12 else 0), 1 if m == 12 else m + 1, 1)
- conn = platform_conn()
- try:
- with conn.cursor() as cur:
- cur.execute(
- """
- SELECT wind_code, engine_code, point_name, diagnosis_type, max_status,
- component_type, create_time,
- COALESCE(record_time, create_time) AS rec_time
- FROM vibration_diagnosis_result
- WHERE wind_code=%s
- AND COALESCE(record_time, create_time) >= %s
- AND COALESCE(record_time, create_time) < %s
- ORDER BY COALESCE(record_time, create_time)
- """,
- (code, start, end),
- )
- rows = cur.fetchall() or []
- finally:
- conn.close()
- if not rows:
- return {"available": False, "error": "故障诊断页面无覆盖所选时间段的诊断结果", "monthly": [], "top_codes": [], "turbines": [], "total": 0, "affected_turbines": 0}
- monthly_map: Dict[str, Dict[str, Any]] = {}
- turbine_map: Dict[str, int] = {}
- type_map: Dict[str, int] = {}
- for row in rows:
- month = row["rec_time"].strftime("%Y-%m")
- m = monthly_map.setdefault(month, {"month": month, "count": 0})
- m["count"] += 1
- eng = row["engine_code"] or row["point_name"]
- if eng:
- turbine_map[eng] = turbine_map.get(eng, 0) + 1
- key = row["diagnosis_type"] or row["component_type"] or "未分类"
- type_map[key] = type_map.get(key, 0) + 1
- return {
- "available": True,
- "total": len(rows),
- "affected_turbines": len(turbine_map),
- "monthly": sorted(monthly_map.values(), key=lambda x: x["month"]),
- "top_codes": sorted([{"code": k, "count": v} for k, v in type_map.items()], key=lambda x: x["count"], reverse=True),
- "turbines": sorted([{"name": k, "count": v} for k, v in turbine_map.items()], key=lambda x: x["count"], reverse=True),
- }
- def collect_algorithm_health_from_page(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]:
- """算法健康评估页面数据:/AnalysisMulti/health-assessment/detail。"""
- code = wind["code"]
- month = None
- # 在所选时间段内取页面最新可用期次(例如选择 2024-12 时回退到 2024-11)
- try:
- pr = requests.get(
- "http://127.0.0.1:8888/health-assessment/periods",
- params={"fieldCode": code},
- timeout=30,
- )
- pr.raise_for_status()
- periods = [x.get("period") for x in (pr.json().get("data") or [])]
- periods = [x for x in periods if x and months[0] <= x <= months[-1]]
- if periods:
- month = max(periods)
- except Exception:
- month = None
- if not month:
- return {"available": False, "error": "算法健康评估页面在所选时间段内无可用期次", "turbines": []}
- try:
- r = requests.get(
- "http://127.0.0.1:8888/health-assessment/detail",
- params={"fieldCode": code, "period": month},
- timeout=30,
- )
- r.raise_for_status()
- doc = (r.json() or {}).get("data") or {}
- except Exception as exc:
- return {"available": False, "error": f"算法健康评估页面无该期结果:{exc}", "turbines": []}
- turbines = doc.get("turbines") or []
- if not turbines:
- return {"available": False, "error": "算法健康评估页面无该期结果", "turbines": []}
- return {
- "available": True,
- "field_code": doc.get("field_code"),
- "period": doc.get("period"),
- "generated_at": doc.get("generated_at"),
- "grade_bands": doc.get("grade_bands") or [],
- "turbines": turbines,
- "treatment": doc.get("treatment") or {},
- }
- def _f(v):
- try:
- return float(v)
- except (TypeError, ValueError):
- return 0.0
|