-
Notifications
You must be signed in to change notification settings - Fork 0
/
FASTA_inspect.py
executable file
·311 lines (253 loc) · 12.3 KB
/
FASTA_inspect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
#!/usr/bin/env python3
"""
Purpose: Inspect a FASTA file for basic metrics of interest and lack of redundancy
Author : Chase W. Nelson <[email protected]>
Cite : https://github.com/chasewnelson/
Date : 2022-01-29
Details: <FILL IN>
Returns:
<FILL IN>
"""
import argparse
import os
import sys
from Bio import Align, AlignIO, SeqIO
from collections import Counter, defaultdict
from evobioinfo import GAPS, hamming, IUPAC, IUPAC_AMBIG, NUCS_DEFINED, NUCS_INDETERMINATE, summary_string
from numpy import nan as NA
from typing import Dict, List, NamedTuple
# Usage
usage = """# -----------------------------------------------------------------------------
FASTA_inspect.py - Inspect a FASTA file for basic metrics of interest and lack of redundancy
# -----------------------------------------------------------------------------
For DOCUMENTATION, run:
$ FASTA_inspect.py --help
$ pydoc ./FASTA_inspect.py
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
EXAMPLE:
$ FASTA_inspect.py --seq_file=seqs.fasta -p
# -----------------------------------------------------------------------------
"""
class Args(NamedTuple):
""" Command-line arguments """
seq_file: str
p_dist: bool
# -----------------------------------------------------------------------------
def get_args() -> Args:
""" Get command-line arguments """
parser = argparse.ArgumentParser(
description='Inspect a FASTA file for basic metrics of interest and lack of redundancy. HELP: FASTA_inspect.py --help',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Rename "optional" arguments
parser._optionals.title = 'Named arguments'
# -------------------------------------------------------------------------
# REQUIRED
parser.add_argument('-i',
'--seq_file',
metavar='FILE',
help='FASTA file containing sequence(s) [REQUIRED]',
required=True,
# nargs='+',
type=str)
# -------------------------------------------------------------------------
# OPTIONAL
parser.add_argument('-p',
'--p_dist',
help='Activate with alignments to calculate p-distance between sequences with identical IDs '
'[OPTIONAL]',
action='store_true')
args = parser.parse_args()
# -------------------------------------------------------------------------
# VALIDATE arguments
if not os.path.isfile(args.seq_file):
parser.error(f'\n### ERROR: seq_file="{args.seq_file}" does not exist')
return Args(seq_file=args.seq_file,
p_dist=args.p_dist)
# -----------------------------------------------------------------------------
def main() -> None:
""" Tell them they are walking around shining like the sun """
# -------------------------------------------------------------------------
# GATHER arguments
args = get_args()
seq_file = args.seq_file
p_dist = args.p_dist
# -------------------------------------------------------------------------
# INITIALIZE OUTPUT AND LOG
print(usage)
print('# -----------------------------------------------------------------------------')
print('LOG:')
print(f'LOG:command="{" ".join(sys.argv)}"')
print(f'LOG:cwd="{os.getcwd()}"')
# arguments received
print(f'LOG:seq_file="{seq_file}"')
print(f'LOG:p_dist="{p_dist}"')
# -------------------------------------------------------------------------
# REGEX & TUPLES
# re_date = re.compile(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).(\d+)')
# -------------------------------------------------------------------------
# Determine whether US=unaligned sequences or MSA=multiple sequence alignment
recs = None # TODO determine whether this is necessary
seq_file_type = 'US'
MSA_length = NA
nseqs = 0
try:
recs = AlignIO.read(seq_file, 'fasta') # Bio.Align.MultipleSeqAlignment
seq_file_type = 'MSA' # only gets here if you don't throw error
MSA_length = int(recs.get_alignment_length())
nseqs = len(recs)
except ValueError: # thrown if AlignIO used for collection of sequences of differing lengths
recs = SeqIO.parse(seq_file, 'fasta') # Bio.SeqIO.FastaIO.FastaIterator
# count sequences
for rec in recs:
nseqs += 1
# change Bio.Align.MultipleSeqAlignment to Bio.SeqIO.FastaIO.FastaIterator if only one sequence
if isinstance(recs, Align.MultipleSeqAlignment) and len(recs) == 1:
recs = SeqIO.parse(seq_file, 'fasta')
seq_file_type = 'US' # change back
# print seq file type
print(f'LOG:seq_file_type="{seq_file_type}" ("US"=unaligned sequences; "MSA"=multiple sequence alignment)')
print(f'LOG:MSA_length={MSA_length} sites')
print(f'LOG:nseqs={nseqs} seqs')
# print(type(recs))
if p_dist and seq_file_type != 'MSA':
print('\n### WARNING: ACTIVATED -p/--p_dist for unaligned sequence(s): WILL SKIP')
# -------------------------------------------------------------------------
# REOPEN as appropriate file type
if seq_file_type == 'US':
recs = SeqIO.parse(seq_file, 'fasta')
else:
recs = AlignIO.read(seq_file, 'fasta')
# -------------------------------------------------------------------------
# Print sequence characters and counts
print('\n# -----------------------------------------------------------------------------')
print('SEQUENCE CHARACTERS (*SUSPICIOUS):', flush=True)
suspicious_rec_count = 0
suspicious_counts_dict: Dict[str, int] = defaultdict(int)
seq_length_dict: Dict[str, int] = defaultdict(int)
gap_ambig_rec_count = 0
gap_ambig_props_dict: Dict[str, int] = defaultdict(int)
# initialize print keys
seq_char_keys_list: List[str] = []
seq_char_keys_list.extend(list(NUCS_DEFINED))
seq_char_keys_list.extend(list(NUCS_INDETERMINATE))
seq_char_keys_list.extend(list(GAPS))
seq_char_keys_list.extend(sorted(list(set(IUPAC_AMBIG).difference(NUCS_INDETERMINATE))))
# print(f'seq_char_keys_list={seq_char_keys_list}')
# PRINT 'header'
seq_char_header = '{:<5} {:<11}{:<9}'.format('num', 'name', 'length')
seq_char_header += '{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}{:>9}'.format(*seq_char_keys_list)
seq_char_header += '{:>11}'.format('GAP_AMBIG')
print(seq_char_header)
# LOOP recs
rec_num = 0
for rec in recs:
rec_num += 1 # first rec will be 1, 1-based
seq_length = len(rec.seq)
counts: Dict[str, int] = Counter(rec.seq)
# counts_list: List[str] = []
warning = False
seq_length_dict[rec.id] = seq_length
# max_digits = len(str(max(counts.values())))
# print(f'max_digits={max_digits}')
# PRINT the counts of recognized IUPAC characters
print('{:<5} {:<11}{:<9}'.format(rec_num, rec.id, seq_length), end='')
for seq_char in seq_char_keys_list:
# print(f'{nuc}={counts[nuc]}', end='\t')
print('{:>9d}'.format(counts[seq_char]), end='')
gap_ambig_sum = 0
for seq_char in sorted(counts.keys()):
# counts_list.append(f'{char}={counts[char]}')
if seq_char in GAPS or seq_char in IUPAC_AMBIG:
gap_ambig_sum += counts[seq_char]
if seq_char not in GAPS and seq_char not in IUPAC:
warning = True
suspicious_rec_count += 1
suspicious_counts_dict[seq_char] += counts[seq_char]
# print GAP_AMBIG percent and newline
print('{:>11}'.format(str(round(100 * gap_ambig_sum / seq_length, 2)) + '%'), end='')
print()
gap_ambig_props_dict[rec.id] = gap_ambig_sum / seq_length
if gap_ambig_sum > 0:
gap_ambig_rec_count += 1
if warning:
# print(f'{rec.id}: ' + ','.join(counts_list))
print(' <= *')
# -------------------------------------------------------------------------
# SEQUENCE SUMMARY, including SUSPICIOUS characters and counts
print('\n# -----------------------------------------------------------------------------')
print('SEQUENCE SUMMARY:', flush=True)
# print(f'LOG:mean_seq_length={np.mean(list(seq_length_dict.values()))}')
print(f'seq_length: {summary_string(list(seq_length_dict.values()))}')
if suspicious_rec_count == 0:
print('NO SUSPICIOUS CHARACTERS')
else:
print(f'### WARNING: {suspicious_rec_count} records with SUSPICIOUS CHARACTERS')
for seq_char in sorted(suspicious_counts_dict.keys()):
print(f'"{seq_char}"={suspicious_counts_dict[seq_char]}')
# # -------------------------------------------------------------------------
# # Print GAP and AMBIGUOUS counts
# print('\n# -----------------------------------------------------------------------------')
# print('GAPS and AMBIGUITIES:', flush=True)
print(f'Records with gaps or ambiguities: {gap_ambig_rec_count} ({round(100 * gap_ambig_rec_count / nseqs, 2)}%)')
print(f'gaps_ambiguities: {summary_string([round(100 * x, 2) for x in list(gap_ambig_props_dict.values())], suffix="%")}')
# -------------------------------------------------------------------------
# Detect and print duplicated IDs
print('\n# -----------------------------------------------------------------------------')
print('DUPLICATED SEQUENCE IDS:', flush=True)
ID_counts: Dict[str, int] = defaultdict(int)
for rec in recs:
ID_counts[str(rec.id)] += 1
# print(dict(ID_counts))
# dict comprehension for repeats
ID_repeats = {ID: count for ID, count in ID_counts.items() if count > 1}
if ID_repeats:
sorted_repeat_IDs = sorted(ID_repeats.keys())
print(f'LOG:num_dup_IDs={len(sorted_repeat_IDs)}')
print(f'LOG:dup_IDs="{",".join(sorted_repeat_IDs)}"')
for dup in sorted_repeat_IDs:
print(f'{dup} ({ID_repeats[dup]} seqs)')
else:
print('NONE')
# -------------------------------------------------------------------------
# Calculate p-distance between sequences having the same name
print('\n# -----------------------------------------------------------------------------')
print('P-DISTANCE BETWEEN DUPLICATED SEQUENCE IDS:', flush=True)
if not p_dist:
print('NOT ACTIVATED (-p/--p_dist not called)')
elif seq_file_type != 'MSA':
print('\n### WARNING: ACTIVATED -p/--p_dist for unaligned sequences (US): SKIPPING')
elif ID_repeats:
for dup_ID in sorted_repeat_IDs:
dup_ID_seq_list: List[str] = []
# p_dist_list: List[float] = []
p_dist_string_list: List[str] = []
if seq_file_type == 'MSA':
recs = AlignIO.read(seq_file, 'fasta')
else:
recs = SeqIO.parse(seq_file, 'fasta')
dup_ID_count = 0
for rec in recs:
if rec.id == dup_ID:
dup_ID_seq_list.append(rec.seq)
dup_ID_count += 1
for i, seq1 in enumerate(dup_ID_seq_list): # range(len(dup_ID_seq_list)):
for j in range(i + 1, len(dup_ID_seq_list)):
seq2 = dup_ID_seq_list[j]
diffs = hamming(seq1, seq2)
prop_diff = diffs / MSA_length
# p_dist_list.append(prop_diff)
p_dist_string_list.append(f'{prop_diff} ({diffs} diffs)')
print(f'{dup_ID} ({dup_ID_count} seqs) distances: {",".join(map(str, p_dist_string_list))}', flush=True)
else:
print('\nACTIVATED -p/--p_dist but there are NO DUPLICATE NAMES (a good thing!)')
# -------------------------------------------------------------------------
# DONE message
print('\n# -----------------------------------------------------------------------------')
print('DONE')
# -----------------------------------------------------------------------------
# CALL MAIN
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
if __name__ == '__main__':
main()