Python rdkit.Chem.Kekulize() Examples

The following are 30 code examples of rdkit.Chem.Kekulize(). 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: __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 #3
Source File: mol_preprocessor.py    From chainer-chemistry with MIT License 6 votes vote down vote up
def prepare_smiles_and_mol(self, mol):
        """Prepare `smiles` and `mol` used in following preprocessing.

        This method is called before `get_input_features` is called, by parser
        class.
        This method may be overriden to support custom `smile`/`mol` extraction

        Args:
            mol (mol): mol instance

        Returns (tuple): (`smiles`, `mol`)
        """
        # Note that smiles expression is not unique.
        # we obtain canonical smiles which is unique in `mol`
        canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False,
                                            canonical=True)
        mol = Chem.MolFromSmiles(canonical_smiles)
        if self.add_Hs:
            mol = Chem.AddHs(mol)
        if self.kekulize:
            Chem.Kekulize(mol)
        return canonical_smiles, mol 
Example #4
Source File: crossover.py    From GB-GA with MIT License 6 votes vote down vote up
def crossover(parent_A,parent_B):
  parent_smiles = [Chem.MolToSmiles(parent_A),Chem.MolToSmiles(parent_B)]
  try:
	  Chem.Kekulize(parent_A,clearAromaticFlags=True)
	  Chem.Kekulize(parent_B,clearAromaticFlags=True)
  except:
  	pass
  for i in range(10):
    if random.random() <= 0.5:
      #print 'non-ring crossover'
      new_mol = crossover_non_ring(parent_A,parent_B)
      if new_mol != None:
        new_smiles = Chem.MolToSmiles(new_mol)
      if new_mol != None and new_smiles not in parent_smiles:
        return new_mol
    else:
      #print 'ring crossover'
      new_mol = crossover_ring(parent_A,parent_B)
      if new_mol != None:
        new_smiles = Chem.MolToSmiles(new_mol)
      if new_mol != None and new_smiles not in parent_smiles:
        return new_mol
  
  return None 
Example #5
Source File: test.py    From xyz2mol with MIT License 5 votes vote down vote up
def test_smiles_from_coord_huckel(smiles):

    # The answer
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)
    canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False)

    # generate forcefield coordinates
    atoms, coordinates = generate_structure_from_smiles(smiles)

    # Generate molobj from atoms, charge and coordinates
    mol = x2m.xyz2mol(atoms, coordinates, charge=charge, use_huckel=True)

    # For this test, remove chira. clean and canonical
    Chem.Kekulize(mol)
    mol = Chem.RemoveHs(mol)
    Chem.RemoveStereochemistry(mol)
    smiles = Chem.MolToSmiles(mol, isomericSmiles=False)

    # Please look away. A small hack that removes the explicit hydrogens
    mol = Chem.MolFromSmiles(smiles)
    smiles = Chem.MolToSmiles(mol)

    assert smiles == canonical_smiles

    return 
Example #6
Source File: goal_directed_generation.py    From guacamol_baselines with MIT License 5 votes vote down vote up
def run_rxn(rxn_smarts, mol):
    new_mol_list = []
    patt = rxn_smarts.split('>>')[0]
    # work on a copy so an un-kekulized version is returned
    # if the molecule is not changed
    mol_copy = Chem.Mol(mol)
    try:
        Chem.Kekulize(mol_copy)
    except ValueError:
        pass
    if mol_copy.HasSubstructMatch(Chem.MolFromSmarts(patt)):
        rxn = AllChem.ReactionFromSmarts(rxn_smarts)
        new_mols = rxn.RunReactants((mol_copy,))
        for new_mol in new_mols:
            try:
                Chem.SanitizeMol(new_mol[0])
                new_mol_list.append(new_mol[0])
            except ValueError:
                pass
        if len(new_mol_list) > 0:
            new_mol = random.choice(new_mol_list)
            return new_mol
        else:
            return mol
    else:
        return mol 
