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