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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from Bio import pairwise2
|
3 |
+
from Bio.Seq import Seq
|
4 |
+
import re
|
5 |
+
from collections import defaultdict
|
6 |
+
import pandas as pd
|
7 |
+
import plotly.express as px
|
8 |
+
import plotly.graph_objects as go
|
9 |
+
|
10 |
+
# Define resistance genes and mutation patterns
|
11 |
+
RESISTANCE_GENES = {
|
12 |
+
'rpoB': {
|
13 |
+
'start': 759807,
|
14 |
+
'end': 763325,
|
15 |
+
'description': 'RNA polymerase β subunit',
|
16 |
+
'drug': 'Rifampicin',
|
17 |
+
'mutations': {
|
18 |
+
'531': {'from': 'S', 'to': ['L'], 'freq': 'High', 'confidence': 'High'},
|
19 |
+
'526': {'from': 'H', 'to': ['Y', 'D', 'R'], 'freq': 'High', 'confidence': 'High'},
|
20 |
+
'516': {'from': 'D', 'to': ['V', 'G'], 'freq': 'Moderate', 'confidence': 'High'},
|
21 |
+
'511': {'from': 'L', 'to': ['P'], 'freq': 'Low', 'confidence': 'Moderate'}
|
22 |
+
}
|
23 |
+
},
|
24 |
+
'katG': {
|
25 |
+
'start': 2153889,
|
26 |
+
'end': 2156111,
|
27 |
+
'description': 'Catalase-peroxidase',
|
28 |
+
'drug': 'Isoniazid',
|
29 |
+
'mutations': {
|
30 |
+
'315': {'from': 'S', 'to': ['T', 'N'], 'freq': 'High', 'confidence': 'High'},
|
31 |
+
'463': {'from': 'R', 'to': ['L'], 'freq': 'Moderate', 'confidence': 'Moderate'}
|
32 |
+
}
|
33 |
+
},
|
34 |
+
'inhA': {
|
35 |
+
'start': 1674202,
|
36 |
+
'end': 1675011,
|
37 |
+
'description': 'Enoyl-ACP reductase',
|
38 |
+
'drug': 'Isoniazid/Ethionamide',
|
39 |
+
'mutations': {
|
40 |
+
'-15': {'from': 'C', 'to': ['T'], 'freq': 'High', 'confidence': 'High'},
|
41 |
+
'94': {'from': 'S', 'to': ['A'], 'freq': 'Moderate', 'confidence': 'High'}
|
42 |
+
}
|
43 |
+
},
|
44 |
+
'gyrA': {
|
45 |
+
'start': 7302,
|
46 |
+
'end': 9818,
|
47 |
+
'description': 'DNA gyrase subunit A',
|
48 |
+
'drug': 'Fluoroquinolones',
|
49 |
+
'mutations': {
|
50 |
+
'90': {'from': 'A', 'to': ['V'], 'freq': 'High', 'confidence': 'High'},
|
51 |
+
'94': {'from': 'D', 'to': ['G', 'A', 'N'], 'freq': 'High', 'confidence': 'High'}
|
52 |
+
}
|
53 |
+
}
|
54 |
+
}
|
55 |
+
|
56 |
+
# File reading functions
|
57 |
+
def read_fasta_file(file_path):
|
58 |
+
"""Read a FASTA file from disk"""
|
59 |
+
try:
|
60 |
+
with open(file_path, 'r') as handle:
|
61 |
+
content = handle.read().strip()
|
62 |
+
parts = content.split('\n', 1)
|
63 |
+
sequence = ''.join(parts[1].split('\n')).replace(' ', '')
|
64 |
+
return sequence.upper()
|
65 |
+
except Exception as e:
|
66 |
+
st.error(f"Error reading file {file_path}: {str(e)}")
|
67 |
+
return None
|
68 |
+
|
69 |
+
def read_fasta_from_upload(uploaded_file):
|
70 |
+
"""Read a FASTA file from Streamlit upload"""
|
71 |
+
try:
|
72 |
+
content = uploaded_file.getvalue().decode('utf-8').strip()
|
73 |
+
parts = content.split('\n', 1)
|
74 |
+
sequence = ''.join(parts[1].split('\n')).replace(' ', '')
|
75 |
+
return sequence.upper()
|
76 |
+
except Exception as e:
|
77 |
+
st.error(f"Error reading uploaded file: {str(e)}")
|
78 |
+
return None
|
79 |
+
|
80 |
+
# Region extraction function
|
81 |
+
def extract_gene_region(genome_seq, gene_start, gene_end):
|
82 |
+
"""Extract a gene region with 200bp flanking for alignment context"""
|
83 |
+
flank = 200
|
84 |
+
start = max(0, gene_start - flank)
|
85 |
+
end = min(len(genome_seq), gene_end + flank)
|
86 |
+
extracted_seq = genome_seq[start:end]
|
87 |
+
return extracted_seq, start
|
88 |
+
|
89 |
+
# Codon alignment extraction
|
90 |
+
def extract_codon_alignment(ref_aligned, query_aligned, gene_start, gene_end, offset):
|
91 |
+
"""Extract codon-level differences from aligned sequences"""
|
92 |
+
codon_list = []
|
93 |
+
real_pos = 0
|
94 |
+
ref_codon = []
|
95 |
+
query_codon = []
|
96 |
+
|
97 |
+
for i in range(len(ref_aligned)):
|
98 |
+
ref_base = ref_aligned[i]
|
99 |
+
query_base = query_aligned[i]
|
100 |
+
if ref_base != '-':
|
101 |
+
real_pos += 1
|
102 |
+
ref_codon.append(ref_base)
|
103 |
+
query_codon.append(query_base if query_base != '-' else 'N')
|
104 |
+
if len(ref_codon) == 3:
|
105 |
+
codon_start_pos = offset + (real_pos - 3)
|
106 |
+
if (codon_start_pos >= gene_start) and (codon_start_pos + 2 <= gene_end):
|
107 |
+
ref_aa = str(Seq(''.join(ref_codon)).translate())
|
108 |
+
query_aa = str(Seq(''.join(query_codon)).translate())
|
109 |
+
gene_nt_pos = codon_start_pos - gene_start + 1
|
110 |
+
codon_number = (gene_nt_pos - 1) // 3 + 1
|
111 |
+
if ref_aa != query_aa:
|
112 |
+
codon_list.append({
|
113 |
+
'codon_number': codon_number,
|
114 |
+
'ref_aa': ref_aa,
|
115 |
+
'query_aa': query_aa
|
116 |
+
})
|
117 |
+
ref_codon = []
|
118 |
+
query_codon = []
|
119 |
+
return codon_list
|
120 |
+
|
121 |
+
# Mutation detection
|
122 |
+
def find_mutations_with_context(ref_seq, query_seq, gene_start, gene_end, offset=0):
|
123 |
+
"""Find codon-level and nucleotide-level mutations"""
|
124 |
+
alignments = pairwise2.align.globalms(ref_seq, query_seq, match=2, mismatch=-3, open=-10, extend=-0.5)
|
125 |
+
if not alignments:
|
126 |
+
return {'codon_diffs': [], 'nt_diffs': []}
|
127 |
+
ref_aligned, query_aligned = alignments[0][0], alignments[0][1]
|
128 |
+
codon_diffs = extract_codon_alignment(ref_aligned, query_aligned, gene_start, gene_end, offset)
|
129 |
+
nt_diffs = []
|
130 |
+
ref_pos = 0
|
131 |
+
for i in range(len(ref_aligned)):
|
132 |
+
ref_base = ref_aligned[i]
|
133 |
+
query_base = query_aligned[i]
|
134 |
+
if ref_base != '-':
|
135 |
+
ref_pos += 1
|
136 |
+
actual_genome_pos = offset + ref_pos
|
137 |
+
if ref_base != query_base and query_base != '-':
|
138 |
+
nt_diffs.append({
|
139 |
+
'genome_pos': actual_genome_pos,
|
140 |
+
'ref_base': ref_base,
|
141 |
+
'query_base': query_base
|
142 |
+
})
|
143 |
+
return {'codon_diffs': codon_diffs, 'nt_diffs': nt_diffs}
|
144 |
+
|
145 |
+
# Resistance analysis
|
146 |
+
def analyze_resistance(mutation_data, gene_info):
|
147 |
+
"""Match mutations to known resistance patterns"""
|
148 |
+
codon_diffs = mutation_data['codon_diffs']
|
149 |
+
nt_diffs = mutation_data['nt_diffs']
|
150 |
+
resistance_found = []
|
151 |
+
for key_str, pattern in gene_info['mutations'].items():
|
152 |
+
key_val = int(key_str)
|
153 |
+
if key_val > 0:
|
154 |
+
for diff in codon_diffs:
|
155 |
+
if diff['codon_number'] == key_val and diff['ref_aa'] == pattern['from'] and diff['query_aa'] in pattern['to']:
|
156 |
+
resistance_found.append({
|
157 |
+
'position': key_str,
|
158 |
+
'change': f"{pattern['from']}{key_str}{diff['query_aa']}",
|
159 |
+
'frequency': pattern['freq'],
|
160 |
+
'confidence': pattern['confidence']
|
161 |
+
})
|
162 |
+
else:
|
163 |
+
promoter_genome_pos = gene_info['start'] + key_val
|
164 |
+
for diff in nt_diffs:
|
165 |
+
if diff['genome_pos'] == promoter_genome_pos and diff['ref_base'] == pattern['from'] and diff['query_base'] in pattern['to']:
|
166 |
+
resistance_found.append({
|
167 |
+
'position': key_str,
|
168 |
+
'change': f"{pattern['from']}{key_str}{diff['query_base']}",
|
169 |
+
'frequency': pattern['freq'],
|
170 |
+
'confidence': pattern['confidence']
|
171 |
+
})
|
172 |
+
return resistance_found
|
173 |
+
|
174 |
+
# Main Streamlit app
|
175 |
+
def main():
|
176 |
+
st.title("M. tuberculosis Drug Resistance Analysis")
|
177 |
+
st.markdown("""
|
178 |
+
### Automated Drug Resistance Analysis Tool
|
179 |
+
Upload your query genome (clinical isolate) in FASTA format to compare with the H37Rv reference.
|
180 |
+
**Note**: Detects codon-based (e.g., rpoB S531L) and nucleotide-based (e.g., inhA -15C>T) mutations.
|
181 |
+
""")
|
182 |
+
|
183 |
+
debug_mode = st.checkbox("Enable debug mode")
|
184 |
+
ref_genome = read_fasta_file("NC_000962.3.fasta")
|
185 |
+
if not ref_genome:
|
186 |
+
st.error("Failed to load reference genome")
|
187 |
+
return
|
188 |
+
st.success(f"Reference genome loaded (length: {len(ref_genome)}bp)")
|
189 |
+
|
190 |
+
query_file = st.file_uploader("Upload Query Genome (FASTA)", type=['fasta', 'fa'])
|
191 |
+
if query_file and st.button("Analyze Drug Resistance"):
|
192 |
+
query_genome = read_fasta_from_upload(query_file)
|
193 |
+
if not query_genome:
|
194 |
+
return
|
195 |
+
st.success(f"Query genome loaded (length: {len(query_genome)}bp)")
|
196 |
+
|
197 |
+
progress_bar = st.progress(0)
|
198 |
+
status_text = st.empty()
|
199 |
+
all_results = {}
|
200 |
+
|
201 |
+
for i, (gene, info) in enumerate(RESISTANCE_GENES.items()):
|
202 |
+
status_text.text(f"Analyzing {gene} ({info['drug']})...")
|
203 |
+
progress_bar.progress((i + 1) / len(RESISTANCE_GENES))
|
204 |
+
if debug_mode:
|
205 |
+
st.subheader(f"Analyzing {gene}")
|
206 |
+
st.write(f"Gene region: {info['start']}-{info['end']}")
|
207 |
+
ref_region, ref_start = extract_gene_region(ref_genome, info['start'], info['end'])
|
208 |
+
query_region, _ = extract_gene_region(query_genome, info['start'], info['end'])
|
209 |
+
if ref_region and query_region:
|
210 |
+
mutation_data = find_mutations_with_context(ref_region, query_region, info['start'], info['end'], ref_start)
|
211 |
+
resistance = analyze_resistance(mutation_data, info)
|
212 |
+
all_results[gene] = {'mutation_data': mutation_data, 'resistance': resistance}
|
213 |
+
if debug_mode:
|
214 |
+
st.write(f"Codon diffs: {len(mutation_data['codon_diffs'])}", mutation_data['codon_diffs'])
|
215 |
+
st.write(f"Nucleotide diffs: {len(mutation_data['nt_diffs'])}", mutation_data['nt_diffs'])
|
216 |
+
st.write(f"Resistance patterns: {len(resistance)}")
|
217 |
+
else:
|
218 |
+
st.error(f"Failed to analyze {gene}")
|
219 |
+
|
220 |
+
progress_bar.empty()
|
221 |
+
status_text.empty()
|
222 |
+
|
223 |
+
# Summary table
|
224 |
+
summary_data = [
|
225 |
+
{
|
226 |
+
'Gene': gene,
|
227 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
228 |
+
'Codon Diffs': len(results['mutation_data']['codon_diffs']),
|
229 |
+
'Nucleotide Diffs': len(results['mutation_data']['nt_diffs']),
|
230 |
+
'Resistance Mutations': len(results['resistance'])
|
231 |
+
}
|
232 |
+
for gene, results in all_results.items()
|
233 |
+
]
|
234 |
+
summary_df = pd.DataFrame(summary_data)
|
235 |
+
def highlight_resistance(row):
|
236 |
+
return ['background-color: yellow' if row['Resistance Mutations'] > 0 else '' for _ in row]
|
237 |
+
styled_summary = summary_df.style.apply(highlight_resistance, axis=1)
|
238 |
+
st.subheader("Summary of Analysis")
|
239 |
+
st.dataframe(styled_summary)
|
240 |
+
|
241 |
+
# Detailed results
|
242 |
+
for gene, results in all_results.items():
|
243 |
+
st.subheader(f"{gene} Analysis")
|
244 |
+
info = RESISTANCE_GENES[gene]
|
245 |
+
st.write(f"**Drug**: {info['drug']}")
|
246 |
+
st.write(f"**Codon-level differences**: {len(results['mutation_data']['codon_diffs'])}")
|
247 |
+
st.write(f"**Nucleotide-level differences**: {len(results['mutation_data']['nt_diffs'])}")
|
248 |
+
if results['resistance']:
|
249 |
+
st.warning(f"Potential resistance mutations found in {gene}")
|
250 |
+
resistance_df = pd.DataFrame(results['resistance'])
|
251 |
+
st.dataframe(resistance_df)
|
252 |
+
else:
|
253 |
+
st.info(f"No known resistance mutations found in {gene}")
|
254 |
+
|
255 |
+
# Download button
|
256 |
+
st.markdown("### Download Complete Analysis")
|
257 |
+
st.write("Download a CSV file with all mutation and resistance data.")
|
258 |
+
report_data = []
|
259 |
+
for gene, results in all_results.items():
|
260 |
+
for diff in results['mutation_data']['codon_diffs']:
|
261 |
+
report_data.append({
|
262 |
+
'Gene': gene,
|
263 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
264 |
+
'Type': 'Codon_diff',
|
265 |
+
'Codon Number': diff['codon_number'],
|
266 |
+
'Reference AA': diff['ref_aa'],
|
267 |
+
'Query AA': diff['query_aa']
|
268 |
+
})
|
269 |
+
for diff in results['mutation_data']['nt_diffs']:
|
270 |
+
report_data.append({
|
271 |
+
'Gene': gene,
|
272 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
273 |
+
'Type': 'Nucleotide_diff',
|
274 |
+
'Genome Position': diff['genome_pos'],
|
275 |
+
'Reference Base': diff['ref_base'],
|
276 |
+
'Query Base': diff['query_base']
|
277 |
+
})
|
278 |
+
for res in results['resistance']:
|
279 |
+
report_data.append({
|
280 |
+
'Gene': gene,
|
281 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
282 |
+
'Type': 'Resistance',
|
283 |
+
'Position': res['position'],
|
284 |
+
'Change': res['change'],
|
285 |
+
'Frequency': res['frequency'],
|
286 |
+
'Confidence': res['confidence']
|
287 |
+
})
|
288 |
+
report_df = pd.DataFrame(report_data)
|
289 |
+
csv = report_df.to_csv(index=False)
|
290 |
+
st.download_button(
|
291 |
+
label="Download Full Report (CSV)",
|
292 |
+
data=csv,
|
293 |
+
file_name="mtb_analysis_report.csv",
|
294 |
+
mime="text/csv"
|
295 |
+
)
|
296 |
+
|
297 |
+
if __name__ == "__main__":
|
298 |
+
main()
|