Example #7
Source File: Show_Epoch.py    From DeepFMPO with MIT License 5 votes vote down vote up
def safe_decode(x, decodings):
    try:
        m = decode(x,decodings)
        Chem.Kekulize(m)
        return m
    except:
        return None 
Example #8
Source File: Show_Epoch.py    From DeepFMPO with MIT License 5 votes vote down vote up
def safe_decode(x, decodings):
    try:
        m = decode(x,decodings)
        Chem.Kekulize(m)
        return m
    except:
        return None 
Example #9
Source File: edit_mol_direct_useScores.py    From ASKCOS with Mozilla Public License 2.0 5 votes vote down vote up
def get_product_smiles(rmol, edits, tatoms):
    smiles = edit_mol(rmol, edits, tatoms)
    if len(smiles) != 0: return smiles
    try:
        Chem.Kekulize(rmol)
    except Exception as e:
        return smiles
    return edit_mol(rmol, edits, tatoms) 
Example #10
Source File: helpers.py    From mol2vec with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _prepare_mol(mol, kekulize):
    """Prepare mol for SVG depiction (embed 2D coords)
    """
    mc = Chem.Mol(mol.ToBinary())
    if kekulize:
        try:
            Chem.Kekulize(mc)
        except:
            mc = Chem.Mol(mol.ToBinary())
    if not mc.GetNumConformers():
        rdDepictor.Compute2DCoords(mc)
    return mc 
Example #11
Source File: test.py    From xyz2mol with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    Chem.Kekulize(mol, clearAromaticFlags=True)
    charge = Chem.GetFormalCharge(mol)
    mol = Chem.AddHs(mol)
    return mol 
Example #12
Source File: test.py    From xyz2mol with MIT License 5 votes vote down vote up
def test_smiles_from_coord_vdw(smiles):

    # The answer
    mol = Chem.MolFromSmiles(smiles)
    charge = Chem.GetFormalCharge(mol)
    canonical_smiles = Chem.MolToSmiles(mol, isomericSmiles=False)

    # generate forcefield coordinates
    atoms, coordinates = generate_structure_from_smiles(smiles)

    # Generate molobj from atoms, charge and coordinates
    mol = x2m.xyz2mol(atoms, coordinates, charge=charge)

    # For this test, remove chira. clean and canonical
    Chem.Kekulize(mol)
    mol = Chem.RemoveHs(mol)
    Chem.RemoveStereochemistry(mol)
    smiles = Chem.MolToSmiles(mol, isomericSmiles=False)

    # Please look away. A small hack that removes the explicit hydrogens
    mol = Chem.MolFromSmiles(smiles)
    smiles = Chem.MolToSmiles(mol)

    assert smiles == canonical_smiles

    return 
Example #13
Source File: chemutils.py    From hgraph2graph with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is not None: Chem.Kekulize(mol)
    return mol 
Example #14
Source File: mutate.py    From GB-GA with MIT License 5 votes vote down vote up
def mutate(mol,mutation_rate):

  if random.random() > mutation_rate:
    return mol
  
  Chem.Kekulize(mol,clearAromaticFlags=True)
  p = [0.15,0.14,0.14,0.14,0.14,0.14,0.15]
  for i in range(10):
    rxn_smarts_list = 7*['']
    rxn_smarts_list[0] = insert_atom()
    rxn_smarts_list[1] = change_bond_order()
    rxn_smarts_list[2] = delete_cyclic_bond()
    rxn_smarts_list[3] = add_ring()
    rxn_smarts_list[4] = delete_atom()
    rxn_smarts_list[5] = change_atom(mol)
    rxn_smarts_list[6] = append_atom()
    rxn_smarts = np.random.choice(rxn_smarts_list, p=p) 
    
    #print('mutation',rxn_smarts)
    
    rxn = AllChem.ReactionFromSmarts(rxn_smarts)

    new_mol_trial = rxn.RunReactants((mol,))
    
    new_mols = []
    for m in new_mol_trial:
      m = m[0]
      #print Chem.MolToSmiles(mol),mol_OK(mol)
      if co.mol_OK(m) and co.ring_OK(m):
        new_mols.append(m)
    
    if len(new_mols) > 0:
      return random.choice(new_mols)
  
  return None 
