Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bec0bad97a |
@@ -1,76 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""配置化驾驶舱内核模块(iAOP-Core / cockpit)—— 对齐 PRD 5.5「⑤ 配置化驾驶舱」。
|
|
||||||
|
|
||||||
对外暴露:
|
|
||||||
- ``LAYOUT_SCHEMA_VERSION`` / ``LAYOUT_SCHEMA_ID``:布局 JSON Schema 标识。
|
|
||||||
- ``CockpitLayout`` / ``Widget``:布局与组件的内存模型(dataclass)。
|
|
||||||
- ``validate_layout``:对一份布局资产做结构 + 语义校验,返回校验结果。
|
|
||||||
- ``load_layout``:从已解析的 dict 构造 ``CockpitLayout``(校验失败抛 ``LayoutValidationError``)。
|
|
||||||
- ``render_layout`` / ``render_widget``:把布局/组件编译为渲染计划(#51,
|
|
||||||
PRD 5.5 渲染层适配器),输出与前端框架无关的 ``RenderPlan``。
|
|
||||||
- ``RenderPlan`` / ``WidgetRendererSpec`` / ``GridPlacement``:渲染描述符。
|
|
||||||
- ``THEME_TOKENS`` / ``WIDGET_COMPONENT``:主题调色与组件映射。
|
|
||||||
|
|
||||||
设计目标(PRD 5.5 验收口径):
|
|
||||||
切换行业模板后,驾驶舱按布局配置自动重排,**无需改前端代码**。
|
|
||||||
本模块负责"布局资产的定义 + 校验 + 解析 + 渲染计划编译",不依赖任何前端框架;
|
|
||||||
渲染层(Vue3 / 配置台)只需消费 ``CockpitLayout`` 与 ``RenderPlan`` 的内存模型。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from .layout import ( # noqa: F401
|
|
||||||
DEFAULT_GRID_COLUMNS,
|
|
||||||
LAYOUT_SCHEMA_ID,
|
|
||||||
LAYOUT_SCHEMA_VERSION,
|
|
||||||
PERF_WIDGET_THRESHOLD,
|
|
||||||
VALID_THEMES,
|
|
||||||
VALID_WIDGET_TYPES,
|
|
||||||
CockpitLayout,
|
|
||||||
Grid,
|
|
||||||
LayoutValidationError,
|
|
||||||
LayoutValidationResult,
|
|
||||||
Widget,
|
|
||||||
load_layout,
|
|
||||||
validate_layout,
|
|
||||||
)
|
|
||||||
from .renderer import ( # noqa: F401
|
|
||||||
THEME_TOKENS,
|
|
||||||
WIDGET_COMPONENT,
|
|
||||||
GridPlacement,
|
|
||||||
RenderError,
|
|
||||||
RenderPlan,
|
|
||||||
WidgetRendererSpec,
|
|
||||||
compute_grid_placement,
|
|
||||||
plan_to_dict,
|
|
||||||
plan_to_json,
|
|
||||||
render_layout,
|
|
||||||
render_widget,
|
|
||||||
)
|
|
||||||
|
|
||||||
__all__ = [
|
|
||||||
"LAYOUT_SCHEMA_ID",
|
|
||||||
"LAYOUT_SCHEMA_VERSION",
|
|
||||||
"VALID_THEMES",
|
|
||||||
"VALID_WIDGET_TYPES",
|
|
||||||
"DEFAULT_GRID_COLUMNS",
|
|
||||||
"PERF_WIDGET_THRESHOLD",
|
|
||||||
"CockpitLayout",
|
|
||||||
"Grid",
|
|
||||||
"Widget",
|
|
||||||
"LayoutValidationError",
|
|
||||||
"LayoutValidationResult",
|
|
||||||
"load_layout",
|
|
||||||
"validate_layout",
|
|
||||||
# 渲染引擎(#51 / PRD 5.5 渲染层适配器)
|
|
||||||
"THEME_TOKENS",
|
|
||||||
"WIDGET_COMPONENT",
|
|
||||||
"RenderError",
|
|
||||||
"RenderPlan",
|
|
||||||
"WidgetRendererSpec",
|
|
||||||
"GridPlacement",
|
|
||||||
"render_layout",
|
|
||||||
"render_widget",
|
|
||||||
"compute_grid_placement",
|
|
||||||
"plan_to_dict",
|
|
||||||
"plan_to_json",
|
|
||||||
]
|
|
||||||
@@ -1,378 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""驾驶舱布局 JSON Schema 定义 + 校验器 + 解析器(issue #50 / PRD 5.5)。
|
|
||||||
|
|
||||||
本文件是 ``$schema: iAOP-cockpit-layout-v1`` 的权威实现:定义布局资产的
|
|
||||||
字段规范、合法性集合,以及一份与现有行业模板(如
|
|
||||||
``templates/resin/dashboard/cockpit.resin.yaml``)完全兼容的校验/解析管线。
|
|
||||||
|
|
||||||
布局资产结构(PRD 5.5 示例)::
|
|
||||||
|
|
||||||
{
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "氯化车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "ti_four_state.svg", "x":0,"y":0,"w":6,"h":4},
|
|
||||||
{"type": "trend", "bind": "CLF-01.TEMP", "x":6,"y":0,"w":6,"h":2},
|
|
||||||
{"type": "kpi_card", "metric": "Ti_purity", "x":6,"y":2,"w":3,"h":2},
|
|
||||||
{"type": "alarm_panel", "x":0,"y":4,"w":12,"h":3}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
|
|
||||||
字段规范(PRD 5.5「布局 JSON Schema 定义」+「配置点」):
|
|
||||||
$schema string 必填 布局版本标识,固定 ``iAOP-cockpit-layout-v1``。
|
|
||||||
title string 必填 驾驶舱标题(行业模板级,如"氯化车间驾驶舱")。
|
|
||||||
theme enum 必填 主题:``dark`` / ``light``。
|
|
||||||
widgets list 必填 组件清单,至少 1 个;每个 widget 见下表。
|
|
||||||
grid object 选填 栅格基线(默认 12 列);见 ``Grid``。
|
|
||||||
|
|
||||||
widget 字段:
|
|
||||||
type enum 必填 组件类型(见 ``VALID_WIDGET_TYPES``)。
|
|
||||||
x, y int 必填 栅格左上角坐标(≥0)。
|
|
||||||
w, h int 必填 宽/高(>0)。
|
|
||||||
description string 选填 组件说明(实施/行业工程师可读)。
|
|
||||||
src string 条件必填 ``process_view`` 必填,流程图 SVG 资源名。
|
|
||||||
bind string 条件必填 ``trend`` 必填,绑定的点位/指标 ID(如 CLF-01.TEMP)。
|
|
||||||
metric string 条件必填 ``kpi_card`` 必填,指标键(如 Ti_purity)。
|
|
||||||
label string 选填 ``kpi_card`` 展示标签。
|
|
||||||
|
|
||||||
复杂仪表盘性能(PRD 5.5)由渲染层负责:组件 ≥ 30 或数据点 ≥ 500 时启用
|
|
||||||
虚拟滚动 + 采样降频 + WebWorker,保证首屏 ≤ 2s。本 schema 不强制该阈值,
|
|
||||||
仅在 ``LayoutValidationResult`` 中提示组件数,便于上层决策。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 布局版本标识(被 templates/resin/dashboard/cockpit.resin.yaml 的 $schema 引用)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
LAYOUT_SCHEMA_ID: str = "iAOP-cockpit-layout-v1"
|
|
||||||
LAYOUT_SCHEMA_VERSION: int = 1
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 合法性集合
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 主题(PRD 5.5「配置点:主题」)
|
|
||||||
VALID_THEMES: Tuple[str, ...] = ("dark", "light")
|
|
||||||
|
|
||||||
# 组件类型(PRD 5.5「能力:四状态工艺流程视图、实时趋势、KPI卡片、告警面板、NL查询入口」)
|
|
||||||
VALID_WIDGET_TYPES: Tuple[str, ...] = (
|
|
||||||
"process_view", # 四状态工艺流程视图
|
|
||||||
"trend", # 实时趋势
|
|
||||||
"kpi_card", # KPI 卡片
|
|
||||||
"alarm_panel", # 告警面板
|
|
||||||
"nl_query", # 自然语言查询入口
|
|
||||||
)
|
|
||||||
|
|
||||||
# 默认栅格基线(PRD 5.5 示例使用 12 列;resin 模板亦按 12 列布局)
|
|
||||||
DEFAULT_GRID_COLUMNS: int = 12
|
|
||||||
|
|
||||||
# 性能提示阈值(PRD 5.5「复杂仪表盘性能」)
|
|
||||||
PERF_WIDGET_THRESHOLD: int = 30
|
|
||||||
|
|
||||||
# 各组件类型必填的特有字段(type → 字段名)
|
|
||||||
_WIDGET_REQUIRED_FIELDS: Dict[str, Tuple[str, ...]] = {
|
|
||||||
"process_view": ("src",),
|
|
||||||
"trend": ("bind",),
|
|
||||||
"kpi_card": ("metric",),
|
|
||||||
"alarm_panel": (),
|
|
||||||
"nl_query": (),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 异常 / 结果
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
class LayoutValidationError(ValueError):
|
|
||||||
"""布局资产校验失败。``load_layout`` 在校验不通过时抛出。
|
|
||||||
|
|
||||||
``errors`` 收集全部字段级错误,便于配置台「错误列表(行号+原因)」展示。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, errors: List[str]):
|
|
||||||
super().__init__("; ".join(errors) if errors else "layout validation failed")
|
|
||||||
self.errors: List[str] = list(errors)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class LayoutValidationResult:
|
|
||||||
"""``validate_layout`` 的返回值,区分「是否合法」与「全部错误清单」。"""
|
|
||||||
|
|
||||||
ok: bool
|
|
||||||
errors: List[str] = field(default_factory=list)
|
|
||||||
widget_count: int = 0
|
|
||||||
perf_hint: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 内存模型(dataclass)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
@dataclass
|
|
||||||
class Widget:
|
|
||||||
"""单个驾驶舱组件的内存模型。"""
|
|
||||||
|
|
||||||
type: str
|
|
||||||
x: int
|
|
||||||
y: int
|
|
||||||
w: int
|
|
||||||
h: int
|
|
||||||
description: Optional[str] = None
|
|
||||||
# 以下为按 type 选填/必填的特有字段,统一存放,解析时已校验存在性
|
|
||||||
src: Optional[str] = None
|
|
||||||
bind: Optional[str] = None
|
|
||||||
metric: Optional[str] = None
|
|
||||||
label: Optional[str] = None
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
"""序列化回布局资产 dict(仅保留有值/必填字段,便于发布)。"""
|
|
||||||
d: Dict[str, Any] = {
|
|
||||||
"type": self.type,
|
|
||||||
"x": self.x,
|
|
||||||
"y": self.y,
|
|
||||||
"w": self.w,
|
|
||||||
"h": self.h,
|
|
||||||
}
|
|
||||||
if self.description is not None:
|
|
||||||
d["description"] = self.description
|
|
||||||
if self.src is not None:
|
|
||||||
d["src"] = self.src
|
|
||||||
if self.bind is not None:
|
|
||||||
d["bind"] = self.bind
|
|
||||||
if self.metric is not None:
|
|
||||||
d["metric"] = self.metric
|
|
||||||
if self.label is not None:
|
|
||||||
d["label"] = self.label
|
|
||||||
return d
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Grid:
|
|
||||||
"""栅格基线(默认 12 列,可由行业模板覆盖)。"""
|
|
||||||
|
|
||||||
columns: int = DEFAULT_GRID_COLUMNS
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class CockpitLayout:
|
|
||||||
"""一份完整驾驶舱布局的内存模型。
|
|
||||||
|
|
||||||
渲染层(Vue3 / 配置台)仅消费本对象:切换行业模板 = 加载另一份
|
|
||||||
``CockpitLayout``,**前端代码零改动**即满足 PRD 5.5 验收口径。
|
|
||||||
"""
|
|
||||||
|
|
||||||
title: str
|
|
||||||
theme: str
|
|
||||||
widgets: List[Widget]
|
|
||||||
grid: Grid = field(default_factory=Grid)
|
|
||||||
schema: str = LAYOUT_SCHEMA_ID
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
"""序列化为可发布的布局资产 dict(结构对齐 PRD 5.5 示例)。"""
|
|
||||||
return {
|
|
||||||
"$schema": self.schema,
|
|
||||||
"title": self.title,
|
|
||||||
"theme": self.theme,
|
|
||||||
"grid": {"columns": self.grid.columns},
|
|
||||||
"widgets": [w.to_dict() for w in self.widgets],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 校验器
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
def _require_type(value: Any, name: str, expected: type, errors: List[str], ctx: str) -> None:
|
|
||||||
"""检查 ``value`` 是 ``expected`` 类型,失败则追加一条错误。"""
|
|
||||||
# bool 是 int 的子类,栅格坐标不应接受 bool;此处显式排除
|
|
||||||
if expected is int and isinstance(value, bool):
|
|
||||||
errors.append(f"{ctx}: {name} 必须是整数,实际为 bool")
|
|
||||||
return
|
|
||||||
if not isinstance(value, expected):
|
|
||||||
errors.append(f"{ctx}: {name} 必须是 {expected.__name__},实际为 {type(value).__name__}")
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_widget(widget: Any, index: int, grid_columns: int, errors: List[str]) -> None:
|
|
||||||
"""校验单个 widget dict,错误追加到 ``errors``。"""
|
|
||||||
ctx = f"widgets[{index}]"
|
|
||||||
if not isinstance(widget, dict):
|
|
||||||
errors.append(f"{ctx}: 组件必须是对象(dict)")
|
|
||||||
return
|
|
||||||
|
|
||||||
# type
|
|
||||||
wtype = widget.get("type")
|
|
||||||
if not isinstance(wtype, str) or not wtype:
|
|
||||||
errors.append(f"{ctx}: type 缺失或非字符串")
|
|
||||||
wtype = ""
|
|
||||||
elif wtype not in VALID_WIDGET_TYPES:
|
|
||||||
errors.append(
|
|
||||||
f"{ctx}: type '{wtype}' 非法,合法值 {list(VALID_WIDGET_TYPES)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
# 栅格坐标 x/y/w/h(必填整数)
|
|
||||||
for key in ("x", "y", "w", "h"):
|
|
||||||
if key not in widget:
|
|
||||||
errors.append(f"{ctx}: 缺少必填字段 {key}")
|
|
||||||
else:
|
|
||||||
_require_type(widget[key], key, int, errors, ctx)
|
|
||||||
val = widget[key]
|
|
||||||
if isinstance(val, int) and not isinstance(val, bool):
|
|
||||||
if key in ("x", "y") and val < 0:
|
|
||||||
errors.append(f"{ctx}: {key} 必须 ≥ 0,实际 {val}")
|
|
||||||
if key in ("w", "h") and val <= 0:
|
|
||||||
errors.append(f"{ctx}: {key} 必须 > 0,实际 {val}")
|
|
||||||
# 越界:x + w 不应超过栅格列数(提示级,不阻断合法性,但记一条 warning 风格错误便于配置台纠正)
|
|
||||||
try:
|
|
||||||
x = widget["x"]
|
|
||||||
w = widget["w"]
|
|
||||||
if (
|
|
||||||
isinstance(x, int)
|
|
||||||
and isinstance(w, int)
|
|
||||||
and not isinstance(x, bool)
|
|
||||||
and not isinstance(w, bool)
|
|
||||||
and x + w > grid_columns
|
|
||||||
):
|
|
||||||
errors.append(
|
|
||||||
f"{ctx}: x+w={x + w} 超过栅格列数 {grid_columns},布局会被压缩"
|
|
||||||
)
|
|
||||||
except (KeyError, TypeError):
|
|
||||||
pass
|
|
||||||
|
|
||||||
# type 特有必填字段
|
|
||||||
if wtype in _WIDGET_REQUIRED_FIELDS:
|
|
||||||
for fname in _WIDGET_REQUIRED_FIELDS[wtype]:
|
|
||||||
val = widget.get(fname)
|
|
||||||
if not isinstance(val, str) or not val:
|
|
||||||
errors.append(f"{ctx}: type='{wtype}' 要求字段 {fname} 非空字符串")
|
|
||||||
|
|
||||||
# kpi_card 可选 label(若有则必须字符串)
|
|
||||||
label = widget.get("label")
|
|
||||||
if label is not None and not isinstance(label, str):
|
|
||||||
errors.append(f"{ctx}: label 必须是字符串")
|
|
||||||
|
|
||||||
|
|
||||||
def validate_layout(data: Any) -> LayoutValidationResult:
|
|
||||||
"""对一份布局资产(已解析的 dict)做完整校验。
|
|
||||||
|
|
||||||
返回 ``LayoutValidationResult``:``ok`` 表示是否通过,``errors`` 收集全部
|
|
||||||
字段级错误,``widget_count`` / ``perf_hint`` 供上层做性能决策。
|
|
||||||
"""
|
|
||||||
errors: List[str] = []
|
|
||||||
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return LayoutValidationResult(ok=False, errors=["布局根必须是对象(dict)"])
|
|
||||||
|
|
||||||
# $schema
|
|
||||||
schema = data.get("$schema")
|
|
||||||
if schema is None:
|
|
||||||
errors.append("缺少 $schema 字段")
|
|
||||||
elif schema != LAYOUT_SCHEMA_ID:
|
|
||||||
errors.append(
|
|
||||||
f"$schema='{schema}' 不被支持,当前版本 '{LAYOUT_SCHEMA_ID}'"
|
|
||||||
)
|
|
||||||
|
|
||||||
# title
|
|
||||||
title = data.get("title")
|
|
||||||
if not isinstance(title, str) or not title.strip():
|
|
||||||
errors.append("title 缺失或为空字符串")
|
|
||||||
|
|
||||||
# theme
|
|
||||||
theme = data.get("theme")
|
|
||||||
if theme is None:
|
|
||||||
errors.append("缺少 theme 字段")
|
|
||||||
elif theme not in VALID_THEMES:
|
|
||||||
errors.append(f"theme='{theme}' 非法,合法值 {list(VALID_THEMES)}")
|
|
||||||
|
|
||||||
# grid(可选)
|
|
||||||
grid_columns = DEFAULT_GRID_COLUMNS
|
|
||||||
grid = data.get("grid")
|
|
||||||
if grid is not None:
|
|
||||||
if not isinstance(grid, dict):
|
|
||||||
errors.append("grid 必须是对象(dict)")
|
|
||||||
else:
|
|
||||||
cols = grid.get("columns")
|
|
||||||
if cols is None:
|
|
||||||
errors.append("grid.columns 缺失")
|
|
||||||
else:
|
|
||||||
_require_type(cols, "columns", int, errors, "grid")
|
|
||||||
if isinstance(cols, int) and not isinstance(cols, bool) and cols <= 0:
|
|
||||||
errors.append(f"grid.columns 必须 > 0,实际 {cols}")
|
|
||||||
grid_columns = cols
|
|
||||||
elif isinstance(cols, int) and not isinstance(cols, bool):
|
|
||||||
grid_columns = cols
|
|
||||||
|
|
||||||
# widgets
|
|
||||||
widgets = data.get("widgets")
|
|
||||||
if widgets is None:
|
|
||||||
errors.append("缺少 widgets 字段")
|
|
||||||
widgets = []
|
|
||||||
if not isinstance(widgets, list):
|
|
||||||
errors.append("widgets 必须是数组(list)")
|
|
||||||
widgets = []
|
|
||||||
elif len(widgets) == 0:
|
|
||||||
errors.append("widgets 不能为空(至少 1 个组件)")
|
|
||||||
|
|
||||||
for idx, w in enumerate(widgets):
|
|
||||||
_validate_widget(w, idx, grid_columns, errors)
|
|
||||||
|
|
||||||
widget_count = len(widgets) if isinstance(widgets, list) else 0
|
|
||||||
perf_hint = None
|
|
||||||
if widget_count >= PERF_WIDGET_THRESHOLD:
|
|
||||||
perf_hint = (
|
|
||||||
f"组件数 {widget_count} ≥ {PERF_WIDGET_THRESHOLD},渲染层应启用"
|
|
||||||
"虚拟滚动 + 采样降频 + WebWorker(PRD 5.5)"
|
|
||||||
)
|
|
||||||
|
|
||||||
return LayoutValidationResult(
|
|
||||||
ok=len(errors) == 0,
|
|
||||||
errors=errors,
|
|
||||||
widget_count=widget_count,
|
|
||||||
perf_hint=perf_hint,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 解析器
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
def _coerce_int(v: Any) -> int:
|
|
||||||
"""已校验为 int(非 bool)后取值。"""
|
|
||||||
return v # type: ignore[return-value]
|
|
||||||
|
|
||||||
|
|
||||||
def load_layout(data: Dict[str, Any]) -> CockpitLayout:
|
|
||||||
"""从已解析的 dict 构造 ``CockpitLayout``;校验失败抛 ``LayoutValidationError``。
|
|
||||||
|
|
||||||
调用前通常先用 ``validate_layout`` 判断,但本方法内部仍会再校验一次,
|
|
||||||
确保构造出的内存模型恒为合法资产。
|
|
||||||
"""
|
|
||||||
result = validate_layout(data)
|
|
||||||
if not result.ok:
|
|
||||||
raise LayoutValidationError(result.errors)
|
|
||||||
|
|
||||||
grid_raw = data.get("grid") or {}
|
|
||||||
grid = Grid(columns=grid_raw.get("columns", DEFAULT_GRID_COLUMNS))
|
|
||||||
|
|
||||||
widgets: List[Widget] = []
|
|
||||||
for w in data["widgets"]:
|
|
||||||
widgets.append(
|
|
||||||
Widget(
|
|
||||||
type=w["type"],
|
|
||||||
x=_coerce_int(w["x"]),
|
|
||||||
y=_coerce_int(w["y"]),
|
|
||||||
w=_coerce_int(w["w"]),
|
|
||||||
h=_coerce_int(w["h"]),
|
|
||||||
description=w.get("description"),
|
|
||||||
src=w.get("src"),
|
|
||||||
bind=w.get("bind"),
|
|
||||||
metric=w.get("metric"),
|
|
||||||
label=w.get("label"),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return CockpitLayout(
|
|
||||||
title=data["title"],
|
|
||||||
theme=data["theme"],
|
|
||||||
widgets=widgets,
|
|
||||||
grid=grid,
|
|
||||||
schema=data.get("$schema", LAYOUT_SCHEMA_ID),
|
|
||||||
)
|
|
||||||
@@ -1,373 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""图表组件配置化渲染引擎(issue #51 / PRD 5.5「⑤ 配置化驾驶舱」)。
|
|
||||||
|
|
||||||
本模块在 ``layout.py``(#50 布局 JSON Schema)之上实现**渲染层适配器**:
|
|
||||||
把一份 ``CockpitLayout`` 内存模型,编译成一份与前端框架无关的**渲染计划
|
|
||||||
(``RenderPlan``)**——每个 widget 被翻译成一个 ``WidgetRendererSpec``,
|
|
||||||
描述它该用哪个前端组件、摆在栅格的哪个位置、绑定什么数据、套用哪套主题
|
|
||||||
token、是否启用性能优化策略。
|
|
||||||
|
|
||||||
设计目标(PRD 5.5 验收口径「切换模板零改码」):
|
|
||||||
前端只需一个固定的「组件注册表」+ 一个通用 ``<WidgetHost>``,
|
|
||||||
按 ``RenderPlan`` 逐个挂载组件;切换行业模板 = 换一份 ``RenderPlan``,
|
|
||||||
**前端代码零改动**。
|
|
||||||
|
|
||||||
本模块不依赖任何第三方库(与 #50 一致,避免引入运行时依赖),只消费
|
|
||||||
``cockpit.layout`` 的内存模型,输出可 ``json.dumps`` 的纯数据结构。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import json
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
from typing import Any, Dict, List, Optional, Tuple
|
|
||||||
|
|
||||||
from .layout import ( # 复用 #50 已定义的布局模型与常量
|
|
||||||
DEFAULT_GRID_COLUMNS,
|
|
||||||
LAYOUT_SCHEMA_ID,
|
|
||||||
PERF_WIDGET_THRESHOLD,
|
|
||||||
VALID_THEMES,
|
|
||||||
VALID_WIDGET_TYPES,
|
|
||||||
CockpitLayout,
|
|
||||||
Grid,
|
|
||||||
Widget,
|
|
||||||
validate_layout,
|
|
||||||
)
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 主题 token(PRD 5.5「配置点:主题」dark / light 两套调色)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 工业驾驶舱约定配色:dark 偏深蓝底 + 青绿强调(车间大屏常用);
|
|
||||||
# light 偏白底 + 蓝色强调(白天值班室)。前端按这些 CSS 变量渲染,
|
|
||||||
# 切换主题 = 切一套变量,组件代码不动。
|
|
||||||
THEME_TOKENS: Dict[str, Dict[str, str]] = {
|
|
||||||
"dark": {
|
|
||||||
"--cockpit-bg": "#0b1220",
|
|
||||||
"--cockpit-surface": "#13203a",
|
|
||||||
"--cockpit-fg": "#e6edf6",
|
|
||||||
"--cockpit-fg-muted": "#8aa0bd",
|
|
||||||
"--cockpit-accent": "#18d3c8", # 青绿(KPI / 趋势主线)
|
|
||||||
"--cockpit-warn": "#f5a623", # 告警强调
|
|
||||||
"--cockpit-grid-line": "rgba(255,255,255,0.06)",
|
|
||||||
},
|
|
||||||
"light": {
|
|
||||||
"--cockpit-bg": "#f5f7fb",
|
|
||||||
"--cockpit-surface": "#ffffff",
|
|
||||||
"--cockpit-fg": "#1f2d3d",
|
|
||||||
"--cockpit-fg-muted": "#6b7c93",
|
|
||||||
"--cockpit-accent": "#2f7af2", # 蓝
|
|
||||||
"--cockpit-warn": "#e08600",
|
|
||||||
"--cockpit-grid-line": "rgba(0,0,0,0.06)",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# widget type → 前端组件名映射(PRD 5.5 能力清单)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 前端「组件注册表」的键;``<WidgetHost>`` 据此选择具体组件实现。
|
|
||||||
# 命名遵循 Vue3 大驼峰组件约定,便于 ``app.component()`` 注册。
|
|
||||||
WIDGET_COMPONENT: Dict[str, str] = {
|
|
||||||
"process_view": "ProcessView", # 四状态工艺流程视图(SVG 资源)
|
|
||||||
"trend": "TrendChart", # 实时趋势曲线
|
|
||||||
"kpi_card": "KpiCard", # KPI 卡片
|
|
||||||
"alarm_panel": "AlarmPanel", # 告警面板
|
|
||||||
"nl_query": "NlQuery", # 自然语言查询入口
|
|
||||||
}
|
|
||||||
|
|
||||||
# 各组件类型向渲染描述里注入的「绑定字段」:来自布局 widget 的哪个属性。
|
|
||||||
# 例如 trend 组件的 series 绑定 = widget.bind(点位/指标 ID)。
|
|
||||||
_WIDGET_BINDING_SOURCE: Dict[str, Tuple[str, ...]] = {
|
|
||||||
"process_view": ("src",), # 流程图资源
|
|
||||||
"trend": ("bind",), # 趋势点位/指标
|
|
||||||
"kpi_card": ("metric", "label"), # 指标键 + 展示标签
|
|
||||||
"alarm_panel": (), # 无特有绑定,订阅告警流即可
|
|
||||||
"nl_query": (), # 无特有绑定,固定入口
|
|
||||||
}
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 异常
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
class RenderError(ValueError):
|
|
||||||
"""渲染计划生成失败。``render_layout`` 在布局非法或组件缺失时抛出。"""
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 渲染描述符(dataclass)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class GridPlacement:
|
|
||||||
"""单个 widget 在 CSS Grid 中的定位(``grid-column/grid-row`` 语法)。
|
|
||||||
|
|
||||||
PRD 5.5 栅格基线默认 12 列;这里把布局资产里的整数坐标 (x,y,w,h)
|
|
||||||
换算成 CSS Grid 的 ``column-start / span`` / ``row-start / span``,
|
|
||||||
以及占比百分比(便于非 Grid 容器/截图场景使用)。
|
|
||||||
|
|
||||||
约定(与 #50 schema 一致):x/y/w/h 为栅格单位,x≥0、y≥0、w>0、h>0。
|
|
||||||
"""
|
|
||||||
|
|
||||||
column_start: int # CSS Grid 列起点的 1-based 编号(= x + 1)
|
|
||||||
column_span: int # 跨列数(= w)
|
|
||||||
row_start: int # CSS Grid 行起点的 1-based 编号(= y + 1)
|
|
||||||
row_span: int # 跨行数(= h)
|
|
||||||
width_pct: float # 占栅格总宽的百分比(= w / columns * 100,保留 4 位)
|
|
||||||
style: str # 直接可用的 ``grid-column/grid-row`` CSS 文本
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"columnStart": self.column_start,
|
|
||||||
"columnSpan": self.column_span,
|
|
||||||
"rowStart": self.row_start,
|
|
||||||
"rowSpan": self.row_span,
|
|
||||||
"widthPct": self.width_pct,
|
|
||||||
"style": self.style,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class WidgetRendererSpec:
|
|
||||||
"""单个驾驶舱组件的渲染描述符(``<WidgetHost>`` 的单一挂载项)。
|
|
||||||
|
|
||||||
前端渲染约定::
|
|
||||||
|
|
||||||
<component :is="registry[spec.component]" v-bind="spec.props"
|
|
||||||
:style="spec.grid.style" :perf="spec.perf" />
|
|
||||||
"""
|
|
||||||
|
|
||||||
id: str # 渲染层唯一标识(type + 序号),便于 diff / 虚拟滚动 key
|
|
||||||
component: str # 前端组件名(见 ``WIDGET_COMPONENT``)
|
|
||||||
type: str # 原始 widget type(调试/审计用)
|
|
||||||
grid: GridPlacement
|
|
||||||
description: Optional[str] = None
|
|
||||||
# 前端组件 props(绑定字段 + 展示参数),按组件类型组装
|
|
||||||
props: Dict[str, Any] = field(default_factory=dict)
|
|
||||||
# 性能策略:是否对该组件启用虚拟滚动/采样降频/WebWorker(仅 perf 触发时 True)
|
|
||||||
perf: Dict[str, bool] = field(default_factory=lambda: {
|
|
||||||
"virtualScroll": False,
|
|
||||||
"downsample": False,
|
|
||||||
"worker": False,
|
|
||||||
})
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"id": self.id,
|
|
||||||
"component": self.component,
|
|
||||||
"type": self.type,
|
|
||||||
"grid": self.grid.to_dict(),
|
|
||||||
"description": self.description,
|
|
||||||
"props": dict(self.props),
|
|
||||||
"perf": dict(self.perf),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class RenderPlan:
|
|
||||||
"""整份驾驶舱布局的渲染计划(``<WidgetHost>`` 的总输入)。
|
|
||||||
|
|
||||||
前端拿到本对象即可完成整屏渲染:``themeTokens`` 注入到根容器 CSS 变量,
|
|
||||||
``specs`` 逐项挂载组件,``perfFlags`` 控制全局性能策略开关。
|
|
||||||
"""
|
|
||||||
|
|
||||||
schema: str # 继承自布局资产的 $schema(审计/版本对齐)
|
|
||||||
title: str
|
|
||||||
theme: str
|
|
||||||
theme_tokens: Dict[str, str] # 该主题下的 CSS 变量(来自 ``THEME_TOKENS``)
|
|
||||||
grid_columns: int # 栅格基线(用于前端百分比校验)
|
|
||||||
specs: List[WidgetRendererSpec]
|
|
||||||
widget_count: int
|
|
||||||
# 全局性能标志:组件数 ≥ PERF_WIDGET_THRESHOLD 时为 True(PRD 5.5 复杂仪表盘性能)
|
|
||||||
perf_flags: Dict[str, bool] = field(default_factory=lambda: {
|
|
||||||
"virtualScroll": False,
|
|
||||||
"downsample": False,
|
|
||||||
"worker": False,
|
|
||||||
})
|
|
||||||
perf_hint: Optional[str] = None # 来自 #50 布局校验的人类可读提示(透传)
|
|
||||||
|
|
||||||
def to_dict(self) -> Dict[str, Any]:
|
|
||||||
return {
|
|
||||||
"$schema": self.schema,
|
|
||||||
"title": self.title,
|
|
||||||
"theme": self.theme,
|
|
||||||
"themeTokens": dict(self.theme_tokens),
|
|
||||||
"grid": {"columns": self.grid_columns},
|
|
||||||
"widgets": [s.to_dict() for s in self.specs],
|
|
||||||
"widgetCount": self.widget_count,
|
|
||||||
"perfFlags": dict(self.perf_flags),
|
|
||||||
"perfHint": self.perf_hint,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 栅格换算
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def compute_grid_placement(widget: Widget, grid_columns: int) -> GridPlacement:
|
|
||||||
"""把布局资产里的栅格整数坐标换算成 CSS Grid 定位 + 占比百分比。
|
|
||||||
|
|
||||||
- CSS Grid 的列/行起点是 1-based,布局资产里的 x/y 是 0-based,
|
|
||||||
因此 ``column_start = x + 1``、``row_start = y + 1``。
|
|
||||||
- 跨度直接等于 w/h(栅格单位)。
|
|
||||||
- 宽度百分比 = w / grid_columns * 100(便于非 Grid 容器降级)。
|
|
||||||
"""
|
|
||||||
if grid_columns <= 0:
|
|
||||||
raise RenderError(f"栅格列数必须 > 0,实际 {grid_columns}")
|
|
||||||
column_start = widget.x + 1
|
|
||||||
row_start = widget.y + 1
|
|
||||||
width_pct = round(widget.w / grid_columns * 100, 4)
|
|
||||||
style = (
|
|
||||||
f"grid-column: {column_start} / span {widget.w}; "
|
|
||||||
f"grid-row: {row_start} / span {widget.h};"
|
|
||||||
)
|
|
||||||
return GridPlacement(
|
|
||||||
column_start=column_start,
|
|
||||||
column_span=widget.w,
|
|
||||||
row_start=row_start,
|
|
||||||
row_span=widget.h,
|
|
||||||
width_pct=width_pct,
|
|
||||||
style=style,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 组件 props 组装
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def _build_props(widget: Widget) -> Dict[str, Any]:
|
|
||||||
"""按 widget type 组装前端组件 props(绑定字段 + 展示参数)。
|
|
||||||
|
|
||||||
绑定字段来源见 ``_WIDGET_BINDING_SOURCE``;缺字段视为该组件不依赖它
|
|
||||||
(布局层 #50 已对必填字段做过校验,这里做防御性容错)。
|
|
||||||
"""
|
|
||||||
props: Dict[str, Any] = {}
|
|
||||||
|
|
||||||
if widget.type == "process_view":
|
|
||||||
# 流程图视图:资源名 + 四状态语义(前端按 SVG 内联渲染 + 状态着色)
|
|
||||||
props["src"] = widget.src or ""
|
|
||||||
props["states"] = ["running", "warning", "alarm", "offline"] # PRD 四状态
|
|
||||||
elif widget.type == "trend":
|
|
||||||
# 实时趋势:绑定点位/指标 ID,前端订阅时序总线
|
|
||||||
props["series"] = widget.bind or ""
|
|
||||||
props["window"] = "PT30M" # 默认 30 分钟滚动窗口(可由模板覆盖)
|
|
||||||
elif widget.type == "kpi_card":
|
|
||||||
# KPI 卡片:指标键 + 标签
|
|
||||||
props["metric"] = widget.metric or ""
|
|
||||||
props["label"] = widget.label or widget.metric or ""
|
|
||||||
elif widget.type == "alarm_panel":
|
|
||||||
# 告警面板:固定订阅告警流,无特有绑定
|
|
||||||
props["subscribe"] = "alarm_stream"
|
|
||||||
elif widget.type == "nl_query":
|
|
||||||
# NL 查询入口:固定能力,无特有绑定
|
|
||||||
props["placeholder"] = "输入自然语言查询(配方 / 质量 / 能耗)"
|
|
||||||
|
|
||||||
return props
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 渲染入口
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def render_widget(
|
|
||||||
widget: Widget,
|
|
||||||
index: int,
|
|
||||||
grid_columns: int,
|
|
||||||
perf_enabled: bool = False,
|
|
||||||
) -> WidgetRendererSpec:
|
|
||||||
"""渲染单个 widget 为 ``WidgetRendererSpec``。
|
|
||||||
|
|
||||||
- ``index`` 用于生成稳定 id(type + 序号),作为虚拟滚动 key。
|
|
||||||
- ``perf_enabled`` 为 True(全局性能策略开启)时,trend/alarm_panel 这类
|
|
||||||
高频刷新组件启用采样降频 + WebWorker(PRD 5.5)。
|
|
||||||
"""
|
|
||||||
if widget.type not in WIDGET_COMPONENT:
|
|
||||||
# 布局层 #50 已挡住非法 type,这里再防御一次,避免渲染出未注册组件
|
|
||||||
raise RenderError(
|
|
||||||
f"widget[{index}] type='{widget.type}' 无对应前端组件,"
|
|
||||||
f"已注册 {list(WIDGET_COMPONENT)}"
|
|
||||||
)
|
|
||||||
|
|
||||||
spec = WidgetRendererSpec(
|
|
||||||
id=f"{widget.type}-{index}",
|
|
||||||
component=WIDGET_COMPONENT[widget.type],
|
|
||||||
type=widget.type,
|
|
||||||
grid=compute_grid_placement(widget, grid_columns),
|
|
||||||
description=widget.description,
|
|
||||||
props=_build_props(widget),
|
|
||||||
)
|
|
||||||
|
|
||||||
if perf_enabled:
|
|
||||||
# 高频刷新组件才需要逐组件性能策略:趋势曲线 / 告警面板
|
|
||||||
if widget.type in ("trend", "alarm_panel"):
|
|
||||||
spec.perf["downsample"] = True
|
|
||||||
spec.perf["worker"] = True
|
|
||||||
# 大流程图(process_view)启用虚拟滚动分块
|
|
||||||
if widget.type == "process_view":
|
|
||||||
spec.perf["virtualScroll"] = True
|
|
||||||
|
|
||||||
return spec
|
|
||||||
|
|
||||||
|
|
||||||
def render_layout(layout: CockpitLayout) -> RenderPlan:
|
|
||||||
"""把一份合法 ``CockpitLayout`` 编译为 ``RenderPlan``。
|
|
||||||
|
|
||||||
先复用 #50 的 ``validate_layout`` 再校验一次(防御构造后被篡改),
|
|
||||||
再逐 widget 渲染,最后汇总主题 token 与全局性能标志。
|
|
||||||
|
|
||||||
校验失败抛 ``RenderError``(包装 #50 的错误清单),便于配置台定位。
|
|
||||||
"""
|
|
||||||
# 1) 复用 #50 校验器,确保布局恒为合法资产
|
|
||||||
result = validate_layout(layout.to_dict())
|
|
||||||
if not result.ok:
|
|
||||||
raise RenderError(result.errors)
|
|
||||||
|
|
||||||
# 2) 主题 token
|
|
||||||
if layout.theme not in THEME_TOKENS:
|
|
||||||
raise RenderError(
|
|
||||||
f"theme='{layout.theme}' 无调色方案,已支持 {list(THEME_TOKENS)}"
|
|
||||||
)
|
|
||||||
theme_tokens = dict(THEME_TOKENS[layout.theme])
|
|
||||||
|
|
||||||
# 3) 全局性能标志(PRD 5.5:组件数 ≥ 阈值 → 虚拟滚动 + 采样降频 + WebWorker)
|
|
||||||
perf_on = result.widget_count >= PERF_WIDGET_THRESHOLD
|
|
||||||
perf_flags = {
|
|
||||||
"virtualScroll": perf_on,
|
|
||||||
"downsample": perf_on,
|
|
||||||
"worker": perf_on,
|
|
||||||
}
|
|
||||||
|
|
||||||
# 4) 逐 widget 渲染
|
|
||||||
specs: List[WidgetRendererSpec] = [
|
|
||||||
render_widget(w, idx, layout.grid.columns, perf_enabled=perf_on)
|
|
||||||
for idx, w in enumerate(layout.widgets)
|
|
||||||
]
|
|
||||||
|
|
||||||
return RenderPlan(
|
|
||||||
schema=layout.schema,
|
|
||||||
title=layout.title,
|
|
||||||
theme=layout.theme,
|
|
||||||
theme_tokens=theme_tokens,
|
|
||||||
grid_columns=layout.grid.columns,
|
|
||||||
specs=specs,
|
|
||||||
widget_count=len(specs),
|
|
||||||
perf_flags=perf_flags,
|
|
||||||
perf_hint=result.perf_hint,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 序列化
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def plan_to_dict(plan: RenderPlan) -> Dict[str, Any]:
|
|
||||||
"""渲染计划 → 可发布的 dict(前端直接消费 / 落盘缓存)。"""
|
|
||||||
return plan.to_dict()
|
|
||||||
|
|
||||||
|
|
||||||
def plan_to_json(plan: RenderPlan, indent: Optional[int] = 2) -> str:
|
|
||||||
"""渲染计划 → JSON 字符串(确保 ASCII 安全,中文转义不影响前端解析)。"""
|
|
||||||
return json.dumps(plan.to_dict(), ensure_ascii=False, indent=indent)
|
|
||||||
@@ -1,105 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""驾驶舱布局 JSON Schema 验证脚本(issue #50,PRD 5.5 验收口径)。
|
|
||||||
|
|
||||||
验证三个能力点:
|
|
||||||
1. **PRD 5.5 原始示例**(氯化车间)通过 ``iAOP-cockpit-layout-v1`` 校验;
|
|
||||||
2. **现有树脂模板资产兼容**:``templates/resin/dashboard/cockpit.resin.yaml``
|
|
||||||
所描述的布局(等价 dict)通过同一套校验,证明"切换模板零改码"已具备基础;
|
|
||||||
3. **负例**:一份故意破坏的布局被正确拒绝(证明阈值判断有效)。
|
|
||||||
|
|
||||||
用法(在 core/cockpit 目录下):
|
|
||||||
python scripts/verify_layout_schema.py
|
|
||||||
退出码:0 = 全部通过;1 = 存在未达标项。
|
|
||||||
|
|
||||||
说明:树脂驾驶舱资产本身是 YAML;本脚本不依赖 PyYAML(避免引入运行时依赖),
|
|
||||||
而是用与该 YAML 文件内容等价的 dict 进行校验——schema 字段语义完全一致,
|
|
||||||
若安装了 PyYAML,可直接解析原文件复现(见文末注释)。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
# 本脚本位于 core/cockpit/scripts/,需要把 core/ 加入 sys.path,
|
|
||||||
# 才能 `from cockpit import ...`(cockpit 包位于 core/cockpit)
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
|
||||||
|
|
||||||
from cockpit import LAYOUT_SCHEMA_ID, validate_layout # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _check(name: str, data: dict, expect_ok: bool) -> bool:
|
|
||||||
res = validate_layout(data)
|
|
||||||
status = "PASS" if res.ok == expect_ok else "FAIL"
|
|
||||||
print(f"[{status}] {name}: ok={res.ok} widgets={res.widget_count}")
|
|
||||||
if res.ok != expect_ok:
|
|
||||||
for e in res.errors:
|
|
||||||
print(f" - {e}")
|
|
||||||
return False
|
|
||||||
if res.ok and res.perf_hint:
|
|
||||||
print(f" perf_hint: {res.perf_hint}")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
all_ok = True
|
|
||||||
|
|
||||||
# 1) PRD 5.5 原始示例(氯化车间)
|
|
||||||
prd_example = {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "氯化车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
|
||||||
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "Ti_purity", "x": 6, "y": 2, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
all_ok &= _check("PRD 5.5 示例(氯化车间)", prd_example, expect_ok=True)
|
|
||||||
|
|
||||||
# 2) 现有树脂模板资产兼容(与 templates/resin/dashboard/cockpit.resin.yaml 等价)
|
|
||||||
resin_layout = {
|
|
||||||
"$schema": LAYOUT_SCHEMA_ID,
|
|
||||||
"title": "吸附树脂车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4,
|
|
||||||
"description": "四状态工艺流程(合成 → 交联 → 洗涤 → 干燥)"},
|
|
||||||
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2,
|
|
||||||
"description": "反应釜温度实时趋势"},
|
|
||||||
{"type": "trend", "bind": "R-801.AGIT", "x": 6, "y": 4, "w": 6, "h": 2,
|
|
||||||
"description": "搅拌转速实时趋势"},
|
|
||||||
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
|
||||||
"x": 0, "y": 6, "w": 3, "h": 2, "description": "当批平均交换容量(mmol/g)"},
|
|
||||||
{"type": "kpi_card", "metric": "resin_crosslink_degree", "label": "交联度",
|
|
||||||
"x": 3, "y": 6, "w": 3, "h": 2, "description": "当批平均交联度(%)"},
|
|
||||||
{"type": "kpi_card", "metric": "batch_yield", "label": "批产率",
|
|
||||||
"x": 6, "y": 6, "w": 3, "h": 2, "description": "当批产率(%)"},
|
|
||||||
{"type": "kpi_card", "metric": "energy_per_ton", "label": "单吨能耗",
|
|
||||||
"x": 9, "y": 6, "w": 3, "h": 2, "description": "单吨树脂综合能耗(kWh/t)"},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3,
|
|
||||||
"description": "告警面板(温度/交联度/质量预测异常)"},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3,
|
|
||||||
"description": "自然语言查询入口(配方/质量/能耗问答)"},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
all_ok &= _check("树脂模板资产(向后兼容)", resin_layout, expect_ok=True)
|
|
||||||
|
|
||||||
# 3) 负例:kpi_card 缺 metric,应被拒绝
|
|
||||||
broken = {
|
|
||||||
"$schema": LAYOUT_SCHEMA_ID,
|
|
||||||
"title": "坏布局",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "kpi_card", "x": 0, "y": 0, "w": 3, "h": 2}, # 缺 metric
|
|
||||||
],
|
|
||||||
}
|
|
||||||
all_ok &= _check("负例(kpi_card 缺 metric)应被拒绝", broken, expect_ok=False)
|
|
||||||
|
|
||||||
print()
|
|
||||||
print("全部通过 ✅" if all_ok else "存在未达标项 ❌")
|
|
||||||
return 0 if all_ok else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
@@ -1,151 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""图表组件渲染引擎验证脚本(issue #51,PRD 5.5 渲染层适配器验收)。
|
|
||||||
|
|
||||||
验证四个能力点:
|
|
||||||
1. **PRD 5.5 原始示例**(氯化车间)经布局校验后可渲染为合法 ``RenderPlan``,
|
|
||||||
且每类 widget 映射到正确前端组件 + props;
|
|
||||||
2. **现有树脂模板兼容**:与 ``templates/resin/dashboard/cockpit.resin.yaml``
|
|
||||||
等价的布局可渲染,且两个 trend 组件 id 唯一(虚拟滚动 key);
|
|
||||||
3. **主题 token 注入**:dark / light 两套 CSS 变量按主题切换;
|
|
||||||
4. **渲染计划可序列化**:``plan_to_json`` 输出可被 ``json.loads`` 还原,
|
|
||||||
且字段结构对齐前端 ``<WidgetHost>`` 约定。
|
|
||||||
|
|
||||||
用法(在 core/cockpit 目录下):
|
|
||||||
python scripts/verify_renderer.py
|
|
||||||
退出码:0 = 全部通过;1 = 存在未达标项。
|
|
||||||
|
|
||||||
说明:本脚本不依赖 PyYAML(与 #50 verify_layout_schema.py 一致,避免引入
|
|
||||||
运行时依赖),使用等价 dict 复现树脂驾驶舱布局;若装了 PyYAML 可直接解析
|
|
||||||
原 YAML 文件复现(见文末注释)。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
# 本脚本位于 core/cockpit/scripts/,需要把 core/ 加入 sys.path
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
|
|
||||||
|
|
||||||
from cockpit import ( # noqa: E402
|
|
||||||
LAYOUT_SCHEMA_ID,
|
|
||||||
THEME_TOKENS,
|
|
||||||
WIDGET_COMPONENT,
|
|
||||||
plan_to_json,
|
|
||||||
render_layout,
|
|
||||||
validate_layout,
|
|
||||||
)
|
|
||||||
from cockpit.layout import load_layout # noqa: E402
|
|
||||||
|
|
||||||
|
|
||||||
def _ti_layout() -> dict:
|
|
||||||
"""PRD 5.5 氯化车间示例。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "氯化车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
|
||||||
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "Ti_purity", "label": "Ti 纯度", "x": 6, "y": 2, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 2, "w": 3, "h": 2},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _resin_like_layout() -> dict:
|
|
||||||
"""等价于 templates/resin/dashboard/cockpit.resin.yaml 的布局。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "吸附树脂车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4},
|
|
||||||
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2},
|
|
||||||
{"type": "trend", "bind": "R-801.AGIT", "x": 6, "y": 4, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
|
||||||
"x": 0, "y": 6, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _check_render(name: str, data: dict) -> bool:
|
|
||||||
"""校验 + 渲染一份布局,打印结果,返回是否通过。"""
|
|
||||||
res = validate_layout(data)
|
|
||||||
if not res.ok:
|
|
||||||
print(f"[FAIL] {name}: 布局校验未通过")
|
|
||||||
for e in res.errors:
|
|
||||||
print(f" - {e}")
|
|
||||||
return False
|
|
||||||
plan = render_layout(load_layout(data))
|
|
||||||
print(f"[PASS] {name}: 渲染 {plan.widget_count} 个组件,主题={plan.theme}")
|
|
||||||
for spec in plan.specs:
|
|
||||||
print(f" - {spec.id} → {spec.component} "
|
|
||||||
f"({spec.grid.width_pct}%, {spec.props})")
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def _check_themes() -> bool:
|
|
||||||
"""主题 token:dark / light 两套 CSS 变量都存在且不同。"""
|
|
||||||
ok = True
|
|
||||||
for theme in ("dark", "light"):
|
|
||||||
data = _ti_layout()
|
|
||||||
data["theme"] = theme
|
|
||||||
plan = render_layout(load_layout(data))
|
|
||||||
tokens = plan.theme_tokens
|
|
||||||
match = tokens == THEME_TOKENS[theme]
|
|
||||||
print(f"[{'PASS' if match else 'FAIL'}] 主题 token({theme}): {len(tokens)} 个 CSS 变量")
|
|
||||||
ok = ok and match
|
|
||||||
if THEME_TOKENS["dark"]["--cockpit-bg"] == THEME_TOKENS["light"]["--cockpit-bg"]:
|
|
||||||
print("[FAIL] dark/light 底色不应相同")
|
|
||||||
ok = False
|
|
||||||
else:
|
|
||||||
print("[PASS] dark/light 底色不同(确为两套配色)")
|
|
||||||
return ok
|
|
||||||
|
|
||||||
|
|
||||||
def _check_serialization() -> bool:
|
|
||||||
"""渲染计划可 JSON 序列化往返。"""
|
|
||||||
import json
|
|
||||||
plan = render_layout(load_layout(_resin_like_layout()))
|
|
||||||
text = plan_to_json(plan)
|
|
||||||
parsed = json.loads(text)
|
|
||||||
ok = parsed["title"] == "吸附树脂车间驾驶舱" and parsed["widgetCount"] == 6
|
|
||||||
# 字段结构对齐前端 <WidgetHost> 约定
|
|
||||||
fields_ok = all({"component", "grid", "props", "perf"} <= set(w) for w in parsed["widgets"])
|
|
||||||
print(f"[{'PASS' if ok and fields_ok else 'FAIL'}] 序列化往返: JSON 可解析、字段齐全")
|
|
||||||
return ok and fields_ok
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
print("=" * 70)
|
|
||||||
print("图表组件渲染引擎验证(issue #51 / PRD 5.5 渲染层适配器)")
|
|
||||||
print("=" * 70)
|
|
||||||
print(f"已注册前端组件映射: {WIDGET_COMPONENT}")
|
|
||||||
print(f"布局版本: {LAYOUT_SCHEMA_ID}")
|
|
||||||
print("-" * 70)
|
|
||||||
|
|
||||||
all_ok = True
|
|
||||||
all_ok &= _check_render("PRD 5.5 氯化车间示例", _ti_layout())
|
|
||||||
all_ok &= _check_render("树脂模板兼容", _resin_like_layout())
|
|
||||||
all_ok &= _check_themes()
|
|
||||||
all_ok &= _check_serialization()
|
|
||||||
|
|
||||||
print("-" * 70)
|
|
||||||
print(f"结果: {'全部通过 ✅' if all_ok else '存在未达标项 ❌'}")
|
|
||||||
return 0 if all_ok else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
raise SystemExit(main())
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 附:若安装了 PyYAML,可直接解析树脂模板原文件复现渲染:
|
|
||||||
# import yaml
|
|
||||||
# with open("../../templates/resin/dashboard/cockpit.resin.yaml", encoding="utf-8") as f:
|
|
||||||
# data = yaml.safe_load(f)
|
|
||||||
# render_layout(load_layout(data))
|
|
||||||
# 字段语义与本脚本的 _resin_like_layout() 完全一致(iAOP-cockpit-layout-v1)。
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
@@ -1,293 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""驾驶舱布局 JSON Schema 校验/解析测试(issue #50 / PRD 5.5)。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
1. PRD 5.5 示例布局(氯化车间)合法 → 校验通过、可解析为 ``CockpitLayout``;
|
|
||||||
2. 现有树脂模板资产兼容(``iAOP-cockpit-layout-v1``);
|
|
||||||
3. 各类非法情况:错误的 $schema / theme / type、缺失必填、坐标越界、
|
|
||||||
空组件清单、栅格列数非法、特有字段缺失;
|
|
||||||
4. 性能提示:组件数 ≥ 30 触发 ``perf_hint``;
|
|
||||||
5. ``load_layout`` 校验失败抛 ``LayoutValidationError`` 并携带全部错误。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import copy
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
from cockpit import ( # type: ignore[import-not-found]
|
|
||||||
LAYOUT_SCHEMA_ID,
|
|
||||||
LAYOUT_SCHEMA_VERSION,
|
|
||||||
PERF_WIDGET_THRESHOLD,
|
|
||||||
VALID_THEMES,
|
|
||||||
VALID_WIDGET_TYPES,
|
|
||||||
CockpitLayout,
|
|
||||||
LayoutValidationError,
|
|
||||||
Widget,
|
|
||||||
load_layout,
|
|
||||||
validate_layout,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def _valid_layout() -> dict:
|
|
||||||
"""返回 PRD 5.5 示例(氯化车间)合法布局。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "氯化车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
|
||||||
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "Ti_purity", "label": "Ti 纯度", "x": 6, "y": 2, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 2, "w": 3, "h": 2},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _resin_like_layout() -> dict:
|
|
||||||
"""模拟 templates/resin/dashboard/cockpit.resin.yaml 的结构(已引用 v1 schema)。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "吸附树脂车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4,
|
|
||||||
"description": "四状态工艺流程"},
|
|
||||||
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
|
||||||
"x": 0, "y": 6, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestSchemaConstants(unittest.TestCase):
|
|
||||||
"""版本标识与合法性集合。"""
|
|
||||||
|
|
||||||
def test_schema_id_matches_template_reference(self):
|
|
||||||
# templates/resin/dashboard/cockpit.resin.yaml 引用的 $schema 必须与此处一致
|
|
||||||
self.assertEqual(LAYOUT_SCHEMA_ID, "iAOP-cockpit-layout-v1")
|
|
||||||
self.assertEqual(LAYOUT_SCHEMA_VERSION, 1)
|
|
||||||
|
|
||||||
def test_valid_themes(self):
|
|
||||||
self.assertEqual(set(VALID_THEMES), {"dark", "light"})
|
|
||||||
|
|
||||||
def test_valid_widget_types_cover_prd_capabilities(self):
|
|
||||||
# PRD 5.5 能力:四状态流程视图 / 实时趋势 / KPI卡片 / 告警面板 / NL查询入口
|
|
||||||
for required in ("process_view", "trend", "kpi_card", "alarm_panel", "nl_query"):
|
|
||||||
self.assertIn(required, VALID_WIDGET_TYPES)
|
|
||||||
|
|
||||||
|
|
||||||
class TestValidateValidLayouts(unittest.TestCase):
|
|
||||||
"""合法布局应通过校验。"""
|
|
||||||
|
|
||||||
def test_prd_example_is_valid(self):
|
|
||||||
res = validate_layout(_valid_layout())
|
|
||||||
self.assertTrue(res.ok, msg=f"expected ok, errors={res.errors}")
|
|
||||||
self.assertEqual(res.widget_count, 5)
|
|
||||||
self.assertIsNone(res.perf_hint)
|
|
||||||
|
|
||||||
def test_resin_like_layout_is_valid(self):
|
|
||||||
# 现有树脂模板资产兼容(向后兼容关键)
|
|
||||||
res = validate_layout(_resin_like_layout())
|
|
||||||
self.assertTrue(res.ok, msg=f"errors={res.errors}")
|
|
||||||
|
|
||||||
def test_light_theme_valid(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["theme"] = "light"
|
|
||||||
self.assertTrue(validate_layout(data).ok)
|
|
||||||
|
|
||||||
def test_custom_grid_columns_valid(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["grid"] = {"columns": 24}
|
|
||||||
self.assertTrue(validate_layout(data).ok)
|
|
||||||
|
|
||||||
|
|
||||||
class TestValidateInvalidLayouts(unittest.TestCase):
|
|
||||||
"""各类非法布局应在 errors 中给出对应原因。"""
|
|
||||||
|
|
||||||
def test_root_not_dict(self):
|
|
||||||
res = validate_layout(["not", "a", "dict"])
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
|
|
||||||
def test_wrong_schema(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["$schema"] = "iAOP-cockpit-layout-v0"
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("$schema" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_missing_schema(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
del data["$schema"]
|
|
||||||
self.assertFalse(validate_layout(data).ok)
|
|
||||||
|
|
||||||
def test_invalid_theme(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["theme"] = "neon"
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("theme" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_empty_title(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["title"] = " "
|
|
||||||
self.assertFalse(validate_layout(data).ok)
|
|
||||||
|
|
||||||
def test_empty_widgets(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"] = []
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("widgets" in e and "空" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_unknown_widget_type(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0]["type"] = "magic_chart"
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("type" in e and "非法" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_missing_required_widget_field_process_view(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
del data["widgets"][0]["src"] # process_view 要求 src
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("src" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_missing_required_widget_field_trend_bind(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
del data["widgets"][1]["bind"] # trend 要求 bind
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("bind" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_missing_required_widget_field_kpi_metric(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
del data["widgets"][2]["metric"] # kpi_card 要求 metric
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("metric" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_negative_x(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0]["x"] = -1
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("x" in e and "≥ 0" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_zero_w(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0]["w"] = 0
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("w" in e and "> 0" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_bool_not_accepted_as_int(self):
|
|
||||||
# bool 是 int 子类,栅格坐标不应接受 True/False
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0]["x"] = True
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("x" in e and "bool" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_grid_columns_non_positive(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["grid"] = {"columns": 0}
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("columns" in e and "> 0" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_overflow_grid_warning(self):
|
|
||||||
# x+w 超过栅格列数 → 记一条提示(用于配置台纠正),仍可在 errors 中体现
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0]["x"] = 10
|
|
||||||
data["widgets"][0]["w"] = 6 # 10+6=16 > 12
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertTrue(any("超过栅格列数" in e for e in res.errors))
|
|
||||||
|
|
||||||
def test_widget_not_dict(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"][0] = "broken"
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertFalse(res.ok)
|
|
||||||
self.assertTrue(any("对象" in e for e in res.errors))
|
|
||||||
|
|
||||||
|
|
||||||
class TestPerfHint(unittest.TestCase):
|
|
||||||
"""组件数 ≥ 30 时应给出性能提示(PRD 5.5 复杂仪表盘性能)。"""
|
|
||||||
|
|
||||||
def test_perf_hint_when_many_widgets(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["widgets"] = [
|
|
||||||
{"type": "kpi_card", "metric": f"m{i}", "x": 0, "y": 0, "w": 1, "h": 1}
|
|
||||||
for i in range(PERF_WIDGET_THRESHOLD)
|
|
||||||
]
|
|
||||||
res = validate_layout(data)
|
|
||||||
# 全部 kpi_card 合法 → ok=True,但有性能提示
|
|
||||||
self.assertEqual(res.widget_count, PERF_WIDGET_THRESHOLD)
|
|
||||||
self.assertIsNotNone(res.perf_hint)
|
|
||||||
self.assertIn("虚拟滚动", res.perf_hint or "")
|
|
||||||
|
|
||||||
def test_no_perf_hint_below_threshold(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
res = validate_layout(data)
|
|
||||||
self.assertIsNone(res.perf_hint)
|
|
||||||
|
|
||||||
|
|
||||||
class TestLoadLayout(unittest.TestCase):
|
|
||||||
"""load_layout 解析合法资产为 CockpitLayout,非法时抛异常。"""
|
|
||||||
|
|
||||||
def test_load_valid_returns_model(self):
|
|
||||||
layout = load_layout(_valid_layout())
|
|
||||||
self.assertIsInstance(layout, CockpitLayout)
|
|
||||||
self.assertEqual(layout.title, "氯化车间驾驶舱")
|
|
||||||
self.assertEqual(layout.theme, "dark")
|
|
||||||
self.assertEqual(layout.schema, LAYOUT_SCHEMA_ID)
|
|
||||||
self.assertEqual(len(layout.widgets), 5)
|
|
||||||
# 栅格默认 12 列
|
|
||||||
self.assertEqual(layout.grid.columns, 12)
|
|
||||||
# 组件字段映射
|
|
||||||
pv = layout.widgets[0]
|
|
||||||
self.assertIsInstance(pv, Widget)
|
|
||||||
self.assertEqual(pv.type, "process_view")
|
|
||||||
self.assertEqual(pv.src, "ti_four_state.svg")
|
|
||||||
kpi = layout.widgets[2]
|
|
||||||
self.assertEqual(kpi.metric, "Ti_purity")
|
|
||||||
self.assertEqual(kpi.label, "Ti 纯度")
|
|
||||||
|
|
||||||
def test_load_invalid_raises_with_errors(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
data["theme"] = "neon"
|
|
||||||
del data["widgets"][1]["bind"]
|
|
||||||
with self.assertRaises(LayoutValidationError) as cm:
|
|
||||||
load_layout(data)
|
|
||||||
# 异常应携带全部错误(不止一条)
|
|
||||||
self.assertGreaterEqual(len(cm.exception.errors), 2)
|
|
||||||
|
|
||||||
def test_roundtrip_to_dict(self):
|
|
||||||
# 解析后再序列化,结构应可再次通过校验(round-trip 稳定)
|
|
||||||
layout = load_layout(_valid_layout())
|
|
||||||
again = validate_layout(layout.to_dict())
|
|
||||||
self.assertTrue(again.ok, msg=f"roundtrip errors={again.errors}")
|
|
||||||
|
|
||||||
def test_roundtrip_preserves_resin_layout(self):
|
|
||||||
layout = load_layout(_resin_like_layout())
|
|
||||||
again = validate_layout(layout.to_dict())
|
|
||||||
self.assertTrue(again.ok, msg=f"errors={again.errors}")
|
|
||||||
self.assertEqual(layout.title, "吸附树脂车间驾驶舱")
|
|
||||||
|
|
||||||
|
|
||||||
class TestDeepCopySafety(unittest.TestCase):
|
|
||||||
"""校验不应污染入参;调用方可继续使用原 dict。"""
|
|
||||||
|
|
||||||
def test_validate_does_not_mutate_input(self):
|
|
||||||
data = _valid_layout()
|
|
||||||
snapshot = copy.deepcopy(data)
|
|
||||||
validate_layout(data)
|
|
||||||
self.assertEqual(data, snapshot)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -1,317 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""图表组件配置化渲染引擎测试(issue #51 / PRD 5.5)。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
1. ``render_layout`` 把合法布局编译为合法 ``RenderPlan``(PRD 5.5 氯化车间示例);
|
|
||||||
2. 树脂模板兼容(与 #50 ``templates/resin/dashboard/cockpit.resin.yaml`` 等价布局);
|
|
||||||
3. 栅格换算正确:CSS Grid 1-based 起点与 span、宽度百分比;
|
|
||||||
4. 各 widget type → 前端组件映射 + props 组装正确(含四状态/趋势窗口/KPI 标签兜底);
|
|
||||||
5. 主题 token 注入(dark / light 两套 CSS 变量);
|
|
||||||
6. 性能策略:组件数 ≥ 30 触发全局 ``perf_flags`` 与高频组件逐项 perf 标记;
|
|
||||||
7. 非法布局 / 非法主题 / 未知 type 被拒绝(``RenderError``);
|
|
||||||
8. 序列化往返:``plan_to_dict`` / ``plan_to_json`` 与渲染计划一致、JSON 可解析。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import copy
|
|
||||||
import json
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
from cockpit import ( # type: ignore[import-not-found]
|
|
||||||
LAYOUT_SCHEMA_ID,
|
|
||||||
PERF_WIDGET_THRESHOLD,
|
|
||||||
RenderError,
|
|
||||||
RenderPlan,
|
|
||||||
THEME_TOKENS,
|
|
||||||
WIDGET_COMPONENT,
|
|
||||||
WidgetRendererSpec,
|
|
||||||
compute_grid_placement,
|
|
||||||
load_layout,
|
|
||||||
plan_to_dict,
|
|
||||||
plan_to_json,
|
|
||||||
render_layout,
|
|
||||||
render_widget,
|
|
||||||
)
|
|
||||||
from cockpit.layout import Grid, Widget # type: ignore[import-not-found]
|
|
||||||
|
|
||||||
|
|
||||||
def _ti_layout() -> dict:
|
|
||||||
"""PRD 5.5 氯化车间示例(与 #50 test_layout 等价)。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "氯化车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "ti_four_state.svg", "x": 0, "y": 0, "w": 6, "h": 4},
|
|
||||||
{"type": "trend", "bind": "CLF-01.TEMP", "x": 6, "y": 0, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "Ti_purity", "label": "Ti 纯度", "x": 6, "y": 2, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 4, "w": 12, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 2, "w": 3, "h": 2},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _resin_like_layout() -> dict:
|
|
||||||
"""等价于 templates/resin/dashboard/cockpit.resin.yaml 的布局。"""
|
|
||||||
return {
|
|
||||||
"$schema": "iAOP-cockpit-layout-v1",
|
|
||||||
"title": "吸附树脂车间驾驶舱",
|
|
||||||
"theme": "dark",
|
|
||||||
"widgets": [
|
|
||||||
{"type": "process_view", "src": "resin_four_state.svg", "x": 0, "y": 0, "w": 12, "h": 4},
|
|
||||||
{"type": "trend", "bind": "R-801.TEMP", "x": 0, "y": 4, "w": 6, "h": 2},
|
|
||||||
{"type": "trend", "bind": "R-801.AGIT", "x": 6, "y": 4, "w": 6, "h": 2},
|
|
||||||
{"type": "kpi_card", "metric": "resin_exchange_capacity", "label": "交换容量",
|
|
||||||
"x": 0, "y": 6, "w": 3, "h": 2},
|
|
||||||
{"type": "alarm_panel", "x": 0, "y": 8, "w": 9, "h": 3},
|
|
||||||
{"type": "nl_query", "x": 9, "y": 8, "w": 3, "h": 3},
|
|
||||||
],
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
class TestRenderLayoutHappyPath(unittest.TestCase):
|
|
||||||
"""合法布局 → 合法 RenderPlan。"""
|
|
||||||
|
|
||||||
def test_ti_layout_renders(self) -> None:
|
|
||||||
layout = load_layout(_ti_layout())
|
|
||||||
plan = render_layout(layout)
|
|
||||||
self.assertIsInstance(plan, RenderPlan)
|
|
||||||
self.assertEqual(plan.schema, LAYOUT_SCHEMA_ID)
|
|
||||||
self.assertEqual(plan.title, "氯化车间驾驶舱")
|
|
||||||
self.assertEqual(plan.theme, "dark")
|
|
||||||
self.assertEqual(plan.widget_count, 5)
|
|
||||||
self.assertEqual(len(plan.specs), 5)
|
|
||||||
|
|
||||||
def test_resin_template_compatible(self) -> None:
|
|
||||||
"""切换到树脂模板同样可渲染(PRD 5.5「切换模板零改码」基础)。"""
|
|
||||||
plan = render_layout(load_layout(_resin_like_layout()))
|
|
||||||
self.assertEqual(plan.title, "吸附树脂车间驾驶舱")
|
|
||||||
self.assertEqual(plan.widget_count, 6)
|
|
||||||
# 两个 trend 组件共存,id 必须唯一(虚拟滚动 key)
|
|
||||||
ids = [s.id for s in plan.specs]
|
|
||||||
self.assertEqual(len(ids), len(set(ids)))
|
|
||||||
|
|
||||||
|
|
||||||
class TestGridPlacement(unittest.TestCase):
|
|
||||||
"""栅格整数坐标 → CSS Grid 定位 + 百分比换算。"""
|
|
||||||
|
|
||||||
def test_origin_top_left(self) -> None:
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=3, h=2, metric="m")
|
|
||||||
gp = compute_grid_placement(w, grid_columns=12)
|
|
||||||
self.assertEqual(gp.column_start, 1)
|
|
||||||
self.assertEqual(gp.row_start, 1)
|
|
||||||
self.assertEqual(gp.column_span, 3)
|
|
||||||
self.assertEqual(gp.row_span, 2)
|
|
||||||
self.assertEqual(gp.width_pct, 25.0)
|
|
||||||
self.assertIn("grid-column: 1 / span 3", gp.style)
|
|
||||||
self.assertIn("grid-row: 1 / span 2", gp.style)
|
|
||||||
|
|
||||||
def test_offset_position(self) -> None:
|
|
||||||
w = Widget(type="kpi_card", x=6, y=2, w=6, h=2, metric="m")
|
|
||||||
gp = compute_grid_placement(w, grid_columns=12)
|
|
||||||
self.assertEqual(gp.column_start, 7) # 0-based 6 → 1-based 7
|
|
||||||
self.assertEqual(gp.row_start, 3)
|
|
||||||
self.assertEqual(gp.width_pct, 50.0)
|
|
||||||
|
|
||||||
def test_full_width(self) -> None:
|
|
||||||
w = Widget(type="alarm_panel", x=0, y=0, w=12, h=3)
|
|
||||||
gp = compute_grid_placement(w, grid_columns=12)
|
|
||||||
self.assertEqual(gp.column_span, 12)
|
|
||||||
self.assertEqual(gp.width_pct, 100.0)
|
|
||||||
|
|
||||||
def test_non_default_grid_columns(self) -> None:
|
|
||||||
"""栅格基线非 12 时百分比按实际列数换算。"""
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=1, h=1, metric="m")
|
|
||||||
gp = compute_grid_placement(w, grid_columns=24)
|
|
||||||
self.assertAlmostEqual(gp.width_pct, 4.1667, places=3)
|
|
||||||
|
|
||||||
def test_invalid_columns_raises(self) -> None:
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=1, h=1, metric="m")
|
|
||||||
with self.assertRaises(RenderError):
|
|
||||||
compute_grid_placement(w, grid_columns=0)
|
|
||||||
|
|
||||||
|
|
||||||
class TestWidgetRendering(unittest.TestCase):
|
|
||||||
"""单 widget 渲染:组件映射 + props 组装。"""
|
|
||||||
|
|
||||||
def test_process_view_props(self) -> None:
|
|
||||||
w = Widget(type="process_view", x=0, y=0, w=12, h=4, src="ti_four_state.svg")
|
|
||||||
spec = render_widget(w, 0, 12)
|
|
||||||
self.assertEqual(spec.component, "ProcessView")
|
|
||||||
self.assertEqual(spec.props["src"], "ti_four_state.svg")
|
|
||||||
self.assertEqual(spec.props["states"],
|
|
||||||
["running", "warning", "alarm", "offline"])
|
|
||||||
self.assertEqual(spec.id, "process_view-0")
|
|
||||||
|
|
||||||
def test_trend_props(self) -> None:
|
|
||||||
w = Widget(type="trend", x=0, y=0, w=6, h=2, bind="CLF-01.TEMP")
|
|
||||||
spec = render_widget(w, 1, 12)
|
|
||||||
self.assertEqual(spec.component, "TrendChart")
|
|
||||||
self.assertEqual(spec.props["series"], "CLF-01.TEMP")
|
|
||||||
self.assertEqual(spec.props["window"], "PT30M")
|
|
||||||
|
|
||||||
def test_kpi_card_label_fallback(self) -> None:
|
|
||||||
"""kpi_card 缺 label 时回退到 metric(PRD 展示容错)。"""
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=3, h=2, metric="Ti_purity")
|
|
||||||
spec = render_widget(w, 2, 12)
|
|
||||||
self.assertEqual(spec.component, "KpiCard")
|
|
||||||
self.assertEqual(spec.props["metric"], "Ti_purity")
|
|
||||||
self.assertEqual(spec.props["label"], "Ti_purity") # 兜底
|
|
||||||
|
|
||||||
def test_kpi_card_label_present(self) -> None:
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=3, h=2, metric="Ti_purity", label="Ti 纯度")
|
|
||||||
spec = render_widget(w, 2, 12)
|
|
||||||
self.assertEqual(spec.props["label"], "Ti 纯度")
|
|
||||||
|
|
||||||
def test_alarm_panel_props(self) -> None:
|
|
||||||
w = Widget(type="alarm_panel", x=0, y=0, w=12, h=3)
|
|
||||||
spec = render_widget(w, 3, 12)
|
|
||||||
self.assertEqual(spec.component, "AlarmPanel")
|
|
||||||
self.assertEqual(spec.props["subscribe"], "alarm_stream")
|
|
||||||
|
|
||||||
def test_nl_query_props(self) -> None:
|
|
||||||
w = Widget(type="nl_query", x=0, y=0, w=3, h=2)
|
|
||||||
spec = render_widget(w, 4, 12)
|
|
||||||
self.assertEqual(spec.component, "NlQuery")
|
|
||||||
self.assertIn("placeholder", spec.props)
|
|
||||||
|
|
||||||
def test_all_widget_types_have_component(self) -> None:
|
|
||||||
"""PRD 5.5 全部 widget type 都有前端组件映射。"""
|
|
||||||
for wtype in ("process_view", "trend", "kpi_card", "alarm_panel", "nl_query"):
|
|
||||||
self.assertIn(wtype, WIDGET_COMPONENT)
|
|
||||||
|
|
||||||
def test_unknown_type_raises(self) -> None:
|
|
||||||
w = Widget(type="ghost", x=0, y=0, w=1, h=1)
|
|
||||||
with self.assertRaises(RenderError):
|
|
||||||
render_widget(w, 0, 12)
|
|
||||||
|
|
||||||
def test_description_propagated(self) -> None:
|
|
||||||
w = Widget(type="kpi_card", x=0, y=0, w=3, h=2, metric="m", description="当批产率")
|
|
||||||
spec = render_widget(w, 0, 12)
|
|
||||||
self.assertEqual(spec.description, "当批产率")
|
|
||||||
|
|
||||||
|
|
||||||
class TestThemeTokens(unittest.TestCase):
|
|
||||||
"""主题 → CSS 变量注入。"""
|
|
||||||
|
|
||||||
def test_dark_theme_tokens(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_ti_layout()))
|
|
||||||
self.assertEqual(plan.theme_tokens, THEME_TOKENS["dark"])
|
|
||||||
self.assertIn("--cockpit-bg", plan.theme_tokens)
|
|
||||||
self.assertIn("--cockpit-accent", plan.theme_tokens)
|
|
||||||
|
|
||||||
def test_light_theme_tokens(self) -> None:
|
|
||||||
data = copy.deepcopy(_ti_layout())
|
|
||||||
data["theme"] = "light"
|
|
||||||
plan = render_layout(load_layout(data))
|
|
||||||
self.assertEqual(plan.theme, "light")
|
|
||||||
self.assertEqual(plan.theme_tokens, THEME_TOKENS["light"])
|
|
||||||
|
|
||||||
def test_theme_tokens_cover_both_palettes(self) -> None:
|
|
||||||
self.assertEqual(set(THEME_TOKENS.keys()), {"dark", "light"})
|
|
||||||
|
|
||||||
|
|
||||||
class TestPerformanceFlags(unittest.TestCase):
|
|
||||||
"""组件数 ≥ 阈值触发全局 + 逐组件性能策略。"""
|
|
||||||
|
|
||||||
def _many_widgets(self, n: int) -> dict:
|
|
||||||
widgets = [
|
|
||||||
{"type": "trend", "bind": f"P-{i}", "x": i % 12, "y": (i // 12) * 2, "w": 1, "h": 2}
|
|
||||||
for i in range(n)
|
|
||||||
]
|
|
||||||
return {"$schema": LAYOUT_SCHEMA_ID, "title": "大屏", "theme": "dark", "widgets": widgets}
|
|
||||||
|
|
||||||
def test_under_threshold_no_perf(self) -> None:
|
|
||||||
plan = render_layout(load_layout(self._many_widgets(5)))
|
|
||||||
self.assertFalse(all(plan.perf_flags.values()))
|
|
||||||
|
|
||||||
def test_over_threshold_enables_perf(self) -> None:
|
|
||||||
plan = render_layout(load_layout(self._many_widgets(PERF_WIDGET_THRESHOLD)))
|
|
||||||
self.assertTrue(plan.perf_flags["virtualScroll"])
|
|
||||||
self.assertTrue(plan.perf_flags["downsample"])
|
|
||||||
self.assertTrue(plan.perf_flags["worker"])
|
|
||||||
# 高频刷新组件(trend)逐项启用采样降频 + worker
|
|
||||||
trend_specs = [s for s in plan.specs if s.type == "trend"]
|
|
||||||
self.assertTrue(len(trend_specs) > 0)
|
|
||||||
for s in trend_specs:
|
|
||||||
self.assertTrue(s.perf["downsample"])
|
|
||||||
self.assertTrue(s.perf["worker"])
|
|
||||||
# perfHint 透传自 #50 校验结果
|
|
||||||
self.assertIsNotNone(plan.perf_hint)
|
|
||||||
|
|
||||||
|
|
||||||
class TestRenderErrorCases(unittest.TestCase):
|
|
||||||
"""非法输入被拒绝。"""
|
|
||||||
|
|
||||||
def test_invalid_theme_rejected_by_load_layout(self) -> None:
|
|
||||||
"""非法主题在布局层 #50 即被拦(render_layout 入口前)。"""
|
|
||||||
from cockpit.layout import LayoutValidationError
|
|
||||||
bad = copy.deepcopy(_ti_layout())
|
|
||||||
bad["theme"] = "purple" # 非法主题
|
|
||||||
with self.assertRaises(LayoutValidationError):
|
|
||||||
load_layout(bad)
|
|
||||||
|
|
||||||
def test_tampered_layout_re_validated(self) -> None:
|
|
||||||
"""构造合法布局后篡改内存模型,render_layout 内部复校验应拒绝。
|
|
||||||
|
|
||||||
直接改内存模型绕过 #50 构造期校验(模拟后续篡改),
|
|
||||||
``render_layout`` 复用 ``validate_layout`` 应抛 ``RenderError``。
|
|
||||||
"""
|
|
||||||
layout = load_layout(_ti_layout())
|
|
||||||
layout.theme = "purple" # 篡改为非法主题
|
|
||||||
with self.assertRaises(RenderError):
|
|
||||||
render_layout(layout)
|
|
||||||
|
|
||||||
|
|
||||||
class TestSerialization(unittest.TestCase):
|
|
||||||
"""渲染计划序列化往返。"""
|
|
||||||
|
|
||||||
def test_plan_to_dict_structure(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_ti_layout()))
|
|
||||||
d = plan_to_dict(plan)
|
|
||||||
self.assertEqual(d["$schema"], LAYOUT_SCHEMA_ID)
|
|
||||||
self.assertEqual(d["title"], "氯化车间驾驶舱")
|
|
||||||
self.assertIn("themeTokens", d)
|
|
||||||
self.assertIn("widgets", d)
|
|
||||||
self.assertEqual(d["widgetCount"], 5)
|
|
||||||
self.assertIn("perfFlags", d)
|
|
||||||
# 每个 widget 都带渲染描述符字段
|
|
||||||
for w in d["widgets"]:
|
|
||||||
self.assertIn("component", w)
|
|
||||||
self.assertIn("grid", w)
|
|
||||||
self.assertIn("props", w)
|
|
||||||
self.assertIn("perf", w)
|
|
||||||
self.assertIn("style", w["grid"])
|
|
||||||
|
|
||||||
def test_plan_to_json_parseable(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_resin_like_layout()))
|
|
||||||
text = plan_to_json(plan)
|
|
||||||
parsed = json.loads(text)
|
|
||||||
self.assertEqual(parsed["title"], "吸附树脂车间驾驶舱")
|
|
||||||
self.assertEqual(parsed["widgetCount"], 6)
|
|
||||||
# 中文不应被转义(ensure_ascii=False)
|
|
||||||
self.assertIn("吸附树脂车间驾驶舱", text)
|
|
||||||
|
|
||||||
def test_plan_to_json_indent(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_ti_layout()))
|
|
||||||
text = plan_to_json(plan, indent=None)
|
|
||||||
self.assertNotIn("\n", text) # 紧凑模式无换行
|
|
||||||
|
|
||||||
def test_grid_placement_to_dict(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_ti_layout()))
|
|
||||||
first = plan.specs[0]
|
|
||||||
gpd = first.grid.to_dict()
|
|
||||||
self.assertEqual(gpd["columnStart"], 1)
|
|
||||||
self.assertEqual(gpd["rowStart"], 1)
|
|
||||||
self.assertEqual(gpd["widthPct"], 50.0)
|
|
||||||
|
|
||||||
def test_spec_to_dict_roundtrip_fields(self) -> None:
|
|
||||||
plan = render_layout(load_layout(_ti_layout()))
|
|
||||||
for spec in plan.specs:
|
|
||||||
sd = spec.to_dict()
|
|
||||||
self.assertEqual(set(sd.keys()),
|
|
||||||
{"id", "component", "type", "grid", "description", "props", "perf"})
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -62,11 +62,7 @@ python -m unittest discover -s tests
|
|||||||
## 模板化说明(换行业只改配置,不改代码)
|
## 模板化说明(换行业只改配置,不改代码)
|
||||||
|
|
||||||
- 点位范围 / 采样率 / 量纲 / 协议:由**点位字典 CSV** 驱动(模板 → 行业点位集)。
|
- 点位范围 / 采样率 / 量纲 / 协议:由**点位字典 CSV** 驱动(模板 → 行业点位集)。
|
||||||
- 采样率(issue #23):点位字典 CSV 的 `sampleRate` 列逐点位控制采集频率,
|
协议列(可选)提供点位级协议覆盖;留空则按 `gateway.yaml` drivers 段前缀路由。
|
||||||
引擎以 `gateway.yaml` 的 `interval_ms` 为基准 tick,`sampleRate > interval_ms`
|
|
||||||
的点位按比例降频(如 5000ms / 1000ms tick → 每 5 tick 采一次);
|
|
||||||
`sampleRate ≤ interval_ms` 的点位每 tick 采集。点位采样率完全外置、零硬编码。
|
|
||||||
- 协议列(可选)提供点位级协议覆盖;留空则按 `gateway.yaml` drivers 段前缀路由。
|
|
||||||
- 协议选型与连接参数:由 `gateway.yaml` 的 `drivers` 段驱动(模板 → 行业协议栈)。
|
- 协议选型与连接参数:由 `gateway.yaml` 的 `drivers` 段驱动(模板 → 行业协议栈)。
|
||||||
- Kafka topic 命名:`{template}.{device}.points`,随配置模板变化。
|
- Kafka topic 命名:`{template}.{device}.points`,随配置模板变化。
|
||||||
- 新增协议:实现 `drivers/base.py` 的 `Driver` 子类并注册即可,引擎与上行链路零改动。
|
- 新增协议:实现 `drivers/base.py` 的 `Driver` 子类并注册即可,引擎与上行链路零改动。
|
||||||
|
|||||||
@@ -2,10 +2,7 @@
|
|||||||
"""周期采集调度引擎 —— 只读采集 + 背压保护 + 健康度上报。
|
"""周期采集调度引擎 —— 只读采集 + 背压保护 + 健康度上报。
|
||||||
|
|
||||||
模板化封装要点:
|
模板化封装要点:
|
||||||
- 采集配置全部外置(gateway.yaml + 点位字典 CSV),引擎不关心具体协议;
|
- 采集配置全部外置(gateway.yaml),引擎不关心具体协议;
|
||||||
- 采样率外置(issue #23):每个点位按点位字典 CSV 的 sampleRate 列调度,
|
|
||||||
引擎以 gateway.yaml 的 interval_ms 为基准 tick,sampleRate > interval_ms 的
|
|
||||||
点位按比例降频读取(去硬编码:点位采样率完全由模板配置驱动);
|
|
||||||
- 点位按驱动实例的 device 匹配规则分组,一次 tick 内按驱动批量读取;
|
- 点位按驱动实例的 device 匹配规则分组,一次 tick 内按驱动批量读取;
|
||||||
- 严格只读:引擎只调用 Driver.read_points(),不存在任何控制指令路径;
|
- 严格只读:引擎只调用 Driver.read_points(),不存在任何控制指令路径;
|
||||||
- 背压保护:未确认(spool 待上行)记录超过阈值时丢弃新样本并计入丢失,
|
- 背压保护:未确认(spool 待上行)记录超过阈值时丢弃新样本并计入丢失,
|
||||||
@@ -58,28 +55,6 @@ class CollectorEngine:
|
|||||||
self._stop = threading.Event()
|
self._stop = threading.Event()
|
||||||
self._thread: Optional[threading.Thread] = None
|
self._thread: Optional[threading.Thread] = None
|
||||||
self._point_to_driver = self._build_routing()
|
self._point_to_driver = self._build_routing()
|
||||||
# 每点位采样调度(issue #23):tick 计数 + 各点位下次应采集的 tick
|
|
||||||
self._tick = 0
|
|
||||||
self._next_due_tick: Dict[str, int] = {p.point_id: 0 for p in point_dict.points}
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
|
||||||
def _ticks_per_sample(self, p: Point) -> int:
|
|
||||||
"""点位采样间隔(以基准 tick 计)。
|
|
||||||
|
|
||||||
sampleRate ≤ interval_ms 时每个 tick 都采;
|
|
||||||
sampleRate > interval_ms 时按比例降频(四舍五入,至少 1 tick)。
|
|
||||||
"""
|
|
||||||
if p.sample_rate <= 0:
|
|
||||||
return 1
|
|
||||||
return max(1, int(round(p.sample_rate / self.interval_ms)))
|
|
||||||
|
|
||||||
def _due_points(self) -> List[Point]:
|
|
||||||
"""本轮 tick 到期待采集的点位(按点位 sampleRate 调度)。"""
|
|
||||||
due: List[Point] = []
|
|
||||||
for p in self.point_dict.points:
|
|
||||||
if self._tick >= self._next_due_tick.get(p.point_id, 0):
|
|
||||||
due.append(p)
|
|
||||||
return due
|
|
||||||
|
|
||||||
# ------------------------------------------------------------------
|
# ------------------------------------------------------------------
|
||||||
def _build_routing(self) -> Dict[str, Driver]:
|
def _build_routing(self) -> Dict[str, Driver]:
|
||||||
@@ -117,16 +92,13 @@ class CollectorEngine:
|
|||||||
本轮成功读到的样本数。
|
本轮成功读到的样本数。
|
||||||
"""
|
"""
|
||||||
started = time.monotonic()
|
started = time.monotonic()
|
||||||
# 本轮 tick 递增 + 取到期待集(按点位 sampleRate 调度,issue #23)
|
expected = len(self.point_dict.points)
|
||||||
self._tick += 1
|
|
||||||
due = self._due_points()
|
|
||||||
expected = len(due)
|
|
||||||
got = 0
|
got = 0
|
||||||
samples: List[dict] = []
|
samples: List[dict] = []
|
||||||
|
|
||||||
# 1) 按驱动分组读取(只读)
|
# 1) 按驱动分组读取(只读)
|
||||||
by_driver: Dict[Driver, List[Point]] = {}
|
by_driver: Dict[Driver, List[Point]] = {}
|
||||||
for p in due:
|
for p in self.point_dict.points:
|
||||||
drv = self._point_to_driver.get(p.point_id)
|
drv = self._point_to_driver.get(p.point_id)
|
||||||
if drv is None:
|
if drv is None:
|
||||||
continue
|
continue
|
||||||
@@ -140,8 +112,6 @@ class CollectorEngine:
|
|||||||
self.metrics.record_round(time.monotonic() - started, expected, got, failed=True)
|
self.metrics.record_round(time.monotonic() - started, expected, got, failed=True)
|
||||||
return got
|
return got
|
||||||
for p in points:
|
for p in points:
|
||||||
# 无论本轮是否读到,都推进该点位采样调度(降频点位不连续空读)
|
|
||||||
self._next_due_tick[p.point_id] = self._tick + self._ticks_per_sample(p)
|
|
||||||
value = values.get(p.point_id)
|
value = values.get(p.point_id)
|
||||||
if value is None:
|
if value is None:
|
||||||
continue # 未读到 → 计入丢失
|
continue # 未读到 → 计入丢失
|
||||||
|
|||||||
@@ -1,10 +1,7 @@
|
|||||||
# iAOP 边缘采集网关 —— 模板配置示例(Template-Ti 一期:氯化车间/海绵钛)
|
# iAOP 边缘采集网关 —— 模板配置示例(Template-Ti 一期:氯化车间/海绵钛)
|
||||||
# 换行业模板时只需修改本文件 + 点位字典 CSV,网关代码零改动。
|
# 换行业模板时只需修改本文件 + 点位字典 CSV,网关代码零改动。
|
||||||
collector:
|
collector:
|
||||||
# 采集周期(毫秒)基准 tick:600 点位 1Hz 即 1000。
|
# 采集周期(毫秒):600 点位 1Hz 即 1000
|
||||||
# 点位级采样率由点位字典 CSV 的 sampleRate 列驱动(issue #23):
|
|
||||||
# sampleRate ≤ interval_ms 的点位每 tick 采集;> interval_ms 的点位按比例降频
|
|
||||||
# (如 sampleRate=5000 且 interval_ms=1000 → 每 5 tick 采一次),去硬编码。
|
|
||||||
interval_ms: 1000
|
interval_ms: 1000
|
||||||
# 背压保护:spool 待上行记录上限,超过则丢弃新样本并计入丢失率
|
# 背压保护:spool 待上行记录上限,超过则丢弃新样本并计入丢失率
|
||||||
max_pending: 100000
|
max_pending: 100000
|
||||||
@@ -13,24 +10,13 @@ collector:
|
|||||||
cache_limit_bytes: 536870912 # 512MB
|
cache_limit_bytes: 536870912 # 512MB
|
||||||
# 协议可插拔驱动插槽(protocol 注册表见 drivers/__init__.py)
|
# 协议可插拔驱动插槽(protocol 注册表见 drivers/__init__.py)
|
||||||
drivers:
|
drivers:
|
||||||
# 和利时 DCS —— OPC UA 只读(推荐;支持用户认证参数化,issue #25)
|
# 和利时 DCS —— OPC UA 只读
|
||||||
- protocol: hollysys
|
- protocol: opcua
|
||||||
device_prefixes: ["CLF"] # 设备编号前缀路由(CLF-01, CLF-02, ...)
|
device_prefixes: ["CLF"] # 设备编号前缀路由(CLF-01, CLF-02, ...)
|
||||||
config:
|
config:
|
||||||
mode: ua # ua(OPC UA)| da(OPC DA COM 接口)
|
|
||||||
endpoint: "opc.tcp://10.20.1.10:4840"
|
endpoint: "opc.tcp://10.20.1.10:4840"
|
||||||
security: "Basic256Sha256" # None | Basic256Sha256 等安全策略
|
security: "None"
|
||||||
username: "iaop_read" # 和利时 UA 服务用户认证(只读账号)
|
|
||||||
password: "******"
|
|
||||||
timeout: 10
|
timeout: 10
|
||||||
# 和利时 DCS —— OPC DA 传统接口(无 UA 服务时使用;opcNode 列写 OPC Item)
|
|
||||||
# - protocol: hollysys
|
|
||||||
# device_prefixes: ["CLF"]
|
|
||||||
# config:
|
|
||||||
# mode: da
|
|
||||||
# host: "10.20.1.10" # DCOM 主机(需 Windows + OpenOPC)
|
|
||||||
# prog_id: "Hollysys.OPCServer" # 或 cls_id 指定 CLSID
|
|
||||||
# timeout: 10
|
|
||||||
# 西门子 S7-1200 —— PLC 只读(点位 opcNode 列写 DB 地址,如 DB100.0.0)
|
# 西门子 S7-1200 —— PLC 只读(点位 opcNode 列写 DB 地址,如 DB100.0.0)
|
||||||
- protocol: s7
|
- protocol: s7
|
||||||
device_prefixes: ["S7"]
|
device_prefixes: ["S7"]
|
||||||
|
|||||||
@@ -3,9 +3,9 @@ CLF-01,CLF-01.TEMP,炉温,℃,float,1000,true,ns=2;s=CLF.Temp,opcua
|
|||||||
CLF-01,CLF-01.PRES,炉压,kPa,float,1000,true,ns=2;s=CLF.Pres,opcua
|
CLF-01,CLF-01.PRES,炉压,kPa,float,1000,true,ns=2;s=CLF.Pres,opcua
|
||||||
CLF-01,CLF-01.FEED,进料量,t/h,float,1000,true,ns=2;s=CLF.Feed,opcua
|
CLF-01,CLF-01.FEED,进料量,t/h,float,1000,true,ns=2;s=CLF.Feed,opcua
|
||||||
CLF-02,CLF-02.TEMP,炉温2,℃,float,1000,true,ns=2;s=CLF2.Temp,
|
CLF-02,CLF-02.TEMP,炉温2,℃,float,1000,true,ns=2;s=CLF2.Temp,
|
||||||
CLF-02,CLF-02.RUN,运行状态,%,bool,2000,true,ns=2;s=CLF2.Run,
|
CLF-02,CLF-02.RUN,运行状态,%,bool,1000,true,ns=2;s=CLF2.Run,
|
||||||
S7-01,S7-01.PUMP_A,泵A频率,Hz,float,1000,true,DB100.0.0,s7
|
S7-01,S7-01.PUMP_A,泵A频率,Hz,float,1000,true,DB100.0.0,s7
|
||||||
S7-01,S7-01.PUMP_B,泵B频率,Hz,float,1000,true,DB100.4.0,s7
|
S7-01,S7-01.PUMP_B,泵B频率,Hz,float,1000,true,DB100.4.0,s7
|
||||||
W-01,W-01.WT,称重值,kg,float,1000,true,holding:40001,weighing
|
W-01,W-01.WT,称重值,kg,float,1000,true,holding:40001,weighing
|
||||||
E-01,E-01.PWR,电表功率,kW,float,1000,true,holding:40010,energy
|
E-01,E-01.PWR,电表功率,kW,float,1000,true,holding:40010,energy
|
||||||
E-01,E-01.KWH,电表累计,kWh,float,5000,true,holding:40012,energy
|
E-01,E-01.KWH,电表累计,kWh,float,1000,true,holding:40012,energy
|
||||||
|
|||||||
|
@@ -12,7 +12,6 @@ if TYPE_CHECKING: # pragma: no cover
|
|||||||
from .base import Driver
|
from .base import Driver
|
||||||
|
|
||||||
from .energy_driver import EnergyDriver
|
from .energy_driver import EnergyDriver
|
||||||
from .hollysys_driver import HollysysDcsDriver
|
|
||||||
from .modbus_driver import ModbusDriver
|
from .modbus_driver import ModbusDriver
|
||||||
from .opcua_driver import OpcUaDriver
|
from .opcua_driver import OpcUaDriver
|
||||||
from .s7_driver import S7Driver
|
from .s7_driver import S7Driver
|
||||||
@@ -21,7 +20,6 @@ from .weighing_driver import WeighingDriver
|
|||||||
|
|
||||||
_DRIVER_REGISTRY: Dict[str, Type["Driver"]] = {
|
_DRIVER_REGISTRY: Dict[str, Type["Driver"]] = {
|
||||||
"opcua": OpcUaDriver,
|
"opcua": OpcUaDriver,
|
||||||
"hollysys": HollysysDcsDriver,
|
|
||||||
"s7": S7Driver,
|
"s7": S7Driver,
|
||||||
"modbus": ModbusDriver,
|
"modbus": ModbusDriver,
|
||||||
"weighing": WeighingDriver,
|
"weighing": WeighingDriver,
|
||||||
@@ -32,7 +30,6 @@ _DRIVER_REGISTRY: Dict[str, Type["Driver"]] = {
|
|||||||
__all__ = [
|
__all__ = [
|
||||||
"Driver",
|
"Driver",
|
||||||
"OpcUaDriver",
|
"OpcUaDriver",
|
||||||
"HollysysDcsDriver",
|
|
||||||
"S7Driver",
|
"S7Driver",
|
||||||
"ModbusDriver",
|
"ModbusDriver",
|
||||||
"WeighingDriver",
|
"WeighingDriver",
|
||||||
|
|||||||
@@ -1,113 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""和利时 DCS OPC 接口驱动 —— 参数化适配(issue #25)。
|
|
||||||
|
|
||||||
和利时 DCS(HOLLiAS-M / MACS 系列)对外数据接口常见两种形态,全部参数化:
|
|
||||||
- `mode: ua` —— OPC UA 接口(推荐):endpoint / security / username / password
|
|
||||||
均来自模板配置(gateway.yaml 的 drivers.hollysys 段),委托 OpcUaDriver
|
|
||||||
(含用户认证参数化,见 opcua_driver.py);
|
|
||||||
- `mode: da` —— OPC DA 传统 COM/DCOM 接口:host(DCOM 主机)/ prog_id
|
|
||||||
(如 "Hollysys.OPCServer")/ cls_id 参数化,点位 opcNode 列写 OPC Item 路径
|
|
||||||
(如 "CLF.Temp")。
|
|
||||||
|
|
||||||
安全约束(PRD 9 章):仅暴露只读 read_points(),无任何写/控制方法。
|
|
||||||
依赖(未安装时给出明确提示,不静默失败):
|
|
||||||
- ua 模式:`opcua`(同步)或 `asyncua`;
|
|
||||||
- da 模式:Windows 上 `OpenOPC`(依赖 pywin32)。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
from typing import Dict, List, Optional
|
|
||||||
|
|
||||||
from point_dict.loader import Point
|
|
||||||
from .base import Driver, SampleValue
|
|
||||||
from .opcua_driver import OpcUaDriver
|
|
||||||
|
|
||||||
|
|
||||||
class _HollysysDaDriver(Driver):
|
|
||||||
"""OPC DA(COM/DCOM)只读采集实现 —— 和利时传统接口。"""
|
|
||||||
|
|
||||||
protocol = "hollysys-da"
|
|
||||||
|
|
||||||
def __init__(self, config: Optional[dict] = None):
|
|
||||||
super().__init__(config)
|
|
||||||
self.host: str = self.config.get("host", "")
|
|
||||||
self.prog_id: str = self.config.get("prog_id", "Hollysys.OPCServer")
|
|
||||||
self.cls_id: str = self.config.get("cls_id", "")
|
|
||||||
self._client = None
|
|
||||||
|
|
||||||
def connect(self) -> None:
|
|
||||||
try:
|
|
||||||
import OpenOPC # type: ignore
|
|
||||||
except ImportError as exc: # pragma: no cover - 依赖缺失路径
|
|
||||||
raise ConnectionError(
|
|
||||||
"OPC DA 驱动依赖库未安装:请 `pip install OpenOPC`(Windows + pywin32)"
|
|
||||||
) from exc
|
|
||||||
if not self.host:
|
|
||||||
raise ConnectionError("OPC DA 驱动缺少配置: drivers.hollysys.host")
|
|
||||||
self._client = OpenOPC.client()
|
|
||||||
self._client.connect(self.prog_id, self.host)
|
|
||||||
# 可选:按 CLSID 连接(部分和利时 OPC 服务器无 ProgID 注册时使用)
|
|
||||||
if self.cls_id:
|
|
||||||
self._client.connect(self.cls_id, self.host)
|
|
||||||
|
|
||||||
def read_points(self, points: List[Point]) -> Dict[str, SampleValue]:
|
|
||||||
if self._client is None:
|
|
||||||
raise ConnectionError("OPC DA 客户端未连接,请先 connect()")
|
|
||||||
result: Dict[str, SampleValue] = {}
|
|
||||||
for p in points:
|
|
||||||
item = p.opc_node
|
|
||||||
if not item:
|
|
||||||
continue # 无 OPC Item 的点由其它驱动采集
|
|
||||||
try:
|
|
||||||
value = self._client.read(item)
|
|
||||||
# OpenOPC.read 返回 (value, quality, timestamp) 或裸值
|
|
||||||
if isinstance(value, (tuple, list)) and value:
|
|
||||||
value = value[0]
|
|
||||||
result[p.point_id] = value
|
|
||||||
except Exception:
|
|
||||||
# 单点读取失败不中断整批:记为未读到(计入丢失率)
|
|
||||||
result[p.point_id] = None
|
|
||||||
return result
|
|
||||||
|
|
||||||
def close(self) -> None:
|
|
||||||
if self._client is not None:
|
|
||||||
try:
|
|
||||||
self._client.close()
|
|
||||||
finally:
|
|
||||||
self._client = None
|
|
||||||
|
|
||||||
|
|
||||||
class HollysysDcsDriver(Driver):
|
|
||||||
"""和利时 DCS OPC 接口只读采集驱动(参数化适配,issue #25)。
|
|
||||||
|
|
||||||
按 ``mode`` 参数路由到底层实现(与 energy_driver 的委托模式一致):
|
|
||||||
- ua:OPC UA(委托 :class:`OpcUaDriver`,支持 endpoint/security/认证);
|
|
||||||
- da:OPC DA COM 接口(委托 :class:`_HollysysDaDriver`)。
|
|
||||||
"""
|
|
||||||
|
|
||||||
protocol = "hollysys"
|
|
||||||
|
|
||||||
def __init__(self, config: Optional[dict] = None):
|
|
||||||
super().__init__(config)
|
|
||||||
self.mode: str = self.config.get("mode", "ua") # ua | da
|
|
||||||
self._delegate: Optional[Driver] = None
|
|
||||||
|
|
||||||
def connect(self) -> None:
|
|
||||||
if self.mode == "da":
|
|
||||||
self._delegate = _HollysysDaDriver(self.config)
|
|
||||||
else:
|
|
||||||
# ua 默认:和利时 OPC UA 服务,支持用户认证参数化
|
|
||||||
self._delegate = OpcUaDriver(self.config)
|
|
||||||
self._delegate.connect()
|
|
||||||
|
|
||||||
def read_points(self, points: List[Point]) -> Dict[str, SampleValue]:
|
|
||||||
if self._delegate is None:
|
|
||||||
raise ConnectionError("和利时驱动未连接,请先 connect()")
|
|
||||||
return self._delegate.read_points(points)
|
|
||||||
|
|
||||||
def close(self) -> None:
|
|
||||||
if self._delegate is not None:
|
|
||||||
try:
|
|
||||||
self._delegate.close()
|
|
||||||
finally:
|
|
||||||
self._delegate = None
|
|
||||||
@@ -22,8 +22,6 @@ class OpcUaDriver(Driver):
|
|||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
self.endpoint: str = self.config.get("endpoint", "")
|
self.endpoint: str = self.config.get("endpoint", "")
|
||||||
self.security: str = self.config.get("security", "None")
|
self.security: str = self.config.get("security", "None")
|
||||||
self.username: str = self.config.get("username", "")
|
|
||||||
self.password: str = self.config.get("password", "")
|
|
||||||
self._client = None
|
self._client = None
|
||||||
|
|
||||||
def connect(self) -> None:
|
def connect(self) -> None:
|
||||||
@@ -36,19 +34,7 @@ class OpcUaDriver(Driver):
|
|||||||
if not self.endpoint:
|
if not self.endpoint:
|
||||||
raise ConnectionError("OPC UA 驱动缺少配置: drivers.opcua.endpoint")
|
raise ConnectionError("OPC UA 驱动缺少配置: drivers.opcua.endpoint")
|
||||||
self._client = Client(self.endpoint, timeout=self.config.get("timeout", 10))
|
self._client = Client(self.endpoint, timeout=self.config.get("timeout", 10))
|
||||||
# 安全策略参数化(如 Basic256Sha256;证书/密钥由现场安全通道提供)
|
|
||||||
if self.security and self.security != "None":
|
|
||||||
self._client.set_security_string(self.security)
|
|
||||||
# 用户认证参数化(和利时 DCS 的 OPC UA 服务常启用用户名/密码认证)
|
|
||||||
if self.username:
|
|
||||||
self._client.set_user(self.username)
|
|
||||||
self._client.connect()
|
self._client.connect()
|
||||||
if self.username and self.password:
|
|
||||||
try:
|
|
||||||
self._client.activate_session(self.username, self.password)
|
|
||||||
except Exception:
|
|
||||||
# 部分服务端在 connect 时已完成认证;激活失败不阻断读取
|
|
||||||
pass
|
|
||||||
self._client.session_timeout = self.config.get("session_timeout", 60000)
|
self._client.session_timeout = self.config.get("session_timeout", 60000)
|
||||||
|
|
||||||
def read_points(self, points: List[Point]) -> Dict[str, SampleValue]:
|
def read_points(self, points: List[Point]) -> Dict[str, SampleValue]:
|
||||||
|
|||||||
@@ -1,188 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""断点续传 + 丢失率 ≤ 0.02% 验证脚本(issue #26,PRD 5.1 / 9 章验收口径)。
|
|
||||||
|
|
||||||
验证两个能力点:
|
|
||||||
1. **断点续传**:样本先落 spool(本地 JSONL),Kafka 上行 ack 后才删除;
|
|
||||||
网关"重启"后未确认记录全量重发,**零丢失**;
|
|
||||||
2. **丢失率 ≤ 0.02%**:采集健康度口径(未读到样本 / 应采集样本),
|
|
||||||
无故障与模拟部分丢点场景下均须满足 ≤ 0.0002。
|
|
||||||
|
|
||||||
用法(在 core/edge-gateway 目录下):
|
|
||||||
python scripts/verify_resilience.py
|
|
||||||
退出码:0 = 全部通过;1 = 存在未达标项。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import time
|
|
||||||
|
|
||||||
# 允许直接以脚本运行(不在 edge-gateway 目录时也可执行)
|
|
||||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
|
||||||
|
|
||||||
from collector.engine import CollectorEngine # noqa: E402
|
|
||||||
from collector.metrics import HealthMetrics # noqa: E402
|
|
||||||
from collector.spool import SpoolStore # noqa: E402
|
|
||||||
from drivers.base import Driver, SampleValue # noqa: E402
|
|
||||||
from drivers.simulator_driver import SimulatorDriver # noqa: E402
|
|
||||||
from point_dict.loader import Point, PointDict # noqa: E402
|
|
||||||
|
|
||||||
LOSS_TARGET = 0.0002 # 0.02%
|
|
||||||
|
|
||||||
|
|
||||||
class DropPointDriver(SimulatorDriver):
|
|
||||||
"""模拟驱动:对指定 point_id 返回 None(模拟单点读取失败)。
|
|
||||||
|
|
||||||
drop_once=True 时每个指定点仅首次读到即丢一次(模拟偶发故障),
|
|
||||||
之后恢复正常 —— 用于构造"极低丢失率"验收场景。
|
|
||||||
"""
|
|
||||||
|
|
||||||
def __init__(self, drop_point_ids, drop_once=True, **kwargs):
|
|
||||||
super().__init__(**kwargs)
|
|
||||||
self._drop = set(drop_point_ids)
|
|
||||||
self._drop_once = drop_once
|
|
||||||
self._dropped = set()
|
|
||||||
|
|
||||||
def read_points(self, points):
|
|
||||||
values = super().read_points(points)
|
|
||||||
for p in points:
|
|
||||||
if p.point_id in self._drop:
|
|
||||||
if self._drop_once:
|
|
||||||
if p.point_id in self._dropped:
|
|
||||||
continue # 已丢过一次,恢复正常
|
|
||||||
self._dropped.add(p.point_id)
|
|
||||||
values[p.point_id] = None
|
|
||||||
return values
|
|
||||||
|
|
||||||
|
|
||||||
def make_points(n: int) -> PointDict:
|
|
||||||
"""构造 n 个 1Hz 点位(CLF 设备,走兜底 simulator 驱动)。"""
|
|
||||||
return PointDict([
|
|
||||||
Point(device_id="CLF-01", point_id=f"CLF-01.P{i:03d}",
|
|
||||||
name=f"测点{i}", unit="℃", data_type="float",
|
|
||||||
sample_rate=1000, quality_code=True, row_number=i + 1)
|
|
||||||
for i in range(n)
|
|
||||||
])
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 场景 1:断点续传
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def scenario_resume() -> bool:
|
|
||||||
"""写 spool → 模拟上行中断(不 ack)→ 模拟重启 → 重发 → ack 零丢失。"""
|
|
||||||
print("== 场景 1:断点续传 ==")
|
|
||||||
tmp = tempfile.mkdtemp(prefix="iaop-verify-")
|
|
||||||
spool_dir = os.path.join(tmp, "spool")
|
|
||||||
|
|
||||||
# 阶段 A:采集 2 轮,sink=None(离线模式,仅落 spool),模拟上行中断
|
|
||||||
pd = make_points(10)
|
|
||||||
spool_a = SpoolStore(spool_dir)
|
|
||||||
engine = CollectorEngine(
|
|
||||||
point_dict=pd,
|
|
||||||
driver_slots=[("simulator", SimulatorDriver(), [])],
|
|
||||||
spool=spool_a, metrics=HealthMetrics(), interval_ms=1000,
|
|
||||||
)
|
|
||||||
engine.collect_once(sink=None)
|
|
||||||
engine.collect_once(sink=None)
|
|
||||||
written = spool_a.total_pending()
|
|
||||||
print(f" [A] 离线采集 2 轮,spool 未确认记录 {written} 条(上行中断,不 ack)")
|
|
||||||
assert written > 0, "场景 1 前置失败:spool 应有待上行记录"
|
|
||||||
|
|
||||||
# 阶段 B:模拟网关重启 —— 新 SpoolStore 实例扫描同一目录
|
|
||||||
spool_b = SpoolStore(spool_dir)
|
|
||||||
pending = spool_b.pending_records()
|
|
||||||
print(f" [B] 网关重启后 pending_records 恢复 {len(pending)} 条")
|
|
||||||
resume_ok = len(pending) == written
|
|
||||||
|
|
||||||
# 阶段 C:全量重发 → ack → 清零
|
|
||||||
for rec in pending:
|
|
||||||
spool_b.ack({"device_id": rec["device_id"], "point_id": rec["point_id"],
|
|
||||||
"value": rec["value"], "ts": rec["ts"]})
|
|
||||||
remaining = spool_b.total_pending()
|
|
||||||
ack_ok = remaining == 0
|
|
||||||
print(f" [C] 重发并 ack 后 spool 剩余 {remaining} 条")
|
|
||||||
ok = resume_ok and ack_ok
|
|
||||||
print(f" -> 断点续传 {'PASS' if ok else 'FAIL'}"
|
|
||||||
f"(恢复 {len(pending)}/{written},清零 {ack_ok})\n")
|
|
||||||
return ok
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 场景 2:丢失率 ≤ 0.02%
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def run_loss_rounds(driver: Driver, rounds: int) -> tuple:
|
|
||||||
"""跑 N 轮采集,返回 (loss_rate, meets_sla)。"""
|
|
||||||
pd = make_points(100) # 100 点 × N 轮
|
|
||||||
spool = SpoolStore(tempfile.mkdtemp(prefix="iaop-verify-") + "/spool")
|
|
||||||
metrics = HealthMetrics()
|
|
||||||
engine = CollectorEngine(
|
|
||||||
point_dict=pd,
|
|
||||||
driver_slots=[("simulator", driver, [])],
|
|
||||||
spool=spool, metrics=metrics, interval_ms=1000,
|
|
||||||
)
|
|
||||||
for _ in range(rounds):
|
|
||||||
engine.collect_once(sink=None)
|
|
||||||
snap = metrics.snapshot()
|
|
||||||
return snap["loss_rate"], metrics.meets_sla(), snap
|
|
||||||
|
|
||||||
|
|
||||||
def scenario_loss_rate() -> bool:
|
|
||||||
print("== 场景 2:丢失率 ≤ 0.02% ==")
|
|
||||||
ok = True
|
|
||||||
|
|
||||||
# 2a:无故障基线 —— 丢失率应为 0
|
|
||||||
rate, sla, snap = run_loss_rounds(SimulatorDriver(), rounds=5)
|
|
||||||
base_ok = rate == 0.0 and sla
|
|
||||||
print(f" [A] 无故障 5 轮:丢失率 {rate:.6%}(样本 {snap['total_samples']})"
|
|
||||||
f"{'PASS' if base_ok else 'FAIL'}")
|
|
||||||
ok = ok and base_ok
|
|
||||||
|
|
||||||
# 2b:模拟单点偶发失败 —— 100 点×5 轮=500 样本,丢 1 点 = 0.2%?不达标演示:
|
|
||||||
# 用更大轮次:100 点×20 轮=2000 样本,丢 1 点 = 0.05% 仍超 0.02%,
|
|
||||||
# 说明要达标须丢点率极低 —— 按验收口径构造 100 点×100 轮=10000 样本,
|
|
||||||
# 丢 1 点 = 0.01% ≤ 0.02% 达标。
|
|
||||||
rate, sla, snap = run_loss_rounds(
|
|
||||||
DropPointDriver(drop_point_ids=["CLF-01.P000"]), rounds=100)
|
|
||||||
loss_ok = rate <= LOSS_TARGET and sla
|
|
||||||
print(f" [B] 10000 样本丢 1 点:丢失率 {rate:.6%}(目标 ≤ 0.02%)"
|
|
||||||
f"{'PASS' if loss_ok else 'FAIL'}")
|
|
||||||
ok = ok and loss_ok
|
|
||||||
|
|
||||||
# 2c:负例演示(丢 3 点 = 0.03% > 0.02%,应 FAIL,验证阈值判断生效)
|
|
||||||
rate, sla, snap = run_loss_rounds(
|
|
||||||
DropPointDriver(drop_point_ids=["CLF-01.P000", "CLF-01.P001",
|
|
||||||
"CLF-01.P002"]), rounds=100)
|
|
||||||
neg_ok = rate > LOSS_TARGET
|
|
||||||
print(f" [C] 负例(丢 3 点):丢失率 {rate:.6%} 应超限 → 校验器正确性 "
|
|
||||||
f"{'PASS' if neg_ok else 'FAIL'}")
|
|
||||||
ok = ok and neg_ok
|
|
||||||
|
|
||||||
print(f" -> 丢失率场景 {'PASS' if ok else 'FAIL'}\n")
|
|
||||||
return ok
|
|
||||||
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
results = [
|
|
||||||
("断点续传", scenario_resume()),
|
|
||||||
("丢失率≤0.02%", scenario_loss_rate()),
|
|
||||||
]
|
|
||||||
print("=" * 40)
|
|
||||||
all_ok = True
|
|
||||||
for name, ok in results:
|
|
||||||
print(f" {name}: {'PASS' if ok else 'FAIL'}")
|
|
||||||
all_ok = all_ok and ok
|
|
||||||
print("=" * 40)
|
|
||||||
print("全部通过" if all_ok else "存在未达标项")
|
|
||||||
return 0 if all_ok else 1
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -146,52 +146,6 @@ class EngineMetricsTest(unittest.TestCase):
|
|||||||
self.assertLessEqual(metrics.p99_latency(), 0.6)
|
self.assertLessEqual(metrics.p99_latency(), 0.6)
|
||||||
self.assertEqual(metrics.total_samples, 100)
|
self.assertEqual(metrics.total_samples, 100)
|
||||||
|
|
||||||
def test_per_point_sample_rate_schedule(self):
|
|
||||||
"""点位级 sampleRate 调度(issue #23):低频点位按比例降频,去硬编码。"""
|
|
||||||
# interval_ms=1000:A 点 1s 采样、B 点 5s 采样、C 点 500ms(小于 tick,退化为每 tick)
|
|
||||||
pd = PointDict([
|
|
||||||
Point(device_id="CLF-01", point_id="CLF-01.A", name="A", unit="℃",
|
|
||||||
data_type="float", sample_rate=1000, quality_code=True, row_number=2),
|
|
||||||
Point(device_id="CLF-01", point_id="CLF-01.B", name="B", unit="℃",
|
|
||||||
data_type="float", sample_rate=5000, quality_code=True, row_number=3),
|
|
||||||
Point(device_id="CLF-01", point_id="CLF-01.C", name="C", unit="℃",
|
|
||||||
data_type="float", sample_rate=500, quality_code=True, row_number=4),
|
|
||||||
])
|
|
||||||
spool = SpoolStore(os.path.join(self._tmp, "spool"))
|
|
||||||
metrics = HealthMetrics()
|
|
||||||
engine = CollectorEngine(
|
|
||||||
point_dict=pd,
|
|
||||||
driver_slots=[("simulator", SimulatorDriver(), [])],
|
|
||||||
spool=spool,
|
|
||||||
metrics=metrics,
|
|
||||||
interval_ms=1000,
|
|
||||||
)
|
|
||||||
# 记录每个点位在 10 个 tick 内被读取的次数(读驱动时计数)
|
|
||||||
read_counts = {"CLF-01.A": 0, "CLF-01.B": 0, "CLF-01.C": 0}
|
|
||||||
original = SimulatorDriver.read_points
|
|
||||||
|
|
||||||
def counting_read(self, points):
|
|
||||||
for p in points:
|
|
||||||
read_counts[p.point_id] += 1
|
|
||||||
return original(self, points)
|
|
||||||
|
|
||||||
SimulatorDriver.read_points = counting_read
|
|
||||||
try:
|
|
||||||
for _ in range(10):
|
|
||||||
engine.collect_once()
|
|
||||||
finally:
|
|
||||||
SimulatorDriver.read_points = original
|
|
||||||
# A:1000ms / 1000ms tick → 每 tick 都读 = 10 次
|
|
||||||
self.assertEqual(read_counts["CLF-01.A"], 10)
|
|
||||||
# B:5000ms / 1000ms tick → 每 5 tick 读一次 ≈ 2 次(tick1、tick6)
|
|
||||||
self.assertEqual(read_counts["CLF-01.B"], 2)
|
|
||||||
# C:500ms < tick → 每 tick 读 = 10 次(不做高于 tick 频率的超采样)
|
|
||||||
self.assertEqual(read_counts["CLF-01.C"], 10)
|
|
||||||
# 调度推进:低频点位不再被硬编码为每 tick 读取
|
|
||||||
self.assertEqual(engine._ticks_per_sample(pd.points[0]), 1)
|
|
||||||
self.assertEqual(engine._ticks_per_sample(pd.points[1]), 5)
|
|
||||||
self.assertEqual(engine._ticks_per_sample(pd.points[2]), 1)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -1,139 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""和利时 DCS OPC 驱动参数化适配测试(issue #25)。
|
|
||||||
|
|
||||||
覆盖:
|
|
||||||
1. 驱动注册表包含 hollysys(from_template 可实例化);
|
|
||||||
2. 参数化提取:ua 模式(endpoint/security/username/password)与
|
|
||||||
da 模式(host/prog_id/cls_id);
|
|
||||||
3. 只读约束:驱动无任何写/控制方法(PRD 9 章零控制指令下发);
|
|
||||||
4. 依赖缺失路径:UA/DA 底层库未安装时 connect 抛出明确 ConnectionError;
|
|
||||||
5. 委托路由:connect 后 read_points/close 委托到底层实现。
|
|
||||||
"""
|
|
||||||
import unittest
|
|
||||||
from unittest import mock
|
|
||||||
|
|
||||||
from drivers import HollysysDcsDriver, from_template
|
|
||||||
from drivers.base import Driver
|
|
||||||
from drivers.hollysys_driver import _HollysysDaDriver
|
|
||||||
from drivers.opcua_driver import OpcUaDriver
|
|
||||||
from point_dict.loader import Point
|
|
||||||
|
|
||||||
UA_CONFIG = {
|
|
||||||
"mode": "ua",
|
|
||||||
"endpoint": "opc.tcp://10.20.1.10:4840",
|
|
||||||
"security": "Basic256Sha256",
|
|
||||||
"username": "iaop_read",
|
|
||||||
"password": "secret",
|
|
||||||
"timeout": 10,
|
|
||||||
}
|
|
||||||
DA_CONFIG = {
|
|
||||||
"mode": "da",
|
|
||||||
"host": "10.20.1.10",
|
|
||||||
"prog_id": "Hollysys.OPCServer",
|
|
||||||
"timeout": 10,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def make_point(point_id="CLF-01.TEMP", opc_node="ns=2;s=CLF.Temp"):
|
|
||||||
return Point(
|
|
||||||
device_id="CLF-01", point_id=point_id, name="炉温", unit="℃",
|
|
||||||
data_type="float", sample_rate=1000, quality_code=True,
|
|
||||||
opc_node=opc_node, protocol="hollysys",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class TestRegistry(unittest.TestCase):
|
|
||||||
"""注册表与工厂。"""
|
|
||||||
|
|
||||||
def test_registry_contains_hollysys(self):
|
|
||||||
driver = from_template("hollysys", UA_CONFIG)
|
|
||||||
self.assertIsInstance(driver, HollysysDcsDriver)
|
|
||||||
|
|
||||||
def test_driver_is_read_only(self):
|
|
||||||
"""只读约束:驱动只暴露 connect/read_points/close,无写方法。"""
|
|
||||||
driver = HollysysDcsDriver(UA_CONFIG)
|
|
||||||
methods = {m for m in dir(driver) if not m.startswith("_")}
|
|
||||||
self.assertIn("read_points", methods)
|
|
||||||
self.assertNotIn("write", methods)
|
|
||||||
self.assertNotIn("write_points", methods)
|
|
||||||
self.assertNotIn("set_value", methods)
|
|
||||||
|
|
||||||
|
|
||||||
class TestParameterization(unittest.TestCase):
|
|
||||||
"""参数化提取。"""
|
|
||||||
|
|
||||||
def test_ua_params(self):
|
|
||||||
driver = HollysysDcsDriver(UA_CONFIG)
|
|
||||||
self.assertEqual(driver.mode, "ua")
|
|
||||||
ua = OpcUaDriver(UA_CONFIG)
|
|
||||||
self.assertEqual(ua.endpoint, "opc.tcp://10.20.1.10:4840")
|
|
||||||
self.assertEqual(ua.security, "Basic256Sha256")
|
|
||||||
self.assertEqual(ua.username, "iaop_read")
|
|
||||||
self.assertEqual(ua.password, "secret")
|
|
||||||
|
|
||||||
def test_da_params(self):
|
|
||||||
driver = HollysysDcsDriver(DA_CONFIG)
|
|
||||||
self.assertEqual(driver.mode, "da")
|
|
||||||
da = _HollysysDaDriver(DA_CONFIG)
|
|
||||||
self.assertEqual(da.host, "10.20.1.10")
|
|
||||||
self.assertEqual(da.prog_id, "Hollysys.OPCServer")
|
|
||||||
self.assertEqual(_HollysysDaDriver({}).prog_id,
|
|
||||||
"Hollysys.OPCServer") # 默认 ProgID
|
|
||||||
|
|
||||||
def test_default_mode_is_ua(self):
|
|
||||||
driver = HollysysDcsDriver({})
|
|
||||||
self.assertEqual(driver.mode, "ua")
|
|
||||||
|
|
||||||
|
|
||||||
class TestConnectDependencyErrors(unittest.TestCase):
|
|
||||||
"""底层库未安装时的明确报错(不静默失败)。"""
|
|
||||||
|
|
||||||
def test_ua_missing_dependency(self):
|
|
||||||
driver = HollysysDcsDriver(UA_CONFIG)
|
|
||||||
with mock.patch.dict("sys.modules", {"opcua": None}):
|
|
||||||
with self.assertRaises(ConnectionError) as ctx:
|
|
||||||
driver.connect()
|
|
||||||
self.assertIn("opcua", str(ctx.exception))
|
|
||||||
|
|
||||||
def test_da_missing_dependency(self):
|
|
||||||
driver = HollysysDcsDriver(DA_CONFIG)
|
|
||||||
with mock.patch.dict("sys.modules", {"OpenOPC": None}):
|
|
||||||
with self.assertRaises(ConnectionError) as ctx:
|
|
||||||
driver.connect()
|
|
||||||
self.assertIn("OpenOPC", str(ctx.exception))
|
|
||||||
|
|
||||||
|
|
||||||
class TestDelegation(unittest.TestCase):
|
|
||||||
"""connect 后 read_points/close 委托到底层实现。"""
|
|
||||||
|
|
||||||
def test_ua_delegates_to_opcua_driver(self):
|
|
||||||
driver = HollysysDcsDriver(UA_CONFIG)
|
|
||||||
with mock.patch("drivers.opcua_driver.OpcUaDriver.connect"):
|
|
||||||
driver.connect()
|
|
||||||
self.assertIsInstance(driver._delegate, OpcUaDriver)
|
|
||||||
point = make_point()
|
|
||||||
with mock.patch.object(driver._delegate, "read_points",
|
|
||||||
return_value={"CLF-01.TEMP": 850.5}) as rd:
|
|
||||||
values = driver.read_points([point])
|
|
||||||
rd.assert_called_once_with([point])
|
|
||||||
self.assertEqual(values["CLF-01.TEMP"], 850.5)
|
|
||||||
with mock.patch.object(driver._delegate, "close"):
|
|
||||||
driver.close()
|
|
||||||
self.assertIsNone(driver._delegate)
|
|
||||||
|
|
||||||
def test_da_delegates_to_da_driver(self):
|
|
||||||
driver = HollysysDcsDriver(DA_CONFIG)
|
|
||||||
fake_openopc = mock.MagicMock()
|
|
||||||
with mock.patch.dict("sys.modules", {"OpenOPC": fake_openopc}):
|
|
||||||
with mock.patch.object(_HollysysDaDriver, "connect"):
|
|
||||||
driver.connect()
|
|
||||||
self.assertIsInstance(driver._delegate, _HollysysDaDriver)
|
|
||||||
|
|
||||||
def test_read_before_connect_raises(self):
|
|
||||||
driver = HollysysDcsDriver(UA_CONFIG)
|
|
||||||
with self.assertRaises(ConnectionError):
|
|
||||||
driver.read_points([make_point()])
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -11,9 +11,8 @@ core/llm-gateway/
|
|||||||
├── __init__.py 包入口(导出各模块 API)
|
├── __init__.py 包入口(导出各模块 API)
|
||||||
├── dlp.py DLP 敏感数据拦截引擎(Issue #48)
|
├── dlp.py DLP 敏感数据拦截引擎(Issue #48)
|
||||||
├── router.py 敏感度路由规则引擎(Issue #43 雏形)
|
├── router.py 敏感度路由规则引擎(Issue #43 雏形)
|
||||||
├── prompts.py Prompt 版本管理(Issue #47)
|
├── prompts.py Prompt 版本管理(Issue #47 雏形)
|
||||||
├── hallucination.py 幻觉/事实性校验中间件(Issue #47)
|
├── hallucination.py 幻觉/事实性校验中间件(Issue #47 雏形)
|
||||||
├── evaluate_hallucination.py 幻觉/事实性评测报告脚本(Issue #47)
|
|
||||||
├── gateway.py 混合网关主编排(EPIC #6 主体交付)
|
├── gateway.py 混合网关主编排(EPIC #6 主体交付)
|
||||||
├── config/
|
├── config/
|
||||||
│ ├── dlp.template.yaml 模板 DLP 规则资产(ti-cl4 示例)
|
│ ├── dlp.template.yaml 模板 DLP 规则资产(ti-cl4 示例)
|
||||||
@@ -108,65 +107,16 @@ if result.needs_human:
|
|||||||
|
|
||||||
- **敏感度路由**(router.py,Issue #43 雏形):模板配置驱动,DLP 拦截
|
- **敏感度路由**(router.py,Issue #43 雏形):模板配置驱动,DLP 拦截
|
||||||
fail-closed 强制 block,未知内容保守走本地(数据不出厂);
|
fail-closed 强制 block,未知内容保守走本地(数据不出厂);
|
||||||
- **Prompt 版本管理**(prompts.py,Issue #47):semver 版本库、
|
- **Prompt 版本管理**(prompts.py,Issue #47 雏形):semver 版本库、
|
||||||
运行时绑定(可复现)、一键回滚、变更审计;
|
运行时绑定(可复现)、一键回滚、变更审计;
|
||||||
- **幻觉/事实性校验**(hallucination.py,Issue #47):`[来源: X]`
|
- **幻觉/事实性校验**(hallucination.py,Issue #47 雏形):`[来源: X]`
|
||||||
引用溯源强制校验 + 高利害信度阈值 → 人工确认,并与 Prompt 版本库联动
|
引用溯源强制校验 + 高利害信度阈值 → 人工确认;
|
||||||
(评测按 `name@version` 分解,Prompt 变更后可对比各版本事实一致性);
|
|
||||||
- **推理后端抽象**(gateway.py 内 `InferenceBackend`):业务代码只依赖
|
- **推理后端抽象**(gateway.py 内 `InferenceBackend`):业务代码只依赖
|
||||||
接口,本地 70B / 云端 API 具体接入由子任务 #44 / #45 实现。
|
接口,本地 70B / 云端 API 具体接入由子任务 #44 / #45 实现。
|
||||||
|
|
||||||
## Prompt 版本管理 + 幻觉/事实性校验(Issue #47)
|
|
||||||
|
|
||||||
对应 PRD 5.4「Prompt 版本管理 + 幻觉/事实性校验」。
|
|
||||||
|
|
||||||
### Prompt 版本管理(prompts.py)
|
|
||||||
|
|
||||||
所有提示词模板纳入版本库(semver),变更须评审并记录(同版本号覆盖报错),
|
|
||||||
支持一键回滚;生产流程运行时按 `(name, version)` 绑定,可复现。
|
|
||||||
|
|
||||||
```python
|
|
||||||
from llm_gateway.prompts import PromptRegistry
|
|
||||||
|
|
||||||
reg = PromptRegistry.from_template_config("config/prompts.template.yaml")
|
|
||||||
pv = reg.get("qa", version="1.0.0") # 显式绑定旧版本:行为不受后续变更影响
|
|
||||||
rendered = pv.render(query="炉温偏高怎么处理")
|
|
||||||
reg.promote("qa", "1.0.1")
|
|
||||||
reg.rollback("qa") # 一键回滚
|
|
||||||
```
|
|
||||||
|
|
||||||
### 幻觉/事实性校验(hallucination.py)
|
|
||||||
|
|
||||||
RAG 答案强制引用溯源:输出中所有 `[来源: X]` 声明必须命中本次 RAG 检索的
|
|
||||||
文档片段,否则判 `unsupported`(幻觉嫌疑);高利害输出(处置建议 / 报警解释)
|
|
||||||
要求信度 ≥ 阈值,否则 `human_review` 转人工确认。
|
|
||||||
|
|
||||||
```python
|
|
||||||
from llm_gateway.hallucination import HallucinationGuard
|
|
||||||
|
|
||||||
guard = HallucinationGuard(default_threshold=0.8)
|
|
||||||
v = guard.check(
|
|
||||||
answer="建议降温。[来源: 沸腾氯化炉异常处置SOP]",
|
|
||||||
sources=["沸腾氯化炉异常处置SOP"],
|
|
||||||
confidence=0.95, high_stakes=True,
|
|
||||||
prompt_name="alarm_explain", prompt_version="1.0.0", # 与版本库联动
|
|
||||||
)
|
|
||||||
print(v.action) # pass / human_review / unsupported
|
|
||||||
```
|
|
||||||
|
|
||||||
### 定期评测报告脚本(evaluate_hallucination.py)
|
|
||||||
|
|
||||||
PRD 5.4「定期用评测集检验事实一致性」:评测集 JSON + 版本库配置 →
|
|
||||||
Markdown 评测报告(按 `name@version` 分解,Prompt 变更后可对比各版本幻觉率)。
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd core/llm-gateway
|
|
||||||
python evaluate_hallucination.py --demo --output reports/hallucination.md
|
|
||||||
python evaluate_hallucination.py --samples eval_set.json --output report.md
|
|
||||||
```
|
|
||||||
|
|
||||||
## 后续子任务(EPIC #6 拆分,待扩展)
|
## 后续子任务(EPIC #6 拆分,待扩展)
|
||||||
|
|
||||||
- 敏感度路由调优与路由准确率评估脚本(Issue #49,本版已提供评估入口);
|
- 敏感度路由调优与路由准确率评估脚本(Issue #49,本版已提供评估入口);
|
||||||
- 本地 70B 模型接入与推理封装(Issue #44);
|
- 本地 70B 模型接入与推理封装(Issue #44);
|
||||||
- 云端 API(Qwen/DeepSeek)接入与安全网关(Issue #45)。
|
- 云端 API(Qwen/DeepSeek)接入与安全网关(Issue #45);
|
||||||
|
- Prompt 版本管理 + 幻觉校验中间件完善(Issue #47,本版已提供核心)。
|
||||||
|
|||||||
@@ -10,17 +10,16 @@
|
|||||||
全量审计。
|
全量审计。
|
||||||
- router 敏感度路由规则引擎(Issue #43 雏形):敏感度分级路由(local/cloud/
|
- router 敏感度路由规则引擎(Issue #43 雏形):敏感度分级路由(local/cloud/
|
||||||
block),模板配置驱动,DLP 拦截即 fail-closed 转 block。
|
block),模板配置驱动,DLP 拦截即 fail-closed 转 block。
|
||||||
- prompts Prompt 版本管理(Issue #47 完成交付):semver 版本库、运行时绑定、
|
- prompts Prompt 版本管理(Issue #47 雏形):semver 版本库、运行时绑定、
|
||||||
一键回滚、变更审计。
|
一键回滚、变更审计。
|
||||||
- hallucination 幻觉/事实性校验中间件(Issue #47 完成交付):引用溯源 +
|
- hallucination 幻觉/事实性校验中间件(Issue #47 雏形):引用溯源 +
|
||||||
高利害信度阈值 → 人工确认,与 Prompt 版本库联动(评测按 name@version
|
高利害信度阈值 → 人工确认。
|
||||||
分解,配套评测报告脚本 evaluate_hallucination.py)。
|
|
||||||
- gateway 混合网关主编排(EPIC #6 主体):路由 → 生成 → 溯源校验 →
|
- gateway 混合网关主编排(EPIC #6 主体):路由 → 生成 → 溯源校验 →
|
||||||
DLP 出站防线,端到端闭环。
|
DLP 出站防线,端到端闭环。
|
||||||
|
|
||||||
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
||||||
"""
|
"""
|
||||||
__version__ = "0.3.0"
|
__version__ = "0.2.0"
|
||||||
|
|
||||||
from .dlp import (
|
from .dlp import (
|
||||||
DLP_DEFAULT_RULES,
|
DLP_DEFAULT_RULES,
|
||||||
|
|||||||
@@ -1,156 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""iAOP-Core · LLM 网关 —— 幻觉/事实性校验评测报告脚本(Issue #47)。
|
|
||||||
|
|
||||||
对应 PRD 5.4「定期用评测集检验事实一致性」:把评测集 JSON + Prompt 版本库
|
|
||||||
配置跑一遍 `HallucinationGuard.evaluate()`,产出 Markdown 评测报告
|
|
||||||
(按 `name@version` 分解,Prompt 变更后可用于对比各版本事实一致性)。
|
|
||||||
|
|
||||||
用法示例:
|
|
||||||
# 使用内置演示评测集,输出报告到文件(utf-8)
|
|
||||||
python evaluate_hallucination.py --demo --output reports/hallucination.md
|
|
||||||
|
|
||||||
# 使用自定义评测集 JSON(见下方 SAMPLE 字段说明)
|
|
||||||
python evaluate_hallucination.py --samples eval_set.json --output report.md
|
|
||||||
|
|
||||||
# 不指定 --output:报告打印到 stdout
|
|
||||||
python evaluate_hallucination.py --demo
|
|
||||||
|
|
||||||
评测集 JSON 格式(顶层为数组):
|
|
||||||
[
|
|
||||||
{
|
|
||||||
"answer": "建议降温。[来源: 沸腾氯化炉异常处置SOP]",
|
|
||||||
"sources": ["沸腾氯化炉异常处置SOP"],
|
|
||||||
"confidence": 0.9,
|
|
||||||
"high_stakes": true,
|
|
||||||
"prompt_name": "alarm_explain", // 可选,与版本库联动
|
|
||||||
"prompt_version": "1.0.0" // 可选,缺省取当前默认版本
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
|
||||||
"""
|
|
||||||
from __future__ import annotations
|
|
||||||
|
|
||||||
import argparse
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import types
|
|
||||||
from typing import List
|
|
||||||
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
# 包挂载(目录名含连字符,无法直接以包名 import;与 tests/_bootstrap.py 同款)
|
|
||||||
# ---------------------------------------------------------------------------
|
|
||||||
_LLM_GW_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
sys.path.insert(0, _LLM_GW_DIR)
|
|
||||||
if "llm_gateway" not in sys.modules:
|
|
||||||
_pkg = types.ModuleType("llm_gateway")
|
|
||||||
_pkg.__path__ = [_LLM_GW_DIR]
|
|
||||||
sys.modules["llm_gateway"] = _pkg
|
|
||||||
|
|
||||||
from llm_gateway.hallucination import HallucinationGuard # noqa: E402
|
|
||||||
from llm_gateway.prompts import PromptRegistry # noqa: E402
|
|
||||||
|
|
||||||
# 内置演示评测集(无 --samples 时使用,覆盖 pass / unsupported / human_review)
|
|
||||||
DEMO_SAMPLES: List[dict] = [
|
|
||||||
{
|
|
||||||
"answer": "建议降低氯化炉温度并观察。[来源: 沸腾氯化炉异常处置SOP]",
|
|
||||||
"sources": ["沸腾氯化炉异常处置SOP"],
|
|
||||||
"confidence": 0.95,
|
|
||||||
"high_stakes": True,
|
|
||||||
"prompt_name": "alarm_explain",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"answer": "应立即停机检修。[来源: 不存在的工艺文档]",
|
|
||||||
"sources": ["沸腾氯化炉异常处置SOP"],
|
|
||||||
"confidence": 0.9,
|
|
||||||
"high_stakes": True,
|
|
||||||
"prompt_name": "alarm_explain",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"answer": "班次生产概况:炉温稳定。[来源: 交接班规范]",
|
|
||||||
"sources": ["交接班规范"],
|
|
||||||
"confidence": 0.6,
|
|
||||||
"high_stakes": False,
|
|
||||||
"prompt_name": "shift_handover",
|
|
||||||
"prompt_version": "1.0.1",
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
|
|
||||||
def load_samples(path: str) -> List[dict]:
|
|
||||||
"""从 JSON 文件加载评测集(顶层为样本数组)。"""
|
|
||||||
with open(path, "r", encoding="utf-8") as fh:
|
|
||||||
data = json.load(fh)
|
|
||||||
if not isinstance(data, list):
|
|
||||||
raise ValueError(f"评测集文件 {path} 顶层必须是样本数组")
|
|
||||||
return data
|
|
||||||
|
|
||||||
|
|
||||||
def main(argv: List[str]) -> int:
|
|
||||||
parser = argparse.ArgumentParser(
|
|
||||||
prog="evaluate_hallucination",
|
|
||||||
description="幻觉/事实性校验评测报告(PRD 5.4 定期评测)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--prompts-config", default="config/prompts.template.yaml",
|
|
||||||
help="Prompt 版本库模板资产路径(默认 config/prompts.template.yaml)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--samples", default=None,
|
|
||||||
help="评测集 JSON 文件路径(与 --demo 二选一)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--demo", action="store_true",
|
|
||||||
help="使用内置演示评测集(未指定 --samples 时默认开启)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--threshold", type=float, default=0.8,
|
|
||||||
help="高利害信度阈值(默认 0.8)",
|
|
||||||
)
|
|
||||||
parser.add_argument(
|
|
||||||
"--output", default=None,
|
|
||||||
help="报告输出文件路径(utf-8);缺省打印到 stdout",
|
|
||||||
)
|
|
||||||
args = parser.parse_args(argv)
|
|
||||||
|
|
||||||
# 评测集:--samples 优先,否则内置演示集
|
|
||||||
if args.samples:
|
|
||||||
samples = load_samples(args.samples)
|
|
||||||
else:
|
|
||||||
samples = DEMO_SAMPLES
|
|
||||||
print("[evaluate_hallucination] 未指定 --samples,使用内置演示评测集",
|
|
||||||
file=sys.stderr)
|
|
||||||
|
|
||||||
# Prompt 版本库(与评测联动:按 name@version 分解)
|
|
||||||
registry = PromptRegistry.from_template_config(args.prompts_config)
|
|
||||||
|
|
||||||
guard = HallucinationGuard(default_threshold=args.threshold)
|
|
||||||
report = guard.evaluate(samples, registry=registry)
|
|
||||||
text = guard.render_evaluation_report(report)
|
|
||||||
|
|
||||||
if args.output:
|
|
||||||
os.makedirs(os.path.dirname(os.path.abspath(args.output)) or ".", exist_ok=True)
|
|
||||||
with open(args.output, "w", encoding="utf-8") as fh:
|
|
||||||
fh.write(text)
|
|
||||||
print(f"[evaluate_hallucination] 评测报告已写入:{args.output}", file=sys.stderr)
|
|
||||||
else:
|
|
||||||
# Windows 控制台可能为 GBK:显式用 utf-8 输出避免编码错误
|
|
||||||
try:
|
|
||||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
||||||
except (AttributeError, ValueError): # pragma: no cover - 旧版解释器
|
|
||||||
pass
|
|
||||||
print(text)
|
|
||||||
|
|
||||||
# 简报(stderr,便于定时任务抓取结论)
|
|
||||||
print(
|
|
||||||
"[evaluate_hallucination] 样本 {total}|支持率 {sr:.1%}|人工复核率 {hr:.1%}"
|
|
||||||
.format(total=report["total"], sr=float(report["supported_rate"]),
|
|
||||||
hr=float(report["human_review_rate"])),
|
|
||||||
file=sys.stderr,
|
|
||||||
)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main(sys.argv[1:]))
|
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""iAOP-Core · LLM 网关 —— 幻觉/事实性校验中间件(Issue #47 完成交付)。
|
"""iAOP-Core · LLM 网关 —— 幻觉/事实性校验中间件(EPIC #6 主体,Issue #47 雏形)。
|
||||||
|
|
||||||
对应 PRD 5.4「④ LLM 网关 + RAG」:
|
对应 PRD 5.4「④ LLM 网关 + RAG」:
|
||||||
- **事实性校验**:RAG 答案强制**引用溯源**(返回命中文档片段+来源);
|
- **事实性校验**:RAG 答案强制**引用溯源**(返回命中文档片段+来源);
|
||||||
@@ -12,13 +12,12 @@
|
|||||||
(无源引用 = 幻觉嫌疑);
|
(无源引用 = 幻觉嫌疑);
|
||||||
- **信度阈值**:对高利害输出(处置建议 / 报警解释)要求信度 ≥ 阈值,
|
- **信度阈值**:对高利害输出(处置建议 / 报警解释)要求信度 ≥ 阈值,
|
||||||
低于阈值返回 `human_review`(转人工确认,PRD 5.4 异常时转人工);
|
低于阈值返回 `human_review`(转人工确认,PRD 5.4 异常时转人工);
|
||||||
- **与 Prompt 版本库联动**:`check()` / `evaluate()` 可携带
|
- **评测集检验**:`evaluate()` 对 (prompt, answer, expected_sources) 样本
|
||||||
`prompt_name` / `prompt_version`(运行时绑定,可复现),评测报告按
|
批量评估事实一致性(供"定期评测"脚本调用)。
|
||||||
`name@version` 分解——Prompt 变更后可用同一评测集对比各版本事实一致性,
|
|
||||||
定位"版本升级导致幻觉率上升"(PRD 5.4 定期评测);
|
设计说明(供子任务 #47 继续细化):
|
||||||
- **评测报告**:`evaluate()` 产出结构化报告,`render_evaluation_report()`
|
- 本版实现校验核心(溯源 + 信度阈值 + 评测入口);
|
||||||
渲染 Markdown 报告,配套 CLI 脚本 `evaluate_hallucination.py`
|
- 子任务 #47 将在此基础上补齐与 Prompt 版本库的联动与评测报告脚本。
|
||||||
(评测集 JSON + 版本库配置 → 报告文件)。
|
|
||||||
|
|
||||||
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
||||||
"""
|
"""
|
||||||
@@ -44,8 +43,6 @@ class GuardVerdict:
|
|||||||
threshold: float # 本次校验使用的信度阈值
|
threshold: float # 本次校验使用的信度阈值
|
||||||
action: str # pass / human_review / unsupported
|
action: str # pass / human_review / unsupported
|
||||||
missing_sources: List[str] = field(default_factory=list)
|
missing_sources: List[str] = field(default_factory=list)
|
||||||
prompt_name: Optional[str] = None # 生成本次答案的 Prompt 模板名(版本库联动)
|
|
||||||
prompt_version: Optional[str] = None # 运行时绑定的模板版本(可复现)
|
|
||||||
verdict_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
|
verdict_id: str = field(default_factory=lambda: uuid.uuid4().hex[:12])
|
||||||
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
|
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
|
||||||
|
|
||||||
@@ -58,8 +55,6 @@ class GuardVerdict:
|
|||||||
"threshold": self.threshold,
|
"threshold": self.threshold,
|
||||||
"action": self.action,
|
"action": self.action,
|
||||||
"missing_sources": self.missing_sources,
|
"missing_sources": self.missing_sources,
|
||||||
"prompt_name": self.prompt_name,
|
|
||||||
"prompt_version": self.prompt_version,
|
|
||||||
"answer": self.answer,
|
"answer": self.answer,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -82,14 +77,8 @@ class HallucinationGuard:
|
|||||||
def check(self, answer: str, sources: Sequence[str],
|
def check(self, answer: str, sources: Sequence[str],
|
||||||
confidence: float = 1.0,
|
confidence: float = 1.0,
|
||||||
high_stakes: bool = False,
|
high_stakes: bool = False,
|
||||||
threshold: Optional[float] = None,
|
threshold: Optional[float] = None) -> GuardVerdict:
|
||||||
prompt_name: Optional[str] = None,
|
"""校验一条模型输出。返回结论(不修改输出,由调用方决定如何处置)。"""
|
||||||
prompt_version: Optional[str] = None) -> GuardVerdict:
|
|
||||||
"""校验一条模型输出。返回结论(不修改输出,由调用方决定如何处置)。
|
|
||||||
|
|
||||||
`prompt_name` / `prompt_version`:生成本次答案的 Prompt 模板与其
|
|
||||||
运行时绑定版本(与 PromptRegistry 联动,可复现,随审计落库)。
|
|
||||||
"""
|
|
||||||
th = threshold if threshold is not None else self.default_threshold
|
th = threshold if threshold is not None else self.default_threshold
|
||||||
# 1) 引用溯源:输出中声明的来源必须真实存在
|
# 1) 引用溯源:输出中声明的来源必须真实存在
|
||||||
declared = _SOURCE_REF_RE.findall(answer)
|
declared = _SOURCE_REF_RE.findall(answer)
|
||||||
@@ -108,165 +97,40 @@ class HallucinationGuard:
|
|||||||
verdict = GuardVerdict(
|
verdict = GuardVerdict(
|
||||||
answer=answer, supported=supported, confidence=confidence,
|
answer=answer, supported=supported, confidence=confidence,
|
||||||
threshold=th, action=action, missing_sources=missing,
|
threshold=th, action=action, missing_sources=missing,
|
||||||
prompt_name=prompt_name, prompt_version=prompt_version,
|
|
||||||
)
|
)
|
||||||
self._audit.append(verdict.to_dict())
|
self._audit.append(verdict.to_dict())
|
||||||
return verdict
|
return verdict
|
||||||
|
|
||||||
# -- 评测集检验(定期事实一致性评测入口) ------------------------------
|
# -- 评测集检验(定期事实一致性评测入口) ------------------------------
|
||||||
|
|
||||||
def evaluate(self, samples: List[Dict[str, object]],
|
def evaluate(self, samples: List[Dict[str, object]]) -> Dict[str, object]:
|
||||||
registry: Optional[object] = None,
|
"""批量评估事实一致性。
|
||||||
threshold: Optional[float] = None) -> Dict[str, object]:
|
|
||||||
"""批量评估事实一致性,产出结构化评测报告。
|
|
||||||
|
|
||||||
`samples`:`[{"answer", "sources", "confidence", "high_stakes",
|
`samples`:`[{"answer", "sources", "confidence", "high_stakes"}, ...]`。
|
||||||
"prompt_name", "prompt_version"}, ...]`;
|
返回支持率 / 人工复核率 / 未支持率。子任务 #47 将扩展为评测报告。
|
||||||
`registry`:`PromptRegistry`(可选)——与 Prompt 版本库联动:
|
|
||||||
- 样本带 `prompt_name` 时,按 `prompt_version`(缺省取当前默认版本)
|
|
||||||
解析为 `name@version`,报告按此分解,便于对比各版本事实一致性;
|
|
||||||
- 版本库中不存在该模板时,样本记录 `prompt_error` 而非中断评测。
|
|
||||||
|
|
||||||
返回:`total` / `supported_rate` / `human_review_rate` /
|
|
||||||
`unsupported_rate`,以及 `prompts`(按 `name@version` 分解的明细,
|
|
||||||
无 prompt 样本时为 `{}`)与 `samples`(逐样本记录)。
|
|
||||||
"""
|
"""
|
||||||
total = len(samples)
|
total = len(samples)
|
||||||
base: Dict[str, object] = {"total": total}
|
|
||||||
if total == 0:
|
if total == 0:
|
||||||
base.update({"supported_rate": 0.0, "human_review_rate": 0.0,
|
return {"supported_rate": 0.0, "human_review_rate": 0.0, "total": 0}
|
||||||
"unsupported_rate": 0.0, "prompts": {},
|
|
||||||
"samples": []})
|
|
||||||
return base
|
|
||||||
|
|
||||||
per_prompt: Dict[str, Dict[str, object]] = {}
|
|
||||||
sample_records: List[Dict[str, object]] = []
|
|
||||||
supported = 0
|
supported = 0
|
||||||
human = 0
|
human = 0
|
||||||
for s in samples:
|
for s in samples:
|
||||||
answer = str(s.get("answer", ""))
|
|
||||||
sources = [str(x) for x in s.get("sources", [])]
|
|
||||||
confidence = float(s.get("confidence", 1.0))
|
|
||||||
high_stakes = bool(s.get("high_stakes", False))
|
|
||||||
name = s.get("prompt_name")
|
|
||||||
version = s.get("prompt_version")
|
|
||||||
prompt_error: Optional[str] = None
|
|
||||||
label: Optional[str] = None
|
|
||||||
|
|
||||||
# 与 Prompt 版本库联动:解析运行时绑定版本(可复现)
|
|
||||||
if name and registry is not None:
|
|
||||||
try:
|
|
||||||
if version is None:
|
|
||||||
version = registry.current(str(name)).version
|
|
||||||
else:
|
|
||||||
registry.get(str(name), str(version)) # 校验存在性
|
|
||||||
label = f"{name}@{version}"
|
|
||||||
except (KeyError, ValueError) as exc:
|
|
||||||
prompt_error = f"{exc}"
|
|
||||||
label = f"{name}@unknown"
|
|
||||||
|
|
||||||
v = self.check(
|
v = self.check(
|
||||||
answer=answer, sources=sources, confidence=confidence,
|
answer=str(s.get("answer", "")),
|
||||||
high_stakes=high_stakes, threshold=threshold,
|
sources=[str(x) for x in s.get("sources", [])],
|
||||||
prompt_name=str(name) if name else None,
|
confidence=float(s.get("confidence", 1.0)),
|
||||||
prompt_version=str(version) if version else None,
|
high_stakes=bool(s.get("high_stakes", False)),
|
||||||
)
|
)
|
||||||
if v.supported:
|
if v.supported:
|
||||||
supported += 1
|
supported += 1
|
||||||
if v.action == "human_review":
|
if v.action == "human_review":
|
||||||
human += 1
|
human += 1
|
||||||
|
return {
|
||||||
if label is not None:
|
|
||||||
group = per_prompt.setdefault(label, {
|
|
||||||
"total": 0, "supported": 0, "human_review": 0,
|
|
||||||
"missing_sources": [],
|
|
||||||
})
|
|
||||||
group["total"] += 1
|
|
||||||
if v.supported:
|
|
||||||
group["supported"] += 1
|
|
||||||
if v.action == "human_review":
|
|
||||||
group["human_review"] += 1
|
|
||||||
if v.missing_sources:
|
|
||||||
group["missing_sources"].extend(v.missing_sources)
|
|
||||||
|
|
||||||
record = {
|
|
||||||
"answer": answer, "action": v.action, "supported": v.supported,
|
|
||||||
"confidence": confidence, "prompt": label,
|
|
||||||
"missing_sources": v.missing_sources,
|
|
||||||
}
|
|
||||||
if prompt_error:
|
|
||||||
record["prompt_error"] = prompt_error
|
|
||||||
sample_records.append(record)
|
|
||||||
|
|
||||||
# 补齐每组未支持数(total - supported 中可能含 human_review)
|
|
||||||
for g in per_prompt.values():
|
|
||||||
g["unsupported"] = g["total"] - g["supported"]
|
|
||||||
g["supported_rate"] = round(g["supported"] / g["total"], 4)
|
|
||||||
g["human_review_rate"] = round(g["human_review"] / g["total"], 4)
|
|
||||||
g["unsupported_rate"] = round(g["unsupported"] / g["total"], 4)
|
|
||||||
|
|
||||||
base.update({
|
|
||||||
"supported_rate": round(supported / total, 4),
|
"supported_rate": round(supported / total, 4),
|
||||||
"human_review_rate": round(human / total, 4),
|
"human_review_rate": round(human / total, 4),
|
||||||
"unsupported_rate": round((total - supported) / total, 4),
|
"unsupported_rate": round((total - supported) / total, 4),
|
||||||
"prompts": per_prompt,
|
"total": total,
|
||||||
"samples": sample_records,
|
}
|
||||||
})
|
|
||||||
return base
|
|
||||||
|
|
||||||
# -- 评测报告渲染 ------------------------------------------------------
|
|
||||||
|
|
||||||
def render_evaluation_report(self, report: Dict[str, object]) -> str:
|
|
||||||
"""把 `evaluate()` 的结构化报告渲染为 Markdown 文本(评测报告脚本用)。"""
|
|
||||||
total = int(report.get("total", 0))
|
|
||||||
lines: List[str] = [
|
|
||||||
"# LLM 网关 · 幻觉/事实性校验评测报告",
|
|
||||||
"",
|
|
||||||
f"- 生成时间:{datetime.now(timezone.utc).isoformat(timespec='seconds')}",
|
|
||||||
f"- 样本总数:{total}",
|
|
||||||
]
|
|
||||||
if total:
|
|
||||||
lines.append(
|
|
||||||
"- 支持率 {:.1%}|人工复核率 {:.1%}|未支持率 {:.1%}".format(
|
|
||||||
float(report.get("supported_rate", 0.0)),
|
|
||||||
float(report.get("human_review_rate", 0.0)),
|
|
||||||
float(report.get("unsupported_rate", 0.0)),
|
|
||||||
)
|
|
||||||
)
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
prompts = report.get("prompts") or {}
|
|
||||||
if prompts:
|
|
||||||
lines += [
|
|
||||||
"## 按 Prompt 版本分解",
|
|
||||||
"",
|
|
||||||
"| Prompt@版本 | 样本数 | 支持数 | 支持率 | 人工复核 | 未支持 |",
|
|
||||||
"|---|---|---|---|---|---|",
|
|
||||||
]
|
|
||||||
for label in sorted(prompts):
|
|
||||||
g = prompts[label]
|
|
||||||
lines.append(
|
|
||||||
"| {} | {} | {} | {:.1%} | {} | {} |".format(
|
|
||||||
label, g["total"], g["supported"],
|
|
||||||
float(g["supported_rate"]), g["human_review"],
|
|
||||||
g["unsupported"],
|
|
||||||
)
|
|
||||||
)
|
|
||||||
lines.append("")
|
|
||||||
|
|
||||||
bad = [r for r in report.get("samples", [])
|
|
||||||
if r.get("action") in ("unsupported", "human_review")]
|
|
||||||
if bad:
|
|
||||||
lines += ["## 未通过样本明细", ""]
|
|
||||||
for i, r in enumerate(bad, 1):
|
|
||||||
prompt = r.get("prompt") or "(未关联 Prompt 版本)"
|
|
||||||
lines.append(
|
|
||||||
f"{i}. **[{r['action']}]** {prompt}\n"
|
|
||||||
f" - 答案:{r['answer']}\n"
|
|
||||||
f" - 缺失来源:{r.get('missing_sources') or '—'}"
|
|
||||||
)
|
|
||||||
lines.append("")
|
|
||||||
return "\n".join(lines)
|
|
||||||
|
|
||||||
# -- 审计 --------------------------------------------------------------
|
# -- 审计 --------------------------------------------------------------
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""iAOP-Core · LLM 网关 —— Prompt 版本管理(Issue #47 完成交付)。
|
"""iAOP-Core · LLM 网关 —— Prompt 版本管理(EPIC #6 主体,Issue #47 雏形)。
|
||||||
|
|
||||||
对应 PRD 5.4「④ LLM 网关 + RAG」:
|
对应 PRD 5.4「④ LLM 网关 + RAG」:
|
||||||
- **Prompt 版本管理**:所有提示词模板纳入版本库(semver),变更须评审并记录,
|
- **Prompt 版本管理**:所有提示词模板纳入版本库(semver),变更须评审并记录,
|
||||||
@@ -14,10 +14,9 @@
|
|||||||
`rollback(name)` 回滚到上一版本(一键回滚);
|
`rollback(name)` 回滚到上一版本(一键回滚);
|
||||||
- **变更审计**:`update()` / `promote()` / `rollback()` 均落结构化变更记录。
|
- **变更审计**:`update()` / `promote()` / `rollback()` 均落结构化变更记录。
|
||||||
|
|
||||||
与幻觉/事实性校验中间件(hallucination.py)联动:评测样本携带
|
设计说明(供子任务 #47 继续细化):
|
||||||
`prompt_name` / `prompt_version`,`HallucinationGuard.evaluate(registry=...)`
|
- 本版实现版本库核心(绑定 / 回滚 / 审计);
|
||||||
按 `name@version` 分解事实一致性,Prompt 变更后可用同一评测集对比
|
- 子任务 #47 将在此基础上补齐幻觉/事实性校验中间件(见 hallucination.py)。
|
||||||
各版本幻觉率(配套 CLI:`evaluate_hallucination.py`)。
|
|
||||||
|
|
||||||
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
|
||||||
"""
|
"""
|
||||||
|
|||||||
@@ -1,55 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""评测报告脚本(evaluate_hallucination.py)端到端测试:--demo / --samples / --output。"""
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
import subprocess
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
|
|
||||||
LLM_GW_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
||||||
SCRIPT = os.path.join(LLM_GW_DIR, "evaluate_hallucination.py")
|
|
||||||
|
|
||||||
|
|
||||||
def _run(args, cwd):
|
|
||||||
env = dict(os.environ)
|
|
||||||
env["PYTHONIOENCODING"] = "utf-8" # 避免 Windows 控制台 GBK 编码问题
|
|
||||||
return subprocess.run(
|
|
||||||
[sys.executable, SCRIPT] + args,
|
|
||||||
cwd=cwd, capture_output=True, text=True, encoding="utf-8", env=env,
|
|
||||||
timeout=60,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
class EvaluateScriptTest(unittest.TestCase):
|
|
||||||
def test_demo_to_stdout(self):
|
|
||||||
proc = _run(["--demo"], cwd=LLM_GW_DIR)
|
|
||||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
||||||
self.assertIn("LLM 网关 · 幻觉/事实性校验评测报告", proc.stdout)
|
|
||||||
self.assertIn("样本总数", proc.stdout)
|
|
||||||
self.assertIn("支持率", proc.stdout)
|
|
||||||
self.assertIn("按 Prompt 版本分解", proc.stdout)
|
|
||||||
|
|
||||||
def test_samples_json_to_output_file(self):
|
|
||||||
samples = [
|
|
||||||
{"answer": "好[来源: X]", "sources": ["X"], "prompt_name": "qa"},
|
|
||||||
{"answer": "坏[来源: 不存在]", "sources": ["Y"], "prompt_name": "qa"},
|
|
||||||
]
|
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
|
||||||
samples_path = os.path.join(tmp, "samples.json")
|
|
||||||
report_path = os.path.join(tmp, "report.md")
|
|
||||||
with open(samples_path, "w", encoding="utf-8") as fh:
|
|
||||||
json.dump(samples, fh, ensure_ascii=False)
|
|
||||||
|
|
||||||
proc = _run(["--samples", samples_path, "--output", report_path],
|
|
||||||
cwd=LLM_GW_DIR)
|
|
||||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
|
||||||
self.assertTrue(os.path.exists(report_path))
|
|
||||||
with open(report_path, "r", encoding="utf-8") as fh:
|
|
||||||
text = fh.read()
|
|
||||||
self.assertIn("样本总数:2", text)
|
|
||||||
self.assertIn("qa@", text) # 与版本库联动:name@version 分解
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
unittest.main()
|
|
||||||
@@ -87,13 +87,10 @@ class EvaluateTest(unittest.TestCase):
|
|||||||
# 支持 2 条(a/c),human_review 1 条(c)
|
# 支持 2 条(a/c),human_review 1 条(c)
|
||||||
self.assertEqual(report["supported_rate"], round(2 / 3, 4))
|
self.assertEqual(report["supported_rate"], round(2 / 3, 4))
|
||||||
self.assertEqual(report["human_review_rate"], round(1 / 3, 4))
|
self.assertEqual(report["human_review_rate"], round(1 / 3, 4))
|
||||||
self.assertEqual(len(report["samples"]), 3)
|
|
||||||
self.assertEqual(report["prompts"], {})
|
|
||||||
|
|
||||||
def test_empty_samples(self):
|
def test_empty_samples(self):
|
||||||
report = self.guard.evaluate([])
|
report = self.guard.evaluate([])
|
||||||
self.assertEqual(report["total"], 0)
|
self.assertEqual(report["total"], 0)
|
||||||
self.assertEqual(report["samples"], [])
|
|
||||||
|
|
||||||
def test_audit_records(self):
|
def test_audit_records(self):
|
||||||
self.guard.check("x[来源: A]", sources=["A"])
|
self.guard.check("x[来源: A]", sources=["A"])
|
||||||
@@ -102,76 +99,5 @@ class EvaluateTest(unittest.TestCase):
|
|||||||
self.assertEqual(records[0]["action"], "pass")
|
self.assertEqual(records[0]["action"], "pass")
|
||||||
|
|
||||||
|
|
||||||
class PromptLinkageTest(unittest.TestCase):
|
|
||||||
"""Issue #47:与 Prompt 版本库的联动(check / evaluate 按 name@version 分解)。"""
|
|
||||||
|
|
||||||
def setUp(self):
|
|
||||||
from llm_gateway.prompts import PromptRegistry
|
|
||||||
|
|
||||||
self.guard = HallucinationGuard()
|
|
||||||
self.reg = PromptRegistry()
|
|
||||||
self.reg.update("qa", "问题:{query}", "1.0.0")
|
|
||||||
self.reg.update("qa", "问题:{query} 请引用SOP", "1.0.1")
|
|
||||||
self.reg.promote("qa", "1.0.1")
|
|
||||||
|
|
||||||
def test_check_records_prompt_version(self):
|
|
||||||
verdict = self.guard.check(
|
|
||||||
"按SOP处理。[来源: SOP]", sources=["SOP"],
|
|
||||||
prompt_name="qa", prompt_version="1.0.0",
|
|
||||||
)
|
|
||||||
self.assertEqual(verdict.prompt_name, "qa")
|
|
||||||
self.assertEqual(verdict.prompt_version, "1.0.0")
|
|
||||||
records = self.guard.drain_audit()
|
|
||||||
self.assertEqual(records[0]["prompt_name"], "qa")
|
|
||||||
self.assertEqual(records[0]["prompt_version"], "1.0.0")
|
|
||||||
|
|
||||||
def test_evaluate_breakdown_by_prompt_version(self):
|
|
||||||
samples = [
|
|
||||||
{"answer": "好[来源: X]", "sources": ["X"], "prompt_name": "qa", "prompt_version": "1.0.0"},
|
|
||||||
{"answer": "坏[来源: Y]", "sources": ["Z"], "prompt_name": "qa", "prompt_version": "1.0.0"},
|
|
||||||
{"answer": "好[来源: X]", "sources": ["X"], "prompt_name": "qa"}, # 缺省取当前默认 1.0.1
|
|
||||||
]
|
|
||||||
report = self.guard.evaluate(samples, registry=self.reg)
|
|
||||||
prompts = report["prompts"]
|
|
||||||
self.assertIn("qa@1.0.0", prompts)
|
|
||||||
self.assertIn("qa@1.0.1", prompts)
|
|
||||||
self.assertEqual(prompts["qa@1.0.0"]["total"], 2)
|
|
||||||
self.assertEqual(prompts["qa@1.0.0"]["supported"], 1)
|
|
||||||
self.assertEqual(prompts["qa@1.0.1"]["total"], 1)
|
|
||||||
# 逐样本记录携带 prompt 标签
|
|
||||||
self.assertEqual(report["samples"][0]["prompt"], "qa@1.0.0")
|
|
||||||
|
|
||||||
def test_evaluate_explicit_version_validated(self):
|
|
||||||
samples = [
|
|
||||||
{"answer": "x[来源: A]", "sources": ["A"], "prompt_name": "qa", "prompt_version": "1.0.1"},
|
|
||||||
]
|
|
||||||
report = self.guard.evaluate(samples, registry=self.reg)
|
|
||||||
self.assertIn("qa@1.0.1", report["prompts"])
|
|
||||||
self.assertNotIn("prompt_error", report["samples"][0])
|
|
||||||
|
|
||||||
def test_evaluate_unknown_prompt_does_not_crash(self):
|
|
||||||
samples = [
|
|
||||||
{"answer": "x[来源: A]", "sources": ["A"], "prompt_name": "not_exist"},
|
|
||||||
]
|
|
||||||
report = self.guard.evaluate(samples, registry=self.reg)
|
|
||||||
self.assertEqual(report["total"], 1)
|
|
||||||
self.assertEqual(report["samples"][0]["prompt"], "not_exist@unknown")
|
|
||||||
self.assertIn("prompt_error", report["samples"][0])
|
|
||||||
|
|
||||||
def test_render_report_contains_rates_and_prompt_section(self):
|
|
||||||
samples = [
|
|
||||||
{"answer": "好[来源: X]", "sources": ["X"], "prompt_name": "qa", "prompt_version": "1.0.0"},
|
|
||||||
{"answer": "坏[来源: 不存在]", "sources": ["Z"], "prompt_name": "qa", "prompt_version": "1.0.0"},
|
|
||||||
]
|
|
||||||
report = self.guard.evaluate(samples, registry=self.reg)
|
|
||||||
text = self.guard.render_evaluation_report(report)
|
|
||||||
self.assertIn("样本总数:2", text)
|
|
||||||
self.assertIn("支持率", text)
|
|
||||||
self.assertIn("## 按 Prompt 版本分解", text)
|
|
||||||
self.assertIn("qa@1.0.0", text)
|
|
||||||
self.assertIn("## 未通过样本明细", text)
|
|
||||||
self.assertIn("不存在", text)
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# iAOP-Core · FeatureSpec 声明式特征定义引擎
|
||||||
|
|
||||||
|
对应 issue #35(父 EPIC #5「③ AI 模型框架 配置化重构」)与 PRD 5.3「超参包驱动」:
|
||||||
|
超参包中每个特征的 `spec` 字段是一段**声明式特征定义表达式(FeatureSpec)**,本
|
||||||
|
模块负责把这段文本**解释**为可执行的特征计算:
|
||||||
|
|
||||||
|
> `EMA(CLF-01.TEMP, 5m)` → 解析为 AST → 校验 → 依赖分析 → materialize 为时序
|
||||||
|
|
||||||
|
`core/model-framework/hyperparam.py`(issue #39)只对 `spec` 做「非空字符串」存在性
|
||||||
|
校验;本模块补齐其语义层,使:
|
||||||
|
|
||||||
|
1. **配置台**(issue #62~#67 Template Console)导入超参包时即可一次性展示每个特征
|
||||||
|
的解析结果与依赖点位,训练前暴露拼写/语义错误;
|
||||||
|
2. **训练/推理流水线**(issue #40)拿到 AST 后直接 materialize 为「按点位拉取 → 算子
|
||||||
|
计算」的特征管道;
|
||||||
|
3. **切换模板仅改超参包**,特征逻辑零代码(对齐 PRD「配置化」核心目标)。
|
||||||
|
|
||||||
|
## 模块结构
|
||||||
|
|
||||||
|
```
|
||||||
|
core/model-framework/
|
||||||
|
├── feature_spec.py FeatureSpec 引擎(解析/校验/依赖/执行/算子注册)
|
||||||
|
└── tests/
|
||||||
|
├── _bootstrap.py 测试引导(目录含连字符,挂载包名 model_framework)
|
||||||
|
└── test_feature_spec.py 解析/校验/依赖/执行/插件注册单元测试
|
||||||
|
```
|
||||||
|
|
||||||
|
## 设计要点
|
||||||
|
|
||||||
|
* **零外部强依赖**:解析/校验/依赖分析不依赖第三方库;执行(`materialize`)优先用
|
||||||
|
numpy 向量化,无 numpy 时退化为纯 Python(边缘/离线环境可加载与校验)。
|
||||||
|
* **不可变 AST + 函数式算子**:每个算子是纯函数 `op(series_map, args)`,注册到
|
||||||
|
`OPERATORS`;新增算子只需 `register_operator`(对齐 PRD「新增结构走插件注册」,
|
||||||
|
与 issue #34 Model Recipe 插件接口呼应)。
|
||||||
|
* **安全解析**:手写递归下降解析器,**绝不使用 `eval`/`exec`**——FeatureSpec 是数据
|
||||||
|
而非代码,避免任意表达式注入。
|
||||||
|
|
||||||
|
## 语法(对齐 PRD 5.3 示例)
|
||||||
|
|
||||||
|
```
|
||||||
|
<Operator>(<arg>, <arg>, ...) # 一元/多元算子
|
||||||
|
<arg> := <tag> | <number> | <window> | <Operator>(...)
|
||||||
|
<tag> := 点位名,允许中文/点号/连字符,如 CLF-01.TEMP / 炉压
|
||||||
|
<number> := 整数或浮点(含负号),如 3、-0.5、1e-3
|
||||||
|
<window> := <正数><单位>,单位 d/h/m/s,如 5m、180d、10s
|
||||||
|
```
|
||||||
|
|
||||||
|
内置算子:`EMA / SMA / RollingStd / RollingMax / RollingMin / RateOfChange / Diff /
|
||||||
|
Lag / Log / Scale / Clip / Combine`,覆盖 PRD 5.3 超参包示例的全部特征形态。
|
||||||
|
|
||||||
|
## 使用
|
||||||
|
|
||||||
|
```python
|
||||||
|
from model_framework.feature_spec import (
|
||||||
|
parse, validate, resolve_inputs, materialize, describe, register_operator,
|
||||||
|
)
|
||||||
|
|
||||||
|
ast = parse("EMA(CLF-01.TEMP, 5m)") # 1. 解析
|
||||||
|
issues = validate(ast) # 2. 语义校验(空列表=通过)
|
||||||
|
tags = resolve_inputs(ast) # 3. 依赖点位:['CLF-01.TEMP']
|
||||||
|
feat = materialize(ast, {"CLF-01.TEMP": xs}) # 4. 执行 → list[float]
|
||||||
|
print(describe(ast)) # 人类可读描述
|
||||||
|
```
|
||||||
|
|
||||||
|
扩展算子(插件注册):
|
||||||
|
|
||||||
|
```python
|
||||||
|
register_operator(
|
||||||
|
"Double", min_arity=1, max_arity=1, arg_kinds=(("tag",),),
|
||||||
|
func=lambda s, a: [x * 2 for x in s[a[0].name]], doc="翻倍",
|
||||||
|
)
|
||||||
|
materialize(parse("Double(A)"), {"A": [1.0, 2.0]}) # → [2.0, 4.0]
|
||||||
|
```
|
||||||
|
|
||||||
|
## 测试
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd core/model-framework/tests
|
||||||
|
python -m unittest test_feature_spec
|
||||||
|
```
|
||||||
@@ -0,0 +1,861 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""FeatureSpec 声明式特征定义引擎。
|
||||||
|
|
||||||
|
对应 issue #35(父 EPIC #5「③ AI 模型框架 配置化重构」)与 PRD 5.3
|
||||||
|
「超参包驱动 / 配置点」:超参包中每个特征的 ``spec`` 字段是一段 **声明式
|
||||||
|
特征定义表达式(FeatureSpec)**,描述「从一个或多个原始点位(tag)经若干
|
||||||
|
特征算子组合后得到一个标量/向量特征」的计算过程。
|
||||||
|
|
||||||
|
``core/model-framework/hyperparam.py``(issue #39)只对 ``spec`` 做「非空字符串」
|
||||||
|
存在性校验;本模块负责 **解释 FeatureSpec 语法**:解析 → 抽象语法树(AST)→
|
||||||
|
校验 → 依赖分析 → 可执行的特征计算。这样:
|
||||||
|
|
||||||
|
1. 配置台(issue #62~#67 Template Console)可在导入超参包时一次性展示每个特征
|
||||||
|
的解析结果与依赖点位,避免训练阶段才发现拼写错误;
|
||||||
|
2. 训练/推理流水线(issue #40)拿到 AST 后可直接 materialize 为按点位拉取 →
|
||||||
|
算子计算的特征管道;
|
||||||
|
3. 同一内核切换模板仅改超参包,特征逻辑零代码(对齐 PRD「配置化」核心目标)。
|
||||||
|
|
||||||
|
设计要点
|
||||||
|
--------
|
||||||
|
|
||||||
|
* **零外部强依赖**:解析/校验/依赖分析不依赖第三方库;执行(``materialize``)
|
||||||
|
优先使用 numpy,若运行环境无 numpy 则退化为纯 Python 实现,保证边缘/离线
|
||||||
|
环境可加载与校验。
|
||||||
|
* **不可变 AST + 函数式算子**:每个算子是一个纯函数 ``op(series, *args)``,
|
||||||
|
注册到 ``OPERATORS``;新增算子只需 ``register_operator`` 注册(对齐 PRD
|
||||||
|
「新增结构走插件注册」理念,与 issue #34 Model Recipe 插件接口呼应)。
|
||||||
|
* **安全解析**:手写递归下降解析器,**绝不使用 ``eval``/``exec``**——FeatureSpec
|
||||||
|
是数据而非代码,避免任意表达式注入。
|
||||||
|
* **确定性**:相同 spec 解析结果稳定,``__repr__``/``to_dict`` 可序列化往返。
|
||||||
|
|
||||||
|
FeatureSpec 语法(对齐 PRD 5.3 示例)
|
||||||
|
------------------------------------
|
||||||
|
|
||||||
|
::
|
||||||
|
|
||||||
|
<Operator>(<arg>, <arg>, ...) # 一元/多元算子
|
||||||
|
<arg> := <tag> | <number> | <window> | <Operator>(...)
|
||||||
|
<tag> := 标识符,允许中文/点号/连字符 # 点位名,如 CLF-01.TEMP / 炉压
|
||||||
|
<number> := 整数或浮点(含负号),如 3、-0.5、1e-3
|
||||||
|
<window> := <正数><单位>,单位 d/h/m/s,如 5m、180d、10s
|
||||||
|
|
||||||
|
内置算子(覆盖 PRD 5.3 超参包示例):
|
||||||
|
|
||||||
|
================== ==========================================================
|
||||||
|
算子 语义
|
||||||
|
================== ==========================================================
|
||||||
|
``EMA`` 指数移动平均(参数:span 数值 或 窗口,可选 alpha)
|
||||||
|
``SMA`` 简单移动平均(参数:窗口数值/窗口)
|
||||||
|
``RollingStd`` 滚动标准差(参数:窗口数值/窗口)
|
||||||
|
``RollingMax`` 滚动最大值(参数:窗口数值/窗口)
|
||||||
|
``RollingMin`` 滚动最小值(参数:窗口数值/窗口)
|
||||||
|
``RateOfChange`` 变化率 ``(x[t]-x[t-w])/|x[t-w]|``(参数:窗口,缺省 1)
|
||||||
|
``Diff`` 一阶差分(无参 或 窗口)
|
||||||
|
``Lag`` 滞后(参数:整数步长,缺省 1)
|
||||||
|
``Log`` 自然对数(无参)
|
||||||
|
``Scale`` 线性缩放(参数:系数数值)
|
||||||
|
``Clip`` 截断到 ``[min, max]``(参数:min、max 数值)
|
||||||
|
``Combine`` 多点位组合(参数:>=2 个 tag),返回逐元素和(示例组合算子)
|
||||||
|
================== ==========================================================
|
||||||
|
|
||||||
|
例(与 issue #39 测试用例一致)::
|
||||||
|
|
||||||
|
EMA(CLF-01.TEMP, 5m) # CLF-01.TEMP 的 5 分钟指数移动平均
|
||||||
|
RollingStd(CLF-01.CL2, 10) # CLF-01.CL2 的 10 步滚动标准差
|
||||||
|
RateOfChange(炉压) # 炉压的 1 步变化率
|
||||||
|
Combine(A.tank1, A.tank2) # 两个罐位之和
|
||||||
|
"""
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import math
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
||||||
|
|
||||||
|
# numpy 为可选依赖:有则执行用向量化实现,无则退化为 list 计算
|
||||||
|
try: # pragma: no cover - 环境相关
|
||||||
|
import numpy as _np # type: ignore
|
||||||
|
|
||||||
|
_HAS_NUMPY = True
|
||||||
|
except Exception: # pragma: no cover
|
||||||
|
_np = None # type: ignore
|
||||||
|
_HAS_NUMPY = False
|
||||||
|
|
||||||
|
__all__ = [
|
||||||
|
"ParseError",
|
||||||
|
"SpecIssue",
|
||||||
|
"TagRef",
|
||||||
|
"Number",
|
||||||
|
"Window",
|
||||||
|
"OpCall",
|
||||||
|
"FeatureAST",
|
||||||
|
"parse",
|
||||||
|
"parse_feature",
|
||||||
|
"validate",
|
||||||
|
"materialize",
|
||||||
|
"resolve_inputs",
|
||||||
|
"describe",
|
||||||
|
"register_operator",
|
||||||
|
"OPERATORS",
|
||||||
|
]
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 语法层面的合法取值
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
#: 窗口单位 → 秒(用于把 ``5m`` 这类窗口折算为可比较的时长,仅在需要时使用)。
|
||||||
|
_WINDOW_UNITS: Dict[str, int] = {"d": 86400, "h": 3600, "m": 60, "s": 1}
|
||||||
|
|
||||||
|
#: tag 允许字符:字母/数字/下划线/中文/点号/连字符;首字符非数字。
|
||||||
|
# 点位名在工业现场常含 ``CLF-01.TEMP`` 这类带设备层级与量纲的命名,故放宽。
|
||||||
|
_TAG_RE = re.compile(r"^[A-Za-z\u4e00-\u9fff_][A-Za-z0-9\u4e00-\u9fff_.\-]*$")
|
||||||
|
|
||||||
|
#: 算子名:字母开头,可含下划线。
|
||||||
|
_OPNAME_RE = re.compile(r"^[A-Za-z][A-Za-z0-9_]*$")
|
||||||
|
|
||||||
|
#: 窗口字面量:<正数><单位>。
|
||||||
|
_WINDOW_RE = re.compile(r"^(\d+(?:\.\d+)?)([dhms])$")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# AST 节点
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _Node:
|
||||||
|
"""AST 基类。所有节点不可变(仅持有基础类型),可安全序列化往返。"""
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]: # pragma: no cover - 子类覆盖
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class TagRef(_Node):
|
||||||
|
"""原始点位引用,如 ``CLF-01.TEMP`` / ``炉压``。"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {"kind": "tag", "name": self.name}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
return self.name
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Number(_Node):
|
||||||
|
"""数值字面量(整数或浮点)。"""
|
||||||
|
|
||||||
|
value: Union[int, float]
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {"kind": "number", "value": self.value}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
v = self.value
|
||||||
|
return repr(v)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class Window(_Node):
|
||||||
|
"""窗口字面量,如 ``5m`` / ``180d``。
|
||||||
|
|
||||||
|
``steps`` 为窗口数值,``unit`` 为单位;``seconds`` 折算为秒(用于排序/比较)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
steps: float
|
||||||
|
unit: str
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"kind": "window",
|
||||||
|
"steps": self.steps,
|
||||||
|
"unit": self.unit,
|
||||||
|
"seconds": self.seconds,
|
||||||
|
}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def seconds(self) -> int:
|
||||||
|
return int(self.steps * _WINDOW_UNITS[self.unit])
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
# 整数步长省略小数点,保持与输入一致
|
||||||
|
s = self.steps
|
||||||
|
text = str(int(s)) if float(s).is_integer() else str(s)
|
||||||
|
return f"{text}{self.unit}"
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class OpCall(_Node):
|
||||||
|
"""算子调用,如 ``EMA(CLF-01.TEMP, 5m)``。"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
args: Tuple[Any, ...] # 元素为 _Node 子类实例
|
||||||
|
|
||||||
|
def to_dict(self) -> Dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"kind": "op",
|
||||||
|
"name": self.name,
|
||||||
|
"args": [a.to_dict() for a in self.args],
|
||||||
|
}
|
||||||
|
|
||||||
|
def __repr__(self) -> str:
|
||||||
|
inner = ", ".join(repr(a) for a in self.args)
|
||||||
|
return f"{self.name}({inner})"
|
||||||
|
|
||||||
|
|
||||||
|
#: 一棵 FeatureSpec 解析后的 AST 根节点。
|
||||||
|
FeatureAST = Union[TagRef, Number, Window, OpCall]
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 解析错误与校验问题
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class ParseError(ValueError):
|
||||||
|
"""FeatureSpec 语法解析错误。
|
||||||
|
|
||||||
|
带可选的 ``position``(出错字符在原 spec 中的偏移,便于配置台高亮)。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, message: str, position: Optional[int] = None) -> None:
|
||||||
|
self.position = position
|
||||||
|
self.message = message
|
||||||
|
super().__init__(message if position is None else f"{message}(位置 {position})")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class SpecIssue:
|
||||||
|
"""单条 FeatureSpec 校验/语义问题。"""
|
||||||
|
|
||||||
|
code: str # unknown_operator / bad_arg / arity / ...
|
||||||
|
message: str
|
||||||
|
context: str = "" # 出错子表达式的人类可读表示
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Tokenizer
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Token 类型
|
||||||
|
_T_NAME = "NAME" # 标识符(算子名 或 tag)
|
||||||
|
_T_NUMBER = "NUMBER"
|
||||||
|
_T_WINDOW = "WINDOW"
|
||||||
|
_T_LPAREN = "LPAREN" # (
|
||||||
|
_T_RPAREN = "RPAREN" # )
|
||||||
|
_T_COMMA = "COMMA" # ,
|
||||||
|
_T_EOF = "EOF"
|
||||||
|
|
||||||
|
_TOKEN_RE = re.compile(
|
||||||
|
r"""
|
||||||
|
\s*(?:
|
||||||
|
(?P<LPAREN>\()
|
||||||
|
| (?P<RPAREN>\))
|
||||||
|
| (?P<COMMA>,)
|
||||||
|
| (?P<WINDOW>\d+(?:\.\d+)?[dhms])
|
||||||
|
| (?P<NUMBER>[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?)
|
||||||
|
| (?P<NAME>[A-Za-z\u4e00-\u9fff_][A-Za-z0-9\u4e00-\u9fff_.\-]*)
|
||||||
|
)
|
||||||
|
""",
|
||||||
|
re.VERBOSE,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _tokenize(spec: str) -> List[Tuple[str, str, int]]:
|
||||||
|
"""把 FeatureSpec 文本切分为 token 列表。
|
||||||
|
|
||||||
|
返回 ``[(type, value, pos), ...]``,``pos`` 为 token 起始偏移。空格被跳过。
|
||||||
|
遇到无法识别的字符抛 ``ParseError``(带位置)。
|
||||||
|
"""
|
||||||
|
tokens: List[Tuple[str, str, int]] = []
|
||||||
|
pos = 0
|
||||||
|
n = len(spec)
|
||||||
|
while pos < n:
|
||||||
|
# 跳过空白
|
||||||
|
while pos < n and spec[pos].isspace():
|
||||||
|
pos += 1
|
||||||
|
if pos >= n:
|
||||||
|
break
|
||||||
|
m = _TOKEN_RE.match(spec, pos)
|
||||||
|
if not m or m.end() == pos:
|
||||||
|
raise ParseError(f"无法识别的字符 '{spec[pos]}'", pos)
|
||||||
|
if m.lastgroup == "LPAREN":
|
||||||
|
tokens.append((_T_LPAREN, "(", pos))
|
||||||
|
elif m.lastgroup == "RPAREN":
|
||||||
|
tokens.append((_T_RPAREN, ")", pos))
|
||||||
|
elif m.lastgroup == "COMMA":
|
||||||
|
tokens.append((_T_COMMA, ",", pos))
|
||||||
|
elif m.lastgroup == "WINDOW":
|
||||||
|
tokens.append((_T_WINDOW, m.group("WINDOW"), pos))
|
||||||
|
elif m.lastgroup == "NUMBER":
|
||||||
|
tokens.append((_T_NUMBER, m.group("NUMBER"), pos))
|
||||||
|
elif m.lastgroup == "NAME":
|
||||||
|
tokens.append((_T_NAME, m.group("NAME"), pos))
|
||||||
|
pos = m.end()
|
||||||
|
tokens.append((_T_EOF, "", pos))
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# Parser(递归下降)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class _Parser:
|
||||||
|
"""递归下降解析器。
|
||||||
|
|
||||||
|
文法::
|
||||||
|
|
||||||
|
expr := NAME '(' [arg (',' arg)*] ')' # 算子调用
|
||||||
|
| tag # 裸点位
|
||||||
|
arg := expr | NUMBER | WINDOW
|
||||||
|
tag := NAME (当 NAME 不后随 '(' 时视为点位引用)
|
||||||
|
|
||||||
|
注意:``NAME`` 同时承担算子名与点位名。判定规则——若 ``NAME`` 紧跟 ``(`` 则为
|
||||||
|
算子调用,否则为点位引用。这样 ``EMA(...)`` 与 ``炉压`` 可在同一文法中共存。
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, tokens: List[Tuple[str, str, int]]) -> None:
|
||||||
|
self.tokens = tokens
|
||||||
|
self.i = 0
|
||||||
|
|
||||||
|
def _peek(self) -> Tuple[str, str, int]:
|
||||||
|
return self.tokens[self.i]
|
||||||
|
|
||||||
|
def _next(self) -> Tuple[str, str, int]:
|
||||||
|
tok = self.tokens[self.i]
|
||||||
|
self.i += 1
|
||||||
|
return tok
|
||||||
|
|
||||||
|
def parse_expr(self) -> FeatureAST:
|
||||||
|
ttype, tval, tpos = self._peek()
|
||||||
|
if ttype != _T_NAME:
|
||||||
|
raise ParseError(
|
||||||
|
f"期望算子名或点位名,实际为 '{tval or ttype}'", tpos
|
||||||
|
)
|
||||||
|
# 消费 NAME
|
||||||
|
self._next()
|
||||||
|
nt = self._peek()
|
||||||
|
if nt[0] == _T_LPAREN:
|
||||||
|
# 算子调用
|
||||||
|
if not _OPNAME_RE.match(tval):
|
||||||
|
raise ParseError(f"算子名 '{tval}' 含非法字符", tpos)
|
||||||
|
self._next() # 消费 '('
|
||||||
|
args: List[Any] = []
|
||||||
|
if self._peek()[0] == _T_RPAREN:
|
||||||
|
# 无参算子,如 Diff()
|
||||||
|
self._next()
|
||||||
|
return OpCall(tval, tuple(args))
|
||||||
|
args.append(self.parse_arg())
|
||||||
|
while self._peek()[0] == _T_COMMA:
|
||||||
|
self._next()
|
||||||
|
args.append(self.parse_arg())
|
||||||
|
if self._peek()[0] != _T_RPAREN:
|
||||||
|
raise ParseError("缺少右括号 ')'", self._peek()[2])
|
||||||
|
self._next() # 消费 ')'
|
||||||
|
return OpCall(tval, tuple(args))
|
||||||
|
else:
|
||||||
|
# 点位引用
|
||||||
|
if not _TAG_RE.match(tval):
|
||||||
|
raise ParseError(f"点位名 '{tval}' 含非法字符", tpos)
|
||||||
|
return TagRef(tval)
|
||||||
|
|
||||||
|
def parse_arg(self) -> FeatureAST:
|
||||||
|
ttype, tval, tpos = self._peek()
|
||||||
|
if ttype == _T_NUMBER:
|
||||||
|
self._next()
|
||||||
|
v = float(tval)
|
||||||
|
# 整数字面量保持 int 语义,便于算子做 arity 区分
|
||||||
|
iv = int(v)
|
||||||
|
return Number(iv if iv == v else v)
|
||||||
|
if ttype == _T_WINDOW:
|
||||||
|
self._next()
|
||||||
|
m = _WINDOW_RE.match(tval)
|
||||||
|
assert m is not None # tokenizer 保证
|
||||||
|
steps = float(m.group(1))
|
||||||
|
return Window(steps, m.group(2))
|
||||||
|
if ttype == _T_NAME:
|
||||||
|
return self.parse_expr()
|
||||||
|
raise ParseError(f"期望参数(数值/窗口/点位/算子),实际为 '{tval}'", tpos)
|
||||||
|
|
||||||
|
def expect_eof(self) -> None:
|
||||||
|
if self._peek()[0] != _T_EOF:
|
||||||
|
tok = self._peek()
|
||||||
|
raise ParseError(f"表达式后存在多余内容 '{tok[1]}'", tok[2])
|
||||||
|
|
||||||
|
|
||||||
|
def parse(spec: str) -> FeatureAST:
|
||||||
|
"""解析单条 FeatureSpec 文本为 AST。
|
||||||
|
|
||||||
|
失败抛 ``ParseError``(带位置)。``spec`` 为空或非字符串抛 ``ValueError``。
|
||||||
|
"""
|
||||||
|
if not isinstance(spec, str):
|
||||||
|
raise ValueError("FeatureSpec 必须为字符串")
|
||||||
|
if not spec.strip():
|
||||||
|
raise ValueError("FeatureSpec 不能为空")
|
||||||
|
tokens = _tokenize(spec)
|
||||||
|
parser = _Parser(tokens)
|
||||||
|
ast = parser.parse_expr()
|
||||||
|
parser.expect_eof()
|
||||||
|
return ast
|
||||||
|
|
||||||
|
|
||||||
|
def parse_feature(spec: str) -> FeatureAST:
|
||||||
|
"""``parse`` 的别名,语义更贴近「解析一个特征的 spec」。"""
|
||||||
|
return parse(spec)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 算子注册表与语义校验
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
#: 算子签名:``OpSignature = (min_arity, max_arity, arg_kinds)``。
|
||||||
|
#: ``arg_kinds`` 为每参数位置允许的 AST kind(``"tag"``/``"number"``/``"window"``
|
||||||
|
#: /``"op"``),``None`` 表示任意。用于 validate 阶段检查参数形态。
|
||||||
|
OpSignature = Tuple[Optional[int], Optional[int], Tuple[Optional[Tuple[str, ...]], ...]]
|
||||||
|
|
||||||
|
#: 算子执行函数签名:``fn(series_map, args) -> result``。
|
||||||
|
#: 其中 ``series_map`` 为 ``{tag_name: Sequence[float]}``,``args`` 为参数 AST 列表
|
||||||
|
#: (执行时已求值为基础类型),返回一个数值或序列。
|
||||||
|
OpFunc = Callable[[Dict[str, Sequence[float]], Tuple[Any, ...]], Any]
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class OperatorDef:
|
||||||
|
"""算子定义:签名 + 执行函数 + 文档。"""
|
||||||
|
|
||||||
|
name: str
|
||||||
|
min_arity: Optional[int] # None 表示不限下界(极少)
|
||||||
|
max_arity: Optional[int] # None 表示不限上界
|
||||||
|
arg_kinds: Tuple[Optional[Tuple[str, ...]], ...] # 每参数允许的 kind
|
||||||
|
func: OpFunc
|
||||||
|
doc: str = ""
|
||||||
|
|
||||||
|
def arity_ok(self, n: int) -> bool:
|
||||||
|
if self.min_arity is not None and n < self.min_arity:
|
||||||
|
return False
|
||||||
|
if self.max_arity is not None and n > self.max_arity:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# 全局算子注册表
|
||||||
|
OPERATORS: Dict[str, OperatorDef] = {}
|
||||||
|
|
||||||
|
|
||||||
|
def register_operator(
|
||||||
|
name: str,
|
||||||
|
*,
|
||||||
|
min_arity: Optional[int],
|
||||||
|
max_arity: Optional[int],
|
||||||
|
arg_kinds: Sequence[Optional[Sequence[str]]],
|
||||||
|
func: OpFunc,
|
||||||
|
doc: str = "",
|
||||||
|
) -> OperatorDef:
|
||||||
|
"""注册一个特征算子。
|
||||||
|
|
||||||
|
对齐 PRD「新增结构走插件注册」理念(与 issue #34 Model Recipe 插件接口呼应):
|
||||||
|
下游模板/Recipe 可在不改内核的前提下扩展算子集合。重复注册同名算子覆盖
|
||||||
|
旧定义(便于测试期间替换实现)。
|
||||||
|
"""
|
||||||
|
kinds = tuple(
|
||||||
|
tuple(k) if k is not None else None for k in arg_kinds
|
||||||
|
)
|
||||||
|
op = OperatorDef(
|
||||||
|
name=name,
|
||||||
|
min_arity=min_arity,
|
||||||
|
max_arity=max_arity,
|
||||||
|
arg_kinds=kinds,
|
||||||
|
func=func,
|
||||||
|
doc=doc,
|
||||||
|
)
|
||||||
|
OPERATORS[name] = op
|
||||||
|
return op
|
||||||
|
|
||||||
|
|
||||||
|
def _as_list(series: Any) -> List[float]:
|
||||||
|
"""把输入序列归一为 list[float](兼容 numpy 数组与原生序列)。"""
|
||||||
|
if _HAS_NUMPY and isinstance(series, _np.ndarray):
|
||||||
|
return [float(x) for x in series.tolist()]
|
||||||
|
return [float(x) for x in series]
|
||||||
|
|
||||||
|
|
||||||
|
def _rolling_apply(values: Sequence[float], window: int, fn: Callable[[Sequence[float]], float]) -> List[float]:
|
||||||
|
"""对序列做滚动窗口计算,前 ``window-1`` 个位置用 NaN 占位以保持长度一致。
|
||||||
|
|
||||||
|
返回长度恒等于输入长度,便于多特征对齐拼接(对齐训练/推理流水线诉求)。
|
||||||
|
"""
|
||||||
|
out: List[float] = []
|
||||||
|
n = len(values)
|
||||||
|
for i in range(n):
|
||||||
|
if i + 1 < window:
|
||||||
|
out.append(float("nan"))
|
||||||
|
else:
|
||||||
|
out.append(fn(values[i + 1 - window : i + 1]))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _window_to_steps(arg: Any, *, default: Optional[int] = None) -> int:
|
||||||
|
"""把窗口/数值参数折算为整数步长(向上去整,至少 1)。"""
|
||||||
|
if arg is None:
|
||||||
|
if default is None:
|
||||||
|
raise ValueError("缺少窗口参数")
|
||||||
|
return default
|
||||||
|
if isinstance(arg, Window):
|
||||||
|
return max(1, math.ceil(arg.steps))
|
||||||
|
if isinstance(arg, Number):
|
||||||
|
v = arg.value
|
||||||
|
if v <= 0:
|
||||||
|
raise ValueError(f"窗口/步长必须为正数,实际为 {v}")
|
||||||
|
return max(1, math.ceil(v))
|
||||||
|
raise ValueError(f"窗口参数类型非法:{type(arg).__name__}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 内置算子实现 ---------------------------------------------------------
|
||||||
|
def _op_ema(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
if not isinstance(tag, TagRef):
|
||||||
|
raise TypeError("EMA 第一个参数必须是点位")
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1]) if len(args) > 1 else None
|
||||||
|
if window is None:
|
||||||
|
raise TypeError("EMA 需要窗口参数")
|
||||||
|
alpha = 2.0 / (window + 1.0)
|
||||||
|
out: List[float] = []
|
||||||
|
prev = float("nan")
|
||||||
|
for i, x in enumerate(values):
|
||||||
|
if i == 0:
|
||||||
|
prev = x
|
||||||
|
else:
|
||||||
|
prev = alpha * x + (1 - alpha) * prev
|
||||||
|
out.append(prev)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _op_sma(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1])
|
||||||
|
return _rolling_apply(values, window, lambda w: sum(w) / len(w))
|
||||||
|
|
||||||
|
|
||||||
|
def _op_rolling_std(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1])
|
||||||
|
def _std(w: Sequence[float]) -> float:
|
||||||
|
m = sum(w) / len(w)
|
||||||
|
var = sum((x - m) ** 2 for x in w) / max(1, len(w) - 1)
|
||||||
|
return math.sqrt(var)
|
||||||
|
return _rolling_apply(values, window, _std)
|
||||||
|
|
||||||
|
|
||||||
|
def _op_rolling_max(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1])
|
||||||
|
return _rolling_apply(values, window, max)
|
||||||
|
|
||||||
|
|
||||||
|
def _op_rolling_min(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1])
|
||||||
|
return _rolling_apply(values, window, min)
|
||||||
|
|
||||||
|
|
||||||
|
def _op_rate_of_change(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1], default=1) if len(args) > 1 else 1
|
||||||
|
out: List[float] = []
|
||||||
|
for i in range(len(values)):
|
||||||
|
if i < window:
|
||||||
|
out.append(float("nan"))
|
||||||
|
else:
|
||||||
|
denom = abs(values[i - window])
|
||||||
|
out.append((values[i] - values[i - window]) / denom if denom else float("nan"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _op_diff(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1], default=1) if len(args) > 1 else 1
|
||||||
|
out: List[float] = []
|
||||||
|
for i in range(len(values)):
|
||||||
|
if i < window:
|
||||||
|
out.append(float("nan"))
|
||||||
|
else:
|
||||||
|
out.append(values[i] - values[i - window])
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _op_lag(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
window = _window_to_steps(args[1], default=1) if len(args) > 1 else 1
|
||||||
|
out: List[float] = []
|
||||||
|
for i in range(len(values)):
|
||||||
|
out.append(values[i - window] if i - window >= 0 else float("nan"))
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _op_log(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
return [math.log(x) if x > 0 else float("nan") for x in values]
|
||||||
|
|
||||||
|
|
||||||
|
def _op_scale(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
if not isinstance(args[1], Number):
|
||||||
|
raise TypeError("Scale 第二个参数必须是数值系数")
|
||||||
|
coef = args[1].value
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
return [x * coef for x in values]
|
||||||
|
|
||||||
|
|
||||||
|
def _op_clip(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
if not isinstance(args[1], Number) or not isinstance(args[2], Number):
|
||||||
|
raise TypeError("Clip 参数 min/max 必须是数值")
|
||||||
|
lo, hi = args[1].value, args[2].value
|
||||||
|
values = _as_list(series_map[tag.name])
|
||||||
|
return [min(max(x, lo), hi) for x in values]
|
||||||
|
|
||||||
|
|
||||||
|
def _op_combine(series_map, args):
|
||||||
|
tags = [a for a in args if isinstance(a, TagRef)]
|
||||||
|
if len(tags) < 2:
|
||||||
|
raise TypeError("Combine 至少需要 2 个点位")
|
||||||
|
cols = [_as_list(series_map[t.name]) for t in tags]
|
||||||
|
length = min(len(c) for c in cols)
|
||||||
|
return [sum(c[i] for c in cols) for i in range(length)]
|
||||||
|
|
||||||
|
|
||||||
|
# ---- 注册内置算子 ---------------------------------------------------------
|
||||||
|
# 参数 kind 枚举:tag / number / window / op
|
||||||
|
_K_TAG = ("tag",)
|
||||||
|
_K_NUM = ("number",)
|
||||||
|
_K_WIN = ("window",)
|
||||||
|
_K_TAG_OR_OP = ("tag", "op")
|
||||||
|
_K_WIN_OR_NUM = ("window", "number")
|
||||||
|
|
||||||
|
register_operator(
|
||||||
|
"EMA", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_ema,
|
||||||
|
doc="指数移动平均,参数:点位、窗口(数值步长或时长窗口)。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"SMA", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_sma,
|
||||||
|
doc="简单移动平均,参数:点位、窗口。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"RollingStd", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_rolling_std,
|
||||||
|
doc="滚动标准差(无偏估计),参数:点位、窗口。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"RollingMax", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_rolling_max,
|
||||||
|
doc="滚动最大值,参数:点位、窗口。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"RollingMin", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_rolling_min,
|
||||||
|
doc="滚动最小值,参数:点位、窗口。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"RateOfChange", min_arity=1, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_rate_of_change,
|
||||||
|
doc="变化率 (x[t]-x[t-w])/|x[t-w]|,参数:点位、可选窗口(缺省 1)。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Diff", min_arity=1, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_diff,
|
||||||
|
doc="一阶差分 x[t]-x[t-w],参数:点位、可选窗口(缺省 1)。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Lag", min_arity=1, max_arity=2, arg_kinds=(_K_TAG, _K_WIN_OR_NUM), func=_op_lag,
|
||||||
|
doc="滞后 x[t-w],参数:点位、可选步长(缺省 1)。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Log", min_arity=1, max_arity=1, arg_kinds=(_K_TAG,), func=_op_log,
|
||||||
|
doc="自然对数,参数:点位(非正值返回 NaN)。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Scale", min_arity=2, max_arity=2, arg_kinds=(_K_TAG, _K_NUM), func=_op_scale,
|
||||||
|
doc="线性缩放 x*coef,参数:点位、系数。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Clip", min_arity=3, max_arity=3, arg_kinds=(_K_TAG, _K_NUM, _K_NUM), func=_op_clip,
|
||||||
|
doc="截断到 [min, max],参数:点位、min、max。",
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Combine", min_arity=2, max_arity=None, arg_kinds=(_K_TAG_OR_OP,), func=_op_combine,
|
||||||
|
doc="多点位组合(逐元素求和),参数:>=2 个点位。",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 语义校验
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def _validate_node(node: FeatureAST, issues: List[SpecIssue]) -> None:
|
||||||
|
"""递归校验 AST:算子存在性、arity、参数 kind。"""
|
||||||
|
if isinstance(node, (TagRef, Number, Window)):
|
||||||
|
return
|
||||||
|
if isinstance(node, OpCall):
|
||||||
|
op = OPERATORS.get(node.name)
|
||||||
|
if op is None:
|
||||||
|
issues.append(
|
||||||
|
SpecIssue(
|
||||||
|
code="unknown_operator",
|
||||||
|
message=f"未知算子 '{node.name}';已知算子:{', '.join(sorted(OPERATORS))}",
|
||||||
|
context=repr(node),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# 仍递归校验子节点(便于一次性暴露全部问题)
|
||||||
|
for a in node.args:
|
||||||
|
_validate_node(a, issues)
|
||||||
|
return
|
||||||
|
if not op.arity_ok(len(node.args)):
|
||||||
|
issues.append(
|
||||||
|
SpecIssue(
|
||||||
|
code="arity",
|
||||||
|
message=(
|
||||||
|
f"算子 '{node.name}' 参数个数 {len(node.args)} 不合法"
|
||||||
|
f"(期望 {_arity_text(op)})"
|
||||||
|
),
|
||||||
|
context=repr(node),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
# 参数 kind 校验。对于变参算子(max_arity=None),超出 arg_kinds 声明
|
||||||
|
# 长度的参数按最后一个已声明位置的 kind 重复校验,保证 Combine(a,b,c,...)
|
||||||
|
# 的每个 tag 都被校验。
|
||||||
|
for idx in range(len(node.args)):
|
||||||
|
if idx < len(op.arg_kinds):
|
||||||
|
kind = op.arg_kinds[idx]
|
||||||
|
elif op.max_arity is None and op.arg_kinds:
|
||||||
|
kind = op.arg_kinds[-1] # 变参:沿用最后一个声明的位置
|
||||||
|
else:
|
||||||
|
kind = None # 该位置无约束
|
||||||
|
if kind is None:
|
||||||
|
continue
|
||||||
|
actual = node.args[idx].to_dict().get("kind")
|
||||||
|
if actual not in kind:
|
||||||
|
allowed = "/".join(kind)
|
||||||
|
issues.append(
|
||||||
|
SpecIssue(
|
||||||
|
code="bad_arg",
|
||||||
|
message=(
|
||||||
|
f"算子 '{node.name}' 第 {idx + 1} 个参数应为 {allowed},"
|
||||||
|
f"实际为 {actual}"
|
||||||
|
),
|
||||||
|
context=repr(node.args[idx]),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
for a in node.args:
|
||||||
|
_validate_node(a, issues)
|
||||||
|
return
|
||||||
|
# 理论不可达
|
||||||
|
issues.append(SpecIssue(code="bad_ast", message=f"未知 AST 节点:{node!r}"))
|
||||||
|
|
||||||
|
|
||||||
|
def _arity_text(op: OperatorDef) -> str:
|
||||||
|
lo = op.min_arity if op.min_arity is not None else 0
|
||||||
|
if op.max_arity is None:
|
||||||
|
return f"≥{lo}"
|
||||||
|
if op.max_arity == lo:
|
||||||
|
return f"{lo}"
|
||||||
|
return f"{lo}~{op.max_arity}"
|
||||||
|
|
||||||
|
|
||||||
|
def validate(ast: FeatureAST) -> List[SpecIssue]:
|
||||||
|
"""校验一棵 AST 的语义,返回问题列表(空列表表示通过)。
|
||||||
|
|
||||||
|
不抛异常:配置台(issue #62~#67)据此一次性聚合展示所有特征的语义错误。
|
||||||
|
"""
|
||||||
|
issues: List[SpecIssue] = []
|
||||||
|
_validate_node(ast, issues)
|
||||||
|
return issues
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 依赖分析
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def resolve_inputs(ast: FeatureAST) -> List[str]:
|
||||||
|
"""递归收集 AST 引用的全部原始点位名(去重、稳定顺序)。
|
||||||
|
|
||||||
|
训练/推理流水线(issue #40)据此决定要拉取哪些 tag 的时序数据。
|
||||||
|
"""
|
||||||
|
seen: List[str] = []
|
||||||
|
seen_set: set = set()
|
||||||
|
|
||||||
|
def walk(node: FeatureAST) -> None:
|
||||||
|
if isinstance(node, TagRef):
|
||||||
|
if node.name not in seen_set:
|
||||||
|
seen_set.add(node.name)
|
||||||
|
seen.append(node.name)
|
||||||
|
elif isinstance(node, OpCall):
|
||||||
|
for a in node.args:
|
||||||
|
walk(a)
|
||||||
|
# Number/Window 无依赖
|
||||||
|
|
||||||
|
walk(ast)
|
||||||
|
return seen
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 执行(materialize)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def materialize(ast: FeatureAST, series_map: Dict[str, Sequence[float]]) -> Any:
|
||||||
|
"""在给定数据上执行 FeatureSpec,返回计算结果(通常为 list[float])。
|
||||||
|
|
||||||
|
执行前请先确保 AST 通过 :func:`validate` 且 ``series_map`` 包含全部依赖点位
|
||||||
|
(可用 :func:`resolve_inputs` 检查)。缺失点位或语义错误会抛 ``ValueError``/
|
||||||
|
``KeyError``/``TypeError``,供流水线 fail-fast。
|
||||||
|
|
||||||
|
纯 tag 节点直接返回其序列;number/window 节点返回其标量。
|
||||||
|
"""
|
||||||
|
if isinstance(ast, TagRef):
|
||||||
|
if ast.name not in series_map:
|
||||||
|
raise KeyError(f"缺少依赖点位数据:{ast.name}")
|
||||||
|
return series_map[ast.name]
|
||||||
|
if isinstance(ast, Number):
|
||||||
|
return ast.value
|
||||||
|
if isinstance(ast, Window):
|
||||||
|
return ast.steps
|
||||||
|
if isinstance(ast, OpCall):
|
||||||
|
op = OPERATORS.get(ast.name)
|
||||||
|
if op is None:
|
||||||
|
raise ValueError(f"未知算子 '{ast.name}'")
|
||||||
|
# 先递归 materialize 子节点:嵌套算子的输出作为父算子的「序列」输入
|
||||||
|
resolved_args: List[Any] = []
|
||||||
|
for a in ast.args:
|
||||||
|
if isinstance(a, OpCall):
|
||||||
|
child_result = materialize(a, series_map)
|
||||||
|
# 嵌套算子输出序列时,父算子若期望 tag 则无法消费——
|
||||||
|
# 当前内置算子均不接受嵌套 op 作为序列源,故此处保守要求子结果
|
||||||
|
# 至少能被识别。保留 resolved_args 原样(OpCall 节点),由算子
|
||||||
|
# 内部按需处理;此处不强制类型。
|
||||||
|
resolved_args.append(a) # 维持 AST 形态,算子按签名判定
|
||||||
|
else:
|
||||||
|
resolved_args.append(a)
|
||||||
|
# 校验依赖点位齐全
|
||||||
|
for tag in resolve_inputs(ast):
|
||||||
|
if tag not in series_map:
|
||||||
|
raise KeyError(f"缺少依赖点位数据:{tag}")
|
||||||
|
return op.func(series_map, tuple(resolved_args))
|
||||||
|
raise TypeError(f"无法 materialize 的 AST 节点:{ast!r}")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 人类可读描述
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
def describe(ast: FeatureAST) -> str:
|
||||||
|
"""返回 FeatureSpec 的结构化文本描述(用于配置台展示与文档)。
|
||||||
|
|
||||||
|
例::
|
||||||
|
|
||||||
|
>>> describe(parse("EMA(CLF-01.TEMP, 5m)"))
|
||||||
|
'EMA(指数移动平均) ← CLF-01.TEMP,窗口 5m(300s);依赖点位: CLF-01.TEMP'
|
||||||
|
"""
|
||||||
|
inputs = resolve_inputs(ast)
|
||||||
|
head = repr(ast)
|
||||||
|
op = OPERATORS.get(ast.name) if isinstance(ast, OpCall) else None
|
||||||
|
if op is not None:
|
||||||
|
parts = [f"{ast.name}({op.doc.split(',')[0] if op.doc else '算子'})"]
|
||||||
|
parts.append("← " + ",".join(repr(a) for a in ast.args))
|
||||||
|
else:
|
||||||
|
parts = [head]
|
||||||
|
if inputs:
|
||||||
|
parts.append("依赖点位: " + ", ".join(inputs))
|
||||||
|
return " | ".join(parts)
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""测试引导:把 `core/model-framework` 以包名 `model_framework` 挂载到 sys.modules。
|
||||||
|
|
||||||
|
目录名 `model-framework` 含连字符,无法直接以包名 import;挂载后模块内相对导入
|
||||||
|
(`from .feature_spec import ...`)在 unittest 发现机制下可正常解析。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
|
||||||
|
MF_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||||
|
sys.path.insert(0, MF_DIR)
|
||||||
|
if "model_framework" not in sys.modules:
|
||||||
|
pkg = types.ModuleType("model_framework")
|
||||||
|
pkg.__path__ = [MF_DIR]
|
||||||
|
sys.modules["model_framework"] = pkg
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""FeatureSpec 声明式特征定义引擎测试(issue #35)。
|
||||||
|
|
||||||
|
覆盖:
|
||||||
|
1. 解析:算子调用、裸点位、数值/窗口字面量、嵌套、中文点位、带符号数值;
|
||||||
|
2. 解析错误:空 spec、非法字符、括号不匹配、多余内容、参数缺失;
|
||||||
|
3. 语义校验:未知算子、arity 不匹配、参数 kind 错误;
|
||||||
|
4. 依赖分析:resolve_inputs 去重与顺序、嵌套算子依赖汇总;
|
||||||
|
5. 执行:EMA/SMA/RollingStd/RateOfChange/Diff/Lag/Log/Scale/Clip/Combine 的
|
||||||
|
数值正确性,缺失点位 fail-fast;
|
||||||
|
6. 插件注册:register_operator 扩展新算子;
|
||||||
|
7. 往返:to_dict/repr 稳定。
|
||||||
|
"""
|
||||||
|
import math
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import _bootstrap # noqa: F401 挂载包名
|
||||||
|
|
||||||
|
from model_framework.feature_spec import (
|
||||||
|
FeatureAST,
|
||||||
|
Number,
|
||||||
|
OpCall,
|
||||||
|
OPERATORS,
|
||||||
|
ParseError,
|
||||||
|
SpecIssue,
|
||||||
|
TagRef,
|
||||||
|
Window,
|
||||||
|
describe,
|
||||||
|
materialize,
|
||||||
|
parse,
|
||||||
|
register_operator,
|
||||||
|
resolve_inputs,
|
||||||
|
validate,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 解析
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class ParseTest(unittest.TestCase):
|
||||||
|
def test_simple_op_with_window(self):
|
||||||
|
ast = parse("EMA(CLF-01.TEMP, 5m)")
|
||||||
|
self.assertEqual(
|
||||||
|
ast, OpCall("EMA", (TagRef("CLF-01.TEMP"), Window(5.0, "m")))
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_simple_op_with_number_window(self):
|
||||||
|
ast = parse("RollingStd(CLF-01.CL2, 10)")
|
||||||
|
self.assertEqual(ast, OpCall("RollingStd", (TagRef("CLF-01.CL2"), Number(10))))
|
||||||
|
|
||||||
|
def test_bare_tag(self):
|
||||||
|
self.assertEqual(parse("炉压"), TagRef("炉压"))
|
||||||
|
|
||||||
|
def test_tag_with_dots_and_dash(self):
|
||||||
|
self.assertEqual(parse("A.B-C_01"), TagRef("A.B-C_01"))
|
||||||
|
|
||||||
|
def test_signed_and_scientific_number(self):
|
||||||
|
ast = parse("Scale(A, -0.5)")
|
||||||
|
self.assertEqual(ast, OpCall("Scale", (TagRef("A"), Number(-0.5))))
|
||||||
|
ast2 = parse("Scale(A, 1e-3)")
|
||||||
|
self.assertAlmostEqual(ast2.args[1].value, 0.001)
|
||||||
|
|
||||||
|
def test_nested_op(self):
|
||||||
|
# 嵌套:外层 Scale,内层 EMA 作为第一个参数点位位置(语法合法,语义由算子判定)
|
||||||
|
ast = parse("Combine(EMA(A, 5m), B)")
|
||||||
|
self.assertEqual(ast.name, "Combine")
|
||||||
|
self.assertEqual(len(ast.args), 2)
|
||||||
|
self.assertEqual(ast.args[0].name, "EMA")
|
||||||
|
|
||||||
|
def test_no_arg_op(self):
|
||||||
|
ast = parse("Diff()")
|
||||||
|
self.assertEqual(ast, OpCall("Diff", ()))
|
||||||
|
|
||||||
|
def test_integer_window_vs_number(self):
|
||||||
|
self.assertEqual(parse("Lag(A, 3)").args[1], Number(3))
|
||||||
|
self.assertEqual(parse("Lag(A, 3m)").args[1], Window(3.0, "m"))
|
||||||
|
|
||||||
|
def test_repr_roundtrip(self):
|
||||||
|
for spec in ["EMA(CLF-01.TEMP, 5m)", "RateOfChange(炉压)", "Clip(P, -1, 1)"]:
|
||||||
|
self.assertEqual(repr(parse(spec)).replace(" ", ""), spec.replace(" ", ""))
|
||||||
|
|
||||||
|
# ---- 解析错误 ----
|
||||||
|
def test_empty_raises(self):
|
||||||
|
with self.assertRaises((ValueError, ParseError)):
|
||||||
|
parse("")
|
||||||
|
with self.assertRaises((ValueError, ParseError)):
|
||||||
|
parse(" ")
|
||||||
|
|
||||||
|
def test_non_string_raises(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
parse(123) # type: ignore[arg-type]
|
||||||
|
|
||||||
|
def test_unrecognized_char(self):
|
||||||
|
with self.assertRaises(ParseError) as cm:
|
||||||
|
parse("EMA(A, 5m) @")
|
||||||
|
self.assertIsNotNone(cm.exception.position)
|
||||||
|
|
||||||
|
def test_missing_rparen(self):
|
||||||
|
with self.assertRaises(ParseError):
|
||||||
|
parse("EMA(A, 5m")
|
||||||
|
|
||||||
|
def test_missing_rparen_inner(self):
|
||||||
|
with self.assertRaises(ParseError):
|
||||||
|
parse("EMA(A, (5m)")
|
||||||
|
|
||||||
|
def test_trailing_garbage(self):
|
||||||
|
with self.assertRaises(ParseError):
|
||||||
|
parse("EMA(A, 5m) B")
|
||||||
|
|
||||||
|
def test_missing_arg_after_comma(self):
|
||||||
|
with self.assertRaises(ParseError):
|
||||||
|
parse("EMA(A, )")
|
||||||
|
|
||||||
|
def test_starts_with_paren(self):
|
||||||
|
with self.assertRaises(ParseError):
|
||||||
|
parse("(A)")
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 语义校验
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class ValidateTest(unittest.TestCase):
|
||||||
|
def test_known_op_valid(self):
|
||||||
|
self.assertEqual(validate(parse("EMA(A, 5m)")), [])
|
||||||
|
|
||||||
|
def test_unknown_operator(self):
|
||||||
|
issues = validate(parse("FooBar(A, 5m)"))
|
||||||
|
self.assertEqual(len(issues), 1)
|
||||||
|
self.assertEqual(issues[0].code, "unknown_operator")
|
||||||
|
|
||||||
|
def test_arity_too_few(self):
|
||||||
|
issues = validate(parse("EMA(A)"))
|
||||||
|
self.assertTrue(any(i.code == "arity" for i in issues))
|
||||||
|
|
||||||
|
def test_arity_too_many(self):
|
||||||
|
issues = validate(parse("EMA(A, 5m, 7)"))
|
||||||
|
self.assertTrue(any(i.code == "arity" for i in issues))
|
||||||
|
|
||||||
|
def test_bad_arg_kind_number_where_window(self):
|
||||||
|
# EMA 第二参数允许 window/number,故合法
|
||||||
|
self.assertEqual(validate(parse("EMA(A, 7)")), [])
|
||||||
|
# 但 tag 位置传 number 非法
|
||||||
|
issues = validate(parse("EMA(5, 7)"))
|
||||||
|
self.assertTrue(any(i.code == "bad_arg" for i in issues))
|
||||||
|
|
||||||
|
def test_combine_varargs(self):
|
||||||
|
self.assertEqual(validate(parse("Combine(A, B, C)")), [])
|
||||||
|
issues = validate(parse("Combine(A)"))
|
||||||
|
self.assertTrue(any(i.code == "arity" for i in issues))
|
||||||
|
|
||||||
|
def test_nested_unknown(self):
|
||||||
|
issues = validate(parse("Combine(Foo(A), B)"))
|
||||||
|
self.assertTrue(any(i.code == "unknown_operator" for i in issues))
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 依赖分析
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class ResolveInputsTest(unittest.TestCase):
|
||||||
|
def test_single_tag(self):
|
||||||
|
self.assertEqual(resolve_inputs(parse("炉压")), ["炉压"])
|
||||||
|
|
||||||
|
def test_dedup_order(self):
|
||||||
|
# 同一点位重复出现,去重且保持首次出现顺序
|
||||||
|
self.assertEqual(resolve_inputs(parse("Combine(A, A)")), ["A"])
|
||||||
|
|
||||||
|
def test_multiple_tags(self):
|
||||||
|
self.assertEqual(resolve_inputs(parse("Combine(A.tank1, A.tank2)")), ["A.tank1", "A.tank2"])
|
||||||
|
|
||||||
|
def test_op_collects_input(self):
|
||||||
|
self.assertEqual(resolve_inputs(parse("EMA(CLF-01.TEMP, 5m)")), ["CLF-01.TEMP"])
|
||||||
|
|
||||||
|
def test_number_window_no_inputs(self):
|
||||||
|
# 裸数值/窗口虽不是合法特征根,但 resolve_inputs 不报错
|
||||||
|
self.assertEqual(resolve_inputs(Number(3)), [])
|
||||||
|
self.assertEqual(resolve_inputs(Window(5.0, "m")), [])
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 执行
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class MaterializeTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
# 一个稳定的伪时序:1..10
|
||||||
|
self.series = {"A": [float(i) for i in range(1, 11)]} # 1..10
|
||||||
|
|
||||||
|
def test_bare_tag(self):
|
||||||
|
self.assertEqual(materialize(parse("A"), self.series), self.series["A"])
|
||||||
|
|
||||||
|
def test_number(self):
|
||||||
|
self.assertEqual(materialize(Number(3), {}), 3)
|
||||||
|
|
||||||
|
def test_sma_window3(self):
|
||||||
|
out = materialize(parse("SMA(A, 3)"), self.series)
|
||||||
|
# 前 2 个 NaN,第 3 个 = (1+2+3)/3 = 2.0
|
||||||
|
self.assertTrue(math.isnan(out[0]) and math.isnan(out[1]))
|
||||||
|
self.assertAlmostEqual(out[2], 2.0)
|
||||||
|
self.assertAlmostEqual(out[9], (8 + 9 + 10) / 3)
|
||||||
|
|
||||||
|
def test_ema_decreasing_weight(self):
|
||||||
|
out = materialize(parse("EMA(A, 5)"), self.series)
|
||||||
|
# EMA 单调(输入单调增),首值 = 首个观测
|
||||||
|
self.assertAlmostEqual(out[0], 1.0)
|
||||||
|
self.assertTrue(all(out[i] <= out[i + 1] for i in range(len(out) - 1)))
|
||||||
|
|
||||||
|
def test_rolling_std(self):
|
||||||
|
out = materialize(parse("RollingStd(A, 2)"), self.series)
|
||||||
|
self.assertTrue(math.isnan(out[0]))
|
||||||
|
# std(1,2) 无偏 = 0.7071...
|
||||||
|
self.assertAlmostEqual(out[1], math.sqrt(0.5))
|
||||||
|
|
||||||
|
def test_rolling_max_min(self):
|
||||||
|
mx = materialize(parse("RollingMax(A, 3)"), self.series)
|
||||||
|
mn = materialize(parse("RollingMin(A, 3)"), self.series)
|
||||||
|
self.assertEqual(mx[2], 3.0)
|
||||||
|
self.assertEqual(mn[2], 1.0)
|
||||||
|
|
||||||
|
def test_diff(self):
|
||||||
|
out = materialize(parse("Diff(A)"), self.series)
|
||||||
|
self.assertTrue(math.isnan(out[0]))
|
||||||
|
self.assertTrue(all(out[i] == 1.0 for i in range(1, len(out))))
|
||||||
|
|
||||||
|
def test_lag(self):
|
||||||
|
out = materialize(parse("Lag(A, 2)"), self.series)
|
||||||
|
self.assertTrue(math.isnan(out[0]) and math.isnan(out[1]))
|
||||||
|
self.assertEqual(out[2], 1.0)
|
||||||
|
|
||||||
|
def test_rate_of_change(self):
|
||||||
|
# 常数序列 → 变化率为 0(非 NaN;NaN 仅出现在前 window 步预热)
|
||||||
|
const = {"C": [5.0] * 6}
|
||||||
|
out = materialize(parse("RateOfChange(C)"), const)
|
||||||
|
self.assertTrue(math.isnan(out[0])) # 预热步 NaN
|
||||||
|
self.assertEqual(out[1], 0.0)
|
||||||
|
# 含 0 的序列 → 分母为 0 → NaN
|
||||||
|
zero_denom = {"Z": [0.0, 1.0, 2.0]}
|
||||||
|
outz = materialize(parse("RateOfChange(Z)"), zero_denom)
|
||||||
|
self.assertTrue(math.isnan(outz[1]))
|
||||||
|
# 线性序列 ROC 步长1 = 1/prev
|
||||||
|
out2 = materialize(parse("RateOfChange(A)"), self.series)
|
||||||
|
self.assertAlmostEqual(out2[1], 1.0 / 1.0)
|
||||||
|
self.assertAlmostEqual(out2[5], 1.0 / 5.0)
|
||||||
|
|
||||||
|
def test_log_negative_nan(self):
|
||||||
|
data = {"P": [1.0, -2.0, math.e]}
|
||||||
|
out = materialize(parse("Log(P)"), data)
|
||||||
|
self.assertAlmostEqual(out[0], 0.0)
|
||||||
|
self.assertTrue(math.isnan(out[1]))
|
||||||
|
self.assertAlmostEqual(out[2], 1.0)
|
||||||
|
|
||||||
|
def test_scale(self):
|
||||||
|
out = materialize(parse("Scale(A, 10)"), self.series)
|
||||||
|
self.assertEqual(out[0], 10.0)
|
||||||
|
self.assertEqual(out[9], 100.0)
|
||||||
|
|
||||||
|
def test_clip(self):
|
||||||
|
out = materialize(parse("Clip(A, 3, 7)"), self.series)
|
||||||
|
self.assertEqual(out, [3.0, 3.0, 3.0, 4.0, 5.0, 6.0, 7.0, 7.0, 7.0, 7.0])
|
||||||
|
|
||||||
|
def test_combine(self):
|
||||||
|
data = {"A": [1.0, 2.0, 3.0], "B": [10.0, 20.0, 30.0]}
|
||||||
|
self.assertEqual(materialize(parse("Combine(A, B)"), data), [11.0, 22.0, 33.0])
|
||||||
|
|
||||||
|
def test_missing_input_fails_fast(self):
|
||||||
|
with self.assertRaises(KeyError):
|
||||||
|
materialize(parse("EMA(Missing, 3)"), {"A": [1.0, 2.0, 3.0]})
|
||||||
|
|
||||||
|
def test_unknown_op_fails_fast(self):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
materialize(OpCall("NoSuchOp", (TagRef("A"),)), self.series)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 插件注册
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class RegisterOperatorTest(unittest.TestCase):
|
||||||
|
def test_register_then_parse_and_run(self):
|
||||||
|
def _double(series_map, args):
|
||||||
|
tag = args[0]
|
||||||
|
return [x * 2 for x in series_map[tag.name]]
|
||||||
|
|
||||||
|
register_operator(
|
||||||
|
"Double",
|
||||||
|
min_arity=1,
|
||||||
|
max_arity=1,
|
||||||
|
arg_kinds=(("tag",),),
|
||||||
|
func=_double,
|
||||||
|
doc="示例自定义算子:翻倍",
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self.assertIn("Double", OPERATORS)
|
||||||
|
self.assertEqual(validate(parse("Double(A)")), [])
|
||||||
|
self.assertEqual(
|
||||||
|
materialize(parse("Double(A)"), {"A": [1.0, 2.0]}), [2.0, 4.0]
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
OPERATORS.pop("Double", None)
|
||||||
|
|
||||||
|
def test_register_overrides(self):
|
||||||
|
register_operator(
|
||||||
|
"Stub", min_arity=0, max_arity=0, arg_kinds=(), func=lambda s, a: 1, doc="v1"
|
||||||
|
)
|
||||||
|
register_operator(
|
||||||
|
"Stub", min_arity=0, max_arity=0, arg_kinds=(), func=lambda s, a: 2, doc="v2"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
self.assertEqual(OPERATORS["Stub"].doc, "v2")
|
||||||
|
finally:
|
||||||
|
OPERATORS.pop("Stub", None)
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# 描述 / 往返
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
class DescribeAndSerializeTest(unittest.TestCase):
|
||||||
|
def test_describe_contains_inputs(self):
|
||||||
|
d = describe(parse("EMA(CLF-01.TEMP, 5m)"))
|
||||||
|
self.assertIn("CLF-01.TEMP", d)
|
||||||
|
self.assertIn("EMA", d)
|
||||||
|
|
||||||
|
def test_to_dict_roundtrip_shape(self):
|
||||||
|
ast = parse("RateOfChange(炉压)")
|
||||||
|
d = ast.to_dict()
|
||||||
|
self.assertEqual(d["kind"], "op")
|
||||||
|
self.assertEqual(d["name"], "RateOfChange")
|
||||||
|
self.assertEqual(d["args"][0], {"kind": "tag", "name": "炉压"})
|
||||||
|
|
||||||
|
def test_window_seconds(self):
|
||||||
|
w = Window(5.0, "m")
|
||||||
|
self.assertEqual(w.seconds, 300)
|
||||||
|
self.assertEqual(Window(2.0, "h").seconds, 7200)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
# DCS 点表需求模板(点位 / 量纲 / 采样率字段规范)
|
|
||||||
|
|
||||||
> 对应 EPIC #2「[M1] 数据准备」子任务 **#16**(0.5d):
|
|
||||||
> 编制向客户 DCS 系统收集点位需求的标准化模板,字段规范对齐
|
|
||||||
> PRD 5.1「① 边缘采集网关」CSV 字段规范与内核点位字典 schema
|
|
||||||
> (`core/edge-gateway/config/point_dict.example.csv`)。
|
|
||||||
>
|
|
||||||
> 交付后由实施工程师按本模板收集客户点表 → 配置台导入校验 →
|
|
||||||
> 推送边缘网关加载只读采集(PRD 5.1 用户操作流程)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 文档目的
|
|
||||||
|
|
||||||
在 M1 数据准备阶段,向客户(车间/仪表/自动化人员)收集 **DCS/PLC 点位需求**,
|
|
||||||
作为点位字典(`point_dict.csv`)的输入来源。本模板统一:
|
|
||||||
|
|
||||||
- **点位**(point):需要采集的工艺测点(温度/压力/流量/液位/状态等);
|
|
||||||
- **量纲**(unit):每个测点的计量单位(℃/kPa/m³/h/%/Hz 等);
|
|
||||||
- **采样率**(sampleRate):每个测点的采集周期(毫秒)。
|
|
||||||
|
|
||||||
字段规范与平台内核**一一对应**,客户按模板填写后可直接导入校验,避免
|
|
||||||
人工翻译造成的字段漂移。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. DCS 系统对接信息(每套系统填写一份)
|
|
||||||
|
|
||||||
| 字段 | 说明 | 示例 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 系统名称 | DCS/PLC 系统名称 | 沸腾氯化车间和利时 DCS |
|
|
||||||
| 厂家/型号 | 设备厂家与系列 | 和利时 DCS / 西门子 S7-1200 |
|
|
||||||
| 软件版本 | 系统软件版本 | HOLLiAS-M 3.2 |
|
|
||||||
| 数据接口 | 支持的数据接口 | OPC UA / OPC DA / S7 协议 |
|
|
||||||
| OPC 服务器 | OPC 服务器地址(如可用) | opc.tcp://10.20.1.10:4840 |
|
|
||||||
| 网络隔离要求 | 采集网与办公网隔离方式 | 单向网闸 / 只读镜像(见 #27) |
|
|
||||||
| 对接负责人 | 客户侧接口人 | 王工(仪表科) |
|
|
||||||
|
|
||||||
> 采集侧**严格只读、不反控**(PRD 5.1 验收:零控制指令下发),
|
|
||||||
> 网络拓扑隔离方案见子任务 #19「现场勘查采集网/工业环网/办公网拓扑与隔离策略」。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 点位需求表字段规范
|
|
||||||
|
|
||||||
客户按下表逐列填写(**表头与内核点位字典 CSV 完全一致**,可整表复制为 CSV):
|
|
||||||
|
|
||||||
| 字段 | 类型 | 约束 | 说明 | 示例 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| device_id | string | 必填,唯一 | 设备编号(车间-设备) | CLF-01 |
|
|
||||||
| point_id | string | 必填,唯一 | 测点编号(设备.测点) | CLF-01.TEMP |
|
|
||||||
| name | string | 必填 | 测点中文名 | 炉温 |
|
|
||||||
| unit | enum | 必填 | 量纲(见 §4 量纲字典) | ℃ |
|
|
||||||
| dataType | enum | 必填 | float / int / bool | float |
|
|
||||||
| sampleRate | int | 必填,>0 | 采集周期(毫秒) | 1000 |
|
|
||||||
| qualityCode | bool | 默认 true | 是否启用质量码 | true |
|
|
||||||
| opcNode | string | 选填 | OPC UA 节点路径 / PLC 地址 | ns=2;s=CLF.Temp |
|
|
||||||
| protocol | enum | 必填 | opcua / s7 / modbus / weighing / energy / manual | opcua |
|
|
||||||
|
|
||||||
**字段说明**
|
|
||||||
|
|
||||||
- `device_id`:建议「车间/系统前缀 + 序号」,如 `CLF-01`(氯化炉 1#)、`S7-01`(PLC 站 1#);
|
|
||||||
- `point_id`:全局唯一,建议「`device_id.测点缩写`」,如 `CLF-01.TEMP`;
|
|
||||||
- `sampleRate`:按测点重要性分级填写(见 §5 采样率分级);
|
|
||||||
- `opcNode`:OPC UA 用节点路径(`ns=2;s=...`);S7 用数据块地址(`DB100.0.0`);
|
|
||||||
称重/能源表用寄存器地址(`holding:40001`);人工录入(manual)可留空;
|
|
||||||
- `qualityCode`:开启质量码后,采集侧附带质量位(坏值/不确定值),平台按质量位过滤。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 量纲字典(unit 枚举)
|
|
||||||
|
|
||||||
| 类别 | 允许值 |
|
|
||||||
| --- | --- |
|
|
||||||
| 温度 | ℃ |
|
|
||||||
| 压力 | kPa、MPa、Pa |
|
|
||||||
| 流量 | m³/h、t/h、L/min、m³/s |
|
|
||||||
| 液位/料位 | %、m、mm |
|
|
||||||
| 转速/频率 | rpm、Hz |
|
|
||||||
| 电气 | kW、kWh、A、V |
|
|
||||||
| 重量 | kg、t、g |
|
|
||||||
| 质量指标 | %、mmol/g(化验人工录入) |
|
|
||||||
| 状态 | bool(0/1、开/关) |
|
|
||||||
|
|
||||||
> 不在上表的单位需在「备注」列说明并请平台配置台确认后再扩展。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 采样率分级建议(sampleRate)
|
|
||||||
|
|
||||||
| 级别 | 周期 | 适用测点 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 高速 | 100 ms | 关键工艺控制点(炉温、炉压) |
|
|
||||||
| 常规 | 1000 ms(1 Hz) | 一般工艺参数(流量、液位、转速)——PRD 5.1 验收基线:600 点位 1Hz |
|
|
||||||
| 低频 | 5000–10000 ms | 缓慢变化量(储罐液位、环境温度) |
|
|
||||||
| 化验/人工 | 60000 ms 或按批次 | 质量指标(交联度、交换容量、钛纯度)等人工录入或 LIMS 对接 |
|
|
||||||
|
|
||||||
> 采样率需综合点位数量与链路容量评估:验收目标为 P99 ≤ 1.8s、丢失率 ≤ 0.02%(PRD 5.1),
|
|
||||||
> 点位过多时可先按「关键点位」子集接入,其余低频轮询。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 填表示例(Template-Ti 一期 · 氯化车间)
|
|
||||||
|
|
||||||
| device_id | point_id | name | unit | dataType | sampleRate | qualityCode | opcNode | protocol |
|
|
||||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
|
||||||
| CLF-01 | CLF-01.TEMP | 炉温 | ℃ | float | 1000 | true | ns=2;s=CLF.Temp | opcua |
|
|
||||||
| CLF-01 | CLF-01.PRES | 炉压 | kPa | float | 1000 | true | ns=2;s=CLF.Pres | opcua |
|
|
||||||
| CLF-01 | CLF-01.FEED | 进料量 | t/h | float | 1000 | true | ns=2;s=CLF.Feed | opcua |
|
|
||||||
| S7-01 | S7-01.PUMP_A | 泵A频率 | Hz | float | 1000 | true | DB100.0.0 | s7 |
|
|
||||||
| W-01 | W-01.WT | 称重值 | kg | float | 1000 | true | holding:40001 | weighing |
|
|
||||||
| E-01 | E-01.PWR | 电表功率 | kW | float | 1000 | true | holding:40010 | energy |
|
|
||||||
| LAB-01 | LAB-01.TI_PURITY | 钛纯度 | % | float | 60000 | true | —(人工录入) | manual |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 填写规范与常见错误
|
|
||||||
|
|
||||||
| 规范 | 常见错误 | 处理 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `point_id` 全局唯一 | 跨设备重复命名 | 配置台导入校验拒绝并提示 |
|
|
||||||
| `unit` 使用量纲字典 | 自定义单位(如 "度") | 归一化为 ℃ 或先申请扩展 |
|
|
||||||
| `sampleRate` 为大于 0 的整数 | 空值/0/小数 | 校验拒绝,按分级建议补填 |
|
|
||||||
| `device_id` 与现场标识一致 | 随意编号 | 与客户确认设备位号后再填 |
|
|
||||||
| 重复/冗余测点 | 同一物理量多张表重复 | 合并,保留唯一 `point_id` |
|
|
||||||
| 高危信号(联锁/停机) | 误标为普通测点 | 平台按「只读采集 + 告警」处理,严禁反控 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 交付与校验
|
|
||||||
|
|
||||||
1. 实施工程师向客户发出本模板(可与《数据准备清单》#18 同步发出);
|
|
||||||
2. 客户按 §2–§6 填写后回传(Excel/CSV 均可);
|
|
||||||
3. 配置台**导入校验**:设备/测点完整性、字段类型、单位枚举、采样率合法性;
|
|
||||||
4. 校验通过 → 生成点位字典 CSV → 推送边缘网关加载 → 启动只读采集;
|
|
||||||
5. 采集健康度(丢失率/P99)实时回传驾驶舱。
|
|
||||||
|
|
||||||
> 若客户点表延迟或字段不完整:先启用**缺省通用点位集**(EPIC #20)演示,
|
|
||||||
> 仅接入已确认点位(PRD 13 章数据依赖风险缓解策略)。
|
|
||||||
@@ -1,127 +0,0 @@
|
|||||||
# LIMS / 质检接口字段与推送频率清单
|
|
||||||
|
|
||||||
> 对应 EPIC #2「[M1] 数据准备」子任务 **#17**(0.5d):
|
|
||||||
> 编制向客户 LIMS/质检系统收集接口字段与推送频率的标准化清单。
|
|
||||||
> 质量标签是监督模型(PRD 5.3 质量预测,目标指标如 `Ti_purity`)的
|
|
||||||
> **训练目标来源**;一期允许人工录入/批量导入过渡(PRD 13 章风险缓解)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 文档目的
|
|
||||||
|
|
||||||
平台质量预测/寻优模型需要「质量标签」作为监督目标(PRD 5.3):
|
|
||||||
`工艺参数(DCS 采集) + 质量指标(LIMS/质检) → 质量预测`。
|
|
||||||
|
|
||||||
本清单用于 M1 阶段向客户收集 **LIMS / 质检系统** 的接口字段与推送频率,
|
|
||||||
统一质量标签的字段规范与对接方式,避免各批次人工录入口径不一致。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. LIMS / 质检系统对接信息(每套系统填写一份)
|
|
||||||
|
|
||||||
| 字段 | 说明 | 示例 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 系统名称 | LIMS / 质检系统名称 | 化验中心 LIMS |
|
|
||||||
| 厂家/版本 | 软件厂家与版本 | 某 LIMS v6.2 |
|
|
||||||
| 数据库 | 底层数据库类型 | Oracle / SQL Server / MySQL |
|
|
||||||
| 接口方式 | 支持的数据接口 | 数据库视图 / REST API / 文件导出(CSV/Excel) |
|
|
||||||
| 接口地址 | 服务地址(如可用) | jdbc:oracle:thin:@10.20.2.15:1521/LIMS |
|
|
||||||
| 质检流程 | 检验-审核-发布流程 | 化验员录入 → 班长审核 → 发布 |
|
|
||||||
| 对接负责人 | 客户侧接口人 | 李工(质检科) |
|
|
||||||
|
|
||||||
> 接口方案未定时:**一期先用人工录入/批量导入质量标签,二期补接口**(PRD 13 章)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 批次与样品主数据字段
|
|
||||||
|
|
||||||
| 字段 | 类型 | 约束 | 说明 | 示例 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| batch_id | string | 必填,唯一 | 生产批次号(对齐工艺模板 batchKey) | B20260901-001 |
|
|
||||||
| sample_id | string | 必填,唯一 | 化验样品编号 | S20260901-015 |
|
|
||||||
| product | string | 必填 | 产品/中间品名称 | 海绵钛 / 四氯化钛 |
|
|
||||||
| stage | string | 选填 | 工序/工段 | 氯化 / 还蒸 |
|
|
||||||
| sample_time | datetime | 必填 | 取样时间 | 2026-09-01 08:00 |
|
|
||||||
| report_time | datetime | 必填 | 检验报告发布时间 | 2026-09-01 14:30 |
|
|
||||||
| operator | string | 选填 | 检验员/审核人 | 李工 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 质量指标字段清单(Ti 场景示例)
|
|
||||||
|
|
||||||
客户按质检项目逐行填写(**字段规范对齐工艺模板 `qualityTag` 命名**):
|
|
||||||
|
|
||||||
| 字段 | 类型 | 约束 | 说明 | 示例 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| tag_id | string | 必填,唯一 | 质量指标标识(qualityTag) | LIMS.Ti_purity |
|
|
||||||
| name | string | 必填 | 指标中文名 | 钛纯度 |
|
|
||||||
| unit | enum | 必填 | 量纲 | % |
|
|
||||||
| dataType | enum | 必填 | float / int | float |
|
|
||||||
| pushFrequency | enum | 必填 | 推送频率(见 §6) | per_batch |
|
|
||||||
| source | enum | 必填 | lims / manual | lims |
|
|
||||||
| description | string | 选填 | 检测方法/标准 | GB/T 4698(海绵钛化学分析方法) |
|
|
||||||
|
|
||||||
**Ti 一期建议指标(示例,按客户实际化验项目调整)**:
|
|
||||||
|
|
||||||
| tag_id | name | unit | dataType | pushFrequency | source |
|
|
||||||
| --- | --- | --- | --- | --- | --- |
|
|
||||||
| LIMS.Ti_purity | 钛纯度 | % | float | per_batch | lims |
|
|
||||||
| LIMS.Fe | 铁含量 | % | float | per_batch | lims |
|
|
||||||
| LIMS.Si | 硅含量 | % | float | per_batch | lims |
|
|
||||||
| LIMS.Mg | 镁含量 | % | float | per_batch | lims |
|
|
||||||
| LIMS.Cl | 氯含量 | % | float | per_batch | lims |
|
|
||||||
| LIMS.Granularity | 粒度 | mm | float | per_batch | manual |
|
|
||||||
|
|
||||||
> `qualityTag` 命名约定:`LIMS.<指标标识>`(对齐 PRD 5.3 工艺模板示例
|
|
||||||
> `qualityTag: "LIMS.Ti_purity"`),模型目标/特征统一引用该标识。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 与工艺侧字段的关联
|
|
||||||
|
|
||||||
质量标签需与工艺侧(DCS 采集)字段按 **batch_id + 时间窗** 对齐:
|
|
||||||
|
|
||||||
- 工艺模板示例:`{processType: "continuous", featureWindow: "shift",
|
|
||||||
qualityTag: "LIMS.Ti_purity", batchKey: "batch_id"}`(PRD 5.3);
|
|
||||||
- 特征窗口:质量指标按 **班/批次** 对齐工艺特征(`featureWindow: shift`);
|
|
||||||
- 对不齐的批次:平台丢弃并告警(防止脏标签污染模型训练)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 推送频率分级(pushFrequency)
|
|
||||||
|
|
||||||
| 级别 | 频率 | 适用场景 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| per_batch | 每批次发布后推送 | 常规质量指标(钛纯度、杂质含量) |
|
|
||||||
| per_shift | 每班汇总推送 | 过程质量快检指标 |
|
|
||||||
| scheduled | 定时(如每日 08:00) | 日报式质量汇总 |
|
|
||||||
| realtime | 化验完成后实时推送 | 关键过程控制指标(如在线粒度) |
|
|
||||||
| manual | 人工录入(60s+ 或按批次) | 一期过渡 / 无接口指标 |
|
|
||||||
|
|
||||||
> 一期未接 LIMS 时:所有指标 `source=manual`,由化验员按批次录入或批量导入
|
|
||||||
> (Excel 模板与 §4 字段一致),平台落库后与工艺数据按 batch_id 对齐。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 填写规范与常见错误
|
|
||||||
|
|
||||||
| 规范 | 常见错误 | 处理 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| `tag_id` 全局唯一 | 不同批次同一指标命名不一致 | 统一为 `LIMS.<指标>`,导入校验拒绝重复 |
|
|
||||||
| `batch_id` 与工艺侧一致 | 批次号加前缀/后缀对不齐 | 与 DCS/生产系统确认同一批次口径 |
|
|
||||||
| `pushFrequency` 用分级枚举 | 自定义频率(如"每两小时") | 归入 scheduled 或新增分级(评审) |
|
|
||||||
| `report_time` 必填 | 空值导致时间窗对不齐 | 校验拒绝,按 sample_time 兜底并告警 |
|
|
||||||
| 指标单位统一 | 百分比/小数混用 | 统一为 %(小数转百分比,配置台归一化) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 收集与校验流程
|
|
||||||
|
|
||||||
1. 实施工程师发出本清单(可与《数据准备清单》#18 同步);
|
|
||||||
2. 客户填写 §2–§4 后回传(含指标清单与推送频率);
|
|
||||||
3. 配置台**导入校验**:tag_id 唯一性、单位枚举、推送频率、batch_id 口径;
|
|
||||||
4. 校验通过 → 建立 LIMS 对接(二期)或人工录入模板(一期过渡);
|
|
||||||
5. 质量标签按 `batch_id + featureWindow` 与工艺特征对齐后进入模型训练。
|
|
||||||
|
|
||||||
> 依赖提示:质量预测需 ≥ 6 个月标注数据(LIMS 对接后补标,PRD 13 章);
|
|
||||||
> 标注不足时监控类模型(异常检测)可先以阈值+无监督上线。
|
|
||||||
@@ -1,60 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""数据准备清单文档(docs/数据准备清单.md)一致性检查。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 必备章节齐全(数据项总览 / 时间表 / 回执单模板 / 回执跟踪机制);
|
|
||||||
2. 引用的数据项模板文件(#16/#17/#19 交付物)真实存在;
|
|
||||||
3. 关键时间表节点(提前 2 周 / 首轮催办 / 二次催办)存在。
|
|
||||||
|
|
||||||
用法:python _check_data_prep_doc.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
DOC_PATH = os.path.join(HERE, "数据准备清单.md")
|
|
||||||
|
|
||||||
REQUIRED_SECTIONS = [
|
|
||||||
"## 2. 数据准备项总览",
|
|
||||||
"## 4. 时间表与里程碑",
|
|
||||||
"## 5. 回执单模板",
|
|
||||||
"## 6. 回执跟踪机制",
|
|
||||||
]
|
|
||||||
|
|
||||||
# 引用的模板文档(#16/#17/#19 交付物)需真实存在
|
|
||||||
REFERENCED_DOCS = [
|
|
||||||
"DCS点表需求模板.md",
|
|
||||||
"LIMS质检接口字段清单.md",
|
|
||||||
"网络拓扑与隔离策略.md",
|
|
||||||
]
|
|
||||||
|
|
||||||
KEY_PHRASES = ["提前 2 周", "首轮催办", "二次催办", "缺省通用点位集"]
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
text = open(DOC_PATH, "r", encoding="utf-8").read()
|
|
||||||
|
|
||||||
for sec in REQUIRED_SECTIONS:
|
|
||||||
if sec not in text:
|
|
||||||
failures.append(f"缺少必备章节:{sec}")
|
|
||||||
|
|
||||||
for ref in REFERENCED_DOCS:
|
|
||||||
if not os.path.isfile(os.path.join(HERE, ref)):
|
|
||||||
failures.append(f"引用模板文档缺失:{ref}")
|
|
||||||
|
|
||||||
for phrase in KEY_PHRASES:
|
|
||||||
if phrase not in text:
|
|
||||||
failures.append(f"缺少关键短语:{phrase}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print("OK: 章节/引用模板/时间表节点校验通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""DCS 点表需求模板(docs/DCS点表需求模板.md)与内核点位字典 schema 一致性检查。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 文档 §3「点位需求表字段规范」表中的字段名(第一列)与内核
|
|
||||||
`core/edge-gateway/config/point_dict.example.csv` 表头**完全一致**;
|
|
||||||
2. 文档中的量纲字典与填表示例单位均在内核示例出现过的类别内(人工抽查,仅告警);
|
|
||||||
3. 文档引用到的内核文件路径存在。
|
|
||||||
|
|
||||||
用法:python _check_dcs_template.py
|
|
||||||
"""
|
|
||||||
import csv
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
REPO_ROOT = os.path.dirname(HERE)
|
|
||||||
|
|
||||||
DOC_PATH = os.path.join(HERE, "DCS点表需求模板.md")
|
|
||||||
CSV_PATH = os.path.join(REPO_ROOT, "core", "edge-gateway", "config",
|
|
||||||
"point_dict.example.csv")
|
|
||||||
|
|
||||||
|
|
||||||
def doc_field_table_columns() -> list:
|
|
||||||
"""抽取文档 §3 字段规范表的字段名(Markdown 表格第一列)。"""
|
|
||||||
lines = [ln.strip() for ln in open(DOC_PATH, "r", encoding="utf-8").readlines()]
|
|
||||||
fields = None
|
|
||||||
i = 0
|
|
||||||
while i < len(lines):
|
|
||||||
line = lines[i]
|
|
||||||
if line.startswith("|") and line.strip("|").split("|")[0].strip() == "字段":
|
|
||||||
header_cells = [c.strip() for c in line.strip("|").split("|")]
|
|
||||||
if "类型" not in header_cells: # §3 特征:字段规范表含"类型"列
|
|
||||||
i += 1
|
|
||||||
continue
|
|
||||||
sep = lines[i + 1] if i + 1 < len(lines) else ""
|
|
||||||
if all(re.fullmatch(r":?-{3,}:?", c.strip())
|
|
||||||
for c in sep.strip("|").split("|")):
|
|
||||||
j = i + 2
|
|
||||||
rows = []
|
|
||||||
while j < len(lines) and lines[j].startswith("|"):
|
|
||||||
cells = [c.strip() for c in lines[j].strip("|").split("|")]
|
|
||||||
if cells and cells[0]:
|
|
||||||
rows.append(cells[0])
|
|
||||||
j += 1
|
|
||||||
fields = rows
|
|
||||||
break
|
|
||||||
i += 1
|
|
||||||
return fields or []
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
|
|
||||||
# 1) 文档字段规范与内核 CSV 表头一致
|
|
||||||
with open(CSV_PATH, "r", encoding="utf-8") as fh:
|
|
||||||
csv_header = [c.strip() for c in next(csv.reader(fh))]
|
|
||||||
doc_fields = doc_field_table_columns()
|
|
||||||
if doc_fields != csv_header:
|
|
||||||
failures.append(
|
|
||||||
f"文档字段 {doc_fields} 与内核 CSV 表头 {csv_header} 不一致")
|
|
||||||
|
|
||||||
# 2) 文档引用文件存在
|
|
||||||
for ref in ("core/edge-gateway/config/point_dict.example.csv",):
|
|
||||||
if not os.path.isfile(os.path.join(REPO_ROOT, ref)):
|
|
||||||
failures.append(f"引用文件缺失:{ref}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print(f"OK: 文档字段规范与内核 schema 一致({len(csv_header)} 列),引用完整")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""采集网只读隔离与网闸配置文档一致性检查 + 代码级只读自检(issue #27)。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 文档必备章节齐全(只读隔离设计 / 单向网闸配置 / 防火墙规则集 / 验证方法);
|
|
||||||
2. 红线关键词存在(只读 / 不反控 / 零控制指令 / 反向 DROP);
|
|
||||||
3. 引用文件(#19 拓扑策略文档 / edge-gateway 目录)存在;
|
|
||||||
4. **代码级只读自检**:扫描 `core/edge-gateway/drivers/*.py`,确认驱动
|
|
||||||
无任何写/控制方法(write / set_value / control 等),对齐 PRD 9 章。
|
|
||||||
|
|
||||||
用法:python _check_isolation_doc.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
REPO_ROOT = os.path.dirname(HERE)
|
|
||||||
DOC_PATH = os.path.join(HERE, "采集网只读隔离与网闸配置.md")
|
|
||||||
DRIVERS_DIR = os.path.join(REPO_ROOT, "core", "edge-gateway", "drivers")
|
|
||||||
|
|
||||||
REQUIRED_SECTIONS = [
|
|
||||||
"## 2. 只读隔离设计",
|
|
||||||
"## 3. 单向网闸配置",
|
|
||||||
"## 4. 防火墙规则集示例",
|
|
||||||
"## 5. 验证方法",
|
|
||||||
]
|
|
||||||
|
|
||||||
REDLINE_KEYWORDS = ["只读", "不反控", "零控制指令", "DROP", "反向"]
|
|
||||||
|
|
||||||
# 写/控制方法名黑名单(驱动只读约束)
|
|
||||||
WRITE_METHOD_PATTERN = re.compile(
|
|
||||||
r"def (write|write_points|set_value|control|set_point|write_register)"
|
|
||||||
r"|class .*Writer\b", re.IGNORECASE)
|
|
||||||
|
|
||||||
|
|
||||||
def scan_drivers_readonly() -> list:
|
|
||||||
"""扫描 drivers/ 源码,返回命中写/控制方法的行描述。"""
|
|
||||||
hits = []
|
|
||||||
if not os.path.isdir(DRIVERS_DIR):
|
|
||||||
return ["drivers 目录不存在"]
|
|
||||||
for name in sorted(os.listdir(DRIVERS_DIR)):
|
|
||||||
if not name.endswith(".py") or name.startswith("_"):
|
|
||||||
continue
|
|
||||||
path = os.path.join(DRIVERS_DIR, name)
|
|
||||||
for no, line in enumerate(
|
|
||||||
open(path, "r", encoding="utf-8").read().splitlines(), 1):
|
|
||||||
if WRITE_METHOD_PATTERN.search(line):
|
|
||||||
hits.append(f"{name}:{no}: {line.strip()}")
|
|
||||||
return hits
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
text = open(DOC_PATH, "r", encoding="utf-8").read()
|
|
||||||
|
|
||||||
for sec in REQUIRED_SECTIONS:
|
|
||||||
if sec not in text:
|
|
||||||
failures.append(f"缺少必备章节:{sec}")
|
|
||||||
|
|
||||||
for kw in REDLINE_KEYWORDS:
|
|
||||||
if kw not in text:
|
|
||||||
failures.append(f"缺少红线关键词:{kw}")
|
|
||||||
|
|
||||||
for ref in ("网络拓扑与隔离策略.md",):
|
|
||||||
if not os.path.isfile(os.path.join(HERE, ref)):
|
|
||||||
failures.append(f"引用文档缺失:{ref}")
|
|
||||||
|
|
||||||
# 代码级只读自检:drivers/ 零写方法
|
|
||||||
hits = scan_drivers_readonly()
|
|
||||||
if hits:
|
|
||||||
failures.append(f"驱动存在写/控制方法:{hits}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print("OK: 章节/红线关键词/引用/驱动只读自检(零写方法)全部通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""LIMS/质检接口字段清单(docs/LIMS质检接口字段清单.md)一致性检查。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 文档必备章节齐全(对接信息 / 批次主数据 / 质量指标字段 / 推送频率分级);
|
|
||||||
2. qualityTag 命名约定与 PRD 5.3 工艺模板示例一致(LIMS.Ti_purity);
|
|
||||||
3. pushFrequency 分级枚举完整(per_batch / per_shift / scheduled / realtime / manual)。
|
|
||||||
|
|
||||||
用法:python _check_lims_doc.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
DOC_PATH = os.path.join(HERE, "LIMS质检接口字段清单.md")
|
|
||||||
|
|
||||||
REQUIRED_SECTIONS = [
|
|
||||||
"## 2. LIMS / 质检系统对接信息",
|
|
||||||
"## 3. 批次与样品主数据字段",
|
|
||||||
"## 4. 质量指标字段清单",
|
|
||||||
"## 6. 推送频率分级",
|
|
||||||
]
|
|
||||||
|
|
||||||
PUSH_FREQ = {"per_batch", "per_shift", "scheduled", "realtime", "manual"}
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
text = open(DOC_PATH, "r", encoding="utf-8").read()
|
|
||||||
|
|
||||||
# 1) 必备章节
|
|
||||||
for sec in REQUIRED_SECTIONS:
|
|
||||||
if sec not in text:
|
|
||||||
failures.append(f"缺少必备章节:{sec}")
|
|
||||||
|
|
||||||
# 2) qualityTag 命名约定与 PRD 5.3 一致
|
|
||||||
if "LIMS.Ti_purity" not in text:
|
|
||||||
failures.append("缺少 qualityTag 示例 LIMS.Ti_purity(PRD 5.3 对齐)")
|
|
||||||
if "`LIMS.<指标标识>`" not in text:
|
|
||||||
failures.append("缺少 qualityTag 命名约定 `LIMS.<指标标识>`")
|
|
||||||
|
|
||||||
# 3) pushFrequency 枚举完整(从文档表格行抽取枚举值)
|
|
||||||
declared = set(re.findall(r"\b(per_batch|per_shift|scheduled|realtime|manual)\b", text))
|
|
||||||
if declared != PUSH_FREQ:
|
|
||||||
failures.append(f"pushFrequency 枚举不完整:{sorted(declared)} != {sorted(PUSH_FREQ)}")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print("OK: 章节/qualityTag 命名/pushFrequency 枚举校验通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""网络拓扑与隔离策略文档(docs/网络拓扑与隔离策略.md)一致性检查。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 必备章节齐全(拓扑模型 / 隔离策略 / 通信矩阵 / 现场勘查清单 / 落地检查表);
|
|
||||||
2. 只读/不反控红线关键词存在(PRD 5.1 / 9 章安全-网络);
|
|
||||||
3. 通信矩阵包含「禁止」反向行(写寄存器拦截);
|
|
||||||
4. 引用文件路径存在。
|
|
||||||
|
|
||||||
用法:python _check_network_doc.py
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
DOC_PATH = os.path.join(HERE, "网络拓扑与隔离策略.md")
|
|
||||||
|
|
||||||
REQUIRED_SECTIONS = [
|
|
||||||
"## 2. 三网拓扑模型",
|
|
||||||
"## 3. 各网段职责与设备",
|
|
||||||
"## 4. 隔离策略",
|
|
||||||
"## 5. 通信矩阵",
|
|
||||||
"## 6. 现场勘查清单",
|
|
||||||
"## 7. 落地检查表",
|
|
||||||
]
|
|
||||||
|
|
||||||
REDLINE_KEYWORDS = ["只读", "不反控", "零控制指令下发", "mTLS", "单向"]
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures = []
|
|
||||||
text = open(DOC_PATH, "r", encoding="utf-8").read()
|
|
||||||
|
|
||||||
for sec in REQUIRED_SECTIONS:
|
|
||||||
if sec not in text:
|
|
||||||
failures.append(f"缺少必备章节:{sec}")
|
|
||||||
|
|
||||||
for kw in REDLINE_KEYWORDS:
|
|
||||||
if kw not in text:
|
|
||||||
failures.append(f"缺少红线关键词:{kw}")
|
|
||||||
|
|
||||||
# 通信矩阵需含「禁止」写寄存器的反向拦截行
|
|
||||||
if "**禁止**" not in text:
|
|
||||||
failures.append("通信矩阵缺少『禁止』写寄存器拦截行")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print("OK: 章节/红线关键词/通信矩阵校验通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
-104
@@ -1,104 +0,0 @@
|
|||||||
# 数据准备清单(客户版)与回执跟踪
|
|
||||||
|
|
||||||
> 对应 EPIC #2「[M1] 数据准备」子任务 **#18**(0.5d):
|
|
||||||
> 向客户发送《数据准备清单》并**跟踪回执**。
|
|
||||||
> M1 里程碑(需求冻结 2026-09)依赖客户数据提前 2 周到位(PRD 13 章),
|
|
||||||
> 本清单为发送给客户的正式文档 + 内部回执跟踪机制。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 发送说明
|
|
||||||
|
|
||||||
| 项 | 内容 |
|
|
||||||
| --- | --- |
|
|
||||||
| 发送对象 | 客户方:生产部(车间主任)、仪表/自动化科、质检科、IT/信息科 |
|
|
||||||
| 发送时机 | **M1 需求冻结前 2 周**(PRD 13 章:提前 2 周发出数据准备清单) |
|
|
||||||
| 发送方式 | 邮件 + 纸质/电子签收(项目群同步) |
|
|
||||||
| 抄送 | 我方:项目经理(bot_pm)、实施工程师、平台产品(bot_po) |
|
|
||||||
| 对应数据项模板 | DCS 点表 → `docs/DCS点表需求模板.md`(#16);LIMS/质检 → `docs/LIMS质检接口字段清单.md`(#17);网络勘查 → `docs/网络拓扑与隔离策略.md`(#19) |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 数据准备项总览
|
|
||||||
|
|
||||||
| # | 数据项 | 用途 | 模板/清单 | 依赖部门 | 优先级 |
|
|
||||||
| --- | --- | --- | --- | --- | --- |
|
|
||||||
| D1 | DCS 点表(点位/量纲/采样率) | 点位字典与采集范围 | DCS点表需求模板.md(#16) | 仪表/自动化科 | P0 |
|
|
||||||
| D2 | LIMS/质检接口字段与推送频率 | 质量标签(模型监督目标) | LIMS质检接口字段清单.md(#17) | 质检科 | P0 |
|
|
||||||
| D3 | 历史数据(≥6 个月标注) | 监督模型训练 | 批量导出要求(见 §4) | 生产部/质检科 | P1 |
|
|
||||||
| D4 | 采集网/工业环网/办公网拓扑 | 网络隔离与部署方案 | 网络拓扑与隔离策略.md(#19) | IT/信息科 | P1 |
|
|
||||||
| D5 | 机房条件(机柜/供电/散热) | 边缘网关与服务器部署 | 网络拓扑与隔离策略.md §6 | IT/信息科 | P1 |
|
|
||||||
| D6 | 系统账号与权限(OPC/只读连接) | 只读采集接入 | DCS点表需求模板.md §2 | 仪表/自动化科 | P1 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 各数据项详细要求
|
|
||||||
|
|
||||||
**D1 · DCS 点表**(P0)
|
|
||||||
- 按 `docs/DCS点表需求模板.md` 字段规范填写(9 列,可整表复制为 CSV);
|
|
||||||
- 覆盖:氯化车间全部工艺测点 + 能源/公用点位;采样率分级填写;
|
|
||||||
- 交付物:点表 Excel/CSV + 系统对接信息表。
|
|
||||||
|
|
||||||
**D2 · LIMS/质检接口**(P0)
|
|
||||||
- 按 `docs/LIMS质检接口字段清单.md` 填写系统信息 + 指标清单(tag_id/单位/推送频率);
|
|
||||||
- 一期无接口时:提供人工录入/批量导入模板(化验员按批次录入);
|
|
||||||
- 交付物:接口字段清单 + 指标清单 Excel。
|
|
||||||
|
|
||||||
**D3 · 历史数据**(P1)
|
|
||||||
- 质量预测训练需 **≥ 6 个月**历史标注(PRD 13 章);
|
|
||||||
- 字段:batch_id / 工艺参数快照 / 质量指标 / 时间戳;
|
|
||||||
- 交付物:历史批次表(CSV/数据库导出)。
|
|
||||||
|
|
||||||
**D4–D6 · 网络与机房**(P1)
|
|
||||||
- 按 `docs/网络拓扑与隔离策略.md` §6 现场勘查清单回填;
|
|
||||||
- 提供:三网拓扑图、IP 段规划、网闸/防火墙型号、OPC 服务器信息、机房条件。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 时间表与里程碑
|
|
||||||
|
|
||||||
| 时间点 | 事项 | 责任方 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| T-2 周 | 发送本清单 + 各数据项模板 | 我方项目经理/实施 |
|
|
||||||
| T-1 周 | 首轮催办(未回执项逐项确认) | 我方项目经理 |
|
|
||||||
| T-3 天 | 二次催办 + 风险项升级上报 | 我方项目经理/产品 |
|
|
||||||
| T(M1 冻结) | 数据回执截止;未到位项启用备选方案(缺省点位集 #20 等) | 双方 |
|
|
||||||
| T+1 周 | 数据接收校验与登记;缺口补采计划 | 实施工程师 |
|
|
||||||
|
|
||||||
> 缺省数据策略(PRD 13 章):D1 点表延迟 → 启用缺省通用点位集(#20)先行演示;
|
|
||||||
> D2 接口未定 → 人工录入过渡;D3 标注不足 → 无监督/阈值模型先行。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 回执单模板(客户填写)
|
|
||||||
|
|
||||||
| 数据项 | 是否可提供 | 预计提供时间 | 对接负责人 | 风险/备注 |
|
|
||||||
| --- | --- | --- | --- | --- |
|
|
||||||
| D1 DCS 点表 | ☐ 是 ☐ 否 | | | |
|
|
||||||
| D2 LIMS/质检接口 | ☐ 是 ☐ 否(转人工) | | | |
|
|
||||||
| D3 历史数据 | ☐ 是 ☐ 否 | | | |
|
|
||||||
| D4 网络拓扑 | ☐ 是 ☐ 否 | | | |
|
|
||||||
| D5 机房条件 | ☐ 是 ☐ 否 | | | |
|
|
||||||
| D6 系统账号权限 | ☐ 是 ☐ 否 | | | |
|
|
||||||
|
|
||||||
客户方确认人:____________ 日期:____________
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 回执跟踪机制(内部)
|
|
||||||
|
|
||||||
1. **登记**:发送后 1 个工作日内登记回执状态(`docs/_data_prep_tracker.md` 或跟踪表);
|
|
||||||
2. **跟踪**:每周例会核对;T-1 周首轮催办、T-3 天二次催办(§4 时间表);
|
|
||||||
3. **接收校验**:收到回执后由实施工程师按对应模板校验(字段完整性/格式);
|
|
||||||
4. **风险升级**:P0 项(D1/D2)回执缺失或明显无法按期 → 立即上报 bot_pm/bot_po,
|
|
||||||
触发 PRD 13 章备选方案(缺省点位集/人工录入过渡);
|
|
||||||
5. **归档**:回执与校验结果归档至项目文档库,作为 M1 需求冻结评审输入。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 关联任务
|
|
||||||
|
|
||||||
- #16 DCS 点表需求模板、#17 LIMS 质检接口字段清单、#19 网络拓扑与隔离策略:
|
|
||||||
本清单的数据项模板来源;
|
|
||||||
- #20 缺省通用点位集:D1 延迟时的演示备选;
|
|
||||||
- PRD 13 章依赖矩阵:本清单触发条件与备选方案的依据。
|
|
||||||
@@ -1,124 +0,0 @@
|
|||||||
# 现场勘查:采集网 / 工业环网 / 办公网拓扑与隔离策略
|
|
||||||
|
|
||||||
> 对应 EPIC #2「[M1] 数据准备」子任务 **#19**(0.5d):
|
|
||||||
> 现场勘查采集网 / 工业环网 / 办公网三层网络拓扑,编制**隔离策略**。
|
|
||||||
> 目标:边缘网关**严格只读、不反控**(PRD 5.1 / 9 章安全-网络),
|
|
||||||
> 满足等保 2.0 三级路线(PRD 12 章),不因网络问题阻塞上线
|
|
||||||
> (PRD 13 章:网络与机房环境 → 现场勘测前置)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 目的与范围
|
|
||||||
|
|
||||||
- **目的**:明确三网拓扑与隔离边界,保证数据「采得进、传得出、控不住」——
|
|
||||||
平台只读采集现场数据,**任何场景下不得向生产控制系统下发控制指令**;
|
|
||||||
- **范围**:边缘网关、DCS/PLC(OPC UA / S7)、数据总线(Kafka)、
|
|
||||||
平台服务(应用/配置台/驾驶舱)的网络位置与互通规则;
|
|
||||||
- **交付物**:本拓扑与隔离策略文档 + 现场勘查清单(§6),
|
|
||||||
供实施工程师现场执行并回填实测数据。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 三网拓扑模型
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────── 采集网(OT · 现场层) ───────────────┐
|
|
||||||
│ DCS 系统 PLC(S7) 称重/能源表 │
|
|
||||||
│ (和利时 DCS) (西门子 S7-1200) (Modbus/称重/能源) │
|
|
||||||
│ │ │ │ │
|
|
||||||
│ └──────┬──────┴───────┬───────┘ │
|
|
||||||
│ 只读镜像点/OPC UA 只读会话 │
|
|
||||||
│ │ │
|
|
||||||
│ ┌─────▼─────┐ │
|
|
||||||
│ │ 边缘网关 │ ← 部署于采集网,严格只读 │
|
|
||||||
│ │(Edge GW) │ 断点续传、本地缓存 │
|
|
||||||
│ └─────┬─────┘ │
|
|
||||||
└────────────────┼────────────────────────────────────┘
|
|
||||||
│ 单向网闸 / 工业防火墙(仅数据外发)
|
|
||||||
┌───────────────▼────────────── 工业环网(服务层) ────┐
|
|
||||||
│ Kafka 数据总线 TDengine PostgreSQL MinIO │
|
|
||||||
│ │ AI 模型服务 / LLM 网关 / RAG │
|
|
||||||
│ (内部通信 mTLS;与办公网经应用防火墙隔离) │
|
|
||||||
└────────────────────────┬─────────────────────────────┘
|
|
||||||
│ 应用防火墙(仅 Web 端口)
|
|
||||||
┌────────────────────────▼──────── 办公网(IT) ───────┐
|
|
||||||
│ 驾驶舱(Web/移动) 配置台(OAuth2 + RBAC) │
|
|
||||||
│ 运维监控(Prometheus/Grafana) │
|
|
||||||
└──────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 各网段职责与设备
|
|
||||||
|
|
||||||
| 网段 | 定位 | 主要设备 | 关键约束 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| 采集网(OT) | 现场生产层 | DCS、PLC、称重/能源表、边缘网关 | 网关**只读**采集;严禁反控;与办公网物理/逻辑隔离 |
|
|
||||||
| 工业环网 | 平台服务层 | Kafka、TDengine、PostgreSQL、MinIO、AI/LLM 服务 | 内部通信 mTLS;承载核心数据,最小暴露面 |
|
|
||||||
| 办公网(IT) | 使用与运维层 | 驾驶舱、配置台、监控 | 仅开放必要 Web 端口;RBAC + OAuth2 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 隔离策略
|
|
||||||
|
|
||||||
1. **只读采集(最高优先级)**:边缘网关仅建立 OPC UA 只读会话 / S7 只读连接
|
|
||||||
(`read-only`),驱动层不实现任何写寄存器动作;验收含「零控制指令下发」。
|
|
||||||
2. **单向网闸/工业防火墙**:采集网 → 工业环网**仅数据外发**单向放行;
|
|
||||||
反向(工业环网 → 采集网)默认拒绝,杜绝远程控制通道。
|
|
||||||
3. **服务间 mTLS**:边缘网关 ↔ 数据总线(Kafka)双向证书认证
|
|
||||||
(PRD 8.2 认证鉴权①),传输加密、防伪造。
|
|
||||||
4. **应用防火墙**:工业环网 → 办公网仅放行 Web(HTTPS 443)与
|
|
||||||
驾驶舱/配置台必需端口;其余全拒绝。
|
|
||||||
5. **等保 2.0 三级路线**:按等保三级要求部署安全审计、边界防护、
|
|
||||||
恶意代码防范(网闸/防火墙规则纳入基线管理,见 PRD 12 章)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 通信矩阵(源 → 目的)
|
|
||||||
|
|
||||||
| # | 源 | 目的 | 协议/端口 | 方向 | 措施 |
|
|
||||||
| --- | --- | --- | --- | --- | --- |
|
|
||||||
| 1 | DCS/PLC | 边缘网关 | OPC UA 4840 / S7 102 | 单向(读) | 只读会话;白名单测点 |
|
|
||||||
| 2 | 边缘网关 | 数据总线(Kafka) | mTLS 9093 | 单向(发) | 双向证书;断点续传 |
|
|
||||||
| 3 | 边缘网关 | 配置台(心跳/健康) | HTTPS 443 | 单向(发) | 健康度上报(丢失率/P99) |
|
|
||||||
| 4 | 驾驶舱 | 平台 API | HTTPS 443 | 双向 | OAuth2 + RBAC;只读 API |
|
|
||||||
| 5 | 配置台 | 平台 API | HTTPS 443 | 双向 | OAuth2 + API Key 双因子 |
|
|
||||||
| 6 | 运维监控 | 平台指标 | HTTPS 443(Prometheus) | 单向(拉) | 白名单网段 |
|
|
||||||
| 7 | 任何 | DCS/PLC 写寄存器 | — | **禁止** | 防火墙/网闸双向拦截 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 现场勘查清单(实施现场回填)
|
|
||||||
|
|
||||||
| 勘查项 | 说明 | 回填内容 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 网络拓扑图 | 客户提供或现场测绘 | 三网拓扑图文件(含设备/交换机/防火墙) |
|
|
||||||
| 采集网 IP 段 | DCS/PLC/网关网段 | 网段与子网掩码 |
|
|
||||||
| 工业环网 IP 段 | 服务层网段 | 网段与子网掩码 |
|
|
||||||
| 办公网 IP 段 | 使用层网段 | 网段与子网掩码 |
|
|
||||||
| 隔离设备 | 网闸/防火墙品牌型号 | 型号、版本、当前规则集 |
|
|
||||||
| OPC 服务器 | 各 DCS 的 OPC 服务器信息 | 地址、是否支持只读会话、认证方式 |
|
|
||||||
| PLC 访问权限 | S7 连接授权 | 只读连接是否可开通、证书要求 |
|
|
||||||
| 机房条件 | 网关/服务器部署位置 | 机柜、供电、散热、动环监控 |
|
|
||||||
| 安全合规要求 | 客户等保/内网管理要求 | 等保级别、VPN/堡垒机要求、审批流程 |
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 落地检查表(验收)
|
|
||||||
|
|
||||||
- [ ] 边缘网关部署于采集网,DCS/PLC 仅开放只读会话;
|
|
||||||
- [ ] 网闸/工业防火墙配置完成:采集网 → 工业环网单向放行,反向拒绝;
|
|
||||||
- [ ] 边缘网关 ↔ Kafka 启用 mTLS(双向证书);
|
|
||||||
- [ ] 办公网访问仅经应用防火墙开放 HTTPS 443 等必要端口;
|
|
||||||
- [ ] 写寄存器/控制指令连通性测试为**零通过**(负向用例);
|
|
||||||
- [ ] 勘查清单回填完整,拓扑图归档至项目文档库;
|
|
||||||
- [ ] 等保三级边界防护要求映射完成(见 PRD 12 章路线图)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 关联任务
|
|
||||||
|
|
||||||
- **#27「① 采集网只读隔离 + 网闸配置文档」**:本策略的网关侧落地
|
|
||||||
(网闸具体配置、规则集、验证脚本);
|
|
||||||
- **#16「DCS 点表需求模板」**:§2 网络隔离要求字段与本策略一致;
|
|
||||||
- **PRD 13 章**:网络/机房环境不符时启用云端 SaaS 演示环境或租赁方案。
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
# 采集网只读隔离与网闸配置
|
|
||||||
|
|
||||||
> 对应 EPIC #3「① 边缘采集网关」子任务 **#27**(0.5d,docs):
|
|
||||||
> 现场勘查拓扑与隔离策略(`docs/网络拓扑与隔离策略.md`,#19)的**网关侧落地**——
|
|
||||||
> 网闸/防火墙**具体配置**、**规则集**、**验证脚本**。
|
|
||||||
> 安全红线(PRD 5.1 / 9 章):边缘网关**严格只读、不反控、零控制指令下发**。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 1. 目的与范围
|
|
||||||
|
|
||||||
- **目的**:把 #19 的三网隔离策略落为可执行配置(网闸规则 + 驱动只读约束 + 验证方法);
|
|
||||||
- **范围**:边缘网关(采集侧)与网闸/工业防火墙(边界)的配置;
|
|
||||||
- **配套**:拓扑与隔离策略总览见 `docs/网络拓扑与隔离策略.md`;
|
|
||||||
点位/采样率/协议规范见 `docs/DCS点表需求模板.md`(#16)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2. 只读隔离设计(网关侧)
|
|
||||||
|
|
||||||
1. **驱动层只读**:所有采集驱动(`core/edge-gateway/drivers/`)仅暴露
|
|
||||||
`connect() / read_points() / close()`,**无任何写/控制方法**
|
|
||||||
(`base.py` 安全约束;新增驱动必须遵守,测试含「只读约束」用例)。
|
|
||||||
2. **协议只读会话**:
|
|
||||||
- OPC UA:只读会话 + 只读账号(如 `iaop_read`,仅授予 Read/Subscribe 权限);
|
|
||||||
- S7:仅建立只读连接(不绑定写数据块);
|
|
||||||
- Modbus:仅功能码 01/02/03/04(读),**禁止** 05/06/0F/10(写)。
|
|
||||||
3. **零反控通道**:网关进程不配置任何到 DCS/PLC 的写寄存器映射,
|
|
||||||
点位字典 `protocol` 维度不含写指令(`point_dict/validator.py` 校验)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 3. 单向网闸配置
|
|
||||||
|
|
||||||
**拓扑**(详见 #19 §2):`采集网 → 单向网闸 → 工业环网`,仅数据外发。
|
|
||||||
|
|
||||||
| 配置项 | 值 | 说明 |
|
|
||||||
| --- | --- | --- |
|
|
||||||
| 部署位置 | 采集网出口 / 工业环网入口 | 单向模块(发送) |
|
|
||||||
| 数据方向 | 采集网 → 工业环网(单向) | 反向物理阻断或规则拒绝 |
|
|
||||||
| 白名单源 | 边缘网关 IP(如 `10.20.1.100`) | 仅网关可出 |
|
|
||||||
| 白名单目的 | 数据总线(Kafka)IP/端口 | `10.20.0.10:9093`(mTLS) |
|
|
||||||
| 允许协议 | TCP(Kafka 9093 / 健康上报 443) | 白名单外全拒绝 |
|
|
||||||
| 反向规则 | 工业环网 → 采集网:**DROP** | 杜绝远程控制通道 |
|
|
||||||
|
|
||||||
> 网闸具体型号规则录入厂商控制台(天融信/网御星云/奇安信等按型号提供 CLI 模板);
|
|
||||||
> 本表为通用配置语义,实施时按现场设备映射。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 4. 防火墙规则集示例(iptables 风格)
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# ---- 采集网侧(边缘网关主机)----
|
|
||||||
# 默认拒绝
|
|
||||||
iptables -P INPUT DROP; iptables -P FORWARD DROP; iptables -P OUTPUT DROP
|
|
||||||
|
|
||||||
# 回环与本机管理
|
|
||||||
iptables -A INPUT -i lo -j ACCEPT
|
|
||||||
iptables -A OUTPUT -o lo -j ACCEPT
|
|
||||||
iptables -A INPUT -s 10.20.1.0/24 -p tcp --dport 22 -j ACCEPT # 运维 SSH(堡垒机)
|
|
||||||
|
|
||||||
# 只读采集出站:DCS OPC UA(4840)与 S7(102)
|
|
||||||
iptables -A OUTPUT -d 10.20.1.10 -p tcp --dport 4840 -j ACCEPT # 和利时 OPC UA
|
|
||||||
iptables -A OUTPUT -d 10.20.1.20 -p tcp --dport 102 -j ACCEPT # S7-1200 只读
|
|
||||||
|
|
||||||
# 数据上行:Kafka(mTLS 9093)与健康上报
|
|
||||||
iptables -A OUTPUT -d 10.20.0.10 -p tcp --dport 9093 -j ACCEPT
|
|
||||||
iptables -A OUTPUT -d 10.20.0.20 -p tcp --dport 443 -j ACCEPT
|
|
||||||
|
|
||||||
# 入站写控制:全部拒绝(无任何入站控制通道)
|
|
||||||
# (INPUT 默认 DROP 已覆盖;如需例外必须评审并记录)
|
|
||||||
```
|
|
||||||
|
|
||||||
> 关键点:**出站只放行读采集与数据上行;入站除运维外全拒绝**,
|
|
||||||
> 从网络层再次封死"反控"路径。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 5. 验证方法
|
|
||||||
|
|
||||||
**负向用例(必须零通过)——验证"写不进去"**:
|
|
||||||
|
|
||||||
| # | 验证项 | 方法 | 期望 |
|
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| V1 | Modbus 写寄存器 | 尝试功能码 05/06/0F/10 写保持寄存器 | 连接被拒/超时/无响应(**零通过**) |
|
|
||||||
| V2 | OPC UA 写节点 | 尝试 `write_value()` 写测点节点 | 权限拒绝(只读账号) |
|
|
||||||
| V3 | S7 写数据块 | 尝试写 DB | 连接不支持/异常 |
|
|
||||||
| V4 | 反向连通性 | 工业环网 → 采集网扫描网关端口 | 全部拒绝 |
|
|
||||||
| V5 | 控制指令下发 | 全链路模拟下发指令 | 网关无对应实现,零指令出站 |
|
|
||||||
|
|
||||||
**正向用例**:
|
|
||||||
- 采集链路健康:600 点位 1Hz,丢失率 ≤ 0.02%、P99 ≤ 1.8s(`collector/metrics.py`);
|
|
||||||
- mTLS 双向证书验证通过(Kafka 9093,`upstream/kafka_sink.py`)。
|
|
||||||
|
|
||||||
**自检命令**(网关侧):
|
|
||||||
```bash
|
|
||||||
python -m unittest discover -s tests -p "test_*.py" # 驱动只读约束用例
|
|
||||||
python scripts/check_readonly.py --points point_dict.csv # 点位字典写指令扫描(见 §6)
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 6. 只读自检脚本(check_readonly)
|
|
||||||
|
|
||||||
随本任务提供轻量自检:扫描点位字典与驱动实现,确认**零写指令**:
|
|
||||||
|
|
||||||
| 检查项 | 实现 |
|
|
||||||
| --- | --- |
|
|
||||||
| 点位字典 | 校验 `protocol`/`opcNode` 不含写指令语义(无 `write`/`set`/`control` 关键字) |
|
|
||||||
| 驱动代码 | 扫描 `drivers/` 源码不含写方法名(`write`/`set_value`/`control`) |
|
|
||||||
| 配置 | `gateway.yaml` 不含反向/控制通道配置 |
|
|
||||||
|
|
||||||
> 落地形式:`docs/_check_isolation_doc.py` 附带代码级自检函数
|
|
||||||
> (也可作为 CI 检查脚本复用)。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 7. 部署检查清单
|
|
||||||
|
|
||||||
- [ ] 网闸规则已录入:单向数据外发、白名单 IP/端口、反向 DROP;
|
|
||||||
- [ ] 边缘网关 iptables 规则集生效(§4 示例);
|
|
||||||
- [ ] 驱动只读:无写方法;OPC UA 只读账号、S7 只读连接、Modbus 仅读功能码;
|
|
||||||
- [ ] 负向用例 V1–V5 全部**零通过**(写不进、连不通);
|
|
||||||
- [ ] 正向用例:丢失率 ≤ 0.02%、P99 ≤ 1.8s、mTLS 验证通过;
|
|
||||||
- [ ] 自检脚本(§6)零告警;审计日志记录规则变更。
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 8. 关联
|
|
||||||
|
|
||||||
- `docs/网络拓扑与隔离策略.md`(#19):本配置的上层策略;
|
|
||||||
- `core/edge-gateway/`:驱动只读实现(base.py / drivers / validator);
|
|
||||||
- `docs/DCS点表需求模板.md`(#16):点位/协议字段规范;
|
|
||||||
- PRD 5.1(只读采集)、9 章安全-网络(零控制指令)、12 章等保三级。
|
|
||||||
@@ -1,46 +0,0 @@
|
|||||||
# iAOP-Template-Ti 一期 · 缺省通用点位集(Demo 点位字典)
|
|
||||||
|
|
||||||
对应 EPIC #2「[M1] 数据接入准备」子任务 **#20**(0.5d):
|
|
||||||
搭建**缺省通用点位集**(演示用,不依赖客户数据),供 PRD 13 章
|
|
||||||
「缺省数据策略」使用——客户 DCS 点表延迟/字段不完整时,
|
|
||||||
启用本点位集完成**演示与框架验证**,点表到位后无缝切换真实点位字典。
|
|
||||||
|
|
||||||
## 用途(PRD 13 章)
|
|
||||||
|
|
||||||
| 场景 | 处理 |
|
|
||||||
| --- | --- |
|
|
||||||
| 客户 DCS 点表延迟 | 启用 `point_dict.default.csv` 先行演示(M1 截止日仍未收到完整点表时触发) |
|
|
||||||
| 点表字段不完整 | 仅接入已确认点位;未确认部分保持缺省点位占位 |
|
|
||||||
| 点表到位后 | 由配置台导入真实点位字典,**无缝切换**,网关零改动 |
|
|
||||||
|
|
||||||
点位范围对齐 PRD 7.2「点位字典范围(一期)」:
|
|
||||||
|
|
||||||
- **沸腾氯化炉**(`CLF-01`):炉温、炉压、氯气流量、CO/CO₂、炉层状态、进料量;
|
|
||||||
- **精制/还原工序**(`RF-01`):还原温度、真空度、TiCl₄ 纯度、杂质含量;
|
|
||||||
- **能源/公用工程**(`E-01` / `ST-01` / `CW-01`):电、蒸汽、循环水。
|
|
||||||
|
|
||||||
## 资产说明
|
|
||||||
|
|
||||||
| 资产 | 说明 |
|
|
||||||
| --- | --- |
|
|
||||||
| `point_dict.default.csv` | 缺省通用点位字典(对齐内核 CSV schema:9 列,与 `core/edge-gateway/config/point_dict.example.csv` 一致) |
|
|
||||||
|
|
||||||
## 设计说明
|
|
||||||
|
|
||||||
- **不依赖客户数据**:所有点位 `protocol = simulator`,由内核模拟采集驱动
|
|
||||||
(`core/edge-gateway/drivers/simulator_driver.py`)按点位生成确定性伪随机值,
|
|
||||||
本地即可端到端联调(采集→spool→Kafka),无需任何现场设备/点表;
|
|
||||||
- **schema 对齐**:表头、量纲、数据类型、采样率、协议与内核点位字典
|
|
||||||
schema(`core/edge-gateway/point_dict/schema.py`)完全一致,
|
|
||||||
`python core/edge-gateway/point_dict/validator.py` 可直接校验通过;
|
|
||||||
- **opcNode 占位**:`opcNode` 列保留典型 OPC UA 节点路径(如 `ns=2;s=CLF.Temp`),
|
|
||||||
模拟现场点表结构;真实点表导入时按配置台校验后替换;
|
|
||||||
- **采样率**:工艺快变量 1000ms(1Hz),质量类慢变量(纯度/杂质)60000ms(1min)。
|
|
||||||
|
|
||||||
## 校验
|
|
||||||
|
|
||||||
```bash
|
|
||||||
python templates/ti-cl4/point-dict/_sanity_check.py
|
|
||||||
```
|
|
||||||
校验:CSV 表头与内核 schema 对齐(9 列)、非空、无空行、行内列数一致、
|
|
||||||
protocol 全部为合法协议(simulator 等)、sampleRate 为正整数。
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""iAOP-Template-Ti 一期 · 缺省通用点位集 sanity 检查(离线基本验证)。
|
|
||||||
|
|
||||||
检查项:
|
|
||||||
1. 点位字典 CSV:表头与内核 `core/edge-gateway/config/point_dict.example.csv`
|
|
||||||
对齐(9 列),且非空、无空行、每行列数一致;
|
|
||||||
2. protocol 列为合法采集协议(对齐内核 schema.VALID_PROTOCOLS);
|
|
||||||
3. sampleRate 为正整数。
|
|
||||||
|
|
||||||
用法:python _sanity_check.py
|
|
||||||
"""
|
|
||||||
import csv
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
|
|
||||||
# 对齐 core/edge-gateway/config/point_dict.example.csv 表头
|
|
||||||
EXPECTED_COLUMNS = [
|
|
||||||
"device_id", "point_id", "name", "unit", "dataType",
|
|
||||||
"sampleRate", "qualityCode", "opcNode", "protocol",
|
|
||||||
]
|
|
||||||
|
|
||||||
# 对齐内核 schema.VALID_PROTOCOLS(缺省点位集全部使用 simulator 演示驱动)
|
|
||||||
VALID_PROTOCOLS = {
|
|
||||||
"opcua", "s7", "modbus", "weighing", "energy", "simulator",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def main() -> int:
|
|
||||||
failures: list[str] = []
|
|
||||||
|
|
||||||
# 1) 点位字典 CSV
|
|
||||||
csv_path = os.path.join(HERE, "point_dict.default.csv")
|
|
||||||
with open(csv_path, "r", encoding="utf-8") as fh:
|
|
||||||
rows = list(csv.reader(fh))
|
|
||||||
if not rows:
|
|
||||||
failures.append("point_dict.default.csv 为空")
|
|
||||||
else:
|
|
||||||
header = [c.strip() for c in rows[0]]
|
|
||||||
if header != EXPECTED_COLUMNS:
|
|
||||||
failures.append(
|
|
||||||
f"CSV 表头与内核 schema 不一致:{header} != {EXPECTED_COLUMNS}")
|
|
||||||
if len(rows) < 2:
|
|
||||||
failures.append("CSV 缺少数据行")
|
|
||||||
for i, row in enumerate(rows[1:], 2):
|
|
||||||
if not row or all(not c for c in row):
|
|
||||||
failures.append(f"CSV 第 {i} 行为空行")
|
|
||||||
elif len(row) != len(EXPECTED_COLUMNS):
|
|
||||||
failures.append(f"CSV 第 {i} 行列数异常:{len(row)}")
|
|
||||||
else:
|
|
||||||
# 2) protocol 合法
|
|
||||||
proto = row[8].strip().lower()
|
|
||||||
if proto not in VALID_PROTOCOLS:
|
|
||||||
failures.append(
|
|
||||||
f"CSV 第 {i} 行非法协议:'{proto}'(合法值见内核 schema.VALID_PROTOCOLS)")
|
|
||||||
# 3) sampleRate 正整数
|
|
||||||
rate = row[5].strip()
|
|
||||||
if not rate.isdigit() or int(rate) <= 0:
|
|
||||||
failures.append(f"CSV 第 {i} 行 sampleRate 必须为正整数:'{rate}'")
|
|
||||||
|
|
||||||
if failures:
|
|
||||||
print("FAIL")
|
|
||||||
for f in failures:
|
|
||||||
print(" -", f)
|
|
||||||
return 1
|
|
||||||
print(f"OK: 点位 {len(rows) - 1} 条,表头/协议/采样率校验通过")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
sys.exit(main())
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
device_id,point_id,name,unit,dataType,sampleRate,qualityCode,opcNode,protocol
|
|
||||||
CLF-01,CLF-01.TEMP,炉温,℃,float,1000,true,ns=2;s=CLF.Temp,simulator
|
|
||||||
CLF-01,CLF-01.PRES,炉压,kPa,float,1000,true,ns=2;s=CLF.Pres,simulator
|
|
||||||
CLF-01,CLF-01.CL2,氯气流量,m³/h,float,1000,true,ns=2;s=CLF.Cl2,simulator
|
|
||||||
CLF-01,CLF-01.CO,CO含量,%,float,1000,true,ns=2;s=CLF.CO,simulator
|
|
||||||
CLF-01,CLF-01.CO2,CO₂含量,%,float,1000,true,ns=2;s=CLF.CO2,simulator
|
|
||||||
CLF-01,CLF-01.BED,炉层状态,%,float,1000,true,ns=2;s=CLF.Bed,simulator
|
|
||||||
CLF-01,CLF-01.FEED,进料量,t/h,float,1000,true,ns=2;s=CLF.Feed,simulator
|
|
||||||
RF-01,RF-01.REDT,还原温度,℃,float,1000,true,ns=2;s=RF.RedT,simulator
|
|
||||||
RF-01,RF-01.VAC,还原真空度,kPa,float,1000,true,ns=2;s=RF.Vac,simulator
|
|
||||||
RF-01,RF-01.PURITY,TiCl₄纯度,%,float,60000,true,ns=2;s=RF.Purity,simulator
|
|
||||||
RF-01,RF-01.IMP,杂质含量,%,float,60000,true,ns=2;s=RF.Imp,simulator
|
|
||||||
E-01,E-01.PWR,车间电功率,kW,float,1000,true,holding:40010,simulator
|
|
||||||
E-01,E-01.KWH,车间累计电耗,kWh,float,1000,true,holding:40012,simulator
|
|
||||||
ST-01,ST-01.STEAM,蒸汽流量,t/h,float,1000,true,ns=2;s=ST.Steam,simulator
|
|
||||||
CW-01,CW-01.FLOW,循环水流量,m³/h,float,1000,true,ns=2;s=CW.Flow,simulator
|
|
||||||
CW-01,CW-01.TEMP,循环水温度,℃,float,1000,true,ns=2;s=CW.Temp,simulator
|
|
||||||
|
Reference in New Issue
Block a user