Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e41e2a5a3f |
@@ -62,11 +62,7 @@ python -m unittest discover -s tests
|
||||
## 模板化说明(换行业只改配置,不改代码)
|
||||
|
||||
- 点位范围 / 采样率 / 量纲 / 协议:由**点位字典 CSV** 驱动(模板 → 行业点位集)。
|
||||
- 采样率(issue #23):点位字典 CSV 的 `sampleRate` 列逐点位控制采集频率,
|
||||
引擎以 `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`,随配置模板变化。
|
||||
- 新增协议:实现 `drivers/base.py` 的 `Driver` 子类并注册即可,引擎与上行链路零改动。
|
||||
|
||||
@@ -2,10 +2,7 @@
|
||||
"""周期采集调度引擎 —— 只读采集 + 背压保护 + 健康度上报。
|
||||
|
||||
模板化封装要点:
|
||||
- 采集配置全部外置(gateway.yaml + 点位字典 CSV),引擎不关心具体协议;
|
||||
- 采样率外置(issue #23):每个点位按点位字典 CSV 的 sampleRate 列调度,
|
||||
引擎以 gateway.yaml 的 interval_ms 为基准 tick,sampleRate > interval_ms 的
|
||||
点位按比例降频读取(去硬编码:点位采样率完全由模板配置驱动);
|
||||
- 采集配置全部外置(gateway.yaml),引擎不关心具体协议;
|
||||
- 点位按驱动实例的 device 匹配规则分组,一次 tick 内按驱动批量读取;
|
||||
- 严格只读:引擎只调用 Driver.read_points(),不存在任何控制指令路径;
|
||||
- 背压保护:未确认(spool 待上行)记录超过阈值时丢弃新样本并计入丢失,
|
||||
@@ -58,28 +55,6 @@ class CollectorEngine:
|
||||
self._stop = threading.Event()
|
||||
self._thread: Optional[threading.Thread] = None
|
||||
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]:
|
||||
@@ -117,16 +92,13 @@ class CollectorEngine:
|
||||
本轮成功读到的样本数。
|
||||
"""
|
||||
started = time.monotonic()
|
||||
# 本轮 tick 递增 + 取到期待集(按点位 sampleRate 调度,issue #23)
|
||||
self._tick += 1
|
||||
due = self._due_points()
|
||||
expected = len(due)
|
||||
expected = len(self.point_dict.points)
|
||||
got = 0
|
||||
samples: List[dict] = []
|
||||
|
||||
# 1) 按驱动分组读取(只读)
|
||||
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)
|
||||
if drv is None:
|
||||
continue
|
||||
@@ -140,8 +112,6 @@ class CollectorEngine:
|
||||
self.metrics.record_round(time.monotonic() - started, expected, got, failed=True)
|
||||
return got
|
||||
for p in points:
|
||||
# 无论本轮是否读到,都推进该点位采样调度(降频点位不连续空读)
|
||||
self._next_due_tick[p.point_id] = self._tick + self._ticks_per_sample(p)
|
||||
value = values.get(p.point_id)
|
||||
if value is None:
|
||||
continue # 未读到 → 计入丢失
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
# iAOP 边缘采集网关 —— 模板配置示例(Template-Ti 一期:氯化车间/海绵钛)
|
||||
# 换行业模板时只需修改本文件 + 点位字典 CSV,网关代码零改动。
|
||||
collector:
|
||||
# 采集周期(毫秒)基准 tick:600 点位 1Hz 即 1000。
|
||||
# 点位级采样率由点位字典 CSV 的 sampleRate 列驱动(issue #23):
|
||||
# sampleRate ≤ interval_ms 的点位每 tick 采集;> interval_ms 的点位按比例降频
|
||||
# (如 sampleRate=5000 且 interval_ms=1000 → 每 5 tick 采一次),去硬编码。
|
||||
# 采集周期(毫秒):600 点位 1Hz 即 1000
|
||||
interval_ms: 1000
|
||||
# 背压保护:spool 待上行记录上限,超过则丢弃新样本并计入丢失率
|
||||
max_pending: 100000
|
||||
@@ -13,24 +10,13 @@ collector:
|
||||
cache_limit_bytes: 536870912 # 512MB
|
||||
# 协议可插拔驱动插槽(protocol 注册表见 drivers/__init__.py)
|
||||
drivers:
|
||||
# 和利时 DCS —— OPC UA 只读(推荐;支持用户认证参数化,issue #25)
|
||||
- protocol: hollysys
|
||||
# 和利时 DCS —— OPC UA 只读
|
||||
- protocol: opcua
|
||||
device_prefixes: ["CLF"] # 设备编号前缀路由(CLF-01, CLF-02, ...)
|
||||
config:
|
||||
mode: ua # ua(OPC UA)| da(OPC DA COM 接口)
|
||||
endpoint: "opc.tcp://10.20.1.10:4840"
|
||||
security: "Basic256Sha256" # None | Basic256Sha256 等安全策略
|
||||
username: "iaop_read" # 和利时 UA 服务用户认证(只读账号)
|
||||
password: "******"
|
||||
security: "None"
|
||||
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)
|
||||
- protocol: 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.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.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_B,泵B频率,Hz,float,1000,true,DB100.4.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
|
||||
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 .energy_driver import EnergyDriver
|
||||
from .hollysys_driver import HollysysDcsDriver
|
||||
from .modbus_driver import ModbusDriver
|
||||
from .opcua_driver import OpcUaDriver
|
||||
from .s7_driver import S7Driver
|
||||
@@ -21,7 +20,6 @@ from .weighing_driver import WeighingDriver
|
||||
|
||||
_DRIVER_REGISTRY: Dict[str, Type["Driver"]] = {
|
||||
"opcua": OpcUaDriver,
|
||||
"hollysys": HollysysDcsDriver,
|
||||
"s7": S7Driver,
|
||||
"modbus": ModbusDriver,
|
||||
"weighing": WeighingDriver,
|
||||
@@ -32,7 +30,6 @@ _DRIVER_REGISTRY: Dict[str, Type["Driver"]] = {
|
||||
__all__ = [
|
||||
"Driver",
|
||||
"OpcUaDriver",
|
||||
"HollysysDcsDriver",
|
||||
"S7Driver",
|
||||
"ModbusDriver",
|
||||
"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)
|
||||
self.endpoint: str = self.config.get("endpoint", "")
|
||||
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
|
||||
|
||||
def connect(self) -> None:
|
||||
@@ -36,19 +34,7 @@ class OpcUaDriver(Driver):
|
||||
if not self.endpoint:
|
||||
raise ConnectionError("OPC UA 驱动缺少配置: drivers.opcua.endpoint")
|
||||
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()
|
||||
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)
|
||||
|
||||
def read_points(self, points: List[Point]) -> Dict[str, SampleValue]:
|
||||
|
||||
@@ -146,52 +146,6 @@ class EngineMetricsTest(unittest.TestCase):
|
||||
self.assertLessEqual(metrics.p99_latency(), 0.6)
|
||||
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__":
|
||||
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()
|
||||
@@ -4,29 +4,27 @@
|
||||
对应 PRD 5.3「③ AI 模型框架」与 EPIC #5(内核平台化改造)。
|
||||
|
||||
当前已交付(自包含,不依赖未合并分支):
|
||||
- ``anomaly_detection``:异常检测模型模板化(固定主干 + 配方加载),
|
||||
issue #37。同一主干代码不变,切换行业/工况只改配方(声明式 JSON
|
||||
- ``quality_forecast``:质量预测模型模板化(固定主干 + 配方加载),
|
||||
issue #36。同一主干代码不变,切换行业/工况只改配方(声明式 JSON
|
||||
超参包)——对齐 PRD 5.3「固定主干 + 可配置超参」默认模式。
|
||||
|
||||
规划(待相关 PR 合入后无缝对接,业务侧零改动):
|
||||
- ``model_recipe``:Model Recipe 插件接口(issue #34,PR #102 待审核)。
|
||||
``anomaly_detection`` 的主干届时可注册为 ``register_backbone`` 的一个
|
||||
``quality_forecast`` 的主干届时可注册为 ``register_backbone`` 的一个
|
||||
具名主干,配方可映射为一条 ``ModelRecipe``。
|
||||
- ``quality_forecast``:质量预测模型模板化(issue #36,PR #103 待审核)。
|
||||
与本模块共享「主干工厂 + Recipe + 验收口径」骨架。
|
||||
"""
|
||||
from model_framework.anomaly_detection import (
|
||||
AnomalyDetectionError,
|
||||
AnomalyDetectionModel,
|
||||
from model_framework.quality_forecast import (
|
||||
Accuracy,
|
||||
BACKBONES,
|
||||
Metrics,
|
||||
ModelHandle,
|
||||
QualityForecastError,
|
||||
QualityForecastModel,
|
||||
Recipe,
|
||||
build_from_recipe,
|
||||
iforest_backbone,
|
||||
dnn_backbone,
|
||||
gbdt_backbone,
|
||||
list_sample_recipes,
|
||||
load_recipe,
|
||||
lof_backbone,
|
||||
register_backbone,
|
||||
sample_recipe_path,
|
||||
stub_backbone,
|
||||
@@ -34,14 +32,14 @@ from model_framework.anomaly_detection import (
|
||||
|
||||
__all__ = [
|
||||
"Recipe",
|
||||
"Metrics",
|
||||
"AnomalyDetectionError",
|
||||
"AnomalyDetectionModel",
|
||||
"Accuracy",
|
||||
"QualityForecastError",
|
||||
"QualityForecastModel",
|
||||
"ModelHandle",
|
||||
"BACKBONES",
|
||||
"register_backbone",
|
||||
"iforest_backbone",
|
||||
"lof_backbone",
|
||||
"gbdt_backbone",
|
||||
"dnn_backbone",
|
||||
"stub_backbone",
|
||||
"load_recipe",
|
||||
"build_from_recipe",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""异常检测模型模板化 sanity 检查(无构建环境下的离线基本验证)。
|
||||
"""质量预测模型模板化 sanity 检查(无构建环境下的离线基本验证)。
|
||||
|
||||
验证 PRD 5.3 验收口径「同框架加载 Ti / 树脂两套配方均跑通」:
|
||||
1. 两套样例配方均可被 ``build_from_recipe`` 加载;
|
||||
@@ -16,7 +16,7 @@ HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
if HERE not in sys.path:
|
||||
sys.path.insert(0, HERE)
|
||||
|
||||
from anomaly_detection import ( # noqa: E402
|
||||
from quality_forecast import ( # noqa: E402
|
||||
build_from_recipe,
|
||||
list_sample_recipes,
|
||||
sample_recipe_path,
|
||||
@@ -36,17 +36,14 @@ def main() -> int:
|
||||
for r in required:
|
||||
try:
|
||||
m = build_from_recipe(sample_recipe_path(r))
|
||||
# 用配方声明的特征数构造演示数据(含少量离群点)
|
||||
# 用配方声明的特征数构造演示数据
|
||||
n_feat = len(m.recipe_meta["feature_columns"]) or 2
|
||||
X = [[float(i + j) for j in range(n_feat)] for i in range(30)]
|
||||
# 注入 3 个明显离群点
|
||||
for k in range(3):
|
||||
X.append([100.0 + k for _ in range(n_feat)])
|
||||
y_true = [0] * 30 + [1] * 3
|
||||
m.fit(X)
|
||||
X = [[float(i + j) for j in range(n_feat)] for i in range(10)]
|
||||
y = [float(i % 4) + 1.0 for i in range(10)]
|
||||
m.fit(X, y)
|
||||
preds = m.predict(X)
|
||||
assert len(preds) == len(y_true), "预测长度异常"
|
||||
m.evaluate(X, y_true)
|
||||
assert len(preds) == len(y), "预测长度异常"
|
||||
m.evaluate(X, y)
|
||||
models[r] = m
|
||||
except Exception as exc: # pragma: no cover - 诊断输出
|
||||
failures.append(f"{r} 加载/训练/评估失败:{exc!r}")
|
||||
|
||||
@@ -1,673 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""异常检测模型模板化(固定主干 + 配方加载)。
|
||||
|
||||
对应 issue #37(父 EPIC #5「③ AI 模型框架 配置化重构」、PRD 5.3
|
||||
「网络结构策略 / 模板化技术路径」)。
|
||||
|
||||
PRD 5.3 的核心诉求
|
||||
------------------
|
||||
|
||||
异常检测属于 PRD 5.3「四类模型模板」之一(③ 异常检测),同样采用
|
||||
「**固定主干 + 可配置超参**」默认模式:同一主干代码不变,切换行业 /
|
||||
工况只改 *配方(recipe)* —— 一个声明式 JSON 超参包。本模块与
|
||||
``quality_forecast``(issue #36)同源,共享「主干工厂 + Recipe + 验收口径」
|
||||
骨架,但任务语义是无监督异常检测:
|
||||
|
||||
* **输入**:多维工艺特征时序点(无需标注,无监督);
|
||||
* **输出**:每个样本的异常分数(越大越异常)+ 二值异常标签(由阈值决定);
|
||||
* **验收**:检出率 / 误报率 / F1(PRD 5.3 / 第 6 章里程碑:关键异常检出率
|
||||
≥ 95%、误报率 ≤ 5%)。
|
||||
|
||||
本模块交付什么
|
||||
--------------
|
||||
|
||||
1. **``AnomalyDetectionModel``**:固定主干的异常检测模型。默认主干是
|
||||
``iforest``(隔离森林,PRD 5.3 推荐的无监督异常检测默认结构);当运行
|
||||
环境存在 ``sklearn`` 时自动升级为真实实现,否则退化为确定性 stub,
|
||||
保证边缘 / 离线 / CI 环境可加载与校验——与 issue #34 / #36 的
|
||||
「numpy/sklearn 可选」策略一致。
|
||||
2. **``Recipe`` 配方加载器**:声明式 JSON 超参包(``load_recipe`` /
|
||||
``build_from_recipe``)。配方描述「主干类型 + 超参 + 特征列 + 阈值策略
|
||||
+ 验收口径」,业务侧只 ``build_from_recipe(path)`` 一行即可拿到一个
|
||||
可训练 / 可推理的异常检测模型——切换模板仅改配方,模型代码零改动。
|
||||
3. **``Metrics`` 验收口径**:PRD 5.3 / 第 6 章里程碑要求「关键异常检出率
|
||||
≥ 95%、误报率 ≤ 5%」。``evaluate`` 直接给出检出率 / 误报率 / 精确率 /
|
||||
召回率 / F1,便于配置台与 UAT 直接读取。
|
||||
4. **样例配方(``samples/`` JSON)**:Ti(海绵钛氯化车间炉层杂质预警)+
|
||||
树脂两套异常检测超参包样例,验证「同框架加载两套配方均跑通」的验收
|
||||
口径。
|
||||
|
||||
与 issue #34 ``model_recipe`` / #36 ``quality_forecast`` 的关系
|
||||
--------------------------------------------------------------
|
||||
|
||||
接口风格对齐 #34 的 ``ModelHandle`` / ``ModelRecipe``(``fit`` /
|
||||
``decision_function`` / ``to_dict``、不可变声明式数据对象),以及 #36
|
||||
的「主干工厂注册表 + Recipe + 验收口径」骨架。本模块**自包含、不依赖
|
||||
#34 / #36 未合并分支**,待二者合入后,异常检测主干可平滑注册为
|
||||
``register_backbone("iforest", ...)`` 的一个具名主干,配方可映射为一条
|
||||
``ModelRecipe``——届时本模块零业务侧改动。
|
||||
|
||||
零外部强依赖
|
||||
------------
|
||||
|
||||
* 主干默认走纯 Python stub(``StubBackbone``):无 sklearn 时也能加载、
|
||||
构造、(伪)拟合与打分,保证 CI 可加载与校验;
|
||||
* 存在 ``sklearn`` 时,``iforest`` 主干自动升级为真实
|
||||
``IsolationForest`` 实现,其余情况退化为 stub,不影响接口契约与测试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
__all__ = [
|
||||
# 数据对象
|
||||
"Recipe",
|
||||
"Metrics",
|
||||
"AnomalyDetectionError",
|
||||
# 模型
|
||||
"AnomalyDetectionModel",
|
||||
"ModelHandle",
|
||||
# 主干工厂
|
||||
"BACKBONES",
|
||||
"register_backbone",
|
||||
"iforest_backbone",
|
||||
"lof_backbone",
|
||||
"stub_backbone",
|
||||
# 配方 API
|
||||
"load_recipe",
|
||||
"build_from_recipe",
|
||||
"list_sample_recipes",
|
||||
"sample_recipe_path",
|
||||
]
|
||||
|
||||
|
||||
class AnomalyDetectionError(Exception):
|
||||
"""异常检测模板化层的统一异常(配方非法 / 主干未注册 / 校验失败)。"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配方(Recipe):声明式超参包,不可变数据对象
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: PRD 5.3 允许的固定主干类型(默认 iforest,PRD 5.3 推荐无监督异常检测默认结构)
|
||||
ALLOWED_BACKBONES = ("iforest", "lof", "stub")
|
||||
|
||||
#: PRD 5.3 允许的阈值策略:contamination(污染率)分数阈值;sigma(Nσ 法则)
|
||||
ALLOWED_THRESHOLD_POLICIES = ("contamination", "sigma")
|
||||
|
||||
#: PRD 5.3 / 第 6 章里程碑:关键异常检出率(召回率)验收线 ≥ 95%
|
||||
DEFAULT_RECALL_FLOOR = 0.95
|
||||
|
||||
#: PRD 5.3 / 第 6 章里程碑:异常误报率上限 ≤ 5%(即特异性 ≥ 0.95)
|
||||
DEFAULT_FALSE_ALARM_CEIL = 0.05
|
||||
|
||||
#: 默认污染率(预期异常比例),对齐 sklearn IsolationForest 默认值
|
||||
DEFAULT_CONTAMINATION = 0.05
|
||||
|
||||
#: 默认 Nσ 法则阈值(3σ 覆盖 ~99.7% 正常区)
|
||||
DEFAULT_SIGMA = 3.0
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Recipe:
|
||||
"""异常检测配方(声明式超参包)。
|
||||
|
||||
一个 Recipe 描述「用什么固定主干 + 如何从超参构造一个可训练 / 可推理
|
||||
的异常检测模型 + 用哪些特征列 + 阈值策略 + 验收口径」。它是不可变数据
|
||||
对象,``to_dict`` / ``from_dict`` 可序列化往返,便于配置台展示与审计。
|
||||
|
||||
切换行业 / 工况只改 Recipe,模型代码(``AnomalyDetectionModel``)零改动
|
||||
——对齐 PRD 5.3「固定主干 + 可配置超参」默认模式。
|
||||
"""
|
||||
|
||||
name: str
|
||||
backbone: str = "iforest"
|
||||
hyperparams: Dict[str, Any] = field(default_factory=dict)
|
||||
feature_columns: Tuple[str, ...] = field(default_factory=tuple)
|
||||
threshold_policy: str = "contamination"
|
||||
contamination: float = DEFAULT_CONTAMINATION
|
||||
sigma: float = DEFAULT_SIGMA
|
||||
recall_floor: float = DEFAULT_RECALL_FLOOR
|
||||
false_alarm_ceil: float = DEFAULT_FALSE_ALARM_CEIL
|
||||
industry: str = ""
|
||||
notes: str = ""
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.name:
|
||||
raise AnomalyDetectionError("Recipe 缺少 name")
|
||||
if self.backbone not in ALLOWED_BACKBONES:
|
||||
raise AnomalyDetectionError(
|
||||
f"非法主干类型 {self.backbone!r},允许:{ALLOWED_BACKBONES}")
|
||||
if self.threshold_policy not in ALLOWED_THRESHOLD_POLICIES:
|
||||
raise AnomalyDetectionError(
|
||||
f"非法阈值策略 {self.threshold_policy!r},"
|
||||
f"允许:{ALLOWED_THRESHOLD_POLICIES}")
|
||||
if not (0.0 < self.contamination < 1.0):
|
||||
raise AnomalyDetectionError(
|
||||
f"contamination 越界:{self.contamination}(应在 (0,1))")
|
||||
if self.sigma <= 0:
|
||||
raise AnomalyDetectionError(
|
||||
f"sigma 非法:{self.sigma}(应 > 0)")
|
||||
if not (0.0 <= self.recall_floor <= 1.0):
|
||||
raise AnomalyDetectionError(
|
||||
f"recall_floor 越界:{self.recall_floor}(应在 [0,1])")
|
||||
if not (0.0 <= self.false_alarm_ceil <= 1.0):
|
||||
raise AnomalyDetectionError(
|
||||
f"false_alarm_ceil 越界:{self.false_alarm_ceil}(应在 [0,1])")
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"backbone": self.backbone,
|
||||
"hyperparams": dict(self.hyperparams),
|
||||
"feature_columns": list(self.feature_columns),
|
||||
"threshold_policy": self.threshold_policy,
|
||||
"contamination": self.contamination,
|
||||
"sigma": self.sigma,
|
||||
"recall_floor": self.recall_floor,
|
||||
"false_alarm_ceil": self.false_alarm_ceil,
|
||||
"industry": self.industry,
|
||||
"notes": self.notes,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "Recipe":
|
||||
try:
|
||||
return cls(
|
||||
name=data["name"],
|
||||
backbone=data.get("backbone", "iforest"),
|
||||
hyperparams=dict(data.get("hyperparams", {})),
|
||||
feature_columns=tuple(data.get("feature_columns", [])),
|
||||
threshold_policy=data.get(
|
||||
"threshold_policy", "contamination"),
|
||||
contamination=float(
|
||||
data.get("contamination", DEFAULT_CONTAMINATION)),
|
||||
sigma=float(data.get("sigma", DEFAULT_SIGMA)),
|
||||
recall_floor=float(
|
||||
data.get("recall_floor", DEFAULT_RECALL_FLOOR)),
|
||||
false_alarm_ceil=float(
|
||||
data.get("false_alarm_ceil", DEFAULT_FALSE_ALARM_CEIL)),
|
||||
industry=data.get("industry", ""),
|
||||
notes=data.get("notes", ""),
|
||||
)
|
||||
except KeyError as exc: # pragma: no cover - 防御性
|
||||
raise AnomalyDetectionError(
|
||||
f"配方缺少必填字段:{exc}") from exc
|
||||
|
||||
|
||||
def load_recipe(path: str) -> Recipe:
|
||||
"""从 JSON 文件加载一个异常检测配方。
|
||||
|
||||
配方 JSON 结构见 ``Recipe.to_dict``;样例见 ``samples/``。
|
||||
"""
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
if not isinstance(data, dict):
|
||||
raise AnomalyDetectionError(f"配方根必须是对象:{path}")
|
||||
return Recipe.from_dict(data)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 主干工厂:固定主干网络(iforest / lof / stub)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ModelHandle:
|
||||
"""统一模型句柄:fit / decision_function / to_dict,与硬件和具体库无关。
|
||||
|
||||
业务代码只持有 ``ModelHandle``,不感知底层是 sklearn 还是 stub。
|
||||
|
||||
约定 ``decision_function`` 返回**异常分数**:**越大越异常**(与
|
||||
sklearn ``score_samples`` 取负号一致),便于阈值策略统一处理。
|
||||
"""
|
||||
|
||||
def __init__(self, backbone: str, params: Dict[str, Any],
|
||||
fitted: bool = False, meta: Optional[Dict[str, Any]] = None):
|
||||
self.backbone = backbone
|
||||
self.params = dict(params)
|
||||
self._fitted = fitted
|
||||
self.meta: Dict[str, Any] = dict(meta or {})
|
||||
|
||||
@property
|
||||
def fitted(self) -> bool:
|
||||
return self._fitted
|
||||
|
||||
def fit(self, X: Sequence[Sequence[float]]) -> "ModelHandle":
|
||||
"""拟合主干(无监督,仅需 X)。"""
|
||||
X = list(X)
|
||||
if not X:
|
||||
raise AnomalyDetectionError("训练数据为空")
|
||||
self._fit_impl(X)
|
||||
self._fitted = True
|
||||
return self
|
||||
|
||||
# 子类/工厂填充
|
||||
def _fit_impl(self, X: Sequence[Sequence[float]]) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def decision_function(
|
||||
self, X: Sequence[Sequence[float]]) -> List[float]:
|
||||
"""返回每个样本的异常分数(越大越异常)。"""
|
||||
if not self._fitted:
|
||||
raise AnomalyDetectionError("模型未拟合,无法打分")
|
||||
return [self._score_one(list(row)) for row in X]
|
||||
|
||||
def _score_one(self, row: Sequence[float]) -> float:
|
||||
raise NotImplementedError
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"backbone": self.backbone,
|
||||
"params": dict(self.params),
|
||||
"fitted": self._fitted,
|
||||
"meta": dict(self.meta),
|
||||
}
|
||||
|
||||
|
||||
class _StubBackbone(ModelHandle):
|
||||
"""确定性 stub 主干:无 sklearn 时的保底实现。
|
||||
|
||||
拟合阶段记录每维特征的均值与标准差;打分取各维偏离均值的标准差倍数
|
||||
之和(马氏距离的简化版),保证可复现、可校验、可对比,便于 CI 与
|
||||
配置台预览。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="stub", params=params)
|
||||
self._means: List[float] = []
|
||||
self._stds: List[float] = []
|
||||
|
||||
def _fit_impl(self, X) -> None:
|
||||
n_feat = len(X[0])
|
||||
self._means = [0.0] * n_feat
|
||||
self._stds = [1.0] * n_feat
|
||||
for j in range(n_feat):
|
||||
col = [float(row[j]) for row in X]
|
||||
mean = sum(col) / len(col)
|
||||
var = sum((v - mean) ** 2 for v in col) / len(col)
|
||||
self._means[j] = mean
|
||||
self._stds[j] = math.sqrt(var) or 1.0
|
||||
self.meta.update({"n_features": n_feat})
|
||||
|
||||
def _score_one(self, row) -> float:
|
||||
# 各维偏离均值的标准差倍数之和(≥0,越大越异常)
|
||||
total = 0.0
|
||||
for j, v in enumerate(row):
|
||||
total += abs(float(v) - self._means[j]) / (self._stds[j] or 1.0)
|
||||
return total
|
||||
|
||||
|
||||
class _SklearnIForestBackbone(ModelHandle):
|
||||
"""真实隔离森林主干(sklearn IsolationForest)。
|
||||
|
||||
仅当运行环境存在 sklearn 时启用;与 stub 接口完全一致。
|
||||
``decision_function`` 对 sklearn ``score_samples`` 取负号,
|
||||
统一为「越大越异常」。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="iforest", params=params)
|
||||
from sklearn.ensemble import IsolationForest # type: ignore
|
||||
self._Clz = IsolationForest
|
||||
self._model: Any = None
|
||||
|
||||
def _fit_impl(self, X) -> None:
|
||||
kw = {
|
||||
"n_estimators": int(self.params.get("n_estimators", 100)),
|
||||
"max_samples": self.params.get("max_samples", "auto"),
|
||||
"contamination": float(
|
||||
self.params.get("contamination", "auto")),
|
||||
"random_state": int(self.params.get("random_state", 42)),
|
||||
}
|
||||
self._model = self._Clz(**kw)
|
||||
self._model.fit(list(X))
|
||||
# 记录实际生效的关键超参(max_samples 可能是 'auto')
|
||||
self.meta.update({"n_estimators": kw["n_estimators"],
|
||||
"random_state": kw["random_state"]})
|
||||
|
||||
def _score_one(self, row) -> float:
|
||||
# score_samples 越大越正常,取负号统一为「越大越异常」
|
||||
return float(-self._model.score_samples([list(row)])[0])
|
||||
|
||||
|
||||
class _SklearnLOFBackbone(ModelHandle):
|
||||
"""真实局部离群因子主干(sklearn LocalOutlierFactor)。
|
||||
|
||||
PRD 5.3 备选结构;仅当运行环境存在 sklearn 时启用。 novelty=True 以
|
||||
支持 predict / score_samples 对新样本打分。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="lof", params=params)
|
||||
from sklearn.neighbors import LocalOutlierFactor # type: ignore
|
||||
self._Clz = LocalOutlierFactor
|
||||
self._model: Any = None
|
||||
|
||||
def _fit_impl(self, X) -> None:
|
||||
kw = {
|
||||
"n_neighbors": int(self.params.get("n_neighbors", 20)),
|
||||
"contamination": float(
|
||||
self.params.get("contamination", "auto")),
|
||||
"novelty": True,
|
||||
}
|
||||
self._model = self._Clz(**kw)
|
||||
self._model.fit(list(X))
|
||||
self.meta.update({"n_neighbors": kw["n_neighbors"]})
|
||||
|
||||
def _score_one(self, row) -> float:
|
||||
return float(-self._model.score_samples([list(row)])[0])
|
||||
|
||||
|
||||
def _has_sklearn() -> bool:
|
||||
try:
|
||||
import sklearn # noqa: F401
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def stub_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""stub 主干工厂(恒可用)。"""
|
||||
return _StubBackbone(hyperparams)
|
||||
|
||||
|
||||
def iforest_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""iforest 主干工厂:有 sklearn 用真实隔离森林,否则退化为 stub。
|
||||
|
||||
PRD 5.3 推荐的无监督异常检测默认结构(隔离森林)。
|
||||
"""
|
||||
if _has_sklearn():
|
||||
return _SklearnIForestBackbone(hyperparams)
|
||||
# 无 sklearn:退化 stub 但保留声明主干名,便于审计
|
||||
h = _StubBackbone(hyperparams)
|
||||
h.meta["degraded_from"] = "iforest"
|
||||
return h
|
||||
|
||||
|
||||
def lof_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""lof 主干工厂:有 sklearn 用真实 LOF,否则退化为 stub。"""
|
||||
if _has_sklearn():
|
||||
return _SklearnLOFBackbone(hyperparams)
|
||||
h = _StubBackbone(hyperparams)
|
||||
h.meta["degraded_from"] = "lof"
|
||||
return h
|
||||
|
||||
|
||||
#: 主干注册表:新增结构走 ``register_backbone`` 注册,不动内核
|
||||
#: (对齐 PRD 5.3「新增结构走插件注册」理念,风格对齐 #34 / #36)。
|
||||
BACKBONES: Dict[str, Any] = {
|
||||
"iforest": iforest_backbone,
|
||||
"lof": lof_backbone,
|
||||
"stub": stub_backbone,
|
||||
}
|
||||
|
||||
|
||||
def register_backbone(name: str, factory: Any) -> None:
|
||||
"""注册一个新主干工厂 ``factory(hyperparams) -> ModelHandle``。
|
||||
|
||||
允许高级行业模板声明非默认主干(如自研流式异常检测),不动内核——对齐
|
||||
PRD「新增结构走插件注册而非改内核」。
|
||||
"""
|
||||
if not callable(factory):
|
||||
raise AnomalyDetectionError("主干工厂必须是可调用对象")
|
||||
BACKBONES[name] = factory
|
||||
|
||||
|
||||
def _build_backbone(backbone: str,
|
||||
hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
factory = BACKBONES.get(backbone)
|
||||
if factory is None:
|
||||
raise AnomalyDetectionError(
|
||||
f"未注册的主干类型:{backbone!r},已注册:{list(BACKBONES)}")
|
||||
return factory(hyperparams)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 异常检测模型:固定主干 + 配方加载
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class AnomalyDetectionModel:
|
||||
"""异常检测模型(固定主干 + 配方加载)。
|
||||
|
||||
业务侧两种等价入口:
|
||||
|
||||
1. 直接构造(显式主干)::
|
||||
|
||||
m = AnomalyDetectionModel(backbone="iforest", hyperparams={...})
|
||||
|
||||
2. 配方加载(推荐,切换模板仅改配方)::
|
||||
|
||||
m = build_from_recipe(
|
||||
"templates/.../anomaly-detection/recipe.ti.json")
|
||||
"""
|
||||
|
||||
def __init__(self,
|
||||
backbone: str = "iforest",
|
||||
hyperparams: Optional[Dict[str, Any]] = None,
|
||||
feature_columns: Optional[Sequence[str]] = None,
|
||||
threshold_policy: str = "contamination",
|
||||
contamination: float = DEFAULT_CONTAMINATION,
|
||||
sigma: float = DEFAULT_SIGMA,
|
||||
recall_floor: float = DEFAULT_RECALL_FLOOR,
|
||||
false_alarm_ceil: float = DEFAULT_FALSE_ALARM_CEIL):
|
||||
self.threshold_policy = threshold_policy
|
||||
self.contamination = contamination
|
||||
self.sigma = sigma
|
||||
self.recall_floor = recall_floor
|
||||
self.false_alarm_ceil = false_alarm_ceil
|
||||
self.recipe_meta: Dict[str, Any] = {
|
||||
"backbone": backbone,
|
||||
"hyperparams": dict(hyperparams or {}),
|
||||
"feature_columns": list(feature_columns or []),
|
||||
"threshold_policy": threshold_policy,
|
||||
"contamination": contamination,
|
||||
"sigma": sigma,
|
||||
"recall_floor": recall_floor,
|
||||
"false_alarm_ceil": false_alarm_ceil,
|
||||
}
|
||||
self._handle: ModelHandle = _build_backbone(
|
||||
backbone, hyperparams or {})
|
||||
self._threshold: Optional[float] = None
|
||||
|
||||
@classmethod
|
||||
def from_recipe(cls, recipe: Recipe) -> "AnomalyDetectionModel":
|
||||
"""从一个 ``Recipe`` 构造模型(推荐入口)。"""
|
||||
m = cls(
|
||||
backbone=recipe.backbone,
|
||||
hyperparams=recipe.hyperparams,
|
||||
feature_columns=recipe.feature_columns,
|
||||
threshold_policy=recipe.threshold_policy,
|
||||
contamination=recipe.contamination,
|
||||
sigma=recipe.sigma,
|
||||
recall_floor=recipe.recall_floor,
|
||||
false_alarm_ceil=recipe.false_alarm_ceil,
|
||||
)
|
||||
m.recipe_meta["recipe_name"] = recipe.name
|
||||
m.recipe_meta["industry"] = recipe.industry
|
||||
return m
|
||||
|
||||
# ---- 训练 / 推理 ----
|
||||
|
||||
def fit(self, X: Sequence[Sequence[float]]) -> "AnomalyDetectionModel":
|
||||
"""拟合主干(无监督)。同时在训练集上确定异常分数阈值。"""
|
||||
X = list(X)
|
||||
self._handle.fit(X)
|
||||
# 用训练分布确定阈值:contamination 取高分位数;sigma 取均值+Nσ
|
||||
scores = self._handle.decision_function(X)
|
||||
self._threshold = self._derive_threshold(scores)
|
||||
return self
|
||||
|
||||
def _derive_threshold(self, scores: Sequence[float]) -> float:
|
||||
"""根据阈值策略从训练分数分布确定异常分数阈值。
|
||||
|
||||
- ``contamination``:取高分位数(1 - contamination),高于即判异常;
|
||||
- ``sigma``:取均值 + Nσ(N=3 默认覆盖 ~99.7% 正常区)。
|
||||
"""
|
||||
scores = sorted(float(s) for s in scores)
|
||||
if not scores:
|
||||
raise AnomalyDetectionError("训练分数为空,无法确定阈值")
|
||||
if self.threshold_policy == "sigma":
|
||||
mean = sum(scores) / len(scores)
|
||||
var = sum((s - mean) ** 2 for s in scores) / len(scores)
|
||||
std = math.sqrt(var) or 1.0
|
||||
return mean + self.sigma * std
|
||||
# contamination:高分位数(线性插值)
|
||||
k = (1.0 - self.contamination) * (len(scores) - 1)
|
||||
lo = int(math.floor(k))
|
||||
hi = int(math.ceil(k))
|
||||
if lo == hi:
|
||||
return scores[lo]
|
||||
frac = k - lo
|
||||
return scores[lo] + (scores[hi] - scores[lo]) * frac
|
||||
|
||||
def decision_function(
|
||||
self, X: Sequence[Sequence[float]]) -> List[float]:
|
||||
"""返回每个样本的异常分数(越大越异常)。"""
|
||||
return self._handle.decision_function(X)
|
||||
|
||||
def predict(self, X: Sequence[Sequence[float]]) -> List[int]:
|
||||
"""返回每个样本的二值异常标签:1=异常,0=正常。
|
||||
|
||||
依据 ``fit`` 时确定的阈值(未拟合或阈值未定则报错)。
|
||||
"""
|
||||
if self._threshold is None:
|
||||
raise AnomalyDetectionError(
|
||||
"阈值未确定:请先 fit,或阈值策略未被应用")
|
||||
scores = self.decision_function(X)
|
||||
return [1 if s > self._threshold else 0 for s in scores]
|
||||
|
||||
@property
|
||||
def fitted(self) -> bool:
|
||||
return self._handle.fitted
|
||||
|
||||
@property
|
||||
def threshold(self) -> Optional[float]:
|
||||
return self._threshold
|
||||
|
||||
# ---- 验收口径 ----
|
||||
|
||||
def evaluate(self, X: Sequence[Sequence[float]],
|
||||
y_true: Sequence[int]) -> "Metrics":
|
||||
"""评估并返回检出率 / 误报率 / 精确率 / 召回率 / F1 与是否达标。
|
||||
|
||||
``y_true`` 中 1=异常、0=正常。检出率即召回率(PRD 5.3 / 里程碑:
|
||||
≥ 95%);误报率即假阳性率(1 - 特异性,里程碑:≤ 5%)。
|
||||
``recall >= recall_floor`` 且 ``false_alarm <= false_alarm_ceil``
|
||||
即视为达标。
|
||||
"""
|
||||
y_pred = self.predict(X)
|
||||
return Metrics.compute(
|
||||
y_true=list(y_true), y_pred=y_pred,
|
||||
recall_floor=self.recall_floor,
|
||||
false_alarm_ceil=self.false_alarm_ceil)
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"recipe_meta": dict(self.recipe_meta),
|
||||
"handle": self._handle.to_dict(),
|
||||
"threshold": self._threshold,
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 验收:Metrics
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Metrics:
|
||||
"""异常检测验收结果(PRD 5.3 检出率 / 误报率口径)。"""
|
||||
|
||||
recall: float # 检出率(TP/TP+FN),里程碑 ≥ 95%
|
||||
precision: float # 精确率(TP/TP+FP)
|
||||
f1: float # F1
|
||||
false_alarm_rate: float # 误报率(FP/FP+TN),里程碑 ≤ 5%
|
||||
n_anomaly_true: int
|
||||
n_normal_true: int
|
||||
recall_floor: float
|
||||
false_alarm_ceil: float
|
||||
passed: bool
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"recall": self.recall,
|
||||
"precision": self.precision,
|
||||
"f1": self.f1,
|
||||
"false_alarm_rate": self.false_alarm_rate,
|
||||
"n_anomaly_true": self.n_anomaly_true,
|
||||
"n_normal_true": self.n_normal_true,
|
||||
"recall_floor": self.recall_floor,
|
||||
"false_alarm_ceil": self.false_alarm_ceil,
|
||||
"passed": self.passed,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def compute(cls, y_true: Sequence[int], y_pred: Sequence[int],
|
||||
recall_floor: float = DEFAULT_RECALL_FLOOR,
|
||||
false_alarm_ceil: float = DEFAULT_FALSE_ALARM_CEIL) -> "Metrics":
|
||||
if len(y_true) != len(y_pred):
|
||||
raise AnomalyDetectionError(
|
||||
f"y_true/y_pred 长度不一致:{len(y_true)} != {len(y_pred)}")
|
||||
if not y_true:
|
||||
raise AnomalyDetectionError("评估数据为空")
|
||||
# 统计混淆矩阵四元
|
||||
tp = fp = fn = tn = 0
|
||||
for yt, yp in zip(y_true, y_pred):
|
||||
if yt == 1 and yp == 1:
|
||||
tp += 1
|
||||
elif yt == 0 and yp == 1:
|
||||
fp += 1
|
||||
elif yt == 1 and yp == 0:
|
||||
fn += 1
|
||||
else:
|
||||
tn += 1
|
||||
n_anomaly = tp + fn
|
||||
n_normal = fp + tn
|
||||
recall = tp / n_anomaly if n_anomaly > 0 else 0.0
|
||||
precision = tp / (tp + fp) if (tp + fp) > 0 else 0.0
|
||||
f1 = (2 * precision * recall / (precision + recall)
|
||||
if (precision + recall) > 0 else 0.0)
|
||||
far = fp / n_normal if n_normal > 0 else 0.0
|
||||
passed = recall >= recall_floor and far <= false_alarm_ceil
|
||||
return cls(
|
||||
recall=recall, precision=precision, f1=f1,
|
||||
false_alarm_rate=far,
|
||||
n_anomaly_true=n_anomaly, n_normal_true=n_normal,
|
||||
recall_floor=recall_floor, false_alarm_ceil=false_alarm_ceil,
|
||||
passed=passed,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配方构建入口 + 样例协议
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_from_recipe(path: str) -> AnomalyDetectionModel:
|
||||
"""从 JSON 配方文件加载并构造一个异常检测模型(推荐入口)。
|
||||
|
||||
切换模板仅改配方文件,业务代码零改动——对齐 PRD 5.3 验收口径。
|
||||
"""
|
||||
return AnomalyDetectionModel.from_recipe(load_recipe(path))
|
||||
|
||||
|
||||
def _samples_dir() -> str:
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"samples", "anomaly-detection")
|
||||
|
||||
|
||||
def list_sample_recipes() -> List[str]:
|
||||
"""列出内置样例配方(树脂 + Ti 两套,验证同框架加载多套配方)。"""
|
||||
d = _samples_dir()
|
||||
if not os.path.isdir(d):
|
||||
return []
|
||||
return sorted(f for f in os.listdir(d) if f.endswith(".json"))
|
||||
|
||||
|
||||
def sample_recipe_path(name: str) -> str:
|
||||
"""返回样例配方的完整路径。"""
|
||||
if not name.endswith(".json"):
|
||||
name = name + ".json"
|
||||
return os.path.join(_samples_dir(), name)
|
||||
@@ -0,0 +1,534 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""质量预测模型模板化(固定主干 + 配方加载)。
|
||||
|
||||
对应 issue #36(父 EPIC #5「③ AI 模型框架 配置化重构」、PRD 5.3
|
||||
「网络结构策略 / 模板化技术路径」)。
|
||||
|
||||
PRD 5.3 的核心诉求
|
||||
------------------
|
||||
|
||||
质量预测属于 PRD 5.3「四类模型模板」之一(① 质量预测),采用
|
||||
「**固定主干网络 + 可配置超参**」为默认模式:同一主干代码不变,
|
||||
切换行业/工况只改 *配方(recipe)* —— 一个声明式 JSON 超参包。
|
||||
|
||||
本模块交付什么
|
||||
--------------
|
||||
|
||||
1. **``QualityForecastModel``**:固定主干的质量预测模型。默认主干是
|
||||
``gbdt``(梯度提升回归,PRD 5.3 推荐的监督回归默认结构);当运行
|
||||
环境存在 ``sklearn`` 时自动升级为真实实现,否则退化为确定性 stub,
|
||||
保证边缘 / 离线 / CI 环境可加载与校验——与 issue #34 / #35 的
|
||||
「numpy/sklearn 可选」策略一致。
|
||||
2. **``Recipe`` 配方加载器**:声明式 JSON 超参包(``load_recipe`` /
|
||||
``build_from_recipe``)。配方描述「主干类型 + 超参 + 特征列 + 目标列
|
||||
+ 验收口径」,业务侧只 ``build_from_recipe(path)`` 一行即可拿到一个
|
||||
可训练/可推理的模型——切换模板仅改配方,模型代码零改动。
|
||||
3. **``Accuracy`` 验收口径**:PRD 5.3 / 第 6 章里程碑要求「关键质量指标
|
||||
预测准确率 ≥ 90%」。``evaluate`` 直接给出准确率 / MAE / RMSE,便于
|
||||
配置台与 UAT 直接读取。
|
||||
4. **样例配方(``samples/`` JSON)**:Ti(海绵钛氯化车间)+ 树脂两套
|
||||
质量预测超参包样例,验证「同框架加载两套配方均跑通」的验收口径。
|
||||
|
||||
与 issue #34 ``model_recipe`` 的关系
|
||||
------------------------------------
|
||||
|
||||
接口风格对齐 #34 的 ``ModelHandle`` / ``ModelRecipe``(``fit`` / ``predict``
|
||||
/ ``to_dict``、不可变声明式数据对象)。本模块**自包含、不依赖 #34 未合并
|
||||
的 ``model_recipe``**,待 #34(PR #102)合入后,质量预测主干可平滑注册为
|
||||
``register_backbone("gbdt", ...)`` 的一个具名主干,配方可映射为一条
|
||||
``ModelRecipe``——届时本模块零业务侧改动。
|
||||
|
||||
零外部强依赖
|
||||
------------
|
||||
|
||||
* 主干默认走纯 Python stub(``StubBackbone``):无 sklearn 时也能加载、
|
||||
构造、(伪)拟合与预测,保证 CI 可加载与校验;
|
||||
* 存在 ``sklearn`` 时,``gbdt`` 主干自动升级为真实
|
||||
``GradientBoostingRegressor`` 实现,其余情况退化为 stub,不影响接口
|
||||
契约与测试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Sequence, Tuple
|
||||
|
||||
__all__ = [
|
||||
# 数据对象
|
||||
"Recipe",
|
||||
"Accuracy",
|
||||
"QualityForecastError",
|
||||
# 模型
|
||||
"QualityForecastModel",
|
||||
"ModelHandle",
|
||||
# 主干工厂
|
||||
"BACKBONES",
|
||||
"register_backbone",
|
||||
"gbdt_backbone",
|
||||
"dnn_backbone",
|
||||
"stub_backbone",
|
||||
# 配方 API
|
||||
"load_recipe",
|
||||
"build_from_recipe",
|
||||
"list_sample_recipes",
|
||||
"sample_recipe_path",
|
||||
]
|
||||
|
||||
|
||||
class QualityForecastError(Exception):
|
||||
"""质量预测模板化层的统一异常(配方非法 / 主干未注册 / 校验失败)。"""
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配方(Recipe):声明式超参包,不可变数据对象
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
#: PRD 5.3 允许的固定主干类型(默认 gbdt,PRD 5.3 推荐监督回归默认结构)
|
||||
ALLOWED_BACKBONES = ("gbdt", "dnn", "stub")
|
||||
|
||||
#: PRD 5.3 / 第 6 章里程碑:质量预测准确率验收线 ≥ 90%
|
||||
DEFAULT_ACCURACY_FLOOR = 0.90
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Recipe:
|
||||
"""质量预测配方(声明式超参包)。
|
||||
|
||||
一个 Recipe 描述「用什么固定主干 + 如何从超参构造一个可训练/可推理的
|
||||
质量预测模型 + 用哪些特征/目标列 + 验收口径」。它是不可变数据对象,
|
||||
``to_dict`` / ``from_dict`` 可序列化往返,便于配置台展示与审计。
|
||||
|
||||
切换行业/工况只改 Recipe,模型代码(``QualityForecastModel``)零改动
|
||||
——对齐 PRD 5.3「固定主干 + 可配置超参」默认模式。
|
||||
"""
|
||||
|
||||
name: str
|
||||
backbone: str = "gbdt"
|
||||
hyperparams: Dict[str, Any] = field(default_factory=dict)
|
||||
feature_columns: Tuple[str, ...] = field(default_factory=tuple)
|
||||
target_column: str = "quality_index"
|
||||
accuracy_floor: float = DEFAULT_ACCURACY_FLOOR
|
||||
industry: str = ""
|
||||
notes: str = ""
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
if not self.name:
|
||||
raise QualityForecastError("Recipe 缺少 name")
|
||||
if self.backbone not in ALLOWED_BACKBONES:
|
||||
raise QualityForecastError(
|
||||
f"非法主干类型 {self.backbone!r},允许:{ALLOWED_BACKBONES}")
|
||||
if self.accuracy_floor < 0 or self.accuracy_floor > 1:
|
||||
raise QualityForecastError(
|
||||
f"accuracy_floor 越界:{self.accuracy_floor}(应在 [0,1])")
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"name": self.name,
|
||||
"backbone": self.backbone,
|
||||
"hyperparams": dict(self.hyperparams),
|
||||
"feature_columns": list(self.feature_columns),
|
||||
"target_column": self.target_column,
|
||||
"accuracy_floor": self.accuracy_floor,
|
||||
"industry": self.industry,
|
||||
"notes": self.notes,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: Dict[str, Any]) -> "Recipe":
|
||||
try:
|
||||
return cls(
|
||||
name=data["name"],
|
||||
backbone=data.get("backbone", "gbdt"),
|
||||
hyperparams=dict(data.get("hyperparams", {})),
|
||||
feature_columns=tuple(data.get("feature_columns", [])),
|
||||
target_column=data.get("target_column", "quality_index"),
|
||||
accuracy_floor=float(data.get(
|
||||
"accuracy_floor", DEFAULT_ACCURACY_FLOOR)),
|
||||
industry=data.get("industry", ""),
|
||||
notes=data.get("notes", ""),
|
||||
)
|
||||
except KeyError as exc: # pragma: no cover - 防御性
|
||||
raise QualityForecastError(f"配方缺少必填字段:{exc}") from exc
|
||||
|
||||
|
||||
def load_recipe(path: str) -> Recipe:
|
||||
"""从 JSON 文件加载一个质量预测配方。
|
||||
|
||||
配方 JSON 结构见 ``Recipe.to_dict``;样例见 ``samples/``。
|
||||
"""
|
||||
with open(path, "r", encoding="utf-8") as fh:
|
||||
data = json.load(fh)
|
||||
if not isinstance(data, dict):
|
||||
raise QualityForecastError(f"配方根必须是对象:{path}")
|
||||
return Recipe.from_dict(data)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 主干工厂:固定主干网络(gbdt / dnn / stub)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class ModelHandle:
|
||||
"""统一模型句柄:fit / predict / to_dict,与硬件和具体库无关。
|
||||
|
||||
业务代码只持有 ``ModelHandle``,不感知底层是 sklearn 还是 stub。
|
||||
"""
|
||||
|
||||
def __init__(self, backbone: str, params: Dict[str, Any],
|
||||
fitted: bool = False, meta: Optional[Dict[str, Any]] = None):
|
||||
self.backbone = backbone
|
||||
self.params = dict(params)
|
||||
self._fitted = fitted
|
||||
self.meta: Dict[str, Any] = dict(meta or {})
|
||||
|
||||
@property
|
||||
def fitted(self) -> bool:
|
||||
return self._fitted
|
||||
|
||||
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> "ModelHandle":
|
||||
"""拟合主干。stub 主干记录均值/极差用于确定性预测。"""
|
||||
X = list(X)
|
||||
y = list(y)
|
||||
if not X or not y:
|
||||
raise QualityForecastError("训练数据为空")
|
||||
if len(X) != len(y):
|
||||
raise QualityForecastError(
|
||||
f"X/y 样本数不一致:{len(X)} != {len(y)}")
|
||||
self._fit_impl(X, y)
|
||||
self._fitted = True
|
||||
return self
|
||||
|
||||
# 子类/工厂填充
|
||||
def _fit_impl(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def predict(self, X: Sequence[Sequence[float]]) -> List[float]:
|
||||
if not self._fitted:
|
||||
raise QualityForecastError("模型未拟合,无法预测")
|
||||
return [self._predict_one(list(row)) for row in X]
|
||||
|
||||
def _predict_one(self, row: Sequence[float]) -> float:
|
||||
raise NotImplementedError
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"backbone": self.backbone,
|
||||
"params": dict(self.params),
|
||||
"fitted": self._fitted,
|
||||
"meta": dict(self.meta),
|
||||
}
|
||||
|
||||
|
||||
class _StubBackbone(ModelHandle):
|
||||
"""确定性 stub 主干:无 sklearn 时的保底实现。
|
||||
|
||||
拟合阶段记录训练目标的均值与极差;预测返回一个由输入求和驱动的
|
||||
确定性值(落在训练目标范围内),保证可复现、可校验、可对比,便于
|
||||
CI 与配置台预览。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="stub", params=params)
|
||||
self._y_mean: float = 0.0
|
||||
self._y_amp: float = 1.0
|
||||
|
||||
def _fit_impl(self, X, y) -> None:
|
||||
self._y_mean = sum(y) / len(y)
|
||||
self._y_amp = (max(y) - min(y)) or 1.0
|
||||
self.meta.update({"y_mean": self._y_mean, "y_amp": self._y_amp})
|
||||
|
||||
def _predict_one(self, row) -> float:
|
||||
# 确定性:输入和的 tanh 压缩到 [y_mean-amp/2, y_mean+amp/2]
|
||||
s = sum(float(v) for v in row) if row else 0.0
|
||||
# 归一化到 [-1,1] 附近,再映射回目标域
|
||||
norm = math.tanh(s / (self._y_amp or 1.0))
|
||||
return self._y_mean + 0.5 * self._y_amp * norm
|
||||
|
||||
|
||||
class _SklearnGbdtBackbone(ModelHandle):
|
||||
"""真实 GBDT 主干(sklearn GradientBoostingRegressor)。
|
||||
|
||||
仅当运行环境存在 sklearn 时启用;与 stub 接口完全一致。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="gbdt", params=params)
|
||||
# 延迟 import,避免无 sklearn 环境加载失败
|
||||
from sklearn.ensemble import GradientBoostingRegressor # type: ignore
|
||||
self._Clz = GradientBoostingRegressor
|
||||
self._model: Any = None
|
||||
|
||||
def _fit_impl(self, X, y) -> None:
|
||||
kw = {
|
||||
"n_estimators": int(self.params.get("n_estimators", 100)),
|
||||
"max_depth": int(self.params.get("max_depth", 3)),
|
||||
"learning_rate": float(self.params.get("learning_rate", 0.1)),
|
||||
"random_state": int(self.params.get("random_state", 42)),
|
||||
}
|
||||
self._model = self._Clz(**kw)
|
||||
self._model.fit(list(X), list(y))
|
||||
self.meta.update(kw)
|
||||
|
||||
def _predict_one(self, row) -> float:
|
||||
return float(self._model.predict([list(row)])[0])
|
||||
|
||||
|
||||
class _SklearnDnnBackbone(ModelHandle):
|
||||
"""真实轻量 DNN 主干(sklearn MLPRegressor)。
|
||||
|
||||
PRD 5.3 备选结构;仅当运行环境存在 sklearn 时启用。
|
||||
"""
|
||||
|
||||
def __init__(self, params: Dict[str, Any]):
|
||||
super().__init__(backbone="dnn", params=params)
|
||||
from sklearn.neural_network import MLPRegressor # type: ignore
|
||||
self._Clz = MLPRegressor
|
||||
self._model: Any = None
|
||||
|
||||
def _fit_impl(self, X, y) -> None:
|
||||
kw = {
|
||||
"hidden_layer_sizes": tuple(
|
||||
self.params.get("hidden_layer_sizes", (32, 16))),
|
||||
"max_iter": int(self.params.get("max_iter", 500)),
|
||||
"random_state": int(self.params.get("random_state", 42)),
|
||||
}
|
||||
self._model = self._Clz(**kw)
|
||||
self._model.fit(list(X), list(y))
|
||||
self.meta.update({"hidden_layer_sizes": list(kw["hidden_layer_sizes"]),
|
||||
"max_iter": kw["max_iter"]})
|
||||
|
||||
def _predict_one(self, row) -> float:
|
||||
return float(self._model.predict([list(row)])[0])
|
||||
|
||||
|
||||
def _has_sklearn() -> bool:
|
||||
try:
|
||||
import sklearn # noqa: F401
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def stub_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""stub 主干工厂(恒可用)。"""
|
||||
return _StubBackbone(hyperparams)
|
||||
|
||||
|
||||
def gbdt_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""gbdt 主干工厂:有 sklearn 用真实 GBDT,否则退化为 stub。
|
||||
|
||||
PRD 5.3 推荐的监督回归默认结构(梯度提升回归)。
|
||||
"""
|
||||
if _has_sklearn():
|
||||
return _SklearnGbdtBackbone(hyperparams)
|
||||
# 无 sklearn:退化 stub 但保留声明主干名,便于审计
|
||||
h = _StubBackbone(hyperparams)
|
||||
h.meta["degraded_from"] = "gbdt"
|
||||
return h
|
||||
|
||||
|
||||
def dnn_backbone(hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
"""dnn 主干工厂:有 sklearn 用真实 MLP,否则退化为 stub。"""
|
||||
if _has_sklearn():
|
||||
return _SklearnDnnBackbone(hyperparams)
|
||||
h = _StubBackbone(hyperparams)
|
||||
h.meta["degraded_from"] = "dnn"
|
||||
return h
|
||||
|
||||
|
||||
#: 主干注册表:新增结构走 ``register_backbone`` 注册,不动内核
|
||||
#: (对齐 PRD 5.3「新增结构走插件注册」理念,风格对齐 #34)。
|
||||
BACKBONES: Dict[str, Any] = {
|
||||
"gbdt": gbdt_backbone,
|
||||
"dnn": dnn_backbone,
|
||||
"stub": stub_backbone,
|
||||
}
|
||||
|
||||
|
||||
def register_backbone(name: str, factory: Any) -> None:
|
||||
"""注册一个新主干工厂 ``factory(hyperparams) -> ModelHandle``。
|
||||
|
||||
允许高级行业模板声明非默认主干(如自研网络),不动内核——对齐 PRD
|
||||
「新增结构走插件注册而非改内核」。
|
||||
"""
|
||||
if not callable(factory):
|
||||
raise QualityForecastError("主干工厂必须是可调用对象")
|
||||
BACKBONES[name] = factory
|
||||
|
||||
|
||||
def _build_backbone(backbone: str, hyperparams: Dict[str, Any]) -> ModelHandle:
|
||||
factory = BACKBONES.get(backbone)
|
||||
if factory is None:
|
||||
raise QualityForecastError(
|
||||
f"未注册的主干类型:{backbone!r},已注册:{list(BACKBONES)}")
|
||||
return factory(hyperparams)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 质量预测模型:固定主干 + 配方加载
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class QualityForecastModel:
|
||||
"""质量预测模型(固定主干 + 配方加载)。
|
||||
|
||||
业务侧两种等价入口:
|
||||
|
||||
1. 直接构造(显式主干)::
|
||||
|
||||
m = QualityForecastModel(backbone="gbdt", hyperparams={...})
|
||||
|
||||
2. 配方加载(推荐,切换模板仅改配方)::
|
||||
|
||||
m = build_from_recipe("templates/.../quality-forecast/recipe.ti.json")
|
||||
"""
|
||||
|
||||
def __init__(self, backbone: str = "gbdt",
|
||||
hyperparams: Optional[Dict[str, Any]] = None,
|
||||
feature_columns: Optional[Sequence[str]] = None,
|
||||
target_column: str = "quality_index",
|
||||
accuracy_floor: float = DEFAULT_ACCURACY_FLOOR):
|
||||
self.recipe_meta: Dict[str, Any] = {
|
||||
"backbone": backbone,
|
||||
"hyperparams": dict(hyperparams or {}),
|
||||
"feature_columns": list(feature_columns or []),
|
||||
"target_column": target_column,
|
||||
"accuracy_floor": accuracy_floor,
|
||||
}
|
||||
self._handle: ModelHandle = _build_backbone(backbone, hyperparams or {})
|
||||
|
||||
@classmethod
|
||||
def from_recipe(cls, recipe: Recipe) -> "QualityForecastModel":
|
||||
"""从一个 ``Recipe`` 构造模型(推荐入口)。"""
|
||||
m = cls(
|
||||
backbone=recipe.backbone,
|
||||
hyperparams=recipe.hyperparams,
|
||||
feature_columns=recipe.feature_columns,
|
||||
target_column=recipe.target_column,
|
||||
accuracy_floor=recipe.accuracy_floor,
|
||||
)
|
||||
m.recipe_meta["recipe_name"] = recipe.name
|
||||
m.recipe_meta["industry"] = recipe.industry
|
||||
return m
|
||||
|
||||
# ---- 训练 / 推理 ----
|
||||
|
||||
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float]) -> "QualityForecastModel":
|
||||
self._handle.fit(X, y)
|
||||
return self
|
||||
|
||||
def predict(self, X: Sequence[Sequence[float]]) -> List[float]:
|
||||
return self._handle.predict(X)
|
||||
|
||||
@property
|
||||
def fitted(self) -> bool:
|
||||
return self._handle.fitted
|
||||
|
||||
# ---- 验收口径 ----
|
||||
|
||||
def evaluate(self, X: Sequence[Sequence[float]],
|
||||
y: Sequence[float]) -> "Accuracy":
|
||||
"""评估并返回准确率/MAE/RMSE 与是否达标。
|
||||
|
||||
准确率口径(PRD 5.3 / 里程碑):相对误差在容忍带
|
||||
``tolerance``(默认 10%)内计为命中。``accuracy >= accuracy_floor``
|
||||
即视为达标(默认 90%)。
|
||||
"""
|
||||
preds = self.predict(X)
|
||||
return Accuracy.compute(
|
||||
y_true=list(y), y_pred=preds,
|
||||
accuracy_floor=self.recipe_meta["accuracy_floor"])
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"recipe_meta": dict(self.recipe_meta),
|
||||
"handle": self._handle.to_dict(),
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 验收:Accuracy
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Accuracy:
|
||||
"""质量预测验收结果(PRD 5.3 准确率口径)。"""
|
||||
|
||||
accuracy: float
|
||||
mae: float
|
||||
rmse: float
|
||||
tolerance: float
|
||||
accuracy_floor: float
|
||||
passed: bool
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"accuracy": self.accuracy,
|
||||
"mae": self.mae,
|
||||
"rmse": self.rmse,
|
||||
"tolerance": self.tolerance,
|
||||
"accuracy_floor": self.accuracy_floor,
|
||||
"passed": self.passed,
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def compute(cls, y_true: Sequence[float], y_pred: Sequence[float],
|
||||
tolerance: float = 0.10,
|
||||
accuracy_floor: float = DEFAULT_ACCURACY_FLOOR) -> "Accuracy":
|
||||
if len(y_true) != len(y_pred):
|
||||
raise QualityForecastError(
|
||||
f"y_true/y_pred 长度不一致:{len(y_true)} != {len(y_pred)}")
|
||||
if not y_true:
|
||||
raise QualityForecastError("评估数据为空")
|
||||
n = len(y_true)
|
||||
hits = 0
|
||||
abs_err_sum = 0.0
|
||||
sq_err_sum = 0.0
|
||||
for yt, yp in zip(y_true, y_pred):
|
||||
denom = abs(yt) if abs(yt) > 1e-9 else 1.0
|
||||
rel = abs(yp - yt) / denom
|
||||
if rel <= tolerance:
|
||||
hits += 1
|
||||
abs_err_sum += abs(yp - yt)
|
||||
sq_err_sum += (yp - yt) ** 2
|
||||
accuracy = hits / n
|
||||
mae = abs_err_sum / n
|
||||
rmse = math.sqrt(sq_err_sum / n)
|
||||
return cls(
|
||||
accuracy=accuracy, mae=mae, rmse=rmse,
|
||||
tolerance=tolerance, accuracy_floor=accuracy_floor,
|
||||
passed=accuracy >= accuracy_floor,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配方构建入口 + 样例协议
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def build_from_recipe(path: str) -> QualityForecastModel:
|
||||
"""从 JSON 配方文件加载并构造一个质量预测模型(推荐入口)。
|
||||
|
||||
切换模板仅改配方文件,业务代码零改动——对齐 PRD 5.3 验收口径。
|
||||
"""
|
||||
return QualityForecastModel.from_recipe(load_recipe(path))
|
||||
|
||||
|
||||
def _samples_dir() -> str:
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)),
|
||||
"samples", "quality-forecast")
|
||||
|
||||
|
||||
def list_sample_recipes() -> List[str]:
|
||||
"""列出内置样例配方(树脂 + Ti 两套,验证同框架加载多套配方)。"""
|
||||
d = _samples_dir()
|
||||
if not os.path.isdir(d):
|
||||
return []
|
||||
return sorted(f for f in os.listdir(d) if f.endswith(".json"))
|
||||
|
||||
|
||||
def sample_recipe_path(name: str) -> str:
|
||||
"""返回样例配方的完整路径。"""
|
||||
if not name.endswith(".json"):
|
||||
name = name + ".json"
|
||||
return os.path.join(_samples_dir(), name)
|
||||
@@ -1,24 +0,0 @@
|
||||
{
|
||||
"name": "resin-reactor-anomaly",
|
||||
"backbone": "iforest",
|
||||
"industry": "吸附树脂(已终验化工新材料AI平台 baseline)",
|
||||
"hyperparams": {
|
||||
"n_estimators": 100,
|
||||
"max_samples": "auto",
|
||||
"contamination": "auto",
|
||||
"random_state": 7
|
||||
},
|
||||
"feature_columns": [
|
||||
"reactor_temp",
|
||||
"reactor_pressure",
|
||||
"flow_rate",
|
||||
"ph_value",
|
||||
"conversion_rate"
|
||||
],
|
||||
"threshold_policy": "contamination",
|
||||
"contamination": 0.05,
|
||||
"sigma": 3.0,
|
||||
"recall_floor": 0.95,
|
||||
"false_alarm_ceil": 0.05,
|
||||
"notes": "PRD 5.3 ③ 异常检测:树脂反应釜工况/质量异常预警,复用已交付化工AI平台 baseline 超参。"
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
{
|
||||
"name": "ti-cl4-furnace-impurity-anomaly",
|
||||
"backbone": "iforest",
|
||||
"industry": "海绵钛氯化车间(Template-Ti 一期)",
|
||||
"hyperparams": {
|
||||
"n_estimators": 150,
|
||||
"max_samples": "auto",
|
||||
"contamination": "auto",
|
||||
"random_state": 42
|
||||
},
|
||||
"feature_columns": [
|
||||
"furnace_temp",
|
||||
"furnace_pressure",
|
||||
"cl2_flow",
|
||||
"ti_feed_rate",
|
||||
"impurity_fe",
|
||||
"impurity_v",
|
||||
"impurity_si"
|
||||
],
|
||||
"threshold_policy": "contamination",
|
||||
"contamination": 0.05,
|
||||
"sigma": 3.0,
|
||||
"recall_floor": 0.95,
|
||||
"false_alarm_ceil": 0.05,
|
||||
"notes": "PRD 5.3 ③ 异常检测:氯化车间炉层杂质/工况异常预警(关联 EPIC #10 炉层杂质预警),验收检出率≥95%、误报率≤5%(PRD 第6章里程碑)。一期数据门槛:≥6个月标注(DCS+LIMS对接后补标)。"
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"name": "resin-quality",
|
||||
"backbone": "gbdt",
|
||||
"industry": "吸附树脂(已终验化工新材料AI平台 baseline)",
|
||||
"hyperparams": {
|
||||
"n_estimators": 100,
|
||||
"max_depth": 3,
|
||||
"learning_rate": 0.1,
|
||||
"random_state": 7
|
||||
},
|
||||
"feature_columns": [
|
||||
"reactor_temp",
|
||||
"reactor_pressure",
|
||||
"flow_rate",
|
||||
"ph_value",
|
||||
"conversion_rate"
|
||||
],
|
||||
"target_column": "resin_purity_index",
|
||||
"accuracy_floor": 0.90,
|
||||
"notes": "PRD 5.3 ① 质量预测:树脂纯度/合格率预测,复用已交付化工AI平台 baseline 超参。"
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "ti-cl4-quality",
|
||||
"backbone": "gbdt",
|
||||
"industry": "海绵钛氯化车间(Template-Ti 一期)",
|
||||
"hyperparams": {
|
||||
"n_estimators": 120,
|
||||
"max_depth": 4,
|
||||
"learning_rate": 0.08,
|
||||
"random_state": 42
|
||||
},
|
||||
"feature_columns": [
|
||||
"furnace_temp",
|
||||
"furnace_pressure",
|
||||
"cl2_flow",
|
||||
"ti_feed_rate",
|
||||
"impurity_fe",
|
||||
"impurity_v"
|
||||
],
|
||||
"target_column": "ti_product_grade_index",
|
||||
"accuracy_floor": 0.90,
|
||||
"notes": "PRD 5.3 ① 质量预测:氯化车间一次合格率预测,验收准确率≥90%(PRD 第6章里程碑)。一期数据门槛:≥6个月标注(LIMS对接后补标)。"
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
@@ -1,333 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""``anomaly_detection`` 单元测试(issue #37)。
|
||||
|
||||
覆盖:
|
||||
- 配方(Recipe)不可变性 / 序列化往返 / 非法主干、非法阈值策略与越界校验;
|
||||
- 主干工厂注册表 + 自定义主干注册(PRD 5.3「新增结构走插件注册」);
|
||||
- stub / iforest / lof 三类主干的 fit/decision_function 契约;
|
||||
- 固定主干 + 配方加载:同框架加载 Ti / 树脂两套配方均跑通(PRD 5.3
|
||||
验收口径);
|
||||
- Metrics 验收口径(PRD 5.3 / 里程碑:检出率 ≥ 95%、误报率 ≤ 5%);
|
||||
- 阈值策略(contamination 高分位 / sigma Nσ 法则);
|
||||
- 零外部强依赖:无 sklearn 时 stub 退化仍可加载与校验。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import _bootstrap # noqa: E402 注册 model_framework 包
|
||||
|
||||
from model_framework import ( # noqa: E402
|
||||
AnomalyDetectionError,
|
||||
AnomalyDetectionModel,
|
||||
BACKBONES,
|
||||
Metrics,
|
||||
ModelHandle,
|
||||
Recipe,
|
||||
build_from_recipe,
|
||||
iforest_backbone,
|
||||
list_sample_recipes,
|
||||
load_recipe,
|
||||
lof_backbone,
|
||||
register_backbone,
|
||||
sample_recipe_path,
|
||||
stub_backbone,
|
||||
)
|
||||
|
||||
|
||||
def _normal_dataset(n=40, n_feat=2, seed=0):
|
||||
"""构造一组「正常」样本(围绕均值的确定性点)。"""
|
||||
X = []
|
||||
for i in range(n):
|
||||
row = []
|
||||
for j in range(n_feat):
|
||||
base = float(i % 7) + 1.0 + 0.1 * j
|
||||
row.append(base)
|
||||
X.append(row)
|
||||
return X
|
||||
|
||||
|
||||
def _labeled_dataset(n_normal=40, n_anomaly=5, n_feat=2):
|
||||
"""构造正常 + 离群点数据集,返回 (X, y_true),1=异常。"""
|
||||
X = _normal_dataset(n_normal, n_feat)
|
||||
y = [0] * n_normal
|
||||
for k in range(n_anomaly):
|
||||
# 明显远离正常区的离群点
|
||||
X.append([100.0 + k for _ in range(n_feat)])
|
||||
y.append(1)
|
||||
return X, y
|
||||
|
||||
|
||||
class TestRecipe(unittest.TestCase):
|
||||
"""配方数据对象与校验。"""
|
||||
|
||||
def test_defaults_and_immutability(self):
|
||||
r = Recipe(name="t")
|
||||
self.assertEqual(r.backbone, "iforest")
|
||||
self.assertEqual(r.threshold_policy, "contamination")
|
||||
self.assertAlmostEqual(r.recall_floor, 0.95)
|
||||
self.assertAlmostEqual(r.false_alarm_ceil, 0.05)
|
||||
with self.assertRaises(Exception):
|
||||
r.name = "other" # frozen
|
||||
|
||||
def test_roundtrip(self):
|
||||
r = Recipe(name="t", backbone="lof",
|
||||
hyperparams={"n_neighbors": 15},
|
||||
feature_columns=("a", "b"),
|
||||
threshold_policy="sigma",
|
||||
contamination=0.1, sigma=2.5,
|
||||
recall_floor=0.9, false_alarm_ceil=0.1,
|
||||
industry="树脂", notes="n")
|
||||
d = r.to_dict()
|
||||
r2 = Recipe.from_dict(d)
|
||||
self.assertEqual(r, r2)
|
||||
# JSON 往返
|
||||
r3 = Recipe.from_dict(json.loads(json.dumps(d)))
|
||||
self.assertEqual(r, r3)
|
||||
|
||||
def test_invalid_backbone_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", backbone="svm")
|
||||
|
||||
def test_invalid_threshold_policy_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", threshold_policy="quantile")
|
||||
|
||||
def test_contamination_out_of_range(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", contamination=0.0)
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", contamination=1.0)
|
||||
|
||||
def test_sigma_nonpositive_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", sigma=0)
|
||||
|
||||
def test_recall_floor_out_of_range(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="t", recall_floor=1.5)
|
||||
|
||||
def test_missing_name(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Recipe(name="")
|
||||
|
||||
def test_load_recipe_from_file(self):
|
||||
path = sample_recipe_path("recipe.ti.json")
|
||||
r = load_recipe(path)
|
||||
self.assertEqual(r.name, "ti-cl4-furnace-impurity-anomaly")
|
||||
self.assertEqual(r.backbone, "iforest")
|
||||
self.assertIn("furnace_temp", r.feature_columns)
|
||||
|
||||
|
||||
class TestBackbones(unittest.TestCase):
|
||||
"""主干工厂与注册表。"""
|
||||
|
||||
def test_builtin_backbones_registered(self):
|
||||
for name in ("iforest", "lof", "stub"):
|
||||
self.assertIn(name, BACKBONES)
|
||||
|
||||
def test_register_custom_backbone(self):
|
||||
class _Custom(ModelHandle):
|
||||
def __init__(self, p):
|
||||
super().__init__("custom", p)
|
||||
self._v = 1.0
|
||||
|
||||
def _fit_impl(self, X):
|
||||
self._v = sum(sum(r) for r in X) / (len(X) * len(X[0]))
|
||||
|
||||
def _score_one(self, row):
|
||||
# 离均值越远分数越高
|
||||
return abs(sum(float(v) for v in row) - self._v)
|
||||
|
||||
register_backbone("custom_test", lambda p: _Custom(p))
|
||||
m = AnomalyDetectionModel(backbone="custom_test")
|
||||
X = _normal_dataset()
|
||||
m.fit(X)
|
||||
self.assertEqual(len(m.predict(X)), len(X))
|
||||
# 清理避免污染其它用例
|
||||
BACKBONES.pop("custom_test", None)
|
||||
|
||||
def test_unknown_backbone_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
AnomalyDetectionModel(backbone="not_a_backbone")
|
||||
|
||||
def test_stub_score_is_deterministic_and_nonneg(self):
|
||||
h = stub_backbone({})
|
||||
X = _normal_dataset()
|
||||
h.fit(X)
|
||||
s1 = h.decision_function(X)
|
||||
s2 = h.decision_function(X)
|
||||
self.assertEqual(s1, s2)
|
||||
self.assertTrue(all(isinstance(v, float) for v in s1))
|
||||
self.assertTrue(all(v >= 0 for v in s1))
|
||||
|
||||
def test_decision_before_fit_raises(self):
|
||||
h = stub_backbone({})
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
h.decision_function([[1.0, 2.0]])
|
||||
|
||||
def test_fit_empty_raises(self):
|
||||
h = stub_backbone({})
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
h.fit([])
|
||||
|
||||
def test_iforest_factory_runs_with_or_without_sklearn(self):
|
||||
# 无论 sklearn 是否存在都不应报错
|
||||
h = iforest_backbone({"n_estimators": 20})
|
||||
X = _normal_dataset()
|
||||
h.fit(X)
|
||||
scores = h.decision_function(X)
|
||||
self.assertEqual(len(scores), len(X))
|
||||
|
||||
|
||||
class TestModelContract(unittest.TestCase):
|
||||
"""模型 fit/decision_function/predict 契约。"""
|
||||
|
||||
def test_fit_predict_shapes(self):
|
||||
m = AnomalyDetectionModel(backbone="stub")
|
||||
X = _normal_dataset(20)
|
||||
m.fit(X)
|
||||
self.assertTrue(m.fitted)
|
||||
self.assertIsNotNone(m.threshold)
|
||||
preds = m.predict(X)
|
||||
self.assertEqual(len(preds), len(X))
|
||||
self.assertTrue(all(p in (0, 1) for p in preds))
|
||||
|
||||
def test_predict_before_fit_raises(self):
|
||||
m = AnomalyDetectionModel(backbone="stub")
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
m.predict([[1.0, 2.0]])
|
||||
|
||||
def test_decision_before_fit_raises(self):
|
||||
m = AnomalyDetectionModel(backbone="stub")
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
m.decision_function([[1.0, 2.0]])
|
||||
|
||||
def test_fit_empty_raises(self):
|
||||
m = AnomalyDetectionModel(backbone="stub")
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
m.fit([])
|
||||
|
||||
def test_to_dict_roundtrip_meta(self):
|
||||
m = AnomalyDetectionModel(backbone="iforest",
|
||||
hyperparams={"n_estimators": 5},
|
||||
feature_columns=["a"],
|
||||
threshold_policy="sigma", sigma=2.0)
|
||||
d = m.to_dict()
|
||||
self.assertEqual(d["recipe_meta"]["backbone"], "iforest")
|
||||
self.assertEqual(d["recipe_meta"]["threshold_policy"], "sigma")
|
||||
self.assertIn("handle", d)
|
||||
|
||||
def test_threshold_contamination_isolate_outliers(self):
|
||||
"""contamination 阈值应把注入的离群点判为异常。"""
|
||||
m = AnomalyDetectionModel(
|
||||
backbone="stub", threshold_policy="contamination",
|
||||
contamination=0.10)
|
||||
X, y_true = _labeled_dataset(n_normal=40, n_anomaly=5)
|
||||
m.fit(X)
|
||||
preds = m.predict(X)
|
||||
# 注入的 5 个离群点应被全部判异常
|
||||
self.assertEqual(sum(preds[40:]), 5)
|
||||
|
||||
def test_threshold_sigma_isolate_outliers(self):
|
||||
"""sigma 阈值也应把注入的极端离群点判为异常。"""
|
||||
m = AnomalyDetectionModel(
|
||||
backbone="stub", threshold_policy="sigma", sigma=2.0)
|
||||
X, y_true = _labeled_dataset(n_normal=40, n_anomaly=5)
|
||||
m.fit(X)
|
||||
preds = m.predict(X)
|
||||
self.assertEqual(sum(preds[40:]), 5)
|
||||
|
||||
|
||||
class TestMetrics(unittest.TestCase):
|
||||
"""验收口径(PRD 5.3:检出率 ≥ 95%、误报率 ≤ 5%)。"""
|
||||
|
||||
def test_perfect_predictions_pass(self):
|
||||
y = [1, 1, 0, 0, 0]
|
||||
met = Metrics.compute(y, y, recall_floor=0.95, false_alarm_ceil=0.05)
|
||||
self.assertAlmostEqual(met.recall, 1.0)
|
||||
self.assertAlmostEqual(met.false_alarm_rate, 0.0)
|
||||
self.assertAlmostEqual(met.f1, 1.0)
|
||||
self.assertTrue(met.passed)
|
||||
|
||||
def test_all_miss_fails(self):
|
||||
y_true = [1, 1, 0, 0]
|
||||
y_pred = [0, 0, 0, 0] # 漏检全部异常
|
||||
met = Metrics.compute(y_true, y_pred)
|
||||
self.assertAlmostEqual(met.recall, 0.0)
|
||||
self.assertFalse(met.passed)
|
||||
|
||||
def test_high_false_alarm_fails(self):
|
||||
y_true = [1, 0, 0, 0, 0]
|
||||
y_pred = [1, 1, 1, 1, 1] # 全判异常:检出但误报爆表
|
||||
met = Metrics.compute(y_true, y_pred, false_alarm_ceil=0.05)
|
||||
self.assertAlmostEqual(met.recall, 1.0)
|
||||
self.assertGreater(met.false_alarm_rate, 0.05)
|
||||
self.assertFalse(met.passed)
|
||||
|
||||
def test_length_mismatch_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Metrics.compute([1, 0], [1])
|
||||
|
||||
def test_empty_raises(self):
|
||||
with self.assertRaises(AnomalyDetectionError):
|
||||
Metrics.compute([], [])
|
||||
|
||||
def test_no_anomaly_in_true_recall_zero_div_safe(self):
|
||||
# 无真实异常时 recall 定义为 0,不应抛 ZeroDivision
|
||||
met = Metrics.compute([0, 0, 0], [0, 0, 0])
|
||||
self.assertEqual(met.recall, 0.0)
|
||||
self.assertEqual(met.n_anomaly_true, 0)
|
||||
|
||||
def test_evaluate_end_to_end(self):
|
||||
m = AnomalyDetectionModel(backbone="stub", threshold_policy="sigma",
|
||||
sigma=2.0)
|
||||
X, y_true = _labeled_dataset(n_normal=40, n_anomaly=5)
|
||||
m.fit(X)
|
||||
met = m.evaluate(X, y_true)
|
||||
self.assertIsInstance(met, Metrics)
|
||||
# 离群点应被检出(stub 在极端离群点上召回=1)
|
||||
self.assertEqual(met.recall, 1.0)
|
||||
|
||||
|
||||
class TestSampleRecipes(unittest.TestCase):
|
||||
"""样例协议:同框架加载 Ti / 树脂两套配方均跑通(PRD 5.3 验收口径)。"""
|
||||
|
||||
def test_samples_present(self):
|
||||
names = list_sample_recipes()
|
||||
self.assertIn("recipe.ti.json", names)
|
||||
self.assertIn("recipe.resin.json", names)
|
||||
|
||||
def test_build_from_each_sample_runs(self):
|
||||
for name in ("recipe.ti.json", "recipe.resin.json"):
|
||||
m = build_from_recipe(sample_recipe_path(name))
|
||||
self.assertIn(
|
||||
m.recipe_meta["backbone"], ("iforest", "lof", "stub"))
|
||||
feat = m.recipe_meta["feature_columns"]
|
||||
n_feat = len(feat)
|
||||
self.assertGreater(n_feat, 0)
|
||||
X = [[float(i + j) for j in range(n_feat)] for i in range(30)]
|
||||
# 注入离群点
|
||||
for k in range(3):
|
||||
X.append([100.0 + k for _ in range(n_feat)])
|
||||
y_true = [0] * 30 + [1] * 3
|
||||
m.fit(X)
|
||||
preds = m.predict(X)
|
||||
self.assertEqual(len(preds), len(y_true))
|
||||
met = m.evaluate(X, y_true)
|
||||
self.assertIsInstance(met, Metrics)
|
||||
|
||||
def test_two_recipes_share_same_code(self):
|
||||
"""切换模板仅改配方,模型代码零改动(PRD 5.3)。"""
|
||||
m1 = build_from_recipe(sample_recipe_path("recipe.ti.json"))
|
||||
m2 = build_from_recipe(sample_recipe_path("recipe.resin.json"))
|
||||
self.assertEqual(type(m1), type(m2))
|
||||
self.assertNotEqual(m1.recipe_meta.get("recipe_name"),
|
||||
m2.recipe_meta.get("recipe_name"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,255 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""``quality_forecast`` 单元测试(issue #36)。
|
||||
|
||||
覆盖:
|
||||
- 配方(Recipe)不可变性 / 序列化往返 / 非法主干与越界校验;
|
||||
- 主干工厂注册表 + 自定义主干注册(PRD 5.3「新增结构走插件注册」);
|
||||
- stub / gbdt / dnn 三类主干的 fit/predict/evaluate 契约;
|
||||
- 固定主干 + 配方加载:同框架加载 Ti / 树脂两套配方均跑通(PRD 5.3
|
||||
验收口径);
|
||||
- Accuracy 验收口径(PRD 5.3 / 里程碑:准确率 ≥ 90%);
|
||||
- 零外部强依赖:无 sklearn 时 stub 退化仍可加载与校验。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, HERE)
|
||||
import _bootstrap # noqa: E402 注册 model_framework 包
|
||||
|
||||
from model_framework import ( # noqa: E402
|
||||
Accuracy,
|
||||
BACKBONES,
|
||||
ModelHandle,
|
||||
QualityForecastError,
|
||||
QualityForecastModel,
|
||||
Recipe,
|
||||
build_from_recipe,
|
||||
dnn_backbone,
|
||||
gbdt_backbone,
|
||||
list_sample_recipes,
|
||||
load_recipe,
|
||||
register_backbone,
|
||||
sample_recipe_path,
|
||||
stub_backbone,
|
||||
)
|
||||
|
||||
|
||||
def _linear_dataset(n=40, noise=0.0):
|
||||
"""构造一个 y ≈ 2*x0 + x1 的可学习数据集(带可选噪声)。"""
|
||||
X, y = [], []
|
||||
for i in range(n):
|
||||
x0 = float(i % 7) + 1.0
|
||||
x1 = float(i % 5) * 0.5 + 0.5
|
||||
yv = 2.0 * x0 + x1 + noise * (i % 3 - 1)
|
||||
X.append([x0, x1])
|
||||
y.append(yv)
|
||||
return X, y
|
||||
|
||||
|
||||
class TestRecipe(unittest.TestCase):
|
||||
"""配方数据对象与校验。"""
|
||||
|
||||
def test_defaults_and_immutability(self):
|
||||
r = Recipe(name="t")
|
||||
self.assertEqual(r.backbone, "gbdt")
|
||||
self.assertEqual(r.target_column, "quality_index")
|
||||
self.assertAlmostEqual(r.accuracy_floor, 0.90)
|
||||
with self.assertRaises(Exception):
|
||||
r.name = "other" # frozen
|
||||
|
||||
def test_roundtrip(self):
|
||||
r = Recipe(name="t", backbone="dnn",
|
||||
hyperparams={"max_iter": 50},
|
||||
feature_columns=("a", "b"),
|
||||
target_column="y",
|
||||
accuracy_floor=0.8, industry="树脂", notes="n")
|
||||
d = r.to_dict()
|
||||
r2 = Recipe.from_dict(d)
|
||||
self.assertEqual(r, r2)
|
||||
# JSON 往返
|
||||
r3 = Recipe.from_dict(json.loads(json.dumps(d)))
|
||||
self.assertEqual(r, r3)
|
||||
|
||||
def test_invalid_backbone_raises(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Recipe(name="t", backbone="svm")
|
||||
|
||||
def test_accuracy_floor_out_of_range(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Recipe(name="t", accuracy_floor=1.5)
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Recipe(name="t", accuracy_floor=-0.1)
|
||||
|
||||
def test_missing_name(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Recipe(name="")
|
||||
|
||||
def test_load_recipe_from_file(self, ):
|
||||
path = sample_recipe_path("recipe.ti.json")
|
||||
r = load_recipe(path)
|
||||
self.assertEqual(r.name, "ti-cl4-quality")
|
||||
self.assertEqual(r.backbone, "gbdt")
|
||||
self.assertIn("furnace_temp", r.feature_columns)
|
||||
|
||||
|
||||
class TestBackbones(unittest.TestCase):
|
||||
"""主干工厂与注册表。"""
|
||||
|
||||
def test_builtin_backbones_registered(self):
|
||||
for name in ("gbdt", "dnn", "stub"):
|
||||
self.assertIn(name, BACKBONES)
|
||||
|
||||
def test_register_custom_backbone(self):
|
||||
class _Custom(ModelHandle):
|
||||
def __init__(self, p):
|
||||
super().__init__("custom", p)
|
||||
self._v = 1.0
|
||||
|
||||
def _fit_impl(self, X, y):
|
||||
self._v = sum(y) / len(y)
|
||||
|
||||
def _predict_one(self, row):
|
||||
return self._v
|
||||
|
||||
register_backbone("custom_test", lambda p: _Custom(p))
|
||||
m = QualityForecastModel(backbone="custom_test")
|
||||
X, y = _linear_dataset()
|
||||
m.fit(X, y)
|
||||
self.assertEqual(len(m.predict(X)), len(X))
|
||||
# 清理避免污染其它用例
|
||||
BACKBONES.pop("custom_test", None)
|
||||
|
||||
def test_unknown_backbone_raises(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
QualityForecastModel(backbone="not_a_backbone")
|
||||
|
||||
def test_stub_predict_is_deterministic(self):
|
||||
h = stub_backbone({})
|
||||
X, y = _linear_dataset()
|
||||
h.fit(X, y)
|
||||
p1 = h.predict(X)
|
||||
p2 = h.predict(X)
|
||||
self.assertEqual(p1, p2)
|
||||
self.assertTrue(all(isinstance(v, float) for v in p1))
|
||||
|
||||
def test_gbdt_factory_runs_with_or_without_sklearn(self):
|
||||
# 无论 sklearn 是否存在都不应报错
|
||||
h = gbdt_backbone({"n_estimators": 20, "max_depth": 2})
|
||||
X, y = _linear_dataset()
|
||||
h.fit(X, y)
|
||||
preds = h.predict(X)
|
||||
self.assertEqual(len(preds), len(y))
|
||||
|
||||
|
||||
class TestModelContract(unittest.TestCase):
|
||||
"""模型 fit/predict/evaluate 契约。"""
|
||||
|
||||
def test_fit_predict_shapes(self):
|
||||
m = QualityForecastModel(backbone="stub")
|
||||
X, y = _linear_dataset(20)
|
||||
m.fit(X, y)
|
||||
self.assertTrue(m.fitted)
|
||||
preds = m.predict(X)
|
||||
self.assertEqual(len(preds), len(y))
|
||||
|
||||
def test_predict_before_fit_raises(self):
|
||||
m = QualityForecastModel(backbone="stub")
|
||||
with self.assertRaises(QualityForecastError):
|
||||
m.predict([[1.0, 2.0]])
|
||||
|
||||
def test_fit_mismatched_lengths_raises(self):
|
||||
m = QualityForecastModel(backbone="stub")
|
||||
with self.assertRaises(QualityForecastError):
|
||||
m.fit([[1.0], [2.0]], [1.0])
|
||||
|
||||
def test_fit_empty_raises(self):
|
||||
m = QualityForecastModel(backbone="stub")
|
||||
with self.assertRaises(QualityForecastError):
|
||||
m.fit([], [])
|
||||
|
||||
def test_to_dict_roundtrip_meta(self):
|
||||
m = QualityForecastModel(backbone="gbdt",
|
||||
hyperparams={"n_estimators": 5},
|
||||
feature_columns=["a"],
|
||||
target_column="y")
|
||||
d = m.to_dict()
|
||||
self.assertEqual(d["recipe_meta"]["backbone"], "gbdt")
|
||||
self.assertIn("handle", d)
|
||||
|
||||
|
||||
class TestAccuracy(unittest.TestCase):
|
||||
"""验收口径(PRD 5.3:准确率 ≥ 90%)。"""
|
||||
|
||||
def test_perfect_predictions_pass(self):
|
||||
y = [10.0, 20.0, 30.0, 40.0]
|
||||
acc = Accuracy.compute(y, y, accuracy_floor=0.9)
|
||||
self.assertAlmostEqual(acc.accuracy, 1.0)
|
||||
self.assertAlmostEqual(acc.mae, 0.0)
|
||||
self.assertAlmostEqual(acc.rmse, 0.0)
|
||||
self.assertTrue(acc.passed)
|
||||
|
||||
def test_bad_predictions_fail(self):
|
||||
y_true = [10.0, 20.0, 30.0, 40.0]
|
||||
y_pred = [11.0, 50.0, 5.0, 80.0] # 大偏差
|
||||
acc = Accuracy.compute(y_true, y_pred, accuracy_floor=0.9)
|
||||
self.assertLess(acc.accuracy, 0.9)
|
||||
self.assertFalse(acc.passed)
|
||||
self.assertGreater(acc.mae, 0.0)
|
||||
self.assertGreater(acc.rmse, 0.0)
|
||||
|
||||
def test_length_mismatch_raises(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Accuracy.compute([1.0, 2.0], [1.0])
|
||||
|
||||
def test_empty_raises(self):
|
||||
with self.assertRaises(QualityForecastError):
|
||||
Accuracy.compute([], [])
|
||||
|
||||
def test_evaluate_end_to_end(self):
|
||||
# stub 主干在确定性、低噪声线性数据上应能给出确定性的验收结果
|
||||
m = QualityForecastModel(backbone="stub", accuracy_floor=0.0)
|
||||
X, y = _linear_dataset(30)
|
||||
m.fit(X, y)
|
||||
acc = m.evaluate(X, y)
|
||||
self.assertIsInstance(acc, Accuracy)
|
||||
self.assertEqual(acc.to_dict()["accuracy_floor"], 0.0)
|
||||
|
||||
|
||||
class TestSampleRecipes(unittest.TestCase):
|
||||
"""样例协议:同框架加载 Ti / 树脂两套配方均跑通(PRD 5.3 验收口径)。"""
|
||||
|
||||
def test_samples_present(self):
|
||||
names = list_sample_recipes()
|
||||
self.assertIn("recipe.ti.json", names)
|
||||
self.assertIn("recipe.resin.json", names)
|
||||
|
||||
def test_build_from_each_sample_runs(self):
|
||||
for name in ("recipe.ti.json", "recipe.resin.json"):
|
||||
m = build_from_recipe(sample_recipe_path(name))
|
||||
self.assertIn(m.recipe_meta["backbone"], ("gbdt", "dnn", "stub"))
|
||||
# 用配方里声明的特征数构造一份演示数据跑通完整链路
|
||||
feat = m.recipe_meta["feature_columns"]
|
||||
n_feat = len(feat)
|
||||
self.assertGreater(n_feat, 0)
|
||||
X = [[float(i + j) for j in range(n_feat)] for i in range(12)]
|
||||
y = [float(i % 4) + 1.0 for i in range(12)]
|
||||
m.fit(X, y)
|
||||
preds = m.predict(X)
|
||||
self.assertEqual(len(preds), len(y))
|
||||
acc = m.evaluate(X, y)
|
||||
self.assertIsInstance(acc, Accuracy)
|
||||
|
||||
def test_two_recipes_share_same_code(self):
|
||||
"""切换模板仅改配方,模型代码零改动(PRD 5.3)。"""
|
||||
m1 = build_from_recipe(sample_recipe_path("recipe.ti.json"))
|
||||
m2 = build_from_recipe(sample_recipe_path("recipe.resin.json"))
|
||||
self.assertEqual(type(m1), type(m2))
|
||||
self.assertNotEqual(m1.recipe_meta.get("recipe_name"),
|
||||
m2.recipe_meta.get("recipe_name"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user