MayaChemTools

   1 #!/bin/env python
   2 #
   3 # File: RDKitGenerateConformers.py
   4 # Author: Manish Sud <msud@san.rr.com>
   5 #
   6 # Copyright (C) 2020 Manish Sud. All rights reserved.
   7 #
   8 # The functionality available in this script is implemented using RDKit, an
   9 # open source toolkit for cheminformatics developed by Greg Landrum.
  10 #
  11 # This file is part of MayaChemTools.
  12 #
  13 # MayaChemTools is free software; you can redistribute it and/or modify it under
  14 # the terms of the GNU Lesser General Public License as published by the Free
  15 # Software Foundation; either version 3 of the License, or (at your option) any
  16 # later version.
  17 #
  18 # MayaChemTools is distributed in the hope that it will be useful, but without
  19 # any warranty; without even the implied warranty of merchantability of fitness
  20 # for a particular purpose.  See the GNU Lesser General Public License for more
  21 # details.
  22 #
  23 # You should have received a copy of the GNU Lesser General Public License
  24 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or
  25 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330,
  26 # Boston, MA, 02111-1307, USA.
  27 #
  28 
  29 from __future__ import print_function
  30 
  31 # Add local python path to the global path and import standard library modules...
  32 import os
  33 import sys;  sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), "..", "lib", "Python"))
  34 import time
  35 import re
  36 import multiprocessing as mp
  37 
  38 # RDKit imports...
  39 try:
  40     from rdkit import rdBase
  41     from rdkit import Chem
  42     from rdkit.Chem import AllChem
  43     from rdkit.Chem import Descriptors
  44 except ImportError as ErrMsg:
  45     sys.stderr.write("\nFailed to import RDKit module/package: %s\n" % ErrMsg)
  46     sys.stderr.write("Check/update your RDKit environment and try again.\n\n")
  47     sys.exit(1)
  48 
  49 # MayaChemTools imports...
  50 try:
  51     from docopt import docopt
  52     import MiscUtil
  53     import RDKitUtil
  54 except ImportError as ErrMsg:
  55     sys.stderr.write("\nFailed to import MayaChemTools module/package: %s\n" % ErrMsg)
  56     sys.stderr.write("Check/update your MayaChemTools environment and try again.\n\n")
  57     sys.exit(1)
  58 
  59 ScriptName = os.path.basename(sys.argv[0])
  60 Options = {}
  61 OptionsInfo = {}
  62 
  63 def main():
  64     """Start execution of the script"""
  65     
  66     MiscUtil.PrintInfo("\n%s (RDK v%s; %s): Starting...\n" % (ScriptName, rdBase.rdkitVersion, time.asctime()))
  67     
  68     (WallClockTime, ProcessorTime) = MiscUtil.GetWallClockAndProcessorTime()
  69     
  70     # Retrieve command line arguments and options...
  71     RetrieveOptions()
  72     
  73     # Process and validate command line arguments and options...
  74     ProcessOptions()
  75     
  76     # Perform actions required by the script...
  77     GenerateConformers()
  78     
  79     MiscUtil.PrintInfo("\n%s: Done...\n" % ScriptName)
  80     MiscUtil.PrintInfo("Total time: %s" % MiscUtil.GetFormattedElapsedTime(WallClockTime, ProcessorTime))
  81 
  82 def GenerateConformers():
  83     """Generate conformers."""
  84     
  85     # Setup a molecule reader...
  86     MiscUtil.PrintInfo("\nProcessing file %s..." % OptionsInfo["Infile"])
  87     Mols  = RDKitUtil.ReadMolecules(OptionsInfo["Infile"], **OptionsInfo["InfileParams"])
  88     
  89     # Set up a molecule writer...
  90     Writer = RDKitUtil.MoleculesWriter(OptionsInfo["Outfile"], **OptionsInfo["OutfileParams"])
  91     if Writer is None:
  92         MiscUtil.PrintError("Failed to setup a writer for output fie %s " % OptionsInfo["Outfile"])
  93     MiscUtil.PrintInfo("Generating file %s..." % OptionsInfo["Outfile"])
  94 
  95     MolCount, ValidMolCount, ConfGenFailedCount = ProcessMolecules(Mols, Writer)
  96 
  97     if Writer is not None:
  98         Writer.close()
  99     
 100     MiscUtil.PrintInfo("\nTotal number of molecules: %d" % MolCount)
 101     MiscUtil.PrintInfo("Number of valid molecules: %d" % ValidMolCount)
 102     MiscUtil.PrintInfo("Number of molecules failed during conformation generation or minimization: %d" % ConfGenFailedCount)
 103     MiscUtil.PrintInfo("Number of ignored molecules: %d" % (MolCount - ValidMolCount + ConfGenFailedCount))
 104 
 105 def ProcessMolecules(Mols, Writer):
 106     """Process molecules to generate conformers."""
 107     
 108     if OptionsInfo["MPMode"]:
 109         return ProcessMoleculesUsingMultipleProcesses(Mols, Writer)
 110     else:
 111         return ProcessMoleculesUsingSingleProcess(Mols, Writer)
 112 
 113 def ProcessMoleculesUsingSingleProcess(Mols, Writer):
 114     """Process molecules to generate conformers using a single process."""
 115     
 116     if OptionsInfo["SkipForceFieldMinimization"]:
 117         MiscUtil.PrintInfo("\nGenerating conformers without performing energy minimization...")
 118     else:
 119         MiscUtil.PrintInfo("\nGenerating conformers and performing energy minimization...")
 120     
 121     (MolCount, ValidMolCount, ConfGenFailedCount) = [0] * 3
 122     for Mol in Mols:
 123         MolCount += 1
 124         
 125         if Mol is None:
 126             continue
 127         
 128         if RDKitUtil.IsMolEmpty(Mol):
 129             if not OptionsInfo["QuietMode"]:
 130                 MolName = RDKitUtil.GetMolName(Mol, MolCount)
 131                 MiscUtil.PrintWarning("Ignoring empty molecule: %s" % MolName)
 132             continue
 133         ValidMolCount += 1
 134 
 135         ConformerMol, CalcStatus, ConfIDs, ConfEnergies = GenerateMolConformers(Mol, MolCount)
 136         
 137         if not CalcStatus:
 138             ConfGenFailedCount += 1
 139             continue
 140         
 141         WriteMolConformers(Writer, ConformerMol, MolCount, ConfIDs, ConfEnergies)
 142     
 143     return (MolCount, ValidMolCount, ConfGenFailedCount)
 144 
 145 def ProcessMoleculesUsingMultipleProcesses(Mols, Writer):
 146     """Process and minimize molecules using multiprocessing."""
 147     
 148     if OptionsInfo["SkipForceFieldMinimization"]:
 149         MiscUtil.PrintInfo("\nGenerating conformers without performing energy minimization using multiprocessing...")
 150     else:
 151         MiscUtil.PrintInfo("\nGenerating conformers and performing energy minimization using multiprocessing...")
 152     
 153     MPParams = OptionsInfo["MPParams"]
 154     
 155     # Setup data for initializing a worker process...
 156     InitializeWorkerProcessArgs = (MiscUtil.ObjectToBase64EncodedString(Options), MiscUtil.ObjectToBase64EncodedString(OptionsInfo))
 157     
 158     # Setup a encoded mols data iterable for a worker process...
 159     WorkerProcessDataIterable = RDKitUtil.GenerateBase64EncodedMolStrings(Mols)
 160 
 161     # Setup process pool along with data initialization for each process...
 162     MiscUtil.PrintInfo("\nConfiguring multiprocessing using %s method..." % ("mp.Pool.imap()" if re.match("^Lazy$", MPParams["InputDataMode"], re.I) else "mp.Pool.map()"))
 163     MiscUtil.PrintInfo("NumProcesses: %s; InputDataMode: %s; ChunkSize: %s\n" % (MPParams["NumProcesses"], MPParams["InputDataMode"], ("automatic" if MPParams["ChunkSize"] is None else MPParams["ChunkSize"])))
 164     
 165     ProcessPool = mp.Pool(MPParams["NumProcesses"], InitializeWorkerProcess, InitializeWorkerProcessArgs)
 166     
 167     # Start processing...
 168     if re.match("^Lazy$", MPParams["InputDataMode"], re.I):
 169         Results = ProcessPool.imap(WorkerProcess, WorkerProcessDataIterable, MPParams["ChunkSize"])
 170     elif re.match("^InMemory$", MPParams["InputDataMode"], re.I):
 171         Results = ProcessPool.map(WorkerProcess, WorkerProcessDataIterable, MPParams["ChunkSize"])
 172     else:
 173         MiscUtil.PrintError("The value, %s, specified for \"--inputDataMode\" is not supported." % (MPParams["InputDataMode"]))
 174     
 175     (MolCount, ValidMolCount, ConfGenFailedCount) = [0] * 3
 176     for Result in Results:
 177         MolCount += 1
 178         MolIndex, EncodedMol, CalcStatus, ConfIDs, ConfEnergies = Result
 179         
 180         if EncodedMol is None:
 181             continue
 182         ValidMolCount += 1
 183         
 184         if not CalcStatus:
 185             ConfGenFailedCount += 1
 186             continue
 187             
 188         Mol = RDKitUtil.MolFromBase64EncodedMolString(EncodedMol)
 189         WriteMolConformers(Writer, Mol, MolCount, ConfIDs, ConfEnergies)
 190     
 191     return (MolCount, ValidMolCount, ConfGenFailedCount)
 192 
 193 def InitializeWorkerProcess(*EncodedArgs):
 194     """Initialize data for a worker process."""
 195     
 196     global Options, OptionsInfo
 197 
 198     MiscUtil.PrintInfo("Starting process (PID: %s)..." % os.getpid())
 199     
 200     # Decode Options and OptionInfo...
 201     Options = MiscUtil.ObjectFromBase64EncodedString(EncodedArgs[0])
 202     OptionsInfo = MiscUtil.ObjectFromBase64EncodedString(EncodedArgs[1])
 203     
 204 def WorkerProcess(EncodedMolInfo):
 205     """Process data for a worker process."""
 206 
 207     MolIndex, EncodedMol = EncodedMolInfo
 208     
 209     CalcStatus = False
 210     ConfIDs = None
 211     ConfEnergies = None
 212     
 213     if EncodedMol is None:
 214         return [MolIndex, None, CalcStatus, ConfIDs, ConfEnergies]
 215 
 216     Mol = RDKitUtil.MolFromBase64EncodedMolString(EncodedMol)
 217     if RDKitUtil.IsMolEmpty(Mol):
 218         if not OptionsInfo["QuietMode"]:
 219             MolName = RDKitUtil.GetMolName(Mol, (MolIndex + 1))
 220             MiscUtil.PrintWarning("Ignoring empty molecule: %s" % MolName)
 221         return [MolIndex, None, CalcStatus, ConfIDs, ConfEnergies]
 222     
 223     Mol, CalcStatus, ConfIDs, ConfEnergies = GenerateMolConformers(Mol, (MolIndex + 1))
 224 
 225     return [MolIndex, RDKitUtil.MolToBase64EncodedMolString(Mol, PropertyPickleFlags = Chem.PropertyPickleOptions.MolProps | Chem.PropertyPickleOptions.PrivateProps), CalcStatus, ConfIDs, ConfEnergies]
 226 
 227 def GenerateMolConformers(Mol, MolNum = None):
 228     "Generate conformers for a molecule"
 229     
 230     if OptionsInfo["SkipForceFieldMinimization"]:
 231         return GenerateMolConformersWithoutMinimization(Mol, MolNum)
 232     else:
 233         return GenerateMolConformersWithMinimization(Mol, MolNum)
 234 
 235 def GenerateMolConformersWithoutMinimization(Mol, MolNum = None):
 236     "Generate conformers for a molecule without performing minimization."
 237     
 238     ConfIDs = EmbedMolecule(Mol, MolNum)
 239     if not len(ConfIDs):
 240         if not OptionsInfo["QuietMode"]:
 241             MolName = RDKitUtil.GetMolName(Mol, MolNum)
 242             MiscUtil.PrintWarning("Conformation generation couldn't be performed for molecule %s: Embedding failed...\n" % MolName)
 243         return [Mol, False, None, None]
 244     
 245     if OptionsInfo["AlignConformers"]:
 246         AllChem.AlignMolConformers(Mol)
 247     
 248     if not OptionsInfo["QuietMode"]:
 249         MolName = RDKitUtil.GetMolName(Mol, MolNum)
 250         MiscUtil.PrintInfo("\nNumber of conformations generated for %s: %d" % (MolName, len(ConfIDs)))
 251 
 252     # Convert ConfIDs into a list...
 253     ConfIDsList = [ConfID for ConfID in ConfIDs]
 254 
 255     # Setup conformation energies...
 256     ConfEnergies = None
 257     if OptionsInfo["EnergyOut"]:
 258         ConfEnergies = []
 259         for ConfID in ConfIDsList:
 260             EnergyStatus, Energy = GetConformerEnergy(Mol, ConfID)
 261             
 262             Energy = "%.2f" % Energy if EnergyStatus else "NotAvailable"
 263             ConfEnergies.append(Energy)
 264             
 265             if not EnergyStatus:
 266                 if not OptionsInfo["QuietMode"]:
 267                     MolName = RDKitUtil.GetMolName(Mol, MolNum)
 268                     MiscUtil.PrintWarning("Failed to retrieve calculated energy for conformation number %d of molecule %s. Try again after removing any salts or cleaing up the molecule...\n" % (ConfID, MolName))
 269     
 270     return [Mol, True, ConfIDsList, ConfEnergies]
 271 
 272 def GenerateMolConformersWithMinimization(Mol, MolNum):
 273     "Generate and mininize conformers for a molecule."
 274     
 275     if  OptionsInfo["AddHydrogens"]:
 276         Mol = Chem.AddHs(Mol)
 277     
 278     ConfIDs = EmbedMolecule(Mol, MolNum)
 279     if not len(ConfIDs):
 280         if not OptionsInfo["QuietMode"]:
 281             MolName = RDKitUtil.GetMolName(Mol, MolNum)
 282             MiscUtil.PrintWarning("Conformation generation couldn't be performed for molecule %s: Embedding failed...\n" % MolName)
 283         return [Mol, False, None, None]
 284 
 285     CalcEnergyMap = {}
 286     for ConfID in ConfIDs:
 287         try:
 288             if OptionsInfo["UseUFF"]:
 289                 Status = AllChem.UFFOptimizeMolecule(Mol, confId = ConfID, maxIters = OptionsInfo["MaxIters"])
 290             elif OptionsInfo["UseMMFF"]:
 291                 Status = AllChem.MMFFOptimizeMolecule(Mol, confId = ConfID, maxIters = OptionsInfo["MaxIters"], mmffVariant = OptionsInfo["MMFFVariant"])
 292             else:
 293                 MiscUtil.PrintError("Minimization couldn't be performed: Specified forcefield, %s, is not supported" % OptionsInfo["ForceField"])
 294         except (RuntimeError, Chem.rdchem.KekulizeException) as ErrMsg:
 295             if not OptionsInfo["QuietMode"]:
 296                 MolName = RDKitUtil.GetMolName(Mol, MolNum)
 297                 MiscUtil.PrintWarning("Minimization couldn't be performed for molecule %s:\n%s\n" % (MolName, ErrMsg))
 298             return [Mol, False, None, None]
 299         
 300         EnergyStatus, Energy = GetConformerEnergy(Mol, ConfID)
 301         if not EnergyStatus:
 302             if not OptionsInfo["QuietMode"]:
 303                 MolName = RDKitUtil.GetMolName(Mol, MolNum)
 304                 MiscUtil.PrintWarning("Failed to retrieve calculated energy for conformation number %d of molecule %s. Try again after removing any salts or cleaing up the molecule...\n" % (ConfID, MolName))
 305             return [Mol, False, None, None]
 306         
 307         if Status != 0:
 308             if not OptionsInfo["QuietMode"]:
 309                 MolName = RDKitUtil.GetMolName(Mol, MolNum)
 310                 MiscUtil.PrintWarning("Minimization failed to converge for conformation number %d of molecule %s in %d steps. Try using higher value for \"--maxIters\" option...\n" % (ConfID, MolName, OptionsInfo["MaxIters"]))
 311             
 312         CalcEnergyMap[ConfID] = Energy
 313 
 314     if  OptionsInfo["RemoveHydrogens"]:
 315         Mol = Chem.RemoveHs(Mol)
 316 
 317     # Align molecules after minimization...
 318     if OptionsInfo["AlignConformers"]:
 319         AllChem.AlignMolConformers(Mol)
 320     
 321     SortedConfIDs = sorted(ConfIDs, key = lambda ConfID: CalcEnergyMap[ConfID])
 322     
 323     MinEnergyConfID = SortedConfIDs[0]
 324     MinConfEnergy = CalcEnergyMap[MinEnergyConfID]
 325     EnergyWindow = OptionsInfo["EnergyWindow"]
 326 
 327     EnergyRMSDCutoff = OptionsInfo["EnergyRMSDCutoff"]
 328     ApplyEnergyRMSDCutoff = False
 329     if EnergyRMSDCutoff > 0:
 330         ApplyEnergyRMSDCutoff = True
 331 
 332     # Calculate RMSD values for conformers...
 333     PreAligned = False
 334     if OptionsInfo["AlignConformers"]:
 335         PreAligned = True
 336     
 337     CalcRMSDMap = {}
 338     if ApplyEnergyRMSDCutoff:
 339         for ConfID in SortedConfIDs:
 340             RMSD = AllChem.GetConformerRMS(Mol, MinEnergyConfID, ConfID, prealigned=PreAligned)
 341             CalcRMSDMap[ConfID] = RMSD
 342     
 343     # Track conformers with in the specified energy window  from the lowest
 344     # energy conformation along with applying RMSD cutoff as needed...
 345     #
 346     SelectedConfIDs = []
 347     
 348     ConfCount = 0
 349     IgnoredByEnergyConfCount = 0
 350     IgnoredByRMSDConfCount = 0
 351     
 352     FirstConf = True
 353     
 354     for ConfID in SortedConfIDs:
 355         if FirstConf:
 356             FirstConf = False
 357             SelectedConfIDs.append(ConfID)
 358             continue
 359             
 360         ConfEnergyDiff = abs(CalcEnergyMap[ConfID] - MinConfEnergy )
 361         if  ConfEnergyDiff > EnergyWindow:
 362             IgnoredByEnergyConfCount += 1
 363             continue
 364         
 365         if ApplyEnergyRMSDCutoff:
 366             if CalcRMSDMap[ConfID] < EnergyRMSDCutoff:
 367                 IgnoredByRMSDConfCount += 1
 368                 continue
 369 
 370         ConfCount += 1
 371         SelectedConfIDs.append(ConfID)
 372     
 373     if not OptionsInfo["QuietMode"]:
 374         MolName = RDKitUtil.GetMolName(Mol, MolNum)
 375         MiscUtil.PrintInfo("\nTotal Number of conformations generated for %s: %d" % (MolName, ConfCount))
 376         MiscUtil.PrintInfo("Number of conformations ignored due to energy window cutoff: %d" % (IgnoredByEnergyConfCount))
 377         if ApplyEnergyRMSDCutoff:
 378             MiscUtil.PrintInfo("Number of conformations ignored due to energy RMSD cutoff:  %d" % (IgnoredByRMSDConfCount))
 379 
 380     SelectedConfEnergies = None
 381     if OptionsInfo["EnergyOut"]:
 382         SelectedConfEnergies = ["%.2f" % CalcEnergyMap[ConfID] for ConfID in SelectedConfIDs]
 383         
 384     return [Mol, True, SelectedConfIDs, SelectedConfEnergies]
 385     
 386 def GetConformerEnergy(Mol, ConfID):
 387     "Calculate conformer energy"
 388 
 389     Status = True
 390     Energy = 0.0
 391     
 392     if OptionsInfo["UseUFF"]:
 393         UFFMoleculeForcefield = AllChem.UFFGetMoleculeForceField(Mol, confId = ConfID)
 394         if UFFMoleculeForcefield is None:
 395             Status = False
 396         else:
 397             Energy = UFFMoleculeForcefield.CalcEnergy()
 398     elif OptionsInfo["UseMMFF"]:
 399         MMFFMoleculeProperties = AllChem.MMFFGetMoleculeProperties(Mol, mmffVariant = OptionsInfo["MMFFVariant"])
 400         MMFFMoleculeForcefield = AllChem.MMFFGetMoleculeForceField(Mol, MMFFMoleculeProperties, confId = ConfID)
 401         if MMFFMoleculeForcefield is None:
 402             Status = False
 403         else:
 404             Energy = MMFFMoleculeForcefield.CalcEnergy()
 405     else:
 406         MiscUtil.PrintError("Couldn't retrieve conformer energy: Specified forcefield, %s, is not supported" % OptionsInfo["ForceField"])
 407 
 408     return (Status, Energy)
 409     
 410 def EmbedMolecule(Mol, MolNum = None):
 411     "Embed conformations"
 412     
 413     ConfIDs = []
 414     
 415     # Figure out the number of conformations to embded...
 416     if re.match("^Auto$", OptionsInfo["MaxConfs"], re.I):
 417         NumOfRotBonds = Descriptors.NumRotatableBonds(Mol)
 418         if NumOfRotBonds <= 5:
 419             MaxConfs = 100
 420         elif NumOfRotBonds >=6 and NumOfRotBonds <= 10:
 421             MaxConfs = 200
 422         else:
 423             MaxConfs = 300
 424     else:
 425         MaxConfs = int(OptionsInfo["MaxConfs"])
 426         
 427     RandomSeed = OptionsInfo["RandomSeed"]
 428     EnforceChirality = OptionsInfo["EnforceChirality"]
 429     UseExpTorsionAnglePrefs = OptionsInfo["UseExpTorsionAnglePrefs"]
 430     UseBasicKnowledge = OptionsInfo["UseBasicKnowledge"]
 431     EmbedRMSDCutoff = OptionsInfo["EmbedRMSDCutoff"]
 432     
 433     try:
 434         ConfIDs = AllChem.EmbedMultipleConfs(Mol, numConfs = MaxConfs, randomSeed = RandomSeed, pruneRmsThresh = EmbedRMSDCutoff, enforceChirality = EnforceChirality, useExpTorsionAnglePrefs = UseExpTorsionAnglePrefs, useBasicKnowledge = UseBasicKnowledge)
 435     except ValueError as ErrMsg:
 436         if not OptionsInfo["QuietMode"]:
 437             MolName = RDKitUtil.GetMolName(Mol, MolNum)
 438             MiscUtil.PrintWarning("Embedding failed  for molecule %s:\n%s\n" % (MolName, ErrMsg))
 439         ConfIDs = []
 440 
 441     return ConfIDs
 442 
 443 def WriteMolConformers(Writer, Mol, MolNum, ConfIDs, ConfEnergies = None):
 444     """Write molecule coformers. """
 445 
 446     if ConfIDs is None:
 447         return
 448     
 449     MolName = RDKitUtil.GetMolName(Mol, MolNum)
 450 
 451     for Index, ConfID in enumerate(ConfIDs):
 452         SetConfMolName(Mol, MolName, ConfID)
 453         
 454         if ConfEnergies is not None:
 455             Mol.SetProp(OptionsInfo["EnergyLabel"], ConfEnergies[Index])
 456             
 457         Writer.write(Mol, confId = ConfID)
 458     
 459 def SetConfMolName(Mol, MolName, ConfCount):
 460     """Set conf mol name"""
 461 
 462     ConfName = "%s_Conf%d" % (MolName, ConfCount)
 463     Mol.SetProp("_Name", ConfName)
 464 
 465 def ProcessOptions():
 466     """Process and validate command line arguments and options"""
 467     
 468     MiscUtil.PrintInfo("Processing options...")
 469     
 470     # Validate options...
 471     ValidateOptions()
 472     
 473     OptionsInfo["Infile"] = Options["--infile"]
 474     OptionsInfo["InfileParams"] = MiscUtil.ProcessOptionInfileParameters("--infileParams", Options["--infileParams"], Options["--infile"])
 475     
 476     OptionsInfo["Outfile"] = Options["--outfile"]
 477     OptionsInfo["OutfileParams"] = MiscUtil.ProcessOptionOutfileParameters("--outfileParams", Options["--outfileParams"])
 478     
 479     OptionsInfo["Overwrite"] = Options["--overwrite"]
 480 
 481     OptionsInfo["AddHydrogens"] = True
 482     if re.match("^no$", Options["--addHydrogens"], re.I):
 483         OptionsInfo["AddHydrogens"] = False
 484 
 485     OptionsInfo["AlignConformers"] = True
 486     if re.match("^no$", Options["--alignConformers"], re.I):
 487         OptionsInfo["AlignConformers"] = False
 488 
 489     if re.match("^ETDG$", Options["--conformerGenerator"], re.I):
 490         ConformerGenerator = "ETDG"
 491         UseExpTorsionAnglePrefs = True
 492         UseBasicKnowledge = False
 493     elif re.match("^KDG$", Options["--conformerGenerator"], re.I):
 494         ConformerGenerator = "KDG"
 495         UseExpTorsionAnglePrefs = False
 496         UseBasicKnowledge = True
 497     elif re.match("^ETKDG$", Options["--conformerGenerator"], re.I):
 498         ConformerGenerator = "ETKDG"
 499         UseExpTorsionAnglePrefs = True
 500         UseBasicKnowledge = True
 501     elif re.match("^SDG$", Options["--conformerGenerator"], re.I):
 502         ConformerGenerator = "SDG"
 503         UseExpTorsionAnglePrefs = False
 504         UseBasicKnowledge = False
 505     
 506     OptionsInfo["ConformerGenerator"] = ConformerGenerator
 507     OptionsInfo["UseExpTorsionAnglePrefs"] = UseExpTorsionAnglePrefs
 508     OptionsInfo["UseBasicKnowledge"] = UseBasicKnowledge
 509 
 510     if re.match("^UFF$", Options["--forceField"], re.I):
 511         ForceField = "UFF"
 512         UseUFF = True
 513         UseMMFF = False
 514         SkipForceFieldMinimization = False
 515     elif re.match("^MMFF$", Options["--forceField"], re.I):
 516         ForceField = "MMFF"
 517         UseUFF = False
 518         UseMMFF = True
 519         SkipForceFieldMinimization = False
 520     else:
 521         ForceField = "None"
 522         UseUFF = False
 523         UseMMFF = False
 524         SkipForceFieldMinimization = True
 525         
 526     MMFFVariant = "MMFF94" if re.match("^MMFF94$", Options["--forceFieldMMFFVariant"], re.I) else "MMFF94s"
 527     
 528     OptionsInfo["SkipForceFieldMinimization"] = SkipForceFieldMinimization
 529     OptionsInfo["ForceField"] = ForceField
 530     OptionsInfo["MMFFVariant"] = MMFFVariant
 531     OptionsInfo["UseMMFF"] = UseMMFF
 532     OptionsInfo["UseUFF"] = UseUFF
 533         
 534     OptionsInfo["EnergyOut"] = True if re.match("^yes$", Options["--energyOut"], re.I) else False
 535     if UseUFF:
 536         EnergyLabel = "UFF_Energy"
 537     elif UseMMFF:
 538         EnergyLabel = "%s_Energy" % MMFFVariant
 539     else:
 540         EnergyLabel = "Energy"
 541     OptionsInfo["EnergyLabel"] = EnergyLabel
 542     
 543     OptionsInfo["EnforceChirality"] = True
 544     if re.match("^no$", Options["--enforceChirality"], re.I):
 545         OptionsInfo["EnforceChirality"] = False
 546     
 547     OptionsInfo["EnergyWindow"] = float(Options["--energyWindow"])
 548     
 549     EmbedRMSDCutoff = -1.0
 550     if not re.match("^none$", Options["--embedRMSDCutoff"], re.I):
 551         EmbedRMSDCutoff = float(Options["--embedRMSDCutoff"])
 552     OptionsInfo["EmbedRMSDCutoff"] = EmbedRMSDCutoff
 553     
 554     EnergyRMSDCutoff = -1.0
 555     if not re.match("^none$", Options["--energyRMSDCutoff"], re.I):
 556         EnergyRMSDCutoff = float(Options["--energyRMSDCutoff"])
 557     OptionsInfo["EnergyRMSDCutoff"] = EnergyRMSDCutoff
 558     
 559     OptionsInfo["MaxIters"] = int(Options["--maxIters"])
 560     OptionsInfo["MaxConfs"] = Options["--maxConfs"]
 561     
 562     OptionsInfo["MPMode"] = True if re.match("^yes$", Options["--mp"], re.I) else False
 563     OptionsInfo["MPParams"] = MiscUtil.ProcessOptionMultiprocessingParameters("--mpParams", Options["--mpParams"])
 564     
 565     OptionsInfo["QuietMode"] = True if re.match("^yes$", Options["--quiet"], re.I) else False
 566     
 567     RandomSeed = -1
 568     if not re.match("^auto$", Options["--randomSeed"], re.I):
 569         RandomSeed = int(Options["--randomSeed"])
 570     OptionsInfo["RandomSeed"] = RandomSeed
 571     
 572     OptionsInfo["RemoveHydrogens"] = True
 573     if re.match("^no$", Options["--removeHydrogens"], re.I):
 574         OptionsInfo["RemoveHydrogens"] = False
 575     
 576 def RetrieveOptions():
 577     """Retrieve command line arguments and options"""
 578     
 579     # Get options...
 580     global Options
 581     Options = docopt(_docoptUsage_)
 582 
 583     # Set current working directory to the specified directory...
 584     WorkingDir = Options["--workingdir"]
 585     if WorkingDir:
 586         os.chdir(WorkingDir)
 587     
 588     # Handle examples option...
 589     if "--examples" in Options and Options["--examples"]:
 590         MiscUtil.PrintInfo(MiscUtil.GetExamplesTextFromDocOptText(_docoptUsage_))
 591         sys.exit(0)
 592 
 593 def ValidateOptions():
 594     """Validate option values"""
 595     
 596     MiscUtil.ValidateOptionTextValue("-a, --addHydrogens", Options["--addHydrogens"], "yes no")
 597     MiscUtil.ValidateOptionTextValue("--alignConformers", Options["--alignConformers"], "yes no")
 598     MiscUtil.ValidateOptionTextValue("-c, --conformerGenerator", Options["--conformerGenerator"], "SDG ETDG KDG ETKDG")
 599     
 600     MiscUtil.ValidateOptionTextValue("-f, --forceField", Options["--forceField"], "UFF MMFF None")
 601     MiscUtil.ValidateOptionTextValue(" --forceFieldMMFFVariant", Options["--forceFieldMMFFVariant"], "MMFF94 MMFF94s")
 602     
 603     MiscUtil.ValidateOptionTextValue("--energyOut", Options["--energyOut"], "yes no")
 604     MiscUtil.ValidateOptionTextValue("--enforceChirality ", Options["--enforceChirality"], "yes no")
 605     MiscUtil.ValidateOptionFloatValue("--energyWindow", Options["--energyWindow"], {">": 0.0})
 606     
 607     if not re.match("^none$", Options["--embedRMSDCutoff"], re.I):
 608         MiscUtil.ValidateOptionFloatValue("--embedRMSDCutoff", Options["--embedRMSDCutoff"], {">": 0.0})
 609     
 610     if not re.match("^none$", Options["--energyRMSDCutoff"], re.I):
 611         MiscUtil.ValidateOptionFloatValue("--energyRMSDCutoff", Options["--energyRMSDCutoff"], {">": 0.0})
 612         # Make sure that the alignConformers option is being used...
 613         if not re.match("^yes$", Options["--alignConformers"], re.I):
 614             MiscUtil.PrintError("%s value of \"--alignConformers\" is not allowed for %s value of \"--energyRMSDCutoff\" option " % (Options["--alignConformers"], Options["--energyRMSDCutoff"]))
 615         
 616     MiscUtil.ValidateOptionFilePath("-i, --infile", Options["--infile"])
 617     MiscUtil.ValidateOptionFileExt("-i, --infile", Options["--infile"], "sdf sd mol smi txt csv tsv")
 618     
 619     MiscUtil.ValidateOptionFileExt("-o, --outfile", Options["--outfile"], "sdf sd")
 620     MiscUtil.ValidateOptionsOutputFileOverwrite("-o, --outfile", Options["--outfile"], "--overwrite", Options["--overwrite"])
 621     MiscUtil.ValidateOptionsDistinctFileNames("-i, --infile", Options["--infile"], "-o, --outfile", Options["--outfile"])
 622         
 623     if not re.match("^auto$", Options["--maxConfs"], re.I):
 624         MiscUtil.ValidateOptionIntegerValue("--maxConfs", Options["--maxConfs"], {">": 0})
 625     
 626     MiscUtil.ValidateOptionIntegerValue("--maxIters", Options["--maxIters"], {">": 0})
 627     
 628     MiscUtil.ValidateOptionTextValue("--mp", Options["--mp"], "yes no")
 629     MiscUtil.ValidateOptionTextValue("-q, --quiet", Options["--quiet"], "yes no")
 630     
 631     if not re.match("^auto$", Options["--randomSeed"], re.I):
 632         MiscUtil.ValidateOptionIntegerValue("--randomSeed", Options["--randomSeed"], {})
 633         RandomSeed = int(Options["--randomSeed"])
 634     
 635     MiscUtil.ValidateOptionTextValue("-r, --removeHydrogens", Options["--removeHydrogens"], "yes no")
 636 
 637 # Setup a usage string for docopt...
 638 _docoptUsage_ = """
 639 RDKitGenerateConformers.py - Generate molecular conformations
 640 
 641 Usage:
 642     RDKitGenerateConformers.py [--alignConformers <yes or no>] [--addHydrogens <yes or no>]
 643                                [--conformerGenerator <SDG, ETDG, KDG, ETKDG>] [--embedRMSDCutoff <number>]
 644                                [--energyOut  <yes or no>] [--enforceChirality <yes or no>] [--energyRMSDCutoff <number>]
 645                                [--energyWindow <number> ]  [--forceField <UFF, MMFF, None>] [--forceFieldMMFFVariant <MMFF94 or MMFF94s>]
 646                                [--infileParams <Name,Value,...>] [--maxConfs <number>]
 647                                [--mp <yes or no>] [--mpParams <Name.Value,...>]
 648                                [--maxIters <number>]  [ --outfileParams <Name,Value,...> ]  [--overwrite]
 649                                [--quiet <yes or no>] [ --removeHydrogens <yes or no>] [--randomSeed <number>]
 650                                [-w <dir>] -i <infile> -o <outfile> 
 651     RDKitGenerateConformers.py -h | --help | -e | --examples
 652 
 653 Description:
 654     Generate molecular conformations using a combination of distance geometry and
 655     forcefield minimization. The forcefield minimization may be skipped to only generate
 656     conformations by available distance geometry based methodologies.
 657 
 658     The supported input file formats are: Mol (.mol), SD (.sdf, .sd), SMILES (.smi,
 659     .csv, .tcsv .txt)
 660 
 661     The supported output file format are: SD (.sdf, .sd)
 662 
 663 Options:
 664     -a, --addHydrogens <yes or no>  [default: yes]
 665         Add hydrogens before minimization.
 666     --alignConformers <yes or no>  [default: yes]
 667         Align conformers for each molecule.
 668     -c, --conformerGenerator <SDG, ETDG, KDG, ETKDG>  [default: ETKDG]
 669         Conformation generation methodology for generating initial 3D coordinates of a
 670         molecule. Possible values: Standard Distance Geometry, (SDG), Experimental
 671         Torsion-angle preference with Distance Geometry (ETDG)  [Ref 129] , basic Knowledge-terms
 672         with Distance Geometry (KDG), and Experimental Torsion-angle preference along
 673         with basic Knowledge-terms and Distance Geometry (ETKDG). 
 674     --embedRMSDCutoff <number>  [default: none]
 675         RMSD cutoff for retaining conformations after embedding and before energy minimization.
 676         All embedded conformations are kept by default. Otherwise, only those conformations
 677         which are different from each other by the specified RMSD cutoff are kept. The first
 678         embedded conformation is always retained.
 679     --energyOut <yes or no>  [default: No]
 680         Write out energy values.
 681     --enforceChirality <yes or no>  [default: Yes]
 682         Enforce chirality for defined chiral centers.
 683     --energyRMSDCutoff <number>  [default: none]
 684         RMSD cutoff for retaining conformations after energy minimization. By default,
 685         all minimized conformations with in the specified energy window from the lowest energy
 686         conformation are kept. Otherwise, only those conformations which are different from
 687         the lowest energy conformation by the specified RMSD cutoff and are with in the
 688         specified energy window are kept. The lowest energy conformation is always retained.
 689     --energyWindow <number>  [default: 20]
 690         Energy window in kcal/mol for selecting conformers. This option is ignored during
 691         'None' value of '-f, --forcefield' option.
 692     -e, --examples
 693         Print examples.
 694     -f, --forceField <UFF, MMFF, None>  [default: MMFF]
 695         Forcefield method to use for energy minimization. Possible values: Universal Force
 696         Field (UFF) [Ref 81],  Merck Molecular Mechanics Force Field (MMFF) [Ref 83-87] or
 697         None.
 698     --forceFieldMMFFVariant <MMFF94 or MMFF94s>  [default: MMFF94]
 699         Variant of MMFF forcefield to use for energy minimization.
 700     -h, --help
 701         Print this help message.
 702     -i, --infile <infile>
 703         Input file name.
 704     --infileParams <Name,Value,...>  [default: auto]
 705         A comma delimited list of parameter name and value pairs for reading
 706         molecules from files. The supported parameter names for different file
 707         formats, along with their default values, are shown below:
 708             
 709             SD, MOL: removeHydrogens,yes,sanitize,yes,strictParsing,yes
 710             SMILES: smilesColumn,1,smilesNameColumn,2,smilesDelimiter,space,
 711                 smilesTitleLine,auto,sanitize,yes
 712             
 713         Possible values for smilesDelimiter: space, comma or tab.
 714     --maxConfs <number>  [default: auto]
 715         Maximum number of conformations to generate for each molecule by conformation
 716         generation methodology. The conformations are minimized using the specified
 717         forcefield as needed and written to the output file. The default value for maximum
 718         number of conformations is dependent on the number of rotatable bonds in molecules:
 719         RotBonds <= 5, maxConfs = 100; RotBonds >=6 and <= 10, MaxConfs = 200;
 720         RotBonds >= 11, maxConfs = 300
 721     --maxIters <number>  [default: 250]
 722         Maximum number of iterations to perform for each molecule during forcefield
 723         minimization.
 724     --mp <yes or no>  [default: no]
 725         Use multiprocessing.
 726          
 727         By default, input data is retrieved in a lazy manner via mp.Pool.imap()
 728         function employing lazy RDKit data iterable. This allows processing of
 729         arbitrary large data sets without any additional requirements memory.
 730         
 731         All input data may be optionally loaded into memory by mp.Pool.map()
 732         before starting worker processes in a process pool by setting the value
 733         of 'inputDataMode' to 'InMemory' in '--mpParams' option.
 734         
 735         A word to the wise: The default 'chunkSize' value of 1 during 'Lazy' input
 736         data mode may adversely impact the performance. The '--mpParams' section
 737         provides additional information to tune the value of 'chunkSize'.
 738     --mpParams <Name,Value,...>  [default: auto]
 739         A comma delimited list of parameter name and value pairs for to
 740         configure multiprocessing.
 741         
 742         The supported parameter names along with their default and possible
 743         values are shown below:
 744         
 745             chunkSize, auto
 746             inputDataMode, Lazy   [ Possible values: InMemory or Lazy ]
 747             numProcesses, auto   [ Default: mp.cpu_count() ]
 748         
 749         These parameters are used by the following functions to configure and
 750         control the behavior of multiprocessing: mp.Pool(), mp.Pool.map(), and
 751         mp.Pool.imap().
 752         
 753         The chunkSize determines chunks of input data passed to each worker
 754         process in a process pool by mp.Pool.map() and mp.Pool.imap() functions.
 755         The default value of chunkSize is dependent on the value of 'inputDataMode'.
 756         
 757         The mp.Pool.map() function, invoked during 'InMemory' input data mode,
 758         automatically converts RDKit data iterable into a list, loads all data into
 759         memory, and calculates the default chunkSize using the following method
 760         as shown in its code:
 761         
 762             chunkSize, extra = divmod(len(dataIterable), len(numProcesses) * 4)
 763             if extra: chunkSize += 1
 764         
 765         For example, the default chunkSize will be 7 for a pool of 4 worker processes
 766         and 100 data items.
 767         
 768         The mp.Pool.imap() function, invoked during 'Lazy' input data mode, employs
 769         'lazy' RDKit data iterable to retrieve data as needed, without loading all the
 770         data into memory. Consequently, the size of input data is not known a priori.
 771         It's not possible to estimate an optimal value for the chunkSize. The default 
 772         chunkSize is set to 1.
 773         
 774         The default value for the chunkSize during 'Lazy' data mode may adversely
 775         impact the performance due to the overhead associated with exchanging
 776         small chunks of data. It is generally a good idea to explicitly set chunkSize to
 777         a larger value during 'Lazy' input data mode, based on the size of your input
 778         data and number of processes in the process pool.
 779         
 780         The mp.Pool.map() function waits for all worker processes to process all
 781         the data and return the results. The mp.Pool.imap() function, however,
 782         returns the the results obtained from worker processes as soon as the
 783         results become available for specified chunks of data.
 784         
 785         The order of data in the results returned by both mp.Pool.map() and 
 786         mp.Pool.imap() functions always corresponds to the input data.
 787     -o, --outfile <outfile>
 788         Output file name.
 789     --outfileParams <Name,Value,...>  [default: auto]
 790         A comma delimited list of parameter name and value pairs for writing
 791         molecules to files. The supported parameter names for different file
 792         formats, along with their default values, are shown below:
 793             
 794             SD: kekulize,no
 795             
 796     --overwrite
 797         Overwrite existing files.
 798     -q, --quiet <yes or no>  [default: no]
 799         Use quiet mode. The warning and information messages will not be printed.
 800     -r, --removeHydrogens <yes or no>  [default: Yes]
 801         Remove hydrogens after minimization.
 802     --randomSeed <number>  [default: auto]
 803         Seed for the random number generator for reproducing 3D coordinates.
 804         Default is to use a random seed.
 805     -w, --workingdir <dir>
 806         Location of working directory which defaults to the current directory.
 807 
 808 Examples:
 809     To generate conformers using Experimental Torsion-angle preference along
 810     with basic Knowledge-terms and Distance Geometry (ETKDG) followed by
 811     MMFF minimization with automatic determination of maximum number of
 812     conformers for each molecule and write out a SD file, type:
 813 
 814         % RDKitGenerateConformers.py  -i Sample.smi -o SampleOut.sdf
 815 
 816     To rerun the first example in a quiet mode and write out a SD file, type:
 817 
 818         % RDKitGenerateConformers.py -q yes -i Sample.smi -o SampleOut.sdf
 819 
 820     To rerun the first example in multiprocessing mode on all available CPUs
 821     without loading all data into memory and write out a SD file, type:
 822 
 823         % RDKitGenerateConformers.py --mp yes -i Sample.smi -o SampleOut.sdf
 824 
 825     To run the first example in multiprocessing mode on all available CPUs
 826     by loading all data into memory and write out a SD file, type:
 827 
 828         % RDKitGenerateConformers.py --mp yes --mpParams "inputDataMode,
 829           InMemory" -i Sample.smi -o SampleOut.sdf
 830 
 831     To rerun the first example in multiprocessing mode on specific number of
 832     CPUs and chunk size without loading all data into memory and write out a SD file,
 833     type:
 834 
 835         % RDKitGenerateConformers.py --mp yes --mpParams "inputDataMode,Lazy,
 836           numProcesses,4,chunkSize,8" -i Sample.smi -o SampleOut.sdf
 837 
 838     To generate up to 150 conformers for each molecule using ETKDG and UFF forcefield
 839     minimization along with conformers within 25 kcal/mol energy window and write out a
 840     SD file, type:
 841 
 842         % RDKitGenerateConformers.py  --energyWindow 25 -f UFF --maxConfs 150
 843           -i Sample.smi -o SampleOut.sdf
 844 
 845     To generate up to 50 conformers for each molecule using KDG without any forcefield
 846     minimization and alignment of conformers and write out a SD file, type:
 847 
 848         % RDKitGenerateConformers.py  -f none --maxConfs 50 --alignConformers no
 849           -i Sample.sdf -o SampleOut.sdf
 850 
 851     To generate up to 50 conformers using SDG without any forcefield minimization
 852     and alignment of conformers for molecules in a  CSV SMILES file, SMILES strings
 853     in column 1, name in column 2, and write out a SD file, type:
 854 
 855         % RDKitGenerateConformers.py  --maxConfs 50  --maxIters 50 -c SDG
 856           --alignConformers no -f none --infileParams "smilesDelimiter,comma,
 857           smilesTitleLine,yes, smilesColumn,1,smilesNameColumn,2"
 858           -i SampleSMILES.csv -o SampleOut.sdf
 859 
 860 Author:
 861     Manish Sud(msud@san.rr.com)
 862 
 863 See also:
 864     RDKitCalculateRMSD.py, RDKitCalculateMolecularDescriptors.py,
 865     RDKitCompareMoleculeShapes.py, RDKitConvertFileFormat.py,
 866     RDKitGenerateConstrainedConformers.py, RDKitPerformMinimization.py
 867 
 868 Copyright:
 869     Copyright (C) 2020 Manish Sud. All rights reserved.
 870 
 871     The functionality available in this script is implemented using RDKit, an
 872     open source toolkit for cheminformatics developed by Greg Landrum.
 873 
 874     This file is part of MayaChemTools.
 875 
 876     MayaChemTools is free software; you can redistribute it and/or modify it under
 877     the terms of the GNU Lesser General Public License as published by the Free
 878     Software Foundation; either version 3 of the License, or (at your option) any
 879     later version.
 880 
 881 """
 882 
 883 if __name__ == "__main__":
 884     main()