annotate 0.7.0/bin/fastq_dir_to_samplesheet.py @ 19:4b304d77bbfb

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