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