Source code

Download source archive ↓

upstream/windowsplitter/windowSplitter.py

1#!/usr/bin/env python
2"""
3Split into windows.
4
5usage: %prog input size out_file
6   -l, --cols=N,N,N,N: Columns for chrom, start, end, strand in file
7"""
8from __future__ import print_function
9
10import sys
11
12from bx.cookbook import doc_optparse
13
14
15# Default chrom, start, end, strand cols for a bed file
16BED_DEFAULT_COLS = 0, 1, 2, 5
17
18
19def parse_cols_arg(cols):
20    """Parse a columns command line argument into a four-tuple"""
21    if cols:
22        # Handle case where no strand column included - in this case, cols
23        # looks something like 1,2,3,
24        if cols.endswith(','):
25            cols += '0'
26        col_list = [int(x) - 1 for x in cols.split(",")]
27        return col_list
28    else:
29        return BED_DEFAULT_COLS
30
31
32def main():
33    # Parsing Command Line here
34    options, args = doc_optparse.parse(__doc__)
35
36    try:
37        chr_col_1, start_col_1, end_col_1, strand_col_1 = parse_cols_arg(options.cols)
38        inp_file, winsize, out_file, makesliding, offset = args
39        winsize = int(winsize)
40        offset = int(offset)
41        makesliding = int(makesliding)
42    except Exception:
43        sys.exit("Data issue, click the pencil icon in the history item to correct the metadata attributes of the input dataset.")
44
45    skipped_lines = 0
46    first_invalid_line = 0
47    invalid_line = None
48    if offset == 0:
49        makesliding = 0
50
51    with open(out_file, 'w') as fo, open(inp_file) as fi:
52        for i, line in enumerate(fi):
53            line = line.strip()
54            if line and line[0:1] != "#":
55                try:
56                    elems = line.split('\t')
57                    start = int(elems[start_col_1])
58                    end = int(elems[end_col_1])
59                    if makesliding == 0:
60                        numwin = (end - start) // winsize
61                    else:
62                        numwin = (end - start) // offset
63                    if numwin > 0:
64                        for _ in range(numwin):
65                            elems_1 = elems
66                            elems_1[start_col_1] = str(start)
67                            elems_1[end_col_1] = str(start + winsize)
68                            fo.write("%s\n" % '\t'.join(elems_1))
69                            if makesliding == 0:
70                                start = start + winsize
71                            else:
72                                start = start + offset
73                                if start + winsize > end:
74                                    break
75                except Exception:
76                    skipped_lines += 1
77                    if not invalid_line:
78                        first_invalid_line = i + 1
79                        invalid_line = line
80
81    if makesliding == 1:
82        print('Window size=%d, Sliding=Yes, Offset=%d' % (winsize, offset))
83    else:
84        print('Window size=%d, Sliding=No' % (winsize))
85    if skipped_lines > 0:
86        print('Skipped %d invalid lines starting with #%d: "%s"' % (skipped_lines, first_invalid_line, invalid_line))
87
88
89if __name__ == "__main__":
90    main()