-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreateMapleFile.py
178 lines (145 loc) · 6.15 KB
/
createMapleFile.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
import sys
import os
from os import path
import argparse
import time
# Translate a fasta alignment into a MAPLE format file.
class Sequence:
'''A sequence parsed from a FASTA file.
Attributes:
description: str
The description of the genome.
sequence: str
The genome sequence.
'''
def __init__(self, description: str, sequence: str):
self.name = description
self.sequence = sequence
def parse_fasta(file_path: str) -> list:
'''Parse a fasta file and return a list of Sequence objects. '''
sequences = []
current_label = None
current_sequence = ""
with open(file_path, 'r') as file:
for line in file:
line = line.strip()
# Check if the line is a label
if line.startswith('>'):
# Flush previous label
if current_label is not None:
sequences.append(Sequence(current_label, current_sequence))
# Start a new label and reset sequence
current_label = line[1:] # Remove the '>'
current_sequence = ""
else:
# Append the sequence lines
current_sequence += line
# Save the last label and sequence
if current_label is not None:
sequences.append(Sequence(current_label, current_sequence.lower()))
return sequences
def generate_consensus(sequences: list) -> str:
'''Generate a consensus sequence from a list of sequences. '''
# Get the length of the sequences
seq_length = len(sequences[0].sequence)
for s in sequences:
if len(s.sequence) != seq_length:
raise ValueError("All sequences must be the same length.")
consensus = ""
for i in range(seq_length):
# Get the nucleotides at position i
nucleotides = [s.sequence[i] for s in sequences]
# Count the number of each nucleotide
counts = {n: nucleotides.count(n) for n in 'acgt-n'}
# Get the most common nucleotide
consensus += max(counts, key=counts.get)
print(f"Consensus sequence: {consensus}")
return consensus
if __name__ == '__main__':
# Parse command line arguments
parser = argparse.ArgumentParser(description='Translate a fasta alignment into a MAPLE format file.')
parser.add_argument('--input', type=str, help='The input fasta file.')
parser.add_argument('--reference', type=str, help='The reference fasta file.')
parser.add_argument("--output", type=str, help="The output MAPLE file.")
args = parser.parse_args()
import time
start_time = time.time()
if not path.exists(args.input):
print(f"ERROR: Input file {args.input} not found.")
sys.exit(1)
if args.reference:
if not path.exists(args.reference):
print(f"ERROR: Reference file {args.reference} not found.")
sys.exit(1)
else:
print("No reference file provided. Consensus sequence will be used as reference.")
reference = None
sequences = parse_fasta(args.input)
if args.reference:
reference = parse_fasta(args.reference)[0].sequence
else:
reference = generate_consensus(sequences)
# Check if the reference sequence length matches the input sequences
for s in sequences:
if len(reference) != len(s.sequence):
print(f"ERROR: Reference sequence length does not match the input sequence {s.name}.")
sys.exit(1)
# Write the output MAPLE file
with open(args.output, 'w') as file:
file.write(f">reference\n{reference.lower()}\n")
for s in sequences:
file.write(f">{s.name}\n")
diff = ""
for i in range(len(s.sequence)):
if s.sequence[i] == 'n' or s.sequence[i] == '-':
diff += s.sequence[i]
elif s.sequence[i] != reference[i]:
diff += s.sequence[i]
else:
diff += "0"
last_n_or_gap = None
last_index = -1
for i in range(len(diff)):
if diff[i] == 'n':
if last_n_or_gap != 'n':
# Flush the last gap
if last_n_or_gap == '-':
file.write(f"-\t{last_index}\t{i - last_index + 1}\n")
last_n_or_gap = 'n'
last_index = i + 1
else:
continue
elif diff[i] == '-':
if last_n_or_gap != '-':
# Flush the last n
if last_n_or_gap == 'n':
file.write(f"n\t{last_index}\t{i - last_index + 1}\n")
last_n_or_gap = '-'
last_index = i + 1
else:
continue
elif diff[i] != '0':
# Flush the last gap or n
if last_n_or_gap == 'n':
file.write(f"n\t{last_index}\t{i - last_index + 1}\n")
elif last_n_or_gap == '-':
file.write(f"n\t{last_index}\t{i - last_index + 1}\n")
last_n_or_gap = None
last_index = -1
file.write(f"{diff[i].lower()}\t{i + 1}\n")
else:
# Flush the last gap or n
if last_n_or_gap == 'n':
file.write(f"n\t{last_index}\t{i - last_index + 1}\n")
elif last_n_or_gap == '-':
file.write(f"n\t{last_index}\t{i - last_index + 1}\n")
last_n_or_gap = None
last_index = -1
# Flush the last gap or n
if last_n_or_gap == 'n':
file.write(f"n {last_index} {i - last_index + 1}\n")
elif last_n_or_gap == '-':
file.write(f"n {last_index} {i - last_index + 1}\n")
last_n_or_gap = None
last_index = -1
print("Time - %s seconds" % (time.time() - start_time))