annotate 0.4.2/bin/fastq_dir_to_samplesheet.py @ 105:52045ea4679d

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