PageRenderTime 23ms CodeModel.GetById 13ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/new_operations/gops_merge.py

https://bitbucket.org/cistrome/cistrome-harvard/
Python | 71 lines | 53 code | 9 blank | 9 comment | 8 complexity | 97476837c90f5d77e4482cc929a54d45 MD5 | raw file
 1#!/usr/bin/env python
 2"""
 3Merge overlaping regions.
 4
 5usage: %prog in_file out_file
 6    -1, --cols1=N,N,N,N: Columns for start, end, strand in first file
 7    -m, --mincols=N: Require this much overlap (default 1bp)
 8    -3, --threecol: Output 3 column bed
 9"""
10from galaxy import eggs
11import pkg_resources
12pkg_resources.require( "bx-python" )
13import sys, traceback, fileinput
14from warnings import warn
15from bx.intervals import *
16from bx.intervals.io import *
17from bx.intervals.operations.merge import *
18from bx.cookbook import doc_optparse
19from galaxy.tools.util.galaxyops import *
20
21assert sys.version_info[:2] >= ( 2, 4 )
22
23def main():
24    mincols = 1
25    upstream_pad = 0
26    downstream_pad = 0
27
28    options, args = doc_optparse.parse( __doc__ )
29    try:
30        chr_col_1, start_col_1, end_col_1, strand_col_1 = parse_cols_arg( options.cols1 )
31        if options.mincols: mincols = int( options.mincols )
32        in_fname, out_fname = args
33    except:
34        doc_optparse.exception()
35
36    g1 = NiceReaderWrapper( fileinput.FileInput( in_fname ),
37                            chrom_col=chr_col_1,
38                            start_col=start_col_1,
39                            end_col=end_col_1,
40                            strand_col = strand_col_1,
41                            fix_strand=True )
42
43    out_file = open( out_fname, "w" )
44
45    try:
46        for line in merge(g1,mincols=mincols):
47            if options.threecol:
48                if type( line ) is GenomicInterval:
49                    out_file.write( "%s\t%s\t%s\n" % ( line.chrom, str( line.startCol ), str( line.endCol ) ) )
50                elif type( line ) is list:
51                    out_file.write( "%s\t%s\t%s\n" % ( line[chr_col_1], str( line[start_col_1] ), str( line[end_col_1] ) ) )
52                else:
53                    out_file.write( "%s\n" % line )
54            else:
55                if type( line ) is GenomicInterval:
56                    out_file.write( "%s\n" % "\t".join( line.fields ) )
57                elif type( line ) is list:
58                    out_file.write( "%s\n" % "\t".join( line ) )
59                else:
60                    out_file.write( "%s\n" % line )
61    except ParseError, exc:
62        out_file.close()
63        fail( "Invalid file format: %s" % str( exc ) )
64
65    out_file.close()
66
67    if g1.skipped > 0:
68        print skipped( g1, filedesc=" of 1st dataset" )
69
70if __name__ == "__main__":
71    main()