comparison scripts/ReMatCh/utils/strip_alignment.py @ 0:c6bab5103a14 draft

"planemo upload commit 6abf3e299d82d07e6c3cf8642bdea80e96df64c3-dirty"
author iss
date Mon, 21 Mar 2022 15:23:09 +0000
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:c6bab5103a14
1 #!/usr/bin/env python3
2
3 # -*- coding: utf-8 -*-
4
5 """
6 strip_alignment.py - Strip alignment positions containing gaps,
7 missing data and invariable positions
8 <https://github.com/B-UMMI/ReMatCh/>
9
10 Copyright (C) 2018 Miguel Machado <mpmachado@medicina.ulisboa.pt>
11
12 Last modified: October 15, 2018
13
14 This program is free software: you can redistribute it and/or modify
15 it under the terms of the GNU General Public License as published by
16 the Free Software Foundation, either version 3 of the License, or
17 (at your option) any later version.
18
19 This program is distributed in the hope that it will be useful,
20 but WITHOUT ANY WARRANTY; without even the implied warranty of
21 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 GNU General Public License for more details.
23
24 You should have received a copy of the GNU General Public License
25 along with this program. If not, see <http://www.gnu.org/licenses/>.
26 """
27
28 from Bio import SeqIO
29 import os
30 import argparse
31 import sys
32
33
34 version = '0.2'
35
36
37 def get_sequences(infile):
38 print('Getting sequences')
39 sequences_seq_io = list(SeqIO.parse(infile, 'fasta'))
40
41 sequence_length = None
42 sequences_dict = {}
43 all_executed_printed = False
44 for x, sequence in enumerate(sequences_seq_io):
45 if sequence_length is None:
46 sequence_length = len(sequence.seq)
47 if sequence_length != len(sequence.seq):
48 sys.exit('Sequences with different length!')
49 sequences_dict[sequence.id] = list(sequence.seq)
50
51 if (x + 1) % 10 == 0:
52 print('\n' + str(round((float(x + 1) / len(sequences_seq_io)) * 100, 2)) + '% of sequences already processed (getting sequences)')
53 if x + 1 == len(sequences_seq_io):
54 all_executed_printed = True
55 if not all_executed_printed:
56 print('\n' + str(round((float(x + 1) / len(sequences_seq_io)) * 100, 2)) + '% of sequences already processed (getting sequences)')
57
58 return sequences_dict, sequence_length
59
60
61 def positions_type(sequences_dict, sequence_length, not_gaps, not_missing, not_invariable):
62 print('Determining positions type')
63 positions_2_keep = []
64 invariable = []
65 missing = []
66 gaps = []
67 gaps_missing = 0
68 all_executed_printed = False
69 for i in range(0, sequence_length):
70 data = []
71 for sample in sequences_dict:
72 data.append(sequences_dict[sample][i])
73 possibilities = set(data)
74 if len(possibilities) == 1:
75 invariable.append(i)
76 if len(possibilities.intersection(set(['N']))) > 0:
77 missing.append(i)
78 if len(possibilities.intersection(set(['-']))) > 0:
79 gaps.append(i)
80 if len(possibilities.intersection(set(['N', '-']))) > 0:
81 gaps_missing += 1
82 if len(possibilities) > 1 and len(possibilities.intersection(set(['N', '-']))) == 0:
83 positions_2_keep.append(i)
84
85 if (i + 1) % 10000 == 0:
86 print('\n' + str(round((float(i + 1) / sequence_length) * 100, 2)) + '% of positions already'
87 ' processed (determining positions'
88 ' type)')
89 if i + 1 == len(sequences_dict):
90 all_executed_printed = True
91 if not all_executed_printed:
92 print('\n' + str(round((float(i + 1) / sequence_length) * 100, 2)) + '% of positions already'
93 ' processed (determining positions'
94 ' type)')
95
96 print('Positions to keep (no matter): ' + str(len(positions_2_keep)))
97 print('Invariable sites: ' + str(len(invariable)))
98 print('Positions with missing data ("N"): ' + str(len(missing)))
99 print('Positions with GAPs ("-"): ' + str(len(gaps)))
100 print('Positions with GAPs or missing data: ' + str(gaps_missing))
101
102 if not_gaps:
103 positions_2_keep.extend(gaps)
104 if not_missing:
105 positions_2_keep.extend(missing)
106 if not_invariable:
107 positions_2_keep.extend(invariable)
108
109 positions_2_keep = sorted(set(positions_2_keep))
110
111 print('Positions to keep (final): ' + str(len(positions_2_keep)))
112
113 return positions_2_keep
114
115
116 def chunkstring(string, length):
117 return (string[0 + i:length + i] for i in range(0, len(string), length))
118
119
120 def write_fasta(sequences_dict, positions_2_keep, outfile):
121 print('Writing stripped sequences')
122 all_executed_printed = False
123 with open(outfile, 'wt') as writer:
124 for x, sample in enumerate(sequences_dict):
125 writer.write('>' + sample + '\n')
126 fasta_sequence_lines = chunkstring(''.join([sequences_dict[sample][i] for i in positions_2_keep]), 80)
127 for line in fasta_sequence_lines:
128 writer.write(line + '\n')
129
130 if (x + 1) % 100 == 0:
131 print('\n' + str(round((float(x + 1) / len(sequences_dict)) * 100, 2)) + '% of sequences already'
132 ' processed (writing stripped'
133 ' sequences)')
134 if x + 1 == len(sequences_dict):
135 all_executed_printed = True
136 if not all_executed_printed:
137 print('\n' + str(round((float(x + 1) / len(sequences_dict)) * 100, 2)) + '% of sequences already'
138 ' processed (writing stripped'
139 ' sequences)')
140
141
142 def strip_alignment(args):
143 outdir = os.path.dirname(os.path.abspath(args.outfile))
144 if not os.path.isdir(outdir):
145 os.makedirs(outdir)
146
147 outfile = os.path.abspath(args.outfile)
148
149 infile = os.path.abspath(args.infile.name)
150
151 sequences_dict, sequence_length = get_sequences(infile)
152 positions_2_keep = positions_type(sequences_dict, sequence_length, args.notGAPs, args.notMissing,
153 args.notInvariable)
154 write_fasta(sequences_dict, positions_2_keep, outfile)
155
156
157 def main():
158 parser = argparse.ArgumentParser(prog='strip_alignment.py',
159 description='Strip alignment positions containing gaps, missing data and'
160 ' invariable positions',
161 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
162 parser.add_argument('--version', help='Version information', action='version', version=str('%(prog)s v' + version))
163
164 parser_required = parser.add_argument_group('Required options')
165 parser_required.add_argument('-i', '--infile', type=argparse.FileType('r'),
166 metavar='/path/to/aligned/input/file.fasta', help='Path to the aligned fasta file',
167 required=True)
168 parser_required.add_argument('-o', '--outfile', type=str, metavar='/path/to/stripped/output/file.fasta',
169 help='Stripped output fasta file', required=True, default='alignment_stripped.fasta')
170
171 parser_optional_general = parser.add_argument_group('General facultative options')
172 parser_optional_general.add_argument('--notGAPs', action='store_true', help='Not strip positions with GAPs')
173 parser_optional_general.add_argument('--notMissing', action='store_true',
174 help='Not strip positions with missing data')
175 parser_optional_general.add_argument('--notInvariable', action='store_true', help='Not strip invariable sites')
176
177 args = parser.parse_args()
178
179 strip_alignment(args)
180
181
182 if __name__ == "__main__":
183 main()