1 | #!/usr/bin/python2.6 |
---|
2 | |
---|
3 | """ |
---|
4 | Read scores in "wiggle" format from `score_file` and intervals in "bed" format |
---|
5 | from `interval_file` and print all scores overlapping intervals. |
---|
6 | |
---|
7 | TODO: Support binned array format scores also. |
---|
8 | |
---|
9 | usage: %prog score_file interval_file [out_file] |
---|
10 | """ |
---|
11 | |
---|
12 | from __future__ import division |
---|
13 | |
---|
14 | import sys |
---|
15 | import psyco_full |
---|
16 | import bx.wiggle |
---|
17 | from bx.binned_array import BinnedArray |
---|
18 | from fpconst import isNaN |
---|
19 | from bx.cookbook import doc_optparse |
---|
20 | from bx import misc |
---|
21 | |
---|
22 | def read_scores( f ): |
---|
23 | scores_by_chrom = dict() |
---|
24 | for chrom, pos, val in bx.wiggle.Reader( f ): |
---|
25 | if chrom not in scores_by_chrom: |
---|
26 | scores_by_chrom[chrom] = BinnedArray() |
---|
27 | scores_by_chrom[chrom][pos] = val |
---|
28 | return scores_by_chrom |
---|
29 | |
---|
30 | def main(): |
---|
31 | |
---|
32 | # Parse command line |
---|
33 | options, args = doc_optparse.parse( __doc__ ) |
---|
34 | try: |
---|
35 | score_file = open( args[0] ) |
---|
36 | interval_file = open( args[1] ) |
---|
37 | if len( args ) > 2: |
---|
38 | out_file = open( args[2], 'w' ) |
---|
39 | else: |
---|
40 | out_file = sys.stdout |
---|
41 | except: |
---|
42 | doc_optparse.exit() |
---|
43 | |
---|
44 | scores_by_chrom = read_scores( misc.open_compressed( sys.argv[1] ) ) |
---|
45 | for line in open( sys.argv[2] ): |
---|
46 | fields = line.split() |
---|
47 | chrom, start, stop = fields[0], int( fields[1] ), int( fields[2] ) |
---|
48 | if chrom in scores_by_chrom: |
---|
49 | ba = scores_by_chrom[chrom] |
---|
50 | scores = [ ba[i] for i in range( start, stop ) ] |
---|
51 | else: |
---|
52 | scores = [] |
---|
53 | print >> out_file, " ".join( fields ), " ".join( map( str, scores ) ) |
---|
54 | |
---|
55 | score_file.close() |
---|
56 | interval_file.close() |
---|
57 | out_file.close() |
---|
58 | |
---|
59 | if __name__ == "__main__": main() |
---|