Example #15
Source File: molecule.py    From chemml with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _to_smiles_rdkit(self, **kwargs):
        """
        This internal function creates and stores the SMILES string for rdkit molecule.
        """
        # kekulize flag
        if 'kekuleSmiles' in kwargs and kwargs['kekuleSmiles']:
            Chem.Kekulize(self.rdkit_molecule)

        # store arguments for future reference
        self._smiles = Chem.MolToSmiles(self.rdkit_molecule, **kwargs)

        # arguments
        self._smiles_args = update_default_kwargs(self._default_rdkit_smiles_args, kwargs,
                                                 self._to_smiles_core_names[0], self._to_smiles_core_docs[0]) 
Example #16
Source File: jtnn.py    From chemprop with MIT License 5 votes vote down vote up
def get_mol(smiles: str) -> Chem.rdchem.Mol:
    mol = Chem.MolFromSmiles(smiles)
    if mol is None:
        return None
    Chem.Kekulize(mol)

    return mol 
Example #17
Source File: chemutils.py    From iclr19-graph2graph with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None: 
        return None
    Chem.Kekulize(mol)
    return mol 
Example #18
Source File: analyze_dataset.py    From guacamol_baselines with MIT License 5 votes vote down vote up
def count_macro_cycles(smiles_list, smarts_list, tot, probs):
    """

    Args:
        smiles_list: list of SMILES
        smarts_list: list of SMARTS
        tot: counter of ... TODO: why is this passed?
        probs: OrderedDict of {SMARTS: counts}

    Returns:

    """
    # probs = collections.OrderedDict()
    for smarts in smarts_list:
        probs[smarts] = 0

    for smiles in smiles_list:
        for smarts in smarts_list:
            mol = Chem.MolFromSmiles(smiles)
            Chem.Kekulize(mol)
            matches = mol.GetSubstructMatches(Chem.MolFromSmarts(smarts), uniquify=True)
            if len(matches) > 0:
                probs[smarts] += 1
                tot += 1

    return tot, probs 
Example #19
Source File: analyze_dataset.py    From guacamol_baselines with MIT License 5 votes vote down vote up
def get_counts(smarts_list, smiles_list, ring=False) -> Tuple[int, Dict[str, int]]:
    """

    Args:
        smarts_list: list of SMARTS of intrest
        smiles_list: a list of SMILES strings
        ring: determines whether or not the matches are uniquified

    Returns:
        tot: sum of SMARTS counts
        probs2: an OrderedDict of {SMART: counts}

    """
    probs = collections.OrderedDict()

    for smarts in smarts_list:
        probs[smarts] = 0

    # number_of_molecules = 0
    # tot = 0
    for smiles in smiles_list:
        # print smiles
        # number_of_molecules += 1
        mol = Chem.MolFromSmiles(smiles)
        Chem.Kekulize(mol)
        for smarts in smarts_list:
            matches = mol.GetSubstructMatches(Chem.MolFromSmarts(smarts), uniquify=ring)
            num_bonds = len(matches)  # not the number of bonds, but the number of matches
            probs[smarts] += num_bonds
            # tot += num_bonds

    tot = 0
    probs2 = collections.OrderedDict()
    for key in probs:
        if probs[key] > 0:
            # print key, probs[key]
            tot += probs[key]
            probs2[key] = probs[key]

    return tot, probs2 
