annotate draw_circos.py @ 0:b73148507037 draft default tip

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