Package Bio :: Package Phylo :: Package PAML :: Module _paml
[hide private]
[frames] | no frames]

Source Code for Module Bio.Phylo.PAML._paml

  1  # Copyright (C) 2011 by Brandon Invergo (b.invergo@gmail.com) 
  2  # This code is part of the Biopython distribution and governed by its 
  3  # license. Please see the LICENSE file that should have been included 
  4  # as part of this package. 
  5   
  6  from __future__ import print_function 
  7   
  8  import os 
  9  import subprocess 
 10   
 11  try: 
 12      from os.path import relpath as _relpath 
 13  except ImportError: 
 14      # New in Python 2.6 
15 - def _relpath(path, start=None):
16 """Return a relative version of a path. 17 18 Implementation by James Gardner in his BareNecessities 19 package, under MIT licence. 20 21 With a fix for Windows where posixpath.sep (and functions like 22 join) use the Unix slash not the Windows slash. 23 """ 24 import posixpath 25 if start is None: 26 start = posixpath.curdir 27 else: 28 start = start.replace(os.path.sep, posixpath.sep) 29 if not path: 30 raise ValueError("no path specified") 31 else: 32 path = path.replace(os.path.sep, posixpath.sep) 33 start_list = posixpath.abspath(start).split(posixpath.sep) 34 path_list = posixpath.abspath(path).split(posixpath.sep) 35 # Work out how much of the filepath is shared by start and path. 36 i = len(posixpath.commonprefix([start_list, path_list])) 37 rel_list = [posixpath.pardir] * (len(start_list) - i) + path_list[i:] 38 if not rel_list: 39 return posixpath.curdir.replace(posixpath.sep, os.path.sep) 40 return posixpath.join(*rel_list).replace(posixpath.sep, os.path.sep)
41 42
43 -class PamlError(EnvironmentError):
44 """paml has failed. Run with verbose = True to view the error 45 message"""
46 47
48 -class Paml(object):
49 """Base class for wrapping PAML commands.""" 50
51 - def __init__(self, alignment=None, working_dir=None, 52 out_file=None):
53 if working_dir is None: 54 self.working_dir = os.getcwd() 55 else: 56 self.working_dir = working_dir 57 if alignment is not None: 58 if not os.path.exists(alignment): 59 raise IOError("The specified alignment file does not exist.") 60 self.alignment = alignment 61 self.out_file = out_file 62 self._options = {} # will be set in subclasses
63
64 - def write_ctl_file(self):
65 pass
66
67 - def read_ctl_file(self):
68 pass
69
70 - def print_options(self):
71 """Print out all of the options and their current settings.""" 72 for option in self._options.items(): 73 print("%s = %s" % (option[0], option[1]))
74
75 - def set_options(self, **kwargs):
76 """Set the value of an option. 77 78 This function abstracts the options dict to prevent the user from 79 adding options that do not exist or mispelling options. 80 """ 81 for option, value in kwargs.items(): 82 if option not in self._options: 83 raise KeyError("Invalid option: " + option) 84 else: 85 self._options[option] = value
86
87 - def get_option(self, option):
88 """Return the value of an option.""" 89 if option not in self._options: 90 raise KeyError("Invalid option: " + option) 91 else: 92 return self._options.get(option)
93
94 - def get_all_options(self):
95 """Return the values of all the options.""" 96 return list(self._options.items())
97
98 - def _set_rel_paths(self):
99 """Convert all file/directory locations to paths relative to the current working directory. 100 101 paml requires that all paths specified in the control file be 102 relative to the directory from which it is called rather than 103 absolute paths. 104 """ 105 if self.working_dir is not None: 106 self._rel_working_dir = _relpath(self.working_dir) 107 if self.alignment is not None: 108 self._rel_alignment = _relpath(self.alignment, 109 self.working_dir) 110 if self.out_file is not None: 111 self._rel_out_file = _relpath(self.out_file, self.working_dir)
112
113 - def run(self, ctl_file, verbose, command):
114 """Run a paml program using the current configuration and then parse the results. 115 116 Return a process signal so the user can determine if 117 the execution was successful (return code 0 is successful, -N 118 indicates a failure). The arguments may be passed as either 119 absolute or relative paths, despite the fact that paml 120 requires relative paths. 121 """ 122 if self.alignment is None: 123 raise ValueError("Alignment file not specified.") 124 if not os.path.exists(self.alignment): 125 raise IOError("The specified alignment file does not exist.") 126 if self.out_file is None: 127 raise ValueError("Output file not specified.") 128 if self.working_dir is None: 129 raise ValueError("Working directory not specified.") 130 # Get the current working directory 131 cwd = os.getcwd() 132 # Move to the desired working directory 133 if not os.path.exists(self.working_dir): 134 os.mkdir(self.working_dir) 135 os.chdir(self.working_dir) 136 # If no external control file was specified... 137 if ctl_file is None: 138 # Dynamically build a control file 139 self.write_ctl_file() 140 if verbose: 141 result_code = subprocess.call([command, self.ctl_file]) 142 else: 143 # To suppress output, redirect it to a pipe to nowhere 144 result_code = subprocess.call([command, self.ctl_file], 145 stdout=subprocess.PIPE) 146 else: 147 if not os.path.exists(ctl_file): 148 raise IOError("The specified control file does not exist.") 149 if verbose: 150 result_code = subprocess.call([command, ctl_file]) 151 else: 152 result_code = subprocess.call([command, ctl_file], 153 stdout=subprocess.PIPE) 154 os.chdir(cwd) 155 if result_code > 0: 156 # If the program fails for any reason 157 raise PamlError( 158 "%s has failed (return code %i). Run with verbose = True to view error message" 159 % (command, result_code)) 160 if result_code < 0: 161 # If the paml process is killed by a signal somehow 162 raise EnvironmentError("The %s process was killed (return code %i)." 163 % (command, result_code))
164