Example #20
Source File: mutate.py    From guacamol_baselines with MIT License 5 votes vote down vote up
def mutate(mol, mutation_rate):
    if random.random() > mutation_rate:
        return mol

    try:
        Chem.Kekulize(mol, clearAromaticFlags=True)
    except ValueError:
        return mol

    p = [0.15, 0.14, 0.14, 0.14, 0.14, 0.14, 0.15]
    for i in range(10):
        rxn_smarts_list = 7 * ['']
        rxn_smarts_list[0] = insert_atom()
        rxn_smarts_list[1] = change_bond_order()
        rxn_smarts_list[2] = delete_cyclic_bond()
        rxn_smarts_list[3] = add_ring()
        rxn_smarts_list[4] = delete_atom()
        rxn_smarts_list[5] = change_atom(mol)
        rxn_smarts_list[6] = append_atom()
        rxn_smarts = np.random.choice(rxn_smarts_list, p=p)

        # print 'mutation',rxn_smarts

        rxn = AllChem.ReactionFromSmarts(rxn_smarts)

        new_mol_trial = rxn.RunReactants((mol,))

        new_mols = []
        for m in new_mol_trial:
            m = m[0]
            # print Chem.MolToSmiles(mol),mol_ok(mol)
            if co.mol_ok(m) and co.ring_OK(m):
                new_mols.append(m)

        if len(new_mols) > 0:
            return random.choice(new_mols)

    return None 
Example #21
Source File: crossover.py    From guacamol_baselines with MIT License 5 votes vote down vote up
def crossover(parent_A, parent_B):
    parent_smiles = [Chem.MolToSmiles(parent_A), Chem.MolToSmiles(parent_B)]
    try:
        Chem.Kekulize(parent_A, clearAromaticFlags=True)
        Chem.Kekulize(parent_B, clearAromaticFlags=True)

    except ValueError:
        pass

    for i in range(10):
        if random.random() <= 0.5:
            # print 'non-ring crossover'
            new_mol = crossover_non_ring(parent_A, parent_B)
            if new_mol is not None:
                new_smiles = Chem.MolToSmiles(new_mol)
                if new_smiles is not None and new_smiles not in parent_smiles:
                    return new_mol
        else:
            # print 'ring crossover'
            new_mol = crossover_ring(parent_A, parent_B)
            if new_mol is not None:
                new_smiles = Chem.MolToSmiles(new_mol)
                if new_smiles is not None and new_smiles not in parent_smiles:
                    return new_mol

    return None 
Example #22
Source File: edit_mol.py    From nips17-rexgen with MIT License 5 votes vote down vote up
def get_product_smiles(rmol, edits, tatoms):
    smiles = edit_mol(rmol, edits, tatoms)
    if len(smiles) != 0: return smiles
    try:
        Chem.Kekulize(rmol)
    except Exception as e:
        return smiles
    return edit_mol(rmol, edits, tatoms) 
Example #23
Source File: rdkit_general_ops.py    From molecule-chef with GNU General Public License v3.0 5 votes vote down vote up
def get_molecule(molecule_strs, kekulize) -> AllChem.Mol:
    """
    Convert string to molecule
    """
    mol = Chem.MolFromSmiles(molecule_strs)
    if kekulize:
        Chem.Kekulize(mol)
    return mol 
Example #24
Source File: chemutils.py    From icml18-jtnn with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None: 
        return None
    Chem.Kekulize(mol)
    return mol 
Example #25
Source File: chemutils.py    From icml18-jtnn with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None: 
        return None
    Chem.Kekulize(mol)
    return mol 
Example #26
Source File: chemutils.py    From dgl with Apache License 2.0 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is None: 
        return None
    Chem.Kekulize(mol)
    return mol 
