annotate 0.5.0/bin/fastq_dir_to_samplesheet.py @ 1:365849f031fd

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