0
|
1 #!/usr/bin/env python
|
|
2
|
|
3 import argparse
|
|
4 import os
|
7
|
5 import random
|
0
|
6
|
7
|
7 import matplotlib.pyplot as pyplot
|
0
|
8 import pandas
|
|
9 from Bio import SeqIO
|
|
10 from dna_features_viewer import GraphicFeature, GraphicRecord
|
|
11
|
|
12
|
|
13 AMR_COLOR = '#FED976'
|
|
14 INC_GROUPS_COLOR = '#0570B0'
|
|
15 FEATURE_COLORS = [AMR_COLOR, INC_GROUPS_COLOR]
|
|
16 FIGURE_WIDTH = 13
|
|
17
|
|
18
|
7
|
19 def get_random_color():
|
8
|
20 r = lambda: random.randint(0,255)
|
|
21 return '#%02X%02X%02X' % (r(),r(),r())
|
7
|
22
|
|
23
|
0
|
24 def draw_features(feature_hits_files, contigs, output_dir):
|
|
25 ofh = open('process_log', 'w')
|
|
26 # Read feature_hits_files.
|
|
27 feature_hits = pandas.Series(dtype=object)
|
|
28 feature_plots = pandas.Series(dtype=object)
|
|
29 for feature_hits_file in feature_hits_files:
|
|
30 feature_name = os.path.basename(feature_hits_file)
|
|
31 # Make sure the file is not empty.
|
|
32 if os.path.isfile(feature_hits_file) and os.path.getsize(feature_hits_file) > 0:
|
|
33 best_hits = pandas.read_csv(filepath_or_buffer=feature_hits_file, sep='\t', header=None)
|
1
|
34 ofh.write("\nFeature file %s will be processed\n" % os.path.basename(feature_hits_file))
|
0
|
35 else:
|
1
|
36 ofh.write("\nEmpty feature file %s will NOT be processed\n" % os.path.basename(feature_hits_file))
|
0
|
37 best_hits = None
|
|
38 feature_hits[feature_name] = best_hits
|
|
39
|
|
40 # Draw one plot per contig for simplicity.
|
|
41 ofh.write("\nProcessing contigs file: %s\n" % str(contigs))
|
|
42 for contig in SeqIO.parse(contigs, 'fasta'):
|
|
43 ofh.write("Processing contig: %s\n" % str(contig))
|
|
44 contig_plot_png = os.path.join(output_dir, '%s.png' % str(contig.id))
|
|
45 feature_sets_to_plot = pandas.Series(dtype=object)
|
|
46 for feature_number in range(len(feature_hits)):
|
|
47 feature_name = feature_hits.index.to_list()[feature_number]
|
|
48 ofh.write("Processing feature name: %s\n" % str(feature_name))
|
|
49 these_features = feature_hits[feature_name]
|
|
50 if these_features is None or these_features.shape[0] == 0:
|
|
51 # No features.
|
|
52 continue
|
|
53 contig_features = these_features.loc[these_features.iloc[:, 0] == contig.id, :]
|
|
54 if contig_features is None or contig_features.shape[0] == 0:
|
|
55 # No features.
|
|
56 continue
|
|
57 features_to_plot = []
|
|
58 for i in range(contig_features.shape[0]):
|
|
59 i = contig_features.iloc[i, :]
|
8
|
60 if feature_number < len(FEATURE_COLORS):
|
7
|
61 color = FEATURE_COLORS[feature_number]
|
|
62 else:
|
|
63 color = get_random_color()
|
|
64 features_to_plot += [GraphicFeature(start=i[1], end=i[2], label=i[3], strand=1 * i[5], color=color)]
|
0
|
65 feature_sets_to_plot[feature_name] = features_to_plot
|
|
66 ofh.write("Number of features to plot: %d\n" % len(feature_sets_to_plot))
|
|
67 if len(feature_sets_to_plot) == 0:
|
|
68 # No features.
|
|
69 continue
|
|
70 # Determine each plot height for later scaling
|
|
71 expected_plot_heights = []
|
|
72 for i in range(len(feature_sets_to_plot)):
|
|
73 record = GraphicRecord(sequence_length=len(contig), features=feature_sets_to_plot[i])
|
|
74 if i == len(feature_sets_to_plot) - 1:
|
|
75 with_ruler = True
|
|
76 else:
|
|
77 with_ruler = False
|
|
78 plot, _ = record.plot(figure_width=FIGURE_WIDTH, with_ruler=with_ruler)
|
|
79 expected_plot_heights += [plot.figure.get_size_inches()[1]]
|
|
80 plot_height_sum = sum(expected_plot_heights)
|
|
81 # Make a figure with separate plots for each feature class.
|
|
82 plots = pyplot.subplots(nrows=len(feature_sets_to_plot),
|
|
83 ncols=1,
|
|
84 sharex=True,
|
|
85 figsize=(FIGURE_WIDTH, plot_height_sum * .66666),
|
|
86 gridspec_kw={"height_ratios": expected_plot_heights})
|
|
87 figure = plots[0]
|
|
88 plots = plots[1]
|
|
89 if len(feature_sets_to_plot) == 1:
|
|
90 plots = [plots]
|
|
91 # Add each feature class's plot with the pre-determined height.
|
|
92 for i in range(len(feature_sets_to_plot)):
|
|
93 record = GraphicRecord(sequence_length=len(contig), features=feature_sets_to_plot[i])
|
|
94 if i == len(feature_sets_to_plot) - 1:
|
|
95 with_ruler = True
|
|
96 else:
|
|
97 with_ruler = False
|
|
98 plot, _ = record.plot(ax=plots[i], with_ruler=with_ruler, figure_width=FIGURE_WIDTH)
|
|
99 ymin, ymax = plot.figure.axes[0].get_ylim()
|
|
100 if i == 0:
|
|
101 plot.text(x=0, y=ymax, s=contig.id)
|
|
102 figure.tight_layout()
|
|
103 ofh.write("Saving PNG plot file: %s\n" % str(contig_plot_png))
|
|
104 figure.savefig(contig_plot_png)
|
|
105 feature_plots[contig.id] = contig_plot_png
|
|
106 ofh.close()
|
|
107
|
|
108
|
|
109 if __name__ == '__main__':
|
|
110 parser = argparse.ArgumentParser()
|
|
111
|
|
112 parser.add_argument('--feature_hits_dir', action='store', dest='feature_hits_dir', help='Directory of tabular files containing feature hits')
|
|
113 parser.add_argument('--contigs', action='store', dest='contigs', help='Fasta file of contigs')
|
|
114 parser.add_argument('--output_dir', action='store', dest='output_dir', help='Output directory')
|
|
115
|
|
116 args = parser.parse_args()
|
|
117
|
|
118 # Get thge collection of feature hits files. The collection
|
|
119 # will be sorted alphabetically and will contain 2 files
|
|
120 # named something like AMR_CDS_311_2022_12_20.fasta and
|
|
121 # Incompatibility_Groups_2023_01_01.fasta.
|
|
122 feature_hits_files = []
|
|
123 for file_name in sorted(os.listdir(args.feature_hits_dir)):
|
|
124 file_path = os.path.abspath(os.path.join(args.feature_hits_dir, file_name))
|
|
125 feature_hits_files.append(file_path)
|
|
126
|
|
127 draw_features(feature_hits_files, args.contigs, args.output_dir)
|