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