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