Python rdkit.Chem.Draw.MolToFile() Examples

The following are 7 code examples of rdkit.Chem.Draw.MolToFile(). 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.Draw , or try the search function .
Example #1
Source File: utils.py    From deepchem with MIT License 5 votes vote down vote up
def mols_to_pngs(mols, basename="test"):
    """Helper to write RDKit mols to png files."""
    filenames = []
    for i, mol in enumerate(mols):
        filename = "%s%d.png" % (basename, i)
        Draw.MolToFile(mol, filename)
        filenames.append(filename)
    return filenames 
Example #2
Source File: chem.py    From spektral with MIT License 5 votes vote down vote up
def plot_rdkit(mol, filename=None):
    """
    Plots an RDKit molecule in Matplotlib
    :param mol: an RDKit molecule 
    :param filename: save the image with the given filename 
    :return: the image as np.array
    """
    if rdc is None:
        raise ImportError('`draw_rdkit_mol` requires RDkit.')
    if filename is not None:
        Draw.MolToFile(mol, filename)
    img = Draw.MolToImage(mol)
    return img 
Example #3
Source File: preprocess.py    From PADME with MIT License 5 votes vote down vote up
def filter_similarity(input_file, output_file, image_folder='./mol_images', threshold=0.85, 
  draw_2d_image=True, limit=False, limit_lines=120):
  # Both input_file and output_file should be csv files.
  df_sim = pd.read_csv(input_file, header=0, index_col=False)
  smiles_array = df_sim['smiles']
  scores_array = df_sim['avg_score']
  similarity_array = df_sim['max_similarity']
  selected_indices_list = []
  for i, sim in enumerate(similarity_array):
    if sim >= threshold:
      continue
    selected_indices_list.append(i)
    if draw_2d_image:
      source_line_num = i + 2
      target_line_num = len(selected_indices_list) + 1
      mol = Chem.MolFromSmiles(smiles_array[i])
      Draw.MolToFile(mol, 
        image_folder + '/' + str(source_line_num) + '_' + str(target_line_num) + '.png',
        size=(700,700))

  with open(output_file, 'w', newline='') as csvfile:
    fieldnames = ['smiles', 'avg_score', 'max_similarity']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writeheader()
    for i, ind in enumerate(selected_indices_list):
      if limit and i + 1 > limit_lines:
        break
      out_line = {'smiles': smiles_array[ind], 'avg_score': scores_array[ind], 
        'max_similarity': similarity_array[ind]}
      writer.writerow(out_line) 
Example #4
Source File: struct_utils.py    From AMPL with MIT License 5 votes vote down vote up
def draw_structure(smiles_str, image_path, image_size=500):
  """
  Draw structure for the compound with the given SMILES string, in a PNG file
  with the given path.
  """
  mol = Chem.MolFromSmiles(smiles_str)
  if mol is None:
    print(("Unable to read original SMILES for %s" % cmpd_num))
  else:
    _discard = AllChem.Compute2DCoords(mol)
    Draw.MolToFile(mol, image_path, size=(image_size,image_size), fitImage=False) 
Example #5
Source File: utils.py    From constrained-graph-variational-autoencoder with MIT License 5 votes vote down vote up
def visualize_mol(path, new_mol):
    AllChem.Compute2DCoords(new_mol)
    print(path)
    Draw.MolToFile(new_mol,path) 
Example #6
Source File: utils.py    From graph-nvp with MIT License 5 votes vote down vote up
def save_mol_png(mol, filepath, size=(600, 600)):
    Draw.MolToFile(mol, filepath, size=size) 
Example #7
Source File: molecule.py    From chemml with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def visualize(self, filename=None, **kwargs):
        """
        This function visualizes the molecule. If both rdkit and pybel objects are avaialble, the rdkit object
        will be used for visualization.

        Parameters
        ----------
        filename: str, optional (default = None)
            This is the path to the file that you want write the image in it.
            Tkinter and Python Imaging Library are required for writing the image.

        kwargs:
            any extra parameter that you want to pass to the rdkit or pybel draw tool.
            Additional information at:
                - https://www.rdkit.org/docs/source/rdkit.Chem.Draw.html
                - http://openbabel.org/docs/dev/UseTheLibrary/Python_PybelAPI.html#pybel.Molecule.draw

        Returns
        -------
        object
            You will be able to display this object, e.g., inside the Jupyter Notebook.

        """
        engine = self._check_original_molecule()
        if engine == 'rdkit':
            from rdkit.Chem import Draw
            if filename is not None:
                Draw.MolToFile(self.rdkit_molecule, filename, **kwargs)
            else:
                return Draw.MolToImage(self.rdkit_molecule, **kwargs)
        elif engine == 'pybel':
            if filename is not None:
                self.pybel_molecule.draw(show=False, filename=filename, **kwargs)
            else:
                return self.pybel_molecule # it seems that the object alone is displayable