Package mmLib :: Module FileIO
[hide private]
[frames] | no frames]

Source Code for Module mmLib.FileIO

  1  ## Copyright 2002-2010 by PyMMLib Development Group (see AUTHORS file) 
  2  ## This code is part of the PyMMLib distribution and governed by 
  3  ## its license.  Please see the LICENSE file that should have been 
  4  ## included as part of this package. 
  5  """Load and save mmLib.Structure objects from/to mmLib supported formats. 
  6  The mmCIF and PDB file formats are currently supported. 
  7  """ 
  8  import os 
  9  import types 
 10   
 11  from mmCIF        import mmCIFFile 
 12  from mmCIFBuilder import mmCIFStructureBuilder, mmCIFFileBuilder 
 13  from PDB          import PDBFile 
 14  from PDBBuilder   import PDBStructureBuilder, PDBFileBuilder 
 15  from CIFBuilder   import CIFStructureBuilder 
 16   
 17   
18 -class FileIOUnsupportedFormat(Exception):
19 pass
20 21
22 -class ZCat(object):
23 - def __init__(self, path):
24 self.path = path
25
26 - def __iter__(self):
27 import subprocess 28 zcat = subprocess.Popen("/bin/zcat %s" % (self.path), 29 shell=True, 30 stdin=subprocess.PIPE, 31 stdout=subprocess.PIPE, 32 stderr=subprocess.PIPE, 33 close_fds=True) 34 for ln in zcat.stdout.readlines(): 35 yield ln 36 zcat.wait()
37
38 - def readlines(self):
39 return iter(self)
40 41
42 -def OpenFile(path, mode):
43 """Right now this only supports opening GZip'ed files, in the future it 44 might be extended for URLs. 45 """ 46 ## if path is not a string, assume it is a file object and return it 47 48 if isinstance(path, str): 49 base, ext = os.path.splitext(path) 50 if ext == ".gz": 51 import gzip 52 return gzip.open(path, mode) 53 elif ext == ".Z" and mode == "r": 54 return ZCat(path) 55 return open(path, mode) 56 57 return path
58 59
60 -def get_file_extension(path, default_extension = "PDB"):
61 """Returns the 3-letter extension of the filename. 62 """ 63 if not isinstance(path, str): 64 return default_extension 65 66 ## check/remove compressed file extension 67 base, ext = os.path.splitext(path) 68 if ext.lower() in ('.z', '.gz', '.bz2'): 69 path = base 70 71 base, ext = os.path.splitext(path) 72 ext = ext.lower() 73 74 if ext == ".cif": 75 return "CIF" 76 elif ext == ".pdb": 77 return "PDB" 78 79 return default_extension
80
81 -def get_file_arg(args):
82 try: 83 fil = args["fil"] 84 except KeyError: 85 try: 86 fil = args["file"] 87 except KeyError: 88 raise TypeError,"LoadStructure(file=) argument required" 89 90 return fil
91 92
93 -def open_fileobj(fil, file_mode):
94 if isinstance(fil, str): 95 fileobj = OpenFile(fil, file_mode) 96 else: 97 fileobj = fil 98 return fileobj
99 100
101 -def LoadStructure(**args):
102 """Loads a mmCIF file(.cif) or PDB file(.pdb) into a Structure class and 103 returns it. 104 The function takes 5 named arguments, one is required: 105 106 file = <file object or path; required> 107 format = <'PDB'|'CIF'; defaults to 'PDB'> 108 structure = <mmLib.Structure object to build on; defaults to creating new> 109 sequence_from_structure = [True|False] <infer sequence from structure file, default False> 110 library_bonds = [True|False] <build bonds from monomer library, default False> 111 distance_bonds = [True|False] <build bonds from covalent distance calculations, default False> 112 """ 113 fil = get_file_arg(args) 114 115 if not args.has_key("format"): 116 args["format"] = get_file_extension(fil) 117 else: 118 args["format"] = args["format"].upper() 119 120 args["fil"] = open_fileobj(fil, "r") 121 122 if args["format"] == "PDB": 123 return PDBStructureBuilder(**args).struct 124 elif args["format"] == "CIF": 125 from mmCIF import mmCIFSyntaxError 126 try: 127 return mmCIFStructureBuilder(**args).struct 128 except mmCIFSyntaxError: 129 args["fil"].seek(0) 130 return CIFStructureBuilder(**args).struct 131 132 raise FileIOUnsupportedFormat("Unsupported file format %s" % (str(fil)))
133 134
135 -def SaveStructure(**args):
136 """Saves a Structure object into a supported file type. 137 file = <file object or path; required> 138 structure = <mmLib.Structure object to save; required> 139 format = <'PDB' or 'CIF'; defaults to 'PDB'> 140 """ 141 fil = get_file_arg(args) 142 143 if not args.has_key("format"): 144 args["format"] = get_file_extension(fil) 145 else: 146 args["format"] = args["format"].upper() 147 148 fileobj = open_fileobj(fil, "w") 149 150 try: 151 struct = args["struct"] 152 except KeyError: 153 try: 154 struct = args["structure"] 155 except KeyError: 156 raise TypeError,"LoadStructure(structure=) argument required" 157 158 if args["format"] == "PDB": 159 pdb_file = PDBFile() 160 PDBFileBuilder(struct, pdb_file) 161 pdb_file.save_file(fileobj) 162 return 163 164 elif args["format"] == "CIF": 165 cif_file = mmCIFFile() 166 mmCIFFileBuilder(struct, cif_file) 167 cif_file.save_file(fileobj) 168 return 169 170 raise FileIOUnsupportedFormat("Unsupported file format %s" % (str(fil)))
171 172 173 ### <TESTING>
174 -def test_module():
175 import sys 176 struct = LoadStructure(fil = sys.argv[1]) 177 SaveStructure(fil=sys.stdout, struct=struct)
178 179 if __name__ == "__main__": 180 test_module() 181 ### </TESTING> 182