-
Notifications
You must be signed in to change notification settings - Fork 4
/
paf_to_dotplot.py
executable file
·394 lines (300 loc) · 11.6 KB
/
paf_to_dotplot.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
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
#!/usr/bin/env python3
## Pombert lab, 2024
version = '0.5e'
updated = '2024-06-06'
name = 'paf_to_dotplot.py'
import sys
import os
import re
import matplotlib
import matplotlib.pyplot as plt
import argparse
import seaborn as sns
from multiprocessing import Pool, Value
matplotlib.use('agg')
################################################################################
## README
################################################################################
usage = f"""
NAME {name}
VERSION {version}
UPDATED {updated}
SYNOPSIS Create genome alignment dotplots from PAF files with matplotlib
REQS matplotlib
COMMAND {name} \\
-p *.paf \\
-o DOTPLOTS
OPTIONS:
-p (--paf) PAF file(s) to plot
-f (--fasta) FASTA files used to generate PAF alignments
-o (--outdir) Output directory [Default: ./]
-u (--unit) Units divider [Default: 1e5]
-h (--height) Figure height in inches [Default: 10.8]
-w (--width) Figure width in inches [Default: 19.2]
-c (--color) Color [Default: blue]
-n (--noticks) Turn off ticks on x and y axes
-x (--affix) Add affix to filename
-a (--palette) Use a color palette (e.g. Spectral) instead
of a monochrome plot
--wdis Horizontal distance (width) between subplots [Default: 0.05]
--hdis Vertical distance (height) between subplots [Default: 0.1]
--fontsize Font size [Default: 8]
--threads Number of threads to use [Default: 16]
--version Show script version
"""
# Print custom message if argv is empty
if (len(sys.argv) <= 1):
print(usage)
exit(0)
################################################################################
## Create command lines switches
################################################################################
cmd = argparse.ArgumentParser(add_help=False)
cmd.add_argument("-p", "--paf", nargs='*')
cmd.add_argument("-f", "--fasta", nargs='*')
cmd.add_argument("-o", "--outdir", default='./')
cmd.add_argument("-u", "--unit", default='1e5')
cmd.add_argument("-h", "--height", default=10.8)
cmd.add_argument("-w", "--width", default=19.2)
cmd.add_argument("-c", "--color", default='blue')
cmd.add_argument("-x", "--affix")
cmd.add_argument("-a", "--palette")
cmd.add_argument("-n", "--noticks", action='store_true')
cmd.add_argument("--wdis", default=0.05)
cmd.add_argument("--hdis", default=0.1)
cmd.add_argument("--fontsize", default=8)
cmd.add_argument("--threads", default=16)
cmd.add_argument("--version", action='store_true')
args = cmd.parse_args()
paf_files = args.paf
fasta_files = args.fasta
outdir = args.outdir
unit = args.unit
height = args.height
width = args.width
ccolor = args.color
affix = args.affix
color_palette = args.palette
noticks = args.noticks
wdis = args.wdis
hdis = args.hdis
fontsize = int(args.fontsize)
threads = int(args.threads)
scversion = args.version
#########################################################################
### Version
#########################################################################
if scversion:
print ("")
print (f"Script: {name}")
print (f"Version: {version}")
print (f"Updated: {updated}\n")
exit(0)
################################################################################
## Working on output directory
################################################################################
svgdir = outdir + '/SVG'
pngdir = outdir + '/PNG'
subdirs = [outdir,svgdir,pngdir]
for dir in subdirs:
if os.path.isdir(dir) == False:
try:
os.makedirs(dir)
except:
sys.exit(f"Can't create directory {dir}...")
################################################################################
## Parsing FASTA file(s)
################################################################################
len_dict = {}
if fasta_files is not None:
for fasta in fasta_files:
basename = os.path.basename(fasta)
x = re.search(r'(\S+)\.fasta', basename)
if x:
basename = x.group(1)
len_dict[basename] = {}
seqname = None
with open(fasta) as f:
for line in f:
m = re.search(r'>(\S+)', line)
if m:
seqname = m.group(1)
len_dict[basename][seqname] = 0
else:
length = len(line.strip())
len_dict[basename][seqname] += length
################################################################################
## Parsing and plotting PAF file(s)
################################################################################
lsize = len(paf_files) * 2
counter = Value('i', 0)
def dotplot(paf):
global counter
basename = os.path.basename(paf)
qfile = None
sfile = None
m = re.search(r'^(\w+)_vs_(\w+)', basename)
if m:
sfile = m.group(1)
qfile = m.group(2)
dataframe = {}
query_len_dict = {}
subject_len_dict = {}
if fasta_files is not None:
query_len_dict = len_dict[qfile]
subject_len_dict = len_dict[sfile]
with open(paf) as file:
matchnum = 0
for line in file:
matchnum += 1
# PAF data structure:
# https://github.com/lh3/miniasm/blob/master/PAF.md
data = line.split("\t")
query = data[0]
query_len = int(data[1])
q_start = int(data[2])
q_end = int(data[3])
orientation = data[4]
subject = data[5]
subject_len = int(data[6])
s_start = int(data[7])
s_end = int(data[8])
if fasta_files is None:
query_len_dict[query] = query_len
subject_len_dict[subject] = subject_len
if query not in dataframe:
dataframe[query] = {}
if subject not in dataframe[query]:
dataframe[query][subject] = {}
dataframe[query][subject][matchnum] = {}
if orientation == '+':
dataframe[query][subject][matchnum] = [(q_start,q_end),(s_start,s_end)]
else:
dataframe[query][subject][matchnum] = [(q_start,q_end),(s_end,s_start)]
##### Output file(s)
output = basename
global ccolor
acolor = ccolor
if color_palette:
acolor = color_palette
global affix
if noticks:
affix = 'noticks'
suffix = ''
if affix is not None:
suffix = '.' + affix
pngfile = pngdir + '/' + output.rsplit('.', 1)[0] + suffix + f".{unit}" + f".{width}x{height}" + f".{acolor}" + '.png'
svgfile = svgdir + '/' + output.rsplit('.', 1)[0] + suffix + f".{unit}" + f".{width}x{height}" + f".{acolor}" + '.svg'
##### Plotting
x_axes_total = int(len(query_len_dict))
y_axes_total = int(len(subject_len_dict))
subplots_total = x_axes_total * y_axes_total
# Setting default image to widescreen by default
plt.rcParams['svg.fonttype'] = 'none'
plt.rcParams["figure.figsize"] = (width,height)
plt.rcParams.update({'font.size': fontsize})
# color palette
palette = sns.color_palette(color_palette, len(query_len_dict))
if noticks:
plt.setp(axes, xticks=[], yticks=[])
## Convert scientific notation to number
divider = int(float(unit))
## No subplot
if subplots_total == 1:
xlabel = list(query_len_dict.keys())[0]
ylabel = list(subject_len_dict.keys())[0]
plt.xlabel(xlabel)
plt.ylabel(ylabel)
xmax = query_len_dict[xlabel] / divider
ymax = subject_len_dict[ylabel] / divider
plt.xlim(1,xmax)
plt.ylim(1,ymax)
if color_palette:
ccolor = palette[0]
for x in dataframe[xlabel][ylabel]:
xmono = dataframe[xlabel][ylabel][x][0]
ymono = dataframe[xlabel][ylabel][x][1]
plt.plot([x / divider for x in xmono], [y / divider for y in ymono], color=ccolor)
## With subplots
elif subplots_total > 1:
fig, axes = plt.subplots(y_axes_total, x_axes_total, sharex='col', sharey='row')
fig.suptitle(basename)
ynum = 0
xnum = 0
cnum = 0
znum = 0
for query in sorted(query_len_dict):
for subject in reversed(sorted(subject_len_dict)):
if color_palette:
ccolor = palette[cnum]
xmax = query_len_dict[query] / divider
ymax = subject_len_dict[subject] / divider
## 1-dimensional array
if ((x_axes_total == 1) or (y_axes_total == 1)):
axes[znum].set_xlim(1,xmax)
axes[znum].set_ylim(1,ymax)
if y_axes_total > 1:
axes[znum].set_ylabel(subject, rotation=45, ha='right')
## x-axes labels and ticks
if (ynum + 1) == len(subject_len_dict):
axes[znum].set_xlabel(query, rotation=45, ha='right')
if (ynum + 1) < len(subject_len_dict):
axes[znum].get_xaxis().set_visible(False)
else:
axes[znum].set_xlabel(query, rotation=45, ha='right')
axes[znum].set_ylabel(subject, rotation=45, ha='right')
if xnum > 0:
axes[znum].get_yaxis().set_visible(False)
## multidimensional array
else:
axes[ynum,xnum].set_xlim(1,xmax)
axes[ynum,xnum].set_ylim(1,ymax)
## x-axes labels and ticks
if (ynum + 1) == len(subject_len_dict):
axes[ynum,xnum].set_xlabel(query, rotation=45, ha='right')
if (ynum + 1) < len(subject_len_dict):
axes[ynum,xnum].get_xaxis().set_visible(False)
# y-axes labels and ticks
if (xnum == 0):
axes[ynum,xnum].set_ylabel(subject, rotation=45, ha='right')
if (xnum > 0):
axes[ynum,xnum].get_yaxis().set_visible(False)
# subplots data
if query in dataframe:
if subject in dataframe[query]:
for x in dataframe[query][subject]:
x1 = dataframe[query][subject][x][0]
y1 = dataframe[query][subject][x][1]
# 1-dimensional array
if ((x_axes_total == 1) or (y_axes_total == 1)):
axes[znum].plot([x / divider for x in x1], [y / divider for y in y1], color=ccolor)
# multidimensional array
else:
axes[ynum,xnum].plot([x / divider for x in x1], [y / divider for y in y1], color=ccolor)
if ((x_axes_total == 1) or (y_axes_total == 1)):
znum += 1
ynum += 1
cnum += 1
xnum += 1
ynum = 0
## Reducing space between subplots
plt.subplots_adjust(
wspace=float(wdis),
hspace=float(hdis)
)
##### Writing to output file
with counter.get_lock():
counter.value += 1
print(f"{counter.value} / {lsize} - plotting {pngfile}...")
plt.savefig(pngfile)
with counter.get_lock():
counter.value += 1
print(f"{counter.value} / {lsize} - plotting {svgfile}...")
plt.savefig(svgfile)
## Close fig
plt.clf()
plt.cla()
plt.close('all')
## Run
pool = Pool(threads)
pool.map(dotplot, paf_files)