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