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