MayaChemTools

    1 #!/bin/env python
    2 # File: PyMOLUtil.py
    3 # Author: Manish Sud <msud@san.rr.com>
    4 #
    5 # Copyright (C) 2020 Manish Sud. All rights reserved.
    6 #
    7 # The functionality available in this file is implemented using PyMOL, a
    8 # molecular visualization system on an open source foundation originally
    9 # developed by Warren DeLano.
   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 import os
   32 import sys
   33 import re
   34 
   35 from pymol import cmd, stored, CmdException
   36 
   37 import MiscUtil
   38 
   39 __all__ = ["AreAminoAcidResiduesPresent", "AreNucleicAcidResiduesPresent", "CalculateCenterOfMass", "ConvertFileFormat", "ConvertPMLFileToPSEFile", "GetChains", "GetChainsAndLigandsInfo", "GetAminoAcidResiduesInfo", "GetInorganicResiduesInfo", "GetInterfaceChainsResiduesByCAlphaAtomsDistance", "GetInterfaceChainsResiduesByHeavyAtomsDistance", "GetInterfaceChainsResiduesBySASAChange", "GetLargestLigand", "GetLigandResiduesInfo", "GetLigands", "GetMolecules", "GetNucleicAcidResiduesInfo", "GetPocketInorganicResiduesInfo", "GetPocketPolymerResiduesInfo", "GetPocketSolventResiduesInfo",  "GetPolymerResiduesInfo", "GetPhiPsiResiduesInfo", "GetPhiPsiChainsAndResiduesInfo", "GetPhiPsiCategoriesResiduesInfo", "GetSelectionResiduesInfo", "GetSolventResiduesInfo", "GetSurfaceResiduesInfo", "ProcessChainsAndLigandsOptionsInfo", "ProcessResidueTypesOptionsInfo", "ProcessChainSelectionsOptionsInfo", "ProcessSurfaceAtomTypesColorsOptionsInfo", "SetupPMLForAlignment", "SetupPMLForBFactorPuttyView", "SetupPMLForBallAndStickView", "SetupPMLForEnableDisable", "SetupPMLForGroup", "SetupPMLForHydrophobicSurfaceView", "SetupPMLForHydrophobicAndChargeSurfaceView", "SetupPMLForInorganicView", "SetupPMLForLigandPocketInorganicView", "SetupPMLForLigandPocketSolventView", "SetupPMLForLigandPocketView", "SetupPMLForLigandView", "SetupPMLForPolarContactsView", "SetupPMLForHydrophobicContactsView", "SetupPMLForPolymerChainComplexView", "SetupPMLForPolymerChainView", "SetupPMLForPolymerComplexView", "SetupPMLForSolventView", "SetupPMLForSurfaceView", "SetupPMLForSelectionDisplayView", "SetupPMLHeaderInfo"]
   40 
   41 def GetMolecules(Selection = "all"):
   42     """Get names of molecule objects in a selection or all molecule objects.
   43 
   44     Arguments:
   45         Selection: (str): A PyMOL selection.
   46 
   47     Returns:
   48         list: Names of molecule objects.
   49 
   50     """
   51     Names = cmd.get_object_list('(' + Selection + ')')
   52 
   53     return Names
   54 
   55 def GetChains(MoleculeName, RemoveEmpty = True):
   56     """Get chain identifiers present in a molecule.
   57 
   58     Arguments:
   59         MoleculeName (str): Name of a PyMOL molecule object.
   60         RemoveEmpty (bool): Remove empty chain ID from the list of chain IDs
   61             returned by PyMOL.
   62 
   63     Returns:
   64         list: Names of chains present in a molecule, sorted alphabetically in a
   65             ascending order.
   66 
   67     """
   68     if not len(MoleculeName):
   69         return None
   70 
   71     ChainIDs = []
   72     try:
   73         ChainIDs = cmd.get_chains('model %s' % MoleculeName)
   74     except CmdException as ErrMsg:
   75         MiscUtil.PrintWarning("PyMOLUtil.GetChains: Invalid molecule name: %s" % MoleculeName)
   76 
   77     if not len(ChainIDs):
   78         return None
   79 
   80     # Remove empty Chain IDs from the list...
   81     if RemoveEmpty:
   82         NonEmptyChainIDs = []
   83         for ChainID in ChainIDs:
   84             if len(ChainID):
   85                 NonEmptyChainIDs.append(ChainID)
   86         if len(NonEmptyChainIDs) != len(ChainIDs):
   87             MiscUtil.PrintInfo("PyMOLUtil.GetChains: Removing non-empty chain IDs from the list of chain IDs...")
   88             
   89         ChainIDs = NonEmptyChainIDs
   90         
   91     return ChainIDs
   92 
   93 def GetChainsAndLigandsInfo(Infile, MolName, Quite = False, LigandSortBy = "Size", LigandSortOrder = "Auto", LigandIgnoreHydrogens = "Yes"):
   94     """Get chain identifiers present in a molecule along with names of the
   95     ligands present in chains. Ligands are identified using PyMOL 'organic'
   96     selection.
   97 
   98     Arguments:
   99         Infile (str) : Name of a file.
  100         MolName (str) : Name to use for PyMOL molecule object.
  101         Quite (bool) : Flag 
  102         LigandSortBy (str): Sort ligand names alphabetically or by size. Possible
  103             values: Alphabetical or Size
  104         LigandSortOrder (str): Sort order for sorting ligands. Possible values:
  105             Ascending, Descending, Auto. The 'Auto' value implies automatic
  106             determination of sort order based on the value of 'SortBy'.
  107             Automatic defaults: Descending for SortBy value of Size; Ascending
  108             for SortBy value of Alphabetical.
  109         LigandIgnoreHydrogens (str): Ignore hydrogens during determination of ligand
  110             size.
  111 
  112     Returns:
  113         dict: A dictionary containing list of chain identifiers and dictionaries
  114             of chains containing lists of ligand names for each chain. Names of
  115             ligands present in chain for a molecule sorted by size or
  116             alphabetically.
  117 
  118     Examples:
  119 
  120         ChainsAndLigandsInfo = GetChainsAndLigandsInfo(Infile, MolName)
  121         for ChainID in ChainsAndLigandsInfo["ChainIDs"]:
  122             for LigandID in ChainsAndLigandsInfo["LigandIDs"][ChainID]:
  123                 MiscUtil.PrintInfo("ChainID: %s; LigandID: %s" % (ChainID,
  124                     LigandID))
  125 
  126     """
  127     if not Quite:
  128         MiscUtil.PrintInfo("\nRetrieving chain and ligand information from input file %s..." % Infile)
  129     
  130     # Collect chains and ligands information with ligands sorted by size to be used for
  131     # identification of largest ligand at the top...
  132     cmd.load(Infile, MolName)
  133     ChainsAndLigandsInfo = _GetChainsAndLigands(MolName, LigandSortBy = "size", LigandSortOrder = "descending")
  134     cmd.delete(MolName)
  135 
  136     # Print out chain and ligand IDs...
  137     if not Quite:
  138         ChainIDs = ", ".join(ChainsAndLigandsInfo["ChainIDs"]) if len(ChainsAndLigandsInfo["ChainIDs"]) else "None"
  139         MiscUtil.PrintInfo("Chain IDs: %s" % ChainIDs)
  140         
  141         for ChainID in ChainsAndLigandsInfo["ChainIDs"]:
  142             LigandIDs = ", ".join(ChainsAndLigandsInfo["LigandIDs"][ChainID]) if len(ChainsAndLigandsInfo["LigandIDs"][ChainID]) else "None"
  143             MiscUtil.PrintInfo("Chain ID: %s; LigandIDs: %s" % (ChainID, LigandIDs))
  144     
  145     return ChainsAndLigandsInfo
  146 
  147 def GetLigands(MoleculeName, ChainName, SortBy = "Size", SortOrder = "Auto", IgnoreHydrogens = "Yes"):
  148     """Get names of ligands present in a chain of a  molecule. Ligands are
  149     identified using PyMOL 'organic' selection.
  150 
  151     Arguments:
  152         MoleculeName (str): Name of a PyMOL molecule object.
  153         ChainName (str): Name of a chain in a molecule.
  154         SortBy (str): Sort ligand names alphabetically or by size. Possible
  155             values: Alphabetical or Size
  156         SortOrder (str): Sort order for sorting ligands. Possible values:
  157             Ascending, Descending, Auto. The 'Auto' value implies automatic
  158             determination of sort order based on the value of 'SortBy'.
  159             Automatic defaults: Descending for SortBy value of Size; Ascending
  160             for SortBy value of Alphabetical.
  161         IgnoreHydrogens (str): Ignore hydrogens during determination of ligand
  162             size.
  163 
  164     Returns:
  165         list: Names of ligands present in chain for a molecule sorted by size
  166             or alphabetically.
  167 
  168     """
  169     if not (len(MoleculeName) and len(ChainName)):
  170         return None
  171 
  172     LigandsInfoMap = _GetLigandsInfo(MoleculeName, ChainName, SortBy, SortOrder, IgnoreHydrogens)
  173     
  174     LigandIDs = LigandsInfoMap["LigandResNames"]
  175     if not len(LigandIDs):
  176         LigandIDs = None
  177     
  178     return LigandIDs
  179 
  180 def GetLargestLigand(MoleculeName, ChainName, IgnoreHydrogens = 'Yes'):
  181     """Get name of the largest ligand for a chain present in a molecule. Ligands
  182     are identified using PyMOL 'organic' selection.
  183 
  184     Arguments:
  185         IgnoreHydrogens (str): Ignore hydrogens during determination of ligand
  186             size.
  187 
  188     Returns:
  189         str: Name of the largest ligand present in a chain. 
  190 
  191     """
  192     if not (len(MoleculeName) and len(ChainName)):
  193         return None
  194 
  195     SortBy = "Size"
  196     SortOrder = "Descending"
  197     LigandsInfoMap = _GetLigandsInfo(MoleculeName, ChainName, SortBy, SortOrder, IgnoreHydrogens)
  198     LigandIDs = LigandsInfoMap["LigandResNames"]
  199     
  200     if len(LigandIDs):
  201         LigandID = LigandIDs[0]
  202     else:
  203         LigandID = None
  204 
  205     return LigandID
  206 
  207 def _GetChainsAndLigands(MoleculeName, LigandSortBy = "Size", LigandSortOrder = "Auto", LigandIgnoreHydrogens = "Yes"):
  208     """Get chain identifiers in a molecule along with names of the ligands
  209     present in chains. Ligands are identified using PyMOL 'organic' selection.
  210     """
  211     if not len(MoleculeName):
  212         return None
  213 
  214     ChainIDs = GetChains(MoleculeName)
  215     if ChainIDs is None:
  216         return None
  217         
  218     ChainsAndLigandsMap = {}
  219     ChainsAndLigandsMap["ChainIDs"] = []
  220     ChainsAndLigandsMap["LigandIDs"] = {}
  221     
  222     for ChainID in ChainIDs:
  223         ChainsAndLigandsMap["ChainIDs"].append(ChainID)
  224         ChainsAndLigandsMap["LigandIDs"][ChainID] = []
  225         
  226         LigandIDs = GetLigands(MoleculeName, ChainID, SortBy = LigandSortBy, SortOrder = LigandSortOrder, IgnoreHydrogens = LigandIgnoreHydrogens)
  227         if LigandIDs is not None:
  228             ChainsAndLigandsMap["LigandIDs"][ChainID] = LigandIDs
  229         
  230     return ChainsAndLigandsMap
  231 
  232 def _GetLigandsInfo(MoleculeName, ChainName, SortBy = "Size", SortOrder = "Auto", IgnoreHydrogens = "Yes"):
  233     """Retrieve information about ligands present in a chain of a molecule."""
  234 
  235     if not MiscUtil.CheckTextValue(SortBy, "Size Alphabetical"):
  236         MiscUtil.PrintError("PyMOLUtil._GetLigandsInfo: The value specified, %s, for parameter SortBy is not valid. SupportedValues: Size Alphabetical" % SortBy)
  237         
  238     if not MiscUtil.CheckTextValue(SortOrder, "Ascending Descending Auto"):
  239         MiscUtil.PrintError("PyMOLUtil._GetLigandsInfo: The value specified, %s, for parameter SortOrder is not valid. SupportedValues: Ascending Descending Auto" % SortOrder)
  240         
  241     if not MiscUtil.CheckTextValue(IgnoreHydrogens, "Yes No"):
  242         MiscUtil.PrintError("PyMOLUtil._GetLigandsInfo: The value specified, %s, for parameter IgnoreHydrogens is not valid. SupportedValues: Yes No" % IgnoreHydrogens)
  243         
  244     SortBySize = True if re.match("^Size$", SortBy, re.I) else False
  245     if re.match("^Auto$", SortOrder, re.I):
  246         SortOrderDescending = True if re.match("^Size$", SortBy, re.I) else False
  247     else:
  248         SortOrderDescending = True if re.match("^Descending$", SortOrder, re.I) else False
  249     IgnoreHydrogenAtoms = True if re.match("^Yes$", IgnoreHydrogens, re.I) else False
  250 
  251     # Set up a command to retrieve all appropriate ligand atoms in organic ligands...
  252     SelectionCmd = "%s and chain %s and organic" % (MoleculeName, ChainName)
  253     if IgnoreHydrogenAtoms:
  254         SelectionCmd = "%s and not hydro" % (SelectionCmd)
  255 
  256     # Retrieve atoms...
  257     stored.LigandsInfo = []
  258     cmd.iterate(SelectionCmd, "stored.LigandsInfo.append([resi, resn])")
  259 
  260     # Retrieve ligands...
  261     LigandsInfoMap = {}
  262     LigandsInfoMap["LigandResNames"] = []
  263     LigandsInfoMap["LigandAtomCount"] = {}
  264     LigandsInfoMap["LigandResNumber"] = {}
  265     
  266     for LigandResNum, LigandResName in stored.LigandsInfo:
  267         if LigandResName in LigandsInfoMap["LigandResNames"]:
  268             LigandsInfoMap["LigandAtomCount"][LigandResName] += 1
  269         else:
  270             LigandsInfoMap["LigandResNames"].append(LigandResName)
  271             LigandsInfoMap["LigandAtomCount"][LigandResName] = 1
  272             LigandsInfoMap["LigandResNumber"][LigandResName] = LigandResNum
  273 
  274     if not len(LigandsInfoMap["LigandResNames"]):
  275         return LigandsInfoMap
  276         
  277     # Sort ligand names...
  278     ReverseOrder = True if SortOrderDescending else False
  279     if SortBySize:
  280         SortedLigandResNames = sorted(LigandsInfoMap["LigandResNames"], key = lambda LigandResName: LigandsInfoMap["LigandAtomCount"][LigandResName], reverse = ReverseOrder)
  281     else:
  282         # Sort alphabetically...
  283         SortedLigandResNames = sorted(LigandsInfoMap["LigandResNames"], reverse = ReverseOrder)
  284 
  285     LigandsInfoMap["LigandResNames"] = SortedLigandResNames
  286     
  287     return LigandsInfoMap
  288 
  289 def AreAminoAcidResiduesPresent(MoleculeName, ChainName, Type = "Any"):
  290     """Check for the presence of amino acid residues in a chain of a
  291     molecule. Chains are identified using PyMOL 'polymer' selection.
  292     Nonstandard amino acid residues correspond to all residues other than
  293     the standard amino acids and nucleic acids. Any amino acid residues cover
  294     all residues other than the standard nucleic acids.
  295 
  296     Arguments:
  297         MoleculeName (str): Name of a PyMOL molecule object.
  298         ChainName (str): Name of a chain in a molecule.
  299         Type (str): Types of amino acids: Standard, NonStandard, Any
  300 
  301     Returns:
  302         boolean: True or False.
  303 
  304     """
  305     
  306     if not (len(MoleculeName) and len(ChainName)):
  307         return False
  308 
  309     if not re.match("^(Standard|NonStandard|Any)$", Type, re.I):
  310         MiscUtil.PrintError("PyMOLUtil.AreAminoAcidResiduesPresent: Invalid amino acid type: %s" % Type)
  311 
  312     SelectionCmd = _SetupAminoAcidResiduesSelectionCmd(MoleculeName, ChainName, Type)
  313     
  314     Status = True if cmd.count_atoms(SelectionCmd) else False
  315     
  316     return Status
  317     
  318 def AreNucleicAcidResiduesPresent(MoleculeName, ChainName):
  319     """Check for the presence of nucleic acid residues in a chain of a 
  320     molecule. Chains are identified using PyMOL 'polymer' selection.
  321 
  322     Arguments:
  323         MoleculeName (str): Name of a PyMOL molecule object.
  324         ChainName (str): Name of a chain in a molecule.
  325 
  326     Returns:
  327         boolean: True or False.
  328 
  329     """
  330     
  331     if not (len(MoleculeName) and len(ChainName)):
  332         return False
  333     
  334     ResidueNames = _GetNucleicAcidResidueNames()
  335     if not len(ResidueNames):
  336         return False
  337     
  338     ResidueNamesSelection = "+".join(ResidueNames)
  339     SelectionCmd = "(%s and chain %s and polymer and (resn %s))" % (MoleculeName, ChainName, ResidueNamesSelection)
  340 
  341     Status = True if cmd.count_atoms(SelectionCmd) else False
  342     
  343     return Status
  344     
  345 def _SetupAminoAcidResiduesSelectionCmd(MoleculeName, ChainName, Type):
  346     """Set up amino acids selection command for PyMOL. """
  347     
  348     AminoAcidsSelection = "+".join(_GetAminoAcidResidueNames())
  349     NucleicAcidsSelection = "+".join(_GetNucleicAcidResidueNames())
  350     
  351     if re.match("^Standard$", Type, re.I):
  352         SelectionCmd = "(%s and chain %s and polymer and (resn %s))" % (MoleculeName, ChainName, AminoAcidsSelection)
  353     elif re.match("^NonStandard$", Type, re.I):
  354         SelectionCmd = "(%s and chain %s and polymer and (not ((resn %s) or (resn %s))))" % (MoleculeName, ChainName, AminoAcidsSelection, NucleicAcidsSelection)
  355     else:
  356         # Any amino acid resiudes...
  357         SelectionCmd = "(%s and chain %s and polymer and (not (resn %s)))" % (MoleculeName, ChainName, NucleicAcidsSelection)
  358 
  359     return SelectionCmd
  360 
  361 def _GetAminoAcidResidueNames():
  362     """Get list of amino acid residue names.
  363     """
  364     
  365     ResidueNames = ["ALA", "ARG", "ASN", "ASP", "CYS", "GLN", "GLU", "GLY", "HIS", "ILE", "LEU", "LYS", "MET", "PHE", "PRO", "SER", "THR", "TRP", "TYR", "VAL"]
  366     
  367     return ResidueNames
  368 
  369 def _GetNucleicAcidResidueNames():
  370     """Get list of nucleic acid residue names.
  371     """
  372     
  373     ResidueNames = ["A", "G", "T", "U", "C", "DA", "DG", "DT", "DU", "DC"]
  374     
  375     return ResidueNames
  376 
  377 def GetPolymerResiduesInfo(MoleculeName, ChainName):
  378     """Get information for residues present in a chain of a  molecule.
  379     Chains are identified using PyMOL 'polymer' selection.
  380 
  381     Arguments:
  382         MoleculeName (str): Name of a PyMOL molecule object.
  383         ChainName (str): Name of a chain in a molecule.
  384 
  385     Returns:
  386         dict: A dictionary containing list of residue names and dictionaries of
  387             residue numbers and residue count for each residue. Names of 
  388             residues in the dictionary are not sorted.
  389 
  390     Examples:
  391 
  392         ResiduesInfo = GetPolymerResiduesInfo(MolName, ChainName)
  393         for ResName in ResiduesInfo["ResNames"]:
  394             ResCount = ResiduesInfo["ResCount"][ResName]
  395             ResNums = ResiduesInfo["ResNum"][ResName]
  396             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  397                 (ResName, ResCount, ResNums))
  398 
  399     """
  400     if not (len(MoleculeName) and len(ChainName)):
  401         return None
  402 
  403     SelectionCmd = "%s and chain %s and polymer" % (MoleculeName, ChainName)
  404     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  405 
  406     return ResiduesInfoMap
  407 
  408 def GetAminoAcidResiduesInfo(MoleculeName, ChainName, Type = "Standard"):
  409     """Get information for amino acid residues present in a chain of a
  410     molecule. Chains are identified using PyMOL 'polymer' selection.
  411     Nonstandard amino acid residues correspond to all residues other than
  412     the standard amino acids and nucleic acids. Any amino acid residues cover
  413     all residues other than the standard nucleic acids.
  414 
  415     Arguments:
  416         MoleculeName (str): Name of a PyMOL molecule object.
  417         ChainName (str): Name of a chain in a molecule.
  418         Type (str): Types of amino acids: Standard, NonStandard, Any
  419 
  420     Returns:
  421         dict: A dictionary containing list of residue names and dictionaries of
  422             residue numbers and residue count for each residue. Names of 
  423             residues in the dictionary are not sorted.
  424 
  425     Examples:
  426 
  427         ResiduesInfo = GetPolymerResiduesInfo(MolName, ChainName)
  428         for ResName in ResiduesInfo["ResNames"]:
  429             ResCount = ResiduesInfo["ResCount"][ResName]
  430             ResNums = ResiduesInfo["ResNum"][ResName]
  431             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  432                 (ResName, ResCount, ResNums))
  433 
  434     """
  435     
  436     if not (len(MoleculeName) and len(ChainName)):
  437         return None
  438 
  439     if not re.match("^(Standard|NonStandard|Any)$", Type, re.I):
  440         MiscUtil.PrintError("PyMOLUtil.GetAminoAcidResiduesInfo: Invalid amino acid type: %s" % Type)
  441     
  442     SelectionCmd = _SetupAminoAcidResiduesSelectionCmd(MoleculeName, ChainName, Type)
  443     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  444 
  445     return ResiduesInfoMap
  446 
  447 def GetNucleicAcidResiduesInfo(MoleculeName, ChainName):
  448     """Get information for nucleic acid residues present in a chain of
  449     a  molecule. Chains are identified using PyMOL 'polymer' selection.
  450 
  451     Arguments:
  452         MoleculeName (str): Name of a PyMOL molecule object.
  453         ChainName (str): Name of a chain in a molecule.
  454 
  455     Returns:
  456         dict: A dictionary containing list of residue names and dictionaries of
  457             residue numbers and residue count for each residue. Names of 
  458             residues in the dictionary are not sorted.
  459 
  460     Examples:
  461 
  462         ResiduesInfo = GetPolymerResiduesInfo(MolName, ChainName)
  463         for ResName in ResiduesInfo["ResNames"]:
  464             ResCount = ResiduesInfo["ResCount"][ResName]
  465             ResNums = ResiduesInfo["ResNum"][ResName]
  466             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  467                 (ResName, ResCount, ResNums))
  468 
  469     """
  470     
  471     if not (len(MoleculeName) and len(ChainName)):
  472         return None
  473 
  474     ResidueNames = _GetNucleicAcidResidueNames()
  475     
  476     ResidueNamesSelection = "+".join(ResidueNames)
  477     SelectionCmd = "(%s and chain %s and polymer and (resn %s))" % (MoleculeName, ChainName, ResidueNamesSelection)
  478     
  479     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  480 
  481     return ResiduesInfoMap
  482 
  483 def GetSelectionResiduesInfo(SelectionCmd):
  484     """Get information for residues in a chain specified by a selection command.
  485 
  486     Arguments:
  487         SelectionCmd (str): PyMOL selection command.
  488 
  489     Returns:
  490         dict: A dictionary containing list of residue names and dictionaries of
  491             residue numbers and residue count for each residue. Names of 
  492             residues in the dictionary are not sorted.
  493 
  494     Examples:
  495 
  496         ResiduesInfo = GetSelectionResiduesInfo(SelectionCmd)
  497         for ResName in ResiduesInfo["ResNames"]:
  498             ResCount = ResiduesInfo["ResCount"][ResName]
  499             ResNums = ResiduesInfo["ResNum"][ResName]
  500             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  501                 (ResName, ResCount, ResNums))
  502 
  503     """
  504     if not len(SelectionCmd):
  505         return None
  506 
  507     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  508 
  509     return ResiduesInfoMap
  510 
  511 def GetSolventResiduesInfo(MoleculeName, ChainName):
  512     """Get information for solvent residues present in a chain of a  molecule.
  513     Solvents are identified using PyMOL 'solvent' selection.
  514 
  515     Arguments:
  516         MoleculeName (str): Name of a PyMOL molecule object.
  517         ChainName (str): Name of a chain in a molecule.
  518 
  519     Returns:
  520         dict: A dictionary containing list of residue names and dictionaries of
  521             residue numbers and residue count for each residue. Names of 
  522             residues in the dictionary are not sorted.
  523 
  524     Examples:
  525 
  526         ResiduesInfo = GetSolventResiduesInfo(MolName, ChainName)
  527         for ResName in ResiduesInfo["ResNames"]:
  528             ResCount = ResiduesInfo["ResCount"][ResName]
  529             ResNums = ResiduesInfo["ResNum"][ResName]
  530             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  531                 (ResName, ResCount, ResNums))
  532 
  533     """
  534     if not (len(MoleculeName) and len(ChainName)):
  535         return None
  536 
  537     SelectionCmd = "%s and chain %s and solvent" % (MoleculeName, ChainName)
  538     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  539 
  540     return ResiduesInfoMap
  541 
  542 def GetInorganicResiduesInfo(MoleculeName, ChainName):
  543     """Get information for inorganic residues present in a chain of a  molecule.
  544     Inorganic residues are identified using PyMOL 'inorganic' selection.
  545 
  546     Arguments:
  547         MoleculeName (str): Name of a PyMOL molecule object.
  548         ChainName (str): Name of a chain in a molecule.
  549 
  550     Returns:
  551         dict: A dictionary containing list of residue names and dictionaries of
  552             residue numbers and residue count for each residue. Names of 
  553             residues in the dictionary are not sorted.
  554 
  555     Examples:
  556 
  557         ResiduesInfo = GetInorganicResiduesInfo(MolName, ChainName)
  558         for ResName in ResiduesInfo["ResNames"]:
  559             ResCount = ResiduesInfo["ResCount"][ResName]
  560             ResNums = ResiduesInfo["ResNum"][ResName]
  561             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  562                 (ResName, ResCount, ResNums))
  563 
  564     """
  565     if not (len(MoleculeName) and len(ChainName)):
  566         return None
  567 
  568     SelectionCmd = "%s and chain %s and inorganic" % (MoleculeName, ChainName)
  569     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  570 
  571     return ResiduesInfoMap
  572 
  573 def GetLigandResiduesInfo(MoleculeName, ChainName):
  574     """Get information for ligand residues present in a chain of a  molecule.
  575     Ligands are identified using PyMOL 'organic' selection.
  576 
  577     Arguments:
  578         MoleculeName (str): Name of a PyMOL molecule object.
  579         ChainName (str): Name of a chain in a molecule.
  580 
  581     Returns:
  582         dict: A dictionary containing list of residue names and dictionaries of
  583             residue numbers and residue count for each residue. Names of 
  584             residues in the dictionary are not sorted.
  585 
  586     Examples:
  587 
  588         ResiduesInfo = GetLigandResiduesInfo(MolName, ChainName)
  589         for ResName in ResiduesInfo["ResNames"]:
  590             ResCount = ResiduesInfo["ResCount"][ResName]
  591             ResNums = ResiduesInfo["ResNum"][ResName]
  592             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  593                 (ResName, ResCount, ResNums))
  594 
  595     """
  596     if not (len(MoleculeName) and len(ChainName)):
  597         return None
  598 
  599     SelectionCmd = "%s and chain %s and organic" % (MoleculeName, ChainName)
  600     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  601 
  602     return ResiduesInfoMap
  603 
  604 def GetPocketPolymerResiduesInfo(MoleculeName, ChainName, LigandResName, LigandResNum, PocketDistanceCutoff):
  605     """Get information for chain residues present in a pocket around a ligand
  606     in a molecule. Polymer residues are identified using negation of PyMOL
  607     selection operators 'organic', 'solvent', and 'inorganic'.
  608 
  609     Arguments:
  610         MoleculeName (str): Name of a PyMOL molecule object.
  611         ChainName (str): Name of a chain in a molecule.
  612         LigandResName (str): Residue name of a ligand in a chain.
  613         LigandResNum (str): Residue number of a ligand in a chain.
  614         PocketDistanceCutoff (float): Distance around ligand to identify pocket
  615             residues.
  616 
  617     Returns:
  618         dict: A dictionary containing list of residue names and dictionaries of
  619             residue numbers and residue count for each residue. Names of 
  620             residues in the dictionary are not sorted.
  621 
  622     Examples:
  623 
  624         ResiduesInfo = GetPocketPolymerResiduesInfo(MolName, ChainName)
  625         for ResName in ResiduesInfo["ResNames"]:
  626             ResCount = ResiduesInfo["ResCount"][ResName]
  627             ResNums = ResiduesInfo["ResNum"][ResName]
  628             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  629                 (ResName, ResCount, ResNums))
  630 
  631     """
  632     if not (len(MoleculeName) and len(ChainName) and len(LigandResName) and len(LigandResNum)):
  633         return None
  634 
  635     LigandSelection = "%s and chain %s and organic and resn %s and resi %s" % (MoleculeName, ChainName, LigandResName, LigandResNum)
  636     MoleculeSelection = "%s and chain %s" % (MoleculeName, ChainName)
  637     SelectionCmd = "((byresidue (%s) within %.1f of (%s))  and (not solvent) and (not inorganic) and (not organic))" % (MoleculeSelection, PocketDistanceCutoff, LigandSelection)
  638 
  639     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  640 
  641     return ResiduesInfoMap
  642 
  643 def GetPocketSolventResiduesInfo(MoleculeName, ChainName, LigandResName, LigandResNum, PocketDistanceCutoff):
  644     """Get information for solvent residues present in a pocket around a ligand
  645     in a molecule. Solvent residues are identified using PyMOL 'solvent'
  646     selection.
  647 
  648     Arguments:
  649         MoleculeName (str): Name of a PyMOL molecule object.
  650         ChainName (str): Name of a chain in a molecule.
  651         LigandResName (str): Residue name of a ligand in a chain.
  652         LigandResNum (str): Residue number of a ligand in a chain.
  653         PocketDistanceCutoff (float): Distance around ligand to identify pocket
  654             residues.
  655 
  656     Returns:
  657         dict: A dictionary containing list of residue names and dictionaries of
  658             residue numbers and residue count for each residue. Names of 
  659             residues in the dictionary are not sorted.
  660 
  661     Examples:
  662 
  663         ResiduesInfo = GetPocketSolventResiduesInfo(MolName, ChainName)
  664         for ResName in ResiduesInfo["ResNames"]:
  665             ResCount = ResiduesInfo["ResCount"][ResName]
  666             ResNums = ResiduesInfo["ResNum"][ResName]
  667             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  668                 (ResName, ResCount, ResNums))
  669 
  670     """
  671     if not (len(MoleculeName) and len(ChainName) and len(LigandResName) and len(LigandResNum)):
  672         return None
  673 
  674     LigandSelection = "%s and chain %s and organic and resn %s and resi %s" % (MoleculeName, ChainName, LigandResName, LigandResNum)
  675     MoleculeSelection = "%s and chain %s" % (MoleculeName, ChainName)
  676     SelectionCmd = "((byresidue (%s) within %.1f of (%s))  and solvent)" % (MoleculeSelection, PocketDistanceCutoff, LigandSelection)
  677 
  678     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  679 
  680     return ResiduesInfoMap
  681 
  682 def GetPocketInorganicResiduesInfo(MoleculeName, ChainName, LigandResName, LigandResNum, PocketDistanceCutoff):
  683     """Get information for inorganic residues present in a pocket around a
  684     ligand in a molecule. Inorganic residues are identified using PyMOL
  685     'inorganic' selection.
  686 
  687     Arguments:
  688         MoleculeName (str): Name of a PyMOL molecule object.
  689         ChainName (str): Name of a chain in a molecule.
  690         LigandResName (str): Residue name of a ligand in a chain.
  691         LigandResNum (str): Residue number of a ligand in a chain.
  692         PocketDistanceCutoff (float): Distance around a ligand to identify
  693             pocket residues.
  694 
  695     Returns:
  696         dict: A dictionary containing list of residue names and dictionaries of
  697             residue numbers and residue count for each residue. Names of 
  698             residues in the dictionary are not sorted.
  699 
  700     Examples:
  701 
  702         ResiduesInfo = GetPocketInorganicResiduesInfo(MolName, ChainName)
  703         for ResName in ResiduesInfo["ResNames"]:
  704             ResCount = ResiduesInfo["ResCount"][ResName]
  705             ResNums = ResiduesInfo["ResNum"][ResName]
  706             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  707                 (ResName, ResCount, ResNums))
  708 
  709     """
  710     if not (len(MoleculeName) and len(ChainName) and len(LigandResName) and len(LigandResNum)):
  711         return None
  712 
  713     LigandSelection = "%s and chain %s and organic and resn %s and resi %s" % (MoleculeName, ChainName, LigandResName, LigandResNum)
  714     MoleculeSelection = "%s and chain %s" % (MoleculeName, ChainName)
  715     SelectionCmd = "((byresidue (%s) within %.1f of (%s))  and inorganic)" % (MoleculeSelection, PocketDistanceCutoff, LigandSelection)
  716 
  717     ResiduesInfoMap = _GetSelectionResiduesInfo(SelectionCmd)
  718 
  719     return ResiduesInfoMap
  720 
  721 def GetPhiPsiResiduesInfo(MoleculeName, ChainName, Categorize = True):
  722     """Get phi and psi torsion angle information for residues in a chain of a
  723     molecule containing amino acids.
  724     
  725     The phi and psi angles are optionally categorized into the following groups
  726     corresponding to four types of  Ramachandran plots:
  727     
  728     General: All residues except glycine, proline, or pre-proline
  729     Glycine: Only glycine residues
  730     Proline: Only proline residues
  731     Pre-Proline: Only residues before proline not including glycine or proline
  732     
  733     Arguments:
  734         MoleculeName (str): Name of a PyMOL molecule object.
  735         ChainName (str): Name of a chain in a molecule.
  736 
  737     Returns:
  738         dict: A dictionary containing sorted list of residue numbers and
  739             dictionaries of residue names, phi and psi angles for each residue
  740             number.
  741 
  742     Examples:
  743 
  744         PhiPsiInfoMap = GetPhiPsiResiduesInfo(MolName, ChainName, True)
  745         for ResNum in PhiPsiInfoMap["ResNums"]:
  746             ResName = PhiPsiInfoMap["ResName"][ResNum]
  747             Phi = PhiPsiInfoMap["Phi"][ResNum]
  748             Psi = PhiPsiInfoMap["Psi"][ResNum]
  749             Category = PhiPsiInfoMap["Category"][ResNum]
  750             MiscUtil.PrintInfo("ResNum: %s; ResName: %s; Phi: %8.2f;
  751                 Psi: %8.2f; Category: %s" % (ResNum, ResName, Phi, Psi,
  752                 Categorize))
  753 
  754     """
  755     if not (len(MoleculeName) and len(ChainName)):
  756         return None
  757     
  758     SelectionCmd = "%s and chain %s" % (MoleculeName, ChainName)
  759     PhiPsiResiduesInfoMap = _GetSelectionPhiPsiResiduesInfo(SelectionCmd, Categorize)
  760 
  761     return PhiPsiResiduesInfoMap
  762 
  763 def GetPhiPsiChainsAndResiduesInfo(MoleculeName, Categorize = True):
  764     """Get phi and psi torsion angle information for residues across chains in
  765     a molecule containing amino acids.
  766 
  767     The phi and psi angles are optionally categorized into the following groups
  768     corresponding to four types of  Ramachandran plots:
  769     
  770     General: All residues except glycine, proline, or pre-proline
  771     Glycine: Only glycine residues
  772     Proline: Only proline residues
  773     Pre-Proline: Only residues before proline not including glycine or proline
  774     
  775     Arguments:
  776         MoleculeName (str): Name of a PyMOL molecule object.
  777 
  778     Returns:
  779         dict: A dictionary containing sorted list of residue numbers for each
  780             chain and dictionaries of residue names, phi and psi angles for each
  781             residue number.
  782 
  783     Examples:
  784 
  785         PhiPsiInfoMap = GetPhiPsiChainsAndResiduesInfo(MolName)
  786         for ChainID in PhiPsiInfoMap["ChainIDs"]:
  787             for ResNum in PhiPsiInfoMap["ResNums"][ChainID]:
  788                 ResName = PhiPsiInfoMap["ResName"][ChainID][ResNum]
  789                 Phi = PhiPsiInfoMap["Phi"][ChainID][ResNum]
  790                 Psi = PhiPsiInfoMap["Psi"][ChainID][ResNum]
  791                 Category = PhiPsiInfoMap["Category"][ChainID][ResNum]
  792                 MiscUtil.PrintInfo("ChainID: %s; ResNum: %s; ResName: %s; Phi: %8.2f;
  793                     Psi: %8.2f; Category: %s" % (ChainID, ResNum, ResName, Phi,
  794                     Psi, Category))
  795 
  796     """
  797     if not len(MoleculeName):
  798         return None
  799 
  800     SelectionCmd = "%s" % (MoleculeName)
  801     PhiPsiResiduesInfoMap = _GetSelectionPhiPsiChainsAndResiduesInfo(SelectionCmd, Categorize)
  802 
  803     return PhiPsiResiduesInfoMap
  804 
  805 def GetPhiPsiCategoriesResiduesInfo(MoleculeName, ChainName):
  806     """Get phi and psi torsion angle information for residues in a chain of a
  807     molecule containing amino acids.
  808 
  809     The phi and psi angles are optionally categorized into the following groups
  810     corresponding to four types of  Ramachandran plots:
  811     
  812     General: All residues except glycine, proline, or pre-proline
  813     Glycine: Only glycine residues
  814     Proline: Only proline residues
  815     Pre-Proline: Only residues before proline not including glycine or proline
  816     
  817     Arguments:
  818         MoleculeName (str): Name of a PyMOL molecule object.
  819         ChainName (str): Name of a chain in a molecule.
  820 
  821     Returns:
  822         dict1: Phi and psi angle information for residues in General category.
  823             It's a dictionary containing sorted list of residue numbers and
  824             dictionaries of residue names, phi and psi angles for each residue
  825             number.
  826         dict2: Phi and psi angle information for residues in Gly category.
  827         dict3: Phi and psi angle information for residues in Pro category.
  828         dict2: Phi and psi angle information for residues in Pre-Pro category.
  829 
  830     Examples:
  831 
  832         GeneralPhiPsiInfo, GlyPhiPsiInfo, ProPhiPsiInfo, PreProPhiPsiInfo =
  833             GetPhiPsiCategoriesResiduesInfo(MolName, ChainID)
  834         for ResNum in GeneralPhiPsiInfo["ResNums"]:
  835             ResName = GeneralPhiPsiInfo["ResName"][ResNum]
  836             Phi = GeneralPhiPsiInfo["Phi"][ResNum]
  837             Psi = GeneralPhiPsiInfo["Psi"][ResNum]
  838             MiscUtil.PrintInfo("ResNum: %s; ResName: %s;
  839                 Phi: %8.2f; Psi: %8.2f" % (ResNum, ResName, Phi, Psi))
  840 
  841     """
  842     if not (len(MoleculeName) and len(ChainName)):
  843         return None
  844 
  845     SelectionCmd = "%s and chain %s" % (MoleculeName, ChainName)
  846     GeneralPhiPsiInfo, GlyPhiPsiInfo, ProPhiPsiInfo, PreProPhiPsiInfo = _GetSelectionPhiPsiCategoriesResiduesInfo(SelectionCmd)
  847 
  848     return GeneralPhiPsiInfo, GlyPhiPsiInfo, ProPhiPsiInfo, PreProPhiPsiInfo
  849 
  850 def GetSurfaceAndBuriedResiduesInfo(MoleculeName, ChainName, SASACutoff = 2.5):
  851     """Get information for surafce and buried residues present in a chain of a
  852     molecule. The surface residues correspond to residues with Solvent Accessible
  853     Surface Area (SASA) greater than or equal to the cutoff value. Otherwise, these
  854     residues are considered as buried residues.
  855 
  856     Arguments:
  857         MoleculeName (str): Name of a PyMOL molecule object.
  858         ChainName (str): Name of a chain in a molecule.
  859         SASACutoff (float): SASA cutoff for heavy atoms corresponding to
  860             surface residues in chain. Units: Angstroms ** 2
  861 
  862     Returns:
  863         dict: A dictionary containing list of residue names and dictionaries of
  864             residue numbers and residue count for each residue. Names of 
  865             residues in the dictionary are not sorted.
  866         dict2: Buried residues in a chain.
  867 
  868     Examples:
  869 
  870         SurfaceResiduesInfo, BurriedResiduesInfo =
  871             GetSurfaceResiduesInfo(MolName, ChainName, 2.5)
  872         for ResName in SurfaceResiduesInfo["ResNames"]:
  873             ResCount = ResiduesInfo["ResCount"][ResName]
  874             ResNums = ResiduesInfo["ResNum"][ResName]
  875             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
  876                 (ResName, ResCount, ResNums))
  877 
  878     """
  879     if not (len(MoleculeName) and len(ChainName)):
  880         return None
  881     
  882     # Get ready to calculate solvent accessible surface area..
  883     CurrentDotSolvent = cmd.get("dot_solvent")
  884     cmd.set("dot_solvent", 1)
  885 
  886     # Setup tmp object name...
  887     TmpChainName = "Tmp_%s" % (MoleculeName)
  888     TmpChainSelection = "(%s and chain %s and polymer and not hydrogens)" % (MoleculeName, ChainName)
  889     cmd.create(TmpChainName, "(%s)" % (TmpChainSelection))
  890 
  891     # Calculate SASA for chain and load it into b...
  892     cmd.get_area(TmpChainName, load_b = 1)
  893     
  894     # Retrieve SASA for residues as B values...
  895     ResiduesBValuesInfoMap = _GetSelectionResiduesBValuesInfo(TmpChainName)
  896 
  897     # Retrieve information for surface and buried residues...
  898     SurfaceResiduesInfoMap = _GetResiduesInfoFromResiduesBValues(ResiduesBValuesInfoMap, ">=", SASACutoff)
  899     BuriedResiduesInfoMap = _GetResiduesInfoFromResiduesBValues(ResiduesBValuesInfoMap, "<", SASACutoff)
  900     
  901     # Delete tmp objects...
  902     cmd.delete(TmpChainName)
  903     
  904     # Restore current dot solvent...
  905     cmd.set("dot_solvent", CurrentDotSolvent)
  906 
  907     return SurfaceResiduesInfoMap, BuriedResiduesInfoMap
  908 
  909 def GetInterfaceChainsResiduesByCAlphaAtomsDistance(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2, DistanceCutoff = 8.0):
  910     """Get information for interface residues between chains in two
  911     molecules based on the distance between CAlpha atoms. The chain
  912     specification for molecules may contain multiple chain names delimited
  913     by commas.
  914     
  915     The interface residues are identified using PyMOL 'bycalpha' selection
  916     operator with in a specified distance.
  917     
  918     Arguments:
  919         MoleculeName1 (str): Name of a PyMOL molecule object.
  920         ChainNames1 (str): A chain name or comma delimited list of chain
  921             names in a molecule.
  922         MoleculeName2 (str): Name of a PyMOL molecule object.
  923         ChainNames2 (str): A chain name or comma delimited list of chain
  924             names in a molecule.
  925         DistanceCutoff (float): Distance cutoff for distance between
  926             any two CAlpha atoms in interface residues in different chains.
  927 
  928     Returns:
  929         dict1: Interface residues in a chain for first molecule. It is a
  930             dictionary containing list of residue names and dictionaries of
  931             residue numbers and residue count for each residue. Names of 
  932             residues in the dictionary are not sorted.
  933         dict2: Interface residues in the chain for second molecule.
  934 
  935     Examples:
  936 
  937         ResiduesInfo1, ResiduesInfo2 = 
  938             GetInterfaceResiduesByHeavyAtomsDistance(MolName1,
  939             ChainName1, MolName2, ChainName2, DistanceCutoff)
  940         for ChainID in ResiduesInfo1["ChainIDs"]:
  941             for ResName in ResiduesInfo1["ResNames"][ChainID]:
  942                 ResCount = ResiduesInfo1["ResCount"][ChainID][ResName]
  943                 ResNums = ResiduesInfo1["ResNum"][ChainID][ResName]
  944                 MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums:
  945                 %s" % (ResName, ResCount, ResNums))
  946 
  947     """
  948     ChainNames1Selection, ChainNames2Selection = _ValidateAndSetupChainSelectionsForInterfaceResidues(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2)
  949     
  950     if ChainNames1Selection is None or ChainNames2Selection is None:
  951         return None
  952 
  953     MoleculeSelection1 = "%s and chain %s" % (MoleculeName1, ChainNames1Selection)
  954     MoleculeSelection2 = "%s and chain %s" % (MoleculeName2, ChainNames2Selection)
  955 
  956     SelectionCmd1 = "((bycalpha (%s) within %.1f of  (%s)) and polymer)" % (MoleculeSelection1, DistanceCutoff, MoleculeSelection2)
  957     ResiduesInfoMap1= _GetSelectionChainsAndResiduesInfo(SelectionCmd1)
  958 
  959     SelectionCmd2 = "((bycalpha (%s) within %.1f of  (%s)) and polymer)" % (MoleculeSelection2, DistanceCutoff, MoleculeSelection1)
  960     ResiduesInfoMap2= _GetSelectionChainsAndResiduesInfo(SelectionCmd2)
  961 
  962     return ResiduesInfoMap1, ResiduesInfoMap2
  963 
  964 def GetnterfaceChainsResiduesByHeavyAtomsDistance(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2, DistanceCutoff = 5.0):
  965     """Get information for interface residues between chains in two
  966     molecules based on the distance between heavy atoms. The chain
  967     specification for molecules may contain multiple chain names delimited
  968     by commas.
  969     
  970     The interface residues are identified using PyMOL 'byresidue' selection
  971     operator with in a specified distance.
  972     
  973     Arguments:
  974         MoleculeName1 (str): Name of a PyMOL molecule object.
  975         ChainNames1 (str): A chain name or comma delimited list of chain
  976             names in a molecule.
  977         MoleculeName2 (str): Name of a PyMOL molecule object.
  978         ChainNames2 (str): A chain name or comma delimited list of chain
  979             names in a molecule.
  980         DistanceCutoff (float): Distance cutoff for distance between
  981             any two heavy atoms in interface residues in different chains.
  982 
  983     Returns:
  984         dict1: Interface residues in a chain for first molecule. It is a
  985             dictionary containing list of residue names and dictionaries of
  986             residue numbers and residue count for each residue. Names of 
  987             residues in the dictionary are not sorted.
  988         dict2: Interface residues in the chain for second molecule.
  989 
  990     Examples:
  991 
  992         ResiduesInfo1, ResiduesInfo2 = 
  993             GetInterfaceResiduesByHeavyAtomsDistance(MolName1,
  994             ChainName1, MolName2, ChainName2, DistanceCutoff)
  995         for ChainID in ResiduesInfo1["ChainIDs"]:
  996             for ResName in ResiduesInfo1["ResNames"][ChainID]:
  997                 ResCount = ResiduesInfo1["ResCount"][ChainID][ResName]
  998                 ResNums = ResiduesInfo1["ResNum"][ChainID][ResName]
  999                 MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums:
 1000                 %s" % (ResName, ResCount, ResNums))
 1001 
 1002     """
 1003     ChainNames1Selection, ChainNames2Selection = _ValidateAndSetupChainSelectionsForInterfaceResidues(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2)
 1004     
 1005     if ChainNames1Selection is None or ChainNames2Selection is None:
 1006         return None
 1007 
 1008     MoleculeSelection1 = "%s and chain %s and (not hydrogens)" % (MoleculeName1, ChainNames1Selection)
 1009     MoleculeSelection2 = "%s and chain %s and (not hydrogens)" % (MoleculeName2, ChainNames2Selection)
 1010 
 1011     SelectionCmd1 = "((byresidue (%s) within %.1f of  (%s)) and polymer)" % (MoleculeSelection1, DistanceCutoff, MoleculeSelection2)
 1012     ResiduesInfoMap1= _GetSelectionChainsAndResiduesInfo(SelectionCmd1)
 1013 
 1014     SelectionCmd2 = "((byresidue (%s) within %.1f of  (%s)) and polymer)" % (MoleculeSelection2, DistanceCutoff, MoleculeSelection1)
 1015     ResiduesInfoMap2= _GetSelectionChainsAndResiduesInfo(SelectionCmd2)
 1016 
 1017     return ResiduesInfoMap1, ResiduesInfoMap2
 1018 
 1019 def GetInterfaceChainsResiduesBySASAChange(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2, ChangeCutoff = 0.75):
 1020     """Get information for interface residues between chains in two
 1021     molecules based on the change in solvent accessible surface area
 1022     (SASA) of a residue in chains in a molecule and chain complex
 1023     containing specified chains across both molecules. The chain 
 1024     specification for molecules may contain multiple chain names
 1025     delimited by commas.
 1026 
 1027     Arguments:
 1028         MoleculeName1 (str): Name of a PyMOL molecule object.
 1029         ChainNames1 (str): A chain name or comma delimited list of chain
 1030             names in a molecule.
 1031         MoleculeName2 (str): Name of a PyMOL molecule object.
 1032         ChainNames2 (str): A chain name or comma delimited list of chain
 1033             names in a molecule.
 1034         ChangeCutoff (float): SASA change cutoff for heavy atoms in
 1035             a interface residue between an individual chain and a complex
 1036             containing both chains.  Units: Angstroms ** 2
 1037 
 1038     Returns:
 1039         dict1: Interface residues in the chain for first molecule. It is a
 1040             dictionary containing list of residue names and dictionaries of
 1041             residue numbers and residue count for each residue. Names of 
 1042             residues in the dictionary are not sorted.
 1043         dict2: Interface residues in the chain for second molecule.
 1044 
 1045     Examples:
 1046 
 1047         ResiduesInfo1, ResiduesInfo2 = 
 1048             GetInterfaceResiduesBySASAChange(MolName1,
 1049             ChainName1, MolName2, ChainName2, DistanceCutoff)
 1050         for ResName in ResiduesInfo1["ResNames"]:
 1051             ResCount = ResiduesInfo1["ResCount"][ResName]
 1052             ResNums = ResiduesInfo1["ResNum"][ResName]
 1053             MiscUtil.PrintInfo("ResName: %s; ResCount: %s; ResNums: %s" %
 1054                 (ResName, ResCount, ResNums))
 1055 
 1056     """
 1057     ChainNames1Selection, ChainNames2Selection = _ValidateAndSetupChainSelectionsForInterfaceResidues(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2)
 1058     
 1059     if ChainNames1Selection is None or ChainNames2Selection is None:
 1060         return None
 1061 
 1062     # Get ready to calculate solvent accessible surface area..
 1063     CurrentDotSolvent = cmd.get("dot_solvent")
 1064     cmd.set("dot_solvent", 1)
 1065 
 1066     # Setup tmp object names...
 1067     TmpComplexName = "Tmp1_%s_%s" % (MoleculeName1, MoleculeName2)
 1068     TmpChainName1 = "Tmp2_%s" % (MoleculeName1)
 1069     TmpChainName2 = "Tmp3_%s" % (MoleculeName2)
 1070     
 1071     # Setup complex...
 1072     TmpComplexSelection = "(%s and chain %s and polymer and not hydrogens) or (%s and chain %s and polymer and not hydrogens)" % (MoleculeName1, ChainNames1Selection, MoleculeName2, ChainNames2Selection)
 1073     cmd.create(TmpComplexName, "(%s)" % (TmpComplexSelection))
 1074 
 1075     # Calculate SASA for complex and load it into b...
 1076     cmd.get_area(TmpComplexName, load_b = 1)
 1077     cmd.alter(TmpComplexName, "q=b")
 1078     
 1079     # Setup individual chains and calculate SASA...
 1080     TmpChainNameSelection1 = "%s and (chain %s)" % (TmpComplexName, ChainNames1Selection)
 1081     cmd.extract(TmpChainName1, "(%s)" % TmpChainNameSelection1)
 1082     cmd.get_area(TmpChainName1, load_b = 1)
 1083 
 1084     TmpChainNameSelection2 = "%s and (chain %s)" % (TmpComplexName, ChainNames2Selection)
 1085     cmd.extract(TmpChainName2, "(%s)" % TmpChainNameSelection2)
 1086     cmd.get_area(TmpChainName2, load_b = 1)
 1087 
 1088     # Calculate SASA difference for individual chains...
 1089     TmpChainNamesSelection = "(%s or %s)" % (TmpChainName1, TmpChainName2)
 1090     cmd.alter(TmpChainNamesSelection, "b=b-q")
 1091 
 1092     ResiduesInfoMap1 = _GetChainsResiduesInfoForSASAChange(TmpChainNamesSelection, TmpChainName1, ChangeCutoff)
 1093     ResiduesInfoMap2 = _GetChainsResiduesInfoForSASAChange(TmpChainNamesSelection, TmpChainName2, ChangeCutoff)
 1094 
 1095     # Delete tmp objects...
 1096     cmd.delete(TmpComplexName)
 1097     cmd.delete(TmpChainName1)
 1098     cmd.delete(TmpChainName2)
 1099     
 1100     # Restore current dot solvent...
 1101     cmd.set("dot_solvent", CurrentDotSolvent)
 1102     
 1103     return ResiduesInfoMap1, ResiduesInfoMap2
 1104 
 1105 def _GetChainsResiduesInfoForSASAChange(SelectionCmd, MoleculeName, ChangeCutoff):
 1106     """Get residue info for SASA change. """
 1107 
 1108     # Retrieve data...
 1109     stored.ResiduesInfo = []
 1110     cmd.iterate(SelectionCmd, "stored.ResiduesInfo.append([model, chain, resi, resn, b])")
 1111 
 1112     # Calculate SASA change for each residue...
 1113     SASAChangeMap = {}
 1114     SASAChangeMap["ChainIDs"] = []
 1115     SASAChangeMap["ResIDs"] = {}
 1116     SASAChangeMap["ResSASAChange"] = {}
 1117     
 1118     for Model, ChainID, ResNum, ResName, AtomSASAChange in stored.ResiduesInfo:
 1119         if not re.match(Model, MoleculeName, re.I):
 1120             continue
 1121         ResID = "%s_%s" % (ResName, ResNum)
 1122         
 1123         if not ChainID in SASAChangeMap["ChainIDs"]:
 1124             # Track new chain ID and intialize SASA change information...
 1125             SASAChangeMap["ChainIDs"].append(ChainID)
 1126             SASAChangeMap["ResIDs"][ChainID] = []
 1127             SASAChangeMap["ResSASAChange"][ChainID]= {}
 1128 
 1129         if ResID in SASAChangeMap["ResSASAChange"][ChainID]:
 1130             SASAChangeMap["ResSASAChange"][ChainID][ResID] += AtomSASAChange
 1131         else:
 1132             # Track new residue ID...
 1133             SASAChangeMap["ResIDs"][ChainID].append(ResID)
 1134             SASAChangeMap["ResSASAChange"][ChainID][ResID] = AtomSASAChange
 1135 
 1136     # Identify residues with SASA change greater than the specified cutoff value...
 1137     SelectionInfoMap = {}
 1138     SelectionInfoMap["ChainIDs"] = []
 1139     
 1140     SelectionInfoMap["ResNames"] = {}
 1141     SelectionInfoMap["ResNum"] = {}
 1142     SelectionInfoMap["ResCount"] = {}
 1143 
 1144     for ChainID in SASAChangeMap["ChainIDs"]:
 1145         for ResID in SASAChangeMap["ResIDs"][ChainID]:
 1146             ResSASAChange = SASAChangeMap["ResSASAChange"][ChainID][ResID]
 1147             if abs(ResSASAChange) < ChangeCutoff:
 1148                 continue
 1149             ResName, ResNum = ResID.split("_")
 1150             
 1151             if not ChainID in SelectionInfoMap["ChainIDs"]:
 1152                 # Track new chain ID and intialize residues information...
 1153                 SelectionInfoMap["ChainIDs"].append(ChainID)
 1154                 SelectionInfoMap["ResNames"][ChainID] = []
 1155                 SelectionInfoMap["ResNum"][ChainID]= {}
 1156                 SelectionInfoMap["ResCount"][ChainID] = {}
 1157             
 1158             if ResName in SelectionInfoMap["ResNames"][ChainID]:
 1159                 if not ResNum in SelectionInfoMap["ResNum"][ChainID][ResName]:
 1160                     # Same residue name but different residue number
 1161                     SelectionInfoMap["ResNum"][ChainID][ResName].append(ResNum)
 1162                     SelectionInfoMap["ResCount"][ChainID][ResName] += 1
 1163             else:
 1164                 # Track new residue information...
 1165                 SelectionInfoMap["ResNames"][ChainID].append(ResName)
 1166                 
 1167                 SelectionInfoMap["ResNum"][ChainID][ResName] = []
 1168                 SelectionInfoMap["ResNum"][ChainID][ResName].append(ResNum)
 1169                 
 1170                 SelectionInfoMap["ResCount"][ChainID][ResName] = 1
 1171     
 1172     return SelectionInfoMap
 1173 
 1174 def _ValidateAndSetupChainSelectionsForInterfaceResidues(MoleculeName1, ChainNames1, MoleculeName2, ChainNames2):
 1175     """Validate and setup chains name selectons for idenfitying interface residues."""
 1176     
 1177     ChainNames1 = re.sub(" ", "", ChainNames1)
 1178     ChainNames2 = re.sub(" ", "", ChainNames2)
 1179     
 1180     if not (len(MoleculeName1) and len(ChainNames1) and len(MoleculeName2) and len(ChainNames2)):
 1181         return None, None
 1182 
 1183     # Setup chain names for PyMOL selections...
 1184     ChainNames1Selection = "+".join(ChainNames1.split(","))
 1185     ChainNames2Selection = "+".join(ChainNames2.split(","))
 1186     
 1187     return ChainNames1Selection, ChainNames2Selection
 1188     
 1189 def _GetSelectionChainsAndResiduesInfo(SelectionCmd):
 1190     """Get chain names, residue names and count information for a selection. """
 1191     
 1192     # Retrieve atoms...
 1193     stored.SelectionInfo = []
 1194     cmd.iterate(SelectionCmd, "stored.SelectionInfo.append([chain, resi, resn])")
 1195 
 1196     # Retrieve chains and residues...
 1197     SelectionInfoMap = {}
 1198     SelectionInfoMap["ChainIDs"] = []
 1199     
 1200     SelectionInfoMap["ResNames"] = {}
 1201     SelectionInfoMap["ResNum"] = {}
 1202     SelectionInfoMap["ResCount"] = {}
 1203 
 1204     for ChainID, ResNum, ResName in stored.SelectionInfo:
 1205         if not ChainID in SelectionInfoMap["ChainIDs"]:
 1206             # Track new chain ID and intialize residues information...
 1207             SelectionInfoMap["ChainIDs"].append(ChainID)
 1208             SelectionInfoMap["ResNames"][ChainID] = []
 1209             SelectionInfoMap["ResNum"][ChainID]= {}
 1210             SelectionInfoMap["ResCount"][ChainID] = {}
 1211             
 1212         if ResName in SelectionInfoMap["ResNames"][ChainID]:
 1213             if not ResNum in SelectionInfoMap["ResNum"][ChainID][ResName]:
 1214                 # Same residue name but different residue number
 1215                 SelectionInfoMap["ResNum"][ChainID][ResName].append(ResNum)
 1216                 SelectionInfoMap["ResCount"][ChainID][ResName] += 1
 1217         else:
 1218             # Track new residue information...
 1219             SelectionInfoMap["ResNames"][ChainID].append(ResName)
 1220             
 1221             SelectionInfoMap["ResNum"][ChainID][ResName] = []
 1222             SelectionInfoMap["ResNum"][ChainID][ResName].append(ResNum)
 1223             
 1224             SelectionInfoMap["ResCount"][ChainID][ResName] = 1
 1225                 
 1226     return SelectionInfoMap
 1227 
 1228 def _GetSelectionResiduesInfo(SelectionCmd):
 1229     """Get residue names and count information for a selection. """
 1230     
 1231     # Retrieve atoms...
 1232     stored.SelectionInfo = []
 1233     cmd.iterate(SelectionCmd, "stored.SelectionInfo.append([resi, resn])")
 1234 
 1235     # Retrieve residues...
 1236     SelectionInfoMap = {}
 1237     SelectionInfoMap["ResNames"] = []
 1238     SelectionInfoMap["ResNum"] = {}
 1239     SelectionInfoMap["ResCount"] = {}
 1240 
 1241     for ResNum, ResName in stored.SelectionInfo:
 1242         if ResName in SelectionInfoMap["ResNames"]:
 1243             if not ResNum in SelectionInfoMap["ResNum"][ResName]:
 1244                 # Same residue name but different residue number
 1245                 SelectionInfoMap["ResNum"][ResName].append(ResNum)
 1246                 SelectionInfoMap["ResCount"][ResName] += 1
 1247         else:
 1248             SelectionInfoMap["ResNames"].append(ResName)
 1249             
 1250             SelectionInfoMap["ResNum"][ResName] = []
 1251             SelectionInfoMap["ResNum"][ResName].append(ResNum)
 1252             
 1253             SelectionInfoMap["ResCount"][ResName] = 1
 1254                 
 1255     return SelectionInfoMap
 1256 
 1257 def _GetSelectionPhiPsiResiduesInfo(SelectionCmd, Categorize):
 1258     """Get phi and psi torsion angle information for residues in a  selection
 1259     with in a chain.
 1260      
 1261     The phi and psi angles are optionally categorized into the following groups
 1262     corresponding to four types of  Ramachandran plots:
 1263     
 1264     General: All residues except glycine, proline, or pre-proline
 1265     Glycine: Only glycine residues
 1266     Proline: Only proline residues
 1267     Pre-Proline: Only residues before proline not including glycine or proline
 1268     
 1269     """
 1270 
 1271     # Initialize...
 1272     SelectionInfoMap = {}
 1273     SelectionInfoMap["ResNums"] = []
 1274     SelectionInfoMap["ResName"] = {}
 1275     SelectionInfoMap["Phi"] = {}
 1276     SelectionInfoMap["Psi"] = {}
 1277     SelectionInfoMap["Category"] = {}
 1278 
 1279     # Retrieve phi and psi info...
 1280     PhiPsiInfo = _GetSelectionPhiPsiInfo(SelectionCmd, Categorize)
 1281     if PhiPsiInfo is None:
 1282         return SelectionInfoMap
 1283 
 1284     # Track...
 1285     for Model, ChainID, ResNum, ResName, Phi, Psi, Category in PhiPsiInfo:
 1286         if ResNum in SelectionInfoMap["ResName"]:
 1287             continue
 1288         
 1289         SelectionInfoMap["ResNums"].append(ResNum)
 1290         SelectionInfoMap["ResName"][ResNum] = ResName
 1291         SelectionInfoMap["Phi"][ResNum] = Phi
 1292         SelectionInfoMap["Psi"][ResNum] = Psi
 1293         SelectionInfoMap["Category"][ResNum] = Category
 1294     
 1295     return SelectionInfoMap
 1296 
 1297 def _GetSelectionPhiPsiChainsAndResiduesInfo(SelectionCmd, Categorize):
 1298     """Get phi and psi torsion angle information for residues in a  selection
 1299     across chains in a molecule.
 1300     
 1301     The phi and psi angles are optionally categorized into the following groups
 1302     corresponding to four types of  Ramachandran plots:
 1303     
 1304     General: All residues except glycine, proline, or pre-proline
 1305     Glycine: Only glycine residues
 1306     Proline: Only proline residues
 1307     Pre-Proline: Only residues before proline not including glycine or proline
 1308     
 1309     """
 1310 
 1311     # Initialize...
 1312     SelectionInfoMap = {}
 1313     SelectionInfoMap["ChainIDs"] = []
 1314     SelectionInfoMap["ResNums"] = {}
 1315     SelectionInfoMap["ResName"] = {}
 1316     SelectionInfoMap["Phi"] = {}
 1317     SelectionInfoMap["Psi"] = {}
 1318     SelectionInfoMap["Category"] = {}
 1319 
 1320     # Retrieve phi and psi info...
 1321     PhiPsiInfo = _GetSelectionPhiPsiInfo(SelectionCmd, Categorize)
 1322     if PhiPsiInfo is None:
 1323         return SelectionInfoMap
 1324 
 1325     # Track...
 1326     for Model, ChainID, ResNum, ResName, Phi, Psi, Category in PhiPsiInfo:
 1327         if not ChainID in SelectionInfoMap["ResNums"]:
 1328             # Track new chain ID and initialize residues information...
 1329             SelectionInfoMap["ChainIDs"].append(ChainID)
 1330             
 1331             SelectionInfoMap["ResNums"][ChainID] = []
 1332             SelectionInfoMap["ResName"][ChainID] = {}
 1333             SelectionInfoMap["Phi"][ChainID] = {}
 1334             SelectionInfoMap["Psi"][ChainID] = {}
 1335             SelectionInfoMap["Category"][ChainID] = {}
 1336             
 1337         # Check for duplicates...
 1338         if ResNum in SelectionInfoMap["ResName"][ChainID]:
 1339             continue
 1340 
 1341         # Track new residues information...
 1342         SelectionInfoMap["ResNums"][ChainID].append(ResNum)
 1343         SelectionInfoMap["ResName"][ChainID][ResNum] = ResName
 1344         SelectionInfoMap["Phi"][ChainID][ResNum] = Phi
 1345         SelectionInfoMap["Psi"][ChainID][ResNum] = Psi
 1346         SelectionInfoMap["Category"][ChainID][ResNum] = Category
 1347     
 1348     return SelectionInfoMap
 1349 
 1350 def _GetSelectionPhiPsiCategoriesResiduesInfo(SelectionCmd):
 1351     """Get phi and psi torsion angle information for residues in a  selection
 1352     with in a chain.
 1353 
 1354     The phi and psi angles are optionally categorized into the following groups
 1355     corresponding to four types of  Ramachandran plots:
 1356     
 1357     General: All residues except glycine, proline, or pre-proline
 1358     Glycine: Only glycine residues
 1359     Proline: Only proline residues
 1360     Pre-Proline: Only residues before proline not including glycine or proline
 1361     
 1362     """
 1363     
 1364     # Initialize...
 1365     PhiPsiInfoMaps = {}
 1366     PhiPsiInfoMaps["Maps"] = []
 1367     for Category in ["General", "Glycine", "Proline", "Pre-Proline"]:
 1368         PhiPsiInfoMap = {}
 1369         PhiPsiInfoMap["ResNums"] = []
 1370         PhiPsiInfoMap["ResName"] = {}
 1371         PhiPsiInfoMap["Phi"] = {}
 1372         PhiPsiInfoMap["Psi"] = {}
 1373         PhiPsiInfoMap["Category"] = {}
 1374         
 1375         PhiPsiInfoMaps[Category] = PhiPsiInfoMap
 1376         PhiPsiInfoMaps["Maps"].append(PhiPsiInfoMap)
 1377         
 1378     # Retrieve phi and psi info...
 1379     PhiPsiInfo = _GetSelectionPhiPsiInfo(SelectionCmd, True)
 1380     if PhiPsiInfo is None:
 1381         return  PhiPsiInfoMaps["Maps"]
 1382     
 1383     Index = -1
 1384     for Model, ChainID, ResNum, ResName, Phi, Psi, Category in PhiPsiInfo:
 1385         Index += 1
 1386         
 1387         if ResNum in PhiPsiInfoMaps[Category]["ResName"]:
 1388             continue
 1389         
 1390         # Track...
 1391         PhiPsiInfoMaps[Category]["ResNums"].append(ResNum)
 1392         PhiPsiInfoMaps[Category]["ResName"][ResNum] = ResName
 1393         PhiPsiInfoMaps[Category]["Phi"][ResNum] = Phi
 1394         PhiPsiInfoMaps[Category]["Psi"][ResNum] = Psi
 1395         PhiPsiInfoMaps[Category]["Category"][ResNum] = Category
 1396     
 1397     return  PhiPsiInfoMaps["Maps"]
 1398 
 1399 def _GetSelectionPhiPsiInfo(SelectionCmd, Categorize = False):
 1400     """Get phi and psi angles for a selection along with information regarding
 1401     model, chain, residue number, and residue name.
 1402     
 1403     The phi and psi angles are optionally categorized into the following groups
 1404     corresponding to four types of  Ramachandran plots:
 1405     
 1406     General: All residues except glycine, proline, or pre-proline
 1407     Glycine: Only glycine residues
 1408     Proline: Only proline residues
 1409     Pre-Proline: Only residues before proline not including glycine or proline
 1410     
 1411     """
 1412 
 1413     # Retrieve phi and psi values...
 1414     PhiPsiInfoMap = cmd.get_phipsi("(%s)" % SelectionCmd)
 1415     if PhiPsiInfoMap is None:
 1416         return None
 1417 
 1418     # Sort keys corresponding to model name and residue numbers...
 1419     PhiPsiKeys = sorted(PhiPsiInfoMap.keys())
 1420     
 1421     # Retrieve related information...
 1422     PhiPsiInfoList = []
 1423 
 1424     Category = None
 1425     for Key in PhiPsiKeys:
 1426         Model, Index = Key
 1427         Phi, Psi = PhiPsiInfoMap[Key]
 1428         
 1429         stored.PhiPsiInfoList = []
 1430         cmd.iterate("(%s`%d)" % (Model, Index), "stored.PhiPsiInfoList.append([model, chain, resi, resn])")
 1431         for Model, Chain, ResNum, ResName in stored.PhiPsiInfoList:
 1432             PhiPsiInfoList.append([Model, Chain, ResNum, ResName, Phi, Psi, Category])
 1433 
 1434     if Categorize:
 1435         _CategorizePhiPsiAnglesInfo(PhiPsiInfoList)
 1436     
 1437     return PhiPsiInfoList
 1438 
 1439 def _CategorizePhiPsiAnglesInfo(PhiPsiInfo):
 1440     """The phi and psi angles are optionally categorized into the following groups
 1441     corresponding to four types of  Ramachandran plots:
 1442     
 1443     General: All residues except glycine, proline, or pre-proline
 1444     Glycine: Only glycine residues
 1445     Proline: Only proline residues
 1446     Pre-Proline: Only residues before proline not including glycine or proline
 1447     
 1448     """
 1449     
 1450     Index = -1
 1451     LastIndex = len(PhiPsiInfo) - 1
 1452     PhiPsiCategories = []
 1453     for Model, ChainID, ResNum, ResName, Phi, Psi, CategoryPlaceHolder in PhiPsiInfo:
 1454         Index += 1
 1455         if re.match("^Gly$", ResName, re.I):
 1456             # Gly: Only glycine residues
 1457             Category = "Glycine"
 1458         elif re.match("^Pro$", ResName, re.I):
 1459             # Pro: Only proline residues
 1460             Category = "Proline"
 1461         elif _IsPreProlinePhiPsiAngle(PhiPsiInfo, Index, LastIndex):
 1462             #  Pre-Proline: Only residues before proline not including glycine or proline
 1463             Category = "Pre-Proline"
 1464         else:
 1465             # General: All residues except Gly, Pro, or pre-Pro
 1466             Category = "General"
 1467         # Track categories...
 1468         PhiPsiCategories.append(Category)
 1469 
 1470     # Update category in PhiPsiInfo...
 1471     CategoryIndex = 6
 1472     for Index, Category in enumerate(PhiPsiCategories):
 1473          PhiPsiInfo[Index][CategoryIndex] = Category
 1474 
 1475 def _IsPreProlinePhiPsiAngle(PhiPsiInfo, Index, LastIndex):
 1476     """Check for Pre-Proline phi and psi angles."""
 1477     
 1478     #  Pre-Proline: Only residues before proline not including glycine or proline
 1479 
 1480     # Not a last residue...
 1481     NextIndex = Index + 1
 1482     if NextIndex  >= LastIndex:
 1483         return False
 1484 
 1485     # Next residue is proline...
 1486     if not re.match("^Pro$", PhiPsiInfo[NextIndex][3], re.I):
 1487         return False
 1488 
 1489     # Current residue is not Gly or Pro...
 1490     NextResName = PhiPsiInfo[Index][3]
 1491     if re.match("^(Gly|Pro)$", NextResName, re.I):
 1492         return False
 1493 
 1494     # Next chain ID is same as current chain ID...
 1495     CurrentChainID =  PhiPsiInfo[Index][1]
 1496     NextChainID = PhiPsiInfo[NextIndex][1]
 1497     if not re.match("^%s$" % CurrentChainID, NextChainID):
 1498         return False
 1499 
 1500     # Current and next residue numbers are sequential...
 1501     CurrentResNum = int(PhiPsiInfo[Index][2])
 1502     NextResNum = int(PhiPsiInfo[NextIndex][2])
 1503     if not (NextResNum - CurrentResNum == 1):
 1504         return False
 1505     
 1506     return True
 1507     
 1508 def _GetSelectionResiduesBValuesInfo(SelectionCmd):
 1509     """Get B values info for residues in a chain. """
 1510 
 1511     # Retrieve data...
 1512     stored.ResiduesInfo = []
 1513     cmd.iterate(SelectionCmd, "stored.ResiduesInfo.append([resi, resn, b])")
 1514 
 1515     # Setup B-values for each residue...
 1516     BValuesInfoMap = {}
 1517     BValuesInfoMap["ResIDs"] = []
 1518     BValuesInfoMap["BValue"] = {}
 1519     
 1520     for ResNum, ResName, AtomBValue in stored.ResiduesInfo:
 1521         ResID = "%s_%s" % (ResName, ResNum)
 1522         
 1523         if ResID in BValuesInfoMap["BValue"]:
 1524             BValuesInfoMap["BValue"][ResID] += AtomBValue
 1525         else:
 1526             # Track new residue ID...
 1527             BValuesInfoMap["ResIDs"].append(ResID)
 1528             BValuesInfoMap["BValue"][ResID] = AtomBValue
 1529 
 1530     return BValuesInfoMap
 1531 
 1532 def _GetResiduesInfoFromResiduesBValues(ResiduesBValuesInfoMap, Mode, Cutoff):
 1533     """Get residues info map using residues B values. """
 1534 
 1535     GreaterThanEquals, GreaterThan, LessThanEquals, LessThan, Equals = [False] * 5
 1536     if re.match("^>=$", Mode, re.I):
 1537         GreaterThanEquals = True
 1538     elif re.match("^>$", Mode, re.I):
 1539         GreaterThan = True
 1540     elif re.match("^<=$", Mode, re.I):
 1541         LessThanEquals = True
 1542     elif re.match("^<$", Mode, re.I):
 1543         LessThan = True
 1544     elif re.match("^=$", Mode, re.I):
 1545         Equals = True
 1546     else:
 1547         MiscUtil.PrintError("PyMOLUtil._GetResiduesInfoFromResiduesBValues: The value, %s, specified for Mode is not valid. Supported values: >=, >, <=, <, =")
 1548     
 1549     # Setup residues info map...
 1550     ResiduesInfoMap = {}
 1551     ResiduesInfoMap["ResNames"] = []
 1552     ResiduesInfoMap["ResNum"] = {}
 1553     ResiduesInfoMap["ResCount"] = {}
 1554 
 1555     for ResID in ResiduesBValuesInfoMap["ResIDs"]:
 1556         ResName, ResNum = ResID.split("_")
 1557         ResBValue = ResiduesBValuesInfoMap["BValue"][ResID]
 1558 
 1559         if GreaterThanEquals:
 1560             if ResBValue < Cutoff:
 1561                 continue
 1562         elif GreaterThan:
 1563             if ResBValue <= Cutoff:
 1564                 continue
 1565         elif LessThanEquals:
 1566             if ResBValue > Cutoff:
 1567                 continue
 1568         elif LessThan:
 1569             if ResBValue >= Cutoff:
 1570                 continue
 1571         elif Equals:
 1572             if ResBValue != Cutoff:
 1573                 continue
 1574         
 1575         if ResName in ResiduesInfoMap["ResNames"]:
 1576             if not ResNum in ResiduesInfoMap["ResNum"][ResName]:
 1577                 # Same residue name but different residue number
 1578                 ResiduesInfoMap["ResNum"][ResName].append(ResNum)
 1579                 ResiduesInfoMap["ResCount"][ResName] += 1
 1580         else:
 1581             ResiduesInfoMap["ResNames"].append(ResName)
 1582             
 1583             ResiduesInfoMap["ResNum"][ResName] = []
 1584             ResiduesInfoMap["ResNum"][ResName].append(ResNum)
 1585             
 1586             ResiduesInfoMap["ResCount"][ResName] = 1
 1587     
 1588     return ResiduesInfoMap
 1589 
 1590 def ProcessChainsAndLigandsOptionsInfo(ChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue, LigandsOptionName = None, LigandsOptionValue = None):
 1591     """Process specified chain and ligand IDs using command line options.
 1592 
 1593     Arguments:
 1594         ChainsAndLigandsInfo (dict): A dictionary containing information
 1595             existing chains and ligands. 
 1596         ChainsOptionName (str): Name of command line chains option.
 1597         ChainsOptionValue (str): Value for command line chains option.
 1598         LigandsOptionName (str): Name of command line ligands option.
 1599         LigandsOptionValue (str): Value for command line ligands option.
 1600 
 1601     Returns:
 1602         dict: A dictionary containing list of chain identifiers and dictionaries
 1603             of chains containing lists of ligand names for each chain.
 1604 
 1605     Examples:
 1606 
 1607         ChainsAndLigandsInfo = ProcessChainsAndLigandsOptionsInfo(
 1608             ChainsAndLigandsInfo, "-c, --chainIDs", OptionsInfo["ChainIDs"],
 1609             "-l, --ligandIDs", OptionsInfo["LigandIDs"])
 1610         for ChainID in ChainsAndLigandsInfo["ChainIDs"]:
 1611             for LigandID in ChainsAndLigandsInfo["LigandIDs"][ChainID]:
 1612                 MiscUtil.PrintInfo("ChainID: %s; LigandID: %s" % (ChainID,
 1613                     LigandID))
 1614 
 1615     """
 1616     SpecifiedChainsAndLigandsInfo = {}
 1617     SpecifiedChainsAndLigandsInfo["ChainIDs"] = []
 1618     SpecifiedChainsAndLigandsInfo["LigandIDs"] = {}
 1619 
 1620     if ChainsOptionValue is None:
 1621         return SpecifiedChainsAndLigandsInfo
 1622         
 1623     _ProcessChainIDs(ChainsAndLigandsInfo, SpecifiedChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue)
 1624 
 1625     if LigandsOptionValue is None:
 1626         return SpecifiedChainsAndLigandsInfo
 1627     
 1628     _ProcessLigandIDs(ChainsAndLigandsInfo, SpecifiedChainsAndLigandsInfo, LigandsOptionName, LigandsOptionValue)
 1629     
 1630     return SpecifiedChainsAndLigandsInfo
 1631 
 1632 def _ProcessChainIDs(ChainsAndLigandsInfo, SpecifiedChainsAndLigandsInfo, ChainsOptionName, ChainsOptionValue):
 1633     """Process chain IDs"""
 1634 
 1635     MiscUtil.PrintInfo("Processing chain IDs...")
 1636     
 1637     if re.match("^All$", ChainsOptionValue, re.I):
 1638         SpecifiedChainsAndLigandsInfo["ChainIDs"] = ChainsAndLigandsInfo["ChainIDs"]
 1639         return
 1640     elif re.match("^(First|Auto)$", ChainsOptionValue, re.I):
 1641         FirstChainID = ChainsAndLigandsInfo["ChainIDs"][0] if (len(ChainsAndLigandsInfo["ChainIDs"])) else None
 1642         if FirstChainID is not None:
 1643             SpecifiedChainsAndLigandsInfo["ChainIDs"].append(FirstChainID)
 1644         return
 1645     
 1646     ChainIDs = re.sub(" ", "", ChainsOptionValue)
 1647     if not ChainIDs:
 1648         MiscUtil.PrintError("No valid value specified using \"%s\" option." % ChainsOptionName)
 1649 
 1650     ChainIDsList = ChainsAndLigandsInfo["ChainIDs"]
 1651     SpecifiedChainIDsList = []
 1652     
 1653     ChainIDsWords = ChainIDs.split(",")
 1654     for ChainID in ChainIDsWords:
 1655         if not ChainID in ChainIDsList:
 1656             MiscUtil.PrintWarning("The chain ID, %s, specified using \"%s\" option is not valid. It'll be ignored. Valid chain IDs: %s" % (ChainID, ChainsOptionName, ", ".join(ChainIDsList)))
 1657             continue
 1658         if ChainID in SpecifiedChainIDsList:
 1659             MiscUtil.PrintWarning("The chain ID, %s, has already been specified using \"%s\" option. It'll be ignored." % (ChainID, ChainsOptionName))
 1660             continue
 1661         SpecifiedChainIDsList.append(ChainID)
 1662     
 1663     if not len(SpecifiedChainIDsList):
 1664         MiscUtil.PrintError("No valid chain IDs \"%s\"  specified using \"%s\" option." % (ChainsOptionValue, ChainsOptionName))
 1665     
 1666     SpecifiedChainsAndLigandsInfo["ChainIDs"] = SpecifiedChainIDsList
 1667     
 1668 def _ProcessLigandIDs(ChainsAndLigandsInfo, SpecifiedChainsAndLigandsInfo, LigandsOptionName, LigandsOptionValue):
 1669     """Process ligand IDs"""
 1670 
 1671     MiscUtil.PrintInfo("Processing ligand IDs...")
 1672     
 1673     # Intialize ligand IDs...
 1674     for ChainID in SpecifiedChainsAndLigandsInfo["ChainIDs"]:
 1675         SpecifiedChainsAndLigandsInfo["LigandIDs"][ChainID] = []
 1676         
 1677     if re.match("^All$", LigandsOptionValue, re.I):
 1678         for ChainID in SpecifiedChainsAndLigandsInfo["ChainIDs"] :
 1679             SpecifiedChainsAndLigandsInfo["LigandIDs"][ChainID] = ChainsAndLigandsInfo["LigandIDs"][ChainID]
 1680         return
 1681     elif re.match("^(Largest|Auto)$", LigandsOptionValue, re.I):
 1682         # Setup largest ligand ID for each chain...
 1683         for ChainID in SpecifiedChainsAndLigandsInfo["ChainIDs"] :
 1684             LargestLigandID = ChainsAndLigandsInfo["LigandIDs"][ChainID][0] if (len(ChainsAndLigandsInfo["LigandIDs"][ChainID])) else None
 1685             if LargestLigandID is not None:
 1686                 SpecifiedChainsAndLigandsInfo["LigandIDs"][ChainID].append(LargestLigandID)
 1687         return
 1688     
 1689     LigandIDs = re.sub(" ", "", LigandsOptionValue)
 1690     if not LigandIDs:
 1691         MiscUtil.PrintError("No valid value specified using \"%s\" option." % LigandsOptionName)
 1692     
 1693     LigandIDsWords = LigandIDs.split(",")
 1694     
 1695     for ChainID in SpecifiedChainsAndLigandsInfo["ChainIDs"]:
 1696         LigandIDsList = ChainsAndLigandsInfo["LigandIDs"][ChainID]
 1697         SpecifiedLigandIDsList = []
 1698 
 1699         for LigandID in LigandIDsWords:
 1700             if not LigandID in LigandIDsList:
 1701                 LigandIDsListNames = ",".join(LigandIDsList) if len(LigandIDsList) else "None"
 1702                 MiscUtil.PrintWarning("The ligand ID, %s, specified using \"%s\" option is not valid for chain, %s. It'll be ignored. Valid ligand IDs: %s" % (LigandID, LigandsOptionName, ChainID, LigandIDsListNames))
 1703                 continue
 1704             if LigandID in SpecifiedLigandIDsList:
 1705                 MiscUtil.PrintWarning("The ligand ID, %s, has already been specified using \"%s\" option. It'll be ignored." % (LigandID, LigandsOptionName))
 1706                 continue
 1707             SpecifiedLigandIDsList.append(LigandID)
 1708             
 1709         if not len(SpecifiedLigandIDsList):
 1710             MiscUtil.PrintWarning("No valid ligand IDs \"%s\" specified using \"%s\" option for chain ID, %s." % (LigandsOptionValue, LigandsOptionName, ChainID))
 1711         
 1712         SpecifiedChainsAndLigandsInfo["LigandIDs"][ChainID] = SpecifiedLigandIDsList
 1713 
 1714 def ProcessResidueTypesOptionsInfo(ResidueTypesOptionName, ResidueTypesOptionValue):
 1715     """Process specified residue types using command line option.
 1716 
 1717     Arguments:
 1718         ResidueTypesOptionName (str): Name of command line  option.
 1719         ResidueTypesOptionValue (str): Value for command line option.
 1720 
 1721     Returns:
 1722         list: A list containing names of valid residue types.
 1723         dict: A dictionary containing residue types pointing to dictionaries of
 1724             color names and list of residues for a residue type.
 1725 
 1726     Examples:
 1727 
 1728         ResidueTypesNamesInfo, ResidueTypesParamsInfo =
 1729             ProcessChainsAndLigandsOptionsInfo("-r, --residueTypes",
 1730             OptionsInfo["ResidueTypes"])
 1731         for ResidueTypeName in ResidueTypesNamesInfo:
 1732             MiscUtil.PrintInfo("ResidueType: %s; Color: %s; Residues: %s" %
 1733             (ResidueTypeName, ResidueTypeName[ResidueTypeName]["Color"],
 1734             " ".join(ResidueTypeName[ResidueTypeName]["Residues"]))
 1735 
 1736     """
 1737     
 1738     # Set up  default values for residue types, colors, and names.
 1739     ResidueTypesNamesInfo = ["Aromatic", "Hydrophobic", "Polar", "Positively_Charged", "Negatively_Charged"]
 1740     
 1741     ResidueTypesParamsInfo = {}
 1742     ResidueTypesParamsInfo["Aromatic"] = {"Color": "brightorange", "Residues" : ["HIS", "PHE", "TRP", "TYR"]}
 1743     ResidueTypesParamsInfo["Hydrophobic"] = {"Color": "orange", "Residues" : ["ALA", "GLY", "VAL", "LEU", "ILE", "PRO", "MET"]}
 1744     ResidueTypesParamsInfo["Polar"] = {"Color": "palegreen", "Residues" : ["ASN", "GLN", "SER", "THR", "CYS"]}
 1745     ResidueTypesParamsInfo["Positively_Charged"] = {"Color": "marine", "Residues" : ["ARG", "LYS"]}
 1746     ResidueTypesParamsInfo["Negatively_Charged"] = {"Color": "red", "Residues" : ["ASP", "GLU"]}
 1747     
 1748     ResidueTypes = ResidueTypesOptionValue
 1749     if re.match("^auto$", ResidueTypesOptionValue, re.I):
 1750         _SetupOtherResidueTypes(ResidueTypesParamsInfo)
 1751         return ResidueTypesNamesInfo, ResidueTypesParamsInfo
 1752     
 1753     # Parse specified residue types...
 1754     ResidueTypesWords = ResidueTypes.split(",")
 1755     if len(ResidueTypesWords) % 3:
 1756         MiscUtil.PrintError("The number of comma delimited residue type, color, and name triplets, %d, specified using \"%s\" option must be a multple of 3." % (len(ResidueTypesWords), ResidueTypesOptionName))
 1757 
 1758     # Set up canonical residue type names...
 1759     ValidResidueTypeNames = []
 1760     CanonicalResidueTypeNamesMap = {}
 1761     for Name in sorted(ResidueTypesNamesInfo):
 1762         ValidResidueTypeNames.append(Name)
 1763         CanonicalResidueTypeNamesMap[Name.lower()] = Name
 1764 
 1765     # Validate and set residue types, colors, and names..
 1766     for Index in range(0, len(ResidueTypesWords), 3):
 1767         TypeName = ResidueTypesWords[Index].strip()
 1768         ResidueTypeColor = ResidueTypesWords[Index + 1].strip()
 1769         ResidueNames = ResidueTypesWords[Index + 2].strip()
 1770         
 1771         ResidueNames = re.sub("[ ]+", " ", ResidueNames)
 1772         ResidueNamesWords = ResidueNames.split(" ")
 1773 
 1774         CanonicalTypeName = TypeName.lower()
 1775         if not CanonicalTypeName in CanonicalResidueTypeNamesMap:
 1776             MiscUtil.PrintError("The residue type, %s, specified using \"%s\" option is not a valid type. Supported residue types: %s" % (TypeName, ResidueTypesOptionName, ", ".join(ValidResidueTypeNames)))
 1777         ResidueTypeName = CanonicalResidueTypeNamesMap[CanonicalTypeName]
 1778 
 1779         if not ResidueTypeColor:
 1780             MiscUtil.PrintError("No color name specified for residue type, %s, using \"%s\" option, %s" % (TypeName, ResidueTypesOptionName, ResidueTypes))
 1781         
 1782         if not ResidueNames:
 1783             MiscUtil.PrintError("No residue names specified for residue type, %s, using \"%s\" option, %s" % (TypeName, ResidueTypesOptionName, ResidueTypes))
 1784             
 1785         ResidueTypesParamsInfo[ResidueTypeName]["Color"] = ResidueTypeColor
 1786         ResidueTypesParamsInfo[ResidueTypeName]["Residues"] = ResidueNamesWords
 1787         
 1788         SetupOtherResidueTypes()
 1789         return ResidueTypesNamesInfo, ResidueTypesParamsInfo
 1790 
 1791 def _SetupOtherResidueTypes(ResidueTypesParamsInfo):
 1792     """Setup other residue types."""
 1793 
 1794     # Set other residues to all specified residues. The other residues are selected by
 1795     # performing a negation operation on this list during the creation of PyMOL objects.
 1796     
 1797     ResidueNames = []
 1798     for ResiduesType in ResidueTypesParamsInfo:
 1799         ResidueNames.extend(ResidueTypesParamsInfo[ResiduesType]["Residues"] )
 1800     
 1801     ResidueTypesParamsInfo["Other"]= {}
 1802     ResidueTypesParamsInfo["Other"]["Color"] = None
 1803     ResidueTypesParamsInfo["Other"]["Residues"] = ResidueNames
 1804     
 1805 def ProcessSurfaceAtomTypesColorsOptionsInfo(ColorOptionName, ColorOptionValue):
 1806     """Process specified surafce atom types colors using command line option.
 1807 
 1808     Arguments:
 1809         ColorOptionName (str): Name of command line  option.
 1810         ColorOptionValue (str): Value for command line option.
 1811 
 1812     Returns:
 1813         dict: A dictionary containing atom types and colors.
 1814 
 1815     Examples:
 1816 
 1817         AtomTypesColorNamesInfo =
 1818             PyMOLUtil.ProcessSurfaceAtomTypesColorsOptionsInfo(
 1819             "--surfaceAtomTypesColors", OptionsInfo["SurfaceAtomTypesColors"])
 1820 
 1821     """
 1822     
 1823     # Set up  default values for atom type colors...
 1824     AtomTypesColorNamesInfo = {"HydrophobicAtomsColor": "yellow", "NegativelyChargedAtomsColor": "red", "PositivelyChargedAtomsColor": "blue", "OtherAtomsColor": "gray90"}
 1825     
 1826     AtomTypesColors = ColorOptionValue
 1827     if re.match("^auto$", AtomTypesColors, re.I):
 1828         return AtomTypesColorNamesInfo
 1829     
 1830     # Parse atom type colors and values...
 1831     AtomTypesColorsWords = AtomTypesColors.split(",")
 1832     if len(AtomTypesColorsWords) % 2:
 1833         MiscUtil.PrintError("The number of comma delimited surface atom color types and values, %d, specified using \"%s\" option must be a multple of 2." % (len(AtomTypesColorsWords), ColorOptionName))
 1834 
 1835     # Set up canonical atom type colors...
 1836     ValidAtomTypesColors = []
 1837     CanonicalAtomTypesColorsMap = {}
 1838     for Type in sorted(AtomTypesColorNamesInfo):
 1839         ValidAtomTypesColors.append(Type)
 1840         CanonicalAtomTypesColorsMap[Type.lower()] = Type
 1841     
 1842     # Validate and process specified values...
 1843     for Index in range(0, len(AtomTypesColorsWords), 2):
 1844         Type = AtomTypesColorsWords[Index].strip()
 1845         Color = AtomTypesColorsWords[Index + 1].strip()
 1846         
 1847         Color = re.sub("[ ]+", " ", Color)
 1848         ColorWords = Color.split(" ")
 1849     
 1850         CanonicalType = Type.lower()
 1851         if not CanonicalType in CanonicalAtomTypesColorsMap:
 1852             MiscUtil.PrintError("The surface atom color type, %s, specified using \"%s\" option  is not a valid type: Supported atom color types: %s" % (Type, ColorOptionName, ", ".join(ValidAtomTypesColors)))
 1853         Type = CanonicalAtomTypesColorsMap[CanonicalType]
 1854 
 1855         if not Color:
 1856             MiscUtil.PrintError("No color type specified for atom color type, %s, using \"%s\" option." % (Type, ColorOptionName))
 1857 
 1858         ColorWordsLen = len(ColorWords)
 1859         if not (ColorWordsLen == 1 or ColorWordsLen == 3):
 1860             MiscUtil.PrintError("The number, %s, of color name or space delimited RGB values, %s, specified for atom color type, %s, using \"%s\" option must be 1 or 3." % (ColorWordsLen, Color, ColorOptionName, Type))
 1861 
 1862         AtomTypesColorNamesInfo[Type] = " ".join(ColorWords)
 1863 
 1864         return AtomTypesColorNamesInfo
 1865 
 1866 def ProcessChainSelectionsOptionsInfo(SelectionOptionName, SelectionOptionValue):
 1867     """Process names and selections specified  using command line option. It
 1868     is a pairwise list comma delimited values corresponding to PyMOL object
 1869     names and selection specification
 1870 
 1871     Arguments:
 1872         SelectionOptionName (str): Name of command line  option.
 1873         SelectionOptionValue (str): Value for command line option.
 1874 
 1875     Returns:
 1876         dict: A dictionary containing lists f names and selection commands.
 1877 
 1878     Examples:
 1879 
 1880         ChainSelectionsInfo =
 1881             PyMOLUtil.ProcessChainSelectionsOptionsInfo("--selectionsChain",
 1882             OptionsInfo["SelectionChains"])
 1883 
 1884     """
 1885     
 1886     # Initialize...
 1887     ChainSelectionsInfo = {}
 1888     ChainSelectionsInfo["Names"] = []
 1889     ChainSelectionsInfo["Selections"] = []
 1890 
 1891     if re.match("^None$", SelectionOptionValue, re.I):
 1892         return ChainSelectionsInfo
 1893     
 1894     # Parse selection chains names and selections...
 1895     ChainSelectionsWords = SelectionOptionValue.split(",")
 1896     if len(ChainSelectionsWords) % 2:
 1897         MiscUtil.PrintError("The number of comma delimited selection chains names and selections, %d, specified using \"%s\" option must be a multple of 2." % (len(ChainSelectionsWords), SelectionOptionName))
 1898 
 1899     CanonicalNamesMap = {}
 1900     for Index in range(0, len(ChainSelectionsWords), 2):
 1901         Name = ChainSelectionsWords[Index].strip()
 1902         Selection = ChainSelectionsWords[Index + 1].strip()
 1903 
 1904         if not len(Name):
 1905             MiscUtil.PrintError("A name specified, \"%s\",  using \"%s\" option is empty." % (SelectionOptionValue, SelectionOptionName))
 1906         if not len(Selection):
 1907             MiscUtil.PrintError("A selection specified, \"%s\", using \"%s\" option is empty." % (SelectionOptionValue, SelectionOptionName))
 1908 
 1909         CanonicalName = Name.lower()
 1910         if CanonicalName in CanonicalNamesMap:
 1911             MiscUtil.PrintError("The name %s  specified using \"%s\" option is a duplicate name." % (Name, SelectionOptionName))
 1912         CanonicalNamesMap[CanonicalName] = Name
 1913 
 1914         if re.search("[^a-zA-Z0-9 _\-]", Name, re.I):
 1915             MiscUtil.PrintError("The name %s  specified using \"%s\" option contains invalid charactors. Supportted characters: alphanumeric,  space, hyphen and underscore.." )
 1916         
 1917         ChainSelectionsInfo["Names"].append(Name)
 1918         ChainSelectionsInfo["Selections"].append(Selection)
 1919     
 1920     return ChainSelectionsInfo
 1921 
 1922 def CalculateCenterOfMass(Selection = "all", Quiet = 0):
 1923     """Calculate center of mass for a selection.
 1924 
 1925     Arguments:
 1926         Selection (str): A PyMOL selection.
 1927         Quiet (int): Print information.
 1928 
 1929     Returns:
 1930         list: X, Y, Z coordinates for center of mass.
 1931 
 1932     """
 1933     MassTotal = 0.0
 1934     X, Y, Z = [0.0, 0.0, 0.0]
 1935     
 1936     Atoms = cmd.get_model(Selection)
 1937     for Atom in Atoms.atom:
 1938         Mass = Atom.get_mass()
 1939         MassTotal += Mass
 1940 
 1941         X += Atom.coord[0] * Mass
 1942         Y += Atom.coord[1] * Mass
 1943         Z += Atom.coord[2] * Mass
 1944 
 1945     XCOM = X/MassTotal
 1946     YCOM = Y/MassTotal
 1947     ZCOM = Z/MassTotal
 1948 
 1949     if not Quiet:
 1950         MiscUtil.PrintInfo("PyMOLUtil.CalculateCenterOfMass: %f, %f, %f" % (XCOM, YCOM, ZCOM))
 1951     
 1952     return [XCOM, YCOM, ZCOM]
 1953 
 1954 def ConvertFileFormat(Infile, Outfile, Reinitialize = True, OutputFeedback = True):
 1955     """Convert infile to outfile by automatically detecting their formats
 1956     from the file extensions.
 1957 
 1958     The formats of both input and output files must be a valid format supported
 1959     by PyMOL.
 1960 
 1961     Arguments:
 1962         Infile (str): Name of input file.
 1963         Outfile (str): Name of outfile file.
 1964         Reinitialize (bool): Reinitialize PyMOL before loading input file.
 1965         OutputFeedback (bool): Control output feedback.
 1966 
 1967     """
 1968     
 1969     if not os.path.exists(Infile):
 1970         MiscUtil.PrintWarning("The input file, %s, doesn't exists.%s..." % (Infile))
 1971 
 1972     if Reinitialize:
 1973         cmd.reinitialize()
 1974 
 1975     if not OutputFeedback:
 1976         # Turn off output feedback...
 1977         MiscUtil.PrintInfo("Disabling output feedback for PyMOL...")
 1978         cmd.feedback("disable", "all", "output")
 1979 
 1980     FileDir, FileName, FileExt = MiscUtil.ParseFileName(Infile)
 1981     MolName = FileName
 1982     
 1983     cmd.load(Infile, MolName)
 1984     cmd.save(Outfile, MolName)
 1985     cmd.delete(MolName)
 1986     
 1987     if not OutputFeedback:
 1988         # Turn it back on...
 1989         MiscUtil.PrintInfo("\nEnabling output feedback for PyMOL...")
 1990         cmd.feedback("enable", "all", "output")
 1991 
 1992 def ConvertPMLFileToPSEFile(PMLFile, PSEFile, Reinitialize = True, OutputFeedback = True):
 1993     """Convert PML file to PME file.
 1994 
 1995     Arguments:
 1996         PMLFile (str): Name of PML file.
 1997         PSEFile (str): Name of PSE file.
 1998         Reinitialize (bool): Reinitialize PyMOL before loading PML file.
 1999         OutputFeedback (bool): Control output feedback.
 2000 
 2001     """
 2002     
 2003     if not os.path.exists(PMLFile):
 2004         MiscUtil.PrintWarning("The PML file, %s, doesn't exists.%s..." % (PMLFile))
 2005 
 2006     if Reinitialize:
 2007         cmd.reinitialize()
 2008 
 2009     if not OutputFeedback:
 2010         # Turn off output feedback...
 2011         MiscUtil.PrintInfo("Disabling output feedback for PyMOL...")
 2012         cmd.feedback("disable", "all", "output")
 2013 
 2014     cmd.do("@%s" % PMLFile)
 2015     cmd.save(PSEFile)
 2016     
 2017     if not OutputFeedback:
 2018         # Turn it back on...
 2019         MiscUtil.PrintInfo("\nEnabling output feedback for PyMOL...")
 2020         cmd.feedback("enable", "all", "output")
 2021 
 2022 def SetupPMLHeaderInfo(ScriptName = None, IncludeLocalPython = True):
 2023     """Setup header information for generating PML files. The local Python
 2024     functions are optionally embedded in the header information for their
 2025     use in PML files.
 2026  
 2027     Arguments:
 2028         ScriptName (str): Name of script calling the function.
 2029         IncludeLocalPython (bool): Include local Python functions.
 2030 
 2031     Returns:
 2032         str: Text containing header information for generating PML files.
 2033 
 2034     """
 2035     if ScriptName is None:
 2036         HeaderInfo = """\
 2037 #
 2038 # This file is automatically generated by a script available in MayaChemTools.
 2039 #
 2040 cmd.reinitialize()"""
 2041     else:
 2042         HeaderInfo = """\
 2043 #
 2044 # This file is automatically generated by the following PyMOL script available in
 2045 # MayaChemTools: %s
 2046 #
 2047 cmd.reinitialize() """ % (ScriptName)
 2048 
 2049     if IncludeLocalPython:
 2050         PMLForLocalPython = _SetupPMLForLocalPython()
 2051         HeaderInfo = "%s\n\n%s" % (HeaderInfo, PMLForLocalPython)
 2052     
 2053     return HeaderInfo
 2054 
 2055 def _SetupPMLForLocalPython():
 2056     """Setup local Python functions for PML file.
 2057     """
 2058     
 2059     PMLForPython = """\
 2060 ""
 2061 "Setting up local Python functions  for PML script..."
 2062 ""
 2063 python
 2064 
 2065 from __future__ import print_function
 2066 import re
 2067 
 2068 def ColorByHydrophobicity(Selection, ColorPalette = "RedToWhite"):
 2069     \"""Color by hydrophobicity using hydrophobic values for amino acid
 2070     residues corresponding to the Eisenberg hydrophobicity scale.
 2071     
 2072     Possible values for ColorPalette: RedToWhite or WhiteToGreen from most
 2073     hydrophobic amino acid to least hydrophobic.
 2074     
 2075     The colors values for amino acids are taken from color_h script avaiable
 2076     as part of the Script Library at PyMOL Wiki. 
 2077         
 2078     \"""
 2079         
 2080     if not re.match("^(RedToWhite|WhiteToGreen)$", ColorPalette, re.I):
 2081         print("Invalid ColorPalette value: %s. Valid values: RedToWhite, WhiteToGreen" % ColorPalette)
 2082     
 2083     ResColors = {}
 2084     ColorType = ""
 2085     
 2086     if re.match("^WhiteToGreen$", ColorPalette, re.I):
 2087         ColorType = "H2"
 2088         ResColors = {"ile" : [0.938,1,0.938], "phe" : [0.891,1,0.891], "val" : [0.844,1,0.844], "leu" : [0.793,1,0.793], "trp" : [0.746,1,0.746], "met" : [0.699,1,0.699], "ala" : [0.652,1,0.652], "gly" : [0.606,1,0.606], "cys" : [0.555,1,0.555], "tyr" : [0.508,1,0.508], "pro" : [0.461,1,0.461], "thr" : [0.414,1,0.414], "ser" : [0.363,1,0.363], "his" : [0.316,1,0.316], "glu" : [0.27,1,0.27], "asn" : [0.223,1,0.223], "gln" : [0.176,1,0.176], "asp" : [0.125,1,0.125], "lys" : [0.078,1,0.078], "arg" : [0.031,1,0.031]}
 2089     else:
 2090         ColorType = "H1"
 2091         ResColors = {"ile" : [0.996,0.062,0.062], "phe" : [0.996,0.109,0.109], "val" : [0.992,0.156,0.156], "leu" : [0.992,0.207,0.207], "trp" : [0.992,0.254,0.254], "met" : [0.988,0.301,0.301], "ala" : [0.988,0.348,0.348], "gly" : [0.984,0.394,0.394], "cys" : [0.984,0.445,0.445], "tyr" : [0.984,0.492,0.492], "pro" : [0.980,0.539,0.539], "thr" : [0.980,0.586,0.586], "ser" : [0.980,0.637,0.637], "his" : [0.977,0.684,0.684], "glu" : [0.977,0.730,0.730], "asn" : [0.973,0.777,0.777], "gln" : [0.973,0.824,0.824], "asp" : [0.973,0.875,0.875], "lys" : [0.899,0.922,0.922], "arg" : [0.899,0.969,0.969]}
 2092         
 2093     # Set up colors...
 2094     for ResName in ResColors:
 2095         ColorName = "color_%s_%s" % (ResName, ColorType)
 2096         cmd.set_color(ColorName, ResColors[ResName])
 2097         
 2098         ResSelection = "(%s and resn %s*)" % (Selection, ResName)
 2099         cmd.color(ColorName, ResSelection)
 2100     
 2101 cmd.extend("ColorByHydrophobicity", ColorByHydrophobicity)
 2102 
 2103 def ColorAtomsByHydrophobicityAndCharge(Selection, HydrophobicAtomsColor = "yellow", NegativelyChargedAtomsColor = "red", PositivelyChargedAtomsColor = "blue", OtherAtomsColor = "gray90"):
 2104     \"""Color atoms in amino acids by their propensity to make hydrophobic and
 2105     charge interactions [REF 140].  The atom names in standard amino acid
 2106     residues are used to identify atom types as shown below:
 2107     
 2108         Hydrophobic: C atoms not bound to N or O atoms
 2109         NegativelyCharged: Side chain O atoms in ASP and GLU
 2110         PositivelyCharged: Side chain N atoms in ARG and LYS
 2111         Others: Remaining atoms in polar and other residues
 2112          
 2113     The following color scheme is used by default:
 2114 
 2115         Hydrophobic: yellow
 2116         NegativelyCharged: red
 2117         PositivelyCharged: blue
 2118         Others: gray90
 2119     
 2120     The  amino acid atom names to color specific atoms  are taken from YRB.py
 2121     script [ REF 140]. The color values may also be specified as comma delimited
 2122     RGB triplets. For example: HydrophobicAtomsColor = "0.950 0.78 0.0",
 2123     NegativelyChargedAtomsColor = "1.0 0.4 0.4", PositivelyChargedAtomsColor
 2124     = "0.2 0.5 0.8", OtherAtomsColor = "0.95 0.95 0.95"
 2125     
 2126     \"""
 2127 
 2128     # Process colors...
 2129     Colors = {"HydrophobicAtomsColor": HydrophobicAtomsColor, "NegativelyChargedAtomsColor": NegativelyChargedAtomsColor, "PositivelyChargedAtomsColor": PositivelyChargedAtomsColor, "OtherAtomsColor": OtherAtomsColor}
 2130     ColorsRGB = {}
 2131     for ColorKey, ColorValue in Colors.items():
 2132         if re.search(" ", ColorValue):
 2133             ColorRGB = ColorValue.split(" ")
 2134         else:
 2135             ColorRGB = cmd.get_color_tuple(cmd.get_color_index(ColorValue))
 2136         ColorsRGB[ColorKey] = ColorRGB
 2137     
 2138     # Set up colors...
 2139     for ColorKey, ColorValue in ColorsRGB.items():
 2140         cmd.set_color(ColorKey, ColorValue)
 2141 
 2142     #  Set up colors for atom names across all resiudes...
 2143     AtomColors = {"OtherAtomsColor": "N,C,CA,O", "HydrophobicAtomsColor": "CB"}
 2144     
 2145     #  Set up colors for atom names across specific resiudes...
 2146     ResAtomColors = {"arg" : {"HydrophobicAtomsColor": "CG", "PositivelyChargedAtomsColor": "NE,NH2,NH1", "OtherAtomsColor": "CD,CZ"}, "asn" : {"OtherAtomsColor": "CG,OD1,ND2"}, "asp" : {"NegativelyChargedAtomsColor": "OD2,OD1", "OtherAtomsColor": "CG"}, "cys" : {"OtherAtomsColor": "SG"}, "gln" : {"HydrophobicAtomsColor": "CG", "OtherAtomsColor": "CD,OE1,NE2"}, "glu" : {"HydrophobicAtomsColor": "CG", "NegativelyChargedAtomsColor": "OE1,OE2", "OtherAtomsColor": "CD"}, "his" : {"OtherAtomsColor": "CG,CD2,ND1,NE2,CE1"}, "ile" : {"HydrophobicAtomsColor": "CG1,CG2,CD1"}, "leu" : {"HydrophobicAtomsColor": "CG,CD1,CD2"}, "lys" : {"HydrophobicAtomsColor": "CG,CD", "PositivelyChargedAtomsColor": "NZ", "OtherAtomsColor": "CE"}, "met" : {"HydrophobicAtomsColor": "CG,CE", "OtherAtomsColor": "SD"}, "phe" : {"HydrophobicAtomsColor": "CG,CD1,CE1,CZ,CE2,CD2"}, "pro" : {"HydrophobicAtomsColor": "CG", "OtherAtomsColor": "CD"}, "ser" : {"OtherAtomsColor": "CB,OG"}, "thr" : {"HydrophobicAtomsColor": "CG2", "OtherAtomsColor": "CB,OG1"}, "trp" : {"HydrophobicAtomsColor": "CG,CD2,CZ2,CH2,CZ3,CE3", "OtherAtomsColor": "CD1,NE1,CE2"}, "tyr" : {"HydrophobicAtomsColor": "CG,CE1,CD1,CE2,CD2", "OtherAtomsColor": "CZ,OH"}, "val" : {"HydrophobicAtomsColor": "CG1,CG2"}}
 2147     
 2148     #  Color atom names across all resiudes...
 2149     for ColorName in AtomColors:
 2150         AtomNames = AtomColors[ColorName]
 2151         AtomsSelection = "(%s and name %s)" % (Selection, AtomNames)
 2152         cmd.color(ColorName, AtomsSelection)
 2153         
 2154     #  Color atom names across specific resiudes...
 2155     for ResName in ResAtomColors:
 2156         for ColorName in ResAtomColors[ResName]:
 2157             AtomNames = ResAtomColors[ResName][ColorName]
 2158             AtomsSelection = "(%s and resn %s and name %s)" % (Selection, ResName, AtomNames)
 2159             cmd.color(ColorName, AtomsSelection)
 2160     
 2161 cmd.extend("ColorAtomsByHydrophobicityAndCharge", ColorAtomsByHydrophobicityAndCharge)
 2162 
 2163 def CheckAndDeleteEmptyObjects(ObjectNames, ParentObjectName = None):
 2164     \"""Delete an empty objects along with optionally deleting their parent.
 2165         
 2166     \"""
 2167     
 2168     ObjectNamesList = ObjectNames.split(",")
 2169 
 2170     AllObjectsEmpty = True
 2171     for ObjectName in ObjectNamesList:
 2172         ObjectName = ObjectName.strip()
 2173         if  cmd.count_atoms("(%s)" % ObjectName):
 2174             AllObjectsEmpty = False
 2175         else:
 2176             cmd.delete("%s" % ObjectName)
 2177     
 2178     if AllObjectsEmpty and ParentObjectName is not None:
 2179         cmd.delete("%s" % ParentObjectName)
 2180     
 2181 cmd.extend("CheckAndDeleteEmptyObjects", CheckAndDeleteEmptyObjects)
 2182 
 2183 python end"""
 2184     
 2185     return PMLForPython
 2186 
 2187 def SetupPMLForEnableDisable(Name, Enable = True):
 2188     """Setup PML command for enabling or disabling display of a PyMOL object.
 2189 
 2190     Arguments:
 2191         Name (str): Name of a PyMOL object.
 2192         Enable (bool): Display status.
 2193 
 2194     Returns:
 2195         str: PML command for enabling or disabling display of an object.
 2196 
 2197     """
 2198     
 2199     if Enable:
 2200         PML = """cmd.enable("%s")""" % Name
 2201     else:
 2202         PML = """cmd.disable("%s")""" % Name
 2203         
 2204     return PML
 2205 
 2206 def SetupPMLForGroup(GroupName, GroupMembersList, Enable = None, Action = None):
 2207     """Setup PML commands for creating a group from a list of group members. The
 2208     display and open status of the group may be optionally set. The 'None' values
 2209     for Enable and Action imply usage of PyMOL defaults for the creation of group.
 2210 
 2211     Arguments:
 2212         GroupName (str): Name of a PyMOL group.
 2213         GroupMembersList (list): List of group member names.
 2214         Enable (bool): Display status of group.
 2215         Action (str): Open or close status of group object.
 2216 
 2217     Returns:
 2218         str: PML commands for creating a group object.
 2219 
 2220     """
 2221 
 2222     PMLCmds = []
 2223     
 2224     GroupMembers = " ".join(GroupMembersList)
 2225     PMLCmds.append("""cmd.group("%s", "%s")""" % (GroupName, GroupMembers))
 2226     
 2227     if Enable is not None:
 2228         if Enable:
 2229             PMLCmds.append("""cmd.enable("%s")""" % GroupName)
 2230         else:
 2231             PMLCmds.append("""cmd.disable("%s")""" % GroupName)
 2232     
 2233     if Action is not None:
 2234         PMLCmds.append("""cmd.group("%s", action="%s")""" % (GroupName, Action))
 2235 
 2236     PML = "\n".join(PMLCmds)
 2237     
 2238     return PML
 2239 
 2240 def SetupPMLForLigandView(Name, Selection, LigandResName, Enable = True):
 2241     """Setup PML commands for creating a ligand view corresponding to a ligand 
 2242     present in a selection. The ligand is identified using organic selection
 2243     operator available in PyMOL in conjunction with the specified ligand ID.
 2244     The ligand is colored by atom types and displayed as 'sticks'.
 2245 
 2246     Arguments:
 2247         Name (str): Name of a new PyMOL ligand object.
 2248         Selection (str): PyMOL selection containing ligand.
 2249         LigandResName (str): Ligand ID.
 2250         Enable (bool): Display status of ligand object.
 2251 
 2252     Returns:
 2253         str: PML commands for a ligand view.
 2254 
 2255     """
 2256 
 2257     PMLCmds = []
 2258     PMLCmds.append("""cmd.create("%s", "((%s) and organic and (resn %s))")""" % (Name, Selection, LigandResName))
 2259     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2260     PMLCmds.append("""util.cbag("%s", _self = cmd)""" % (Name))
 2261     PMLCmds.append("""cmd.show("sticks", "%s")""" % (Name))
 2262     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2263     
 2264     PML = "\n".join(PMLCmds)
 2265     
 2266     return PML
 2267 
 2268 def SetupPMLForLigandPocketView(Name, Selection, LigandSelection, DistanceCutoff, Enable = True):
 2269     """Setup PML commands for creating a ligand binding pocket view
 2270     corresponding all residues present in a selection within a specified
 2271     distance from a ligand selection. The solvent and inorganic portions of
 2272     the selection are not included in the binding pocket. The pocket residues
 2273     are shown as 'lines'. The hydrogen atoms are not displayed.
 2274 
 2275     Arguments:
 2276         Name (str): Name of a new PyMOL binding pocket object.
 2277         Selection (str): PyMOL selection containing binding pocket residues.
 2278         LigandSelection (str): PyMOL selection containing ligand.
 2279         DistanceCutoff (float): Distance cutoff from ligand for selecting
 2280             binding pockect residues.
 2281         Enable (bool): Display status of binding pocket object.
 2282 
 2283     Returns:
 2284         str: PML commands for a ligand binding pocket view.
 2285 
 2286     """
 2287 
 2288     PMLCmds = []
 2289     PMLCmds.append("""cmd.create("%s", "((byresidue (%s) within %.1f of (%s)) and (not solvent) and (not inorganic) and (not organic))")""" % (Name, Selection, DistanceCutoff, LigandSelection))
 2290     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2291     PMLCmds.append("""cmd.show("lines", "(%s)")""" % (Name))
 2292     PMLCmds.append("""cmd.hide("(%s and hydro)")""" % (Name))
 2293     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2294     
 2295     PML = "\n".join(PMLCmds)
 2296     
 2297     return PML
 2298 
 2299 def SetupPMLForLigandPocketSolventView(Name, Selection, LigandSelection, DistanceCutoff, Enable = True):
 2300     """Setup PML commands for creating a ligand binding pocket view
 2301     corresponding to only solvent residues present in a selection within a
 2302     specified distance from a ligand selection. The solvent pocket residues
 2303     are shown as 'lines' and 'nonbonded'.
 2304 
 2305     Arguments:
 2306         Name (str): Name of a new PyMOL solvent binding pocket object.
 2307         Selection (str): PyMOL selection containing binding pocket residues.
 2308         LigandSelection (str): PyMOL selection containing ligand.
 2309         DistanceCutoff (float): Distance cutoff from ligand for selecting
 2310             binding pocket solvent residues.
 2311         Enable (bool): Display status of binding pocket object.
 2312 
 2313     Returns:
 2314         str: PML commands for a ligand binding pocket view only showing solvent
 2315             residues.
 2316 
 2317     """
 2318 
 2319     PMLCmds = []
 2320     PMLCmds.append("""cmd.create("%s", "((byresidue (%s) within %.1f of (%s)) and solvent)")""" % (Name, Selection, DistanceCutoff, LigandSelection))
 2321     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2322     PMLCmds.append("""cmd.show("nonbonded", "%s")""" % (Name))
 2323     PMLCmds.append("""cmd.show("lines", "%s")""" % (Name))
 2324     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2325     
 2326     PML = "\n".join(PMLCmds)
 2327     
 2328     return PML
 2329 
 2330 def SetupPMLForLigandPocketInorganicView(Name, Selection, LigandSelection, DistanceCutoff, Enable = True):
 2331     """Setup PML commands for creating a ligand binding pocket view
 2332     corresponding to only inorganic residues present in a selection within a
 2333     specified distance from a ligand selection. The inorganic pocket residues
 2334     are shown as 'lines' and 'nonbonded'.
 2335 
 2336     Arguments:
 2337         Name (str): Name of a new PyMOL solvent binding pocket object.
 2338         Selection (str): PyMOL selection containing binding pocket residues.
 2339         LigandSelection (str): PyMOL selection containing ligand.
 2340         DistanceCutoff (float): Distance cutoff from ligand for selecting
 2341             binding pocket inorganic residues.
 2342         Enable (bool): Display status of binding pocket object.
 2343 
 2344     Returns:
 2345         str: PML commands for a ligand binding pocket view only showing inorganic
 2346             residues.
 2347 
 2348     """
 2349 
 2350     PMLCmds = []
 2351     PMLCmds.append("""cmd.create("%s", "((byresidue (%s) within %.1f of (%s)) and inorganic)")""" % (Name, Selection, DistanceCutoff, LigandSelection))
 2352     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2353     PMLCmds.append("""cmd.show("nonbonded", "%s")""" % (Name))
 2354     PMLCmds.append("""cmd.show("lines", "%s")""" % (Name))
 2355     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2356     
 2357     PML = "\n".join(PMLCmds)
 2358     
 2359     return PML
 2360 
 2361 def SetupPMLForPolarContactsView(Name, Selection1, Selection2, Enable = True, Color = "yellow", Cutoff = None):
 2362     """Setup PML commands for creating polar contacts view between a pair of
 2363     selections. The polar contact view is generated using 'util.dist' command. The
 2364     distance labels are shown by default.
 2365 
 2366     Arguments:
 2367         Name (str): Name of a new PyMOL polar contacts object.
 2368         Selection1 (str): First PyMOL selection.
 2369         Selection2 (str): Second PyMOL selection.
 2370         Enable (bool): Display status of polar contacts object.
 2371         Color (str): Color for polar contact lines and labels.
 2372         DistanceCutoff (float): None or distance cutoff for polar contacts.
 2373 
 2374     Returns:
 2375         str: PML commands for polar contacts view between a pair of selections.
 2376 
 2377     """
 2378     
 2379     PMLCmds = []
 2380     if Cutoff is None:
 2381         PMLCmds.append("""cmd.dist("%s","(%s)","(%s)", quiet = 1, mode = 2, label = 1, reset = 1)""" % (Name, Selection1, Selection2))
 2382     else:
 2383         PMLCmds.append("""cmd.dist("%s","(%s)","(%s)", cutoff = %.1f, quiet = 1, mode = 2, label = 1, reset = 1)""" % (Name, Selection1, Selection2, Cutoff))
 2384         
 2385     PMLCmds.append("""util.color_deep("%s", "%s")""" % (Color, Name))
 2386     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2387     
 2388     PML = "\n".join(PMLCmds)
 2389     
 2390     return PML
 2391 
 2392 def SetupPMLForHydrophobicContactsView(Name, Selection1, Selection2, Enable = True, Color = "yellow", Cutoff = None):
 2393     """Setup PML commands for creating hydrophobic contacts view between a pair of
 2394     selections. The hydrophobic contacts are shown between pairs of carbon atoms not
 2395     connected to hydrogen bond donor or acceptors atoms as identified by PyMOL. The
 2396     distance labels are shown by default.
 2397 
 2398     Arguments:
 2399         Name (str): Name of a new PyMOL polar contacts object.
 2400         Selection1 (str): First PyMOL selection.
 2401         Selection2 (str): Second PyMOL selection.
 2402         Enable (bool): Display status of polar contacts object.
 2403         Color (str): Color for polar contact lines and labels.
 2404         Cutoff (float): None or distance cutoff for hydrophobic contacts.
 2405 
 2406     Returns:
 2407         str: PML commands for polar contacts view between a pair of selections.
 2408 
 2409     """
 2410 
 2411     PMLCmds = []
 2412     
 2413     HydrophobicSelectionAtoms1 = "((%s) and (elem C) and (not bound_to (donors or acceptors)))" % (Selection1)
 2414     HydrophobicSelectionAtoms2 = "((%s) and (elem C) and (not bound_to (donors or acceptors)))" % (Selection2)
 2415     
 2416     if Cutoff is None:
 2417         PMLCmds.append("""cmd.dist("%s","(%s)","(%s)", quiet = 1, label = 1, reset = 1)""" % (Name, HydrophobicSelectionAtoms1, HydrophobicSelectionAtoms2))
 2418     else:
 2419         PMLCmds.append("""cmd.dist("%s","(%s)","(%s)", cutoff = %.1f, quiet = 1,  label = 1, reset = 1)""" % (Name, HydrophobicSelectionAtoms1, HydrophobicSelectionAtoms2, Cutoff))
 2420         
 2421     PMLCmds.append("""util.color_deep("%s", "%s")""" % (Color, Name))
 2422     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2423     
 2424     PML = "\n".join(PMLCmds)
 2425     
 2426     return PML
 2427 
 2428 def SetupPMLForAlignment(Method, RefSelection, FitSelection):
 2429     """Setup PML commands for aligning a pair of selection using  a specified
 2430     alignment method.
 2431 
 2432     Arguments:
 2433         Method (str): Alignment method. Possible values: align, cealign, super.
 2434         RefSelection (str): Name of reference selection which stays stationary.
 2435         FitSelection (str): Name of selection to align to reference selection.
 2436 
 2437     Returns:
 2438         str: PML commands for aligning  a pair of selections.
 2439 
 2440     """
 2441 
 2442     PMLCmds = []
 2443     if re.match("^align$", Method, re.I):
 2444         PMLCmds.append("""cmd.align("(%s)", "(%s)")""" % (FitSelection, RefSelection))
 2445     elif re.match("^cealign$", Method, re.I):
 2446         PMLCmds.append("""cmd.cealign("(%s)", "(%s)")""" % (RefSelection, FitSelection))
 2447     elif re.match("^super$", Method, re.I):
 2448         PMLCmds.append("""cmd.super("(%s)", "(%s)")""" % (FitSelection, RefSelection))
 2449     else:
 2450         MiscUtil.PrintWarning("PyMOLUtil.SetupPMLForAlignment: Invalid method name: %s" % Method)
 2451 
 2452     PML = "\n".join(PMLCmds)
 2453     
 2454     return PML
 2455 
 2456 def SetupPMLForBFactorPuttyView(Name, Selection, ColorPalette = "blue_white_red", Enable = True):
 2457     """Setup PML commands for creating a B factor putty view for a specified
 2458     selection. The B factor values must be available for the atoms. The atoms
 2459     are colored using a color spectrum corresponding to a specified color
 2460     palette. Any valid PyMOL color palette name may be used.
 2461 
 2462     Arguments:
 2463         Name (str): Name of a new PyMOL B factor putty object.
 2464         Selection (str): Name of PyMOL selection.
 2465         ColorPalette (str): Name of color palette to use for color spectrum.
 2466         Enable (bool): Display status of B factor putty object.
 2467 
 2468     Returns:
 2469         str: PML commands for B factor putty view.
 2470 
 2471     """
 2472     
 2473     PMLCmds = []
 2474     PMLCmds.append("""cmd.create("%s", "(%s)")""" % (Name, Selection))
 2475     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2476     PMLCmds.append("""cmd.spectrum("b", "%s", "(%s)")""" % (ColorPalette, Name))
 2477     PMLCmds.append("""cmd.show("cartoon", "%s")""" % (Name))
 2478     PMLCmds.append("""cmd.cartoon("putty", "%s")""" % (Name))
 2479     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2480     
 2481     PML = "\n".join(PMLCmds)
 2482     
 2483     return PML
 2484 
 2485 def SetupPMLForHydrophobicSurfaceView(Name, Selection, ColorPalette = "RedToWhite", Enable = True, DisplayAs = "cartoon"):
 2486     """Setup PML commands for creating a hydrophobic surface view for a specified
 2487     selection. The surfaces are colored using a specified color palette. This is only valid
 2488     for amino acids.
 2489 
 2490     Arguments:
 2491         Name (str): Name of a new PyMOL hydrophobic surface object.
 2492         Selection (str): Name of PyMOL selection.
 2493         ColorPalette (str): Name of color palette to use for coloring surfaces.
 2494             Possible values: RedToWhite or WhiteToGreen for most hydrophobic
 2495             to least hydrophobic amino acids.
 2496         Enable (bool): Display status of surface object.
 2497         DisplayAs (str): Any additional valid display type such as lines,
 2498             sticks, ribbon, cartoon, or None. 
 2499 
 2500     Returns:
 2501         str: PML commands for hydrophobic surface view.
 2502 
 2503     """
 2504 
 2505     PMLCmds = _GetPMLCmdsForSurfaceView(Name, Selection, DisplayAs)
 2506     PMLCmds.append("""ColorByHydrophobicity("%s", "%s")""" % (Name, ColorPalette))
 2507     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2508     
 2509     PML = "\n".join(PMLCmds)
 2510     
 2511     return PML
 2512 
 2513 def SetupPMLForHydrophobicAndChargeSurfaceView(Name, Selection, HydrophobicAtomsColor = "yellow", NegativelyChargedAtomsColor = "red", PositivelyChargedAtomsColor = "blue", OtherAtomsColor = "gray90", Enable = True, DisplayAs = "cartoon"):
 2514     """Setup PML commands for creating a surface colored by hydrophobic and
 2515     charge [ REF 140] properties of atoms in amino acids. The atom names in
 2516     standard amino acid residues are used to identify atom types as shown below:
 2517 
 2518     Hydrophobic: C atoms not bound to N or O atoms; NegativelyCharged: Side
 2519     chain O atoms in ASP and GLU; PositivelyCharged: Side chain N atoms in
 2520     ARG and LYS; Others: Remaining atoms in polar and other residues
 2521 
 2522     The  amino acid atom names to color specific atoms  are taken from YRB.py
 2523     script [ REF 140]. The color values may also be specified as comma delimited
 2524     RGB triplets. For example: HydrophobicAtomsColor = "0.950 0.78 0.0",
 2525     NegativelyChargedAtomsColor = "1.0 0.4 0.4", PositivelyChargedAtomsColor
 2526     = "0.2 0.5 0.8", OtherAtomsColor = "0.95 0.95 0.95"
 2527 
 2528     Arguments:
 2529         Name (str): Name of a new PyMOL hydrophobic surface object.
 2530         Selection (str): Name of PyMOL selection.
 2531         HydrophobicAtomsColor (str): Color name or space delimited RGB values
 2532         NegativelyChargedAtomsColor (str): Color name or space delimited RGB values
 2533         PositivelyChargedAtomsColor (str): Color name or space delimited RGB values
 2534         OtherAtomsColor (str): Color name or space delimited RGB values
 2535         Enable (bool): Display status of surface object.
 2536         DisplayAs (str): Any additional valid display type such as lines,
 2537             sticks, ribbon, cartoon, or None. 
 2538 
 2539     Returns:
 2540         str: PML commands for hydrophobic and charge surface view.
 2541 
 2542     """
 2543 
 2544     PMLCmds = _GetPMLCmdsForSurfaceView(Name, Selection, DisplayAs)
 2545     PMLCmds.append("""ColorAtomsByHydrophobicityAndCharge("%s", "%s", "%s", "%s", "%s")""" % (Name, HydrophobicAtomsColor, NegativelyChargedAtomsColor, PositivelyChargedAtomsColor, OtherAtomsColor))
 2546     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2547     
 2548     PML = "\n".join(PMLCmds)
 2549     
 2550     return PML
 2551 
 2552 def SetupPMLForSurfaceView(Name, Selection, Enable = True, DisplayAs = "cartoon", Color = "None"):
 2553     """Setup PML commands for creating a molecular surface view for a specified
 2554     selection.
 2555 
 2556     Arguments:
 2557         Name (str): Name of a new PyMOL molecular surface object.
 2558         Selection (str): Name of PyMOL selection.
 2559         Enable (bool): Display status of surface object.
 2560         DisplayAs (str): Any additional valid display type such as lines,
 2561             sticks, ribbon, cartoon, or None. 
 2562         Color (str): Surafce color.
 2563 
 2564     Returns:
 2565         str: PML commands for molecular surface view.
 2566 
 2567     """
 2568 
 2569     PMLCmds = _GetPMLCmdsForSurfaceView(Name, Selection, DisplayAs)
 2570     if Color is not None:
 2571         PMLCmds.append("""util.color_deep("%s", "%s")""" % (Color, Name))
 2572     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2573     
 2574     PML = "\n".join(PMLCmds)
 2575     
 2576     return PML
 2577 
 2578 def _GetPMLCmdsForSurfaceView(Name, Selection, DisplayAs = "cartoon"):
 2579     """Setup PML command for surface view."""
 2580 
 2581     PMLCmds = []
 2582     PMLCmds.append("""cmd.create("%s", "(%s)")""" % (Name, Selection))
 2583     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2584     if DisplayAs is not None:
 2585         PMLCmds.append("""cmd.show("%s", "%s")""" % (DisplayAs, Name))
 2586     PMLCmds.append("""cmd.show("surface", "%s")""" % (Name))
 2587 
 2588     return PMLCmds
 2589     
 2590 def SetupPMLForSelectionDisplayView(Name, Selection, DisplayAs, Color = None, Enable = True):
 2591     """Setup PML commands for creating a specific molecular display view for a
 2592      selection.
 2593 
 2594     Arguments:
 2595         Name (str): Name of a new PyMOL object.
 2596         Selection (str): Name of PyMOL selection.
 2597         DisplayAs (str): Any valid display type such as lines, sticks, ribbon,
 2598             cartoon, or surface
 2599         Color (str): Color name or use default color.
 2600         Enable (bool): Display status of object.
 2601 
 2602     Returns:
 2603         str: PML commands for molecular selection view.
 2604 
 2605     """
 2606 
 2607     PMLCmds = []
 2608     PMLCmds.append("""cmd.create("%s", "(%s)")""" % (Name, Selection))
 2609     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2610     PMLCmds.append("""cmd.show("%s", "%s")""" % (DisplayAs, Name))
 2611     if Color is not None:
 2612         PMLCmds.append("""util.color_deep("%s", "%s")""" % (Color, Name))
 2613     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2614     
 2615     PML = "\n".join(PMLCmds)
 2616     
 2617     return PML
 2618 
 2619 def SetupPMLForBallAndStickView(Name, Selection, Enable = True, SphereScale = 0.3, StickRadius = 0.2):
 2620     """Setup PML commands for creating a ball and stick view for a specified
 2621     selection.
 2622 
 2623     Arguments:
 2624         Name (str): Name of a new PyMOL ball and stick object.
 2625         Selection (str): Name of PyMOL selection.
 2626         Enable (bool): Display status of ball and stick object.
 2627         SphereScale (float): Scaling factor for sphere radii.
 2628         StickScale (float): Scaling factor for stick radii.
 2629 
 2630     Returns:
 2631         str: PML commands for ball and stick view.
 2632 
 2633     """
 2634 
 2635     PMLCmds = []
 2636     PMLCmds.append("""cmd.create("%s", "(%s)")""" % (Name, Selection))
 2637     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2638     PMLCmds.append("""cmd.show("sphere", "%s")""" % (Name))
 2639     PMLCmds.append("""cmd.show("sticks", "%s")""" % (Name))
 2640     PMLCmds.append("""cmd.set("sphere_scale", %.1f, "%s")""" % (SphereScale, Name))
 2641     PMLCmds.append("""cmd.set("stick_radius", %.1f, "%s")""" % (StickRadius, Name))
 2642     
 2643     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2644     
 2645     PML = "\n".join(PMLCmds)
 2646     
 2647     return PML
 2648 
 2649 def SetupPMLForInorganicView(Name, Selection, Enable = True):
 2650     """Setup PML commands for creating a inorganic view corresponding to
 2651     inorganic residues present in a selection. The inorganic residues are
 2652     identified using inorganic selection operator available in PyMOL. The
 2653     inorganic residues are displayed as 'lines' and 'nonbonded'.
 2654 
 2655     Arguments:
 2656         Name (str): Name of a new PyMOL inorganic object.
 2657         Selection (str): Name of PyMOL selection.
 2658         Enable (bool): Display status of inorganic object.
 2659 
 2660     Returns:
 2661         str: PML commands for inorganic view.
 2662 
 2663     """
 2664 
 2665     PMLCmds = []
 2666     PMLCmds.append("""cmd.create("%s", "((%s) and inorganic)")""" % (Name, Selection))
 2667     PMLCmds.append("""cmd.show("nonbonded", "%s")""" % (Name))
 2668     PMLCmds.append("""cmd.show("lines", "%s")""" % (Name))
 2669     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2670     
 2671     PML = "\n".join(PMLCmds)
 2672     
 2673     return PML
 2674 
 2675 def SetupPMLForSolventView(Name, Selection, Enable = True):
 2676     """Setup PML commands for creating a solvent view corresponding to
 2677     solvent residues present in a selection. The solvent residues are
 2678     identified using solvent selection operator available in PyMOL. The
 2679     solvent residues are displayed as 'nonbonded'.
 2680 
 2681     Arguments:
 2682         Name (str): Name of a new PyMOL solvent object.
 2683         Selection (str): Name of PyMOL selection.
 2684         Enable (bool): Display status of inorganic object.
 2685 
 2686     Returns:
 2687         str: PML commands for solvent view.
 2688 
 2689     """
 2690 
 2691     PMLCmds = []
 2692     PMLCmds.append("""cmd.create("%s", "((%s) and solvent)")""" % (Name, Selection))
 2693     PMLCmds.append("""cmd.show("nonbonded", "%s")""" % (Name))
 2694     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2695     
 2696     PML = "\n".join(PMLCmds)
 2697     
 2698     return PML
 2699 
 2700 def SetupPMLForPolymerChainView(Name, Selection, Enable = True):
 2701     """Setup PML commands for creating a polymer chain view corresponding
 2702     to backbone and sidechain residues in a selection. The polymer chain is
 2703     displayed as 'cartoon'.
 2704 
 2705     Arguments:
 2706         Name (str): Name of a new PyMOL polymer chain object.
 2707         Selection (str): Name of PyMOL selection.
 2708         Enable (bool): Display status of chain object.
 2709 
 2710     Returns:
 2711         str: PML commands for polymer chain view.
 2712 
 2713     """
 2714 
 2715     PMLCmds = []
 2716     PMLCmds.append("""cmd.create("%s", "((%s) and (backbone or sidechain))")""" % (Name, Selection))
 2717     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2718     PMLCmds.append("""util.cbag("%s", _self = cmd)""" % (Name))
 2719     PMLCmds.append("""cmd.show("cartoon", "%s")""" % (Name))
 2720     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2721     
 2722     
 2723     PML = "\n".join(PMLCmds)
 2724     
 2725     return PML
 2726 
 2727 
 2728 def SetupPMLForPolymerComplexView(MoleculeName, PDBFile, Enable = True, ShowSolvent = True, ShowInorganic = True, ShowLines = True):
 2729     """Setup PML commands for creating a polymer complex view for all chains
 2730     in a PDB file. The solvent and inorganic residues are also shown by default.
 2731      The polymer chains are displayed as 'cartoon'. The 'line' display for the
 2732     polymer chains is also shown and may be turned off. The organic residues are
 2733     displayed as 'sticks'. The solvent and inorganic residues are displayed as
 2734     'nonbonded' and 'lines'.
 2735     
 2736     Arguments:
 2737         MoleculeName (str): Name of a new PyMOL molecule object.
 2738         PDBFile (str): Name of PDB file.
 2739         Enable (bool): Display status of chain object.
 2740         ShowSolvent (bool): Display solvent residues.
 2741         ShowInorganic (bool): Display inorganic residues.
 2742         ShowLines (bool): Display lines for polymer chains.
 2743 
 2744     Returns:
 2745         str: PML commands for polymer complex view.
 2746 
 2747     """
 2748 
 2749     PMLCmds = []
 2750     
 2751     PMLCmds.append("""cmd.load("%s", "%s")""" % (PDBFile, MoleculeName))
 2752     PML = _SetupPMLForPolymerComplexView(MoleculeName, Enable, ShowSolvent, ShowInorganic, ShowLines)
 2753     PMLCmds.append(PML)
 2754     
 2755     PML = "\n".join(PMLCmds)
 2756     
 2757     return PML
 2758 
 2759 def SetupPMLForPolymerChainComplexView(ChainComplexName, Selection, ChainName, Enable = True, ShowSolvent = True, ShowInorganic = True, ShowLines = True):
 2760     """Setup PML commands for creating a polymer chain complex view for a specified
 2761     chain in a selection. The solvent and inorganic residues are also shown by
 2762     default. The polymer chain is displayed as 'cartoon'. The 'line' display for the
 2763     polymer chain is also shown and may be turned off. The organic residues are
 2764     displayed as 'sticks'. The solvent and inorganic residues are displayed as
 2765     'nonbonded' and 'lines'.
 2766 
 2767     Arguments:
 2768         ChainComplexName (str): Name of a new PyMOL polymer chain complex.
 2769         Selection (str): Name of PyMOL selection.
 2770         ChainName (str): Name of a chain.
 2771         Enable (bool): Display status of chain object.
 2772         ShowSolvent (bool): Display solvent residues.
 2773         ShowInorganic (bool): Display inorganic residues.
 2774         ShowLines (bool): Display lines for polymer chain.
 2775 
 2776     Returns:
 2777         str: PML commands for polymer chain complex view.
 2778 
 2779     """
 2780 
 2781     PMLCmds = []
 2782     
 2783     PMLCmds.append("""cmd.create("%s", "(%s and chain %s)")""" % (ChainComplexName, Selection, ChainName))
 2784     PML = _SetupPMLForPolymerComplexView(ChainComplexName, Enable, ShowSolvent, ShowInorganic, ShowLines)
 2785     PMLCmds.append(PML)
 2786 
 2787     PML = "\n".join(PMLCmds)
 2788     
 2789     return PML
 2790 
 2791 def _SetupPMLForPolymerComplexView(Name, Enable = True, ShowSolvent = True, ShowInorganic = True,  ShowLines = False):
 2792     """Setup PML for creating a polymer complex view."""
 2793 
 2794     PMLCmds = []
 2795     
 2796     PMLCmds.append("""cmd.hide("everything", "%s")""" % (Name))
 2797     PMLCmds.append("""cmd.show("cartoon", "%s")""" % (Name))
 2798     PMLCmds.append("""util.cba(33, "%s", _self = cmd)""" % (Name))
 2799     PMLCmds.append("""cmd.show("sticks", "(organic and (%s))")""" % (Name))
 2800     if ShowSolvent:
 2801         PMLCmds.append("""cmd.show("nonbonded", "(solvent and (%s))")""" % (Name))
 2802     if ShowInorganic:
 2803         PMLCmds.append("""cmd.show("nonbonded", "(inorganic and (%s))")""" % (Name))
 2804     
 2805     if ShowLines:
 2806         PMLCmds.append("""cmd.show("lines", "%s")""" % (Name))
 2807     else:
 2808         if ShowInorganic:
 2809             PMLCmds.append("""cmd.show("lines", "(inorganic and (%s))")""" % (Name))
 2810     
 2811     PMLCmds.append("""cmd.set_bond("valence", "1", "%s", quiet = 1)""" % (Name))
 2812     PMLCmds.append(SetupPMLForEnableDisable(Name, Enable))
 2813 
 2814     PML = "\n".join(PMLCmds)
 2815     
 2816     return PML