annotate 0.4.2/bin/check_samplesheet.py @ 143:620bffa66bbb tip

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