annotate 0.4.0/bin/check_samplesheet.py @ 101:ce6d9548fe89

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