-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpolyplotter.py
More file actions
executable file
·429 lines (353 loc) · 11.7 KB
/
polyplotter.py
File metadata and controls
executable file
·429 lines (353 loc) · 11.7 KB
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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/env python
# coding: utf-8
import sys
import csv
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import gaussian_kde
from Utils import CSVreader, Pathname
## Classes
class Plot():
outfile = None
imgformat = "png"
title = None
xlabel = None
ylabel = None
xsize = 10
ysize = 8
def parseCommonArgs(self, args):
other = []
prev = ""
for a in args:
if prev == "-o":
self.outfile = a
prev = ""
elif prev == "-t":
self.title = a
prev = ""
elif prev == "-xl":
self.xlabel = a
prev = ""
elif prev == "-yl":
self.ylabel = a
prev = ""
elif prev == "-xs":
self.xsize = float(a)
prev = ""
elif prev == "-ys":
self.ysize = float(a)
prev = ""
elif prev == "-f":
self.imgformat = a
prev = ""
elif a in ["-o", "-t", "-xl", "-yl", "-f", "-xs", "-ys"]:
prev = a
else:
other.append(a)
return other
class DensityPlot(Plot):
infile = None
log = False
hasHeader = None
skipRows = None
pointSize = 50
cx = 4
cy = 3
def parseArgs(self, args):
if "-h" in args or "--help" in args:
return self.usage()
args = self.parseCommonArgs(args)
prev = ""
for a in args:
if prev == "-cx":
self.cx = int(a)
prev = ""
elif prev == "-cy":
self.cy = int(a)
prev = ""
elif prev == "-s":
self.skipRows = int(a)
prev = ""
elif prev == "-p":
self.pointSize = int(a)
prev = ""
elif a in ["-cx", "-cy", "-s", "-p"]:
prev = a
elif a == "-l":
self.log = np.log(2)
elif a == "-l10":
self.log = np.log(10)
elif a == "-t":
self.hasHeader = 0
elif self.infile is None:
self.infile = a
return (self.infile and self.outfile)
def run(self):
df = pd.read_table(self.infile, header=self.hasHeader, skiprows=self.skipRows)
sys.stderr.write("Data file read.\n")
if self.log:
df[self.cy] = df[self.cy].apply(lambda x: np.log(x+1) / self.log)
df[self.cx] = df[self.cx].apply(lambda x: np.log(x+1) / self.log)
min_x = min(df[self.cx])-0.1
min_y = min(df[self.cy])-0.1
xy = np.vstack([df[self.cx], df[self.cy]])
z = gaussian_kde(xy)(xy)
idx = z.argsort()
x, y, z = df[self.cx][idx], df[self.cy][idx], z[idx]
fig, ax = plt.subplots(figsize=(self.xsize, self.ysize))
ax.scatter(x, y, c=z, s=self.pointSize, edgecolor='')
if self.log:
plt.xlim(xmin=min_x)
plt.ylim(ymin=min_y)
diag_line, = ax.plot(ax.get_xlim(), ax.get_ylim(), ls="-", c="0.3")
if self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel:
plt.ylabel(self.ylabel)
plt.savefig(self.outfile, format=self.imgformat)
def usage(self):
sys.stdout.write("""polyplotter.py dscatt - Draw density scatterplots of paired data.
Usage: polyplotter.py dscatt [options] datafile imgfile
Read data from two columns of file `datafile' and draw a density heatmap
of their scatterplot to `imgfile'.
Options related to input data:
-cx C | Use column C for X axis coordinates (default: {}).
-cy C | Use column C for Y axis coordinates (default: {}).
-s S | Skip S rows from top of input file (default: {}).
-l | If supplied, log-transform data (base 2).
-l10 | If supplied, log-transform data (base 10).
Graphical options:
-xs S | Set X dimension of image to S inches (default: {}).
-ys S | Set Y dimension of image to S inches (default: {}).
-xl L | Set X axis label to L.
-yl L | Set Y axis label to L.
-p P | Set dot size to P (default: {}).
-f F | Set output image format to F (default: {}).
""".format(DensityPlot.cx, DensityPlot.cy, DensityPlot.skipRows, DensityPlot.xsize, DensityPlot.ysize, DensityPlot.pointSize, DensityPlot.imgformat))
sys.exit(1)
class MethylHist(Plot):
infile = None
def parseArgs(self, args):
if "-h" in args or "--help" in args:
return self.usage()
args = self.parseCommonArgs(args)
prev = ""
for a in args:
if self.infile == None:
self.infile = a
return (self.infile and self.outfile)
def makeHistogramFromColumn(self, column, edges, normalize=False):
nbins = len(edges) - 1
bins = np.zeros(nbins)
for line in CSVreader(self.infile):
x = float(line[column])
if x < edges[0]:
continue
for i in range(nbins):
if x < edges[i+1]:
bins[i] += 1
break
if normalize:
bins = bins / np.sum(bins)
return bins
def run(self):
path = Pathname(self.infile)
edges = np.linspace(0.0, 1.0, num=11, endpoint=True)
bins = self.makeHistogramFromColumn(3, edges, normalize=True)
xc = [ int((x - 0.05) * 100) for x in edges[1:] ]
fig, ax = plt.subplots(1, 1, figsize=(self.xsize, self.ysize))
ax.bar(xc, bins, width=8)
if self.title:
ax.set_title(self.title)
else:
ax.set_title("{} - histogram of methylation values".format(path.name))
ax.set_xlabel("% Methylation")
ax.set_ylabel("% Sites")
fig.savefig(self.outfile)
def usage(self):
sys.stdout.write("""polyplotter.py mhist - Draw histogram of methylation data.
Usage: polyplotter.py mhist [options] datafile
Read data from file `datafile' and draw a histogram.
Options related to input data:
- TODO
Graphical options:
- TODO
""".format(MethylHist.infile))
sys.exit(1)
class DistPlot(Plot):
infile = None
log = False
plot_type = None
skipRows = None
pointSize = 50
index_col = 0
cx = 4
cy = 3
def parseArgs(self, args):
if "-h" in args or "--help" in args:
return self.usage()
args = self.parseCommonArgs(args)
prev = ""
for a in args:
if prev == "-i":
self.index_col = a
prev = ""
elif prev == "-p":
self.plot_type = a
prev = ""
elif a in ["-i","-p"]:
prev = a
if a == "-l":
self.log = np.log(2)
elif a == "-l10":
self.log = np.log(10)
if self.infile == None:
self.infile = a
if self.plot_type == None:
self.plot_type = "box"
return (self.infile and self.outfile)
def run(self):
df = pd.read_table(self.infile, index_col=self.index_col)
sys.stderr.write("Data file read\n")
df = df.melt()
if self.log:
df.value = df["value"].apply(lambda x: np.log(x+1) / self.log)
if self.plot_type == "box":
ax = sns.boxplot(x="variable", y="value", data=df)
elif self.plot_type == "violin":
ax = sns.violinplot(x="variable", y="value", data=df)
elif self.plot_type == "boxen":
ax = sns.boxenplot(x="variable", y="value", data=df)
else:
sys.stderr.write("Invalid plot_type\n")
self.usage()
if self.title:
plt.title(self.title)
if self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel:
plt.ylabel(self.ylabel)
plt.savefig(self.outfile, format=self.imgformat)
def usage(self):
sys.stdout.write("""polyplotter.py distr - Draw distribution plot ("box", "violin" or "boxen") for each column in data matrix.
Usage: polyplotter.py distr [options] datafile
Read data from n x m matrix `datafile' and draw a boxplot for each column
onto single plot.
Options related to input data:
-l | If supplied, log-scale values (base 2).
-l10 | If supplied, log-scale values (base 10).
Graphical options:
-xs S | Set X dimension of image to S inches (default: {}).
-ys S | Set Y dimension of image to S inches (default: {}).
-xl L | Set X axis label to L.
-yl L | Set Y axis label to L.
-i N | Set index column number to N. (default: {})
-p S | Set plot type to S. (default: {})
-f F | Set output image format to F (default: {}).
""".format(DistPlot.xsize, DistPlot.ysize, DistPlot.index_col, DistPlot.plot_type, DistPlot.imgformat))
sys.exit(1)
class SwarmPlot(Plot):
def parseArgs():
pass
def run():
pass
def usage():
pass
class JointPlot(Plot):
pass
class HeatmapPlot(Plot):
infile = None
log = False
plot_type = None
skipRows = None
pointSize = 50
index_col = 0
cx = 4
cy = 3
def parseArgs(self, args):
pass
def run(self):
df = pd.read_table(self.infile, index_col=self.index_col)
sys.stderr.write("Data file read\n")
df = df.melt()
if self.log:
df.value = df["value"].apply(lambda x: np.log(x+1) / self.log)
if self.cluster:
ax = sns.clustermap(x="variable", y="value", data=df)
else:
ax = sns.heatmap(x="variable", y="value", data=df)
if self.title:
plt.title(self.title)
if self.xlabel:
plt.xlabel(self.xlabel)
if self.ylabel:
plt.ylabel(self.ylabel)
plt.savefig(self.outfile, format=self.imgformat)
def usage(self):
sys.stdout.write("""polyplotter.py heat - Draw heatmap
Usage: polyplotter.py heat [options] datafile
Read data from n x m matrix `datafile' and draw a heat map.
Options related to input data:
-l | If supplied, log-scale values (base 2).
-l10 | If supplied, log-scale values (base 10).
Graphical options:
-xs S | Set X dimension of image to S inches (default: {}).
-ys S | Set Y dimension of image to S inches (default: {}).
-xl L | Set X axis label to L.
-yl L | Set Y axis label to L.
-i N | Set index column number to N. (default: {})
-p S | Set plot type to S. (default: {})
-f F | Set output image format to F (default: {}).
""".format(HeatmapPlot.xsize, HeatmapPlot.ysize, HeatmapPlot.index_col, HeatmapPlot.plot_type, HeatmapPlot.imgformat))
sys.exit(1)
class ScatterPlot(Plot):
pass
class KDEPlot(Plot):
pass
class LinearModelPlot(Plot):
pass
class LinePlot(Plot):
pass
class BarPlot(Plot):
pass
def mainUsage():
sys.stdout.write("""polyplotter.py - command-line tool to generate a variety of useful plots
Usage: polyplotter.py [command] [command-specific_arguments]
Available subcommands:
dscatt
mhist
dist
heat -- coming soon
Ex. polyplotter.py mhist -h
""")
## Main
if __name__ == "__main__":
try:
cmd = sys.argv[1]
args = sys.argv[2:]
except IndexError:
sys.stderr.write("Too few parameters\n")
mainUsage()
sys.exit(1)
if cmd == "dscatt":
P = DensityPlot()
elif cmd == "mhist":
P = MethylHist()
elif cmd == "dist":
P = DistPlot()
else:
mainUsage()
sys.exit(1)
try:
if P.parseArgs(args):
P.run()
else:
P.usage()
except NameError as error:
sys.stderr.write(error)
mainUsage()
sys.exit(1)