Example #27
Source File: __init__.py    From 3DGCN with MIT License 5 votes vote down vote up
def MolToMPL(mol, size=(300, 300), kekulize=True, wedgeBonds=True, imageType=None, fitImage=False,
             options=None, **kwargs):
    """ Generates a drawing of a molecule on a matplotlib canvas
    """
    if not mol:
        raise ValueError('Null molecule provided')
    from experiment.figure.Draw.mplCanvas 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
    drawer = MolDrawing(canvas=canvas, drawingOptions=options)
    omol = mol
    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.AddMol(mol, **kwargs)
    omol._atomPs = drawer.atomPs[mol]
    for k, v in iteritems(omol._atomPs):
        omol._atomPs[k] = canvas.rescalePt(v)
    canvas._figure.set_size_inches(float(size[0]) / 100, float(size[1]) / 100)
    return canvas._figure 
Example #28
Source File: __init__.py    From 3DGCN with MIT License 5 votes vote down vote up
def MolToFile(mol, fileName, size=(300, 300), kekulize=True, wedgeBonds=True, imageType=None,
              fitImage=False, options=None, **kwargs):
    """ Generates a drawing of a molecule and writes it to a file
    """
    # original contribution from Uwe Hoffmann
    if not fileName:
        raise ValueError('no fileName provided')
    if not mol:
        raise ValueError('Null molecule provided')

    if imageType is None:
        imageType = os.path.splitext(fileName)[1][1:]

    if options is None:
        options = DrawingOptions()
    useAGG, useCairo, Canvas = _getCanvas()
    if fitImage:
        options.dotsPerAngstrom = int(min(size) / 10)
    options.wedgeDashedBonds = wedgeBonds
    if useCairo or useAGG:
        canvas = Canvas(size=size, imageType=imageType, fileName=fileName)
    else:
        options.radicalSymbol = '.'  # <- the sping canvas doesn't support unicode well
        canvas = Canvas(size=size, name=fileName, imageType=imageType)
    drawer = MolDrawing(canvas=canvas, drawingOptions=options)
    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.AddMol(mol, **kwargs)
    if useCairo or useAGG:
        canvas.flush()
    else:
        canvas.save() 
Example #29
Source File: chemutils.py    From hgraph2graph with MIT License 5 votes vote down vote up
def get_mol(smiles):
    mol = Chem.MolFromSmiles(smiles)
    if mol is not None: Chem.Kekulize(mol)
    return mol 
Example #30
Source File: chemutils.py    From icml18-jtnn with MIT License 4 votes vote down vote up
def enum_assemble(node, neighbors, prev_nodes=[], prev_amap=[]):
    all_attach_confs = []
    singletons = [nei_node.nid for nei_node in neighbors + prev_nodes if nei_node.mol.GetNumAtoms() == 1]

    def search(cur_amap, depth):
        if len(all_attach_confs) > MAX_NCAND:
            return
        if depth == len(neighbors):
            all_attach_confs.append(cur_amap)
            return

        nei_node = neighbors[depth]
        cand_amap = enum_attach(node.mol, nei_node, cur_amap, singletons)
        cand_smiles = set()
        candidates = []
        for amap in cand_amap:
            cand_mol = local_attach(node.mol, neighbors[:depth+1], prev_nodes, amap)
            cand_mol = sanitize(cand_mol)
            if cand_mol is None:
                continue
            smiles = get_smiles(cand_mol)
            if smiles in cand_smiles:
                continue
            cand_smiles.add(smiles)
            candidates.append(amap)

        if len(candidates) == 0:
            return

        for new_amap in candidates:
            search(new_amap, depth + 1)

    search(prev_amap, 0)
    cand_smiles = set()
    candidates = []
    for amap in all_attach_confs:
        cand_mol = local_attach(node.mol, neighbors, prev_nodes, amap)
        cand_mol = Chem.MolFromSmiles(Chem.MolToSmiles(cand_mol))
        smiles = Chem.MolToSmiles(cand_mol)
        if smiles in cand_smiles:
            continue
        cand_smiles.add(smiles)
        Chem.Kekulize(cand_mol)
        candidates.append( (smiles,cand_mol,amap) )

    return candidates

#Only used for debugging purpose