Package Bio :: Package SearchIO :: Package HmmerIO :: Module hmmer3_text
[hide private]
[frames] | no frames]

Source Code for Module Bio.SearchIO.HmmerIO.hmmer3_text

  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 HMMER plain text output format.""" 
  7   
  8  import re 
  9   
 10  from Bio._py3k import _as_bytes, _bytes_to_string 
 11  from Bio._utils import read_forward 
 12  from Bio.Alphabet import generic_protein 
 13  from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment 
 14   
 15  from ._base import _BaseHmmerTextIndexer 
 16   
 17  __all__ = ['Hmmer3TextParser', 'Hmmer3TextIndexer'] 
 18   
 19   
 20  # precompile regex patterns for faster processing 
 21  # regex for program name capture 
 22  _RE_PROGRAM = re.compile(r'^# (\w*hmm\w+) :: .*$') 
 23  # regex for version string capture 
 24  _RE_VERSION = re.compile(r'# \w+ ([\w+\.]+) .*; http.*$') 
 25  # regex for option string capture 
 26  _RE_OPT = re.compile(r'^# (.+):\s+(.+)$') 
 27  # regex for parsing query id and length, for parsing 
 28  _QRE_ID_LEN_PTN = r'^Query:\s*(.*)\s+\[\w=(\d+)\]' 
 29  _QRE_ID_LEN = re.compile(_QRE_ID_LEN_PTN) 
 30  # regex for hsp validation 
 31  _HRE_VALIDATE = re.compile(r'score:\s(-?\d+\.?\d+)\sbits.*value:\s(.*)') 
 32  # regexes for parsing hsp alignment blocks 
 33  _HRE_ANNOT_LINE = re.compile(r'^(\s+)(.+)\s(\w+)') 
 34  _HRE_ID_LINE = re.compile(r'^(\s+\S+\s+[0-9-]+ )(.+?)(\s+[0-9-]+)') 
 35   
 36   
37 -class Hmmer3TextParser(object):
38 39 """Parser for the HMMER 3.0 text output.""" 40
41 - def __init__(self, handle):
42 self.handle = handle 43 self.line = read_forward(self.handle) 44 self._meta = self._parse_preamble()
45
46 - def __iter__(self):
47 for qresult in self._parse_qresult(): 48 yield qresult
49
50 - def _read_until(self, bool_func):
51 """Reads the file handle until the given function returns True.""" 52 while True: 53 if not self.line or bool_func(self.line): 54 return 55 else: 56 self.line = read_forward(self.handle)
57
58 - def _parse_preamble(self):
59 """Parses HMMER preamble (lines beginning with '#').""" 60 meta = {} 61 # bool flag for storing state ~ whether we are parsing the option 62 # lines or not 63 has_opts = False 64 while True: 65 # no pound sign means we've left the preamble 66 if not self.line.startswith('#'): 67 break 68 # dashes could either mean we are entering or leaving the options 69 # section ~ so it's a switch for the has_opts flag 70 elif '- - -' in self.line: 71 if not has_opts: 72 # if flag is false, that means we're entering opts 73 # so switch the flag accordingly 74 has_opts = True 75 else: 76 # if flag is true, that means we've reached the end of opts 77 # so we can break out of the function 78 break 79 elif not has_opts: 80 # try parsing program 81 regx = re.search(_RE_PROGRAM, self.line) 82 if regx: 83 meta['program'] = regx.group(1) 84 # try parsing version 85 regx = re.search(_RE_VERSION, self.line) 86 if regx: 87 meta['version'] = regx.group(1) 88 elif has_opts: 89 regx = re.search(_RE_OPT, self.line) 90 # if target in regx.group(1), then we store the key as target 91 if 'target' in regx.group(1): 92 meta['target'] = regx.group(2).strip() 93 else: 94 meta[regx.group(1)] = regx.group(2) 95 96 self.line = read_forward(self.handle) 97 98 return meta
99
100 - def _parse_qresult(self):
101 """Parses a HMMER3 query block.""" 102 103 self._read_until(lambda line: line.startswith('Query:')) 104 105 while self.line: 106 107 # get query id and length 108 regx = re.search(_QRE_ID_LEN, self.line) 109 qid = regx.group(1).strip() 110 # store qresult attributes 111 qresult_attrs = { 112 'seq_len': int(regx.group(2)), 113 'program': self._meta.get('program'), 114 'version': self._meta.get('version'), 115 'target': self._meta.get('target'), 116 } 117 118 # get description and accession, if they exist 119 qdesc = '<unknown description>' # placeholder 120 while not self.line.startswith('Scores for '): 121 self.line = read_forward(self.handle) 122 123 if self.line.startswith('Accession:'): 124 acc = self.line.strip().split(' ', 1)[1] 125 qresult_attrs['accession'] = acc.strip() 126 elif self.line.startswith('Description:'): 127 qdesc = self.line.strip().split(' ', 1)[1].strip() 128 qresult_attrs['description'] = qdesc 129 130 # parse the query hits 131 while self.line and '//' not in self.line: 132 hit_list = self._parse_hit(qid, qdesc) 133 # read through the statistics summary 134 # TODO: parse and store this information? 135 if self.line.startswith('Internal pipeline'): 136 while self.line and '//' not in self.line: 137 self.line = read_forward(self.handle) 138 139 # create qresult, set its attributes and yield 140 # not initializing hit_list directly to handle empty hits 141 # (i.e. need to set its query description manually) 142 qresult = QueryResult(id=qid, hits=hit_list) 143 for attr, value in qresult_attrs.items(): 144 setattr(qresult, attr, value) 145 yield qresult 146 self.line = read_forward(self.handle) 147 148 # Skip line beginning with '# Alignment of', which are output 149 # when running phmmer with the '-A' flag. 150 if self.line.startswith('# Alignment of'): 151 self.line = self.handle.readline() 152 153 # HMMER >= 3.1 outputs '[ok]' at the end of all results file, 154 # which means we can break the main loop when we see the line 155 if '[ok]' in self.line: 156 break
157
158 - def _parse_hit(self, qid, qdesc):
159 """Parses a HMMER3 hit block, beginning with the hit table.""" 160 # get to the end of the hit table delimiter and read one more line 161 self._read_until(lambda line: 162 line.startswith(' ------- ------ -----')) 163 self.line = read_forward(self.handle) 164 165 # assume every hit is in inclusion threshold until the inclusion 166 # threshold line is encountered 167 is_included = True 168 169 # parse the hit table 170 hit_attr_list = [] 171 while True: 172 if not self.line: 173 return [] 174 elif self.line.startswith(' ------ inclusion'): 175 is_included = False 176 self.line = read_forward(self.handle) 177 # if there are no hits, then there are no hsps 178 # so we forward-read until 'Internal pipeline..' 179 elif self.line.startswith(' [No hits detected that satisfy ' 180 'reporting'): 181 while True: 182 self.line = read_forward(self.handle) 183 if self.line.startswith('Internal pipeline'): 184 assert len(hit_attr_list) == 0 185 return [] 186 elif self.line.startswith('Domain annotation for each '): 187 hit_list = self._create_hits(hit_attr_list, qid, qdesc) 188 return hit_list 189 # entering hit results row 190 # parse the columns into a list 191 row = [x for x in self.line.strip().split(' ') if x] 192 # join the description words if it's >1 word 193 if len(row) > 10: 194 row[9] = ' '.join(row[9:]) 195 # if there's no description, set it to an empty string 196 elif len(row) < 10: 197 row.append('') 198 assert len(row) == 10 199 # create the hit object 200 hit_attrs = { 201 'id': row[8], 202 'query_id': qid, 203 'evalue': float(row[0]), 204 'bitscore': float(row[1]), 205 'bias': float(row[2]), 206 # row[3:6] is not parsed, since the info is available 207 # at the HSP level 208 'domain_exp_num': float(row[6]), 209 'domain_obs_num': int(row[7]), 210 'description': row[9], 211 'is_included': is_included, 212 } 213 hit_attr_list.append(hit_attrs) 214 215 self.line = read_forward(self.handle)
216
217 - def _create_hits(self, hit_attrs, qid, qdesc):
218 """Parses a HMMER3 hsp block, beginning with the hsp table.""" 219 # read through until the beginning of the hsp block 220 self._read_until(lambda line: line.startswith('Internal pipeline') or 221 line.startswith('>>')) 222 223 # start parsing the hsp block 224 hit_list = [] 225 while True: 226 if self.line.startswith('Internal pipeline'): 227 # by this time we should've emptied the hit attr list 228 assert len(hit_attrs) == 0 229 return hit_list 230 assert self.line.startswith('>>') 231 hid, hdesc = self.line[len('>> '):].split(' ', 1) 232 hdesc = hdesc.strip() 233 234 # read through the hsp table header and move one more line 235 self._read_until(lambda line: 236 line.startswith(' --- ------ ----- --------') or 237 line.startswith(' [No individual domains')) 238 self.line = read_forward(self.handle) 239 240 # parse the hsp table for the current hit 241 hsp_list = [] 242 while True: 243 # break out of hsp parsing if there are no hits, it's the last hsp 244 # or it's the start of a new hit 245 if self.line.startswith(' [No targets detected that satisfy') or \ 246 self.line.startswith(' [No individual domains') or \ 247 self.line.startswith('Internal pipeline statistics summary:') or \ 248 self.line.startswith(' Alignments for each domain:') or \ 249 self.line.startswith('>>'): 250 251 hit_attr = hit_attrs.pop(0) 252 hit = Hit(hsp_list) 253 for attr, value in hit_attr.items(): 254 if attr == "description": 255 cur_val = getattr(hit, attr) 256 if cur_val and value and cur_val.startswith(value): 257 continue 258 setattr(hit, attr, value) 259 if not hit: 260 hit.query_description = qdesc 261 hit_list.append(hit) 262 break 263 264 parsed = [x for x in self.line.strip().split(' ') if x] 265 assert len(parsed) == 16 266 # parsed column order: 267 # index, is_included, bitscore, bias, evalue_cond, evalue 268 # hmmfrom, hmmto, query_ends, hit_ends, alifrom, alito, 269 # envfrom, envto, acc_avg 270 frag = HSPFragment(hid, qid) 271 # set query and hit descriptions if they are defined / nonempty string 272 if qdesc: 273 frag.query_description = qdesc 274 if hdesc: 275 frag.hit_description = hdesc 276 # HMMER3 alphabets are always protein alphabets 277 frag.alphabet = generic_protein 278 # depending on whether the program is hmmsearch, hmmscan, or phmmer 279 # {hmm,ali}{from,to} can either be hit_{from,to} or query_{from,to} 280 # for hmmscan, hit is the hmm profile, query is the sequence 281 if self._meta.get('program') == 'hmmscan': 282 # adjust 'from' and 'to' coordinates to 0-based ones 283 frag.hit_start = int(parsed[6]) - 1 284 frag.hit_end = int(parsed[7]) 285 frag.query_start = int(parsed[9]) - 1 286 frag.query_end = int(parsed[10]) 287 elif self._meta.get('program') in ['hmmsearch', 'phmmer']: 288 # adjust 'from' and 'to' coordinates to 0-based ones 289 frag.hit_start = int(parsed[9]) - 1 290 frag.hit_end = int(parsed[10]) 291 frag.query_start = int(parsed[6]) - 1 292 frag.query_end = int(parsed[7]) 293 # strand is always 0, since HMMER now only handles protein 294 frag.hit_strand = frag.query_strand = 0 295 296 hsp = HSP([frag]) 297 hsp.domain_index = int(parsed[0]) 298 hsp.is_included = parsed[1] == '!' 299 hsp.bitscore = float(parsed[2]) 300 hsp.bias = float(parsed[3]) 301 hsp.evalue_cond = float(parsed[4]) 302 hsp.evalue = float(parsed[5]) 303 if self._meta.get('program') == 'hmmscan': 304 # adjust 'from' and 'to' coordinates to 0-based ones 305 hsp.hit_endtype = parsed[8] 306 hsp.query_endtype = parsed[11] 307 elif self._meta.get('program') in ['hmmsearch', 'phmmer']: 308 # adjust 'from' and 'to' coordinates to 0-based ones 309 hsp.hit_endtype = parsed[11] 310 hsp.query_endtype = parsed[8] 311 # adjust 'from' and 'to' coordinates to 0-based ones 312 hsp.env_start = int(parsed[12]) - 1 313 hsp.env_end = int(parsed[13]) 314 hsp.env_endtype = parsed[14] 315 hsp.acc_avg = float(parsed[15]) 316 317 hsp_list.append(hsp) 318 self.line = read_forward(self.handle) 319 320 # parse the hsp alignments 321 if self.line.startswith(' Alignments for each domain:'): 322 self._parse_aln_block(hid, hit.hsps)
323
324 - def _parse_aln_block(self, hid, hsp_list):
325 """Parses a HMMER3 HSP alignment block.""" 326 self.line = read_forward(self.handle) 327 dom_counter = 0 328 while True: 329 if self.line.startswith('>>') or \ 330 self.line.startswith('Internal pipeline'): 331 return hsp_list 332 assert self.line.startswith(' == domain %i' % (dom_counter + 1)) 333 # alias hsp to local var 334 # but note that we're still changing the attrs of the actual 335 # hsp inside the qresult as we're not creating a copy 336 frag = hsp_list[dom_counter][0] 337 # XXX: should we validate again here? regex is expensive.. 338 # regx = re.search(_HRE_VALIDATE, self.line) 339 # assert hsp.bitscore == float(regx.group(1)) 340 # assert hsp.evalue_cond == float(regx.group(2)) 341 hmmseq = '' 342 aliseq = '' 343 annot = {} 344 self.line = self.handle.readline() 345 346 # parse all the alignment blocks in the hsp 347 while True: 348 349 regx = None 350 351 # check for hit or query line 352 # we don't check for the hit or query id specifically 353 # to anticipate special cases where query id == hit id 354 regx = re.search(_HRE_ID_LINE, self.line) 355 if regx: 356 # the first hit/query self.line we encounter is the hmmseq 357 if len(hmmseq) == len(aliseq): 358 hmmseq += regx.group(2) 359 # and for subsequent self.lines, len(hmmseq) is either 360 # > or == len(aliseq) 361 elif len(hmmseq) > len(aliseq): 362 aliseq += regx.group(2) 363 assert len(hmmseq) >= len(aliseq) 364 # check for start of new domain 365 elif self.line.startswith(' == domain') or \ 366 self.line.startswith('>>') or \ 367 self.line.startswith('Internal pipeline'): 368 frag.aln_annotation = annot 369 if self._meta.get('program') == 'hmmscan': 370 frag.hit = hmmseq 371 frag.query = aliseq 372 elif self._meta.get('program') in ['hmmsearch', 'phmmer']: 373 frag.hit = aliseq 374 frag.query = hmmseq 375 dom_counter += 1 376 hmmseq = '' 377 aliseq = '' 378 annot = {} 379 break 380 # otherwise check if it's an annotation line and parse it 381 # len(hmmseq) is only != len(aliseq) when the cursor is parsing 382 # the similarity character. Since we're not parsing that, we 383 # check for when the condition is False (i.e. when it's ==) 384 elif len(hmmseq) == len(aliseq): 385 regx = re.search(_HRE_ANNOT_LINE, self.line) 386 if regx: 387 annot_name = regx.group(3) 388 if annot_name in annot: 389 annot[annot_name] += regx.group(2) 390 else: 391 annot[annot_name] = regx.group(2) 392 393 self.line = self.handle.readline()
394 395
396 -class Hmmer3TextIndexer(_BaseHmmerTextIndexer):
397 398 """Indexer class for HMMER plain text output.""" 399 400 _parser = Hmmer3TextParser 401 qresult_start = _as_bytes('Query: ') 402 qresult_end = _as_bytes('//') 403
404 - def __iter__(self):
405 handle = self._handle 406 handle.seek(0) 407 start_offset = handle.tell() 408 regex_id = re.compile(_as_bytes(_QRE_ID_LEN_PTN)) 409 410 while True: 411 line = read_forward(handle) 412 end_offset = handle.tell() 413 414 if line.startswith(self.qresult_start): 415 regx = re.search(regex_id, line) 416 qresult_key = regx.group(1).strip() 417 # qresult start offset is the offset of this line 418 # (starts with the start mark) 419 start_offset = end_offset - len(line) 420 elif line.startswith(self.qresult_end): 421 yield _bytes_to_string(qresult_key), start_offset, 0 422 start_offset = end_offset 423 elif not line: 424 break
425 426 # if not used as a module, run the doctest 427 if __name__ == "__main__": 428 from Bio._utils import run_doctest 429 run_doctest() 430