kkonganti@92: #!/usr/bin/env python3 kkonganti@92: kkonganti@92: import os kkonganti@92: import sys kkonganti@92: import errno kkonganti@92: import argparse kkonganti@92: kkonganti@92: kkonganti@92: def parse_args(args=None): kkonganti@92: Description = "Reformat samplesheet file and check its contents." kkonganti@92: Epilog = "Example usage: python check_samplesheet.py " kkonganti@92: kkonganti@92: parser = argparse.ArgumentParser(description=Description, epilog=Epilog) kkonganti@92: parser.add_argument("FILE_IN", help="Input samplesheet file.") kkonganti@92: parser.add_argument("FILE_OUT", help="Output file.") kkonganti@92: return parser.parse_args(args) kkonganti@92: kkonganti@92: kkonganti@92: def make_dir(path): kkonganti@92: if len(path) > 0: kkonganti@92: try: kkonganti@92: os.makedirs(path) kkonganti@92: except OSError as exception: kkonganti@92: if exception.errno != errno.EEXIST: kkonganti@92: raise exception kkonganti@92: kkonganti@92: kkonganti@92: def print_error(error, context="Line", context_str=""): kkonganti@92: error_str = f"ERROR: Please check samplesheet -> {error}" kkonganti@92: if context != "" and context_str != "": kkonganti@92: error_str = f"ERROR: Please check samplesheet -> {error}\n{context.strip()}: '{context_str.strip()}'" kkonganti@92: print(error_str) kkonganti@92: sys.exit(1) kkonganti@92: kkonganti@92: kkonganti@92: def check_samplesheet(file_in, file_out): kkonganti@92: """ kkonganti@92: This function checks that the samplesheet follows the following structure: kkonganti@92: kkonganti@92: sample,fq1,fq2,strandedness kkonganti@92: SAMPLE_PE,SAMPLE_PE_RUN1_1.fastq.gz,SAMPLE_PE_RUN1_2.fastq.gz,forward kkonganti@92: SAMPLE_PE,SAMPLE_PE_RUN2_1.fastq.gz,SAMPLE_PE_RUN2_2.fastq.gz,forward kkonganti@92: SAMPLE_SE,SAMPLE_SE_RUN1_1.fastq,,forward kkonganti@92: SAMPLE_SE,SAMPLE_SE_RUN1_2.fastq.gz,,forward kkonganti@92: kkonganti@92: For an example see: kkonganti@92: https://github.com/nf-core/test-datasets/blob/rnaseq/samplesheet/v3.1/samplesheet_test.csv kkonganti@92: """ kkonganti@92: kkonganti@92: sample_mapping_dict = {} kkonganti@92: with open(file_in, "r", encoding='utf-8-sig') as fin: kkonganti@92: kkonganti@92: ## Check header kkonganti@92: MIN_COLS = 3 kkonganti@92: HEADER = ["sample", "fq1", "fq2", "strandedness"] kkonganti@92: header = [x.strip('"') for x in fin.readline().strip().split(",")] kkonganti@92: if header[: len(HEADER)] != HEADER: kkonganti@92: print( kkonganti@92: f"ERROR: Please check samplesheet header -> {','.join(header)} != {','.join(HEADER)}" kkonganti@92: ) kkonganti@92: sys.exit(1) kkonganti@92: kkonganti@92: ## Check sample entries kkonganti@92: for line in fin: kkonganti@92: if line.strip(): kkonganti@92: lspl = [x.strip().strip('"') for x in line.strip().split(",")] kkonganti@92: kkonganti@92: ## Check valid number of columns per row kkonganti@92: if len(lspl) < len(HEADER): kkonganti@92: print_error( kkonganti@92: f"Invalid number of columns (minimum = {len(HEADER)})!", kkonganti@92: "Line", kkonganti@92: line, kkonganti@92: ) kkonganti@92: kkonganti@92: num_cols = len([x for x in lspl if x]) kkonganti@92: if num_cols < MIN_COLS: kkonganti@92: print_error( kkonganti@92: f"Invalid number of populated columns (minimum = {MIN_COLS})!", kkonganti@92: "Line", kkonganti@92: line, kkonganti@92: ) kkonganti@92: kkonganti@92: ## Check sample name entries kkonganti@92: sample, fq1, fq2, strandedness = lspl[: len(HEADER)] kkonganti@92: if sample.find(" ") != -1: kkonganti@92: print( kkonganti@92: f"WARNING: Spaces have been replaced by underscores for sample: {sample}" kkonganti@92: ) kkonganti@92: sample = sample.replace(" ", "_") kkonganti@92: if not sample: kkonganti@92: print_error("Sample entry has not been specified!", "Line", line) kkonganti@92: kkonganti@92: ## Check FastQ file extension kkonganti@92: for fastq in [fq1, fq2]: kkonganti@92: if fastq: kkonganti@92: if fastq.find(" ") != -1: kkonganti@92: print_error("FastQ file contains spaces!", "Line", line) kkonganti@92: # if not fastq.endswith(".fastq.gz") and not fastq.endswith(".fq.gz"): kkonganti@92: # print_error( kkonganti@92: # "FastQ file does not have extension '.fastq.gz' or '.fq.gz'!", kkonganti@92: # "Line", kkonganti@92: # line, kkonganti@92: # ) kkonganti@92: kkonganti@92: ## Check strandedness kkonganti@92: strandednesses = ["unstranded", "forward", "reverse"] kkonganti@92: if strandedness: kkonganti@92: if strandedness not in strandednesses: kkonganti@92: print_error( kkonganti@92: f"Strandedness must be one of '{', '.join(strandednesses)}'!", kkonganti@92: "Line", kkonganti@92: line, kkonganti@92: ) kkonganti@92: else: kkonganti@92: print_error( kkonganti@92: f"Strandedness has not been specified! Must be one of {', '.join(strandednesses)}.", kkonganti@92: "Line", kkonganti@92: line, kkonganti@92: ) kkonganti@92: kkonganti@92: ## Auto-detect paired-end/single-end kkonganti@92: sample_info = [] ## [single_end, fq1, fq2, strandedness] kkonganti@92: if sample and fq1 and fq2: ## Paired-end short reads kkonganti@92: sample_info = ["0", fq1, fq2, strandedness] kkonganti@92: elif sample and fq1 and not fq2: ## Single-end short reads kkonganti@92: sample_info = ["1", fq1, fq2, strandedness] kkonganti@92: else: kkonganti@92: print_error("Invalid combination of columns provided!", "Line", line) kkonganti@92: kkonganti@92: ## Create sample mapping dictionary = {sample: [[ single_end, fq1, fq2, strandedness ]]} kkonganti@92: if sample not in sample_mapping_dict: kkonganti@92: sample_mapping_dict[sample] = [sample_info] kkonganti@92: else: kkonganti@92: if sample_info in sample_mapping_dict[sample]: kkonganti@92: print_error("Samplesheet contains duplicate rows!", "Line", line) kkonganti@92: else: kkonganti@92: sample_mapping_dict[sample].append(sample_info) kkonganti@92: kkonganti@92: ## Write validated samplesheet with appropriate columns kkonganti@92: if len(sample_mapping_dict) > 0: kkonganti@92: out_dir = os.path.dirname(file_out) kkonganti@92: make_dir(out_dir) kkonganti@92: with open(file_out, "w") as fout: kkonganti@92: fout.write( kkonganti@92: ",".join(["sample", "single_end", "fq1", "fq2", "strandedness"]) kkonganti@92: + "\n" kkonganti@92: ) kkonganti@92: for sample in sorted(sample_mapping_dict.keys()): kkonganti@92: kkonganti@92: ## Check that multiple runs of the same sample are of the same datatype i.e. single-end / paired-end kkonganti@92: if not all( kkonganti@92: x[0] == sample_mapping_dict[sample][0][0] kkonganti@92: for x in sample_mapping_dict[sample] kkonganti@92: ): kkonganti@92: print_error( kkonganti@92: f"Multiple runs of a sample must be of the same datatype i.e. single-end or paired-end!", kkonganti@92: "Sample", kkonganti@92: sample, kkonganti@92: ) kkonganti@92: kkonganti@92: ## Check that multiple runs of the same sample are of the same strandedness kkonganti@92: if not all( kkonganti@92: x[-1] == sample_mapping_dict[sample][0][-1] kkonganti@92: for x in sample_mapping_dict[sample] kkonganti@92: ): kkonganti@92: print_error( kkonganti@92: f"Multiple runs of a sample must have the same strandedness!", kkonganti@92: "Sample", kkonganti@92: sample, kkonganti@92: ) kkonganti@92: kkonganti@92: for idx, val in enumerate(sample_mapping_dict[sample]): kkonganti@92: fout.write(",".join([f"{sample}_T{idx+1}"] + val) + "\n") kkonganti@92: else: kkonganti@92: print_error(f"No entries to process!", "Samplesheet: {file_in}") kkonganti@92: kkonganti@92: kkonganti@92: def main(args=None): kkonganti@92: args = parse_args(args) kkonganti@92: check_samplesheet(args.FILE_IN, args.FILE_OUT) kkonganti@92: kkonganti@92: kkonganti@92: if __name__ == "__main__": kkonganti@92: sys.exit(main())