<commit_before>## Copyright (c) 2008-2011, <NAME>
## All rights reserved.
##
##  This file is part of Cinfony.
##  The contents are covered by the terms of the BSD license
##  which is included in the file LICENSE_BSD.txt.

"""
rdkit - A Cinfony module for accessing the RDKit from CPython

Global variables:
  Chem and AllChem - the underlying RDKit Python bindings
  informats - a dictionary of supported input formats
  outformats - a dictionary of supported output formats
  descs - a list of supported descriptors
  fps - a list of supported fingerprint types
  forcefields - a list of supported forcefields
"""

import os

from rdkit import Chem
from rdkit.Chem import AllChem, Draw
from rdkit.Chem import Descriptors

_descDict = dict(Descriptors.descList)

import rdkit.DataStructs
import rdkit.Chem.MACCSkeys
import rdkit.Chem.AtomPairs.Pairs
import rdkit.Chem.AtomPairs.Torsions

# PIL and Tkinter
try:
    import Tkinter as tk
    import Image as PIL
    import ImageTk as PILtk
except:
    PILtk = None

# Aggdraw
try:
    import aggdraw
    from rdkit.Chem.Draw import aggCanvas
except ImportError:
    aggdraw = None

fps = ['rdkit', 'layered', 'maccs', 'atompairs', 'torsions']
"""A list of supported fingerprint types"""
descs = _descDict.keys()
"""A list of supported descriptors"""

_formats = {'smi': "SMILES"
            ,'can': "Canonical SMILES"
            ,'mol': "MDL MOL file", 'sdf': "MDL SDF file"
            ,"inchi":"InChI"
            ,"inchikey":"InChIKey"}
_notinformats = ['can', 'inchikey']
_notoutformats = []
if not Chem.INCHI_AVAILABLE:
    _notinformats += ['inchi']
    _notoutformats += ['inchi', 'inchikey']

informats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notinformats])
"""A dictionary of supported input formats"""
outformats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notoutformats])
"""A dictionary of supported output formats"""

_forcefields = {'uff': AllChem.UFFOptimizeMolecule}
forcefields = _forcefields.keys()
"""A list of supported forcefields"""

def readfile(format, filename):
    """Iterate over the molecules in a file.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       filename

    You can access the first molecule in a file using the next() method
    of the iterator:
        mol = readfile("smi", "myfile.smi").next()

    You can make a list of the molecules in a file using:
        mols = list(readfile("smi", "myfile.smi"))

    You can iterate over the molecules in a file as shown in the
    following code snippet:
    >>> atomtotal = 0
    >>> for mol in readfile("sdf", "head.sdf"):
    ...     atomtotal += len(mol.atoms)
    ...
    >>> print atomtotal
    43
    """
    if not os.path.isfile(filename):
        raise IOError, "No such file: '%s'" % filename
    format = format.lower()
    # Eagerly evaluate the supplier functions in order to report
    # errors in the format and errors in opening the file.
    # Then switch to an iterator...
    if format=="sdf":
        iterator = Chem.SDMolSupplier(filename)
        def sdf_reader():
            for mol in iterator:
                yield Molecule(mol)
        return sdf_reader()
    elif format=="mol":
        def mol_reader():
            yield Molecule(Chem.MolFromMolFile(filename))
        return mol_reader()
    elif format=="smi":
        iterator = Chem.SmilesMolSupplier(filename, delimiter=" \t",
                                          titleLine=False)
        def smi_reader():
            for mol in iterator:
                yield Molecule(mol)
        return smi_reader()
    elif format=='inchi' and Chem.INCHI_AVAILABLE:
        def  inchi_reader():
            for line in open(filename, 'rb'):
                mol = Chem.inchi.MolFromInchi(line.strip())
                yield Molecule(mol)
        return inchi_reader()
    else:
        raise ValueError, "%s is not a recognised RDKit format" % format

def readstring(format, string):
    """Read in a molecule from a string.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       string

    Example:
    >>> input = "C1=CC=CS1"
    >>> mymol = readstring("smi", input)
    >>> len(mymol.atoms)
    5
    """
    format = format.lower()
    if format=="mol":
        mol = Chem.MolFromMolBlock(string)
    elif format=="smi":
        mol = Chem.MolFromSmiles(string)
    elif format=='inchi'and Chem.INCHI_AVAILABLE:
        mol = Chem.inchi.MolFromInchi(string)
    else:
        raise ValueError,"%s is not a recognised RDKit format" % format
    if mol:
        return Molecule(mol)
    else:
        raise IOError, "Failed to convert '%s' to format '%s'" % (
            string, format)

class Outputfile(object):
    """Represent a file to which *output* is to be sent.

    Required parameters:
       format - see the outformats variable for a list of available
                output formats
       filename

    Optional parameters:
       overwite -- if the output file already exists, should it
                   be overwritten? (default is False)

    Methods:
       write(molecule)
       close()
    """
    def __init__(self, format, filename, overwrite=False):<commit_msg>add mol2 string read to rdk<commit_after>## Copyright (c) 2008-2011, <NAME>
## All rights reserved.
##
##  This file is part of Cinfony.
##  The contents are covered by the terms of the BSD license
##  which is included in the file LICENSE_BSD.txt.

