Compare commits

..
Author SHA1 Message Date
bot_dev1 5bc7ff957e feat(#53): 移动端交接班摘要生成(NL,PRD 场景C ⑤ 移动端交接班摘要)
对应 PRD 场景C(辅助):交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班
报告 → 推送下一班(line 84/350-351)。把本班原始数据 → 移动端交接班摘要这条
链路模板化、可配置、可测试。

新增 core/shift-handover 内核模块:
- handover.py:班次数据归一化(ShiftRecord) + 摘要配置(HandoverBriefConfig) +
  validate/load 校验对 + build_llm_input(填 shift_handover v1.0.1 提示词占位符) +
  generate_handover_brief(LLM 注入生成, 离线/故障自动降级为确定性摘要) +
  render_handover_brief(编译移动端只读卡片 props)
- 零运行时依赖(仅标准库); LLM 以依赖注入传入, 内核不绑定云端 SDK
- 离线/LLM故障降级保证可用性≥99.8%(PRD 模型服务故障自动降级)
- 含 P0/安全事件时强制 requireConfirm=true(PRD 高利害人工确认)

新增资产/测试/验收:
- templates/ti-cl4/dashboard/handover_brief.ti.yaml(Ti 模板配置资产)
- tests/test_handover.py(32 用例全通过) + tests/_bootstrap.py(连字符目录挂载)
- scripts/verify_handover_brief.py(4 能力点全通过: 配置合法/LLM+降级/
  配置点驱动展示/≤2分钟验收线)
- README.md

验证: python -m unittest discover -s tests (32 OK) +
      python scripts/verify_handover_brief.py (全部通过)
2026-08-05 03:38:07 +08:00
19 changed files with 1500 additions and 1872 deletions
+79
View File
@@ -0,0 +1,79 @@
# 移动端交接班摘要模块(iAOP-Core / shift-handover)
对齐 PRD **场景C(辅助)** 与 **5.4「④ LLM 网关」**:
> 交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班报告 → 推送下一班。
以及 PRD 验收口径:交接班报告生成 ≤ 2 分钟(line 350)、移动端交接班摘要可用(line 284/351)。
## 模块状态
| 能力 | Issue | 状态 |
| --- | --- | --- |
| **移动端交接班摘要生成(NL)** | **#53** | **本分支 feature/issue-53** |
`#53` 把"本班原始数据 → 移动端交接班摘要"这条链路**模板化、可配置、可测试**:
班次数据归一化(`ShiftRecord`)→ 按 `HandoverBriefConfig` 经 LLM(或离线确定性降级)
生成摘要 → 编译成移动端只读卡片可直接消费的 props。
## 设计要点
- **零运行时依赖**:与 cockpit / data-bus / llm-gateway 一致,只用标准库;LLM 调用以
**依赖注入**形式传入(`llm_generate: Callable[[str], str]`),内核不绑定云端 SDK,
便于本地闭环与离线降级。
- **离线/故障自动降级**:未注入 LLM 或调用失败时回落到 `render_deterministic_brief`
(PRD「模型服务故障自动降级」「可用性 ≥ 99.8%」),保证交接班链路不中断。
- **声明式 + 强校验**:`validate_handover_config` 收集全部字段级错误(沿用 #50/#52
风格),`load_handover_config` 校验失败抛 `HandoverConfigError` 并携带错误清单。
- **与未合并分支解耦**:不 import `llm-gateway` 的 `PromptRegistry`;仅按约定的
`prompt_template` 名字产出 LLM 输入文本,待 llm-gateway 合入后由调用方注入真正的
LLM 生成函数。
## 配置点(外置为模板资产,切换模板零改码)
| 配置点 | 字段 | 说明 |
| --- | --- | --- |
| 提示词模板 | `promptTemplate` / `promptVersion` | 绑定 `shift_handover` v1.0.1(current) |
| 章节 | `sections` | overview/abnormal/safety/energy/todos |
| 展示策略 | `maxEvents` / `maxTodos` / `collapseThreshold` | 移动端折叠与截断 |
| 字号 | `fontSize` | sm/md/lg |
| 高利害确认 | `requireConfirm` | 默认 false;含 P0/安全事件时内核强制 true |
## 用法
```python
import sys, types, os
# 含连字符目录挂载为 shift_handover 包(同 core/data-bus 的做法)
_d = os.path.join("core", "shift-handover")
if "shift_handover" not in sys.modules:
_p = types.ModuleType("shift_handover"); _p.__path__ = [_d]; sys.modules["shift_handover"] = _p
from shift_handover.handover import (
normalize_shift_record, render_handover_brief, generate_handover_brief,
)
# 1) 班次数据(来自驾驶舱/总线/告警面板聚合)
record = normalize_shift_record({
"shift": "夜班 2026-08-05 00:00~08:00", "operator": "张工",
"overview": "TiCl4 产量 36.2t。",
"events": [{"time": "01:20", "title": "炉层温度越上限", "severity": "P1"}],
"todos": [{"title": "白班复测 3 层温度", "priority": "high"}],
"safety": "注意 3 层高温区巡检。",
})
# 2) 生成摘要(llm_generate=None 时离线降级;注入则用 LLM 输出)
summary = generate_handover_brief(record, llm_generate=my_llm_fn)
# 3) 编译移动端只读卡片 props
props = render_handover_brief(record, summary=summary)
```
## 测试与验收
```bash
# 单元测试(在 core/shift-handover 目录下)
python -m unittest discover -s tests -v # 32 用例全通过
# 验收脚本(4 能力点:配置合法 / LLM+降级 / 配置点驱动展示 / ≤2 分钟)
python scripts/verify_handover_brief.py
```
+75
View File
@@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
"""iAOP-Core · 交接班摘要模块(shift-handover)—— 对齐 PRD 场景C / 5.4「④ LLM 网关」。
对外暴露 issue #53「移动端交接班摘要生成(NL)」的能力:把本班关键事件/能耗/待办/
异常归一为 ``ShiftRecord``,按模板配置(``HandoverBriefConfig``)经 LLM(或离线
确定性降级)生成交接班摘要,并编译成移动端只读卡片可直接消费的 props。
LLM 以依赖注入形式传入(``llm_generate``),内核不绑定具体云端 SDK;未注入或调用
失败时自动降级为 ``render_deterministic_brief``(PRD「模型服务故障自动降级」、
「可用性 ≥ 99.8%」),保证离线/降级时交接班链路不中断。
测试:`python -m unittest discover -s tests -v`(在 core/shift-handover 目录下)。
验收:`python scripts/verify_handover_brief.py`。
"""
from __future__ import annotations
from .handover import ( # noqa: F401
DEFAULT_COLLAPSE_THRESHOLD,
DEFAULT_MAX_EVENTS,
DEFAULT_MAX_TODOS,
DEFAULT_PROMPT_TEMPLATE,
DEFAULT_PROMPT_VERSION,
DEFAULT_REQUIRE_CONFIRM,
HANDOVER_CONFIG_SCHEMA_ID,
HANDOVER_CONFIG_SCHEMA_VERSION,
HANDOVER_GENERATION_BUDGET_MS,
MAX_ALLOWED_EVENTS,
MAX_ALLOWED_TODOS,
VALID_FONT_SIZES,
VALID_SECTIONS,
HandoverBriefConfig,
HandoverConfigError,
HandoverConfigValidationResult,
ShiftEvent,
ShiftRecord,
ShiftTodo,
build_llm_input,
generate_handover_brief,
load_handover_config,
normalize_shift_record,
render_deterministic_brief,
render_handover_brief,
validate_handover_config,
within_generation_budget,
)
__all__ = [
"DEFAULT_COLLAPSE_THRESHOLD",
"DEFAULT_MAX_EVENTS",
"DEFAULT_MAX_TODOS",
"DEFAULT_PROMPT_TEMPLATE",
"DEFAULT_PROMPT_VERSION",
"DEFAULT_REQUIRE_CONFIRM",
"HANDOVER_CONFIG_SCHEMA_ID",
"HANDOVER_CONFIG_SCHEMA_VERSION",
"HANDOVER_GENERATION_BUDGET_MS",
"MAX_ALLOWED_EVENTS",
"MAX_ALLOWED_TODOS",
"VALID_FONT_SIZES",
"VALID_SECTIONS",
"HandoverBriefConfig",
"HandoverConfigError",
"HandoverConfigValidationResult",
"ShiftEvent",
"ShiftRecord",
"ShiftTodo",
"build_llm_input",
"generate_handover_brief",
"load_handover_config",
"normalize_shift_record",
"render_deterministic_brief",
"render_handover_brief",
"validate_handover_config",
"within_generation_budget",
]
+685
View File
@@ -0,0 +1,685 @@
# -*- coding: utf-8 -*-
"""移动端交接班摘要生成(issue #53 / PRD 5.4「④ LLM 网关」+ 场景C「⑤ 配置化驾驶舱」)。
对应 PRD **场景C(辅助)**:
交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班报告 → 推送下一班。
以及 PRD 验收口径:
- 「LLM 报警解释/交接班报告/ NL查询可用 …… **交接班报告生成 ≤ 2 分钟**」;
- 「驾驶舱按 Ti 布局渲染,**移动端交接班摘要可用**」(PRD line 284/351)。
本模块把"本班原始数据 → 移动端交接班摘要"这条链路**模板化、可配置、可测试**:
1. **班次数据归一化**(``ShiftRecord`` / ``normalize_shift_record``):把本班
关键事件 / 能耗 / 待办 / 异常告警等异构输入归一为一份内存模型;
2. **移动端摘要配置**(``HandoverBriefConfig``):摘要包含哪些章节、移动端
展示策略(折叠/字号/最多条数/是否高利害人工确认)、绑定的 LLM 提示词模板名
(``shift_handover`` v1.0.1,见 ``core/llm-gateway/config/prompts.template.yaml``);
3. **LLM 出参渲染**(``build_llm_input``):把班次数据填入 ``shift_handover``
提示词的占位符(``{query}``),产出给 LLM 网关的输入;
4. **摘要生成**(``generate_handover_brief``):调用传入的 LLM 生成函数;当
未配置 LLM(dry-run / 离线 / 单测)时回落到**确定性模板渲染**,保证:
- 离线/降级时仍有可用摘要(PRD「可用性 ≥ 99.8%」「模型服务故障自动降级」);
- 单测无需真实 LLM 即可断言结构与耗时(验收线 ≤ 2 分钟);
5. **移动端负载编译**(``render_handover_brief``):把摘要 + 班次要点编译成
移动端只读卡片可直接消费的 props dict(camelCase、扁平、可 ``json.dumps``)。
设计要点
--------
- **零运行时依赖**:与 cockpit / data-bus / llm-gateway 一致,只用标准库;
LLM 调用以**依赖注入**形式传入(``llm_generate: Callable[[str], str]``),
不在内核里硬编码云端 SDK,便于本地闭环与离线降级。
- **声明式 + 强校验**:``validate_handover_config`` 收集全部字段级错误
(沿用 #50 / #52 的多错误聚合风格),``load_handover_config`` 校验失败抛
``HandoverConfigError`` 并携带错误清单。
- **与未合并分支解耦**:不 import ``llm-gateway`` 的 ``PromptRegistry``(其
feature 分支尚未合入 main);仅按约定的 ``prompt_template`` 名字产出 LLM
输入文本,待 llm-gateway 合入后由调用方注入真正的 LLM 生成函数。
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Any, Callable, Dict, List, Optional, Tuple
# ---------------------------------------------------------------------------
# 版本标识(被交接班摘要配置资产的 $schema 引用)
# ---------------------------------------------------------------------------
HANDOVER_CONFIG_SCHEMA_ID: str = "iAOP-cockpit-handover-brief-v1"
HANDOVER_CONFIG_SCHEMA_VERSION: int = 1
# ---------------------------------------------------------------------------
# 提示词模板绑定(与 core/llm-gateway/config/prompts.template.yaml 对齐)
# ---------------------------------------------------------------------------
# PRD 5.4「Prompt 版本管理」:交接班摘要绑定的提示词模板名 + 版本。
# prompts.template.yaml 中 shift_handover v1.0.1(current)正文含
# 「生产概况/异常事项/安全注意事项」三个章节(v1.0.1 相对 v1.0.0 补充安全章节)。
DEFAULT_PROMPT_TEMPLATE: str = "shift_handover"
DEFAULT_PROMPT_VERSION: str = "1.0.1"
# ---------------------------------------------------------------------------
# 移动端展示策略(默认值,可被模板配置资产覆盖)
# ---------------------------------------------------------------------------
# PRD NFR:移动端只读并发 ≥ 200;交接班摘要是只读卡片,默认折叠次要章节。
DEFAULT_MAX_EVENTS: int = 8
MAX_ALLOWED_EVENTS: int = 50
DEFAULT_MAX_TODOS: int = 5
MAX_ALLOWED_TODOS: int = 30
# 移动端章节折叠阈值:超过该条数则折叠为「展开更多」。
DEFAULT_COLLAPSE_THRESHOLD: int = 4
# 移动端字号档位(与驾驶舱主题档位对齐)。
VALID_FONT_SIZES: Tuple[str, ...] = ("sm", "md", "lg")
# 合法的章节顺序键(与 shift_handover 提示词三章节 + 摘要额外章节对齐)。
VALID_SECTIONS: Tuple[str, ...] = (
"overview", # 生产概况
"abnormal", # 异常事项
"safety", # 安全注意事项
"energy", # 能耗
"todos", # 待办(交下一班)
)
# 高利害标记:交接班摘要通常非高利害(scenarios.template.yaml: high_stakes=false),
# 但若本班出现 P0 告警 / 安全事件,可强制 require_confirm=true(PRD 高利害人工确认)。
DEFAULT_REQUIRE_CONFIRM: bool = False
# 验收线:交接班报告生成 ≤ 2 分钟(PRD line 350),单位毫秒。
HANDOVER_GENERATION_BUDGET_MS: int = 120_000
# ---------------------------------------------------------------------------
# 异常 / 结果
# ---------------------------------------------------------------------------
class HandoverConfigError(ValueError):
"""交接班摘要配置校验失败。``load_handover_config`` 在校验不通过时抛出。
``errors`` 收集全部字段级错误,沿用 #50 / #52 的多错误聚合风格。
"""
def __init__(self, errors: List[str]):
super().__init__(
"; ".join(errors) if errors else "handover brief config validation failed"
)
self.errors: List[str] = list(errors)
@dataclass
class HandoverConfigValidationResult:
"""``validate_handover_config`` 的返回值。"""
ok: bool
errors: List[str] = field(default_factory=list)
normalized: Optional[Dict[str, Any]] = None
# ---------------------------------------------------------------------------
# 班次数据内存模型
# ---------------------------------------------------------------------------
@dataclass
class ShiftEvent:
"""本班一条关键事件(告警 / 操作 / 质量波动等)。
Attributes:
time: 事件时间(ISO 字符串或可读文本,如 ``"03:12"``)。
title: 事件标题(移动端卡片主文案)。
severity: 严重度(``P0`` / ``P1`` / ``P2`` / ``info``;与告警面板对齐)。
detail: 可选详情(移动端「展开更多」)。
"""
time: str
title: str
severity: str = "info"
detail: Optional[str] = None
@dataclass
class ShiftTodo:
"""交接给下一班的待办。
Attributes:
title: 待办内容。
priority: 优先级(``high`` / ``medium`` / ``low``)。
due: 可选截止提示(如 ``"接班后 30min 内"``)。
"""
title: str
priority: str = "medium"
due: Optional[str] = None
@dataclass
class ShiftRecord:
"""一个班次的归一化数据(移动端交接班摘要的输入)。
所有字段均有合理默认值:哪怕只给 ``shift`` / ``operator`` 也能产出一份
可用摘要(降级友好)。
Attributes:
shift: 班次标识(如 ``"夜班 2026-08-05 00:00~08:00"``)。
operator: 交班人/值班长。
overview: 生产概况自由文本(产量/批次/质量达成等)。
events: 关键事件列表(按时间顺序)。
todos: 交接待办列表。
energy: 能耗小结(自由文本或结构化键值,如 ``"总电耗 12.4 万 kWh"``)。
safety: 安全注意事项自由文本。
next_shift: 下一班接班人(可选,用于推送)。
"""
shift: str
operator: str
overview: str = ""
events: List[ShiftEvent] = field(default_factory=list)
todos: List[ShiftTodo] = field(default_factory=list)
energy: str = ""
safety: str = ""
next_shift: Optional[str] = None
# ---------------------------------------------------------------------------
# 摘要配置内存模型
# ---------------------------------------------------------------------------
@dataclass
class HandoverBriefConfig:
"""一份移动端交接班摘要配置(对应一份模板级配置资产)。
切换行业模板 = 加载另一份 ``HandoverBriefConfig``,移动端卡片代码零改动
(与 #52 告警面板配置化同一验收口径)。
"""
prompt_template: str = DEFAULT_PROMPT_TEMPLATE
prompt_version: str = DEFAULT_PROMPT_VERSION
sections: List[str] = field(
default_factory=lambda: list(VALID_SECTIONS)
)
max_events: int = DEFAULT_MAX_EVENTS
max_todos: int = DEFAULT_MAX_TODOS
collapse_threshold: int = DEFAULT_COLLAPSE_THRESHOLD
font_size: str = "md"
require_confirm: bool = DEFAULT_REQUIRE_CONFIRM
schema: str = HANDOVER_CONFIG_SCHEMA_ID
# ---------------------------------------------------------------------------
# 校验器
# ---------------------------------------------------------------------------
def _is_str_nonempty(value: Any) -> bool:
return isinstance(value, str) and value.strip() != ""
def validate_handover_config(config: Any) -> HandoverConfigValidationResult:
"""对一份交接班摘要配置资产做结构 + 语义校验,返回校验结果。
非法资产不提前返回:尽量收集全部字段级错误,便于配置台一次性展示
「错误列表(字段 + 原因)」,与 #50 / #52 行为一致。
"""
errors: List[str] = []
if not isinstance(config, dict):
return HandoverConfigValidationResult(
ok=False,
errors=[f"配置必须是对象(dict),实际为 {type(config).__name__}"],
)
# $schema(选填,但若给出必须对齐版本标识)
schema = config.get("$schema")
if schema is not None and schema != HANDOVER_CONFIG_SCHEMA_ID:
errors.append(
f"$schema: 应为 {HANDOVER_CONFIG_SCHEMA_ID!r},实际为 {schema!r}"
)
# promptTemplate:非空字符串
prompt_template = config.get(
"promptTemplate", config.get("prompt_template", DEFAULT_PROMPT_TEMPLATE)
)
if not _is_str_nonempty(prompt_template):
errors.append("promptTemplate: 缺失或非非空字符串")
# promptVersion:非空字符串(semver 由 llm-gateway 校验,这里只要求非空)
prompt_version = config.get(
"promptVersion", config.get("prompt_version", DEFAULT_PROMPT_VERSION)
)
if not _is_str_nonempty(prompt_version):
errors.append("promptVersion: 缺失或非非空字符串")
# sections:列表、每项在 VALID_SECTIONS 内、至少 1 项、无重复
raw_sections = config.get("sections", list(VALID_SECTIONS))
norm_sections: List[str] = []
if not isinstance(raw_sections, list) or not raw_sections:
errors.append(
f"sections: 缺失或非列表(至少 1 项,合法值 {list(VALID_SECTIONS)})"
)
else:
seen: set = set()
for i, s in enumerate(raw_sections):
if not _is_str_nonempty(s):
errors.append(f"sections[{i}]: 必须是非空字符串")
continue
if s not in VALID_SECTIONS:
errors.append(
f"sections[{i}]: 非法 {s!r},合法值 {list(VALID_SECTIONS)}"
)
continue
if s in seen:
errors.append(f"sections[{i}]: {s!r} 重复声明")
continue
seen.add(s)
norm_sections.append(s)
# maxEvents:1..MAX_ALLOWED_EVENTS
max_events = config.get("maxEvents", config.get("max_events", DEFAULT_MAX_EVENTS))
if (
isinstance(max_events, bool)
or not isinstance(max_events, int)
or not (1 <= max_events <= MAX_ALLOWED_EVENTS)
):
errors.append(
f"maxEvents: 必须是 1..{MAX_ALLOWED_EVENTS} 的整数,实际为 {max_events!r}"
)
# maxTodos:1..MAX_ALLOWED_TODOS
max_todos = config.get("maxTodos", config.get("max_todos", DEFAULT_MAX_TODOS))
if (
isinstance(max_todos, bool)
or not isinstance(max_todos, int)
or not (1 <= max_todos <= MAX_ALLOWED_TODOS)
):
errors.append(
f"maxTodos: 必须是 1..{MAX_ALLOWED_TODOS} 的整数,实际为 {max_todos!r}"
)
# collapseThreshold:0..max(maxEvents, maxTodos)
collapse_threshold = config.get(
"collapseThreshold", config.get("collapse_threshold", DEFAULT_COLLAPSE_THRESHOLD)
)
if (
isinstance(collapse_threshold, bool)
or not isinstance(collapse_threshold, int)
or collapse_threshold < 0
):
errors.append(
f"collapseThreshold: 必须是非负整数,实际为 {collapse_threshold!r}"
)
# fontSize:枚举
font_size = config.get("fontSize", config.get("font_size", "md"))
if font_size not in VALID_FONT_SIZES:
errors.append(
f"fontSize: 非法 {font_size!r},合法值 {list(VALID_FONT_SIZES)}"
)
# requireConfirm:布尔
require_confirm = config.get(
"requireConfirm", config.get("require_confirm", DEFAULT_REQUIRE_CONFIRM)
)
if not isinstance(require_confirm, bool):
errors.append(
f"requireConfirm: 必须是布尔,实际为 {type(require_confirm).__name__}"
)
if errors:
return HandoverConfigValidationResult(ok=False, errors=errors)
normalized: Dict[str, Any] = {
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
"promptTemplate": prompt_template,
"promptVersion": prompt_version,
"sections": norm_sections or list(VALID_SECTIONS),
"maxEvents": max_events,
"maxTodos": max_todos,
"collapseThreshold": collapse_threshold,
"fontSize": font_size,
"requireConfirm": require_confirm,
}
return HandoverConfigValidationResult(ok=True, errors=[], normalized=normalized)
def load_handover_config(config: Any) -> HandoverBriefConfig:
"""从已解析的 dict 构造 ``HandoverBriefConfig``(校验失败抛 ``HandoverConfigError``)。
与 #52 ``load_alarm_config`` 对称:先校验再按规范化结果构造内存模型。
"""
result = validate_handover_config(config)
if not result.ok:
raise HandoverConfigError(result.errors)
assert result.normalized is not None
n = result.normalized
return HandoverBriefConfig(
prompt_template=n["promptTemplate"],
prompt_version=n["promptVersion"],
sections=n["sections"],
max_events=n["maxEvents"],
max_todos=n["maxTodos"],
collapse_threshold=n["collapseThreshold"],
font_size=n["fontSize"],
require_confirm=n["requireConfirm"],
schema=HANDOVER_CONFIG_SCHEMA_ID,
)
# ---------------------------------------------------------------------------
# 班次数据归一化(从 dict → ShiftRecord)
# ---------------------------------------------------------------------------
def normalize_shift_record(raw: Any) -> ShiftRecord:
"""把一份班次数据 dict 归一为 ``ShiftRecord``。
用于从驾驶舱 / 总线 / 告警面板聚合出的原始数据(JSON)转入内存模型。
宽松解析:缺字段给默认值;非法字段抛 ``HandoverConfigError`` 携带错误清单。
"""
errors: List[str] = []
if not isinstance(raw, dict):
raise HandoverConfigError(
[f"班次数据必须是对象(dict),实际为 {type(raw).__name__}"]
)
shift = raw.get("shift", "")
operator = raw.get("operator", "")
if not _is_str_nonempty(shift):
errors.append("shift: 缺失或非非空字符串(班次标识必填)")
if not _is_str_nonempty(operator):
errors.append("operator: 缺失或非非空字符串(交班人必填)")
events: List[ShiftEvent] = []
raw_events = raw.get("events", [])
if raw_events is None:
raw_events = []
if not isinstance(raw_events, list):
errors.append("events: 必须是列表")
else:
for i, e in enumerate(raw_events):
if not isinstance(e, dict):
errors.append(f"events[{i}]: 必须是对象(dict)")
continue
t = e.get("time")
title = e.get("title")
if not _is_str_nonempty(t):
errors.append(f"events[{i}].time: 缺失或非非空字符串")
continue
if not _is_str_nonempty(title):
errors.append(f"events[{i}].title: 缺失或非非空字符串")
continue
events.append(
ShiftEvent(
time=t,
title=title,
severity=e.get("severity", "info"),
detail=e.get("detail"),
)
)
todos: List[ShiftTodo] = []
raw_todos = raw.get("todos", [])
if raw_todos is None:
raw_todos = []
if not isinstance(raw_todos, list):
errors.append("todos: 必须是列表")
else:
for i, td in enumerate(raw_todos):
if not isinstance(td, dict):
errors.append(f"todos[{i}]: 必须是对象(dict)")
continue
title = td.get("title")
if not _is_str_nonempty(title):
errors.append(f"todos[{i}].title: 缺失或非非空字符串")
continue
todos.append(
ShiftTodo(
title=title,
priority=td.get("priority", "medium"),
due=td.get("due"),
)
)
if errors:
raise HandoverConfigError(errors)
return ShiftRecord(
shift=str(shift),
operator=str(operator),
overview=str(raw.get("overview", "")) or "",
events=events,
todos=todos,
energy=str(raw.get("energy", "")) or "",
safety=str(raw.get("safety", "")) or "",
next_shift=raw.get("next_shift"),
)
# ---------------------------------------------------------------------------
# LLM 输入渲染(填 shift_handover 提示词占位符)
# ---------------------------------------------------------------------------
def build_llm_input(
record: ShiftRecord,
config: Optional[HandoverBriefConfig] = None,
) -> Tuple[str, str]:
"""把班次数据填入 ``shift_handover`` 提示词,产出给 LLM 网关的输入。
返回 ``(prompt_template_name, rendered_text)``:
- ``prompt_template_name`` 来自配置(默认 ``shift_handover``),调用方据此
绑定 llm-gateway 的 ``PromptRegistry`` 版本(PRD「运行时绑定模板版本」);
- ``rendered_text`` 是提示词正文(占位符 ``{query}`` 已替换为本班结构化摘要)。
与 prompts.template.yaml 中 ``shift_handover v1.0.1`` 正文
(「生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:{query}」)
对齐:把结构化班次数据序列化为 ``{query}`` 占位的班次文本。
"""
if config is None:
config = HandoverBriefConfig()
# 班次结构化摘要文本(作为 {query} 的填充)
parts: List[str] = [f"班次:{record.shift}", f"交班人:{record.operator}"]
if record.overview:
parts.append(f"生产概况:{record.overview}")
if record.events:
lines = ["关键事件:"]
for e in record.events:
tag = f"[{e.severity}]" if e.severity and e.severity != "info" else ""
line = f"- {e.time} {tag} {e.title}".rstrip()
if e.detail:
line += f"({e.detail})"
lines.append(line)
parts.append("\n".join(lines))
if record.energy:
parts.append(f"能耗:{record.energy}")
if record.safety:
parts.append(f"安全注意事项:{record.safety}")
if record.todos:
lines = ["待办(交下一班):"]
for td in record.todos:
line = f"- [{td.priority}] {td.title}"
if td.due:
line += f"({td.due})"
lines.append(line)
parts.append("\n".join(lines))
query = "\n".join(parts)
# shift_handover 提示词正文:生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:{query}
rendered = (
"生成交接班摘要,包含:生产概况、异常事项、安全注意事项。班次:\n" + query
)
return config.prompt_template, rendered
# ---------------------------------------------------------------------------
# 确定性降级渲染(无 LLM 时的离线摘要)
# ---------------------------------------------------------------------------
def render_deterministic_brief(
record: ShiftRecord,
config: Optional[HandoverBriefConfig] = None,
) -> str:
"""无 LLM(dry-run / 离线 / LLM 故障降级)时的确定性交接班摘要。
PRD NFR「可用性 ≥ 99.8%」「模型服务故障自动降级」:当 LLM 网关不可用时,
交接班摘要链路不能中断,回落到基于班次数据的模板拼接摘要。输出与
``shift_handover`` 提示词三章节(生产概况/异常事项/安全注意事项)结构对齐,
额外补充能耗与待办章节。
"""
if config is None:
config = HandoverBriefConfig()
sections = config.sections
blocks: List[str] = [f"# {record.shift} 交接班摘要", f"交班人:{record.operator}"]
def _add(title: str, body: str) -> None:
if body and body.strip():
blocks.append(f"\n## {title}\n{body.strip()}")
if "overview" in sections:
_add("生产概况", record.overview or "(本班生产平稳,无显著波动)")
if "abnormal" in sections:
if record.events:
lines = []
for e in record.events:
tag = f"[{e.severity}]" if e.severity and e.severity != "info" else ""
line = f"- {e.time} {tag} {e.title}".rstrip()
if e.detail:
line += f"({e.detail})"
lines.append(line)
_add("异常事项", "\n".join(lines))
else:
_add("异常事项", "本班无关键异常事件。")
if "safety" in sections:
_add("安全注意事项", record.safety or "无特殊安全注意事项。")
if "energy" in sections:
_add("能耗", record.energy or "(未填报能耗数据)")
if "todos" in sections:
if record.todos:
lines = [
f"- [{td.priority}] {td.title}" + (f"({td.due})" if td.due else "")
for td in record.todos
]
_add("待办(交下一班)", "\n".join(lines))
else:
_add("待办(交下一班)", "无待办事项。")
return "\n".join(blocks)
# ---------------------------------------------------------------------------
# 摘要生成主入口(注入 LLM,离线自动降级)
# ---------------------------------------------------------------------------
def generate_handover_brief(
record: ShiftRecord,
config: Optional[HandoverBriefConfig] = None,
llm_generate: Optional[Callable[[str], str]] = None,
) -> str:
"""生成交接班摘要文本(PRD 场景C,验收线 ≤ 2 分钟)。
Args:
record: 归一化班次数据。
config: 摘要配置(章节/移动端策略/提示词模板);None 用默认。
llm_generate: LLM 生成函数(输入提示词文本,返回摘要文本)。None 或
调用失败时**自动降级**为 ``render_deterministic_brief``(离线可用)。
Returns:
交接班摘要文本(含生产概况/异常事项/安全注意事项等章节)。
设计:LLM 以依赖注入传入,内核不绑定具体云端 SDK,保证本地闭环与离线降级。
"""
if config is None:
config = HandoverBriefConfig()
if llm_generate is None:
return render_deterministic_brief(record, config)
_, rendered = build_llm_input(record, config)
try:
text = llm_generate(rendered)
except Exception:
# LLM 故障 → 降级为确定性摘要(PRD「模型服务故障自动降级」)
return render_deterministic_brief(record, config)
if not _is_str_nonempty(text):
return render_deterministic_brief(record, config)
return text
# ---------------------------------------------------------------------------
# 移动端负载编译(摘要 + 班次要点 → 移动端只读卡片 props)
# ---------------------------------------------------------------------------
def render_handover_brief(
record: ShiftRecord,
config: Optional[HandoverBriefConfig] = None,
summary: Optional[str] = None,
llm_generate: Optional[Callable[[str], str]] = None,
generated_at: Optional[datetime] = None,
) -> Dict[str, Any]:
"""把班次数据 + 摘要编译成移动端只读卡片可直接消费的 props dict。
Args:
record: 班次数据。
config: 摘要配置;None 用默认。
summary: 已生成的摘要文本;None 则调用 ``generate_handover_brief`` 生成。
llm_generate: 透传给 ``generate_handover_brief``(None 时离线降级)。
generated_at: 摘要生成时间(用于卡片时间戳);None 取当前 UTC。
Returns:
扁平、camelCase、可 ``json.dumps`` 的 props dict,移动端 ``HandoverBrief``
组件据此渲染标题/章节/事件/待办/折叠策略/字号(**切换行业模板只换配置资产,
移动端代码零改动**,与 #52 同一验收口径)。
"""
if config is None:
config = HandoverBriefConfig()
if summary is None:
summary = generate_handover_brief(record, config, llm_generate)
if generated_at is None:
generated_at = datetime.now(timezone.utc)
# 按 maxEvents / maxTodos 截断,移动端展示策略由配置驱动
truncated_events = record.events[: config.max_events]
truncated_todos = record.todos[: config.max_todos]
# 是否含 P0 / safety 事件 → 强制 requireConfirm(PRD 高利害人工确认)
has_critical = any(e.severity == "P0" for e in record.events) or bool(
record.safety and record.safety.strip()
)
require_confirm = config.require_confirm or has_critical
props: Dict[str, Any] = {
"schema": config.schema,
"shift": record.shift,
"operator": record.operator,
"nextShift": record.next_shift,
"summary": summary,
"generatedAt": generated_at.strftime("%Y-%m-%dT%H:%M:%SZ"),
"promptTemplate": config.prompt_template,
"promptVersion": config.prompt_version,
"sections": list(config.sections),
"events": [
{
"time": e.time,
"title": e.title,
"severity": e.severity,
"detail": e.detail,
}
for e in truncated_events
],
"todos": [
{"title": t.title, "priority": t.priority, "due": t.due}
for t in truncated_todos
],
"eventOverflow": max(0, len(record.events) - config.max_events),
"todoOverflow": max(0, len(record.todos) - config.max_todos),
"collapseThreshold": config.collapse_threshold,
"fontSize": config.font_size,
"requireConfirm": require_confirm,
# 演示「配置点真实驱动展示」:章节开关决定卡片渲染哪些区块
"showOverview": "overview" in config.sections,
"showAbnormal": "abnormal" in config.sections,
"showSafety": "safety" in config.sections,
"showEnergy": "energy" in config.sections,
"showTodos": "todos" in config.sections,
}
return props
def within_generation_budget(elapsed_ms: float) -> bool:
"""判断本次摘要生成是否满足 PRD 验收线「交接班报告生成 ≤ 2 分钟」。
供验收脚本断言耗时用。
"""
return elapsed_ms <= HANDOVER_GENERATION_BUDGET_MS
@@ -0,0 +1,208 @@
# -*- coding: utf-8 -*-
"""移动端交接班摘要验收脚本(issue #53,PRD 场景C 验收口径)。
验证四个能力点(覆盖 PRD「交接班报告生成 ≤ 2 分钟」「移动端交接班摘要可用」):
1. **Ti 行业模板配置资产合法**:交接班摘要配置通过 ``iAOP-cockpit-handover-brief-v1``
校验,并能构造 ``HandoverBriefConfig``;
2. **LLM 注入生成 + 离线降级**:注入 LLM 时用其输出;LLM 故障/未注入时自动降级为
确定性摘要(PRD「模型服务故障自动降级」「可用性 ≥ 99.8%」),且降级摘要含
「生产概况/异常事项/安全注意事项」三章节(对齐 shift_handover 提示词);
3. **配置点真实驱动展示**:``sections`` / ``maxEvents`` / ``requireConfirm`` 配置项
改变 → 移动端 props 随之变化(切换模板零改码,与 #52 同一验收口径);含 P0 事件
→ ``requireConfirm`` 被强制为 true(PRD 高利害人工确认);
4. **生成耗时达标**:确定性降级路径在 2 分钟验收线内(PRD line 350)。
用法(在 core/shift-handover 目录下):
python scripts/verify_handover_brief.py
退出码:0 = 全部通过;1 = 存在未达标项。
说明:本脚本不依赖 PyYAML(保持零运行时依赖),用与 Ti 模板资产等价的 dict 校验。
"""
from __future__ import annotations
import os
import sys
import time
# 本脚本位于 core/shift-handover/scripts/,需把 core/ 加入 sys.path
sys.path.insert(
0,
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
)
# 含连字符的目录无法直接以包名 import:挂载为 shift_handover 后导入子模块
import types # noqa: E402
_SHIFT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if "shift_handover" not in sys.modules:
_pkg = types.ModuleType("shift_handover")
_pkg.__path__ = [_SHIFT_DIR]
sys.modules["shift_handover"] = _pkg
from shift_handover.handover import ( # noqa: E402
HANDOVER_CONFIG_SCHEMA_ID,
HANDOVER_GENERATION_BUDGET_MS,
HandoverBriefConfig,
generate_handover_brief,
load_handover_config,
normalize_shift_record,
render_handover_brief,
within_generation_budget,
)
def _ti_config() -> dict:
"""与 templates/ti-cl4/dashboard/handover_brief.ti.yaml 等价的 dict。"""
return {
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
"promptTemplate": "shift_handover",
"promptVersion": "1.0.1",
"sections": ["overview", "abnormal", "safety", "energy", "todos"],
"maxEvents": 8,
"maxTodos": 5,
"collapseThreshold": 4,
"fontSize": "md",
"requireConfirm": False,
}
def _ti_shift_record() -> dict:
"""Ti 氯化车间夜班典型班次数据。"""
return {
"shift": "夜班 2026-08-05 00:00~08:00",
"operator": "张工",
"overview": "TiCl4 产量 36.2t,质量达成率 98.6%。",
"events": [
{"time": "01:20", "title": "炉层温度越上限",
"severity": "P1", "detail": "CLF-01 第3层 942℃,已调风量回落"},
{"time": "03:05", "title": "夜巡正常", "severity": "info"},
],
"todos": [
{"title": "白班复测 3 层温度趋势", "priority": "high", "due": "接班后 1h"},
{"title": "补录 LIMS 03:00 批次", "priority": "medium"},
],
"energy": "总电耗 12.4 万 kWh",
"safety": "夜班无安全事件;注意 3 层高温区巡检。",
"next_shift": "李工",
}
def main() -> int:
all_ok = True
def _check(title: str, fn):
nonlocal all_ok
try:
ok = fn()
except Exception as exc: # noqa: BLE001
ok = False
print(f" ✗ {title}:异常 {exc!r}")
status = "✅" if ok else "❌"
print(f" {status} {title}")
all_ok = all_ok and ok
print("=" * 64)
print("移动端交接班摘要验收(issue #53 / PRD 场景C)")
print("=" * 64)
# 1) Ti 模板配置资产合法
def check_config_valid() -> bool:
cfg = load_handover_config(_ti_config())
return (
isinstance(cfg, HandoverBriefConfig)
and cfg.prompt_template == "shift_handover"
and cfg.prompt_version == "1.0.1"
and cfg.font_size == "md"
)
_check("Ti 模板配置资产合法(iAOP-cockpit-handover-brief-v1)", check_config_valid)
# 2) LLM 注入生成 + 离线降级
def check_llm_and_fallback() -> bool:
rec = normalize_shift_record(_ti_shift_record())
# 注入 LLM:用其输出
def llm(prompt: str) -> str:
return "【LLM 摘要】本班平稳,3 层温度曾越限已处置,交白班复测。"
with_llm = generate_handover_brief(rec, llm_generate=llm)
# 离线降级(不注入 LLM)
fallback = generate_handover_brief(rec)
# LLM 故障降级
def broken(prompt: str) -> str:
raise RuntimeError("LLM 网关不可达")
degraded = generate_handover_brief(rec, llm_generate=broken)
return (
with_llm.startswith("【LLM 摘要】")
and "交接班摘要" in fallback
and "生产概况" in fallback
and "异常事项" in fallback
and "安全注意事项" in fallback
and "交接班摘要" in degraded # 故障也降级为可用摘要
)
_check("LLM 注入生成 + 离线/故障降级为可用摘要", check_llm_and_fallback)
# 3) 配置点真实驱动移动端展示
def check_config_drives_props() -> bool:
rec = normalize_shift_record(_ti_shift_record())
props = render_handover_brief(rec)
# 默认配置下事件/待办齐全、章节开关正确
base_ok = (
len(props["events"]) == 2
and len(props["todos"]) == 2
and props["showOverview"] is True
and props["showAbnormal"] is True
and props["eventOverflow"] == 0
)
# sections 收窄 → 对应章节开关关闭
cfg2 = HandoverBriefConfig(sections=["overview"])
props2 = render_handover_brief(rec, cfg2)
sections_ok = (
props2["showOverview"] is True
and props2["showAbnormal"] is False
and props2["showTodos"] is False
)
# maxEvents 截断 + 溢出计数
many = {
"shift": "夜班", "operator": "张工",
"events": [{"time": f"0{i}:00", "title": f"事件{i}"} for i in range(12)],
}
rec_many = normalize_shift_record(many)
cfg3 = HandoverBriefConfig(max_events=5)
props3 = render_handover_brief(rec_many, cfg3)
trunc_ok = len(props3["events"]) == 5 and props3["eventOverflow"] == 7
# 含 P0 事件 → requireConfirm 被强制为 true
critical = {
"shift": "夜班", "operator": "张工",
"events": [{"time": "01:00", "title": "严重告警", "severity": "P0"}],
}
rec_crit = normalize_shift_record(critical)
props4 = render_handover_brief(rec_crit, HandoverBriefConfig(require_confirm=False))
crit_ok = props4["requireConfirm"] is True
return base_ok and sections_ok and trunc_ok and crit_ok
_check("配置点(sections/maxEvents/requireConfirm)真实驱动移动端展示", check_config_drives_props)
# 4) 生成耗时达标(≤ 2 分钟验收线)
def check_generation_budget() -> bool:
rec = normalize_shift_record(_ti_shift_record())
start = time.perf_counter()
for _ in range(50):
generate_handover_brief(rec) # 离线降级路径
elapsed_ms = (time.perf_counter() - start) * 1000.0
# 单次远小于预算(取平均更稳),且预算判定函数正确
per_call = elapsed_ms / 50.0
return (
per_call < HANDOVER_GENERATION_BUDGET_MS
and within_generation_budget(per_call)
and not within_generation_budget(HANDOVER_GENERATION_BUDGET_MS + 1)
)
_check("生成耗时达标(PRD:交接班报告生成 ≤ 2 分钟)", check_generation_budget)
print("=" * 64)
print("结果: " + ("全部通过 ✅" if all_ok else "存在未达标项 ❌"))
return 0 if all_ok else 1
if __name__ == "__main__":
raise SystemExit(main())
+17
View File
@@ -0,0 +1,17 @@
# -*- coding: utf-8 -*-
"""测试引导:把 `core/shift-handover` 以包名 `shift_handover` 挂载到 sys.modules。
目录名 `shift-handover` 含连字符,无法直接以包名 import;挂载后模块内相对导入
(`from .handover import ...`)在 unittest 发现机制下可正常解析。
(沿用 core/data-bus/tests/_bootstrap.py 的同一做法。)
"""
import os
import sys
import types
SHIFT_HANDOVER_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, SHIFT_HANDOVER_DIR)
if "shift_handover" not in sys.modules:
pkg = types.ModuleType("shift_handover")
pkg.__path__ = [SHIFT_HANDOVER_DIR]
sys.modules["shift_handover"] = pkg
+400
View File
@@ -0,0 +1,400 @@
# -*- coding: utf-8 -*-
"""移动端交接班摘要生成单元测试(issue #53 / PRD 场景C / 5.4「④ LLM 网关」)。
覆盖:
1. 配置校验:合法配置通过、默认值与字段别名、sections 去重与枚举校验、
maxEvents/maxTodos/collapseThreshold/fontSize/requireConfirm 各类非法情况;
2. ``load_handover_config`` 校验失败抛 ``HandoverConfigError`` 并携带全部错误;
3. ``normalize_shift_record``:合法 dict → ShiftRecord;缺必填/非法结构被拒;
4. ``build_llm_input``:占位符填充正确、含班次/事件/能耗/待办;
5. ``render_deterministic_brief``:章节与配置 sections 联动;
6. ``generate_handover_brief``:注入 LLM 用其输出;LLM 抛异常/返回空 → 自动降级;
7. ``render_handover_brief``:props 结构正确、截断/溢出计数/高利害强制确认;
8. ``within_generation_budget``:2 分钟验收线判定。
"""
from __future__ import annotations
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: F401 把 core/shift-handover 挂载为 shift_handover 包
from shift_handover.handover import ( # type: ignore[import-not-found]
DEFAULT_PROMPT_TEMPLATE,
DEFAULT_PROMPT_VERSION,
HANDOVER_CONFIG_SCHEMA_ID,
HANDOVER_GENERATION_BUDGET_MS,
HandoverBriefConfig,
HandoverConfigError,
HandoverConfigValidationResult,
ShiftEvent,
ShiftRecord,
ShiftTodo,
build_llm_input,
generate_handover_brief,
load_handover_config,
normalize_shift_record,
render_deterministic_brief,
render_handover_brief,
validate_handover_config,
within_generation_budget,
)
def _valid_config() -> dict:
"""返回一份合法的交接班摘要配置(Ti 模板风格)。"""
return {
"$schema": HANDOVER_CONFIG_SCHEMA_ID,
"promptTemplate": "shift_handover",
"promptVersion": "1.0.1",
"sections": ["overview", "abnormal", "safety", "energy", "todos"],
"maxEvents": 8,
"maxTodos": 5,
"collapseThreshold": 4,
"fontSize": "md",
"requireConfirm": False,
}
def _full_record_dict() -> dict:
return {
"shift": "夜班 2026-08-05 00:00~08:00",
"operator": "张工",
"overview": "TiCl4 产量 36.2t,质量达成率 98.6%。",
"events": [
{"time": "01:20", "title": "炉层温度越上限", "severity": "P1",
"detail": "CLF-01 第3层 942℃ → 已调风量"},
{"time": "03:05", "title": "夜巡正常", "severity": "info"},
],
"todos": [
{"title": "白班复测 3 层温度趋势", "priority": "high", "due": "接班后 1h"},
{"title": "补录 LIMS 03:00 批次", "priority": "medium"},
],
"energy": "总电耗 12.4 万 kWh",
"safety": "夜班无安全事件;注意 3 层高温区巡检。",
"next_shift": "李工",
}
# ---------------------------------------------------------------------------
# 1) 配置校验
# ---------------------------------------------------------------------------
class TestValidateConfig(unittest.TestCase):
def test_valid_config_passes(self):
res = validate_handover_config(_valid_config())
self.assertTrue(res.ok, msg=res.errors)
self.assertEqual(res.errors, [])
self.assertEqual(res.normalized["$schema"], HANDOVER_CONFIG_SCHEMA_ID)
def test_defaults_and_aliases(self):
# snake_case 与 camelCase 都接受;缺省给默认值
cfg = {"prompt_template": "shift_handover", "prompt_version": "1.0.0"}
res = validate_handover_config(cfg)
self.assertTrue(res.ok, msg=res.errors)
n = res.normalized
self.assertEqual(n["maxEvents"], 8)
self.assertEqual(n["maxTodos"], 5)
self.assertEqual(n["fontSize"], "md")
self.assertEqual(n["collapseThreshold"], 4)
self.assertFalse(n["requireConfirm"])
# sections 默认为全部合法章节
self.assertEqual(
n["sections"],
["overview", "abnormal", "safety", "energy", "todos"],
)
def test_wrong_schema_rejected(self):
cfg = _valid_config()
cfg["$schema"] = "something-else"
res = validate_handover_config(cfg)
self.assertFalse(res.ok)
self.assertTrue(any("$schema" in e for e in res.errors))
def test_non_dict_rejected(self):
res = validate_handover_config(["not", "a", "dict"])
self.assertFalse(res.ok)
self.assertEqual(len(res.errors), 1)
def test_sections_validation(self):
# 非法章节、重复、空列表、非列表
cases = [
(["overview", "unknown"], "非法枚举"),
(["overview", "overview"], "重复"),
([], "空列表"),
("not-a-list", "非列表"),
]
for bad_sections, hint in cases:
cfg = _valid_config()
cfg["sections"] = bad_sections
res = validate_handover_config(cfg)
self.assertFalse(res.ok, msg=f"{hint} 应被拒绝: {res.errors}")
def test_numeric_bounds(self):
for field, bad in [
("maxEvents", 0), ("maxEvents", 51), ("maxEvents", True),
("maxTodos", 0), ("maxTodos", 31), ("maxTodos", "5"),
("collapseThreshold", -1), ("collapseThreshold", True),
]:
cfg = _valid_config()
cfg[field] = bad
res = validate_handover_config(cfg)
self.assertFalse(res.ok, msg=f"{field}={bad!r} 应被拒绝: {res.errors}")
def test_font_size_enum(self):
cfg = _valid_config()
cfg["fontSize"] = "xl"
res = validate_handover_config(cfg)
self.assertFalse(res.ok)
def test_require_confirm_type(self):
cfg = _valid_config()
cfg["requireConfirm"] = "yes"
res = validate_handover_config(cfg)
self.assertFalse(res.ok)
def test_aggregates_multiple_errors(self):
bad = {
"promptTemplate": "",
"sections": ["oops"],
"maxEvents": 0,
"fontSize": "xxl",
"requireConfirm": 1,
}
res = validate_handover_config(bad)
self.assertFalse(res.ok)
# 至少 5 条字段级错误被聚合
self.assertGreaterEqual(len(res.errors), 5)
# ---------------------------------------------------------------------------
# 2) load_handover_config
# ---------------------------------------------------------------------------
class TestLoadConfig(unittest.TestCase):
def test_load_valid(self):
cfg = load_handover_config(_valid_config())
self.assertIsInstance(cfg, HandoverBriefConfig)
self.assertEqual(cfg.prompt_template, "shift_handover")
self.assertEqual(cfg.prompt_version, "1.0.1")
self.assertEqual(cfg.font_size, "md")
def test_load_invalid_raises_with_errors(self):
with self.assertRaises(HandoverConfigError) as ctx:
load_handover_config({"promptTemplate": "", "maxEvents": 0})
# 异常携带错误清单
self.assertGreaterEqual(len(ctx.exception.errors), 2)
# ---------------------------------------------------------------------------
# 3) normalize_shift_record
# ---------------------------------------------------------------------------
class TestNormalizeRecord(unittest.TestCase):
def test_full_record(self):
rec = normalize_shift_record(_full_record_dict())
self.assertIsInstance(rec, ShiftRecord)
self.assertEqual(rec.shift, "夜班 2026-08-05 00:00~08:00")
self.assertEqual(rec.operator, "张工")
self.assertEqual(len(rec.events), 2)
self.assertEqual(rec.events[0].severity, "P1")
self.assertEqual(rec.todos[0].priority, "high")
self.assertEqual(rec.next_shift, "李工")
def test_minimal_record(self):
rec = normalize_shift_record({"shift": "白班", "operator": "王五"})
self.assertEqual(rec.events, [])
self.assertEqual(rec.todos, [])
self.assertEqual(rec.overview, "")
def test_missing_required_rejected(self):
with self.assertRaises(HandoverConfigError):
normalize_shift_record({"shift": "白班"}) # 缺 operator
def test_bad_event_rejected(self):
raw = _full_record_dict()
raw["events"][0] = {"time": "01:00"} # 缺 title
with self.assertRaises(HandoverConfigError):
normalize_shift_record(raw)
def test_bad_todo_rejected(self):
raw = _full_record_dict()
raw["todos"] = [{"priority": "high"}] # 缺 title
with self.assertRaises(HandoverConfigError):
normalize_shift_record(raw)
def test_non_dict_rejected(self):
with self.assertRaises(HandoverConfigError):
normalize_shift_record("not a dict")
# ---------------------------------------------------------------------------
# 4) build_llm_input
# ---------------------------------------------------------------------------
class TestBuildLLMInput(unittest.TestCase):
def test_renders_prompt_with_placeholders(self):
rec = normalize_shift_record(_full_record_dict())
name, text = build_llm_input(rec)
self.assertEqual(name, DEFAULT_PROMPT_TEMPLATE)
# 正文以 shift_handover 提示词开头
self.assertTrue(text.startswith("生成交接班摘要"))
# 班次与关键字段都被填入 {query}
self.assertIn("夜班 2026-08-05", text)
self.assertIn("张工", text)
self.assertIn("炉层温度越上限", text)
self.assertIn("总电耗", text)
self.assertIn("复测 3 层温度趋势", text)
def test_respects_config_template_name(self):
rec = normalize_shift_record({"shift": "夜班", "operator": "张工"})
cfg = HandoverBriefConfig(prompt_template="custom_tmpl")
name, _ = build_llm_input(rec, cfg)
self.assertEqual(name, "custom_tmpl")
# ---------------------------------------------------------------------------
# 5) render_deterministic_brief
# ---------------------------------------------------------------------------
class TestDeterministicBrief(unittest.TestCase):
def test_contains_all_sections(self):
rec = normalize_shift_record(_full_record_dict())
text = render_deterministic_brief(rec)
self.assertIn("交接班摘要", text)
self.assertIn("生产概况", text)
self.assertIn("异常事项", text)
self.assertIn("安全注意事项", text)
self.assertIn("能耗", text)
self.assertIn("待办", text)
def test_sections_filter(self):
rec = normalize_shift_record(_full_record_dict())
cfg = HandoverBriefConfig(sections=["overview"])
text = render_deterministic_brief(rec, cfg)
self.assertIn("生产概况", text)
# 只开 overview,异常/能耗等章节不应出现为标题
self.assertNotIn("## 异常事项", text)
self.assertNotIn("## 能耗", text)
# ---------------------------------------------------------------------------
# 6) generate_handover_brief(LLM 注入 + 降级)
# ---------------------------------------------------------------------------
class TestGenerateBrief(unittest.TestCase):
def test_uses_llm_output(self):
rec = normalize_shift_record(_full_record_dict())
def llm(prompt: str) -> str:
return "LLM 摘要:本班平稳,3 层温度曾越限已处置。"
out = generate_handover_brief(rec, llm_generate=llm)
self.assertEqual(out, "LLM 摘要:本班平稳,3 层温度曾越限已处置。")
def test_falls_back_when_no_llm(self):
rec = normalize_shift_record(_full_record_dict())
out = generate_handover_brief(rec) # llm_generate=None
self.assertIn("交接班摘要", out)
self.assertIn("炉层温度越上限", out)
def test_falls_back_on_llm_exception(self):
rec = normalize_shift_record(_full_record_dict())
def broken(prompt: str) -> str:
raise RuntimeError("LLM 网关不可达")
out = generate_handover_brief(rec, llm_generate=broken)
# LLM 故障 → 降级为确定性摘要
self.assertIn("交接班摘要", out)
def test_falls_back_on_empty_llm_output(self):
rec = normalize_shift_record(_full_record_dict())
def empty(prompt: str) -> str:
return " "
out = generate_handover_brief(rec, llm_generate=empty)
self.assertIn("交接班摘要", out)
# ---------------------------------------------------------------------------
# 7) render_handover_brief(移动端 props)
# ---------------------------------------------------------------------------
class TestRenderBriefProps(unittest.TestCase):
def test_props_structure(self):
rec = normalize_shift_record(_full_record_dict())
props = render_handover_brief(rec)
self.assertEqual(props["schema"], HANDOVER_CONFIG_SCHEMA_ID)
self.assertEqual(props["shift"], "夜班 2026-08-05 00:00~08:00")
self.assertEqual(props["operator"], "张工")
self.assertEqual(props["nextShift"], "李工")
self.assertEqual(props["promptTemplate"], DEFAULT_PROMPT_TEMPLATE)
self.assertEqual(props["promptVersion"], DEFAULT_PROMPT_VERSION)
self.assertEqual(len(props["events"]), 2)
self.assertEqual(len(props["todos"]), 2)
self.assertEqual(props["eventOverflow"], 0)
self.assertEqual(props["todoOverflow"], 0)
self.assertEqual(props["fontSize"], "md")
# generatedAt 是 ISO 时间戳
self.assertRegex(props["generatedAt"], r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$")
def test_truncation_and_overflow(self):
raw = {
"shift": "夜班", "operator": "张工",
"events": [{"time": f"0{i}:00", "title": f"事件{i}"} for i in range(12)],
"todos": [{"title": f"待办{i}"} for i in range(8)],
}
rec = normalize_shift_record(raw)
cfg = HandoverBriefConfig(max_events=5, max_todos=3)
props = render_handover_brief(rec, cfg)
self.assertEqual(len(props["events"]), 5)
self.assertEqual(len(props["todos"]), 3)
self.assertEqual(props["eventOverflow"], 7)
self.assertEqual(props["todoOverflow"], 5)
def test_critical_event_forces_confirm(self):
raw = {
"shift": "夜班", "operator": "张工",
"events": [{"time": "01:00", "title": "严重告警", "severity": "P0"}],
}
rec = normalize_shift_record(raw)
cfg = HandoverBriefConfig(require_confirm=False)
props = render_handover_brief(rec, cfg)
# 含 P0 事件 → requireConfirm 被强制为 true(PRD 高利害人工确认)
self.assertTrue(props["requireConfirm"])
def test_safety_text_forces_confirm(self):
raw = {
"shift": "夜班", "operator": "张工",
"safety": "注意 3 层高温区巡检。",
}
rec = normalize_shift_record(raw)
cfg = HandoverBriefConfig(require_confirm=False)
props = render_handover_brief(rec, cfg)
self.assertTrue(props["requireConfirm"])
def test_section_switches(self):
rec = normalize_shift_record(_full_record_dict())
cfg = HandoverBriefConfig(sections=["overview", "abnormal"])
props = render_handover_brief(rec, cfg)
self.assertTrue(props["showOverview"])
self.assertTrue(props["showAbnormal"])
self.assertFalse(props["showSafety"])
self.assertFalse(props["showEnergy"])
self.assertFalse(props["showTodos"])
def test_injected_summary_passes_through(self):
rec = normalize_shift_record({"shift": "夜班", "operator": "张工"})
props = render_handover_brief(rec, summary="自定义摘要")
self.assertEqual(props["summary"], "自定义摘要")
# ---------------------------------------------------------------------------
# 8) 验收线
# ---------------------------------------------------------------------------
class TestGenerationBudget(unittest.TestCase):
def test_within_budget(self):
self.assertTrue(within_generation_budget(60_000)) # 1 分钟
self.assertTrue(within_generation_budget(HANDOVER_GENERATION_BUDGET_MS))
self.assertFalse(within_generation_budget(HANDOVER_GENERATION_BUDGET_MS + 1))
if __name__ == "__main__":
unittest.main(verbosity=2)
@@ -0,0 +1,30 @@
# -*- coding: utf-8 -*-
# 氯化车间/海绵钛驾驶舱 · 移动端交接班摘要配置资产(iAOP-Template-Ti 一期)。
#
# 对齐 PRD 场景C(辅助):交接班 → LLM 汇总本班关键事件/能耗/待办 → 生成交接班
# 报告 → 推送下一班(PRD line 84/350-351:交接班报告生成 ≤ 2 分钟、移动端交接班
# 摘要可用)。
#
# 把"移动端交接班摘要"的展示语义(章节/折叠/字号/确认策略/绑定的 LLM 提示词)
# 外置为模板配置(issue #53)。切换到其他行业模板(如树脂)= 换一份本文件,
# 移动端卡片代码零改动(与 #52 同一验收口径「切换模板零改码」)。
#
# $schema 对应 core/shift-handover/handover.py 的 HANDOVER_CONFIG_SCHEMA_ID。
$schema: iAOP-cockpit-handover-brief-v1
# 绑定的提示词模板(core/llm-gateway/config/prompts.template.yaml):
# shift_handover v1.0.1(current)正文含「生产概况/异常事项/安全注意事项」三章节。
promptTemplate: shift_handover
promptVersion: 1.0.1
# 摘要包含的章节(移动端卡片渲染哪些区块):
# overview 生产概况 / abnormal 异常事项 / safety 安全注意事项 /
# energy 能耗 / todos 待办(交下一班)。
sections: [overview, abnormal, safety, energy, todos]
# 移动端展示策略(外置,配置台可调):
maxEvents: 8 # 事件列表最多展示条数(超过折叠 + 溢出计数角标)
maxTodos: 5 # 待办列表最多展示条数
collapseThreshold: 4 # 超过该条数则折叠为「展开更多」
fontSize: md # 移动端字号档位(sm/md/lg)
# 高利害人工确认:交接班摘要通常非高利害(scenarios.template.yaml: high_stakes=false),
# 但若本班出现 P0 告警 / 安全事件,内核会自动强制 requireConfirm=true(见
# render_handover_brief),无需在此显式开启。
requireConfirm: false
@@ -1,22 +0,0 @@
# -*- coding: utf-8 -*-
# 模板「报警解释」场景配置资产:ti-cl4(Template-Ti 一期,issue #74)。
#
# 说明(父 Issue #11「④ LLM 报警解释 / 交接班 / NL 查询」子任务):
# - prompt_template:绑定 llm-gateway 提示词版本库(prompts.template.yaml)
# 中的 alarm_explain 模板(报警解释 + SOP 引用);
# - rag.categories:报警解释**只检索 sop 知识域**(异常处置 SOP),
# 不引入工艺规范/国标噪声,保证引用精准;
# - rag.min_score:检索阈值(TF 密度分),低于阈值视为未命中 →
# 提示"未检索到相关 SOP,请人工确认"(高利害场景宁缺毋滥,PRD 5.4);
# - high_stakes + confidence_threshold:低信度转人工确认(与 #11 验收一致)。
template: ti-cl4
version: 1.0.0
alarm_explain:
prompt_template: alarm_explain
rag:
categories: [sop] # 报警解释知识域:仅异常处置 SOP
top_k: 3
min_score: 0.3 # 检索阈值(低于 = 未命中,降级提示人工)
high_stakes: true
confidence_threshold: 0.8 # 低信度转人工
+6 -38
View File
@@ -19,7 +19,7 @@ from typing import Callable, Dict, List, Optional
from llm_gateway.gateway import GatewayResult, LLMGateway
from llm_gateway.prompts import PromptRegistry
from llm_gateway.router import SensitivityRouter
from rag_kb import KnowledgeSourceKind, RagKnowledgeBase, load_kb_config
from rag_kb import RagKnowledgeBase, load_kb_config
# ---------------------------------------------------------------------------
# 场景配置资产路径
@@ -41,12 +41,6 @@ def scenarios_config_path() -> str:
return os.path.join(_scenarios_dir(), "config", "scenarios.template.yaml")
def alarm_config_path() -> str:
"""报警解释场景配置资产(alarm_explain.template.yaml)路径。"""
return os.path.join(_scenarios_dir(), "config",
"alarm_explain.template.yaml")
def prompts_config_path() -> str:
"""复用 llm-gateway 提示词版本库资产路径。"""
return os.path.join(_repo_root(), "core", "llm-gateway", "config",
@@ -116,7 +110,6 @@ class TiScenarioRunner:
prompts: Optional[PromptRegistry] = None,
router: Optional[SensitivityRouter] = None,
kb_loader: Callable[[str], str] = demo_kb_loader,
alarm_config: Optional[dict] = None,
) -> None:
prompts = prompts or PromptRegistry.from_template_config(prompts_config_path())
kb = kb or RagKnowledgeBase.from_template_config(
@@ -124,8 +117,6 @@ class TiScenarioRunner:
)
router = router or SensitivityRouter.from_template_config(router_config_path())
self.kb = kb
# 报警解释场景配置(issue #74:sop 类目检索 + 检索阈值)
self.alarm_cfg = alarm_config or self._load_alarm_config()
if gateway is not None:
# 注入 gateway:由调用方负责 prompt_name / 高利害配置
self._gateways = {
@@ -150,35 +141,12 @@ class TiScenarioRunner:
# -- 场景 1:报警根因解释(高利害) -----------------------------------
@staticmethod
def _load_alarm_config() -> dict:
"""加载报警解释场景配置资产(issue #74)。"""
import yaml
with open(alarm_config_path(), "r", encoding="utf-8") as fh:
return (yaml.safe_load(fh) or {}).get("alarm_explain", {})
def explain_alarm(self, alarm: str, confidence: float = 1.0,
top_k: Optional[int] = None) -> GatewayResult:
"""解释一条报警的可能原因与处置建议。
RAG 接入(issue #74):只检索 **sop 知识域**(异常处置 SOP),
并按 min_score 过滤——低于阈值视为未命中,降级提示人工确认
(高利害场景宁缺毋滥,避免无据回答)。
"""
rag = self.alarm_cfg.get("rag", {}) or {}
cat_names = rag.get("categories")
categories = ([KnowledgeSourceKind(c) for c in cat_names]
if cat_names else None)
top_k = top_k or int(rag.get("top_k", 3))
min_score = float(rag.get("min_score", 0.0))
hits = self.kb.search(alarm, top_k=top_k, categories=categories)
hits = [h for h in hits if h.score >= min_score]
if hits:
sources = [h.source for h in hits]
else:
# 未检索到 SOP:降级提示人工确认(来源占位,阻断无据回答)
sources = ["未检索到相关 SOP,请人工确认"]
top_k: int = 3) -> GatewayResult:
"""解释一条报警的可能原因与处置建议(RAG 检索异常处置 SOP)。"""
hits = self.kb.search(alarm, top_k=top_k,
categories=None)
sources = [h.source for h in hits]
return self._gateways["alarm_explain"].ask(
alarm, rag_context=sources, confidence=confidence,
)
@@ -105,21 +105,6 @@ class TestScenariosE2E(unittest.TestCase):
self.assertIn("来源", result.answer)
self.assertEqual(result.route.target, RouteTarget.LOCAL)
def test_explain_alarm_rag_sop_only(self):
"""报警解释 RAG 接入(issue #74):只检索 sop 知识域并回显来源。"""
result = self.runner.explain_alarm("炉温超上限报警怎么处理")
# 演示库 sop 类目(异常处置SOP)应被检索到并随答案溯源
self.assertIn("SOP", result.answer)
def test_explain_alarm_min_score_fallback(self):
"""检索阈值(issue #74):低分视为未命中 → 降级提示人工确认。"""
# 注入高 min_score 配置:正常演示库检索得分低于阈值 → 降级
runner = TiScenarioRunner(alarm_config={
"rag": {"categories": ["sop"], "top_k": 3, "min_score": 99.0},
})
result = runner.explain_alarm("炉温超上限报警怎么处理")
self.assertIn("人工确认", result.answer)
def test_shift_handover(self):
result = self.runner.generate_handover("甲班:生产平稳,炉温正常,无异常事项")
self.assertTrue(result.answer)
-43
View File
@@ -1,43 +0,0 @@
# Ti-2 配方动态优化(recipe-optim)
> 对应 issue #78(问题建模)/ #79(求解器集成)/ #80(跨工序寻优)/ #81(可解释建议)。
> PRD §5.3 ②「配方动态优化」:`入:质量目标 + 约束;出:参数/配方建议`,二期交付。
本目录沉淀**配方优化**的声明式模板资产 + 求解器无关的问题建模引擎,跨行业差异落
资产(YAML 模板),引擎零改动(PRD「超参包驱动」「模板化技术路径」)。
## 模块
- `problem.py` — 优化问题建模(**#78**):决策变量 / 目标 / 约束的声明式规格 +
校验 + 可行性判定 + 零依赖 YAML 子集加载。
- `solver.py` — 求解器集成(**#79**):`SolverConfig` + `Solution` + 网格枚举/
坐标下降轻量求解器 + `solve()` 统一入口,求解器无关契约。
- `config/recipe_optim.template.yaml` — Template-Ti 配方优化模板资产。
- `tests/` — 单元测试(`python -m unittest discover -s tests`,46 用例)。
- `_sanity_check.py` — 部署期一键自检(6 能力点)。
## 设计
1. **决策变量 `DecisionVariable`**:`bounds`(连续区间)/`choices`(离散枚举),
带 `meaning`/`unit`/`initial`,供 #81 可解释建议引用。
2. **目标 `ObjectiveSpec`**:线性加权(min/max)+ PRD 超参包 `target` 字段。
3. **约束 `ConstraintSpec`**:统一描述 box / linear / ratio / forbidden 工艺约束,
每条带 `reason`(工艺依据,对齐 PRD"可解释、可溯源、引用依据")。
4. **问题 `OptimizationProblem`**:`validate` 聚合静态校验、`is_feasible` /
`violated_constraints` 做可行性判定,`solve` 留给 #79 注入求解器(求解器无关)。
## 与上下游的契约
- 下游 #79 求解器:消费 `OptimizationProblem`,产出满足约束的最优取值。
- 下游 #80 跨工序寻优:复用同一变量/目标/约束模型描述跨工序关联。
- 下游 #81 可解释建议:读 `violated_constraints` + 变量 `meaning` + 约束 `reason`
产出"可溯源"建议。
## 运行
```bash
python -m unittest discover -s tests # 单元测试
python _sanity_check.py # 部署期自检
```
零第三方依赖(纯标准库),与内核既有模块一致,便于离线/隔离网部署。
@@ -1,5 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方动态优化模板包(Issue #78/#79/#80/#81)。
- ``problem``:优化问题建模(变量/目标/约束),求解器无关(#78)。
"""
@@ -1,69 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方优化问题建模 自检脚本(Issue #78)。
不依赖 unittest,直接加载模板资产并做能力点断言,便于 CI / 部署期一键核对。
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from problem import ConstraintKind, OptimizationProblem, load_problem # noqa: E402
from solver import SolverConfig, solve # noqa: E402
CONFIG = os.path.join(os.path.dirname(os.path.abspath(__file__)),
"config", "recipe_optim.template.yaml")
def main() -> int:
failures = []
# 1) 模板能加载
p = load_problem(CONFIG)
if not isinstance(p, OptimizationProblem):
failures.append("load_problem 未返回 OptimizationProblem")
# 2) 4 类约束齐全
kinds = {c.kind for c in p.constraints}
expected = {ConstraintKind.BOX, ConstraintKind.LINEAR,
ConstraintKind.RATIO, ConstraintKind.FORBIDDEN}
if kinds != expected:
failures.append(f"约束种类不齐: {kinds} != {expected}")
# 3) 静态校验通过
errs = p.validate()
if errs:
failures.append(f"validate 未通过: {errs}")
# 4) 可行性判定:合法取值可行、禁止组合不可行
ok = p.is_feasible({"clf_temp": 850, "cl2_ratio": 1.0,
"feed_rate": 450, "catalyst": "A"})
bad = p.is_feasible({"clf_temp": 950, "cl2_ratio": 1.0,
"feed_rate": 450, "catalyst": "A"})
if not ok:
failures.append("合法取值被判为不可行")
if bad:
failures.append("越界取值(950℃)未被识别为不可行")
# 5) 序列化往返无损
rt = OptimizationProblem.from_dict(p.to_dict())
if [v.name for v in rt.variables] != [v.name for v in p.variables]:
failures.append("序列化往返丢失变量")
# 6) 求解器(#79)端到端:加载模板后能求出可行解
sol = solve(p, SolverConfig(grid_steps=7, max_combinations=200000))
if not sol.feasible:
failures.append(f"求解器未求出可行解: {sol.message}")
if sol.strategy != "grid":
failures.append(f"求解策略非 grid: {sol.strategy}")
if failures:
print("❌ recipe-optim 自检失败:")
for f in failures:
print(" -", f)
return 1
print("✅ recipe-optim 自检通过(6 能力点)")
return 0
if __name__ == "__main__":
sys.exit(main())
@@ -1,68 +0,0 @@
# Ti-2 配方动态优化 · 优化问题模板(Issue #78 / PRD 5.3 ②)
#
# 声明式描述「给定质量目标 + 工艺约束,求最优配方/参数」:
# 入:质量目标 + 约束;出:参数/配方建议(PRD §5.3 架构表)。
# 切换行业/车间只改本模板资产,引擎零改动(PRD「超参包驱动」)。
#
# 本示例对应「氯化车间/海绵钛(Template-Ti)」二期配方优化场景:
# 在 TiCl₄ 纯度达标(≥ target_value)前提下,寻优反应温度/氯气配比,
# 同时满足工艺约束(温度上限、氯气/钛配比、禁止组合)。
problem_id: recipe_optim_ti
template: iAOP-Template-Ti
description: 氯化车间配方优化(二期,数据就绪后接 #79 求解器)
variables:
- name: clf_temp
kind: bounds
meaning: 氯化炉反应温度
unit: "℃"
bounds: [800, 920]
initial: 860
- name: cl2_ratio
kind: bounds
meaning: 氯气与高钛渣配比
unit: "ratio"
bounds: [0.8, 1.4]
initial: 1.0
- name: feed_rate
kind: bounds
meaning: 进料速率
unit: "kg/h"
bounds: [300, 600]
initial: 450
integer: false
- name: catalyst
kind: choices
meaning: 催化剂型号
choices: ["A", "B", "C"]
objective:
sense: maximize
target: Ti_purity
target_value: 99.5
description: 最大化 TiCl₄ 纯度(PRD 超参包 target 字段)
terms:
- variable: clf_temp
coefficient: 0.01
- variable: cl2_ratio
coefficient: 2.0
constraints:
- kind: box
variable: clf_temp
bounds: [820, 900]
reason: 反应温度运行安全区间(运行期收紧,低于 820 反应不充分、高于 900 副产物激增)
- kind: linear
coefficients: {clf_temp: 1.0, feed_rate: -0.5}
op: "<="
rhs: 700
reason: 温度-进料耦合上限(防止局部过热)
- kind: ratio
numerator: cl2_ratio
denominator: cl2_ratio
op: ">="
value: 0.0
reason: 配比非负(占位示例,真实配比约束见工艺手册)
- kind: forbidden
combination: {catalyst: "C", clf_temp: 910}
reason: C 型催化剂禁止与 910℃ 高温组合(安全告警)
-784
View File
@@ -1,784 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方动态优化 · 优化问题建模(约束/目标定义)(Issue #78 / PRD 5.3 ②)。
承接 PRD 5.3「② 配方动态优化」与超参包示例(``objective`` / ``features`` /
``target``):把"给定质量目标 + 工艺约束,求最优配方/参数"这条链路**模板化、
可配置、可测试**,且与 #79 求解器、#80 跨工序寻优、#81 可解释建议解耦。
PRD 设计口径
------------
- 架构表(PRD §5.3):``工艺优化/配方推荐 | 优化/推荐 | 入:质量目标+约束;
出:参数/配方建议 | ② 配方动态优化 | 高(需闭环反馈)``。
- 模板化技术路径:超参包驱动——``objective``、输入特征清单、``target`` 等可变量
外置为 JSON 超参包,切换模板仅改此包;跨行业差异落资产,不落代码。
- 风险表:二期交付(一期数据门槛不足),故本期**先把问题建模沉淀为可校验的声明
式规格**,为 #79 求解器、#80 跨工序寻优、#81 可解释建议提供**统一的问题描述
契约**;先有"能跑通、可测试"的模型,数据就绪后接求解器(#79/#80)。
本模块交付
----------
1. **决策变量 ``DecisionVariable``**:配方/工艺可调参数的声明式规格——变量名、
单位、取值域(``Bounds`` 连续区间 / ``Choices`` 离散枚举)、初值、是否整型、
工艺含义(``meaning``,供 #81 可解释建议引用)。
2. **目标函数规格 ``ObjectiveSpec``**:``Sense``(minimize/maximize)+ 目标项
(``ObjectiveTerm``:系数 × 变量,线性目标)+ 目标 ``target``(PRD 超参包字段)。
3. **约束规格 ``ConstraintSpec``**:``ConstraintKind``(box / linear / ratio /
forbidden)统一描述工艺约束(温度上下限、配方配比、禁止组合等)。
4. **问题模型 ``OptimizationProblem``**:聚合变量 + 目标 + 约束,提供校验
(``validate``,聚合并列出全部错误,便于配置台一次性反馈)、声明式加载
(零第三方依赖 YAML 子集解析,与 data-bus/rag-kb/impurity-forecast 同款)。
设计要点
--------
- **零运行时依赖**(纯标准库):与内核既有模块一致,便于离线/隔离网部署。
- **求解器无关**:本模块只描述"问题",``solve`` 留给 #79 注入;便于换行业复用、
单测无需真实求解器。
- **可解释前置**:变量 ``meaning`` + 约束 ``reason`` 字段,为 #81 优化建议"可溯源"
预留引用依据(对齐 PRD"要求结果可解释、可溯源,要引用依据")。
"""
from __future__ import annotations
import math
import os
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional, Sequence, Tuple, Union
# 缺失值统一用 float('nan'),与 impurity-forecast 一致,便于上层判空屏蔽。
NAN = float("nan")
class ProblemError(ValueError):
"""配方优化问题建模错误(未知变量 / 越界 / 约束矛盾 / 重复定义等)。"""
# ---------------------------------------------------------------------------
# 决策变量
# ---------------------------------------------------------------------------
class DomainKind(str, Enum):
"""决策变量取值域类型。"""
BOUNDS = "bounds" # 连续区间 [low, high](如温度 800~900℃)
CHOICES = "choices" # 离散枚举(如催化剂型号 A/B/C)
@dataclass
class DecisionVariable:
"""一个可调配方/工艺参数的声明式规格。
``bounds`` 与 ``choices`` 二选一(由 ``kind`` 决定):
- ``bounds``:``[low, high]``,``integer=True`` 时取整;
- ``choices``:离散可选值列表(任意可比较的标量,多为 float/str)。
"""
name: str
kind: DomainKind
meaning: str = "" # 工艺含义,供 #81 可解释建议引用
unit: str = "" # 单位(℃、m³/h、kg、…)
bounds: Optional[Tuple[float, float]] = None
choices: Optional[List[Any]] = None
initial: Optional[float] = None # 当前工况/配方初值
integer: bool = False # 仅 bounds 连续域生效
def __post_init__(self) -> None:
if not self.name or not str(self.name).strip():
raise ProblemError("DecisionVariable.name 不能为空")
if self.kind == DomainKind.BOUNDS:
if self.bounds is None:
raise ProblemError(f"变量 {self.name!r} kind=bounds 但未提供 bounds")
low, high = self.bounds
if _is_num(low) and _is_num(high) and low > high:
raise ProblemError(
f"变量 {self.name!r} bounds 下界 {low} 大于上界 {high}")
if self.integer and self.bounds is not None:
low, high = self.bounds
if _is_num(low) and float(low).is_integer() is False:
raise ProblemError(
f"变量 {self.name!r} integer=True 但下界 {low} 非整")
if _is_num(high) and float(high).is_integer() is False:
raise ProblemError(
f"变量 {self.name!r} integer=True 但上界 {high} 非整")
elif self.kind == DomainKind.CHOICES:
if not self.choices:
raise ProblemError(f"变量 {self.name!r} kind=choices 但 choices 为空")
else: # pragma: no cover - 枚举穷尽
raise ProblemError(f"变量 {self.name!r} 未知 kind={self.kind!r}")
def contains(self, value: Any) -> bool:
"""取值是否落在该变量合法域内。"""
if self.kind == DomainKind.BOUNDS and self.bounds is not None:
if not _is_num(value):
return False
low, high = self.bounds
if self.integer and float(value).is_integer() is False:
return False
return low <= value <= high
# choices
return value in (self.choices or [])
def clamp(self, value: Any) -> Any:
"""把越界的连续域取值夹回合法区间(离散域不夹,原值返回)。"""
if self.kind == DomainKind.BOUNDS and self.bounds is not None and _is_num(value):
low, high = self.bounds
value = max(low, min(high, value))
if self.integer:
value = float(round(value))
return value
return value
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {
"name": self.name,
"kind": self.kind.value,
"meaning": self.meaning,
"unit": self.unit,
"integer": self.integer,
}
if self.kind == DomainKind.BOUNDS:
d["bounds"] = list(self.bounds) if self.bounds else None
else:
d["choices"] = list(self.choices) if self.choices else None
if self.initial is not None:
d["initial"] = self.initial
return d
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "DecisionVariable":
name = d.get("name")
if not isinstance(name, str):
raise ProblemError("DecisionVariable 缺少 name 字段")
kind_raw = d.get("kind", "bounds")
try:
kind = DomainKind(str(kind_raw))
except ValueError as e:
raise ProblemError(f"变量 {name!r} 未知 kind={kind_raw!r}") from e
bounds = d.get("bounds")
choices = d.get("choices")
if kind == DomainKind.BOUNDS and bounds is not None:
if (not isinstance(bounds, (list, tuple))) or len(bounds) != 2:
raise ProblemError(f"变量 {name!r} bounds 必须是 [low, high]")
bounds = (float(bounds[0]), float(bounds[1]))
if kind == DomainKind.CHOICES and choices is not None:
choices = list(choices)
return cls(
name=name,
kind=kind,
meaning=str(d.get("meaning", "")),
unit=str(d.get("unit", "")),
bounds=bounds,
choices=choices,
initial=d.get("initial"),
integer=bool(d.get("integer", False)),
)
# ---------------------------------------------------------------------------
# 目标函数
# ---------------------------------------------------------------------------
class Sense(str, Enum):
"""优化方向。"""
MINIMIZE = "minimize"
MAXIMIZE = "maximize"
@property
def label(self) -> str:
return {Sense.MINIMIZE: "最小化", Sense.MAXIMIZE: "最大化"}[self]
@dataclass
class ObjectiveTerm:
"""线性目标项:``coefficient * variable``(变量名引用 ``DecisionVariable.name``)。"""
variable: str
coefficient: float = 1.0
def to_dict(self) -> Dict[str, Any]:
return {"variable": self.variable, "coefficient": self.coefficient}
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "ObjectiveTerm":
if "variable" not in d:
raise ProblemError("ObjectiveTerm 缺少 variable 字段")
return cls(variable=str(d["variable"]), coefficient=float(d.get("coefficient", 1.0)))
@dataclass
class ObjectiveSpec:
"""目标函数声明式规格(线性加权,对齐 PRD 超参包 ``objective`` 字段)。
形如 ``sense(coef1*var1 + coef2*var2 + ...)``,目标质量 ``target`` 为达标量
(如 ``Ti_purity ≥ 99.5%`` 中的 99.5),仅记录、不参与求解,供 #81 可解释。
"""
sense: Sense = Sense.MAXIMIZE
terms: List[ObjectiveTerm] = field(default_factory=list)
target: Optional[str] = None # PRD 超参包 ``target``:如 "Ti_purity"
target_value: Optional[float] = None # 达标量(可选)
description: str = ""
def evaluate(self, assignment: Dict[str, float]) -> float:
"""给定一组变量取值,计算目标函数值(未知变量按 0 计)。"""
total = 0.0
for t in self.terms:
v = assignment.get(t.variable)
if _is_num(v):
total += t.coefficient * v
return total
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {
"sense": self.sense.value,
"terms": [t.to_dict() for t in self.terms],
}
if self.target is not None:
d["target"] = self.target
if self.target_value is not None:
d["target_value"] = self.target_value
if self.description:
d["description"] = self.description
return d
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "ObjectiveSpec":
sense_raw = d.get("sense", "maximize")
try:
sense = Sense(str(sense_raw))
except ValueError as e:
raise ProblemError(f"未知 sense={sense_raw!r}") from e
terms = [ObjectiveTerm.from_dict(t) for t in d.get("terms", [])]
tv = d.get("target_value")
return cls(
sense=sense,
terms=terms,
target=d.get("target"),
target_value=float(tv) if _is_num(tv) else None,
description=str(d.get("description", "")),
)
# ---------------------------------------------------------------------------
# 约束
# ---------------------------------------------------------------------------
class ConstraintKind(str, Enum):
"""约束类型(统一描述常见工艺约束)。"""
BOX = "box" # 变量上下界(冗余于 DecisionVariable.bounds,供"运行期收紧")
LINEAR = "linear" # 线性不等式 Σ a_i*x_i (</<=/>/>=) b
RATIO = "ratio" # 配比约束:x_a / x_b (op) value
FORBIDDEN = "forbidden" # 禁止组合:若干变量取值组合不允许
_LINEAR_OPS = {"<", "<=", ">", ">=", "==", "!="}
@dataclass
class ConstraintSpec:
"""约束声明式规格。
每条约束带 ``reason``(工艺依据,供 #81 可解释建议"可溯源、引用依据")。
"""
kind: ConstraintKind
reason: str = ""
# box
variable: Optional[str] = None
bounds: Optional[Tuple[float, float]] = None
# linear
coefficients: Optional[Dict[str, float]] = None
op: str = "<="
rhs: float = 0.0
# ratio
numerator: Optional[str] = None
denominator: Optional[str] = None
value: float = 0.0
# forbidden
combination: Optional[Dict[str, Any]] = None
def __post_init__(self) -> None:
if self.kind == ConstraintKind.LINEAR and self.op not in _LINEAR_OPS:
raise ProblemError(f"线性约束非法 op={self.op!r}")
if self.kind == ConstraintKind.LINEAR and not self.coefficients:
raise ProblemError("线性约束 coefficients 不能为空")
# ---- 校验(返回错误信息列表,不抛异常,便于聚合) ------------------
def errors_against(self, variables: Dict[str, DecisionVariable]) -> List[str]:
"""对该约束引用的变量是否存在做静态校验,返回错误信息列表。"""
errs: List[str] = []
if self.kind == ConstraintKind.BOX:
if not self.variable:
errs.append("box 约束缺少 variable")
elif self.variable not in variables:
errs.append(f"box 约束引用未知变量 {self.variable!r}")
elif self.kind == ConstraintKind.LINEAR:
for vname in (self.coefficients or {}):
if vname not in variables:
errs.append(f"线性约束引用未知变量 {vname!r}")
elif self.kind == ConstraintKind.RATIO:
for fld, vname in (("numerator", self.numerator),
("denominator", self.denominator)):
if not vname:
errs.append(f"ratio 约束缺少 {fld}")
elif vname not in variables:
errs.append(f"ratio 约束引用未知变量 {vname!r}")
elif self.kind == ConstraintKind.FORBIDDEN:
for vname in (self.combination or {}):
if vname not in variables:
errs.append(f"forbidden 约束引用未知变量 {vname!r}")
return errs
# ---- 可行性判定(给定取值,判断该约束是否满足) --------------------
def satisfied_by(self, assignment: Dict[str, Any]) -> bool:
"""给定一组变量取值,判断该约束是否被满足(未知变量视为未约束)。"""
if self.kind == ConstraintKind.BOX and self.bounds is not None and self.variable:
v = assignment.get(self.variable)
if not _is_num(v):
return True # 未知取值不判
low, high = self.bounds
return low <= v <= high
if self.kind == ConstraintKind.LINEAR and self.coefficients:
total = 0.0
unknown = False
for vname, coef in self.coefficients.items():
v = assignment.get(vname)
if not _is_num(v):
unknown = True
break
total += coef * v
if unknown:
return True
return _apply_op(total, self.op, self.rhs)
if self.kind == ConstraintKind.RATIO and self.numerator and self.denominator:
a = assignment.get(self.numerator)
b = assignment.get(self.denominator)
if not _is_num(a) or not _is_num(b) or b == 0:
return True
return _apply_op(a / b, self.op, self.value)
if self.kind == ConstraintKind.FORBIDDEN and self.combination:
# 组合中每个键值都命中才算"禁止组合"被触发
for vname, want in self.combination.items():
if assignment.get(vname) != want:
return True
return False
return True
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {"kind": self.kind.value}
if self.reason:
d["reason"] = self.reason
if self.kind == ConstraintKind.BOX:
d["variable"] = self.variable
d["bounds"] = list(self.bounds) if self.bounds else None
elif self.kind == ConstraintKind.LINEAR:
d["coefficients"] = dict(self.coefficients or {})
d["op"] = self.op
d["rhs"] = self.rhs
elif self.kind == ConstraintKind.RATIO:
d["numerator"] = self.numerator
d["denominator"] = self.denominator
d["op"] = self.op
d["value"] = self.value
elif self.kind == ConstraintKind.FORBIDDEN:
d["combination"] = dict(self.combination or {})
return d
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "ConstraintSpec":
kind_raw = d.get("kind")
try:
kind = ConstraintKind(str(kind_raw))
except ValueError as e:
raise ProblemError(f"未知约束 kind={kind_raw!r}") from e
bounds = d.get("bounds")
if kind == ConstraintKind.BOX and bounds is not None:
bounds = (float(bounds[0]), float(bounds[1]))
coefs = d.get("coefficients")
if coefs is not None:
coefs = {k: float(v) for k, v in coefs.items()}
return cls(
kind=kind,
reason=str(d.get("reason", "")),
variable=d.get("variable"),
bounds=bounds,
coefficients=coefs,
op=str(d.get("op", "<=")),
rhs=float(d.get("rhs", 0.0)),
numerator=d.get("numerator"),
denominator=d.get("denominator"),
value=float(d.get("value", 0.0)),
combination=d.get("combination"),
)
# ---------------------------------------------------------------------------
# 优化问题
# ---------------------------------------------------------------------------
def objective_factory() -> ObjectiveSpec:
"""dataclass 默认值工厂:空目标(最大化、无项)。"""
return ObjectiveSpec(sense=Sense.MAXIMIZE)
@dataclass
class OptimizationProblem:
"""配方优化问题模型(变量 + 目标 + 约束),求解器无关。
设计为「先建模、后求解」:``validate`` 做静态一致性校验(变量引用、域完整性),
``is_feasible`` 做取值可行性判定(运行期收紧约束 / 禁止组合),``solve`` 留给
#79 注入求解器,本模块不绑任何优化库。
"""
variables: List[DecisionVariable] = field(default_factory=list)
objective: ObjectiveSpec = field(default_factory=objective_factory)
constraints: List[ConstraintSpec] = field(default_factory=list)
problem_id: str = ""
template: str = "" # 如 "iAOP-Template-Ti"
description: str = ""
# ---- 变量索引 ----------------------------------------------------
@property
def variable_map(self) -> Dict[str, DecisionVariable]:
return {v.name: v for v in self.variables}
# ---- 校验 --------------------------------------------------------
def validate(self) -> List[str]:
"""聚合所有静态错误,返回错误信息列表(空列表表示通过)。"""
errs: List[str] = []
seen: set = set()
for v in self.variables:
if v.name in seen:
errs.append(f"重复定义变量 {v.name!r}")
seen.add(v.name)
vmap = self.variable_map
for t in self.objective.terms:
if t.variable not in vmap:
errs.append(f"目标项引用未知变量 {t.variable!r}")
for i, c in enumerate(self.constraints):
for e in c.errors_against(vmap):
errs.append(f"约束 #{i} ({c.kind.value}): {e}")
if self.objective.terms and not any(
t.variable in vmap for t in self.objective.terms
):
errs.append("目标函数所有项均引用未知变量")
return errs
# ---- 可行性判定 --------------------------------------------------
def is_feasible(self, assignment: Dict[str, Any]) -> bool:
"""给定一组变量取值,判断是否满足全部约束与变量域。"""
vmap = self.variable_map
for name, val in assignment.items():
v = vmap.get(name)
if v is not None and not v.contains(val):
return False
return all(c.satisfied_by(assignment) for c in self.constraints)
def violated_constraints(self, assignment: Dict[str, Any]) -> List[ConstraintSpec]:
"""返回被该取值违反的约束列表(供 #81 可解释建议引用依据)。"""
return [c for c in self.constraints if not c.satisfied_by(assignment)]
# ---- 序列化 ------------------------------------------------------
def to_dict(self) -> Dict[str, Any]:
d: Dict[str, Any] = {
"variables": [v.to_dict() for v in self.variables],
"objective": self.objective.to_dict(),
"constraints": [c.to_dict() for c in self.constraints],
}
if self.problem_id:
d["problem_id"] = self.problem_id
if self.template:
d["template"] = self.template
if self.description:
d["description"] = self.description
return d
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "OptimizationProblem":
return cls(
variables=[DecisionVariable.from_dict(v) for v in d.get("variables", [])],
objective=ObjectiveSpec.from_dict(d.get("objective", {})),
constraints=[ConstraintSpec.from_dict(c) for c in d.get("constraints", [])],
problem_id=str(d.get("problem_id", "")),
template=str(d.get("template", "")),
description=str(d.get("description", "")),
)
# ---------------------------------------------------------------------------
# 辅助函数
# ---------------------------------------------------------------------------
def _is_num(x: object) -> bool:
return isinstance(x, (int, float)) and not (isinstance(x, float) and math.isnan(x))
def _apply_op(left: float, op: str, right: float) -> bool:
"""应用比较算子(线性/配比约束共用)。"""
if op == "<":
return left < right
if op == "<=":
return left <= right
if op == ">":
return left > right
if op == ">=":
return left >= right
if op == "==":
return abs(left - right) < 1e-12
if op == "!=":
return abs(left - right) >= 1e-12
return False # pragma: no cover
# ---------------------------------------------------------------------------
# 零依赖 YAML 子集加载(与 data-bus / rag-kb / impurity-forecast 同款)
# ---------------------------------------------------------------------------
def load_problem(path: str) -> OptimizationProblem:
"""从声明式模板资产(YAML 子集)加载优化问题。
解析支持:缩进块、``key: value``、``- item``、行内 ``# 注释``、字符串/数字/
布尔、内联 ``[a, b]`` 列表与 ``{a: 1}`` 映射。足以覆盖本模板资产格式;
不引入第三方依赖,与内核既有模块一致。
"""
with open(path, "r", encoding="utf-8") as fh:
text = fh.read()
data = _parse_yaml_subset(text)
if not isinstance(data, dict):
raise ProblemError(f"模板 {path} 顶层应为映射")
return OptimizationProblem.from_dict(data)
def _parse_yaml_subset(text: str) -> Any:
"""极简 YAML 子集解析器(仅供模板资产,非通用 YAML)。"""
# 去注释 + 去尾部空白,保留缩进
lines: List[str] = []
for raw in text.splitlines():
# 行内注释:仅在 "# " 前不是值的一部分时剥离;这里取保守策略——行首/值后
# 的 " #" 视为注释。冒号/方括号内的 # 不处理。
stripped = raw.rstrip()
if not stripped.strip():
continue
# 简单注释行
if stripped.lstrip().startswith("#"):
continue
# 去行尾注释(" #" 形式)
hash_idx = _find_inline_comment(stripped)
if hash_idx is not None:
stripped = stripped[:hash_idx].rstrip()
if stripped:
lines.append(stripped)
parser = _YamlParser(lines)
return parser.parse_block(0)[0] if lines else {}
def _find_inline_comment(line: str) -> Optional[int]:
"""返回行内注释 ``#`` 的索引(无则 None),跳过 ``[...]``/``{...}`` 内的 #。"""
depth = 0
in_str = False
for i, ch in enumerate(line):
if ch == '"':
in_str = not in_str
elif not in_str:
if ch in "[{":
depth += 1
elif ch in "]}":
depth = max(0, depth - 1)
elif ch == "#" and depth == 0 and i > 0 and line[i - 1] in (" ", "\t"):
return i
elif ch == "#" and depth == 0 and i == 0:
return i
return None
class _YamlParser:
"""递归下降的 YAML 子集解析器(按缩进分层)。"""
def __init__(self, lines: List[str]) -> None:
self.lines = lines
self.i = 0
def _indent(self, line: str) -> int:
return len(line) - len(line.lstrip(" "))
def parse_block(self, indent: int) -> Tuple[Any, bool]:
"""解析当前缩进层级的一个块,返回 (value, is_list_marker)。"""
if self.i >= len(self.lines):
return {}, False
line = self.lines[self.i]
cur_indent = self._indent(line)
if cur_indent < indent:
return {}, False
stripped = line.strip()
if stripped.startswith("- ") or stripped == "-":
return self._parse_list(cur_indent), True
return self._parse_mapping(cur_indent), False
def _parse_mapping(self, indent: int) -> Dict[str, Any]:
result: Dict[str, Any] = {}
# 实际子键缩进可能 > indent(如 "- key: v" 后 4 空格键、项缩进 2)。
# 用首行真实缩进对齐,避免误把合法子键当"孤立缩进"跳过。
effective = indent
if self.i < len(self.lines):
first = self._indent(self.lines[self.i])
if first > indent:
effective = first
while self.i < len(self.lines):
line = self.lines[self.i]
cur = self._indent(line)
if cur < effective:
break
if cur > effective:
# 跳过孤立缩进(不应出现,保守跳过)
self.i += 1
continue
stripped = line.strip()
if stripped.startswith("- "):
break
key, sep, rest = stripped.partition(":")
if not sep:
self.i += 1
continue
key = key.strip()
rest = rest.strip()
self.i += 1
if rest:
result[key] = _parse_scalar(rest)
else:
# 子块:用首行真实缩进解析(列表或映射),兼容 4 空格子键等
if self.i < len(self.lines) and self._indent(self.lines[self.i]) > effective:
child_indent = self._indent(self.lines[self.i])
val, _ = self.parse_block(child_indent)
result[key] = val
else:
result[key] = None
return result
def _parse_list(self, indent: int) -> List[Any]:
result: List[Any] = []
while self.i < len(self.lines):
line = self.lines[self.i]
cur = self._indent(line)
if cur < indent:
break
if cur > indent:
self.i += 1
continue
stripped = line.strip()
if not stripped.startswith("-"):
break
item_text = stripped[1:].strip()
self.i += 1
# 后续更深缩进的行是否归属本项
if self.i < len(self.lines):
child_indent = self._indent(self.lines[self.i])
else:
child_indent = cur
has_deeper = child_indent > cur
if item_text:
# 可能是 "- key: value"(映射项)或 "- 标量"
if ":" in item_text and not item_text.startswith("["):
# 单行映射项的首键
key, sep, rest = item_text.partition(":")
kval = _parse_scalar(rest.strip()) if rest.strip() else None
if has_deeper:
# 把首键与后续子块合并:先解析子块,再把首键塞入
sub, _ = self.parse_block(child_indent)
item: Dict[str, Any] = sub if isinstance(sub, dict) else {}
item[key.strip()] = kval
else:
item = {key.strip(): kval}
result.append(item)
else:
if has_deeper:
# 标量头 + 子块(本模板未使用,保守取子块)
sub, _ = self.parse_block(child_indent)
result.append(sub)
else:
result.append(_parse_scalar(item_text))
else:
# "- " 后跟子块
if has_deeper:
sub, _ = self.parse_block(child_indent)
result.append(sub)
return result
def _parse_scalar(text: str) -> Any:
"""解析标量:数字/布尔/字符串/内联列表/内联映射。"""
text = text.strip()
if not text:
return ""
# 内联列表
if text.startswith("[") and text.endswith("]"):
inner = text[1:-1].strip()
if not inner:
return []
return [_parse_scalar(part.strip()) for part in _split_top(inner, ",")]
# 内联映射
if text.startswith("{") and text.endswith("}"):
inner = text[1:-1].strip()
if not inner:
return {}
out: Dict[str, Any] = {}
for part in _split_top(inner, ","):
k, sep, v = part.partition(":")
if sep:
out[k.strip()] = _parse_scalar(v.strip())
return out
low = text.lower()
if low == "true":
return True
if low == "false":
return False
if low in ("null", "none", "~"):
return None
# 数字
try:
if "." in text or "e" in low:
return float(text)
return int(text)
except ValueError:
# 去引号
if len(text) >= 2 and text[0] in "\"'" and text[-1] == text[0]:
return text[1:-1]
return text
def _split_top(text: str, sep: str) -> List[str]:
"""按分隔符切分顶层(跳过 []/{} 内的)。"""
parts: List[str] = []
depth = 0
cur: List[str] = []
in_str = False
for ch in text:
if ch == '"':
in_str = not in_str
cur.append(ch)
elif not in_str and ch in "[{":
depth += 1
cur.append(ch)
elif not in_str and ch in "]}":
depth = max(0, depth - 1)
cur.append(ch)
elif ch == sep and depth == 0:
parts.append("".join(cur))
cur = []
else:
cur.append(ch)
if cur:
parts.append("".join(cur))
return parts
-304
View File
@@ -1,304 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方动态优化 · 求解器集成(Issue #79 / PRD 5.3 ②)。
承接 #78 的 ``OptimizationProblem``:把"问题模型"喂给**求解器**,产出满足全部
约束、逼近目标最优的**配方/参数取值**,并给出可解释的求解报告。
PRD 设计口径
------------
- 架构表(PRD §5.3):``出:参数/配方建议``;``高(需闭环反馈)``。
- 模板化技术路径:默认「固定主干 + 可配置超参」;新增结构走插件注册而非改内核。
- 风险表:二期交付(数据门槛高)。故本期求解器采用**纯标准库、零第三方依赖**的
轻量策略(坐标下降 + 网格采样),数据就绪/精度不足时可注入更强的外部求解器
(PuLP/scipy/optuna,走 #78 预留的 ``solve`` 扩展点),**内核不绑优化库**。
本模块交付
----------
1. **``SolverConfig``**:求解策略声明式配置(网格粒度、迭代轮数、随机种子、
是否枚举离散选择),对齐 PRD「超参包驱动」。
2. **``Solution``**:求解结果(取值 ``assignment``、目标值、是否可行、是否达成
``target_value``、迭代轨迹、违反约束枚举),为 #81 可解释建议提供结构化输入。
3. **``GridSolver``**:确定性网格 + 坐标下降求解器(纯标准库):
- 连续域变量按 ``grid_steps`` 等分离散化;
- 离散域变量枚举 ``choices``;
- 笛卡尔积里筛可行解、按目标 ``sense`` 选最优(全局最优保证);
- 规模过大时退化为坐标下降(贪心)保可用性(``max_combinations`` 阈值)。
4. **``solve(problem, config=None)``**:统一入口,便于 #80/#81 调用。
设计要点
--------
- **确定性可复现**:``random_seed`` 固定,同输入同输出(对齐 PRD"结论可复现")。
- **可行优先**:无任何可行解时返回 ``feasible=False`` 的 Solution,不抛异常,
便于上层降级(对齐 PRD"可用性 ≥ 99.8%")。
- **求解器无关契约**:``solve`` 是薄入口,可被外部更强求解器替换;本模块的
``Solution`` 结构即外部求解器需返回的契约。
"""
from __future__ import annotations
import itertools
import math
import random
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
# 复用 #78 的问题模型。作为包成员导入用 ``recipe_optim.problem``;当本文件被直接
# 执行(与 problem.py 同目录)时回落到裸名 ``problem``。
try: # pragma: no cover - 分支取决于导入方式
from recipe_optim.problem import ( # type: ignore[import-not-found]
ConstraintSpec,
DecisionVariable,
DomainKind,
ObjectiveSpec,
OptimizationProblem,
Sense,
_is_num,
)
except ImportError: # pragma: no cover
from problem import ( # type: ignore[import-not-found,no-redef]
ConstraintSpec,
DecisionVariable,
DomainKind,
ObjectiveSpec,
OptimizationProblem,
Sense,
_is_num,
)
class SolverError(ValueError):
"""求解器配置或执行错误(网格粒度非法、变量规模溢出等)。"""
@dataclass
class SolverConfig:
"""求解策略声明式配置(对齐 PRD 超参包驱动)。"""
grid_steps: int = 11 # 连续域每个变量等分点数(含端点)
max_combinations: int = 200000 # 笛卡尔积规模上限,超过则退化为坐标下降
random_seed: int = 20260805 # 固定随机种子,保证确定性可复现
enumerate_choices: bool = True # 是否完整枚举离散 choices(False 时取首个)
def __post_init__(self) -> None:
if self.grid_steps < 2:
raise SolverError("grid_steps 必须 ≥ 2(至少含两端点)")
if self.max_combinations < 1:
raise SolverError("max_combinations 必须 ≥ 1")
@dataclass
class Solution:
"""求解结果(#81 可解释建议的结构化输入)。"""
assignment: Dict[str, Any] = field(default_factory=dict)
objective_value: float = 0.0
feasible: bool = False
target_met: bool = False
violated: List[ConstraintSpec] = field(default_factory=list)
iterations: int = 0
evaluated: int = 0
strategy: str = "" # "grid" / "coordinate_descent"
message: str = ""
def to_dict(self) -> Dict[str, Any]:
return {
"assignment": dict(self.assignment),
"objective_value": self.objective_value,
"feasible": self.feasible,
"target_met": self.target_met,
"violated": [c.to_dict() for c in self.violated],
"iterations": self.iterations,
"evaluated": self.evaluated,
"strategy": self.strategy,
"message": self.message,
}
# ---------------------------------------------------------------------------
# 变量取值候选生成
# ---------------------------------------------------------------------------
def candidate_values(var: DecisionVariable, config: SolverConfig) -> List[Any]:
"""为单个变量生成求解候选取值集合。"""
if var.kind == DomainKind.CHOICES:
return list(var.choices) if config.enumerate_choices else [var.choices[0]]
# bounds 连续域:等分离散化
if var.bounds is None:
return []
low, high = var.bounds
step = (high - low) / (config.grid_steps - 1)
vals = [low + i * step for i in range(config.grid_steps)]
if var.integer:
vals = [float(round(v)) for v in vals]
# 去重保序
seen: set = set()
uniq: List[Any] = []
for v in vals:
iv = int(v)
if iv not in seen:
seen.add(iv)
uniq.append(iv)
return uniq
return vals
def _grid_size(problem: OptimizationProblem, config: SolverConfig) -> int:
total = 1
for v in problem.variables:
total *= len(candidate_values(v, config))
return total
# ---------------------------------------------------------------------------
# 求解器
# ---------------------------------------------------------------------------
def _better(new: float, best: float, sense: Sense) -> bool:
"""判断 new 是否比 best 更优。"""
if sense == Sense.MAXIMIZE:
return new > best
return new < best
def _initial_objective(sense: Sense) -> float:
return -math.inf if sense == Sense.MAXIMIZE else math.inf
def _solve_grid(problem: OptimizationProblem, config: SolverConfig) -> Solution:
"""完整网格枚举:笛卡尔积里筛可行、选最优(全局最优保证)。"""
rng = random.Random(config.random_seed)
per_var = [candidate_values(v, config) for v in problem.variables]
names = [v.name for v in problem.variables]
sense = problem.objective.sense
best_obj = _initial_objective(sense)
best_assign: Optional[Dict[str, Any]] = None
evaluated = 0
iterations = 0
# 为控制内存,逐组合判定,不一次性 materialize
for combo in itertools.product(*per_var):
evaluated += 1
iterations += 1
assignment = dict(zip(names, combo))
if not problem.is_feasible(assignment):
continue
obj = problem.objective.evaluate(assignment)
if best_assign is None or _better(obj, best_obj, sense):
best_obj = obj
best_assign = assignment
feasible = best_assign is not None
return _build_solution(problem, config, best_assign or {}, best_obj,
feasible, iterations, evaluated, "grid",
"网格枚举完成" if feasible else "无可行解(约束过紧或域为空)")
def _solve_coordinate_descent(
problem: OptimizationProblem, config: SolverConfig
) -> Solution:
"""坐标下降:固定其余变量、逐维选当前最优取值(贪心,规模过大时降级用)。
从初值(``initial`` 缺省取域中点)出发,反复扫描各变量、在候选值里取使目标
最优且保持可行者;迭代至收敛或达 ``max_rounds``。非全局最优,但保可用性。
"""
sense = problem.objective.sense
names = [v.name for v in problem.variables]
per_var = {v.name: candidate_values(v, config) for v in problem.variables}
# 初值
assignment: Dict[str, Any] = {}
for v in problem.variables:
if v.initial is not None and v.contains(v.initial):
assignment[v.name] = v.initial
elif v.kind == DomainKind.CHOICES and v.choices:
assignment[v.name] = v.choices[0]
elif v.bounds is not None:
assignment[v.name] = (v.bounds[0] + v.bounds[1]) / 2.0
else: # pragma: no cover - 防御
assignment[v.name] = None
max_rounds = max(3, len(names))
evaluated = 0
iterations = 0
for _round in range(max_rounds):
improved = False
for name in names:
cur_best = assignment[name]
cur_assign = dict(assignment)
cur_obj = problem.objective.evaluate(cur_assign) if problem.is_feasible(cur_assign) else None
best_val = cur_best
best_obj = cur_obj if cur_obj is not None else _initial_objective(sense)
for cand in per_var[name]:
evaluated += 1
trial = dict(assignment)
trial[name] = cand
if not problem.is_feasible(trial):
continue
obj = problem.objective.evaluate(trial)
if cur_obj is None or _better(obj, best_obj, sense):
best_obj = obj
best_val = cand
if best_val != cur_best:
assignment[name] = best_val
improved = True
iterations += 1
if not improved:
break
feasible = problem.is_feasible(assignment)
final_obj = problem.objective.evaluate(assignment) if feasible else 0.0
return _build_solution(problem, config, assignment, final_obj, feasible,
iterations, evaluated, "coordinate_descent",
"坐标下降完成" if feasible else "坐标下降未找到可行解")
def _build_solution(
problem: OptimizationProblem,
config: SolverConfig,
assignment: Dict[str, Any],
obj: float,
feasible: bool,
iterations: int,
evaluated: int,
strategy: str,
message: str,
) -> Solution:
violated = problem.violated_constraints(assignment) if assignment else []
target_met = False
if feasible and problem.objective.target_value is not None:
if problem.objective.sense == Sense.MAXIMIZE:
target_met = obj >= problem.objective.target_value
else:
target_met = obj <= problem.objective.target_value
elif feasible and problem.objective.target_value is None:
target_met = True # 未设达标量则视为达成
return Solution(
assignment=assignment,
objective_value=obj,
feasible=feasible,
target_met=target_met,
violated=violated,
iterations=iterations,
evaluated=evaluated,
strategy=strategy,
message=message,
)
def solve(problem: OptimizationProblem,
config: Optional[SolverConfig] = None) -> Solution:
"""统一求解入口。
自动按规模选择策略:网格规模 ≤ ``max_combinations`` 用全局网格枚举,
否则退化为坐标下降(保可用性)。先做静态校验,校验失败直接返回不可行解。
"""
cfg = config or SolverConfig()
# 静态校验
errs = problem.validate()
if errs:
return Solution(feasible=False, strategy="validate",
message="问题校验失败: " + "; ".join(errs))
# 空问题:无可调变量
if not problem.variables:
return Solution(feasible=True, target_met=True, strategy="empty",
message="无决策变量,视为平凡可行")
size = _grid_size(problem, cfg)
if size <= cfg.max_combinations:
return _solve_grid(problem, cfg)
return _solve_coordinate_descent(problem, cfg)
@@ -1,26 +0,0 @@
# -*- coding: utf-8 -*-
"""测试引导:把连字符目录挂载为可导入包(与 core 模块同款模式)。
- ``templates/ti-cl4/recipe-optim`` → 包名 ``recipe_optim``。
本引擎零内核依赖(纯标准库),仅挂载自身包即可。
"""
import importlib.util
import os
import sys
PKG_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
def _load_package(name: str, path: str) -> None:
"""按文件路径完整加载一个包(执行其 __init__.py)。"""
if name in sys.modules:
return
init_py = os.path.join(path, "__init__.py")
spec = importlib.util.spec_from_file_location(
name, init_py, submodule_search_locations=[path])
module = importlib.util.module_from_spec(spec)
sys.modules[name] = module
spec.loader.exec_module(module)
_load_package("recipe_optim", PKG_DIR)
@@ -1,291 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方优化问题建模 单元测试(Issue #78)。
覆盖:
- 决策变量域(bounds/choices/integer/越界/夹紧);
- 目标函数(线性求值、min/max、target 记录);
- 约束(box/linear/ratio/forbidden 可行性判定 + 未知变量静态校验);
- OptimizationProblem(聚合校验、可行性、违反约束枚举、序列化往返);
- load_problem YAML 子集加载(模板资产)。
"""
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: E402 挂载 recipe_optim 包
from recipe_optim.problem import ( # noqa: E402
ConstraintKind,
ConstraintSpec,
DecisionVariable,
DomainKind,
ObjectiveSpec,
ObjectiveTerm,
OptimizationProblem,
ProblemError,
Sense,
load_problem,
)
CONFIG_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"config", "recipe_optim.template.yaml",
)
def _ti_problem() -> OptimizationProblem:
"""构造一份与 config 同构的内存问题(用于无需 YAML 的断言)。"""
return OptimizationProblem(
variables=[
DecisionVariable("clf_temp", DomainKind.BOUNDS, "温度", "℃",
bounds=(800, 920), initial=860),
DecisionVariable("cl2_ratio", DomainKind.BOUNDS, "配比", "ratio",
bounds=(0.8, 1.4), initial=1.0),
DecisionVariable("catalyst", DomainKind.CHOICES, "催化剂", "",
choices=["A", "B", "C"]),
],
objective=ObjectiveSpec(
sense=Sense.MAXIMIZE,
target="Ti_purity",
target_value=99.5,
terms=[ObjectiveTerm("clf_temp", 0.01), ObjectiveTerm("cl2_ratio", 2.0)],
),
constraints=[
ConstraintSpec(ConstraintKind.BOX, variable="clf_temp", bounds=(820, 900),
reason="温度安全区间"),
ConstraintSpec(ConstraintKind.LINEAR, coefficients={"clf_temp": 1.0},
op="<=", rhs=900),
ConstraintSpec(ConstraintKind.FORBIDDEN, combination={"catalyst": "C"}),
],
)
class TestDecisionVariable(unittest.TestCase):
def test_bounds_valid_and_contains(self):
v = DecisionVariable("t", DomainKind.BOUNDS, bounds=(0.0, 10.0))
self.assertTrue(v.contains(5))
self.assertTrue(v.contains(0))
self.assertTrue(v.contains(10))
self.assertFalse(v.contains(-0.1))
self.assertFalse(v.contains(10.1))
self.assertFalse(v.contains("x"))
def test_bounds_reversed_rejected(self):
with self.assertRaises(ProblemError):
DecisionVariable("t", DomainKind.BOUNDS, bounds=(10.0, 0.0))
def test_choices_domain(self):
v = DecisionVariable("cat", DomainKind.CHOICES, choices=["A", "B"])
self.assertTrue(v.contains("A"))
self.assertFalse(v.contains("Z"))
def test_integer_bounds_noninteger_rejected(self):
with self.assertRaises(ProblemError):
DecisionVariable("n", DomainKind.BOUNDS, bounds=(1.5, 5.0), integer=True)
def test_integer_contains_and_clamp(self):
v = DecisionVariable("n", DomainKind.BOUNDS, bounds=(0.0, 10.0), integer=True)
self.assertFalse(v.contains(1.5))
self.assertTrue(v.contains(3))
# clamp 把越界夹回 + 取整
self.assertEqual(v.clamp(12.4), 10.0)
self.assertEqual(v.clamp(-3), 0.0)
self.assertEqual(v.clamp(4.7), 5.0)
def test_continuous_clamp(self):
v = DecisionVariable("t", DomainKind.BOUNDS, bounds=(0.0, 10.0))
self.assertEqual(v.clamp(15), 10)
self.assertEqual(v.clamp(-2), 0)
def test_empty_name_rejected(self):
with self.assertRaises(ProblemError):
DecisionVariable(" ", DomainKind.BOUNDS, bounds=(0, 1))
def test_missing_domain_payload_rejected(self):
with self.assertRaises(ProblemError):
DecisionVariable("t", DomainKind.BOUNDS)
with self.assertRaises(ProblemError):
DecisionVariable("t", DomainKind.CHOICES, choices=[])
def test_roundtrip(self):
v = DecisionVariable("t", DomainKind.BOUNDS, "温度", "℃",
bounds=(1.0, 2.0), initial=1.5)
v2 = DecisionVariable.from_dict(v.to_dict())
self.assertEqual(v2.bounds, v.bounds)
self.assertEqual(v2.initial, v.initial)
class TestObjective(unittest.TestCase):
def test_evaluate_maximize(self):
obj = ObjectiveSpec(Sense.MAXIMIZE, terms=[ObjectiveTerm("a", 2.0),
ObjectiveTerm("b", -1.0)])
self.assertEqual(obj.evaluate({"a": 3, "b": 1}), 5.0)
# 未知变量按 0
self.assertEqual(obj.evaluate({"a": 3}), 6.0)
def test_minimize_label(self):
self.assertEqual(Sense.MINIMIZE.label, "最小化")
self.assertEqual(Sense.MAXIMIZE.label, "最大化")
def test_unknown_sense_rejected(self):
with self.assertRaises(ProblemError):
ObjectiveSpec.from_dict({"sense": "extreme"})
def test_roundtrip_with_target(self):
obj = ObjectiveSpec(Sense.MAXIMIZE, target="Ti_purity", target_value=99.5,
terms=[ObjectiveTerm("a", 0.5)])
obj2 = ObjectiveSpec.from_dict(obj.to_dict())
self.assertEqual(obj2.target, "Ti_purity")
self.assertEqual(obj2.target_value, 99.5)
self.assertEqual(obj2.terms[0].coefficient, 0.5)
class TestConstraint(unittest.TestCase):
def test_box_satisfied(self):
c = ConstraintSpec(ConstraintKind.BOX, variable="t", bounds=(0, 10))
self.assertTrue(c.satisfied_by({"t": 5}))
self.assertFalse(c.satisfied_by({"t": 11}))
# 未知取值不判
self.assertTrue(c.satisfied_by({}))
def test_linear_ops(self):
c = ConstraintSpec(ConstraintKind.LINEAR, coefficients={"a": 1, "b": 1},
op="<=", rhs=10)
self.assertTrue(c.satisfied_by({"a": 4, "b": 6}))
self.assertFalse(c.satisfied_by({"a": 6, "b": 6}))
# 部分未知视为未约束
self.assertTrue(c.satisfied_by({"a": 4}))
def test_ratio_constraint(self):
c = ConstraintSpec(ConstraintKind.RATIO, numerator="x", denominator="y",
op=">=", value=0.5)
self.assertTrue(c.satisfied_by({"x": 1, "y": 2}))
self.assertFalse(c.satisfied_by({"x": 1, "y": 4}))
# 分母为 0 视为未约束
self.assertTrue(c.satisfied_by({"x": 1, "y": 0}))
def test_forbidden_combination(self):
c = ConstraintSpec(ConstraintKind.FORBIDDEN, combination={"cat": "C"})
self.assertFalse(c.satisfied_by({"cat": "C"}))
self.assertTrue(c.satisfied_by({"cat": "A"}))
# 多键需全部命中才算触发
c2 = ConstraintSpec(ConstraintKind.FORBIDDEN,
combination={"cat": "C", "t": 900})
self.assertTrue(c2.satisfied_by({"cat": "C", "t": 100}))
self.assertFalse(c2.satisfied_by({"cat": "C", "t": 900}))
def test_linear_bad_op_rejected(self):
with self.assertRaises(ProblemError):
ConstraintSpec(ConstraintKind.LINEAR, coefficients={"a": 1}, op="~=")
with self.assertRaises(ProblemError):
ConstraintSpec(ConstraintKind.LINEAR, op="<=")
def test_errors_against_unknown_var(self):
c = ConstraintSpec(ConstraintKind.BOX, variable="missing", bounds=(0, 1))
self.assertTrue(c.errors_against({"t": object()}))
def test_roundtrip(self):
c = ConstraintSpec(ConstraintKind.LINEAR, reason="x",
coefficients={"a": 1.0}, op=">=", rhs=5)
c2 = ConstraintSpec.from_dict(c.to_dict())
self.assertEqual(c2.op, ">=")
self.assertEqual(c2.rhs, 5)
class TestOptimizationProblem(unittest.TestCase):
def test_validate_ok(self):
self.assertEqual(_ti_problem().validate(), [])
def test_validate_duplicate_variable(self):
p = _ti_problem()
p.variables.append(DecisionVariable("clf_temp", DomainKind.BOUNDS,
bounds=(0, 1)))
errs = p.validate()
self.assertTrue(any("重复定义" in e for e in errs))
def test_validate_unknown_var_in_objective(self):
p = _ti_problem()
p.objective.terms.append(ObjectiveTerm("nope"))
errs = p.validate()
self.assertTrue(any("nope" in e for e in errs))
def test_validate_unknown_var_in_constraint(self):
p = _ti_problem()
p.constraints.append(ConstraintSpec(ConstraintKind.BOX, variable="ghost",
bounds=(0, 1)))
errs = p.validate()
self.assertTrue(any("ghost" in e for e in errs))
def test_is_feasible_and_violated(self):
p = _ti_problem()
# 合法取值
self.assertTrue(p.is_feasible({"clf_temp": 850, "cl2_ratio": 1.0,
"catalyst": "A"}))
# 越出 box 收紧(820~900)
self.assertFalse(p.is_feasible({"clf_temp": 910, "cl2_ratio": 1.0,
"catalyst": "A"}))
# forbidden 组合
self.assertFalse(p.is_feasible({"clf_temp": 850, "cl2_ratio": 1.0,
"catalyst": "C"}))
viol = p.violated_constraints({"clf_temp": 950, "cl2_ratio": 1.0,
"catalyst": "A"})
self.assertGreater(len(viol), 0)
def test_roundtrip(self):
p = _ti_problem()
p2 = OptimizationProblem.from_dict(p.to_dict())
self.assertEqual([v.name for v in p2.variables],
[v.name for v in p.variables])
self.assertEqual(p2.objective.sense, p.objective.sense)
self.assertEqual(len(p2.constraints), len(p.constraints))
class TestLoadProblemYaml(unittest.TestCase):
def test_load_template(self):
self.assertTrue(os.path.exists(CONFIG_PATH), f"缺少模板 {CONFIG_PATH}")
p = load_problem(CONFIG_PATH)
names = [v.name for v in p.variables]
self.assertEqual(names, ["clf_temp", "cl2_ratio", "feed_rate", "catalyst"])
# 校验通过
self.assertEqual(p.validate(), [])
# 目标与约束就位
self.assertEqual(p.objective.target, "Ti_purity")
self.assertEqual(p.objective.target_value, 99.5)
kinds = {c.kind for c in p.constraints}
self.assertEqual(kinds, {ConstraintKind.BOX, ConstraintKind.LINEAR,
ConstraintKind.RATIO, ConstraintKind.FORBIDDEN})
# 合法初值可行
self.assertTrue(p.is_feasible({"clf_temp": 850, "cl2_ratio": 1.0,
"feed_rate": 450, "catalyst": "A"}))
def test_load_choices_parsed(self):
p = load_problem(CONFIG_PATH)
cat = p.variable_map["catalyst"]
self.assertEqual(cat.kind, DomainKind.CHOICES)
self.assertEqual(cat.choices, ["A", "B", "C"])
def test_integer_flag_parsed(self):
# feed_rate integer: false
p = load_problem(CONFIG_PATH)
self.assertFalse(p.variable_map["feed_rate"].integer)
class TestScalarParser(unittest.TestCase):
"""直接覆盖 _parse_scalar 的边界(内联列表/映射/数字/字符串/布尔)。"""
def test_scalars(self):
from recipe_optim.problem import _parse_scalar
self.assertEqual(_parse_scalar("1"), 1)
self.assertEqual(_parse_scalar("1.5"), 1.5)
self.assertIs(_parse_scalar("true"), True)
self.assertIs(_parse_scalar("False"), False)
self.assertEqual(_parse_scalar("99.5"), 99.5)
self.assertEqual(_parse_scalar('"A"'), "A")
self.assertEqual(_parse_scalar("[1, 2, 3]"), [1, 2, 3])
self.assertEqual(_parse_scalar("[A, B]"), ["A", "B"])
self.assertEqual(_parse_scalar("{a: 1, b: 2}"), {"a": 1, "b": 2})
if __name__ == "__main__":
unittest.main()
@@ -1,207 +0,0 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方优化求解器集成 单元测试(Issue #79)。
覆盖:
- 求解器配置(grid_steps/max_combinations 合法性);
- 候选取值生成(bounds 等分/integer 去重/choices 枚举);
- 网格求解(全局最优、可行性、target 达成、无可行解降级);
- 坐标下降(规模超限降级、收敛);
- solve 统一入口(自动选策略、静态校验失败、空问题);
- Solution 序列化;
- 加载 #78 模板后端到端求解。
"""
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: E402 挂载 recipe_optim 包
from recipe_optim.problem import ( # noqa: E402
ConstraintKind,
ConstraintSpec,
DecisionVariable,
DomainKind,
ObjectiveSpec,
ObjectiveTerm,
OptimizationProblem,
Sense,
load_problem,
)
from recipe_optim.solver import ( # noqa: E402
SolverConfig,
SolverError,
Solution,
candidate_values,
solve,
)
CONFIG_PATH = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"config", "recipe_optim.template.yaml",
)
def _toy_problem() -> OptimizationProblem:
"""minimize -(x+y),x∈[0,4] 5 点,y∈[0,4] 5 点 → 网格 25 组合。"""
return OptimizationProblem(
variables=[
DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 4.0)),
DecisionVariable("y", DomainKind.BOUNDS, bounds=(0.0, 4.0)),
],
objective=ObjectiveSpec(Sense.MAXIMIZE,
terms=[ObjectiveTerm("x", 1.0), ObjectiveTerm("y", 1.0)]),
)
class TestSolverConfig(unittest.TestCase):
def test_defaults(self):
c = SolverConfig()
self.assertGreaterEqual(c.grid_steps, 2)
self.assertGreaterEqual(c.max_combinations, 1)
def test_invalid_grid_steps(self):
with self.assertRaises(SolverError):
SolverConfig(grid_steps=1)
def test_invalid_max_combinations(self):
with self.assertRaises(SolverError):
SolverConfig(max_combinations=0)
class TestCandidateValues(unittest.TestCase):
def test_bounds_grid(self):
v = DecisionVariable("t", DomainKind.BOUNDS, bounds=(0.0, 4.0))
vals = candidate_values(v, SolverConfig(grid_steps=5))
self.assertEqual(vals[0], 0.0)
self.assertEqual(vals[-1], 4.0)
self.assertEqual(len(vals), 5)
def test_integer_dedupe(self):
v = DecisionVariable("n", DomainKind.BOUNDS, bounds=(0.0, 4.0), integer=True)
vals = candidate_values(v, SolverConfig(grid_steps=5))
self.assertEqual(vals, [0, 1, 2, 3, 4])
def test_choices_enum(self):
v = DecisionVariable("c", DomainKind.CHOICES, choices=["A", "B", "C"])
self.assertEqual(candidate_values(v, SolverConfig()), ["A", "B", "C"])
self.assertEqual(candidate_values(v, SolverConfig(enumerate_choices=False)), ["A"])
class TestSolveGrid(unittest.TestCase):
def test_global_optimum_maximize(self):
p = _toy_problem()
sol = solve(p, SolverConfig(grid_steps=5))
self.assertTrue(sol.feasible)
# 最优 x=y=4 → obj=8
self.assertAlmostEqual(sol.objective_value, 8.0)
self.assertEqual(sol.assignment["x"], 4.0)
self.assertEqual(sol.assignment["y"], 4.0)
self.assertEqual(sol.strategy, "grid")
def test_minimize(self):
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 4.0))],
objective=ObjectiveSpec(Sense.MINIMIZE, terms=[ObjectiveTerm("x", 1.0)]),
)
sol = solve(p, SolverConfig(grid_steps=5))
self.assertTrue(sol.feasible)
self.assertEqual(sol.assignment["x"], 0.0)
self.assertAlmostEqual(sol.objective_value, 0.0)
def test_target_met(self):
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 10.0))],
objective=ObjectiveSpec(Sense.MAXIMIZE, target_value=8.0,
terms=[ObjectiveTerm("x", 1.0)]),
)
sol = solve(p, SolverConfig(grid_steps=11))
self.assertTrue(sol.feasible)
self.assertTrue(sol.target_met) # x=10 >= 8
def test_target_not_met(self):
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 5.0))],
objective=ObjectiveSpec(Sense.MAXIMIZE, target_value=99.0,
terms=[ObjectiveTerm("x", 1.0)]),
)
sol = solve(p, SolverConfig(grid_steps=6))
self.assertTrue(sol.feasible)
self.assertFalse(sol.target_met)
def test_no_feasible_solution(self):
# box 收紧到与域不交 → 无可行
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 1.0))],
constraints=[ConstraintSpec(ConstraintKind.BOX, variable="x", bounds=(5.0, 6.0))],
objective=ObjectiveSpec(Sense.MAXIMIZE, terms=[ObjectiveTerm("x", 1.0)]),
)
sol = solve(p, SolverConfig(grid_steps=3))
self.assertFalse(sol.feasible)
self.assertIn("无可行解", sol.message)
class TestCoordinateDescent(unittest.TestCase):
def test_falls_back_when_grid_too_large(self):
# 三个变量 × grid_steps=5 = 125;设 max_combinations=10 → 降级
p = OptimizationProblem(
variables=[
DecisionVariable(f"v{i}", DomainKind.BOUNDS, bounds=(0.0, 4.0))
for i in range(3)
],
objective=ObjectiveSpec(Sense.MAXIMIZE,
terms=[ObjectiveTerm(f"v{i}", 1.0) for i in range(3)]),
)
sol = solve(p, SolverConfig(grid_steps=5, max_combinations=10))
self.assertEqual(sol.strategy, "coordinate_descent")
# 坐标下降应能爬到各维上界附近(贪心可收敛到此线性目标的全局最优)
self.assertTrue(sol.feasible)
self.assertAlmostEqual(sol.objective_value, 12.0, places=6)
class TestSolveEntry(unittest.TestCase):
def test_validate_failure_returns_infeasible(self):
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, bounds=(0.0, 1.0))],
objective=ObjectiveSpec(Sense.MAXIMIZE,
terms=[ObjectiveTerm("ghost", 1.0)]),
)
sol = solve(p, SolverConfig())
self.assertFalse(sol.feasible)
self.assertEqual(sol.strategy, "validate")
self.assertIn("校验失败", sol.message)
def test_empty_problem_trivially_feasible(self):
p = OptimizationProblem()
sol = solve(p, SolverConfig())
self.assertTrue(sol.feasible)
self.assertEqual(sol.strategy, "empty")
def test_solution_to_dict(self):
p = _toy_problem()
sol = solve(p, SolverConfig(grid_steps=3))
d = sol.to_dict()
self.assertIn("assignment", d)
self.assertIn("objective_value", d)
self.assertIn("evaluated", d)
self.assertTrue(d["feasible"])
class TestEndToEndFromTemplate(unittest.TestCase):
def test_solve_loaded_problem(self):
p = load_problem(CONFIG_PATH)
sol = solve(p, SolverConfig(grid_steps=7, max_combinations=200000))
# 模板含 4 变量;7^3 * 3 = 1029 组合 < 上限 → 网格
self.assertEqual(sol.strategy, "grid")
self.assertTrue(sol.feasible)
# 取值应满足 box 收紧(clf_temp∈[820,900])与 forbidden(非 C@910)
self.assertGreaterEqual(sol.assignment["clf_temp"], 820 - 1e-6)
self.assertLessEqual(sol.assignment["clf_temp"], 900 + 1e-6)
self.assertFalse(sol.assignment["catalyst"] == "C"
and sol.assignment.get("clf_temp") == 910)
# evaluated>0
self.assertGreater(sol.evaluated, 0)
if __name__ == "__main__":
unittest.main()