Python rdkit.Chem.Mol() Examples

The following are 30 code examples of rdkit.Chem.Mol(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rdkit.Chem , or try the search function .
Example #1
Source File: molViewWidget.py    From rdeditor with GNU Lesser General Public License v3.0 7 votes vote down vote up
def sanitizeMol(self, kekulize=False, drawkekulize=False):
        self.computeNewCoords()
        self._drawmol = Chem.Mol(self._mol.ToBinary()) #Is this necessary?
        try:
            Chem.SanitizeMol(self._drawmol)
            self.sanitizeSignal.emit("Sanitizable")
        except:
            self.sanitizeSignal.emit("UNSANITIZABLE")
            self.logger.warning("Unsanitizable")
            try:
                self._drawmol.UpdatePropertyCache(strict=False)
            except:
                self.sanitizeSignal.emit("UpdatePropertyCache FAIL")
                self.logger.error("Update Property Cache failed")
        #Kekulize
        if kekulize:
            try:
                Chem.Kekulize(self._drawmol)
            except:
                self.logger.warning("Unkekulizable")
        try:
            self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=drawkekulize)
        except ValueError:  # <- can happen on a kekulization failure
            self._drawmol = rdMolDraw2D.PrepareMolForDrawing(self._drawmol, kekulize=False) 
Example #2
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def calcdesc(self, descnames=None):
        """Calculate descriptor values.

        Optional parameter:
           descnames -- a list of names of descriptors

        If descnames is not specified, all available descriptors are
        calculated. See the descs variable for a list of available
        descriptors.
        """
        descnames = descnames or descs
        ans = {}
        for descname in descnames:
            try:
                desc = _descDict[descname]
            except KeyError:
                raise ValueError("%s is not a recognised RDKit descriptor type" % descname)
            ans[descname] = desc(self.Mol)
        return ans 
Example #3
Source File: xyz_to_2d.py    From ARC with MIT License 6 votes vote down vote up
def to_rdkit_mol(self):
        """
        Convert the graph to an RDKit molecule with atom map numbers set
        by the indices of the atoms.
        """
        assert all(atom.idx is not None for atom in self)

        rd_mol = Chem.rdchem.EditableMol(Chem.rdchem.Mol())
        for atom in self:
            rd_atom = Chem.rdchem.Atom(atom.symbol)
            rd_atom.SetAtomMapNum(atom.idx)
            rd_mol.AddAtom(rd_atom)

        for atom1 in self:
            for atom2 in atom1.connections.keys():
                idx1 = self.atoms.index(atom1)  # This is the index in the atoms list
                idx2 = self.atoms.index(atom2)
                if idx1 < idx2:
                    rd_mol.AddBond(idx1, idx2, Chem.rdchem.BondType.SINGLE)

        rd_mol = rd_mol.GetMol()
        return rd_mol 
Example #4
Source File: __init__.py    From 3DGCN with MIT License 6 votes vote down vote up
def MolToQPixmap(mol, size=(300, 300), kekulize=True, wedgeBonds=True, fitImage=False, options=None,
                 **kwargs):
    """ Generates a drawing of a molecule on a Qt QPixmap
      """
    if not mol:
        raise ValueError('Null molecule provided')
    from rdkit.Chem.Draw.qtCanvas import Canvas
    canvas = Canvas(size)
    if options is None:
        options = DrawingOptions()
    options.bgColor = None
    if fitImage:
        options.dotsPerAngstrom = int(min(size) / 10)
    options.wedgeDashedBonds = wedgeBonds
    if kekulize:
        from rdkit import Chem
        mol = Chem.Mol(mol.ToBinary())
        Chem.Kekulize(mol)
    if not mol.GetNumConformers():
        from rdkit.Chem import AllChem
        AllChem.Compute2DCoords(mol)
    drawer = MolDrawing(canvas=canvas, drawingOptions=options)
    drawer.AddMol(mol, **kwargs)
    canvas.flush()
    return canvas.pixmap 
Example #5
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make3D(self, forcefield="mmff94", steps=50):
        """Generate 3D coordinates.

        Optional parameters:
           forcefield -- default is "uff". See the forcefields variable
                         for a list of available forcefields.
           steps -- default is 50

        Once coordinates are generated, a quick
        local optimization is carried out with 50 steps and the
        UFF forcefield. Call localopt() if you want
        to improve the coordinates further.
        """
        forcefield = forcefield.lower()
        success = AllChem.EmbedMolecule(self.Mol,
                                        useExpTorsionAnglePrefs=True,
                                        useBasicKnowledge=True,
                                        enforceChirality=True,
                                        )
        if success == -1:
            raise Exception("Embedding failed!")

        self.localopt(forcefield, steps)
        self._clear_cache() 
