Source code

Download source archive ↓

upstream-extended/devteam/tools/weightedaverage/WeightedAverage.py

1#!/usr/bin/env python
2"""
3usage: %prog bed_file_1 bed_file_2 out_file
4    -1, --cols1=N,N,N,N: Columns for chr, start, end, strand in first file
5    -2, --cols2=N,N,N,N,N: Columns for chr, start, end, strand, name/value in second file
6    -z, --allow_zeros: Include zeros in calculations
7"""
8
9import collections
10import sys
11from galaxy.tools.util.galaxyops import *
12from bx.cookbook import doc_optparse
13
14
15#export PYTHONPATH=~/galaxy/lib/
16#running command python WeightedAverage.py interval_interpolate.bed value_interpolate.bed interpolate_result.bed
17
18def stop_err(msg):
19    sys.stderr.write(msg)
20    sys.exit()
21
22
23def FindRate(chromosome, start_stop, dictType):
24    OverlapList = []
25    for tempO in dictType[chromosome]:
26        DatabaseInterval = [tempO[0], tempO[1]]
27        Overlap = GetOverlap( start_stop, DatabaseInterval )
28        if Overlap > 0:
29            OverlapList.append([Overlap, tempO[2]])
30    
31    if len(OverlapList) > 0:
32        SumRecomb = 0
33        SumOverlap = 0
34        for member in OverlapList:
35            SumRecomb += member[0]*member[1]
36            SumOverlap += member[0]
37        averageRate = SumRecomb/SumOverlap
38        return averageRate
39    else:
40        return 'NA'
41
42
43def GetOverlap(a, b):
44    return min(a[1], b[1])-max(a[0], b[0])
45
46def get_float_no_zero( field ):
47    rval = float( field )
48    assert rval
49    return rval
50
51
52options, args = doc_optparse.parse( __doc__ )
53
54try:
55    chr_col_1, start_col_1, end_col_1, strand_col1 = parse_cols_arg( options.cols1 )
56    chr_col_2, start_col_2, end_col_2, strand_col2, name_col_2 = parse_cols_arg( options.cols2 )
57    input1, input2, input3 = args
58except Exception, eee:
59    print eee
60    stop_err( "Data issue: click the pencil icon in the history item to correct the metadata attributes." )
61
62if options.allow_zeros:
63    get_value = float
64else:
65    get_value = get_float_no_zero
66RecombChrDict = collections.defaultdict(list)
67
68skipped = 0
69for line in open( input2 ):
70    temp = line.strip().split()
71    try:
72        value = get_value( temp[ name_col_2 ] )
73    except Exception:
74        skipped += 1
75        continue
76    tempIndex = [ int( temp[ start_col_2 ] ), int( temp[ end_col_2 ] ), value ]
77    RecombChrDict[ temp[ chr_col_2 ] ].append( tempIndex )
78
79print "Skipped %d features with invalid values" % (skipped)
80
81fdd = open( input3, 'w' )
82for line in open( input1 ):
83    line = line.strip()
84    temp = line.split('\t')
85    chromosome = temp[ chr_col_1 ]
86    start = int( temp[ start_col_1 ] )
87    stop = int( temp[ end_col_1 ] )
88    start_stop = [start, stop]
89    RecombRate = FindRate( chromosome, start_stop, RecombChrDict )
90    try:
91        RecombRate = "%.4f" % (float(RecombRate))
92    except:
93        RecombRate = RecombRate
94    fdd.write( "%s\t%s\n" % ( line, RecombRate ) )
95fdd.close()