MayaChemTools

   1 #!/bin/env python
   2 # File: RDKitUtil.py
   3 # Author: Manish Sud <msud@san.rr.com>
   4 #
   5 # Copyright (C) 2020 Manish Sud. All rights reserved.
   6 #
   7 # The functionality available in this file is implemented using RDKit, an
   8 # open source toolkit for cheminformatics developed by Greg Landrum.
   9 #
  10 # This file is part of MayaChemTools.
  11 #
  12 # MayaChemTools is free software; you can redistribute it and/or modify it under
  13 # the terms of the GNU Lesser General Public License as published by the Free
  14 # Software Foundation; either version 3 of the License, or (at your option) any
  15 # later version.
  16 #
  17 # MayaChemTools is distributed in the hope that it will be useful, but without
  18 # any warranty; without even the implied warranty of merchantability of fitness
  19 # for a particular purpose.  See the GNU Lesser General Public License for more
  20 # details.
  21 #
  22 # You should have received a copy of the GNU Lesser General Public License
  23 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or
  24 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330,
  25 # Boston, MA, 02111-1307, USA.
  26 #
  27 
  28 from __future__ import print_function
  29 
  30 import os
  31 import sys
  32 import re
  33 import base64
  34 import pickle
  35 
  36 from rdkit import Chem
  37 from rdkit.Chem import AllChem
  38 from rdkit.Chem import Draw
  39 
  40 import MiscUtil
  41 
  42 __all__ = ["AreAtomIndicesSequentiallyConnected", "FilterSubstructureMatchByAtomMapNumbers", "FilterSubstructureMatchesByAtomMapNumbers", "GetInlineSVGForMolecule", "GetInlineSVGForMolecules", "GetMolName", "GetSVGForMolecule", "GetSVGForMolecules", "GenerateBase64EncodedMolStrings", "IsMolEmpty", "MolFromBase64EncodedMolString", "MolToBase64EncodedMolString", "MolFromSubstructureMatch", "MolsFromSubstructureMatches", "ReadMolecules", "ReadAndValidateMolecules", "ReadMoleculesFromSDFile", "ReadMoleculesFromMolFile", "ReadMoleculesFromMol2File", "ReadMoleculesFromPDBFile", "ReadMoleculesFromSMILESFile", "SetWriterMolProps", "WriteMolecules"]
  43 
  44 def GetMolName(Mol, MolNum = None):
  45     """Get molecule name.
  46     
  47     Arguments:
  48         Mol (object): RDKit molecule object.
  49         MolNum (int or None): Molecule number in input file.
  50 
  51     Returns:
  52         str : Molname corresponding to _Name property of a molecule, generated
  53             from specieid MolNum using the format "Mol%d" % MolNum, or an
  54             empty string.
  55 
  56     """
  57     
  58     MolName = ''
  59     if Mol.HasProp("_Name"):
  60         MolName = Mol.GetProp("_Name")
  61 
  62     if not len(MolName):
  63         if MolNum is not None:
  64             MolName = "Mol%d" % MolNum
  65     
  66     return MolName
  67 
  68 def GetInlineSVGForMolecule(Mol, Width, Height, Legend = None, AtomListToHighlight = None, BondListToHighlight = None, BoldText = True, Base64Encoded = True):
  69     """Get SVG image text for a molecule suitable for inline embedding into a HTML page.
  70     
  71     Arguments:
  72         Mol (object): RDKit molecule object.
  73         Width (int): Width of a molecule image in pixels.
  74         Height (int): Height of a molecule image in pixels.
  75         Legend (str): Text to display under the image.
  76         AtomListToHighlight (list): List of atoms to highlight.
  77         BondListToHighlight (list): List of bonds to highlight.
  78         BoldText (bool): Flag to make text bold in the image of molecule. 
  79         Base64Encoded (bool): Flag to return base64 encoded string. 
  80 
  81     Returns:
  82         str : SVG image text for inline embedding into a HTML page using "img"
  83             tag: <img src="data:image/svg+xml;charset=UTF-8,SVGImageText> or
  84             tag: <img src="data:image/svg+xml;base64,SVGImageText>
  85 
  86     """
  87 
  88     SVGText = GetSVGForMolecule(Mol, Width, Height, Legend, AtomListToHighlight, BondListToHighlight, BoldText)
  89     return _ModifySVGForInlineEmbedding(SVGText, Base64Encoded)
  90     
  91 def GetInlineSVGForMolecules(Mols, MolsPerRow, MolWidth, MolHeight, Legends = None, AtomListsToHighlight = None, BondListsToHighLight = None, BoldText = True, Base64Encoded = True):
  92     """Get SVG image text for  molecules suitable for inline embedding into a HTML page.
  93     
  94     Arguments:
  95         Mols (list): List of RDKit molecule objects.
  96         MolsPerRow (int): Number of molecules per row.
  97         Width (int): Width of a molecule image in pixels.
  98         Height (int): Height of a molecule image in pixels.
  99         Legends (list): List containing strings to display under images.
 100         AtomListsToHighlight (list): List of lists containing atoms to highlight
 101             for molecules.
 102         BondListsToHighlight (list): List of lists containing bonds to highlight
 103             for molecules
 104         BoldText (bool): Flag to make text bold in the image of molecules. 
 105         Base64Encoded (bool): Flag to return base64 encoded string. 
 106 
 107     Returns:
 108         str : SVG image text for inline embedding into a HTML page using "img"
 109             tag: <img src="data:image/svg+xml;charset=UTF-8,SVGImageText> or
 110             tag: <img src="data:image/svg+xml;base64,SVGImageText>
 111 
 112     """
 113     
 114     SVGText = GetSVGForMolecules(Mols, MolsPerRow, MolWidth, MolHeight, Legends, AtomListsToHighlight, BondListsToHighLight, BoldText)
 115     return _ModifySVGForInlineEmbedding(SVGText, Base64Encoded)
 116 
 117 def _ModifySVGForInlineEmbedding(SVGText, Base64Encoded):
 118     """Modify SVG for inline embedding into a HTML page using "img" tag
 119     along with performing base64 encoding.
 120     """
 121     
 122     # Take out all tags till the start of '<svg' tag...
 123     Pattern = re.compile("^.*<svg", re.I | re.S)
 124     SVGText = Pattern.sub("<svg", SVGText)
 125     
 126     # Add an extra space before the "width=..." tag. Otherwise, inline embedding may
 127     # cause the following XML error on some browsers due to start of the "width=..."
 128     # at the begining of the line in <svg ...> tag:
 129     #
 130     #  XML5607: Whitespace expected.
 131     #
 132     SVGText = re.sub("width='", " width='", SVGText, flags = re.I)
 133     
 134     # Take out trailing new line...
 135     SVGText = SVGText.strip()
 136 
 137     # Perform base64 encoding by turning text into byte stream using string
 138     # encode and transform byte stream returned by b64encode into a string
 139     # by string decode...
 140     #
 141     if Base64Encoded:
 142         SVGText = base64.b64encode(SVGText.encode()).decode()
 143 
 144     return SVGText
 145 
 146 def GetSVGForMolecule(Mol, Width, Height, Legend = None, AtomListToHighlight = None, BondListToHighlight = None, BoldText = True):
 147     """Get SVG image text for a molecule suitable for viewing in a browser.
 148     
 149     Arguments:
 150         Mol (object): RDKit molecule object.
 151         Width (int): Width of a molecule image in pixels.
 152         Height (int): Height of a molecule image in pixels.
 153         Legend (str): Text to display under the image.
 154         AtomListToHighlight (list): List of atoms to highlight.
 155         BondListToHighlight (list): List of bonds to highlight.
 156         BoldText (bool): Flag to make text bold in the image of molecule. 
 157 
 158     Returns:
 159         str : SVG image text for writing to a SVG file for viewing in a browser.
 160 
 161     """
 162     
 163     Mols = [Mol]
 164     
 165     MolsPerRow = 1
 166     MolWidth = Width
 167     MolHeight = Height
 168     
 169     Legends = [Legend] if Legend is not None else None
 170     AtomListsToHighlight = [AtomListToHighlight] if AtomListToHighlight is not None else None
 171     BondListsToHighLight = [BondListsToHighLight] if BondListToHighlight is not None else None
 172     
 173     return GetSVGForMolecules(Mols, MolsPerRow, MolWidth, MolHeight, Legends, AtomListsToHighlight, BondListsToHighLight, BoldText)
 174 
 175 def GetSVGForMolecules(Mols, MolsPerRow, MolWidth, MolHeight, Legends = None, AtomListsToHighlight = None, BondListsToHighlight = None, BoldText = True):
 176     """Get SVG image text for molecules suitable for viewing in a browser.
 177     
 178     Arguments:
 179         Mols (list): List of RDKit molecule objects.
 180         MolsPerRow (int): Number of molecules per row.
 181         Width (int): Width of a molecule image in pixels.
 182         Height (int): Height of a molecule image in pixels.
 183         Legends (list): List containing strings to display under images.
 184         AtomListsToHighlight (list): List of lists containing atoms to highlight
 185             for molecules.
 186         BondListsToHighlight (list): List of lists containing bonds to highlight
 187             for molecules
 188         BoldText (bool): Flag to make text bold in the image of molecules. 
 189 
 190     Returns:
 191         str : SVG image text for writing to a SVG file for viewing in a browser.
 192 
 193     """
 194     
 195     SVGText = Draw.MolsToGridImage(Mols, molsPerRow = MolsPerRow, subImgSize = (MolWidth,MolHeight), legends = Legends, highlightAtomLists = AtomListsToHighlight, highlightBondLists = BondListsToHighlight, useSVG = True)
 196     
 197     return _ModifySVGForBrowserViewing(SVGText, BoldText)
 198 
 199 def _ModifySVGForBrowserViewing(SVGText, BoldText = True):
 200     """Modify SVG for loading into a browser."""
 201     
 202     # It appears that the string 'xmlns:svg' needs to be replaced with 'xmlns' in the
 203     # SVG image string generated by RDKit. Otherwise, the image doesn't load in 
 204     # web browsers.
 205     #
 206     if re.search("xmlns:svg", SVGText, re.I):
 207         SVGText = re.sub("xmlns:svg", "xmlns", SVGText, flags = re.I)
 208     
 209     # Make text bold...
 210     if BoldText:
 211         SVGText = re.sub("font-weight:normal;", "font-weight:bold;", SVGText, flags = re.I)
 212     
 213     return SVGText
 214 
 215 def IsMolEmpty(Mol):
 216     """Check for the presence of atoms in a molecule.
 217     
 218     Arguments:
 219         Mol (object): RDKit molecule object.
 220 
 221     Returns:
 222         bool : True - No atoms in molecule; Otherwise, false. 
 223 
 224     """
 225 
 226     Status = False if Mol.GetNumAtoms() else True
 227     
 228     return Status
 229 
 230 def AreAtomIndicesSequentiallyConnected(Mol, AtomIndices):
 231     """Check for the presence bonds between sequential pairs of atoms in a
 232     molecule.
 233     
 234     Arguments:
 235         Mol (object): RDKit molecule object.
 236         AtomIndices (list): List of atom indices.
 237 
 238     Returns:
 239         bool : True - Sequentially connected; Otherwise, false. 
 240 
 241     """
 242 
 243     for Index in range(0, (len(AtomIndices) -1)):
 244         if Mol.GetBondBetweenAtoms(AtomIndices[Index], AtomIndices[Index + 1]).GetIdx() is None:
 245             return False
 246     
 247     return True
 248     
 249 def MolToBase64EncodedMolString(Mol, PropertyPickleFlags = Chem.PropertyPickleOptions.AllProps):
 250     """Encode RDkit molecule object into a base64 encoded string. The properties
 251     can be optionally excluded.
 252     
 253     The molecule is pickled using RDKit Mol.ToBinary() function before
 254     their encoding.
 255    
 256     Arguments:
 257         Mol (object): RDKit molecule object.
 258         PropertyPickleFlags: RDKit property pickle options.
 259 
 260     Returns:
 261         str : Base64 encode molecule string or None.
 262 
 263     Notes:
 264         The following property pickle flags are currently available in RDKit:
 265             
 266             Chem.PropertyPickleOptions.NoProps
 267             Chem.PropertyPickleOptions.MolProps
 268             Chem.PropertyPickleOptions.AtomProps
 269             Chem.PropertyPickleOptions.BondProps
 270             Chem.PropertyPickleOptions.PrivateProps
 271             Chem.PropertyPickleOptions.AllProps
 272 
 273     """
 274 
 275     return None if Mol is None else base64.b64encode(Mol.ToBinary(PropertyPickleFlags)).decode()
 276 
 277 def MolFromBase64EncodedMolString(EncodedMol):
 278     """Generate a RDKit molecule object from a base64 encoded string.
 279     
 280     Arguments:
 281         str: Base64 encoded molecule string.
 282 
 283     Returns:
 284         object : RDKit molecule object or None.
 285 
 286     """
 287 
 288     return None if EncodedMol is None else Chem.Mol(base64.b64decode(EncodedMol))
 289 
 290 def GenerateBase64EncodedMolStrings(Mols, PropertyPickleFlags = Chem.PropertyPickleOptions.AllProps):
 291     """Setup an iterator for generating base64 encoded molecule string
 292     from a RDKit molecule iterator. The iterator returns a list containing
 293     a molecule index and encoded molecule string or None.
 294     
 295     The molecules are pickled using RDKit Mol.ToBinary() function
 296     before their encoding.
 297     
 298     Arguments:
 299         iterator: RDKit molecules iterator.
 300         PropertyFlags: RDKit property pickle options.
 301 
 302     Returns:
 303         object : Base64 endcoded molecules iterator. The iterator returns a
 304             list containing a molecule index and an encoded molecule string
 305             or None.
 306 
 307     Notes:
 308         The following property pickle flags are currently available in RDKit:
 309             
 310             Chem.PropertyPickleOptions.NoProps
 311             Chem.PropertyPickleOptions.MolProps
 312             Chem.PropertyPickleOptions.AtomProps
 313             Chem.PropertyPickleOptions.BondProps
 314             Chem.PropertyPickleOptions.PrivateProps
 315             Chem.PropertyPickleOptions.AllProps
 316 
 317     Examples:
 318 
 319         EncodedMolsInfo = GenerateBase64EncodedMolStrings(Mols)
 320         for MolIndex, EncodedMol in EncodedMolsInfo:
 321             if EncodeMol is not None:
 322                 Mol = MolFromBase64EncodedMolString(EncodedMol)
 323 
 324     """
 325     for MolIndex, Mol in enumerate(Mols):
 326         yield [MolIndex, None] if Mol is None else [MolIndex, MolToBase64EncodedMolString(Mol, PropertyPickleFlags)]
 327 
 328 def MolFromSubstructureMatch(Mol, PatternMol, AtomIndices, FilterByAtomMapNums = False):
 329     """Generate a RDKit molecule object for a list of matched atom indices
 330     present in a pattern molecule. The list of atom indices correspond to a
 331     list retrieved by RDKit function GetSubstructureMatche using SMILES/SMARTS
 332     pattern. The atom indices are optionally filtered by mapping atom numbers
 333     to appropriate atom indices during the generation of the molecule. For
 334     example: [O:1]=[S:2](=[O])[C:3][C:4].
 335     
 336     Arguments:
 337         Mol (object): RDKit molecule object.
 338         PatternMol (object): RDKit molecule object for a SMILES/SMARTS pattern.
 339         AtomIndices (list): Atom indices.
 340         FilterByAtomMapNums (bool): Filter matches by atom map numbers.
 341 
 342     Returns:
 343         object : RDKit molecule object or None.
 344 
 345     """
 346 
 347     AtomMapIndices = _GetAtomMapIndices(PatternMol) if FilterByAtomMapNums else None
 348 
 349     return (_MolFromSubstructureMatch(Mol, PatternMol, AtomIndices, AtomMapIndices))
 350 
 351 def MolsFromSubstructureMatches(Mol, PatternMol, AtomIndicesList, FilterByAtomMapNums = False):
 352     """Generate  a list of RDKit molecule objects for a list containing lists of
 353     matched atom indices present in a pattern molecule. The list of atom indices
 354     correspond to a list retrieved by RDKit function GetSubstructureMatches using
 355     SMILES/SMARTS pattern. The atom indices are optionally filtered by mapping
 356     atom numbers to appropriate atom indices during the generation of the molecule. For
 357     example: [O:1]=[S:2](=[O])[C:3][C:4].
 358      
 359     Arguments:
 360         Mol (object): RDKit molecule object.
 361         PatternMol (object): RDKit molecule object for a SMILES/SMARTS pattern.
 362         AtomIndicesList (list): A list of lists containing atom indices.
 363         FilterByAtomMapNums (bool): Filter matches by atom map numbers.
 364 
 365     Returns:
 366         list : A list of lists containg RDKit molecule objects or None.
 367 
 368     """
 369 
 370     AtomMapIndices = _GetAtomMapIndices(PatternMol) if FilterByAtomMapNums else None
 371 
 372     Mols = []
 373     for AtomIndices in AtomIndicesList:
 374         Mols.append(_MolFromSubstructureMatch(Mol, PatternMol, AtomIndices, AtomMapIndices))
 375     
 376     return Mols if len(Mols) else None
 377 
 378 def FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices):
 379     """Filter a list of matched atom indices by map atom numbers present in a
 380     pattern molecule. The list of atom indices correspond to a list retrieved by
 381     RDKit function GetSubstructureMatches using SMILES/SMARTS pattern. The
 382     atom map numbers are mapped to appropriate atom indices during the generation
 383     of molecules. For example: [O:1]=[S:2](=[O])[C:3][C:4].
 384     
 385     Arguments:
 386         Mol (object): RDKit molecule object.
 387         PatternMol (object): RDKit molecule object for a SMILES/SMARTS pattern.
 388         AtomIndices (list): Atom indices.
 389 
 390     Returns:
 391         list : A list of filtered atom indices.
 392 
 393     """
 394     AtomMapIndices = _GetAtomMapIndices(PatternMol)
 395 
 396     return _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices)
 397 
 398 def FilterSubstructureMatchesByAtomMapNumbers(Mol, PatternMol, AtomIndicesList):
 399     """Filter a list of lists comtaining matched atom indices by map atom numbers
 400     present in a pattern molecule. The list of atom indices correspond to a list retrieved by
 401     RDKit function GetSubstructureMatches using SMILES/SMARTS pattern. The
 402     atom map numbers are mapped to appropriate atom indices during the generation
 403     of molecules. For example: [O:1]=[S:2](=[O])[C:3][C:4].
 404      
 405     Arguments:
 406         Mol (object): RDKit molecule object.
 407         PatternMol (object): RDKit molecule object for a SMILES/SMARTS pattern.
 408         AtomIndicesList (list): A list of lists containing atom indices.
 409 
 410     Returns:
 411         list : A list of lists containing filtered atom indices.
 412 
 413     """
 414     AtomMapIndices = _GetAtomMapIndices(PatternMol)
 415 
 416     MatchedAtomIndicesList = []
 417     for AtomIndices in AtomIndicesList:
 418         MatchedAtomIndicesList.append(_FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices))
 419     
 420     return MatchedAtomIndicesList
 421 
 422 def _MolFromSubstructureMatch(Mol, PatternMol, AtomIndices, AtomMapIndices):
 423     """Generate a RDKit molecule object for a list of matched atom indices and available
 424    atom map indices.
 425     """
 426 
 427     if AtomMapIndices is not None:
 428         MatchedAtomIndices = [AtomIndices[Index] for Index in AtomMapIndices]
 429     else:
 430         MatchedAtomIndices = list(AtomIndices)
 431 
 432     return _GetMolFromAtomIndices(Mol, MatchedAtomIndices)
 433 
 434 def _GetAtomMapIndices(PatternMol):
 435     """Get a list of any available atom indices corresponding to atom map numbers
 436     present in  pattern SMILES/SMARTS used for creating pattern molecule.
 437     """
 438 
 439     # Setup a atom map number to atom indices map..
 440     AtomMapNumToIndices = {}
 441     for Atom in PatternMol.GetAtoms():
 442         AtomMapNum = Atom.GetAtomMapNum()
 443         
 444         if AtomMapNum:
 445             AtomMapNumToIndices[AtomMapNum] = Atom.GetIdx()
 446     
 447     # Setup atom indices corresponding to atom map numbers...
 448     AtomMapIndices = None
 449     if len(AtomMapNumToIndices):
 450         AtomMapIndices = [AtomMapNumToIndices[AtomMapNum] for AtomMapNum in sorted(AtomMapNumToIndices)]
 451 
 452     return AtomMapIndices
 453 
 454 def _FilterSubstructureMatchByAtomMapNumbers(Mol, PatternMol, AtomIndices, AtomMapIndices):
 455     """Filter substructure match atom indices by atom map indices corresponding to
 456     atom map numbers.
 457     """
 458     
 459     if AtomMapIndices is None:
 460         return list(AtomIndices)
 461                                                
 462     return [AtomIndices[Index] for Index in AtomMapIndices]
 463 
 464 def _GetMolFromAtomIndices(Mol, AtomIndices):
 465     """Generate a RDKit molecule object from atom indices returned by
 466    substructure search.
 467     """
 468 
 469     BondIndices = []
 470     for AtomIndex in AtomIndices:
 471         Atom = Mol.GetAtomWithIdx(AtomIndex)
 472         
 473         for AtomNbr in Atom.GetNeighbors():
 474             AtomNbrIndex = AtomNbr.GetIdx()
 475             if AtomNbrIndex not in AtomIndices:
 476                 continue
 477             
 478             BondIndex = Mol.GetBondBetweenAtoms(AtomIndex, AtomNbrIndex).GetIdx()
 479             if BondIndex in BondIndices:
 480                 continue
 481                 
 482             BondIndices.append(BondIndex)
 483             
 484     MatchedMol = Chem.PathToSubmol(Mol, BondIndices) if len(BondIndices) else None
 485     
 486     return MatchedMol
 487 
 488 
 489 def ReadAndValidateMolecules(FileName, **KeyWordArgs):
 490     """Read molecules from an input file, validate all molecule objects, and return
 491     a list of valid and non-valid molecule objects along with their counts.
 492     
 493     Arguments:
 494         FileName (str): Name of a file with complete path.
 495         **KeyWordArgs (dictionary) : Parameter name and value pairs for reading and
 496             processing molecules.
 497 
 498     Returns:
 499         list : List of valid RDKit molecule objects.
 500         int : Number of total molecules in input file. 
 501         int : Number of valid molecules in input file. 
 502 
 503     Notes:
 504         The file extension is used to determine type of the file and set up an appropriate
 505         file reader.
 506 
 507     """
 508 
 509     AllowEmptyMols = True
 510     if "AllowEmptyMols" in KeyWordArgs:
 511         AllowEmptyMols = KeyWordArgs["AllowEmptyMols"]
 512     
 513     Mols = ReadMolecules(FileName, **KeyWordArgs)
 514 
 515     if AllowEmptyMols:
 516         ValidMols = [Mol for Mol in Mols if Mol is not None]
 517     else:
 518         ValidMols = []
 519         MolCount = 0
 520         for Mol in Mols:
 521             MolCount += 1
 522             if Mol is None:
 523                 continue
 524             
 525             if IsMolEmpty(Mol):
 526                 MolName = GetMolName(Mol, MolCount)
 527                 MiscUtil.PrintWarning("Ignoring empty molecule: %s" % MolName)
 528                 continue
 529             
 530             ValidMols.append(Mol)
 531             
 532     MolCount = len(Mols)
 533     ValidMolCount = len(ValidMols)
 534 
 535     return (ValidMols, MolCount, ValidMolCount)
 536 
 537 def ReadMolecules(FileName, **KeyWordArgs):
 538     """Read molecules from an input file without performing any validation
 539     and creation of molecule objects.
 540     
 541     Arguments:
 542         FileName (str): Name of a file with complete path.
 543         **KeyWordArgs (dictionary) : Parameter name and value pairs for reading and
 544             processing molecules.
 545 
 546     Returns:
 547         list : List of RDKit molecule objects.
 548 
 549     Notes:
 550         The file extension is used to determine type of the file and set up an appropriate
 551         file reader.
 552 
 553     """
 554 
 555     # Set default values for possible arguments...
 556     ReaderArgs = {"Sanitize": True, "RemoveHydrogens": True, "StrictParsing": True,  "SMILESDelimiter" : ' ', "SMILESColumn": 1, "SMILESNameColumn": 2, "SMILESTitleLine": True }
 557 
 558     # Set specified values for possible arguments...
 559     for Arg in ReaderArgs:
 560         if Arg in KeyWordArgs:
 561             ReaderArgs[Arg] = KeyWordArgs[Arg]
 562 
 563     # Modify specific valeus for SMILES...
 564     if MiscUtil.CheckFileExt(FileName, "smi csv tsv txt"):
 565         Args = ["Sanitize", "SMILESTitleLine"]
 566         for Arg in Args:
 567             if ReaderArgs[Arg] is True:
 568                 ReaderArgs[Arg] = 1
 569             else:
 570                 ReaderArgs[Arg] = 0
 571     
 572     Mols = []
 573     if MiscUtil.CheckFileExt(FileName, "sdf sd"):
 574         return ReadMoleculesFromSDFile(FileName, ReaderArgs["Sanitize"], ReaderArgs["RemoveHydrogens"], ReaderArgs['StrictParsing'])
 575     elif MiscUtil.CheckFileExt(FileName, "mol"):
 576         return ReadMoleculesFromMolFile(FileName, ReaderArgs["Sanitize"], ReaderArgs["RemoveHydrogens"], ReaderArgs['StrictParsing'])
 577     elif MiscUtil.CheckFileExt(FileName, "mol2"):
 578         return ReadMoleculesFromMol2File(FileName, ReaderArgs["Sanitize"], ReaderArgs["RemoveHydrogens"])
 579     elif MiscUtil.CheckFileExt(FileName, "pdb"):
 580         return ReadMoleculesFromPDBFile(FileName, ReaderArgs["Sanitize"], ReaderArgs["RemoveHydrogens"])
 581     elif MiscUtil.CheckFileExt(FileName, "smi txt csv tsv"):
 582         SMILESColumnIndex = ReaderArgs["SMILESColumn"] - 1
 583         SMILESNameColumnIndex = ReaderArgs["SMILESNameColumn"] - 1
 584         return ReadMoleculesFromSMILESFile(FileName, ReaderArgs["SMILESDelimiter"], SMILESColumnIndex, SMILESNameColumnIndex, ReaderArgs["SMILESTitleLine"], ReaderArgs["Sanitize"])
 585     else:
 586         MiscUtil.PrintWarning("RDKitUtil.ReadMolecules: Non supported file type: %s" % FileName)
 587     
 588     return Mols
 589 
 590 def ReadMoleculesFromSDFile(FileName, Sanitize = True, RemoveHydrogens = True, StrictParsing = True):
 591     """Read molecules from a SD file.
 592     
 593     Arguments:
 594         FileName (str): Name of a file with complete path.
 595         Sanitize (bool): Sanitize molecules.
 596         RemoveHydrogens (bool): Remove hydrogens from molecules.
 597         StrictParsing (bool): Perform strict parsing.
 598 
 599     Returns:
 600         list : List of RDKit molecule objects.
 601 
 602     """
 603     return  Chem.SDMolSupplier(FileName, sanitize = Sanitize, removeHs = RemoveHydrogens, strictParsing = StrictParsing)
 604 
 605 def ReadMoleculesFromMolFile(FileName, Sanitize = True, RemoveHydrogens = True, StrictParsing = True):
 606     """Read molecule from a MDL Mol file.
 607     
 608     Arguments:
 609         FileName (str): Name of a file with complete path.
 610         Sanitize (bool): Sanitize molecules.
 611         RemoveHydrogens (bool): Remove hydrogens from molecules.
 612         StrictParsing (bool): Perform strict parsing.
 613 
 614     Returns:
 615         list : List of RDKit molecule objects.
 616 
 617     """
 618     
 619     Mols = []
 620     Mols.append(Chem.MolFromMolFile(FileName, sanitize = Sanitize, removeHs = RemoveHydrogens, strictParsing = StrictParsing))
 621     return Mols
 622 
 623 def ReadMoleculesFromMol2File(FileName, Sanitize = True, RemoveHydrogens = True):
 624     """Read molecule from a Tripos Mol2  file.
 625     
 626     Arguments:
 627         FileName (str): Name of a file with complete path.
 628         Sanitize (bool): Sanitize molecules.
 629         RemoveHydrogens (bool): Remove hydrogens from molecules.
 630 
 631     Returns:
 632         list : List of RDKit molecule objects.
 633 
 634     """
 635     
 636     Mols = []
 637     Mols.append(Chem.MolFromMol2File(FileName,  sanitize = Sanitize, removeHs = RemoveHydrogens))
 638     return Mols
 639 
 640 def ReadMoleculesFromPDBFile(FileName, Sanitize = True, RemoveHydrogens = True):
 641     """Read molecule from a PDB  file.
 642     
 643     Arguments:
 644         FileName (str): Name of a file with complete path.
 645         Sanitize (bool): Sanitize molecules.
 646         RemoveHydrogens (bool): Remove hydrogens from molecules.
 647 
 648     Returns:
 649         list : List of RDKit molecule objects.
 650 
 651     """
 652     
 653     Mols = []
 654     Mols.append(Chem.MolFromPDBFile(FileName,  sanitize = Sanitize, removeHs = RemoveHydrogens))
 655     return Mols
 656 
 657 def ReadMoleculesFromSMILESFile(FileName, SMILESDelimiter = ' ', SMILESColIndex = 0, SMILESNameColIndex = 1, SMILESTitleLine = 1, Sanitize = 1):
 658     """Read molecules from a SMILES file.
 659     
 660     Arguments:
 661         SMILESDelimiter (str): Delimiter for parsing SMILES line
 662         SMILESColIndex (int): Column index containing SMILES string.
 663         SMILESNameColIndex (int): Column index containing molecule name.
 664         SMILESTitleLine (int): Flag to indicate presence of title line.
 665         Sanitize (int): Sanitize molecules.
 666 
 667     Returns:
 668         list : List of RDKit molecule objects.
 669 
 670     """
 671     
 672     return  Chem.SmilesMolSupplier(FileName, delimiter = SMILESDelimiter, smilesColumn = SMILESColIndex, nameColumn = SMILESNameColIndex, titleLine = SMILESTitleLine, sanitize = Sanitize)
 673 
 674 def MoleculesWriter(FileName, **KeyWordArgs):
 675     """Set up a molecule writer.
 676     
 677     Arguments:
 678         FileName (str): Name of a file with complete path.
 679         **KeyWordArgs (dictionary) : Parameter name and value pairs for writing and
 680             processing molecules.
 681 
 682     Returns:
 683         RDKit object : Molecule writer.
 684 
 685     Notes:
 686         The file extension is used to determine type of the file and set up an appropriate
 687         file writer.
 688 
 689     """
 690     
 691     # Set default values for possible arguments...
 692     WriterArgs = {"Compute2DCoords" : False, "Kekulize": False, "SMILESDelimiter" : ' ', "SMILESIsomeric": True, "SMILESTitleLine": True, "SMILESMolName": True}
 693 
 694     # Set specified values for possible arguments...
 695     for Arg in WriterArgs:
 696         if Arg in KeyWordArgs:
 697             WriterArgs[Arg] = KeyWordArgs[Arg]
 698     
 699     Writer = None
 700     if MiscUtil.CheckFileExt(FileName, "sdf sd"):
 701         Writer = Chem.SDWriter(FileName)
 702         if WriterArgs["Kekulize"]:
 703             Writer.SetKekulize(True)
 704     elif MiscUtil.CheckFileExt(FileName, "pdb"):
 705         Writer = Chem.PDBWriter(FileName)
 706     elif MiscUtil.CheckFileExt(FileName, "smi"):
 707         # Text for the name column in the title line. Blank indicates not to include name column
 708         # in the output file...
 709         NameHeader = 'Name' if WriterArgs["SMILESMolName"] else ''
 710         Writer = Chem.SmilesWriter(FileName, delimiter = WriterArgs["SMILESDelimiter"], nameHeader = NameHeader, includeHeader = WriterArgs["SMILESTitleLine"],  isomericSmiles = WriterArgs["SMILESIsomeric"], kekuleSmiles = WriterArgs["Kekulize"])
 711     else:
 712         MiscUtil.PrintWarning("RDKitUtil.WriteMolecules: Non supported file type: %s" % FileName)
 713     
 714     return Writer
 715     
 716 def WriteMolecules(FileName, Mols, **KeyWordArgs):
 717     """Write molecules to an output file.
 718     
 719     Arguments:
 720         FileName (str): Name of a file with complete path.
 721         Mols (list): List of RDKit molecule objects. 
 722         **KeyWordArgs (dictionary) : Parameter name and value pairs for writing and
 723             processing molecules.
 724 
 725     Returns:
 726         int : Number of total molecules.
 727         int : Number of processed molecules written to output file.
 728 
 729     Notes:
 730         The file extension is used to determine type of the file and set up an appropriate
 731         file writer.
 732 
 733     """
 734     
 735     Compute2DCoords = False
 736     if "Compute2DCoords" in KeyWordArgs:
 737         Compute2DCoords = KeyWordArgs["Compute2DCoords"]
 738     
 739     SetSMILESMolProps = KeyWordArgs["SetSMILESMolProps"] if "SetSMILESMolProps" in KeyWordArgs else False
 740         
 741     MolCount = len(Mols)
 742     ProcessedMolCount = 0
 743     
 744     Writer = MoleculesWriter(FileName, **KeyWordArgs)
 745     
 746     if Writer is None:
 747         return (MolCount, ProcessedMolCount)
 748     
 749     FirstMol = True
 750     for Mol in Mols:
 751         if Mol is None:
 752             continue
 753 
 754         if FirstMol:
 755             FirstMol = False
 756             if SetSMILESMolProps:
 757                 SetWriterMolProps(Writer, Mol)
 758                 
 759         ProcessedMolCount += 1
 760         if Compute2DCoords:
 761             AllChem.Compute2DCoords(Mol)
 762         
 763         Writer.write(Mol)
 764     
 765     Writer.close()
 766     
 767     return (MolCount, ProcessedMolCount)
 768 
 769 def SetWriterMolProps(Writer, Mol):
 770     """Setup molecule properties for a writer to output.
 771     
 772     Arguments:
 773         Writer (object): RDKit writer object.
 774         Mol (object): RDKit molecule object.
 775 
 776     Returns:
 777         object : Writer object.
 778 
 779     """
 780     PropNames = list(Mol.GetPropNames())
 781     if len(PropNames):
 782         Writer.SetProps(PropNames)
 783         
 784     return Writer
 785