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