File: QCumber.py

package info (click to toggle)
qcumber 1.0.14%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 360 kB
  • ctags: 160
  • sloc: python: 1,272; sh: 68; makefile: 12
file content (596 lines) | stat: -rwxr-xr-x 24,092 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
#!/usr/bin/env python3
__author__ = 'LieuV'
__version__ = "1.0.14"

from classes import *
from helper import *
import os
from itertools import groupby
from jinja2 import Environment,FileSystemLoader
import shutil
import configparser
from collections import OrderedDict
import json

#dependencies
try:
	import argparse
except ImportError:
	print('The "argparse" module is not available. Use Python >3.2.')
	sys.exit(1)

#parameter = configparser.ConfigParser(strict=False, interpolation=None)
#parameter.read(join(dirname(__file__), "parameter.txt"))

#r1_pattern = parameter["Pattern"]["R1"]
#r2_pattern = parameter["Pattern"]["R2"]
#sep_pattern = parameter["Pattern"]["sep"]
#lane_pattern = parameter["Pattern"]["lane"]
global parameter
global r1_pattern
global r2_pattern
global sep_pattern
global lane_pattern

from sys import stderr
from Bio import SeqIO

def check_fasta(fastafile, filetype='File'):
	seq_record = SeqIO.parse(fastafile, "fasta")
	try:
		for seq in seq_record:
			break # break after first sequence
	except FileNotFoundError as err:
		print("%s %s does not exist" % (filetype, fastafile), file=stderr)
		return False
	try:
		s=str(seq) # we somehow need to touch the sequence element to trigger an error or not
		return True
	except:
		print('%s %s does not contain valid fasta data' % (filetype, fastafile), file=stderr)
		return False

def get_illumina_reads(tmp):
	readsets = []
	if not all([re.search(lane_pattern, x) for x in arguments["r1"]]):
		readname = re.sub(r1_pattern + ".*", "", os.path.basename(arguments["r1"][0]))
		if len(arguments["r1"]) != 1:
			r1 = FastQFile(join_reads(arguments["r1"], tmp, readname + "R1"),
						   [toLatex(os.path.basename(x)) for x in arguments["r1"]])
		else:
			r1 = FastQFile(arguments["r1"][0])
		if arguments["r2"]:
			if len(arguments["r2"]) != 1:
				r2 = FastQFile(join_reads(arguments["r2"], tmp, readname + "R2"),
							   [toLatex(os.path.basename(x)) for x in arguments["r2"]])
			else:
				r2 = FastQFile(arguments["r2"][0])
			readsets.append(ReadSet(r1, r2))
		else:
			readsets.append(ReadSet(r1))

	else:
		# split by lanes
		for lane in sorted(set([re.search(lane_pattern, x).group() for x in arguments["r1"]])):
			# concat same lanes
			r1_reads = [x for x in arguments["r1"] if lane in x]
			readname = re.sub(r1_pattern + ".*", "", os.path.basename(r1_reads[0]))
			if len(arguments["r1"]) != 1:
				r1 = FastQFile(join_reads(r1_reads, tmp, readname + "R1"), [toLatex(os.path.basename(x)) for x in r1_reads]  )
			else:
				r1 = FastQFile(r1_reads[0])
			if arguments["r2"]:
				r2_reads = [x for x in arguments["r2"] if lane in x]

				if len(r2_reads) != 1:
					r2 = FastQFile(join_reads(r2_reads, tmp, readname + "R2"),[toLatex(os.path.basename(x)) for x in r2_reads] )
				else:
					r2 = FastQFile(r2_reads[0])
				readsets.append(ReadSet(r1,r2))
			else:
				readsets.append(ReadSet(r1))
	return readsets

