Skip to content

Instantly share code, notes, and snippets.

@matteoferla
Last active October 1, 2021 08:56
Show Gist options
  • Save matteoferla/43abfa0cccb509d47e35d76c5391a8b6 to your computer and use it in GitHub Desktop.
Save matteoferla/43abfa0cccb509d47e35d76c5391a8b6 to your computer and use it in GitHub Desktop.
A context manager that allows operations on a mol containing dummy atoms (R/*) that otherwise would raise an RDKit error.
from rdkit import Chem
from rdkit.Chem import AllChem
class DummyMasker:
"""
A context manager that allows operations on a mol containing dummy atoms (R/*) that
otherwise would raise an RDKit error.
It simply masks and unmasks the dummy atoms.
>>> mol = Chem.MolFromSmiles('*CCC(C)C')
>>> with DummyMasker(mol):
>>> AllChem.EmbedMolecule(mol)
"""
def __init__(self, mol: Chem.Mol):
self.mol = mol
self.is_masked = False
self.dummies = list( mol.GetAtomsMatchingQuery(Chem.rdqueries.AtomNumEqualsQueryAtom(0)) )
def mask(self):
for dummy in self.dummies:
dummy.SetAtomicNum(6)
self.is_masked = True
def unmask(self):
for dummy in self.dummies:
dummy.SetAtomicNum(0)
self.is_masked = False
def __enter__(self):
self.mask()
def __exit__(self, exc_type: Exception, exc_value: str, exc_traceback: 'bultins.traceback'):
self.unmask()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment