annotate 0.7.0/bin/check_samplesheet.py @ 21:4ce0e079377d tip

planemo upload
author kkonganti
date Mon, 15 Jul 2024 12:01:00 -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 errno
kkonganti@17 6 import argparse
kkonganti@17 7
kkonganti@17 8
kkonganti@17 9 def parse_args(args=None):
kkonganti@17 10 Description = "Reformat samplesheet file and check its contents."
kkonganti@17 11 Epilog = "Example usage: python check_samplesheet.py <FILE_IN> <FILE_OUT>"
kkonganti@17 12
kkonganti@17 13 parser = argparse.ArgumentParser(description=Description, epilog=Epilog)
kkonganti@17 14 parser.add_argument("FILE_IN", help="Input samplesheet file.")
kkonganti@17 15 parser.add_argument("FILE_OUT", help="Output file.")
kkonganti@17 16 return parser.parse_args(args)
kkonganti@17 17
kkonganti@17 18
kkonganti@17 19 def make_dir(path):
kkonganti@17 20 if len(path) > 0:
kkonganti@17 21 try:
kkonganti@17 22 os.makedirs(path)
kkonganti@17 23 except OSError as exception:
kkonganti@17 24 if exception.errno != errno.EEXIST:
kkonganti@17 25 raise exception
kkonganti@17 26
kkonganti@17 27
kkonganti@17 28 def print_error(error, context="Line", context_str=""):
kkonganti@17 29 error_str = f"ERROR: Please check samplesheet -> {error}"
kkonganti@17 30 if context != "" and context_str != "":
kkonganti@17 31 error_str = f"ERROR: Please check samplesheet -> {error}\n{context.strip()}: '{context_str.strip()}'"
kkonganti@17 32 print(error_str)
kkonganti@17 33 sys.exit(1)
kkonganti@17 34
kkonganti@17 35
kkonganti@17 36 def check_samplesheet(file_in, file_out):
kkonganti@17 37 """
kkonganti@17 38 This function checks that the samplesheet follows the following structure:
kkonganti@17 39
kkonganti@17 40 sample,fq1,fq2,strandedness
kkonganti@17 41 SAMPLE_PE,SAMPLE_PE_RUN1_1.fastq.gz,SAMPLE_PE_RUN1_2.fastq.gz,forward
kkonganti@17 42 SAMPLE_PE,SAMPLE_PE_RUN2_1.fastq.gz,SAMPLE_PE_RUN2_2.fastq.gz,forward
kkonganti@17 43 SAMPLE_SE,SAMPLE_SE_RUN1_1.fastq,,forward
kkonganti@17 44 SAMPLE_SE,SAMPLE_SE_RUN1_2.fastq.gz,,forward
kkonganti@17 45
kkonganti@17 46 For an example see:
kkonganti@17 47 https://github.com/nf-core/test-datasets/blob/rnaseq/samplesheet/v3.1/samplesheet_test.csv
kkonganti@17 48 """
kkonganti@17 49
kkonganti@17 50 sample_mapping_dict = {}
kkonganti@17 51 with open(file_in, "r", encoding='utf-8-sig') as fin:
kkonganti@17 52
kkonganti@17 53 ## Check header
kkonganti@17 54 MIN_COLS = 3
kkonganti@17 55 HEADER = ["sample", "fq1", "fq2", "strandedness"]
kkonganti@17 56 header = [x.strip('"') for x in fin.readline().strip().split(",")]
kkonganti@17 57 if header[: len(HEADER)] != HEADER:
kkonganti@17 58 print(
kkonganti@17 59 f"ERROR: Please check samplesheet header -> {','.join(header)} != {','.join(HEADER)}"
kkonganti@17 60 )
kkonganti@17 61 sys.exit(1)
kkonganti@17 62
kkonganti@17 63 ## Check sample entries
kkonganti@17 64 for line in fin:
kkonganti@17 65 if line.strip():
kkonganti@17 66 lspl = [x.strip().strip('"') for x in line.strip().split(",")]
kkonganti@17 67
kkonganti@17 68 ## Check valid number of columns per row
kkonganti@17 69 if len(lspl) < len(HEADER):
kkonganti@17 70 print_error(
kkonganti@17 71 f"Invalid number of columns (minimum = {len(HEADER)})!",
kkonganti@17 72 "Line",
kkonganti@17 73 line,
kkonganti@17 74 )
kkonganti@17 75
kkonganti@17 76 num_cols = len([x for x in lspl if x])
kkonganti@17 77 if num_cols < MIN_COLS:
kkonganti@17 78 print_error(
kkonganti@17 79 f"Invalid number of populated columns (minimum = {MIN_COLS})!",
kkonganti@17 80 "Line",
kkonganti@17 81 line,
kkonganti@17 82 )
kkonganti@17 83
kkonganti@17 84 ## Check sample name entries
kkonganti@17 85 sample, fq1, fq2, strandedness = lspl[: len(HEADER)]
kkonganti@17 86 if sample.find(" ") != -1:
kkonganti@17 87 print(
kkonganti@17 88 f"WARNING: Spaces have been replaced by underscores for sample: {sample}"
kkonganti@17 89 )
kkonganti@17 90 sample = sample.replace(" ", "_")
kkonganti@17 91 if not sample:
kkonganti@17 92 print_error("Sample entry has not been specified!", "Line", line)
kkonganti@17 93
kkonganti@17 94 ## Check FastQ file extension
kkonganti@17 95 for fastq in [fq1, fq2]:
kkonganti@17 96 if fastq:
kkonganti@17 97 if fastq.find(" ") != -1:
kkonganti@17 98 print_error("FastQ file contains spaces!", "Line", line)
kkonganti@17 99 # if not fastq.endswith(".fastq.gz") and not fastq.endswith(".fq.gz"):
kkonganti@17 100 # print_error(
kkonganti@17 101 # "FastQ file does not have extension '.fastq.gz' or '.fq.gz'!",
kkonganti@17 102 # "Line",
kkonganti@17 103 # line,
kkonganti@17 104 # )
kkonganti@17 105
kkonganti@17 106 ## Check strandedness
kkonganti@17 107 strandednesses = ["unstranded", "forward", "reverse"]
kkonganti@17 108 if strandedness:
kkonganti@17 109 if strandedness not in strandednesses:
kkonganti@17 110 print_error(
kkonganti@17 111 f"Strandedness must be one of '{', '.join(strandednesses)}'!",
kkonganti@17 112 "Line",
kkonganti@17 113 line,
kkonganti@17 114 )
kkonganti@17 115 else:
kkonganti@17 116 print_error(
kkonganti@17 117 f"Strandedness has not been specified! Must be one of {', '.join(strandednesses)}.",
kkonganti@17 118 "Line",
kkonganti@17 119 line,
kkonganti@17 120 )
kkonganti@17 121
kkonganti@17 122 ## Auto-detect paired-end/single-end
kkonganti@17 123 sample_info = [] ## [single_end, fq1, fq2, strandedness]
kkonganti@17 124 if sample and fq1 and fq2: ## Paired-end short reads
kkonganti@17 125 sample_info = ["0", fq1, fq2, strandedness]
kkonganti@17 126 elif sample and fq1 and not fq2: ## Single-end short reads
kkonganti@17 127 sample_info = ["1", fq1, fq2, strandedness]
kkonganti@17 128 else:
kkonganti@17 129 print_error("Invalid combination of columns provided!", "Line", line)
kkonganti@17 130
kkonganti@17 131 ## Create sample mapping dictionary = {sample: [[ single_end, fq1, fq2, strandedness ]]}
kkonganti@17 132 if sample not in sample_mapping_dict:
kkonganti@17 133 sample_mapping_dict[sample] = [sample_info]
kkonganti@17 134 else:
kkonganti@17 135 if sample_info in sample_mapping_dict[sample]:
kkonganti@17 136 print_error("Samplesheet contains duplicate rows!", "Line", line)
kkonganti@17 137 else:
kkonganti@17 138 sample_mapping_dict[sample].append(sample_info)
kkonganti@17 139
kkonganti@17 140 ## Write validated samplesheet with appropriate columns
kkonganti@17 141 if len(sample_mapping_dict) > 0:
kkonganti@17 142 out_dir = os.path.dirname(file_out)
kkonganti@17 143 make_dir(out_dir)
kkonganti@17 144 with open(file_out, "w") as fout:
kkonganti@17 145 fout.write(
kkonganti@17 146 ",".join(["sample", "single_end", "fq1", "fq2", "strandedness"])
kkonganti@17 147 + "\n"
kkonganti@17 148 )
kkonganti@17 149 for sample in sorted(sample_mapping_dict.keys()):
kkonganti@17 150
kkonganti@17 151 ## Check that multiple runs of the same sample are of the same datatype i.e. single-end / paired-end
kkonganti@17 152 if not all(
kkonganti@17 153 x[0] == sample_mapping_dict[sample][0][0]
kkonganti@17 154 for x in sample_mapping_dict[sample]
kkonganti@17 155 ):
kkonganti@17 156 print_error(
kkonganti@17 157 f"Multiple runs of a sample must be of the same datatype i.e. single-end or paired-end!",
kkonganti@17 158 "Sample",
kkonganti@17 159 sample,
kkonganti@17 160 )
kkonganti@17 161
kkonganti@17 162 ## Check that multiple runs of the same sample are of the same strandedness
kkonganti@17 163 if not all(
kkonganti@17 164 x[-1] == sample_mapping_dict[sample][0][-1]
kkonganti@17 165 for x in sample_mapping_dict[sample]
kkonganti@17 166 ):
kkonganti@17 167 print_error(
kkonganti@17 168 f"Multiple runs of a sample must have the same strandedness!",
kkonganti@17 169 "Sample",
kkonganti@17 170 sample,
kkonganti@17 171 )
kkonganti@17 172
kkonganti@17 173 for idx, val in enumerate(sample_mapping_dict[sample]):
kkonganti@17 174 fout.write(",".join([f"{sample}_T{idx+1}"] + val) + "\n")
kkonganti@17 175 else:
kkonganti@17 176 print_error(f"No entries to process!", "Samplesheet: {file_in}")
kkonganti@17 177
kkonganti@17 178
kkonganti@17 179 def main(args=None):
kkonganti@17 180 args = parse_args(args)
kkonganti@17 181 check_samplesheet(args.FILE_IN, args.FILE_OUT)
kkonganti@17 182
kkonganti@17 183
kkonganti@17 184 if __name__ == "__main__":
kkonganti@17 185 sys.exit(main())