Package Bio :: Package SearchIO :: Package BlastIO :: Module blast_xml
[hide private]
[frames] | no frames]

Source Code for Module Bio.SearchIO.BlastIO.blast_xml

  1  # Copyright 2012 by Wibowo Arindrarto.  All rights reserved. 
  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  """Bio.SearchIO parser for BLAST+ XML output formats.""" 
  7  # for more info: http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.mod.dtd 
  8   
  9  import sys 
 10  import re 
 11  import warnings 
 12  from itertools import chain 
 13  from xml.sax.saxutils import XMLGenerator, escape 
 14   
 15  from Bio import BiopythonParserWarning 
 16   
 17   
 18  # For speed try to use cElementTree rather than ElementTree 
 19  try: 
 20      if (3, 0) <= sys.version_info[:2] <= (3, 1): 
 21          # Workaround for bug in python 3.0 and 3.1, 
 22          # see http://bugs.python.org/issue9257 
 23          from xml.etree import ElementTree as ElementTree 
 24      else: 
 25          from xml.etree import cElementTree as ElementTree 
 26  except ImportError: 
 27      from xml.etree import ElementTree as ElementTree 
 28   
 29   
 30  from Bio._py3k import _as_bytes, _bytes_to_string, unicode 
 31  _empty_bytes_string = _as_bytes("") 
 32   
 33  from Bio.Alphabet import generic_dna, generic_protein 
 34  from Bio.SearchIO._index import SearchIndexer 
 35  from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment 
 36   
 37   
 38  __all__ = ['BlastXmlParser', 'BlastXmlIndexer', 'BlastXmlWriter'] 
 39   
 40  __docformat__ = "restructuredtext en" 
 41   
 42   
 43  # element - optional qresult attribute name mapping 
 44  _ELEM_QRESULT_OPT = { 
 45      'Statistics_db-num': ('stat_db_num', int), 
 46      'Statistics_db-len': ('stat_db_len', int), 
 47      'Statistics_eff-space': ('stat_eff_space', float), 
 48      'Statistics_hsp-len': ('stat_hsp_len', int), 
 49      'Statistics_kappa': ('stat_kappa', float), 
 50      'Statistics_lambda': ('stat_lambda', float), 
 51      'Statistics_entropy': ('stat_entropy', float), 
 52  } 
 53  # element - hit attribute name mapping 
 54  _ELEM_HIT = { 
 55      # 'Hit_def': ('description', str),   # not set by this dict 
 56      'Hit_accession': ('accession', str), 
 57      'Hit_len': ('seq_len', int), 
 58  } 
 59  # element - hsp attribute name mapping 
 60  _ELEM_HSP = { 
 61      'Hsp_bit-score': ('bitscore', float), 
 62      'Hsp_score': ('bitscore_raw', int), 
 63      'Hsp_evalue': ('evalue', float), 
 64      'Hsp_identity': ('ident_num', int), 
 65      'Hsp_positive': ('pos_num', int), 
 66      'Hsp_gaps': ('gap_num', int), 
 67      'Hsp_density': ('density', float), 
 68  } 
 69  # element - fragment attribute name mapping 
 70  _ELEM_FRAG = { 
 71      'Hsp_query-from': ('query_start', int), 
 72      'Hsp_query-to': ('query_end', int), 
 73      'Hsp_hit-from': ('hit_start', int), 
 74      'Hsp_hit-to': ('hit_end', int), 
 75      'Hsp_query-frame': ('query_frame', int), 
 76      'Hsp_hit-frame': ('hit_frame', int), 
 77      'Hsp_align-len': ('aln_span', int), 
 78      'Hsp_pattern-from': ('pattern_start', int), 
 79      'Hsp_pattern-to': ('pattern_end', int), 
 80      'Hsp_hseq': ('hit', str), 
 81      'Hsp_qseq': ('query', str), 
 82  } 
 83  # dictionary for mapping tag name and meta key name 
 84  _ELEM_META = { 
 85      'BlastOutput_db': ('target', str), 
 86      'BlastOutput_program': ('program', str), 
 87      'BlastOutput_version': ('version', str), 
 88      'BlastOutput_reference': ('reference', str), 
 89      'Parameters_expect': ('param_evalue_threshold', float), 
 90      'Parameters_entrez-query': ('param_entrez_query', str), 
 91      'Parameters_filter': ('param_filter', str), 
 92      'Parameters_gap-extend': ('param_gap_extend', int), 
 93      'Parameters_gap-open': ('param_gap_open', int), 
 94      'Parameters_include': ('param_include', str), 
 95      'Parameters_matrix': ('param_matrix', str), 
 96      'Parameters_pattern': ('param_pattern', str), 
 97      'Parameters_sc-match': ('param_score_match', int), 
 98      'Parameters_sc-mismatch': ('param_score_mismatch', int), 
 99  } 
