Deploy_0.9.0/src/torusfold/scheme2/multifidelity_scheduler.py

src / torusfold / scheme2 / multifidelity_scheduler.py

src/torusfold/scheme2/multifidelity_scheduler.py · 5.0 KB

"""
multifidelity_scheduler.py — 多保真度调度器 (简化 3 级版)

聚焦 CG 精修阶段,3 级保真度:
- CG_FAST:    LAMMPS 500 steps, 快速探索
- CG_MEDIUM:  LAMMPS 5000 steps, 中等精度
- CG_REST2:   REST2 8 副本增强采样

调度规则:
  1. 前 3 轮: CG_FAST (快速探索)
  2. 能量波动大: CG_FAST (快速逃离)
  3. 接近能量盆地: CG_REST2 (增强采样)
  4. 默认: CG_MEDIUM (中等精度)

保留旧接口兼容: FidelityLevel.name 仍可被 _steps_for_level() 使用。
"""
from __future__ import annotations

from dataclasses import dataclass, field
from enum import IntEnum
from typing import Dict, List, Optional

import numpy as np


class FidelityLevel(IntEnum):
    """保真度级别 (3 级, 聚焦 CG 阶段)."""
    CG_FAST = 0       # LAMMPS 500 steps, 快速探索 (~1ps)
    CG_MEDIUM = 1     # LAMMPS 5000 steps, 中等精度 (~10ps)
    CG_REST2 = 2      # REST2 8副本增强采样 (~100ps)


@dataclass
class SimulationState:
    """当前模拟状态."""
    step: int = 0                          # 当前轮数
    temperature: float = 300.0             # 当前温度 (K)
    energy: float = 0.0                    # 当前能量 (kT)
    energy_history: List[float] = field(default_factory=list)
    rmsd_to_last_minima: float = 100.0     # 与最近能量最低点的 RMSD
    pair_rate: float = 0.0                 # 配对率
    cross_segment_ok_rate: float = 0.0     # 跨片段配对距离<15Å的比例
    clash_count: int = 0                   # P-P 碰撞数 (新增)
    rmsd_change: float = 0.0               # 相对上一轮 RMSD 变化 (新增)

    @property
    def energy_fluctuation(self) -> float:
        """能量波动 (最近 100 步的标准差)."""
        if len(self.energy_history) < 5:
            return float("inf")
        recent = self.energy_history[-100:]
        return float(np.std(recent))


class RuleScheduler:
    """规则调度器: 基于简单规则决定保真度.

    3 级调度, 聚焦 CG 阶段:
      - CG_FAST: 前期探索 + 波动大时快速逃离
      - CG_REST2: 接近盆地时增强采样
      - CG_MEDIUM: 默认中等精度
    """

    def __init__(
        self,
        n_fast_rounds: int = 3,
        rmsd_threshold: float = 5.0,
        pair_rate_threshold: float = 0.7,
        cross_segment_threshold: float = 0.8,
    ):
        self.n_fast_rounds = n_fast_rounds
        self.rmsd_threshold = rmsd_threshold
        self.pair_rate_threshold = pair_rate_threshold
        self.cross_segment_threshold = cross_segment_threshold
        self.history: List[Dict] = []

    def decide(self, state: SimulationState) -> FidelityLevel:
        """根据状态决定保真度级别.

        规则:
        1. 前 n_fast_rounds 轮: CG_FAST (快速探索)
        2. 能量波动大: CG_FAST (快速逃离)
        3. 接近能量盆地 (RMSD 低): CG_REST2 (增强采样)
        4. 默认: CG_MEDIUM (中等精度)
        """
        record = {"step": state.step, "energy": state.energy}

        # 规则 1: 前期快速探索
        if state.step < self.n_fast_rounds:
            level = FidelityLevel.CG_FAST
            record["reason"] = f"前期探索 (step={state.step})"

        # 规则 2: 能量波动大 → 快速逃离
        elif state.energy_fluctuation > 500.0:
            level = FidelityLevel.CG_FAST
            record["reason"] = f"波动大 (σ={state.energy_fluctuation:.0f})"

        # 规则 3: 接近能量盆地 → 增强采样
        elif state.rmsd_to_last_minima < self.rmsd_threshold:
            level = FidelityLevel.CG_REST2
            record["reason"] = f"接近盆地 (RMSD={state.rmsd_to_last_minima:.1f})"

        # 默认: 中等精度
        else:
            level = FidelityLevel.CG_MEDIUM
            record["reason"] = "默认中等精度"

        record["level"] = level.value
        record["level_name"] = level.name
        self.history.append(record)

        return level

    def get_summary(self) -> Dict:
        """获取调度历史摘要."""
        if not self.history:
            return {}
        levels = [h["level"] for h in self.history]
        return {
            "total_steps": len(self.history),
            "level_distribution": {
                level.name: levels.count(level.value)
                for level in FidelityLevel
            },
            "time_ratio": self._estimate_time_ratio(),
        }

    def _estimate_time_ratio(self) -> Dict[str, float]:
        """估算各保真度的时间占比."""
        time_per_step = {
            FidelityLevel.CG_FAST: 1.0,       # ~1min
            FidelityLevel.CG_MEDIUM: 10.0,     # ~10min
            FidelityLevel.CG_REST2: 80.0,      # ~80min
        }
        total_time = 0
        level_time = {}
        for h in self.history:
            level = FidelityLevel(h["level"])
            t = time_per_step[level]
            level_time[level.name] = level_time.get(level.name, 0) + t
            total_time += t

        return {k: v / total_time for k, v in level_time.items()} if total_time > 0 else {}

← 返回文件树 · 在 GitHub 上查看