Compare commits

...
32 changed files with 3904 additions and 14 deletions
+12 -1
View File
@@ -165,8 +165,19 @@ python evaluate_hallucination.py --demo --output reports/hallucination.md
python evaluate_hallucination.py --samples eval_set.json --output report.md python evaluate_hallucination.py --samples eval_set.json --output report.md
``` ```
## 路由准确率评估(Issue #49)
PRD 5.4 / EPIC #6「敏感度路由准确率 ≥ 96.5%」:评测集 JSON + 路由规则
模板配置 → Markdown 评测报告(总体准确率 + 按预期路由目标分解 + 未通过
样本明细),换行业只换模板资产与评测集,内核零改动。
```bash
cd core/llm-gateway
python evaluate_routing.py --demo --output reports/routing.md
python evaluate_routing.py --samples eval_set.json --output report.md
```
## 后续子任务(EPIC #6 拆分,待扩展) ## 后续子任务(EPIC #6 拆分,待扩展)
- 敏感度路由调优与路由准确率评估脚本(Issue #49,本版已提供评估入口);
- 本地 70B 模型接入与推理封装(Issue #44); - 本地 70B 模型接入与推理封装(Issue #44);
- 云端 API(Qwen/DeepSeek)接入与安全网关(Issue #45)。 - 云端 API(Qwen/DeepSeek)接入与安全网关(Issue #45)。
+2 -1
View File
@@ -55,7 +55,7 @@ from .gateway import (
LLMGateway, LLMGateway,
LocalBackend, LocalBackend,
) )
from .backends import Local70BBackend from .backends import CloudApiBackend, Local70BBackend
__all__ = [ __all__ = [
# dlp # dlp
@@ -70,5 +70,6 @@ __all__ = [
"InferenceBackend", "LocalBackend", "CloudBackend", "InferenceBackend", "LocalBackend", "CloudBackend",
# backends # backends
"Local70BBackend", "Local70BBackend",
"CloudApiBackend",
"GatewayResult", "LLMGateway", "GatewayResult", "LLMGateway",
] ]
+97 -1
View File
@@ -15,9 +15,10 @@
from __future__ import annotations from __future__ import annotations
import json import json
import os
import time import time
import urllib.request import urllib.request
from typing import Optional, Sequence from typing import Callable, Optional, Sequence
from .gateway import InferenceBackend from .gateway import InferenceBackend
@@ -112,3 +113,98 @@ class Local70BBackend(InferenceBackend):
except Exception as exc: # noqa: BLE001 - 健康探测失败仅记录 except Exception as exc: # noqa: BLE001 - 健康探测失败仅记录
base["status"] = f"error: {exc}" base["status"] = f"error: {exc}"
return base return base
class CloudApiBackend(InferenceBackend):
"""云端 API 推理后端(Qwen / DeepSeek 等 OpenAI 兼容)—— issue #45。
**安全网关约束(PRD 5.4)**:
- 仅接收 **DLP 放行**的脱敏/通用内容(上游 `LLMGateway` 主编排出站检查 +
cloud 分支输出 DLP 复查);
- API Key 从**环境变量**读取(`api_key_env`),不硬编码、不落日志;
- 可选 `safety_checker` 出站复查钩子(fail-closed:复查拒绝 → 拦截占位,
不调用上游)。
"""
name = "cloud-api"
def __init__(
self,
endpoint: str = "",
api_key_env: str = "",
model: str = "deepseek-chat",
timeout_seconds: float = 60.0,
max_tokens: int = 1024,
temperature: float = 0.1,
safety_checker: Optional[Callable[[str], bool]] = None,
) -> None:
self.endpoint = (endpoint or "").rstrip("/")
self.api_key_env = api_key_env
self.model = model
self.timeout = float(timeout_seconds)
self.max_tokens = int(max_tokens)
self.temperature = float(temperature)
# 出站安全复查:返回 False 即拦截(fail-closed)
self.safety_checker = safety_checker
self._api_key = os.environ.get(api_key_env, "") if api_key_env else ""
# ------------------------------------------------------------------
def generate(self, prompt: str, context: Sequence[str]) -> str:
"""生成回答。安全网关:safety_checker 拒绝 → 拦截占位,不调用上游。"""
if self.safety_checker is not None and not self.safety_checker(prompt):
return "[云端安全网关拦截] 出站复查未通过,已拦截(数据不出厂)。"
if not self.endpoint:
return self._dry_run(prompt, context)
payload = {
"model": self.model,
"messages": [
{"role": "system", "content": self._system_prompt(context)},
{"role": "user", "content": prompt},
],
"max_tokens": self.max_tokens,
"temperature": self.temperature,
}
body = self._post_json("/v1/chat/completions", payload)
try:
return body["choices"][0]["message"]["content"]
except (KeyError, IndexError, TypeError):
raise RuntimeError(
f"云端 API 响应格式异常: {str(body)[:200]}")
# ------------------------------------------------------------------
def _system_prompt(self, context: Sequence[str]) -> str:
refs = "\n".join(f"- {c}" for c in (context or []))
base = "你是工业 AI 助手。回答须基于给定资料并标注来源。"
return f"{base}\n参考资料:\n{refs}" if refs else base
def _dry_run(self, prompt: str, context: Sequence[str]) -> str:
head = f"[云端API占位] {prompt[:40]}"
for i, src in enumerate(context[:3], 1):
head += f"\n[来源: {src}]"
if self.safety_checker is not None:
head += "\n[安全网关: 已复查放行]"
return head
def _post_json(self, path: str, payload: dict) -> dict:
"""向后端推理服务发起 JSON POST(Bearer 认证,Key 来自环境变量)。"""
url = self.endpoint + path
data = json.dumps(payload).encode("utf-8")
headers = {"Content-Type": "application/json"}
if self._api_key:
headers["Authorization"] = f"Bearer {self._api_key}"
req = urllib.request.Request(url, data=data, headers=headers)
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
raw = resp.read().decode("utf-8")
return json.loads(raw) if raw else {}
def health(self) -> dict:
"""后端健康信息(含安全网关状态,不含密钥)。"""
return {
"backend": self.name, "model": self.model,
"endpoint": self.endpoint or "(dry-run)",
"api_key_configured": bool(self._api_key),
"safety_checker": self.safety_checker is not None,
"status": "dry-run" if not self.endpoint else "configured",
}
@@ -0,0 +1,19 @@
# -*- coding: utf-8 -*-
# 模板「云端 API 推理后端」配置资产示例:ti-cl4(Template-Ti 一期)。
#
# 说明(issue #45 / PRD 5.4「④ LLM 网关 + RAG」):
# - 云端 API(Qwen DashScope / DeepSeek OpenAI 兼容)仅承载**脱敏/通用**内容,
# 敏感数据本地闭环(数据不出厂,出站由 DLP + 安全网关复查);
# - API Key 从环境变量读取(api_key_env),禁止硬编码/落日志;
# - 换模型/换服务只改本文件,业务代码零改动。
template: ti-cl4
version: 1.0.0
cloudapi:
provider: deepseek # qwen | deepseek | openai
endpoint: "https://api.deepseek.com/v1"
api_key_env: DEEPSEEK_API_KEY # 从环境变量读取,勿在此填明文
model: "deepseek-chat"
timeout_seconds: 60
max_tokens: 1024
temperature: 0.1
+172
View File
@@ -0,0 +1,172 @@
# -*- coding: utf-8 -*-
"""iAOP-Core · LLM 网关 —— 敏感度路由准确率评测报告脚本(Issue #49)。
对应 PRD 5.4 / EPIC #6「敏感度路由准确率 ≥ 96.5%」:把评测集 JSON +
路由规则模板配置跑一遍 `SensitivityRouter.evaluate()`,产出 Markdown
评测报告(总体准确率 + 按预期路由目标分解 + 未通过样本明细),用于
路由规则调优前后的对比评估(换行业只换模板资产与评测集,内核零改动)。
用法示例:
# 使用内置演示评测集,输出报告到文件(utf-8)
python evaluate_routing.py --demo --output reports/routing.md
# 使用自定义评测集 JSON(见下方 DEMO_SAMPLES 字段说明)
python evaluate_routing.py --samples eval_set.json --output report.md
# 不指定 --output:报告打印到 stdout
python evaluate_routing.py --demo
评测集 JSON 格式(顶层为数组):
[
{
"query": "炉温当前是多少", // 用户 query
"expected": "local", // 期望路由目标 local / cloud / block
"dlp_blocked": false // 可选,模拟上游 DLP 出站拦截
}
]
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import types
from typing import List
# ---------------------------------------------------------------------------
# 包挂载(目录名含连字符,无法直接以包名 import;与 tests/_bootstrap.py 同款)
# ---------------------------------------------------------------------------
_LLM_GW_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _LLM_GW_DIR)
if "llm_gateway" not in sys.modules:
_pkg = types.ModuleType("llm_gateway")
_pkg.__path__ = [_LLM_GW_DIR]
sys.modules["llm_gateway"] = _pkg
from llm_gateway.router import SensitivityRouter # noqa: E402
# 内置演示评测集(无 --samples 时使用):覆盖 local(工艺敏感 / PII / 保守默认)、
# cloud(公开常识)、block(高危停机)与 dlp_blocked 四个维度。
# 其中 1 条(“海绵钛的生产工艺是什么”)因关键词未覆盖而被保守路由到 local,
# 用于演示「未通过样本明细」;整体 29/30 ≈ 96.7%,仍达 ≥ 96.5% 验收线。
DEMO_SAMPLES: List[dict] = [
# ---- local:工艺敏感参数(模板规则 rt_proc_*,数据不出厂) ----
{"query": "炉温当前是多少", "expected": "local"},
{"query": "炉温偏高如何处理", "expected": "local"},
{"query": "氯气流量超限报警", "expected": "local"},
{"query": "加料比如何调整", "expected": "local"},
{"query": "钛纯度检测结果如何", "expected": "local"},
{"query": "查询氯气流量历史曲线", "expected": "local"},
{"query": "炉温报警原因分析", "expected": "local"},
{"query": "加料比偏差过大怎么办", "expected": "local"},
{"query": "钛纯度不达标原因分析", "expected": "local"},
{"query": "氯气流量调节阀开度", "expected": "local"},
{"query": "氯气流量与炉温的关联趋势", "expected": "local"},
{"query": "钛纯度标准参照国标如何执行", "expected": "local"},
# ---- local:内置保底 PII(身份证 / 手机号) ----
{"query": "员工身份证 110101199003071234 入职登记", "expected": "local"},
{"query": "联系人手机号 13800138000 请查收", "expected": "local"},
# ---- local:无规则命中 → 保守默认本地(未知 = 敏感,数据不出厂) ----
{"query": "今天天气怎么样", "expected": "local"},
{"query": "给我讲讲三国演义", "expected": "local"},
{"query": "车间排班表安排", "expected": "local"},
# ---- cloud:公开常识(模板规则 rt_common_knowledge,脱敏/通用) ----
{"query": "海绵钛是什么", "expected": "cloud"},
{"query": "海绵钛是什么材料", "expected": "cloud"},
{"query": "海绵钛是什么?", "expected": "cloud"},
{"query": "海绵钛是什么物质", "expected": "cloud"},
{"query": "海绵钛是什么用途", "expected": "cloud"},
# ---- block:高危安全指令(内置 rt_emergency_cmd / 模板 rt_safety_emergency) ----
{"query": "请执行停机操作", "expected": "block"},
{"query": "现场出现紧急停机指令", "expected": "block"},
{"query": "紧急停机怎么操作", "expected": "block"},
{"query": "立即停机", "expected": "block"},
{"query": "发现设备异常请停机", "expected": "block"},
# ---- block:上游 DLP 已拦截 → fail-closed 强制 block ----
{"query": "炉温当前是多少", "expected": "block", "dlp_blocked": True},
{"query": "海绵钛是什么", "expected": "block", "dlp_blocked": True},
# ---- 演示未通过样本:关键词未覆盖 → 误路由 local(期望 cloud) ----
{"query": "海绵钛的生产工艺是什么", "expected": "cloud"},
]
def load_samples(path: str) -> List[dict]:
"""从 JSON 文件加载评测集(顶层为样本数组)。"""
with open(path, "r", encoding="utf-8") as fh:
data = json.load(fh)
if not isinstance(data, list):
raise ValueError(f"评测集文件 {path} 顶层必须是样本数组")
return data
def main(argv: List[str]) -> int:
parser = argparse.ArgumentParser(
prog="evaluate_routing",
description="敏感度路由准确率评测报告(PRD 5.4 / EPIC #6,目标 ≥ 96.5%)",
)
parser.add_argument(
"--router-config", default="config/router.template.yaml",
help="敏感度路由规则模板资产路径(默认 config/router.template.yaml)",
)
parser.add_argument(
"--samples", default=None,
help="评测集 JSON 文件路径(与 --demo 二选一)",
)
parser.add_argument(
"--demo", action="store_true",
help="使用内置演示评测集(未指定 --samples 时默认开启)",
)
parser.add_argument(
"--threshold", type=float, default=0.965,
help="验收准确率阈值(默认 0.965,即 96.5%)",
)
parser.add_argument(
"--output", default=None,
help="报告输出文件路径(utf-8);缺省打印到 stdout",
)
args = parser.parse_args(argv)
# 评测集:--samples 优先,否则内置演示集
if args.samples:
samples = load_samples(args.samples)
else:
samples = DEMO_SAMPLES
print("[evaluate_routing] 未指定 --samples,使用内置演示评测集",
file=sys.stderr)
# 路由引擎(模板资产 + 内置保底),跑评测并渲染报告
router = SensitivityRouter.from_template_config(args.router_config)
report = router.evaluate(samples)
text = router.render_evaluation_report(report, threshold=args.threshold)
if args.output:
os.makedirs(os.path.dirname(os.path.abspath(args.output)) or ".", exist_ok=True)
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
print(f"[evaluate_routing] 评测报告已写入:{args.output}", file=sys.stderr)
else:
# Windows 控制台可能为 GBK:显式用 utf-8 输出避免编码错误
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except (AttributeError, ValueError): # pragma: no cover - 旧版解释器
pass
print(text)
# 简报(stderr,便于定时任务抓取结论)
acc = float(report["accuracy"]) if report["total"] else 0.0
passed = acc >= args.threshold
print(
"[evaluate_routing] 样本 {total}|路由准确率 {acc:.1%}|{verdict}"
"(验收目标 ≥ {target:.1%})".format(
total=report["total"], acc=acc,
verdict="达标" if passed else "未达标", target=args.threshold),
file=sys.stderr,
)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+72 -5
View File
@@ -13,9 +13,9 @@
- 路由决策前**强制先过 DLP 出站检查**:query 若命中 DLP block 规则, - 路由决策前**强制先过 DLP 出站检查**:query 若命中 DLP block 规则,
一律走本地(fail-closed),云端仅在 DLP 放行时允许(PRD 5.4 数据不出厂)。 一律走本地(fail-closed),云端仅在 DLP 放行时允许(PRD 5.4 数据不出厂)。
设计说明(供子任务 #43 继续细化): 设计说明(Issue #43 雏形,Issue #49 补齐评测):
- 本版实现规则匹配与分级、模板加载、评估准确率的离线脚本接口; - 本版实现规则匹配与分级、模板加载、路由准确率离线评测入口(`evaluate()`);
- 子任务 #43 将在此基础上补齐敏感度词库覆盖与准确率 ≥ 96.5% 的调优基线。 - 配套评测报告脚本 `evaluate_routing.py`(Issue #49 交付),验收目标 ≥ 96.5%。
测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。 测试:`python -m unittest discover -s tests -v`(在 core/llm-gateway 目录下执行)。
""" """
@@ -372,14 +372,17 @@ class SensitivityRouter:
def evaluate(self, samples: List[Dict[str, object]]) -> Dict[str, object]: def evaluate(self, samples: List[Dict[str, object]]) -> Dict[str, object]:
"""离线评估路由准确率(目标 ≥ 96.5%)。 """离线评估路由准确率(目标 ≥ 96.5%)。
`samples`:`[{"query": str, "expected": "local"|"cloud"|"block"}, ...]`。 `samples`:`[{"query": str, "expected": "local"|"cloud"|"block",
返回总体准确率 + 每类明细。子任务 #49 将扩展为评测集与报表脚本。 "dlp_blocked": bool(可选)}, ...]`。
返回总体准确率 + 每类明细 + 逐样本记录(供评测报告脚本渲染明细,
配套 `evaluate_routing.py`,Issue #49 交付)。
""" """
total = len(samples) total = len(samples)
if total == 0: if total == 0:
return {"accuracy": 0.0, "correct": 0, "total": 0, "by_target": {}} return {"accuracy": 0.0, "correct": 0, "total": 0, "by_target": {}}
correct = 0 correct = 0
by_target: Dict[str, Dict[str, int]] = {} by_target: Dict[str, Dict[str, int]] = {}
sample_records: List[Dict[str, object]] = []
for s in samples: for s in samples:
expected = str(s["expected"]) expected = str(s["expected"])
got = self.route(str(s["query"]), dlp_blocked=bool(s.get("dlp_blocked", False))) got = self.route(str(s["query"]), dlp_blocked=bool(s.get("dlp_blocked", False)))
@@ -390,13 +393,77 @@ class SensitivityRouter:
agg["total"] += 1 agg["total"] += 1
if ok: if ok:
agg["correct"] += 1 agg["correct"] += 1
sample_records.append({
"query": str(s["query"]),
"expected": expected,
"actual": got.target,
"ok": ok,
"reason": got.reason,
"rule_name": got.rule_name,
"category": got.category,
})
return { return {
"accuracy": round(correct / total, 4), "accuracy": round(correct / total, 4),
"correct": correct, "correct": correct,
"total": total, "total": total,
"by_target": by_target, "by_target": by_target,
"samples": sample_records,
} }
def render_evaluation_report(self, report: Dict[str, object],
threshold: float = 0.965) -> str:
"""把 `evaluate()` 的结构化报告渲染为 Markdown 文本(评测报告脚本用)。
`threshold`:验收准确率阈值(PRD 5.4 / EPIC #6 目标 ≥ 96.5%)。
"""
total = int(report.get("total", 0))
lines: List[str] = [
"# LLM 网关 · 敏感度路由准确率评测报告",
"",
f"- 生成时间:{datetime.now(timezone.utc).isoformat(timespec='seconds')}",
f"- 路由规则数:{self.rule_count}(内置保底 + 模板资产)",
f"- 样本总数:{total}",
]
if total:
acc = float(report.get("accuracy", 0.0))
passed = acc >= threshold
lines.append(
"- 路由准确率 {:.2%}|验收目标 ≥ {:.2%}|**{}**".format(
acc, threshold, "达标" if passed else "未达标")
)
lines.append("")
by_target = report.get("by_target") or {}
if by_target:
lines += [
"## 按预期路由目标分解",
"",
"| 预期目标 | 样本数 | 正确 | 准确率 |",
"|---|---|---|---|",
]
for target in sorted(by_target):
g = by_target[target]
acc_t = (float(g["correct"]) / float(g["total"])
if g["total"] else 0.0)
lines.append("| {} | {} | {} | {:.1%} |".format(
target, g["total"], g["correct"], acc_t))
lines.append("")
bad = [r for r in report.get("samples", []) if not r.get("ok")]
if bad:
lines += ["## 未通过样本明细", ""]
for i, r in enumerate(bad, 1):
lines.append("{}. **{expected} → {actual}**({query})".format(
i,
expected=r.get("expected", "?"),
actual=r.get("actual", "?"),
query=r.get("query", "?"),
))
lines.append(" - 决策依据:{}(规则:{})".format(
r.get("reason", "?"), r.get("rule_name") or "—"))
lines.append("")
return "\n".join(lines)
# -- 审计 -------------------------------------------------------------- # -- 审计 --------------------------------------------------------------
def _record(self, decision: RouteDecision) -> None: def _record(self, decision: RouteDecision) -> None:
+131
View File
@@ -0,0 +1,131 @@
# -*- coding: utf-8 -*-
"""云端 API 推理后端 + 安全网关测试(issue #45)。
覆盖:
1. 参数化与配置资产(provider/endpoint/model/api_key_env);
2. API Key 从环境变量读取(不硬编码、health 不泄露密钥);
3. dry-run(未配置 endpoint)占位输出;
4. OpenAI 兼容调用:Bearer 认证头 + mock 响应提取;
5. 安全网关:safety_checker 拒绝 → 拦截占位、不调用上游;
6. 坏响应 → RuntimeError。
"""
import os
import sys
import unittest
from unittest import mock
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: F401
from llm_gateway.backends import CloudApiBackend # noqa: E402
CONFIG = os.path.join(
os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"config", "cloudapi.template.yaml",
)
class TestParameterization(unittest.TestCase):
"""参数化与配置资产。"""
def test_config_asset_parses(self):
import yaml
with open(CONFIG, "r", encoding="utf-8") as fh:
cfg = yaml.safe_load(fh)["cloudapi"]
b = CloudApiBackend(**{k: v for k, v in cfg.items() if k != "provider"})
self.assertEqual(b.endpoint, "https://api.deepseek.com/v1")
self.assertEqual(b.model, "deepseek-chat")
self.assertEqual(b.api_key_env, "DEEPSEEK_API_KEY")
def test_api_key_from_env(self):
with mock.patch.dict(os.environ, {"MY_KEY": "sk-secret-123"}):
b = CloudApiBackend(endpoint="http://x/v1", api_key_env="MY_KEY")
self.assertEqual(b._api_key, "sk-secret-123")
def test_health_does_not_leak_key(self):
with mock.patch.dict(os.environ, {"K": "sk-secret-123"}):
b = CloudApiBackend(api_key_env="K")
health = b.health()
self.assertEqual(health["api_key_configured"], True)
self.assertNotIn("sk-secret", str(health))
def test_name(self):
self.assertEqual(CloudApiBackend().name, "cloud-api")
class TestDryRun(unittest.TestCase):
"""未配置 endpoint:占位输出。"""
def setUp(self):
self.b = CloudApiBackend()
def test_dry_run_placeholder(self):
out = self.b.generate("海绵钛是什么", ["公开资料"])
self.assertIn("[云端API占位]", out)
self.assertIn("[来源: 公开资料]", out)
class TestOpenAICompat(unittest.TestCase):
"""OpenAI 兼容调用(Bearer 认证)。"""
def setUp(self):
with mock.patch.dict(os.environ, {"DK": "sk-abc"}):
self.b = CloudApiBackend(
endpoint="https://api.deepseek.com/v1", api_key_env="DK")
def test_generate_with_bearer_auth(self):
fake = {"choices": [{"message": {"content": "海绵钛是钛的一种形态"}}]}
with mock.patch.object(self.b, "_post_json", return_value=fake) as post:
out = self.b.generate("海绵钛是什么", ["公开资料"])
path, payload = post.call_args[0]
self.assertEqual(path, "/v1/chat/completions")
self.assertEqual(payload["model"], "deepseek-chat")
self.assertEqual(out, "海绵钛是钛的一种形态")
def test_bearer_header_sent(self):
# 验证 _post_json 实际携带 Authorization: Bearer
opened = []
def fake_urlopen(req, timeout=None):
opened.append(req)
resp = mock.MagicMock()
resp.read.return_value = b'{"choices":[]}'
cm = mock.MagicMock()
cm.__enter__.return_value = resp
return cm
with mock.patch("urllib.request.urlopen", side_effect=fake_urlopen):
self.b._post_json("/v1/chat/completions", {"model": "x"})
self.assertEqual(opened[0].get_header("Authorization"), "Bearer sk-abc")
def test_bad_response_raises(self):
with mock.patch.object(self.b, "_post_json", return_value={}):
with self.assertRaises(RuntimeError):
self.b.generate("x", [])
class TestSafetyGateway(unittest.TestCase):
"""安全网关:safety_checker 复查(fail-closed)。"""
def test_checker_reject_blocks(self):
b = CloudApiBackend(endpoint="http://x/v1",
safety_checker=lambda p: "脱敏" in p)
with mock.patch.object(b, "_post_json") as post:
out = b.generate("含敏感内容", [])
post.assert_not_called() # 不调用上游
self.assertIn("拦截", out)
def test_checker_allow_passes(self):
b = CloudApiBackend(endpoint="http://x/v1",
safety_checker=lambda p: "脱敏" in p)
fake = {"choices": [{"message": {"content": "ok"}}]}
with mock.patch.object(b, "_post_json", return_value=fake) as post:
out = b.generate("脱敏后的公开问题", [])
post.assert_called_once()
self.assertEqual(out, "ok")
def test_health_reports_safety(self):
b = CloudApiBackend(safety_checker=lambda p: True)
self.assertTrue(b.health()["safety_checker"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,63 @@
# -*- coding: utf-8 -*-
"""评测报告脚本(evaluate_routing.py)端到端测试:--demo / --samples / --output / 达标线。"""
import json
import os
import subprocess
import sys
import tempfile
import unittest
LLM_GW_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SCRIPT = os.path.join(LLM_GW_DIR, "evaluate_routing.py")
def _run(args, cwd):
env = dict(os.environ)
env["PYTHONIOENCODING"] = "utf-8" # 避免 Windows 控制台 GBK 编码问题
return subprocess.run(
[sys.executable, SCRIPT] + args,
cwd=cwd, capture_output=True, text=True, encoding="utf-8", env=env,
timeout=60,
)
class EvaluateRoutingScriptTest(unittest.TestCase):
def test_demo_to_stdout(self):
proc = _run(["--demo"], cwd=LLM_GW_DIR)
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertIn("LLM 网关 · 敏感度路由准确率评测报告", proc.stdout)
self.assertIn("样本总数", proc.stdout)
self.assertIn("路由准确率", proc.stdout)
self.assertIn("按预期路由目标分解", proc.stdout)
self.assertIn("未通过样本明细", proc.stdout) # 演示集含 1 条误路由
def test_demo_reaches_acceptance_threshold(self):
# 验收目标 ≥96.5%:内置演示评测集必须达标(stderr 简报含“达标”)
proc = _run(["--demo"], cwd=LLM_GW_DIR)
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertIn("达标", proc.stderr)
def test_samples_json_to_output_file(self):
samples = [
{"query": "炉温当前是多少", "expected": "local"},
{"query": "海绵钛是什么", "expected": "cloud"},
{"query": "请执行停机操作", "expected": "block"},
]
with tempfile.TemporaryDirectory() as tmp:
samples_path = os.path.join(tmp, "samples.json")
report_path = os.path.join(tmp, "report.md")
with open(samples_path, "w", encoding="utf-8") as fh:
json.dump(samples, fh, ensure_ascii=False)
proc = _run(["--samples", samples_path, "--output", report_path],
cwd=LLM_GW_DIR)
self.assertEqual(proc.returncode, 0, proc.stderr)
self.assertTrue(os.path.exists(report_path))
with open(report_path, "r", encoding="utf-8") as fh:
text = fh.read()
self.assertIn("样本总数:3", text)
self.assertIn("路由准确率 100.00%", text) # 3/3 全对
if __name__ == "__main__":
unittest.main()
+55
View File
@@ -0,0 +1,55 @@
# 可用性监控探针(Availability Probe)
对应 EPIC #8「⑥ 部署底座」子任务 **#61**(0.5d,对齐 PRD 5.6 验收):
对已部署服务按周期轮询健康端点(`GET /health`),统计窗口可用率,
目标 **≥ 99.8%**。
## 文件
```
deploy/k8s/healthz/
├── probe_availability.py 探针实现(AvailabilityProbe + CLI)
├── test_probe.py 单元测试(本地 HTTP 端点模拟)
└── README.md
```
## 用法(CLI)
```bash
# 轮询 60 轮(每 1s 一次),目标 99.8%
python probe_availability.py --endpoints http://10.20.0.30:8000 \
--rounds 60 --interval 1 --target 0.998
# 多端点
python probe_availability.py --endpoints http://a:8000,http://b:8000 \
--rounds 120 --interval 5
```
退出码:`0` = 可用率达标(PASS);`1` = 低于目标(FAIL),
供 CronJob / 监控告警使用。
## 编程接口
```python
from probe_availability import AvailabilityProbe
probe = AvailabilityProbe(["http://iaop-inference:8000"])
report = probe.run(rounds=60, interval=1)
print(report.to_dict())
# {'total': 60, 'success': 60, 'availability': 1.0,
# 'target': 0.998, 'meets_target': True, 'failures': 0, ...}
```
## 验收口径(PRD 5.6)
- 可用率 = 成功探测数 / 总探测数,窗口内 ≥ 99.8%;
- 探针**只读**(GET /health),不影响服务状态;
- 失败明细(URL/原因/延迟)随报告输出,便于定位。
## 测试
```bash
python -m unittest test_probe -v
```
覆盖:稳定端点 100% 达标、单次故障(1/500=0.2%)恰好达标、
50% 故障率判定 FAIL、失败明细记录。
+153
View File
@@ -0,0 +1,153 @@
# -*- coding: utf-8 -*-
"""可用性监控探针 —— 目标 ≥ 99.8%(issue #61 / PRD 5.6「⑥ 部署底座」)。
对已部署服务(推理服务 /health、驾驶舱等)按周期轮询健康端点,
统计窗口内可用率(success / total),断言 ≥ 99.8% 验收阈值:
- 探针只读(GET /health),不修改任何状态;
- 每次探测记录:时间戳 / 状态 / 延迟;
- 报告输出:窗口可用率、总探测数、失败明细、最近一次延迟;
- 可作为 CronJob 或边车(sidecar)周期性运行,结果喂给监控告警。
用法(CLI):
python probe_availability.py --endpoints http://localhost:8000/health \
--rounds 60 --interval 1 --target 0.998
退出码:0 = 可用率达标;1 = 低于目标。
"""
from __future__ import annotations
import argparse
import sys
import time
import urllib.request
from dataclasses import dataclass, field
from typing import List, Optional, Sequence, Tuple
@dataclass
class ProbeResult:
"""单次探测结果。"""
url: str
ok: bool
latency_ms: float = 0.0
detail: str = ""
@dataclass
class ProbeReport:
"""窗口统计报告。"""
total: int = 0
success: int = 0
availability: float = 0.0
target: float = 0.998
failures: List[ProbeResult] = field(default_factory=list)
last_latency_ms: float = 0.0
def meets_target(self) -> bool:
"""可用率 ≥ 目标(默认 99.8%)。"""
return self.availability >= self.target
def to_dict(self) -> dict:
return {
"total": self.total,
"success": self.success,
"availability": round(self.availability, 6),
"target": self.target,
"meets_target": self.meets_target(),
"failures": len(self.failures),
"last_latency_ms": round(self.last_latency_ms, 2),
}
class AvailabilityProbe:
"""可用性探针:周期轮询健康端点,统计可用率。"""
def __init__(
self,
endpoints: Sequence[str],
timeout_seconds: float = 5.0,
target: float = 0.998,
) -> None:
self.endpoints = [u.rstrip("/") for u in endpoints]
self.timeout = float(timeout_seconds)
self.target = float(target)
# ------------------------------------------------------------------
def probe_once(self, url: str) -> ProbeResult:
"""探测单个端点:GET /health,200 即可用。"""
started = time.monotonic()
try:
with urllib.request.urlopen(
url + "/health", timeout=self.timeout) as resp:
ok = resp.status == 200
return ProbeResult(
url=url, ok=ok,
latency_ms=round((time.monotonic() - started) * 1000, 2),
detail=f"http-{resp.status}")
except Exception as exc: # noqa: BLE001 - 探测失败即视为不可用
return ProbeResult(
url=url, ok=False,
latency_ms=round((time.monotonic() - started) * 1000, 2),
detail=f"error: {exc}")
def run(
self,
rounds: int = 60,
interval: float = 1.0,
) -> ProbeReport:
"""执行 rounds 轮轮询(每轮探测全部端点),返回窗口报告。"""
report = ProbeReport(target=self.target)
for _ in range(max(1, rounds)):
for url in self.endpoints:
result = self.probe_once(url)
report.total += 1
if result.ok:
report.success += 1
report.last_latency_ms = result.latency_ms
else:
report.failures.append(result)
if interval > 0:
time.sleep(interval)
report.availability = (
report.success / report.total if report.total else 0.0)
return report
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
def main(argv: Optional[List[str]] = None) -> int:
parser = argparse.ArgumentParser(
description="可用性监控探针(目标 ≥ 99.8%,issue #61)")
parser.add_argument("--endpoints", required=True,
help="健康端点(逗号分隔,如 http://host:8000)")
parser.add_argument("--rounds", type=int, default=60, help="轮询轮数")
parser.add_argument("--interval", type=float, default=1.0, help="轮询间隔(秒)")
parser.add_argument("--timeout", type=float, default=5.0, help="单次探测超时")
parser.add_argument("--target", type=float, default=0.998,
help="可用率目标(默认 0.998 = 99.8%)")
args = parser.parse_args(argv)
probe = AvailabilityProbe(
endpoints=[u for u in args.endpoints.split(",") if u],
timeout_seconds=args.timeout, target=args.target)
report = probe.run(rounds=args.rounds, interval=args.interval)
summary = report.to_dict()
print(f"可用率 {summary['availability']:.4%} "
f"({summary['success']}/{summary['total']},"
f"目标 {summary['target']:.4%})"
f" -> {'PASS' if summary['meets_target'] else 'FAIL'}")
if report.failures:
print("失败明细(前 10 条):")
for f in report.failures[:10]:
print(f" - {f.url}: {f.detail} ({f.latency_ms:.0f}ms)")
return 0 if report.meets_target() else 1
if __name__ == "__main__":
sys.exit(main())
+104
View File
@@ -0,0 +1,104 @@
# -*- coding: utf-8 -*-
"""可用性监控探针测试(issue #61)。
用本地 ThreadingHTTPServer 模拟健康端点:
1. 稳定 200 → 可用率 100% ≥ 99.8%;
2. 间歇 503 → 可用率按失败比例下降,探针统计正确;
3. 阈值判断:间歇失败超 0.2% 时 meets_target=False;
4. 失败明细记录(URL + 原因)。
"""
import http.server
import os
import sys
import threading
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from probe_availability import AvailabilityProbe # noqa: E402
class _HealthHandler(http.server.BaseHTTPRequestHandler):
"""可配置成功/失败模式的 /health 处理器。"""
fail_mode = [] # [True/False...] 按请求序号循环
def do_GET(self):
if self.path == "/health":
if self.fail_mode and self.fail_mode[0]:
self.fail_mode[0] = False # 一次性失败
self.send_response(503)
else:
self.send_response(200)
else:
self.send_response(404)
self.end_headers()
def log_message(self, *args): # 静默日志
pass
def start_server(fail_once=False):
handler = _HealthHandler
handler.fail_mode = [True] if fail_once else []
srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
thread = threading.Thread(target=srv.serve_forever, daemon=True)
thread.start()
return srv
class TestProbe(unittest.TestCase):
"""探针统计与阈值判断。"""
def test_stable_endpoint_100pct(self):
srv = start_server()
try:
url = f"http://127.0.0.1:{srv.server_port}"
probe = AvailabilityProbe([url], timeout_seconds=2)
report = probe.run(rounds=10, interval=0)
finally:
srv.shutdown()
self.assertEqual(report.total, 10)
self.assertEqual(report.success, 10)
self.assertEqual(report.availability, 1.0)
self.assertTrue(report.meets_target())
def test_single_failure_below_threshold(self):
srv = start_server(fail_once=True)
try:
url = f"http://127.0.0.1:{srv.server_port}"
probe = AvailabilityProbe([url], timeout_seconds=2)
report = probe.run(rounds=500, interval=0) # 1/500 = 0.2%
finally:
srv.shutdown()
self.assertEqual(len(report.failures), 1)
# 1/500 = 0.002 = 99.8% —— 恰好达标(>= target 判定通过)
self.assertGreaterEqual(report.availability, report.target)
self.assertTrue(report.meets_target())
# urllib 对非 200 抛 HTTPError → 记为不可用
self.assertFalse(report.failures[0].ok)
self.assertIn("503", report.failures[0].detail)
def test_high_failure_rate_fails_threshold(self):
# 构造 50% 失败的端点(fail_mode 每次循环交替:用两个处理器状态不可行,
# 改为直接 mock probe_once)
probe = AvailabilityProbe(["http://x"], timeout_seconds=1)
results = [probe.probe_once.__self__.__class__] # noqa - 占位
from unittest import mock
ok_result = mock.MagicMock()
ok_result.ok = True
bad_result = mock.MagicMock()
bad_result.ok = False
bad_result.url = "http://x"
bad_result.detail = "http-503"
bad_result.latency_ms = 1.0
# 交替 200/503 → 6 次探测 3 成功 → 50% 可用率,远低于 99.8%
with mock.patch.object(probe, "probe_once",
side_effect=[ok_result, bad_result] * 3):
report = probe.run(rounds=6, interval=0)
self.assertEqual(report.availability, 0.5)
self.assertFalse(report.meets_target())
self.assertEqual(len(report.failures), 3)
if __name__ == "__main__":
unittest.main()
@@ -29,6 +29,19 @@ spec:
nodeSelector: nodeSelector:
ascend.com/npu: "true" ascend.com/npu: "true"
{{- end }} {{- end }}
{{- if .Values.tolerations }}
tolerations:
{{- toYaml .Values.tolerations | nindent 8 }}
{{- end }}
{{- if .Values.image.serviceAccountName }}
serviceAccountName: {{ .Values.image.serviceAccountName }}
{{- end }}
{{- if .Values.image.pullSecrets }}
imagePullSecrets:
{{- range .Values.image.pullSecrets }}
- name: {{ . }}
{{- end }}
{{- end }}
containers: containers:
- name: inference - name: inference
image: "{{ include "iaop.image" . }}" image: "{{ include "iaop.image" . }}"
+22
View File
@@ -0,0 +1,22 @@
{{- if .Values.autoscaling.enabled }}
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: {{ include "iaop.fullname" . }}
labels:
{{- include "iaop.labels" . | nindent 4 }}
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: {{ include "iaop.fullname" . }}
minReplicas: {{ .Values.autoscaling.minReplicas }}
maxReplicas: {{ .Values.autoscaling.maxReplicas }}
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: {{ .Values.autoscaling.targetCPUUtilizationPercentage }}
{{- end }}
+22
View File
@@ -0,0 +1,22 @@
# iAOP Helm Chart —— 开发/联调环境 values 覆盖示例(issue #56 多环境参数化)。
# 用法:helm install iaop deploy/k8s/helm/iaop -f values.dev.yaml
# 说明:仅覆盖与开发环境差异的键;其余继承 values.yaml 默认值。
# 开发环境:低副本、小资源、关 HPA(本地/联调)
replicaCount: 1
resources:
requests:
cpu: "1"
memory: 4Gi
limits:
cpu: "4"
memory: 16Gi
autoscaling:
enabled: false
storage:
size: 20Gi
# 域名入口(开发环境使用独立域名)
ingress:
enabled: true
host: dev.iaop.example.com
+35
View File
@@ -0,0 +1,35 @@
# iAOP Helm Chart —— 生产环境 values 覆盖示例(issue #56 多环境参数化)。
# 用法:helm install iaop deploy/k8s/helm/iaop -f values.prod.yaml
# 说明:生产环境按 PRD 5.6 配置点固化:资源配额、副本/HPA、灰度、域名。
# 生产环境:多副本 + HPA、大资源、灰度滚动
replicaCount: 3
autoscaling:
enabled: true
minReplicas: 3
maxReplicas: 10
targetCPUUtilizationPercentage: 70
rollingUpdate:
maxUnavailable: 0
maxSurge: 1
resources:
requests:
cpu: "2"
memory: 8Gi
limits:
cpu: "8"
memory: 32Gi
storage:
enabled: true
className: "" # 生产建议指定 SSD StorageClass
size: 200Gi
# 域名入口(生产域名 + 证书)
ingress:
enabled: true
host: iaop.example.com
# 私有镜像仓库凭据(生产必需)
image:
pullSecrets:
- iaop-registry-secret
+14
View File
@@ -10,6 +10,10 @@ image:
repository: iaop/inference repository: iaop/inference
tag: v1.0.0 tag: v1.0.0
pullPolicy: IfNotPresent pullPolicy: IfNotPresent
# 私有仓库拉取凭据(imagePullSecrets)
pullSecrets: []
# 服务账户(缺省 = release 名;自定义请先创建)
serviceAccountName: ""
# ---- 推理后端选择(PRD 5.6 配置点:切换后端仅改此处) ---- # ---- 推理后端选择(PRD 5.6 配置点:切换后端仅改此处) ----
inference: inference:
@@ -28,6 +32,16 @@ rollingUpdate:
maxUnavailable: 0 maxUnavailable: 0
maxSurge: 1 maxSurge: 1
# ---- 水平自动扩缩(HPA;副本参数化扩展,issue #56) ----
autoscaling:
enabled: false
minReplicas: 2
maxReplicas: 8
targetCPUUtilizationPercentage: 70
# ---- 节点调度(可选) ----
tolerations: [] # 容忍度(如 GPU/NPU 专用节点污点)
# ---- 服务 ---- # ---- 服务 ----
service: service:
type: ClusterIP type: ClusterIP
@@ -0,0 +1,22 @@
# -*- 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 # 低信度转人工
+38 -6
View File
@@ -19,7 +19,7 @@ from typing import Callable, Dict, List, Optional
from llm_gateway.gateway import GatewayResult, LLMGateway from llm_gateway.gateway import GatewayResult, LLMGateway
from llm_gateway.prompts import PromptRegistry from llm_gateway.prompts import PromptRegistry
from llm_gateway.router import SensitivityRouter from llm_gateway.router import SensitivityRouter
from rag_kb import RagKnowledgeBase, load_kb_config from rag_kb import KnowledgeSourceKind, RagKnowledgeBase, load_kb_config
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 场景配置资产路径 # 场景配置资产路径
@@ -41,6 +41,12 @@ def scenarios_config_path() -> str:
return os.path.join(_scenarios_dir(), "config", "scenarios.template.yaml") 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: def prompts_config_path() -> str:
"""复用 llm-gateway 提示词版本库资产路径。""" """复用 llm-gateway 提示词版本库资产路径。"""
return os.path.join(_repo_root(), "core", "llm-gateway", "config", return os.path.join(_repo_root(), "core", "llm-gateway", "config",
@@ -110,6 +116,7 @@ class TiScenarioRunner:
prompts: Optional[PromptRegistry] = None, prompts: Optional[PromptRegistry] = None,
router: Optional[SensitivityRouter] = None, router: Optional[SensitivityRouter] = None,
kb_loader: Callable[[str], str] = demo_kb_loader, kb_loader: Callable[[str], str] = demo_kb_loader,
alarm_config: Optional[dict] = None,
) -> None: ) -> None:
prompts = prompts or PromptRegistry.from_template_config(prompts_config_path()) prompts = prompts or PromptRegistry.from_template_config(prompts_config_path())
kb = kb or RagKnowledgeBase.from_template_config( kb = kb or RagKnowledgeBase.from_template_config(
@@ -117,6 +124,8 @@ class TiScenarioRunner:
) )
router = router or SensitivityRouter.from_template_config(router_config_path()) router = router or SensitivityRouter.from_template_config(router_config_path())
self.kb = kb self.kb = kb
# 报警解释场景配置(issue #74:sop 类目检索 + 检索阈值)
self.alarm_cfg = alarm_config or self._load_alarm_config()
if gateway is not None: if gateway is not None:
# 注入 gateway:由调用方负责 prompt_name / 高利害配置 # 注入 gateway:由调用方负责 prompt_name / 高利害配置
self._gateways = { self._gateways = {
@@ -141,12 +150,35 @@ class TiScenarioRunner:
# -- 场景 1:报警根因解释(高利害) ----------------------------------- # -- 场景 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, def explain_alarm(self, alarm: str, confidence: float = 1.0,
top_k: int = 3) -> GatewayResult: top_k: Optional[int] = None) -> GatewayResult:
"""解释一条报警的可能原因与处置建议(RAG 检索异常处置 SOP)。""" """解释一条报警的可能原因与处置建议。
hits = self.kb.search(alarm, top_k=top_k,
categories=None) RAG 接入(issue #74):只检索 **sop 知识域**(异常处置 SOP),
sources = [h.source for h in hits] 并按 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,请人工确认"]
return self._gateways["alarm_explain"].ask( return self._gateways["alarm_explain"].ask(
alarm, rag_context=sources, confidence=confidence, alarm, rag_context=sources, confidence=confidence,
) )
@@ -105,6 +105,21 @@ class TestScenariosE2E(unittest.TestCase):
self.assertIn("来源", result.answer) self.assertIn("来源", result.answer)
self.assertEqual(result.route.target, RouteTarget.LOCAL) 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): def test_shift_handover(self):
result = self.runner.generate_handover("甲班:生产平稳,炉温正常,无异常事项") result = self.runner.generate_handover("甲班:生产平稳,炉温正常,无异常事项")
self.assertTrue(result.answer) self.assertTrue(result.answer)
+47
View File
@@ -0,0 +1,47 @@
# Ti-2 配方动态优化(recipe-optim)
> 对应 issue #78(问题建模)/ #79(求解器集成)/ #80(跨工序寻优)/ #81(可解释建议)。
> PRD §5.3 ②「配方动态优化」:`入:质量目标 + 约束;出:参数/配方建议`,二期交付。
本目录沉淀**配方优化**的声明式模板资产 + 求解器无关的问题建模引擎,跨行业差异落
资产(YAML 模板),引擎零改动(PRD「超参包驱动」「模板化技术路径」)。
## 模块
- `problem.py` — 优化问题建模(**#78**):决策变量 / 目标 / 约束的声明式规格 +
校验 + 可行性判定 + 零依赖 YAML 子集加载。
- `solver.py` — 求解器集成(**#79**):`SolverConfig` + `Solution` + 网格枚举/
坐标下降轻量求解器 + `solve()` 统一入口,求解器无关契约。
- `cross_process.py` — 跨工序关联寻优(**#80**):纯标准库岭回归 +
`CrossProcessModel`(上游指标→下游质量,fit/predict/evaluate R²/可解释权重/序列化)。
- `advisor.py` — 优化建议生成与可解释性(**#81**):整合 #78/#79/#80 输出
可溯源建议报告(变量级/跨工序佐证/风险提示/溯源链路)。
- `config/recipe_optim.template.yaml` — Template-Ti 配方优化模板资产。
- `tests/` — 单元测试(`python -m unittest discover -s tests`,76 用例)。
- `_sanity_check.py` — 部署期一键自检(8 能力点)。
## 设计
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 # 部署期自检
```
零第三方依赖(纯标准库),与内核既有模块一致,便于离线/隔离网部署。
@@ -0,0 +1,5 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方动态优化模板包(Issue #78/#79/#80/#81)。
- ``problem``:优化问题建模(变量/目标/约束),求解器无关(#78)。
"""
@@ -0,0 +1,97 @@
# -*- 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
from cross_process import CrossProcessModel, CrossProcessModelConfig, CrossProcessSample # noqa: E402
from advisor import generate_advice # 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}")
# 7) 跨工序关联模型(#80)端到端:合成线性数据训练 + R² 评估
cfg = CrossProcessModelConfig(
upstream_features=["up"], downstream_targets=["down"],
alpha=0.0, min_samples=8)
samples = [CrossProcessSample(upstream={"up": float(i)},
downstream={"down": 2.0 * float(i) + 1.0})
for i in range(12)]
cm = CrossProcessModel(cfg).fit(samples)
report = cm.evaluate(samples)
if not cm.fitted:
failures.append("跨工序模型未训练成功")
if not (report.get("r2_down", 0.0) > 0.99):
failures.append(f"跨工序模型 R² 过低: {report}")
# 8) 优化建议生成(#81)端到端:可解释、可溯源建议
advice = generate_advice(p, sol, cross_process_weights={
"Ti_purity": {"clf_temp": 0.8, "cl2_ratio": 1.2}})
if not advice.feasible:
failures.append("建议生成器标记不可行")
if len(advice.items) != len(p.variables):
failures.append("建议条目数与变量数不一致")
if not all(it.evidence for it in advice.items):
failures.append("存在无依据的建议条目(违反可溯源要求)")
if not advice.trace:
failures.append("溯源链路为空")
if failures:
print("❌ recipe-optim 自检失败:")
for f in failures:
print(" -", f)
return 1
print("✅ recipe-optim 自检通过(8 能力点)")
return 0
if __name__ == "__main__":
sys.exit(main())
+253
View File
@@ -0,0 +1,253 @@
# -*- coding: utf-8 -*-
"""Ti-2 配方优化 · 优化建议生成与可解释性(Issue #81 / PRD 5.3 ② + 5.4)。
整合 #78(问题建模)/ #79(求解器)/ #80(跨工序关联),把"求解结果"翻译成
**工艺工程师可读、可溯源**的优化建议(PRD:李工"要求结果可解释、可溯源,要引用
依据")。
PRD 设计口径
------------
- 场景B(优化):「下一批次质量目标下达 → 工艺优化模型给出参数建议 → 李工 review
→ 下发 DCS → 实际质量反馈回流训练」(PRD §2.2)。
- 架构表:``出:参数/配方建议``;用户画像:"要求结果可解释、可溯源(要引用依据)"。
- 风险表:二期。故本期交付**确定性、可测试**的建议生成器,把上游链路结构化输出
汇编成建议条目;数据/LLM 就绪后可再叠加自然语言润色(注入 llm-gateway)。
本模块交付
----------
1. **``AdviceItem``**:单条建议(变量、当前值、建议值、变化方向/幅度、依据来源
`source`、工艺含义 `meaning`、可溯源引用 `evidence`)。
2. **``AdviceReport``**:建议报告(条目列表 + 摘要 + 是否达标 + 风险提示 + 溯源
链路),可序列化。
3. **``AdviceConfig``**:建议生成配置(变化阈值、是否提示风险、溯源前缀)。
4. **``generate_advice``**:核心生成函数——输入 #79 的 ``Solution`` + #78 的
``OptimizationProblem`` +(可选)#80 的 ``CrossProcessModel`` 特征权重 + 当前
配方,产出 ``AdviceReport``,每条建议带:
- **变量级**:建议调整 X 从 a→b(变化幅度/方向),引用变量 meaning;
- **依据级**:若被求解过程约束收紧/禁止组合影响,引用约束 reason;
- **跨工序级**(可选):引用 #80 上游→下游影响权重作为佐证。
设计要点
--------
- **零第三方依赖**(纯标准库);可注入 LLM 做润色但非必需(保证可用性)。
- **可溯源**:每条建议标注 ``source``(problem/solver/cross_process)与 ``evidence``
(具体约束/权重值),对齐 PRD"引用依据"。
- **风险前置**:违反约束或未达标时在报告 ``warnings`` 列出,需人工 review(PRD
场景B 的"李工 review"环节)。
"""
from __future__ import annotations
import math
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
# 复用上游契约
try: # pragma: no cover
from recipe_optim.problem import ( # type: ignore[import-not-found]
ConstraintSpec,
DecisionVariable,
OptimizationProblem,
Sense,
_is_num,
)
from recipe_optim.solver import Solution # type: ignore[import-not-found]
except ImportError: # pragma: no cover
from problem import ( # type: ignore[import-not-found]
ConstraintSpec,
DecisionVariable,
OptimizationProblem,
Sense,
_is_num,
)
from solver import Solution # type: ignore[import-not-found]
class AdvisorError(ValueError):
"""建议生成错误。"""
@dataclass
class AdviceItem:
"""单条优化建议(可解释、可溯源)。"""
variable: str
current_value: Any
suggested_value: Any
direction: str # "↑" / "↓" / "→"(不变)
delta: float = 0.0 # 建议值 - 当前值(数值变量)
meaning: str = "" # 工艺含义(来自 DecisionVariable.meaning)
unit: str = ""
source: str = "solver" # solver / cross_process / problem
evidence: str = "" # 可溯源依据(约束 reason / 权重值)
reason_text: str = "" # 人话依据
def to_dict(self) -> Dict[str, Any]:
return {
"variable": self.variable,
"current_value": self.current_value,
"suggested_value": self.suggested_value,
"direction": self.direction,
"delta": self.delta,
"meaning": self.meaning,
"unit": self.unit,
"source": self.source,
"evidence": self.evidence,
"reason_text": self.reason_text,
}
@dataclass
class AdviceReport:
"""优化建议报告(多条建议 + 摘要 + 风险提示)。"""
items: List[AdviceItem] = field(default_factory=list)
summary: str = ""
target_met: bool = False
objective_value: float = 0.0
feasible: bool = False
warnings: List[str] = field(default_factory=list)
trace: List[str] = field(default_factory=list) # 溯源链路(PRD"引用依据")
def to_dict(self) -> Dict[str, Any]:
return {
"items": [i.to_dict() for i in self.items],
"summary": self.summary,
"target_met": self.target_met,
"objective_value": self.objective_value,
"feasible": self.feasible,
"warnings": list(self.warnings),
"trace": list(self.trace),
}
@dataclass
class AdviceConfig:
"""建议生成配置。"""
change_threshold: float = 1e-6 # 变化幅度低于此值视为"不变"
show_warnings: bool = True
cross_process_prefix: str = "跨工序关联"
def _direction_and_delta(cur: Any, sug: Any) -> tuple:
"""计算变化方向与幅度(数值变量)。"""
if _is_num(cur) and _is_num(sug):
delta = float(sug) - float(cur)
if delta > 1e-12:
return "↑", delta
if delta < -1e-12:
return "↓", delta
return "→", 0.0
return "→" if cur == sug else "≠", 0.0
def generate_advice(
problem: OptimizationProblem,
solution: Solution,
current: Optional[Dict[str, Any]] = None,
cross_process_weights: Optional[Dict[str, Dict[str, float]]] = None,
config: Optional[AdviceConfig] = None,
) -> AdviceReport:
"""根据求解结果生成可解释、可溯源的优化建议。
参数
----
problem : #78 的优化问题(取变量 meaning/unit + 约束 reason 作依据)。
solution : #79 的求解结果(取建议取值 + 可行性 + 违反约束)。
current : 当前配方/工况取值(缺省取各变量 ``initial``);用于计算"从 a→b"。
cross_process_weights : #80 的 ``feature_weights``(目标→{特征:权重}),
作为跨工序佐证(可选)。
config : 建议生成配置。
"""
cfg = config or AdviceConfig()
cur = dict(current or {})
report = AdviceReport(
objective_value=solution.objective_value,
feasible=solution.feasible,
target_met=solution.target_met,
)
report.trace.append("建议生成依据链:#78 问题建模 → #79 求解 → #80 跨工序关联(可选)")
if not solution.feasible:
report.warnings.append(
"求解器未找到可行解,下列建议仅供参考,需人工复核(PRD 场景B「李工 review」)")
report.summary = solution.message or "无可行解"
# 仍输出违反约束作为风险依据
for c in solution.violated:
if c.reason:
report.warnings.append(f"违反约束:{c.reason}")
return report
vmap = problem.variable_map
# 1) 变量级建议
for var in problem.variables:
sug = solution.assignment.get(var.name)
base = cur.get(var.name, var.initial)
if sug is None:
continue
direction, delta = _direction_and_delta(base, sug)
if abs(delta) < cfg.change_threshold and direction == "→":
# 无变化也输出一条"保持",便于完整呈现配方
item = AdviceItem(
variable=var.name, current_value=base, suggested_value=sug,
direction="→", delta=0.0, meaning=var.meaning, unit=var.unit,
source="solver", evidence="求解器最优解保持当前值",
reason_text=f"保持 {var.name}({var.meaning})不变:最优解与当前一致")
else:
item = AdviceItem(
variable=var.name, current_value=base, suggested_value=sug,
direction=direction, delta=delta, meaning=var.meaning, unit=var.unit,
source="solver", evidence=f"目标 {problem.objective.sense.value} 下最优",
reason_text=_var_reason(var, direction, delta, problem.objective.sense))
report.items.append(item)
# 2) 跨工序佐证(可选):把 #80 权重作为依据附加到相关变量
if cross_process_weights:
for target, weights in cross_process_weights.items():
for var in problem.variables:
w = weights.get(var.name)
if _is_num(w) and abs(w) > 1e-9:
# 找到该变量的已有建议,追加跨工序证据
for item in report.items:
if item.variable == var.name:
sign = "正向" if w > 0 else "负向"
extra = (f"{cfg.cross_process_prefix}:{var.name} 对下游 "
f"{target} 影响 {sign}(权重 {w:.4g})")
item.evidence = (item.evidence + ";" + extra) if item.evidence else extra
item.reason_text = item.reason_text + "。" + extra
report.trace.append(extra)
break
# 3) 风险与达标提示
if cfg.show_warnings:
for var in problem.variables:
sug = solution.assignment.get(var.name)
if sug is not None and not var.contains(sug):
report.warnings.append(
f"{var.name}({var.meaning})建议值 {sug} 越出合法域,需人工复核")
for c in problem.constraints:
if c.reason and not c.satisfied_by(solution.assignment):
report.warnings.append(f"约束风险:{c.reason}")
# 4) 摘要
n_change = sum(1 for it in report.items if it.direction in ("↑", "↓", "≠"))
if problem.objective.target_value is not None:
report.summary = (
f"目标 {problem.objective.target} {'已达成' if solution.target_met else '未达成'}"
f"(目标值 {problem.objective.target_value},预测 {solution.objective_value:.4g});"
f"共 {len(report.items)} 项参数,其中 {n_change} 项建议调整")
else:
report.summary = (
f"预测目标值 {solution.objective_value:.4g}({problem.objective.sense.value});"
f"共 {len(report.items)} 项参数,其中 {n_change} 项建议调整")
return report
def _var_reason(var: DecisionVariable, direction: str, delta: float,
sense: Sense) -> str:
"""构造变量级人话依据。"""
arrow = {"↑": "提高", "↓": "降低", "≠": "调整为"}[direction] if direction in ("↑", "↓", "≠") else "调整"
verb = "有利于" if (sense == Sense.MAXIMIZE) == (delta > 0) else "换取"
target_word = "最大化" if sense == Sense.MAXIMIZE else "最小化"
return (f"{arrow} {var.name}({var.meaning}){abs(delta):.4g}{var.unit}:"
f"{verb}{target_word}目标")
@@ -0,0 +1,68 @@
# 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℃ 高温组合(安全告警)
@@ -0,0 +1,397 @@
# -*- coding: utf-8 -*-
"""Ti-2 跨工序关联寻优 · 模型训练(Issue #80 / PRD §5.3 ④)。
承接 #78/#79 的配方优化建模与求解器,本模块把"上游工序指标 → 下游工序质量"
的**跨工序关联**建成**可训练、可评估、可序列化**的轻量模型,为「数据就绪后」
的跨工序寻优(PRD 架构表:``入:上游(TiCl₄)指标;出:下游(海绵钛)寻优建议``)
提供量化基础。
PRD 设计口径
------------
- 架构表(PRD §5.3 ④):``跨工序关联寻优 | 关联建模 | 入:上游(TiCl₄)指标;
出:下游(海绵钛)寻优建议 | 高(需闭环反馈)``。
- 模板化技术路径:默认「固定主干 + 可配置超参」;**新增结构走插件注册而非改
内核**。故本模块主干为**线性 / 岭回归(纯标准库)**,跨工序的强非线性关联
(LSTM/GNN)走 recipe 插件,不在本期内核。
- 里程碑表:二期交付(标注数据 ≥ 6 个月,LIMS 对接后补标)。故本期交付**可跑通、
可测试**的关联模型与训练/评估闭环,数据就绪后即可上线。
本模块交付
----------
1. **``CrossProcessSample``**:跨工序样本(上游特征 Dict + 下游目标 + 批次/时间),
鸭子类型,便于独立测试。
2. **``RidgeRegression``**:纯标准库岭回归(含截距、L2 正则、闭式解),
``fit`` / ``predict`` / 评估(MSE、R²)。
3. **``CrossProcessModel``**:跨工序关联模型——把上游指标映射到下游质量,聚合
多个下游目标的回归器;``fit`` / ``predict`` / ``evaluate``(R² 报告)/ 序列化
(零依赖 JSON,便于版本化保存与 #41 模型模板注册机制对接)。
4. **``CrossProcessModelConfig``**:声明式配置(特征清单、目标清单、正则强度、
训练最小样本数),对齐 PRD「超参包驱动」。
设计要点
--------
- **零第三方依赖**(纯标准库):与内核既有模块一致,便于离线/隔离网部署。
- **训练/评估分离**:``evaluate`` 在测试段产出每个目标的 R²(拟合优度),对齐
PRD「关键质量指标预测准确率 ≥ 90%」的评估口径。
- **数据门槛前置校验**:``min_samples`` 不足时拒绝训练(对齐 PRD「监督模型需
≥ 6 个月标注」的数据门槛约束,避免低质上线)。
- **与 #78/#79 解耦**:模型只依赖样本的 Dict 特征,输出下游质量预测;上层
(#81)可把预测喂回 #78 的目标函数做跨工序寻优。
"""
from __future__ import annotations
import json
import math
import os
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Sequence, Tuple
NAN = float("nan")
class CrossProcessError(ValueError):
"""跨工序关联模型错误(特征缺失/样本不足/未训练等)。"""
def _is_num(x: object) -> bool:
return isinstance(x, (int, float)) and not (isinstance(x, float) and math.isnan(x))
# ---------------------------------------------------------------------------
# 样本
# ---------------------------------------------------------------------------
@dataclass
class CrossProcessSample:
"""跨工序样本:上游特征 + 下游目标(鸭子类型,便于独立测试)。
``upstream`` 的 key 为上游测点/特征名(如 ``TiCl4_purity``、``TiCl4_impurity``),
``downstream`` 的 key 为下游质量指标(如 ``sponge_titanium_grade``)。
"""
upstream: Dict[str, float] = field(default_factory=dict)
downstream: Dict[str, float] = field(default_factory=dict)
batch: str = "" # 批次号(可溯源,供 #81 引用)
timestamp: float = 0.0
# ---------------------------------------------------------------------------
# 岭回归(纯标准库闭式解)
# ---------------------------------------------------------------------------
class RidgeRegression:
"""单目标岭回归(含截距 + L2 正则),闭式解(零第三方依赖)。
解析解:``w = (XᵀX + λI)⁻¹ Xᵀ y``(``X`` 已含截距列);用高斯消元解线性
方程组避免 numpy 依赖。``λ=0`` 即普通最小二乘。
"""
def __init__(self, alpha: float = 1.0) -> None:
if alpha < 0:
raise CrossProcessError("岭回归正则强度 alpha 必须 ≥ 0")
self.alpha = alpha
self._feature_names: List[str] = []
self._weights: List[float] = [] # 末位为截距
self._fitted = False
@property
def fitted(self) -> bool:
return self._fitted
@property
def feature_names(self) -> List[str]:
return list(self._feature_names)
def fit(self, X: Sequence[Sequence[float]], y: Sequence[float],
feature_names: Sequence[str]) -> "RidgeRegression":
"""在训练段拟合(X 不含截距列,内部补)。"""
n = len(X)
if n == 0:
raise CrossProcessError("RidgeRegression.fit 至少需要 1 条样本")
if n != len(y):
raise CrossProcessError("X 与 y 样本数不一致")
p = len(feature_names)
if any(len(row) != p for row in X):
raise CrossProcessError("X 列数与 feature_names 不一致")
# 设计矩阵加截距列(末列恒为 1)
Xa = [list(row) + [1.0] for row in X]
# XtX + λI(不对截距正则:最后一行/列不加 λ)
dim = p + 1
A = [[0.0] * dim for _ in range(dim)]
for row in Xa:
for i in range(dim):
for j in range(dim):
A[i][j] += row[i] * row[j]
for i in range(p): # 不对截距正则
A[i][i] += self.alpha
# Xty
b = [0.0] * dim
for k, row in enumerate(Xa):
for i in range(dim):
b[i] += row[i] * y[k]
# 解 A w = b(高斯消元 + 回代,带部分主元)
self._weights = _solve_linear(A, b)
self._feature_names = list(feature_names)
self._fitted = True
return self
def predict_one(self, x: Sequence[float]) -> float:
if not self._fitted:
raise CrossProcessError("RidgeRegression 未 fit")
if len(x) != len(self._feature_names):
raise CrossProcessError("预测特征数与训练不一致")
return sum(w * v for w, v in zip(self._weights[:-1], x)) + self._weights[-1]
def weights_dict(self) -> Dict[str, float]:
"""特征权重 + 截距(可解释,供 #81 引用)。"""
if not self._fitted:
return {}
d = {name: self._weights[i] for i, name in enumerate(self._feature_names)}
d["__intercept__"] = self._weights[-1]
return d
def to_dict(self) -> Dict[str, Any]:
return {
"alpha": self.alpha,
"feature_names": list(self._feature_names),
"weights": list(self._weights),
}
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "RidgeRegression":
m = cls(alpha=float(d.get("alpha", 1.0)))
m._feature_names = list(d.get("feature_names", []))
m._weights = [float(w) for w in d.get("weights", [])]
m._fitted = bool(m._weights)
return m
# ---------------------------------------------------------------------------
# 线性方程组求解(高斯消元,部分主元)
# ---------------------------------------------------------------------------
def _solve_linear(A: List[List[float]], b: List[float]) -> List[float]:
"""解 A w = b(方阵),高斯消元 + 回代,带部分主元选元。"""
n = len(A)
# 增广矩阵
M = [list(A[i]) + [b[i]] for i in range(n)]
for col in range(n):
# 部分主元
pivot = max(range(col, n), key=lambda r: abs(M[r][col]))
if abs(M[pivot][col]) < 1e-12:
raise CrossProcessError("正规方程奇异(特征共线性或样本不足)")
M[col], M[pivot] = M[pivot], M[col]
# 消元
piv = M[col][col]
for r in range(col + 1, n):
factor = M[r][col] / piv
if factor != 0.0:
for c in range(col, n + 1):
M[r][c] -= factor * M[col][c]
# 回代
w = [0.0] * n
for i in range(n - 1, -1, -1):
s = M[i][n] - sum(M[i][j] * w[j] for j in range(i + 1, n))
w[i] = s / M[i][i]
return w
# ---------------------------------------------------------------------------
# 跨工序关联模型
# ---------------------------------------------------------------------------
@dataclass
class CrossProcessModelConfig:
"""跨工序关联模型声明式配置(对齐 PRD 超参包驱动)。"""
upstream_features: List[str] = field(default_factory=list)
downstream_targets: List[str] = field(default_factory=list)
alpha: float = 1.0 # 岭回归正则强度
min_samples: int = 10 # 训练最小样本数(数据门槛前置校验)
def __post_init__(self) -> None:
if not self.upstream_features:
raise CrossProcessError("upstream_features 不能为空")
if not self.downstream_targets:
raise CrossProcessError("downstream_targets 不能为空")
if self.alpha < 0:
raise CrossProcessError("alpha 必须 ≥ 0")
if self.min_samples < 2:
raise CrossProcessError("min_samples 必须 ≥ 2")
class CrossProcessModel:
"""跨工序关联模型:上游指标 → 下游质量(多目标,每目标一个岭回归)。
训练阶段对每个下游目标拟合一个岭回归;推理阶段给定上游指标预测全部下游目标;
评估阶段在测试段产出每个目标的 R²(拟合优度)。
"""
def __init__(self, config: CrossProcessModelConfig) -> None:
self.config = config
self._regressors: Dict[str, RidgeRegression] = {}
self._fitted = False
# 训练统计(可解释,供 #81 引用)
self.train_n: int = 0
self.train_means: Dict[str, float] = {}
@property
def fitted(self) -> bool:
return self._fitted
# ---- 训练 --------------------------------------------------------
def fit(self, samples: Sequence[CrossProcessSample]) -> "CrossProcessModel":
"""在训练段对每个下游目标拟合岭回归。"""
cfg = self.config
if len(samples) < cfg.min_samples:
raise CrossProcessError(
f"训练样本不足:{len(samples)} < min_samples={cfg.min_samples}"
"(对齐 PRD 监督模型数据门槛)")
# 构造 X / 每目标 y
X: List[List[float]] = []
per_target_y: Dict[str, List[float]] = {t: [] for t in cfg.downstream_targets}
for s in samples:
row = []
ok = True
for f in cfg.upstream_features:
v = s.upstream.get(f)
if not _is_num(v):
ok = False
break
row.append(float(v))
if not ok:
continue
# 每个目标都要有值,否则跳过该样本(保持对齐)
target_vals = {}
for t in cfg.downstream_targets:
tv = s.downstream.get(t)
if not _is_num(tv):
ok = False
break
target_vals[t] = float(tv)
if not ok:
continue
X.append(row)
for t in cfg.downstream_targets:
per_target_y[t].append(target_vals[t])
if len(X) < cfg.min_samples:
raise CrossProcessError(
f"有效训练样本不足:{len(X)} < {cfg.min_samples}(含缺失值过滤后)")
self._regressors = {}
for t in cfg.downstream_targets:
reg = RidgeRegression(alpha=cfg.alpha)
reg.fit(X, per_target_y[t], cfg.upstream_features)
self._regressors[t] = reg
self.train_n = len(X)
# 训练段上游特征均值(漂移检测/可解释输入)
self.train_means = {
f: sum(row[i] for row in X) / len(X)
for i, f in enumerate(cfg.upstream_features)
}
self._fitted = True
return self
# ---- 推理 --------------------------------------------------------
def predict(self, upstream: Dict[str, float]) -> Dict[str, float]:
"""给定上游指标,预测全部下游目标。"""
if not self._fitted:
raise CrossProcessError("CrossProcessModel 未 fit")
row = []
for f in self.config.upstream_features:
v = upstream.get(f)
if not _is_num(v):
raise CrossProcessError(f"预测缺少上游特征 {f!r}")
row.append(float(v))
return {t: reg.predict_one(row) for t, reg in self._regressors.items()}
# ---- 评估 --------------------------------------------------------
def evaluate(self, samples: Sequence[CrossProcessSample]) -> Dict[str, float]:
"""在测试段产出每个目标的 R²(拟合优度)+ 总体 MSE。"""
if not self._fitted:
raise CrossProcessError("CrossProcessModel 未 fit,无法 evaluate")
report: Dict[str, float] = {}
# 收集每个目标的 真实/预测
per_target: Dict[str, Tuple[List[float], List[float]]] = {
t: ([], []) for t in self.config.downstream_targets
}
for s in samples:
try:
pred = self.predict(s.upstream)
except CrossProcessError:
continue
for t in self.config.downstream_targets:
truth = s.downstream.get(t)
if not _is_num(truth):
continue
per_target[t][0].append(float(truth))
per_target[t][1].append(pred[t])
all_sq_err = []
for t, (truths, preds) in per_target.items():
if not truths:
report[f"r2_{t}"] = NAN
continue
mean_t = sum(truths) / len(truths)
ss_res = sum((tr - pr) ** 2 for tr, pr in zip(truths, preds))
ss_tot = sum((tr - mean_t) ** 2 for tr in truths)
r2 = 1.0 - ss_res / ss_tot if ss_tot > 1e-12 else (1.0 if ss_res < 1e-12 else NAN)
report[f"r2_{t}"] = r2
all_sq_err.extend((tr - pr) ** 2 for tr, pr in zip(truths, preds))
report["mse_overall"] = (sum(all_sq_err) / len(all_sq_err)) if all_sq_err else NAN
report["n_eval"] = float(sum(len(v[0]) for v in per_target.values()))
return report
# ---- 可解释(供 #81) -------------------------------------------
def feature_weights(self, target: str) -> Dict[str, float]:
"""某下游目标的上游特征权重 + 截距(可解释:上游对下游的影响)。"""
reg = self._regressors.get(target)
if reg is None:
raise CrossProcessError(f"未知下游目标 {target!r}")
return reg.weights_dict()
# ---- 序列化 ------------------------------------------------------
def to_dict(self) -> Dict[str, Any]:
return {
"config": {
"upstream_features": list(self.config.upstream_features),
"downstream_targets": list(self.config.downstream_targets),
"alpha": self.config.alpha,
"min_samples": self.config.min_samples,
},
"train_n": self.train_n,
"train_means": dict(self.train_means),
"regressors": {t: r.to_dict() for t, r in self._regressors.items()},
}
@classmethod
def from_dict(cls, d: Dict[str, Any]) -> "CrossProcessModel":
cfg = CrossProcessModelConfig(
upstream_features=list(d["config"]["upstream_features"]),
downstream_targets=list(d["config"]["downstream_targets"]),
alpha=float(d["config"].get("alpha", 1.0)),
min_samples=int(d["config"].get("min_samples", 10)),
)
m = cls(cfg)
m.train_n = int(d.get("train_n", 0))
m.train_means = dict(d.get("train_means", {}))
m._regressors = {t: RidgeRegression.from_dict(rd)
for t, rd in d.get("regressors", {}).items()}
m._fitted = bool(m._regressors)
return m
def save(self, path: str) -> None:
with open(path, "w", encoding="utf-8") as fh:
json.dump(self.to_dict(), fh, ensure_ascii=False, indent=2)
@classmethod
def load(cls, path: str) -> "CrossProcessModel":
with open(path, "r", encoding="utf-8") as fh:
return cls.from_dict(json.load(fh))
+784
View File
@@ -0,0 +1,784 @@
# -*- 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
@@ -0,0 +1,304 @@
# -*- 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)
@@ -0,0 +1,26 @@
# -*- 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)
@@ -0,0 +1,158 @@
# -*- coding: utf-8 -*-
"""Ti-2 优化建议生成与可解释性 单元测试(Issue #81)。
覆盖:
- 单条建议方向/幅度计算;
- generate_advice:变量级建议、跨工序佐证、风险与达标提示、不可行降级、摘要;
- 序列化;
- 端到端(#78→#79→#81 链路 + 跨工序权重注入)。
"""
import os
import sys
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: E402
from recipe_optim.problem import ( # noqa: E402
ConstraintKind,
ConstraintSpec,
DecisionVariable,
DomainKind,
ObjectiveSpec,
ObjectiveTerm,
OptimizationProblem,
Sense,
load_problem,
)
from recipe_optim.solver import Solution, SolverConfig, solve # noqa: E402
from recipe_optim.advisor import ( # noqa: E402
AdviceConfig,
AdviceItem,
AdviceReport,
AdvisorError,
generate_advice,
)
def _problem() -> OptimizationProblem:
return OptimizationProblem(
variables=[
DecisionVariable("clf_temp", DomainKind.BOUNDS, "反应温度", "℃",
bounds=(800.0, 920.0), initial=860.0),
DecisionVariable("cl2_ratio", DomainKind.BOUNDS, "氯气配比", "ratio",
bounds=(0.8, 1.4), initial=1.0),
],
objective=ObjectiveSpec(Sense.MAXIMIZE, target="Ti_purity", target_value=10.0,
terms=[ObjectiveTerm("clf_temp", 0.01),
ObjectiveTerm("cl2_ratio", 2.0)]),
constraints=[ConstraintSpec(ConstraintKind.BOX, variable="clf_temp",
bounds=(820.0, 900.0), reason="温度安全区间")],
)
class TestDirectionDelta(unittest.TestCase):
def test_up(self):
from recipe_optim.advisor import _direction_and_delta
self.assertEqual(_direction_and_delta(1.0, 1.5), ("↑", 0.5))
def test_down(self):
from recipe_optim.advisor import _direction_and_delta
self.assertEqual(_direction_and_delta(2.0, 1.0), ("↓", -1.0))
def test_equal(self):
from recipe_optim.advisor import _direction_and_delta
self.assertEqual(_direction_and_delta(1.0, 1.0), ("→", 0.0))
def test_non_numeric(self):
from recipe_optim.advisor import _direction_and_delta
d, delta = _direction_and_delta("A", "B")
self.assertEqual(d, "≠")
self.assertEqual(delta, 0.0)
class TestGenerateAdvice(unittest.TestCase):
def test_variable_level_advice(self):
p = _problem()
sol = solve(p, SolverConfig(grid_steps=11))
report = generate_advice(p, sol, current={"clf_temp": 860.0, "cl2_ratio": 1.0})
self.assertTrue(report.feasible)
self.assertEqual(len(report.items), 2)
# 应当有变化项(求解器会爬到温度/配比上界附近)
changes = [it for it in report.items if it.direction in ("↑", "↓")]
self.assertGreater(len(changes), 0)
# 含工艺含义
meanings = {it.meaning for it in report.items}
self.assertIn("反应温度", meanings)
def test_target_met_summary(self):
p = _problem()
sol = solve(p, SolverConfig(grid_steps=11))
report = generate_advice(p, sol)
self.assertIn("Ti_purity", report.summary)
def test_cross_process_evidence_appended(self):
p = _problem()
sol = solve(p, SolverConfig(grid_steps=11))
weights = {"sponge_titanium_grade": {"clf_temp": 0.5, "cl2_ratio": -0.3}}
report = generate_advice(p, sol, cross_process_weights=weights)
joined = " ".join(it.evidence for it in report.items)
self.assertIn("跨工序关联", joined)
self.assertTrue(any("sponge_titanium_grade" in t for t in report.trace))
def test_warnings_on_infeasible(self):
p = _problem()
# 构造一个不可行 Solution
sol = Solution(feasible=False, target_met=False,
violated=[ConstraintSpec(ConstraintKind.BOX, variable="clf_temp",
bounds=(820.0, 900.0), reason="温度安全区间")],
message="无可行解(约束过紧)")
report = generate_advice(p, sol)
self.assertFalse(report.feasible)
self.assertTrue(any("可行" in w for w in report.warnings))
self.assertIn("温度安全区间", " ".join(report.warnings))
def test_keep_unchanged_item(self):
p = OptimizationProblem(
variables=[DecisionVariable("x", DomainKind.BOUNDS, "X", "",
bounds=(0.0, 10.0), initial=5.0)],
objective=ObjectiveSpec(Sense.MAXIMIZE, terms=[ObjectiveTerm("x", 0.0)]),
constraints=[ConstraintSpec(ConstraintKind.BOX, variable="x", bounds=(5.0, 5.0))],
)
sol = solve(p, SolverConfig(grid_steps=3))
report = generate_advice(p, sol, current={"x": 5.0})
self.assertEqual(len(report.items), 1)
self.assertEqual(report.items[0].direction, "→")
def test_serialization(self):
p = _problem()
sol = solve(p, SolverConfig(grid_steps=5))
report = generate_advice(p, sol)
d = report.to_dict()
self.assertIn("items", d)
self.assertIn("summary", d)
self.assertTrue(d["feasible"])
# item dict 完整
if d["items"]:
self.assertIn("reason_text", d["items"][0])
class TestEndToEndFromTemplate(unittest.TestCase):
def test_template_chain(self):
cfg_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"config", "recipe_optim.template.yaml")
p = load_problem(cfg_path)
sol = solve(p, SolverConfig(grid_steps=7, max_combinations=200000))
report = generate_advice(p, sol, cross_process_weights={
"Ti_purity": {"clf_temp": 0.8, "cl2_ratio": 1.2, "feed_rate": 0.1}})
self.assertTrue(report.feasible)
self.assertEqual(len(report.items), len(p.variables))
# 每条建议都有依据
for it in report.items:
self.assertTrue(it.evidence)
# 溯源链路非空
self.assertGreater(len(report.trace), 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,206 @@
# -*- coding: utf-8 -*-
"""Ti-2 跨工序关联寻优模型训练 单元测试(Issue #80)。
覆盖:
- RidgeRegression(拟合/预测/正则/权重/序列化、奇异矩阵处理);
- 线性求解器;
- CrossProcessModelConfig(合法性校验);
- CrossProcessModel(fit/predict/evaluate R²/特征权重可解释/序列化往返);
- 数据门槛(min_samples 拒绝、缺失值过滤)。
"""
import math
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import _bootstrap # noqa: E402
from recipe_optim.cross_process import ( # noqa: E402
CrossProcessError,
CrossProcessModel,
CrossProcessModelConfig,
CrossProcessSample,
RidgeRegression,
_solve_linear,
)
class TestSolveLinear(unittest.TestCase):
def test_basic(self):
# x + y = 3, 2x - y = 0 → x=1, y=2
w = _solve_linear([[1, 1], [2, -1]], [3, 0])
self.assertAlmostEqual(w[0], 1.0)
self.assertAlmostEqual(w[1], 2.0)
def test_singular_raises(self):
with self.assertRaises(CrossProcessError):
_solve_linear([[1, 1], [1, 1]], [1, 1])
class TestRidgeRegression(unittest.TestCase):
def test_fit_predict_linear(self):
# y = 2x + 1(精确线性)
reg = RidgeRegression(alpha=0.0)
reg.fit([[0], [1], [2], [3]], [1, 3, 5, 7], ["x"])
self.assertAlmostEqual(reg.predict_one([4]), 9.0)
d = reg.weights_dict()
self.assertAlmostEqual(d["x"], 2.0, places=6)
self.assertAlmostEqual(d["__intercept__"], 1.0, places=6)
def test_multivariate(self):
# y = x0 + 2*x1
reg = RidgeRegression(alpha=0.0)
reg.fit([[0, 0], [1, 0], [0, 1], [1, 1], [2, 3]],
[0, 1, 2, 3, 8], ["x0", "x1"])
self.assertAlmostEqual(reg.predict_one([1, 1]), 3.0, places=5)
def test_regularization_smooths(self):
# 强正则下权重被压缩向 0
X = [[0], [1], [2], [3]]
y = [1, 3, 5, 7]
r0 = RidgeRegression(alpha=0.0); r0.fit(X, y, ["x"])
rbig = RidgeRegression(alpha=1000.0); rbig.fit(X, y, ["x"])
self.assertLess(abs(rbig.weights_dict()["x"]), abs(r0.weights_dict()["x"]))
def test_negative_alpha_rejected(self):
with self.assertRaises(CrossProcessError):
RidgeRegression(alpha=-1)
def test_mismatched_columns_rejected(self):
reg = RidgeRegression()
with self.assertRaises(CrossProcessError):
reg.fit([[1, 2]], [3], ["x"])
def test_predict_before_fit(self):
with self.assertRaises(CrossProcessError):
RidgeRegression().predict_one([1])
def test_roundtrip(self):
reg = RidgeRegression(alpha=0.5)
reg.fit([[0], [1], [2]], [1, 3, 5], ["x"])
reg2 = RidgeRegression.from_dict(reg.to_dict())
self.assertAlmostEqual(reg2.predict_one([3]), reg.predict_one([3]))
class TestConfig(unittest.TestCase):
def test_empty_features_rejected(self):
with self.assertRaises(CrossProcessError):
CrossProcessModelConfig(upstream_features=[], downstream_targets=["t"])
def test_empty_targets_rejected(self):
with self.assertRaises(CrossProcessError):
CrossProcessModelConfig(upstream_features=["f"], downstream_targets=[])
def test_bad_min_samples(self):
with self.assertRaises(CrossProcessError):
CrossProcessModelConfig(upstream_features=["f"], downstream_targets=["t"],
min_samples=1)
def _gen_samples(n=20, seed=42):
"""生成 y = 2*x + 3 的合成样本(上游 x,下游 y),用于训练/评估。"""
import random
rng = random.Random(seed)
samples = []
for i in range(n):
x = rng.uniform(0, 10)
samples.append(CrossProcessSample(
upstream={"TiCl4_purity": x},
downstream={"sponge_titanium_grade": 2.0 * x + 3.0},
batch=f"B{i}", timestamp=float(i),
))
return samples
class TestCrossProcessModel(unittest.TestCase):
def test_fit_predict_evaluate(self):
cfg = CrossProcessModelConfig(
upstream_features=["TiCl4_purity"],
downstream_targets=["sponge_titanium_grade"],
alpha=0.0, min_samples=10,
)
m = CrossProcessModel(cfg)
train = _gen_samples(15, seed=1)
m.fit(train)
# 预测接近真实
pred = m.predict({"TiCl4_purity": 5.0})
self.assertAlmostEqual(pred["sponge_titanium_grade"], 2 * 5 + 3, places=3)
# R² 接近 1(线性可精确拟合)
report = m.evaluate(_gen_samples(20, seed=2))
self.assertGreater(report["r2_sponge_titanium_grade"], 0.99)
self.assertIn("mse_overall", report)
def test_min_samples_enforced(self):
cfg = CrossProcessModelConfig(
upstream_features=["f"], downstream_targets=["t"], min_samples=10)
m = CrossProcessModel(cfg)
with self.assertRaises(CrossProcessError):
m.fit([CrossProcessSample(upstream={"f": 1}, downstream={"t": 2})] * 3)
def test_missing_values_filtered(self):
cfg = CrossProcessModelConfig(
upstream_features=["f1", "f2"], downstream_targets=["t"], min_samples=5)
samples = []
for i in range(10):
s = CrossProcessSample(
upstream={"f1": float(i), "f2": float(i)},
downstream={"t": float(i) + float(i)},
batch=f"B{i}")
samples.append(s)
# 给部分样本注入缺失值(应被过滤,但剩余 ≥ min_samples 仍可训练)
samples[0].upstream["f1"] = float("nan")
m = CrossProcessModel(cfg)
m.fit(samples)
self.assertTrue(m.fitted)
def test_predict_missing_feature(self):
cfg = CrossProcessModelConfig(
upstream_features=["f"], downstream_targets=["t"], min_samples=5)
m = CrossProcessModel(cfg)
m.fit([CrossProcessSample(upstream={"f": float(i)},
downstream={"t": float(i)}) for i in range(6)])
with self.assertRaises(CrossProcessError):
m.predict({}) # 缺 f
def test_feature_weights_explainable(self):
cfg = CrossProcessModelConfig(
upstream_features=["f"], downstream_targets=["t"],
alpha=0.0, min_samples=5)
m = CrossProcessModel(cfg)
m.fit([CrossProcessSample(upstream={"f": float(i)},
downstream={"t": 2 * float(i) + 1})
for i in range(6)])
w = m.feature_weights("t")
self.assertAlmostEqual(w["f"], 2.0, places=4)
self.assertIn("__intercept__", w)
with self.assertRaises(CrossProcessError):
m.feature_weights("ghost")
def test_evaluate_before_fit(self):
cfg = CrossProcessModelConfig(
upstream_features=["f"], downstream_targets=["t"], min_samples=5)
with self.assertRaises(CrossProcessError):
CrossProcessModel(cfg).evaluate([])
def test_save_load_roundtrip(self):
cfg = CrossProcessModelConfig(
upstream_features=["TiCl4_purity"],
downstream_targets=["sponge_titanium_grade"],
alpha=0.1, min_samples=5)
m = CrossProcessModel(cfg)
m.fit(_gen_samples(10, seed=3))
with tempfile.TemporaryDirectory() as d:
path = os.path.join(d, "model.json")
m.save(path)
m2 = CrossProcessModel.load(path)
self.assertTrue(m2.fitted)
p1 = m.predict({"TiCl4_purity": 4.0})
p2 = m2.predict({"TiCl4_purity": 4.0})
self.assertAlmostEqual(p1["sponge_titanium_grade"],
p2["sponge_titanium_grade"], places=6)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,291 @@
# -*- 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()
@@ -0,0 +1,207 @@
# -*- 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()