100  # these are fallback tags that store information on the first query 
101  # outside the <Iteration> tag 
102  # only used if query_{ID,def,len} is not found in <Iteration> 
103  # (seen in legacy Blast <2.2.14) 
104  _ELEM_QRESULT_FALLBACK = { 
105      'BlastOutput_query-ID': ('id', str), 
106      'BlastOutput_query-def': ('description', str), 
107      'BlastOutput_query-len': ('len', str), 
108  } 
109  # element-attribute maps, for writing 
110  _WRITE_MAPS = { 
111      'preamble': ( 
112          ('program', 'program'), 
113          ('version', 'version'), 
114          ('reference', 'reference'), 
115          ('db', 'target'), 
116          ('query-ID', 'id'), 
117          ('query-def', 'description'), 
118          ('query-len', 'seq_len'), 
119          ('param', None), 
120      ), 
121      'param': ( 
122          ('matrix', 'param_matrix'), 
123          ('expect', 'param_evalue_threshold'), 
124          ('sc-match', 'param_score_match'), 
125          ('sc-mismatch', 'param_score_mismatch'), 
126          ('gap-open', 'param_gap_open'), 
127          ('gap-extend', 'param_gap_extend'), 
128          ('filter', 'param_filter'), 
129          ('pattern', 'param_pattern'), 
130          ('entrez-query', 'param_entrez_query'), 
131      ), 
132      'qresult': ( 
133          ('query-ID', 'id'), 
134          ('query-def', 'description'), 
135          ('query-len', 'seq_len'), 
136      ), 
137      'stat': ( 
138          ('db-num', 'stat_db_num'), 
139          ('db-len', 'stat_db_len'), 
140          ('hsp-len', 'stat_hsp_len'), 
141          ('eff-space', 'stat_eff_space'), 
142          ('kappa', 'stat_kappa'), 
143          ('lambda', 'stat_lambda'), 
144          ('entropy', 'stat_entropy'), 
145      ), 
146      'hit': ( 
147          ('id', 'id'), 
148          ('def', 'description'), 
149          ('accession', 'accession'), 
150          ('len', 'seq_len'), 
151      ), 
152      'hsp': ( 
153          ('bit-score', 'bitscore'), 
154          ('score', 'bitscore_raw'), 
155          ('evalue', 'evalue'), 
156          ('query-from', 'query_start'), 
157          ('query-to', 'query_end'), 
158          ('hit-from', 'hit_start'), 
159          ('hit-to', 'hit_end'), 
160          ('pattern-from', 'pattern_start'), 
161          ('pattern-to', 'pattern_end'), 
162          ('query-frame', 'query_frame'), 
163          ('hit-frame', 'hit_frame'), 
164          ('identity', 'ident_num'), 
165          ('positive', 'pos_num'), 
166          ('gaps', 'gap_num'), 
167          ('align-len', 'aln_span'), 
168          ('density', 'density'), 
169          ('qseq', 'query'), 
170          ('hseq', 'hit'), 
171          ('midline', None), 
172      ), 
173  } 
174  # optional elements, based on the DTD 
175  _DTD_OPT = ( 
176      'BlastOutput_query-seq', 'BlastOutput_mbstat', 'Iteration_query-def', 
177      'Iteration_query-len', 'Iteration-hits', 'Iteration_stat', 
178      'Iteration_message', 'Parameters_matrix', 'Parameters_include', 
179      'Parameters_sc-match', 'Parameters_sc-mismatch', 'Parameters_filter', 
180      'Parameters_pattern', 'Parameters_entrez-query', 'Hit_hsps', 
181      'Hsp_pattern-from', 'Hsp_pattern-to', 'Hsp_query-frame', 'Hsp_hit-frame', 
182      'Hsp_identity', 'Hsp_positive', 'Hsp_gaps', 'Hsp_align-len', 'Hsp_density', 
183      'Hsp_midline', 
184  ) 
185   
186  # compile RE patterns 
187  _RE_VERSION = re.compile(r'\d+\.\d+\.\d+\+?') 
188   
189   
190 -class BlastXmlParser(object):
191 """Parser for the BLAST XML format""" 192
193 - def __init__(self, handle):
194 self.xml_iter = iter(ElementTree.iterparse(handle, events=('start', 'end'))) 195 self._meta, self._fallback = self._parse_preamble()
196
197 - def __iter__(self):
198 for qresult in self._parse_qresult(): 199 yield qresult
200
201 - def _parse_preamble(self):
202 """Parses all tag data prior to the first query result.""" 203 # dictionary for containing all information prior to the first query 204 meta = {} 205 # dictionary for fallback information 206 fallback = {} 207 208 # parse the preamble part (anything prior to the first result) 209 for event, elem in self.xml_iter: 210 # get the tag values, cast appropriately, store into meta 211 if event == 'end' and elem.tag in _ELEM_META: 212 attr_name, caster = _ELEM_META[elem.tag] 213 214 if caster is not str: 215 meta[attr_name] = caster(elem.text) 216 else: 217 meta[attr_name] = elem.text 218 219 # delete element after we finish parsing it 220 elem.clear() 221 continue 222 # capture fallback values 223 # these are used only if the first <Iteration> does not have any 224 # ID, ref, or len. 225 elif event == 'end' and elem.tag in _ELEM_QRESULT_FALLBACK: 226 attr_name, caster = _ELEM_QRESULT_FALLBACK[elem.tag] 227 228 if caster is not str: 229 fallback[attr_name] = caster(elem.text) 230 else: 231 fallback[attr_name] = elem.text 232 233 elem.clear() 234 continue 235 236 if event == 'start' and elem.tag == 'Iteration': 237 break 238 239 # we only want the version number, sans the program name or date 240 if meta.get('version') is not None: 241 meta['version'] = re.search(_RE_VERSION, 242 meta['version']).group(0) 243 244 return meta, fallback
245
246 - def _parse_qresult(self):
247 """Parses query results.""" 248 # parse the queries 249 for event, qresult_elem in self.xml_iter: 250 # </Iteration> marks the end of a single query 251 # which means we can process it 252 if event == 'end' and qresult_elem.tag == 'Iteration': 253 254 # we'll use the following schema 255 # <!ELEMENT Iteration ( 256 # Iteration_iter-num, 257 # Iteration_query-ID?, 258 # Iteration_query-def?, 259 # Iteration_query-len?, 260 # Iteration_hits?, 261 # Iteration_stat?, 262 # Iteration_message?)> 263 264 # assign query attributes with fallbacks 265 query_id = qresult_elem.findtext('Iteration_query-ID') 266 if query_id is None: 267 query_id = self._fallback['id'] 268 269 query_desc = qresult_elem.findtext('Iteration_query-def') 270 if query_desc is None: 271 query_desc = self._fallback['description'] 272 273 query_len = qresult_elem.findtext('Iteration_query-len') 274 if query_len is None: 275 query_len = self._fallback['len'] 276 277 # handle blast searches against databases with Blast's IDs 278 # 'Query_' marks the beginning of a BLAST+-generated ID, 279 # 'lcl|' marks the beginning of a BLAST legacy-generated ID 280 if query_id.startswith('Query_') or query_id.startswith('lcl|'): 281 # store the Blast-generated query ID 282 blast_query_id = query_id 283 id_desc = query_desc.split(' ', 1) 284 query_id = id_desc[0] 285 try: 286 query_desc = id_desc[1] 287 except IndexError: 288 query_desc = '' 289 else: 290 blast_query_id = '' 291 292 hit_list, key_list = [], [] 293 for hit in self._parse_hit(qresult_elem.find('Iteration_hits'), 294 query_id): 295 if hit: 296 # need to keep track of hit IDs, since there could be duplicates, 297 if hit.id in key_list: 298 warnings.warn("Adding hit with BLAST-generated ID " 299 "%r since hit ID %r is already present " 300 "in query %r. Your BLAST database may contain " 301 "duplicate entries." % 302 (hit._blast_id, hit.id, query_id), BiopythonParserWarning) 303 # fallback to Blast-generated IDs, if the ID is already present 304 # and restore the desc, too 305 hit.description = '%s %s' % (hit.id, hit.description) 306 hit.id = hit._blast_id 307 # and change the hit_id of the HSPs contained 308 for hsp in hit: 309 hsp.hit_id = hit._blast_id 310 else: 311 key_list.append(hit.id) 312 313 hit_list.append(hit) 314 315 # create qresult and assign its attributes 316 qresult = QueryResult(hit_list, query_id) 317 qresult.description = query_desc 318 qresult.seq_len = int(query_len) 319 qresult._blast_id = blast_query_id 320 for key, value in self._meta.items(): 321 setattr(qresult, key, value) 322 323 # statistics are stored in Iteration_stat's 'grandchildren' with the 324 # following DTD 325 # <!ELEMENT Statistics ( 326 # Statistics_db-num, 327 # Statistics_db-len, 328 # Statistics_hsp-len, 329 # Statistics_eff-space, 330 # Statistics_kappa, 331 # Statistics_lambda, 332 # Statistics_entropy)> 333 334 stat_iter_elem = qresult_elem.find('Iteration_stat') 335 if stat_iter_elem is not None: 336 stat_elem = stat_iter_elem.find('Statistics') 337 338 for key, val_info in _ELEM_QRESULT_OPT.items(): 339 value = stat_elem.findtext(key) 340 if value is not None: 341 caster = val_info[1] 342 # recast only if value is not intended to be str 343 if value is not None and caster is not str: 344 value = caster(value) 345 setattr(qresult, val_info[0], value) 346 347 # delete element after we finish parsing it 348 qresult_elem.clear() 349 yield qresult
350
351 - def _parse_hit(self, root_hit_elem, query_id):
352 """Generator that transforms Iteration_hits XML elements into Hit objects. 353 354 :param root_hit_elem: root element of the Iteration_hits tag. 355 :type root_hit_elem: XML element tag 356 :param query_id: QueryResult ID of this Hit 357 :type query_id: string 358 359 """ 360 # Hit level processing 361 # Hits are stored in the Iteration_hits tag, with the following 362 # DTD 363 # <!ELEMENT Hit ( 364 # Hit_num, 365 # Hit_id, 366 # Hit_def, 367 # Hit_accession, 368 # Hit_len, 369 # Hit_hsps?)> 370 371 # feed the loop below an empty list so iteration still works 372 if root_hit_elem is None: 373 root_hit_elem = [] 374 375 for hit_elem in root_hit_elem: 376 377 # create empty hit object 378 hit_id = hit_elem.findtext('Hit_id') 379 hit_desc = hit_elem.findtext('Hit_def') 380 # handle blast searches against databases with Blast's IDs 381 if hit_id.startswith('gnl|BL_ORD_ID|'): 382 blast_hit_id = hit_id 383 id_desc = hit_desc.split(' ', 1) 384 hit_id = id_desc[0] 385 try: 386 hit_desc = id_desc[1] 387 except IndexError: 388 hit_desc = '' 389 else: 390 blast_hit_id = '' 391 392 # combine primary ID and defline first before splitting 393 full_id_desc = hit_id + ' ' + hit_desc 394 id_descs = [(x.strip(), y.strip()) for x, y in 395 [a.split(' ', 1) for a in full_id_desc.split(' >')]] 396 hit_id, hit_desc = id_descs[0] 397 398 hsps = [hsp for hsp in 399 self._parse_hsp(hit_elem.find('Hit_hsps'), 400 query_id, hit_id)] 401 402 hit = Hit(hsps) 403 hit.description = hit_desc 404 hit._id_alt = [x[0] for x in id_descs[1:]] 405 hit._description_alt = [x[1] for x in id_descs[1:]] 406 # blast_hit_id is only set if the hit ID is Blast-generated 407 hit._blast_id = blast_hit_id 408 409 for key, val_info in _ELEM_HIT.items(): 410 value = hit_elem.findtext(key) 411 if value is not None: 412 caster = val_info[1] 413 # recast only if value is not intended to be str 414 if value is not None and caster is not str: 415 value = caster(value) 416 setattr(hit, val_info[0], value) 417 418 # delete element after we finish parsing it 419 hit_elem.clear() 420 yield hit
421
422 - def _parse_hsp(self, root_hsp_frag_elem, query_id, hit_id):
423 """Iterator that transforms Hit_hsps XML elements into HSP objects. 424 425 :param root_hsp_frag_elem: the ``Hit_hsps`` tag 426 :type root_hsp_frag_elem: XML element tag 427 :param query_id: query ID 428 :type query_id: string 429 :param hit_id: hit ID 430 :type hit_id: string 431 432 """ 433 # Hit_hsps DTD: 434 # <!ELEMENT Hsp ( 435 # Hsp_num, 436 # Hsp_bit-score, 437 # Hsp_score, 438 # Hsp_evalue, 439 # Hsp_query-from, 440 # Hsp_query-to, 441 # Hsp_hit-from, 442 # Hsp_hit-to, 443 # Hsp_pattern-from?, 444 # Hsp_pattern-to?, 445 # Hsp_query-frame?, 446 # Hsp_hit-frame?, 447 # Hsp_identity?, 448 # Hsp_positive?, 449 # Hsp_gaps?, 450 # Hsp_align-len?, 451 # Hsp_density?, 452 # Hsp_qseq, 453 # Hsp_hseq, 454 # Hsp_midline?)> 455 456 # if value is None, feed the loop below an empty list 457 if root_hsp_frag_elem is None: 458 root_hsp_frag_elem = [] 459 460 for hsp_frag_elem in root_hsp_frag_elem: 461 coords = {} # temporary container for coordinates 462 frag = HSPFragment(hit_id, query_id) 463 for key, val_info in _ELEM_FRAG.items(): 464 value = hsp_frag_elem.findtext(key) 465 caster = val_info[1] 466 467 # adjust 'from' and 'to' coordinates to 0-based ones 468 if value is not None: 469 if key.endswith('-from') or key.endswith('-to'): 470 # store coordinates for further processing 471 coords[val_info[0]] = caster(value) 472 continue 473 # recast only if value is not intended to be str 474 elif caster is not str: 475 value = caster(value) 476 setattr(frag, val_info[0], value) 477 478 # set the similarity characters into aln_annotation dict 479 frag.aln_annotation['similarity'] = \ 480 hsp_frag_elem.findtext('Hsp_midline') 481 482 # process coordinates 483 # since 'x-from' could be bigger than 'x-to', we need to figure 484 # out which one is smaller/bigger since 'x_start' is always smaller 485 # than 'x_end' 486 for coord_type in ('query', 'hit', 'pattern'): 487 start_type = coord_type + '_start' 488 end_type = coord_type + '_end' 489 try: 490 start = coords[start_type] 491 end = coords[end_type] 492 except KeyError: 493 continue 494 else: 495 # convert to python range and setattr 496 setattr(frag, start_type, min(start, end) - 1) 497 setattr(frag, end_type, max(start, end)) 498 499 # set alphabet, based on program 500 prog = self._meta.get('program') 501 if prog == 'blastn': 502 frag.alphabet = generic_dna 503 elif prog in ['blastp', 'blastx', 'tblastn', 'tblastx']: 504 frag.alphabet = generic_protein 505 506 hsp = HSP([frag]) 507 for key, val_info in _ELEM_HSP.items(): 508 value = hsp_frag_elem.findtext(key) 509 caster = val_info[1] 510 if value is not None: 511 if caster is not str: 512 value = caster(value) 513 setattr(hsp, val_info[0], value) 514 # delete element after we finish parsing it 515 hsp_frag_elem.clear() 516 yield hsp
517 518
519 -class BlastXmlIndexer(SearchIndexer):
520 """Indexer class for BLAST XML output.""" 521 522 _parser = BlastXmlParser 523 qstart_mark = _as_bytes('<Iteration>') 524 qend_mark = _as_bytes('</Iteration>') 525 block_size = 16384 526
527 - def __init__(self, filename):
528 SearchIndexer.__init__(self, filename) 529 # TODO: better way to do this? 530 iter_obj = self._parser(self._handle) 531 self._meta, self._fallback = iter_obj._meta, iter_obj._fallback
532
533 - def __iter__(self):
534 qstart_mark = self.qstart_mark 535 qend_mark = self.qend_mark 536 blast_id_mark = _as_bytes('Query_') 537 block_size = self.block_size 538 handle = self._handle 539 handle.seek(0) 540 re_desc = re.compile(_as_bytes(r'<Iteration_query-ID>(.*?)' 541 '</Iteration_query-ID>\s+?<Iteration_query-def>' 542 '(.*?)</Iteration_query-def>')) 543 re_desc_end = re.compile(_as_bytes(r'</Iteration_query-def>')) 544 counter = 0 545 546 while True: 547 start_offset = handle.tell() 548 line = handle.readline() 549 if not line: 550 break 551 if qstart_mark not in line: 552 continue 553 # The following requirements are to make supporting BGZF compressed 554 # BLAST XML files simpler (avoids complex offset manipulations): 555 assert line.count(qstart_mark) == 1, "XML without line breaks?" 556 assert line.lstrip().startswith(qstart_mark), line 557 if qend_mark in line: 558 # Should cope with <Iteration>...</Iteration> on one long line 559 block = line 560 else: 561 # Load the rest of this block up to and including </Iteration> 562 block = [line] 563 while line and qend_mark not in line: 564 line = handle.readline() 565 assert qstart_mark not in line, line 566 block.append(line) 567 assert line.rstrip().endswith(qend_mark), line 568 block = _empty_bytes_string.join(block) 569 assert block.count(qstart_mark) == 1, "XML without line breaks? %r" % block 570 assert block.count(qend_mark) == 1, "XML without line breaks? %r" % block 571 # Now we have a full <Iteration>...</Iteration> block, find the ID 572 regx = re.search(re_desc, block) 573 try: 574 qstart_desc = regx.group(2) 575 qstart_id = regx.group(1) 576 except AttributeError: 577 # use the fallback values 578 assert re.search(re_desc_end, block) 579 qstart_desc = _as_bytes(self._fallback['description']) 580 qstart_id = _as_bytes(self._fallback['id']) 581 if qstart_id.startswith(blast_id_mark): 582 qstart_id = qstart_desc.split(_as_bytes(' '), 1)[0] 583 yield _bytes_to_string(qstart_id), start_offset, len(block) 584 counter += 1
585
586 - def _parse(self, handle):
587 # overwrites SearchIndexer._parse, since we need to set the meta and 588 # fallback dictionaries to the parser 589 generator = self._parser(handle, **self._kwargs) 590 generator._meta = self._meta 591 generator._fallback = self._fallback 592 return next(iter(generator))
593
594 - def get_raw(self, offset):
595 qend_mark = self.qend_mark 596 handle = self._handle 597 handle.seek(offset) 598 599 qresult_raw = handle.readline() 600 assert qresult_raw.lstrip().startswith(self.qstart_mark) 601 while qend_mark not in qresult_raw: 602 qresult_raw += handle.readline() 603 assert qresult_raw.rstrip().endswith(qend_mark) 604 assert qresult_raw.count(qend_mark) == 1 605 # Note this will include any leading and trailing whitespace, in 606 # general expecting " <Iteration>\n...\n </Iteration>\n" 607 return qresult_raw
608 609
610 -class _BlastXmlGenerator(XMLGenerator):
611 """Event-based XML Generator.""" 612
613 - def __init__(self, out, encoding='utf-8', indent=" ", increment=2):
614 XMLGenerator.__init__(self, out, encoding) 615 # the indentation character 616 self._indent = indent 617 # nest level 618 self._level = 0 619 # how many indentation character should we increment per level 620 self._increment = increment 621 # container for names of tags with children 622 self._parent_stack = [] 623 # determine writer method 624 try: 625 # this should work for all platforms except Jython 626 self.write = self._write 627 except AttributeError: 628 # Jython uses self._out.write 629 self.write = self._out.write
630
631 - def startDocument(self):
632 """Starts the XML document.""" 633 self.write(u'<?xml version="1.0"?>\n' 634 '<!DOCTYPE BlastOutput PUBLIC "-//NCBI//NCBI BlastOutput/EN" ' 635 '"http://www.ncbi.nlm.nih.gov/dtd/NCBI_BlastOutput.dtd">\n')
636
637 - def startElement(self, name, attrs={}, children=False):
638 """Starts an XML element. 639 640 :param name: element name 641 :type name: string 642 :param attrs: element attributes 643 :type attrs: dictionary {string: object} 644 :param children: whether the element has children or not 645 :type children: bool 646 647 """ 648 self.ignorableWhitespace(self._indent * self._level) 649 XMLGenerator.startElement(self, name, attrs)
650
651 - def endElement(self, name):
652 """Ends and XML element of the given name.""" 653 XMLGenerator.endElement(self, name) 654 self.write(u'\n')
655
656 - def startParent(self, name, attrs={}):
657 """Starts an XML element which has children. 658 659 :param name: element name 660 :type name: string 661 :param attrs: element attributes 662 :type attrs: dictionary {string: object} 663 664 """ 665 self.startElement(name, attrs, children=True) 666 self._level += self._increment 667 self.write(u'\n') 668 # append the element name, so we can end it later 669 self._parent_stack.append(name)
670
671 - def endParent(self):
672 """Ends an XML element with children.""" 673 # the element to end is the one on top of the stack 674 name = self._parent_stack.pop() 675 self._level -= self._increment 676 self.ignorableWhitespace(self._indent * self._level) 677 self.endElement(name)
678
679 - def startParents(self, *names):
680 """Starts XML elements without children.""" 681 for name in names: 682 self.startParent(name)
683
684 - def endParents(self, num):
685 """Ends XML elements, according to the given number.""" 686 for i in range(num): 687 self.endParent()
688
689 - def simpleElement(self, name, content=None):
690 """Creates an XML element without children with the given content.""" 691 self.startElement(name, attrs={}) 692 if content: 693 self.characters(content) 694 self.endElement(name)
695
696 - def characters(self, content):
697 content = escape(unicode(content)) 698 for a, b in ((u'"', u'&quot;'), (u"'", u'&apos;')): 699 content = content.replace(a, b) 700 self.write(content)
701 702
703 -class BlastXmlWriter(object):
704 """Stream-based BLAST+ XML Writer.""" 705
706 - def __init__(self, handle):
707 self.xml = _BlastXmlGenerator(handle, 'utf-8')
708
709 - def write_file(self, qresults):
710 """Writes the XML contents to the output handle.""" 711 xml = self.xml 712 self.qresult_counter, self.hit_counter, self.hsp_counter, \ 713 self.frag_counter = 0, 0, 0, 0 714 715 # get the first qresult, since the preamble requires its attr values 716 first_qresult = next(qresults) 717 # start the XML document, set the root element, and create the preamble 718 xml.startDocument() 719 xml.startParent('BlastOutput') 720 self._write_preamble(first_qresult) 721 # and write the qresults 722 xml.startParent('BlastOutput_iterations') 723 self._write_qresults(chain([first_qresult], qresults)) 724 xml.endParents(2) 725 xml.endDocument() 726 727 return self.qresult_counter, self.hit_counter, self.hsp_counter, \ 728 self.frag_counter
729
730 - def _write_elem_block(self, block_name, map_name, obj, opt_dict={}):
731 """Writes sibling XML elements. 732 733 :param block_name: common element name prefix 734 :type block_name: string 735 :param map_name: name of mapping between element and attribute names 736 :type map_name: string 737 :param obj: object whose attribute value will be used 738 :type obj: object 739 :param opt_dict: custom element-attribute mapping 740 :type opt_dict: dictionary {string: string} 741 742 """ 743 for elem, attr in _WRITE_MAPS[map_name]: 744 elem = block_name + elem 745 try: 746 content = str(getattr(obj, attr)) 747 except AttributeError: 748 # ensure attrs that is not present is optional 749 assert elem in _DTD_OPT, "Element %r (attribute %r) not " \ 750 "found" % (elem, attr) 751 else: 752 # custom element-attribute mapping, for fallback values 753 if elem in opt_dict: 754 content = opt_dict[elem] 755 self.xml.simpleElement(elem, content)
756
757 - def _write_preamble(self, qresult):
758 """Writes the XML file preamble.""" 759 xml = self.xml 760 761 for elem, attr in _WRITE_MAPS['preamble']: 762 elem = 'BlastOutput_' + elem 763 if elem == 'BlastOutput_param': 764 xml.startParent(elem) 765 self._write_param(qresult) 766 xml.endParent() 767 continue 768 try: 769 content = str(getattr(qresult, attr)) 770 except AttributeError: 771 assert elem in _DTD_OPT, "Element %s (attribute %s) not " \ 772 "found" % (elem, attr) 773 else: 774 if elem == 'BlastOutput_version': 775 content = '%s %s' % (qresult.program.upper(), 776 qresult.version) 777 elif qresult._blast_id: 778 if elem == 'BlastOutput_query-ID': 779 content = qresult._blast_id 780 elif elem == 'BlastOutput_query-def': 781 content = ' '.join([qresult.id, 782 qresult.description]).strip() 783 xml.simpleElement(elem, content)
784
785 - def _write_param(self, qresult):
786 """Writes the parameter block of the preamble.""" 787 xml = self.xml 788 xml.startParent('Parameters') 789 self._write_elem_block('Parameters_', 'param', qresult) 790 xml.endParent()
791
792 - def _write_qresults(self, qresults):
793 """Writes QueryResult objects into iteration elements.""" 794 xml = self.xml 795 796 for num, qresult in enumerate(qresults): 797 xml.startParent('Iteration') 798 xml.simpleElement('Iteration_iter-num', str(num+1)) 799 opt_dict = {} 800 # use custom Iteration_query-ID and Iteration_query-def mapping 801 # if the query has a BLAST-generated ID 802 if qresult._blast_id: 803 opt_dict = { 804 'Iteration_query-ID': qresult._blast_id, 805 'Iteration_query-def': ' '.join([qresult.id, 806 qresult.description]).strip(), 807 } 808 self._write_elem_block('Iteration_', 'qresult', qresult, opt_dict) 809 # the Iteration_hits tag only has children if there are hits 810 if qresult: 811 xml.startParent('Iteration_hits') 812 self._write_hits(qresult.hits) 813 xml.endParent() 814 # otherwise it's a simple element without any contents 815 else: 816 xml.simpleElement('Iteration_hits', '') 817 818 xml.startParents('Iteration_stat', 'Statistics') 819 self._write_elem_block('Statistics_', 'stat', qresult) 820 xml.endParents(2) 821 # there's a message if no hits is present 822 if not qresult: 823 xml.simpleElement('Iteration_message', 'No hits found') 824 self.qresult_counter += 1 825 xml.endParent()
826
827 - def _write_hits(self, hits):
828 """Writes Hit objects.""" 829 xml = self.xml 830 831 for num, hit in enumerate(hits): 832 xml.startParent('Hit') 833 xml.simpleElement('Hit_num', str(num+1)) 834 # use custom hit_id and hit_def mapping if the hit has a 835 # BLAST-generated ID 836 opt_dict = {} 837 if hit._blast_id: 838 opt_dict = { 839 'Hit_id': hit._blast_id, 840 'Hit_def': ' '.join([hit.id, hit.description]).strip(), 841 } 842 self._write_elem_block('Hit_', 'hit', hit, opt_dict) 843 xml.startParent('Hit_hsps') 844 self._write_hsps(hit.hsps) 845 self.hit_counter += 1 846 xml.endParents(2)
847
848 - def _write_hsps(self, hsps):
849 """Writes HSP objects.""" 850 xml = self.xml 851 for num, hsp in enumerate(hsps): 852 xml.startParent('Hsp') 853 xml.simpleElement('Hsp_num', str(num+1)) 854 for elem, attr in _WRITE_MAPS['hsp']: 855 elem = 'Hsp_' + elem 856 try: 857 content = self._adjust_output(hsp, elem, attr) 858 # make sure any elements that is not present is optional 859 # in the DTD 860 except AttributeError: 861 assert elem in _DTD_OPT, "Element %s (attribute %s) not found" \ 862 % (elem, attr) 863 else: 864 xml.simpleElement(elem, str(content)) 865 self.hsp_counter += 1 866 self.frag_counter += len(hsp.fragments) 867 xml.endParent()
868
869 - def _adjust_output(self, hsp, elem, attr):
870 """Adjusts output to mimic native BLAST+ XML as much as possible.""" 871 872 # adjust coordinates 873 if attr in ('query_start', 'query_end', 'hit_start', 'hit_end', 874 'pattern_start', 'pattern_end'): 875 content = getattr(hsp, attr) + 1 876 if '_start' in attr: 877 content = getattr(hsp, attr) + 1 878 else: 879 content = getattr(hsp, attr) 880 881 # adjust for 'from' <--> 'to' flip if it's not a translated search 882 # and frames are different 883 # adapted from /src/algo/blast/format/blastxml_format.cpp#L216 884 if hsp.query_frame != 0 and hsp.hit_frame < 0: 885 if attr == 'hit_start': 886 content = getattr(hsp, 'hit_end') 887 elif attr == 'hit_end': 888 content = getattr(hsp, 'hit_start') + 1 889 890 # for seqrecord objects, we only need the sequence string 891 elif elem in ('Hsp_hseq', 'Hsp_qseq'): 892 content = str(getattr(hsp, attr).seq) 893 elif elem == 'Hsp_midline': 894 content = hsp.aln_annotation['similarity'] 895 elif elem in ('Hsp_evalue', 'Hsp_bit-score'): 896 # adapted from src/algo/blast/format/blastxml_format.cpp#L138-140 897 content = '%.*g' % (6, getattr(hsp, attr)) 898 else: 899 content = getattr(hsp, attr) 900 901 return content
902 903 904 # if not used as a module, run the doctest 905 if __name__ == "__main__": 906 from Bio._utils import run_doctest 907 run_doctest() 908