|
| 1 | +#!/usr/bin/env python |
| 2 | + |
| 3 | + |
| 4 | +import argparse |
| 5 | +import csv |
| 6 | + |
| 7 | + |
| 8 | +def _get_args(): |
| 9 | + '''This function parses and return arguments passed in''' |
| 10 | + parser = argparse.ArgumentParser( |
| 11 | + prog='kraken_parse', |
| 12 | + formatter_class=argparse.RawDescriptionHelpFormatter, |
| 13 | + description='Parsing kraken') |
| 14 | + parser.add_argument('krakenReport', help="path to kraken report file") |
| 15 | + parser.add_argument( |
| 16 | + '-c', |
| 17 | + dest="count", |
| 18 | + default=50, |
| 19 | + help="Minimum number of hits on clade to report it. Default = 50") |
| 20 | + parser.add_argument( |
| 21 | + '-o', |
| 22 | + dest="output", |
| 23 | + default=None, |
| 24 | + help="Output file. Default = <basename>.kraken_parsed.csv") |
| 25 | + |
| 26 | + args = parser.parse_args() |
| 27 | + |
| 28 | + infile = args.krakenReport |
| 29 | + countlim = int(args.count) |
| 30 | + outfile = args.output |
| 31 | + |
| 32 | + return(infile, countlim, outfile) |
| 33 | + |
| 34 | + |
| 35 | +def _get_basename(file_name): |
| 36 | + if ("/") in file_name: |
| 37 | + basename = file_name.split("/")[-1].split(".")[0] |
| 38 | + else: |
| 39 | + basename = file_name.split(".")[0] |
| 40 | + return(basename) |
| 41 | + |
| 42 | + |
| 43 | +def parse_kraken(infile, countlim): |
| 44 | + ''' |
| 45 | + INPUT: |
| 46 | + infile (str): path to kraken report file |
| 47 | + countlim (int): lowest count threshold to report hit |
| 48 | + OUTPUT: |
| 49 | + resdict (dict): key=taxid, value=readCount |
| 50 | +
|
| 51 | + ''' |
| 52 | + with open(infile, 'r') as f: |
| 53 | + resdict = {} |
| 54 | + csvreader = csv.reader(f, delimiter='\t') |
| 55 | + for line in csvreader: |
| 56 | + reads = int(line[1]) |
| 57 | + if reads >= countlim: |
| 58 | + taxid = line[4] |
| 59 | + resdict[taxid] = reads |
| 60 | + return(resdict) |
| 61 | + |
| 62 | + |
| 63 | +def write_output(resdict, infile, outfile): |
| 64 | + with open(outfile, 'w') as f: |
| 65 | + basename = _get_basename(infile) |
| 66 | + f.write(f"TAXID,{basename}\n") |
| 67 | + for akey in resdict.keys(): |
| 68 | + f.write(f"{akey},{resdict[akey]}\n") |
| 69 | + |
| 70 | + |
| 71 | +if __name__ == '__main__': |
| 72 | + INFILE, COUNTLIM, outfile = _get_args() |
| 73 | + |
| 74 | + if not outfile: |
| 75 | + outfile = _get_basename(INFILE)+".kraken_parsed.csv" |
| 76 | + |
| 77 | + tmp_dict = parse_kraken(infile=INFILE, countlim=COUNTLIM) |
| 78 | + write_output(resdict=tmp_dict, infile=INFILE, outfile=outfile) |
0 commit comments