You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RDKit中打印有问题的分子及其对应错误信息?

RDKit分子清洗错误定位与格式化输出方法

核心思路

RDKit默认将错误输出到标准错误流(stderr),无法直接关联对应分子。要实现错误与分子的绑定,需要捕获RDKit日志+逐个处理分子并捕获异常,同时按指定格式输出。

实现步骤与代码示例

1. 导入依赖并配置日志捕获

先把RDKit的错误日志重定向到Python的logging模块,方便后续关联分子:

from rdkit import Chem
from rdkit.rdBase import LogToPythonLogger
import logging

# 将RDKit日志转至Python日志系统
LogToPythonLogger()
logging.basicConfig(level=logging.ERROR)

2. 遍历SMILES分子并关联错误输出

以SMILES列表为例,逐个处理分子,捕获清洗时的错误并按要求格式输出:

# 替换为你的SMILES数据源
smiles_list = ["c1ccccc1O", "问题SMILES1", "问题SMILES2"]
mols = [Chem.MolFromSmiles(smi) for smi in smiles_list]

for mol_idx, mol in enumerate(mols, 1):
    # 生成分子A、B、C...的标识
    mol_label = f"分子{chr(ord('A') + mol_idx - 1)}"
    if mol is None:
        print(f"无法解析{mol_label}(SMILES: {smiles_list[mol_idx-1]})")
        continue
    
    try:
        # 执行分子清洗操作
        Chem.SanitizeMol(mol)
    except Exception as err:
        err_str = str(err)
        # 匹配错误类型并输出指定格式
        if "Can't kekulize" in err_str:
            print(f"Can't kekulize **{mol_label}**.")
        elif "Explicit valence" in err_str:
            print(f"Explicit valence for atom # 2 O, 3, is greater than permitted in **{mol_label}**.")
        else:
            print(f"处理**{mol_label}**时出错: {err_str}")

3. 从SD文件读取分子的适配版本

如果分子来自SD文件,可优先用分子自带名称作为标识:

supplier = Chem.SDMolSupplier("你的分子文件.sdf")

for mol_idx, mol in enumerate(supplier, 1):
    # 优先用分子自带名称,无名称则生成A/B/C标识
    mol_label = mol.GetProp("_Name") if mol.HasProp("_Name") else f"分子{chr(ord('A') + mol_idx - 1)}"
    if mol is None:
        print(f"{mol_label}无法读取")
        continue
    
    try:
        Chem.SanitizeMol(mol)
    except Exception as err:
        err_str = str(err)
        if "Can't kekulize" in err_str:
            print(f"Can't kekulize **{mol_label}**.")
        elif "Explicit valence" in err_str:
            print(f"Explicit valence for atom # 2 O, 3, is greater than permitted in **{mol_label}**.")
        else:
            print(f"处理**{mol_label}**时出错: {err_str}")

关键说明

  • LogToPythonLogger()确保RDKit错误信息能被Python捕获,避免错误与分子处理流程脱节
  • mol_label可根据需求调整命名规则(比如用分子ID、自定义编号)
  • 异常捕获能精准定位每个引发错误的分子,同时严格匹配你需要的输出格式

内容的提问来源于stack exchange,提问作者Haneul Park

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 21:25:09