/nanopore/_scripts/trim-leaders-fastq.py

https://github.com/hyeshik/sars-cov-2-transcriptome
Python | 100 lines | 58 code | 19 blank | 23 comment | 17 complexity | 45ea7b0bcc611bde1618e8f025a4498e MD5 | raw file
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (c) 2020 Hyeshik Chang
  4. #
  5. # Permission is hereby granted, free of charge, to any person obtaining a copy
  6. # of this software and associated documentation files (the "Software"), to deal
  7. # in the Software without restriction, including without limitation the rights
  8. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. # copies of the Software, and to permit persons to whom the Software is
  10. # furnished to do so, subject to the following conditions:
  11. #
  12. # The above copyright notice and this permission notice shall be included in
  13. # all copies or substantial portions of the Software.
  14. #
  15. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. # THE SOFTWARE.
  22. #
  23. import pysam
  24. from itertools import groupby
  25. import re
  26. import sys
  27. import pandas as pd
  28. import glob
  29. from Bio import SeqIO
  30. import gzip
  31. LEADER_TRIMMING_UPPER_LIMIT = 100
  32. cigar_pat = re.compile('\\d+[A-Z]')
  33. input_bam = sys.argv[1]
  34. input_fn = sys.argv[2]
  35. output_fn = sys.argv[3]
  36. def get_sam_reads_by_group(filename):
  37. get_subject_name = lambda aln: aln.reference_name
  38. with pysam.AlignmentFile(filename) as alnfile:
  39. for qname, alns in groupby(alnfile, key=get_subject_name):
  40. yield qname, list(alns)
  41. def get_alignment_lengths(cigar):
  42. tokens = cigar_pat.findall(cigar)
  43. left_clip = int(tokens[0][:-1]) if tokens[0][-1] == 'H' else 0
  44. right_clip = int(tokens[-1][:-1]) if tokens[-1][-1] == 'H' else 0
  45. refpos = readpos = 0
  46. for tok in tokens:
  47. op = tok[-1]
  48. length = int(tok[:-1])
  49. if op in 'MI':
  50. readpos += length
  51. if op in 'MDN':
  52. refpos += length
  53. if op == 'S':
  54. raise ValueError('S is not handled.')
  55. return readpos, refpos, left_clip, right_clip
  56. leader_matches = []
  57. for filename in glob.glob('alignments/VeroInf24h.viral-leader.blast/part-*.bam'):
  58. #print(filename)
  59. for qname, alns in get_sam_reads_by_group(filename):
  60. if len(alns) > 1:
  61. continue
  62. for aln in alns:
  63. readstart = aln.reference_start
  64. salnwidth, qalnwidth, lclip, rclip = get_alignment_lengths(aln.cigarstring)
  65. vg_range = lclip, lclip + salnwidth
  66. rd_range = readstart, readstart + qalnwidth
  67. leader_matches.append([aln.reference_name, rd_range[0], rd_range[1],
  68. vg_range[0], vg_range[1], lclip, rclip])
  69. leader_matches = \
  70. pd.DataFrame(leader_matches, columns=['read_id', 'read_start', 'read_end',
  71. 'query_start', 'query_end',
  72. 'left_clip', 'right_clip'])
  73. high_quality_matches = \
  74. leader_matches[(leader_matches['read_end'] < LEADER_TRIMMING_UPPER_LIMIT) &
  75. (leader_matches['right_clip'] < 1)]
  76. trimming_length = high_quality_matches.set_index('read_id')['read_end'].to_dict()
  77. with gzip.open(output_fn, 'wt') as wrtfile:
  78. for seq in SeqIO.parse(gzip.open(input_fn, 'rt'), 'fastq'):
  79. trimlen = trimming_length.get(seq.name)
  80. if trimlen is not None:
  81. SeqIO.write([seq[trimlen:]], wrtfile, 'fastq')