-
Notifications
You must be signed in to change notification settings - Fork 0
/
load.py
268 lines (212 loc) · 6.71 KB
/
load.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
import os, sys
import json, csv
import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np
import pylab
import optparse
dictionary = {}
'''
Create the specified directory, if not exists.
'''
def path_to_dir(out):
if not os.path.exists(out) and not out == '':
os.makedirs(out)
if out == '':
home = os.path.expanduser('~')
out = './output/'
os.makedirs(out)
'''
Parse tsv file and get corresponding columns in array.
'''
def parse(out):
files = os.listdir(data)
count = 0
line_num = 0
for file in files:
if file.endswith('.tsv'):
count+=1
print 'Processing file: ' + str(count) + ' of ' + str(len(files))
print 'File name: ' + str(file)
with open(str(data) + file, 'r') as tsv:
reader = csv.reader(tsv, dialect = 'excel-tab', skipinitialspace = True)
next(reader, None)
for line in reader:
IA = []
PP = []
line_num+=1
for index, ele in enumerate(line):
if index >= 8 and index <= 15:
if index == 8:
stop = int(index+30)
else:
stop = int(index+30+2)
if ele == '' or ele == None:
ele = 0.0
if line[stop] == '' or line[stop] == None:
line[stop] = 0.0
IA.append(float(ele))
PP.append(float(line[stop]))
save_dict(IA, PP, str(file))
dictionary = save_dict(IA, PP, str(file))
plot_stat(dictionary, file, str(out + '/'))
'''
Save data in dictionary format.
'''
def save_dict(IA, PP, file):
keys = [
'113',
'114',
'115',
'116',
'117',
'118',
'119',
'121'
]
for index, ele in enumerate(IA):
if str(keys[index]) not in dictionary:
dictionary[str(keys[index])] = {}
if 'x' not in dictionary[str(keys[index])]:
dictionary[str(keys[index])]['x'] = []
dictionary[str(keys[index])]['y'] = []
dictionary[str(keys[index])]['x'].append(ele)
dictionary[str(keys[index])]['y'].append(PP[index])
else:
dictionary[str(keys[index])]['x'].append(ele)
dictionary[str(keys[index])]['y'].append(PP[index])
else:
dictionary[str(keys[index])]['x'].append(ele)
dictionary[str(keys[index])]['y'].append(PP[index])
return dictionary
# jsonify(dictionary, './data/plot_data/')
'''
Scatter plot, linear fit and correlation coefficient.
Display stat details on sub plots.
Save figures.
'''
def plot_stat(dictionary, file, location=None):
fig = pylab.figure(figsize=(7,10))
# gs = gridspec.GridSpec(4, 2, width_ratios=[.5,.5])
count = 0
lis = sorted(dictionary.keys())
for key in lis:
count+=1
axes = dictionary.get(key)
filename = str(file[:-4]) + '.png'
ax = fig.add_subplot(4, 2, (count), adjustable='box-forced')
ax.ticklabel_format(style='sci', axis = 'both', scilimits=(0,0), fontsize = 5.5)
ax.plot(axes.get('x'), axes.get('y'), str(1), color='0.7',
marker='o', markeredgecolor='0.3', alpha=0.5)
ax.set_xlabel('iTRAQAnalyzer', fontsize = 5.5)
ax.set_ylabel('Protein Pilot', fontsize = 5.5)
pylab.rc('font', size=5.5)
# z[0] denotes slope, z[1] denotes the intercept
z = np.polyfit(axes.get('x'), axes.get('y'), 1)
p = np.poly1d(z)
coeff = np.corrcoef(axes.get('x'), axes.get('y'))
ax.plot(axes.get('x'), p(axes.get('x')), "r-", color='0')
if z[1] >= 0:
ax.annotate("y = %.6fx + %.6f "%(z[0],z[1]), xy=(0.97,0.10),xycoords='axes fraction', fontsize=5.5, horizontalalignment='right', verticalalignment='bottom')
else:
ax.annotate("y = %.6fx - %.6f "%(z[0],abs(z[1])), xy=(0.97,0.10), xycoords='axes fraction', fontsize=5.5, horizontalalignment='right', verticalalignment='bottom')
ax.annotate("$\mathregular{R^2}$" + ': ' + str(round(coeff[0][1], 4)), xy=(0.97,0.04), xycoords='axes fraction', fontsize=5.5,horizontalalignment='right', verticalalignment='bottom')
pylab.title(str(key))
fig.tight_layout()
graph = pylab.gcf()
graph.canvas.set_window_title(str(filename))
# pylab.show()
fig.dpi = 400
graph.savefig(location + '/' + filename, dpi = fig.dpi)
pylab.close()
'''
Scatter plot, linear fit and correlation coefficients.
Does not show equations and correlation coefficients on subplots.
Save figures.
'''
def plot_stat_without_eq(dictionary, file, location=None):
fig = pylab.figure()
count = 0
print(type(dictionary))
lis = sorted(dictionary.keys())
for key in lis:
count+=1
axes = dictionary.get(key)
filename = str(file) + '.png'
fig.add_subplot(4, 2, (count))
pylab.ticklabel_format(style='sci', axis = 'both', scilimits=(0,0))
pylab.plot(axes.get('x'), axes.get('y'), str(1), color='0.4', marker='o', markeredgecolor='0.4')
pylab.xlabel('iTRAQAnalyzer')
pylab.ylabel('Protein Pilot')
pylab.rc('font', size=5.5)
# z[0] denotes slope, z[1] denotes the intercept
z = np.polyfit(axes.get('x'), axes.get('y'), 1)
p = np.poly1d(z)
coeff = np.corrcoef(axes.get('x'), axes.get('y'))
pylab.plot(axes.get('x'), p(axes.get('x')), "r-", color='0')
print "y=%.6fx+(%.6f)"%(z[0],z[1])
# pylab.text(0.1, 0.3, "y=%.6fx+(%.6f)"%(z[0],z[1]))
print str(coeff[0][1])
pylab.title(str(key))
pylab.tight_layout()
graph = pylab.gcf()
graph.canvas.set_window_title(str(filename))
graph.savefig(location + '/' + filename)
pylab.close()
'''
Scatter plot and save figures
'''
def plot(dictionary, file, location=None):
# print(dictionary.keys())
for key in dictionary:
axes = dictionary.get(key)
print len(axes.get('y'))
print len(axes.get('x'))
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
# ax.scatter(axes.get('x'), axes.get('y'), c='r', marker='o')
ax.scatter(axes.get('x'), axes.get('y'))
ax.set_xlabel('IA')
ax.set_ylabel('PP')
filename = str(file) + '--' + str(key) + '.png'
fig.canvas.set_window_title(str(filename))
graph = plt.gcf()
plt.show()
graph.savefig(location + '/' + filename)
plt.close()
def parse_column_wise():
pass
def skip_header(tsv):
has_header = csv.Sniffer().has_header(tsv.read())
return has_header
def main():
global out
global data
# data = '../protein_pilot_results/output/'
# out = '../protein_pilot_results/plot_output/'
parser = optparse.OptionParser()
parser.add_option("-d", "--input", action="store", dest="data_dir",
help="Data directory")
parser.add_option("-o", "--output", action="store", dest="output_dir",
help="Directory for plots that are output.")
(options, args) = parser.parse_args()
if not options.data_dir:
data = './data/'
else:
if not options.data_dir[:-1] == '\\':
data = options.data_dir + '\\'
else:
data = options.data_dir
print 'Fetching data from directory: ' + str(data)
if not options.output_dir:
out = './plot_output/'
else:
if not options.output_dir[:-1] == '\\':
out = options.output_dir + '\\'
else:
out = options.output_dir
path_to_dir(out)
print 'Writing output plots to directory: ' + str(out)
if __name__ == '__main__':
main()
parse(out)