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

Source Code for Module Bio.SearchIO.HmmerIO.hmmer3_tab

  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 table output format.""" 
  7   
  8  from itertools import chain 
  9   
 10  from Bio._py3k import _as_bytes, _bytes_to_string 
 11  from Bio.Alphabet import generic_protein 
 12  from Bio.SearchIO._index import SearchIndexer 
 13  from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment 
 14   
 15   
 16  __all__ = ['Hmmer3TabParser', 'Hmmer3TabIndexer', 'Hmmer3TabWriter'] 
 17   
 18   
19 -class Hmmer3TabParser(object):
20 21 """Parser for the HMMER table format.""" 22
23 - def __init__(self, handle):
24 self.handle = handle 25 self.line = self.handle.readline()
26
27 - def __iter__(self):
28 header_mark = '#' 29 # read through the header if it exists 30 while self.line.startswith(header_mark): 31 self.line = self.handle.readline() 32 # if we have result rows, parse it 33 if self.line: 34 for qresult in self._parse_qresult(): 35 yield qresult
36
37 - def _parse_row(self):
38 """Returns a dictionary of parsed row values.""" 39 cols = [x for x in self.line.strip().split(' ') if x] 40 # if len(cols) > 19, we have extra description columns 41 # combine them all into one string in the 19th column 42 if len(cols) > 19: 43 cols[18] = ' '.join(cols[18:]) 44 # if it's < 19, we have no description columns, so use an empty string 45 # instead 46 elif len(cols) < 19: 47 cols.append('') 48 assert len(cols) == 19 49 50 # assign parsed column data into qresult, hit, and hsp dicts 51 qresult = {} 52 qresult['id'] = cols[2] # query name 53 qresult['accession'] = cols[3] # query accession 54 hit = {} 55 hit['id'] = cols[0] # target name 56 hit['accession'] = cols[1] # target accession 57 hit['evalue'] = float(cols[4]) # evalue (full sequence) 58 hit['bitscore'] = float(cols[5]) # score (full sequence) 59 hit['bias'] = float(cols[6]) # bias (full sequence) 60 hit['domain_exp_num'] = float(cols[10]) # exp 61 hit['region_num'] = int(cols[11]) # reg 62 hit['cluster_num'] = int(cols[12]) # clu 63 hit['overlap_num'] = int(cols[13]) # ov 64 hit['env_num'] = int(cols[14]) # env 65 hit['domain_obs_num'] = int(cols[15]) # dom 66 hit['domain_reported_num'] = int(cols[16]) # rep 67 hit['domain_included_num'] = int(cols[17]) # inc 68 hit['description'] = cols[18] # description of target 69 hsp = {} 70 hsp['evalue'] = float(cols[7]) # evalue (best 1 domain) 71 hsp['bitscore'] = float(cols[8]) # score (best 1 domain) 72 hsp['bias'] = float(cols[9]) # bias (best 1 domain) 73 # strand is always 0, since HMMER now only handles protein 74 frag = {} 75 frag['hit_strand'] = frag['query_strand'] = 0 76 frag['alphabet'] = generic_protein 77 78 return {'qresult': qresult, 'hit': hit, 'hsp': hsp, 'frag': frag}
79
80 - def _parse_qresult(self):
81 """Generator function that returns QueryResult objects.""" 82 # state values, determines what to do for each line 83 state_EOF = 0 84 state_QRES_NEW = 1 85 state_QRES_SAME = 3 86 # initial value dummies 87 qres_state = None 88 file_state = None 89 prev_qid = None 90 cur, prev = None, None 91 # container for Hit objects, used to create QueryResult 92 hit_list = [] 93 94 while True: 95 # store previous line's parsed values for all lines after the first 96 if cur is not None: 97 prev = cur 98 prev_qid = cur_qid 99 # only parse the result row if it's not EOF 100 # NOTE: we are not parsing the extra '#' lines appended to the end 101 # of hmmer31b1 tabular results since storing them in qresult 102 # objects means we can not do a single-pass parsing 103 if self.line and not self.line.startswith('#'): 104 cur = self._parse_row() 105 cur_qid = cur['qresult']['id'] 106 else: 107 file_state = state_EOF 108 # mock value for cur_qid, since we have nothing to parse 109 cur_qid = None 110 111 if prev_qid != cur_qid: 112 qres_state = state_QRES_NEW 113 else: 114 qres_state = state_QRES_SAME 115 116 if prev is not None: 117 # since domain tab formats only have 1 Hit per line 118 # we always create HSPFragment, HSP, and Hit per line 119 prev_hid = prev['hit']['id'] 120 121 # create fragment and HSP and set their attributes 122 frag = HSPFragment(prev_hid, prev_qid) 123 for attr, value in prev['frag'].items(): 124 setattr(frag, attr, value) 125 hsp = HSP([frag]) 126 for attr, value in prev['hsp'].items(): 127 setattr(hsp, attr, value) 128 129 # create Hit and set its attributes 130 hit = Hit([hsp]) 131 for attr, value in prev['hit'].items(): 132 setattr(hit, attr, value) 133 hit_list.append(hit) 134 135 # create qresult and yield if we're at a new qresult or at EOF 136 if qres_state == state_QRES_NEW or file_state == state_EOF: 137 qresult = QueryResult(hit_list, prev_qid) 138 for attr, value in prev['qresult'].items(): 139 setattr(qresult, attr, value) 140 yield qresult 141 # if we're at EOF, break 142 if file_state == state_EOF: 143 break 144 hit_list = [] 145 146 self.line = self.handle.readline()
147 148
149 -class Hmmer3TabIndexer(SearchIndexer):
150 151 """Indexer class for HMMER table output.""" 152 153 _parser = Hmmer3TabParser 154 # denotes column location for query identifier 155 _query_id_idx = 2 156
157 - def __iter__(self):
158 """Iterates over the file handle; yields key, start offset, and length.""" 159 handle = self._handle 160 handle.seek(0) 161 query_id_idx = self._query_id_idx 162 qresult_key = None 163 header_mark = _as_bytes('#') 164 split_mark = _as_bytes(' ') 165 # set line with initial mock value, to emulate header 166 line = header_mark 167 168 # read through header 169 while line.startswith(header_mark): 170 start_offset = handle.tell() 171 line = handle.readline() 172 173 # and index the qresults 174 while True: 175 end_offset = handle.tell() 176 177 if not line: 178 break 179 180 cols = [x for x in line.strip().split(split_mark) if x] 181 if qresult_key is None: 182 qresult_key = cols[query_id_idx] 183 else: 184 curr_key = cols[query_id_idx] 185 186 if curr_key != qresult_key: 187 adj_end = end_offset - len(line) 188 yield _bytes_to_string(qresult_key), start_offset, \ 189 adj_end - start_offset 190 qresult_key = curr_key 191 start_offset = adj_end 192 193 line = handle.readline() 194 if not line: 195 yield _bytes_to_string(qresult_key), start_offset, \ 196 end_offset - start_offset 197 break
198
199 - def get_raw(self, offset):
200 """Returns the raw string of a QueryResult object from the given offset.""" 201 handle = self._handle 202 handle.seek(offset) 203 query_id_idx = self._query_id_idx 204 qresult_key = None 205 qresult_raw = _as_bytes('') 206 split_mark = _as_bytes(' ') 207 208 while True: 209 line = handle.readline() 210 if not line: 211 break 212 cols = [x for x in line.strip().split(split_mark) if x] 213 if qresult_key is None: 214 qresult_key = cols[query_id_idx] 215 else: 216 curr_key = cols[query_id_idx] 217 if curr_key != qresult_key: 218 break 219 qresult_raw += line 220 221 return qresult_raw
222 223
224 -class Hmmer3TabWriter(object):
225 226 """Writer for hmmer3-tab output format.""" 227
228 - def __init__(self, handle):
229 self.handle = handle
230
231 - def write_file(self, qresults):
232 """Writes to the handle. 233 234 Returns a tuple of how many QueryResult, Hit, and HSP objects were written. 235 236 """ 237 handle = self.handle 238 qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 239 240 try: 241 first_qresult = next(qresults) 242 except StopIteration: 243 handle.write(self._build_header()) 244 else: 245 # write header 246 handle.write(self._build_header(first_qresult)) 247 # and then the qresults 248 for qresult in chain([first_qresult], qresults): 249 if qresult: 250 handle.write(self._build_row(qresult)) 251 qresult_counter += 1 252 hit_counter += len(qresult) 253 hsp_counter += sum(len(hit) for hit in qresult) 254 frag_counter += sum(len(hit.fragments) for hit in qresult) 255 256 return qresult_counter, hit_counter, hsp_counter, frag_counter
257
258 - def _build_header(self, first_qresult=None):
259 """Returns the header string of a HMMER table output.""" 260 261 # calculate whitespace required 262 # adapted from HMMER's source: src/p7_tophits.c#L1083 263 if first_qresult is not None: 264 #qnamew = max(20, len(first_qresult.id)) 265 qnamew = 20 # why doesn't the above work? 266 tnamew = max(20, len(first_qresult[0].id)) 267 qaccw = max(10, len(first_qresult.accession)) 268 taccw = max(10, len(first_qresult[0].accession)) 269 else: 270 qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10 271 272 header = "#%*s %22s %22s %33s\n" % \ 273 (tnamew + qnamew + taccw + qaccw + 2, "", 274 "--- full sequence ----", "--- best 1 domain ----", 275 "--- domain number estimation ----") 276 header += "#%-*s %-*s %-*s %-*s %9s %6s %5s %9s %6s %5s %5s %3s " \ 277 "%3s %3s %3s %3s %3s %3s %s\n" % (tnamew-1, " target name", 278 taccw, "accession", qnamew, "query name", qaccw, 279 "accession", " E-value", " score", " bias", 280 " E-value", " score", " bias", "exp", 281 "reg", "clu", " ov", "env", "dom", "rep", 282 "inc", "description of target") 283 header += "#%*s %*s %*s %*s %9s %6s %5s %9s %6s %5s %5s %3s %3s " \ 284 "%3s %3s %3s %3s %3s %s\n" % (tnamew-1, "-------------------", 285 taccw, "----------", qnamew, "--------------------", qaccw, 286 "----------", "---------", "------", "-----", "---------", 287 "------", "-----", "---", "---", "---", "---", "---", "---", 288 "---", "---", "---------------------") 289 290 return header
291
292 - def _build_row(self, qresult):
293 """Returns a string or one row or more of the QueryResult object.""" 294 rows = '' 295 296 # calculate whitespace required 297 # adapted from HMMER's source: src/p7_tophits.c#L1083 298 qnamew = max(20, len(qresult.id)) 299 tnamew = max(20, len(qresult[0].id)) 300 qaccw = max(10, len(qresult.accession)) 301 taccw = max(10, len(qresult[0].accession)) 302 303 for hit in qresult: 304 rows += "%-*s %-*s %-*s %-*s %9.2g %6.1f %5.1f %9.2g %6.1f %5.1f " \ 305 "%5.1f %3d %3d %3d %3d %3d %3d %3d %s\n" % (tnamew, hit.id, taccw, 306 hit.accession, qnamew, qresult.id, qaccw, qresult.accession, hit.evalue, 307 hit.bitscore, hit.bias, hit.hsps[0].evalue, hit.hsps[0].bitscore, 308 hit.hsps[0].bias, hit.domain_exp_num, hit.region_num, hit.cluster_num, 309 hit.overlap_num, hit.env_num, hit.domain_obs_num, 310 hit.domain_reported_num, hit.domain_included_num, hit.description) 311 312 return rows
313 314 315 # if not used as a module, run the doctest 316 if __name__ == "__main__": 317 from Bio._utils import run_doctest 318 run_doctest() 319