sebagonz106/Anomaly-Detection-System
GitHub: sebagonz106/Anomaly-Detection-System
结合 LLM 语义解析与搜索算法,自动检测质谱和蛋白质组学实验数据中违反自定义质量规则的异常测量值的 AI 系统。
Stars: 0 | Forks: 0
# 质谱与蛋白质组学数据中的异常检测
**课程:** 人工智能与仿真
**技术:** 约束满足问题 (CSP) · 模拟退火 (SA) · LLM 语义 Agent
**领域:** 分析化学 — MS1, DDA, 蛋白质组学, 代谢组学
## 概述
该系统用于检测质谱和蛋白质组学实验数据集中的异常测量值。它结合了三种 AI/优化范式:
1. **LLM Pipeline** — 一个两步语言模型 Agent,(A) 从自然语言描述中解析实验背景并推断数据 schema,然后 (B) 将用户定义的质量规则形式化为一个类型化的结构化目录。
2. **规则引擎** — 一个多态评估引擎,支持跨三个作用域(个体、全局、分组)的 16 种规则类型,涵盖特定领域的约束,如 PPM 质量误差、同位素模式匹配、漏切位点、电荷态验证和统计异常值检测。
3. **求解器引擎** — 两个可互换的求解器,用于寻找需要移除的最小测量值子集,以满足所有硬约束:用于小型数据集的精确 Branch-and-Bound CSP 求解器,以及用于在较大型数据集上可扩展操作的模拟退火求解器。
## 系统架构
```
User Input (CSV + natural language description + rules)
│
▼
┌───────────────────────────────┐
│ LLM Pipeline │
│ Step A: ExperimentParser │ → infers technique, schema, field types
│ Step B: RuleExtractor │ → formalizes rules referencing real fields
└──────────────┬────────────────┘
│ ExperimentSpec
▼
┌───────────────────────────────┐
│ Rule Engine │ → evaluates 16 rule types, returns violators
└──────────────┬────────────────┘
│
▼
┌───────────────────────────────┐
│ Solver Engine │
│ CSP (exact, n < 200) │
│ SA (scalable, any size) │ → min |S| s.t. dataset \ S satisfies all hard rules
└──────────────┬────────────────┘
│
▼
AnomalyResult + LLM Explanations
```
## 项目结构
```
Anomaly-Detection-System/
├── config.yaml # LLM provider and solver hyperparameters
├── requirements.txt
│
├── src/
│ ├── domain/
│ │ ├── models.py # Core data structures
│ │ ├── generator.py # Synthetic dataset generator
│ │ └── instances/ # Pre-generated JSON instances
│ │
│ ├── llm/
│ │ ├── base_agent.py # Abstract LLMAgent interface
│ │ ├── prompts.py # Reusable system prompts
│ │ ├── ollama_agent.py # Llama 3.2 (local)
│ │ ├── anthropic_agent.py # Claude (cloud)
│ │ ├── openai_agent.py # GPT (cloud)
│ │ ├── utils.py # Uility functions
│ │ └── factory.py # Agent factory from config
│ │
│ ├── rules/
│ │ ├── engine.py # RuleEngine — 16 rule type implementations
│ │ └── loader.py # JSON dict[] → Rule[]
│ │
│ ├── solvers/
│ │ ├── base_solver.py # Abstract AnomalySolver interface
│ │ ├── csp_solver.py # Branch-and-Bound exact solver
│ │ ├── sa_solver.py # Simulated Annealing solver
│ │ └── factory.py # Solver factory from config
│ │
│ ├── evaluation/
│ │ ├── metrics.py # Precision, recall, F1
│ │ ├── benchmark.py # Multi-config SA vs CSP runner
│ │ └── plots.py # Convergence curves, heatmaps, boxplots
│ │
│ ├── cli.py # Unified CLI entry point
│ │
│ └── main.py # Backend orchestrator
│
├── tests/ # Unit tests
│ ├── test_generator.py
│ ├── test_llm.py
│ ├── test_models.py
│ ├── test_rules.py
│ └── test_solvers.py
│
└── results/ # Output directory (git-ignored)
```
## 关键组件
### 数据模型 (`models.py`)
系统使用完全通用的 `Measurement` 类型和 `fields: dict[str, Any]` 容器,允许在无需修改代码的情况下表示任何实验格式。`ExperimentSpec` 将推断的 schema、解析的测量值和形式化的规则聚合到一个对象中,贯穿整个 pipeline 传递。
`Rule` 对象包含一个 `RuleType` 枚举、一个 `Severity` (hard/soft)、一个 `RuleScope` (individual/global/group),以及一个 `params` 字典,其键取决于规则类型。
### LLM Pipeline (`llm/`)
`LLMAgent` 是一个抽象类,包含三个方法:
- `parse_experiment_context(description, columns, sample_rows)` — 步骤 A。识别实验技术并推断字段名称和类型。返回一个带有 `ExperimentSchema` 的结构化 JSON。
- `parse_rules(user_rules_text, schema, technique)` — 步骤 B。将自由文本规则转换为 `Rule` 兼容的 JSON,使用已知的字段名称以确保正确的引用。
- `explain_anomaly(measurement, violated_rules, technique)` — 步骤 C (post-solver)。为每个检测到的异常生成特定领域的自然语言解释。
为 **Ollama (Llama 3.2)** 和 **Anthropic (Claude)** 提供了具体的实现。通过 `config.yaml` 选择活跃的提供者。
### 规则引擎 (`rules/engine.py`)
`RuleEngine.evaluate(rule, measurements)` 分发给 16 个类型化的处理程序之一,并返回违反该规则的测量值索引列表。这 16 种类型按作用域组织:
| 作用域 | 规则类型 |
|---|---|
| Individual | `range`, `threshold`, `ppm_error`, `ratio`, `inter_field`, `sequence_match`, `uniqueness` |
| Global | `zscore`, `iqr_outlier`, `correlation`, `monotonic`, `temporal_jump` |
| Group | `isotope_pattern`, `coverage`, `charge_state`, `missed_cleavages` |
`RuleEngine.cost(rules, measurements, alpha, beta)` 计算 SA 求解器使用的加权能量分数,其中硬规则违规由 `alpha` 惩罚,软规则违规由 `beta` 惩罚。
### CSP 求解器 (`solvers/csp_solver.py`)
对大小不断增加的移除子集实现 Branch-and-Bound 搜索。它预先识别强制移除候选者(孤立情况下违反个体硬规则的测量值),以优先安排分支顺序。保证找到全局最小的移除集,但由于组合复杂度,仅适用于 `n < 200` 的情况。
### 模拟退火求解器 (`solvers/sa_solver.py`)
能量函数为:
```
E(S) = α · Σ(hard violations × weight)
+ β · Σ(soft violations × weight)
+ γ · |removed measurements|
```
`γ` 项驱动移除集大小的最小化。使用了两个邻域算子:**flip**(切换一个测量值的激活状态)和 **swap**(交换两个测量值的状态),由 `swap_prob` 控制。温度遵循几何冷却计划 `T(t) = T₀ · cooling^t`。适用于任意大的数据集。
### 模拟器 (`simulation/generator.py`)
`MassSpecSimulator` 为四种实验类型生成合成数据集,每种类型都带有特定领域的异常注入:
- **MS1** — 超出范围的 m/z、负强度、强度尖峰、低信噪比
- **DDA** — 高 PPM 质量误差、无效电荷态、低鉴定得分、过多的漏切位点
- **Proteomics** — 极端强度比、零强度、重复肽段
- **Isotope** — 模式反转、相对于理论分布的强度尖峰
## 安装
**要求:** Python 3.11+
```
# Clone the repository
git clone https://github.com/your-org/spectro_anomaly.git
cd spectro_anomaly
# Create and activate a virtual environment (recommended)
python -m venv .venv
source .venv/bin/activate # Linux/macOS
.venv\Scripts\activate # Windows
# Install dependencies
pip install -r requirements.txt
```
## 配置
运行前请编辑 `config.yaml`。最重要的选项:
```
llm:
provider: ollama # "ollama" | "anthropic"
params:
model: llama3.2
base_url: http://localhost:11434
solver:
default: sa # "sa" | "csp"
sa:
T_initial: 1.0
T_final: 0.001
cooling: 0.995
max_iter: 15000
alpha: 100.0 # hard rule violation penalty
beta: 10.0 # soft rule violation penalty
gamma: 1.0 # removal size penalty
seed: 42
csp:
max_removals: 50
```
**使用 Ollama(本地,默认):**
```
# Install Ollama from https://ollama.com, then:
ollama pull llama3.2
# Ensure config.yaml has: llm.provider = ollama
```
**使用 Claude(云端):**
```
export ANTHROPIC_API_KEY=sk-ant-...
# Set in config.yaml: llm.provider = anthropic
```
## 用法
### 分析实验
准备三个文件:
- `data.csv` — 实验数据集(任意列名)
- `description.txt` — 实验的纯文本描述(技术、仪器、目的)
- `rules.txt` — 用自然语言编写的质量规则(例如,*"m/z 必须在 50 到 1100 之间"*,*"电荷态不得超过 6"*)
然后运行:
```
python main.py \
--input data.csv \
--description description.txt \
--rules rules.txt \
--solver sa
```
结果将保存到 `results/result.json`,包括检测到的异常索引、每项规则的违规计数以及 LLM 生成的解释。
若要改用精确的 CSP 求解器:
```
python main.py --input data.csv --description description.txt --rules rules.txt --solver csp
```
### 生成合成测试实例
```
python -c "
from simulation.generator import MassSpecSimulator
sim = MassSpecSimulator()
sim.save_instances(sim.generate_batch())
"
# Instances are written to simulation/instances/
```
### 运行完整基准测试
跨所有实验类型和异常率(5%、10%、20%、30%)比较三种 SA 配置和 CSP 求解器,生成评估表和图表:
```
python main.py --benchmark
```
输出文件位于 `results/`:
- `benchmark_results.csv` — 每个求解器和实例的原始指标
- `heatmap_f1.png` — F1 分数热图:求解器 × 异常率
- `time_boxplot.png` — 每个求解器的执行时间分布
- `convergence_*.png` — 每种实验类型的 SA 能量收敛曲线
### 运行测试
```
python -m pytest tests/ -v
```
## 基准求解器配置
| 配置 | α | β | γ | 冷却 | 备注 |
|---|---|---|---|---|---|
| SA-base | 100 | 10 | 1 | 0.995 | 均衡默认值 |
| SA-strict | 200 | 5 | 2 | 0.998 | 优先考虑硬约束 |
| SA-soft | 50 | 50 | 1 | 0.990 | 同等平衡硬约束和软约束 |
| CSP | — | — | — | — | 精确;仅限 n ≤ 100 的实例 |
## 输出格式
`results/result.json` 遵循此结构:
```
{
"experiment": {
"name": "...",
"technique": "DDA",
"schema": { "fields": { "mz": "float", ... } }
},
"anomalies": [3, 17, 42],
"violations_per_rule": {
"R1": [3, 17],
"R2": [42]
},
"explanations": {
"3": "Measurement 3 exhibits a PPM error of 87.4, far exceeding ...",
"17": "..."
},
"solver": "SimulatedAnnealing",
"iterations": 14823,
"elapsed_seconds": 1.74
}
```
## 依赖
```
numpy>=1.26
pandas>=2.0
matplotlib>=3.8
seaborn>=0.13
requests>=2.31
anthropic>=0.25
pyyaml>=6.0
```
## 许可
本项目是作为人工智能与仿真课程的一部分为学术目的而开发的。模拟器生成的所有合成数据均为虚构,不包含任何真实的实验测量值。
标签:AI风险缓解, DLL 劫持, 云计算, 人工智能, 分析化学, 大语言模型, 异常检测, 用户模式Hook绕过, 约束满足问题, 规则引擎, 质谱分析, 逆向工具