annotate 0.3.0/bin/check_samplesheet.py @ 92:295c2597a475

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