view tandem_repeats_finder_wrapper.py @ 0:a2e1d1f25e35 draft default tip

Uploaded
author urgi-team
date Thu, 10 Jul 2014 09:32:30 -0400
parents
children
line wrap: on
line source

#!/usr/bin/env python


import subprocess, tempfile, sys, os, glob, shutil, time
from optparse import OptionParser


class tandemRepeatsFinderWrapper(object):

	def __init__(self):
		self._options = None

	def getSystemCommand(self, prg, lArgs):
		systemCmd = prg
		for arg in lArgs:
			systemCmd += " " + arg
		return systemCmd

	def setOptions(self, options):
		self._options = options

	def stop_err(self, msg ):
		sys.stderr.write( "%s\n" % msg )
		sys.exit()

	def setAttributesFromCmdLine(self):
		parser = OptionParser(description = "Tandem Repeats Finder wrapper", version = "4.0")
		parser.add_option( "--html", dest = "html", help = "html summary file for Galaxy")
		parser.add_option( "--dirhtml", dest = "dir", help = "html files directory for Galaxy")
		parser.add_option( "--txt", dest = "txt", default="", help = "txt summary file for Galaxy")
		parser.add_option( "--file", dest = "inputFile", help = "Input Fasta File name")
		parser.add_option( "--match", dest = "match", type="int", default=2, help = "matching weight"),
		parser.add_option( "--mismatch", dest = "mismatch", type="int", default=7, help = "mismatching penalty"),
		parser.add_option( "--delta", dest = "delta", type="int", default = 7, help = "indel penalty")
		parser.add_option( "--pm", dest = "pm", type="int", default=80, help="matching probability")
		parser.add_option( "--pi", dest="pi", type="int", default=10, help="indel probability")
		parser.add_option( "--minscore", dest="minscore", type="int", default=30, help="minimum alignment score to report")
		parser.add_option( "--maxperiod", dest="maxperiod", type="int", default=500, help="maximum period size to report")
		parser.add_option( "--flanking", dest="flanking", action="store_true", help="")
		parser.add_option( "--mask", dest="mask", help="" )
		options, args = parser.parse_args()
		self._setAttributesFromOptions(options)

	def _setAttributesFromOptions(self, options):
		self.setOptions(options)

	def run(self):
		prg = "trf"
		args = []
		args.append("%s" % self._options.inputFile)
		args.append("%d" % self._options.match)
		args.append("%d" % self._options.mismatch)
		args.append("%d" % self._options.delta)
		args.append("%d" % self._options.pm)
		args.append("%d" % self._options.pi)
		args.append("%d" % self._options.minscore)
		args.append("%d" % self._options.maxperiod)
		if not self._options.html and not self._options.dir:
			args.append("-h")
		if self._options.flanking == True:
			args.append("-f")
		if self._options.mask:
			args.append("-m")
		args.append("-d")

		cmd = self.getSystemCommand(prg, args)

		try:
			tmp_err = tempfile.NamedTemporaryFile().name
			tmp_stderr = open( tmp_err, 'wb' )
			proc = subprocess.Popen( args=cmd, shell=True, cwd=".", stderr=tmp_stderr )
			returncode = proc.wait()
			tmp_stderr.close()
			# get stderr, allowing for case where it's very large
			tmp_stderr = open( tmp_err, 'rb' )
			stderr = ''
			buffsize = 1048576
			try:
				while True:
					stderr += tmp_stderr.read( buffsize )
					if not stderr or len( stderr ) % buffsize != 0:
						break
			except OverflowError:
				pass
			tmp_stderr.close()
			if stderr:
				raise Exception, stderr
		except Exception, e:
			self.stop_err( 'Error in Tandem Repeats Finder:\n' + str( e ) )
		if self._options.html:
			summary = glob.glob("*.summary.html")
			if not summary:
				summary = glob.glob("*1.html")

			shutil.move("%s" % (summary[0]) , "%s" % (self._options.html))

			os.mkdir("%s" % (self._options.dir))
			for results in glob.glob("*.html"):
				baseName = os.path.basename(results)
				shutil.move("%s" % (results) , "%s/%s" % (self._options.dir, baseName))

			if self._options.txt:
				data = glob.glob("*.dat")
				shutil.move("%s" % (data[0]) , "%s" % (self._options.txt))
		else:
			data = glob.glob("*.dat")
			shutil.move("%s" % (data[0]) , "%s" % (self._options.txt))

		if self._options.mask:
			masked_file = glob.glob("*.mask")
			shutil.move("%s" % (masked_file[0]) , "%s" % (self._options.mask))


if __name__ == "__main__":
	iWrapper = tandemRepeatsFinderWrapper()
	iWrapper.setAttributesFromCmdLine()
	iWrapper.run()