comparison small_rna_map.py @ 3:2e0dc6032a98 draft

planemo upload for repository https://github.com/ARTbio/tools-artbio/tree/master/tools/small_rna_map commit 93f212712d9846c7aaa389de60babb332d38363e
author artbio
date Tue, 18 Jul 2017 13:34:36 -0400
parents 1ad5d040f85f
children d65045e976e6
comparison
equal deleted inserted replaced
2:7feee0446c5c 3:2e0dc6032a98
1 import os 1 import argparse
2 from os.path import basename 2 from collections import defaultdict
3
4 import numpy
5
3 import pysam 6 import pysam
4 import argparse
5 import numpy
6 import collections
7 7
8 8
9 def Parser(): 9 def Parser():
10 the_parser = argparse.ArgumentParser() 10 the_parser = argparse.ArgumentParser()
11 the_parser.add_argument('--input', dest="input", required=True, nargs='+', help='input BAM files') 11 the_parser.add_argument('--input', dest='input', required=True,
12 the_parser.add_argument('--output', action="store", type=str, help="output tabular file") 12 nargs='+', help='input BAM files')
13 the_parser.add_argument('--sample_name', dest='sample_name',
14 required=True, nargs='+', help='sample name')
15 the_parser.add_argument('--output', action="store",
16 type=str, help='output tabular file')
13 args = the_parser.parse_args() 17 args = the_parser.parse_args()
14 return args 18 return args
15 19
16 20
17 def Ref_length(bamfile): 21 def compute_map_dictionary(pysam_object):
18 """ 22 '''
19 bamfile.references: list of reference names, and bamfile.lengths is list of their lengths 23 returns
20 """ 24 - map_dictionary {(read_chromosome,read_position,polarity):
21 ref_length={} 25 [list_of_read_length]}
22 for e1, e2 in zip(bamfile.references, bamfile.lengths): 26 - max_dictionary {chromosome_name:
23 ref_length[e1]=e2 27 max_of_number_of_read_at_any_position}
24 return ref_length 28 '''
29 unmatched_chromosomes = list(pysam_object.references)
30 map_dictionary = defaultdict(list)
31 max_dictionary = dict.fromkeys(pysam_object.references, 0)
32 for read in pysam_object:
33 if not read.is_unmapped:
34 read_chromosome = read.reference_name
35 # to shift from 0-based to 1-based coordinate
36 read_position = read.pos + 1
37 polarity = "F" if (not read.is_reverse) else "R"
38 map_dictionary[(read_chromosome, read_position,
39 polarity)].append(read.qlen)
40 if read_chromosome in unmatched_chromosomes:
41 unmatched_chromosomes.remove(read_chromosome)
42 for name in unmatched_chromosomes:
43 # to put at least a null value by chromosome
44 map_dictionary[(name, 1, 'F')] = [0]
45 # make a dictionary with max value of reads by chromosome
46 max_dictionary = defaultdict(int)
47 for name in pysam_object.references:
48 for key in map_dictionary.keys():
49 if name in key and len(map_dictionary[key]) > max_dictionary[name]:
50 max_dictionary[name] = len(map_dictionary[key])
51 return map_dictionary, max_dictionary
25 52
26 53
27 def Ref_coord_pol(bamfile): 54 def main(inputs, sample_names, output):
28 ref_coord ={} 55 with open(output, 'w') as outfile:
29 rnames =list(bamfile.references) 56 outfile.write('\t'.join(['Dataset', 'Chromosome', 'Chrom_length',
30 for read in bamfile: 57 'Coordinate', 'Nbr_reads', 'Polarity',
31 if not read.is_unmapped: 58 'Max', 'Mean', 'Median\n']))
32 polarity = "F" if (not read.is_reverse) else "R" 59 chr_lengths = dict(zip(pysam.AlignmentFile(inputs[0], 'rb').references,
33 read_rname = read.reference_name 60 pysam.AlignmentFile(inputs[0], 'rb').lengths))
34 read_position = read.pos + 1 61 for file, sample in zip(inputs, sample_names):
35 the_key = (read_rname, read_position,polarity) 62 with pysam.AlignmentFile(file, 'rb') as bamfile:
36 read_length = read.qlen 63 map, maximum = compute_map_dictionary(bamfile)
37 try: 64 for record in sorted(map):
38 ref_coord[the_key][0] = ref_coord[the_key][0]+1 65 line = [sample, record[0],
39 ref_coord[the_key][1].append(read_length) 66 str(chr_lengths[record[0]]),
40 except: 67 str(record[1]), str(len(map[record])),
41 ref_coord[the_key] = [1,[read_length]] 68 record[2], str(maximum[record[0]]),
42 if read_rname in rnames: 69 str(round(numpy.mean(map[record]), 1)),
43 rnames.remove(read_rname) 70 str(numpy.median(map[record]))]
44 for rname in rnames: 71 outfile.write("\t".join(line) + "\n")
45 ref_coord[(rname, 0, "F")]=[0,[0]]
46 return collections.OrderedDict(sorted(ref_coord.items())) #dictionary {(read_rname,read_position,polarity):[nmbr_read,list_of_alignment_length]}
47
48
49 def calcul_stat(dictionary,ref):
50 dico = {}
51 for keys in dictionary:
52 key = keys[0] #reference name
53 value = dictionary[keys][0] # position
54 try:
55 dico[key].append(value)
56 except:
57 dico[key] = []
58 dico[key].append(value)
59 the_max = max(dico[ref])
60 return the_max
61
62
63 def filename(infile):
64 filename = basename(infile.filename)
65 the_name = filename.split('.')
66 return the_name[0]
67
68
69 def main(infile, output):
70 with open(output,"w") as outfile:
71 outfile.write("Dataset" + "\t" + "Chromosome"+ "\t" + "Chrom_length" + "\t" + "Coordinate" + "\t" + "Nbr_reads" + "\t" + "Polarity" + "\t" + "Max" + "\t" + "Mean" + "\t" + "Median" + "\n")
72 for bamfile in infile:
73 with pysam.AlignmentFile(bamfile,"rb") as bamfile:
74 ref_coord = Ref_coord_pol(bamfile)
75 ref_length = Ref_length(bamfile)
76 tabulation = "\t"
77 for read in ref_coord:
78 table = (str(filename(bamfile)), str(read[0]), str(ref_length[str(read[0])]), str(read[1]), str(ref_coord[read][0]), str(read[2]), str(calcul_stat(ref_coord,read[0])), str(round(numpy.mean(ref_coord[read][1]),1)), str(numpy.median(ref_coord[read][1])))
79 outfile.write(tabulation.join(table) + "\n")
80 72
81 73
82 if __name__ == "__main__": 74 if __name__ == "__main__":
83 args= Parser() 75 args = Parser()
84 main(args.input, args.output) 76 # if identical sample names # to be tested
77 if len(set(args.sample_name)) != len(args.sample_name):
78 args.sample_name = [name + '_' + str(i) for
79 i, name in enumerate(args.sample_name)]
80 main(args.input, args.sample_name, args.output)