0
|
1 import argparse
|
|
2 import os
|
|
3 import pandas
|
|
4 import pypandoc
|
|
5 import re
|
|
6 import subprocess
|
|
7 import sys
|
|
8
|
|
9 from Bio import SeqIO
|
|
10 from datetime import date
|
|
11 from mdutils.mdutils import MdUtils
|
|
12
|
|
13 CDC_ADVISORY = 'The analysis and report presented here should be treated as preliminary. Please contact the CDC/BDRD with any results regarding _Bacillus anthracis_.'
|
|
14
|
|
15
|
|
16 class PimaReport:
|
|
17
|
1
|
18 def __init__(self, analysis_name=None, amr_deletions_file=None, amr_matrix_files=None, assembly_fasta_file=None,
|
2
|
19 assembly_name=None, blastn_version=None, compute_sequence_length_file=None, contig_coverage_file=None,
|
|
20 dbkey=None, dnadiff_snps_file=None, dnadiff_version=None, feature_bed_files=None, feature_png_files=None,
|
|
21 flye_assembly_info_file=None, flye_version=None, genome_insertions_file=None, gzipped=None,
|
|
22 illumina_fastq_file=None, kraken2_report_file=None, kraken2_version=None, mutation_regions_bed_file=None,
|
|
23 mutation_regions_tsv_files=None, pima_css=None, plasmids_file=None, reference_insertions_file=None):
|
0
|
24 self.ofh = open("process_log.txt", "w")
|
|
25
|
1
|
26 self.ofh.write("amr_deletions_file: %s\n" % str(amr_deletions_file))
|
|
27 self.ofh.write("amr_matrix_files: %s\n" % str(amr_matrix_files))
|
0
|
28 self.ofh.write("analysis_name: %s\n" % str(analysis_name))
|
|
29 self.ofh.write("assembly_fasta_file: %s\n" % str(assembly_fasta_file))
|
|
30 self.ofh.write("assembly_name: %s\n" % str(assembly_name))
|
2
|
31 self.ofh.write("blastn_version: %s\n" % str(blastn_version))
|
1
|
32 self.ofh.write("compute_sequence_length_file: %s\n" % str(compute_sequence_length_file))
|
|
33 self.ofh.write("contig_coverage_file: %s\n" % str(contig_coverage_file))
|
|
34 self.ofh.write("dbkey: %s\n" % str(dbkey))
|
|
35 self.ofh.write("dnadiff_snps_file: %s\n" % str(dnadiff_snps_file))
|
2
|
36 self.ofh.write("dnadiff_version: %s\n" % str(dnadiff_version))
|
0
|
37 self.ofh.write("feature_bed_files: %s\n" % str(feature_bed_files))
|
|
38 self.ofh.write("feature_png_files: %s\n" % str(feature_png_files))
|
1
|
39 self.ofh.write("flye_assembly_info_file: %s\n" % str(flye_assembly_info_file))
|
|
40 self.ofh.write("flye_version: %s\n" % str(flye_version))
|
0
|
41 self.ofh.write("gzipped: %s\n" % str(gzipped))
|
1
|
42 self.ofh.write("genome_insertions_file: %s\n" % str(genome_insertions_file))
|
0
|
43 self.ofh.write("illumina_fastq_file: %s\n" % str(illumina_fastq_file))
|
2
|
44 self.ofh.write("kraken2_report_file: %s\n" % str(kraken2_report_file))
|
|
45 self.ofh.write("kraken2_version: %s\n" % str(kraken2_version))
|
0
|
46 self.ofh.write("mutation_regions_bed_file: %s\n" % str(mutation_regions_bed_file))
|
|
47 self.ofh.write("mutation_regions_tsv_files: %s\n" % str(mutation_regions_tsv_files))
|
|
48 self.ofh.write("pima_css: %s\n" % str(pima_css))
|
1
|
49 self.ofh.write("plasmids_file: %s\n" % str(plasmids_file))
|
|
50 # self.ofh.write("reference_genome: %s\n" % str(reference_genome))
|
|
51 self.ofh.write("reference_insertions_file: %s\n" % str(reference_insertions_file))
|
0
|
52
|
|
53 # General
|
|
54 self.doc = None
|
|
55 self.report_md = 'pima_report.md'
|
|
56
|
|
57 # Inputs
|
1
|
58 self.amr_deletions_file = amr_deletions_file
|
|
59 self.amr_matrix_files = amr_matrix_files
|
0
|
60 self.analysis_name = analysis_name
|
|
61 self.assembly_fasta_file = assembly_fasta_file
|
|
62 self.assembly_name = assembly_name
|
2
|
63 self.blastn_version = blastn_version
|
1
|
64 self.compute_sequence_length_file = compute_sequence_length_file
|
|
65 self.contig_coverage_file = contig_coverage_file
|
|
66 self.dbkey = dbkey
|
|
67 self.dnadiff_snps_file = dnadiff_snps_file
|
2
|
68 self.dnadiff_version = dnadiff_version
|
0
|
69 self.feature_bed_files = feature_bed_files
|
|
70 self.feature_png_files = feature_png_files
|
1
|
71 self.flye_assembly_info_file = flye_assembly_info_file
|
|
72 self.flye_version = flye_version
|
0
|
73 self.gzipped = gzipped
|
1
|
74 self.genome_insertions_file = genome_insertions_file
|
0
|
75 self.illumina_fastq_file = illumina_fastq_file
|
2
|
76 self.kraken2_report_file = kraken2_report_file
|
|
77 self.kraken2_version = kraken2_version
|
0
|
78 self.mutation_regions_bed_file = mutation_regions_bed_file
|
|
79 self.mutation_regions_tsv_files = mutation_regions_tsv_files
|
|
80 self.read_type = 'Illumina'
|
|
81 self.ont_bases = None
|
|
82 self.ont_n50 = None
|
|
83 self.ont_read_count = None
|
|
84 self.pima_css = pima_css
|
1
|
85 self.plasmids_file = plasmids_file
|
|
86 # self.reference_genome = reference_genome
|
|
87 self.reference_insertions_file = reference_insertions_file
|
0
|
88
|
|
89 # Titles
|
|
90 self.alignment_title = 'Comparison with reference'
|
|
91 self.alignment_notes_title = 'Alignment notes'
|
|
92 self.amr_matrix_title = 'AMR matrix'
|
|
93 self.assembly_methods_title = 'Assembly'
|
|
94 self.assembly_notes_title = 'Assembly notes'
|
|
95 self.basecalling_title = 'Basecalling'
|
|
96 self.basecalling_methods_title = 'Basecalling'
|
|
97 self.contamination_methods_title = 'Contamination check'
|
|
98 self.contig_alignment_title = 'Alignment vs. reference contigs'
|
|
99 self.feature_title = 'Features found in the assembly'
|
|
100 self.feature_methods_title = 'Feature annotation'
|
|
101 self.feature_plot_title = 'Feature annotation plots'
|
|
102 self.large_indel_title = 'Large insertions & deletions'
|
|
103 self.methods_title = 'Methods'
|
|
104 self.mutation_title = 'Mutations found in the sample'
|
|
105 self.mutation_methods_title = 'Mutation screening'
|
|
106 self.plasmid_methods_title = 'Plasmid annotation'
|
1
|
107 self.plasmid_title = 'Plasmid annotation'
|
0
|
108 self.reference_methods_title = 'Reference comparison'
|
|
109 self.snp_indel_title = 'SNPs and small indels'
|
|
110 self.summary_title = 'Analysis of %s' % analysis_name
|
|
111
|
|
112 # Methods
|
|
113 self.methods = pandas.Series(dtype='float64')
|
|
114 self.methods[self.contamination_methods_title] = pandas.Series(dtype='float64')
|
|
115 self.methods[self.assembly_methods_title] = pandas.Series(dtype='float64')
|
|
116 self.methods[self.reference_methods_title] = pandas.Series(dtype='float64')
|
|
117 self.methods[self.mutation_methods_title] = pandas.Series(dtype='float64')
|
|
118 self.methods[self.feature_methods_title] = pandas.Series(dtype='float64')
|
|
119 self.methods[self.plasmid_methods_title] = pandas.Series(dtype='float64')
|
|
120
|
|
121 # Notes
|
|
122 self.assembly_notes = pandas.Series(dtype=object)
|
|
123 self.alignment_notes = pandas.Series(dtype=object)
|
|
124 self.contig_alignment = pandas.Series(dtype=object)
|
|
125
|
|
126 # Values
|
|
127 self.assembly_size = 0
|
|
128 self.contig_info = None
|
|
129 self.did_medaka_ont_assembly = False
|
|
130 self.feature_hits = pandas.Series(dtype='float64')
|
|
131 self.illumina_length_mean = 0
|
|
132 self.illumina_read_count = 0
|
|
133 self.illumina_bases = 0
|
|
134 self.mean_coverage = 0
|
|
135 self.num_assembly_contigs = 0
|
1
|
136 # TODO: should the following 2 values be passed as parameters?
|
|
137 self.ont_n50_min = 2500
|
|
138 self.ont_coverage_min = 30
|
|
139 self.quast_indels = 0
|
|
140 self.quast_mismatches = 0
|
0
|
141
|
|
142 # Actions
|
|
143 self.did_guppy_ont_fast5 = False
|
|
144 self.did_qcat_ont_fastq = False
|
|
145 self.info_illumina_fastq()
|
|
146 self.load_contig_info()
|
|
147
|
|
148 def run_command(self, command):
|
|
149 self.ofh.write("\nXXXXXX In run_command, command:\n%s\n\n" % str(command))
|
|
150 try:
|
|
151 return re.split('\\n', subprocess.check_output(command, shell=True).decode('utf-8'))
|
|
152 except Exception:
|
|
153 message = 'Command %s failed: exiting...' % command
|
|
154 sys.exit(message)
|
|
155
|
|
156 def format_kmg(self, number, decimals=0):
|
|
157 self.ofh.write("\nXXXXXX In format_kmg, number:\n%s\n" % str(number))
|
|
158 self.ofh.write("XXXXXX In format_kmg, decimals:\n%s\n\n" % str(decimals))
|
|
159 if number == 0:
|
|
160 return '0'
|
|
161 magnitude_powers = [10**9, 10**6, 10**3, 1]
|
|
162 magnitude_units = ['G', 'M', 'K', '']
|
|
163 for i in range(len(magnitude_units)):
|
|
164 if number >= magnitude_powers[i]:
|
|
165 magnitude_power = magnitude_powers[i]
|
|
166 magnitude_unit = magnitude_units[i]
|
|
167 return ('{:0.' + str(decimals) + 'f}').format(number / magnitude_power) + magnitude_unit
|
|
168
|
|
169 def load_contig_info(self):
|
|
170 self.contig_info = pandas.Series(dtype=object)
|
|
171 self.contig_info[self.read_type] = pandas.read_csv(self.contig_coverage_file, header=None, index_col=None, sep='\t').sort_values(1, axis=0, ascending=False)
|
|
172 self.contig_info[self.read_type].columns = ['contig', 'size', 'coverage']
|
|
173 self.mean_coverage = (self.contig_info[self.read_type].iloc[:, 1] * self.contig_info[self.read_type].iloc[:, 2]).sum() / self.contig_info[self.read_type].iloc[:, 1].sum()
|
1
|
174 if self.mean_coverage <= self.ont_coverage_min:
|
|
175 warning = '%s mean coverage ({:.0f}X) is less than the recommended minimum ({:.0f}X).'.format(self.mean_coverage, self.ont_coverage_min) % self.read_type
|
|
176 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
177 # Report if some contigs have low coverage.
|
|
178 low_coverage = self.contig_info[self.read_type].loc[self.contig_info[self.read_type]['coverage'] < self.ont_coverage_min, :]
|
|
179 if low_coverage.shape[0] >= 0:
|
|
180 for contig_i in range(low_coverage.shape[0]):
|
|
181 warning = '%s coverage of {:s} ({:.0f}X) is less than the recommended minimum ({:.0f}X).'.format(low_coverage.iloc[contig_i, 0], low_coverage.iloc[contig_i, 2], self.ont_coverage_min) % self.read_type
|
|
182 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
183 # See if some contigs have anolously low coverage.
|
|
184 fold_coverage = self.contig_info[self.read_type]['coverage'] / self.mean_coverage
|
|
185 low_coverage = self.contig_info[self.read_type].loc[fold_coverage < 1 / 5, :]
|
8
|
186 if low_coverage.shape[0] >= 0:
|
1
|
187 for contig_i in range(low_coverage.shape[0]):
|
|
188 warning = '%s coverage of {:s} ({:.0f}X) is less than 1/5 the mean coverage ({:.0f}X).'.format(low_coverage.iloc[contig_i, 0], low_coverage.iloc[contig_i, 2], self.mean_coverage) % self.read_type
|
|
189 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
0
|
190
|
|
191 def load_fasta(self, fasta):
|
|
192 sequence = pandas.Series(dtype=object)
|
|
193 for contig in SeqIO.parse(fasta, 'fasta'):
|
|
194 sequence[contig.id] = contig
|
|
195 return sequence
|
|
196
|
|
197 def load_assembly(self):
|
|
198 self.assembly = self.load_fasta(self.assembly_fasta_file)
|
|
199 self.num_assembly_contigs = len(self.assembly)
|
|
200 for i in self.assembly:
|
|
201 self.assembly_size += len(i.seq)
|
|
202 self.assembly_size = self.format_kmg(self.assembly_size, decimals=1)
|
|
203
|
|
204 def info_illumina_fastq(self):
|
|
205 self.ofh.write("\nXXXXXX In info_illumina_fastq\n\n")
|
|
206 if self.gzipped:
|
|
207 opener = 'gunzip -c'
|
|
208 else:
|
|
209 opener = 'cat'
|
|
210 command = ' '.join([opener,
|
|
211 self.illumina_fastq_file,
|
|
212 '| awk \'{getline;s += length($1);getline;getline;}END{print s/(NR/4)"\t"(NR/4)"\t"s}\''])
|
|
213 output = self.run_command(command)
|
|
214 self.ofh.write("output:\n%s\n" % str(output))
|
|
215 self.ofh.write("re.split('\\t', self.run_command(command)[0]:\n%s\n" % str(re.split('\\t', self.run_command(command)[0])))
|
|
216 values = []
|
|
217 for i in re.split('\\t', self.run_command(command)[0]):
|
|
218 if i == '':
|
|
219 values.append(float('nan'))
|
|
220 else:
|
|
221 values.append(float(i))
|
|
222 self.ofh.write("values:\n%s\n" % str(values))
|
|
223 self.ofh.write("values[0]:\n%s\n" % str(values[0]))
|
|
224 self.illumina_length_mean += values[0]
|
|
225 self.ofh.write("values[1]:\n%s\n" % str(values[1]))
|
|
226 self.illumina_read_count += int(values[1])
|
|
227 self.ofh.write("values[2]:\n%s\n" % str(values[2]))
|
|
228 self.illumina_bases += int(values[2])
|
|
229 # The original PIMA code inserts self.illumina_fastq into
|
|
230 # a list for no apparent reason. We don't do that here.
|
|
231 # self.illumina_length_mean /= len(self.illumina_fastq)
|
|
232 self.illumina_length_mean /= 1
|
|
233 self.illumina_bases = self.format_kmg(self.illumina_bases, decimals=1)
|
|
234
|
|
235 def start_doc(self):
|
|
236 self.doc = MdUtils(file_name=self.report_md, title='')
|
|
237
|
|
238 def add_run_information(self):
|
|
239 self.ofh.write("\nXXXXXX In add_run_information\n\n")
|
|
240 self.doc.new_line()
|
|
241 self.doc.new_header(1, 'Run information')
|
|
242 # Tables in md.utils are implemented as a wrapping function.
|
|
243 Table_list = [
|
|
244 "Category",
|
|
245 "Information",
|
|
246 "Date",
|
|
247 date.today(),
|
|
248 "ONT FAST5",
|
|
249 "N/A",
|
|
250 "ONT FASTQ",
|
|
251 "N/A",
|
|
252 "Illumina FASTQ",
|
|
253 self.wordwrap_markdown(self.analysis_name),
|
|
254 "Assembly",
|
|
255 self.wordwrap_markdown(self.assembly_name),
|
|
256 "Reference",
|
|
257 self.wordwrap_markdown(self.dbkey),
|
|
258 ]
|
|
259 self.doc.new_table(columns=2, rows=7, text=Table_list, text_align='left')
|
|
260 self.doc.new_line()
|
|
261 self.doc.new_line()
|
|
262
|
|
263 def add_ont_library_information(self):
|
|
264 self.ofh.write("\nXXXXXX In add_ont_library_information\n\n")
|
|
265 if self.ont_n50 is None:
|
|
266 return
|
|
267 self.doc.new_line()
|
|
268 self.doc.new_header(2, 'ONT library statistics')
|
|
269 Table_List = [
|
|
270 "Category",
|
|
271 "Quantity",
|
|
272 "ONT N50",
|
|
273 '{:,}'.format(self.ont_n50),
|
|
274 "ONT reads",
|
|
275 '{:,}'.format(self.ont_read_count),
|
|
276 "ONT bases",
|
|
277 '{:s}'.format(self.ont_bases),
|
|
278 "Illumina FASTQ",
|
|
279 self.wordwrap_markdown(self.illumina_fastq_file),
|
|
280 "Assembly",
|
|
281 self.wordwrap_markdown(self.assembly_name),
|
|
282 "Reference",
|
|
283 self.wordwrap_markdown(self.dbkey),
|
|
284 ]
|
|
285 self.doc.new_table(columns=2, rows=7, text=Table_List, text_align='left')
|
|
286 self.doc.new_line()
|
|
287
|
|
288 def add_illumina_library_information(self):
|
|
289 self.ofh.write("\nXXXXXX In add_illumina_library_information\n\n")
|
|
290 if self.illumina_length_mean is None:
|
|
291 return
|
|
292 self.doc.new_line()
|
|
293 self.doc.new_header(2, 'Illumina library statistics')
|
|
294 Table_List = [
|
|
295 "Illumina Info.",
|
|
296 "Quantity",
|
|
297 'Illumina mean length',
|
|
298 '{:.1f}'.format(self.illumina_length_mean),
|
|
299 'Illumina reads',
|
|
300 '{:,}'.format(self.illumina_read_count),
|
|
301 'Illumina bases',
|
|
302 '{:s}'.format(self.illumina_bases)
|
|
303 ]
|
|
304 self.doc.new_table(columns=2, rows=4, text=Table_List, text_align='left')
|
|
305
|
8
|
306 def evaluate_assembly(self):
|
1
|
307 assembly_info = pandas.read_csv(self.compute_sequence_length_file, sep='\t', header=None)
|
|
308 assembly_info.columns = ['contig', 'length']
|
|
309 self.contig_sizes = assembly_info
|
|
310 # Take a look at the number of contigs, their sizes,
|
|
311 # and circularity. Warn if things don't look good.
|
|
312 if assembly_info.shape[0] > 4:
|
|
313 warning = 'Assembly produced {:d} contigs, more than ususally expected; assembly may be fragmented'.format(assembly_info.shape[0])
|
|
314 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
315 small_contigs = assembly_info.loc[assembly_info['length'] <= 3000, :]
|
|
316 if small_contigs.shape[0] > 0:
|
|
317 warning = 'Assembly produced {:d} small contigs ({:s}); assembly may include spurious sequences.'.format(small_contigs.shape[0], ', '.join(small_contigs['contig']))
|
|
318 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
|
319
|
0
|
320 def add_assembly_information(self):
|
|
321 self.ofh.write("\nXXXXXX In add_assembly_information\n\n")
|
|
322 if self.assembly_fasta_file is None:
|
|
323 return
|
|
324 self.load_assembly()
|
|
325 self.doc.new_line()
|
|
326 self.doc.new_header(2, 'Assembly statistics')
|
|
327 Table_List = [
|
|
328 "Category",
|
|
329 "Information",
|
|
330 "Contigs",
|
|
331 str(self.num_assembly_contigs),
|
|
332 "Assembly size",
|
|
333 str(self.assembly_size),
|
|
334 ]
|
|
335 self.doc.new_table(columns=2, rows=3, text=Table_List, text_align='left')
|
|
336
|
|
337 def info_ont_fastq(self, fastq_file):
|
|
338 self.ofh.write("\nXXXXXX In info_ont_fastq, fastq_file:\n%s\n\n" % str(fastq_file))
|
|
339 opener = 'cat'
|
|
340 if self.gzipped:
|
|
341 opener = 'gunzip -c'
|
|
342 else:
|
|
343 opener = 'cat'
|
|
344 command = ' '.join([opener,
|
|
345 fastq_file,
|
|
346 '| awk \'{getline;print length($0);s += length($1);getline;getline;}END{print "+"s}\'',
|
|
347 '| sort -gr',
|
|
348 '| awk \'BEGIN{bp = 0;f = 0}',
|
|
349 '{if(NR == 1){sub(/+/, "", $1);s=$1}else{bp += $1;if(bp > s / 2 && f == 0){n50 = $1;f = 1}}}',
|
|
350 'END{printf "%d\\t%d\\t%d\\n", n50, (NR - 1), s;exit}\''])
|
|
351 result = list(re.split('\\t', self.run_command(command)[0]))
|
|
352 if result[1] == '0':
|
|
353 self.error_out('No ONT reads found')
|
|
354 ont_n50, ont_read_count, ont_raw_bases = [int(i) for i in result]
|
|
355 command = ' '.join([opener,
|
|
356 fastq_file,
|
|
357 '| awk \'{getline;print length($0);getline;getline;}\''])
|
|
358 result = self.run_command(command)
|
|
359 result = list(filter(lambda x: x != '', result))
|
1
|
360 # TODO: the following are not yet used...
|
|
361 # ont_read_lengths = [int(i) for i in result]
|
|
362 # ont_bases = self.format_kmg(ont_raw_bases, decimals=1)
|
|
363 if ont_n50 <= self.ont_n50_min:
|
|
364 warning = 'ONT N50 (%s) is less than the recommended minimum (%s)' % (str(ont_n50), str(self.ont_n50_min))
|
|
365 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
0
|
366
|
|
367 def wordwrap_markdown(self, string):
|
|
368 if string:
|
|
369 if len(string) < 35:
|
|
370 return string
|
|
371 else:
|
|
372 if '/' in string:
|
|
373 adjust = string.split('/')
|
|
374 out = ''
|
|
375 max = 35
|
|
376 for i in adjust:
|
|
377 out = out + '/' + i
|
|
378 if len(out) > max:
|
|
379 out += '<br>'
|
|
380 max += 35
|
|
381 return out
|
|
382 else:
|
|
383 out = [string[i:i + 35] for i in range(0, len(string), 50)]
|
|
384 return '<br>'.join(out)
|
|
385 else:
|
|
386 return string
|
|
387
|
|
388 def add_contig_info(self):
|
|
389 self.ofh.write("\nXXXXXX In add_contig_info\n\n")
|
|
390 if self.contig_info is None:
|
|
391 return
|
|
392 for method in ['ONT', 'Illumina']:
|
|
393 if method not in self.contig_info.index:
|
|
394 continue
|
|
395 self.doc.new_line()
|
|
396 self.doc.new_header(2, 'Assembly coverage by ' + method)
|
|
397 Table_List = ["Contig", "Length (bp)", "Coverage (X)"]
|
|
398 formatted = self.contig_info[method].copy()
|
|
399 formatted.iloc[:, 1] = formatted.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
400 for i in range(self.contig_info[method].shape[0]):
|
|
401 Table_List = Table_List + formatted.iloc[i, :].values.tolist()
|
|
402 row_count = int(len(Table_List) / 3)
|
|
403 self.doc.new_table(columns=3, rows=row_count, text=Table_List, text_align='left')
|
|
404
|
|
405 def add_assembly_notes(self):
|
|
406 self.ofh.write("\nXXXXXX In add_assembly_notes\n\n")
|
|
407 if len(self.assembly_notes) == 0:
|
|
408 return
|
|
409 self.doc.new_line()
|
|
410 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
411 self.doc.new_line()
|
|
412 self.doc.new_header(2, self.assembly_notes_title)
|
1
|
413 for note in self.assembly_notes:
|
|
414 self.doc.new_line(note)
|
0
|
415
|
|
416 def add_contamination(self):
|
|
417 self.ofh.write("\nXXXXXX In add_contamination\n\n")
|
2
|
418 if self.kraken2_report_file is None:
|
0
|
419 return
|
2
|
420 # Read in the Kraken fractions and pull out the useful parts
|
8
|
421 kraken_fracs = pandas.read_csv(self.kraken2_report_file, delimiter='\t', header=None)
|
|
422 kraken_fracs.index = kraken_fracs.iloc[:, 4].values
|
|
423 kraken_fracs = kraken_fracs.loc[kraken_fracs.iloc[:, 3].str.match('[UG]1?'), :]
|
|
424 kraken_fracs = kraken_fracs.loc[(kraken_fracs.iloc[:, 0] >= 1) | (kraken_fracs.iloc[:, 3] == 'U'), :]
|
|
425 kraken_fracs = kraken_fracs.iloc[:, [0, 1, 3, 5]]
|
|
426 kraken_fracs.columns = ['Fraction', 'Reads', 'Level', 'Taxa']
|
|
427 kraken_fracs['Fraction'] = (kraken_fracs['Fraction'] / 100).round(4)
|
|
428 kraken_fracs.sort_values(by='Fraction', inplace=True, ascending=False)
|
|
429 kraken_fracs['Taxa'] = kraken_fracs['Taxa'].str.lstrip()
|
0
|
430 self.doc.new_line()
|
|
431 self.doc.new_header(2, 'Contamination check')
|
10
|
432 self.doc.new_line(self.read_type + ' classifications')
|
|
433 self.doc.new_line()
|
|
434 Table_List = ["Percent of Reads", "Reads", "Level", "Label"]
|
|
435 for index, row in kraken_fracs.iterrows():
|
|
436 Table_List = Table_List + row.tolist()
|
|
437 row_count = int(len(Table_List) / 4)
|
|
438 self.doc.new_table(columns=4, rows=row_count, text=Table_List, text_align='left')
|
|
439 if self.contamination_methods_title not in self.methods:
|
|
440 self.methods[self.contamination_methods_title] = ''
|
2
|
441 method = 'Kraken2 version %s was used to assign the raw reads into taxa.' % self.kraken2_version
|
0
|
442 self.methods[self.contamination_methods_title] = self.methods[self.contamination_methods_title].append(pandas.Series(method))
|
|
443
|
|
444 def add_alignment(self):
|
|
445 self.ofh.write("\nXXXXXX In add_alignment\n\n")
|
|
446 # TODO: implement the draw_circos function for this.
|
|
447 if len(self.contig_alignment) > 0:
|
|
448 alignments = self.contig_alignment
|
|
449 else:
|
|
450 return
|
|
451 self.doc.new_line()
|
|
452 self.doc.new_header(level=2, title=self.alignment_title)
|
|
453 self.doc.new_line()
|
|
454 self.doc.new_header(level=3, title=self.snp_indel_title)
|
|
455 Table_1 = [
|
|
456 "Category",
|
|
457 "Quantity",
|
|
458 'SNPs',
|
1
|
459 '{:,}'.format(self.quast_mismatches),
|
0
|
460 'Small indels',
|
1
|
461 '{:,}'.format(self.quast_indels)
|
0
|
462 ]
|
|
463 self.doc.new_table(columns=2, rows=3, text=Table_1, text_align='left')
|
|
464 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
465 self.doc.new_line()
|
|
466 if len(self.alignment_notes) > 0:
|
|
467 self.doc.new_header(level=3, title=self.alignment_notes_title)
|
|
468 for note in self.alignment_notes:
|
|
469 self.doc.new_line(note)
|
|
470 for contig in alignments.index.tolist():
|
|
471 contig_title = 'Alignment to %s' % contig
|
|
472 image_png = alignments[contig]
|
|
473 self.doc.new_line()
|
|
474 self.doc.new_header(level=3, title=contig_title)
|
|
475 self.doc.new_line(self.doc.new_inline_image(text='contig_title', path=os.path.abspath(image_png)))
|
|
476 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
477 self.doc.new_line()
|
2
|
478 method = 'The genome assembly was aligned against the reference sequencing using dnadiff version %s.' % self.dnadiff_version
|
0
|
479 self.methods[self.reference_methods_title] = self.methods[self.reference_methods_title].append(pandas.Series(method))
|
|
480
|
|
481 def add_features(self):
|
|
482 self.ofh.write("\nXXXXXX In add_features\n\n")
|
|
483 if len(self.feature_bed_files) == 0:
|
|
484 return
|
|
485 for bbf in self.feature_bed_files:
|
|
486 if os.path.getsize(bbf) > 0:
|
|
487 best = pandas.read_csv(filepath_or_buffer=bbf, sep='\t', header=None)
|
|
488 self.feature_hits[os.path.basename(bbf)] = best
|
|
489 if len(self.feature_hits) == 0:
|
|
490 return
|
|
491 self.ofh.write("self.feature_hits: %s\n" % str(self.feature_hits))
|
|
492 self.doc.new_line()
|
|
493 self.doc.new_header(level=2, title=self.feature_title)
|
|
494 for feature_name in self.feature_hits.index.tolist():
|
|
495 self.ofh.write("feature_name: %s\n" % str(feature_name))
|
|
496 features = self.feature_hits[feature_name].copy()
|
|
497 self.ofh.write("features: %s\n" % str(features))
|
|
498 if features.shape[0] == 0:
|
|
499 continue
|
|
500 features.iloc[:, 1] = features.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
501 features.iloc[:, 2] = features.iloc[:, 2].apply(lambda x: '{:,}'.format(x))
|
|
502 self.doc.new_line()
|
|
503 self.doc.new_header(level=3, title=feature_name)
|
|
504 if (features.shape[0] == 0):
|
|
505 continue
|
|
506 for contig in pandas.unique(features.iloc[:, 0]):
|
|
507 self.ofh.write("contig: %s\n" % str(contig))
|
|
508 self.doc.new_line(contig)
|
|
509 contig_features = features.loc[(features.iloc[:, 0] == contig), :]
|
|
510 self.ofh.write("contig_features: %s\n" % str(contig_features))
|
|
511 Table_List = ['Start', 'Stop', 'Feature', 'Identity (%)', 'Strand']
|
|
512 for i in range(contig_features.shape[0]):
|
|
513 self.ofh.write("i: %s\n" % str(i))
|
|
514 feature = contig_features.iloc[i, :].copy(deep=True)
|
|
515 self.ofh.write("feature: %s\n" % str(feature))
|
|
516 feature[4] = '{:.3f}'.format(feature[4])
|
2
|
517 self.ofh.write("feature[1:].values.tolist(): %s\n" % str(feature[1:].values.tolist()))
|
|
518 Table_List = Table_List + feature[1:].values.tolist()
|
0
|
519 self.ofh.write("Table_List: %s\n" % str(Table_List))
|
|
520 row_count = int(len(Table_List) / 5)
|
|
521 self.ofh.write("row_count: %s\n" % str(row_count))
|
|
522 self.doc.new_line()
|
1
|
523 self.ofh.write("Before new_table, len(Table_List):: %s\n" % str(len(Table_List)))
|
|
524 self.doc.new_table(columns=5, rows=row_count, text=Table_List, text_align='left')
|
2
|
525 if self.blastn_version is not None:
|
|
526 blastn_version = 'The genome assembly was queried for features using blastn version %s.' % self.blastn_version
|
0
|
527 bedtools_version = 'Feature hits were clustered using bedtools and the highest scoring hit for each cluster was reported.'
|
|
528 method = '%s %s' % (blastn_version, bedtools_version)
|
|
529 self.methods[self.feature_methods_title] = self.methods[self.feature_methods_title].append(pandas.Series(method))
|
|
530
|
|
531 def add_feature_plots(self):
|
|
532 self.ofh.write("\nXXXXXX In add_feature_plots\n\n")
|
|
533 if len(self.feature_png_files) == 0:
|
|
534 return
|
|
535 self.doc.new_line()
|
|
536 self.doc.new_header(level=2, title='Feature Plots')
|
|
537 self.doc.new_paragraph('Only contigs with features are shown')
|
|
538 for feature_png_file in self.feature_png_files:
|
|
539 self.doc.new_line(self.doc.new_inline_image(text='Analysis', path=os.path.abspath(feature_png_file)))
|
|
540
|
|
541 def add_mutations(self):
|
|
542 self.ofh.write("\nXXXXXX In add_mutations\n\n")
|
|
543 if len(self.mutation_regions_tsv_files) == 0:
|
|
544 return
|
8
|
545 try:
|
0
|
546 mutation_regions = pandas.read_csv(self.mutation_regions_bed_file, sep='\t', header=0, index_col=False)
|
|
547 except Exception:
|
|
548 # Likely an empty file.
|
|
549 return
|
1
|
550 # TODO: this is the only place where reference_genome is used,
|
|
551 # so I'm commenting it out for now. We need to confirm if these
|
|
552 # errors that require the reference genmoe being passed are necessary.
|
|
553 # If so, we'll need to implement data tables in this tool.
|
|
554 # Make sure that the positions in the BED file fall within
|
|
555 # the chromosomes provided in the reference sequence.
|
|
556 """
|
|
557 for mutation_region in range(mutation_regions.shape[0]):
|
|
558 mutation_region = mutation_regions.iloc[mutation_region, :]
|
|
559 if not (mutation_region[0] in self.reference_genome):
|
|
560 self.ofh.write("\nMutation region: %s not found in reference genome.\n" % ' '.join(mutation_region.astype(str)))
|
|
561 continue
|
|
562 if not isinstance(mutation_region[1], int):
|
|
563 self.ofh.write("\nNon-integer found in mutation region start (column 2): %s.\n" % str(mutation_region[1]))
|
|
564 break
|
|
565 elif not isinstance(mutation_region[2], int):
|
|
566 self.ofh.write("\nNon-integer found in mutation region start (column 3): %s.\n" % str(mutation_region[2]))
|
|
567 break
|
|
568 if mutation_region[1] <= 0 or mutation_region[2] <= 0:
|
|
569 self.ofh.write("\nMutation region %s starts before the reference sequence.\n" % ' '.join(mutation_region.astype(str)))
|
|
570 if mutation_region[1] > len(self.reference_genome[mutation_region[0]].seq) or mutation_region[2] > len(self.reference_genome[mutation_region[0]].seq):
|
|
571 self.ofh.write("\nMutation region %s ends after the reference sequence.\n" % ' '.join(mutation_region.astype(str)))
|
|
572 """
|
0
|
573 amr_mutations = pandas.Series(dtype=object)
|
|
574 for region_i in range(mutation_regions.shape[0]):
|
|
575 region = mutation_regions.iloc[region_i, :]
|
|
576 region_name = str(region['name'])
|
|
577 self.ofh.write("Processing mutations for region %s\n" % region_name)
|
|
578 region_mutations_tsv_name = '%s_mutations.tsv' % region_name
|
|
579 if region_mutations_tsv_name not in self.mutation_regions_tsv_files:
|
|
580 continue
|
|
581 region_mutations_tsv = self.mutation_regions_tsv_files[region_mutations_tsv_name]
|
8
|
582 try:
|
0
|
583 region_mutations = pandas.read_csv(region_mutations_tsv, sep='\t', header=0, index_col=False)
|
|
584 except Exception:
|
|
585 region_mutations = pandas.DataFrame()
|
|
586 if region_mutations.shape[0] == 0:
|
|
587 continue
|
1
|
588 # Figure out what kind of mutations are in this region.
|
0
|
589 region_mutation_types = pandas.Series(['snp'] * region_mutations.shape[0], name='TYPE', index=region_mutations.index)
|
|
590 region_mutation_types[region_mutations['REF'].str.len() != region_mutations['ALT'].str.len()] = 'small-indel'
|
|
591 region_mutation_drugs = pandas.Series(region['drug'] * region_mutations.shape[0], name='DRUG', index=region_mutations.index)
|
|
592 region_notes = pandas.Series(region['note'] * region_mutations.shape[0], name='NOTE', index=region_mutations.index)
|
|
593 region_mutations = pandas.concat([region_mutations, region_mutation_types, region_mutation_drugs, region_notes], axis=1)
|
|
594 region_mutations = region_mutations[['#CHROM', 'POS', 'TYPE', 'REF', 'ALT', 'DRUG', 'NOTE']]
|
|
595 amr_mutations[region['name']] = region_mutations
|
2
|
596 if (amr_mutations.shape[0] > 0):
|
|
597 # Report the mutations.
|
0
|
598 self.doc.new_line()
|
2
|
599 self.doc.new_header(level=2, title=self.mutation_title)
|
|
600 for region_name in amr_mutations.index.tolist():
|
|
601 region_mutations = amr_mutations[region_name].copy()
|
|
602 self.doc.new_line()
|
|
603 self.doc.new_header(level=3, title=region_name)
|
|
604 if (region_mutations.shape[0] == 0):
|
|
605 self.doc.append('None')
|
|
606 continue
|
|
607 region_mutations.iloc[:, 1] = region_mutations.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
608 Table_List = ['Reference contig', 'Position', 'Reference', 'Alternate', 'Drug', 'Note']
|
|
609 for i in range(region_mutations.shape[0]):
|
|
610 Table_List = Table_List + region_mutations.iloc[i, [0, 1, 3, 4, 5, 6]].values.tolist()
|
|
611 row_count = int(len(Table_List) / 6)
|
|
612 self.doc.new_table(columns=6, rows=row_count, text=Table_List, text_align='left')
|
0
|
613 method = '%s reads were mapped to the reference sequence using minimap2.' % self.read_type
|
|
614 self.methods[self.mutation_methods_title] = self.methods[self.mutation_methods_title].append(pandas.Series(method))
|
|
615 method = 'Mutations were identified using samtools mpileup and varscan.'
|
|
616 self.methods[self.mutation_methods_title] = self.methods[self.mutation_methods_title].append(pandas.Series(method))
|
|
617
|
|
618 def add_amr_matrix(self):
|
|
619 self.ofh.write("\nXXXXXX In add_amr_matrix\n\n")
|
|
620 # Make sure that we have an AMR matrix to plot
|
1
|
621 if len(self.amr_matrix_files) == 0:
|
|
622 return
|
|
623 self.doc.new_line()
|
|
624 self.doc.new_header(level=2, title=self.amr_matrix_title)
|
|
625 self.doc.new_line('AMR genes and mutations with their corresponding drugs')
|
|
626 for amr_matrix_file in self.amr_matrix_files:
|
|
627 self.doc.new_line(self.doc.new_inline_image(text='AMR genes and mutations with their corresponding drugs',
|
|
628 path=os.path.abspath(amr_matrix_file)))
|
0
|
629
|
|
630 def add_large_indels(self):
|
|
631 self.ofh.write("\nXXXXXX In add_large_indels\n\n")
|
1
|
632 large_indels = pandas.Series(dtype='float64')
|
|
633 # Pull in insertions.
|
|
634 try:
|
|
635 reference_insertions = pandas.read_csv(filepath_or_buffer=self.reference_insertions_file, sep='\t', header=None)
|
|
636 except Exception:
|
|
637 reference_insertions = pandas.DataFrame()
|
|
638 try:
|
|
639 genome_insertions = pandas.read_csv(filepath_or_buffer=self.genome_insertions_file, sep='\t', header=None)
|
|
640 except Exception:
|
|
641 genome_insertions = pandas.DataFrame()
|
|
642 large_indels['Reference insertions'] = reference_insertions
|
|
643 large_indels['Query insertions'] = genome_insertions
|
|
644 # TODO: we don't seem to be reporting snps and deletions for some reason...
|
|
645 # Pull in the number of SNPs and small indels.
|
|
646 try:
|
|
647 snps = pandas.read_csv(filepath_or_buffer=self.dnadiff_snps_file, sep='\t', header=None)
|
|
648 # TODO: the following is not used...
|
|
649 # small_indels = snps.loc[(snps.iloc[:, 1] == '.') | (snps.iloc[:, 2] == '.'), :]
|
|
650 snps = snps.loc[(snps.iloc[:, 1] != '.') & (snps.iloc[:, 2] != '.'), :]
|
|
651 except Exception:
|
|
652 snps = pandas.DataFrame()
|
|
653 # Pull in deletions.
|
|
654 try:
|
|
655 amr_deletions = pandas.read_csv(filepath_or_buffer=self.amr_deletion_file, sep='\t', header=None)
|
|
656 except Exception:
|
|
657 amr_deletions = pandas.DataFrame()
|
|
658 if amr_deletions.shape[0] > 0:
|
|
659 amr_deletions.columns = ['contig', 'start', 'stop', 'name', 'type', 'drug', 'note']
|
|
660 amr_deletions = amr_deletions.loc[amr_deletions['type'].isin(['large-deletion', 'any']), :]
|
|
661 self.doc.new_line()
|
|
662 self.doc.new_header(level=2, title=self.large_indel_title)
|
|
663 for genome in ['Reference insertions', 'Query insertions']:
|
|
664 genome_indels = large_indels[genome].copy()
|
|
665 self.doc.new_line()
|
|
666 self.doc.new_header(level=3, title=genome)
|
|
667 if (genome_indels.shape[0] == 0):
|
|
668 continue
|
|
669 genome_indels.iloc[:, 1] = genome_indels.iloc[:, 1].apply(lambda x: '{:,}'.format(x))
|
|
670 genome_indels.iloc[:, 2] = genome_indels.iloc[:, 2].apply(lambda x: '{:,}'.format(x))
|
|
671 genome_indels.iloc[:, 3] = genome_indels.iloc[:, 3].apply(lambda x: '{:,}'.format(x))
|
|
672 Table_List = [
|
|
673 'Reference contig', 'Start', 'Stop', 'Size (bp)'
|
|
674 ]
|
|
675 for i in range(genome_indels.shape[0]):
|
|
676 Table_List = Table_List + genome_indels.iloc[i, :].values.tolist()
|
|
677 row_count = int(len(Table_List) / 4)
|
|
678 self.doc.new_table(columns=4, rows=row_count, text=Table_List, text_align='left')
|
|
679 method = 'Large insertions or deletions were found as the complement of aligned regions using bedtools.'
|
|
680 self.methods[self.reference_methods_title] = self.methods[self.reference_methods_title].append(pandas.Series(method))
|
|
681 self.doc.new_line()
|
|
682 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
683 self.doc.new_line()
|
0
|
684
|
|
685 def add_plasmids(self):
|
8
|
686 try:
|
1
|
687 plasmids = pandas.read_csv(filepath_or_buffer=self.plasmids_file, sep='\t', header=0)
|
|
688 except Exception:
|
0
|
689 return
|
|
690 plasmids = plasmids.copy()
|
|
691 self.doc.new_line()
|
1
|
692 self.doc.new_header(level=2, title=self.plasmid_title)
|
0
|
693 if (plasmids.shape[0] == 0):
|
|
694 self.doc.new_line('None')
|
|
695 return
|
|
696 plasmids.iloc[:, 3] = plasmids.iloc[:, 3].apply(lambda x: '{:,}'.format(x))
|
|
697 plasmids.iloc[:, 4] = plasmids.iloc[:, 4].apply(lambda x: '{:,}'.format(x))
|
|
698 plasmids.iloc[:, 5] = plasmids.iloc[:, 5].apply(lambda x: '{:,}'.format(x))
|
1
|
699 Table_List = ['Genome contig', 'Plasmid hit', 'Plasmid acc.', 'Contig size', 'Aliged', 'Plasmid size']
|
0
|
700 for i in range(plasmids.shape[0]):
|
|
701 Table_List = Table_List + plasmids.iloc[i, 0:6].values.tolist()
|
|
702 row_count = int(len(Table_List) / 6)
|
|
703 self.doc.new_table(columns=6, rows=row_count, text=Table_List, text_align='left')
|
|
704 method = 'The plasmid reference database was queried against the genome assembly using minimap2.'
|
|
705 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
2
|
706 method = 'The resulting BAM was converted to a PSL using a custom version of sam2psl.'
|
0
|
707 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
|
708 method = 'Plasmid-to-genome hits were resolved using the pChunks algorithm.'
|
|
709 self.methods[self.plasmid_methods_title] = self.methods[self.plasmid_methods_title].append(pandas.Series(method))
|
|
710
|
|
711 def add_methods(self):
|
|
712 self.ofh.write("\nXXXXXX In add_methods\n\n")
|
|
713 self.doc.new_line('<div style="page-break-after: always;"></div>')
|
|
714 self.doc.new_line()
|
|
715 if len(self.methods) == 0:
|
|
716 return
|
|
717 self.doc.new_line()
|
|
718 self.doc.new_header(level=2, title=self.methods_title)
|
|
719 for methods_section in self.methods.index.tolist():
|
|
720 if self.methods[methods_section] is None or len(self.methods[methods_section]) == 0:
|
|
721 continue
|
|
722 self.doc.new_line()
|
|
723 self.doc.new_header(level=3, title=methods_section)
|
|
724 self.doc.new_paragraph(' '.join(self.methods[methods_section]))
|
|
725
|
|
726 def add_summary(self):
|
|
727 self.ofh.write("\nXXXXXX In add_summary\n\n")
|
|
728 # Add summary title
|
|
729 self.doc.new_header(level=1, title=self.summary_title)
|
|
730 # First section of Summary
|
|
731 self.doc.new_header(level=1, title='CDC Advisory')
|
|
732 self.doc.new_paragraph(CDC_ADVISORY)
|
|
733 self.doc.new_line()
|
|
734 self.add_run_information()
|
|
735 self.add_ont_library_information()
|
|
736 methods = []
|
|
737 if self.did_guppy_ont_fast5:
|
|
738 methods += ['ONT reads were basecalled using guppy']
|
|
739 if self.did_qcat_ont_fastq:
|
|
740 methods += ['ONT reads were demultiplexed and trimmed using qcat']
|
|
741 self.methods[self.basecalling_methods_title] = pandas.Series(methods)
|
|
742 self.add_illumina_library_information()
|
1
|
743 self.add_contig_info()
|
|
744 self.evaluate_assembly()
|
0
|
745 self.add_assembly_information()
|
1
|
746 if self.flye_assembly_info_file is not None:
|
|
747 method = 'ONT reads were assembled using %s' % self.flye_version
|
0
|
748 self.methods[self.assembly_methods_title] = self.methods[self.assembly_methods_title].append(pandas.Series(method))
|
1
|
749 # Pull in the assembly summary and look at the coverage.
|
|
750 assembly_info = pandas.read_csv(self.flye_assembly_info_file, header=0, index_col=0, sep='\t')
|
|
751 # Look for non-circular contigs.
|
|
752 open_contigs = assembly_info.loc[assembly_info['circ.'] == 'N', :]
|
|
753 if open_contigs.shape[0] > 0:
|
|
754 open_contig_ids = open_contigs.index.values
|
|
755 warning = 'Flye reported {:d} open contigs ({:s}); assembly may be incomplete.'.format(open_contigs.shape[0], ', '.join(open_contig_ids))
|
|
756 self.assembly_notes = self.assembly_notes.append(pandas.Series(warning))
|
0
|
757 if self.did_medaka_ont_assembly:
|
|
758 method = 'the genome assembly was polished using ont reads and medaka.'
|
|
759 self.methods[self.assembly_methods_title] = self.methods[self.assembly_methods_title].append(pandas.series(method))
|
1
|
760 self.info_ont_fastq(self.illumina_fastq_file)
|
|
761 self.add_assembly_notes()
|
0
|
762
|
|
763 def make_tex(self):
|
|
764 self.doc.new_table_of_contents(table_title='detailed run information', depth=2, marker="tableofcontents")
|
|
765 text = self.doc.file_data_text
|
|
766 text = text.replace("##--[", "")
|
|
767 text = text.replace("]--##", "")
|
|
768 self.doc.file_data_text = text
|
|
769 self.doc.create_md_file()
|
|
770
|
|
771 def make_report(self):
|
|
772 self.ofh.write("\nXXXXXX In make_report\n\n")
|
|
773 self.start_doc()
|
|
774 self.add_summary()
|
|
775 self.add_contamination()
|
|
776 self.add_alignment()
|
|
777 self.add_features()
|
|
778 self.add_feature_plots()
|
|
779 self.add_mutations()
|
|
780 self.add_large_indels()
|
|
781 self.add_plasmids()
|
|
782 self.add_amr_matrix()
|
|
783 # self.add_snps()
|
|
784 self.add_methods()
|
|
785 self.make_tex()
|
|
786 # It took me quite a long time to find out that the value of the -t
|
|
787 # (implied) argument in the following command must be 'html' instead of
|
|
788 # the more logical 'pdf'. see the answer from snsn in this thread:
|
|
789 # https://github.com/jessicategner/pypandoc/issues/186
|
|
790 self.ofh.write("\nXXXXX In make_report, calling pypandoc.convert_file...\n\n")
|
|
791 pypandoc.convert_file(self.report_md,
|
|
792 'html',
|
|
793 extra_args=['--pdf-engine=weasyprint', '-V', '-css=%s' % self.pima_css],
|
|
794 outputfile='pima_report.pdf')
|
|
795 self.ofh.close()
|
|
796
|
|
797
|
|
798 parser = argparse.ArgumentParser()
|
|
799
|
1
|
800 parser.add_argument('--amr_deletions_file', action='store', dest='amr_deletions_file', help='AMR deletions BED file')
|
|
801 parser.add_argument('--amr_matrix_png_dir', action='store', dest='amr_matrix_png_dir', help='Directory of AMR matrix PNG files')
|
0
|
802 parser.add_argument('--analysis_name', action='store', dest='analysis_name', help='Sample identifier')
|
|
803 parser.add_argument('--assembly_fasta_file', action='store', dest='assembly_fasta_file', help='Assembly fasta file')
|
|
804 parser.add_argument('--assembly_name', action='store', dest='assembly_name', help='Assembly identifier')
|
2
|
805 parser.add_argument('--blastn_version', action='store', dest='blastn_version', default=None, help='Blastn version string')
|
1
|
806 parser.add_argument('--compute_sequence_length_file', action='store', dest='compute_sequence_length_file', help='Comnpute sequence length tabular file')
|
|
807 parser.add_argument('--contig_coverage_file', action='store', dest='contig_coverage_file', help='Contig coverage TSV file')
|
|
808 parser.add_argument('--dbkey', action='store', dest='dbkey', help='Reference genome identifier')
|
|
809 parser.add_argument('--dnadiff_snps_file', action='store', dest='dnadiff_snps_file', help='DNAdiff snps tabular file')
|
2
|
810 parser.add_argument('--dnadiff_version', action='store', dest='dnadiff_version', help='DNAdiff version string')
|
0
|
811 parser.add_argument('--feature_bed_dir', action='store', dest='feature_bed_dir', help='Directory of best feature hits bed files')
|
|
812 parser.add_argument('--feature_png_dir', action='store', dest='feature_png_dir', help='Directory of best feature hits png files')
|
1
|
813 parser.add_argument('--flye_assembly_info_file', action='store', dest='flye_assembly_info_file', default=None, help='Flye assembly info tabular file')
|
|
814 parser.add_argument('--flye_version', action='store', dest='flye_version', default=None, help='Flye version string')
|
|
815 parser.add_argument('--genome_insertions_file', action='store', dest='genome_insertions_file', help='Genome insertions BED file')
|
0
|
816 parser.add_argument('--gzipped', action='store_true', dest='gzipped', default=False, help='Input sample is gzipped')
|
|
817 parser.add_argument('--illumina_fastq_file', action='store', dest='illumina_fastq_file', help='Input sample')
|
2
|
818 parser.add_argument('--kraken2_report_file', action='store', dest='kraken2_report_file', default=None, help='kraken2 report file')
|
|
819 parser.add_argument('--kraken2_version', action='store', dest='kraken2_version', default=None, help='kraken2 version string')
|
0
|
820 parser.add_argument('--mutation_regions_bed_file', action='store', dest='mutation_regions_bed_file', help='AMR mutation regions BRD file')
|
|
821 parser.add_argument('--mutation_regions_dir', action='store', dest='mutation_regions_dir', help='Directory of mutation regions TSV files')
|
|
822 parser.add_argument('--pima_css', action='store', dest='pima_css', help='PIMA css stypesheet')
|
1
|
823 parser.add_argument('--plasmids_file', action='store', dest='plasmids_file', help='pChunks plasmids TSV file')
|
|
824 parser.add_argument('--reference_insertions_file', action='store', dest='reference_insertions_file', help='Reference insertions BED file')
|
|
825 # parser.add_argument('--reference_genome', action='store', dest='reference_genome', help='Reference genome fasta file')
|
0
|
826
|
|
827 args = parser.parse_args()
|
|
828
|
1
|
829 # Prepare the AMR matrix PNG files.
|
|
830 amr_matrix_files = []
|
|
831 for file_name in sorted(os.listdir(args.amr_matrix_png_dir)):
|
|
832 file_path = os.path.abspath(os.path.join(args.amr_matrix_png_dir, file_name))
|
|
833 amr_matrix_files.append(file_path)
|
0
|
834 # Prepare the features BED files.
|
|
835 feature_bed_files = []
|
|
836 for file_name in sorted(os.listdir(args.feature_bed_dir)):
|
|
837 file_path = os.path.abspath(os.path.join(args.feature_bed_dir, file_name))
|
|
838 feature_bed_files.append(file_path)
|
|
839 # Prepare the features PNG files.
|
|
840 feature_png_files = []
|
|
841 for file_name in sorted(os.listdir(args.feature_png_dir)):
|
|
842 file_path = os.path.abspath(os.path.join(args.feature_png_dir, file_name))
|
|
843 feature_png_files.append(file_path)
|
|
844 # Prepare the mutation regions TSV files.
|
|
845 mutation_regions_files = []
|
|
846 for file_name in sorted(os.listdir(args.mutation_regions_dir)):
|
|
847 file_path = os.path.abspath(os.path.join(args.feature_png_dir, file_name))
|
|
848 mutation_regions_files.append(file_path)
|
|
849
|
|
850 markdown_report = PimaReport(args.analysis_name,
|
1
|
851 args.amr_deletions_file,
|
|
852 amr_matrix_files,
|
0
|
853 args.assembly_fasta_file,
|
|
854 args.assembly_name,
|
2
|
855 args.blastn_version,
|
1
|
856 args.compute_sequence_length_file,
|
|
857 args.contig_coverage_file,
|
|
858 args.dbkey,
|
|
859 args.dnadiff_snps_file,
|
2
|
860 args.dnadiff_version,
|
0
|
861 feature_bed_files,
|
|
862 feature_png_files,
|
1
|
863 args.flye_assembly_info_file,
|
|
864 args.flye_version,
|
|
865 args.genome_insertions_file,
|
0
|
866 args.gzipped,
|
|
867 args.illumina_fastq_file,
|
2
|
868 args.kraken2_report_file,
|
|
869 args.kraken2_version,
|
0
|
870 args.mutation_regions_bed_file,
|
|
871 mutation_regions_files,
|
1
|
872 args.pima_css,
|
|
873 args.plasmids_file,
|
|
874 args.reference_insertions_file)
|
0
|
875 markdown_report.make_report()
|