comparison draw_circos.py @ 0:b73148507037 draft default tip

Uploaded
author greg
date Wed, 15 Mar 2023 19:57:22 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:b73148507037
1 #!/usr/bin/env python
2
3 import argparse
4 import os
5 import subprocess
6 import sys
7 import tempfile
8
9 import Bio.SeqIO
10 import numpy
11 import pandas
12
13
14 def format_kmg(number, decimals=0):
15 if number == 0:
16 return '0'
17 magnitude_powers = [10**9, 10**6, 10**3, 1]
18 magnitude_units = ['G', 'M', 'K', '']
19 for i in range(len(magnitude_units)):
20 if number >= magnitude_powers[i]:
21 magnitude_power = magnitude_powers[i]
22 magnitude_unit = magnitude_units[i]
23 return ('{:0.' + str(decimals) + 'f}').format(number / magnitude_power) + magnitude_unit
24
25
26 def load_fasta(fasta_file):
27 sequence = pandas.Series(dtype=object)
28 for contig in Bio.SeqIO.parse(fasta_file, 'fasta'):
29 sequence[contig.id] = contig
30 return sequence
31
32
33 def nicenumber(x, round):
34 exp = numpy.floor(numpy.log10(x))
35 f = x / 10**exp
36 if round:
37 if f < 1.5:
38 nf = 1.0
39 elif f < 3.0:
40 nf = 2.0
41 elif f < 7.0:
42 nf = 5.0
43 else:
44 nf = 10.0
45 else:
46 if f <= 1.0:
47 nf = 1.0
48 elif f <= 2.0:
49 nf = 2.0
50 elif f <= 5.0:
51 nf = 5.0
52 else:
53 nf = 10.0
54 return nf * 10.0**exp
55
56
57 def pretty(low, high, n):
58 rnge = nicenumber(high - low, False)
59 d = nicenumber(rnge / (n - 1), True)
60 miny = numpy.floor(low / d) * d
61 maxy = numpy.ceil(high / d) * d
62 return numpy.arange(miny, maxy + 0.5 * d, d)
63
64
65 def run_command(cmd):
66 try:
67 tmp_name = tempfile.NamedTemporaryFile(dir=".").name
68 tmp_stderr = open(tmp_name, 'wb')
69 proc = subprocess.Popen(args=cmd, shell=True, stderr=tmp_stderr.fileno())
70 returncode = proc.wait()
71 tmp_stderr.close()
72 if returncode != 0:
73 # Get stderr, allowing for case where it's very large.
74 tmp_stderr = open(tmp_name, 'rb')
75 stderr = ''
76 buffsize = 1048576
77 try:
78 while True:
79 stderr += tmp_stderr.read(buffsize)
80 if not stderr or len(stderr) % buffsize != 0:
81 break
82 except OverflowError:
83 pass
84 tmp_stderr.close()
85 os.remove(tmp_name)
86 stop_err(stderr)
87 except Exception as e:
88 stop_err('Command:\n%s\n\nended with error:\n%s\n\n' % (cmd, str(e)))
89
90
91 def stop_err(msg):
92 sys.stderr.write(msg)
93 sys.exit(1)
94
95
96 def draw_circos(circos_conf, dnadiff_1coords_file, output_png_dir, reference, reference_sequence_lengths_file, tick_base_conf):
97 ofh = open('process_log', 'w')
98 ofh.write("circos_conf: %s\n" % str(circos_conf))
99 ofh.write("reference: %s\n" % str(reference))
100 reference_contigs = reference.index.tolist()
101 ofh.write("reference_contigs: %s\n" % str(reference_contigs))
102 # Draw one circos plot for each of the contigs in the reference sequence.
103 for contig in reference_contigs:
104 ofh.write("contig: %s\n" % str(contig))
105 contig_dir = os.path.join('circos_dir', contig)
106 os.makedirs(contig_dir)
107 # Pull the aligned regions out of the dnadiff 1coords file.
108 cmd = ' '.join(['cat', dnadiff_1coords_file,
109 '| awk \'$12 == "' + contig + '"\'',
110 '| awk \'{OFS = "\t";print $(NF - 1),$1,$2}\'',
111 '| bedtools complement -g', reference_sequence_lengths_file, '-i -',
112 '| awk \'$3 - $2 >= 25\'',
113 '| bedtools complement -g', reference_sequence_lengths_file, '-i -',
114 '| awk \'{OFS = "\t";print $1,$2,$3}\'',
115 '| awk \'$1 == "' + contig + '"\'',
116 '>', os.path.join(contig_dir, 'alignment.txt')])
117 ofh.write("cmd: %s\n" % str(cmd))
118 run_command(cmd)
119 # Pull the gap regions out of the dnadiff 1coords file.
120 cmd = ' '.join(['cat', dnadiff_1coords_file,
121 '| awk \'$12 == "' + contig + '"\'',
122 '| awk \'{OFS = "\t";print $(NF - 1),$1,$2}\'',
123 '| bedtools complement -g', reference_sequence_lengths_file, '-i -',
124 '| awk \'$3 - $2 >= 25\'',
125 '| awk \'{OFS = "\t";print $1,$2,$3}\'',
126 '| awk \'$1 == "' + contig + '"\'',
127 '>', os.path.join(contig_dir, 'gap.txt')])
128 ofh.write("cmd: %s\n" % str(cmd))
129 run_command(cmd)
130 cmd = ' '.join(['cat', reference_sequence_lengths_file,
131 '| awk \'$1 == "' + contig + '"\'',
132 '| awk \'{OFS = "\t";print "chr\t-",$1,$1,0,$2,"plasmid_grey"}\''
133 '>', os.path.join(contig_dir, 'karyotype.txt')])
134 ofh.write("cmd: %s\n" % str(cmd))
135 run_command(cmd)
136 # Figure out the tick labels to use and where to place them.
137 # We don't want the last tick since this thing is circular.
138 tick_at = pretty(1, len(reference[contig].seq), 12).astype(int)[:-1]
139 tick_major = tick_at[1] - tick_at[0]
140 tick_minor = tick_major / 5
141 cmd = ' '.join(['cat', tick_base_conf,
142 '| awk \'{sub("TICK_MAJOR", "' + str(tick_major) + '", $0);',
143 'sub("TICK_MINOR", "' + str(tick_minor) + '", $0);print}\'',
144 '>', os.path.join(contig_dir, 'tick.conf')])
145 ofh.write("cmd: %s\n" % str(cmd))
146 run_command(cmd)
147 tick_labels = [format_kmg(i) for i in tick_at]
148 tick_data = pandas.DataFrame()
149 for i in range(len(tick_labels)) :
150 tick_data = pandas.concat([tick_data, pandas.Series([contig, tick_at[i], tick_at[i], tick_labels[i]])], axis=1)
151 tick_data = tick_data.transpose()
152 tick_data.to_csv(path_or_buf=os.path.join(contig_dir, 'tick.txt'), sep='\t', header=False, index=False)
153 cmd = ' '.join(['cd', contig_dir,
154 '&& circos --conf', os.path.abspath(circos_conf)])
155 ofh.write("cmd: %s\n" % str(cmd))
156 run_command(cmd)
157 # Move the circos png file for the current
158 # contig to the collection output directory.
159 ofh.write("\nrenaming: %s to be named %s\n" % (str(os.path.join(contig_dir, 'circos.png')), str(os.path.join(output_png_dir, '%s.png' % contig))))
160 os.rename(os.path.join(contig_dir, 'circos.png'), os.path.join(output_png_dir, '%s.png' % contig))
161 ofh.close()
162
163
164 if __name__ == '__main__':
165 parser = argparse.ArgumentParser()
166
167 parser.add_argument('--circos_conf', action='store', dest='circos_conf', help='Circos configuration file')
168 parser.add_argument('--dnadiff_1coords_file', action='store', dest='dnadiff_1coords_file', help='Dnadiff 1coords tabular file')
169 parser.add_argument('--output_png_dir', action='store', dest='output_png_dir', help='Directory for all circos png outputs')
170 parser.add_argument('--reference_file', action='store', dest='reference_file', help='Reference genome fasta file')
171 parser.add_argument('--reference_sequence_lengths_file', action='store', dest='reference_sequence_lengths_file', help='Reference sequence lengths tabular file')
172 parser.add_argument('--tick_base_conf', action='store', dest='tick_base_conf', help='Tick base configuration file')
173
174 args = parser.parse_args()
175
176 # Load the reference genome into memory.
177 reference = load_fasta(args.reference_file)
178
179 draw_circos(args.circos_conf, args.dnadiff_1coords_file, args.output_png_dir, reference, args.reference_sequence_lengths_file, args.tick_base_conf)