Przeglądaj źródła

fix: source report strictly from platform page data

zhouyang.xie 1 tydzień temu
rodzic
commit
3aa71b7f70
3 zmienionych plików z 330 dodań i 25 usunięć
  1. 15 6
      app/report/collector.py
  2. 270 0
      app/report/page_source.py
  3. 45 19
      app/report/template_builder.py

+ 15 - 6
app/report/collector.py

@@ -546,15 +546,18 @@ def collect_vibration(wind: Dict[str, Any], months: List[str]) -> Dict[str, Any]
 
 
 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": collect_overview(wind, months) if "overview" in selected else {"available": False, "error": "未勾选分析概览章节", "monthly": [], "turbines": []},
+        "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": "未勾选健康评估章节"},
-        "fault": collect_fault(wind, months) if "fault" in selected else {"available": False, "error": "未勾选故障诊断章节", "monthly": [], "top_codes": []},
+        "algorithm_health": page_source.collect_algorithm_health_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"),
@@ -563,9 +566,15 @@ def collect_all(wind_code: str, start_month: str, end_month: str, sections=None)
         "provenance": {
             "overview": {
                 "page": "分析概览",
-                "source": f"energy_data_prod.{wind_code}_minute",
+                "source": "platform.analysis_result / analysis_general_file(页面 analysisDetail 同源)",
                 "period": [start_month, end_month],
-                "filter": "year_month + 分钟级有功/风速聚合",
+                "filter": "分析批次文件",
+            },
+            "algorithm_health": {
+                "page": "算法健康评估",
+                "source": "http://127.0.0.1:8888/health-assessment/detail",
+                "period": months,
+                "filter": "fieldCode + period,读取 health.json",
             },
             "health": {
                 "page": "健康评估",
@@ -575,9 +584,9 @@ def collect_all(wind_code: str, start_month: str, end_month: str, sections=None)
             },
             "fault": {
                 "page": "故障诊断",
-                "source": f"energy_data_prod.{wind_code}_fault",
+                "source": "platform.vibration_diagnosis_result(页面 autodiag 结果)",
                 "period": [start_month, end_month],
-                "filter": "time_stamp 月区间",
+                "filter": "create_time 月区间",
             },
             "vibration": {
                 "page": "振动分析",

+ 270 - 0
app/report/page_source.py

@@ -0,0 +1,270 @@
+"""报告页面数据源:只读取健康度检测平台各页面实际使用的数据。
+
+对应关系:
+- 分析概览  -> 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_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),供报告复用页面文件。"""
+    url = f"{MINIO_ENDPOINT}/{MINIO_BUCKET}/{file_addr}"
+    try:
+        r = requests.get(url, timeout=timeout)
+        r.raise_for_status()
+        return r.text
+    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 ""
+            gen_kwh = _f(row.get("gen_kwh") 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("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)
+
+    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
+        m["completeness"] = 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": None,
+        "integrity_files": integ_files,
+    }
+
+
+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
+                FROM vibration_diagnosis_result
+                WHERE wind_code=%s AND create_time >= %s AND create_time < %s
+                ORDER BY 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["create_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 = months[-1]
+    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

+ 45 - 19
app/report/template_builder.py

@@ -266,25 +266,51 @@ def _section_reliability(doc, data: Dict[str, Any], tmp: str):
     L._heading(doc, "5.2 大部件温度异常检测", 2)
     if not h.get("available"):
         L._para(doc, f"健康评估数据不足:{h.get('error', '未取得有效记录')}。")
-        return
-    sub = h.get("subsystems") or {}
-    L._table(
-        doc,
-        ["子系统", "平均得分", "关注点"],
-        [
-            ["发电机组", _num(sub.get("generator"), 2), "绕组、轴承温度与电气量"],
-            ["机舱系统", _num(sub.get("nacelle"), 2), "机舱振动、温度与位置"],
-            ["电网环境", _num(sub.get("grid"), 2), "电流、功率与并网质量"],
-            ["传动系统", _num(sub.get("drive_train"), 2), "主轴承、齿轮箱温度"],
-        ],
-        [4.5, 4.0, 8.0],
-    )
-    L._image(doc, L.charts.health_subsystems(sub, os.path.join(tmp, "health_subsys.png")), "图 5-3 子系统平均健康得分")
-    L._para(
-        doc,
-        "大部件温度异常检测需要温度测点与工况数据的完整配对。本期健康评估已对发电机、机舱、"
-        "电网环境和传动系统给出综合得分;具体温度偏差、温升趋势和传感器可信度仍需结合专项温度分析复核。",
-    )
+    else:
+        sub = h.get("subsystems") or {}
+        L._table(
+            doc,
+            ["子系统", "平均得分", "关注点"],
+            [
+                ["发电机组", _num(sub.get("generator"), 2), "绕组、轴承温度与电气量"],
+                ["机舱系统", _num(sub.get("nacelle"), 2), "机舱振动、温度与位置"],
+                ["电网环境", _num(sub.get("grid"), 2), "电流、功率与并网质量"],
+                ["传动系统", _num(sub.get("drive_train"), 2), "主轴承、齿轮箱温度"],
+            ],
+            [4.5, 4.0, 8.0],
+        )
+        L._image(doc, L.charts.health_subsystems(sub, os.path.join(tmp, "health_subsys.png")), "图 5-3 子系统平均健康得分")
+        L._para(
+            doc,
+            "大部件温度异常检测需要温度测点与工况数据的完整配对。本期健康评估已对发电机、机舱、"
+            "电网环境和传动系统给出综合得分;具体温度偏差、温升趋势和传感器可信度仍需结合专项温度分析复核。",
+        )
+    L._heading(doc, "5.3 算法健康评估", 2)
+    ah = data.get("algorithm_health") or {}
+    if not ah.get("available"):
+        L._para(doc, f"算法健康评估页面数据不足:{ah.get('error', '未取得有效结果')}。")
+    else:
+        L._para(
+            doc,
+            f"算法健康评估期次 {ah.get('period')},生成时间 {ah.get('generated_at')},"
+            f"共评估 {len(ah.get('turbines') or [])} 台机组。总分按可评系统数是否达到适用系统半数决定;"
+            "未达半数时总分显示为未评估。",
+        )
+        rows = []
+        for t in (ah.get("turbines") or [])[:20]:
+            ov = t.get("overall") or {}
+            systems = t.get("systems") or []
+            scored = sum(1 for s in systems if s.get("status") == "scored")
+            applicable = sum(1 for s in systems if s.get("status") != "not_applicable")
+            reason = (ov.get("reasons") or [{}])[0].get("text", "")
+            rows.append([
+                t.get("turbine_name") or t.get("turbine"),
+                ov.get("score") if ov.get("status") == "scored" else "未评估",
+                f"{scored}/{applicable}",
+                reason,
+            ])
+        if rows:
+            L._table(doc, ["机组", "总分", "可评分系统", "未评估原因"], rows, [4.0, 2.6, 3.4, 6.0])
 
 
 def _section_risk(doc, data: Dict[str, Any], tmp: str):