annotate 0.2.1/bin/fastq_dir_to_samplesheet.py @ 0:77494b0fa3c7

"planemo upload"
author kkonganti
date Mon, 27 Jun 2022 15:55:37 -0400
parents
children
rev   line source
kkonganti@0 1 #!/usr/bin/env python3
kkonganti@0 2
kkonganti@0 3 import os
kkonganti@0 4 import sys
kkonganti@0 5 import glob
kkonganti@0 6 import argparse
kkonganti@0 7 import re
kkonganti@0 8
kkonganti@0 9
kkonganti@0 10 def parse_args(args=None):
kkonganti@0 11 Description = "Generate samplesheet from a directory of FastQ files."
kkonganti@0 12 Epilog = "Example usage: python fastq_dir_to_samplesheet.py <FASTQ_DIR> <SAMPLESHEET_FILE>"
kkonganti@0 13
kkonganti@0 14 parser = argparse.ArgumentParser(description=Description, epilog=Epilog)
kkonganti@0 15 parser.add_argument("FASTQ_DIR", help="Folder containing raw FastQ files.")
kkonganti@0 16 parser.add_argument("SAMPLESHEET_FILE", help="Output samplesheet file.")
kkonganti@0 17 parser.add_argument(
kkonganti@0 18 "-st",
kkonganti@0 19 "--strandedness",
kkonganti@0 20 type=str,
kkonganti@0 21 dest="STRANDEDNESS",
kkonganti@0 22 default="unstranded",
kkonganti@0 23 help="Value for 'strandedness' in samplesheet. Must be one of 'unstranded', 'forward', 'reverse'.",
kkonganti@0 24 )
kkonganti@0 25 parser.add_argument(
kkonganti@0 26 "-r1",
kkonganti@0 27 "--read1_extension",
kkonganti@0 28 type=str,
kkonganti@0 29 dest="READ1_EXTENSION",
kkonganti@0 30 default="_R1_001.fastq.gz",
kkonganti@0 31 help="File extension for read 1.",
kkonganti@0 32 )
kkonganti@0 33 parser.add_argument(
kkonganti@0 34 "-r2",
kkonganti@0 35 "--read2_extension",
kkonganti@0 36 type=str,
kkonganti@0 37 dest="READ2_EXTENSION",
kkonganti@0 38 default="_R2_001.fastq.gz",
kkonganti@0 39 help="File extension for read 2.",
kkonganti@0 40 )
kkonganti@0 41 parser.add_argument(
kkonganti@0 42 "-se",
kkonganti@0 43 "--single_end",
kkonganti@0 44 dest="SINGLE_END",
kkonganti@0 45 action="store_true",
kkonganti@0 46 help="Single-end information will be auto-detected but this option forces paired-end FastQ files to be treated as single-end so only read 1 information is included in the samplesheet.",
kkonganti@0 47 )
kkonganti@0 48 parser.add_argument(
kkonganti@0 49 "-sn",
kkonganti@0 50 "--sanitise_name",
kkonganti@0 51 dest="SANITISE_NAME",
kkonganti@0 52 action="store_true",
kkonganti@0 53 help="Whether to further sanitise FastQ file name to get sample id. Used in conjunction with --sanitise_name_delimiter and --sanitise_name_index.",
kkonganti@0 54 )
kkonganti@0 55 parser.add_argument(
kkonganti@0 56 "-sd",
kkonganti@0 57 "--sanitise_name_delimiter",
kkonganti@0 58 type=str,
kkonganti@0 59 dest="SANITISE_NAME_DELIMITER",
kkonganti@0 60 default="_",
kkonganti@0 61 help="Delimiter to use to sanitise sample name.",
kkonganti@0 62 )
kkonganti@0 63 parser.add_argument(
kkonganti@0 64 "-si",
kkonganti@0 65 "--sanitise_name_index",
kkonganti@0 66 type=int,
kkonganti@0 67 dest="SANITISE_NAME_INDEX",
kkonganti@0 68 default=1,
kkonganti@0 69 help="After splitting FastQ file name by --sanitise_name_delimiter all elements before this index (1-based) will be joined to create final sample name.",
kkonganti@0 70 )
kkonganti@0 71 return parser.parse_args(args)
kkonganti@0 72
kkonganti@0 73
kkonganti@0 74 def fastq_dir_to_samplesheet(
kkonganti@0 75 fastq_dir,
kkonganti@0 76 samplesheet_file,
kkonganti@0 77 strandedness="unstranded",
kkonganti@0 78 read1_extension="_R1_001.fastq.gz",
kkonganti@0 79 read2_extension="_R2_001.fastq.gz",
kkonganti@0 80 single_end=False,
kkonganti@0 81 sanitise_name=False,
kkonganti@0 82 sanitise_name_delimiter="_",
kkonganti@0 83 sanitise_name_index=1,
kkonganti@0 84 ):
kkonganti@0 85 def sanitize_sample(path, extension):
kkonganti@0 86 """Retrieve sample id from filename"""
kkonganti@0 87 sample = os.path.basename(path).replace(extension, "")
kkonganti@0 88 if sanitise_name:
kkonganti@0 89 if sanitise_name_index > 0:
kkonganti@0 90 sample = sanitise_name_delimiter.join(
kkonganti@0 91 os.path.basename(path).split(sanitise_name_delimiter)[
kkonganti@0 92 :sanitise_name_index
kkonganti@0 93 ]
kkonganti@0 94 )
kkonganti@0 95 # elif sanitise_name_index == -1:
kkonganti@0 96 # sample = os.path.basename(path)[ :os.path.basename(path).index('.') ]
kkonganti@0 97 return sample
kkonganti@0 98
kkonganti@0 99 def get_fastqs(extension):
kkonganti@0 100 """
kkonganti@0 101 Needs to be sorted to ensure R1 and R2 are in the same order
kkonganti@0 102 when merging technical replicates. Glob is not guaranteed to produce
kkonganti@0 103 sorted results.
kkonganti@0 104 See also https://stackoverflow.com/questions/6773584/how-is-pythons-glob-glob-ordered
kkonganti@0 105 """
kkonganti@0 106 abs_fq_files = glob.glob(os.path.join(fastq_dir, f"**", f"*{extension}"), recursive=True)
kkonganti@0 107 return sorted(
kkonganti@0 108 [
kkonganti@0 109 fq for _, fq in enumerate(abs_fq_files) if re.match('^((?!undetermined|unclassified|fail|class|qc|downloads).)*$', fq, flags=re.IGNORECASE)
kkonganti@0 110 ]
kkonganti@0 111 )
kkonganti@0 112
kkonganti@0 113 read_dict = {}
kkonganti@0 114
kkonganti@0 115 ## Get read 1 files
kkonganti@0 116 for read1_file in get_fastqs(read1_extension):
kkonganti@0 117 sample = sanitize_sample(read1_file, read1_extension)
kkonganti@0 118 if sample not in read_dict:
kkonganti@0 119 read_dict[sample] = {"R1": [], "R2": []}
kkonganti@0 120 read_dict[sample]["R1"].append(read1_file)
kkonganti@0 121
kkonganti@0 122 ## Get read 2 files
kkonganti@0 123 if not single_end:
kkonganti@0 124 for read2_file in get_fastqs(read2_extension):
kkonganti@0 125 sample = sanitize_sample(read2_file, read2_extension)
kkonganti@0 126 read_dict[sample]["R2"].append(read2_file)
kkonganti@0 127
kkonganti@0 128 ## Write to file
kkonganti@0 129 if len(read_dict) > 0:
kkonganti@0 130 out_dir = os.path.dirname(samplesheet_file)
kkonganti@0 131 if out_dir and not os.path.exists(out_dir):
kkonganti@0 132 os.makedirs(out_dir)
kkonganti@0 133
kkonganti@0 134 with open(samplesheet_file, "w") as fout:
kkonganti@0 135 header = ["sample", "fq1", "fq2", "strandedness"]
kkonganti@0 136 fout.write(",".join(header) + "\n")
kkonganti@0 137 for sample, reads in sorted(read_dict.items()):
kkonganti@0 138 for idx, read_1 in enumerate(reads["R1"]):
kkonganti@0 139 read_2 = ""
kkonganti@0 140 if idx < len(reads["R2"]):
kkonganti@0 141 read_2 = reads["R2"][idx]
kkonganti@0 142 sample_info = ",".join([sample, read_1, read_2, strandedness])
kkonganti@0 143 fout.write(f"{sample_info}\n")
kkonganti@0 144 else:
kkonganti@0 145 error_str = (
kkonganti@0 146 "\nWARNING: No FastQ files found so samplesheet has not been created!\n\n"
kkonganti@0 147 )
kkonganti@0 148 error_str += "Please check the values provided for the:\n"
kkonganti@0 149 error_str += " - Path to the directory containing the FastQ files\n"
kkonganti@0 150 error_str += " - '--read1_extension' parameter\n"
kkonganti@0 151 error_str += " - '--read2_extension' parameter\n"
kkonganti@0 152 print(error_str)
kkonganti@0 153 sys.exit(1)
kkonganti@0 154
kkonganti@0 155
kkonganti@0 156 def main(args=None):
kkonganti@0 157 args = parse_args(args)
kkonganti@0 158
kkonganti@0 159 strandedness = "unstranded"
kkonganti@0 160 if args.STRANDEDNESS in ["unstranded", "forward", "reverse"]:
kkonganti@0 161 strandedness = args.STRANDEDNESS
kkonganti@0 162
kkonganti@0 163 fastq_dir_to_samplesheet(
kkonganti@0 164 fastq_dir=args.FASTQ_DIR,
kkonganti@0 165 samplesheet_file=args.SAMPLESHEET_FILE,
kkonganti@0 166 strandedness=strandedness,
kkonganti@0 167 read1_extension=args.READ1_EXTENSION,
kkonganti@0 168 read2_extension=args.READ2_EXTENSION,
kkonganti@0 169 single_end=args.SINGLE_END,
kkonganti@0 170 sanitise_name=args.SANITISE_NAME,
kkonganti@0 171 sanitise_name_delimiter=args.SANITISE_NAME_DELIMITER,
kkonganti@0 172 sanitise_name_index=args.SANITISE_NAME_INDEX,
kkonganti@0 173 )
kkonganti@0 174
kkonganti@0 175
kkonganti@0 176 if __name__ == "__main__":
kkonganti@0 177 sys.exit(main())