GetSubstructMatch 仅返回第一个匹配项。使用GetSubstructMatches。根据您安装的 rdkit 版本,这里有多种方案。在最新的 rdkit 版本(2021.09.2)中,以下代码应该可以工作。
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
from copy import deepcopy
def increase_resolution(mol, substructure, size=(400, 200)):
mol = deepcopy(mol)
substructure = deepcopy(substructure)
drawer = rdMolDraw2D.MolDraw2DSVG(size[0], size[1])
# highlightAtoms expects only one tuple, not tuple of tuples. So it needs to be merged into a single tuple
matches = sum(mol.GetSubstructMatches(substructure), ())
drawer.DrawMolecule(mol, highlightAtoms=matches)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
mol = Chem.MolFromSmiles('c1cc(C(=O)O)c(OC(=O)C)cc1')
substructure = Chem.MolFromSmarts('C(=O)O')
SVG(increase_resolution(mol, substructure))
如果您收到 Value Error: Bad Conformer id 错误,请将 rdkit 包更新到最新版本或尝试以下操作:
from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D
from IPython.display import SVG
from copy import deepcopy
def increase_resolution(mol, substructure, size=(400, 200), kekulize=True):
mol = deepcopy(mol)
substructure = deepcopy(substructure)
rdDepictor.Compute2DCoords(mol)
if kekulize:
Chem.Kekulize(mol) # Localize the benzene ring bonds
drawer = rdMolDraw2D.MolDraw2DSVG(size[0], size[1])
# highlightAtoms expects only one tuple, not tuple of tuples. So it needs to be merged into a single tuple
matches = sum(mol.GetSubstructMatches(substructure), ())
drawer.DrawMolecule(mol, highlightAtoms=matches)
drawer.FinishDrawing()
svg = drawer.GetDrawingText()
return svg.replace('svg:','')
mol = Chem.MolFromSmiles('c1cc(C(=O)O)c(OC(=O)C)cc1')
substructure = Chem.MolFromSmarts('C(=O)O')
SVG(increase_resolution(mol, substructure, kekulize=True))
如果在某些情况下,例如将手性结构作为 SMILES 字符串的一部分引入其中,它可能无法工作。对于这种情况,请设置kekulize=False。