Example #6
Source File: goal_directed_generation.py    From guacamol_baselines with MIT License 6 votes vote down vote up
def add_atom(rdkit_mol, stats: Stats):
    old_mol = Chem.Mol(rdkit_mol)
    if np.random.random() < 0.63:  # probability of adding ring atom
        rxn_smarts = np.random.choice(stats.rxn_smarts_ring_list, p=stats.p_ring)
        if not rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts('[r3,r4,r5]')) \
                or AllChem.CalcNumAliphaticRings(rdkit_mol) == 0:
            rxn_smarts = np.random.choice(stats.rxn_smarts_make_ring, p=stats.p_ring)
            if np.random.random() < 0.036:  # probability of starting a fused ring
                rxn_smarts = rxn_smarts.replace("!", "")
    else:
        if rdkit_mol.HasSubstructMatch(Chem.MolFromSmarts('[*]1=[*]-[*]=[*]-1')):
            rxn_smarts = '[r4:1][r4:2]>>[*:1]C[*:2]'
        else:
            rxn_smarts = np.random.choice(stats.rxn_smarts_list, p=stats.p)

    rdkit_mol = run_rxn(rxn_smarts, rdkit_mol)
    if valences_not_too_large(rdkit_mol):
        return rdkit_mol
    else:
        return old_mol 
Example #7
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def write(self, molecule):
        """Write a molecule to the output file.

        Required parameters:
           molecule
        """
        if not self.filename:
            raise IOError("Outputfile instance is closed.")
        if self.format in ('inchi', 'inchikey', 'mol2'):
            self._writer.write(molecule.write(self.format) + '\n')
        if self.format == 'pdbqt':
            self._writer.write('MODEL %i\n' % (self.total + 1) +
                               molecule.write(self.format) + '\nENDMDL\n')
        else:
            self._writer.write(molecule.Mol)
        self.total += 1 
Example #8
Source File: conformers.py    From deepchem with MIT License 6 votes vote down vote up
def get_conformer_rmsd(mol):
    """
    Calculate conformer-conformer RMSD.

    Parameters
    ----------
    mol : RDKit Mol
        Molecule.
    """
    from rdkit.Chem import AllChem
    rmsd = np.zeros(
        (mol.GetNumConformers(), mol.GetNumConformers()), dtype=float)
    for i, ref_conf in enumerate(mol.GetConformers()):
      for j, fit_conf in enumerate(mol.GetConformers()):
        if i >= j:
          continue
        rmsd[i, j] = AllChem.GetBestRMS(mol, mol, ref_conf.GetId(),
                                        fit_conf.GetId())
        rmsd[j, i] = rmsd[i, j]
    return rmsd 
Example #9
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __getstate__(self):
        if self._source is None:
            state = {'Mol': self.Mol,
                     'source': None,
                     'protein': self.protein,
                     'data': dict([(k, self.Mol.GetProp(k))
                                   for k in self.Mol.GetPropNames(includePrivate=True)]),
                     'dicts': {'atom_dict': self._atom_dict,
                               'ring_dict': self._ring_dict,
                               'res_dict': self._res_dict,
                               }
                     }
        else:
            state = {'Mol': None,
                     'source': self._source,
                     'data': {},
                     'protein': self.protein,
                     'dicts': {'atom_dict': None,
                               'ring_dict': None,
                               'res_dict': None,
                               }
                     }
        return state 
Example #10
Source File: common_scoring_functions.py    From guacamol with MIT License 5 votes vote down vote up
def __init__(self, descriptor: Callable[[Chem.Mol], float], score_modifier: ScoreModifier = None) -> None:
        """
        Args:
            descriptor: molecular descriptors, such as the ones in descriptors.py
            score_modifier: score modifier
        """
        super().__init__(score_modifier=score_modifier)
        self.descriptor = descriptor 
Example #11
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def make2D(self):
        """Generate 2D coordinates for molecule"""
        AllChem.Compute2DCoords(self.Mol)
        self._clear_cache() 
Example #12
Source File: common_scoring_functions.py    From guacamol with MIT License 5 votes vote down vote up
def score_mol(self, mol: Chem.Mol) -> float:
        fp = get_fingerprint(mol, self.fp_type)
        return TanimotoSimilarity(fp, self.ref_fp) 
Example #13
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def match(self, molecule):
        """Find all matches of the SMARTS pattern to a particular molecule.

        Required parameters:
           molecule
        """
        return molecule.Mol.HasSubstructMatch(self.rdksmarts) 
Example #14
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def findall(self, molecule, unique=True):
        """Find all matches of the SMARTS pattern to a particular molecule.

        Required parameters:
           molecule
        """
        return molecule.Mol.GetSubstructMatches(self.rdksmarts, uniquify=unique) 
Example #15
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, Mol):
        self._mol = Mol 