def get_input():
	all_files = []
	bam_ext = [x.strip(" ") for x in parameter["Fileextension"]["bam"].split(",")]
	fastq_ext = [x.strip(" ") for x in parameter["Fileextension"]["fastq"].split(",")]

	if arguments["technology"]:
		if arguments["technology"]=="IonTorrent":
			fastq_ext = []
		else:
			bam_ext = []

	if arguments["r1"]:
		if not arguments["technology"]:
			if any([arguments["r1"].endswith(ext) for ext in bam_ext]):
				arguments["technology"] = "IonTorrent"
			else:
				arguments["technology"] = "Illumina"
		if arguments["r2"]:
			return [[[arguments["r1"]], [arguments["r2"]]]]
		else:
			return [[[arguments["r1"]]]]


	for root, dirs, files in os.walk(arguments["input"]):
		for file in files:
			if any([file.endswith(ext) for ext in fastq_ext + bam_ext ]):
				all_files.append(join(root,file))

	if not arguments["technology"]:
		if len([x for x in all_files if any([ext in x for ext in bam_ext])]) == len(all_files):
			arguments["technology"] = "IonTorrent"
		else:
			arguments["technology"] = "Illumina"
	#if arguments["technology"]:
	#	if arguments["technology"]=="Illumina":
	#		# fastq only
	#		all_files = [x for x in all_files if any([ext in x for ext in fastq_ext])]
	#	elif arguments["technology"]=="IonTorrent":
	#		# bam only
	#		all_files = [x for x in all_files if any([ext in x for ext in bam_ext])]

	if (len(all_files) == 0):
		sys.exit(arguments["input"] + " does not contain fastq or bam files.")

	# find read pairs
	all_files = sorted(list(all_files))
	paired_reads_pattern =sep_pattern.join([lane_pattern , "(" + r1_pattern + "|" + r2_pattern + ")","\d{3}"])
	if all([re.search(paired_reads_pattern, x) for x in all_files]):
		paired_reads = []
		for setname, files in groupby(all_files, key=lambda x: "_".join(x.split("_")[:-3])):
			temp = sorted(list(files))
			r1_reads = [x for x in temp if r1_pattern in x]
			r2_reads = [x for x in temp if r2_pattern in x]
			if len(r1_reads) != 0:
				if len(r2_reads) != 0:
					paired_reads.append([r1_reads, r2_reads])
				else:
					paired_reads.append([r1_reads])
		return paired_reads
	else: # treat each file as sample
		return [[[x]] for x in all_files ]


def getSetname():
	try:
		if arguments["rename"]:
			new_name = [arguments["rename"][x] for x in arguments["rename"].keys() if basename(arguments["r1"][0]).startswith(x)]

			if len(new_name)>1:
				print("Name mapping ambiguous. Found: ", new_name)
				return getFilenameWithoutExtension(arguments["r1"][0], True)
			elif len(new_name)==0:
				return getFilenameWithoutExtension(arguments["r1"][0], True)
			else:
				print("Renamed to " ,new_name)
				return new_name[0]
	except:
		print("Couldnt rename sample files.")
	try:
		paired_reads_pattern = sep_pattern.join([sep_pattern + lane_pattern, "(" + r1_pattern + "|" + r2_pattern + ")", "\d{3}.*"])
		if isinstance(arguments["r1"], list):
			return re.sub(paired_reads_pattern, "" ,basename(arguments["r1"][0]))
		else:
			return re.sub(paired_reads_pattern,"",basename(arguments["r1"]))
	except:
		print("Problems getting samplenames")
		return arguments["r1"]

def runAnalyses(temp_bowtie_path, tmp):
	try:
		output = getDir([arguments["output"], "QCResults"], True)
		sample = Sample(getSetname(), output, arguments["reference"],arguments["threads"], arguments["technology"])

		if arguments["technology"].startswith("Illumina"):
			readsets = get_illumina_reads(tmp)
		elif arguments["technology"] == "IonTorrent":
			print("IonTorrent", arguments["r1"])
			fastqfile = bam_to_fastq(arguments["r1"],tmp)
			readsets = [ReadSet( fastqfile)]

		for rs in readsets:
			print("Run FastQC...")
			rs.run_FastQC(join(output, "FastQC"))
			if not arguments["notrimming"]:
				if arguments["trimBetter"]:
					trimming_perc = arguments["trimBetter_threshold"]
				else:
					trimming_perc = ""
				rs.run_Trimmomatic(arguments["adapter"], arguments["palindrome"], arguments["minlen"],
										arguments["trimOption"], trimming_perc, arguments["gz"])
				rs.trimRes = rs.trimRes.run_FastQC(tmp)
			sample = sample.add_readSet(rs)
		if not arguments["nomapping"]:
			if arguments["save_mapping"]:
				sample.mappingRes = sample.run_Bowtie2(temp_bowtie_path, join(arguments["output"], "QCResults", sample.name +".sam"), not arguments["notrimming"])
			else:
				sample.mappingRes = sample.run_Bowtie2(temp_bowtie_path, "/dev/null", not arguments["notrimming"])
		if not arguments["nokraken"]:
			print("Run Kraken.")
			sample = sample.run_Kraken(arguments["db"], not arguments["notrimming"])

		sample.stop = datetime.datetime.strftime(datetime.datetime.now(),"%d.%m.%Y, %H:%M:%S")
	finally:
		shutil.rmtree(tmp)
	return sample

