Debian Codegraph @

misc/read_length_identity.py

raw
1 #!/usr/bin/env python3
2
3 """
4 Copyright 2017 Ryan Wick ([email protected])
5 https://github.com/rrwick/Filtlong
6
7 This script was used to get read length/identity stats from a minimap2 PAF alignment file. I used
8 it to make the scatterplot/histogram figures in the Filtlong README. It uses a particularly strict
9 definition of read identity: all bases are considered and unaligned bases are assigned an identity
10 of 0. So if a read had half of its bases align with an identity of 90% and the other half is
11 unaligned, then the read's final identity would be 45%.
12
13 Example commands:
14 filtlong {OPTIONS} input.fastq.gz | gzip > filtered.fastq.gz
15 minimap2 -x map10k -t 16 -c reference.fasta filtered.fastq.gz > alignments.paf
16 read_length_identity.py alignments.paf > read_stats.tsv
17
18 This file is part of Filtlong. Filtlong is free software: you can redistribute it and/or modify
19 it under the terms of the GNU General Public License as published by the Free Software Foundation,
20 either version 3 of the License, or (at your option) any later version. Filtlong is distributed in
21 the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
22 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
23 details. You should have received a copy of the GNU General Public License along with Filtlong. If
24 not, see <http://www.gnu.org/licenses/>.
25 """
26
27 import sys
28 import collections
29 import statistics
30
31
32 def main():
33 read_lengths = {}
34 read_alignments = collections.defaultdict(list)
35
36 paf_filename = sys.argv[1]
37 with open(paf_filename, 'rt') as paf:
38 for line in paf:
39 paf_parts = line.strip().split('\t')
40 if len(paf_parts) < 11:
41 continue
42 read_name = paf_parts[0]
43 read_length = int(paf_parts[1])
44 read_lengths[read_name] = read_length
45 start = int(paf_parts[2])
46 end = int(paf_parts[3])
47 identity = 100.0 * int(paf_parts[9]) / int(paf_parts[10])
48 read_alignments[read_name].append((start, end, identity))
49
50 print('\t'.join(['Name', 'Length', 'Identity']))
51 for read_name, read_length in read_lengths.items():
52 alignments = read_alignments[read_name]
53 identity_by_base = [0.0] * read_length
54 for start, end, identity in alignments:
55 for i in range(start, end):
56 if identity > identity_by_base[i]:
57 identity_by_base[i] = identity
58 whole_read_identity = statistics.mean(identity_by_base)
59 print('\t'.join([read_name, str(read_length), str(whole_read_identity)]))
60
61
62 if __name__ == '__main__':
63 main()