comparison gops_complement.py @ 0:d958d5a0d1e8

Imported from capsule None
author devteam
date Tue, 01 Apr 2014 10:51:48 -0400
parents
children e0a23ab32d7f
comparison
equal deleted inserted replaced
-1:000000000000 0:d958d5a0d1e8
1 #!/usr/bin/env python
2 """
3 Complement regions.
4
5 usage: %prog in_file out_file
6 -1, --cols1=N,N,N,N: Columns for chrom, start, end, strand in file
7 -l, --lengths=N: Filename of .len file for species (chromosome lengths)
8 -a, --all: Complement all chromosomes (Genome-wide complement)
9 """
10
11 import sys, traceback, fileinput
12 from warnings import warn
13 from bx.intervals import *
14 from bx.intervals.io import *
15 from bx.intervals.operations.complement import complement
16 from bx.intervals.operations.subtract import subtract
17 from bx.cookbook import doc_optparse
18 from galaxy.tools.util.galaxyops import *
19
20 assert sys.version_info[:2] >= ( 2, 4 )
21
22 def main():
23 allchroms = False
24 upstream_pad = 0
25 downstream_pad = 0
26
27 options, args = doc_optparse.parse( __doc__ )
28 try:
29 chr_col_1, start_col_1, end_col_1, strand_col_1 = parse_cols_arg( options.cols1 )
30 lengths = options.lengths
31 if options.all: allchroms = True
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 lens = dict()
44 chroms = list()
45 # dbfile is used to determine the length of each chromosome. The lengths
46 # are added to the lens dict and passed copmlement operation code in bx.
47 dbfile = fileinput.FileInput( lengths )
48
49 if dbfile:
50 if not allchroms:
51 try:
52 for line in dbfile:
53 fields = line.split("\t")
54 lens[fields[0]] = int(fields[1])
55 except:
56 # assume LEN doesn't exist or is corrupt somehow
57 pass
58 elif allchroms:
59 try:
60 for line in dbfile:
61 fields = line.split("\t")
62 end = int(fields[1])
63 chroms.append("\t".join([fields[0],"0",str(end)]))
64 except:
65 pass
66
67 # Safety...if the dbfile didn't exist and we're on allchroms, then
68 # default to generic complement
69 if allchroms and len(chroms) == 0:
70 allchroms = False
71
72 if allchroms:
73 chromReader = GenomicIntervalReader(chroms)
74 generator = subtract([chromReader, g1])
75 else:
76 generator = complement(g1, lens)
77
78 out_file = open( out_fname, "w" )
79
80 try:
81 for interval in generator:
82 if type( interval ) is GenomicInterval:
83 out_file.write( "%s\n" % "\t".join( interval ) )
84 else:
85 out_file.write( "%s\n" % interval )
86 except ParseError, exc:
87 out_file.close()
88 fail( "Invalid file format: %s" % str( exc ) )
89
90 out_file.close()
91
92 if g1.skipped > 0:
93 print skipped( g1, filedesc="" )
94
95 if __name__ == "__main__":
96 main()