def writeReport(sample):
	report_name = os.path.join(sample.mainResultsPath, "Report",
		 "summary_" + sample.name + "_" + datetime.datetime.strftime(datetime.datetime.now(), "%d-%m-%y_%H-%M"))
	print("Writing latex " ,report_name)
	template_dir = '/usr/share/qcumber'
	template_file = 'report.tex'
	loader = FileSystemLoader(template_dir)
	env = Environment(loader=loader)
	template = env.get_template(template_file)
	try:
		trim_param= sample.readSets[0].trimRes.print_param(arguments["palindrome"], arguments["minlen"], arguments["trimOption"])
	except:
		trim_param = "None"
	pdf_latex = template.render(sample=sample, pipeline=Pipeline(), trim_param = trim_param )

	latex = open(report_name + ".tex", "w")
	latex.write(pdf_latex)
	latex.close()

	process = subprocess.Popen(" ".join(["pdflatex", "-interaction=nonstopmode", "-output-directory=" + join(sample.mainResultsPath, "Report"), report_name + ".tex"]),shell=True, stdout = subprocess.DEVNULL, stderr = subprocess.PIPE)
	for line in iter(process.stderr.readline, b''):
		print(line)
	process.communicate()
	#os.system(" ".join(["pdflatex", "-interaction=nonstopmode", "-output-directory=" + join(sample.mainResultsPath, "Report"), report_name + ".tex > " + join(sample.mainResultsPath, "Report", "latex.log 2&")]))

	for ext in (".tex",".aux", ".log", ".toc", ".lof", ".lot", ".synctex.gz"):
		try:
			os.remove(report_name + ext)
		except OSError:
			pass
def check_input_validity():
	#
	# Check options for Trimmomatic
	#pattern = re.match("(?P<option>\w+):(?P<value1>\d+):(?P<value2>\d+)", arguments["trimOption"])
	#if (arguments["trimOption"] != ""):
	#	if not ((pattern.group("option") == "SLIDINGWINDOW") or (pattern.group("option") == "MAXINFO")):
	#		sys.exit("Check trimOption. Only 'SLIDINGWINDOW' or 'MAXINFO' allowed")
	#	try:
	#		int(pattern.group("value1"))
	#		int(pattern.group("value2"))
	#	except:
	#		sys.exit("Check trimOptions.")

	#
	# Check if adapter is required
	if  not (arguments['notrimming'] or arguments['adapter'] or arguments["technology"] == "IonTorrent") :
		sys.exit("Illumina projects requires an adapter file")

	#
	# Check if reference is required and valid
	if arguments["nomapping"]:
		arguments["reference"] = ""
	else:
		if not arguments["reference"]:
			sys.exit("Mapping needs a reference.")
		else:
			if not check_fasta(arguments["reference"],"Reference"):
				sys.exit(1)
			try:
				from Bio import SeqIO
				seq_record = SeqIO.parse(arguments["reference"], "fasta")
			except:
				print("Couldnt check if reference input is a valid fasta due to missing python library Bio.")
			try:
				for seq in seq_record:
					break  # break after first sequence
			except FileNotFoundError as err:
				sys.exit("File %s does not exist" % arguments["reference"])
			try:
				str(seq)  # we somehow need to touch the sequence element to trigger an error or not
			except:
				sys.exit('File %s does not contain valid fasta data' % arguments["reference"])

	#
	#Check validity of Kraken DB
	if not arguments["nokraken"]:
		if not os.path.exists(arguments["db"]):
			sys.exit(arguments["db"] + " does not exist. Enter a valid database for kraken")
		else:
			if "database.kdb" not in os.listdir(arguments["db"]):
				sys.exit("database " + arguments["db"] + " does not contain necessary file database.kdb")
	#
	# Check input
	if arguments["input"]:
		if not os.path.exists(arguments["input"]):
			sys.exit(arguments["input"] + " does not exist.")
	else:
		if not os.path.isfile(arguments["r1"]):
			sys.exit(arguments["r1"] + " does not exist. Input file required. Use option -input or -1 / -2.")

		if arguments["r2"]:
			if not os.path.isfile(arguments["r2"]):
				sys.exit(arguments["r2"] + " does not exist.")

