-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFASTA_to_haplotypes.py
More file actions
executable file
·266 lines (209 loc) · 9.56 KB
/
FASTA_to_haplotypes.py
File metadata and controls
executable file
·266 lines (209 loc) · 9.56 KB
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
#!/usr/bin/env python3
"""
Purpose: Tally the unique haplotypes in a FASTA file (nucleotide or amino acid)
Author : Chase W. Nelson <chase.nelson@nih.gov>
Cite : https://github.com/chasewnelson/
Date : 2023-05-23
"""
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from collections import Counter
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 NamedTuple # FASTA_to_haplotypes.py -i HPV16_A_n4013_E6_aa.fasta
# Usage
usage = """# -----------------------------------------------------------------------------
FASTA_to_haplotypes.py - Tally the unique haplotypes in a FASTA file (nucleotide or amino acid)
# -----------------------------------------------------------------------------
For DOCUMENTATION, run:
$ FASTA_to_haplotypes.py --help
$ pydoc ./FASTA_to_haplotypes.py
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
EXAMPLE:
$ FASTA_to_haplotypes.py -i HPV16_A_n4013_E6_aa.fasta
# -----------------------------------------------------------------------------
"""
class Args(NamedTuple):
""" Command-line arguments """
fasta_file: str
out_file: str
prefix: str
header: str
# p_dist: bool
# -----------------------------------------------------------------------------
def get_args() -> Args:
""" Get command-line arguments """
parser = argparse.ArgumentParser(
description='Tally the unique haplotypes in a FASTA file (nucleotide or amino acid). HELP: FASTA_to_haplotypes.py --help',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# Rename "optional" arguments
parser._optionals.title = 'Named arguments'
# -------------------------------------------------------------------------
# REQUIRED
parser.add_argument('-i',
'--fasta_file',
metavar='FILE',
help='FASTA file containing sequence(s) [REQUIRED]',
required=True,
# nargs='+',
type=str)
# -------------------------------------------------------------------------
# OPTIONAL
parser.add_argument('-o',
'--out_file',
metavar='str',
help='Output file name [OPTIONAL]',
required=False,
type=str,
default='<INPUT>_haplotypes.tsv') # detect this later
parser.add_argument('-p',
'--prefix',
metavar='str',
help='Prefix of FASTA name for most common haplotype [OPTIONAL]',
required=False,
type=str,
default='<INPUT>_haplotype1') # detect this later
parser.add_argument('-H',
'--header',
metavar='str',
help='Header for FASTA of most common haplotype [OPTIONAL]',
required=False,
type=str,
default='<INPUT>_haplotype1') # detect this later
# 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.fasta_file):
parser.error(f'\n### ERROR: fasta_file="{args.fasta_file}" does not exist')
# FORM the output file name if not given
if args.out_file == '<INPUT>_haplotypes.tsv':
args.out_file = os.path.splitext(args.fasta_file)[0] + '_haplotypes.tsv'
# ensure out_file not present
if os.path.isfile(args.out_file):
parser.error(f'\n### ERROR: out_file="{args.out_file}" already exists')
# FORM the prefix FASTA name if not given
if args.prefix == '<INPUT>_haplotype1':
args.prefix = os.path.splitext(args.fasta_file)[0] + '_haplotype1'
# FORM the HEADER of FASTA
if args.header == '<INPUT>_haplotype1':
args.header = os.path.splitext(args.fasta_file)[0] + '_haplotype1'
return Args(fasta_file=args.fasta_file,
out_file=args.out_file,
prefix=args.prefix,
header=args.header)
# -----------------------------------------------------------------------------
def main() -> None:
""" Tell them they are walking around shining like the sun """
# -------------------------------------------------------------------------
# GATHER arguments
args = get_args()
fasta_file = args.fasta_file
out_file = args.out_file
prefix = args.prefix
header = args.header
# p_dist = args.p_dist
# form output fasta - HACK
out_fasta = out_file.replace('.tsv', '.fasta')
# ensure out_fasta not present
if os.path.isfile(out_fasta):
sys.exit(f'\n### ERROR: out_file="{out_fasta}" already exists')
# -------------------------------------------------------------------------
# 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:fasta_file="{fasta_file}"')
print(f'LOG:out_file="{out_file}"')
print(f'LOG:out_fasta="{out_fasta}"')
print(f'LOG:prefix="{prefix}"')
print(f'LOG:header="{header}"')
# print(f'LOG:p_dist="{p_dist}"')
# -------------------------------------------------------------------------
# REGEX & TUPLES
# re_date = re.compile(r'(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+).(\d+)')
# -------------------------------------------------------------------------
# BUSINESS
sequences = read_fasta_file(fasta_file)
sequence_counts = count_unique_sequences(sequences)
# write the tsv
write_sequence_counts(sequence_counts, out_file)
# write the fasta
write_seq_counts_fasta(sequence_counts, out_fasta)
# get and print min_X_count
min_X_count = get_min_x_count(sequence_counts)
print(f"Minimum X_count: {min_X_count}")
# get most common seq and its count
most_common_tuple = sequence_counts.most_common(1)[0]
most_common_sequence, most_common_count = most_common_tuple[0], most_common_tuple[1]
# write the most common sequence (haplotype)
if header == prefix:
header = f'{prefix}_n{most_common_count}'
out_fasta_name = f'{prefix}_n{most_common_count}.fasta'
most_common_Seq = Seq(most_common_sequence)
record = SeqRecord(most_common_Seq, id=header, description="")
SeqIO.write(record, out_fasta_name, "fasta")
# WARNING if the most commmon sequence didn't have the minimum nujber of Xs
if count_x_chars(most_common_Seq) > min_X_count:
print(f'\n### WARNING: min_X_count={min_X_count} but most common seq has X={count_x_chars(most_common_Seq)}')
else:
print(f'CONFIRMED: most common seq has min_X_count={min_X_count}')
# -------------------------------------------------------------------------
# DONE message
print('\n# -----------------------------------------------------------------------------')
print('DONE')
# -----------------------------------------------------------------------------
def read_fasta_file(fasta_file):
sequences = []
for record in SeqIO.parse(fasta_file, "fasta"):
sequences.append(str(record.seq))
return sequences
# -----------------------------------------------------------------------------
def count_unique_sequences(sequences):
sequence_counts = Counter(sequences)
return sequence_counts
# -----------------------------------------------------------------------------
def count_x_chars(sequence):
return sequence.count('X')
# -----------------------------------------------------------------------------
def write_sequence_counts(sequence_counts, output_file):
with open(output_file, 'w') as f:
f.write("Seq_ID\tSequence\tCount\tX_Count\n")
counter = 0
for sequence, count in sequence_counts.most_common():
counter += 1
x_count = count_x_chars(sequence)
f.write(f"h{counter}\t{sequence}\t{count}\t{x_count}\n")
# -----------------------------------------------------------------------------
def write_seq_counts_fasta(sequence_counts, output_file):
with open(output_file, 'w') as f:
counter = 0
for sequence, count in sequence_counts.most_common():
counter += 1
x_count = count_x_chars(sequence)
f.write(f">h{counter}_n{count}_x{x_count}\n")
f.write(sequence + "\n")
# -----------------------------------------------------------------------------
def get_min_x_count(sequence_counts):
min_X_count = min(count_x_chars(seq) for seq in sequence_counts.keys())
return(min_X_count)
# -----------------------------------------------------------------------------
# CALL MAIN
# -----------------------------------------------------------------------------
# -----------------------------------------------------------------------------
if __name__ == '__main__':
main()