Initial port to python3
[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 import \
17    ElementTree, \
18    VERSION_RE, \
19    EUROPEAN_STRPTIME
20
21 LOGGER = logging.getLogger(__name__)
22
23 # make epydoc happy
24 __docformat__ = "restructuredtext en"
25
26 LANE_LIST = list(range(1,9))
27
28 class Phasing(object):
29     PHASING = 'Phasing'
30     PREPHASING = 'Prephasing'
31
32     def __init__(self, fromfile=None, xml=None):
33         self.lane = None
34         self.phasing = None
35         self.prephasing = None
36
37         if fromfile is not None:
38             self._initialize_from_file(fromfile)
39         elif xml is not None:
40             self.set_elements(xml)
41
42     def _initialize_from_file(self, pathname):
43         path, name = os.path.split(pathname)
44         basename, ext = os.path.splitext(name)
45         # the last character of the param base filename should be the
46         # lane number
47         tree = ElementTree.parse(pathname).getroot()
48         self.set_elements(tree)
49         self.lane = int(basename[-1])
50
51     def get_elements(self):
52         root = ElementTree.Element(Phasing.PHASING, {'lane': str(self.lane)})
53         root.tail = os.linesep
54         phasing = ElementTree.SubElement(root, Phasing.PHASING)
55         phasing.text = str(self.phasing)
56         phasing.tail = os.linesep
57         prephasing = ElementTree.SubElement(root, Phasing.PREPHASING)
58         prephasing.text = str(self.prephasing)
59         prephasing.tail = os.linesep
60         return root
61
62     def set_elements(self, tree):
63         if tree.tag not in ('Phasing', 'Parameters'):
64             raise ValueError('exptected Phasing or Parameters')
65         lane = tree.attrib.get('lane', None)
66         if lane is not None:
67             self.lane = int(lane)
68         for element in list(tree):
69             if element.tag == Phasing.PHASING:
70                 self.phasing = float(element.text)
71             elif element.tag == Phasing.PREPHASING:
72                 self.prephasing = float(element.text)
73
74 class CrosstalkMatrix(object):
75     CROSSTALK = "MatrixElements"
76     BASE = 'Base'
77     ELEMENT = 'Element'
78
79     def __init__(self, fromfile=None, xml=None):
80         self.base = {}
81
82         if fromfile is not None:
83             self._initialize_from_file(fromfile)
84         elif xml is not None:
85             self.set_elements(xml)
86
87     def _initialize_from_file(self, pathname):
88         data = open(pathname).readlines()
89         auto_header = '# Auto-generated frequency response matrix'
90         if data[0].strip() == auto_header and len(data) == 9:
91             # skip over lines 1,2,3,4 which contain the 4 bases
92             self.base['A'] = [ float(v) for v in data[5].split() ]
93             self.base['C'] = [ float(v) for v in data[6].split() ]
94             self.base['G'] = [ float(v) for v in data[7].split() ]
95             self.base['T'] = [ float(v) for v in data[8].split() ]
96         elif len(data) == 16:
97             self.base['A'] = [ float(v) for v in data[:4] ]
98             self.base['C'] = [ float(v) for v in data[4:8] ]
99             self.base['G'] = [ float(v) for v in data[8:12] ]
100             self.base['T'] = [ float(v) for v in data[12:16] ]
101         else:
102             raise RuntimeError("matrix file %s is unusual" % (pathname,))
103     def get_elements(self):
104         root = ElementTree.Element(CrosstalkMatrix.CROSSTALK)
105         root.tail = os.linesep
106         base_order = ['A','C','G','T']
107         for b in base_order:
108             base_element = ElementTree.SubElement(root, CrosstalkMatrix.BASE)
109             base_element.text = b
110             base_element.tail = os.linesep
111         for b in base_order:
112             for value in self.base[b]:
113                 crosstalk_value = ElementTree.SubElement(root, CrosstalkMatrix.ELEMENT)
114                 crosstalk_value.text = str(value)
115                 crosstalk_value.tail = os.linesep
116
117         return root
118
119     def set_elements(self, tree):
120         if tree.tag != CrosstalkMatrix.CROSSTALK:
121             raise ValueError('Invalid run-xml exptected '+CrosstalkMatrix.CROSSTALK)
122         base_order = []
123         current_base = None
124         current_index = 0
125         for element in tree.getchildren():
126             # read in the order of the bases
127             if element.tag == 'Base':
128                 base_order.append(element.text)
129             elif element.tag == 'Element':
130                 # we're done reading bases, now its just the 4x4 matrix
131                 # written out as a list of elements
132                 # if this is the first element, make a copy of the list
133                 # to play with and initialize an empty list for the current base
134                 if current_base is None:
135                     current_base = copy(base_order)
136                     self.base[current_base[0]] = []
137                 # we found (probably) 4 bases go to the next base
138                 if current_index == len(base_order):
139                     current_base.pop(0)
140                     current_index = 0
141                     self.base[current_base[0]] = []
142                 value = float(element.text)
143                 self.base[current_base[0]].append(value)
144
145                 current_index += 1
146             else:
147                 raise RuntimeError("Unrecognized tag in run xml: %s" %(element.tag,))
148
149 def crosstalk_matrix_from_bustard_config(bustard_path, bustard_config_tree):
150     """
151     Analyze the bustard config file and try to find the crosstalk matrix.
152     """
153     bustard_run = bustard_config_tree[0]
154     if bustard_run.tag != 'Run':
155         raise RuntimeError('Expected Run tag, got %s' % (bustard_run.tag,))
156
157     call_parameters = bustard_run.find('BaseCallParameters')
158     if call_parameters is None:
159         raise RuntimeError('Missing BaseCallParameters section')
160
161     matrix = call_parameters.find('Matrix')
162     if matrix is None:
163         raise RuntimeError('Expected to find Matrix in Bustard BaseCallParameters')
164
165     matrix_auto_flag = int(matrix.find('AutoFlag').text)
166     matrix_auto_lane = int(matrix.find('AutoLane').text)
167
168     crosstalk = None
169     if matrix_auto_flag:
170         # we estimated the matrix from something in this run.
171         # though we don't really care which lane it was
172         if matrix_auto_lane == 0:
173             # its defaulting to all of the lanes, so just pick one
174             auto_lane_fragment = "_1"
175         else:
176             auto_lane_fragment = "_%d" % ( matrix_auto_lane,)
177
178         for matrix_name in ['s%s_02_matrix.txt' % (auto_lane_fragment,),
179                             's%s_1_matrix.txt' % (auto_lane_fragment,),
180                             ]:
181             matrix_path = os.path.join(bustard_path, 'Matrix', matrix_name)
182             if os.path.exists(matrix_path):
183                 break
184         else:
185             raise RuntimeError("Couldn't find matrix for lane %d" % \
186                                (matrix_auto_lane,))
187
188         crosstalk = CrosstalkMatrix(matrix_path)
189     else:
190         matrix_elements = call_parameters.find('MatrixElements')
191         # the matrix was provided
192         if matrix_elements is not None:
193             crosstalk = CrosstalkMatrix(xml=matrix_elements)
194         else:
195             # we have no crosstalk matrix?
196             pass
197
198     return crosstalk
199
200 class Bustard(object):
201     XML_VERSION = 2
202
203     # Xml Tags
204     BUSTARD = 'Bustard'
205     SOFTWARE_VERSION = 'version'
206     DATE = 'run_time'
207     USER = 'user'
208     PARAMETERS = 'Parameters'
209     BUSTARD_CONFIG = 'BaseCallAnalysis'
210
211     def __init__(self, xml=None):
212         self._path_version = None # version number from directory name
213         self.date = None
214         self.user = None
215         self.phasing = {}
216         self.crosstalk = None
217         self.pathname = None
218         self.bustard_config = None
219
220         if xml is not None:
221             self.set_elements(xml)
222
223     def update_attributes_from_pathname(self):
224         """Update version, date, user from bustard directory names
225         Obviously this wont work for BaseCalls or later runfolders
226         """
227         if self.pathname is None:
228             raise ValueError(
229                 "Set pathname before calling update_attributes_from_pathname")
230         path, name = os.path.split(self.pathname)
231
232         if not re.match('bustard', name, re.IGNORECASE):
233             return
234
235         groups = name.split("_")
236         version = re.search(VERSION_RE, groups[0])
237         self._path_version = version.group(1)
238         t = time.strptime(groups[1], EUROPEAN_STRPTIME)
239         self.date = date(*t[0:3])
240         self.user = groups[2]
241
242     def _get_sequence_format(self):
243         """Guess sequence format"""
244         project_glob = os.path.join(self.pathname, 'Project_*')
245         LOGGER.debug("Scanning: %s" % (project_glob,))
246         projects = glob(project_glob)
247         if len(projects) > 0:
248             # Hey we look like a demultiplexed run
249             return 'fastq'
250         seqs = glob(os.path.join(self.pathname, '*_seq.txt'))
251         if len(seqs) > 0:
252             return 'srf'
253         return 'qseq'
254     sequence_format = property(_get_sequence_format)
255
256     def _get_software_version(self):
257         """return software name, version tuple"""
258         if self.bustard_config is None:
259             if self._path_version is not None:
260                 return 'Bustard', self._path_version
261             else:
262                 return None
263         software_nodes = self.bustard_config.xpath('Run/Software')
264         if len(software_nodes) == 0:
265             return None
266         elif len(software_nodes) > 1:
267             raise RuntimeError("Too many software XML elements for bustard.py")
268         else:
269             return (software_nodes[0].attrib['Name'],
270                     software_nodes[0].attrib['Version'])
271
272     def _get_software(self):
273         """Return software name"""
274         software_version = self._get_software_version()
275         return software_version[0] if software_version is not None else None
276     software = property(_get_software)
277
278     def _get_version(self):
279         """Return software name"""
280         software_version = self._get_software_version()
281         return software_version[1] if software_version is not None else None
282     version = property(_get_version)
283
284
285     def _get_time(self):
286         if self.date is None:
287             return None
288         return time.mktime(self.date.timetuple())
289     time = property(_get_time, doc='return run time as seconds since epoch')
290
291     def dump(self):
292         #print ElementTree.tostring(self.get_elements())
293         ElementTree.dump(self.get_elements())
294
295     def get_elements(self):
296         root = ElementTree.Element('Bustard',
297                                    {'version': str(Bustard.XML_VERSION)})
298         version = ElementTree.SubElement(root, Bustard.SOFTWARE_VERSION)
299         version.text = self.version
300         if self.time is not None:
301             run_date = ElementTree.SubElement(root, Bustard.DATE)
302             run_date.text = str(self.time)
303         if self.user is not None:
304             user = ElementTree.SubElement(root, Bustard.USER)
305             user.text = self.user
306         params = ElementTree.SubElement(root, Bustard.PARAMETERS)
307
308         # add phasing parameters
309         for lane in LANE_LIST:
310             if lane in self.phasing:
311                 params.append(self.phasing[lane].get_elements())
312
313         # add crosstalk matrix if it exists
314         if self.crosstalk is not None:
315             root.append(self.crosstalk.get_elements())
316
317         # add bustard config if it exists
318         if self.bustard_config is not None:
319             root.append(self.bustard_config)
320         return root
321
322     def set_elements(self, tree):
323         if tree.tag != Bustard.BUSTARD:
324             raise ValueError('Expected "Bustard" SubElements')
325         xml_version = int(tree.attrib.get('version', 0))
326         if xml_version > Bustard.XML_VERSION:
327             LOGGER.warn('Bustard XML tree is a higher version than this class')
328         for element in list(tree):
329             if element.tag == Bustard.SOFTWARE_VERSION:
330                 self._path_version = element.text
331             elif element.tag == Bustard.DATE:
332                 self.date = date.fromtimestamp(float(element.text))
333             elif element.tag == Bustard.USER:
334                 self.user = element.text
335             elif element.tag == Bustard.PARAMETERS:
336                 for param in element:
337                     p = Phasing(xml=param)
338                     self.phasing[p.lane] = p
339             elif element.tag == CrosstalkMatrix.CROSSTALK:
340                 self.crosstalk = CrosstalkMatrix(xml=element)
341             elif element.tag == Bustard.BUSTARD_CONFIG:
342                 self.bustard_config = element
343             else:
344                 raise ValueError("Unrecognized tag: %s" % (element.tag,))
345
346 def bustard(pathname):
347     """
348     Construct a Bustard object by analyzing an Illumina Bustard directory.
349
350     :Parameters:
351       - `pathname`: A bustard directory
352
353     :Return:
354       Fully initialized Bustard object.
355     """
356     pathname = os.path.abspath(pathname)
357     bustard_filename = os.path.join(pathname, 'config.xml')
358     demultiplexed_filename = os.path.join(pathname,
359                                           'DemultiplexedBustardConfig.xml')
360
361     if os.path.exists(demultiplexed_filename):
362         b = bustard_from_hiseq(pathname, demultiplexed_filename)
363     elif os.path.exists(bustard_filename):
364         b = bustard_from_ga2(pathname, bustard_filename)
365     else:
366         b = bustard_from_ga1(pathname)
367
368     if not b:
369         raise RuntimeError("Unable to parse base-call directory at %s" % (pathname,))
370
371     return b
372
373 def bustard_from_ga1(pathname):
374     """Initialize bustard class from ga1 era runfolders.
375     """
376     path, name = os.path.split(pathname)
377
378     groups = name.split("_")
379     if len(groups) < 3:
380         msg = "Not enough information to create attributes"\
381               " from directory name: %s"
382         LOGGER.error(msg % (pathname,))
383         return None
384
385     b = Bustard()
386     b.pathname = pathname
387     b.update_attributes_from_pathname()
388     version = re.search(VERSION_RE, groups[0])
389     b._path_version = version.group(1)
390     t = time.strptime(groups[1], EUROPEAN_STRPTIME)
391     b.date = date(*t[0:3])
392     b.user = groups[2]
393
394     # I only found these in Bustard1.9.5/1.9.6 directories
395     if b.version in ('1.9.5', '1.9.6'):
396         # at least for our runfolders for 1.9.5 and 1.9.6 matrix[1-8].txt are always the same
397         crosstalk_file = os.path.join(pathname, "matrix1.txt")
398         b.crosstalk = CrosstalkMatrix(crosstalk_file)
399
400     add_phasing(b)
401     return b
402
403
404 def bustard_from_ga2(pathname, config_filename):
405     """Initialize bustard class from ga2-era runfolder
406     Actually I don't quite remember if it is exactly the GA2s, but
407     its after the original runfolder style and before the HiSeq.
408     """
409     # for version 1.3.2 of the pipeline the bustard version number went down
410     # to match the rest of the pipeline. However there's now a nifty
411     # new (useful) bustard config file.
412
413     # stub values
414     b = Bustard()
415     b.pathname = pathname
416     b.update_attributes_from_pathname()
417     bustard_config_root = ElementTree.parse(config_filename)
418     b.bustard_config = bustard_config_root.getroot()
419     b.crosstalk = crosstalk_matrix_from_bustard_config(b.pathname,
420                                                        b.bustard_config)
421     add_phasing(b)
422
423     return b
424
425 def bustard_from_hiseq(pathname, config_filename):
426     b = Bustard()
427     b.pathname = pathname
428     bustard_config_root = ElementTree.parse(config_filename)
429     b.bustard_config = bustard_config_root.getroot()
430     add_phasing(b)
431     return b
432
433 def add_phasing(bustard_obj):
434     paramfiles = glob(os.path.join(bustard_obj.pathname,
435                                    "params?.xml"))
436     for paramfile in paramfiles:
437         phasing = Phasing(paramfile)
438         assert (phasing.lane >= 1 and phasing.lane <= 8)
439         bustard_obj.phasing[phasing.lane] = phasing
440
441 def fromxml(tree):
442     """
443     Reconstruct a htsworkflow.pipelines.Bustard object from an xml block
444     """
445     b = Bustard()
446     b.set_elements(tree)
447     return b
448
449 def make_cmdline_parser():
450     from optparse import OptionParser
451     parser = OptionParser('%prog: bustard_directory')
452     return parser
453
454 def main(cmdline):
455     parser = make_cmdline_parser()
456     opts, args = parser.parse_args(cmdline)
457
458     for bustard_dir in args:
459         print('analyzing bustard directory: ' + str(bustard_dir))
460         bustard_object = bustard(bustard_dir)
461         bustard_object.dump()
462
463         bustard_object2 = Bustard(xml=bustard_object.get_elements())
464         print ('-------------------------------------')
465         bustard_object2.dump()
466         print ('=====================================')
467         b1_tree = bustard_object.get_elements()
468         b1 = ElementTree.tostring(b1_tree).split(os.linesep)
469         b2_tree = bustard_object2.get_elements()
470         b2 = ElementTree.tostring(b2_tree).split(os.linesep)
471         for line1, line2 in zip(b1, b2):
472             if b1 != b2:
473                 print("b1: ", b1)
474                 print("b2: ", b2)
475
476 if __name__ == "__main__":
477     main(sys.argv[1:])