def get_defaults():
	if arguments["forAssembly"]:
		if not arguments["trimBetter_threshold"]:
			arguments["trimBetter_threshold"] = parameter["forAssembly." + arguments['technology']][
				"trimBetter_threshold"]
		if not arguments["trimOption"]:
			arguments["trimOption"] = parameter["forAssembly." + arguments['technology']]["trimOption"]

	elif arguments["forMapping"]:
		if not arguments["trimBetter_threshold"]:
			arguments["trimBetter_threshold"] = parameter["forMapping." + arguments['technology']][
				"trimBetter_threshold"]
		if not arguments["trimOption"]:
			arguments["trimOption"] = parameter["forMapping." + arguments['technology']]["trimOption"]

	if not arguments["trimOption"]:
		arguments["trimOption"] = parameter["Trimmomatic"]["trimOption"]
	if not arguments["trimBetter_threshold"]:
		arguments["trimBetter_threshold"] = parameter["Trimmomatic"]["trimBetter_threshold"]


def plot():
	try:
		#
		# Plot BOXPLOTS
		boxplots = [{"file": "Per_sequence_quality_scores.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Per_sequence_quality_scores.png"),
					 "title": "Per sequence quality scores",
					 "ylab": "Mean Sequence Quality (Phred Score)",
					 "xlab": "Sample"},
					{"file": "Sequence_Length_Distribution.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Sequence_Length_Distribution.png"),
					 "title": "Sequence Length Distribution",
					 "ylab": "Sequence Length (bp)",
					 "xlab": "Sample"},
					{"file": "Per_sequence_GC_content.csv",
					 "output": join(arguments["output"], "QCResults/Report/src/img", "Per_sequence_GC_content.png"),
					 "title": "Per sequence GC content",
					 "ylab": "Mean GC content (%)",
					 "xlab": "Sample"}]
		for plot in boxplots:
			process = subprocess.Popen(" ".join(["Rscript --vanilla ", join(os.path.dirname(__file__), "boxplot.R"),
												 join(arguments["output"], "QCResults", "Report", "src", plot["file"]),
												 plot["output"], '"' + plot["title"] + '"', '"' + plot["xlab"] + '"',
												 '"' + plot["ylab"] + '"']),
									   stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
			#for line in iter(process.stderr.readline, b''):
			#	print(line)
			process.communicate()

		#
		# Plot BARPLOTS
		process = subprocess.Popen(
			" ".join(["Rscript --vanilla ", join(os.path.dirname(__file__), "barplot.R"), join(arguments["output"], "QCResults/Report/src", "summary.json"),
					  join(arguments["output"], "QCResults/Report/src/img")]), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
		process.communicate()
	except:
		print("Couldnt plot summary")


def writeSummaryTex(batch_json):
	try:
		summary_latex_name = join(arguments["output"], "QCResults", "Report", "summary.tex")
		with open(summary_latex_name, "w") as summary_latex:
			summary_latex.write("\\rowcolors{2}{gray!10}{}\n\\begin{table}[H]\\begin{tabular}{lcc}\n")
			summary_latex.write(
				"\\rowcolor{tableBlue} \\textbf{Sample} &  \\textbf{Reads after trimming [\#]} & \\textbf{Reads after trimming [\%]} &\\textbf{Map to reference [\#]} & \\textbf{Map to reference[\%]} & \\textbf{Classified (Kraken)} & \\textbf{Shorter fragments [\%]} \\ \n")

			for i in range(0, len(batch_json["summary"])):
				summary_latex.write(
					str(batch_json["summary"][i]["setname"]) + " & " +
					str(batch_json["summary"][i]["Reads after trimming [#]"]) + " & " +
					str(batch_json["summary"][i]["Reads after trimming [%]"]) + " & " +
					str(batch_json["summary"][i]["Map to reference [#]"]) + " & " +
					str(batch_json["summary"][i]["Map to reference [%]"]) + " & " +
					str(batch_json["summary"][i]["Classified (Kraken)"]) + " & " +
					str(batch_json["summary"][i]["Shorter fragments"]) + "\\\\\n"
				)
			summary_latex.write("\\end{tabular}\n")
			summary_latex.write("\\caption{Statistics on reads after trimming. }")
			summary_latex.close()
	except:

		print("Couldnt write summary.tex file.")

def main(arguments):

	tmp = join(arguments["output"],"QCResults" ,"qc_tmp")
	makedirs(tmp, exist_ok=True)
	makedirs(join(arguments["output"], "QCResults"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "FastQC"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Trimmed"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Trimmed", "FastQC"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report", "src"), exist_ok=True)
	makedirs(join(arguments["output"], "QCResults", "Report", "src", "img"), exist_ok=True)

	if not os.path.exists(join(arguments["output"], "QCResults", "Report", "lib" )):
		shutil.copytree(join(os.path.dirname(__file__),"lib"),join(arguments["output"], "QCResults", "Report", "lib" ))

	####
	# rename sample names
	####
	if arguments["rename"]:
		rename_dict = {}
		with open(arguments["rename"], "r") as csvfile:
			for line in csvfile:
				row = line.split("\t")
				rename_dict[row[0]] = row[1].strip()
		arguments["rename"] = rename_dict

	###
	# create new boxplot csv files
	###
	for csv in ["Per_sequence_quality_scores.csv", "Per_sequence_GC_content.csv", "Sequence_Length_Distribution.csv"]:
		new_csv = open(join(arguments["output"], "QCResults", "Report", "src", csv), "w")
		new_csv.write("Sample,Read,Lane,Trimmed,Value,Count\n")
		new_csv.close()

	###
	# Write SAV
	###
	try:
		if arguments["sav"]:
			write_SAV(arguments["sav"], join(arguments["output"], "QCResults", "Report", "src"))
	except:
		print("Couldnt write SAV.")


	#
	# Check input validity
	check_input_validity()

	if arguments["index"]:
		mapping_index_path = arguments["index"]
	else:
		mapping_index_path = join(tmp, "bowtie2_index")
		os.makedirs(mapping_index_path, exist_ok=True)

	myFiles = get_input()
	print("Found " + str(len(myFiles)) + " sample(s).")

	#
	# Get parameter defaults
	get_defaults()

	batch_json = json.dump({
			"commandline": arguments,
			"summary": [],
			"kraken": {},
			"versions": Pipeline().__dict__},
		open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "w"))

	output = join(arguments["output"], "QCResults")  # getDir([arguments["output"], "QCResults"], True)

	i = 1
	#######
	# Run for each sample
	#######
	try:
		for subset in myFiles:
			print("Analyse " + str(i) + "/" + str(len(myFiles)))
			sample_tmp = join(tmp, "Sample_" + str(i))
			os.makedirs(sample_tmp, exist_ok=True)

			if isinstance(subset, str):
				arguments["r1"] = subset
			else:
				arguments["r1"] = subset[0]
				if len(subset)>1:
					arguments["r2"] = subset[1]

			####
			# Run Analyses
			####
			sample = runAnalyses( mapping_index_path, sample_tmp )

			####
			# Write output
			####
			if sample is not None:
				try:
					writeReport(sample)
				except:
					print("Couldnt write pdf.")
				try:
					batch_json = json.load(open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "r"), object_pairs_hook=OrderedDict)
					if sample.mappingRes is None:
						pMapping = 0
						nMapping = 0
					else:
						pMapping = sample.mappingRes.percentAlignedReads
						nMapping = sample.mappingRes.numberOfAlignedReads
					if sample.krakenRes is None:
						kraken = 0
						kraken_reports ={}
					else:
						kraken = sample.krakenRes.pClassified
						batch_json["kraken"][sample.name] = json.loads(str_to_json(sample.krakenRes.report))
					#tmp_overview.write(",".join([sample.name, str(sample.nTrimmed()), str(nMapping), str(kraken)]) +"\n")
					try:
						trim_param = sample.readSets[0].trimRes.print_param(arguments["palindrome"], arguments["minlen"],
															   arguments["trimOption"])
					except:
						trim_param="None"
					batch_json["summary"].append(
							OrderedDict([("setname", sample.name),
										 ("Total reads [#]", sample.total_reads()),
										 ("Reads after trimming [#]", sample.nTrimmed()),
										 ("Reads after trimming [%]", sample.pTrimmed()),
										 ("Map to reference [#]", nMapping),
										 ("Map to reference [%]", pMapping),
										 ("Classified (Kraken)", kraken),
										 ("Shorter fragments", sample.get_mean_trimRes()),
										 ("Trim Parameter",trim_param),
										 ("images", [x.get_all_qc_dict() for x in sample.readSets])]))

					json.dump(batch_json, open(join(arguments["output"], "QCResults/Report/src", "summary.json"), "w"))
				except:
					print("Couldnt produce HTML report.")

			sample = None
			arguments["r1"]=None
			arguments["r2"]=None
			i+=1
		# plot boxplots and barplots
		plot()
		writeSummaryTex(batch_json)
		shutil.copy(join(os.path.dirname(__file__), "batch_report.html"), join(arguments["output"], "QCResults", "Report", "batch_report.html"))

	finally:

		shutil.rmtree(tmp)
		delete_files(join(arguments["output"],"QCResults"), "FastQC", "_fastqc.html")
		delete_files(join(arguments["output"],"QCResults"), "Trimmed/FastQC", "_fastqc.html")
 
if __name__ == "__main__":
	config = configparser.ConfigParser()
	config.read(join(dirname(__file__), "config.txt"))
	kraken_db = ""
	if "DEFAULT" in config:
		if "kraken_db" in config["DEFAULT"].keys():
			kraken_db = config["DEFAULT"]["kraken_db"]

	parser = argparse.ArgumentParser()
	parser.add_argument( '-input', dest='input', help = "input sample folder. Illumina filenames should end with _<lane>_<R1|R2>_number, e.g. Sample_12_345_R1_001.fastq, to find the right paired set.", required=False)
	parser.add_argument('-1' , dest='r1', help = "input file", required=False)
	parser.add_argument( '-2', dest='r2', help = "input file", required=False)

	parser.add_argument('-output', dest='output', default="")
	parser.add_argument('-technology', dest='technology',choices=['Illumina',"IonTorrent"] ,required=False , help = "If not set, automatically determine technology and search for fastq and bam files. Set technology to IonTorrent if all files are bam-files, else set technology to Illumina.")
	parser.add_argument('-threads', dest='threads', default = 4, type = int, help= "Number of threads. Default:  %(default)s")
	parser.add_argument('-adapter', dest = 'adapter', choices = ['TruSeq2-PE', 'TruSeq2-SE' , 'TruSeq3-PE' , 'TruSeq3-SE' , 'TruSeq3-PE-2', 'NexteraPE-PE' ])
	parser.add_argument('-reference', dest='reference', required = False, help = "Map reads against reference")
	parser.add_argument('-index', dest='index', required = False, help = "Bowtie2 index if available.")
	parser.add_argument('-sav', dest='sav', required=False,help="Illumina folder for SAV. Requires RunInfo.xml, RunParamter.xml and Interop folder.")

	parser.add_argument('-save_mapping', action = "store_true")
	parser.add_argument('-db', dest='db', help='Kraken database', required = False, default= kraken_db)
	parser.add_argument('-palindrome', dest='palindrome', default=30, help= 'Use palindrome parameter 30 or 1000 for further analysis. Default: %(default)s', type = int)
	parser.add_argument('-minlen', default=50,dest='minlen',help='Minlen parameter for Trimmomatic. Default: %(default)s',  type=int)
	parser.add_argument('-trimOption', dest="trimOption", help='Use maxinfo or slidinginfo for Trimmomatic.MAXINFO:<target length>:<strictness> | SLIDINGWINDOW:<window size>:<required quality>.', type= str)
	parser.add_argument('-version', action='version', version='%(prog)s v' + __version__)
	parser.add_argument('-nokraken', action = "store_true")
	parser.add_argument('-nomapping', action = "store_true")
	parser.add_argument('-notrimming', action = "store_true")
	parser.add_argument('-gz', action = "store_true")
	parser.add_argument('-trimBetter', action = "store_true", help= "Optimize trimming parameter using 'Per sequence base content' from fastqc. Not recommended for amplicons.")
	parser.add_argument('-trimBetter_threshold', dest='trimBetter_threshold', help = "Set -trimBetter to use this option.Default setting for Illumina: 0.15 and for IonTorrent: 0.25.", required=False, type=float)
	parser.add_argument('-forAssembly', action = "store_true", help = "Set -trimBetter to use this option.Trim parameter are optimized for assemblies (trim more aggressive).")
	parser.add_argument('-forMapping', action = "store_true", help = "Set -trimBetter to use this option.Trim parameter are optimized for mapping (allow more errors).")
	parser.add_argument('-rename', dest="rename", required=False, help="TSV File with two columns: <old sample name> <new sample name>")
	parser.add_argument('-parameters', dest = 'parameters', default = join(dirname(__file__), "parameter.txt"))

	arguments = vars(parser.parse_args())
	parameter = configparser.ConfigParser(strict=False, interpolation=None)
	parameter.read(arguments['parameters'])

	r1_pattern = parameter["Pattern"]["R1"]
	r2_pattern = parameter["Pattern"]["R2"]
	sep_pattern = parameter["Pattern"]["sep"]
	lane_pattern = parameter["Pattern"]["lane"]
	main(arguments)