Example #16
Source File: fixer.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def FetchStructure(pdbid, sanitize=False, removeHs=True, cache_dir=None):
    """Fetch the structure in PDB format from RCSB PDB server and read it with
    rdkit.

    Parameters
    ----------
        pdbid: str
            PDB IDs of the structre
        sanitize: bool, optional (default False)
            Toggles molecule sanitation
        removeHs: bool, optional (default False)
            Indicates wheter Hs should be removed during reading

    Returns
    -------
        mol: Chem.rdchem.Mol
            Retrieved molecule
"""
    if cache_dir is not None:
        structure_dir = os.path.join(cache_dir, pdbid)
        structure_path = os.path.join(structure_dir, '%s.pdb' % pdbid)
        if not os.path.isdir(cache_dir):
            os.makedirs(cache_dir)
        if not os.path.isdir(structure_dir):
            os.makedirs(structure_dir)
        if os.path.isfile(structure_path):
            mol = Chem.MolFromPDBFile(structure_path, sanitize=sanitize,
                                      removeHs=removeHs)
            return mol

    req = urllib.request.Request('https://files.rcsb.org/view/%s.pdb' % pdbid)
    response = urllib.request.urlopen(req)
    pdb_block = response.read().decode('utf-8')

    mol = Chem.MolFromPDBBlock(pdb_block, sanitize=sanitize, removeHs=removeHs)
    if cache_dir is not None:
        with open(structure_path, 'w') as f:
            f.write(pdb_block)

    return mol 
Example #17
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def formula(self):
        return Descriptors.MolecularFormula(self.Mol) 
Example #18
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def localopt(self, forcefield="uff", steps=500):
        """Locally optimize the coordinates.

        Optional parameters:
           forcefield -- default is "uff". See the forcefields variable
                         for a list of available forcefields.
           steps -- default is 500

        If the molecule does not have any coordinates, make3D() is
        called before the optimization.
        """
        forcefield = forcefield.lower()
        if self.Mol.GetNumConformers() == 0:
            self.make3D(forcefield)
        _forcefields[forcefield](self.Mol, maxIters=steps) 
Example #19
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def calccharges(self, model='gasteiger'):
        """Calculate partial charges for a molecule. By default the Gasteiger
        charge model is used.

        Parameters
        ----------
        model : str (default="gasteiger")
            Method for generating partial charges. Supported models:
            * gasteiger
            * mmff94
        """
        self._clear_cache()
        if model.lower() == 'gasteiger':
            ComputeGasteigerCharges(self.Mol, nIter=50)
        elif model.lower() == 'mmff94':
            fps = AllChem.MMFFGetMoleculeProperties(self.Mol)
            if fps is None:
                raise Exception('Could not charge molecule "%s"' % self.title)
            for i, atom in enumerate(self.Mol.GetAtoms()):
                atom.SetDoubleProp('_MMFF94Charge', fps.GetMMFFPartialCharge(i))
        else:
            raise ValueError('The "%s" is not supported in RDKit backend' %
                             model)
        if np.isnan(self.charges).any() or np.isinf(self.charges).any():
            warnings.warn('Some partial charges for molecule "%s" are not '
                          'finite (NaN, +/-Inf).' % self.title, UserWarning) 
Example #20
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def removeh(self, **kwargs):
        """Remove hydrogens."""
        self.Mol = Chem.RemoveHs(self.Mol, **kwargs)
        self._clear_cache() 
Example #21
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clone_coords(self, source):
        self.Mol.RemoveAllConformers()
        for conf in source.Mol.GetConformers():
            self.Mol.AddConformer(conf)
        return self 
Example #22
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clone(self):
        return Molecule(Chem.Mol(self.Mol.ToBinary())) 
Example #23
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bonds(self):
        return BondStack(self.Mol) 
Example #24
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def num_rotors(self):
        return NumRotatableBonds(self.Mol) 
Example #25
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sssr(self):
        return [list(path) for path in list(Chem.GetSymmSSSR(self.Mol))] 
Example #26
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def residues(self):
        if self._residues is None:
            res_idx = []
            # get residue information for each atom
            for atom in self.Mol.GetAtoms():
                info = atom.GetPDBResidueInfo()
                if info is None:
                    res_idx.append(0)
                else:
                    res_idx.append('%s%05.i' % (info.GetChainId()
                                                if info.GetChainId().split()
                                                else '_',
                                                info.GetResidueNumber()))
            res_idx = np.array(res_idx)
            # get unique residues
            res_idx_unique = np.unique(res_idx)
            # group atom indices by residue; residues are in alphabetical order
            if len(res_idx_unique) > 1:
                idx_sorted = np.argsort(res_idx, kind='mergesort')
                self._residues = np.split(
                    idx_sorted,   # use atom indices sorted by residue
                    # find indices where residue changes
                    np.where(np.diff(np.searchsorted(res_idx_unique,
                                     res_idx[idx_sorted])) > 0)[0] + 1)
            else:
                # if there is a single residue (or no residue information
                # at all) there is only one group of atoms
                self._residues = [tuple(range(self.Mol.GetNumAtoms()))]
        return ResidueStack(self.Mol, self._residues) 
Example #27
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def smiles(self):
        return Chem.MolToSmiles(self.Mol, isomericSmiles=True)

    # Custom ODDT properties # 
Example #28
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _exchange(self):
        if self.Mol.GetNumConformers() == 0:
            return (0, self.write("smi"))
        else:
            return (1, self.write("mol"))

    # cache frequently used properties and cache them in prefixed [_] variables 
Example #29
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _settitle(self, val):
        self.Mol.SetProp("_Name", val) 
Example #30
Source File: rdk.py    From oddt with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def Mol(self, value):
        self._Mol = value