Spaces:
Sleeping
Sleeping
Download backend/app/main.py from dauphinking/pump: direct link, hf CLI and curl.
- Browser
- Download file 15.2 kB
-
https://huggingface.co/spaces/dauphinking/pump/resolve/main/backend/app/main.py
- Command line
-
hf download hf://spaces/dauphinking/pump/backend/app/main.py
-
curl -L -o main.py https://huggingface.co/spaces/dauphinking/pump/resolve/main/backend/app/main.py
15.2 kB
| """FastAPI 入口:暴露优化建议与曲线/工作点查询(文档 4.2 API 草案的 Phase2 部分)。 | |
| 数据采集由 Node-RED(node-red-contrib-opcua)承担,本服务专注优化算法。 | |
| 现场可把 /api/realtime 的 Node-RED 快照 POST 进来驱动优化,或由 Node-RED 定时拉取 /api/optimization/suggestion。 | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import os | |
| import time | |
| from contextlib import asynccontextmanager | |
| from pathlib import Path | |
| from typing import Any, Optional | |
| from fastapi import FastAPI, WebSocket | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.staticfiles import StaticFiles | |
| from pydantic import BaseModel | |
| from .integration_api import router as integration_router | |
| from .cloud_api import router as cloud_router, forwarder as cloud_forwarder | |
| from .demo_runtime import demo_runtime | |
| from .plant import Plant | |
| async def lifespan(_: FastAPI): | |
| await demo_runtime.start_from_env() | |
| cloud_task = asyncio.create_task( | |
| cloud_forwarder.run(lambda: demo_runtime.latest)) # 云端转发后台循环 | |
| try: | |
| yield | |
| finally: | |
| cloud_task.cancel() | |
| await demo_runtime.stop() | |
| app = FastAPI(title="泵站 AI 节能优化服务", version="0.2.0", lifespan=lifespan) | |
| app.add_middleware( | |
| CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], | |
| ) | |
| app.include_router(integration_router) | |
| app.include_router(cloud_router) | |
| from .branding_api import router as branding_router # noqa: E402 | |
| app.include_router(branding_router) | |
| plant = Plant() | |
| class OptimizeRequest(BaseModel): | |
| Q_target: Optional[float] = None # 目标流量 m³/h;缺省用预测/均值 | |
| current_freqs: dict[int, float] = {} # {pump_id: freq} | |
| current_active: list[int] = [] # 当前在运泵 | |
| run_hours: dict[int, float] = {} # 累计运行 h(轮换均衡) | |
| current_total_power: Optional[float] = None # 当前实测总有功功率 kW | |
| level: Optional[float] = None # 当前集水井液位 m | |
| class ModeRequest(BaseModel): | |
| mode: str # manual | auto | |
| class EnableRequest(BaseModel): | |
| enable: bool | |
| class AlarmRequest(BaseModel): | |
| critical: bool | |
| class ApplyRequest(BaseModel): | |
| suggestion: dict[str, Any] # {active, freqs} | |
| realtime: dict[str, Any] # {pressure, pumps:[{id,freq,status}], ...} | |
| def health(): | |
| return { | |
| "status": "ok", | |
| "pumps": list(plant.pumps.keys()), | |
| "historical_opc_demo": { | |
| "enabled": demo_runtime.enabled, | |
| "ready": demo_runtime.latest is not None, | |
| "error": demo_runtime.error, | |
| }, | |
| } | |
| def realtime_snapshot(): | |
| if demo_runtime.latest is None: | |
| return { | |
| "success": False, | |
| "source": "historical_opc_replay", | |
| "error": demo_runtime.error or "Historical OPC replay is starting", | |
| } | |
| return demo_runtime.latest | |
| def config(): | |
| """泵组配置(数量 + 每台性质)+ 约束 + 频率范围,供前端动态构建。""" | |
| return { | |
| "station": plant.station.get("name"), | |
| "freq_min": plant.station["freq_min"], | |
| "freq_max": plant.station["freq_max"], | |
| "constraints": plant.constraints, | |
| "level_range": plant.level_range, | |
| "pumps": [plant.pump_meta[pid] for pid in plant.pumps], | |
| } | |
| def pump_curve(pid: int, freq: float = 50.0, n: int = 40): | |
| """单泵曲线(给定频率):H-Q / η-Q / P-Q 采样点。""" | |
| if pid not in plant.pumps: | |
| return {"success": False, "error": "no such pump"} | |
| pm = plant.pumps[pid] | |
| qmin, qmax = pm.q_min(freq), pm.q_max(freq) | |
| hq, eq, pq = [], [], [] | |
| for i in range(n + 1): | |
| q = qmin + (qmax - qmin) * i / n | |
| hq.append([round(q, 2), round(pm.head(q, freq), 3)]) | |
| eq.append([round(q, 2), round(pm.eta(q, freq) * 100, 2)]) | |
| p = pm.input_power(q, freq) | |
| if p == p: | |
| pq.append([round(q, 2), round(p, 3)]) | |
| return {"success": True, "pump_id": pid, "freq": freq, | |
| "bep_flow": round(pm.bep_flow(freq), 2), | |
| "meta": plant.pump_meta[pid], | |
| "HQ": hq, "etaQ": eq, "PQ": pq} | |
| class IdentifyRequest(BaseModel): | |
| # 历史运行点:每条含 Q(m³/h), H(m), 以及 P(kW) 或 eta(0~1), freq(Hz) | |
| records: list[dict[str, Any]] | |
| variable_speed: bool = True | |
| rated_kw: Optional[float] = None | |
| name: Optional[str] = None | |
| class CurveFitRequest(BaseModel): | |
| # 数字化的曲线点(额定频率):H-Q 必填,η-Q 可选 | |
| hq: list[list[float]] # [[Q,H],...] | |
| eta: Optional[list[list[float]]] = None # [[Q,eta],...],eta 百分数或小数 | |
| class CurveApplyRequest(BaseModel): | |
| poly: dict[str, float] # {a0,a1,a2,q_max} | |
| eta_gauss: dict[str, float] # {eta_max,q_bep,sigma} | |
| name: Optional[str] = None | |
| variable_speed: Optional[bool] = None | |
| rated_kw: Optional[float] = None | |
| def curve_fit_endpoint(pid: int, req: CurveFitRequest): | |
| """把在曲线图上点取(或粘贴)的 H-Q / η-Q 数据点拟合成 poly+高斯参数,并回采样预览。""" | |
| from .models.curve_fit import fit_from_points | |
| from .models.pump_curve import PumpCurveModel | |
| try: | |
| fit = fit_from_points(req.hq, req.eta) | |
| except (ValueError, RuntimeError) as e: | |
| return {"success": False, "error": str(e)} | |
| # 用拟合参数建临时模型出预览曲线 | |
| preview = None | |
| if fit.get("eta_gauss"): | |
| p = fit["poly"]; g = fit["eta_gauss"] | |
| m = PumpCurveModel.from_poly(pid, p["a0"], p["a1"], p["a2"], p["q_max"], | |
| g["eta_max"], g["q_bep"], g["sigma"], | |
| freq_nominal=plant.station["freq_nominal"]) | |
| qmax = m.q_max(50.0) | |
| preview = {"HQ": [[round(qmax * i / 40, 1), round(m.head(qmax * i / 40, 50), 3)] for i in range(41)], | |
| "etaQ": [[round(qmax * i / 40, 1), round(m.eta(qmax * i / 40, 50) * 100, 2)] for i in range(41)]} | |
| return {"success": True, **fit, "preview": preview} | |
| def curve_apply(pid: int, req: CurveApplyRequest): | |
| """把拟合好的曲线应用到该泵(运行时热更新 + 持久化,无需改 YAML)。""" | |
| if pid not in plant.pumps: | |
| return {"success": False, "error": "no such pump"} | |
| spec = {"poly": req.poly, "eta_gauss": req.eta_gauss} | |
| if req.name is not None: | |
| spec["name"] = req.name | |
| if req.variable_speed is not None: | |
| spec["variable_speed"] = req.variable_speed | |
| if req.rated_kw is not None: | |
| spec["rated_kw"] = req.rated_kw | |
| try: | |
| meta = plant.apply_curve(pid, spec) | |
| except (KeyError, ValueError, TypeError) as e: | |
| return {"success": False, "error": str(e)} | |
| return {"success": True, "meta": meta, "curve": plant.sampled_curve(pid)} | |
| def identify(pid: int, req: IdentifyRequest): | |
| """从历史运行数据辨识该泵曲线,返回 a0/a1/a2 + 高斯效率参数、拟合 R², | |
| 以及可直接粘进 pumps.yaml 的片段。用历史数据反推真实曲线。""" | |
| from .models.curve_fit import identify_pump, to_yaml_block | |
| try: | |
| ident = identify_pump( | |
| req.records, freq_nominal=plant.station["freq_nominal"], | |
| pump_id=pid, name=req.name, variable_speed=req.variable_speed, | |
| rated_kw=req.rated_kw, | |
| ) | |
| except (ValueError, RuntimeError) as e: | |
| return {"success": False, "error": str(e)} | |
| ident["yaml"] = to_yaml_block(ident) | |
| ident["success"] = True | |
| return ident | |
| def suggestion(req: OptimizeRequest): | |
| """核心:给出最优开泵组合与频率建议,并对比全 50Hz 基线的节能潜力。""" | |
| Q_target = req.Q_target | |
| if Q_target is None: | |
| Q_target = plant.forecaster.predict() or plant.forecaster.current_avg() or 300.0 | |
| result = plant.optimizer.optimize( | |
| Q_target=Q_target, | |
| current_freqs={int(k): float(v) for k, v in req.current_freqs.items()}, | |
| current_active=[int(x) for x in req.current_active], | |
| run_hours={int(k): float(v) for k, v in req.run_hours.items()}, | |
| level=req.level, | |
| ) | |
| if not result.get("success"): | |
| return result | |
| # 基线优先使用总管流量 + 实测总有功功率。即使2号泵反馈频率未知, | |
| # 也能形成真实SEC基线;未知频率绝不再按0 Hz处理。 | |
| cur_active = [int(x) for x in req.current_active] | |
| cur_freqs = {int(k): float(v) for k, v in req.current_freqs.items()} | |
| if req.current_total_power is not None and req.current_total_power > 0 and Q_target > 0: | |
| base_data = { | |
| "P_total": float(req.current_total_power), | |
| "spec_energy": float(req.current_total_power) / float(Q_target), | |
| "Q_total": float(Q_target), | |
| "kind": "current_measured", | |
| } | |
| elif cur_active and all(cur_freqs.get(p, 0) > 1e-6 for p in cur_active): | |
| base = plant.group.solve( | |
| {p: cur_freqs[p] for p in cur_active}, level=req.level | |
| ) | |
| if base.feasible: | |
| base_data = { | |
| "P_total": base.P_total, "spec_energy": base.spec_energy, | |
| "Q_total": base.Q_total, "kind": "current_modelled", | |
| } | |
| else: | |
| base = plant.baseline_meet_target(Q_target, level=req.level) | |
| base_data = { | |
| "P_total": base.P_total, "spec_energy": base.spec_energy, | |
| "Q_total": base.Q_total, "kind": "meet_target_50hz", | |
| } | |
| else: | |
| base = plant.baseline_meet_target(Q_target, level=req.level) | |
| base_data = { | |
| "P_total": base.P_total, "spec_energy": base.spec_energy, | |
| "Q_total": base.Q_total, "kind": "meet_target_50hz", | |
| } | |
| saving = None | |
| if base_data["spec_energy"] > 1e-6: | |
| saving = round( | |
| (base_data["spec_energy"] - result["spec_energy"]) | |
| / base_data["spec_energy"] * 100, 1 | |
| ) | |
| result["Q_target"] = round(Q_target, 2) | |
| result["baseline"] = { | |
| "P_total": round(base_data["P_total"], 2), | |
| "spec_energy": round(base_data["spec_energy"], 4), | |
| "Q_total": round(base_data["Q_total"], 2), | |
| "kind": base_data["kind"], | |
| } | |
| result["sec_saving_pct"] = saving | |
| if saving is None: | |
| result.update({ | |
| "status": "baseline_unavailable", "executable": False, | |
| "message": "缺少可比较的实测功率基线,仅展示计算结果,不下发。", | |
| }) | |
| elif saving <= 0: | |
| result.update({ | |
| "status": "no_improvement", "executable": False, | |
| "message": "未找到优于当前工况的方案,建议保持现状。", | |
| }) | |
| else: | |
| result.update({"status": "optimized", "executable": True}) | |
| return result | |
| # ---------------- Phase 3 控制 / 安全联锁 ---------------- | |
| def _control_snapshot(): | |
| st = plant.control | |
| return { | |
| "mode": st.mode, | |
| "write_enable": st.write_enable, | |
| "critical_alarm": st.critical_alarm, | |
| "reverted": st.reverted, | |
| "heartbeat_count": st.heartbeat_count, | |
| "watchdog_age_s": round(st.watchdog_age(), 2), | |
| "watchdog_ok": st.watchdog_age() <= plant.safety_gate.watchdog_timeout_s, | |
| "watchdog_timeout_s": plant.safety_gate.watchdog_timeout_s, | |
| "last_command": st.last_command, | |
| } | |
| def control_state(): | |
| return _control_snapshot() | |
| def set_mode(req: ModeRequest): | |
| if req.mode not in ("manual", "auto"): | |
| return {"success": False, "error": "mode must be manual|auto"} | |
| plant.control.mode = req.mode | |
| if req.mode == "auto": # 进入闭环即视为一次心跳、清除切回标志 | |
| plant.control.reverted = False | |
| plant.control.beat() | |
| return {"success": True, **_control_snapshot()} | |
| def set_enable(req: EnableRequest): | |
| plant.control.write_enable = bool(req.enable) | |
| return {"success": True, **_control_snapshot()} | |
| def set_alarm(req: AlarmRequest): | |
| plant.control.critical_alarm = bool(req.critical) | |
| return {"success": True, **_control_snapshot()} | |
| def heartbeat(): | |
| plant.control.beat() | |
| return {"success": True, **_control_snapshot()} | |
| def revert(): | |
| """一键反悔 / 无扰切回:停自动、关写使能、切回本地 PID(维持最后有效设定)。""" | |
| plant.control.mode = "manual" | |
| plant.control.write_enable = False | |
| plant.control.reverted = True | |
| return {"success": True, "message": "已切回手动/本地 PID(无扰,维持最后有效设定)", | |
| **_control_snapshot()} | |
| def apply(req: ApplyRequest): | |
| """闭环下发:把建议过安全门控(写使能/限幅/斜坡/高压/watchdog/最少台数), | |
| 返回可下发的安全指令与拦截项。调用本身兼作一次心跳。""" | |
| plant.control.beat() # 前端每周期调用即喂狗 | |
| gated = plant.safety_gate.gate( | |
| suggestion=req.suggestion, realtime=req.realtime, | |
| state=plant.control, now=time.time(), | |
| ) | |
| return {"success": True, "mode": plant.control.mode, **gated} | |
| async def realtime_ws(websocket: WebSocket): | |
| """Stream the internal historical OPC replay in single-container demos.""" | |
| await websocket.accept() | |
| if not demo_runtime.enabled: | |
| await websocket.close(code=1013, reason="Realtime source unavailable") | |
| return | |
| try: | |
| while True: | |
| if demo_runtime.latest is not None: | |
| await websocket.send_json(demo_runtime.latest) | |
| await asyncio.sleep(1.0) | |
| except Exception: | |
| return | |
| # ---------------- 静态前端托管(单进程/单容器:后端直接提供大屏)---------------- | |
| # 存在 frontend 目录则挂到根路径,实现「一个进程 = 大屏 + API」,方便任意平台一步部署。 | |
| # 挂载放在所有 /api 路由之后,作为兜底(catch-all),不影响 API。 | |
| _FRONT = os.environ.get( | |
| "FRONTEND_DIR", str(Path(__file__).resolve().parents[2] / "frontend")) | |
| if Path(_FRONT).is_dir(): | |
| from fastapi.responses import FileResponse | |
| _home = Path(_FRONT) / "home.html" | |
| if _home.exists(): | |
| # 首页=品牌封面/登录页;大屏在 index.html | |
| def _landing(): | |
| return FileResponse(str(_home), headers={"Cache-Control": "no-store"}) | |
| app.mount("/", StaticFiles(directory=_FRONT, html=True), name="frontend") | |