MayaChemTools

   1 #!/bin/env python
   2 #
   3 # File: PyMOLConvertLigandFileFormat.py
   4 # Author: Manish Sud <msud@san.rr.com>
   5 #
   6 # Copyright (C) 2024 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; MayaChemTools v%s; %s): Starting...\n" % (ScriptName, pymol.cmd.get_version()[0], MiscUtil.GetMayaChemToolsVersion(), 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     ConvertLigandFileFormat()
  79     
  80     MiscUtil.PrintInfo("\n%s: Done...\n" % ScriptName)
  81     MiscUtil.PrintInfo("Total time: %s" % MiscUtil.GetFormattedElapsedTime(WallClockTime, ProcessorTime))
  82 
  83 def ConvertLigandFileFormat():
  84     """Comvert ligand file format."""
  85 
  86     Infile = OptionsInfo["Infile"]
  87     Outfile = OptionsInfo["Outfile"]
  88     
  89     MiscUtil.PrintInfo("\nGenerating file %s..." % Outfile)
  90 
  91     PyMOLUtil.ConvertFileFormat(Infile, Outfile)
  92     
  93     if not os.path.exists(Outfile):
  94         MiscUtil.PrintWarning("Failed to generate Outfile file, %s..." % (Outfile))
  95 
  96 def ProcessOptions():
  97     """Process and validate command line arguments and options."""
  98 
  99     MiscUtil.PrintInfo("Processing options...")
 100     
 101     # Validate options...
 102     ValidateOptions()
 103     
 104     OptionsInfo["Infile"] = Options["--infile"]
 105     OptionsInfo["Outfile"] = Options["--outfile"]
 106 
 107 def RetrieveOptions(): 
 108     """Retrieve command line arguments and options."""
 109     
 110     # Get options...
 111     global Options
 112     Options = docopt(_docoptUsage_)
 113 
 114     # Set current working directory to the specified directory...
 115     WorkingDir = Options["--workingdir"]
 116     if WorkingDir:
 117         os.chdir(WorkingDir)
 118     
 119     # Handle examples option...
 120     if "--examples" in Options and Options["--examples"]:
 121         MiscUtil.PrintInfo(MiscUtil.GetExamplesTextFromDocOptText(_docoptUsage_))
 122         sys.exit(0)
 123 
 124 def ValidateOptions():
 125     """Validate option values."""
 126 
 127     MiscUtil.ValidateOptionFilePath("-i, --infile", Options["--infile"])
 128     MiscUtil.ValidateOptionFileExt("-i, --infile", Options["--infile"], "mol mol2 pdb")
 129     
 130     MiscUtil.ValidateOptionFileExt("-o, --outfile", Options["--outfile"], "mol mol2 pdb")
 131     MiscUtil.ValidateOptionsOutputFileOverwrite("-o, --outfile", Options["--outfile"], "--overwrite", Options["--overwrite"])
 132     MiscUtil.ValidateOptionsDistinctFileNames("-i, --infile", Options["--infile"], "-o, --outfile", Options["--outfile"])
 133 
 134 # Setup a usage string for docopt...
 135 _docoptUsage_ = """
 136 PyMOLConvertLigandFileFormat.py.py - Convert between ligand file formats
 137 
 138 Usage:
 139     PyMOLConvertLigandFileFormat.py.py [--overwrite]
 140                             [-w <dir>] -i <infile> -o <outfile>
 141     PyMOLConvertLigandFileFormat.py.py -h | --help | -e | --examples
 142 
 143 Description:
 144     Convert between ligand file formats.
 145 
 146     The supported input and output file formats are: MDLMOL (.mol), MOL2 (.mol2),
 147     and PDB (.pdb).
 148 
 149 Options:
 150     -e, --examples
 151         Print examples.
 152     -h, --help
 153         Print this help message.
 154     -i, --infile <infile>
 155         Input file name.
 156     -o, --outfile <outfile>
 157         Output file name.
 158     --overwrite
 159         Overwrite existing files.
 160     -w, --workingdir <dir>
 161         Location of working directory which defaults to the current directory.
 162 
 163 Examples:
 164     To convert MDLMOL file format to MOL2  file format, type:
 165 
 166         % PyMOLConvertLigandFileFormat.py -i caffeine.mol -o caffeine.mol2
 167 
 168     To convert MDLMOL file format to PDB  file format, type:
 169 
 170         % PyMOLConvertLigandFileFormat.py -i caffeine.mol -o caffeine.pdb
 171 
 172 Author:
 173     Manish Sud(msud@san.rr.com)
 174 
 175 See also:
 176     PyMOLConvertPMLToPSE.py, PyMOLSplitChainsAndLigands.py,
 177     PyMOLVisualizeMacromolecules.py
 178 
 179 Copyright:
 180     Copyright (C) 2024 Manish Sud. All rights reserved.
 181 
 182     The functionality available in this script is implemented using PyMOL, a
 183     molecular visualization system on an open source foundation originally
 184     developed by Warren DeLano.
 185 
 186     This file is part of MayaChemTools.
 187 
 188     MayaChemTools is free software; you can redistribute it and/or modify it under
 189     the terms of the GNU Lesser General Public License as published by the Free
 190     Software Foundation; either version 3 of the License, or (at your option) any
 191     later version.
 192 
 193 """
 194 
 195 if __name__ == "__main__":
 196     main()