1 #!/bin/env python
2 #
3 # File: RDKitGenerateConstrainedConformers.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 rdFMCS
44 from rdkit.Chem import rdMolAlign
45 except ImportError as ErrMsg:
46 sys.stderr.write("\nFailed to import RDKit module/package: %s\n" % ErrMsg)
47 sys.stderr.write("Check/update your RDKit environment and try again.\n\n")
48 sys.exit(1)
49
50 # MayaChemTools imports...
51 try:
52 from docopt import docopt
53 import MiscUtil
54 import RDKitUtil
55 except ImportError as ErrMsg:
56 sys.stderr.write("\nFailed to import MayaChemTools module/package: %s\n" % ErrMsg)
57 sys.stderr.write("Check/update your MayaChemTools environment and try again.\n\n")
58 sys.exit(1)
59
60 ScriptName = os.path.basename(sys.argv[0])
61 Options = {}
62 OptionsInfo = {}
63
64 def main():
65 """Start execution of the script"""
66
67 MiscUtil.PrintInfo("\n%s (RDK v%s; %s): Starting...\n" % (ScriptName, rdBase.rdkitVersion, time.asctime()))
68
69 (WallClockTime, ProcessorTime) = MiscUtil.GetWallClockAndProcessorTime()
70
71 # Retrieve command line arguments and options...
72 RetrieveOptions()
73
74 # Process and validate command line arguments and options...
75 ProcessOptions()
76
77 # Perform actions required by the script...
78 GenerateConstrainedConformers()
79
80 MiscUtil.PrintInfo("\n%s: Done...\n" % ScriptName)
81 MiscUtil.PrintInfo("Total time: %s" % MiscUtil.GetFormattedElapsedTime(WallClockTime, ProcessorTime))
82
83 def GenerateConstrainedConformers():
84 """Perform constrained minimization."""
85
86 # Read and validate reference molecule...
87 RefMol = RetrieveReferenceMolecule()
88
89 # Setup a molecule reader for input file...
90 MiscUtil.PrintInfo("\nProcessing file %s..." % OptionsInfo["Infile"])
91 OptionsInfo["InfileParams"]["AllowEmptyMols"] = True
92 Mols = RDKitUtil.ReadMolecules(OptionsInfo["Infile"], **OptionsInfo["InfileParams"])
93
94 # Set up a molecule writer...
95 Writer = RDKitUtil.MoleculesWriter(OptionsInfo["Outfile"], **OptionsInfo["OutfileParams"])
96 if Writer is None:
97 MiscUtil.PrintError("Failed to setup a writer for output fie %s " % OptionsInfo["Outfile"])
98 MiscUtil.PrintInfo("Generating file %s..." % OptionsInfo["Outfile"])
99
100 MolCount, ValidMolCount, CoreScaffoldMissingCount, ConfGenFailedCount = ProcessMolecules(RefMol, Mols, Writer)
101
102 if Writer is not None:
103 Writer.close()
104
105 MiscUtil.PrintInfo("\nTotal number of molecules: %d" % MolCount)
106 MiscUtil.PrintInfo("Number of valid molecules: %d" % ValidMolCount)
107 MiscUtil.PrintInfo("Number of molecules with missing core scaffold: %d" % CoreScaffoldMissingCount)
108 MiscUtil.PrintInfo("Number of molecules failed during conformation generation or minimization: %d" % ConfGenFailedCount)
109 MiscUtil.PrintInfo("Number of ignored molecules: %d" % (MolCount - ValidMolCount + CoreScaffoldMissingCount + ConfGenFailedCount))
110
111 def ProcessMolecules(RefMol, Mols, Writer):
112 """Process molecules to generate constrained conformers."""
113
114 if OptionsInfo["MPMode"]:
115 return ProcessMoleculesUsingMultipleProcesses(RefMol, Mols, Writer)
116 else:
117 return ProcessMoleculesUsingSingleProcess(RefMol, Mols, Writer)
118
119 def ProcessMoleculesUsingSingleProcess(RefMol, Mols, Writer):
120 """Process molecules to generate constrained conformers using a single process."""
121
122 (MolCount, ValidMolCount, CoreScaffoldMissingCount, ConfGenFailedCount) = [0] * 4
123
124 for Mol in Mols:
125 MolCount += 1
126
127 if Mol is None:
128 continue
129
130 if RDKitUtil.IsMolEmpty(Mol):
131 if not OptionsInfo["QuietMode"]:
132 MolName = RDKitUtil.GetMolName(Mol, MolCount)
133 MiscUtil.PrintWarning("Ignoring empty molecule: %s" % MolName)
134 continue
135 ValidMolCount += 1
136
137 # Setup a reference molecule core containing common scaffold atoms...
138 RefMolCore = SetupCoreScaffold(RefMol, Mol, MolCount)
139 if RefMolCore is None:
140 CoreScaffoldMissingCount += 1
141 continue
142
143 ConfMols, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues = GenerateMolConformers(Mol, RefMolCore, MolCount)
144
145 if not CalcStatus:
146 ConfGenFailedCount += 1
147 continue
148
149 WriteMolConformers(Writer, Mol, MolCount, ConfMols, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues)
150
151 return (MolCount, ValidMolCount, CoreScaffoldMissingCount, ConfGenFailedCount)
152
153 def ProcessMoleculesUsingMultipleProcesses(RefMol, Mols, Writer):
154 """Process molecules to generate constrained conformers using multiprocessing."""
155
156 MPParams = OptionsInfo["MPParams"]
157
158 # Setup data for initializing a worker process...
159 MiscUtil.PrintInfo("Encoding options info and reference molecule...")
160
161 OptionsInfo["EncodedRefMol"] = RDKitUtil.MolToBase64EncodedMolString(RefMol)
162 InitializeWorkerProcessArgs = (MiscUtil.ObjectToBase64EncodedString(Options), MiscUtil.ObjectToBase64EncodedString(OptionsInfo))
163
164 # Setup a encoded mols data iterable for a worker process...
165 WorkerProcessDataIterable = RDKitUtil.GenerateBase64EncodedMolStrings(Mols)
166
167 # Setup process pool along with data initialization for each process...
168 MiscUtil.PrintInfo("\nConfiguring multiprocessing using %s method..." % ("mp.Pool.imap()" if re.match("^Lazy$", MPParams["InputDataMode"], re.I) else "mp.Pool.map()"))
169 MiscUtil.PrintInfo("NumProcesses: %s; InputDataMode: %s; ChunkSize: %s\n" % (MPParams["NumProcesses"], MPParams["InputDataMode"], ("automatic" if MPParams["ChunkSize"] is None else MPParams["ChunkSize"])))
170
171 ProcessPool = mp.Pool(MPParams["NumProcesses"], InitializeWorkerProcess, InitializeWorkerProcessArgs)
172
173 # Start processing...
174 if re.match("^Lazy$", MPParams["InputDataMode"], re.I):
175 Results = ProcessPool.imap(WorkerProcess, WorkerProcessDataIterable, MPParams["ChunkSize"])
176 elif re.match("^InMemory$", MPParams["InputDataMode"], re.I):
177 Results = ProcessPool.map(WorkerProcess, WorkerProcessDataIterable, MPParams["ChunkSize"])
178 else:
179 MiscUtil.PrintError("The value, %s, specified for \"--inputDataMode\" is not supported." % (MPParams["InputDataMode"]))
180
181 (MolCount, ValidMolCount, CoreScaffoldMissingCount, ConfGenFailedCount) = [0] * 4
182 for Result in Results:
183 MolCount += 1
184 MolIndex, EncodedMol, EncodedConfMols, CoreScaffoldMissingStatus, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues = Result
185
186 if EncodedMol is None:
187 continue
188 ValidMolCount += 1
189
190 if CoreScaffoldMissingStatus:
191 CoreScaffoldMissingCount += 1
192 continue
193
194 if not CalcStatus:
195 ConfGenFailedCount += 1
196 continue
197
198 Mol = RDKitUtil.MolFromBase64EncodedMolString(EncodedMol)
199 ConfMols = [RDKitUtil.MolFromBase64EncodedMolString(EncodedConfMol) for EncodedConfMol in EncodedConfMols]
200
201 WriteMolConformers(Writer, Mol, MolCount, ConfMols, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues)
202
203 return (MolCount, ValidMolCount, CoreScaffoldMissingCount, ConfGenFailedCount)
204
205 def InitializeWorkerProcess(*EncodedArgs):
206 """Initialize data for a worker process."""
207
208 global Options, OptionsInfo
209
210 MiscUtil.PrintInfo("Starting process (PID: %s)..." % os.getpid())
211
212 # Decode Options and OptionInfo...
213 Options = MiscUtil.ObjectFromBase64EncodedString(EncodedArgs[0])
214 OptionsInfo = MiscUtil.ObjectFromBase64EncodedString(EncodedArgs[1])
215
216 # Decode RefMol...
217 OptionsInfo["RefMol"] = RDKitUtil.MolFromBase64EncodedMolString(OptionsInfo["EncodedRefMol"])
218
219 def WorkerProcess(EncodedMolInfo):
220 """Process data for a worker process."""
221
222 MolIndex, EncodedMol = EncodedMolInfo
223
224 ConfMols = None
225 CoreScaffoldMissingStatus = False
226 CalcStatus = False
227 ConfIDs = None
228 ConfEnergyValues = None
229 ConfScaffoldEmbedRMSDValues = None
230
231 if EncodedMol is None:
232 return [MolIndex, None, ConfMols, CoreScaffoldMissingStatus, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues]
233
234 RefMol = OptionsInfo["RefMol"]
235
236 Mol = RDKitUtil.MolFromBase64EncodedMolString(EncodedMol)
237 if RDKitUtil.IsMolEmpty(Mol):
238 if not OptionsInfo["QuietMode"]:
239 MolName = RDKitUtil.GetMolName(Mol, (MolIndex + 1))
240 MiscUtil.PrintWarning("Ignoring empty molecule: %s" % MolName)
241 return [MolIndex, None, ConfMols, CoreScaffoldMissingStatus, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues]
242
243 # Setup a reference molecule core containing common scaffold atoms...
244 RefMolCore = SetupCoreScaffold(RefMol, Mol, (MolIndex + 1))
245 if RefMolCore is None:
246 CoreScaffoldMissingStatus = True
247 return [MolIndex, Mol, ConfMols, CoreScaffoldMissingStatus, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues]
248
249 ConfMols, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues = GenerateMolConformers(Mol, RefMolCore, (MolIndex + 1))
250
251 EncodedConfMols = [RDKitUtil.MolToBase64EncodedMolString(ConfMol, PropertyPickleFlags = Chem.PropertyPickleOptions.MolProps | Chem.PropertyPickleOptions.PrivateProps) for ConfMol in ConfMols]
252 return [MolIndex, EncodedMol, EncodedConfMols, CoreScaffoldMissingStatus, CalcStatus, ConfIDs, ConfEnergyValues, ConfScaffoldEmbedRMSDValues]
253
254 def RetrieveReferenceMolecule():
255 """Retrieve and validate reference molecule """
256
257 RefFile = OptionsInfo["RefFile"]
258
259 MiscUtil.PrintInfo("\nProcessing file %s..." % (RefFile))
260 OptionsInfo["InfileParams"]["AllowEmptyMols"] = False
261 ValidRefMols, RefMolCount, ValidRefMolCount = RDKitUtil.ReadAndValidateMolecules(RefFile, **OptionsInfo["InfileParams"])
262
263 if ValidRefMolCount == 0:
264 MiscUtil.PrintError("The reference file, %s, contains no valid molecules." % RefFile)
265 elif ValidRefMolCount > 1:
266 MiscUtil.PrintWarning("The reference file, %s, contains, %d, valid molecules. Using first molecule as the reference molecule..." % (RefFile, ValidRefMolCount))
267
268 RefMol = ValidRefMols[0]
269
270 if OptionsInfo["UseScaffoldSMARTS"]:
271 ScaffoldPatternMol = Chem.MolFromSmarts(OptionsInfo["ScaffoldSMARTS"])
272 if ScaffoldPatternMol is None:
273 MiscUtil.PrintError("Failed to create scaffold pattern molecule. The scaffold SMARTS pattern, %s, specified using \"-s, --scaffold\" option is not valid." % (OptionsInfo["ScaffoldSMARTS"]))
274
275 if not RefMol.HasSubstructMatch(ScaffoldPatternMol):
276 MiscUtil.PrintError("The scaffold SMARTS pattern, %s, specified using \"-s, --scaffold\" option, is missing in the first valid reference molecule." % (OptionsInfo["ScaffoldSMARTS"]))
277
278 return RefMol
279
280 def SetupCoreScaffold(RefMol, Mol, MolCount):
281 """Setup a reference molecule core containing common scaffold atoms between
282 a pair of molecules."""
283
284 if OptionsInfo["UseScaffoldMCS"]:
285 return SetupCoreScaffoldByMCS(RefMol, Mol, MolCount)
286 elif OptionsInfo["UseScaffoldSMARTS"]:
287 return SetupCoreScaffoldBySMARTS(RefMol, Mol, MolCount)
288 else:
289 MiscUtil.PrintError("The value, %s, specified for \"-s, --scaffold\" option is not supported." % (OptionsInfo["Scaffold"]))
290
291 def SetupCoreScaffoldByMCS(RefMol, Mol, MolCount):
292 """Setup a reference molecule core containing common scaffold atoms between
293 a pair of molecules using MCS."""
294
295 MCSParams = OptionsInfo["MCSParams"]
296 Mols = [RefMol, Mol]
297
298 MCSResultObject = rdFMCS.FindMCS(Mols, maximizeBonds = MCSParams["MaximizeBonds"], threshold = MCSParams["Threshold"], timeout = MCSParams["TimeOut"], verbose = MCSParams["Verbose"], matchValences = MCSParams["MatchValences"], ringMatchesRingOnly = MCSParams["RingMatchesRingOnly"], completeRingsOnly = MCSParams["CompleteRingsOnly"], matchChiralTag = MCSParams["MatchChiralTag"], atomCompare = MCSParams["AtomCompare"], bondCompare = MCSParams["BondCompare"], seedSmarts = MCSParams["SeedSMARTS"])
299
300 if MCSResultObject.canceled:
301 if not OptionsInfo["QuietMode"]:
302 MiscUtil.PrintWarning("MCS failed to identify a common core scaffold between reference moecule and input molecule %s. Specify a different set of parameters using \"-m, --mcsParams\" option and try again." % (RDKitUtil.GetMolName(Mol, MolCount)))
303 return None
304
305 CoreNumAtoms = MCSResultObject.numAtoms
306 CoreNumBonds = MCSResultObject.numBonds
307
308 SMARTSCore = MCSResultObject.smartsString
309
310 if not len(SMARTSCore):
311 if not OptionsInfo["QuietMode"]:
312 MiscUtil.PrintWarning("MCS failed to identify a common core scaffold between reference moecule and input molecule %s. Specify a different set of parameters using \"-m, --mcsParams\" option and try again." % (RDKitUtil.GetMolName(Mol, MolCount)))
313 return None
314
315 if CoreNumAtoms < MCSParams["MinNumAtoms"]:
316 if not OptionsInfo["QuietMode"]:
317 MiscUtil.PrintWarning("Number of atoms, %d, in core scaffold identified by MCS is less than, %d, as specified by \"minNumAtoms\" parameter in \"-m, --mcsParams\" option." % (CoreNumAtoms, MCSParams["MinNumAtoms"]))
318 return None
319
320 if CoreNumBonds < MCSParams["MinNumBonds"]:
321 if not OptionsInfo["QuietMode"]:
322 MiscUtil.PrintWarning("Number of bonds, %d, in core scaffold identified by MCS is less than, %d, as specified by \"minNumBonds\" parameter in \"-m, --mcsParams\" option." % (CoreNumBonds, MCSParams["MinNumBonds"]))
323 return None
324
325 return GenerateCoreMol(RefMol, SMARTSCore)
326
327 def SetupCoreScaffoldBySMARTS(RefMol, Mol, MolCount):
328 """Setup a reference molecule core containing common scaffold atoms between
329 a pair of molecules using specified SMARTS."""
330
331 if OptionsInfo["ScaffoldPatternMol"] is None:
332 OptionsInfo["ScaffoldPatternMol"] = Chem.MolFromSmarts(OptionsInfo["ScaffoldSMARTS"])
333
334 if not Mol.HasSubstructMatch(OptionsInfo["ScaffoldPatternMol"]):
335 if not OptionsInfo["QuietMode"]:
336 MiscUtil.PrintWarning("The scaffold SMARTS pattern, %s, specified using \"-s, --scaffold\" option is missing in input molecule, %s." % (OptionsInfo["ScaffoldSMARTS"], RDKitUtil.GetMolName(Mol, MolCount)))
337 return None
338
339 return GenerateCoreMol(RefMol, OptionsInfo["ScaffoldSMARTS"])
340
341 def GenerateCoreMol(RefMol, SMARTSCore):
342 """Generate core molecule for embedding. """
343
344 # Create a molecule corresponding to core atoms...
345 SMARTSCoreMol = Chem.MolFromSmarts(SMARTSCore)
346
347 # Setup a ref molecule containing core atoms with dummy atoms as
348 # attachment points for atoms around the core atoms...
349 Core = AllChem.ReplaceSidechains(Chem.RemoveHs(RefMol), SMARTSCoreMol)
350
351 # Delete any substructures containing dummy atoms..
352 RefMolCore = AllChem.DeleteSubstructs(Core, Chem.MolFromSmiles('*'))
353 RefMolCore.UpdatePropertyCache()
354
355 return RefMolCore
356
357 def GenerateMolConformers(Mol, RefMolCore, MolNum = None):
358 "Generate constrained conformers."
359
360 if OptionsInfo["AddHydrogens"]:
361 Mol = Chem.AddHs(Mol, addCoords = True)
362
363 # Setup forcefield function to use for constrained minimization...
364 ForceFieldFunction = None
365 ForceFieldName = None
366 if OptionsInfo["UseUFF"]:
367 ForceFieldFunction = lambda mol, confId = -1 : AllChem.UFFGetMoleculeForceField(mol, confId = confId)
368 ForeceFieldName = "UFF"
369 else:
370 ForceFieldFunction = lambda mol, confId = -1 : AllChem.MMFFGetMoleculeForceField(mol, AllChem.MMFFGetMoleculeProperties(mol, mmffVariant = OptionsInfo["MMFFVariant"]) , confId = confId)
371 ForeceFieldName = "MMFF"
372
373 if ForceFieldFunction is None:
374 if not OptionsInfo["QuietMode"]:
375 MiscUtil.PrintWarning("Failed to setup forcefield %s for molecule: %s\n" % (ForceFieldName, RDKitUtil.GetMolName(Mol, MolNum)))
376 return (None, False, None, None)
377
378 MaxConfs = OptionsInfo["MaxConfs"]
379 EnforceChirality = OptionsInfo["EnforceChirality"]
380 UseExpTorsionAnglePrefs = OptionsInfo["UseExpTorsionAnglePrefs"]
381 UseBasicKnowledge = OptionsInfo["UseBasicKnowledge"]
382 UseTethers = OptionsInfo["UseTethers"]
383
384 CalcEnergyMap = {}
385 MolConfsMap = {}
386 CalcRMSDMap = {}
387
388 ScaffoldEmbedRMSDMap = {}
389
390 ConfIDs = [ConfID for ConfID in range(0, MaxConfs)]
391 for ConfID in ConfIDs:
392 try:
393 MolConf = Chem.Mol(Mol)
394 AllChem.ConstrainedEmbed(MolConf, RefMolCore, useTethers = UseTethers, coreConfId = -1, randomseed = ConfID, getForceField = ForceFieldFunction, enforceChirality = EnforceChirality, useExpTorsionAnglePrefs = UseExpTorsionAnglePrefs, useBasicKnowledge = UseBasicKnowledge)
395 except (ValueError, RuntimeError, Chem.rdchem.KekulizeException) as ErrMsg:
396 if not OptionsInfo["QuietMode"]:
397 MolName = RDKitUtil.GetMolName(Mol, MolNum)
398 MiscUtil.PrintWarning("Constrained embedding coupldn't be performed for molecule %s:\n%s\n" % (RDKitUtil.GetMolName(Mol, MolNum), ErrMsg))
399 return (None, False, None, None)
400
401 EnergyStatus, Energy = GetEnergy(MolConf)
402
403 if not EnergyStatus:
404 if not OptionsInfo["QuietMode"]:
405 MolName = RDKitUtil.GetMolName(Mol, MolNum)
406 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))
407 return (None, False, None, None)
408
409 CalcEnergyMap[ConfID] = Energy
410
411 if OptionsInfo["ScaffoldRMSDOut"]:
412 ScaffoldEmbedRMSDMap[ConfID] = "%.4f" % float(MolConf.GetProp('EmbedRMS'))
413 MolConf.ClearProp('EmbedRMS')
414
415 if OptionsInfo["RemoveHydrogens"]:
416 MolConf = Chem.RemoveHs(MolConf)
417 MolConfsMap[ConfID] = MolConf
418
419 # Sort conformers by energy...
420 SortedConfIDs = sorted(ConfIDs, key = lambda ConfID: CalcEnergyMap[ConfID])
421
422 MinEnergyConfID = SortedConfIDs[0]
423 EnergyWindow = OptionsInfo["EnergyWindow"]
424
425 MinConfEnergy = CalcEnergyMap[MinEnergyConfID]
426 MinEnergyMolConf = MolConfsMap[MinEnergyConfID]
427
428 # Calculate RMSD values for conformers...
429 CalcRMSDMap = {}
430
431 EnergyRMSDCutoff = OptionsInfo["EnergyRMSDCutoff"]
432 ApplyEnergyRMSDCutoff = True if EnergyRMSDCutoff > 0 else False
433
434 if ApplyEnergyRMSDCutoff:
435 FirstConf = True
436 RefMolConf = None
437 for ConfID in SortedConfIDs:
438 if FirstConf:
439 FirstConf = False
440 RefMolConf = MolConfsMap[ConfID]
441 CalcRMSDMap[ConfID] = 0.0
442 continue
443
444 # Make a copy for probe molecule. It gets updated during the calculation...
445 ProbeMolConf = Chem.Mol(MolConfsMap[ConfID])
446 RMSD = rdMolAlign.AlignMol(ProbeMolConf, MinEnergyMolConf)
447 CalcRMSDMap[ConfID] = RMSD
448
449 # Track conformers with in the specified energy window from the lowest
450 # energy conformation along with applying RMSD cutoff as needed...
451 #
452 SelectedConfIDs = []
453
454 ConfCount = 0
455 IgnoredByEnergyConfCount = 0
456 IgnoredByRMSDConfCount = 0
457
458 FirstConf = True
459 for ConfID in SortedConfIDs:
460 if FirstConf:
461 ConfCount += 1
462 FirstConf = False
463 SelectedConfIDs.append(ConfID)
464 continue
465
466 ConfEnergyDiff = abs(CalcEnergyMap[ConfID] - MinConfEnergy )
467 if ConfEnergyDiff > EnergyWindow:
468 IgnoredByEnergyConfCount += 1
469 continue
470
471 if ApplyEnergyRMSDCutoff:
472 if CalcRMSDMap[ConfID] < EnergyRMSDCutoff:
473 IgnoredByRMSDConfCount += 1
474 continue
475
476 ConfCount += 1
477 SelectedConfIDs.append(ConfID)
478
479 if not OptionsInfo["QuietMode"]:
480 MolName = RDKitUtil.GetMolName(Mol, MolNum)
481 MiscUtil.PrintInfo("\nTotal Number of conformations generated for %s: %d" % (MolName, ConfCount))
482 MiscUtil.PrintInfo("Number of conformations ignored due to energy window cutoff: %d" % (IgnoredByEnergyConfCount))
483 if ApplyEnergyRMSDCutoff:
484 MiscUtil.PrintInfo("Number of conformations ignored due to energy RMSD cutoff: %d" % (IgnoredByRMSDConfCount))
485
486 # Setup selected conformer molecules...
487 SelectedConfMols = [MolConfsMap[ConfID] for ConfID in SelectedConfIDs]
488
489 # Setup selected conformer energy values...
490 SelectedConfEnergyValues = None
491 if OptionsInfo["EnergyOut"]:
492 SelectedConfEnergyValues = ["%.2f" % CalcEnergyMap[ConfID] for ConfID in SelectedConfIDs]
493
494 # Setup selected conformer scaffold RMSD values...
495 SelectedConfScaffoldEmbedRMSDValues = None
496 if OptionsInfo["ScaffoldRMSDOut"]:
497 SelectedConfScaffoldEmbedRMSDValues = []
498 for ConfID in SelectedConfIDs:
499 SelectedConfScaffoldEmbedRMSDValues.append(ScaffoldEmbedRMSDMap[ConfID])
500
501 return (SelectedConfMols, True, SelectedConfIDs, SelectedConfEnergyValues, SelectedConfScaffoldEmbedRMSDValues)
502
503 def GetEnergy(Mol, ConfID = None):
504 "Calculate energy."
505
506 Status = True
507 Energy = None
508
509 if ConfID is None:
510 ConfID = -1
511
512 if OptionsInfo["UseUFF"]:
513 UFFMoleculeForcefield = AllChem.UFFGetMoleculeForceField(Mol, confId = ConfID)
514 if UFFMoleculeForcefield is None:
515 Status = False
516 else:
517 Energy = UFFMoleculeForcefield.CalcEnergy()
518 elif OptionsInfo["UseMMFF"]:
519 MMFFMoleculeProperties = AllChem.MMFFGetMoleculeProperties(Mol, mmffVariant = OptionsInfo["MMFFVariant"])
520 MMFFMoleculeForcefield = AllChem.MMFFGetMoleculeForceField(Mol, MMFFMoleculeProperties, confId = ConfID)
521 if MMFFMoleculeForcefield is None:
522 Status = False
523 else:
524 Energy = MMFFMoleculeForcefield.CalcEnergy()
525 else:
526 MiscUtil.PrintError("Couldn't retrieve conformer energy: Specified forcefield, %s, is not supported" % OptionsInfo["ForceField"])
527
528 return (Status, Energy)
529
530 def WriteMolConformers(Writer, Mol, MolNum, ConfMols, ConfIDs, ConfEnergyValues = None, ConfScaffoldEmbedRMSDValues = None):
531 """Write molecule coformers. """
532
533 if ConfMols is None:
534 return
535
536 for Index, ConfMol in enumerate(ConfMols):
537 ConfMolName = RDKitUtil.GetMolName(Mol, MolNum)
538 SetConfMolName(ConfMol, ConfMolName, ConfIDs[Index])
539
540 if ConfScaffoldEmbedRMSDValues is not None:
541 ConfMol.SetProp("CoreScaffoldEmbedRMSD", ConfScaffoldEmbedRMSDValues[Index])
542
543 if ConfEnergyValues is not None:
544 ConfMol.SetProp(OptionsInfo["EnergyLabel"], ConfEnergyValues[Index])
545
546 Writer.write(ConfMol)
547
548 def SetConfMolName(Mol, MolName, ConfCount):
549 """Set conf mol name"""
550
551 ConfName = "%s_Conf%d" % (MolName, ConfCount)
552 Mol.SetProp("_Name", ConfName)
553
554 def ProcessMCSParameters():
555 """Set up and process MCS parameters."""
556
557 SetupMCSParameters()
558 ProcessSpecifiedMCSParameters()
559
560 def SetupMCSParameters():
561 """Set up default MCS parameters."""
562
563 OptionsInfo["MCSParams"] = {"MaximizeBonds": True, "Threshold": 0.9, "TimeOut": 3600, "Verbose": False, "MatchValences": True, "MatchChiralTag": False, "RingMatchesRingOnly": True, "CompleteRingsOnly": True, "AtomCompare": rdFMCS.AtomCompare.CompareElements, "BondCompare": rdFMCS.BondCompare.CompareOrder, "SeedSMARTS": "", "MinNumAtoms": 1, "MinNumBonds": 0}
564
565 def ProcessSpecifiedMCSParameters():
566 """Process specified MCS parameters."""
567
568 if re.match("^auto$", OptionsInfo["SpecifiedMCSParams"], re.I):
569 # Nothing to process...
570 return
571
572 # Parse specified parameters...
573 MCSParams = re.sub(" ", "", OptionsInfo["SpecifiedMCSParams"])
574 if not MCSParams:
575 MiscUtil.PrintError("No valid parameter name and value pairs specified using \"-m, --mcsParams\" option.")
576
577 MCSParamsWords = MCSParams.split(",")
578 if len(MCSParamsWords) % 2:
579 MiscUtil.PrintError("The number of comma delimited paramater names and values, %d, specified using \"-m, --mcsParams\" option must be an even number." % (len(MCSParamsWords)))
580
581 # Setup canonical parameter names...
582 ValidParamNames = []
583 CanonicalParamNamesMap = {}
584 for ParamName in sorted(OptionsInfo["MCSParams"]):
585 ValidParamNames.append(ParamName)
586 CanonicalParamNamesMap[ParamName.lower()] = ParamName
587
588 # Validate and set paramater names and value...
589 for Index in range(0, len(MCSParamsWords), 2):
590 Name = MCSParamsWords[Index]
591 Value = MCSParamsWords[Index + 1]
592
593 CanonicalName = Name.lower()
594 if not CanonicalName in CanonicalParamNamesMap:
595 MiscUtil.PrintError("The parameter name, %s, specified using \"-m, --mcsParams\" option is not a valid name. Supported parameter names: %s" % (Name, " ".join(ValidParamNames)))
596
597 ParamName = CanonicalParamNamesMap[CanonicalName]
598 if re.match("^Threshold$", ParamName, re.I):
599 Value = float(Value)
600 if Value <= 0.0 or Value > 1.0 :
601 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: > 0 and <= 1.0" % (Value, Name))
602 ParamValue = Value
603 elif re.match("^Timeout$", ParamName, re.I):
604 Value = int(Value)
605 if Value <= 0:
606 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: > 0" % (Value, Name))
607 ParamValue = Value
608 elif re.match("^MinNumAtoms$", ParamName, re.I):
609 Value = int(Value)
610 if Value < 1:
611 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: >= 1" % (Value, Name))
612 ParamValue = Value
613 elif re.match("^MinNumBonds$", ParamName, re.I):
614 Value = int(Value)
615 if Value < 0:
616 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: >=0 " % (Value, Name))
617 ParamValue = Value
618 elif re.match("^AtomCompare$", ParamName, re.I):
619 if re.match("^CompareAny$", Value, re.I):
620 ParamValue = rdFMCS.AtomCompare.CompareAny
621 elif re.match("^CompareElements$", Value, re.I):
622 ParamValue = Chem.rdFMCS.AtomCompare.CompareElements
623 elif re.match("^CompareIsotopes$", Value, re.I):
624 ParamValue = Chem.rdFMCS.AtomCompare.CompareIsotopes
625 else:
626 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: CompareAny CompareElements CompareIsotopes" % (Value, Name))
627 elif re.match("^BondCompare$", ParamName, re.I):
628 if re.match("^CompareAny$", Value, re.I):
629 ParamValue = Chem.rdFMCS.BondCompare.CompareAny
630 elif re.match("^CompareOrder$", Value, re.I):
631 ParamValue = rdFMCS.BondCompare.CompareOrder
632 elif re.match("^CompareOrderExact$", Value, re.I):
633 ParamValue = rdFMCS.BondCompare.CompareOrderExact
634 else:
635 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: CompareAny CompareOrder CompareOrderExact" % (Value, Name))
636 elif re.match("^SeedSMARTS$", ParamName, re.I):
637 if not len(Value):
638 MiscUtil.PrintError("The parameter value specified using \"-m, --mcsParams\" option for parameter, %s, is empty. " % (Name))
639 ParamValue = Value
640 else:
641 if not re.match("^(Yes|No|True|False)$", Value, re.I):
642 MiscUtil.PrintError("The parameter value, %s, specified using \"-m, --mcsParams\" option for parameter, %s, is not a valid value. Supported values: Yes No True False" % (Value, Name))
643 ParamValue = False
644 if re.match("^(Yes|True)$", Value, re.I):
645 ParamValue = True
646
647 # Set value...
648 OptionsInfo["MCSParams"][ParamName] = ParamValue
649
650 def ProcessOptions():
651 """Process and validate command line arguments and options"""
652
653 MiscUtil.PrintInfo("Processing options...")
654
655 # Validate options...
656 ValidateOptions()
657
658 OptionsInfo["Infile"] = Options["--infile"]
659 OptionsInfo["InfileParams"] = MiscUtil.ProcessOptionInfileParameters("--infileParams", Options["--infileParams"], Options["--infile"])
660
661 OptionsInfo["RefFile"] = Options["--reffile"]
662
663 OptionsInfo["Scaffold"] = Options["--scaffold"]
664 if re.match("^auto$", Options["--scaffold"], re.I):
665 UseScaffoldMCS = True
666 UseScaffoldSMARTS = False
667 ScaffoldSMARTS = None
668 else:
669 UseScaffoldMCS = False
670 UseScaffoldSMARTS = True
671 ScaffoldSMARTS = OptionsInfo["Scaffold"]
672
673 OptionsInfo["UseScaffoldMCS"] = UseScaffoldMCS
674 OptionsInfo["UseScaffoldSMARTS"] = UseScaffoldSMARTS
675 OptionsInfo["ScaffoldSMARTS"] = ScaffoldSMARTS
676 OptionsInfo["ScaffoldPatternMol"] = None
677
678 OptionsInfo["SpecifiedMCSParams"] = Options["--mcsParams"]
679 ProcessMCSParameters()
680
681 OptionsInfo["Outfile"] = Options["--outfile"]
682 OptionsInfo["OutfileParams"] = MiscUtil.ProcessOptionOutfileParameters("--outfileParams", Options["--outfileParams"])
683
684 OptionsInfo["Overwrite"] = Options["--overwrite"]
685
686 OptionsInfo["AddHydrogens"] = True if re.match("^yes$", Options["--addHydrogens"], re.I) else False
687
688 if re.match("^ETDG$", Options["--conformerGenerator"], re.I):
689 ConformerGenerator = "ETDG"
690 UseExpTorsionAnglePrefs = True
691 UseBasicKnowledge = False
692 elif re.match("^KDG$", Options["--conformerGenerator"], re.I):
693 ConformerGenerator = "KDG"
694 UseExpTorsionAnglePrefs = False
695 UseBasicKnowledge = True
696 elif re.match("^ETKDG$", Options["--conformerGenerator"], re.I):
697 ConformerGenerator = "ETKDG"
698 UseExpTorsionAnglePrefs = True
699 UseBasicKnowledge = True
700 elif re.match("^SDG$", Options["--conformerGenerator"], re.I):
701 ConformerGenerator = "SDG"
702 UseExpTorsionAnglePrefs = False
703 UseBasicKnowledge = False
704 else:
705 MiscUtil.PrintError("The value, %s, specified for option \"-c, --conformerGenerator\" is not supported." % (Options["--conformerGenerator"]))
706
707 OptionsInfo["ConformerGenerator"] = ConformerGenerator
708 OptionsInfo["UseExpTorsionAnglePrefs"] = UseExpTorsionAnglePrefs
709 OptionsInfo["UseBasicKnowledge"] = UseBasicKnowledge
710
711 if re.match("^UFF$", Options["--forceField"], re.I):
712 ForceField = "UFF"
713 UseUFF = True
714 UseMMFF = False
715 elif re.match("^MMFF$", Options["--forceField"], re.I):
716 ForceField = "MMFF"
717 UseUFF = False
718 UseMMFF = True
719 else:
720 MiscUtil.PrintError("The value, %s, specified for \"--forceField\" is not supported." % (Options["--forceField"],))
721
722 MMFFVariant = "MMFF94" if re.match("^MMFF94$", Options["--forceFieldMMFFVariant"], re.I) else "MMFF94s"
723
724 OptionsInfo["ForceField"] = ForceField
725 OptionsInfo["MMFFVariant"] = MMFFVariant
726 OptionsInfo["UseMMFF"] = UseMMFF
727 OptionsInfo["UseUFF"] = UseUFF
728
729 OptionsInfo["ScaffoldRMSDOut"] = True if re.match("^yes$", Options["--scaffoldRMSDOut"], re.I) else False
730
731 OptionsInfo["EnergyOut"] = True if re.match("^yes$", Options["--energyOut"], re.I) else False
732 if UseMMFF:
733 OptionsInfo["EnergyLabel"] = "%s_Energy" % MMFFVariant
734 else:
735 OptionsInfo["EnergyLabel"] = "%s_Energy" % ForceField
736
737 OptionsInfo["EnforceChirality"] = True if re.match("^yes$", Options["--enforceChirality"], re.I) else False
738 EnergyRMSDCutoff = -1.0
739 if not re.match("^none$", Options["--energyRMSDCutoff"], re.I):
740 EnergyRMSDCutoff = float(Options["--energyRMSDCutoff"])
741 OptionsInfo["EnergyRMSDCutoff"] = EnergyRMSDCutoff
742
743 OptionsInfo["EnergyWindow"] = float(Options["--energyWindow"])
744
745 OptionsInfo["MaxConfs"] = int(Options["--maxConfs"])
746
747 OptionsInfo["MPMode"] = True if re.match("^yes$", Options["--mp"], re.I) else False
748 OptionsInfo["MPParams"] = MiscUtil.ProcessOptionMultiprocessingParameters("--mpParams", Options["--mpParams"])
749
750 OptionsInfo["QuietMode"] = True if re.match("^yes$", Options["--quiet"], re.I) else False
751
752 OptionsInfo["RemoveHydrogens"] = True if re.match("^yes$", Options["--removeHydrogens"], re.I) else False
753 OptionsInfo["UseTethers"] = True if re.match("^yes$", Options["--useTethers"], re.I) else False
754
755 def RetrieveOptions():
756 """Retrieve command line arguments and options"""
757
758 # Get options...
759 global Options
760 Options = docopt(_docoptUsage_)
761
762 # Set current working directory to the specified directory...
763 WorkingDir = Options["--workingdir"]
764 if WorkingDir:
765 os.chdir(WorkingDir)
766
767 # Handle examples option...
768 if "--examples" in Options and Options["--examples"]:
769 MiscUtil.PrintInfo(MiscUtil.GetExamplesTextFromDocOptText(_docoptUsage_))
770 sys.exit(0)
771
772 def ValidateOptions():
773 """Validate option values"""
774
775 MiscUtil.ValidateOptionTextValue("-a, --addHydrogens", Options["--addHydrogens"], "yes no")
776 MiscUtil.ValidateOptionTextValue("-c, --conformerGenerator", Options["--conformerGenerator"], "SDG ETDG KDG ETKDG")
777
778 MiscUtil.ValidateOptionTextValue("-f, --forceField", Options["--forceField"], "UFF MMFF")
779 MiscUtil.ValidateOptionTextValue(" --forceFieldMMFFVariant", Options["--forceFieldMMFFVariant"], "MMFF94 MMFF94s")
780
781 MiscUtil.ValidateOptionFloatValue("--energyWindow", Options["--energyWindow"], {">": 0.0})
782 if not re.match("^none$", Options["--energyRMSDCutoff"], re.I):
783 MiscUtil.ValidateOptionFloatValue("--energyRMSDCutoff", Options["--energyRMSDCutoff"], {">": 0.0})
784
785 MiscUtil.ValidateOptionTextValue("--scaffoldRMSDOut", Options["--scaffoldRMSDOut"], "yes no")
786
787 MiscUtil.ValidateOptionTextValue("--energyOut", Options["--energyOut"], "yes no")
788 MiscUtil.ValidateOptionTextValue("--enforceChirality ", Options["--enforceChirality"], "yes no")
789
790 MiscUtil.ValidateOptionFilePath("-i, --infile", Options["--infile"])
791 MiscUtil.ValidateOptionFileExt("-i, --infile", Options["--infile"], "sdf sd mol smi txt csv tsv")
792
793 MiscUtil.ValidateOptionFilePath("-r, --reffile", Options["--reffile"])
794 MiscUtil.ValidateOptionFileExt("-r, --reffile", Options["--reffile"], "sdf sd mol")
795
796 MiscUtil.ValidateOptionFileExt("-o, --outfile", Options["--outfile"], "sdf sd")
797 MiscUtil.ValidateOptionsOutputFileOverwrite("-o, --outfile", Options["--outfile"], "--overwrite", Options["--overwrite"])
798 MiscUtil.ValidateOptionsDistinctFileNames("-i, --infile", Options["--infile"], "-o, --outfile", Options["--outfile"])
799
800 MiscUtil.ValidateOptionIntegerValue("--maxConfs", Options["--maxConfs"], {">": 0})
801
802 MiscUtil.ValidateOptionTextValue("--mp", Options["--mp"], "yes no")
803 MiscUtil.ValidateOptionTextValue("-q, --quiet", Options["--quiet"], "yes no")
804
805 MiscUtil.ValidateOptionTextValue("-r, --removeHydrogens", Options["--removeHydrogens"], "yes no")
806
807 MiscUtil.ValidateOptionTextValue("-u, --useTethers", Options["--useTethers"], "yes no")
808
809 # Setup a usage string for docopt...
810 _docoptUsage_ = """
811 RDKitGenerateConstrainedConformers.py - Generate constrained molecular conformations
812
813 Usage:
814 RDKitGenerateConstrainedConformers.py [--addHydrogens <yes or no>] [--conformerGenerator <SDG, ETDG, KDG, ETKDG>]
815 [--forceField <UFF, or MMFF>] [--forceFieldMMFFVariant <MMFF94 or MMFF94s>]
816 [--energyOut <yes or no>] [--enforceChirality <yes or no>] [--energyRMSDCutoff <number>]
817 [--energyWindow <number> ] [--infileParams <Name,Value,...>] [--maxConfs <number>]
818 [--mcsParams <Name,Value,...>] [--mp <yes or no>] [--mpParams <Name.Value,...>]
819 [ --outfileParams <Name,Value,...> ] [--overwrite] [--quiet <yes or no>] [ --removeHydrogens <yes or no>]
820 [--scaffold <auto or SMARTS>] [--scaffoldRMSDOut <yes or no>] [--useTethers <yes or no>]
821 [-w <dir>] -i <infile> -r <reffile> -o <outfile>
822 RDKitGenerateConstrainedConformers.py -h | --help | -e | --examples
823
824 Description:
825 Generate molecular conformations by performing a constrained energy minimization
826 against a reference molecule. An initial set of 3D conformers are generated for the input
827 molecules using distance geometry. A common core scaffold, corresponding to
828 a Maximum Common Substructure (MCS) or an explicit SMARTS pattern, is identified
829 between a pair of input and reference molecules. The core scaffold atoms in input
830 molecules are aligned against the same atoms in the reference molecule. The energy
831 of aligned structures are minimized using the forcefield to generate the final 3D structures.
832
833 The supported input file formats are: Mol (.mol), SD (.sdf, .sd)
834 .csv, .tcsv .txt)
835
836 The supported output file formats are: SD (.sdf, .sd)
837
838 Options:
839 -a, --addHydrogens <yes or no> [default: yes]
840 Add hydrogens before minimization.
841 -c, --conformerGenerator <SDG, ETDG, KDG, ETKDG> [default: ETKDG]
842 Conformation generation methodology for generating initial 3D coordinates
843 for molecules in input file. A common core scaffold is identified between a
844 a pair of input and reference molecules. The atoms in common core scaffold
845 of input molecules are aligned against the reference molecule followed by
846 energy minimization to generate final 3D structure.
847
848 Possible values: Standard Distance Geometry, (SDG), Experimental Torsion-angle
849 preference with Distance Geometry (ETDG), basic Knowledge-terms with Distance
850 Geometry (KDG), and Experimental Torsion-angle preference along with basic
851 Knowledge-terms with Distance Geometry (ETKDG) [Ref 129] .
852 -f, --forceField <UFF, MMFF> [default: MMFF]
853 Forcefield method to use for constrained energy minimization. Possible values:
854 Universal Force Field (UFF) [ Ref 81 ] or Merck Molecular Mechanics Force
855 Field [ Ref 83-87 ] .
856 --forceFieldMMFFVariant <MMFF94 or MMFF94s> [default: MMFF94]
857 Variant of MMFF forcefield to use for energy minimization.
858 --energyOut <yes or no> [default: No]
859 Write out energy values.
860 --enforceChirality <yes or no> [default: Yes]
861 Enforce chirality for defined chiral centers.
862 --energyRMSDCutoff <number> [default: 0.5]
863 RMSD cutoff for retaining conformations after embedding and energy minimization.
864 Possible values. A number or None
865
866 The default is to keep only those conformations which are different from the
867 lowest energy conformation by the specified RMSD cutoff. The None value may
868 be used to keep all minimized conformations with in the specified energy window
869 from the lowest energy conformation. The lowest energy conformation is always
870 retained.
871 --energyWindow <number> [default: 20]
872 Energy window in kcal/mol for selecting conformers.
873 -e, --examples
874 Print examples.
875 -h, --help
876 Print this help message.
877 -i, --infile <infile>
878 Input file name.
879 --infileParams <Name,Value,...> [default: auto]
880 A comma delimited list of parameter name and value pairs for reading
881 molecules from files. The supported parameter names for different file
882 formats, along with their default values, are shown below:
883
884 SD, MOL: removeHydrogens,yes,sanitize,yes,strictParsing,yes
885
886 SMILES: smilesColumn,1,smilesNameColumn,2,smilesDelimiter,space,
887 smilesTitleLine,auto,sanitize,yes
888
889 Possible values for smilesDelimiter: space, comma or tab.
890 --maxConfs <number> [default: 50]
891 Maximum number of conformations to generate for each molecule by conformation
892 generation methodology for initial 3D coordinates. A constrained minimization is
893 performed using the specified forcefield and the lowest energy conformation is written
894 to the output file.
895 --mcsParams <Name,Value,...> [default: auto]
896 Parameter values to use for identifying a maximum common substructure
897 (MCS) in between a pair of reference and input molecules.In general, it is a
898 comma delimited list of parameter name and value pairs. The supported
899 parameter names along with their default values are shown below:
900
901 atomCompare,CompareElements,bondCompare,CompareOrder,
902 maximizeBonds,yes,matchValences,yes,matchChiralTag,no,
903 minNumAtoms,1,minNumBonds,0,ringMatchesRingOnly,yes,
904 completeRingsOnly,yes,threshold,1.0,timeOut,3600,seedSMARTS,none
905
906 Possible values for atomCompare: CompareAny, CompareElements,
907 CompareIsotopes. Possible values for bondCompare: CompareAny,
908 CompareOrder, CompareOrderExact.
909
910 A brief description of MCS parameters taken from RDKit documentation is
911 as follows:
912
913 atomCompare - Controls match between two atoms
914 bondCompare - Controls match between two bonds
915 maximizeBonds - Maximize number of bonds instead of atoms
916 matchValences - Include atom valences in the MCS match
917 matchChiralTag - Include atom chirality in the MCS match
918 minNumAtoms - Minimum number of atoms in the MCS match
919 minNumBonds - Minimum number of bonds in the MCS match
920 ringMatchesRingOnly - Ring bonds only match other ring bonds
921 completeRingsOnly - Partial rings not allowed during the match
922 threshold - Fraction of the dataset that must contain the MCS
923 seedSMARTS - SMARTS string as the seed of the MCS
924 timeout - Timeout for the MCS calculation in seconds
925
926 --mp <yes or no> [default: no]
927 Use multiprocessing.
928
929 By default, input data is retrieved in a lazy manner via mp.Pool.imap()
930 function employing lazy RDKit data iterable. This allows processing of
931 arbitrary large data sets without any additional requirements memory.
932
933 All input data may be optionally loaded into memory by mp.Pool.map()
934 before starting worker processes in a process pool by setting the value
935 of 'inputDataMode' to 'InMemory' in '--mpParams' option.
936
937 A word to the wise: The default 'chunkSize' value of 1 during 'Lazy' input
938 data mode may adversely impact the performance. The '--mpParams' section
939 provides additional information to tune the value of 'chunkSize'.
940 --mpParams <Name,Value,...> [default: auto]
941 A comma delimited list of parameter name and value pairs for to
942 configure multiprocessing.
943
944 The supported parameter names along with their default and possible
945 values are shown below:
946
947 chunkSize, auto
948 inputDataMode, Lazy [ Possible values: InMemory or Lazy ]
949 numProcesses, auto [ Default: mp.cpu_count() ]
950
951 These parameters are used by the following functions to configure and
952 control the behavior of multiprocessing: mp.Pool(), mp.Pool.map(), and
953 mp.Pool.imap().
954
955 The chunkSize determines chunks of input data passed to each worker
956 process in a process pool by mp.Pool.map() and mp.Pool.imap() functions.
957 The default value of chunkSize is dependent on the value of 'inputDataMode'.
958
959 The mp.Pool.map() function, invoked during 'InMemory' input data mode,
960 automatically converts RDKit data iterable into a list, loads all data into
961 memory, and calculates the default chunkSize using the following method
962 as shown in its code:
963
964 chunkSize, extra = divmod(len(dataIterable), len(numProcesses) * 4)
965 if extra: chunkSize += 1
966
967 For example, the default chunkSize will be 7 for a pool of 4 worker processes
968 and 100 data items.
969
970 The mp.Pool.imap() function, invoked during 'Lazy' input data mode, employs
971 'lazy' RDKit data iterable to retrieve data as needed, without loading all the
972 data into memory. Consequently, the size of input data is not known a priori.
973 It's not possible to estimate an optimal value for the chunkSize. The default
974 chunkSize is set to 1.
975
976 The default value for the chunkSize during 'Lazy' data mode may adversely
977 impact the performance due to the overhead associated with exchanging
978 small chunks of data. It is generally a good idea to explicitly set chunkSize to
979 a larger value during 'Lazy' input data mode, based on the size of your input
980 data and number of processes in the process pool.
981
982 The mp.Pool.map() function waits for all worker processes to process all
983 the data and return the results. The mp.Pool.imap() function, however,
984 returns the the results obtained from worker processes as soon as the
985 results become available for specified chunks of data.
986
987 The order of data in the results returned by both mp.Pool.map() and
988 mp.Pool.imap() functions always corresponds to the input data.
989 -o, --outfile <outfile>
990 Output file name.
991 --outfileParams <Name,Value,...> [default: auto]
992 A comma delimited list of parameter name and value pairs for writing
993 molecules to files. The supported parameter names for different file
994 formats, along with their default values, are shown below:
995
996 SD: kekulize,no
997
998 --overwrite
999 Overwrite existing files.
1000 -q, --quiet <yes or no> [default: no]
1001 Use quiet mode. The warning and information messages will not be printed.
1002 -r, --reffile <reffile>
1003 Reference input file name containing a 3D reference molecule. A common
1004 core scaffold must be present in a pair of an input and reference molecules.
1005 Otherwise, no constrained minimization is performed on the input molecule.
1006 --removeHydrogens <yes or no> [default: Yes]
1007 Remove hydrogens after minimization.
1008 -s, --scaffold <auto or SMARTS> [default: auto]
1009 Common core scaffold between a pair of input and reference molecules used for
1010 constrained minimization of molecules in input file. Possible values: Auto or a
1011 valid SMARTS pattern. The common core scaffold is automatically detected
1012 corresponding to the Maximum Common Substructure (MCS) between a pair of
1013 reference and input molecules. A valid SMARTS pattern may be optionally specified
1014 for the common core scaffold.
1015 --scaffoldRMSDOut <yes or no> [default: No]
1016 Write out RMSD value for common core alignment between a pair of input and
1017 reference molecules.
1018 -u, --useTethers <yes or no> [default: yes]
1019 Use tethers to optimize the final conformation by applying a series of extra forces
1020 to align matching atoms to the positions of the core atoms. Otherwise, use simple
1021 distance constraints during the optimization.
1022 -w, --workingdir <dir>
1023 Location of working directory which defaults to the current directory.
1024
1025 Examples:
1026 To generate conformers by performing constrained energy minimization for molecules
1027 in a SMILES file against a reference 3D molecule in a SD file using a common core
1028 scaffold between pairs of input and reference molecules identified using MCS,
1029 generating up to 50 conformations using ETKDG methodology followed by MMFF
1030 forcefield minimization within energy window of 20 kcal/mol and RMSD of greater
1031 than 0.5 from the lowest energy conformation, and write out a SD file:
1032
1033 % RDKitGenerateConstrainedConformers.py -i SampleSeriesD3R.smi
1034 -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1035
1036 To rerun the first example in a quiet mode and write out a SD file, type:
1037
1038 % RDKitGenerateConstrainedConformers.py -q yes -i SampleSeriesD3R.smi
1039 -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1040
1041 To rerun the first example in multiprocessing mode on all available CPUs
1042 without loading all data into memory and write out a SD file, type:
1043
1044 % RDKitGenerateConstrainedConformers.py --mp yes -i SampleSeriesD3R.smi
1045 -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1046
1047 To run the first example in multiprocessing mode on all available CPUs
1048 by loading all data into memory and write out a SD file, type:
1049
1050 % RDKitGenerateConstrainedConformers.py --mp yes --mpParams
1051 "inputDataMode,InMemory" -i SampleSeriesD3R.smi
1052 -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1053
1054 To rerun the first example in multiprocessing mode on specific number of
1055 CPUs and chunk size without loading all data into memory and write out a SD file,
1056 type:
1057
1058 % RDKitGenerateConstrainedConformers.py --mp yes --mpParams
1059 "inputDataMode,Lazy,numProcesses,4,chunkSize,8"
1060 -i SampleSeriesD3R.smi -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1061
1062 To rerun the first example using an explicit SMARTS string for a common core
1063 scaffold and write out a SD file, type:
1064
1065 % RDKitGenerateConstrainedConformers.py --scaffold
1066 "c2cc(-c3nc(N)ncc3)cn2" -i SampleSeriesD3R.smi
1067 -r SampleSeriesRef3D.sdf -o SampleOut.sdf
1068
1069 To rerun the first example using molecules in a CSV SMILES file, SMILES
1070 strings in column 1, name in column2, and write out a SD file, type:
1071
1072 % RDKitGenerateConstrainedConformers.py --infileParams
1073 "smilesDelimiter,comma,smilesTitleLine,yes,smilesColumn,1,
1074 smilesNameColumn,2" -i SampleSeriesD3R.csv -r SampleSeriesRef3D.sdf
1075 -o SampleOut.sdf
1076
1077 To generate constrained conformers for molecules in a SD file against a reference
1078 3D molecule in a SD file using a common core scaffold between pairs of input and
1079 reference molecules identified using MCS, generating up to 10 conformations
1080 using SDG methodology followed by UFF forcefield minimization, conformations
1081 with in an energy window of 10 kcal/mol and RMSD of greater that 1, and write out
1082 a SD file containing minimum energy structure along with energy and embed RMS
1083 values corresponding to each constrained molecule, type:
1084
1085 % RDKitGenerateConstrainedConformers.py --maxConfs 10 -c SDG -f UFF
1086 --scaffoldRMSDOut yes --energyOut yes --energyRMSDCutoff 1.0
1087 --energyWindow 10 -i SampleSeriesD3R.sdf -r SampleSeriesRef3D.sdf
1088 -o SampleOut.sdf
1089
1090 Author:
1091 Manish Sud(msud@san.rr.com)
1092
1093 See also:
1094 RDKitCalculateRMSD.py, RDKitCalculateMolecularDescriptors.py, RDKitCompareMoleculeShapes.py,
1095 RDKitConvertFileFormat.py, RDKitGenerateConformers.py, RDKitPerformConstrainedMinimization.py
1096
1097 Copyright:
1098 Copyright (C) 2020 Manish Sud. All rights reserved.
1099
1100 The functionality available in this script is implemented using RDKit, an
1101 open source toolkit for cheminformatics developed by Greg Landrum.
1102
1103 This file is part of MayaChemTools.
1104
1105 MayaChemTools is free software; you can redistribute it and/or modify it under
1106 the terms of the GNU Lesser General Public License as published by the Free
1107 Software Foundation; either version 3 of the License, or (at your option) any
1108 later version.
1109
1110 """
1111
1112 if __name__ == "__main__":
1113 main()