"""
rdkit - A Cinfony module for accessing the RDKit from CPython

Global variables:
  Chem and AllChem - the underlying RDKit Python bindings
  informats - a dictionary of supported input formats
  outformats - a dictionary of supported output formats
  descs - a list of supported descriptors
  fps - a list of supported fingerprint types
  forcefields - a list of supported forcefields
"""

import os

from rdkit import Chem
from rdkit.Chem import AllChem, Draw
from rdkit.Chem import Descriptors

_descDict = dict(Descriptors.descList)

import rdkit.DataStructs
import rdkit.Chem.MACCSkeys
import rdkit.Chem.AtomPairs.Pairs
import rdkit.Chem.AtomPairs.Torsions

# PIL and Tkinter
try:
    import Tkinter as tk
    import Image as PIL
    import ImageTk as PILtk
except:
    PILtk = None

# Aggdraw
try:
    import aggdraw
    from rdkit.Chem.Draw import aggCanvas
except ImportError:
    aggdraw = None

fps = ['rdkit', 'layered', 'maccs', 'atompairs', 'torsions']
"""A list of supported fingerprint types"""
descs = _descDict.keys()
"""A list of supported descriptors"""

_formats = {'smi': "SMILES"
            ,'can': "Canonical SMILES"
            ,'mol': "MDL MOL file"
            ,'mol2': "Tripos MOL2 file"
            , 'sdf': "MDL SDF file"
            ,"inchi":"InChI"
            ,"inchikey":"InChIKey"}
_notinformats = ['can', 'inchikey']
_notoutformats = ['mol2']
if not Chem.INCHI_AVAILABLE:
    _notinformats += ['inchi']
    _notoutformats += ['inchi', 'inchikey']

informats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notinformats])
"""A dictionary of supported input formats"""
outformats = dict([(_x, _formats[_x]) for _x in _formats if _x not in _notoutformats])
"""A dictionary of supported output formats"""

_forcefields = {'uff': AllChem.UFFOptimizeMolecule}
forcefields = _forcefields.keys()
"""A list of supported forcefields"""

def readfile(format, filename):
    """Iterate over the molecules in a file.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       filename

    You can access the first molecule in a file using the next() method
    of the iterator:
        mol = readfile("smi", "myfile.smi").next()

    You can make a list of the molecules in a file using:
        mols = list(readfile("smi", "myfile.smi"))

    You can iterate over the molecules in a file as shown in the
    following code snippet:
    >>> atomtotal = 0
    >>> for mol in readfile("sdf", "head.sdf"):
    ...     atomtotal += len(mol.atoms)
    ...
    >>> print atomtotal
    43
    """
    if not os.path.isfile(filename):
        raise IOError, "No such file: '%s'" % filename
    format = format.lower()
    # Eagerly evaluate the supplier functions in order to report
    # errors in the format and errors in opening the file.
    # Then switch to an iterator...
    if format=="sdf":
        iterator = Chem.SDMolSupplier(filename)
        def sdf_reader():
            for mol in iterator:
                yield Molecule(mol)
        return sdf_reader()
    elif format=="mol":
        def mol_reader():
            yield Molecule(Chem.MolFromMolFile(filename))
        return mol_reader()
    elif format=="smi":
        iterator = Chem.SmilesMolSupplier(filename, delimiter=" \t",
                                          titleLine=False)
        def smi_reader():
            for mol in iterator:
                yield Molecule(mol)
        return smi_reader()
    elif format=='inchi' and Chem.INCHI_AVAILABLE:
        def  inchi_reader():
            for line in open(filename, 'rb'):
                mol = Chem.inchi.MolFromInchi(line.strip())
                yield Molecule(mol)
        return inchi_reader()
    else:
        raise ValueError, "%s is not a recognised RDKit format" % format

def readstring(format, string):
    """Read in a molecule from a string.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       string

    Example:
    >>> input = "C1=CC=CS1"
    >>> mymol = readstring("smi", input)
    >>> len(mymol.atoms)
    5
    """
    format = format.lower()
    if format=="mol":
        mol = Chem.MolFromMolBlock(string)
    elif format=="mol2":
        mol = Chem.MolFromMol2Block(string)
    elif format=="smi":
        mol = Chem.MolFromSmiles(string)
    elif format=='inchi'and Chem.INCHI_AVAILABLE:
        mol = Chem.inchi.MolFromInchi(string)
    else:
        raise ValueError,"%s is not a recognised RDKit format" % format
    if mol:
        return Molecule(mol)
    else:
        raise IOError, "Failed to convert '%s' to format '%s'" % (
            string, format)

class Outputfile(object):
    """Represent a file to which *output* is to be sent.

    Required parameters:
       format - see the outformats variable for a list of available
                output formats
       filename

    Optional parameters:
       overwite -- if the output file already exists, should it
                   be overwritten? (default is False)

    Methods:
       write(molecule)
       close()
    """
    def __init__(self, format, filename, overwrite=False):
{'fraction_non_alphanumeric': 0.09899422611287018, 'fraction_numerical': 0.003166325200223505, 'mean_word_length': 2.6341793570219965, 'pattern_counts': {'":': 15, '<': 5, '<?xml version=': 0, '>': 41, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7098583', 'n_tokens_mistral': 3345, 'n_tokens_neox': 3164, 'n_words': 1111}