1 #!/bin/env python 2 # 3 # File: PyMOLMutateNucleicAcids.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 PyMOL, a 9 # molecular visualization system on an open source foundation originally 10 # developed by Warren DeLano. 11 # 12 # This file is part of MayaChemTools. 13 # 14 # MayaChemTools is free software; you can redistribute it and/or modify it under 15 # the terms of the GNU Lesser General Public License as published by the Free 16 # Software Foundation; either version 3 of the License, or (at your option) any 17 # later version. 18 # 19 # MayaChemTools is distributed in the hope that it will be useful, but without 20 # any warranty; without even the implied warranty of merchantability of fitness 21 # for a particular purpose. See the GNU Lesser General Public License for more 22 # details. 23 # 24 # You should have received a copy of the GNU Lesser General Public License 25 # along with MayaChemTools; if not, see <http://www.gnu.org/licenses/> or 26 # write to the Free Software Foundation Inc., 59 Temple Place, Suite 330, 27 # Boston, MA, 02111-1307, USA. 28 # 29 30 from __future__ import print_function 31 32 # Add local python path to the global path and import standard library modules... 33 import os 34 import sys; sys.path.insert(0, os.path.join(os.path.dirname(sys.argv[0]), "..", "lib", "Python")) 35 import time 36 import re 37 38 # PyMOL imports... 39 try: 40 import pymol 41 # Finish launching PyMOL in a command line mode for batch processing (-c) 42 # along with the following options: disable loading of pymolrc and plugins (-k); 43 # suppress start up messages (-q) 44 pymol.finish_launching(['pymol', '-ckq']) 45 except ImportError as ErrMsg: 46 sys.stderr.write("\nFailed to import PyMOL module/package: %s\n" % ErrMsg) 47 sys.stderr.write("Check/update your PyMOL 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 PyMOLUtil 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 (PyMOL v%s; %s) Starting...\n" % (ScriptName, pymol.cmd.get_version()[0], 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 PerformMutagenesis() 79 80 MiscUtil.PrintInfo("\n%s: Done...\n" % ScriptName) 81 MiscUtil.PrintInfo("Total time: %s" % MiscUtil.GetFormattedElapsedTime(WallClockTime, ProcessorTime)) 82 83 def PerformMutagenesis(): 84 """Mutate specified residues across chains and generate an output file.""" 85 86 MiscUtil.PrintInfo("\nApplying mutations...") 87 88 # Load macromolecule from input file... 89 MolName = OptionsInfo["InfileRoot"] 90 LoadMolecule(OptionsInfo["Infile"], MolName) 91 92 # Apply mutations... 93 for Mutation, ChainID, ResNum, NewBaseName in OptionsInfo["SpecifiedMutationsInfo"] : 94 ApplyMutation(Mutation, MolName, ChainID, ResNum, NewBaseName) 95 96 # Generate output file... 97 Outfile = OptionsInfo["Outfile"] 98 MiscUtil.PrintInfo("\nGenerating output file %s..." % Outfile) 99 pymol.cmd.save(Outfile, MolName) 100 101 # Delete macromolecule... 102 DeleteMolecule(MolName) 103 104 def ApplyMutation(Mutation, MolName, ChainID, ResNum, NewBaseName): 105 """Apply mutatation. """ 106 107 MiscUtil.PrintInfo("\nApplying mutation %s" % Mutation) 108 109 # Setup wizard for nucleic acids mutagenesis... 110 try: 111 pymol.cmd.wizard("nucmutagenesis") 112 except pymol.CmdException as ErrMsg: 113 MiscUtil.PrintError("The nucleic acids mutageneis wizard is not available in your PyMOL environment.") 114 115 pymol.cmd.refresh_wizard() 116 117 # Setup residue to be mutated... 118 ResSelection = "/%s//%s/%s" % (MolName, ChainID, ResNum) 119 pymol.cmd.get_wizard().do_select(ResSelection) 120 121 # Setup new mutated residue... 122 pymol.cmd.get_wizard().set_mode("%s" % NewBaseName) 123 124 # Mutate... 125 pymol.cmd.get_wizard().apply() 126 127 # Quit wizard... 128 pymol.cmd.set_wizard() 129 130 def RetrieveChainsIDs(): 131 """Retrieve chain IDs. """ 132 133 MolName = OptionsInfo["InfileRoot"] 134 Infile = OptionsInfo["Infile"] 135 136 MiscUtil.PrintInfo("\nRetrieving chains information for input file %s..." % Infile) 137 138 LoadMolecule(Infile, MolName) 139 140 ChainIDs = PyMOLUtil.GetChains(MolName) 141 142 DeleteMolecule(MolName) 143 144 if ChainIDs is None: 145 ChainIDs = [] 146 147 # Print out chain and ligand IDs... 148 ChainInfo = ", ".join(ChainIDs) if len(ChainIDs) else "None" 149 MiscUtil.PrintInfo("Chain IDs: %s" % ChainInfo) 150 151 OptionsInfo["ChainIDs"] = ChainIDs 152 153 def ProcessSpecifiedMutations(): 154 """Process specified mutations""" 155 156 MiscUtil.PrintInfo("\nProcessing specified mutations...") 157 158 CanonicalBaseNameMap = {'ADENINE': 'Adenine', 'CYTOSINE': 'Cytosine', 'GUANINE': 'Guanine', 'THYMINE': 'Thymine', 'URACIL': 'Uracil', 'ADE': 'Adenine', 'CYT': 'Cytosine', 'GUA': 'Guanine', 'THY': 'Thymine', 'URA': 'Uracil'} 159 160 SpecifiedMutationsInfo = [] 161 162 Mutations = re.sub(" ", "", OptionsInfo["Mutations"]) 163 MutationsWords = Mutations.split(",") 164 if not len(MutationsWords): 165 MiscUtil.PrintError("The number of comma delimited mutations specified using \"-m, --mutations\" option, \"%s\", must be > 0." % (OptionsInfo["Mutations"])) 166 167 # Load macromolecule from input file... 168 MolName = OptionsInfo["InfileRoot"] 169 LoadMolecule(OptionsInfo["Infile"], MolName) 170 171 FirstMutation = True 172 CurrentChainID = None 173 CanonicalMutationMap = {} 174 MutationsCount, ValidMutationsCount = [0] * 2 175 176 for Mutation in MutationsWords: 177 MutationsCount += 1 178 if not len(Mutation): 179 MiscUtil.PrintWarning("The mutation, \"%s\", specified using \"-m, --mutations\" option is empty.\nIgnoring mutation..." % (Mutation)) 180 continue 181 182 CanonicalMutation = Mutation.lower() 183 if CanonicalMutation in CanonicalMutationMap: 184 MiscUtil.PrintWarning("The mutation, \"%s\", specified using \"-m, --mutations\" option already exist.\nIgnoring mutation..." % (Mutation)) 185 continue 186 CanonicalMutationMap[CanonicalMutation] = Mutation 187 188 # Match with a chain ID... 189 MatchedResults = re.match(r"^([a-z0-9]+):([0-9]+)([a-z]+)$", Mutation, re.I) 190 if not MatchedResults: 191 # Match without a chain ID... 192 MatchedResults = re.match(r"^([0-9]+)([a-z]+)$", Mutation, re.I) 193 194 if not MatchedResults: 195 MiscUtil.PrintWarning("The format of mutation, \"%s\", specified using \"-m, --mutations\" option is not valid. Supported format: <ChainID>:<ResNum><BaseName> or <ResNum><BaseName>\nIgnoring mutation..." % (Mutation)) 196 continue 197 198 NumOfMatchedGroups = len(MatchedResults.groups()) 199 if NumOfMatchedGroups == 2: 200 ResNum, NewBaseName = MatchedResults.groups() 201 elif NumOfMatchedGroups == 3: 202 CurrentChainID, ResNum, NewBaseName = MatchedResults.groups() 203 else: 204 MiscUtil.PrintWarning("The format of mutation, \"%s\", specified using \"-m, --mutations\" option is not valid. Supported format: <ChainID>:<ResNum><BaseName> or <ResNum><BaseName>\nIgnoring mutation..." % (Mutation)) 205 continue 206 207 if FirstMutation: 208 FirstMutation = False 209 if CurrentChainID is None: 210 MiscUtil.PrintError("The first mutation, \"%s\", specified using \"-m, --mutations\" option must be colon delimited and contain only two values, the first value corresponding to chain ID" % (Mutation)) 211 212 CanonicalBaseName = NewBaseName.upper() 213 if CanonicalBaseName in CanonicalBaseNameMap: 214 NewBaseName = CanonicalBaseNameMap[CanonicalBaseName] 215 216 # Is ResNum and BaseName present in input file? 217 SelectionCmd = "%s and chain %s and resi %s" % (MolName, CurrentChainID, ResNum) 218 ResiduesInfo = PyMOLUtil.GetSelectionResiduesInfo(SelectionCmd) 219 if (ResiduesInfo is None) or (not len(ResiduesInfo["ResNames"])): 220 MiscUtil.PrintWarning("The residue number, %s, in mutation, \"%s\", specified using \"-m, --mutations\" option appears to be missing in input file.\nIgnoring mutation..." % (ResNum, Mutation)) 221 continue 222 223 ValidMutationsCount += 1 224 225 # Track mutation information... 226 SpecifiedMutationsInfo.append([Mutation, CurrentChainID, ResNum, NewBaseName]) 227 228 # Delete macromolecule... 229 DeleteMolecule(MolName) 230 231 MiscUtil.PrintInfo("\nTotal number of mutations: %d" % MutationsCount) 232 MiscUtil.PrintInfo("Number of valid mutations: %d" % ValidMutationsCount) 233 MiscUtil.PrintInfo("Number of ignored mutations: %d" % (MutationsCount - ValidMutationsCount)) 234 235 if not len(SpecifiedMutationsInfo): 236 MiscUtil.PrintError("No valid mutations, \"%s\" specified using \"-m, --mutations\" option." % (OptionsInfo["Mutations"])) 237 238 OptionsInfo["SpecifiedMutationsInfo"] = SpecifiedMutationsInfo 239 240 def LoadMolecule(Infile, MolName): 241 """Load input file. """ 242 243 pymol.cmd.reinitialize() 244 pymol.cmd.load(Infile, MolName) 245 246 def DeleteMolecule(MolName): 247 """Delete molecule.""" 248 249 pymol.cmd.delete(MolName) 250 251 def ProcessOptions(): 252 """Process and validate command line arguments and options""" 253 254 MiscUtil.PrintInfo("Processing options...") 255 256 # Validate options... 257 ValidateOptions() 258 259 OptionsInfo["Infile"] = Options["--infile"] 260 FileDir, FileName, FileExt = MiscUtil.ParseFileName(OptionsInfo["Infile"]) 261 OptionsInfo["InfileRoot"] = FileName 262 263 OptionsInfo["Overwrite"] = Options["--overwrite"] 264 OptionsInfo["Outfile"] = Options["--outfile"] 265 266 RetrieveChainsIDs() 267 268 Mutations = Options["--mutations"] 269 if re.match("^None$", Mutations, re.I): 270 MiscUtil.PrintError("No mutations specified using \"-m, --mutations\" option.") 271 272 OptionsInfo["Mutations"] = Options["--mutations"] 273 ProcessSpecifiedMutations() 274 275 def RetrieveOptions(): 276 """Retrieve command line arguments and options""" 277 278 # Get options... 279 global Options 280 Options = docopt(_docoptUsage_) 281 282 # Set current working directory to the specified directory... 283 WorkingDir = Options["--workingdir"] 284 if WorkingDir: 285 os.chdir(WorkingDir) 286 287 # Handle examples option... 288 if "--examples" in Options and Options["--examples"]: 289 MiscUtil.PrintInfo(MiscUtil.GetExamplesTextFromDocOptText(_docoptUsage_)) 290 sys.exit(0) 291 292 def ValidateOptions(): 293 """Validate option values""" 294 295 MiscUtil.ValidateOptionFilePath("-i, --infile", Options["--infile"]) 296 MiscUtil.ValidateOptionFileExt("-i, --infile", Options["--infile"], "pdb") 297 298 MiscUtil.ValidateOptionsDistinctFileNames("-i, --infile", Options["--infile"], "-o, --outfile", Options["--outfile"]) 299 MiscUtil.ValidateOptionFileExt("-o, --outfile", Options["--outfile"], "pdb") 300 MiscUtil.ValidateOptionsOutputFileOverwrite("-o, --outfile", Options["--outfile"], "--overwrite", Options["--overwrite"]) 301 302 # Setup a usage string for docopt... 303 _docoptUsage_ = """ 304 PyMOLMutateNucleicAcids.py - Mutate nucleic acids 305 306 Usage: 307 PyMOLMutateNucleicAcids.py [--mutations <Spec1,Spec2,...>] 308 [--overwrite] [-w <dir>] -i <infile> -o <outfile> 309 PyMOLMutateNucleicAcids.py -h | --help | -e | --examples 310 311 Description: 312 Mutate nucleic acids in macromolecules. The mutations are performed using 313 nucleic acids mutagenesis wizard available in PyMOL starting V2.2. 314 315 The supported input and output file format is: PDB (.pdb) 316 317 Options: 318 -m, --mutations <Spec1,Spec2,...> [default: None] 319 Comma delimited list of specifications for mutating nucleic acids. 320 321 The format of mutation specification is as follows: 322 323 <ChainID>:<ResNum><BaseName>,... 324 325 A chain ID in the first specification of a mutation is required. It may be 326 skipped in subsequent specifications. The most recent chain ID is used 327 for the missing chain ID. The residue number corresponds to the residue 328 to be mutated and must be present in the current chain. The base name 329 represents the new base. 330 331 Examples: 332 333 A:9Thy, A:10Thy 334 A:9Thy,10Thy,11Thy 335 A:9Thy,10Thy,B:5Ade,6Ade 336 337 The base names must be valid for mutating nucleic acids. No validation 338 validation is performed before mutating residues via nucleic acids 339 mutagenesis wizard available in PyMOL. The current version of the 340 wizard supports the following base names: 341 342 Adenine, Ade 343 Cytosine, Cyt 344 Guanine, Gua 345 Thymine, Thy 346 Uracil, Ura 347 348 -e, --examples 349 Print examples. 350 -h, --help 351 Print this help message. 352 -i, --infile <infile> 353 Input file name. 354 -o, --outfile <outfile> 355 Output file name. 356 --overwrite 357 Overwrite existing files. 358 -w, --workingdir <dir> 359 Location of working directory which defaults to the current directory. 360 361 Examples: 362 To mutate a single residue in a specific chain and write a PDB file, type: 363 364 % PyMOLMutateNucleicAcids.py -m "A:9Thy" -i Sample9.pdb 365 -o Sample9Out.pdb 366 367 To mutate multiple residues in a single chain and write a PDB file, type: 368 369 % PyMOLMutateNucleicAcids.py -m "A:9Thy,10Thy,11Thy" -i Sample9.pdb 370 -o Sample9Out.pdb 371 372 To mutate multiple residues across multiple chains and write a PDB file, type: 373 374 % PyMOLMutateNucleicAcids.py -m "A:9Thy,10Thy,B:5Ade,6Ade" 375 -i Sample9.pdb -o Sample9Out.pdb 376 377 Author: 378 Manish Sud(msud@san.rr.com) 379 380 See also: 381 DownloadPDBFiles.pl, PyMOLMutateAminoAcids.py, 382 PyMOLVisualizeMacromolecules.py 383 384 Copyright: 385 Copyright (C) 2020 Manish Sud. All rights reserved. 386 387 The functionality available in this script is implemented using PyMOL, a 388 molecular visualization system on an open source foundation originally 389 developed by Warren DeLano. 390 391 This file is part of MayaChemTools. 392 393 MayaChemTools is free software; you can redistribute it and/or modify it under 394 the terms of the GNU Lesser General Public License as published by the Free 395 Software Foundation; either version 3 of the License, or (at your option) any 396 later version. 397 398 """ 399 400 if __name__ == "__main__": 401 main()