PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Tests/test_Emboss.py

https://bitbucket.org/christophchamp/biopython
Python | 913 lines | 844 code | 21 blank | 48 comment | 49 complexity | 9e9343ba7aaea26df4aaf888fb26ae31 MD5 | raw file
  1. # Copyright 2009 by Peter Cock. 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. """Runs a few EMBOSS tools to check our wrappers and parsers."""
  6. import os
  7. import sys
  8. import unittest
  9. import subprocess
  10. from StringIO import StringIO
  11. from Bio.Emboss.Applications import WaterCommandline, NeedleCommandline
  12. from Bio.Emboss.Applications import SeqretCommandline, SeqmatchallCommandline
  13. from Bio import SeqIO
  14. from Bio import AlignIO
  15. from Bio import MissingExternalDependencyError
  16. from Bio.Alphabet import generic_protein, generic_dna, generic_nucleotide
  17. from Bio.Seq import Seq, translate
  18. from Bio.SeqRecord import SeqRecord
  19. #from Bio.Data.IUPACData import ambiguous_dna_letters
  20. #################################################################
  21. #Try to avoid problems when the OS is in another language
  22. os.environ['LANG'] = 'C'
  23. exes_wanted = ["water", "needle", "seqret", "transeq", "seqmatchall",
  24. "embossversion"]
  25. exes = dict() #Dictionary mapping from names to exe locations
  26. if "EMBOSS_ROOT" in os.environ:
  27. #Windows default installation path is C:\mEMBOSS which contains the exes.
  28. #EMBOSS also sets an environment variable which we will check for.
  29. path = os.environ["EMBOSS_ROOT"]
  30. if os.path.isdir(path):
  31. for name in exes_wanted:
  32. if os.path.isfile(os.path.join(path, name+".exe")):
  33. exes[name] = os.path.join(path, name+".exe")
  34. del path, name
  35. if sys.platform!="win32":
  36. import commands
  37. for name in exes_wanted:
  38. #This will "just work" if installed on the path as normal on Unix
  39. output = commands.getoutput("%s -help" % name)
  40. if "not found" not in output and "not recognized" not in output:
  41. exes[name] = name
  42. del output
  43. del name
  44. if len(exes) < len(exes_wanted):
  45. raise MissingExternalDependencyError(\
  46. "Install EMBOSS if you want to use Bio.Emboss.")
  47. def get_emboss_version():
  48. """Returns a tuple of three ints, e.g. (6,1,0)"""
  49. #Windows and Unix versions of EMBOSS seem to differ in
  50. #which lines go to stdout and stderr - so merge them.
  51. child = subprocess.Popen(exes["embossversion"],
  52. stdout=subprocess.PIPE,
  53. stderr=subprocess.STDOUT,
  54. universal_newlines=True,
  55. shell=(sys.platform!="win32"))
  56. stdout, stderr = child.communicate()
  57. child.stdout.close() #This is both stdout and stderr
  58. del child
  59. assert stderr is None #Send to stdout instead
  60. for line in stdout.split("\n"):
  61. if line.strip()=="Reports the current EMBOSS version number":
  62. pass
  63. elif line.startswith("Writes the current EMBOSS version number"):
  64. pass
  65. elif line.count(".")==2:
  66. return tuple(int(v) for v in line.strip().split("."))
  67. elif line.count(".")==3:
  68. #e.g. I installed mEMBOSS-6.2.0.1-setup.exe
  69. #which reports 6.2.0.1 - for this return (6,2,0)
  70. return tuple(int(v) for v in line.strip().split("."))[:3]
  71. else:
  72. #Either we can't understand the output, or this is really
  73. #an error message not caught earlier (e.g. not in English)
  74. raise MissingExternalDependencyError(\
  75. "Install EMBOSS if you want to use Bio.Emboss (%s)." \
  76. % line)
  77. #To avoid confusing known errors from old versions of EMBOSS ...
  78. emboss_version = get_emboss_version()
  79. if emboss_version < (6,1,0):
  80. raise MissingExternalDependencyError(\
  81. "Test requires EMBOSS 6.1.0 patch 3 or later.")
  82. #################################################################
  83. #Top level function as this makes it easier to use for debugging:
  84. def emboss_convert(filename, old_format, new_format):
  85. """Run seqret, returns handle."""
  86. #Setup, this assumes for all the format names used
  87. #Biopython and EMBOSS names are consistent!
  88. cline = SeqretCommandline(exes["seqret"],
  89. sequence = filename,
  90. sformat = old_format,
  91. osformat = new_format,
  92. auto = True, #no prompting
  93. stdout = True)
  94. #Run the tool,
  95. child = subprocess.Popen(str(cline),
  96. stdin=subprocess.PIPE,
  97. stdout=subprocess.PIPE,
  98. stderr=subprocess.PIPE,
  99. universal_newlines=True,
  100. shell=(sys.platform!="win32"))
  101. child.stdin.close()
  102. child.stderr.close()
  103. return child.stdout
  104. #Top level function as this makes it easier to use for debugging:
  105. def emboss_piped_SeqIO_convert(records, old_format, new_format):
  106. """Run seqret, returns records (as a generator)."""
  107. #Setup, this assumes for all the format names used
  108. #Biopython and EMBOSS names are consistent!
  109. cline = SeqretCommandline(exes["seqret"],
  110. sformat = old_format,
  111. osformat = new_format,
  112. auto = True, #no prompting
  113. filter = True)
  114. #Run the tool,
  115. child = subprocess.Popen(str(cline),
  116. stdin=subprocess.PIPE,
  117. stdout=subprocess.PIPE,
  118. stderr=subprocess.PIPE,
  119. universal_newlines=True,
  120. shell=(sys.platform!="win32"))
  121. SeqIO.write(records, child.stdin, old_format)
  122. child.stdin.close()
  123. child.stderr.close()
  124. #TODO - Is there a nice way to return an interator AND
  125. #automatically close the handle?
  126. records = list(SeqIO.parse(child.stdout, new_format))
  127. child.stdout.close()
  128. return records
  129. #Top level function as this makes it easier to use for debugging:
  130. def emboss_piped_AlignIO_convert(alignments, old_format, new_format):
  131. """Run seqret, returns alignments (as a generator)."""
  132. #Setup, this assumes for all the format names used
  133. #Biopython and EMBOSS names are consistent!
  134. cline = SeqretCommandline(exes["seqret"],
  135. sformat = old_format,
  136. osformat = new_format,
  137. auto = True, #no prompting
  138. filter = True)
  139. #Run the tool,
  140. child = subprocess.Popen(str(cline),
  141. stdin=subprocess.PIPE,
  142. stdout=subprocess.PIPE,
  143. stderr=subprocess.PIPE,
  144. universal_newlines=True,
  145. shell=(sys.platform!="win32"))
  146. try:
  147. AlignIO.write(alignments, child.stdin, old_format)
  148. except Exception, err:
  149. child.stdin.close()
  150. child.stderr.close()
  151. child.stdout.close()
  152. raise
  153. child.stdin.close()
  154. child.stderr.close()
  155. #TODO - Is there a nice way to return an interator AND
  156. #automatically close the handle?
  157. try:
  158. aligns = list(AlignIO.parse(child.stdout, new_format))
  159. except Exception, err:
  160. child.stdout.close()
  161. raise
  162. child.stdout.close()
  163. return aligns
  164. #Top level function as this makes it easier to use for debugging:
  165. def compare_records(old_list, new_list):
  166. """Check two lists of SeqRecords agree, raises a ValueError if mismatch."""
  167. if len(old_list) != len(new_list):
  168. raise ValueError("%i vs %i records" % (len(old_list), len(new_list)))
  169. for old, new in zip(old_list, new_list):
  170. #Note the name matching is a bit fuzzy, e.g. truncation and
  171. #no spaces in PHYLIP files.
  172. if old.id != new.id and old.name != new.name \
  173. and (old.id not in new.id) and (new.id not in old.id) \
  174. and (old.id.replace(" ","_") != new.id.replace(" ","_")):
  175. raise ValueError("'%s' or '%s' vs '%s' or '%s' records" \
  176. % (old.id, old.name, new.id, new.name))
  177. if len(old.seq) != len(new.seq):
  178. raise ValueError("%i vs %i" % (len(old.seq), len(new.seq)))
  179. if str(old.seq).upper() != str(new.seq).upper():
  180. if str(old.seq).replace("X","N")==str(new.seq) :
  181. raise ValueError("X -> N (protein forced into nucleotide?)")
  182. if len(old.seq) < 200:
  183. raise ValueError("'%s' vs '%s'" % (old.seq, new.seq))
  184. else:
  185. raise ValueError("'%s...%s' vs '%s...%s'" \
  186. % (old.seq[:60], old.seq[-10:],
  187. new.seq[:60], new.seq[-10:]))
  188. if old.features and new.features \
  189. and len(old.features) != len(new.features):
  190. raise ValueError("%i vs %i features" \
  191. % (len(old.features, len(new.features))))
  192. #TODO - check annotation
  193. return True
  194. #Top level function as this makes it easier to use for debugging:
  195. def compare_alignments(old_list, new_list):
  196. """Check two lists of Alignments agree, raises a ValueError if mismatch."""
  197. if len(old_list) != len(new_list):
  198. raise ValueError("%i vs %i alignments" % (len(old_list), len(new_list)))
  199. for old, new in zip(old_list, new_list):
  200. if len(old) != len(new):
  201. raise ValueError("Alignment with %i vs %i records" \
  202. % (len(old), len(new)))
  203. compare_records(old,new)
  204. return True
  205. class SeqRetSeqIOTests(unittest.TestCase):
  206. """Check EMBOSS seqret against Bio.SeqIO for converting files."""
  207. def tearDown(self):
  208. clean_up()
  209. def check_SeqIO_to_EMBOSS(self, in_filename, in_format, skip_formats=[],
  210. alphabet=None):
  211. """Can Bio.SeqIO write files seqret can read back?"""
  212. if alphabet:
  213. records = list(SeqIO.parse(in_filename, in_format, alphabet))
  214. else:
  215. records = list(SeqIO.parse(in_filename, in_format))
  216. for temp_format in ["genbank","embl","fasta"]:
  217. if temp_format in skip_formats:
  218. continue
  219. new_records = list(emboss_piped_SeqIO_convert(records, temp_format, "fasta"))
  220. try:
  221. self.assertTrue(compare_records(records, new_records))
  222. except ValueError, err:
  223. raise ValueError("Disagree on file %s %s in %s format: %s" \
  224. % (in_format, in_filename, temp_format, err))
  225. def check_EMBOSS_to_SeqIO(self, filename, old_format,
  226. skip_formats=[]):
  227. """Can Bio.SeqIO read seqret's conversion of the file?"""
  228. #TODO: Why can't we read EMBOSS's swiss output?
  229. self.assertTrue(os.path.isfile(filename))
  230. old_records = list(SeqIO.parse(filename, old_format))
  231. for new_format in ["genbank","fasta","pir","embl", "ig"]:
  232. if new_format in skip_formats:
  233. continue
  234. handle = emboss_convert(filename, old_format, new_format)
  235. new_records = list(SeqIO.parse(handle, new_format))
  236. handle.close()
  237. try:
  238. self.assertTrue(compare_records(old_records, new_records))
  239. except ValueError, err:
  240. raise ValueError("Disagree on %s file %s in %s format: %s" \
  241. % (old_format, filename, new_format, err))
  242. def check_SeqIO_with_EMBOSS(self, filename, old_format, skip_formats=[],
  243. alphabet=None):
  244. #Check EMBOSS can read Bio.SeqIO output...
  245. self.check_SeqIO_to_EMBOSS(filename, old_format, skip_formats,
  246. alphabet)
  247. #Check Bio.SeqIO can read EMBOSS seqret output...
  248. self.check_EMBOSS_to_SeqIO(filename, old_format, skip_formats)
  249. def test_abi(self):
  250. """SeqIO agrees with EMBOSS' Abi to FASTQ conversion."""
  251. #This lets use check the id, sequence, and quality scores
  252. for filename in ["Abi/3730.ab1", "Abi/empty.ab1"]:
  253. old = SeqIO.read(filename, "abi")
  254. handle = emboss_convert(filename, "abi", "fastq-sanger")
  255. new = SeqIO.read(handle, "fastq-sanger")
  256. handle.close()
  257. if emboss_version == (6,4,0) and new.id == "EMBOSS_001":
  258. #Avoid bug in EMBOSS 6.4.0 (patch forthcoming)
  259. pass
  260. else:
  261. self.assertEqual(old.id, new.id)
  262. self.assertEqual(str(old.seq), str(new.seq))
  263. if emboss_version < (6,3,0) and new.letter_annotations["phred_quality"] == [1]*len(old):
  264. #Apparent bug in EMBOSS 6.2.0.1 on Windows
  265. pass
  266. else:
  267. self.assertEqual(old.letter_annotations, new.letter_annotations)
  268. def test_genbank(self):
  269. """SeqIO & EMBOSS reading each other's conversions of a GenBank file."""
  270. self.check_SeqIO_with_EMBOSS("GenBank/cor6_6.gb", "genbank")
  271. def test_genbank2(self):
  272. """SeqIO & EMBOSS reading each other's conversions of another GenBank file."""
  273. self.check_SeqIO_with_EMBOSS("GenBank/NC_000932.gb", "genbank")
  274. def test_embl(self):
  275. """SeqIO & EMBOSS reading each other's conversions of an EMBL file."""
  276. self.check_SeqIO_with_EMBOSS("EMBL/U87107.embl", "embl")
  277. def test_ig(self):
  278. """SeqIO & EMBOSS reading each other's conversions of an ig file."""
  279. #NOTE - EMBOSS considers "genbank" to be for nucleotides only,
  280. #and will turn "X" into "N" for GenBank output.
  281. self.check_SeqIO_to_EMBOSS("IntelliGenetics/VIF_mase-pro.txt", "ig",
  282. alphabet=generic_protein,
  283. skip_formats=["genbank","embl"])
  284. #TODO - What does a % in an ig sequence mean?
  285. #e.g. "IntelliGenetics/vpu_nucaligned.txt"
  286. #and "IntelliGenetics/TAT_mase_nuc.txt"
  287. #EMBOSS seems to ignore them.
  288. def test_pir(self):
  289. """SeqIO & EMBOSS reading each other's conversions of a PIR file."""
  290. #Skip genbank here, EMBOSS mangles the LOCUS line:
  291. self.check_SeqIO_with_EMBOSS("NBRF/clustalw.pir", "pir",
  292. skip_formats=["genbank"])
  293. #Skip EMBL here, EMBOSS mangles the ID line
  294. #Skip GenBank, EMBOSS 6.0.1 on Windows won't output proteins as GenBank
  295. self.check_SeqIO_with_EMBOSS("NBRF/DMB_prot.pir", "pir",
  296. skip_formats=["embl","genbank"])
  297. def test_clustalw(self):
  298. """SeqIO & EMBOSS reading each other's conversions of a Clustalw file."""
  299. self.check_SeqIO_with_EMBOSS("Clustalw/hedgehog.aln", "clustal",
  300. skip_formats=["embl","genbank"])
  301. self.check_SeqIO_with_EMBOSS("Clustalw/opuntia.aln", "clustal",
  302. skip_formats=["embl","genbank"])
  303. class SeqRetAlignIOTests(unittest.TestCase):
  304. """Check EMBOSS seqret against Bio.SeqIO for converting files."""
  305. def tearDown(self):
  306. clean_up()
  307. def check_EMBOSS_to_AlignIO(self, filename, old_format,
  308. skip_formats=[]):
  309. """Can AlignIO read seqret's conversion of the file?"""
  310. self.assertTrue(os.path.isfile(filename), filename)
  311. old_aligns = list(AlignIO.parse(filename, old_format))
  312. formats = ["clustal", "phylip", "ig"]
  313. if len(old_aligns) == 1:
  314. formats.extend(["fasta","nexus"])
  315. for new_format in formats:
  316. if new_format in skip_formats:
  317. continue
  318. handle = emboss_convert(filename, old_format, new_format)
  319. try:
  320. new_aligns = list(AlignIO.parse(handle, new_format))
  321. except:
  322. handle.close()
  323. raise ValueError("Can't parse %s file %s in %s format." \
  324. % (old_format, filename, new_format))
  325. handle.close()
  326. try:
  327. self.assertTrue(compare_alignments(old_aligns, new_aligns))
  328. except ValueError, err:
  329. raise ValueError("Disagree on %s file %s in %s format: %s" \
  330. % (old_format, filename, new_format, err))
  331. def check_AlignIO_to_EMBOSS(self, in_filename, in_format, skip_formats=[],
  332. alphabet=None):
  333. """Can Bio.AlignIO write files seqret can read back?"""
  334. if alphabet:
  335. old_aligns = list(AlignIO.parse(in_filename,in_format,alphabet))
  336. else:
  337. old_aligns = list(AlignIO.parse(in_filename,in_format))
  338. formats = ["clustal", "phylip"]
  339. if len(old_aligns) == 1:
  340. formats.extend(["fasta","nexus"])
  341. for temp_format in formats:
  342. if temp_format in skip_formats:
  343. continue
  344. #PHYLIP is a simple format which explicitly supports
  345. #multiple alignments (unlike FASTA).
  346. try:
  347. new_aligns = list(emboss_piped_AlignIO_convert(old_aligns,
  348. temp_format,
  349. "phylip"))
  350. except ValueError, e:
  351. #e.g. ValueError: Need a DNA, RNA or Protein alphabet
  352. #from writing Nexus files...
  353. continue
  354. try:
  355. self.assertTrue(compare_alignments(old_aligns, new_aligns))
  356. except ValueError, err:
  357. raise ValueError("Disagree on file %s %s in %s format: %s" \
  358. % (in_format, in_filename, temp_format, err))
  359. def check_AlignIO_with_EMBOSS(self, filename, old_format, skip_formats=[],
  360. alphabet=None):
  361. #Check EMBOSS can read Bio.AlignIO output...
  362. self.check_AlignIO_to_EMBOSS(filename, old_format, skip_formats,
  363. alphabet)
  364. #Check Bio.AlignIO can read EMBOSS seqret output...
  365. self.check_EMBOSS_to_AlignIO(filename, old_format, skip_formats)
  366. def test_align_clustalw(self):
  367. """AlignIO & EMBOSS reading each other's conversions of a ClustalW file."""
  368. self.check_AlignIO_with_EMBOSS("Clustalw/hedgehog.aln", "clustal")
  369. self.check_AlignIO_with_EMBOSS("Clustalw/opuntia.aln", "clustal")
  370. self.check_AlignIO_with_EMBOSS("Clustalw/odd_consensus.aln", "clustal",
  371. skip_formats=["nexus"]) #TODO - why not nexus?
  372. self.check_AlignIO_with_EMBOSS("Clustalw/protein.aln", "clustal")
  373. self.check_AlignIO_with_EMBOSS("Clustalw/promals3d.aln", "clustal")
  374. def test_clustalw(self):
  375. """AlignIO & EMBOSS reading each other's conversions of a PHYLIP file."""
  376. self.check_AlignIO_with_EMBOSS("Phylip/horses.phy", "phylip")
  377. self.check_AlignIO_with_EMBOSS("Phylip/hennigian.phy", "phylip")
  378. self.check_AlignIO_with_EMBOSS("Phylip/reference_dna.phy", "phylip")
  379. self.check_AlignIO_with_EMBOSS("Phylip/reference_dna2.phy", "phylip")
  380. self.check_AlignIO_with_EMBOSS("Phylip/interlaced.phy", "phylip")
  381. self.check_AlignIO_with_EMBOSS("Phylip/interlaced2.phy", "phylip")
  382. self.check_AlignIO_with_EMBOSS("Phylip/random.phy", "phylip")
  383. class PairwiseAlignmentTests(unittest.TestCase):
  384. """Run pairwise alignments with water and needle, and parse them."""
  385. def tearDown(self):
  386. clean_up()
  387. def pairwise_alignment_check(self, query_seq,
  388. targets, alignments,
  389. local=True):
  390. """Check pairwise alignment data is sane."""
  391. #The datasets should be small, so making iterators into lists is OK
  392. targets = list(targets)
  393. alignments = list(alignments)
  394. self.assertEqual(len(targets), len(alignments))
  395. for target, alignment in zip(targets, alignments):
  396. self.assertEqual(len(alignment), 2)
  397. #self.assertEqual(target.id, alignment[1].id) #too strict
  398. if alignment[1].id not in target.id \
  399. and alignment[1].id not in target.name:
  400. raise AssertionError("%s vs %s or %s" \
  401. % (alignment[1].id , target.id, target.name))
  402. if local:
  403. #Local alignment
  404. self.assertTrue(str(alignment[0].seq).replace("-","") \
  405. in query_seq)
  406. self.assertTrue(str(alignment[1].seq).replace("-","").upper() \
  407. in str(target.seq).upper())
  408. else:
  409. #Global alignment
  410. self.assertEqual(str(query_seq), str(alignment[0].seq).replace("-",""))
  411. self.assertEqual(str(target.seq).upper(), \
  412. str(alignment[1].seq).replace("-","").upper())
  413. return True
  414. def run_water(self, cline):
  415. #Run the tool,
  416. stdout, stderr = cline()
  417. self.assertTrue(stderr.strip().startswith("Smith-Waterman local alignment"),
  418. stderr)
  419. if cline.outfile:
  420. self.assertEqual(stdout.strip(), "")
  421. self.assertTrue(os.path.isfile(cline.outfile),
  422. "Missing output file %r from:\n%s" % (cline.outfile, cline))
  423. else :
  424. #Don't use this yet... could return stdout handle instead?
  425. return stdout
  426. def test_water_file(self):
  427. """water with the asis trick, output to a file."""
  428. #Setup, try a mixture of keyword arguments and later additions:
  429. cline = WaterCommandline(cmd=exes["water"],
  430. gapopen="10", gapextend="0.5")
  431. #Try using both human readable names, and the literal ones:
  432. cline.set_parameter("asequence", "asis:ACCCGGGCGCGGT")
  433. cline.set_parameter("-bsequence", "asis:ACCCGAGCGCGGT")
  434. #Try using a property set here:
  435. cline.outfile = "Emboss/temp with space.water"
  436. self.assertEqual(str(eval(repr(cline))), str(cline))
  437. #Run the tool,
  438. self.run_water(cline)
  439. #Check we can parse the output...
  440. align = AlignIO.read(cline.outfile,"emboss")
  441. self.assertEqual(len(align), 2)
  442. self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT")
  443. self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT")
  444. #Clean up,
  445. os.remove(cline.outfile)
  446. def test_water_piped(self):
  447. """water with asis trick, output piped to stdout."""
  448. cline = WaterCommandline(cmd=exes["water"],
  449. asequence="asis:ACCCGGGCGCGGT",
  450. bsequence="asis:ACCCGAGCGCGGT",
  451. gapopen=10,
  452. gapextend=0.5,
  453. auto=True, filter=True)
  454. self.assertEqual(str(cline),
  455. exes["water"] + " -auto -filter" \
  456. + " -asequence=asis:ACCCGGGCGCGGT" \
  457. + " -bsequence=asis:ACCCGAGCGCGGT" \
  458. + " -gapopen=10 -gapextend=0.5")
  459. #Run the tool,
  460. child = subprocess.Popen(str(cline),
  461. stdin=subprocess.PIPE,
  462. stdout=subprocess.PIPE,
  463. stderr=subprocess.PIPE,
  464. universal_newlines=True,
  465. shell=(sys.platform!="win32"))
  466. child.stdin.close()
  467. #Check we could read it's output
  468. align = AlignIO.read(child.stdout, "emboss")
  469. self.assertEqual(len(align), 2)
  470. self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT")
  471. self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT")
  472. #Check no error output:
  473. self.assertEqual(child.stderr.read(), "")
  474. self.assertEqual(0, child.wait())
  475. child.stdout.close()
  476. child.stderr.close()
  477. def test_needle_file(self):
  478. """needle with the asis trick, output to a file."""
  479. #Setup,
  480. cline = NeedleCommandline(cmd=exes["needle"])
  481. cline.set_parameter("-asequence", "asis:ACCCGGGCGCGGT")
  482. cline.set_parameter("-bsequence", "asis:ACCCGAGCGCGGT")
  483. cline.set_parameter("-gapopen", "10")
  484. cline.set_parameter("-gapextend", "0.5")
  485. #EMBOSS would guess this, but let's be explicit:
  486. cline.set_parameter("-snucleotide", "True")
  487. cline.set_parameter("-outfile", "Emboss/temp with space.needle")
  488. self.assertEqual(str(eval(repr(cline))), str(cline))
  489. #Run the tool,
  490. stdout, stderr = cline()
  491. #Check it worked,
  492. self.assertTrue(stderr.strip().startswith("Needleman-Wunsch global alignment"), stderr)
  493. self.assertEqual(stdout.strip(), "")
  494. filename = cline.outfile
  495. self.assertTrue(os.path.isfile(filename),
  496. "Missing output file %r from:\n%s" % (filename, cline))
  497. #Check we can parse the output...
  498. align = AlignIO.read(filename,"emboss")
  499. self.assertEqual(len(align), 2)
  500. self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT")
  501. self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT")
  502. #Clean up,
  503. os.remove(filename)
  504. def test_needle_piped(self):
  505. """needle with asis trick, output piped to stdout."""
  506. cline = NeedleCommandline(cmd=exes["needle"],
  507. asequence="asis:ACCCGGGCGCGGT",
  508. bsequence="asis:ACCCGAGCGCGGT",
  509. gapopen=10,
  510. gapextend=0.5,
  511. auto=True, filter=True)
  512. self.assertEqual(str(cline),
  513. exes["needle"] + " -auto -filter" \
  514. + " -asequence=asis:ACCCGGGCGCGGT" \
  515. + " -bsequence=asis:ACCCGAGCGCGGT" \
  516. + " -gapopen=10 -gapextend=0.5")
  517. #Run the tool,
  518. child = subprocess.Popen(str(cline),
  519. stdin=subprocess.PIPE,
  520. stdout=subprocess.PIPE,
  521. stderr=subprocess.PIPE,
  522. universal_newlines=True,
  523. shell=(sys.platform!="win32"))
  524. child.stdin.close()
  525. #Check we could read it's output
  526. align = AlignIO.read(child.stdout, "emboss")
  527. self.assertEqual(len(align), 2)
  528. self.assertEqual(str(align[0].seq), "ACCCGGGCGCGGT")
  529. self.assertEqual(str(align[1].seq), "ACCCGAGCGCGGT")
  530. #Check no error output:
  531. self.assertEqual(child.stderr.read(), "")
  532. self.assertEqual(0, child.wait())
  533. child.stdout.close()
  534. child.stderr.close()
  535. def test_water_file2(self):
  536. """water with the asis trick and nucleotide FASTA file, output to a file."""
  537. #Setup,
  538. query = "ACACACTCACACACACTTGGTCAGAGATGCTGTGCTTCTTGGAAGCAAGGNCTCAAAGGCAAGGTGCACGCAGAGGGACGTTTGAGTCTGGGATGAAGCATGTNCGTATTATTTATATGATGGAATTTCACGTTTTTATG"
  539. out_file = "Emboss/temp_test2.water"
  540. in_file = "Fasta/f002"
  541. self.assertTrue(os.path.isfile(in_file))
  542. if os.path.isfile(out_file):
  543. os.remove(out_file)
  544. cline = WaterCommandline(cmd=exes["water"])
  545. cline.set_parameter("-asequence", "asis:%s" % query)
  546. cline.set_parameter("-bsequence", in_file)
  547. cline.set_parameter("-gapopen", "10")
  548. cline.set_parameter("-gapextend", "0.5")
  549. cline.set_parameter("-outfile", out_file)
  550. self.assertEqual(str(eval(repr(cline))), str(cline))
  551. #Run the tool,
  552. self.run_water(cline)
  553. #Check we can parse the output and it is sensible...
  554. self.pairwise_alignment_check(query,
  555. SeqIO.parse(in_file,"fasta"),
  556. AlignIO.parse(out_file,"emboss"),
  557. local=True)
  558. #Clean up,
  559. os.remove(out_file)
  560. def test_water_file3(self):
  561. """water with the asis trick and GenBank file, output to a file."""
  562. #Setup,
  563. query = "TGTTGTAATGTTTTAATGTTTCTTCTCCCTTTAGATGTACTACGTTTGGA"
  564. out_file = "Emboss/temp_test3.water"
  565. in_file = "GenBank/cor6_6.gb"
  566. self.assertTrue(os.path.isfile(in_file))
  567. if os.path.isfile(out_file):
  568. os.remove(out_file)
  569. cline = WaterCommandline(cmd=exes["water"])
  570. cline.set_parameter("asequence", "asis:%s" % query)
  571. cline.set_parameter("bsequence", in_file)
  572. #TODO - Tell water this is a GenBank file!
  573. cline.set_parameter("gapopen", "1")
  574. cline.set_parameter("gapextend", "0.5")
  575. cline.set_parameter("outfile", out_file)
  576. self.assertEqual(str(eval(repr(cline))), str(cline))
  577. #Run the tool,
  578. self.run_water(cline)
  579. #Check we can parse the output and it is sensible...
  580. self.pairwise_alignment_check(query,
  581. SeqIO.parse(in_file,"genbank"),
  582. AlignIO.parse(out_file,"emboss"),
  583. local=True)
  584. #Clean up,
  585. os.remove(out_file)
  586. def test_water_file4(self):
  587. """water with the asis trick and SwissProt file, output to a file."""
  588. #Setup,
  589. query = "DVCTGKALCDPVTQNIKTYPVKIENLRVMI"
  590. out_file = "Emboss/temp_test4.water"
  591. in_file = "SwissProt/sp004"
  592. self.assertTrue(os.path.isfile(in_file))
  593. if os.path.isfile(out_file):
  594. os.remove(out_file)
  595. cline = WaterCommandline(cmd=exes["water"])
  596. cline.set_parameter("-asequence", "asis:%s" % query)
  597. cline.set_parameter("-bsequence", in_file)
  598. #EMBOSS should work this out, but let's be explicit:
  599. cline.set_parameter("-sprotein", True)
  600. #TODO - Tell water this is a SwissProt file!
  601. cline.set_parameter("-gapopen", "20")
  602. cline.set_parameter("-gapextend", "5")
  603. cline.set_parameter("-outfile", out_file)
  604. self.assertEqual(str(eval(repr(cline))), str(cline))
  605. #Run the tool,
  606. self.run_water(cline)
  607. #Check we can parse the output and it is sensible...
  608. self.pairwise_alignment_check(query,
  609. SeqIO.parse(in_file,"swiss"),
  610. AlignIO.parse(out_file,"emboss"),
  611. local=True)
  612. #Clean up,
  613. os.remove(out_file)
  614. def test_needle_piped2(self):
  615. """needle with asis trick, and nucleotide FASTA file, output piped to stdout."""
  616. #TODO - Support needle in Bio.Emboss.Applications
  617. #(ideally with the -auto and -filter arguments)
  618. #Setup,
  619. query = "ACACACTCACACACACTTGGTCAGAGATGCTGTGCTTCTTGGAA"
  620. cline = exes["needle"]
  621. cline += " -asequence asis:" + query
  622. cline += " -bsequence Fasta/f002"
  623. cline += " -auto" #no prompting
  624. cline += " -filter" #use stdout
  625. #Run the tool,
  626. child = subprocess.Popen(str(cline),
  627. stdin=subprocess.PIPE,
  628. stdout=subprocess.PIPE,
  629. stderr=subprocess.PIPE,
  630. universal_newlines=True,
  631. shell=(sys.platform!="win32"))
  632. child.stdin.close()
  633. #Check we can parse the output and it is sensible...
  634. self.pairwise_alignment_check(query,
  635. SeqIO.parse("Fasta/f002","fasta"),
  636. AlignIO.parse(child.stdout,"emboss"),
  637. local=False)
  638. #Check no error output:
  639. self.assertEqual(child.stderr.read(), "")
  640. self.assertEqual(0, child.wait())
  641. child.stdout.close()
  642. child.stderr.close()
  643. def test_water_needs_output(self):
  644. """water without output file or stdout/filter should give error."""
  645. cline = WaterCommandline(cmd=exes["water"],
  646. asequence="asis:ACCCGGGCGCGGT",
  647. bsequence="asis:ACCCGAGCGCGGT",
  648. gapopen=10,
  649. gapextend=0.5,
  650. auto=True)
  651. self.assertTrue(cline.auto)
  652. self.assertTrue(not cline.stdout)
  653. self.assertTrue(not cline.filter)
  654. self.assertEqual(cline.outfile, None)
  655. self.assertRaises(ValueError, str, cline)
  656. def test_needle_needs_output(self):
  657. """needle without output file or stdout/filter should give error."""
  658. cline = NeedleCommandline(cmd=exes["needle"],
  659. asequence="asis:ACCCGGGCGCGGT",
  660. bsequence="asis:ACCCGAGCGCGGT",
  661. gapopen=10,
  662. gapextend=0.5,
  663. auto=True)
  664. self.assertTrue(cline.auto)
  665. self.assertTrue(not cline.stdout)
  666. self.assertTrue(not cline.filter)
  667. self.assertEqual(cline.outfile, None)
  668. self.assertRaises(ValueError, str, cline)
  669. def test_seqtmatchall_piped(self):
  670. """seqmatchall with pair output piped to stdout."""
  671. cline = SeqmatchallCommandline(cmd=exes["seqmatchall"],
  672. sequence="Fasta/f002",
  673. aformat="pair", wordsize=9,
  674. auto=True, stdout=True)
  675. self.assertEqual(str(cline),
  676. exes["seqmatchall"] + " -auto -stdout" \
  677. + " -sequence=Fasta/f002"
  678. + " -wordsize=9 -aformat=pair")
  679. #Run the tool,
  680. child = subprocess.Popen(str(cline),
  681. stdin=subprocess.PIPE,
  682. stdout=subprocess.PIPE,
  683. stderr=subprocess.PIPE,
  684. universal_newlines=True,
  685. shell=(sys.platform!="win32"))
  686. child.stdin.close()
  687. #Check we could read it's output
  688. for align in AlignIO.parse(child.stdout, "emboss") :
  689. self.assertEqual(len(align), 2)
  690. self.assertEqual(align.get_alignment_length(), 9)
  691. #Check no error output:
  692. self.assertEqual(child.stderr.read(), "")
  693. self.assertEqual(0, child.wait())
  694. child.stdout.close()
  695. child.stderr.close()
  696. #Top level function as this makes it easier to use for debugging:
  697. def emboss_translate(sequence, table=None, frame=None):
  698. """Call transeq, returns protein sequence as string."""
  699. #TODO - Support transeq in Bio.Emboss.Applications?
  700. #(doesn't seem worthwhile as Biopython can do translations)
  701. if not sequence:
  702. raise ValueError(sequence)
  703. #Setup,
  704. cline = exes["transeq"]
  705. if len(sequence) < 100:
  706. filename = None
  707. cline += " -sequence asis:%s" % sequence
  708. else:
  709. #There are limits on command line string lengths...
  710. #use a temp file instead.
  711. filename = "Emboss/temp_transeq.txt"
  712. SeqIO.write(SeqRecord(sequence, id="Test"), filename, "fasta")
  713. cline += " -sequence %s" % filename
  714. cline += " -auto" #no prompting
  715. cline += " -filter" #use stdout
  716. if table is not None:
  717. cline += " -table %s" % str(table)
  718. if frame is not None:
  719. cline += " -frame %s" % str(frame)
  720. #Run the tool,
  721. child = subprocess.Popen(str(cline),
  722. stdin=subprocess.PIPE,
  723. stdout=subprocess.PIPE,
  724. stderr=subprocess.PIPE,
  725. universal_newlines=True,
  726. shell=(sys.platform!="win32"))
  727. out, err = child.communicate()
  728. #Check no error output:
  729. if err != "":
  730. raise ValueError(str(cline) + "\n" + err)
  731. #Check we could read it's output
  732. record = SeqIO.read(StringIO(out), "fasta")
  733. if 0 != child.wait():
  734. raise ValueError(str(cline))
  735. if filename:
  736. os.remove(filename)
  737. if not record.id.startswith("Test"):
  738. raise ValueError(str(cline))
  739. else:
  740. if not record.id.startswith("asis"):
  741. raise ValueError(str(cline))
  742. return str(record.seq)
  743. #Top level function as this makes it easier to use for debugging:
  744. def check_translation(sequence, translation, table=None):
  745. if table is None:
  746. t = 1
  747. else:
  748. t = table
  749. if translation != str(sequence.translate(t)) \
  750. or translation != str(translate(sequence,t)) \
  751. or translation != translate(str(sequence),t):
  752. #More details...
  753. for i, amino in enumerate(translation):
  754. codon = sequence[i*3:i*3+3]
  755. if amino != str(codon.translate(t)):
  756. raise ValueError("%s -> %s not %s (table %s)" \
  757. % (codon, amino, codon.translate(t), t))
  758. #Shouldn't reach this line:
  759. raise ValueError("%s -> %s (table %s)" \
  760. % (sequence, translation, t))
  761. return True
  762. class TranslationTests(unittest.TestCase):
  763. """Run pairwise alignments with water and needle, and parse them."""
  764. def tearDown(self):
  765. clean_up()
  766. def test_simple(self):
  767. """transeq vs Bio.Seq for simple translations (including alt tables)."""
  768. examples = [Seq("ACGTGACTGACGTAGCATGCCACTAGG"),
  769. #Unamibguous TA? codons:
  770. Seq("TAATACTATTAG", generic_dna),
  771. #Most of the ambiguous TA? codons:
  772. Seq("TANTARTAYTAMTAKTAHTABTADTAV", generic_dna),
  773. #Problem cases,
  774. #
  775. #Seq("TAW", generic_dna),
  776. #W = A or T, but EMBOSS does TAW -> X
  777. #TAA -> Y, TAT ->Y, so in Biopython TAW -> Y
  778. #
  779. #Seq("TAS", generic_dna),
  780. #S = C or G, but EMBOSS does TAS -> Y
  781. #TAG -> *, TAC ->Y, so in Biopython TAS -> X (Y or *)
  782. #
  783. #Seq("AAS", generic_dna),
  784. #On table 9, EMBOSS gives N, we give X.
  785. #S = C or G, so according to my reading of
  786. #table 9 on the NCBI page, AAC=N, AAG=K
  787. #suggesting this is a bug in EMBOSS.
  788. #
  789. Seq("ACGGGGGGGGTAAGTGGTGTGTGTGTAGT", generic_dna),
  790. ]
  791. for sequence in examples:
  792. #EMBOSS treats spare residues differently... avoid this issue
  793. if len(sequence) % 3 != 0:
  794. sequence = sequence[:-(len(sequence)%3)]
  795. self.assertEqual(len(sequence) % 3, 0)
  796. self.assertTrue(len(sequence) > 0)
  797. self.check(sequence)
  798. def check(self, sequence):
  799. """Compare our translation to EMBOSS's using all tables.
  800. Takes a Seq object (and a filename containing it)."""
  801. translation = emboss_translate(sequence)
  802. self.assertTrue(check_translation(sequence, translation))
  803. for table in [1,2,3,4,5,6,9,10,11,12,13,14,15,16,21,22,23]:
  804. translation = emboss_translate(sequence, table)
  805. self.assertTrue(check_translation(sequence, translation, table))
  806. return True
  807. def translate_all_codons(self, letters):
  808. sequence = Seq("".join([c1+c3+c3 \
  809. for c1 in letters \
  810. for c2 in letters \
  811. for c3 in letters]),
  812. generic_nucleotide)
  813. self.check(sequence)
  814. #def test_all_ambig_dna_codons(self):
  815. # """transeq vs Bio.Seq on ambiguous DNA codons (inc. alt tables)."""
  816. # self.translate_all_codons(ambiguous_dna_letters)
  817. def test_all_unambig_dna_codons(self):
  818. """transeq vs Bio.Seq on unambiguous DNA codons (inc. alt tables)."""
  819. self.translate_all_codons("ATCGatcg")
  820. def test_all_unambig_rna_codons(self):
  821. """transeq vs Bio.Seq on unambiguous RNA codons (inc. alt tables)."""
  822. self.translate_all_codons("AUCGaucg")
  823. def test_mixed_unambig_rna_codons(self):
  824. """transeq vs Bio.Seq on unambiguous DNA/RNA codons (inc. alt tables)."""
  825. self.translate_all_codons("ATUCGatucg")
  826. def clean_up():
  827. """Fallback clean up method to remove temp files."""
  828. for filename in os.listdir("Emboss"):
  829. if filename.startswith("temp_"):
  830. try:
  831. os.remove(filename)
  832. except:
  833. pass
  834. if __name__ == "__main__":
  835. runner = unittest.TextTestRunner(verbosity = 2)
  836. unittest.main(testRunner=runner)
  837. clean_up()