Files
galaxy/tools/regVariation/windowSplitter.py
T

91 lines
3.0 KiB
Python

#! /usr/bin/python
"""
Split into windows.
usage: %prog input size out_file
-l, --cols=N,N,N,N: Columns for chrom, start, end, strand in file
"""
import sys, sets, re, os
import pkg_resources; pkg_resources.require( "bx-python" )
from bx.cookbook import doc_optparse
from galaxyops import *
def main():
# Parsing Command Line here
options, args = doc_optparse.parse( __doc__ )
try:
chr_col_1, start_col_1, end_col_1, strand_col_1 = parse_cols_arg( options.cols )
inp_file, winsize, out_file, makesliding, offset = args
winsize = int(winsize)
offset = int(offset)
makesliding = int(makesliding)
if strand_col_1 <= 0:
strand = "+" #if strand is not defined, default it to +
except:
print >> sys.stderr, "Data issue: Please check the metadata attributes of the chosen input by clicking on the pencil icon next to it."
sys.exit()
try:
fi = open(inp_file,'r')
except:
print >> sys.stderr, "Unable to open input file"
sys.exit()
try:
fo = open(out_file,'w')
except:
print >> sys.stderr, "Unable to open output file"
sys.exit()
skipped_lines = 0
first_invalid_line = 0
invalid_line = None
if offset == 0:
makesliding = 0
for i, line in enumerate( fi ):
line = line.strip()
if line and line[0:1] != "#":
try:
elems = line.split('\t')
if strand_col_1 != -1:
strand = elems[strand_col_1]
start = int(elems[start_col_1])
end = int(elems[end_col_1])
if makesliding == 0:
numwin = (end - start)/winsize
else:
numwin = (end - start)/offset
if numwin > 0:
for win in range(numwin):
elems_1 = elems
elems_1[start_col_1] = str(start)
elems_1[end_col_1] = str(start + winsize)
print >>fo, '\t'.join(elems_1)
if makesliding == 0:
start = start + winsize
else:
start = start + offset
if start+winsize > end:
break
except Exception, exc:
print exc
skipped_lines += 1
if not invalid_line:
first_invalid_line = i + 1
invalid_line = line
if makesliding == 1:
print 'Window size = %d, Sliding = Yes, Offset = %d' %(winsize, offset)
else:
print 'Window size = %d, Sliding = No' %(winsize)
if skipped_lines > 0:
print '(Data issue: skipped %d invalid lines starting at line #%d which is "%s")' % ( skipped_lines, first_invalid_line, invalid_line )
if __name__ == "__main__":
main()