PageRenderTime 64ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Bio/Blast/NCBIStandalone.py

https://bitbucket.org/christophchamp/biopython
Python | 2199 lines | 2065 code | 37 blank | 97 comment | 54 complexity | c753c26957376830ac0068a5828c4d28 MD5 | raw 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 = _safe_int(x), _safe_int(y)
  1023. assert self._hsp.align_length == _safe_int(y)
  1024. if line.find('Gaps') != -1:
  1025. x, y = _re_search(
  1026. r"Gaps = (\d+)\/(\d+)", line,
  1027. "I could not find the gaps in line\n%s" % line)
  1028. self._hsp.gaps = _safe_int(x), _safe_int(y)
  1029. assert self._hsp.align_length == _safe_int(y)
  1030. def strand(self, line):
  1031. self._hsp.strand = _re_search(
  1032. r"Strand\s?=\s?(\w+)\s?/\s?(\w+)", line,
  1033. "I could not find the strand in line\n%s" % line)
  1034. def frame(self, line):
  1035. # Frame can be in formats:
  1036. # Frame = +1
  1037. # Frame = +2 / +2
  1038. if line.find('/') != -1:
  1039. self._hsp.frame = _re_search(
  1040. r"Frame\s?=\s?([-+][123])\s?/\s?([-+][123])", line,
  1041. "I could not find the frame in line\n%s" % line)
  1042. else:
  1043. self._hsp.frame = _re_search(
  1044. r"Frame = ([-+][123])", line,
  1045. "I could not find the frame in line\n%s" % line)
  1046. # Match a space, if one is available. Masahir Ishikawa found a
  1047. # case where there's no space between the start and the sequence:
  1048. # Query: 100tt 101
  1049. # line below modified by Yair Benita, Sep 2004
  1050. # Note that the colon is not always present. 2006
  1051. _query_re = re.compile(r"Query(:?) \s*(\d+)\s*(.+) (\d+)")
  1052. def query(self, line):
  1053. m = self._query_re.search(line)
  1054. if m is None:
  1055. raise ValueError("I could not find the query in line\n%s" % line)
  1056. # line below modified by Yair Benita, Sep 2004.
  1057. # added the end attribute for the query
  1058. colon, start, seq, end = m.groups()
  1059. self._hsp.query = self._hsp.query + seq
  1060. if self._hsp.query_start is None:
  1061. self._hsp.query_start = _safe_int(start)
  1062. # line below added by Yair Benita, Sep 2004.
  1063. # added the end attribute for the query
  1064. self._hsp.query_end = _safe_int(end)
  1065. #Get index for sequence start (regular expression element 3)
  1066. self._query_start_index = m.start(3)
  1067. self._query_len = len(seq)
  1068. def align(self, line):
  1069. seq = line[self._query_start_index:].rstrip()
  1070. if len(seq) < self._query_len:
  1071. # Make sure the alignment is the same length as the query
  1072. seq = seq + ' ' * (self._query_len-len(seq))
  1073. elif len(seq) < self._query_len:
  1074. raise ValueError("Match is longer than the query in line\n%s" \
  1075. % line)
  1076. self._hsp.match = self._hsp.match + seq
  1077. # To match how we do the query, cache the regular expression.
  1078. # Note that the colon is not always present.
  1079. _sbjct_re = re.compile(r"Sbjct(:?) \s*(\d+)\s*(.+) (\d+)")
  1080. def sbjct(self, line):
  1081. m = self._sbjct_re.search(line)
  1082. if m is None:
  1083. raise ValueError("I could not find the sbjct in line\n%s" % line)
  1084. colon, start, seq, end = m.groups()
  1085. #mikep 26/9/00
  1086. #On occasion, there is a blast hit with no subject match
  1087. #so far, it only occurs with 1-line short "matches"
  1088. #I have decided to let these pass as they appear
  1089. if not seq.strip():
  1090. seq = ' ' * self._query_len
  1091. self._hsp.sbjct = self._hsp.sbjct + seq
  1092. if self._hsp.sbjct_start is None:
  1093. self._hsp.sbjct_start = _safe_int(start)
  1094. self._hsp.sbjct_end = _safe_int(end)
  1095. if len(seq) != self._query_len:
  1096. raise ValueError( \
  1097. "QUERY and SBJCT sequence lengths don't match in line\n%s" \
  1098. % line)
  1099. del self._query_start_index # clean up unused variables
  1100. del self._query_len
  1101. def end_hsp(self):
  1102. pass
  1103. class _DatabaseReportConsumer:
  1104. def start_database_report(self):
  1105. self._dr = Record.DatabaseReport()
  1106. def database(self, line):
  1107. m = re.search(r"Database: (.+)$", line)
  1108. if m:
  1109. self._dr.database_name.append(m.group(1))
  1110. elif self._dr.database_name:
  1111. # This must be a continuation of the previous name.
  1112. self._dr.database_name[-1] = "%s%s" % (self._dr.database_name[-1],
  1113. line.strip())
  1114. def posted_date(self, line):
  1115. self._dr.posted_date.append(_re_search(
  1116. r"Posted date:\s*(.+)$", line,
  1117. "I could not find the posted date in line\n%s" % line))
  1118. def num_letters_in_database(self, line):
  1119. letters, = _get_cols(
  1120. line, (-1,), ncols=6, expected={2:"letters", 4:"database:"})
  1121. self._dr.num_letters_in_database.append(_safe_int(letters))
  1122. def num_sequences_in_database(self, line):
  1123. sequences, = _get_cols(
  1124. line, (-1,), ncols=6, expected={2:"sequences", 4:"database:"})
  1125. self._dr.num_sequences_in_database.append(_safe_int(sequences))
  1126. def ka_params(self, line):
  1127. x = line.split()
  1128. self._dr.ka_params = map(_safe_float, x)
  1129. def gapped(self, line):
  1130. self._dr.gapped = 1
  1131. def ka_params_gap(self, line):
  1132. x = line.split()
  1133. self._dr.ka_params_gap = map(_safe_float, x)
  1134. def end_database_report(self):
  1135. pass
  1136. class _ParametersConsumer:
  1137. def start_parameters(self):
  1138. self._params = Record.Parameters()
  1139. def matrix(self, line):
  1140. self._params.matrix = line[8:].rstrip()
  1141. def gap_penalties(self, line):
  1142. x = _get_cols(
  1143. line, (3, 5), ncols=6, expected={2:"Existence:", 4:"Extension:"})
  1144. self._params.gap_penalties = map(_safe_float, x)
  1145. def num_hits(self, line):
  1146. if line.find('1st pass') != -1:
  1147. x, = _get_cols(line, (-4,), ncols=11, expected={2:"Hits"})
  1148. self._params.num_hits = _safe_int(x)
  1149. else:
  1150. x, = _get_cols(line, (-1,), ncols=6, expected={2:"Hits"})
  1151. self._params.num_hits = _safe_int(x)
  1152. def num_sequences(self, line):
  1153. if line.find('1st pass') != -1:
  1154. x, = _get_cols(line, (-4,), ncols=9, expected={2:"Sequences:"})
  1155. self._params.num_sequences = _safe_int(x)
  1156. else:
  1157. x, = _get_cols(line, (-1,), ncols=4, expected={2:"Sequences:"})
  1158. self._params.num_sequences = _safe_int(x)
  1159. def num_extends(self, line):
  1160. if line.find('1st pass') != -1:
  1161. x, = _get_cols(line, (-4,), ncols=9, expected={2:"extensions:"})
  1162. self._params.num_extends = _safe_int(x)
  1163. else:
  1164. x, = _get_cols(line, (-1,), ncols=4, expected={2:"extensions:"})
  1165. self._params.num_extends = _safe_int(x)
  1166. def num_good_extends(self, line):
  1167. if line.find('1st pass') != -1:
  1168. x, = _get_cols(line, (-4,), ncols=10, expected={3:"extensions:"})
  1169. self._params.num_good_extends = _safe_int(x)
  1170. else:
  1171. x, = _get_cols(line, (-1,), ncols=5, expected={3:"extensions:"})
  1172. self._params.num_good_extends = _safe_int(x)
  1173. def num_seqs_better_e(self, line):
  1174. self._params.num_seqs_better_e, = _get_cols(
  1175. line, (-1,), ncols=7, expected={2:"sequences"})
  1176. self._params.num_seqs_better_e = _safe_int(
  1177. self._params.num_seqs_better_e)
  1178. def hsps_no_gap(self, line):
  1179. self._params.hsps_no_gap, = _get_cols(
  1180. line, (-1,), ncols=9, expected={3:"better", 7:"gapping:"})
  1181. self._params.hsps_no_gap = _safe_int(self._params.hsps_no_gap)
  1182. def hsps_prelim_gapped(self, line):
  1183. self._params.hsps_prelim_gapped, = _get_cols(
  1184. line, (-1,), ncols=9, expected={4:"gapped", 6:"prelim"})
  1185. self._params.hsps_prelim_gapped = _safe_int(
  1186. self._params.hsps_prelim_gapped)
  1187. def hsps_prelim_gapped_attempted(self, line):
  1188. self._params.hsps_prelim_gapped_attempted, = _get_cols(
  1189. line, (-1,), ncols=10, expected={4:"attempted", 7:"prelim"})
  1190. self._params.hsps_prelim_gapped_attempted = _safe_int(
  1191. self._params.hsps_prelim_gapped_attempted)
  1192. def hsps_gapped(self, line):
  1193. self._params.hsps_gapped, = _get_cols(
  1194. line, (-1,), ncols=6, expected={3:"gapped"})
  1195. self._params.hsps_gapped = _safe_int(self._params.hsps_gapped)
  1196. def query_length(self, line):
  1197. self._params.query_length, = _get_cols(
  1198. line.lower(), (-1,), ncols=4, expected={0:"length", 2:"query:"})
  1199. self._params.query_length = _safe_int(self._params.query_length)
  1200. def database_length(self, line):
  1201. self._params.database_length, = _get_cols(
  1202. line.lower(), (-1,), ncols=4, expected={0:"length", 2:"database:"})
  1203. self._params.database_length = _safe_int(self._params.database_length)
  1204. def effective_hsp_length(self, line):
  1205. self._params.effective_hsp_length, = _get_cols(
  1206. line, (-1,), ncols=4, expected={1:"HSP", 2:"length:"})
  1207. self._params.effective_hsp_length = _safe_int(
  1208. self._params.effective_hsp_length)
  1209. def effective_query_length(self, line):
  1210. self._params.effective_query_length, = _get_cols(
  1211. line, (-1,), ncols=5, expected={1:"length", 3:"query:"})
  1212. self._params.effective_query_length = _safe_int(
  1213. self._params.effective_query_length)
  1214. def effective_database_length(self, line):
  1215. self._params.effective_database_length, = _get_cols(
  1216. line.lower(), (-1,), ncols=5, expected={1:"length", 3:"database:"})
  1217. self._params.effective_database_length = _safe_int(
  1218. self._params.effective_database_length)
  1219. def effective_search_space(self, line):
  1220. self._params.effective_search_space, = _get_cols(
  1221. line, (-1,), ncols=4, expected={1:"search"})
  1222. self._params.effective_search_space = _safe_int(
  1223. self._params.effective_search_space)
  1224. def effective_search_space_used(self, line):
  1225. self._params.effective_search_space_used, = _get_cols(
  1226. line, (-1,), ncols=5, expected={1:"search", 3:"used:"})
  1227. self._params.effective_search_space_used = _safe_int(
  1228. self._params.effective_search_space_used)
  1229. def frameshift(self, line):
  1230. self._params.frameshift = _get_cols(
  1231. line, (4, 5), ncols=6, expected={0:"frameshift", 2:"decay"})
  1232. def threshold(self, line):
  1233. if line[:2] == "T:":
  1234. #Assume its an old stlye line like "T: 123"
  1235. self._params.threshold, = _get_cols(
  1236. line, (1,), ncols=2, expected={0:"T:"})
  1237. elif line[:28] == "Neighboring words threshold:":
  1238. self._params.threshold, = _get_cols(
  1239. line, (3,), ncols=4, expected={0:"Neighboring", 1:"words", 2:"threshold:"})
  1240. else:
  1241. raise ValueError("Unrecognised threshold line:\n%s" % line)
  1242. self._params.threshold = _safe_int(self._params.threshold)
  1243. def window_size(self, line):
  1244. if line[:2] == "A:":
  1245. self._params.window_size, = _get_cols(
  1246. line, (1,), ncols=2, expected={0:"A:"})
  1247. elif line[:25] == "Window for multiple hits:":
  1248. self._params.window_size, = _get_cols(
  1249. line, (4,), ncols=5, expected={0:"Window", 2:"multiple", 3:"hits:"})
  1250. else:
  1251. raise ValueError("Unrecognised window size line:\n%s" % line)
  1252. self._params.window_size = _safe_int(self._params.window_size)
  1253. def dropoff_1st_pass(self, line):
  1254. score, bits = _re_search(
  1255. r"X1: (\d+) \(\s*([0-9,.]+) bits\)", line,
  1256. "I could not find the dropoff in line\n%s" % line)
  1257. self._params.dropoff_1st_pass = _safe_int(score), _safe_float(bits)
  1258. def gap_x_dropoff(self, line):
  1259. score, bits = _re_search(
  1260. r"X2: (\d+) \(\s*([0-9,.]+) bits\)", line,
  1261. "I could not find the gap dropoff in line\n%s" % line)
  1262. self._params.gap_x_dropoff = _safe_int(score), _safe_float(bits)
  1263. def gap_x_dropoff_final(self, line):
  1264. score, bits = _re_search(
  1265. r"X3: (\d+) \(\s*([0-9,.]+) bits\)", line,
  1266. "I could not find the gap dropoff final in line\n%s" % line)
  1267. self._params.gap_x_dropoff_final = _safe_int(score), _safe_float(bits)
  1268. def gap_trigger(self, line):
  1269. score, bits = _re_search(
  1270. r"S1: (\d+) \(\s*([0-9,.]+) bits\)", line,
  1271. "I could not find the gap trigger in line\n%s" % line)
  1272. self._params.gap_trigger = _safe_int(score), _safe_float(bits)
  1273. def blast_cutoff(self, line):
  1274. score, bits = _re_search(
  1275. r"S2: (\d+) \(\s*([0-9,.]+) bits\)", line,
  1276. "I could not find the blast cutoff in line\n%s" % line)
  1277. self._params.blast_cutoff = _safe_int(score), _safe_float(bits)
  1278. def end_parameters(self):
  1279. pass
  1280. class _BlastConsumer(AbstractConsumer,
  1281. _HeaderConsumer,
  1282. _DescriptionConsumer,
  1283. _AlignmentConsumer,
  1284. _HSPConsumer,
  1285. _DatabaseReportConsumer,
  1286. _ParametersConsumer
  1287. ):
  1288. # This Consumer is inherits from many other consumer classes that handle
  1289. # the actual dirty work. An alternate way to do it is to create objects
  1290. # of those classes and then delegate the parsing tasks to them in a
  1291. # decorator-type pattern. The disadvantage of that is that the method
  1292. # names will need to be resolved in this classes. However, using
  1293. # a decorator will retain more control in this class (which may or
  1294. # may not be a bad thing). In addition, having each sub-consumer as
  1295. # its own object prevents this object's dictionary from being cluttered
  1296. # with members and reduces the chance of member collisions.
  1297. def __init__(self):
  1298. self.data = None
  1299. def round(self, line):
  1300. # Make sure nobody's trying to pass me PSI-BLAST data!
  1301. raise ValueError("This consumer doesn't handle PSI-BLAST data")
  1302. def start_header(self):
  1303. self.data = Record.Blast()
  1304. _HeaderConsumer.start_header(self)
  1305. def end_header(self):
  1306. _HeaderConsumer.end_header(self)
  1307. self.data.__dict__.update(self._header.__dict__)
  1308. def end_descriptions(self):
  1309. self.data.descriptions = self._descriptions
  1310. def end_alignment(self):
  1311. _AlignmentConsumer.end_alignment(self)
  1312. if self._alignment.hsps:
  1313. self.data.alignments.append(self._alignment)
  1314. if self._multiple_alignment.alignment:
  1315. self.data.multiple_alignment = self._multiple_alignment
  1316. def end_hsp(self):
  1317. _HSPConsumer.end_hsp(self)
  1318. try:
  1319. self._alignment.hsps.append(self._hsp)
  1320. except AttributeError:
  1321. raise ValueError("Found an HSP before an alignment")
  1322. def end_database_report(self):
  1323. _DatabaseReportConsumer.end_database_report(self)
  1324. self.data.__dict__.update(self._dr.__dict__)
  1325. def end_parameters(self):
  1326. _ParametersConsumer.end_parameters(self)
  1327. self.data.__dict__.update(self._params.__dict__)
  1328. class _PSIBlastConsumer(AbstractConsumer,
  1329. _HeaderConsumer,
  1330. _DescriptionConsumer,
  1331. _AlignmentConsumer,
  1332. _HSPConsumer,
  1333. _DatabaseReportConsumer,
  1334. _ParametersConsumer
  1335. ):
  1336. def __init__(self):
  1337. self.data = None
  1338. def start_header(self):
  1339. self.data = Record.PSIBlast()
  1340. _HeaderConsumer.start_header(self)
  1341. def end_header(self):
  1342. _HeaderConsumer.end_header(self)
  1343. self.data.__dict__.update(self._header.__dict__)
  1344. def start_descriptions(self):
  1345. self._round = Record.Round()
  1346. self.data.rounds.append(self._round)
  1347. _DescriptionConsumer.start_descriptions(self)
  1348. def end_descriptions(self):
  1349. _DescriptionConsumer.end_descriptions(self)
  1350. self._round.number = self._roundnum
  1351. if self._descriptions:
  1352. self._round.new_seqs.extend(self._descriptions)
  1353. self._round.reused_seqs.extend(self._model_sequences)
  1354. self._round.new_seqs.extend(self._nonmodel_sequences)
  1355. if self._converged:
  1356. self.data.converged = 1
  1357. def end_alignment(self):
  1358. _AlignmentConsumer.end_alignment(self)
  1359. if self._alignment.hsps:
  1360. self._round.alignments.append(self._alignment)
  1361. if self._multiple_alignment:
  1362. self._round.multiple_alignment = self._multiple_alignment
  1363. def end_hsp(self):
  1364. _HSPConsumer.end_hsp(self)
  1365. try:
  1366. self._alignment.hsps.append(self._hsp)
  1367. except AttributeError:
  1368. raise ValueError("Found an HSP before an alignment")
  1369. def end_database_report(self):
  1370. _DatabaseReportConsumer.end_database_report(self)
  1371. self.data.__dict__.update(self._dr.__dict__)
  1372. def end_parameters(self):
  1373. _ParametersConsumer.end_parameters(self)
  1374. self.data.__dict__.update(self._params.__dict__)
  1375. class Iterator(object):
  1376. """Iterates over a file of multiple BLAST results.
  1377. Methods:
  1378. next Return the next record from the stream, or None.
  1379. """
  1380. def __init__(self, handle, parser=None):
  1381. """__init__(self, handle, parser=None)
  1382. Create a new iterator. handle is a file-like object. parser
  1383. is an optional Parser object to change the results into another form.
  1384. If set to None, then the raw contents of the file will be returned.
  1385. """
  1386. try:
  1387. handle.readline
  1388. except AttributeError:
  1389. raise ValueError(
  1390. "I expected a file handle or file-like object, got %s"
  1391. % type(handle))
  1392. self._uhandle = File.UndoHandle(handle)
  1393. self._parser = parser
  1394. self._header = []
  1395. def next(self):
  1396. """next(self) -> object
  1397. Return the next Blast record from the file. If no more records,
  1398. return None.
  1399. """
  1400. lines = []
  1401. query = False
  1402. while 1:
  1403. line = self._uhandle.readline()
  1404. if not line:
  1405. break
  1406. # If I've reached the next one, then put the line back and stop.
  1407. if lines and (line.startswith('BLAST')
  1408. or line.startswith('BLAST', 1)
  1409. or line.startswith('<?xml ')):
  1410. self._uhandle.saveline(line)
  1411. break
  1412. # New style files ommit the BLAST line to mark a new query:
  1413. if line.startswith("Query="):
  1414. if not query:
  1415. if not self._header:
  1416. self._header = lines[:]
  1417. query = True
  1418. else:
  1419. #Start of another record
  1420. self._uhandle.saveline(line)
  1421. break
  1422. lines.append(line)
  1423. if query and "BLAST" not in lines[0]:
  1424. #Cheat and re-insert the header
  1425. #print "-"*50
  1426. #print "".join(self._header)
  1427. #print "-"*50
  1428. #print "".join(lines)
  1429. #print "-"*50
  1430. lines = self._header + lines
  1431. if not lines:
  1432. return None
  1433. data = ''.join(lines)
  1434. if self._parser is not None:
  1435. return self._parser.parse(StringIO.StringIO(data))
  1436. return data
  1437. def __iter__(self):
  1438. return iter(self.next, None)
  1439. def blastall(blastcmd, program, database, infile, align_view='7', **keywds):
  1440. """Execute and retrieve data from standalone BLASTPALL as handles (OBSOLETE).
  1441. NOTE - This function is obsolete, you are encouraged to the command
  1442. line wrapper Bio.Blast.Applications.BlastallCommandline instead.
  1443. Execute and retrieve data from blastall. blastcmd is the command
  1444. used to launch the 'blastall' executable. program is the blast program
  1445. to use, e.g. 'blastp', 'blastn', etc. database is the path to the database
  1446. to search against. infile is the path to the file containing
  1447. the sequence to search with.
  1448. The return values are two handles, for standard output and standard error.
  1449. You may pass more parameters to **keywds to change the behavior of
  1450. the search. Otherwise, optional values will be chosen by blastall.
  1451. The Blast output is by default in XML format. Use the align_view keyword
  1452. for output in a different format.
  1453. Scoring
  1454. matrix Matrix to use.
  1455. gap_open Gap open penalty.
  1456. gap_extend Gap extension penalty.
  1457. nuc_match Nucleotide match reward. (BLASTN)
  1458. nuc_mismatch Nucleotide mismatch penalty. (BLASTN)
  1459. query_genetic_code Genetic code for Query.
  1460. db_genetic_code Genetic code for database. (TBLAST[NX])
  1461. Algorithm
  1462. gapped Whether to do a gapped alignment. T/F (not for TBLASTX)
  1463. expectation Expectation value cutoff.
  1464. wordsize Word size.
  1465. strands Query strands to search against database.([T]BLAST[NX])
  1466. keep_hits Number of best hits from a region to keep.
  1467. xdrop Dropoff value (bits) for gapped alignments.
  1468. hit_extend Threshold for extending hits.
  1469. region_length Length of region used to judge hits.
  1470. db_length Effective database length.
  1471. search_length Effective length of search space.
  1472. Processing
  1473. filter Filter query sequence for low complexity (with SEG)? T/F
  1474. believe_query Believe the query defline. T/F
  1475. restrict_gi Restrict search to these GI's.
  1476. nprocessors Number of processors to use.
  1477. oldengine Force use of old engine T/F
  1478. Formatting
  1479. html Produce HTML output? T/F
  1480. descriptions Number of one-line descriptions.
  1481. alignments Number of alignments.
  1482. align_view Alignment view. Integer 0-11,
  1483. passed as a string or integer.
  1484. show_gi Show GI's in deflines? T/F
  1485. seqalign_file seqalign file to output.
  1486. outfile Output file for report. Filename to write to, if
  1487. ommitted standard output is used (which you can access
  1488. from the returned handles).
  1489. """
  1490. _security_check_parameters(keywds)
  1491. att2param = {
  1492. 'matrix' : '-M',
  1493. 'gap_open' : '-G',
  1494. 'gap_extend' : '-E',
  1495. 'nuc_match' : '-r',
  1496. 'nuc_mismatch' : '-q',
  1497. 'query_genetic_code' : '-Q',
  1498. 'db_genetic_code' : '-D',
  1499. 'gapped' : '-g',
  1500. 'expectation' : '-e',
  1501. 'wordsize' : '-W',
  1502. 'strands' : '-S',
  1503. 'keep_hits' : '-K',
  1504. 'xdrop' : '-X',
  1505. 'hit_extend' : '-f',
  1506. 'region_length' : '-L',
  1507. 'db_length' : '-z',
  1508. 'search_length' : '-Y',
  1509. 'program' : '-p',
  1510. 'database' : '-d',
  1511. 'infile' : '-i',
  1512. 'filter' : '-F',
  1513. 'believe_query' : '-J',
  1514. 'restrict_gi' : '-l',
  1515. 'nprocessors' : '-a',
  1516. 'oldengine' : '-V',
  1517. 'html' : '-T',
  1518. 'descriptions' : '-v',
  1519. 'alignments' : '-b',
  1520. 'align_view' : '-m',
  1521. 'show_gi' : '-I',
  1522. 'seqalign_file' : '-O',
  1523. 'outfile' : '-o',
  1524. }
  1525. import warnings
  1526. warnings.warn("This function is obsolete, you are encouraged to the command line wrapper Bio.Blast.Applications.BlastallCommandline instead.", PendingDeprecationWarning)
  1527. from Applications import BlastallCommandline
  1528. cline = BlastallCommandline(blastcmd)
  1529. cline.set_parameter(att2param['program'], program)
  1530. cline.set_parameter(att2param['database'], database)
  1531. cline.set_parameter(att2param['infile'], infile)
  1532. cline.set_parameter(att2param['align_view'], str(align_view))
  1533. for key, value in keywds.iteritems():
  1534. cline.set_parameter(att2param[key], str(value))
  1535. return _invoke_blast(cline)
  1536. def blastpgp(blastcmd, database, infile, align_view='7', **keywds):
  1537. """Execute and retrieve data from standalone BLASTPGP as handles (OBSOLETE).
  1538. NOTE - This function is obsolete, you are encouraged to the command
  1539. line wrapper Bio.Blast.Applications.BlastpgpCommandline instead.
  1540. Execute and retrieve data from blastpgp. blastcmd is the command
  1541. used to launch the 'blastpgp' executable. database is the path to the
  1542. database to search against. infile is the path to the file containing
  1543. the sequence to search with.
  1544. The return values are two handles, for standard output and standard error.
  1545. You may pass more parameters to **keywds to change the behavior of
  1546. the search. Otherwise, optional values will be chosen by blastpgp.
  1547. The Blast output is by default in XML format. Use the align_view keyword
  1548. for output in a different format.
  1549. Scoring
  1550. matrix Matrix to use.
  1551. gap_open Gap open penalty.
  1552. gap_extend Gap extension penalty.
  1553. window_size Multiple hits window size.
  1554. npasses Number of passes.
  1555. passes Hits/passes. Integer 0-2.
  1556. Algorithm
  1557. gapped Whether to do a gapped alignment. T/F
  1558. expectation Expectation value cutoff.
  1559. wordsize Word size.
  1560. keep_hits Number of beset hits from a region to keep.
  1561. xdrop Dropoff value (bits) for gapped alignments.
  1562. hit_extend Threshold for extending hits.
  1563. region_length Length of region used to judge hits.
  1564. db_length Effective database length.
  1565. search_length Effective length of search space.
  1566. nbits_gapping Number of bits to trigger gapping.
  1567. pseudocounts Pseudocounts constants for multiple passes.
  1568. xdrop_final X dropoff for final gapped alignment.
  1569. xdrop_extension Dropoff for blast extensions.
  1570. model_threshold E-value threshold to include in multipass model.
  1571. required_start Start of required region in query.
  1572. required_end End of required region in query.
  1573. Processing
  1574. XXX should document default values
  1575. program The blast program to use. (PHI-BLAST)
  1576. filter Filter query sequence for low complexity (with SEG)? T/F
  1577. believe_query Believe the query defline? T/F
  1578. nprocessors Number of processors to use.
  1579. Formatting
  1580. html Produce HTML output? T/F
  1581. descriptions Number of one-line descriptions.
  1582. alignments Number of alignments.
  1583. align_view Alignment view. Integer 0-11,
  1584. passed as a string or integer.
  1585. show_gi Show GI's in deflines? T/F
  1586. seqalign_file seqalign file to output.
  1587. align_outfile Output file for alignment.
  1588. checkpoint_outfile Output file for PSI-BLAST checkpointing.
  1589. restart_infile Input file for PSI-BLAST restart.
  1590. hit_infile Hit file for PHI-BLAST.
  1591. matrix_outfile Output file for PSI-BLAST matrix in ASCII.
  1592. align_outfile Output file for alignment. Filename to write to, if
  1593. ommitted standard output is used (which you can access
  1594. from the returned handles).
  1595. align_infile Input alignment file for PSI-BLAST restart.
  1596. """
  1597. import warnings
  1598. warnings.warn("This function is obsolete, you are encouraged to the command line wrapper Bio.Blast.Applications.BlastpgpCommandline instead.", PendingDeprecationWarning)
  1599. _security_check_parameters(keywds)
  1600. att2param = {
  1601. 'matrix' : '-M',
  1602. 'gap_open' : '-G',
  1603. 'gap_extend' : '-E',
  1604. 'window_size' : '-A',
  1605. 'npasses' : '-j',
  1606. 'passes' : '-P',
  1607. 'gapped' : '-g',
  1608. 'expectation' : '-e',
  1609. 'wordsize' : '-W',
  1610. 'keep_hits' : '-K',
  1611. 'xdrop' : '-X',
  1612. 'hit_extend' : '-f',
  1613. 'region_length' : '-L',
  1614. 'db_length' : '-Z',
  1615. 'search_length' : '-Y',
  1616. 'nbits_gapping' : '-N',
  1617. 'pseudocounts' : '-c',
  1618. 'xdrop_final' : '-Z',
  1619. 'xdrop_extension' : '-y',
  1620. 'model_threshold' : '-h',
  1621. 'required_start' : '-S',
  1622. 'required_end' : '-H',
  1623. 'program' : '-p',
  1624. 'database' : '-d',
  1625. 'infile' : '-i',
  1626. 'filter' : '-F',
  1627. 'believe_query' : '-J',
  1628. 'nprocessors' : '-a',
  1629. 'html' : '-T',
  1630. 'descriptions' : '-v',
  1631. 'alignments' : '-b',
  1632. 'align_view' : '-m',
  1633. 'show_gi' : '-I',
  1634. 'seqalign_file' : '-O',
  1635. 'align_outfile' : '-o',
  1636. 'checkpoint_outfile' : '-C',
  1637. 'restart_infile' : '-R',
  1638. 'hit_infile' : '-k',
  1639. 'matrix_outfile' : '-Q',
  1640. 'align_infile' : '-B',
  1641. }
  1642. from Applications import BlastpgpCommandline
  1643. cline = BlastpgpCommandline(blastcmd)
  1644. cline.set_parameter(att2param['database'], database)
  1645. cline.set_parameter(att2param['infile'], infile)
  1646. cline.set_parameter(att2param['align_view'], str(align_view))
  1647. for key, value in keywds.iteritems():
  1648. cline.set_parameter(att2param[key], str(value))
  1649. return _invoke_blast(cline)
  1650. def rpsblast(blastcmd, database, infile, align_view="7", **keywds):
  1651. """Execute and retrieve data from standalone RPS-BLAST as handles (OBSOLETE).
  1652. NOTE - This function is obsolete, you are encouraged to the command
  1653. line wrapper Bio.Blast.Applications.RpsBlastCommandline instead.
  1654. Execute and retrieve data from standalone RPS-BLAST. blastcmd is the
  1655. command used to launch the 'rpsblast' executable. database is the path
  1656. to the database to search against. infile is the path to the file
  1657. containing the sequence to search with.
  1658. The return values are two handles, for standard output and standard error.
  1659. You may pass more parameters to **keywds to change the behavior of
  1660. the search. Otherwise, optional values will be chosen by rpsblast.
  1661. Please note that this function will give XML output by default, by
  1662. setting align_view to seven (i.e. command line option -m 7).
  1663. You should use the NCBIXML.parse() function to read the resulting output.
  1664. This is because NCBIStandalone.BlastParser() does not understand the
  1665. plain text output format from rpsblast.
  1666. WARNING - The following text and associated parameter handling has not
  1667. received extensive testing. Please report any errors we might have made...
  1668. Algorithm/Scoring
  1669. gapped Whether to do a gapped alignment. T/F
  1670. multihit 0 for multiple hit (default), 1 for single hit
  1671. expectation Expectation value cutoff.
  1672. range_restriction Range restriction on query sequence (Format: start,stop) blastp only
  1673. 0 in 'start' refers to the beginning of the sequence
  1674. 0 in 'stop' refers to the end of the sequence
  1675. Default = 0,0
  1676. xdrop Dropoff value (bits) for gapped alignments.
  1677. xdrop_final X dropoff for final gapped alignment (in bits).
  1678. xdrop_extension Dropoff for blast extensions (in bits).
  1679. search_length Effective length of search space.
  1680. nbits_gapping Number of bits to trigger gapping.
  1681. protein Query sequence is protein. T/F
  1682. db_length Effective database length.
  1683. Processing
  1684. filter Filter query sequence for low complexity? T/F
  1685. case_filter Use lower case filtering of FASTA sequence T/F, default F
  1686. believe_query Believe the query defline. T/F
  1687. nprocessors Number of processors to use.
  1688. logfile Name of log file to use, default rpsblast.log
  1689. Formatting
  1690. html Produce HTML output? T/F
  1691. descriptions Number of one-line descriptions.
  1692. alignments Number of alignments.
  1693. align_view Alignment view. Integer 0-11,
  1694. passed as a string or integer.
  1695. show_gi Show GI's in deflines? T/F
  1696. seqalign_file seqalign file to output.
  1697. align_outfile Output file for alignment. Filename to write to, if
  1698. ommitted standard output is used (which you can access
  1699. from the returned handles).
  1700. """
  1701. import warnings
  1702. warnings.warn("This function is obsolete, you are encouraged to the command line wrapper Bio.Blast.Applications.BlastrpsCommandline instead.", PendingDeprecationWarning)
  1703. _security_check_parameters(keywds)
  1704. att2param = {
  1705. 'multihit' : '-P',
  1706. 'gapped' : '-g',
  1707. 'expectation' : '-e',
  1708. 'range_restriction' : '-L',
  1709. 'xdrop' : '-X',
  1710. 'xdrop_final' : '-Z',
  1711. 'xdrop_extension' : '-y',
  1712. 'search_length' : '-Y',
  1713. 'nbits_gapping' : '-N',
  1714. 'protein' : '-p',
  1715. 'db_length' : '-z',
  1716. 'database' : '-d',
  1717. 'infile' : '-i',
  1718. 'filter' : '-F',
  1719. 'case_filter' : '-U',
  1720. 'believe_query' : '-J',
  1721. 'nprocessors' : '-a',
  1722. 'logfile' : '-l',
  1723. 'html' : '-T',
  1724. 'descriptions' : '-v',
  1725. 'alignments' : '-b',
  1726. 'align_view' : '-m',
  1727. 'show_gi' : '-I',
  1728. 'seqalign_file' : '-O',
  1729. 'align_outfile' : '-o',
  1730. }
  1731. from Applications import RpsBlastCommandline
  1732. cline = RpsBlastCommandline(blastcmd)
  1733. cline.set_parameter(att2param['database'], database)
  1734. cline.set_parameter(att2param['infile'], infile)
  1735. cline.set_parameter(att2param['align_view'], str(align_view))
  1736. for key, value in keywds.iteritems():
  1737. cline.set_parameter(att2param[key], str(value))
  1738. return _invoke_blast(cline)
  1739. def _re_search(regex, line, error_msg):
  1740. m = re.search(regex, line)
  1741. if not m:
  1742. raise ValueError(error_msg)
  1743. return m.groups()
  1744. def _get_cols(line, cols_to_get, ncols=None, expected={}):
  1745. cols = line.split()
  1746. # Check to make sure number of columns is correct
  1747. if ncols is not None and len(cols) != ncols:
  1748. raise ValueError("I expected %d columns (got %d) in line\n%s" \
  1749. % (ncols, len(cols), line))
  1750. # Check to make sure columns contain the correct data
  1751. for k in expected:
  1752. if cols[k] != expected[k]:
  1753. raise ValueError("I expected '%s' in column %d in line\n%s" \
  1754. % (expected[k], k, line))
  1755. # Construct the answer tuple
  1756. results = []
  1757. for c in cols_to_get:
  1758. results.append(cols[c])
  1759. return tuple(results)
  1760. def _safe_int(str):
  1761. try:
  1762. return int(str)
  1763. except ValueError:
  1764. # Something went wrong. Try to clean up the string.
  1765. # Remove all commas from the string
  1766. str = str.replace(',', '')
  1767. # try again after removing commas.
  1768. # Note int() will return a long rather than overflow
  1769. try:
  1770. return int(str)
  1771. except ValueError:
  1772. pass
  1773. # Call float to handle things like "54.3", note could lose precision, e.g.
  1774. # >>> int("5399354557888517312")
  1775. # 5399354557888517312
  1776. # >>> int(float("5399354557888517312"))
  1777. # 5399354557888517120
  1778. return int(float(str))
  1779. def _safe_float(str):
  1780. # Thomas Rosleff Soerensen (rosleff@mpiz-koeln.mpg.de) noted that
  1781. # float('e-172') does not produce an error on his platform. Thus,
  1782. # we need to check the string for this condition.
  1783. # Sometimes BLAST leaves of the '1' in front of an exponent.
  1784. if str and str[0] in ['E', 'e']:
  1785. str = '1' + str
  1786. try:
  1787. return float(str)
  1788. except ValueError:
  1789. # Remove all commas from the string
  1790. str = str.replace(',', '')
  1791. # try again.
  1792. return float(str)
  1793. def _invoke_blast(cline):
  1794. """Start BLAST and returns handles for stdout and stderr (PRIVATE).
  1795. Expects a command line wrapper object from Bio.Blast.Applications
  1796. """
  1797. import subprocess, sys
  1798. blast_cmd = cline.program_name
  1799. if not os.path.exists(blast_cmd):
  1800. raise ValueError("BLAST executable does not exist at %s" % blast_cmd)
  1801. #We don't need to supply any piped input, but we setup the
  1802. #standard input pipe anyway as a work around for a python
  1803. #bug if this is called from a Windows GUI program. For
  1804. #details, see http://bugs.python.org/issue1124861
  1805. blast_process = subprocess.Popen(str(cline),
  1806. stdin=subprocess.PIPE,
  1807. stdout=subprocess.PIPE,
  1808. stderr=subprocess.PIPE,
  1809. universal_newlines=True,
  1810. shell=(sys.platform!="win32"))
  1811. blast_process.stdin.close()
  1812. return blast_process.stdout, blast_process.stderr
  1813. def _security_check_parameters(param_dict):
  1814. """Look for any attempt to insert a command into a parameter.
  1815. e.g. blastall(..., matrix='IDENTITY -F 0; rm -rf /etc/passwd')
  1816. Looks for ";" or "&&" in the strings (Unix and Windows syntax
  1817. for appending a command line), or ">", "<" or "|" (redirection)
  1818. and if any are found raises an exception.
  1819. """
  1820. for key, value in param_dict.iteritems():
  1821. str_value = str(value) # Could easily be an int or a float
  1822. for bad_str in [";", "&&", ">", "<", "|"]:
  1823. if bad_str in str_value:
  1824. raise ValueError("Rejecting suspicious argument for %s" % key)
  1825. class _BlastErrorConsumer(_BlastConsumer):
  1826. def __init__(self):
  1827. _BlastConsumer.__init__(self)
  1828. def noevent(self, line):
  1829. if line.find("Query must be at least wordsize") != -1:
  1830. raise ShortQueryBlastError("Query must be at least wordsize")
  1831. # Now pass the line back up to the superclass.
  1832. method = getattr(_BlastConsumer, 'noevent',
  1833. _BlastConsumer.__getattr__(self, 'noevent'))
  1834. method(line)
  1835. class BlastErrorParser(AbstractParser):
  1836. """Attempt to catch and diagnose BLAST errors while parsing.
  1837. This utilizes the BlastParser module but adds an additional layer
  1838. of complexity on top of it by attempting to diagnose ValueErrors
  1839. that may actually indicate problems during BLAST parsing.
  1840. Current BLAST problems this detects are:
  1841. o LowQualityBlastError - When BLASTing really low quality sequences
  1842. (ie. some GenBank entries which are just short streches of a single
  1843. nucleotide), BLAST will report an error with the sequence and be
  1844. unable to search with this. This will lead to a badly formatted
  1845. BLAST report that the parsers choke on. The parser will convert the
  1846. ValueError to a LowQualityBlastError and attempt to provide useful
  1847. information.
  1848. """
  1849. def __init__(self, bad_report_handle = None):
  1850. """Initialize a parser that tries to catch BlastErrors.
  1851. Arguments:
  1852. o bad_report_handle - An optional argument specifying a handle
  1853. where bad reports should be sent. This would allow you to save
  1854. all of the bad reports to a file, for instance. If no handle
  1855. is specified, the bad reports will not be saved.
  1856. """
  1857. self._bad_report_handle = bad_report_handle
  1858. #self._b_parser = BlastParser()
  1859. self._scanner = _Scanner()
  1860. self._consumer = _BlastErrorConsumer()
  1861. def parse(self, handle):
  1862. """Parse a handle, attempting to diagnose errors.
  1863. """
  1864. results = handle.read()
  1865. try:
  1866. self._scanner.feed(StringIO.StringIO(results), self._consumer)
  1867. except ValueError, msg:
  1868. # if we have a bad_report_file, save the info to it first
  1869. if self._bad_report_handle:
  1870. # send the info to the error handle
  1871. self._bad_report_handle.write(results)
  1872. # now we want to try and diagnose the error
  1873. self._diagnose_error(
  1874. StringIO.StringIO(results), self._consumer.data)
  1875. # if we got here we can't figure out the problem
  1876. # so we should pass along the syntax error we got
  1877. raise
  1878. return self._consumer.data
  1879. def _diagnose_error(self, handle, data_record):
  1880. """Attempt to diagnose an error in the passed handle.
  1881. Arguments:
  1882. o handle - The handle potentially containing the error
  1883. o data_record - The data record partially created by the consumer.
  1884. """
  1885. line = handle.readline()
  1886. while line:
  1887. # 'Searchingdone' instead of 'Searching......done' seems
  1888. # to indicate a failure to perform the BLAST due to
  1889. # low quality sequence
  1890. if line.startswith('Searchingdone'):
  1891. raise LowQualityBlastError("Blast failure occured on query: ",
  1892. data_record.query)
  1893. line = handle.readline()