PageRenderTime 72ms CodeModel.GetById 38ms RepoModel.GetById 1ms app.codeStats 0ms

/Bio/Blast/NCBIStandalone.py

https://bitbucket.org/christophchamp/biopython
Python | 2199 lines | 2065 code | 37 blank | 97 comment | 54 complexity | c753c26957376830ac0068a5828c4d28 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. # Copyright 1999-2000 by Jeffrey Chang. 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. # Patches by Mike Poidinger to support multiple databases.
  6. # Updated by Peter Cock in 2007 to do a better job on BLAST 2.2.15
  7. """Code for calling standalone BLAST and parsing plain text output (OBSOLETE).
  8. Rather than parsing the human readable plain text BLAST output (which seems to
  9. change with every update to BLAST), we and the NBCI recommend you parse the
  10. XML output instead. The plain text parser in this module still works at the
  11. time of writing, but is considered obsolete and updating it to cope with the
  12. latest versions of BLAST is not a priority for us.
  13. This module also provides code to work with the "legacy" standalone version of
  14. NCBI BLAST, tools blastall, rpsblast and blastpgp via three helper functions of
  15. the same name. These functions are very limited for dealing with the output as
  16. files rather than handles, for which the wrappers in Bio.Blast.Applications are
  17. prefered. Furthermore, the NCBI themselves regard these command line tools as
  18. "legacy", and encourage using the new BLAST+ tools instead. Biopython has
  19. wrappers for these under Bio.Blast.Applications (see the tutorial).
  20. Classes:
  21. LowQualityBlastError Except that indicates low quality query sequences.
  22. BlastParser Parses output from blast.
  23. BlastErrorParser Parses output and tries to diagnose possible errors.
  24. PSIBlastParser Parses output from psi-blast.
  25. Iterator Iterates over a file of blast results.
  26. _Scanner Scans output from standalone BLAST.
  27. _BlastConsumer Consumes output from blast.
  28. _PSIBlastConsumer Consumes output from psi-blast.
  29. _HeaderConsumer Consumes header information.
  30. _DescriptionConsumer Consumes description information.
  31. _AlignmentConsumer Consumes alignment information.
  32. _HSPConsumer Consumes hsp information.
  33. _DatabaseReportConsumer Consumes database report information.
  34. _ParametersConsumer Consumes parameters information.
  35. Functions:
  36. blastall Execute blastall (OBSOLETE).
  37. blastpgp Execute blastpgp (OBSOLETE).
  38. rpsblast Execute rpsblast (OBSOLETE).
  39. For calling the BLAST command line tools, we encourage you to use the
  40. command line wrappers in Bio.Blast.Applications - the three functions
  41. blastall, blastpgp and rpsblast are considered to be obsolete now, and
  42. are likely to be deprecated and then removed in future releases.
  43. """
  44. import warnings
  45. warnings.warn("The plain text parser in this module still works at the time of writing, but is considered obsolete and updating it to cope with the latest versions of BLAST is not a priority for us.", PendingDeprecationWarning)
  46. import os
  47. import re
  48. import StringIO
  49. from Bio import File
  50. from Bio.ParserSupport import *
  51. from Bio.Blast import Record
  52. from Bio.Application import _escape_filename
  53. class LowQualityBlastError(Exception):
  54. """Error caused by running a low quality sequence through BLAST.
  55. When low quality sequences (like GenBank entries containing only
  56. stretches of a single nucleotide) are BLASTed, they will result in
  57. BLAST generating an error and not being able to perform the BLAST.
  58. search. This error should be raised for the BLAST reports produced
  59. in this case.
  60. """
  61. pass
  62. class ShortQueryBlastError(Exception):
  63. """Error caused by running a short query sequence through BLAST.
  64. If the query sequence is too short, BLAST outputs warnings and errors:
  65. Searching[blastall] WARNING: [000.000] AT1G08320: SetUpBlastSearch failed.
  66. [blastall] ERROR: [000.000] AT1G08320: Blast:
  67. [blastall] ERROR: [000.000] AT1G08320: Blast: Query must be at least wordsize
  68. done
  69. This exception is raised when that condition is detected.
  70. """
  71. pass
  72. class _Scanner:
  73. """Scan BLAST output from blastall or blastpgp.
  74. Tested with blastall and blastpgp v2.0.10, v2.0.11
  75. Methods:
  76. feed Feed data into the scanner.
  77. """
  78. def feed(self, handle, consumer):
  79. """S.feed(handle, consumer)
  80. Feed in a BLAST report for scanning. handle is a file-like
  81. object that contains the BLAST report. consumer is a Consumer
  82. object that will receive events as the report is scanned.
  83. """
  84. if isinstance(handle, File.UndoHandle):
  85. uhandle = handle
  86. else:
  87. uhandle = File.UndoHandle(handle)
  88. # Try to fast-forward to the beginning of the blast report.
  89. read_and_call_until(uhandle, consumer.noevent, contains='BLAST')
  90. # Now scan the BLAST report.
  91. self._scan_header(uhandle, consumer)
  92. self._scan_rounds(uhandle, consumer)
  93. self._scan_database_report(uhandle, consumer)
  94. self._scan_parameters(uhandle, consumer)
  95. def _scan_header(self, uhandle, consumer):
  96. # BLASTP 2.0.10 [Aug-26-1999]
  97. #
  98. #
  99. # Reference: Altschul, Stephen F., Thomas L. Madden, Alejandro A. Schaf
  100. # Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997),
  101. # "Gapped BLAST and PSI-BLAST: a new generation of protein database sea
  102. # programs", Nucleic Acids Res. 25:3389-3402.
  103. #
  104. # Query= test
  105. # (140 letters)
  106. #
  107. # Database: sdqib40-1.35.seg.fa
  108. # 1323 sequences; 223,339 total letters
  109. #
  110. # ========================================================
  111. # This next example is from the online version of Blast,
  112. # note there are TWO references, an RID line, and also
  113. # the database is BEFORE the query line.
  114. # Note there possibleuse of non-ASCII in the author names.
  115. # ========================================================
  116. #
  117. # BLASTP 2.2.15 [Oct-15-2006]
  118. # Reference: Altschul, Stephen F., Thomas L. Madden, Alejandro A. Sch??ffer,
  119. # Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman
  120. # (1997), "Gapped BLAST and PSI-BLAST: a new generation of
  121. # protein database search programs", Nucleic Acids Res. 25:3389-3402.
  122. #
  123. # Reference: Sch??ffer, Alejandro A., L. Aravind, Thomas L. Madden, Sergei
  124. # Shavirin, John L. Spouge, Yuri I. Wolf, Eugene V. Koonin, and
  125. # Stephen F. Altschul (2001), "Improving the accuracy of PSI-BLAST
  126. # protein database searches with composition-based statistics
  127. # and other refinements", Nucleic Acids Res. 29:2994-3005.
  128. #
  129. # RID: 1166022616-19998-65316425856.BLASTQ1
  130. #
  131. #
  132. # Database: All non-redundant GenBank CDS
  133. # translations+PDB+SwissProt+PIR+PRF excluding environmental samples
  134. # 4,254,166 sequences; 1,462,033,012 total letters
  135. # Query= gi:16127998
  136. # Length=428
  137. #
  138. consumer.start_header()
  139. read_and_call(uhandle, consumer.version, contains='BLAST')
  140. read_and_call_while(uhandle, consumer.noevent, blank=1)
  141. # There might be a <pre> line, for qblast output.
  142. attempt_read_and_call(uhandle, consumer.noevent, start="<pre>")
  143. # Read the reference(s)
  144. while attempt_read_and_call(uhandle,
  145. consumer.reference, start='Reference'):
  146. # References are normally multiline terminated by a blank line
  147. # (or, based on the old code, the RID line)
  148. while 1:
  149. line = uhandle.readline()
  150. if is_blank_line(line):
  151. consumer.noevent(line)
  152. break
  153. elif line.startswith("RID"):
  154. break
  155. else:
  156. #More of the reference
  157. consumer.reference(line)
  158. #Deal with the optional RID: ...
  159. read_and_call_while(uhandle, consumer.noevent, blank=1)
  160. attempt_read_and_call(uhandle, consumer.reference, start="RID:")
  161. read_and_call_while(uhandle, consumer.noevent, blank=1)
  162. # blastpgp may have a reference for compositional score matrix
  163. # adjustment (see Bug 2502):
  164. if attempt_read_and_call(
  165. uhandle, consumer.reference, start="Reference"):
  166. read_and_call_until(uhandle, consumer.reference, blank=1)
  167. read_and_call_while(uhandle, consumer.noevent, blank=1)
  168. # blastpgp has a Reference for composition-based statistics.
  169. if attempt_read_and_call(
  170. uhandle, consumer.reference, start="Reference"):
  171. read_and_call_until(uhandle, consumer.reference, blank=1)
  172. read_and_call_while(uhandle, consumer.noevent, blank=1)
  173. line = uhandle.peekline()
  174. assert line.strip() != ""
  175. assert not line.startswith("RID:")
  176. if line.startswith("Query="):
  177. #This is an old style query then database...
  178. # Read the Query lines and the following blank line.
  179. read_and_call(uhandle, consumer.query_info, start='Query=')
  180. read_and_call_until(uhandle, consumer.query_info, blank=1)
  181. read_and_call_while(uhandle, consumer.noevent, blank=1)
  182. # Read the database lines and the following blank line.
  183. read_and_call_until(uhandle, consumer.database_info, end='total letters')
  184. read_and_call(uhandle, consumer.database_info, contains='sequences')
  185. read_and_call_while(uhandle, consumer.noevent, blank=1)
  186. elif line.startswith("Database:"):
  187. #This is a new style database then query...
  188. read_and_call_until(uhandle, consumer.database_info, end='total letters')
  189. read_and_call(uhandle, consumer.database_info, contains='sequences')
  190. read_and_call_while(uhandle, consumer.noevent, blank=1)
  191. # Read the Query lines and the following blank line.
  192. # Or, on BLAST 2.2.22+ there is no blank link - need to spot
  193. # the "... Score E" line instead.
  194. read_and_call(uhandle, consumer.query_info, start='Query=')
  195. # BLAST 2.2.25+ has a blank line before Length=
  196. read_and_call_until(uhandle, consumer.query_info, start='Length=')
  197. while True:
  198. line = uhandle.peekline()
  199. if not line.strip() : break
  200. if "Score E" in line : break
  201. #It is more of the query (and its length)
  202. read_and_call(uhandle, consumer.query_info)
  203. read_and_call_while(uhandle, consumer.noevent, blank=1)
  204. else:
  205. raise ValueError("Invalid header?")
  206. consumer.end_header()
  207. def _scan_rounds(self, uhandle, consumer):
  208. # Scan a bunch of rounds.
  209. # Each round begins with either a "Searching......" line
  210. # or a 'Score E' line followed by descriptions and alignments.
  211. # The email server doesn't give the "Searching....." line.
  212. # If there is no 'Searching.....' line then you'll first see a
  213. # 'Results from round' line
  214. while not self._eof(uhandle):
  215. line = safe_peekline(uhandle)
  216. if (not line.startswith('Searching') and
  217. not line.startswith('Results from round') and
  218. re.search(r"Score +E", line) is None and
  219. line.find('No hits found') == -1):
  220. break
  221. self._scan_descriptions(uhandle, consumer)
  222. self._scan_alignments(uhandle, consumer)
  223. def _scan_descriptions(self, uhandle, consumer):
  224. # Searching..................................................done
  225. # Results from round 2
  226. #
  227. #
  228. # Sc
  229. # Sequences producing significant alignments: (b
  230. # Sequences used in model and found again:
  231. #
  232. # d1tde_2 3.4.1.4.4 (119-244) Thioredoxin reductase [Escherichia ...
  233. # d1tcob_ 1.31.1.5.16 Calcineurin regulatory subunit (B-chain) [B...
  234. # d1symb_ 1.31.1.2.2 Calcyclin (S100) [RAT (RATTUS NORVEGICUS)]
  235. #
  236. # Sequences not found previously or not previously below threshold:
  237. #
  238. # d1osa__ 1.31.1.5.11 Calmodulin [Paramecium tetraurelia]
  239. # d1aoza3 2.5.1.3.3 (339-552) Ascorbate oxidase [zucchini (Cucurb...
  240. #
  241. # If PSI-BLAST, may also have:
  242. #
  243. # CONVERGED!
  244. consumer.start_descriptions()
  245. # Read 'Searching'
  246. # This line seems to be missing in BLASTN 2.1.2 (others?)
  247. attempt_read_and_call(uhandle, consumer.noevent, start='Searching')
  248. # blastpgp 2.0.10 from NCBI 9/19/99 for Solaris sometimes crashes here.
  249. # If this happens, the handle will yield no more information.
  250. if not uhandle.peekline():
  251. raise ValueError("Unexpected end of blast report. " + \
  252. "Looks suspiciously like a PSI-BLAST crash.")
  253. # BLASTN 2.2.3 sometimes spews a bunch of warnings and errors here:
  254. # Searching[blastall] WARNING: [000.000] AT1G08320: SetUpBlastSearch
  255. # [blastall] ERROR: [000.000] AT1G08320: Blast:
  256. # [blastall] ERROR: [000.000] AT1G08320: Blast: Query must be at leas
  257. # done
  258. # Reported by David Weisman.
  259. # Check for these error lines and ignore them for now. Let
  260. # the BlastErrorParser deal with them.
  261. line = uhandle.peekline()
  262. if line.find("ERROR:") != -1 or line.startswith("done"):
  263. read_and_call_while(uhandle, consumer.noevent, contains="ERROR:")
  264. read_and_call(uhandle, consumer.noevent, start="done")
  265. # Check to see if this is PSI-BLAST.
  266. # If it is, the 'Searching' line will be followed by:
  267. # (version 2.0.10)
  268. # Searching.............................
  269. # Results from round 2
  270. # or (version 2.0.11)
  271. # Searching.............................
  272. #
  273. #
  274. # Results from round 2
  275. # Skip a bunch of blank lines.
  276. read_and_call_while(uhandle, consumer.noevent, blank=1)
  277. # Check for the results line if it's there.
  278. if attempt_read_and_call(uhandle, consumer.round, start='Results'):
  279. read_and_call_while(uhandle, consumer.noevent, blank=1)
  280. # Three things can happen here:
  281. # 1. line contains 'Score E'
  282. # 2. line contains "No hits found"
  283. # 3. no descriptions
  284. # The first one begins a bunch of descriptions. The last two
  285. # indicates that no descriptions follow, and we should go straight
  286. # to the alignments.
  287. if not attempt_read_and_call(
  288. uhandle, consumer.description_header,
  289. has_re=re.compile(r'Score +E')):
  290. # Either case 2 or 3. Look for "No hits found".
  291. attempt_read_and_call(uhandle, consumer.no_hits,
  292. contains='No hits found')
  293. try:
  294. read_and_call_while(uhandle, consumer.noevent, blank=1)
  295. except ValueError, err:
  296. if str(err) != "Unexpected end of stream." : raise err
  297. consumer.end_descriptions()
  298. # Stop processing.
  299. return
  300. # Read the score header lines
  301. read_and_call(uhandle, consumer.description_header,
  302. start='Sequences producing')
  303. # If PSI-BLAST, read the 'Sequences used in model' line.
  304. attempt_read_and_call(uhandle, consumer.model_sequences,
  305. start='Sequences used in model')
  306. read_and_call_while(uhandle, consumer.noevent, blank=1)
  307. # In BLAT, rather than a "No hits found" line, we just
  308. # get no descriptions (and no alignments). This can be
  309. # spotted because the next line is the database block:
  310. if safe_peekline(uhandle).startswith(" Database:"):
  311. consumer.end_descriptions()
  312. # Stop processing.
  313. return
  314. # Read the descriptions and the following blank lines, making
  315. # sure that there are descriptions.
  316. if not uhandle.peekline().startswith('Sequences not found'):
  317. read_and_call_until(uhandle, consumer.description, blank=1)
  318. read_and_call_while(uhandle, consumer.noevent, blank=1)
  319. # If PSI-BLAST, read the 'Sequences not found' line followed
  320. # by more descriptions. However, I need to watch out for the
  321. # case where there were no sequences not found previously, in
  322. # which case there will be no more descriptions.
  323. if attempt_read_and_call(uhandle, consumer.nonmodel_sequences,
  324. start='Sequences not found'):
  325. # Read the descriptions and the following blank lines.
  326. read_and_call_while(uhandle, consumer.noevent, blank=1)
  327. l = safe_peekline(uhandle)
  328. # Brad -- added check for QUERY. On some PSI-BLAST outputs
  329. # there will be a 'Sequences not found' line followed by no
  330. # descriptions. Check for this case since the first thing you'll
  331. # get is a blank line and then 'QUERY'
  332. if not l.startswith('CONVERGED') and l[0] != '>' \
  333. and not l.startswith('QUERY'):
  334. read_and_call_until(uhandle, consumer.description, blank=1)
  335. read_and_call_while(uhandle, consumer.noevent, blank=1)
  336. attempt_read_and_call(uhandle, consumer.converged, start='CONVERGED')
  337. read_and_call_while(uhandle, consumer.noevent, blank=1)
  338. consumer.end_descriptions()
  339. def _scan_alignments(self, uhandle, consumer):
  340. if self._eof(uhandle) : return
  341. # qblast inserts a helpful line here.
  342. attempt_read_and_call(uhandle, consumer.noevent, start="ALIGNMENTS")
  343. # First, check to see if I'm at the database report.
  344. line = safe_peekline(uhandle)
  345. if not line:
  346. #EOF
  347. return
  348. elif line.startswith(' Database') or line.startswith("Lambda"):
  349. return
  350. elif line[0] == '>':
  351. # XXX make a better check here between pairwise and masterslave
  352. self._scan_pairwise_alignments(uhandle, consumer)
  353. else:
  354. # XXX put in a check to make sure I'm in a masterslave alignment
  355. self._scan_masterslave_alignment(uhandle, consumer)
  356. def _scan_pairwise_alignments(self, uhandle, consumer):
  357. while not self._eof(uhandle):
  358. line = safe_peekline(uhandle)
  359. if line[0] != '>':
  360. break
  361. self._scan_one_pairwise_alignment(uhandle, consumer)
  362. def _scan_one_pairwise_alignment(self, uhandle, consumer):
  363. if self._eof(uhandle) : return
  364. consumer.start_alignment()
  365. self._scan_alignment_header(uhandle, consumer)
  366. # Scan a bunch of score/alignment pairs.
  367. while 1:
  368. if self._eof(uhandle):
  369. #Shouldn't have issued that _scan_alignment_header event...
  370. break
  371. line = safe_peekline(uhandle)
  372. if not line.startswith(' Score'):
  373. break
  374. self._scan_hsp(uhandle, consumer)
  375. consumer.end_alignment()
  376. def _scan_alignment_header(self, uhandle, consumer):
  377. # >d1rip__ 2.24.7.1.1 Ribosomal S17 protein [Bacillus
  378. # stearothermophilus]
  379. # Length = 81
  380. #
  381. # Or, more recently with different white space:
  382. #
  383. # >gi|15799684|ref|NP_285696.1| threonine synthase ...
  384. # gi|15829258|ref|NP_308031.1| threonine synthase
  385. # ...
  386. # Length=428
  387. read_and_call(uhandle, consumer.title, start='>')
  388. while 1:
  389. line = safe_readline(uhandle)
  390. if line.lstrip().startswith('Length =') \
  391. or line.lstrip().startswith('Length='):
  392. consumer.length(line)
  393. break
  394. elif is_blank_line(line):
  395. # Check to make sure I haven't missed the Length line
  396. raise ValueError("I missed the Length in an alignment header")
  397. consumer.title(line)
  398. # Older versions of BLAST will have a line with some spaces.
  399. # Version 2.0.14 (maybe 2.0.13?) and above print a true blank line.
  400. if not attempt_read_and_call(uhandle, consumer.noevent,
  401. start=' '):
  402. read_and_call(uhandle, consumer.noevent, blank=1)
  403. def _scan_hsp(self, uhandle, consumer):
  404. consumer.start_hsp()
  405. self._scan_hsp_header(uhandle, consumer)
  406. self._scan_hsp_alignment(uhandle, consumer)
  407. consumer.end_hsp()
  408. def _scan_hsp_header(self, uhandle, consumer):
  409. # Score = 22.7 bits (47), Expect = 2.5
  410. # Identities = 10/36 (27%), Positives = 18/36 (49%)
  411. # Strand = Plus / Plus
  412. # Frame = +3
  413. #
  414. read_and_call(uhandle, consumer.score, start=' Score')
  415. read_and_call(uhandle, consumer.identities, start=' Identities')
  416. # BLASTN
  417. attempt_read_and_call(uhandle, consumer.strand, start = ' Strand')
  418. # BLASTX, TBLASTN, TBLASTX
  419. attempt_read_and_call(uhandle, consumer.frame, start = ' Frame')
  420. read_and_call(uhandle, consumer.noevent, blank=1)
  421. def _scan_hsp_alignment(self, uhandle, consumer):
  422. # Query: 11 GRGVSACA-------TCDGFFYRNQKVAVIGGGNTAVEEALYLSNIASEVHLIHRRDGF
  423. # GRGVS+ TC Y + + V GGG+ + EE L + I R+
  424. # Sbjct: 12 GRGVSSVVRRCIHKPTCKE--YAVKIIDVTGGGSFSAEEVQELREATLKEVDILRKVSG
  425. #
  426. # Query: 64 AEKILIKR 71
  427. # I +K
  428. # Sbjct: 70 PNIIQLKD 77
  429. #
  430. while 1:
  431. # Blastn adds an extra line filled with spaces before Query
  432. attempt_read_and_call(uhandle, consumer.noevent, start=' ')
  433. read_and_call(uhandle, consumer.query, start='Query')
  434. read_and_call(uhandle, consumer.align, start=' ')
  435. read_and_call(uhandle, consumer.sbjct, start='Sbjct')
  436. try:
  437. read_and_call_while(uhandle, consumer.noevent, blank=1)
  438. except ValueError, err:
  439. if str(err) != "Unexpected end of stream." : raise err
  440. # End of File (well, it looks like it with recent versions
  441. # of BLAST for multiple queries after the Iterator class
  442. # has broken up the whole file into chunks).
  443. break
  444. line = safe_peekline(uhandle)
  445. # Alignment continues if I see a 'Query' or the spaces for Blastn.
  446. if not (line.startswith('Query') or line.startswith(' ')):
  447. break
  448. def _scan_masterslave_alignment(self, uhandle, consumer):
  449. consumer.start_alignment()
  450. while 1:
  451. line = safe_readline(uhandle)
  452. # Check to see whether I'm finished reading the alignment.
  453. # This is indicated by 1) database section, 2) next psi-blast
  454. # round, which can also be a 'Results from round' if no
  455. # searching line is present
  456. # patch by chapmanb
  457. if line.startswith('Searching') or \
  458. line.startswith('Results from round'):
  459. uhandle.saveline(line)
  460. break
  461. elif line.startswith(' Database'):
  462. uhandle.saveline(line)
  463. break
  464. elif is_blank_line(line):
  465. consumer.noevent(line)
  466. else:
  467. consumer.multalign(line)
  468. read_and_call_while(uhandle, consumer.noevent, blank=1)
  469. consumer.end_alignment()
  470. def _eof(self, uhandle):
  471. try:
  472. line = safe_peekline(uhandle)
  473. except ValueError, err:
  474. if str(err) != "Unexpected end of stream." : raise err
  475. line = ""
  476. return not line
  477. def _scan_database_report(self, uhandle, consumer):
  478. # Database: sdqib40-1.35.seg.fa
  479. # Posted date: Nov 1, 1999 4:25 PM
  480. # Number of letters in database: 223,339
  481. # Number of sequences in database: 1323
  482. #
  483. # Lambda K H
  484. # 0.322 0.133 0.369
  485. #
  486. # Gapped
  487. # Lambda K H
  488. # 0.270 0.0470 0.230
  489. #
  490. ##########################################
  491. # Or, more recently Blast 2.2.15 gives less blank lines
  492. ##########################################
  493. # Database: All non-redundant GenBank CDS translations+PDB+SwissProt+PIR+PRF excluding
  494. # environmental samples
  495. # Posted date: Dec 12, 2006 5:51 PM
  496. # Number of letters in database: 667,088,753
  497. # Number of sequences in database: 2,094,974
  498. # Lambda K H
  499. # 0.319 0.136 0.395
  500. # Gapped
  501. # Lambda K H
  502. # 0.267 0.0410 0.140
  503. if self._eof(uhandle) : return
  504. consumer.start_database_report()
  505. # Subset of the database(s) listed below
  506. # Number of letters searched: 562,618,960
  507. # Number of sequences searched: 228,924
  508. if attempt_read_and_call(uhandle, consumer.noevent, start=" Subset"):
  509. read_and_call(uhandle, consumer.noevent, contains="letters")
  510. read_and_call(uhandle, consumer.noevent, contains="sequences")
  511. read_and_call(uhandle, consumer.noevent, start=" ")
  512. # Sameet Mehta reported seeing output from BLASTN 2.2.9 that
  513. # was missing the "Database" stanza completely.
  514. while attempt_read_and_call(uhandle, consumer.database,
  515. start=' Database'):
  516. # BLAT output ends abruptly here, without any of the other
  517. # information. Check to see if this is the case. If so,
  518. # then end the database report here gracefully.
  519. if not uhandle.peekline().strip() \
  520. or uhandle.peekline().startswith("BLAST"):
  521. consumer.end_database_report()
  522. return
  523. # Database can span multiple lines.
  524. read_and_call_until(uhandle, consumer.database, start=' Posted')
  525. read_and_call(uhandle, consumer.posted_date, start=' Posted')
  526. read_and_call(uhandle, consumer.num_letters_in_database,
  527. start=' Number of letters')
  528. read_and_call(uhandle, consumer.num_sequences_in_database,
  529. start=' Number of sequences')
  530. #There may not be a line starting with spaces...
  531. attempt_read_and_call(uhandle, consumer.noevent, start=' ')
  532. line = safe_readline(uhandle)
  533. uhandle.saveline(line)
  534. if line.find('Lambda') != -1:
  535. break
  536. read_and_call(uhandle, consumer.noevent, start='Lambda')
  537. read_and_call(uhandle, consumer.ka_params)
  538. #This blank line is optional:
  539. attempt_read_and_call(uhandle, consumer.noevent, blank=1)
  540. # not BLASTP
  541. attempt_read_and_call(uhandle, consumer.gapped, start='Gapped')
  542. # not TBLASTX
  543. if attempt_read_and_call(uhandle, consumer.noevent, start='Lambda'):
  544. read_and_call(uhandle, consumer.ka_params_gap)
  545. # Blast 2.2.4 can sometimes skip the whole parameter section.
  546. # Thus, I need to be careful not to read past the end of the
  547. # file.
  548. try:
  549. read_and_call_while(uhandle, consumer.noevent, blank=1)
  550. except ValueError, x:
  551. if str(x) != "Unexpected end of stream.":
  552. raise
  553. consumer.end_database_report()
  554. def _scan_parameters(self, uhandle, consumer):
  555. # Matrix: BLOSUM62
  556. # Gap Penalties: Existence: 11, Extension: 1
  557. # Number of Hits to DB: 50604
  558. # Number of Sequences: 1323
  559. # Number of extensions: 1526
  560. # Number of successful extensions: 6
  561. # Number of sequences better than 10.0: 5
  562. # Number of HSP's better than 10.0 without gapping: 5
  563. # Number of HSP's successfully gapped in prelim test: 0
  564. # Number of HSP's that attempted gapping in prelim test: 1
  565. # Number of HSP's gapped (non-prelim): 5
  566. # length of query: 140
  567. # length of database: 223,339
  568. # effective HSP length: 39
  569. # effective length of query: 101
  570. # effective length of database: 171,742
  571. # effective search space: 17345942
  572. # effective search space used: 17345942
  573. # T: 11
  574. # A: 40
  575. # X1: 16 ( 7.4 bits)
  576. # X2: 38 (14.8 bits)
  577. # X3: 64 (24.9 bits)
  578. # S1: 41 (21.9 bits)
  579. # S2: 42 (20.8 bits)
  580. ##########################################
  581. # Or, more recently Blast(x) 2.2.15 gives
  582. ##########################################
  583. # Matrix: BLOSUM62
  584. # Gap Penalties: Existence: 11, Extension: 1
  585. # Number of Sequences: 4535438
  586. # Number of Hits to DB: 2,588,844,100
  587. # Number of extensions: 60427286
  588. # Number of successful extensions: 126433
  589. # Number of sequences better than 2.0: 30
  590. # Number of HSP's gapped: 126387
  591. # Number of HSP's successfully gapped: 35
  592. # Length of query: 291
  593. # Length of database: 1,573,298,872
  594. # Length adjustment: 130
  595. # Effective length of query: 161
  596. # Effective length of database: 983,691,932
  597. # Effective search space: 158374401052
  598. # Effective search space used: 158374401052
  599. # Neighboring words threshold: 12
  600. # Window for multiple hits: 40
  601. # X1: 16 ( 7.3 bits)
  602. # X2: 38 (14.6 bits)
  603. # X3: 64 (24.7 bits)
  604. # S1: 41 (21.7 bits)
  605. # S2: 32 (16.9 bits)
  606. # Blast 2.2.4 can sometimes skip the whole parameter section.
  607. # BLAT also skips the whole parameter section.
  608. # Thus, check to make sure that the parameter section really
  609. # exists.
  610. if not uhandle.peekline().strip():
  611. return
  612. # BLASTN 2.2.9 looks like it reverses the "Number of Hits" and
  613. # "Number of Sequences" lines.
  614. consumer.start_parameters()
  615. # Matrix line may be missing in BLASTN 2.2.9
  616. attempt_read_and_call(uhandle, consumer.matrix, start='Matrix')
  617. # not TBLASTX
  618. attempt_read_and_call(uhandle, consumer.gap_penalties, start='Gap')
  619. attempt_read_and_call(uhandle, consumer.num_sequences,
  620. start='Number of Sequences')
  621. attempt_read_and_call(uhandle, consumer.num_hits,
  622. start='Number of Hits')
  623. attempt_read_and_call(uhandle, consumer.num_sequences,
  624. start='Number of Sequences')
  625. attempt_read_and_call(uhandle, consumer.num_extends,
  626. start='Number of extensions')
  627. attempt_read_and_call(uhandle, consumer.num_good_extends,
  628. start='Number of successful')
  629. attempt_read_and_call(uhandle, consumer.num_seqs_better_e,
  630. start='Number of sequences')
  631. # not BLASTN, TBLASTX
  632. if attempt_read_and_call(uhandle, consumer.hsps_no_gap,
  633. start="Number of HSP's better"):
  634. # BLASTN 2.2.9
  635. if attempt_read_and_call(uhandle, consumer.noevent,
  636. start="Number of HSP's gapped:"):
  637. read_and_call(uhandle, consumer.noevent,
  638. start="Number of HSP's successfully")
  639. #This is ommitted in 2.2.15
  640. attempt_read_and_call(uhandle, consumer.noevent,
  641. start="Number of extra gapped extensions")
  642. else:
  643. read_and_call(uhandle, consumer.hsps_prelim_gapped,
  644. start="Number of HSP's successfully")
  645. read_and_call(uhandle, consumer.hsps_prelim_gap_attempted,
  646. start="Number of HSP's that")
  647. read_and_call(uhandle, consumer.hsps_gapped,
  648. start="Number of HSP's gapped")
  649. #e.g. BLASTX 2.2.15 where the "better" line is missing
  650. elif attempt_read_and_call(uhandle, consumer.noevent,
  651. start="Number of HSP's gapped"):
  652. read_and_call(uhandle, consumer.noevent,
  653. start="Number of HSP's successfully")
  654. # not in blastx 2.2.1
  655. attempt_read_and_call(uhandle, consumer.query_length,
  656. has_re=re.compile(r"[Ll]ength of query"))
  657. # Not in BLASTX 2.2.22+
  658. attempt_read_and_call(uhandle, consumer.database_length,
  659. has_re=re.compile(r"[Ll]ength of \s*[Dd]atabase"))
  660. # BLASTN 2.2.9
  661. attempt_read_and_call(uhandle, consumer.noevent,
  662. start="Length adjustment")
  663. attempt_read_and_call(uhandle, consumer.effective_hsp_length,
  664. start='effective HSP')
  665. # Not in blastx 2.2.1
  666. attempt_read_and_call(
  667. uhandle, consumer.effective_query_length,
  668. has_re=re.compile(r'[Ee]ffective length of query'))
  669. # This is not in BLASTP 2.2.15
  670. attempt_read_and_call(
  671. uhandle, consumer.effective_database_length,
  672. has_re=re.compile(r'[Ee]ffective length of \s*[Dd]atabase'))
  673. # Not in blastx 2.2.1, added a ':' to distinguish between
  674. # this and the 'effective search space used' line
  675. attempt_read_and_call(
  676. uhandle, consumer.effective_search_space,
  677. has_re=re.compile(r'[Ee]ffective search space:'))
  678. # Does not appear in BLASTP 2.0.5
  679. attempt_read_and_call(
  680. uhandle, consumer.effective_search_space_used,
  681. has_re=re.compile(r'[Ee]ffective search space used'))
  682. # BLASTX, TBLASTN, TBLASTX
  683. attempt_read_and_call(uhandle, consumer.frameshift, start='frameshift')
  684. # not in BLASTN 2.2.9
  685. attempt_read_and_call(uhandle, consumer.threshold, start='T')
  686. # In BLASTX 2.2.15 replaced by: "Neighboring words threshold: 12"
  687. attempt_read_and_call(uhandle, consumer.threshold, start='Neighboring words threshold')
  688. # not in BLASTX 2.2.15
  689. attempt_read_and_call(uhandle, consumer.window_size, start='A')
  690. # get this instead: "Window for multiple hits: 40"
  691. attempt_read_and_call(uhandle, consumer.window_size, start='Window for multiple hits')
  692. # not in BLASTX 2.2.22+
  693. attempt_read_and_call(uhandle, consumer.dropoff_1st_pass, start='X1')
  694. # not TBLASTN
  695. attempt_read_and_call(uhandle, consumer.gap_x_dropoff, start='X2')
  696. # not BLASTN, TBLASTX
  697. attempt_read_and_call(uhandle, consumer.gap_x_dropoff_final,
  698. start='X3')
  699. # not TBLASTN
  700. attempt_read_and_call(uhandle, consumer.gap_trigger, start='S1')
  701. # not in blastx 2.2.1
  702. # first we make sure we have additional lines to work with, if
  703. # not then the file is done and we don't have a final S2
  704. if not is_blank_line(uhandle.peekline(), allow_spaces=1):
  705. read_and_call(uhandle, consumer.blast_cutoff, start='S2')
  706. consumer.end_parameters()
  707. class BlastParser(AbstractParser):
  708. """Parses BLAST data into a Record.Blast object.
  709. """
  710. def __init__(self):
  711. """__init__(self)"""
  712. self._scanner = _Scanner()
  713. self._consumer = _BlastConsumer()
  714. def parse(self, handle):
  715. """parse(self, handle)"""
  716. self._scanner.feed(handle, self._consumer)
  717. return self._consumer.data
  718. class PSIBlastParser(AbstractParser):
  719. """Parses BLAST data into a Record.PSIBlast object.
  720. """
  721. def __init__(self):
  722. """__init__(self)"""
  723. self._scanner = _Scanner()
  724. self._consumer = _PSIBlastConsumer()
  725. def parse(self, handle):
  726. """parse(self, handle)"""
  727. self._scanner.feed(handle, self._consumer)
  728. return self._consumer.data
  729. class _HeaderConsumer:
  730. def start_header(self):
  731. self._header = Record.Header()
  732. def version(self, line):
  733. c = line.split()
  734. self._header.application = c[0]
  735. self._header.version = c[1]
  736. if len(c) > 2:
  737. #The date is missing in the new C++ output from blastx 2.2.22+
  738. #Just get "BLASTX 2.2.22+\n" and that's all.
  739. self._header.date = c[2][1:-1]
  740. def reference(self, line):
  741. if line.startswith('Reference: '):
  742. self._header.reference = line[11:]
  743. else:
  744. self._header.reference = self._header.reference + line
  745. def query_info(self, line):
  746. if line.startswith('Query= '):
  747. self._header.query = line[7:].lstrip()
  748. elif line.startswith('Length='):
  749. #New style way to give the query length in BLAST 2.2.22+ (the C++ code)
  750. self._header.query_letters = _safe_int(line[7:].strip())
  751. elif not line.startswith(' '): # continuation of query_info
  752. self._header.query = "%s%s" % (self._header.query, line)
  753. else:
  754. #Hope it is the old style way to give the query length:
  755. letters, = _re_search(
  756. r"([0-9,]+) letters", line,
  757. "I could not find the number of letters in line\n%s" % line)
  758. self._header.query_letters = _safe_int(letters)
  759. def database_info(self, line):
  760. line = line.rstrip()
  761. if line.startswith('Database: '):
  762. self._header.database = line[10:]
  763. elif not line.endswith('total letters'):
  764. if self._header.database:
  765. #Need to include a space when merging multi line datase descr
  766. self._header.database = self._header.database + " " + line.strip()
  767. else:
  768. self._header.database = line.strip()
  769. else:
  770. sequences, letters =_re_search(
  771. r"([0-9,]+) sequences; ([0-9,-]+) total letters", line,
  772. "I could not find the sequences and letters in line\n%s" %line)
  773. self._header.database_sequences = _safe_int(sequences)
  774. self._header.database_letters = _safe_int(letters)
  775. def end_header(self):
  776. # Get rid of the trailing newlines
  777. self._header.reference = self._header.reference.rstrip()
  778. self._header.query = self._header.query.rstrip()
  779. class _DescriptionConsumer:
  780. def start_descriptions(self):
  781. self._descriptions = []
  782. self._model_sequences = []
  783. self._nonmodel_sequences = []
  784. self._converged = 0
  785. self._type = None
  786. self._roundnum = None
  787. self.__has_n = 0 # Does the description line contain an N value?
  788. def description_header(self, line):
  789. if line.startswith('Sequences producing'):
  790. cols = line.split()
  791. if cols[-1] == 'N':
  792. self.__has_n = 1
  793. def description(self, line):
  794. dh = self._parse(line)
  795. if self._type == 'model':
  796. self._model_sequences.append(dh)
  797. elif self._type == 'nonmodel':
  798. self._nonmodel_sequences.append(dh)
  799. else:
  800. self._descriptions.append(dh)
  801. def model_sequences(self, line):
  802. self._type = 'model'
  803. def nonmodel_sequences(self, line):
  804. self._type = 'nonmodel'
  805. def converged(self, line):
  806. self._converged = 1
  807. def no_hits(self, line):
  808. pass
  809. def round(self, line):
  810. if not line.startswith('Results from round'):
  811. raise ValueError("I didn't understand the round line\n%s" % line)
  812. self._roundnum = _safe_int(line[18:].strip())
  813. def end_descriptions(self):
  814. pass
  815. def _parse(self, description_line):
  816. line = description_line # for convenience
  817. dh = Record.Description()
  818. # I need to separate the score and p-value from the title.
  819. # sp|P21297|FLBT_CAUCR FLBT PROTEIN [snip] 284 7e-77
  820. # sp|P21297|FLBT_CAUCR FLBT PROTEIN [snip] 284 7e-77 1
  821. # special cases to handle:
  822. # - title must be preserved exactly (including whitespaces)
  823. # - score could be equal to e-value (not likely, but what if??)
  824. # - sometimes there's an "N" score of '1'.
  825. cols = line.split()
  826. if len(cols) < 3:
  827. raise ValueError( \
  828. "Line does not appear to contain description:\n%s" % line)
  829. if self.__has_n:
  830. i = line.rfind(cols[-1]) # find start of N
  831. i = line.rfind(cols[-2], 0, i) # find start of p-value
  832. i = line.rfind(cols[-3], 0, i) # find start of score
  833. else:
  834. i = line.rfind(cols[-1]) # find start of p-value
  835. i = line.rfind(cols[-2], 0, i) # find start of score
  836. if self.__has_n:
  837. dh.title, dh.score, dh.e, dh.num_alignments = \
  838. line[:i].rstrip(), cols[-3], cols[-2], cols[-1]
  839. else:
  840. dh.title, dh.score, dh.e, dh.num_alignments = \
  841. line[:i].rstrip(), cols[-2], cols[-1], 1
  842. dh.num_alignments = _safe_int(dh.num_alignments)
  843. dh.score = _safe_int(dh.score)
  844. dh.e = _safe_float(dh.e)
  845. return dh
  846. class _AlignmentConsumer:
  847. # This is a little bit tricky. An alignment can either be a
  848. # pairwise alignment or a multiple alignment. Since it's difficult
  849. # to know a-priori which one the blast record will contain, I'm going
  850. # to make one class that can parse both of them.
  851. def start_alignment(self):
  852. self._alignment = Record.Alignment()
  853. self._multiple_alignment = Record.MultipleAlignment()
  854. def title(self, line):
  855. if self._alignment.title:
  856. self._alignment.title += " "
  857. self._alignment.title += line.strip()
  858. def length(self, line):
  859. #e.g. "Length = 81" or more recently, "Length=428"
  860. parts = line.replace(" ","").split("=")
  861. assert len(parts)==2, "Unrecognised format length line"
  862. self._alignment.length = parts[1]
  863. self._alignment.length = _safe_int(self._alignment.length)
  864. def multalign(self, line):
  865. # Standalone version uses 'QUERY', while WWW version uses blast_tmp.
  866. if line.startswith('QUERY') or line.startswith('blast_tmp'):
  867. # If this is the first line of the multiple alignment,
  868. # then I need to figure out how the line is formatted.
  869. # Format of line is:
  870. # QUERY 1 acttg...gccagaggtggtttattcagtctccataagagaggggacaaacg 60
  871. try:
  872. name, start, seq, end = line.split()
  873. except ValueError:
  874. raise ValueError("I do not understand the line\n%s" % line)
  875. self._start_index = line.index(start, len(name))
  876. self._seq_index = line.index(seq,
  877. self._start_index+len(start))
  878. # subtract 1 for the space
  879. self._name_length = self._start_index - 1
  880. self._start_length = self._seq_index - self._start_index - 1
  881. self._seq_length = line.rfind(end) - self._seq_index - 1
  882. #self._seq_index = line.index(seq)
  883. ## subtract 1 for the space
  884. #self._seq_length = line.rfind(end) - self._seq_index - 1
  885. #self._start_index = line.index(start)
  886. #self._start_length = self._seq_index - self._start_index - 1
  887. #self._name_length = self._start_index
  888. # Extract the information from the line
  889. name = line[:self._name_length]
  890. name = name.rstrip()
  891. start = line[self._start_index:self._start_index+self._start_length]
  892. start = start.rstrip()
  893. if start:
  894. start = _safe_int(start)
  895. end = line[self._seq_index+self._seq_length:].rstrip()
  896. if end:
  897. end = _safe_int(end)
  898. seq = line[self._seq_index:self._seq_index+self._seq_length].rstrip()
  899. # right pad the sequence with spaces if necessary
  900. if len(seq) < self._seq_length:
  901. seq = seq + ' '*(self._seq_length-len(seq))
  902. # I need to make sure the sequence is aligned correctly with the query.
  903. # First, I will find the length of the query. Then, if necessary,
  904. # I will pad my current sequence with spaces so that they will line
  905. # up correctly.
  906. # Two possible things can happen:
  907. # QUERY
  908. # 504
  909. #
  910. # QUERY
  911. # 403
  912. #
  913. # Sequence 504 will need padding at the end. Since I won't know
  914. # this until the end of the alignment, this will be handled in
  915. # end_alignment.
  916. # Sequence 403 will need padding before being added to the alignment.
  917. align = self._multiple_alignment.alignment # for convenience
  918. align.append((name, start, seq, end))
  919. # This is old code that tried to line up all the sequences
  920. # in a multiple alignment by using the sequence title's as
  921. # identifiers. The problem with this is that BLAST assigns
  922. # different HSP's from the same sequence the same id. Thus,
  923. # in one alignment block, there may be multiple sequences with
  924. # the same id. I'm not sure how to handle this, so I'm not
  925. # going to.
  926. # # If the sequence is the query, then just add it.
  927. # if name == 'QUERY':
  928. # if len(align) == 0:
  929. # align.append((name, start, seq))
  930. # else:
  931. # aname, astart, aseq = align[0]
  932. # if name != aname:
  933. # raise ValueError, "Query is not the first sequence"
  934. # aseq = aseq + seq
  935. # align[0] = aname, astart, aseq
  936. # else:
  937. # if len(align) == 0:
  938. # raise ValueError, "I could not find the query sequence"
  939. # qname, qstart, qseq = align[0]
  940. #
  941. # # Now find my sequence in the multiple alignment.
  942. # for i in range(1, len(align)):
  943. # aname, astart, aseq = align[i]
  944. # if name == aname:
  945. # index = i
  946. # break
  947. # else:
  948. # # If I couldn't find it, then add a new one.
  949. # align.append((None, None, None))
  950. # index = len(align)-1
  951. # # Make sure to left-pad it.
  952. # aname, astart, aseq = name, start, ' '*(len(qseq)-len(seq))
  953. #
  954. # if len(qseq) != len(aseq) + len(seq):
  955. # # If my sequences are shorter than the query sequence,
  956. # # then I will need to pad some spaces to make them line up.
  957. # # Since I've already right padded seq, that means aseq
  958. # # must be too short.
  959. # aseq = aseq + ' '*(len(qseq)-len(aseq)-len(seq))
  960. # aseq = aseq + seq
  961. # if astart is None:
  962. # astart = start
  963. # align[index] = aname, astart, aseq
  964. def end_alignment(self):
  965. # Remove trailing newlines
  966. if self._alignment:
  967. self._alignment.title = self._alignment.title.rstrip()
  968. # This code is also obsolete. See note above.
  969. # If there's a multiple alignment, I will need to make sure
  970. # all the sequences are aligned. That is, I may need to
  971. # right-pad the sequences.
  972. # if self._multiple_alignment is not None:
  973. # align = self._multiple_alignment.alignment
  974. # seqlen = None
  975. # for i in range(len(align)):
  976. # name, start, seq = align[i]
  977. # if seqlen is None:
  978. # seqlen = len(seq)
  979. # else:
  980. # if len(seq) < seqlen:
  981. # seq = seq + ' '*(seqlen - len(seq))
  982. # align[i] = name, start, seq
  983. # elif len(seq) > seqlen:
  984. # raise ValueError, \
  985. # "Sequence %s is longer than the query" % name
  986. # Clean up some variables, if they exist.
  987. try:
  988. del self._seq_index
  989. del self._seq_length
  990. del self._start_index
  991. del self._start_length
  992. del self._name_length
  993. except AttributeError:
  994. pass
  995. class _HSPConsumer:
  996. def start_hsp(self):
  997. self._hsp = Record.HSP()
  998. def score(self, line):
  999. self._hsp.bits, self._hsp.score = _re_search(
  1000. r"Score =\s*([0-9.e+]+) bits \(([0-9]+)\)", line,
  1001. "I could not find the score in line\n%s" % line)
  1002. self._hsp.score = _safe_float(self._hsp.score)
  1003. self._hsp.bits = _safe_float(self._hsp.bits)
  1004. x, y = _re_search(
  1005. r"Expect\(?(\d*)\)? = +([0-9.e\-|\+]+)", line,
  1006. "I could not find the expect in line\n%s" % line)
  1007. if x:
  1008. self._hsp.num_alignments = _safe_int(x)
  1009. else:
  1010. self._hsp.num_alignments = 1
  1011. self._hsp.expect = _safe_float(y)
  1012. def identities(self, line):
  1013. x, y = _re_search(
  1014. r"Identities = (\d+)\/(\d+)", line,
  1015. "I could not find the identities in line\n%s" % line)
  1016. self._hsp.identities = _safe_int(x), _safe_int(y)
  1017. self._hsp.align_length = _safe_int(y)
  1018. if line.find('Positives') != -1:
  1019. x, y = _re_search(
  1020. r"Positives = (\d+)\/(\d+)", line,
  1021. "I could not find the positives in line\n%s" % line)
  1022. self._hsp.positives

Large files files are truncated, but you can click here to view the full file