remove some useless debugging print statements
[htsworkflow.git] / htsworkflow / pipelines / bustard.py
1 """
2 Extract configuration from Illumina Bustard Directory.
3
4 This includes the version number, run date, bustard executable parameters, and 
5 phasing estimates. 
6 """
7 from copy import copy
8 from datetime import date
9 from glob import glob
10 import logging
11 import os
12 import re
13 import sys
14 import time
15
16 from htsworkflow.pipelines.runfolder import \
17    ElementTree, \
18    VERSION_RE, \
19    EUROPEAN_STRPTIME
20
21 # make epydoc happy
22 __docformat__ = "restructuredtext en"
23
24 LANE_LIST = range(1,9)
25
26 class Phasing(object):
27     PHASING = 'Phasing'
28     PREPHASING = 'Prephasing'
29
30     def __init__(self, fromfile=None, xml=None):
31         self.lane = None
32         self.phasing = None
33         self.prephasing = None
34
35         if fromfile is not None:
36             self._initialize_from_file(fromfile)
37         elif xml is not None:
38             self.set_elements(xml)
39
40     def _initialize_from_file(self, pathname):
41         path, name = os.path.split(pathname)
42         basename, ext = os.path.splitext(name)
43         # the last character of the param base filename should be the
44         # lane number
45         tree = ElementTree.parse(pathname).getroot()
46         self.set_elements(tree)
47         self.lane = int(basename[-1])
48
49     def get_elements(self):
50         root = ElementTree.Element(Phasing.PHASING, {'lane': str(self.lane)})
51         root.tail = os.linesep
52         phasing = ElementTree.SubElement(root, Phasing.PHASING)
53         phasing.text = str(self.phasing)
54         phasing.tail = os.linesep
55         prephasing = ElementTree.SubElement(root, Phasing.PREPHASING)
56         prephasing.text = str(self.prephasing)
57         prephasing.tail = os.linesep
58         return root
59
60     def set_elements(self, tree):
61         if tree.tag not in ('Phasing', 'Parameters'):
62             raise ValueError('exptected Phasing or Parameters')
63         lane = tree.attrib.get('lane', None)
64         if lane is not None:
65             self.lane = int(lane)
66         for element in list(tree):
67             if element.tag == Phasing.PHASING:
68                 self.phasing = float(element.text)
69             elif element.tag == Phasing.PREPHASING:
70                 self.prephasing = float(element.text)
71
72 class CrosstalkMatrix(object):
73     CROSSTALK = "MatrixElements"
74     BASE = 'Base'
75     ELEMENT = 'Element'
76
77     def __init__(self, fromfile=None, xml=None):
78         self.base = {}
79
80         if fromfile is not None:
81             self._initialize_from_file(fromfile)
82         elif xml is not None:
83             self.set_elements(xml)
84
85     def _initialize_from_file(self, pathname):
86         data = open(pathname).readlines()
87         auto_header = '# Auto-generated frequency response matrix'
88         if data[0].strip() != auto_header or len(data) != 9:
89             raise RuntimeError("matrix file %s is unusual" % (pathname,))
90         # skip over lines 1,2,3,4 which contain the 4 bases
91         self.base['A'] = [ float(v) for v in data[5].split() ]
92         self.base['C'] = [ float(v) for v in data[6].split() ]
93         self.base['G'] = [ float(v) for v in data[7].split() ]
94         self.base['T'] = [ float(v) for v in data[8].split() ]
95
96     def get_elements(self):
97         root = ElementTree.Element(CrosstalkMatrix.CROSSTALK)
98         root.tail = os.linesep
99         base_order = ['A','C','G','T']
100         for b in base_order:
101             base_element = ElementTree.SubElement(root, CrosstalkMatrix.BASE)
102             base_element.text = b
103             base_element.tail = os.linesep
104         for b in base_order:
105             for value in self.base[b]:
106                 crosstalk_value = ElementTree.SubElement(root, CrosstalkMatrix.ELEMENT)
107                 crosstalk_value.text = unicode(value)
108                 crosstalk_value.tail = os.linesep
109
110         return root
111
112     def set_elements(self, tree):
113         if tree.tag != CrosstalkMatrix.CROSSTALK:
114             raise ValueError('Invalid run-xml exptected '+CrosstalkMatrix.CROSSTALK)
115         base_order = []
116         current_base = None
117         current_index = 0
118         for element in tree.getchildren():
119             # read in the order of the bases
120             if element.tag == 'Base':
121                 base_order.append(element.text)
122             elif element.tag == 'Element':
123                 # we're done reading bases, now its just the 4x4 matrix
124                 # written out as a list of elements
125                 # if this is the first element, make a copy of the list
126                 # to play with and initialize an empty list for the current base
127                 if current_base is None:
128                     current_base = copy(base_order)
129                     self.base[current_base[0]] = []
130                 # we found (probably) 4 bases go to the next base
131                 if current_index == len(base_order):
132                     current_base.pop(0)
133                     current_index = 0
134                     self.base[current_base[0]] = []
135                 value = float(element.text)
136                 self.base[current_base[0]].append(value)
137
138                 current_index += 1
139             else:
140                 raise RuntimeError("Unrecognized tag in run xml: %s" %(element.tag,))
141
142 def crosstalk_matrix_from_bustard_config(bustard_path, bustard_config_tree):
143     """
144     Analyze the bustard config file and try to find the crosstalk matrix.
145     """
146     bustard_run = bustard_config_tree[0]
147     if bustard_run.tag != 'Run':
148         raise RuntimeError('Expected Run tag, got %s' % (bustard_run.tag,))
149
150     call_parameters = bustard_run.find('BaseCallParameters')
151     if call_parameters is None:
152         raise RuntimeError('Missing BaseCallParameters section')
153
154     matrix = call_parameters.find('Matrix')
155     if matrix is None:
156         raise RuntimeError('Expected to find Matrix in Bustard BaseCallParameters')
157
158     matrix_auto_flag = int(matrix.find('AutoFlag').text)
159     matrix_auto_lane = int(matrix.find('AutoLane').text)
160
161     if matrix_auto_flag:
162         # we estimated the matrix from something in this run.
163         # though we don't really care which lane it was
164         matrix_path = os.path.join(bustard_path, 'Matrix', 's_02_matrix.txt')
165         matrix = CrosstalkMatrix(matrix_path)
166     else:
167         # the matrix was provided
168         matrix_elements = call_parameters.find('MatrixElements')
169         if matrix_elements is None:
170             raise RuntimeError('Expected to find MatrixElements in Bustard BaseCallParameters')
171         matrix = CrosstalkMatrix(xml=matrix_elements)
172
173     return matrix
174
175 class Bustard(object):
176     XML_VERSION = 2
177
178     # Xml Tags
179     BUSTARD = 'Bustard'
180     SOFTWARE_VERSION = 'version'
181     DATE = 'run_time'
182     USER = 'user'
183     PARAMETERS = 'Parameters'
184     BUSTARD_CONFIG = 'BaseCallAnalysis'
185
186     def __init__(self, xml=None):
187         self.version = None
188         self.date = date.today()
189         self.user = None
190         self.phasing = {}
191         self.crosstalk = None
192         self.pathname = None
193         self.bustard_config = None
194
195         if xml is not None:
196             self.set_elements(xml)
197
198     def _get_time(self):
199         return time.mktime(self.date.timetuple())
200     time = property(_get_time, doc='return run time as seconds since epoch')
201
202     def dump(self):
203         #print ElementTree.tostring(self.get_elements())
204         ElementTree.dump(self.get_elements())
205
206     def get_elements(self):
207         root = ElementTree.Element('Bustard', 
208                                    {'version': str(Bustard.XML_VERSION)})
209         version = ElementTree.SubElement(root, Bustard.SOFTWARE_VERSION)
210         version.text = self.version
211         run_date = ElementTree.SubElement(root, Bustard.DATE)
212         run_date.text = str(self.time)
213         user = ElementTree.SubElement(root, Bustard.USER)
214         user.text = self.user
215         params = ElementTree.SubElement(root, Bustard.PARAMETERS)
216
217         # add phasing parameters
218         for lane in LANE_LIST:
219             params.append(self.phasing[lane].get_elements())
220
221         # add crosstalk matrix if it exists
222         if self.crosstalk is not None:
223             root.append(self.crosstalk.get_elements())
224        
225         # add bustard config if it exists
226         if self.bustard_config is not None:
227             root.append(self.bustard_config)
228         return root
229
230     def set_elements(self, tree):
231         if tree.tag != Bustard.BUSTARD:
232             raise ValueError('Expected "Bustard" SubElements')
233         xml_version = int(tree.attrib.get('version', 0))
234         if xml_version > Bustard.XML_VERSION:
235             logging.warn('Bustard XML tree is a higher version than this class')
236         for element in list(tree):
237             if element.tag == Bustard.SOFTWARE_VERSION:
238                 self.version = element.text
239             elif element.tag == Bustard.DATE:
240                 self.date = date.fromtimestamp(float(element.text))
241             elif element.tag == Bustard.USER:
242                 self.user = element.text
243             elif element.tag == Bustard.PARAMETERS:
244                 for param in element:
245                     p = Phasing(xml=param)
246                     self.phasing[p.lane] = p
247             elif element.tag == CrosstalkMatrix.CROSSTALK:
248                 self.crosstalk = CrosstalkMatrix(xml=element)
249             elif element.tag == Bustard.BUSTARD_CONFIG:
250                 self.bustard_config = element
251             else:
252                 raise ValueError("Unrecognized tag: %s" % (element.tag,))
253         
254 def bustard(pathname):
255     """
256     Construct a Bustard object by analyzing an Illumina Bustard directory.
257
258     :Parameters:
259       - `pathname`: A bustard directory
260
261     :Return:
262       Fully initialized Bustard object.
263     """
264     b = Bustard()
265     pathname = os.path.abspath(pathname)
266     path, name = os.path.split(pathname)
267     groups = name.split("_")
268     version = re.search(VERSION_RE, groups[0])
269     b.version = version.group(1)
270     t = time.strptime(groups[1], EUROPEAN_STRPTIME)
271     b.date = date(*t[0:3])
272     b.user = groups[2]
273     b.pathname = pathname
274     bustard_config_filename = os.path.join(pathname, 'config.xml')
275     paramfiles = glob(os.path.join(pathname, "params?.xml"))
276     for paramfile in paramfiles:
277         phasing = Phasing(paramfile)
278         assert (phasing.lane >= 1 and phasing.lane <= 8)
279         b.phasing[phasing.lane] = phasing
280     # I only found these in Bustard1.9.5/1.9.6 directories
281     if b.version in ('1.9.5', '1.9.6'):
282         # at least for our runfolders for 1.9.5 and 1.9.6 matrix[1-8].txt are always the same
283         crosstalk_file = os.path.join(pathname, "matrix1.txt")
284         b.crosstalk = CrosstalkMatrix(crosstalk_file)
285     # for version 1.3.2 of the pipeline the bustard version number went down
286     # to match the rest of the pipeline. However there's now a nifty
287     # new (useful) bustard config file.
288     elif os.path.exists(bustard_config_filename):
289         bustard_config_root = ElementTree.parse(bustard_config_filename)
290         b.bustard_config = bustard_config_root.getroot()
291         b.crosstalk = crosstalk_matrix_from_bustard_config(b.pathname, b.bustard_config)
292
293     return b
294
295 def fromxml(tree):
296     """
297     Reconstruct a htsworkflow.pipelines.Bustard object from an xml block
298     """
299     b = Bustard()
300     b.set_elements(tree)
301     return b
302
303 def make_cmdline_parser():
304     from optparse import OptionParser
305     parser = OptionParser('%prog: bustard_directory')
306     return parser
307
308 def main(cmdline):
309     parser = make_cmdline_parser()
310     opts, args = parser.parse_args(cmdline)
311
312     for bustard_dir in args:
313         print u'analyzing bustard directory: ' + unicode(bustard_dir)
314         bustard_object = bustard(bustard_dir)
315         bustard_object.dump() 
316
317         bustard_object2 = Bustard(xml=bustard_object.get_elements())
318         print ('-------------------------------------')
319         bustard_object2.dump()
320         print ('=====================================')
321         b1_tree = bustard_object.get_elements()
322         b1 = ElementTree.tostring(b1_tree).split(os.linesep)
323         b2_tree = bustard_object2.get_elements()
324         b2 = ElementTree.tostring(b2_tree).split(os.linesep)
325         for line1, line2 in zip(b1, b2):
326             if b1 != b2:
327                 print "b1: ", b1
328                 print "b2: ", b2
329
330 if __name__ == "__main__":
331     main(sys.argv[1:])