0
|
1 #!/usr/bin/env python
|
2
|
2 # New in this version:
|
|
3 # - handle commented-out header lines
|
|
4 # - did everything through the Rpy2 interface instead of inline R code
|
0
|
5
|
|
6 import os,sys,numpy
|
|
7 from rpy2.robjects import Formula
|
|
8 from rpy2.robjects.packages import importr
|
|
9 from rpy2 import robjects
|
|
10
|
|
11 def fail(message):
|
|
12 sys.stderr.write(message+'\n')
|
|
13 sys.exit(1)
|
|
14
|
|
15 args = sys.argv[1:]
|
|
16 if '-r' in args:
|
|
17 make_report = True
|
|
18 else:
|
|
19 make_report = False
|
|
20 if len(args) >= 1:
|
|
21 infile = args[0]
|
|
22 else:
|
|
23 fail('Error: No input filename provided (as argument 1).')
|
|
24 if len(args) >= 2:
|
|
25 outfile = args[1]
|
|
26 else:
|
|
27 fail('Error: No output filename provided (as argument 2).')
|
|
28 if len(args) >= 3:
|
|
29 report = args[2]
|
|
30 elif make_report:
|
|
31 fail('Error: No output report filename provided (as argument 3).')
|
|
32
|
2
|
33 # Check input file
|
0
|
34 if not os.path.exists(infile):
|
|
35 fail('Error: Input file '+infile+' could not be found.')
|
2
|
36 with open(infile, 'r') as lines:
|
|
37 line = lines.readline()
|
|
38 if not line:
|
|
39 fail('Error: Input file seems to be empty')
|
|
40 line = line.strip().lstrip('#') # rm whitespace, comment chars
|
|
41 labels = line.split("\t")
|
|
42 if 'SAMPLE' not in labels or labels[11] != 'MINOR.FREQ.PERC.':
|
|
43 fail('Error: Input file does not seem to have a proper header line.')
|
0
|
44
|
|
45
|
|
46 utils = importr('utils')
|
|
47 graphics = importr('graphics')
|
|
48 base = importr('base')
|
|
49 stats = importr('stats')
|
|
50 rprint = robjects.globalenv.get("print")
|
|
51 grdevices = importr('grDevices')
|
|
52 grdevices.png(file=outfile, width=1024, height=768)
|
|
53
|
|
54 # Read file into a data frame
|
|
55 DATA = utils.read_delim(infile)
|
2
|
56 # Remove comment from header, if
|
|
57 labels = robjects.r.names(DATA)
|
|
58 if labels[0][0:2] == 'X.':
|
|
59 labels[0] = labels[0][2:]
|
|
60 #robjects.r.assign('data', DATA)
|
|
61 #robjects.r('data$MINOR.FREQ.PERC. = data$MINOR.FREQ.PERC. * 100')
|
|
62 #DATA = robjects.r('data')
|
|
63 #index = data.names.index('MINOR.FREQ.PERC.')
|
0
|
64 # Multiply minor allele frequencies by 100 to get percentage
|
2
|
65 # .rx2() looks up a column by its label and returns it as a vector
|
|
66 # .ro turns the returned object into one that can be operated on per-element
|
|
67 minor_freq = DATA.rx2('MINOR.FREQ.PERC.').ro * 100
|
|
68 samples = DATA.rx2('SAMPLE')
|
0
|
69 # Formula() creates a Python object representing the R object returned by x ~ y
|
2
|
70 formula = Formula('minor_freq ~ samples')
|
0
|
71 # The "environment" in .getenvironment() is the entire R workspace in which the
|
|
72 # Formula object exists. The R workspace meaning all the defined variables.
|
|
73 # Here, the .getenvironment() method is being used to set some variables in the
|
|
74 # R workspace
|
2
|
75 formula.getenvironment()['minor_freq'] = minor_freq
|
|
76 formula.getenvironment()['samples'] = samples
|
0
|
77
|
|
78 # create boxplot - fill kwargs1 with the options for the boxplot function
|
2
|
79 kwargs1 = {'ylab':"Minor allele frequency (%)", 'col':"gray", 'xaxt':"n", 'outpch':"*",'main':"Distribution of minor allele frequencies >= 2%", 'cex.lab':"1.5"}
|
0
|
80 p = graphics.boxplot(formula, **kwargs1)
|
|
81
|
2
|
82 table = base.table(DATA.rx2('SAMPLE'))
|
|
83 graphics.text(0.5, 1, 'N:', font=2)
|
|
84 for i in range(1, base.length(table)[0]+1, 1):
|
|
85 graphics.text(i, 1, table[i-1], font=2)
|
0
|
86
|
2
|
87 graphlabels = base.names(table)
|
0
|
88 kwargs3 = {'pos':"0", 'las':"2", 'cex.axis':"1"}
|
2
|
89 graphics.axis(1, at=range(1, len(graphlabels)+1, 1), labels=graphlabels, **kwargs3)
|
0
|
90 grdevices.dev_off()
|
|
91
|
|
92 if not make_report:
|
|
93 sys.exit(0)
|
|
94
|
2
|
95
|
0
|
96 ####################################
|
|
97 # GENERATE REPORT
|
|
98 # report should be something like:
|
|
99 # SAMPLE NoHET MEDIAN MAD TEST
|
|
100 # s1 7 10% n p/w/f
|
|
101 # n <= 5 pass
|
|
102 # 6 <= n <=10 warn
|
|
103 # n >= 11 fail
|
|
104 # MAD <= 2.0 fail
|
|
105 # MAD > 2.0 pass
|
|
106 ###################################
|
|
107
|
|
108 SAMPLES=[]
|
|
109 for i in range(len(tab)):
|
|
110 SAMPLES.append(base.names(tab)[i])
|
|
111
|
|
112 def boxstats(data,sample):
|
|
113 VALUES = [100*float(x.strip().split('\t')[11]) for x in list(open(data)) if x.strip().split('\t')[0]==sample]
|
|
114 NoHET = len(VALUES)
|
|
115 MEDIAN = numpy.median(VALUES)
|
|
116 MAD = numpy.median([abs(i - MEDIAN) for i in VALUES]) # Median absolute distance (robust spread statistic)
|
|
117 return [NoHET,MEDIAN, MAD]
|
|
118
|
|
119 boxreport = open(report, "w+")
|
|
120 boxreport.write("SAMPLE\tTOTAL.SITES\tMEDIAN.FREQ.\tMAD.FREQ\tEVAL\n")
|
|
121 for sample in SAMPLES:
|
|
122 ENTRY = [sample] + boxstats(infile,sample)
|
|
123 if ENTRY[1] <= 5:
|
|
124 ENTRY.append('pass')
|
|
125 elif 6 <= ENTRY[1] <=10:
|
|
126 ENTRY.append('warn')
|
|
127 elif ENTRY[1] >= 11:
|
|
128 ENTRY.append('fail')
|
|
129 if ENTRY[3] <=2.0:
|
|
130 ENTRY.append('fail')
|
|
131 elif ENTRY[3] >2.0:
|
|
132 ENTRY.append('pass')
|
|
133 if len(set(ENTRY[4:6])) == 2:
|
|
134 ENTRY.append('warn')
|
|
135 else:
|
|
136 ENTRY.append(list(set(ENTRY[4:6]))[0])
|
|
137 boxreport.write ('%s\t%d\t%.1f\t%.1f\t%s\n' % tuple([ENTRY[i] for i in [0,1,2,3,6]]))
|
|
138
|
|
139 boxreport.close()
|
|
140
|
|
141
|
|
142
|
|
143
|
|
144
|
|
145
|
|
146 #####################################
|
|
147 #STUFF
|
|
148 #
|
|
149 #kwargs = {'ylab':"Minor allele frequency (sites >= 2%)",'col':"blue", 'axes':"FALSE", 'outpch':"*", 'ylim':"c(-0.03,0.5)", 'main':"Minor allele frequencies run020 at 2%"}
|
|
150 #boxplot(freq~id,data=run020[run020$freq>=0.02,], col="blue", axes=FALSE, outpch="*", ylab="Minor allele frequency (sites >= 2%)", ylim=c(-0.03,0.5), main="Minor allele frequencies run020 at 2%")
|
|
151 #biglabels2=sort(as.vector(unique(run020$id)))
|
|
152 #biglabels=apply(as.matrix(biglabels2), 1,function(x) substr(x,1,5))
|
|
153 #axis(1, at=c(1:length(biglabels)),labels=biglabels, pos=-0.02, las=2, cex.axis=0.9)
|
|
154 #axis(2, at=c(seq(0,50,5)/100), pos=0,cex.axis=0.9)
|
|
155 #nbig=as.vector(table(run020[run020$freq>=0.02,1]))
|
|
156 #for (i in 1:length(nbig)){text(i,-0.01,nbig[i],cex=0.9, font=2)}
|
|
157
|