如何用Python自动化批量生成分子3D棒状结构图像?
批量生成分子棒状3D图像的方案
方法一:使用RDKit库
RDKit是 cheminformatics 领域常用的Python工具库,支持读取.mol文件、生成3D分子结构并渲染保存图像,完全满足批量处理需求。
步骤与代码示例
- 先安装RDKit(推荐通过conda安装:
conda install -c conda-forge rdkit) - 编写批量处理脚本:
import os from rdkit import Chem from rdkit.Chem import Draw, rdDepictor from rdkit.Chem.Draw import rdMolDraw2D def generate_stick_image(mol_file_path, output_path, size=(400, 300)): # 读取mol文件 mol = Chem.MolFromMolFile(mol_file_path) if not mol: print(f"无法读取文件: {mol_file_path}") return # 确保分子有3D坐标(若mol文件不含3D,可添加生成步骤) if not mol.GetNumConformers(): # 如需生成3D坐标,使用ETKDG算法 from rdkit.Chem import AllChem AllChem.EmbedMolecule(mol, AllChem.ETKDG()) # 创建Draw对象,设置棒状样式 drawer = rdMolDraw2D.MolDraw2DSVG(size[0], size[1]) opts = drawer.drawOptions() opts.bondLineWidth = 2.0 # 调整棒状键的宽度 opts.useAtomLabels = False # 可选:关闭原子标签 # 绘制并保存SVG图像 drawer.DrawMolecule(mol) drawer.FinishDrawing() with open(output_path, 'w') as f: f.write(drawer.GetDrawingText()) # 可选:将SVG转为PNG(需安装svglib和pillow) # from svglib.svglib import svg2rlg # from reportlab.graphics import renderPM # drawing = svg2rlg(output_path) # renderPM.drawToFile(drawing, output_path.replace('.svg', '.png'), fmt='PNG') # 批量处理文件夹中的mol文件 input_dir = "./mol_files" # 替换为你的mol文件目录 output_dir = "./mol_images" os.makedirs(output_dir, exist_ok=True) for filename in os.listdir(input_dir): if filename.endswith('.mol'): mol_path = os.path.join(input_dir, filename) output_filename = os.path.splitext(filename)[0] + '_stick.svg' output_path = os.path.join(output_dir, output_filename) generate_stick_image(mol_path, output_path) print(f"已生成图像: {output_path}")
方法二:使用PyMOL命令行模式
如果需要更精细的3D渲染效果,可以用PyMOL的Python接口实现无GUI批量处理:
- 安装PyMOL(可使用开源版本PyMOL-Open-Source)
- 编写批量渲染脚本(
batch_render.py):
import os from pymol import cmd def batch_render_mols(input_dir, output_dir): os.makedirs(output_dir, exist_ok=True) cmd.set('stick_radius', 0.15) # 设置棒状半径 cmd.set('background_color', 'white') # 设置背景色 for filename in os.listdir(input_dir): if filename.endswith('.mol'): mol_name = os.path.splitext(filename)[0] mol_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir, f"{mol_name}_stick.png") # 加载分子并设置棒状显示 cmd.load(mol_path, mol_name) cmd.show('sticks', mol_name) cmd.zoom(mol_name) # 自动调整视角 cmd.png(output_path, width=800, height=600, dpi=300) # 保存PNG cmd.delete(mol_name) # 清理内存 print(f"已生成图像: {output_path}") if __name__ == '__main__': input_dir = "./mol_files" output_dir = "./mol_images" batch_render_mols(input_dir, output_dir)
通过命令行运行脚本:pymol -cq batch_render.py(-cq表示无GUI静默运行)
内容的提问来源于stack exchange,提问作者Mirk
相关产品推荐
相关产品推荐

