Source code

Download source archive ↓

upstream/sam2interval/sam2interval.py

1#!/usr/bin/env python
2
3import sys
4import optparse
5import re
6
7
8def stop_err(msg):
9    sys.exit(msg)
10
11
12def main():
13    usage = """%prog [options]
14
15options (listed below) default to 'None' if omitted
16    """
17    parser = optparse.OptionParser(usage=usage)
18
19    parser.add_option(
20        '-f', '--input_sam_file',
21        metavar="INPUT_SAM_FILE",
22        dest='input_sam',
23        default=False,
24        help='Name of the SAM file to be filtered. STDIN is default')
25
26    parser.add_option(
27        '-c', '--flag_column',
28        dest='flag_col',
29        default='2',
30        help='Column containing SAM bitwise flag. 1-based')
31
32    parser.add_option(
33        '-s', '--start_column',
34        dest='start_col',
35        default='4',
36        help='Column containing position. 1-based')
37
38    parser.add_option(
39        '-g', '--cigar_column',
40        dest='cigar_col',
41        default='6',
42        help='Column containing CIGAR or extended CIGAR string')
43
44    parser.add_option(
45        '-r', '--ref_column',
46        dest='ref_col',
47        default='3',
48        help='Column containing name of the reference sequence coordinate. 1-based')
49
50    parser.add_option(
51        '-e', '--read_column',
52        dest='read_col',
53        default='1',
54        help='Column containing read name. 1-based')
55
56    parser.add_option(
57        '-p', '--print_all',
58        dest='prt_all',
59        action='store_true',
60        default=False,
61        help='Print coordinates and original SAM?')
62
63    options, args = parser.parse_args()
64
65    if options.input_sam:
66        infile = open(options.input_sam, 'r')
67    else:
68        infile = sys.stdin
69
70    cigar = re.compile('\d+M|\d+N|\d+D|\d+P')
71
72    print('#chrom\tstart\tend\tstrand\tread_name')  # provide a (partial) header so that strand is automatically set in metadata
73
74    for line in infile:
75        line = line.rstrip('\r\n')
76        if line and not line.startswith('#') and not line.startswith('@'):
77            fields = line.split('\t')
78            start = int(fields[int(options.start_col) - 1]) - 1
79            end = 0
80            for op in cigar.findall(fields[int(options.cigar_col) - 1]):
81                end += int(op[0:len(op) - 1])
82
83            strand = '+'
84            if bool(int(fields[int(options.flag_col) - 1]) & 0x0010):
85                strand = '-'
86            read_name = fields[int(options.read_col) - 1]
87            ref_name = fields[int(options.ref_col) - 1]
88
89            if ref_name != '*':
90                # Do not print lines with unmapped reads that contain '*' instead of chromosome name
91                if options.prt_all:
92                    print('%s\t%s\t%s\t%s\t%s' % (ref_name, str(start), str(end + start), strand, line))
93                else:
94                    print('%s\t%s\t%s\t%s\t%s' % (ref_name, str(start), str(end + start), strand, read_name))
95
96
97if __name__ == "__main__":
98    main()