Update app.py
Browse files
app.py
CHANGED
@@ -1,12 +1,15 @@
|
|
1 |
import streamlit as st
|
2 |
from Bio import pairwise2
|
|
|
3 |
import re
|
4 |
from collections import defaultdict
|
5 |
import pandas as pd
|
6 |
import plotly.express as px
|
7 |
import plotly.graph_objects as go
|
8 |
|
9 |
-
#
|
|
|
|
|
10 |
RESISTANCE_GENES = {
|
11 |
'rpoB': {
|
12 |
'start': 759807,
|
@@ -14,6 +17,7 @@ RESISTANCE_GENES = {
|
|
14 |
'description': 'RNA polymerase β subunit',
|
15 |
'drug': 'Rifampicin',
|
16 |
'mutations': {
|
|
|
17 |
'531': {'from': 'S', 'to': ['L'], 'freq': 'High', 'confidence': 'High'},
|
18 |
'526': {'from': 'H', 'to': ['Y', 'D', 'R'], 'freq': 'High', 'confidence': 'High'},
|
19 |
'516': {'from': 'D', 'to': ['V', 'G'], 'freq': 'Moderate', 'confidence': 'High'},
|
@@ -36,8 +40,9 @@ RESISTANCE_GENES = {
|
|
36 |
'description': 'Enoyl-ACP reductase',
|
37 |
'drug': 'Isoniazid/Ethionamide',
|
38 |
'mutations': {
|
|
|
39 |
'-15': {'from': 'C', 'to': ['T'], 'freq': 'High', 'confidence': 'High'},
|
40 |
-
'94':
|
41 |
}
|
42 |
},
|
43 |
'gyrA': {
|
@@ -52,6 +57,9 @@ RESISTANCE_GENES = {
|
|
52 |
}
|
53 |
}
|
54 |
|
|
|
|
|
|
|
55 |
def read_fasta_file(file_path):
|
56 |
"""Read a FASTA file from disk"""
|
57 |
try:
|
@@ -75,96 +83,203 @@ def read_fasta_from_upload(uploaded_file):
|
|
75 |
st.error(f"Error reading uploaded file: {str(e)}")
|
76 |
return None
|
77 |
|
|
|
|
|
|
|
78 |
def extract_gene_region(genome_seq, gene_start, gene_end):
|
79 |
-
"""Extract a gene region with additional context"""
|
80 |
try:
|
81 |
flank = 200
|
82 |
start = max(0, gene_start - flank)
|
83 |
end = min(len(genome_seq), gene_end + flank)
|
84 |
extracted_seq = genome_seq[start:end]
|
85 |
-
st.write(f"Extracted sequence length: {len(extracted_seq)}bp")
|
86 |
return extracted_seq, start
|
87 |
except Exception as e:
|
88 |
st.error(f"Error extracting gene region: {str(e)}")
|
89 |
return None, None
|
90 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
91 |
def find_mutations_with_context(ref_seq, query_seq, gene_start, gene_end, offset=0):
|
92 |
-
"""
|
|
|
|
|
|
|
|
|
93 |
try:
|
94 |
-
|
95 |
-
|
96 |
-
alignments = pairwise2.align.globalms(ref_seq, query_seq,
|
97 |
-
match=2,
|
98 |
-
mismatch=-3,
|
99 |
-
open=-10,
|
100 |
-
extend=-0.5)
|
101 |
|
102 |
if not alignments:
|
103 |
st.warning("No alignments found")
|
104 |
-
return []
|
105 |
|
|
|
106 |
alignment = alignments[0]
|
107 |
ref_aligned, query_aligned = alignment[0], alignment[1]
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
|
|
|
|
114 |
for i in range(len(ref_aligned)):
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
if
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
134 |
|
135 |
-
|
136 |
-
|
|
|
|
|
137 |
except Exception as e:
|
138 |
st.error(f"Error in mutation analysis: {str(e)}")
|
139 |
-
return []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
140 |
|
141 |
-
def analyze_resistance(mutations, gene_info):
|
142 |
-
"""Analyze mutations for drug resistance patterns"""
|
143 |
resistance_found = []
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
154 |
-
|
155 |
-
|
156 |
-
|
157 |
-
|
158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
|
160 |
return resistance_found
|
161 |
|
|
|
|
|
|
|
162 |
def main():
|
163 |
-
st.title("M. tuberculosis Drug Resistance Analysis")
|
164 |
|
165 |
st.markdown("""
|
166 |
### Automated Drug Resistance Analysis Tool
|
167 |
Upload your query genome (clinical isolate) in FASTA format for comparison with H37Rv reference.
|
|
|
|
|
|
|
168 |
""")
|
169 |
|
170 |
# Debug mode toggle
|
@@ -180,101 +295,122 @@ def main():
|
|
180 |
|
181 |
query_file = st.file_uploader("Upload Query Genome (FASTA)", type=['fasta', 'fa'])
|
182 |
|
183 |
-
if query_file:
|
184 |
-
|
185 |
-
|
186 |
-
|
187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
188 |
|
189 |
-
|
190 |
-
|
191 |
-
|
192 |
|
193 |
-
#
|
194 |
-
|
|
|
195 |
|
196 |
-
|
197 |
-
|
198 |
-
|
199 |
-
|
|
|
|
|
|
|
200 |
|
201 |
-
|
202 |
-
|
203 |
-
st.write(f"Gene region: {info['start']}-{info['end']}")
|
204 |
|
205 |
-
|
206 |
-
|
207 |
-
|
|
|
208 |
|
209 |
-
if
|
210 |
-
|
211 |
-
|
212 |
-
|
213 |
-
|
214 |
-
ref_start
|
215 |
-
)
|
216 |
-
|
217 |
-
# Analyze resistance
|
218 |
-
resistance = analyze_resistance(mutations, info)
|
219 |
-
|
220 |
-
all_results[gene] = {
|
221 |
-
'mutations': mutations,
|
222 |
-
'resistance': resistance
|
223 |
-
}
|
224 |
|
225 |
-
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
230 |
|
231 |
-
|
232 |
-
progress_bar.empty()
|
233 |
-
status_text.empty()
|
234 |
|
235 |
-
|
236 |
-
|
|
|
|
|
237 |
|
238 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
239 |
for gene, results in all_results.items():
|
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 |
-
'Drug': RESISTANCE_GENES[gene]['drug'],
|
267 |
-
**mut
|
268 |
-
})
|
269 |
-
|
270 |
-
report_df = pd.DataFrame(report_data)
|
271 |
-
csv = report_df.to_csv(index=False)
|
272 |
-
st.download_button(
|
273 |
-
"Download Full Report (CSV)",
|
274 |
-
csv,
|
275 |
-
"mtb_analysis_report.csv",
|
276 |
-
"text/csv"
|
277 |
-
)
|
278 |
|
|
|
279 |
if __name__ == "__main__":
|
280 |
-
main()
|
|
|
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 |
+
# -------------------------------------------------
|
11 |
+
# 1. Define important gene regions and their associated resistance patterns
|
12 |
+
# -------------------------------------------------
|
13 |
RESISTANCE_GENES = {
|
14 |
'rpoB': {
|
15 |
'start': 759807,
|
|
|
17 |
'description': 'RNA polymerase β subunit',
|
18 |
'drug': 'Rifampicin',
|
19 |
'mutations': {
|
20 |
+
# Example: codon 531: from S -> L
|
21 |
'531': {'from': 'S', 'to': ['L'], 'freq': 'High', 'confidence': 'High'},
|
22 |
'526': {'from': 'H', 'to': ['Y', 'D', 'R'], 'freq': 'High', 'confidence': 'High'},
|
23 |
'516': {'from': 'D', 'to': ['V', 'G'], 'freq': 'Moderate', 'confidence': 'High'},
|
|
|
40 |
'description': 'Enoyl-ACP reductase',
|
41 |
'drug': 'Isoniazid/Ethionamide',
|
42 |
'mutations': {
|
43 |
+
# Negative positions typically refer to promoter/regulatory sites. Compare nucleotides directly.
|
44 |
'-15': {'from': 'C', 'to': ['T'], 'freq': 'High', 'confidence': 'High'},
|
45 |
+
'94': {'from': 'S', 'to': ['A'], 'freq': 'Moderate', 'confidence': 'High'}
|
46 |
}
|
47 |
},
|
48 |
'gyrA': {
|
|
|
57 |
}
|
58 |
}
|
59 |
|
60 |
+
# -------------------------------------------------
|
61 |
+
# 2. File reading functions
|
62 |
+
# -------------------------------------------------
|
63 |
def read_fasta_file(file_path):
|
64 |
"""Read a FASTA file from disk"""
|
65 |
try:
|
|
|
83 |
st.error(f"Error reading uploaded file: {str(e)}")
|
84 |
return None
|
85 |
|
86 |
+
# -------------------------------------------------
|
87 |
+
# 3. Region extraction function
|
88 |
+
# -------------------------------------------------
|
89 |
def extract_gene_region(genome_seq, gene_start, gene_end):
|
90 |
+
"""Extract a gene region with additional 200bp on each side for alignment context."""
|
91 |
try:
|
92 |
flank = 200
|
93 |
start = max(0, gene_start - flank)
|
94 |
end = min(len(genome_seq), gene_end + flank)
|
95 |
extracted_seq = genome_seq[start:end]
|
96 |
+
st.write(f"Extracted sequence length: {len(extracted_seq)}bp (for region {gene_start}-{gene_end})")
|
97 |
return extracted_seq, start
|
98 |
except Exception as e:
|
99 |
st.error(f"Error extracting gene region: {str(e)}")
|
100 |
return None, None
|
101 |
|
102 |
+
# -------------------------------------------------
|
103 |
+
# 4. Codon-level extraction from aligned sequences
|
104 |
+
# -------------------------------------------------
|
105 |
+
def extract_codon_alignment(ref_aligned, query_aligned, gene_start, gene_end, offset):
|
106 |
+
"""
|
107 |
+
Convert the nucleotide alignment into a list of codon diffs (ref_aa, query_aa, codon_number).
|
108 |
+
We skip codons that have a gap in the reference, because we can’t reliably translate them.
|
109 |
+
"""
|
110 |
+
codon_list = []
|
111 |
+
real_pos = 0 # tracks how many non-gap reference bases we've seen
|
112 |
+
|
113 |
+
ref_codon = []
|
114 |
+
query_codon = []
|
115 |
+
|
116 |
+
for i in range(len(ref_aligned)):
|
117 |
+
ref_base = ref_aligned[i]
|
118 |
+
query_base = query_aligned[i]
|
119 |
+
|
120 |
+
# Only increment real_pos if the reference base is not a gap
|
121 |
+
if ref_base != '-':
|
122 |
+
real_pos += 1
|
123 |
+
ref_codon.append(ref_base)
|
124 |
+
query_codon.append(query_base if query_base != '-' else 'N') # 'N' for missing
|
125 |
+
|
126 |
+
# Once we have 3 bases for the reference, translate
|
127 |
+
if len(ref_codon) == 3:
|
128 |
+
# Example: If real_pos is 3, that means we just completed codon #1 for this region, etc.
|
129 |
+
codon_start_pos = offset + (real_pos - 3) # The first base of this codon in genome coords
|
130 |
+
|
131 |
+
# Check if at least part of this codon is in the gene boundaries
|
132 |
+
# Typically we want the entire codon to be within gene_start..gene_end
|
133 |
+
if (codon_start_pos >= gene_start) and (codon_start_pos + 2 <= gene_end):
|
134 |
+
ref_aa = str(Seq(''.join(ref_codon)).translate())
|
135 |
+
query_aa = str(Seq(''.join(query_codon)).translate())
|
136 |
+
|
137 |
+
# codon_number in the gene
|
138 |
+
gene_nt_pos = codon_start_pos - gene_start + 1 # nucleotide offset into the gene
|
139 |
+
# e.g., if gene_nt_pos is 1..3 => codon_number = 1, if 4..6 => codon_number = 2, etc.
|
140 |
+
codon_number = (gene_nt_pos - 1) // 3 + 1
|
141 |
+
|
142 |
+
if ref_aa != query_aa:
|
143 |
+
codon_list.append({
|
144 |
+
'codon_number': codon_number,
|
145 |
+
'ref_aa': ref_aa,
|
146 |
+
'query_aa': query_aa
|
147 |
+
})
|
148 |
+
|
149 |
+
# Reset for the next codon
|
150 |
+
ref_codon = []
|
151 |
+
query_codon = []
|
152 |
+
|
153 |
+
return codon_list
|
154 |
+
|
155 |
+
# -------------------------------------------------
|
156 |
+
# 5. Find both codon-level and promoter-level mutations
|
157 |
+
# -------------------------------------------------
|
158 |
def find_mutations_with_context(ref_seq, query_seq, gene_start, gene_end, offset=0):
|
159 |
+
"""
|
160 |
+
1) Align the nucleotide sequences for the gene region.
|
161 |
+
2) Extract codon-level amino-acid differences for coding changes.
|
162 |
+
3) Identify direct nucleotide changes for promoter or negative positions (like -15).
|
163 |
+
"""
|
164 |
try:
|
165 |
+
# Align the two nucleotide sequences
|
166 |
+
alignments = pairwise2.align.globalms(ref_seq, query_seq, match=2, mismatch=-3, open=-10, extend=-0.5)
|
|
|
|
|
|
|
|
|
|
|
167 |
|
168 |
if not alignments:
|
169 |
st.warning("No alignments found")
|
170 |
+
return {'codon_diffs': [], 'nt_diffs': []}
|
171 |
|
172 |
+
# Take the best-scoring alignment
|
173 |
alignment = alignments[0]
|
174 |
ref_aligned, query_aligned = alignment[0], alignment[1]
|
175 |
+
|
176 |
+
# 1) Extract codon-level diffs
|
177 |
+
codon_diffs = extract_codon_alignment(ref_aligned, query_aligned, gene_start, gene_end, offset)
|
178 |
+
|
179 |
+
# 2) Identify direct nucleotide differences for negative or regulatory positions
|
180 |
+
# We only care about positions that are outside the coding region or specifically listed as negative
|
181 |
+
nt_diffs = []
|
182 |
+
ref_pos = 0 # tracks real position in reference
|
183 |
for i in range(len(ref_aligned)):
|
184 |
+
ref_base = ref_aligned[i]
|
185 |
+
query_base = query_aligned[i]
|
186 |
+
|
187 |
+
# only increment ref_pos if ref_base isn't a gap
|
188 |
+
if ref_base != '-':
|
189 |
+
ref_pos += 1
|
190 |
+
actual_genome_pos = offset + ref_pos # actual coordinate in entire genome
|
191 |
+
|
192 |
+
# Check if there's a mismatch
|
193 |
+
if ref_base != query_base and (query_base != '-'):
|
194 |
+
# If the position is < gene_start, it might be negative or promoter region
|
195 |
+
# Or if the position is > gene_end, it might be some flanking region
|
196 |
+
# We'll store it, and 'analyze_resistance' can figure out if it's relevant
|
197 |
+
if actual_genome_pos < gene_start or actual_genome_pos > gene_end:
|
198 |
+
# It's outside the coding region
|
199 |
+
nt_diffs.append({
|
200 |
+
'genome_pos': actual_genome_pos,
|
201 |
+
'ref_base': ref_base,
|
202 |
+
'query_base': query_base
|
203 |
+
})
|
204 |
+
else:
|
205 |
+
# Even if it's inside the gene, it might be an in-frame insertion or something
|
206 |
+
# not forming a complete codon in the reference. We'll store it anyway.
|
207 |
+
nt_diffs.append({
|
208 |
+
'genome_pos': actual_genome_pos,
|
209 |
+
'ref_base': ref_base,
|
210 |
+
'query_base': query_base
|
211 |
+
})
|
212 |
|
213 |
+
return {
|
214 |
+
'codon_diffs': codon_diffs,
|
215 |
+
'nt_diffs': nt_diffs
|
216 |
+
}
|
217 |
except Exception as e:
|
218 |
st.error(f"Error in mutation analysis: {str(e)}")
|
219 |
+
return {'codon_diffs': [], 'nt_diffs': []}
|
220 |
+
|
221 |
+
# -------------------------------------------------
|
222 |
+
# 6. Analyze the found mutations for known resistance patterns
|
223 |
+
# -------------------------------------------------
|
224 |
+
def analyze_resistance(mutation_data, gene_info):
|
225 |
+
"""Analyze codon-level amino-acid diffs and any direct nucleotide diffs for known patterns."""
|
226 |
+
codon_diffs = mutation_data['codon_diffs'] # list of {codon_number, ref_aa, query_aa}
|
227 |
+
nt_diffs = mutation_data['nt_diffs'] # list of {genome_pos, ref_base, query_base}
|
228 |
|
|
|
|
|
229 |
resistance_found = []
|
230 |
+
|
231 |
+
# We need to parse the dictionary keys in gene_info['mutations'] (they can be negative or numeric)
|
232 |
+
for key_str, pattern in gene_info['mutations'].items():
|
233 |
+
try:
|
234 |
+
key_val = int(key_str)
|
235 |
+
except ValueError:
|
236 |
+
# Should never happen if the dictionary is consistent, but just in case
|
237 |
+
continue
|
238 |
+
|
239 |
+
# If key_val > 0 => it's a codon-based mutation (like 531 for rpoB).
|
240 |
+
# If key_val <= 0 => it's a nucleotide-based mutation in promoter or upstream region (like -15).
|
241 |
+
if key_val > 0:
|
242 |
+
# Codon-based
|
243 |
+
for diff in codon_diffs:
|
244 |
+
if diff['codon_number'] == key_val:
|
245 |
+
# e.g. pattern['from'] = 'S', pattern['to'] = ['L']
|
246 |
+
if diff['ref_aa'] == pattern['from'] and diff['query_aa'] in pattern['to']:
|
247 |
+
resistance_found.append({
|
248 |
+
'position': key_str,
|
249 |
+
'change': f"{pattern['from']}{key_str}{diff['query_aa']}",
|
250 |
+
'frequency': pattern['freq'],
|
251 |
+
'confidence': pattern['confidence']
|
252 |
+
})
|
253 |
+
else:
|
254 |
+
# Nucleotide-based (promoter or upstream).
|
255 |
+
# We need to find an nt_diff at that offset from the gene_start.
|
256 |
+
# e.g. -15 => actual genome position = gene_start + (-15)
|
257 |
+
promoter_genome_pos = gene_info['start'] + key_val
|
258 |
+
for diff in nt_diffs:
|
259 |
+
if diff['genome_pos'] == promoter_genome_pos:
|
260 |
+
# Check if ref_base = pattern['from'], query_base in pattern['to']
|
261 |
+
if diff['ref_base'] == pattern['from'] and diff['query_base'] in pattern['to']:
|
262 |
+
resistance_found.append({
|
263 |
+
'position': key_str,
|
264 |
+
'change': f"{pattern['from']}{key_str}{diff['query_base']}",
|
265 |
+
'frequency': pattern['freq'],
|
266 |
+
'confidence': pattern['confidence']
|
267 |
+
})
|
268 |
|
269 |
return resistance_found
|
270 |
|
271 |
+
# -------------------------------------------------
|
272 |
+
# 7. Main Streamlit App
|
273 |
+
# -------------------------------------------------
|
274 |
def main():
|
275 |
+
st.title("M. tuberculosis Drug Resistance Analysis - FIXED VERSION")
|
276 |
|
277 |
st.markdown("""
|
278 |
### Automated Drug Resistance Analysis Tool
|
279 |
Upload your query genome (clinical isolate) in FASTA format for comparison with H37Rv reference.
|
280 |
+
|
281 |
+
**Note**: This version correctly checks *codon-based* amino-acid mutations (e.g., rpoB S531L)
|
282 |
+
and *nucleotide-based* promoter mutations (e.g., inhA -15C>T).
|
283 |
""")
|
284 |
|
285 |
# Debug mode toggle
|
|
|
295 |
|
296 |
query_file = st.file_uploader("Upload Query Genome (FASTA)", type=['fasta', 'fa'])
|
297 |
|
298 |
+
if query_file and st.button("Analyze Drug Resistance"):
|
299 |
+
query_genome = read_fasta_from_upload(query_file)
|
300 |
+
if query_genome:
|
301 |
+
st.success(f"Query genome loaded successfully (length: {len(query_genome)}bp)")
|
302 |
+
|
303 |
+
# Analysis progress tracking
|
304 |
+
progress_bar = st.progress(0)
|
305 |
+
status_text = st.empty()
|
306 |
+
|
307 |
+
# Store all results
|
308 |
+
all_results = {}
|
309 |
+
|
310 |
+
# Analyze each gene
|
311 |
+
for i, (gene, info) in enumerate(RESISTANCE_GENES.items()):
|
312 |
+
status_text.text(f"Analyzing {gene} ({info['drug']})...")
|
313 |
+
progress_bar.progress((i + 1) / len(RESISTANCE_GENES))
|
314 |
|
315 |
+
if debug_mode:
|
316 |
+
st.subheader(f"Analyzing {gene}")
|
317 |
+
st.write(f"Gene region: {info['start']}-{info['end']}")
|
318 |
|
319 |
+
# Extract regions
|
320 |
+
ref_region, ref_start = extract_gene_region(ref_genome, info['start'], info['end'])
|
321 |
+
query_region, _ = extract_gene_region(query_genome, info['start'], info['end'])
|
322 |
|
323 |
+
if ref_region and query_region:
|
324 |
+
# Find mutations (codon-level + any promoter-level)
|
325 |
+
mutation_data = find_mutations_with_context(
|
326 |
+
ref_region, query_region,
|
327 |
+
info['start'], info['end'],
|
328 |
+
ref_start
|
329 |
+
)
|
330 |
|
331 |
+
# Analyze resistance
|
332 |
+
resistance = analyze_resistance(mutation_data, info)
|
|
|
333 |
|
334 |
+
all_results[gene] = {
|
335 |
+
'mutation_data': mutation_data,
|
336 |
+
'resistance': resistance
|
337 |
+
}
|
338 |
|
339 |
+
if debug_mode:
|
340 |
+
st.write(f"Codon-level differences: {len(mutation_data['codon_diffs'])}")
|
341 |
+
st.write(mutation_data['codon_diffs'])
|
342 |
+
st.write(f"Nucleotide-level differences: {len(mutation_data['nt_diffs'])}")
|
343 |
+
st.write(mutation_data['nt_diffs'])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
344 |
|
345 |
+
st.write(f"Identified {len(resistance)} resistance patterns")
|
346 |
+
else:
|
347 |
+
st.error(f"Failed to analyze {gene}")
|
348 |
+
|
349 |
+
# Clear progress indicators
|
350 |
+
progress_bar.empty()
|
351 |
+
status_text.empty()
|
352 |
+
|
353 |
+
# Display Results
|
354 |
+
st.header("Analysis Results")
|
355 |
+
|
356 |
+
# Show results for each gene
|
357 |
+
for gene, results in all_results.items():
|
358 |
+
st.subheader(f"{gene} Analysis")
|
359 |
+
info = RESISTANCE_GENES[gene]
|
360 |
|
361 |
+
st.write(f"Drug: {info['drug']}")
|
|
|
|
|
362 |
|
363 |
+
num_codon_diffs = len(results['mutation_data']['codon_diffs'])
|
364 |
+
num_nt_diffs = len(results['mutation_data']['nt_diffs'])
|
365 |
+
st.write(f"Total codon-level differences found: {num_codon_diffs}")
|
366 |
+
st.write(f"Total nucleotide-level differences found: {num_nt_diffs}")
|
367 |
|
368 |
+
if results['resistance']:
|
369 |
+
st.warning(f"Potential resistance mutations found in {gene}")
|
370 |
+
resistance_df = pd.DataFrame(results['resistance'])
|
371 |
+
st.dataframe(resistance_df)
|
372 |
+
else:
|
373 |
+
st.info(f"No known resistance mutations found in {gene}")
|
374 |
+
|
375 |
+
# Download complete results
|
376 |
+
if st.button("Download Complete Analysis"):
|
377 |
+
# Create detailed report DataFrame
|
378 |
+
report_data = []
|
379 |
for gene, results in all_results.items():
|
380 |
+
# Store codon diffs
|
381 |
+
for diff in results['mutation_data']['codon_diffs']:
|
382 |
+
report_data.append({
|
383 |
+
'Gene': gene,
|
384 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
385 |
+
'Type': 'Codon_diff',
|
386 |
+
**diff
|
387 |
+
})
|
388 |
+
# Store nt diffs
|
389 |
+
for diff in results['mutation_data']['nt_diffs']:
|
390 |
+
report_data.append({
|
391 |
+
'Gene': gene,
|
392 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
393 |
+
'Type': 'Nucleotide_diff',
|
394 |
+
**diff
|
395 |
+
})
|
396 |
+
# Store recognized resistance mutations
|
397 |
+
for res in results['resistance']:
|
398 |
+
report_data.append({
|
399 |
+
'Gene': gene,
|
400 |
+
'Drug': RESISTANCE_GENES[gene]['drug'],
|
401 |
+
'Type': 'Resistance',
|
402 |
+
**res
|
403 |
+
})
|
404 |
|
405 |
+
report_df = pd.DataFrame(report_data)
|
406 |
+
csv = report_df.to_csv(index=False)
|
407 |
+
st.download_button(
|
408 |
+
"Download Full Report (CSV)",
|
409 |
+
csv,
|
410 |
+
"mtb_analysis_report_fixed.csv",
|
411 |
+
"text/csv"
|
412 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
413 |
|
414 |
+
# Entry point
|
415 |
if __name__ == "__main__":
|
416 |
+
main()
|