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