Compare commits

..
Author SHA1 Message Date
bot_dev1 1290a8bc54 feat(#55): Ti 行业布局模板(四状态流程视图)+ layout_validator
纯标准库实现,对齐 PRD 5.5「⑤ 配置化驾驶舱」iAOP-cockpit-layout-v1:

- cockpit.ti.yaml:海绵钛四状态工艺流程(氯化→精制→还原→蒸馏),
  process_view 主视图声明 stages 覆盖,trend/kpi_card bind 对齐
  point_dict.default.csv 的 point_id(CLF-01/RF-01/E-01/ST-01)。
- layout_validator.py:LayoutValidator 校验 widget 类型合法、12 列网格
  不越界、bind point_id 在点位字典内、四状态覆盖完整(order 单调/id 唯一);
  零依赖 YAML 子集解析(复制 impurity-forecast _parse_yaml_subset)。
- tests:18 用例覆盖真实资产端到端、非法类型、网格越界/负坐标/零宽、
  bind 漂移、缺 process_view、缺必需状态、order 非单调、stage 重复、
  $schema 头、CSV 加载、空布局。
- _sanity_check.py:冒烟验证 9 widgets 全校验通过。
2026-08-05 05:32:23 +08:00
9 changed files with 1025 additions and 762 deletions
-484
View File
@@ -1,484 +0,0 @@
# -*- coding: utf-8 -*-
"""树脂驾驶舱布局提取器 —— issue #84(父 EPIC #13「树脂模板封装」子任务)。
把已交付的树脂驾驶舱布局资产(`dashboard/cockpit.resin.yaml`)**抽取为可复用
模板**,并提供「点位字典回填」能力,验证内核复制不同行业时的零改动假设
(对齐 PRD 5.5「⑤ 配置化驾驶舱」:换行业只替换驾驶舱布局资产,前端代码不动)。
核心抽象:**布局资产 ↔ 布局模板 ↔ 点位字典** 三者解耦——
- 具体布局资产(`cockpit.resin.yaml`)含**硬编码**的点位绑定
(如 `bind: R-801.TEMP`)与 KPI 指标名(如 `metric: resin_exchange_capacity`);
- 布局模板把这些硬编码值**变量化**为占位符(`{device}.{point}` / `{metric}`),
仅保留布局骨架($schema / title / theme / widgets 几何位置 / widget 类型);
- 实例化时用**目标行业的点位字典**回填占位符,得到该行业的具体驾驶舱布局。
对外 API:
- `extract_template(layout_yaml) -> dict`
从具体布局资产抽取通用模板(变量化硬编码点位/指标)。
- `instantiate(template, point_dict) -> dict`
用点位字典回填占位符,生成具体布局(`bind` 用 `device.point` 填回)。
- `diff_layouts(layout_a, layout_b) -> LayoutDiff`
布局差异比对(schema/title/theme/widgets 几何与绑定差异)。
- `PointDict.from_csv(path)` / `PointDict.lookup(device, point)`
点位字典加载与查询(CSV 9 列,对齐内核 schema)。
纯标准库实现(无 yaml 依赖):YAML 子集用 `_parse_yaml_subset` 解析;
与 `templates/ti-cl4/llm-scenarios/` 同款「dataclass + Enum + 类型注解 +
中文 docstring 引 PRD/EPIC」范式。
"""
from __future__ import annotations
import csv
import os
import re
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Tuple, Union
# ----------------------------------------------------------------------
# 资产路径
# ----------------------------------------------------------------------
#: 模板根目录(templates/resin/)
TEMPLATE_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#: 驾驶舱布局资产(issue #84 的提取对象)
DEFAULT_LAYOUT_PATH = os.path.join(
TEMPLATE_ROOT, "dashboard", "cockpit.resin.yaml")
#: 点位字典资产(issue #82,回填占位符用)
DEFAULT_POINT_DICT_PATH = os.path.join(
TEMPLATE_ROOT, "point-dict", "point_dict.resin.csv")
#: PRD 5.5 iAOP-cockpit-layout-v1 允许的 widget 类型
ALLOWED_WIDGETS = {
"process_view", "trend", "kpi_card", "alarm_panel", "nl_query",
}
#: 驾驶舱布局的 $schema(绑定布局模板版本)
COCKPIT_SCHEMA = "iAOP-cockpit-layout-v1"
#: 占位符:设备位号 / 测点 / KPI 指标(变量化布局)
DEVICE_PLACEHOLDER = "{device}"
POINT_PLACEHOLDER = "{point}"
METRIC_PLACEHOLDER = "{metric}"
#: trend widget 的 bind 变量化形态(设备.测点)
BIND_TEMPLATE = f"{DEVICE_PLACEHOLDER}.{POINT_PLACEHOLDER}"
#: 识别「设备.测点」绑定(如 `R-801.TEMP`),用于变量化与回填
_BIND_RE = re.compile(r"^([A-Za-z0-9_\-]+)\.([A-Za-z0-9_\-]+)$")
# ----------------------------------------------------------------------
# Widget 类型(枚举)
# ----------------------------------------------------------------------
class WidgetType(str, Enum):
"""PRD 5.5 允许的 widget 类型(str 继承便于直接作 YAML 值)。"""
PROCESS_VIEW = "process_view"
TREND = "trend"
KPI_CARD = "kpi_card"
ALARM_PANEL = "alarm_panel"
NL_QUERY = "nl_query"
@classmethod
def is_allowed(cls, value: str) -> bool:
"""widget 类型是否在 PRD 5.5 schema 允许集合内。"""
return any(member.value == value for member in cls)
# ----------------------------------------------------------------------
# 数据类
# ----------------------------------------------------------------------
@dataclass
class PointEntry:
"""点位字典中的单条点位(CSV 9 列,对齐内核 schema)。"""
device_id: str
point_id: str
name: str
unit: str
data_type: str
sample_rate: str
quality_code: str
opc_node: str
protocol: str
@property
def point(self) -> str:
"""短测点名:`R-801.TEMP` → `TEMP`(剥离设备前缀)。"""
prefix = f"{self.device_id}."
if self.point_id.startswith(prefix):
return self.point_id[len(prefix):]
return self.point_id
@dataclass
class PointDict:
"""点位字典(按 device_id 索引点位集合)。
用于 `instantiate` 把布局模板里的 `{device}.{point}` 占位符回填为
目标行业的具体点位绑定。
"""
entries: List[PointEntry] = field(default_factory=list)
@classmethod
def from_csv(cls, path: str = DEFAULT_POINT_DICT_PATH) -> "PointDict":
"""从 CSV 加载点位字典(9 列,对齐 point_dict.resin.csv schema)。"""
entries: List[PointEntry] = []
with open(path, "r", encoding="utf-8") as fh:
reader = csv.reader(fh)
header = next(reader, None)
if header is None:
raise ValueError(f"点位字典 CSV 为空:{path}")
for row in reader:
if len(row) != 9:
raise ValueError(
f"点位字典 CSV 行列数异常(需 9 列):{row}")
entries.append(PointEntry(*row))
return cls(entries=entries)
def devices(self) -> List[str]:
"""去重保序返回所有设备位号。"""
seen: List[str] = []
for e in self.entries:
if e.device_id not in seen:
seen.append(e.device_id)
return seen
def lookup(self, device: str, point: Optional[str] = None) -> List[PointEntry]:
"""查询某设备(可选过滤测点名)的点位。"""
out: List[PointEntry] = []
for e in self.entries:
if e.device_id == device and (point is None or e.point == point):
out.append(e)
return out
def first_device(self) -> str:
"""首个设备位号(单设备趋势绑定回填的默认设备)。"""
return self.entries[0].device_id
@dataclass
class LayoutDiff:
"""两份布局的差异(`diff_layouts` 返回)。"""
schema_changed: bool = False
title_changed: bool = False
theme_changed: bool = False
widget_count_a: int = 0
widget_count_b: int = 0
geometry_changes: List[str] = field(default_factory=list)
binding_changes: List[str] = field(default_factory=list)
@property
def is_identical(self) -> bool:
"""两份布局是否完全一致。"""
return (not self.schema_changed and not self.title_changed
and not self.theme_changed
and not self.geometry_changes and not self.binding_changes
and self.widget_count_a == self.widget_count_b)
def summary(self) -> List[str]:
"""人读的差异摘要(可解释性:列每条差异的含义/原因)。"""
items: List[str] = []
if self.schema_changed:
items.append("$schema 不一致(布局版本不同,可能不兼容)")
if self.title_changed:
items.append("title 不一致(驾驶舱标题文案不同)")
if self.theme_changed:
items.append("theme 不一致(明暗主题不同)")
if self.widget_count_a != self.widget_count_b:
items.append(
f"widget 数量不同:{self.widget_count_a} → {self.widget_count_b}")
for g in self.geometry_changes:
items.append(f"几何变更:{g}")
for b in self.binding_changes:
items.append(f"绑定变更:{b}")
if not items:
items.append("布局完全一致")
return items
# ----------------------------------------------------------------------
# YAML 子集解析器(零依赖,复制自 ti-cl4 范式)
# ----------------------------------------------------------------------
def _parse_value(token: str) -> Union[str, int, float, bool, None]:
"""把标量 token 解析为 Python 类型(int/float/bool/None/str)。"""
token = token.strip()
if token == "":
return ""
if token.lower() == "true":
return True
if token.lower() == "false":
return False
if token.lower() in ("null", "none", "~"):
return None
# int
if re.fullmatch(r"-?\d+", token):
return int(token)
# float
if re.fullmatch(r"-?\d+\.\d+", token):
return float(token)
# 去引号
if len(token) >= 2 and token[0] in "\"'" and token[-1] == token[0]:
return token[1:-1]
return token
def _is_bare_scalar(item_text: str) -> bool:
"""列表项是否为裸标量(非 `key: value` 形式)。
注意:`R-801.TEMP` 这类含冒号但被引号包裹或无分隔冒号的情况需判别。
本驾驶舱 YAML 中列表项的 mapping 形式形如 `type: trend`,分隔符 `: `
后有值;裸标量(无冒号)按标量处理。
"""
# 含 ": " 或以 ":" 结尾 → 视作 mapping 起点
return ": " not in item_text and not item_text.endswith(":")
def _parse_yaml_subset(text: str) -> dict:
"""零依赖 YAML 子集解析器。
仅支持本模块所读的驾驶舱布局资产用到的 YAML 语法:
- 顶层 mapping(`key: value`);
- 列表(`- item`),列表元素可为 mapping(多行 `key: value`);
- 缩进表示嵌套(2 空格缩进);
- 行内值支持 int/float/bool/None/带引号字符串/裸字符串;
- `#` 注释行、空行跳过;
- `key:`(空值)后跟 `- ` 列表项 → 该 key 的值解析为 list。
复杂特性(多行字符串 / 流式语法 / 锚点)按需再加,本模板用不到。
"""
root: dict = {}
# 栈元素:(indent, container, container_owner, owner_key)
# container_owner/owner_key 用于:当 container 是「按需创建的 list」时
# 能回写到父 dict(解决 `widgets:` 后跟列表项的场景)。
stack: List[Tuple[int, Union[dict, list], Optional[dict], Optional[str]]] = [
(0, root, None, None)]
def _indent(line: str) -> int:
return len(line) - len(line.lstrip(" "))
for raw in text.splitlines():
stripped = raw.rstrip()
if not stripped.strip():
continue
if stripped.lstrip().startswith("#"):
continue
indent = _indent(stripped)
content = stripped[indent:]
# 弹栈到当前缩进的父级(>= 而非 >,保留同缩进兄弟)
while len(stack) > 1 and stack[-1][0] > indent:
stack.pop()
if content.startswith("- "):
# 列表项
item_text = content[2:].strip()
top_indent, container, owner, key = stack[-1]
# 若当前容器是「待创建 list」(dict 里某 key 值还指向 dict 自身的占位)
if isinstance(container, dict):
raise ValueError(f"列表项出现在非列表上下文:{raw!r}")
if ":" in item_text and not _is_bare_scalar(item_text):
# 列表项是 mapping 起点(如 `- type: trend`)
k, _, v = item_text.partition(":")
child: dict = {k.strip(): _parse_value(v) if v.strip() else None}
container.append(child)
stack.append((indent + 2, child, None, None))
else:
container.append(_parse_value(item_text))
else:
# mapping 项
key, sep, val = content.partition(":")
if not sep:
continue
key = key.strip()
val = val.strip()
top_indent, container, owner, owner_key = stack[-1]
if not isinstance(container, dict):
raise ValueError(f"键值项出现在非 mapping 上下文:{raw!r}")
if val == "":
# 子结构占位:先建空 list(驾驶舱 widgets 后跟列表项),
# 入栈供后续 `- ` 项填充;若实际跟的是 mapping,append 时会
# 因类型不符报错(本资产不会发生)。
child_list: list = []
container[key] = child_list
stack.append((indent + 1, child_list, container, key))
else:
container[key] = _parse_value(val)
return root
# ----------------------------------------------------------------------
# 布局加载
# ----------------------------------------------------------------------
def load_layout(path: str = DEFAULT_LAYOUT_PATH) -> dict:
"""加载驾驶舱布局资产(零依赖 YAML 子集解析)。"""
with open(path, "r", encoding="utf-8") as fh:
text = fh.read()
return _parse_yaml_subset(text)
# ----------------------------------------------------------------------
# 提取 / 实例化 / 比对
# ----------------------------------------------------------------------
def _is_device_point_binding(value: str) -> Optional[Tuple[str, str]]:
"""识别 `设备.测点` 形态的绑定,返回 (device, point) 或 None。"""
m = _BIND_RE.match(value or "")
if m:
return m.group(1), m.group(2)
return None
def extract_template(layout_yaml: Union[str, dict]) -> dict:
"""从具体布局资产抽取通用模板。
把硬编码的点位绑定(`R-801.TEMP`)与 KPI 指标名
(`resin_exchange_capacity`)**变量化**为占位符,保留布局骨架
($schema / title / theme / widgets 几何与类型 / description)。
Args:
layout_yaml: 具体布局资产路径、或已解析 dict、或 YAML 文本。
Returns:
模板 dict,widget 的 `bind`/`metric` 被替换为占位符;并附带
`placeholder_binding` 字段记录每个占位符的语义(可解释性)。
"""
if isinstance(layout_yaml, str):
if os.path.isfile(layout_yaml):
layout = load_layout(layout_yaml)
else:
layout = _parse_yaml_subset(layout_yaml)
elif isinstance(layout_yaml, dict):
layout = layout_yaml
else:
raise TypeError(f"layout_yaml 类型不支持:{type(layout_yaml)}")
template: dict = {
"$schema": layout.get("$schema", COCKPIT_SCHEMA),
"title": layout.get("title", ""),
"theme": layout.get("theme", "dark"),
"widgets": [],
# 占位符语义说明(提取记录,便于实例化时回填与可解释性)
"placeholder_binding": {
DEVICE_PLACEHOLDER: "设备位号(点位字典 device_id)",
POINT_PLACEHOLDER: "测点名(点位字典 point_id 去设备前缀)",
METRIC_PLACEHOLDER: "KPI 指标名(业务语义键)",
},
}
for w in layout.get("widgets", []):
wt = dict(w) # 浅拷贝
# 1) trend widget 的 bind:R-801.TEMP → {device}.{point}
if wt.get("type") == WidgetType.TREND.value and "bind" in wt:
dp = _is_device_point_binding(str(wt["bind"]))
if dp:
wt["bind"] = BIND_TEMPLATE
wt.setdefault("extracted_from", {})["bind"] = list(dp)
# 2) kpi_card 的 metric:变量化为 {metric}(保留 label)
if wt.get("type") == WidgetType.KPI_CARD.value and "metric" in wt:
wt.setdefault("extracted_from", {})["metric"] = wt["metric"]
wt["metric"] = METRIC_PLACEHOLDER
template["widgets"].append(wt)
return template
def instantiate(template: dict, point_dict: PointDict) -> dict:
"""用点位字典把模板占位符回填为具体布局。
回填策略(对齐 PRD 5.5 布局语义):
- trend widget:`{device}.{point}` 占位符 → 按模板中记录的
`extracted_from.bind` 设备/测点回填;若模板已抽象到只剩占位符
且未记录来源,则用点位字典首个设备 + 同名测点回填。
- kpi_card:`{metric}` → 回填为模板 `extracted_from.metric` 原值
(指标名属业务语义键,不随设备变,保持原值最安全)。
Args:
template: `extract_template` 的输出。
point_dict: 目标行业点位字典(`PointDict.from_csv`)。
Returns:
具体布局 dict(去除 `extracted_from` / `placeholder_binding`
内部字段,符合 iAOP-cockpit-layout-v1 schema)。
"""
if not isinstance(template, dict):
raise TypeError(f"template 必须是 dict:{type(template)}")
if not point_dict.entries:
raise ValueError("点位字典为空,无法回填")
devices = point_dict.devices()
out: dict = {
"$schema": template.get("$schema", COCKPIT_SCHEMA),
"title": template.get("title", ""),
"theme": template.get("theme", "dark"),
"widgets": [],
}
for w in template.get("widgets", []):
cw = dict(w)
src = cw.pop("extracted_from", None) or {}
if cw.get("type") == WidgetType.TREND.value and "bind" in cw:
bind = str(cw["bind"])
if DEVICE_PLACEHOLDER in bind or POINT_PLACEHOLDER in bind:
# 优先用提取时记录的来源设备/测点
device = src.get("bind", [None, None])[0] if src.get("bind") else None
point = src.get("bind", [None, None])[1] if len(src.get("bind", [])) > 1 else None
# 用点位字典校验/覆盖:若设备在字典中则用之,否则回退首个设备
if not device or device not in devices:
device = devices[0]
if not point:
cands = point_dict.lookup(device)
point = cands[0].point if cands else "TEMP"
cw["bind"] = f"{device}.{point}"
if cw.get("type") == WidgetType.KPI_CARD.value and "metric" in cw:
if str(cw["metric"]) == METRIC_PLACEHOLDER:
# metric 是业务语义键,保留模板提取时的原值
cw["metric"] = src.get("metric", "kpi_metric")
out["widgets"].append(cw)
return out
def diff_layouts(layout_a: dict, layout_b: dict) -> LayoutDiff:
"""比对两份具体布局(或模板)的差异。
返回 `LayoutDiff`:含 schema/title/theme/widgets 几何位置与
bind/metric 绑定的逐条差异(用于换行业时回归比对,定位漂移)。
"""
diff = LayoutDiff(
schema_changed=layout_a.get("$schema") != layout_b.get("$schema"),
title_changed=layout_a.get("title") != layout_b.get("title"),
theme_changed=layout_a.get("theme") != layout_b.get("theme"),
)
wa = layout_a.get("widgets", []) or []
wb = layout_b.get("widgets", []) or []
diff.widget_count_a = len(wa)
diff.widget_count_b = len(wb)
# 按位置(索引)对齐 widgets,比对几何与绑定
n = max(len(wa), len(wb))
for i in range(n):
a = wa[i] if i < len(wa) else None
b = wb[i] if i < len(wb) else None
if a is None or b is None:
diff.geometry_changes.append(
f"widget[{i}] {'缺失' if a is None else '新增'}")
continue
# 几何(x/y/w/h)
for k in ("x", "y", "w", "h"):
av, bv = a.get(k), b.get(k)
if av != bv:
diff.geometry_changes.append(
f"widget[{i}].{k}: {av} → {bv}")
# 类型
if a.get("type") != b.get("type"):
diff.geometry_changes.append(
f"widget[{i}].type: {a.get('type')} → {b.get('type')}")
# 绑定(bind / metric)
for k in ("bind", "metric"):
av, bv = a.get(k), b.get(k)
if av != bv:
diff.binding_changes.append(
f"widget[{i}].{k}: {av!r} → {bv!r}")
return diff
-278
View File
@@ -1,278 +0,0 @@
# -*- coding: utf-8 -*-
"""树脂驾驶舱布局提取器测试(issue #84)。
覆盖(>=8 用例):
1. load_layout:驾驶舱布局资产解析(schema/title/theme/widgets 9 个);
2. extract_template:trend bind 变量化(R-801.TEMP → {device}.{point});
3. extract_template:kpi metric 变量化(→ {metric});
4. extract_template:占位符语义(placeholder_binding)+ 提取来源记录;
5. PointDict.from_csv:21 条点位、device 去重;
6. PointDict.lookup:按设备/测点查询;
7. instantiate:用点位字典回填 bind(具体点位);
8. instantiate:metric 回填为模板原指标名(业务语义键不变);
9. instantiate:去除内部字段(extracted_from/placeholder_binding);
10. diff_layouts:一致布局 → is_identical;
11. diff_layouts:bind 变更 → binding_changes;
12. diff_layouts:几何变更 → geometry_changes;
13. WidgetType.is_allowed / COCKPIT_SCHEMA 常量。
14. 端到端:extract → instantiate → 与原布局一致(回填幂等性)。
"""
import copy
import os
import sys
import unittest
# 把 templates/resin/dashboard 挂到 sys.path 以便 `from extractor import ...`
_RESIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_DASHBOARD_DIR = os.path.join(_RESIN_DIR, "dashboard")
sys.path.insert(0, _DASHBOARD_DIR)
from extractor import ( # noqa: E402
BIND_TEMPLATE,
COCKPIT_SCHEMA,
DEVICE_PLACEHOLDER,
METRIC_PLACEHOLDER,
POINT_PLACEHOLDER,
DEFAULT_LAYOUT_PATH,
DEFAULT_POINT_DICT_PATH,
ALLOWED_WIDGETS,
LayoutDiff,
PointDict,
PointEntry,
WidgetType,
diff_layouts,
extract_template,
instantiate,
load_layout,
)
class TestYAMLSubsetParse(unittest.TestCase):
"""零依赖 YAML 子集解析(驾驶舱布局资产)。"""
def test_load_layout_basic(self):
"""#1 驾驶舱资产解析:schema/title/theme/widgets 9 个。"""
layout = load_layout()
self.assertEqual(layout["$schema"], COCKPIT_SCHEMA)
self.assertEqual(layout["title"], "吸附树脂车间驾驶舱")
self.assertEqual(layout["theme"], "dark")
self.assertEqual(len(layout["widgets"]), 9)
def test_widget_types_all_allowed(self):
"""#13 所有 widget 类型在 PRD 5.5 schema 允许集合内。"""
layout = load_layout()
for w in layout["widgets"]:
self.assertIn(w["type"], ALLOWED_WIDGETS)
self.assertTrue(WidgetType.is_allowed(w["type"]))
def test_parse_inline_scalar_types(self):
"""YAML 行内标量解析:int/float/bool/None/带引号字符串。"""
from extractor import _parse_yaml_subset, _parse_value
self.assertEqual(_parse_value("12"), 12)
self.assertEqual(_parse_value("4.5"), 4.5)
self.assertIs(_parse_value("true"), True)
self.assertIs(_parse_value("false"), False)
self.assertIsNone(_parse_value("null"))
self.assertEqual(_parse_value("'x'"), "x")
# 缩进嵌套 + 列表项 mapping
doc = _parse_yaml_subset(
"title: T\nwidgets:\n - type: trend\n bind: R1.X\n x: 1\n")
self.assertEqual(doc["title"], "T")
self.assertEqual(doc["widgets"][0]["type"], "trend")
self.assertEqual(doc["widgets"][0]["bind"], "R1.X")
self.assertEqual(doc["widgets"][0]["x"], 1)
class TestExtractTemplate(unittest.TestCase):
"""布局资产 → 通用模板(变量化)。"""
def setUp(self):
self.layout = load_layout()
self.tmpl = extract_template(self.layout)
def test_trend_bind_placeholderized(self):
"""#2 trend bind:R-801.TEMP → {device}.{point}。"""
trend_binds = [w.get("bind") for w in self.tmpl["widgets"]
if w.get("type") == "trend"]
self.assertTrue(trend_binds)
for b in trend_binds:
self.assertEqual(b, BIND_TEMPLATE)
def test_kpi_metric_placeholderized(self):
"""#3 kpi metric:resin_exchange_capacity → {metric}。"""
kpi_metrics = [w.get("metric") for w in self.tmpl["widgets"]
if w.get("type") == "kpi_card"]
self.assertEqual(len(kpi_metrics), 4)
for m in kpi_metrics:
self.assertEqual(m, METRIC_PLACEHOLDER)
def test_placeholder_semantics_and_source(self):
"""#4 占位符语义(placeholder_binding)+ 提取来源记录。"""
# 占位符语义说明
pb = self.tmpl["placeholder_binding"]
self.assertIn(DEVICE_PLACEHOLDER, pb)
self.assertIn(POINT_PLACEHOLDER, pb)
self.assertIn(METRIC_PLACEHOLDER, pb)
# trend widget 记录提取来源(device/point 二元组)
trend = next(w for w in self.tmpl["widgets"]
if w.get("type") == "trend")
self.assertEqual(trend["extracted_from"]["bind"], ["R-801", "TEMP"])
# kpi widget 记录原指标名
kpi = next(w for w in self.tmpl["widgets"]
if w.get("type") == "kpi_card")
self.assertEqual(kpi["extracted_from"]["metric"],
"resin_exchange_capacity")
def test_extract_from_yaml_text_and_path(self):
"""extract_template 接受路径 / dict / YAML 文本三种入参。"""
tmpl_from_path = extract_template(DEFAULT_LAYOUT_PATH)
self.assertEqual(tmpl_from_path["$schema"], COCKPIT_SCHEMA)
tmpl_from_dict = extract_template(self.layout)
self.assertEqual(tmpl_from_dict["title"], self.tmpl["title"])
class TestPointDict(unittest.TestCase):
"""点位字典加载与查询。"""
def setUp(self):
self.pd = PointDict.from_csv()
def test_csv_load_count_and_devices(self):
"""#5 21 条点位 + device 去重保序。"""
self.assertEqual(len(self.pd.entries), 21)
self.assertEqual(self.pd.entries[0].device_id, "R-801")
self.assertEqual(self.pd.devices()[0], "R-801")
# device 去重(R-801 出现 6 次,去重后 1)
self.assertEqual(self.pd.devices().count("R-801"), 1)
def test_lookup_and_point_short_name(self):
"""#6 查询某设备测点 + point 短名(去设备前缀)。"""
r801 = self.pd.lookup("R-801")
self.assertTrue(r801)
# 短测点名剥离设备前缀
temps = [e.point for e in r801 if e.point == "TEMP"]
self.assertEqual(temps, ["TEMP"])
# 精确测点过滤
temp_only = self.pd.lookup("R-801", "TEMP")
self.assertEqual(len(temp_only), 1)
self.assertEqual(temp_only[0].unit, "℃")
# 未知设备 → 空列表
self.assertEqual(self.pd.lookup("NOPE"), [])
class TestInstantiate(unittest.TestCase):
"""模板 + 点位字典 → 具体布局(回填占位符)。"""
def setUp(self):
self.pd = PointDict.from_csv()
self.tmpl = extract_template(load_layout())
self.concrete = instantiate(self.tmpl, self.pd)
def test_backfill_trend_bind(self):
"""#7 trend bind 回填为具体点位(R-801.TEMP)。"""
binds = [w.get("bind") for w in self.concrete["widgets"]
if w.get("type") == "trend"]
self.assertEqual(binds, ["R-801.TEMP", "R-801.AGIT"])
# 不残留占位符
for b in binds:
self.assertNotIn(DEVICE_PLACEHOLDER, b)
def test_backfill_metric_keeps_business_key(self):
"""#8 metric 回填为模板原指标名(业务语义键不变)。"""
metrics = [w.get("metric") for w in self.concrete["widgets"]
if w.get("type") == "kpi_card"]
self.assertEqual(metrics[0], "resin_exchange_capacity")
def test_instantiate_strips_internal_fields(self):
"""#9 实例化输出去除 extracted_from / placeholder_binding 内部字段。"""
self.assertNotIn("placeholder_binding", self.concrete)
for w in self.concrete["widgets"]:
self.assertNotIn("extracted_from", w)
# 输出仍是合法布局(schema/widgets 齐全)
self.assertEqual(self.concrete["$schema"], COCKPIT_SCHEMA)
def test_instantiate_fallback_unknown_device(self):
"""占位符回填:来源设备不在点位字典 → 回退首个设备。"""
tmpl = copy.deepcopy(self.tmpl)
# 篡改 trend 来源为字典中不存在的设备
for w in tmpl["widgets"]:
if w.get("type") == "trend":
w["extracted_from"]["bind"] = ["ZZZ-999", "TEMP"]
break
conc = instantiate(tmpl, self.pd)
bind0 = next(w.get("bind") for w in conc["widgets"]
if w.get("type") == "trend")
self.assertTrue(bind0.startswith(self.pd.devices()[0] + "."))
def test_instantiate_rejects_empty_pointdict(self):
"""空点位字典 → ValueError(无法回填)。"""
empty = PointDict(entries=[])
with self.assertRaises(ValueError):
instantiate(self.tmpl, empty)
class TestDiffLayouts(unittest.TestCase):
"""布局差异比对。"""
def setUp(self):
self.layout = load_layout()
def test_identical_layout(self):
"""#10 相同布局 → is_identical。"""
d = diff_layouts(self.layout, self.layout)
self.assertTrue(d.is_identical)
self.assertIn("完全一致", d.summary()[0])
def test_binding_change_detected(self):
"""#11 bind 变更 → binding_changes(换行业回归比对)。"""
b = copy.deepcopy(self.layout)
for w in b["widgets"]:
if w.get("type") == "trend" and w.get("bind") == "R-801.TEMP":
w["bind"] = "R-802.TEMP"
d = diff_layouts(self.layout, b)
self.assertFalse(d.is_identical)
self.assertTrue(any("bind" in s for s in d.binding_changes))
self.assertTrue(any("R-802.TEMP" in s for s in d.binding_changes))
def test_geometry_change_detected(self):
"""#12 几何位置变更 → geometry_changes。"""
b = copy.deepcopy(self.layout)
b["widgets"][0]["x"] = 99
b["title"] = "改了"
d = diff_layouts(self.layout, b)
self.assertFalse(d.is_identical)
self.assertTrue(d.title_changed)
self.assertTrue(any("widget[0].x" in s for s in d.geometry_changes))
def test_widget_count_diff(self):
"""widget 数量不同 → 摘要体现。"""
a = {"$schema": COCKPIT_SCHEMA, "title": "t", "widgets": [
{"type": "trend", "bind": "R-801.TEMP"}]}
b = {"$schema": COCKPIT_SCHEMA, "title": "t", "widgets": []}
d = diff_layouts(a, b)
self.assertEqual(d.widget_count_a, 1)
self.assertEqual(d.widget_count_b, 0)
self.assertFalse(d.is_identical)
class TestEndToEndRoundTrip(unittest.TestCase):
"""端到端:extract → instantiate 与原布局一致(回填幂等性)。"""
def test_roundtrip_identical_to_source(self):
"""extract 后用同一点位字典 instantiate,结果与原布局一致。
验证「布局资产 ↔ 模板 ↔ 点位字典」三者解耦后可无损还原——
这是模板可复用的关键:换行业只需换点位字典即可重排驾驶舱。
"""
layout = load_layout()
pd = PointDict.from_csv()
tmpl = extract_template(layout)
concrete = instantiate(tmpl, pd)
d = diff_layouts(layout, concrete)
self.assertTrue(
d.is_identical,
f"回填结果与原布局不一致:{d.summary()}")
if __name__ == "__main__":
unittest.main()
+37
View File
@@ -0,0 +1,37 @@
# 海绵钛驾驶舱布局资产 + 校验器(Issue #55 / PRD 5.5)
> 父 Issue「⑤ Ti 行业布局模板(四状态流程视图)· 0.5d」
把海绵钛车间驾驶舱布局落为**对齐 iAOP-cockpit-layout-v1 的资产 + 可校验的纯标准库
校验器**(无 node/前端构建环境,零运行时依赖)。
## 资产:`cockpit.ti.yaml`
四状态工艺流程(PRD 4.2 海绵钛:**氯化 → 精制 → 还原 → 蒸馏**):
- `process_view` 主视图(首屏立即加载),`stages` 声明四状态覆盖;
- `trend` 实时趋势(氯化炉温度 `CLF-01.TEMP` / 氯气流量 `CLF-01.CL2`);
- `kpi_card` KPI(TiCl₄纯度 `RF-01.PURITY` / 杂质 `RF-01.IMP` / 电耗 `E-01.KWH` / 蒸汽 `ST-01.STEAM`);
- `alarm_panel` 告警面板 + `nl_query` NL 查询入口。
所有 `bind` 的 `point_id` 对齐 `templates/ti-cl4/point-dict/point_dict.default.csv`。
## 校验器:`layout_validator.py`
`LayoutValidator(layout_yaml, point_dict_csv).validate()` → `LayoutReport`,校验:
1. **widget 类型合法**:在 `iAOP-cockpit-layout-v1` 允许集合内(process_view/trend/kpi_card/alarm_panel/nl_query);
2. **12 列网格不越界**:`0 ≤ x`、`x + w ≤ 12`、`y ≥ 0`、`w/h > 0`;
3. **bind point_id 在点位字典内**:防模板漂移(trend/kpi_card 的 bind 必须命中点字典);
4. **四状态覆盖完整**:process_view 的 stages 必须覆盖氯化/精制/还原/蒸馏,order 单调递增、id 唯一。
零依赖 YAML 子集解析(复制 impurity-forecast 的 `_parse_yaml_subset`,无 pyyaml)。
## 测试
```bash
python -m unittest discover -s templates/ti-cl4/dashboard/tests -p "test_*.py" -v
```
覆盖正常 + 边界 + 错误(18 用例):真实资产端到端通过、非法类型、网格越界/负坐标/零宽、
bind 漂移、缺 process_view、缺必需状态、order 非单调、stage 重复、$schema 头、CSV 加载、空布局。
+27
View File
@@ -0,0 +1,27 @@
# -*- coding: utf-8 -*-
"""海绵钛驾驶舱布局资产 + 校验器包(Issue #55)。
对齐 PRD 5.5「⑤ 配置化驾驶舱」布局 JSON Schema(iAOP-cockpit-layout-v1):
四状态工艺流程(氯化 → 精制 → 还原 → 蒸馏)。
"""
from .layout_validator import (
LayoutError,
LayoutIssue,
LayoutReport,
LayoutValidator,
WidgetSpec,
ALLOWED_WIDGET_TYPES,
GRID_COLUMNS,
REQUIRED_STAGES,
)
__all__ = [
"LayoutError",
"LayoutIssue",
"LayoutReport",
"LayoutValidator",
"WidgetSpec",
"ALLOWED_WIDGET_TYPES",
"GRID_COLUMNS",
"REQUIRED_STAGES",
]
@@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
"""海绵钛驾驶舱布局冒烟脚本(Issue #55)。
直接运行 ``python _sanity_check.py`` 验证:cockpit.ti.yaml + point_dict.default.csv
端到端校验通过(widget 类型/网格/bind/四状态全覆盖)。零第三方依赖。
"""
import os
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from layout_validator import LayoutValidator # noqa: E402
LAYOUT_YAML = os.path.join(HERE, "cockpit.ti.yaml")
POINT_DICT_CSV = os.path.join(
HERE, os.pardir, "point-dict", "point_dict.default.csv")
def main() -> int:
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
if not report.passed:
print("FAIL")
for issue in report.errors:
print(f" - [{issue.widget_id}] {issue.field}: {issue.reason}")
return 1
print(f"OK: {report.widget_count} widgets,"
f"类型/网格/bind/四状态校验通过")
return 0
if __name__ == "__main__":
raise SystemExit(main())
+108
View File
@@ -0,0 +1,108 @@
# -*- coding: utf-8 -*-
# 海绵钛(Ti)车间驾驶舱布局资产(iAOP-Template-Ti,EPIC #12)。
#
# 对齐 PRD 5.5「⑤ 配置化驾驶舱」布局 JSON Schema(iAOP-cockpit-layout-v1):
# 切换行业模板后,驾驶舱按本布局自动重排,无需改前端代码。
# widget 类型:process_view(工艺流程视图)/ trend(实时趋势)/ kpi_card(KPI卡片)/
# alarm_panel(告警面板)/ nl_query(NL查询入口)。
#
# 四状态工艺流程(PRD 4.2 海绵钛:氯化 → 精制 → 还原 → 蒸馏):
# - 氯化 (CLF-01):TiO₂ + Cl₂ + C → TiCl₄(沸腾氯化炉)
# - 精制 :粗 TiCl₄ → 精 TiCl₄(除钒/除硅,常压精馏)
# - 还原 (RF-01):TiCl₄ + Mg → 海绵钛(真空还原,Kroll 法)
# - 蒸馏 :海绵钛 + 残余 Mg/MgCl₂ 分离(真空蒸馏)
# process_view 的 stages 字段声明四状态覆盖,layout_validator 校验完整性。
#
# bind 的 point_id 对齐 templates/ti-cl4/point-dict/point_dict.default.csv。
$schema: iAOP-cockpit-layout-v1
title: 海绵钛车间驾驶舱
theme: dark
widgets:
# ---- 四状态工艺流程主视图(首屏立即加载) ---------------------------
- type: process_view
src: ti_four_state.svg
x: 0
y: 0
w: 12
h: 4
description: 四状态工艺流程(氯化 → 精制 → 还原 → 蒸馏)
stages:
- id: chlorination
name: 氯化
device: CLF-01
order: 1
- id: purification
name: 精制
order: 2
- id: reduction
name: 还原
device: RF-01
order: 3
- id: distillation
name: 蒸馏
order: 4
# ---- 实时趋势:氯化炉温度/氯气流量(工艺核心监控) -------------------
- type: trend
bind: CLF-01.TEMP
x: 0
y: 4
w: 6
h: 2
description: 氯化炉温度实时趋势(沸腾氯化炉温 850±50℃)
- type: trend
bind: CLF-01.CL2
x: 6
y: 4
w: 6
h: 2
description: 氯气流量实时趋势(流态化监控)
# ---- KPI 卡片:还原质量/能耗(海绵钛核心指标) -----------------------
- type: kpi_card
metric: ticl4_purity
bind: RF-01.PURITY
label: TiCl₄纯度
x: 0
y: 6
w: 3
h: 2
description: 还原 TiCl₄ 纯度(%,工艺 ≥ 99.9%)
- type: kpi_card
metric: ticl4_impurity
bind: RF-01.IMP
label: 杂质含量
x: 3
y: 6
w: 3
h: 2
description: 还原杂质含量(%,越低越好)
- type: kpi_card
metric: energy_per_ton
bind: E-01.KWH
label: 累计电耗
x: 6
y: 6
w: 3
h: 2
description: 车间累计电耗(kWh,单吨海绵钛综合能耗输入)
- type: kpi_card
metric: steam_flow
bind: ST-01.STEAM
label: 蒸汽流量
x: 9
y: 6
w: 3
h: 2
description: 蒸汽流量(t/h,公用工程监控)
# ---- 告警面板 + NL 查询入口 ------------------------------------------
- type: alarm_panel
x: 0
y: 8
w: 9
h: 3
description: 告警面板(氯化炉温/还原真空度/纯度/杂质异常)
- type: nl_query
x: 9
y: 8
w: 3
h: 3
description: 自然语言查询入口(工艺/质量/能耗问答)
@@ -0,0 +1,500 @@
# -*- coding: utf-8 -*-
"""海绵钛驾驶舱布局校验器(Issue #55 / PRD 5.5「⑤ 配置化驾驶舱」)。
PRD 5.5:切换行业模板后,驾驶舱按布局资产自动重排,无需改前端代码。
本模块把布局资产(``cockpit.ti.yaml``)落为**可校验的纯标准库资产 + 校验器**——
给定布局 YAML + 点位字典 CSV,校验:
1. **widget 类型合法**:在 PRD 5.5 ``iAOP-cockpit-layout-v1`` 允许集合内
(process_view/trend/kpi_card/alarm_panel/nl_query)。
2. **12 列网格不越界**:每个 widget ``0 ≤ x`` 且 ``x + w ≤ 12``,``y ≥ 0``、
``h > 0``;坐标为非负整数,w/h 正整数(网格对齐)。
3. **bind 的 point_id 在点位字典内**:trend/kpi_card 的 ``bind`` 必须命中
``point_dict.default.csv`` 的 ``point_id`` 列(防模板漂移)。
4. **四状态视图覆盖完整**:process_view 的 ``stages`` 必须覆盖工艺全流程
(氯化/精制/还原/蒸馏),且 order 单调递增、id 唯一。
校验产出 :class:`LayoutReport`(PASS/FAIL + 逐条 :class:`LayoutIssue`,
每条 issue 带 ``reason`` 可解释)。
设计要点
--------
- **零依赖 YAML 子集解析**:复制 impurity-forecast features.py 的
``_parse_yaml_subset``(无 pyyaml),支持 map/list/标量/行内 flow map。
- **纯标准库**:CSV 用标准库 csv,无 numpy/pyyaml 依赖。
- **换行业只改资产**:校验器对任何对齐 ``iAOP-cockpit-layout-v1`` 的布局都适用。
用法::
report = LayoutValidator(layout_yaml, point_dict_csv).validate()
if not report.passed:
for issue in report.issues:
print(issue.severity, issue.widget_id, issue.reason)
"""
from __future__ import annotations
import csv
import os
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Tuple
#: iAOP-cockpit-layout-v1 允许的 widget 类型集合(对齐 resin _sanity_check)。
ALLOWED_WIDGET_TYPES = frozenset({
"process_view", "trend", "kpi_card", "alarm_panel", "nl_query",
})
#: 12 列网格(主流前端栅格标准,对齐 cockpit layout v1)。
GRID_COLUMNS = 12
#: 海绵钛四状态工艺流程(PRD 4.2:氯化 → 精制 → 还原 → 蒸馏)。
#: process_view 的 stages 必须覆盖这四个 id。
REQUIRED_STAGES = ("chlorination", "purification", "reduction", "distillation")
class LayoutError(ValueError):
"""布局资产解析/声明错误(YAML 格式错、表头缺字段等)。"""
class Severity(str, Enum):
"""问题严重度。"""
ERROR = "error" # 阻断:布局不可用(类型非法/越界/bind 缺失/状态缺失)
WARN = "warn" # 告警:可运行但不规范(重复/顺序乱)
@dataclass
class LayoutIssue:
"""单条布局校验问题(含 reason 可解释)。"""
severity: Severity
reason: str
widget_id: str = "" # 关联 widget(index 或 src/metric)
field: str = "" # 关联字段(type/x/bind/stages ...)
@property
def is_error(self) -> bool:
return self.severity is Severity.ERROR
@dataclass
class LayoutReport:
"""布局校验报告。"""
issues: List[LayoutIssue] = field(default_factory=list)
widget_count: int = 0
@property
def errors(self) -> List[LayoutIssue]:
return [i for i in self.issues if i.is_error]
@property
def passed(self) -> bool:
"""通过 = 无 ERROR(WARN 不阻断)。"""
return not any(i.is_error for i in self.issues)
def to_dict(self) -> dict:
return {
"passed": self.passed,
"widget_count": self.widget_count,
"error_count": len(self.errors),
"warn_count": len(self.issues) - len(self.errors),
"issues": [
{"severity": i.severity.value, "widget_id": i.widget_id,
"field": i.field, "reason": i.reason}
for i in self.issues
],
}
@dataclass
class WidgetSpec:
"""单个 widget 的内存模型(从 YAML 解析)。"""
index: int # 在 widgets 列表中的位置(0 起)
type: str
x: int = 0
y: int = 0
w: int = 1
h: int = 1
bind: str = "" # trend/kpi_card 绑定的 point_id
src: str = "" # process_view 的 SVG
metric: str = "" # kpi_card 的 metric
label: str = ""
description: str = ""
stages: List[Dict[str, object]] = field(default_factory=list)
# ---------------------------------------------------------------------------
# 零依赖 YAML 子集解析(复制自 impurity-forecast features.py,对齐 data-bus)
# ---------------------------------------------------------------------------
def _parse_scalar(text: str) -> str:
"""去掉标量两侧引号与行内注释。"""
t = text.split(" #", 1)[0].strip()
if len(t) >= 2 and t[0] == t[-1] and t[0] in ("'", '"'):
return t[1:-1]
return t
def _parse_flow_value(text: str):
"""解析 ``key: value`` 右侧值,支持行内 flow map ``{k: v, k: v}``。"""
t = text.split(" #", 1)[0].strip()
if t.startswith("{") and t.endswith("}"):
inner = t[1:-1].strip()
out: Dict[str, object] = {}
if not inner:
return out
for part in inner.split(","):
if ":" not in part:
raise LayoutError(f"flow map 项不是键值对:{part!r}")
k, _, v = part.partition(":")
out[k.strip()] = _parse_scalar(v)
return out
return _parse_scalar(text)
def _strip_comments(lines: List[str]) -> List[Tuple[str, int]]:
out: List[Tuple[str, int]] = []
for i, ln in enumerate(lines):
s = ln.strip()
if not s or s.startswith("#"):
continue
out.append((ln, i + 1))
return out
def _parse_node(lines: List[Tuple[str, int]], i: int, indent: int):
"""递归解析 YAML 节点(map / list / scalar)。返回 (value, next_i)。"""
text, _ = lines[i]
# ---- list 节点 ----
if text.lstrip(" ").startswith("- "):
items: List[object] = []
while i < len(lines):
t, no = lines[i]
stripped = t.lstrip(" ")
if not stripped.startswith("- "):
break
lead_j = len(t) - len(t.lstrip(" "))
if lead_j != indent:
break
item_text = stripped[2:].strip()
if not item_text:
raise LayoutError(f"cockpit.yaml 第 {no} 行:list 项为空")
if ":" in item_text:
map_indent = len(t) - len(t.lstrip(" ")) + 2
lines[i] = (" " * map_indent + item_text, no)
v, i = _parse_node(lines, i, map_indent)
items.append(v)
else:
items.append(_parse_flow_value(item_text))
i += 1
return items, i
# ---- map 节点 ----
result: Dict[str, object] = {}
while i < len(lines):
t, no = lines[i]
lead_j = len(t) - len(t.lstrip(" "))
if lead_j < indent or t.lstrip(" ").startswith("- "):
break
if lead_j > indent:
raise LayoutError(
f"cockpit.yaml 第 {no} 行缩进异常(期望 {indent},实际 {lead_j})")
if ":" not in t:
raise LayoutError(f"cockpit.yaml 第 {no} 行不是合法键值对:{t!r}")
key, _, rest = t.partition(":")
key = key.strip()
rest = rest.strip()
if rest:
result[key] = _parse_flow_value(rest)
i += 1
continue
if i + 1 >= len(lines):
raise LayoutError(f"cockpit.yaml 第 {no} 行 {key!r} 缺少值")
sub_indent = len(lines[i + 1][0]) - len(lines[i + 1][0].lstrip(" "))
if sub_indent <= indent:
raise LayoutError(f"cockpit.yaml 第 {no} 行 {key!r} 缺少值(无嵌套)")
v, i = _parse_node(lines, i + 1, sub_indent)
result[key] = v
return result, i
def _load_yaml_text(text: str) -> Dict[str, object]:
"""解析 YAML 文本为 dict(顶层必须是 map)。"""
lines = _strip_comments(text.splitlines())
if not lines:
return {}
top_indent = len(lines[0][0]) - len(lines[0][0].lstrip(" "))
value, next_i = _parse_node(lines, 0, top_indent)
if not isinstance(value, dict):
raise LayoutError("cockpit.yaml 顶层必须是 map")
if next_i < len(lines):
raise LayoutError(
f"cockpit.yaml 第 {lines[next_i][1]} 行:顶层存在多个节点")
return value
# ---------------------------------------------------------------------------
# 点位字典加载(CSV → point_id 集合)
# ---------------------------------------------------------------------------
def load_point_ids(csv_path: str) -> List[str]:
"""从点位字典 CSV 加载全部 point_id(保序,对齐 CSV point_id 列)。
CSV 表头对齐 core/edge-gateway point_dict schema(第二列 point_id)。
"""
if not os.path.isfile(csv_path):
raise LayoutError(f"点位字典 CSV 不存在:{csv_path}")
with open(csv_path, "r", encoding="utf-8") as fh:
rows = list(csv.reader(fh))
if not rows:
raise LayoutError(f"点位字典 CSV 为空:{csv_path}")
header = [c.strip() for c in rows[0]]
if "point_id" not in header:
raise LayoutError(
f"点位字典 CSV 表头缺 point_id 列:{header}")
col = header.index("point_id")
ids: List[str] = []
for i, row in enumerate(rows[1:], 2):
if len(row) <= col:
continue
pid = row[col].strip()
if pid:
ids.append(pid)
if not ids:
raise LayoutError(f"点位字典 CSV 无 point_id 数据行:{csv_path}")
return ids
# ---------------------------------------------------------------------------
# 校验器
# ---------------------------------------------------------------------------
class LayoutValidator:
"""海绵钛驾驶舱布局校验器。
Args:
layout_yaml_path: 布局资产路径(cockpit.ti.yaml)。
point_dict_csv_path: 点位字典 CSV 路径(point_dict.default.csv)。
grid_columns: 网格列数(默认 12,对齐 cockpit layout v1)。
required_stages: process_view 必须覆盖的 stage id(默认海绵钛四状态)。
"""
def __init__(
self,
layout_yaml_path: str,
point_dict_csv_path: Optional[str] = None,
grid_columns: int = GRID_COLUMNS,
required_stages: Tuple[str, ...] = REQUIRED_STAGES,
) -> None:
if grid_columns <= 0:
raise LayoutError(f"grid_columns 必须 > 0,实际 {grid_columns}")
self.layout_path = layout_yaml_path
self.point_dict_path = point_dict_csv_path
self.grid_columns = int(grid_columns)
self.required_stages = tuple(required_stages)
# ------------------------------------------------------------------
def validate(self) -> LayoutReport:
"""执行全部校验,返回报告。"""
report = LayoutReport()
# 1) 解析布局 YAML
try:
with open(self.layout_path, "r", encoding="utf-8") as fh:
data = _load_yaml_text(fh.read())
except LayoutError:
raise
except OSError as exc:
raise LayoutError(f"布局 YAML 读取失败:{self.layout_path} ({exc})") from exc
# schema 头校验
schema = str(data.get("$schema", "")).strip()
if schema != "iAOP-cockpit-layout-v1":
report.issues.append(LayoutIssue(
severity=Severity.ERROR,
field="$schema",
reason=f"$schema 应为 'iAOP-cockpit-layout-v1',实际 {schema!r}",
))
# 2) 解析 widgets
raw_widgets = data.get("widgets") or []
if not isinstance(raw_widgets, list):
report.issues.append(LayoutIssue(
severity=Severity.ERROR, field="widgets",
reason=f"widgets 必须是 list,实际 {type(raw_widgets).__name__}"))
return report
widgets = self._parse_widgets(raw_widgets, report)
report.widget_count = len(widgets)
if not widgets:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, field="widgets",
reason="布局无任何 widget"))
return report
# 3) 加载点位字典(bind 校验需要)
point_ids: Optional[set] = None
if self.point_dict_path:
try:
point_ids = set(load_point_ids(self.point_dict_path))
except LayoutError as exc:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, field="point_dict",
reason=str(exc)))
# 4) 逐 widget 校验
for w in widgets:
self._check_widget(w, point_ids, report)
# 5) process_view 四状态覆盖
self._check_process_views(widgets, report)
return report
# ------------------------------------------------------------------
def _parse_widgets(self, raw_widgets: List[object],
report: LayoutReport) -> List[WidgetSpec]:
widgets: List[WidgetSpec] = []
for idx, item in enumerate(raw_widgets):
if not isinstance(item, dict):
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=f"[{idx}]",
field="widgets",
reason=f"widgets[{idx}] 必须是 map,实际 {type(item).__name__}"))
continue
wtype = str(item.get("type", "")).strip()
widgets.append(WidgetSpec(
index=idx,
type=wtype,
x=_to_int(item.get("x"), 0),
y=_to_int(item.get("y"), 0),
w=_to_int(item.get("w"), 1),
h=_to_int(item.get("h"), 1),
bind=str(item.get("bind", "")).strip(),
src=str(item.get("src", "")).strip(),
metric=str(item.get("metric", "")).strip(),
label=str(item.get("label", "")).strip(),
description=str(item.get("description", "")).strip(),
stages=_as_list_of_dict(item.get("stages")),
))
return widgets
# ------------------------------------------------------------------
def _check_widget(self, w: WidgetSpec, point_ids: Optional[set],
report: LayoutReport) -> None:
wid = f"[{w.index}]({w.type})"
# 4a) widget 类型合法
if w.type not in ALLOWED_WIDGET_TYPES:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="type",
reason=f"非法 widget 类型 {w.type!r}(允许 {sorted(ALLOWED_WIDGET_TYPES)})"))
# 4b) 12 列网格不越界(坐标非负整数、x+w ≤ columns、h>0)
if w.x < 0 or w.y < 0:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="grid",
reason=f"坐标不能为负:x={w.x} y={w.y}"))
if w.w <= 0 or w.h <= 0:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="grid",
reason=f"w/h 必须为正整数:w={w.w} h={w.h}"))
if w.x + w.w > self.grid_columns:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="grid",
reason=f"越出 {self.grid_columns} 列网格:x={w.x}+w={w.w}"
f"={w.x + w.w} > {self.grid_columns}"))
# 4c) bind 的 point_id 必须在点位字典内(trend/kpi_card)
if w.bind:
if point_ids is not None and w.bind not in point_ids:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="bind",
reason=f"bind point_id {w.bind!r} 不在点位字典内"
f"(防模板漂移,对齐 point_dict.default.csv)"))
# ------------------------------------------------------------------
def _check_process_views(self, widgets: List[WidgetSpec],
report: LayoutReport) -> None:
"""校验 process_view 的四状态覆盖完整。"""
pv = [w for w in widgets if w.type == "process_view"]
if not pv:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, field="process_view",
reason="布局缺少 process_view(四状态工艺流程主视图必需)"))
return
covered: Dict[str, WidgetSpec] = {} # stage_id → widget
for w in pv:
wid = f"[{w.index}](process_view)"
if not w.stages:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="stages",
reason="process_view 缺少 stages 声明(四状态覆盖必需)"))
continue
stage_ids: List[str] = []
orders: List[int] = []
seen: set = set()
for st in w.stages:
sid = str(st.get("id", "")).strip()
sname = str(st.get("name", "")).strip()
if not sid:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="stages",
reason=f"stage 缺少 id(name={sname!r})"))
continue
if sid in seen:
report.issues.append(LayoutIssue(
severity=Severity.WARN, widget_id=wid, field="stages",
reason=f"stage id 重复:{sid!r}"))
continue
seen.add(sid)
stage_ids.append(sid)
covered.setdefault(sid, w)
order = st.get("order")
if order is not None:
try:
orders.append(int(order))
except (TypeError, ValueError):
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="stages",
reason=f"stage {sid!r} order 非整数:{order!r}"))
# order 单调递增校验
if orders and len(orders) == len(stage_ids):
if orders != sorted(orders):
report.issues.append(LayoutIssue(
severity=Severity.ERROR, widget_id=wid, field="stages",
reason=f"stage order 非单调递增:{orders}"))
# 必需四状态全覆盖
missing = [s for s in self.required_stages if s not in covered]
if missing:
report.issues.append(LayoutIssue(
severity=Severity.ERROR, field="stages",
reason=f"process_view stages 未覆盖必需四状态:{missing}"
f"(氯化/精制/还原/蒸馏)"))
# ---------------------------------------------------------------------------
# 辅助
# ---------------------------------------------------------------------------
def _to_int(value: object, default: int) -> int:
"""把 YAML 解析出的值(可能是 str/int)转为 int;失败返回 default。"""
if value is None or value == "":
return default
try:
return int(value)
except (TypeError, ValueError):
raise LayoutError(f"坐标值不是整数:{value!r}")
def _as_list_of_dict(value: object) -> List[Dict[str, object]]:
if not isinstance(value, list):
return []
out: List[Dict[str, object]] = []
for item in value:
if isinstance(item, dict):
out.append(item)
return out
@@ -0,0 +1,13 @@
# -*- coding: utf-8 -*-
"""测试引导:把 dashboard 测试根目录加入 sys.path,使 layout_validator 可导入。
dashboard 目录名是合法 Python 标识符,直接作为包导入;本引导把父目录
(templates/ti-cl4/dashboard)挂到 sys.path,使 ``from layout_validator import ...``
在 unittest 发现机制下可解析(与 core 模块测试引导同款)。
"""
import os
import sys
PKG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if PKG_DIR not in sys.path:
sys.path.insert(0, PKG_DIR)
@@ -0,0 +1,307 @@
# -*- coding: utf-8 -*-
"""海绵钛驾驶舱布局校验器测试(Issue #55)。
覆盖:
1. 真实 cockpit.ti.yaml + point_dict.default.csv 全部通过(端到端);
2. widget 类型合法集合(非法类型 → ERROR);
3. 12 列网格校验(越界/负坐标/非正 w/h);
4. bind point_id 在点位字典内(漂移 → ERROR);
5. process_view 四状态覆盖(缺 stage id / order 非单调 / 缺必需状态);
6. $schema 头校验;
7. YAML 解析(flow map / 嵌套);
8. 点位字典 CSV 加载(缺表头/空文件);
9. 空布局 / 边界。
"""
import os
import unittest
import _bootstrap # noqa: F401 (sys.path 挂载)
from layout_validator import (
GRID_COLUMNS,
LayoutError,
LayoutValidator,
REQUIRED_STAGES,
Severity,
load_point_ids,
)
HERE = os.path.dirname(os.path.abspath(__file__))
DASHBOARD_DIR = os.path.dirname(HERE)
LAYOUT_YAML = os.path.join(DASHBOARD_DIR, "cockpit.ti.yaml")
POINT_DICT_CSV = os.path.join(
DASHBOARD_DIR, os.pardir, "point-dict", "point_dict.default.csv")
def _write_layout(tmp_path: str, content: str) -> str:
"""把布局内容写到临时文件,返回路径。"""
path = os.path.join(tmp_path, "cockpit.test.yaml")
with open(path, "w", encoding="utf-8") as fh:
fh.write(content)
return path
def _write_point_dict(tmp_path: str, ids: list) -> str:
"""写一个最小点位字典 CSV(仅 point_id 列)。"""
path = os.path.join(tmp_path, "points.csv")
with open(path, "w", encoding="utf-8") as fh:
fh.write("device_id,point_id,name,unit,dataType,sampleRate,qualityCode,opcNode,protocol\n")
for i, pid in enumerate(ids):
fh.write(f"D{i},{pid},n,u,float,1000,true,n,simulator\n")
return path
# 最小合法布局模板(便于构造各类变形)
_VALID_LAYOUT = """\
$schema: iAOP-cockpit-layout-v1
title: 测试驾驶舱
theme: dark
widgets:
- type: process_view
src: ti_four_state.svg
x: 0
y: 0
w: 12
h: 4
description: 四状态工艺流程
stages:
- id: chlorination
name: 氯化
order: 1
- id: purification
name: 精制
order: 2
- id: reduction
name: 还原
order: 3
- id: distillation
name: 蒸馏
order: 4
- type: trend
bind: CLF-01.TEMP
x: 0
y: 4
w: 6
h: 2
description: 氯化炉温度
"""
class TestEndToEndRealAssets(unittest.TestCase):
"""真实 cockpit.ti.yaml + point_dict.default.csv 端到端校验。"""
def test_real_layout_passes(self):
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
if not report.passed:
for issue in report.errors:
print("ERROR:", issue.widget_id, issue.field, issue.reason)
self.assertTrue(report.passed, "真实布局应通过全部校验")
self.assertGreater(report.widget_count, 0)
def test_real_layout_has_process_view_with_four_stages(self):
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
# 无 stages 相关 ERROR
stage_errors = [i for i in report.errors if i.field == "stages"]
self.assertEqual(stage_errors, [])
class TestWidgetType(unittest.TestCase):
"""widget 类型合法性。"""
def test_invalid_widget_type_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
layout = _VALID_LAYOUT.replace("type: trend", "type: radar_chart")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
errors = [i for i in report.errors if i.field == "type"]
self.assertEqual(len(errors), 1)
self.assertIn("非法 widget 类型", errors[0].reason)
class TestGridBounds(unittest.TestCase):
"""12 列网格校验。"""
def test_x_plus_w_exceeds_columns(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
# trend x=10 w=6 → 16 > 12
layout = _VALID_LAYOUT.replace(
" bind: CLF-01.TEMP\n x: 0\n y: 4\n w: 6\n h: 2",
" bind: CLF-01.TEMP\n x: 10\n y: 4\n w: 6\n h: 2")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
grid_errors = [i for i in report.errors if i.field == "grid"
and "越出" in i.reason]
self.assertEqual(len(grid_errors), 1)
def test_negative_x_rejected(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
layout = _VALID_LAYOUT.replace(" x: 0\n y: 4\n w: 6\n h: 2",
" x: -1\n y: 4\n w: 6\n h: 2")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
neg = [i for i in report.errors if "坐标不能为负" in i.reason]
self.assertEqual(len(neg), 1)
def test_zero_width_rejected(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
layout = _VALID_LAYOUT.replace(" x: 0\n y: 4\n w: 6\n h: 2",
" x: 0\n y: 4\n w: 0\n h: 2")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
wh = [i for i in report.errors if "w/h 必须为正整数" in i.reason]
self.assertEqual(len(wh), 1)
class TestBindPointId(unittest.TestCase):
"""bind point_id 在点位字典内。"""
def test_bind_not_in_dict_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
path = _write_layout(td, _VALID_LAYOUT)
# 点位字典不含 CLF-01.TEMP
csv_path = _write_point_dict(td, ["OTHER-01.X"])
report = LayoutValidator(path, csv_path).validate()
bind_err = [i for i in report.errors if i.field == "bind"]
self.assertEqual(len(bind_err), 1)
self.assertIn("不在点位字典内", bind_err[0].reason)
def test_bind_in_dict_passes(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
path = _write_layout(td, _VALID_LAYOUT)
csv_path = _write_point_dict(td, ["CLF-01.TEMP"])
report = LayoutValidator(path, csv_path).validate()
bind_err = [i for i in report.errors if i.field == "bind"]
self.assertEqual(bind_err, [])
class TestProcessViewStages(unittest.TestCase):
"""process_view 四状态覆盖。"""
def test_missing_process_view_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
# 删除 process_view 块(保留 trend)
layout = """\
$schema: iAOP-cockpit-layout-v1
title: t
widgets:
- type: trend
bind: CLF-01.TEMP
x: 0
y: 0
w: 6
h: 2
"""
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
pv_err = [i for i in report.errors if i.field == "process_view"]
self.assertEqual(len(pv_err), 1)
def test_missing_required_stage_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
# 删除 distillation stage
layout = _VALID_LAYOUT.replace(
" - id: distillation\n name: 蒸馏\n order: 4\n", "")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
missing = [i for i in report.errors if "未覆盖必需四状态" in i.reason]
self.assertEqual(len(missing), 1)
self.assertIn("distillation", missing[0].reason)
def test_non_monotonic_order_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
# 把 reduction order 改为 5(> distillation 的 4)→ 非单调
layout = _VALID_LAYOUT.replace(" - id: reduction\n name: 还原\n order: 3",
" - id: reduction\n name: 还原\n order: 5")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
order_err = [i for i in report.errors if "order 非单调递增" in i.reason]
self.assertEqual(len(order_err), 1)
def test_duplicate_stage_id_warn(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
# 重复 chlorination(覆盖必需状态校验仍过,但 WARN 重复)
layout = _VALID_LAYOUT + """\
"""
# 构造一个有重复 stage 的 process_view(替换 stages 块)
dup_layout = _VALID_LAYOUT.replace(
" - id: distillation\n name: 蒸馏\n order: 4",
" - id: distillation\n name: 蒸馏\n order: 4\n"
" - id: chlorination\n name: 氯化2\n order: 5")
path = _write_layout(td, dup_layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
dup = [i for i in report.issues if "stage id 重复" in i.reason]
self.assertEqual(len(dup), 1)
class TestSchemaHeader(unittest.TestCase):
"""$schema 头校验。"""
def test_wrong_schema_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
layout = _VALID_LAYOUT.replace("iAOP-cockpit-layout-v1", "some-other-schema")
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
schema_err = [i for i in report.errors if i.field == "$schema"]
self.assertEqual(len(schema_err), 1)
class TestPointDictLoader(unittest.TestCase):
"""点位字典 CSV 加载。"""
def test_load_point_ids(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
csv_path = _write_point_dict(td, ["A.X", "B.Y"])
ids = load_point_ids(csv_path)
self.assertEqual(ids, ["A.X", "B.Y"])
def test_missing_csv_raises(self):
with self.assertRaises(LayoutError):
load_point_ids("/nonexistent/points.csv")
def test_csv_missing_point_id_column_raises(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
path = os.path.join(td, "bad.csv")
with open(path, "w", encoding="utf-8") as fh:
fh.write("device_id,name\nD1,n\n")
with self.assertRaises(LayoutError):
load_point_ids(path)
class TestReportExport(unittest.TestCase):
"""报告序列化 + 边界。"""
def test_empty_layout_error(self):
import tempfile
with tempfile.TemporaryDirectory() as td:
layout = """\
$schema: iAOP-cockpit-layout-v1
title: t
widgets: []
"""
path = _write_layout(td, layout)
report = LayoutValidator(path, _write_point_dict(td, ["CLF-01.TEMP"])).validate()
self.assertFalse(report.passed)
def test_report_to_dict(self):
report = LayoutValidator(LAYOUT_YAML, POINT_DICT_CSV).validate()
d = report.to_dict()
self.assertEqual(d["passed"], True)
self.assertIn("widget_count", d)
self.assertEqual(d["error_count"], 0)
if __name__ == "__main__":
unittest.main()