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 cur_qid = None 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 """Indexer class for HMMER table output.""" 150 151 _parser = Hmmer3TabParser 152 # denotes column location for query identifier 153 _query_id_idx = 2 154
155 - def __iter__(self):
156 """Iterates over the file handle; yields key, start offset, and length.""" 157 handle = self._handle 158 handle.seek(0) 159 query_id_idx = self._query_id_idx 160 qresult_key = None 161 header_mark = _as_bytes('#') 162 split_mark = _as_bytes(' ') 163 # set line with initial mock value, to emulate header 164 line = header_mark 165 166 # read through header 167 while line.startswith(header_mark): 168 start_offset = handle.tell() 169 line = handle.readline() 170 171 # and index the qresults 172 while True: 173 end_offset = handle.tell() 174 175 if not line: 176 break 177 178 cols = [x for x in line.strip().split(split_mark) if x] 179 if qresult_key is None: 180 qresult_key = cols[query_id_idx] 181 else: 182 curr_key = cols[query_id_idx] 183 184 if curr_key != qresult_key: 185 adj_end = end_offset - len(line) 186 yield _bytes_to_string(qresult_key), start_offset, \ 187 adj_end - start_offset 188 qresult_key = curr_key 189 start_offset = adj_end 190 191 line = handle.readline() 192 if not line: 193 yield _bytes_to_string(qresult_key), start_offset, \ 194 end_offset - start_offset 195 break
196
197 - def get_raw(self, offset):
198 """Returns the raw bytes string of a QueryResult object from the given offset.""" 199 handle = self._handle 200 handle.seek(offset) 201 query_id_idx = self._query_id_idx 202 qresult_key = None 203 qresult_raw = _as_bytes('') 204 split_mark = _as_bytes(' ') 205 206 while True: 207 line = handle.readline() 208 if not line: 209 break 210 cols = [x for x in line.strip().split(split_mark) if x] 211 if qresult_key is None: 212 qresult_key = cols[query_id_idx] 213 else: 214 curr_key = cols[query_id_idx] 215 if curr_key != qresult_key: 216 break 217 qresult_raw += line 218 219 return qresult_raw
220 221
222 -class Hmmer3TabWriter(object):
223 """Writer for hmmer3-tab output format.""" 224
225 - def __init__(self, handle):
226 self.handle = handle
227
228 - def write_file(self, qresults):
229 """Writes to the handle. 230 231 Returns a tuple of how many QueryResult, Hit, and HSP objects were written. 232 233 """ 234 handle = self.handle 235 qresult_counter, hit_counter, hsp_counter, frag_counter = 0, 0, 0, 0 236 237 try: 238 first_qresult = next(qresults) 239 except StopIteration: 240 handle.write(self._build_header()) 241 else: 242 # write header 243 handle.write(self._build_header(first_qresult)) 244 # and then the qresults 245 for qresult in chain([first_qresult], qresults): 246 if qresult: 247 handle.write(self._build_row(qresult)) 248 qresult_counter += 1 249 hit_counter += len(qresult) 250 hsp_counter += sum(len(hit) for hit in qresult) 251 frag_counter += sum(len(hit.fragments) for hit in qresult) 252 253 return qresult_counter, hit_counter, hsp_counter, frag_counter
254
255 - def _build_header(self, first_qresult=None):
256 """Returns the header string of a HMMER table output.""" 257 # calculate whitespace required 258 # adapted from HMMER's source: src/p7_tophits.c#L1083 259 if first_qresult is not None: 260 # qnamew = max(20, len(first_qresult.id)) 261 qnamew = 20 # why doesn't the above work? 262 tnamew = max(20, len(first_qresult[0].id)) 263 qaccw = max(10, len(first_qresult.accession)) 264 taccw = max(10, len(first_qresult[0].accession)) 265 else: 266 qnamew, tnamew, qaccw, taccw = 20, 20, 10, 10 267 268 header = "#%*s %22s %22s %33s\n" % \ 269 (tnamew + qnamew + taccw + qaccw + 2, "", 270 "--- full sequence ----", "--- best 1 domain ----", 271 "--- domain number estimation ----") 272 header += "#%-*s %-*s %-*s %-*s %9s %6s %5s %9s %6s %5s %5s %3s " \ 273 "%3s %3s %3s %3s %3s %3s %s\n" % (tnamew - 1, " target name", 274 taccw, "accession", qnamew, "query name", qaccw, 275 "accession", " E-value", " score", " bias", 276 " E-value", " score", " bias", "exp", 277 "reg", "clu", " ov", "env", "dom", "rep", 278 "inc", "description of target") 279 header += "#%*s %*s %*s %*s %9s %6s %5s %9s %6s %5s %5s %3s %3s " \ 280 "%3s %3s %3s %3s %3s %s\n" % (tnamew - 1, "-------------------", 281 taccw, "----------", qnamew, "--------------------", qaccw, 282 "----------", "---------", "------", "-----", "---------", 283 "------", "-----", "---", "---", "---", "---", "---", "---", 284 "---", "---", "---------------------") 285 286 return header
287
288 - def _build_row(self, qresult):
289 """Returns a string or one row or more of the QueryResult object.""" 290 rows = '' 291 292 # calculate whitespace required 293 # adapted from HMMER's source: src/p7_tophits.c#L1083 294 qnamew = max(20, len(qresult.id)) 295 tnamew = max(20, len(qresult[0].id)) 296 qaccw = max(10, len(qresult.accession)) 297 taccw = max(10, len(qresult[0].accession)) 298 299 for hit in qresult: 300 rows += "%-*s %-*s %-*s %-*s %9.2g %6.1f %5.1f %9.2g %6.1f %5.1f " \ 301 "%5.1f %3d %3d %3d %3d %3d %3d %3d %s\n" % (tnamew, hit.id, taccw, 302 hit.accession, qnamew, qresult.id, qaccw, qresult.accession, hit.evalue, 303 hit.bitscore, hit.bias, hit.hsps[0].evalue, hit.hsps[0].bitscore, 304 hit.hsps[0].bias, hit.domain_exp_num, hit.region_num, hit.cluster_num, 305 hit.overlap_num, hit.env_num, hit.domain_obs_num, 306 hit.domain_reported_num, hit.domain_included_num, hit.description) 307 308 return rows
309 310 311 # if not used as a module, run the doctest 312 if __name__ == "__main__": 313 from Bio._utils import run_doctest 314 run_doctest() 315