PageRenderTime 48ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/Bio/SearchIO/FastaIO.py

https://gitlab.com/18runt88/biopython
Python | 581 lines | 535 code | 19 blank | 27 comment | 27 complexity | 59cf824f7b23156c123a9546ae4e8cbe MD5 | raw file
  1. # Adapted from Bio.AlignIO.FastaIO copyright 2008-2011 by Peter Cock.
  2. # Copyright 2012 by Wibowo Arindrarto.
  3. # All rights reserved.
  4. # This code is part of the Biopython distribution and governed by its
  5. # license. Please see the LICENSE file that should have been included
  6. # as part of this package.
  7. """Bio.SearchIO support for Bill Pearson's FASTA tools.
  8. This module adds support for parsing FASTA outputs. FASTA is a suite of
  9. programs that finds regions of local or global similarity between protein
  10. or nucleotide sequences, either by searching databases or identifying
  11. local duplications.
  12. Bio.SearchIO.FastaIO was tested on the following FASTA flavors and versions:
  13. - flavors: fasta, ssearch, tfastx
  14. - versions: 35, 36
  15. Other flavors and/or versions may introduce some bugs. Please file a bug report
  16. if you see such problems to Biopython's bug tracker.
  17. More information on FASTA are available through these links:
  18. - Website: http://fasta.bioch.virginia.edu/fasta_www2/fasta_list2.shtml
  19. - User guide: http://fasta.bioch.virginia.edu/fasta_www2/fasta_guide.pdf
  20. Supported Formats
  21. =================
  22. Bio.SearchIO.FastaIO supports parsing and indexing FASTA outputs triggered by
  23. the -m 10 flag. Other formats that mimic other programs (e.g. the BLAST tabular
  24. format using the -m 8 flag) may be parseable but using SearchIO's other parsers
  25. (in this case, using the 'blast-tab' parser).
  26. fasta-m10
  27. =========
  28. Note that in FASTA -m 10 outputs, HSPs from different strands are considered to
  29. be from different hits. They are listed as two separate entries in the hit
  30. table. FastaIO recognizes this and will group HSPs with the same hit ID into a
  31. single Hit object, regardless of strand.
  32. FASTA also sometimes output extra sequences adjacent to the HSP match. These
  33. extra sequences are discarded by FastaIO. Only regions containing the actual
  34. sequence match are extracted.
  35. The following object attributes are provided:
  36. +-----------------+-------------------------+----------------------------------+
  37. | Object | Attribute | Value |
  38. +=================+=========================+==================================+
  39. | QueryResult | description | query sequence description |
  40. | +-------------------------+----------------------------------+
  41. | | id | query sequence ID |
  42. | +-------------------------+----------------------------------+
  43. | | program | FASTA flavor |
  44. | +-------------------------+----------------------------------+
  45. | | seq_len | full length of query sequence |
  46. | +-------------------------+----------------------------------+
  47. | | target | target search database |
  48. | +-------------------------+----------------------------------+
  49. | | version | FASTA version |
  50. +-----------------+-------------------------+----------------------------------+
  51. | Hit | seq_len | full length of the hit sequence |
  52. +-----------------+-------------------------+----------------------------------+
  53. | HSP | bitscore | \*_bits line |
  54. | +-------------------------+----------------------------------+
  55. | | evalue | \*_expect line |
  56. | +-------------------------+----------------------------------+
  57. | | ident_pct | \*_ident line |
  58. | +-------------------------+----------------------------------+
  59. | | init1_score | \*_init1 line |
  60. | +-------------------------+----------------------------------+
  61. | | initn_score | \*_initn line |
  62. | +-------------------------+----------------------------------+
  63. | | opt_score | \*_opt line, \*_s-w opt line |
  64. | +-------------------------+----------------------------------+
  65. | | pos_pct | \*_sim line |
  66. | +-------------------------+----------------------------------+
  67. | | sw_score | \*_score line |
  68. | +-------------------------+----------------------------------+
  69. | | z_score | \*_z-score line |
  70. +-----------------+-------------------------+----------------------------------+
  71. | HSPFragment | aln_annotation | al_cons block, if present |
  72. | (also via HSP) +-------------------------+----------------------------------+
  73. | | hit | hit sequence |
  74. | +-------------------------+----------------------------------+
  75. | | hit_end | hit sequence end coordinate |
  76. | +-------------------------+----------------------------------+
  77. | | hit_start | hit sequence start coordinate |
  78. | +-------------------------+----------------------------------+
  79. | | hit_strand | hit sequence strand |
  80. | +-------------------------+----------------------------------+
  81. | | query | query sequence |
  82. | +-------------------------+----------------------------------+
  83. | | query_end | query sequence end coordinate |
  84. | +-------------------------+----------------------------------+
  85. | | query_start | query sequence start coordinate |
  86. | +-------------------------+----------------------------------+
  87. | | query_strand | query sequence strand |
  88. +-----------------+-------------------------+----------------------------------+
  89. """
  90. import re
  91. from Bio._py3k import _as_bytes, _bytes_to_string
  92. from Bio.Alphabet import generic_dna, generic_protein
  93. from Bio.File import UndoHandle
  94. from Bio.SearchIO._index import SearchIndexer
  95. from Bio.SearchIO._model import QueryResult, Hit, HSP, HSPFragment
  96. __all__ = ['FastaM10Parser', 'FastaM10Indexer']
  97. __docformat__ = "restructuredtext en"
  98. # precompile regex patterns
  99. # regex for program name
  100. _RE_FLAVS = re.compile(r't?fast[afmsxy]|pr[sf][sx]|lalign|[gs]?[glso]search')
  101. # regex for sequence ID and length ~ deals with both \n and \r\n
  102. _PTR_ID_DESC_SEQLEN = r'>>>(.+?)\s+(.*?) *- (\d+) (?:aa|nt)\s*$'
  103. _RE_ID_DESC_SEQLEN = re.compile(_PTR_ID_DESC_SEQLEN)
  104. _RE_ID_DESC_SEQLEN_IDX = re.compile(_as_bytes(_PTR_ID_DESC_SEQLEN))
  105. # regex for qresult, hit, or hsp attribute value
  106. _RE_ATTR = re.compile(r'^; [a-z]+(_[ \w-]+):\s+(.*)$')
  107. # regex for capturing excess start and end sequences in alignments
  108. _RE_START_EXC = re.compile(r'^-*')
  109. _RE_END_EXC = re.compile(r'-*$')
  110. # attribute name mappings
  111. _HSP_ATTR_MAP = {
  112. '_initn': ('initn_score', int),
  113. '_init1': ('init1_score', int),
  114. '_opt': ('opt_score', int),
  115. '_s-w opt': ('opt_score', int),
  116. '_z-score': ('z_score', float),
  117. '_bits': ('bitscore', float),
  118. '_expect': ('evalue', float),
  119. '_score': ('sw_score', int),
  120. '_ident': ('ident_pct', float),
  121. '_sim': ('pos_pct', float),
  122. }
  123. # state flags
  124. _STATE_NONE = 0
  125. _STATE_QUERY_BLOCK = 1
  126. _STATE_HIT_BLOCK = 2
  127. _STATE_CONS_BLOCK = 3
  128. def _set_qresult_hits(qresult, hit_rows=()):
  129. """Helper function for appending Hits without alignments into QueryResults."""
  130. for hit_row in hit_rows:
  131. hit_id, remainder = hit_row.split(' ', 1)
  132. # TODO: parse hit and hsp properties properly; by dealing with:
  133. # - any character in the description (brackets, spaces, etc.)
  134. # - possible [f] or [r] presence (for frame info)
  135. # - possible presence of E2() column
  136. # - possible incomplete hit_id due to column length limit
  137. # The current method only looks at the Hit ID, none of the things above
  138. if hit_id not in qresult:
  139. frag = HSPFragment(hit_id, qresult.id)
  140. hsp = HSP([frag])
  141. hit = Hit([hsp])
  142. qresult.append(hit)
  143. return qresult
  144. def _set_hsp_seqs(hsp, parsed, program):
  145. """Helper function for the main parsing code.
  146. :param hsp: HSP whose properties will be set
  147. :type hsp: HSP
  148. :param parsed: parsed values of the HSP attributes
  149. :type parsed: dictionary {string: object}
  150. :param program: program name
  151. :type program: string
  152. """
  153. # get aligned sequences and check if they have equal lengths
  154. start = 0
  155. for seq_type in ('hit', 'query'):
  156. if 'tfast' not in program:
  157. pseq = parsed[seq_type]
  158. # adjust start and end coordinates based on the amount of
  159. # filler characters
  160. start, stop = _get_aln_slice_coords(pseq)
  161. start_adj = len(re.search(_RE_START_EXC, pseq['seq']).group(0))
  162. stop_adj = len(re.search(_RE_END_EXC, pseq['seq']).group(0))
  163. start = start + start_adj
  164. stop = stop + start_adj - stop_adj
  165. parsed[seq_type]['seq'] = pseq['seq'][start:stop]
  166. assert len(parsed['query']['seq']) == len(parsed['hit']['seq']), "%r %r" \
  167. % (len(parsed['query']['seq']), len(parsed['hit']['seq']))
  168. if 'similarity' in hsp.aln_annotation:
  169. # only using 'start' since FASTA seems to have trimmed the 'excess'
  170. # end part
  171. hsp.aln_annotation['similarity'] = hsp.aln_annotation['similarity'][start:]
  172. # hit or query works equally well here
  173. assert len(hsp.aln_annotation['similarity']) == len(parsed['hit']['seq'])
  174. # query and hit sequence types must be the same
  175. assert parsed['query']['_type'] == parsed['hit']['_type']
  176. type_val = parsed['query']['_type'] # hit works fine too
  177. alphabet = generic_dna if type_val == 'D' else generic_protein
  178. setattr(hsp.fragment, 'alphabet', alphabet)
  179. for seq_type in ('hit', 'query'):
  180. # get and set start and end coordinates
  181. start = int(parsed[seq_type]['_start'])
  182. end = int(parsed[seq_type]['_stop'])
  183. setattr(hsp.fragment, seq_type + '_start', min(start, end) - 1)
  184. setattr(hsp.fragment, seq_type + '_end', max(start, end))
  185. # set seq and alphabet
  186. setattr(hsp.fragment, seq_type, parsed[seq_type]['seq'])
  187. if alphabet is not generic_protein:
  188. # get strand from coordinate; start <= end is plus
  189. # start > end is minus
  190. if start <= end:
  191. setattr(hsp.fragment, seq_type + '_strand', 1)
  192. else:
  193. setattr(hsp.fragment, seq_type + '_strand', -1)
  194. else:
  195. setattr(hsp.fragment, seq_type + '_strand', 0)
  196. def _get_aln_slice_coords(parsed_hsp):
  197. """Helper function for the main parsing code.
  198. To get the actual pairwise alignment sequences, we must first
  199. translate the un-gapped sequence based coordinates into positions
  200. in the gapped sequence (which may have a flanking region shown
  201. using leading - characters). To date, I have never seen any
  202. trailing flanking region shown in the m10 file, but the
  203. following code should also cope with that.
  204. Note that this code seems to work fine even when the "sq_offset"
  205. entries are prsent as a result of using the -X command line option.
  206. """
  207. seq = parsed_hsp['seq']
  208. seq_stripped = seq.strip('-')
  209. disp_start = int(parsed_hsp['_display_start'])
  210. start = int(parsed_hsp['_start'])
  211. stop = int(parsed_hsp['_stop'])
  212. if start <= stop:
  213. start = start - disp_start
  214. stop = stop - disp_start + 1
  215. else:
  216. start = disp_start - start
  217. stop = disp_start - stop + 1
  218. stop += seq_stripped.count('-')
  219. assert 0 <= start and start < stop and stop <= len(seq_stripped), \
  220. "Problem with sequence start/stop,\n%s[%i:%i]\n%s" \
  221. % (seq, start, stop, parsed_hsp)
  222. return start, stop
  223. class FastaM10Parser(object):
  224. """Parser for Bill Pearson's FASTA suite's -m 10 output."""
  225. def __init__(self, handle, __parse_hit_table=False):
  226. self.handle = UndoHandle(handle)
  227. self._preamble = self._parse_preamble()
  228. def __iter__(self):
  229. for qresult in self._parse_qresult():
  230. # re-set desc, for hsp query description
  231. qresult.description = qresult.description
  232. yield qresult
  233. def _parse_preamble(self):
  234. """Parses the Fasta preamble for Fasta flavor and version."""
  235. preamble = {}
  236. while True:
  237. self.line = self.handle.readline()
  238. # this should be the line just before the first qresult
  239. if self.line.startswith('Query'):
  240. break
  241. # try to match for version line
  242. elif self.line.startswith(' version'):
  243. preamble['version'] = self.line.split(' ')[2]
  244. else:
  245. # try to match for flavor line
  246. flav_match = re.match(_RE_FLAVS, self.line.lower())
  247. if flav_match:
  248. preamble['program'] = flav_match.group(0)
  249. return preamble
  250. def __parse_hit_table(self):
  251. """Parses hit table rows."""
  252. # move to the first row
  253. self.line = self.handle.readline()
  254. # parse hit table until we see an empty line
  255. hit_rows = []
  256. while self.line and not self.line.strip():
  257. hit_rows.append(self.line.strip())
  258. self.line = self.handle.readline()
  259. return hit_rows
  260. def _parse_qresult(self):
  261. # initial qresult value
  262. qresult = None
  263. hit_rows = []
  264. # state values
  265. state_QRES_NEW = 1
  266. state_QRES_HITTAB = 3
  267. state_QRES_CONTENT = 5
  268. state_QRES_END = 7
  269. while True:
  270. # one line before the hit table
  271. if self.line.startswith('The best scores are:'):
  272. qres_state = state_QRES_HITTAB
  273. # the end of a query or the file altogether
  274. elif self.line.strip() == '>>>///' or not self.line:
  275. qres_state = state_QRES_END
  276. # the beginning of a new query
  277. elif not self.line.startswith('>>>') and '>>>' in self.line:
  278. qres_state = state_QRES_NEW
  279. # the beginning of the query info and its hits + hsps
  280. elif self.line.startswith('>>>') and not \
  281. self.line.strip() == '>>><<<':
  282. qres_state = state_QRES_CONTENT
  283. # default qres mark
  284. else:
  285. qres_state = None
  286. if qres_state is not None:
  287. if qres_state == state_QRES_HITTAB:
  288. # parse hit table if flag is set
  289. hit_rows = self.__parse_hit_table()
  290. elif qres_state == state_QRES_END:
  291. yield _set_qresult_hits(qresult, hit_rows)
  292. break
  293. elif qres_state == state_QRES_NEW:
  294. # if qresult is filled, yield it first
  295. if qresult is not None:
  296. yield _set_qresult_hits(qresult, hit_rows)
  297. regx = re.search(_RE_ID_DESC_SEQLEN, self.line)
  298. query_id = regx.group(1)
  299. seq_len = regx.group(3)
  300. desc = regx.group(2)
  301. qresult = QueryResult(id=query_id)
  302. qresult.seq_len = int(seq_len)
  303. # get target from the next line
  304. self.line = self.handle.readline()
  305. qresult.target = [x for x in self.line.split(' ') if x][1].strip()
  306. if desc is not None:
  307. qresult.description = desc
  308. # set values from preamble
  309. for key, value in self._preamble.items():
  310. setattr(qresult, key, value)
  311. elif qres_state == state_QRES_CONTENT:
  312. assert self.line[3:].startswith(qresult.id), self.line
  313. for hit, strand in self._parse_hit(query_id):
  314. # HACK: re-set desc, for hsp hit and query description
  315. hit.description = hit.description
  316. hit.query_description = qresult.description
  317. # if hit is not in qresult, append it
  318. if hit.id not in qresult:
  319. qresult.append(hit)
  320. # otherwise, it might be the same hit with a different strand
  321. else:
  322. # make sure strand is different and then append hsp to
  323. # existing hit
  324. for hsp in hit.hsps:
  325. assert strand != hsp.query_strand
  326. qresult[hit.id].append(hsp)
  327. self.line = self.handle.readline()
  328. def _parse_hit(self, query_id):
  329. while True:
  330. self.line = self.handle.readline()
  331. if self.line.startswith('>>'):
  332. break
  333. state = _STATE_NONE
  334. strand = None
  335. hsp_list = []
  336. while True:
  337. peekline = self.handle.peekline()
  338. # yield hit if we've reached the start of a new query or
  339. # the end of the search
  340. if peekline.strip() in [">>><<<", ">>>///"] or \
  341. (not peekline.startswith('>>>') and '>>>' in peekline):
  342. # append last parsed_hsp['hit']['seq'] line
  343. if state == _STATE_HIT_BLOCK:
  344. parsed_hsp['hit']['seq'] += self.line.strip()
  345. elif state == _STATE_CONS_BLOCK:
  346. hsp.aln_annotation['similarity'] += \
  347. self.line.strip('\r\n')
  348. # process HSP alignment and coordinates
  349. _set_hsp_seqs(hsp, parsed_hsp, self._preamble['program'])
  350. hit = Hit(hsp_list)
  351. hit.description = hit_desc
  352. hit.seq_len = seq_len
  353. yield hit, strand
  354. hsp_list = []
  355. break
  356. # yield hit and create a new one if we're still in the same query
  357. elif self.line.startswith('>>'):
  358. # try yielding, if we have hsps
  359. if hsp_list:
  360. _set_hsp_seqs(hsp, parsed_hsp, self._preamble['program'])
  361. hit = Hit(hsp_list)
  362. hit.description = hit_desc
  363. hit.seq_len = seq_len
  364. yield hit, strand
  365. hsp_list = []
  366. # try to get the hit id and desc, and handle cases without descs
  367. try:
  368. hit_id, hit_desc = self.line[2:].strip().split(' ', 1)
  369. except ValueError:
  370. hit_id = self.line[2:].strip().split(' ', 1)[0]
  371. hit_desc = ''
  372. # create the HSP object for Hit
  373. frag = HSPFragment(hit_id, query_id)
  374. hsp = HSP([frag])
  375. hsp_list.append(hsp)
  376. # set or reset the state to none
  377. state = _STATE_NONE
  378. parsed_hsp = {'query': {}, 'hit': {}}
  379. # create and append a new HSP if line starts with '>--'
  380. elif self.line.startswith('>--'):
  381. # set seq attributes of previous hsp
  382. _set_hsp_seqs(hsp, parsed_hsp, self._preamble['program'])
  383. # and create a new one
  384. frag = HSPFragment(hit_id, query_id)
  385. hsp = HSP([frag])
  386. hsp_list.append(hsp)
  387. # set the state ~ none yet
  388. state = _STATE_NONE
  389. parsed_hsp = {'query': {}, 'hit': {}}
  390. # this is either query or hit data in the HSP, depending on the state
  391. elif self.line.startswith('>'):
  392. if state == _STATE_NONE:
  393. # make sure it's the correct query
  394. assert query_id.startswith(self.line[1:].split(' ')[0]), \
  395. "%r vs %r" % (query_id, self.line)
  396. state = _STATE_QUERY_BLOCK
  397. parsed_hsp['query']['seq'] = ''
  398. elif state == _STATE_QUERY_BLOCK:
  399. # make sure it's the correct hit
  400. assert hit_id.startswith(self.line[1:].split(' ')[0])
  401. state = _STATE_HIT_BLOCK
  402. parsed_hsp['hit']['seq'] = ''
  403. # check for conservation block
  404. elif self.line.startswith('; al_cons'):
  405. state = _STATE_CONS_BLOCK
  406. hsp.fragment.aln_annotation['similarity'] = ''
  407. elif self.line.startswith(';'):
  408. # Fasta outputs do not make a clear distinction between Hit
  409. # and HSPs, so we check the attribute names to determine
  410. # whether it belongs to a Hit or HSP
  411. regx = re.search(_RE_ATTR, self.line.strip())
  412. name = regx.group(1)
  413. value = regx.group(2)
  414. # for values before the '>...' query block
  415. if state == _STATE_NONE:
  416. if name in _HSP_ATTR_MAP:
  417. attr_name, caster = _HSP_ATTR_MAP[name]
  418. if caster is not str:
  419. value = caster(value)
  420. if name in ['_ident', '_sim']:
  421. value *= 100
  422. setattr(hsp, attr_name, value)
  423. # otherwise, pool the values for processing later
  424. elif state == _STATE_QUERY_BLOCK:
  425. parsed_hsp['query'][name] = value
  426. elif state == _STATE_HIT_BLOCK:
  427. if name == '_len':
  428. seq_len = int(value)
  429. else:
  430. parsed_hsp['hit'][name] = value
  431. # for values in the hit block
  432. else:
  433. raise ValueError("Unexpected line: %r" % self.line)
  434. # otherwise, it must be lines containing the sequences
  435. else:
  436. assert '>' not in self.line
  437. # if we're in hit, parse into hsp.hit
  438. if state == _STATE_HIT_BLOCK:
  439. parsed_hsp['hit']['seq'] += self.line.strip()
  440. elif state == _STATE_QUERY_BLOCK:
  441. parsed_hsp['query']['seq'] += self.line.strip()
  442. elif state == _STATE_CONS_BLOCK:
  443. hsp.fragment.aln_annotation['similarity'] += \
  444. self.line.strip('\r\n')
  445. # we should not get here!
  446. else:
  447. raise ValueError("Unexpected line: %r" % self.line)
  448. self.line = self.handle.readline()
  449. class FastaM10Indexer(SearchIndexer):
  450. """Indexer class for Bill Pearson's FASTA suite's -m 10 output."""
  451. _parser = FastaM10Parser
  452. def __init__(self, filename):
  453. SearchIndexer.__init__(self, filename)
  454. self._handle = UndoHandle(self._handle)
  455. def __iter__(self):
  456. handle = self._handle
  457. handle.seek(0)
  458. start_offset = handle.tell()
  459. qresult_key = None
  460. query_mark = _as_bytes('>>>')
  461. while True:
  462. line = handle.readline()
  463. peekline = handle.peekline()
  464. end_offset = handle.tell()
  465. if not line.startswith(query_mark) and query_mark in line:
  466. regx = re.search(_RE_ID_DESC_SEQLEN_IDX, line)
  467. qresult_key = _bytes_to_string(regx.group(1))
  468. start_offset = end_offset - len(line)
  469. # yield whenever we encounter a new query or at the end of the file
  470. if qresult_key is not None:
  471. if (not peekline.startswith(query_mark)
  472. and query_mark in peekline) or not line:
  473. yield qresult_key, start_offset, end_offset - start_offset
  474. if not line:
  475. break
  476. start_offset = end_offset
  477. def get_raw(self, offset):
  478. """Return the raw record from the file as a bytes string."""
  479. handle = self._handle
  480. qresult_raw = _as_bytes('')
  481. query_mark = _as_bytes('>>>')
  482. # read header first
  483. handle.seek(0)
  484. while True:
  485. line = handle.readline()
  486. peekline = handle.peekline()
  487. qresult_raw += line
  488. if not peekline.startswith(query_mark) and query_mark in peekline:
  489. break
  490. # and read the qresult raw string
  491. handle.seek(offset)
  492. while True:
  493. # preserve whitespace, don't use read_forward
  494. line = handle.readline()
  495. peekline = handle.peekline()
  496. qresult_raw += line
  497. # break when we've reached qresult end
  498. if (not peekline.startswith(query_mark) and query_mark in peekline) or \
  499. not line:
  500. break
  501. # append mock end marker to qresult_raw, since it's not always present
  502. return qresult_raw + _as_bytes('>>><<<\n')
  503. # if not used as a module, run the doctest
  504. if __name__ == "__main__":
  505. from Bio._utils import run_doctest
  506. run_doctest()