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

src / torusfold / scheme2 / isrnacirc_wrapper.py

src/torusfold/scheme2/isrnacirc_wrapper.py · 28.6 KB

"""
isrnacirc_wrapper.py — IsRNAcirc C++ 组件的 Python 包装器

调用 Vfold3D/LAMMPS/全原子重建的 C++ 可执行文件,
提供 Python 接口供 isRNAcircLong 管线使用。

核心改动: LAMMPS 精修改为调用 IsRNAcirc.exe (Type=1 模式),
不再自己生成 LAMMPS 脚本(原实现有 read_data 格式错误)。
"""
from __future__ import annotations

import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import List, Optional, Tuple

import numpy as np

# MinGW DLL 路径: CG_to_allatom.exe / IsRNAcirc.exe 等都依赖
_mingw_bin = "C:/msys64/mingw64/bin"
if Path(_mingw_bin).exists():
    os.environ["PATH"] = _mingw_bin + ";" + os.environ.get("PATH", "")


# ── 路径配置 ──
# 优先从环境变量读取,否则用相对路径推断
_ISRNCIRC_ROOT = None
for _env_var in ["ISRNCIRC_ROOT", "ISRNCIRC_PATH"]:
    if _env_var in os.environ:
        _ISRNCIRC_ROOT = Path(os.environ[_env_var])
        break

if _ISRNCIRC_ROOT is None:
    # 从本文件位置推断: src/torusfold/scheme2/ → 项目根 → deploy/IGEM集成方案/...
    _this_dir = Path(__file__).resolve().parent
    _candidate = _this_dir.parents[4] / "deploy" / "IGEM集成方案" / "tools" / "IsRNAcirc" / "IsRNAcirc_standalone"
    if _candidate.exists():
        _ISRNCIRC_ROOT = _candidate
    else:
        # 尝试另一个常见位置
        _candidate2 = Path("C:/Users/颜子壹/deploy/IGEM集成方案/tools/IsRNAcirc/IsRNAcirc_standalone")
        if _candidate2.exists():
            _ISRNCIRC_ROOT = _candidate2
        else:
            _ISRNCIRC_ROOT = _this_dir.parents[2] / "IsRNAcirc_standalone"

_VFOLD3D_DIR = _ISRNCIRC_ROOT / "Data" / "vfold3D"
_VFOLDLA_DIR = _ISRNCIRC_ROOT / "Data" / "vfoldLA"
_BIN_DIR = _ISRNCIRC_ROOT / "bin"
_DATA_DIR = _ISRNCIRC_ROOT / "Data"  # IsRNAcirc 的 INPUT 参数是 Data/ 目录
_EXCLUDE_FILE = _ISRNCIRC_ROOT / "Data" / "data" / "PDB201505.helix2"  # 排除列表在 Data/data/ 下
# 如果排除文件不存在,创建空文件(IsRNAcirc 也这么做)
if not _EXCLUDE_FILE.exists():
    try:
        _EXCLUDE_FILE.parent.mkdir(parents=True, exist_ok=True)
        _EXCLUDE_FILE.touch()
    except Exception:
        pass

# IsRNAcirc 可执行文件路径
# 优先 standalone bin/ (2MB 完整版: read_structure/聚类/输出全通),
# 不用 C:/tmp/isrna_bin/ 的 879KB 精简版 (read_structure 崩溃 SIGSEGV).
# 依赖 MSYS2 DLL (libgcc_s_seh-1.dll 等) 需与 exe 同目录, 已部署.
_ISRNCIRC_EXE = _BIN_DIR / "IsRNAcirc.exe"
if not _ISRNCIRC_EXE.exists():
    _ISRNCIRC_EXE = Path("C:/tmp/isrna_bin/IsRNAcirc.exe")

# LAMMPS 可执行文件路径
_LMP_EXE = _DATA_DIR / "lmp_mpi.exe"
if not _LMP_EXE.exists():
    _LMP_EXE = _DATA_DIR / "lmp_mpi"
if not _LMP_EXE.exists():
    _LMP_EXE = Path("C:/tmp/isrna_data/lmp_mpi.exe")
if not _LMP_EXE.exists():
    _LMP_EXE = Path("C:/tmp/isrna_bin/lmp_mpi.exe")


def _find_exe(name: str) -> str:
    """查找可执行文件,支持 .exe 和无扩展名."""
    for ext in ["", ".exe", ".o"]:
        p = _BIN_DIR / f"{name}{ext}"
        if p.exists():
            return str(p)
    # 也检查 Data 目录(Vfold3D 组件)
    for d in [_VFOLD3D_DIR, _VFOLDLA_DIR]:
        for ext in ["", ".exe", ".o"]:
            p = d / f"{name}{ext}"
            if p.exists():
                return str(p)
    raise FileNotFoundError(f"找不到 {name},请先编译 IsRNAcirc")


def vfold3d_init(
    sequence: str,
    secondary_structure: str,
    output_dir: str,
    name: str = "temp",
    max_models: int = 3,
    n_candidates: int = 1,
) -> str:
    """调用 Vfold3D/VfoldLA 生成初始 3D 构象.

    先尝试 Vfold3D,如果失败(如有 open loop),自动 fallback 到 VfoldLA。

    Args:
        sequence: RNA 序列 (ACGU)
        secondary_structure: 二级结构 (dot-bracket)
        output_dir: 输出目录
        name: 项目名
        max_models: 最大模型数
        n_candidates: 返回候选数量

    Returns:
        n_candidates=1 时返回 PDB 路径 (str),
        n_candidates>1 时返回 PDB 路径列表 (List[str])
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    # 写 2D 文件
    f2d = output_dir / f"{name}_vfold.2d"
    with open(f2d, "w") as f:
        f.write(f"{sequence}\n{secondary_structure}\n")

    # ── 尝试 Vfold3D ──
    vfold3d_error = None
    try:
        # 调用 vfold3D_motif
        fmtf = output_dir / f"{name}_vfold3D.mtf"
        ferr = output_dir / f"{name}_vfold3D.err"
        motif_exe = _find_exe("vfold3D_motif")
        cmd = [motif_exe, str(f2d), str(fmtf), str(ferr), "0"]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            raise RuntimeError(f"vfold3D_motif 失败: {result.stderr}")

        # 调用 vfold3D_pdb
        fpdb = output_dir / f"{name}_vfold3D-INI.pdb"
        pdb_exe = _find_exe("vfold3D_pdb")
        cmd = [pdb_exe, str(_DATA_DIR), str(f2d), str(fmtf), str(fpdb), str(ferr), "0",
               str(_EXCLUDE_FILE)]
        result = subprocess.run(cmd, capture_output=True, text=True)
        if result.returncode != 0:
            raise RuntimeError(f"vfold3D_pdb 失败")

        if fpdb.exists() and fpdb.stat().st_size > 0:
            return str(fpdb)
        else:
            raise RuntimeError("vfold3D_pdb 未生成 PDB")

    except Exception as e:
        vfold3d_error = str(e)
        print(f"  Vfold3D 不可用: {vfold3d_error},尝试 VfoldLA...")

    # ── Fallback: VfoldLA ──
    try:
        return vfoldla_init(sequence, secondary_structure, output_dir, name,
                            max_models, n_candidates=n_candidates)
    except Exception as e2:
        raise RuntimeError(f"Vfold3D 和 VfoldLA 都失败: Vfold3D={vfold3d_error}, VfoldLA={e2}")


def vfoldla_init(
    sequence: str,
    secondary_structure: str,
    output_dir: str,
    name: str = "temp",
    max_models: int = 3,
    n_candidates: int = 1,
) -> str:
    """调用 VfoldLA 生成大组装初始 3D 构象(适用于长序列).

    Args:
        sequence: RNA 序列
        secondary_structure: 二级结构
        output_dir: 输出目录
        name: 项目名
        max_models: LA 最大模型数
        n_candidates: 返回候选数量 (多候选模式, 覆盖 cluster 输出)

    Returns:
        n_candidates=1 时返回单个 PDB 路径 (str),
        n_candidates>1 时返回 PDB 路径列表 (List[str])
    """
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    f2d = output_dir / f"{name}_vfold.2d"
    with open(f2d, "w") as f:
        f.write(f"{sequence}\n{secondary_structure}\n")

    # vfold3D2_BPs: 拆分子 2D 结构
    f2dLA = output_dir / f"{name}_vfoldLA-2Ds.2d"
    bps_exe = _find_exe("vfold3D2_BPs")
    cmd = [bps_exe, str(f2d), str(f2dLA), "0"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"vfold3D2_BPs 失败: {result.stderr}")

    # vfold3D2_LA: 大组装
    fpdb0 = output_dir / f"{name}_vfoldLA-INI.pdb"
    la_exe = _find_exe("vfold3D2_LA")
    cmd = [la_exe, str(_DATA_DIR), str(_EXCLUDE_FILE), str(f2dLA), str(fpdb0), "0"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"vfold3D2_LA 失败: {result.stderr}")

    # vfold3D2_cluster: 聚类去重
    fpdb1 = output_dir / f"{name}_vfoldLA-CLU.pdb"
    cluster_exe = _find_exe("vfold3D2_cluster")
    cmd = [cluster_exe, str(fpdb0), str(fpdb1), "7.5", "0"]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(f"vfold3D2_cluster 失败: {result.stderr}")

    if n_candidates <= 1:
        return str(fpdb1)

    # 多候选: 从 cluster PDB 提取 MODEL 块,每块存为独立文件
    candidates = _extract_pdb_models(str(fpdb1), output_dir, name, n_candidates)
    if not candidates:
        candidates = [str(fpdb1)]
    return candidates


def _extract_pdb_models(
    pdb_path: str, output_dir: Path, name: str, n_candidates: int
) -> List[str]:
    """从多模型 PDB 提取前 n_candidates 个 MODEL 为独立文件."""
    models: List[List[str]] = []
    current: List[str] = []

    with open(pdb_path) as f:
        for line in f:
            if line.startswith("MODEL"):
                current = [line]
            elif line.startswith("ENDMDL"):
                current.append(line)
                if current:
                    models.append(current)
                current = []
            elif current:
                current.append(line)

    # 如果没有 MODEL 标记,整个文件算一个模型
    if not models:
        with open(pdb_path) as f:
            content = f.read()
        models = [[content]]

    out_paths: List[str] = []
    for i, model_lines in enumerate(models[:n_candidates]):
        out_pdb = output_dir / f"{name}_candidate_{i}.pdb"
        with open(out_pdb, "w") as f:
            f.writelines(model_lines)
            if not model_lines[-1].endswith("\n"):
                f.write("\n")
        out_paths.append(str(out_pdb))

    return out_paths


# ── CG MD 精修:调用 IsRNAcirc.exe ──

def isrnacirc_cg_refine(
    input_pdb: str,
    output_dir: str,
    sequence: str,
    secondary_structure: str,
    name: str = "refine",
    nstep: int = 1000000,
    nstep_close: int = 500000,
    nstru: int = 500,
    timeout: int = 0,
) -> Tuple[str, float]:
    """调用 IsRNAcirc.exe 做 CG MD 精修.

    利用 IsRNAcirc.exe 的 Type=1 模式:
    - 读取用户提供的初始 PDB
    - 用 IsRNA2 力场做 close_ends + REMD
    - 输出精修后的全原子 PDB

    Args:
        input_pdb: 输入 PDB 文件路径
        output_dir: 输出目录
        sequence: RNA 序列
        secondary_structure: 二级结构
        name: 项目名
        nstep: MD 步数
        nstep_close: 闭合末端步数
        nstru: 快照数
        timeout: 超时时间 (秒)

    Returns:
        (输出 PDB 路径, 最终能量)
    """
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    # isRNAcirc 只认大写 A/C/G/U; DNA/T/小写 → RNA 大写
    sequence = _normalize_rna_sequence(sequence)
    secondary_structure = secondary_structure.upper()

    # IsRNAcirc.exe C++ 内部按 outDIR/{Name}/{Name}_config.txt 构造路径
    # 所以 outDIR 的上级必须包含 {Name}/ 子目录
    # 如果 out_path 已经是 name 目录 (如 remd_r0/),则 parent 是 outDIR
    # 如果 out_path 不包含 name,则在 out_path 下创建 name 子目录
    if out_path.name == name:
        work_dir = out_path
        is_outdir = out_path.parent
    else:
        work_dir = out_path / name
        work_dir.mkdir(parents=True, exist_ok=True)
        is_outdir = out_path

    # 1. 写 .2d 文件
    f2d = work_dir / f"{name}.2d"
    with open(f2d, "w", newline="\n") as f:
        f.write(f"{sequence}\n{secondary_structure}\n")

    # 2. 写 config.txt
    conf = work_dir / f"{name}_config.txt"
    with open(conf, "w", newline="\n") as f:
        f.write(f"Nstep {nstep}\n")
        f.write(f"Nstep_close {nstep_close}\n")
        f.write(f"Nstru {nstru}\n")
        f.write(f"PS 0.5\n")
        f.write(f"PE 0.1\n")
        f.write(f"RMSD_Cut -1\n")
        f.write(f"Nout 3\n")

    # 3. 写 init PDB
    init_pdb = work_dir / f"{name}_init.pdb"
    _write_single_model_pdb(input_pdb, str(init_pdb))

    # 4. 调用 IsRNAcirc.exe
    exe = str(_ISRNCIRC_EXE)
    cmd = [
        exe,
        str(_ISRNCIRC_ROOT / "Data"),  # INPUT = Data/ 目录
        str(f2d),               # in2D
        str(is_outdir),         # outDIR (C++ 在此下建 {Name}/)
        name,                   # Name
        str(conf),              # inCONF
        "1",                    # Type=1 (用户提供初始 PDB)
        str(init_pdb),          # inPDB
    ]

    result = subprocess.run(
        cmd, capture_output=True, text=True, cwd=str(work_dir)
    )

    if result.returncode != 0:
        stderr_msg = result.stderr[:500] if result.stderr else ""
        stdout_msg = result.stdout[:500] if result.stdout else ""
        raise RuntimeError(
            f"IsRNAcirc.exe 返回 {result.returncode}: {stderr_msg or stdout_msg}"
        )

    # 5. 找到输出 PDB
    # IsRNAcirc 输出: {work_dir}/{Name}_IsRNAcirc.pdb
    output_pdb = work_dir / f"{name}_IsRNAcirc.pdb"
    if not output_pdb.exists():
        # 列出所有 pdb 文件
        pdb_files = list(work_dir.rglob("*.pdb"))
        if pdb_files:
            # 选择最大的 PDB 文件(通常是全原子输出)
            output_pdb = max(pdb_files, key=lambda p: p.stat().st_size)
        else:
            # 也检查上层目录 (旧版本兼容)
            alt_pdb = out_path / f"{name}_IsRNAcirc.pdb"
            if alt_pdb.exists():
                output_pdb = alt_pdb
            else:
                raise FileNotFoundError(
                    f"IsRNAcirc.exe 未生成输出 PDB。stdout: {result.stdout[:200]}"
                )

    # 6. 解析能量
    energy = _parse_isrnairc_energy(result.stdout)

    return str(output_pdb), energy


def _write_single_model_pdb(input_pdb: str, output_pdb: str):
    """将多模型 PDB 转为单模型 PDB.

    IsRNAcirc Type=1 需要单模型 PDB 作为输入。
    """
    with open(input_pdb) as f:
        lines = f.readlines()

    with open(output_pdb, "w") as out:
        in_model = False
        for line in lines:
            if line.startswith("MODEL"):
                if in_model:
                    break  # 只取第一个 MODEL
                in_model = True
                out.write("MODEL        1\n")
            elif line.startswith("ENDMDL"):
                out.write("ENDMDL\n")
                break
            elif line.startswith("ATOM") or line.startswith("HETATM"):
                # 规范化 resname (T/小写 → RNA 大写), 与 .2d 序列一致
                # resname 在 PDB col 18-20 (索引 17-20)
                resname = _normalize_rna_sequence(line[17:20].strip())
                out.write(line[:17] + f"{resname:>3s}" + line[20:])
            elif line.startswith("TER"):
                out.write(line)
        out.write("END\n")


def _parse_isrnairc_energy(stdout: str) -> float:
    """从 IsRNAcirc 输出解析最终能量."""
    energy = 0.0
    for line in stdout.split("\n"):
        if "TotEng" in line:
            parts = line.split()
            for i, p in enumerate(parts):
                if p == "TotEng" and i + 1 < len(parts):
                    try:
                        energy = float(parts[i + 1])
                    except ValueError:
                        pass
    return energy


# ── IsRNAcirc.exe 完整管线 (Type=0) ──

def isrnacirc_segmented_pipeline(
    sequence: str,
    secondary_structure: str,
    output_dir: str,
    name: str = "pipeline",
    nstep: int = 100000,
    nstep_close: int = 10000,
    nstru: int = 10,
    max_seg_len: int = 200,
    overlap: int = 20,
    timeout: int = 0,
) -> Tuple[str, float]:
    """调用 IsRNAcirc.exe Type=2 做分层管线 (分段 Vfold3D + Kabsch + close_ends + REMD).

    这是新增的分层模式,用于处理长序列 circRNA:
    - 自动分段 (max_seg_len, overlap)
    - 每段独立 Vfold3D
    - Kabsch 对齐拼装
    - IsRNA2 力场 close_ends + REMD
    - 输出精修后的全原子 PDB

    Args:
        sequence: RNA 序列
        secondary_structure: 二级结构 (dot-bracket)
        output_dir: 输出目录
        name: 项目名
        nstep: MD 步数
        nstep_close: 闭合末端步数
        nstru: 快照数
        max_seg_len: 分段最大长度 (default: 200)
        overlap: 重叠长度 (default: 20)
        timeout: 超时时间 (秒)

    Returns:
        (输出 PDB 路径, 最终能量)
    """
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    # IsRNAcirc.exe 期望 {outDIR}/{Name}/ 子目录结构
    work_dir = out_path / name
    work_dir.mkdir(parents=True, exist_ok=True)

    # 写 .2d 文件
    f2d = work_dir / f"{name}.2d"
    with open(f2d, "w", newline="\n") as f:
        f.write(f"{sequence}\n{secondary_structure}\n")

    # 写 config.txt (含分段参数, 必须在 {Name}/ 子目录下)
    conf = work_dir / f"{name}_config.txt"
    with open(conf, "w", newline="\n") as f:
        f.write(f"Nstep {nstep}\n")
        f.write(f"Nstep_close {nstep_close}\n")
        f.write(f"Nstru {nstru}\n")
        f.write(f"PS 0.5\n")
        f.write(f"PE 0.1\n")
        f.write(f"RMSD_Cut -1\n")
        f.write(f"Nout 3\n")
        f.write(f"MaxSegLen {max_seg_len}\n")
        f.write(f"Overlap {overlap}\n")

    # 调用 IsRNAcirc.exe Type=2
    exe = str(_ISRNCIRC_EXE)
    cmd = [
        exe,
        str(_ISRNCIRC_ROOT / "Data"),  # INPUT
        str(f2d),                       # in2D
        str(work_dir),                  # outDIR = {out}/{Name}/
        name,                           # Name
        str(conf),                      # inCONF
        "2",                            # Type=2 (分层模式)
    ]

    result = subprocess.run(
        cmd, capture_output=True, text=True, cwd=str(work_dir)
    )

    if result.returncode != 0:
        print(f"WARNING: IsRNAcirc.exe Type=2 返回 {result.returncode}")
        if result.stdout:
            print(f"  stdout: {result.stdout[:500]}")

    # 找输出 PDB
    output_pdb = work_dir / f"{name}_IsRNAcirc.pdb"
    if not output_pdb.exists():
        for pat in [f"*{name}*IsRNAcirc.pdb", "*_IsRNAcirc.pdb", "*.pdb"]:
            found = list(work_dir.rglob(pat))
            if found:
                output_pdb = max(found, key=lambda p: p.stat().st_size)
                break
        # 兼容旧路径
        if not output_pdb.exists():
            alt = out_path / f"{name}_IsRNAcirc.pdb"
            if alt.exists():
                output_pdb = alt

    energy = _parse_isrnairc_energy(result.stdout)
    return str(output_pdb), energy


def isrnacirc_full_pipeline(
    sequence: str,
    secondary_structure: str,
    output_dir: str,
    name: str = "pipeline",
    nstep: int = 100000,
    nstep_close: int = 10000,
    nstru: int = 10,
    timeout: int = 0,
) -> Tuple[str, float]:
    """调用 IsRNAcirc.exe Type=0 做完整管线 (Vfold3D + LAMMPS).

    这是 IsRNAcirc 的标准用法:
    - 自动用 Vfold3D/VfoldLA 生成初始结构
    - 用 IsRNA2 力场做 LAMMPS CG MD (close_ends + REMD)
    - 输出精修后的全原子 PDB

    Args:
        sequence: RNA 序列
        secondary_structure: 二级结构 (dot-bracket)
        output_dir: 输出目录
        name: 项目名
        nstep: MD 步数
        nstep_close: 闭合末端步数
        nstru: 快照数
        timeout: 超时时间 (秒)

    Returns:
        (输出 PDB 路径, 最终能量)
    """
    out_path = Path(output_dir)
    out_path.mkdir(parents=True, exist_ok=True)

    # IsRNAcirc.exe 期望 {outDIR}/{Name}/ 子目录结构
    work_dir = out_path / name
    work_dir.mkdir(parents=True, exist_ok=True)

    # 1. 写 .2d 文件
    f2d = work_dir / f"{name}.2d"
    with open(f2d, "w", newline="\n") as f:
        f.write(f"{sequence}\n{secondary_structure}\n")

    # 2. 写 config.txt (必须在 {Name}/ 子目录下)
    conf = work_dir / f"{name}_config.txt"
    with open(conf, "w", newline="\n") as f:
        f.write(f"Nstep {nstep}\n")
        f.write(f"Nstep_close {nstep_close}\n")
        f.write(f"Nstru {nstru}\n")
        f.write(f"PS 0.5\n")
        f.write(f"PE 0.1\n")
        f.write(f"RMSD_Cut -1\n")
        f.write(f"Nout 3\n")

    # 3. 调用 IsRNAcirc.exe Type=0
    exe = str(_ISRNCIRC_EXE)
    cmd = [
        exe,
        str(_ISRNCIRC_ROOT / "Data"),  # INPUT
        str(f2d),                       # in2D
        str(work_dir),                  # outDIR = {out}/{Name}/
        name,                           # Name
        str(conf),                      # inCONF
        "0",                            # Type=0 (自动生成)
    ]

    result = subprocess.run(
        cmd, capture_output=True, text=True, cwd=str(work_dir)
    )

    if result.returncode != 0:
        print(f"WARNING: IsRNAcirc.exe Type=0 返回 {result.returncode}")

    # 4. 找输出 PDB
    output_pdb = work_dir / f"{name}_IsRNAcirc.pdb"
    if not output_pdb.exists():
        # 搜索所有 PDB
        for pat in [f"*{name}*_IsRNAcirc.pdb", "*_IsRNAcirc.pdb", "*.pdb"]:
            found = list(work_dir.rglob(pat))
            if found:
                output_pdb = max(found, key=lambda p: p.stat().st_size)
                break
        # 兼容旧路径
        if not output_pdb.exists():
            alt = out_path / f"{name}_IsRNAcirc.pdb"
            if alt.exists():
                output_pdb = alt

    energy = _parse_isrnairc_energy(result.stdout)
    return str(output_pdb), energy


def lammps_refine(
    input_pdb: str,
    output_pdb: str,
    sequence: str,
    secondary_structure: str,
    temperature: float = 300.0,
    n_steps: int = 10000,
    dt: float = 0.002,
    pair_weights: Optional[dict] = None,
) -> Tuple[str, float]:
    """调用 LAMMPS 做 CG 精修 (向后兼容接口).

    注意: 推荐使用 isrnacirc_cg_refine() 替代此函数。
    此函数保留用于 isrnaclong.py 的 Level 2 迭代弛豫循环。

    Args:
        input_pdb: 输入 PDB
        output_pdb: 输出 PDB
        sequence: RNA 序列
        secondary_structure: 二级结构
        temperature: 温度 (K)
        n_steps: MD 步数
        dt: 时间步长 (ps)
        pair_weights: 配对权重 {(i,j): weight}

    Returns:
        (输出 PDB 路径, 最终能量)
    """
    # 使用新的 isrnacirc_cg_refine
    output_dir = str(Path(output_pdb).parent)
    name = Path(output_pdb).stem

    try:
        result_pdb, energy = isrnacirc_cg_refine(
            input_pdb, output_dir, sequence, secondary_structure,
            name=name, nstep=n_steps,
        )
        return result_pdb, energy
    except Exception as e:
        print(f"WARNING: isrnacirc_cg_refine 失败: {e}, 返回输入坐标")
        return input_pdb, 0.0


def _normalize_rna_sequence(seq: str) -> str:
    """规范化 RNA 序列: 转大写, T→U (DNA→RNA).

    isRNAcirc/CG_to_allatom 只认大写 A/C/G/U, 小写或 T 会导致
    碱基模板加载失败 (base atoms missed).
    """
    return seq.upper().replace("T", "U")


def cg_to_allatom(
    input_pdb: str,
    output_pdb: str,
    sequence: str,
) -> str:
    """CG 坐标 → 全原子重建.

    CG_to_allatom standalone 只输出骨架原子, 再用 _add_base_atoms 补碱基.
    """
    sequence = _normalize_rna_sequence(sequence)
    cg_exe = _find_exe("CG_to_allatom")
    coeff_dir = str(_DATA_DIR / "data" / "IsRNA2")
    cmd = [cg_exe, input_pdb, output_pdb, coeff_dir]
    result = subprocess.run(cmd, capture_output=True, text=True)
    if result.returncode != 0:
        raise RuntimeError(
            f"CG_to_allatom 失败 (rc={result.returncode}): "
            f"{result.stderr[-500:] if result.stderr else result.stdout[-500:]}"
        )
    # 补碱基原子
    _add_base_atoms(output_pdb, sequence, output_pdb)
    return output_pdb


def _load_base_template(resname: str):
    """从 IsRNA2 数据加载碱基模板, 返回 {atom_name: (x,y,z)} 和 C4'/C1' 坐标."""
    template_dir = _DATA_DIR / "data" / "IsRNA2"
    fname = f"AA_base{resname}.dat"
    fpath = template_dir / fname
    if not fpath.exists():
        return None, None, None
    atoms = {}
    c4p = c1p = None
    with open(fpath) as f:
        for line in f:
            line = line.strip()
            if not line or line.startswith("#") or line[0].isdigit():
                continue
            parts = line.split()
            if len(parts) >= 4:
                name = parts[0]
                x, y, z = float(parts[1]), float(parts[2]), float(parts[3])
                atoms[name] = (x, y, z)
                if name == "C4'":
                    c4p = np.array([x, y, z])
                elif name == "C1'":
                    c1p = np.array([x, y, z])
    return atoms, c4p, c1p


def _kabsch_align(P, Q):
    """Kabsch: 找旋转+平移使 P→Q. 返回旋转矩阵 R 和平移向量 t."""
    centroid_p = P.mean(axis=0)
    centroid_q = Q.mean(axis=0)
    P_c = P - centroid_p
    Q_c = Q - centroid_q
    H = P_c.T @ Q_c
    U, S, Vt = np.linalg.svd(H)
    R = Vt.T @ U.T
    if np.linalg.det(R) < 0:
        Vt[-1, :] *= -1
        R = Vt.T @ U.T
    t = centroid_q - R @ centroid_p
    return R, t


def _add_base_atoms(pdb_path: str, sequence: str, output_pdb: str):
    """给骨架-only PDB 补碱基原子.

    CG_to_allatom 只输出 P/OP1/OP2/O5'/C5'/C4'/O4'/C3'/O3'/C2'/O2'/C1'.
    本函数用 IsRNA2 碱基模板 + Kabsch 对齐补全 N1/N3/C2/C4/C5/C6/N7/C8/N9 等.
    """
    # 读骨架 PDB
    backbone_atoms = []  # [(atom_name, res_idx, x, y, z, element)]
    residues = {}  # {res_idx: resname}
    with open(pdb_path) as f:
        for line in f:
            if not line.startswith("ATOM"):
                continue
            atom_name = line[12:16].strip()
            resname = line[17:20].strip()
            # 规范化 resname (DNA/小写 → RNA 大写), 否则碱基模板加载失败
            resname = _normalize_rna_sequence(resname)
            try:
                res_idx = int(line[22:26].strip())
            except ValueError:
                continue
            x = float(line[30:38])
            y = float(line[38:46])
            z = float(line[46:54])
            backbone_atoms.append((atom_name, res_idx, x, y, z))
            residues[res_idx] = resname

    # 按残基分组, 找 C4' 和 C1'
    res_groups = {}
    for atom_name, res_idx, x, y, z in backbone_atoms:
        if res_idx not in res_groups:
            res_groups[res_idx] = {}
        res_groups[res_idx][atom_name] = np.array([x, y, z])

    # 生成完整全原子 PDB
    lines = ["HEADER    isRNAcircLong allatom with bases"]
    atom_idx = 0

    for res_idx in sorted(res_groups.keys()):
        atoms = res_groups[res_idx]
        resname = residues.get(res_idx, "A")

        # 写骨架原子
        for atom_name in ["P", "OP1", "OP2", "O5'", "C5'", "C4'", "O4'",
                          "C3'", "O3'", "C2'", "O2'", "C1'"]:
            if atom_name in atoms:
                atom_idx += 1
                x, y, z = atoms[atom_name]
                elem = atom_name[0]
                lines.append(
                    f"ATOM  {atom_idx:5d} {atom_name:>4s} {resname:>3s} A{res_idx:4d}"
                    f"    {x:8.3f}{y:8.3f}{z:8.3f}  1.00  0.00           {elem:>2s}"
                )

        # 补碱基原子
        if resname in ("A", "U", "C", "G") and "C4'" in atoms and "C1'" in atoms:
            template, tpl_c4p, tpl_c1p = _load_base_template(resname)
            if template is None:
                continue
            actual_c4p = atoms["C4'"]
            actual_c1p = atoms["C1'"]

            # Kabsch 对齐: 模板 (C4', C1') → 实际 (C4', C1')
            P = np.array([tpl_c4p, tpl_c1p])
            Q = np.array([actual_c4p, actual_c1p])
            R, t = _kabsch_align(P, Q)

            for atom_name, (tx, ty, tz) in template.items():
                if atom_name in ("C4'", "C1'"):
                    continue  # 骨架已有
                # 对齐到实际坐标
                new_pos = R @ np.array([tx, ty, tz]) + t
                atom_idx += 1
                elem = atom_name[0]
                lines.append(
                    f"ATOM  {atom_idx:5d} {atom_name:>4s} {resname:>3s} A{res_idx:4d}"
                    f"    {new_pos[0]:8.3f}{new_pos[1]:8.3f}{new_pos[2]:8.3f}"
                    f"  1.00  0.00           {elem:>2s}"
                )

    lines.append("END")
    with open(output_pdb, "w") as f:
        f.write("\n".join(lines))


def _read_pdb_coords(pdb_path: str) -> np.ndarray:
    """从 PDB 读取 P 坐标."""
    coords = []
    with open(pdb_path) as f:
        for line in f:
            if line.startswith("ATOM") and " P " in line:
                x = float(line[30:38])
                y = float(line[38:46])
                z = float(line[46:54])
                coords.append([x, y, z])
    return np.array(coords)


def _write_pdb(structure, output_path: str):
    """写 PDB 文件."""
    lines = ["HEADER    CG to allatom structure"]
    idx = 0
    for res_idx in range(len(structure.residue_atom_spans)):
        start, end = structure.residue_atom_spans[res_idx]
        for atom_i in range(start, end):
            idx += 1
            aname = structure.atoms[atom_i].atom_name
            x, y, z = structure.xyz[atom_i]
            res_name = structure.sequence[res_idx]
            lines.append(
                f"ATOM  {idx:5d} {aname:>4s} {res_name:>3s} A{res_idx%9999+1:4d}"
                f"    {x:8.3f}{y:8.3f}{z:8.3f}  1.00  0.00           {aname[0]:>2s}"
            )
    lines.append("END")
    with open(output_path, "w") as f:
        f.write("\n".join(lines))

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